File: pipes_unix.c

package info (click to toggle)
cfengine3 3.24.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,552 kB
  • sloc: ansic: 163,161; sh: 10,296; python: 2,950; makefile: 1,744; lex: 784; yacc: 633; perl: 211; pascal: 157; xml: 21; sed: 13
file content (1112 lines) | stat: -rw-r--r-- 27,460 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
/*
  Copyright 2024 Northern.tech AS

  This file is part of CFEngine 3 - written and maintained by Northern.tech AS.

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the
  Free Software Foundation; version 3.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

  To the extent this program is licensed as part of the Enterprise
  versions of CFEngine, the applicable Commercial Open Source License
  (COSL) may apply to this file if you as a licensee so wish it. See
  included file COSL.txt.
*/

#include <pipes.h>

#include <mutex.h>
#include <global_mutex.h>
#include <exec_tools.h>
#include <rlist.h>
#include <policy.h>
#include <eval_context.h>
#include <file_lib.h>
#include <signals.h>
#include <string_lib.h>

static bool CfSetuid(uid_t uid, gid_t gid);

static int cf_pwait(pid_t pid);

static pid_t *CHILDREN = NULL; /* GLOBAL_X */
static int MAX_FD = 2048; /* GLOBAL_X */ /* Max number of simultaneous pipes */


static void ChildrenFDInit()
{
    ThreadLock(cft_count);
    if (CHILDREN == NULL)       /* first time */
    {
        CHILDREN = xcalloc(MAX_FD, sizeof(pid_t));
    }

    ThreadUnlock(cft_count);
}

/*****************************************************************************/

/* This leaks memory and is not thread-safe! To be used only when you are
 * about to exec() or _exit(), and only async-signal-safe code is allowed. */
static void ChildrenFDUnsafeClose()
{
    /* GenericCreatePipeAndFork() must have been called to init this. */
    assert(CHILDREN != NULL);

    for (int i = 0; i < MAX_FD; i++)
    {
        if (CHILDREN[i] > 0)
        {
            close(i);
        }
    }
    CHILDREN = NULL;                                    /* leaks on purpose */
}

/* This is the original safe version, but not signal-handler-safe.
   It's currently unused. */
#if 0
static void ChildrenFDClose()
{
    ThreadLock(cft_count);
    int i;
    for (i = 0; i < MAX_FD; i++)
    {
        if (CHILDREN[i] > 0)
        {
            close(i);
        }
    }
    free(CHILDREN);
    CHILDREN = NULL;
    ThreadUnlock(cft_count);
}
#endif

static void ChildOutputSelectDupClose(int pd[2], OutputSelect output_select)
{
    close(pd[0]); // Don't need output from parent

    if (pd[1] != 1) // TODO: When is pd[1] == 1 ???
    {
        if ((output_select == OUTPUT_SELECT_BOTH)
            || (output_select == OUTPUT_SELECT_STDOUT))
        {
            // close our(child) stdout(1) and open (pd[1]) as stdout
            dup2(pd[1], 1);
            // Subsequent stdout output will go to parent (pd[1])
        }
        else
        {
            // Close / discard stdout
            int nullfd = open(NULLFILE, O_WRONLY);
            dup2(nullfd, 1);
            close(nullfd);
        }

        if ((output_select == OUTPUT_SELECT_BOTH)
            || (output_select == OUTPUT_SELECT_STDERR))
        {
            // close our(child) stderr(2) and open (pd[1]) as stderr
            dup2(pd[1], 2);
            // Subsequent stderr output will go to parent (pd[1])
        }
        else
        {
            // Close / discard stderr
            int nullfd = open(NULLFILE, O_WRONLY);
            dup2(nullfd, 2);
            close(nullfd);
        }

        close(pd[1]);
    }
}

/*****************************************************************************/

static void ChildrenFDSet(int fd, pid_t pid)
{
    int new_max = 0;

    if (fd >= MAX_FD)
    {
        Log(LOG_LEVEL_WARNING,
            "File descriptor %d of child %jd higher than MAX_FD, check for defunct children",
            fd, (intmax_t) pid);
        new_max = fd + 32;
    }

    ThreadLock(cft_count);

    if (new_max)
    {
        CHILDREN = xrealloc(CHILDREN, new_max * sizeof(pid_t));
        MAX_FD = new_max;
    }

    CHILDREN[fd] = pid;
    ThreadUnlock(cft_count);
}

/*****************************************************************************/

typedef struct
{
    const char *type;
    int pipe_desc[2];
} IOPipe;

static pid_t GenericCreatePipeAndFork(IOPipe *pipes)
{
    for (int i = 0; i < 2; i++)
    {
        if (pipes[i].type && !PipeTypeIsOk(pipes[i].type))
        {
            errno = EINVAL;
            return -1;
        }
    }

    ChildrenFDInit();

    /* Create pair of descriptors to this process. */
    if (pipes[0].type && pipe(pipes[0].pipe_desc) < 0)
    {
        return -1;
    }

    /* Create second pair of descriptors (if exists) to this process.
     * This will allow full I/O operations. */
    if (pipes[1].type && pipe(pipes[1].pipe_desc) < 0)
    {
        close(pipes[0].pipe_desc[0]);
        close(pipes[0].pipe_desc[1]);
        return -1;
    }

    pid_t pid = -1;

    if ((pid = fork()) == (pid_t) -1)
    {
        /* One pipe will be always here. */
        close(pipes[0].pipe_desc[0]);
        close(pipes[0].pipe_desc[1]);

        /* Second pipe is optional so we have to check existence. */
        if (pipes[1].type)
        {
            close(pipes[1].pipe_desc[0]);
            close(pipes[1].pipe_desc[1]);
        }
        return -1;
    }

    /* Ignore SIGCHLD, by setting the handler to SIG_DFL. NOTE: this is
     * different than setting to SIG_IGN. In the latter case no zombies are
     * generated ever and you can't wait() for the child to finish. */
    struct sigaction sa = {
        .sa_handler = SIG_DFL,
    };
    sigemptyset(&sa.sa_mask);
    sigaction(SIGCHLD, &sa, NULL);

    if (pid == 0)                                               /* child */
    {
        /* WARNING only call async-signal-safe functions in child. */

        /* The fork()ed child is always single-threaded, but we are only
         * allowed to call async-signal-safe functions (man 3p fork). */

        // Redmine #2971: reset SIGPIPE signal handler in the child to have a
        // sane behavior of piped commands within child
        signal(SIGPIPE, SIG_DFL);

        /* The child should always accept all signals after it has exec'd,
         * else the child might be unkillable! (happened in ENT-3147). */
        sigset_t sigmask;
        sigemptyset(&sigmask);
        sigprocmask(SIG_SETMASK, &sigmask, NULL);
    }

    ALARM_PID = (pid != 0 ? pid : -1);

    return pid;
}

/*****************************************************************************/

static pid_t CreatePipeAndFork(const char *type, int *pd)
{
    IOPipe pipes[2];
    pipes[0].type = type;
    pipes[1].type = NULL; /* We don't want to create this one. */

    pid_t pid = GenericCreatePipeAndFork(pipes);

    pd[0] = pipes[0].pipe_desc[0];
    pd[1] = pipes[0].pipe_desc[1];

    return pid;
}

/*****************************************************************************/

static pid_t CreatePipesAndFork(const char *type, int *pd, int *pdb)
{
    IOPipe pipes[2];
    /* Both pipes MUST have the same type. */
    pipes[0].type = type;
    pipes[1].type = type;

    pid_t pid =  GenericCreatePipeAndFork(pipes);

    pd[0] = pipes[0].pipe_desc[0];
    pd[1] =  pipes[0].pipe_desc[1];
    pdb[0] = pipes[1].pipe_desc[0];
    pdb[1] = pipes[1].pipe_desc[1];
    return pid;
}

/*****************************************************************************/

IOData cf_popen_full_duplex(const char *command, bool capture_stderr, bool require_full_path)
{
    /* For simplifying reading and writing directions */
    const int READ=0, WRITE=1;
    int child_pipe[2];  /* From child to parent */
    int parent_pipe[2]; /* From parent to child */
    pid_t pid;

    char **argv = ArgSplitCommand(command, NULL);

    fflush(NULL); /* Empty file buffers */
    pid = CreatePipesAndFork("r+t", child_pipe, parent_pipe);

    if (pid == (pid_t) -1)
    {
        Log(LOG_LEVEL_ERR, "Couldn't fork child process: %s", GetErrorStr());
        ArgFree(argv);
        return (IOData) {-1, -1, NULL, NULL};
    }

    else if (pid > 0) // parent
    {
        close(child_pipe[WRITE]);
        close(parent_pipe[READ]);

        IOData io_desc;
        io_desc.write_fd = parent_pipe[WRITE];
        io_desc.read_fd = child_pipe[READ];
        io_desc.read_stream = NULL;
        io_desc.write_stream = NULL;

        ChildrenFDSet(parent_pipe[WRITE], pid);
        ChildrenFDSet(child_pipe[READ], pid);
        ArgFree(argv);
        return io_desc;
    }
    else // child
    {
        close(child_pipe[READ]);
        close(parent_pipe[WRITE]);

        /* Open stdin from parant process and stdout from child */
        if (dup2(parent_pipe[READ], 0) == -1 || dup2(child_pipe[WRITE],1) == -1)
        {
            Log(LOG_LEVEL_ERR, "Can not execute dup2: %s", GetErrorStr());
            _exit(EXIT_FAILURE);
        }

        if (capture_stderr)
        {
            /* Merge stdout/stderr */
            if(dup2(child_pipe[WRITE], 2) == -1)
            {
                Log(LOG_LEVEL_ERR, "Can not execute dup2 for merging stderr: %s",
                    GetErrorStr());
                _exit(EXIT_FAILURE);
            }
        }
        else
        {
            /* leave stderr open */
        }

        close(child_pipe[WRITE]);
        close(parent_pipe[READ]);

        ChildrenFDUnsafeClose();

        int res;
        if (require_full_path)
        {
            res = execv(argv[0], argv);
        }
        else
        {
            res = execvp(argv[0], argv);
        }

        if (res == -1)
        {
            /* NOTE: exec functions return only when error have occurred. */
            Log(LOG_LEVEL_ERR, "Couldn't run '%s'. (%s: %s)",
                argv[0],
                require_full_path ? "execv" : "execvp",
                GetErrorStr());
        }

        /* We shouldn't reach this point */
        _exit(EXIT_FAILURE);
    }
}

FILE *cf_popen_select(const char *command, const char *type, OutputSelect output_select)
{
    int pd[2];
    pid_t pid;
    FILE *pp = NULL;

    char **argv = ArgSplitCommand(command, NULL);

    pid = CreatePipeAndFork(type, pd);
    if (pid == (pid_t) -1)
    {
        ArgFree(argv);
        return NULL;
    }

    if (pid == 0)                                               /* child */
    {
        /* WARNING only call async-signal-safe functions in child. */

        switch (*type)
        {
        case 'r':
            ChildOutputSelectDupClose(pd, output_select);
            break;

        case 'w':

            close(pd[1]);

            if (pd[0] != 0)
            {
                dup2(pd[0], 0);
                close(pd[0]);
            }
        }

        ChildrenFDUnsafeClose();

        if (execv(argv[0], argv) == -1)
        {
            Log(LOG_LEVEL_ERR, "Couldn't run '%s'. (execv: %s)", argv[0], GetErrorStr());
        }

        _exit(EXIT_FAILURE);
    }
    else                                                        /* parent */
    {
        switch (*type)
        {
        case 'r':

            close(pd[1]);

            if ((pp = fdopen(pd[0], type)) == NULL)
            {
                cf_pwait(pid);
                ArgFree(argv);
                return NULL;
            }
            break;

        case 'w':

            close(pd[0]);

            if ((pp = fdopen(pd[1], type)) == NULL)
            {
                cf_pwait(pid);
                ArgFree(argv);
                return NULL;
            }
        }

        ChildrenFDSet(fileno(pp), pid);
        ArgFree(argv);
        return pp;
    }

    ProgrammingError("Unreachable code");
    return NULL;
}

FILE *cf_popen(const char *command, const char *type, bool capture_stderr)
{
    return cf_popen_select(
        command,
        type,
        capture_stderr ? OUTPUT_SELECT_BOTH : OUTPUT_SELECT_STDOUT);
}

/*****************************************************************************/

/*
 * WARNING: this is only allowed to be called from single-threaded code,
 *          because of the safe_chdir() call in the forked child.
 */
FILE *cf_popensetuid(const char *command, const Seq *arglist,
                     const char *type, uid_t uid, gid_t gid, char *chdirv,
                     char *chrootv, ARG_UNUSED int background)
{
    int pd[2];
    pid_t pid;
    FILE *pp = NULL;

    char **argv = ArgSplitCommand(command, arglist);

    pid = CreatePipeAndFork(type, pd);
    if (pid == (pid_t) -1)
    {
        ArgFree(argv);
        return NULL;
    }

    if (pid == 0)                                               /* child */
    {
        /* WARNING only call async-signal-safe functions in child. */

        switch (*type)
        {
        case 'r':

            close(pd[0]);       /* Don't need output from parent */

            if (pd[1] != 1)
            {
                dup2(pd[1], 1); /* Attach pp=pd[1] to our stdout */
                dup2(pd[1], 2); /* Merge stdout/stderr */
                close(pd[1]);
            }

            break;

        case 'w':

            close(pd[1]);

            if (pd[0] != 0)
            {
                dup2(pd[0], 0);
                close(pd[0]);
            }
        }

        ChildrenFDUnsafeClose();

        if (chrootv && (strlen(chrootv) != 0))
        {
            if (chroot(chrootv) == -1)
            {
                Log(LOG_LEVEL_ERR, "Couldn't chroot to '%s'. (chroot: %s)", chrootv, GetErrorStr());
                _exit(EXIT_FAILURE);
            }
        }

        if (chdirv && (strlen(chdirv) != 0))
        {
            if (safe_chdir(chdirv) == -1)
            {
                Log(LOG_LEVEL_ERR, "Couldn't chdir to '%s'. (chdir: %s)", chdirv, GetErrorStr());
                _exit(EXIT_FAILURE);
            }
        }

        if (!CfSetuid(uid, gid))
        {
            _exit(EXIT_FAILURE);
        }

        if (execv(argv[0], argv) == -1)
        {
            Log(LOG_LEVEL_ERR, "Couldn't run '%s'. (execv: %s)", argv[0], GetErrorStr());
        }

        _exit(EXIT_FAILURE);
    }
    else                                                        /* parent */
    {
        switch (*type)
        {
        case 'r':

            close(pd[1]);

            if ((pp = fdopen(pd[0], type)) == NULL)
            {
                cf_pwait(pid);
                ArgFree(argv);
                return NULL;
            }
            break;

        case 'w':

            close(pd[0]);

            if ((pp = fdopen(pd[1], type)) == NULL)
            {
                cf_pwait(pid);
                ArgFree(argv);
                return NULL;
            }
        }

        ChildrenFDSet(fileno(pp), pid);
        ArgFree(argv);
        return pp;
    }

    ProgrammingError("Unreachable code");
    return NULL;
}

/*****************************************************************************/
/* Shell versions of commands - not recommended for security reasons         */
/*****************************************************************************/

FILE *cf_popen_sh_select(const char *command, const char *type, OutputSelect output_select)
{
    int pd[2];
    pid_t pid;
    FILE *pp = NULL;

    pid = CreatePipeAndFork(type, pd);
    if (pid == (pid_t) -1)
    {
        return NULL;
    }

    if (pid == 0)                                               /* child */
    {
        /* WARNING only call async-signal-safe functions in child. */

        switch (*type)
        {
        case 'r':
            ChildOutputSelectDupClose(pd, output_select);

            break;

        case 'w':

            close(pd[1]);

            if (pd[0] != 0)
            {
                dup2(pd[0], 0);
                close(pd[0]);
            }
        }

        ChildrenFDUnsafeClose();

        execl(SHELL_PATH, "sh", "-c", command, NULL);

        Log(LOG_LEVEL_ERR, "Couldn't run: '%s'  (execl: %s)", command, GetErrorStr());
        _exit(EXIT_FAILURE);
    }
    else                                                        /* parent */
    {
        switch (*type)
        {
        case 'r':

            close(pd[1]);

            if ((pp = fdopen(pd[0], type)) == NULL)
            {
                cf_pwait(pid);
                return NULL;
            }
            break;

        case 'w':

            close(pd[0]);

            if ((pp = fdopen(pd[1], type)) == NULL)
            {
                cf_pwait(pid);
                return NULL;
            }
        }

        ChildrenFDSet(fileno(pp), pid);
        return pp;
    }

    ProgrammingError("Unreachable code");
    return NULL;
}

FILE *cf_popen_sh(const char *command, const char *type)
{
    return cf_popen_sh_select(command, type, OUTPUT_SELECT_BOTH);
}

/******************************************************************************/

/*
 * WARNING: this is only allowed to be called from single-threaded code,
 *          because of the safe_chdir() call in the forked child.
 */
FILE *cf_popen_shsetuid(const char *command, const char *type,
                        uid_t uid, gid_t gid, char *chdirv, char *chrootv,
                        ARG_UNUSED int background)
{
    int pd[2];
    pid_t pid;
    FILE *pp = NULL;

    pid = CreatePipeAndFork(type, pd);
    if (pid == (pid_t) -1)
    {
        return NULL;
    }

    if (pid == 0)                                               /* child */
    {
        /* WARNING only call async-signal-safe functions in child. */

        switch (*type)
        {
        case 'r':

            close(pd[0]);       /* Don't need output from parent */

            if (pd[1] != 1)
            {
                dup2(pd[1], 1); /* Attach pp=pd[1] to our stdout */
                dup2(pd[1], 2); /* Merge stdout/stderr */
                close(pd[1]);
            }

            break;

        case 'w':

            close(pd[1]);

            if (pd[0] != 0)
            {
                dup2(pd[0], 0);
                close(pd[0]);
            }
        }

        ChildrenFDUnsafeClose();

        if (chrootv && (strlen(chrootv) != 0))
        {
            if (chroot(chrootv) == -1)
            {
                Log(LOG_LEVEL_ERR, "Couldn't chroot to '%s'. (chroot: %s)", chrootv, GetErrorStr());
                _exit(EXIT_FAILURE);
            }
        }

        if (chdirv && (strlen(chdirv) != 0))
        {
            if (safe_chdir(chdirv) == -1)
            {
                Log(LOG_LEVEL_ERR, "Couldn't chdir to '%s'. (chdir: %s)", chdirv, GetErrorStr());
                _exit(EXIT_FAILURE);
            }
        }

        if (!CfSetuid(uid, gid))
        {
            _exit(EXIT_FAILURE);
        }

        execl(SHELL_PATH, "sh", "-c", command, NULL);

        Log(LOG_LEVEL_ERR, "Couldn't run: '%s'  (execl: %s)", command, GetErrorStr());
        _exit(EXIT_FAILURE);
    }
    else                                                        /* parent */
    {
        switch (*type)
        {
        case 'r':

            close(pd[1]);

            if ((pp = fdopen(pd[0], type)) == NULL)
            {
                cf_pwait(pid);
                return NULL;
            }
            break;

        case 'w':

            close(pd[0]);

            if ((pp = fdopen(pd[1], type)) == NULL)
            {
                cf_pwait(pid);
                return NULL;
            }
        }

        ChildrenFDSet(fileno(pp), pid);
        return pp;
    }

    ProgrammingError("Unreachable code");
    return NULL;
}

static int cf_pwait(pid_t pid)
{
    Log(LOG_LEVEL_DEBUG,
        "cf_pwait - waiting for process %jd", (intmax_t) pid);

    int status;
    while (waitpid(pid, &status, 0) < 0)
    {
        if (errno != EINTR)
        {
            Log(LOG_LEVEL_ERR,
                "Waiting for child PID %jd failed (waitpid: %s)",
                (intmax_t) pid, GetErrorStr());
            return -1;
        }
    }

    if (!WIFEXITED(status))
    {
        Log(LOG_LEVEL_VERBOSE,
            "Child PID %jd exited abnormally (%s)", (intmax_t) pid,
            WIFSIGNALED(status) ? "signalled" : (
                WIFSTOPPED(status) ? "stopped" : (
                    WIFCONTINUED(status) ? "continued" : "unknown" )));
        return -1;
    }

    int retcode = WEXITSTATUS(status);

    Log(LOG_LEVEL_DEBUG, "cf_pwait - process %jd exited with code: %d",
        (intmax_t) pid, retcode);
    return retcode;
}

/*******************************************************************/

/**
 * Closes the pipe without waiting the child.
 *
 * @param pp pipe to the child process
 */
void cf_pclose_nowait(FILE *pp)
{
    if (fclose(pp) == EOF)
    {
        Log(LOG_LEVEL_ERR,
            "Could not close the pipe to the executed subcommand (fclose: %s)",
            GetErrorStr());
    }
}

/**
 * Closes the pipe and wait()s for PID of the child,
 * in order to reap the zombies.
 */
int cf_pclose(FILE *pp)
{
    int fd = fileno(pp);
    pid_t pid;

    ThreadLock(cft_count);

    if (CHILDREN == NULL)       /* popen hasn't been called */
    {
        ThreadUnlock(cft_count);
        fclose(pp);
        return -1;
    }

    ALARM_PID = -1;

    if (fd >= MAX_FD)
    {
        ThreadUnlock(cft_count);
        Log(LOG_LEVEL_ERR,
            "File descriptor %d of child higher than MAX_FD in cf_pclose!",
            fd);
        fclose(pp);
        return -1;
    }

    pid = CHILDREN[fd];
    CHILDREN[fd] = 0;
    ThreadUnlock(cft_count);

    if (fclose(pp) == EOF)
    {
        Log(LOG_LEVEL_ERR,
            "Could not close the pipe to the executed subcommand (fclose: %s)",
            GetErrorStr());
    }

    return cf_pwait(pid);
}

int cf_pclose_full_duplex_side(int fd)
{
    ThreadLock(cft_count);

    if (CHILDREN == NULL)       /* popen hasn't been called */
    {
        ThreadUnlock(cft_count);
        close(fd);
        return -1;
    }

    if (fd >= MAX_FD)
    {
        ThreadUnlock(cft_count);
        Log(LOG_LEVEL_ERR,
            "File descriptor %d of child higher than MAX_FD in cf_pclose_full_duplex_side!",
            fd);
    }
    else
    {
        CHILDREN[fd] = 0;
        ThreadUnlock(cft_count);
    }
    return close(fd);
}


/* We are assuming that read_fd part will be always open at this point. */
int cf_pclose_full_duplex(IOData *data)
{
    assert(data != NULL);
    ThreadLock(cft_count);

    if (CHILDREN == NULL)
    {
        ThreadUnlock(cft_count);
        if (data->read_stream != NULL)
        {
            // fclose closes the underlying fd / socket,
            // but we need the fd for handling of processes below.
            assert(data->read_fd >= 0);
            fclose(data->read_stream);
        }
        else if (data->read_fd >= 0)
        {
            close(data->read_fd);
        }

        if (data->write_stream != NULL)
        {
            // fclose closes the underlying fd / socket,
            // but we need the fd for handling of processes below.
            assert(data->write_fd >= 0);
            fclose(data->write_stream);
        }
        else if (data->write_fd >= 0)
        {
            close(data->write_fd);
        }
        return -1;
    }

    ALARM_PID = -1;
    pid_t pid = 0;

    /* Safe as pipes[1] is -1 if not initialized */
    if (data->read_fd >= MAX_FD || data->write_fd >= MAX_FD)
    {
        ThreadUnlock(cft_count);
        Log(LOG_LEVEL_ERR,
            "File descriptor %d of child higher than MAX_FD in cf_pclose!",
            data->read_fd > data->write_fd ? data->read_fd : data->write_fd);
    }
    else
    {
        pid = CHILDREN[data->read_fd];
        if (data->write_fd >= 0)
        {
            assert(pid == CHILDREN[data->write_fd]);
            CHILDREN[data->write_fd] = 0;
        }
        CHILDREN[data->read_fd] = 0;
        ThreadUnlock(cft_count);
    }

    if (data->read_stream != NULL)
    {
        // Stream is open, fclose it
        if (fclose(data->read_stream) != 0)
        {
            return -1;
        }
    }
    else
    {
        // No stream, just close fd
        if (close(data->read_fd) != 0)
        {
            return -1;
        }
    }

    if (data->write_fd >= 0)
    {
        // write fd needs to be closed
        if (data->write_stream != NULL)
        {
            // Stream is open, fclose it
            if (fclose(data->write_stream) != 0)
            {
                return -1;
            }
        }
        else
        {
            // No stream, close fd directly
            if (close(data->write_fd) != 0)
            {
                return -1;
            }
        }
    }

    if (pid == 0)
    {
        return -1;
    }

    return cf_pwait(pid);
}

bool PipeToPid(pid_t *pid, FILE *pp)
{
    int fd = fileno(pp);
    ThreadLock(cft_count);

    if (CHILDREN == NULL)       /* popen hasn't been called */
    {
        ThreadUnlock(cft_count);
        return false;
    }

    *pid = CHILDREN[fd];
    ThreadUnlock(cft_count);

    return true;
}

/*******************************************************************/

static bool CfSetuid(uid_t uid, gid_t gid)
{
    struct passwd *pw;

    if (gid != (gid_t) - 1)
    {
        Log(LOG_LEVEL_VERBOSE, "Changing gid to %ju", (uintmax_t)gid);

        if (setgid(gid) == -1)
        {
            Log(LOG_LEVEL_ERR, "Couldn't set gid to '%ju'. (setgid: %s)", (uintmax_t)gid, GetErrorStr());
            return false;
        }

        /* Now eliminate any residual privileged groups */

        if ((pw = getpwuid(uid)) == NULL)
        {
            Log(LOG_LEVEL_ERR, "Unable to get login groups when dropping privilege to '%ju'. (getpwuid: %s)", (uintmax_t)uid, GetErrorStr());
            return false;
        }

        if (initgroups(pw->pw_name, pw->pw_gid) == -1)
        {
            Log(LOG_LEVEL_ERR, "Unable to set login groups when dropping privilege to '%s=%ju'. (initgroups: %s)", pw->pw_name,
                  (uintmax_t)uid, GetErrorStr());
            return false;
        }
    }

    if (uid != (uid_t) - 1)
    {
        Log(LOG_LEVEL_VERBOSE, "Changing uid to '%ju'", (uintmax_t)uid);

        if (setuid(uid) == -1)
        {
            Log(LOG_LEVEL_ERR, "Couldn't set uid to '%ju'. (setuid: %s)", (uintmax_t)uid, GetErrorStr());
            return false;
        }
    }

    return true;
}

/* For Windows we need a different method because select() does not */
/* work with non-socket file descriptors. */
int PipeIsReadWriteReady(const IOData *io, int timeout_sec)
{
    fd_set  rset;
    FD_ZERO(&rset);
    FD_SET(io->read_fd, &rset);

    struct timeval tv = {
        .tv_sec = timeout_sec,
        .tv_usec = 0,
    };

    Log(LOG_LEVEL_DEBUG,
        "PipeIsReadWriteReady: wait max %ds for data on fd %d",
        timeout_sec, io->read_fd);

    int ret = select(io->read_fd + 1, &rset, NULL, NULL, &tv);

    if (ret < 0)
    {
        Log(LOG_LEVEL_VERBOSE, "Failed checking for data (select: %s)",
            GetErrorStr());
        return -1;
    }
    else if (FD_ISSET(io->read_fd, &rset))
    {
        return io->read_fd;
    }
    else if (ret == 0)
    {
        /* timeout_sec has elapsed but no data was available. */
        return 0;
    }
    else
    {
        UnexpectedError("select() returned > 0 but our only fd is not set!");
        return -1;
    }
}