-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoproc.c
1524 lines (1247 loc) · 56.9 KB
/
coproc.c
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
/*
* libslack - https://libslack.org
*
* Copyright (C) 1999-2004, 2010, 2020-2023 raf <[email protected]>
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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, see <https://www.gnu.org/licenses/>.
*
* 20230824 raf <[email protected]>
*/
/*
=head1 NAME
I<libslack(coproc)> - coprocess module
=head1 SYNOPSIS
#include <slack/std.h>
#include <slack/coproc.h>
pid_t coproc_open(int *to, int *from, int *err, const char *cmd, char * const *argv, char * const *envv, void (*action)(void *data), void *data);
int coproc_close(pid_t pid, int *to, int *from, int *err);
pid_t coproc_pty_open(int *pty_user_fd, char *pty_device_name, size_t pty_device_name_size, const struct termios *pty_device_termios, const struct winsize *pty_device_winsize, const char *cmd, char * const *argv, char * const *envv, void (*action)(void *data), void *data);
int coproc_pty_close(pid_t pid, int *pty_user_fd, const char *pty_device_name);
=head1 DESCRIPTION
This module contains functions for creating coprocesses that use either
pipes or pseudo terminals for communication.
=over 4
=cut
*/
#ifndef _BSD_SOURCE
#define _BSD_SOURCE /* For snprintf() on OpenBSD-4.7 */
#endif
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE /* New name for _BSD_SOURCE */
#endif
#include "config.h"
#include "std.h"
#include <sys/wait.h>
#include "coproc.h"
#include "daemon.h"
#include "pseudo.h"
#include "err.h"
#ifndef HAVE_SNPRINTF
#include "snprintf.h"
#endif
#ifndef TEST
extern char **environ;
#ifndef SHELL_META_CHARACTERS
#define SHELL_META_CHARACTERS "|&;()<>[]{}$`'~\"\\*? \t\r\n"
#endif
#ifndef DEFAULT_ROOT_PATH
#define DEFAULT_ROOT_PATH "/bin:/usr/bin"
#endif
#ifndef DEFAULT_USER_PATH
#define DEFAULT_USER_PATH ":/bin:/usr/bin"
#endif
#define RD 0
#define WR 1
/*
=item C<pid_t coproc_open(int *to, int *from, int *err, const char *cmd, char * const *argv, char * const *envv, void (*action)(void *data), void *data)>
Starts a coprocess. C<cmd> is the name of the process or a shell command.
C<argv> is the command line argument vector to be passed to I<execve(2)>.
C<envv> is the environment variable vector to be passed to I<execve(2)>. If
C<envv> is C<null>, the current environment is used. If C<cmd> is the name
of a program, C<argv> must not be C<null>. If C<cmd> contains shell
metacharacters, it will executed by C<sh -c> and C<argv> must be C<null>.
This provides protection from unintentionally invoking C<sh -c>. If C<cmd>
does not contain any shell metacharacters, but does contain a slash
character (C</>), it is passed directly to I<execve(2)>. If it doesn't
contain a slash character, we search for the executable in the directories
specified by the C<PATH> environment variable. If the C<PATH> environment
variable is not set, a default path is used: C</bin:/usr/bin> for I<root>;
C<:/bin:/usr/bin> for other users. If permission is denied for a file
(I<execve(2)> returns C<EACCES>), then searching continues. If the header of
a file isn't recognised (I<execve(2)> returns C<ENOEXEC>), then C</bin/sh>
will be executed with C<cmd> as its first argument. This is done so that
shell scripts without a C<#!> line can be used. If this attempt fails, no
further searching is done. Communication with the coprocess occurs over
pipes. Data written to C<*to> can be read from the standard input of the
coprocess. Data written to the standard output or standard error of the
coprocess may be read from C<*from> and C<*err>, respectively. If the
function pointer C<action> is not C<null>, it is invoked in the child
process between the calls to I<fork(2)> and I<execve(2)>. Specifically, it
is invoked before the pipes are duplicated onto C<stdin>, C<stdout> and
C<stderr>. I<data> is passed as the argument to I<action>. This is useful
when you need to prevent the coprocess from inheriting certain process
attributes. It can be used to ignore signals, set default signal handlers,
modify the signal mask and close files. On success, returns the process id
of the coprocess. On error, returns C<-1> with C<errno> set appropriately.
Note: That this can only be used with coprocesses that do not buffer I/O or
that explicitly set line buffering (or no buffering) with I<setbuf(3)> or
I<setvbuf(3)>. If a potential coprocess uses standard I/O, and you don't
have access to the source code, you will need to use I<coproc_pty_open(3)>
instead.
B<Note: If I<cmd> does contain shell metacharacters, make sure that the
application provides the command to execute. If the command comes from
outside the application, do not trust it. Verify that it is safe to
execute.>
=cut
*/
static char * const *new_shargv(const char *cmd, char * const *argv)
{
char **shargv;
int nargs = 0;
while (argv[nargs])
++nargs;
if (!(shargv = malloc((nargs + 2) * sizeof(char **))))
return NULL;
shargv[0] = "/bin/sh";
shargv[1] = (char *)cmd;
for (nargs = 1; argv[nargs]; ++nargs)
shargv[nargs + 1] = argv[nargs];
shargv[nargs + 1] = NULL;
return (char * const *)shargv;
}
static void do_exec(int has_meta, const char *cmd, char * const *argv, char * const *envv)
{
if (has_meta)
{
char const *shargv[4];
shargv[0] = "sh";
shargv[1] = "-c";
shargv[2] = cmd;
shargv[3] = NULL;
execve("/bin/sh", (char * const *)shargv, (envv) ? envv : environ);
}
else if (strchr(cmd, PATH_SEP))
{
execve(cmd, argv, (envv) ? envv : environ);
if (errno == ENOEXEC)
{
char * const *shargv = new_shargv(cmd, argv);
execve("/bin/sh", shargv, (envv) ? envv : environ);
free((void *)shargv);
}
}
else
{
char *path, *s, *f;
char cmdbuf[512];
if (!(path = getenv("PATH")))
path = geteuid() ? DEFAULT_USER_PATH : DEFAULT_ROOT_PATH;
for (s = path; s; s = (*f) ? f + 1 : NULL)
{
if (!(f = strchr(s, PATH_LIST_SEP)))
f = s + strlen(s);
if (snprintf(cmdbuf, 512, "%.*s%s%s", (int)(f - s), s, (f - s) ? PATH_SEP_STR : "", cmd) >= 512)
continue;
if (execve(cmdbuf, argv, (envv) ? envv : environ) == -1)
{
if (errno == EACCES)
continue;
if (errno == ENOEXEC)
{
char * const *shargv = new_shargv(cmdbuf, argv);
execve("/bin/sh", shargv, (envv) ? envv : environ);
free((void *)shargv);
break;
}
}
}
}
}
pid_t coproc_open(int *to, int *from, int *err, const char *cmd, char * const *argv, char * const *envv, void (*action)(void *data), void *data)
{
int to_pipe[2]; /* pipe for writing to the coprocess */
int from_pipe[2]; /* pipe for reading from the coprocess */
int err_pipe[2]; /* pipe for reading errors from the coprocess */
pid_t pid; /* process id of the coprocess */
int has_meta; /* does cmd contain shell meta characters? */
/* Check arguments */
if (!to || !from || !err || !cmd)
return set_errno(EINVAL);
has_meta = (cmd[strcspn(cmd, SHELL_META_CHARACTERS)] != '\0');
if ((has_meta && argv) || (!has_meta && !argv))
return set_errno(EINVAL);
/* Create pipes */
if (pipe(to_pipe) == -1)
return -1;
if (pipe(from_pipe) == -1)
{
close(to_pipe[RD]);
close(to_pipe[WR]);
return -1;
}
if (pipe(err_pipe) == -1)
{
close(to_pipe[RD]);
close(to_pipe[WR]);
close(from_pipe[RD]);
close(from_pipe[WR]);
return -1;
}
/* Create child process */
switch (pid = fork())
{
case -1:
{
close(to_pipe[RD]);
close(to_pipe[WR]);
close(from_pipe[RD]);
close(from_pipe[WR]);
close(err_pipe[RD]);
close(err_pipe[WR]);
return -1;
}
case 0:
{
/* Adjust process attributes */
if (action)
action(data);
/* Attach pipes to stdin, stdout and stderr */
close(to_pipe[WR]);
close(from_pipe[RD]);
close(err_pipe[RD]);
if (to_pipe[RD] != STDIN_FILENO)
{
if (dup2(to_pipe[RD], STDIN_FILENO) == -1)
_exit(1);
close(to_pipe[RD]);
}
if (from_pipe[WR] != STDOUT_FILENO)
{
if (dup2(from_pipe[WR], STDOUT_FILENO) == -1)
_exit(1);
close(from_pipe[WR]);
}
if (err_pipe[WR] != STDERR_FILENO)
{
if (dup2(err_pipe[WR], STDERR_FILENO) == -1)
_exit(1);
close(err_pipe[WR]);
}
/* Execute co-process */
do_exec(has_meta, cmd, argv, envv);
_exit(EXIT_FAILURE);
}
default:
{
/* Return the pipe descriptors and the coprocess id to the caller */
close(to_pipe[RD]);
close(from_pipe[WR]);
close(err_pipe[WR]);
*to = to_pipe[WR];
*from = from_pipe[RD];
*err = err_pipe[RD];
return pid;
}
}
}
/*
=item C<int coproc_close(pid_t pid, int *to, int *from, int *err)>
Closes the coprocess referred to by C<pid> which must have been obtained
from I<coproc_open(3)>. C<*to>, C<*from> and C<*err> will be closed and set
to C<-1> if they are not already C<-1>. The current process will then wait
for the coprocess to terminate by calling I<waitpid(2)>. On success, returns
the status of the child process as determined by I<waitpid(2)>. On error,
returns C<-1> with C<errno> set appropriately. B<Note:> If I<waitpid(2)> is
interrupted by a signal, I<coproc_close(3)> will return C<-1> with C<errno>
set to C<EINTR>. The caller has to call I<coproc_close(3)> (or just
I<waitpid(2)>) again until it succeeds (or a real error occurs).
=cut
*/
int coproc_close(pid_t pid, int *to, int *from, int *err)
{
int status = 0;
if (pid <= 0)
return set_errno(EINVAL);
if (to && *to != -1)
{
close(*to);
*to = -1;
}
if (from && *from != -1)
{
close(*from);
*from = -1;
}
if (err && *err != -1)
{
close(*err);
*err = -1;
}
if (waitpid(pid, &status, 0) == -1)
return -1;
return status;
}
/*
=item C<pid_t coproc_pty_open(int *pty_user_fd, char *pty_device_name, size_t pty_device_name_size, const struct termios *pty_device_termios, const struct winsize *pty_device_winsize, const char *cmd, char * const *argv, char * const *envv, void (*action)(void *data), void *data)>
Equivalent to I<coproc_open(3)> except that communication with the coprocess
occurs over a pseudo terminal. This is useful when the coprocess uses
standard I/O, and you don't have the source code. Standard I/O is fully
buffered unless connected to a terminal. C<*pty_user_fd> is set to the user
(or controlling process) side of a pseudo terminal. Data written to
C<*pty_user_fd> can be read from the standard input of the coprocess. Data
written to the standard output or standard error of the coprocess can be
read from C<*pty_user_fd>. The device name of the coprocess side of the
pseudo terminal is stored in the buffer pointed to by C<pty_device_name>
which must be able to store at least 64 bytes. C<pty_device_name_size> is
the size of the buffer pointed to by C<pty_device_name>. No more than
C<pty_device_name_size> bytes will be written into the buffer pointed to by
C<pty_device_name> including the terminating C<nul> byte. If
C<pty_device_termios> is not null, it is passed to I<tcsetattr(3)> with the
command C<TCSANOW> to set the terminal attributes of the device on the
coprocess side of the pseudo terminal. If C<pty_device_winsize> is not null,
it is passed to I<ioctl(2)> with the command C<TIOCSWINSZ> to set the window
size of the device on the coprocess side of the pseudo terminal. On success,
returns C<0>. On error, returns C<-1> with C<errno> set appropriately.
=cut
*/
pid_t coproc_pty_open(int *pty_user_fd, char *pty_device_name, size_t pty_device_name_size, const struct termios *pty_device_termios, const struct winsize *pty_device_winsize, const char *cmd, char * const *argv, char * const *envv, void (*action)(void *data), void *data)
{
pid_t pid; /* process id of the coprocess */
int has_meta; /* does cmd contain shell meta characters? */
/* Check arguments */
if (!pty_user_fd || !pty_device_name || pty_device_name_size < 64 || !cmd)
return set_errno(EINVAL);
has_meta = (cmd[strcspn(cmd, SHELL_META_CHARACTERS)] != '\0');
if ((has_meta && argv) || (!has_meta && !argv))
return set_errno(EINVAL);
/* Create pty and child process */
switch (pid = pty_fork(pty_user_fd, pty_device_name, pty_device_name_size, pty_device_termios, pty_device_winsize))
{
case -1:
return -1;
case 0:
{
/* Adjust process attributes */
if (action)
action(data);
/* Execute co-process */
do_exec(has_meta, cmd, argv, envv);
_exit(EXIT_FAILURE);
}
default:
return pid;
}
}
/*
=item C<int coproc_pty_close(pid_t pid, int *pty_user_fd, const char *pty_device_name)>
Closes the coprocess referred to by C<pid> which must have been obtained
from I<coproc_pty_open(3)>. The coprocess side of the pseudo terminal is
released with I<pty_release(3)> and C<*pty_user_fd> is closed and set to
C<-1> if it is not already C<-1>. The current process will then wait for the
coprocess to terminate by calling I<waitpid(2)>. On success, returns the
status of the child process as determined by I<waitpid(2)>. On error,
returns C<-1> with C<errno> set appropriately. B<Note:> If I<waitpid(2)> is
interrupted by a signal, I<coproc_close(3)> will return C<-1> with C<errno>
set to C<EINTR>. The caller has to call I<coproc_close(3)> (or just
I<waitpid(2)>) again until it succeeds (or until a real error occurs).
=cut
*/
int coproc_pty_close(pid_t pid, int *pty_user_fd, const char *pty_device_name)
{
int status = 0;
if (pid <= 0)
return set_errno(EINVAL);
if (pty_user_fd && *pty_user_fd != -1)
{
pty_release(pty_device_name);
close(*pty_user_fd);
*pty_user_fd = -1;
}
if (waitpid(pid, &status, 0) == -1)
return -1;
return status;
}
/*
=back
=head1 ERRORS
Additional errors may be generated and returned from the underlying system
calls. See their manual pages.
=over 4
=item C<EINVAL>
Invalid arguments were passed to I<coproc_open(3)>, I<coproc_close(3)>,
I<coproc_pty_open(3)> or I<coproc_pty_close(3)>.
=back
=head1 MT-Level
I<MT-Safe> (I<coproc_pty_open(3)> is I<MT-Safe> iff the I<pseudo(3)> module
is I<MT-Safe>).
=head1 EXAMPLES
The following examples add two numbers from the command line using dc as a coprocess
in four different ways.
This version uses pipes and does not use C<sh -c>.
#include <slack/std.h>
#include <slack/coproc.h>
int main(int ac, char **av)
{
if (ac == 3)
{
char *argv[2] = { "dc", NULL };
int to, from, err, status;
char buf[BUFSIZ];
ssize_t bytes;
pid_t pid;
// Start the coprocess (without using sh -c)
if ((pid = coproc_open(&to, &from, &err, "dc", argv, NULL, NULL, NULL)) == (pid_t)-1)
{
fprintf(stderr, "coproc_open(dc) failed: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Send it input and read its output
snprintf(buf, BUFSIZ, "%s %s + p\n", av[1], av[2]);
write(to, buf, strlen(buf));
bytes = read(from, buf, BUFSIZ);
printf("%*.*s", bytes, bytes, buf);
// Stop the coprocess (it's ok if you close to, from and/or err beforehand)
while ((status = coproc_close(pid, &to, &from, &err)) == -1 && errno == EINTR)
{}
if (status == -1)
{
fprintf(stderr, "coproc_close(dc) failed: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Evaluate its exit status
if (WIFSIGNALED(status))
{
fprintf(stderr, "dc was killed by signal %d\n", WTERMSIG(status));
return EXIT_FAILURE;
}
if (WIFEXITED(status) && WEXITSTATUS(status) != EXIT_SUCCESS)
{
fprintf(stderr, "dc was killed by signal %d\n", WEXITSTATUS(status));
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
This version uses pipes and C<sh -c>.
#include <slack/std.h>
#include <slack/coproc.h>
int main(int ac, char **av)
{
if (ac == 3)
{
int to, from, err, status;
char buf[BUFSIZ];
ssize_t bytes;
pid_t pid;
// Start the coprocess (using sh -c)
if ((pid = coproc_open(&to, &from, &err, "dc 2>&1", NULL, NULL, NULL, NULL)) == (pid_t)-1)
{
fprintf(stderr, "coproc_open(dc) failed: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Send it input and read its output
snprintf(buf, BUFSIZ, "%s %s + p\n", av[1], av[2]);
write(to, buf, strlen(buf));
bytes = read(from, buf, BUFSIZ);
printf("%*.*s", bytes, bytes, buf);
// Stop the coprocess (it's ok if you close to, from and/or err beforehand)
while ((status = coproc_close(pid, &to, &from, &err)) == -1 && errno == EINTR)
{}
if (status == -1)
{
fprintf(stderr, "coproc_close(dc) failed: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Evaluate its exit status
if (WIFSIGNALED(status))
{
fprintf(stderr, "dc was killed by signal %d\n", WTERMSIG(status));
return EXIT_FAILURE;
}
if (WIFEXITED(status) && WEXITSTATUS(status) != EXIT_SUCCESS)
{
fprintf(stderr, "dc was killed by signal %d\n", WEXITSTATUS(status));
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
This version uses a pseudo terminal and does not use C<sh -c>.
#include <slack/std.h>
#include <slack/coproc.h>
int tty_noecho(int fd)
{
struct termios attr[1];
if (tcgetattr(fd, attr) == -1)
return -1;
attr->c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
#ifdef ONLCR
attr->c_oflag &= ~ONLCR;
#endif
return tcsetattr(fd, TCSANOW, attr);
}
int main(int ac, char **av)
{
if (ac == 3)
{
char *argv[2] = { "dc", NULL };
struct termios attr[1];
char eof = CEOF;
int pty_user_fd, status;
char pty_device_name[64];
char buf[BUFSIZ];
ssize_t bytes;
pid_t pid;
// Start the coprocess (without using sh -c)
if ((pid = coproc_pty_open(&pty_user_fd, pty_device_name, 64, NULL, NULL, "dc", argv, NULL, NULL, NULL)) == (pid_t)-1)
{
fprintf(stderr, "coproc_pty_open(dc) failed: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Turn off echo so we don't read back what we are about to write
if (tty_noecho(pty_user_fd) == -1)
fprintf(stderr, "tty_noecho(pty_user_fd) failed: %s\n", strerror(errno));
// Send it input and eof and read its output
snprintf(buf, BUFSIZ, "%s %s + p\n", av[1], av[2]);
write(pty_user_fd, buf, strlen(buf));
if (tcgetattr(pty_user_fd, attr) != -1)
eof = attr->c_cc[VEOF];
write(pty_user_fd, &eof, 1);
while ((bytes = read(pty_user_fd, buf, BUFSIZ)) > 0)
printf("%*.*s", bytes, bytes, buf);
if (bytes == -1 && errno != EIO)
fprintf(stderr, "read(pty_user_fd) failed: %s\n", strerror(errno));
// Stop the coprocess (pty_user_fd must not be closed beforehand)
while ((status = coproc_pty_close(pid, &pty_user_fd, pty_device_name)) == -1 && errno == EINTR)
{}
if (status == -1)
{
fprintf(stderr, "coproc_pty_close(dc) failed: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Evaluate its exit status
if (WIFSIGNALED(status))
{
fprintf(stderr, "dc was killed by signal %d\n", WTERMSIG(status));
return EXIT_FAILURE;
}
if (WIFEXITED(status) && WEXITSTATUS(status) != EXIT_SUCCESS)
{
fprintf(stderr, "dc was killed by signal %d\n", WEXITSTATUS(status));
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
This version uses a pseudo terminal and C<sh -c>.
#include <slack/std.h>
#include <slack/coproc.h>
int tty_noecho(int fd)
{
struct termios attr[1];
if (tcgetattr(fd, attr) == -1)
return -1;
attr->c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
#ifdef ONLCR
attr->c_oflag &= ~ONLCR;
#endif
return tcsetattr(fd, TCSANOW, attr);
}
int main(int ac, char **av)
{
if (ac == 3)
{
int pty_user_fd, status;
char pty_device_name[64];
char buf[BUFSIZ];
struct termios attr[1];
char eof = CEOF;
ssize_t bytes;
pid_t pid;
// Start the coprocess (without using sh -c)
if ((pid = coproc_pty_open(&pty_user_fd, pty_device_name, 64, NULL, NULL, "dc 2>&1", NULL, NULL, NULL, NULL)) == (pid_t)-1)
{
fprintf(stderr, "coproc_pty_open(dc) failed: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Turn off echo so we don't read back what we are about to write
if (tty_noecho(pty_user_fd) == -1)
fprintf(stderr, "tty_noecho(pty_user_fd) failed: %s\n", strerror(errno));
// Send it input and eof and read its output
snprintf(buf, BUFSIZ, "%s %s + p\n", av[1], av[2]);
write(pty_user_fd, buf, strlen(buf));
if (tcgetattr(pty_user_fd, attr) != -1)
eof = attr->c_cc[VEOF];
write(pty_user_fd, &eof, 1);
while ((bytes = read(pty_user_fd, buf, BUFSIZ)) > 0)
printf("%*.*s", bytes, bytes, buf);
if (bytes == -1 && errno != EIO)
fprintf(stderr, "read(pty_user_fd) failed: %s\n", strerror(errno));
// Stop the coprocess (pty_user_fd must not be closed beforehand)
while ((status = coproc_pty_close(pid, &pty_user_fd, pty_device_name)) == -1 && errno == EINTR)
{}
if (status == -1)
{
fprintf(stderr, "coproc_pty_close(dc) failed: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Evaluate its exit status
if (WIFSIGNALED(status))
{
fprintf(stderr, "dc was killed by signal %d\n", WTERMSIG(status));
return EXIT_FAILURE;
}
if (WIFEXITED(status) && WEXITSTATUS(status) != EXIT_SUCCESS)
{
fprintf(stderr, "dc was killed by signal %d\n", WEXITSTATUS(status));
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
=head1 SEE ALSO
I<libslack(3)>,
I<execve(2)>,
I<system(3)>,
I<popen(3)>,
I<waitpid(2)>,
I<sh(1)>,
I<pseudo(3>>
=head1 AUTHOR
20230824 raf <[email protected]>
=cut
*/
#endif
#ifdef TEST
#include <fcntl.h>
#include "fio.h"
#include "str.h"
static int cwd_in_path()
{
const char *path = getenv("PATH");
const char *s, *r;
if (!path)
return 1;
for (r = path, s = strchr(path, PATH_LIST_SEP); s; r = s, s = strchr(s + 1, PATH_LIST_SEP))
if ((r == s) || (s - r == 1 && r[0] == '.') || (s - r == 2 && r[0] == ':' && r[1] == '.'))
return 1;
if (r[0] == '\0' || (r[0] == ':' && r[1] == '\0') || (r[0] == ':' && r[1] == '.' && r[2] == '\0'))
return 1;
return 0;
}
static void print_error_details(char *buf, int bytes, char *expected)
{
String *qbuf;
if (bytes == -1)
printf("(%s)\n", strerror(errno));
else
{
buf[bytes] = '\0';
qbuf = encode(buf, "\a\b\t\n\v\f\r", "abtnvfr", '\\', 1);
printf("read <%s> expected <%s>\n", cstr(qbuf), expected);
str_destroy(&qbuf);
}
}
int main()
{
int errors = 0;
int to, from, err, pty_user_fd;
int status;
pid_t pid;
int fd;
char *argv[2] = { "cat", NULL };
char *argv2[5] = { "arkleseizure", "a", "b", "c", NULL };
char buf[BUFSIZ];
char pty_device_name[64];
ssize_t bytes;
printf("Testing: %s\n", "coproc");
/* Test coproc_open("cat") - searches path, locating binary executable */
if ((pid = coproc_open(&to, &from, &err, "cat", argv, NULL, NULL, NULL)) == -1)
++errors, printf("Test1: coproc_open(\"cat\") failed (%s)\n", strerror(errno));
else
{
if (write_timeout(to, 5, 0) == -1 || write(to, "abc\n", 4) != 4)
++errors, printf("Test2: write_timeout(to) or write(to, \"abc\\n\") failed (%s)\n", strerror(errno));
else if (write_timeout(to, 5, 0) == -1 || write(to, "def\n", 4) != 4)
++errors, printf("Test3: write_timeout(to) or write(to, \"def\\n\") failed (%s)\n", strerror(errno));
else if (write_timeout(to, 5, 0) == -1 || write(to, "ghi\n", 4) != 4)
++errors, printf("Test4: write_timeout(to) or write(to, \"ghi\\n\") failed (%s)\n", strerror(errno));
else
{
close(to);
to = -1;
if (read_timeout(from, 5, 0) == -1)
++errors, printf("Test5: read_timeout(from) failed (%s)\n", strerror(errno));
else if ((bytes = read(from, buf, 4)) != 4)
{
++errors, printf("Test6: read(from) failed (returned %d, not %d) ", (int)bytes, 4);
print_error_details(buf, (int)bytes, "abc\\n");
}
else if (memcmp(buf, "abc\n", 4))
++errors, printf("Test7: read(from) failed (read \"%.4s\", not \"%.4s\")\n", buf, "abc\n");
else if (read_timeout(from, 5, 0) == -1)
++errors, printf("Test8: read_timeout(from) failed (%s)\n", strerror(errno));
else if ((bytes = read(from, buf, 4)) != 4)
{
++errors, printf("Test9: read(from) failed (returned %d, not %d) ", (int)bytes, 4);
print_error_details(buf, (int)bytes, "def\\n");
}
else if (memcmp(buf, "def\n", 4))
++errors, printf("Test10: read(from) failed (read \"%.4s\", not \"%.4s\")\n", buf, "def\n");
else if (read_timeout(from, 5, 0) == -1)
++errors, printf("Test11: read_timeout(from) failed (%s)\n", strerror(errno));
else if ((bytes = read(from, buf, 4)) != 4)
{
++errors, printf("Test12: read(from) failed (returned %d, not %d) ", (int)bytes, 4);
print_error_details(buf, (int)bytes, "ghi\\n");
}
else if (memcmp(buf, "ghi\n", 4))
++errors, printf("Test13: read(from) failed (read \"%.4s\", not \"%.4s\")\n", buf, "ghi\n");
else if (read_timeout(from, 5, 0) == -1)
++errors, printf("Test14: read_timeout(from) failed (%s)\n", strerror(errno));
else if ((bytes = read(from, buf, 4)) != 0)
{
++errors, printf("Test15: read(from) failed (returned %d, not %d) ", (int)bytes, 0);
print_error_details(buf, (int)bytes, "");
}
if ((status = coproc_close(pid, &to, &from, &err)) == -1)
++errors, printf("Test16: coproc_close() failed (%s)\n", strerror(errno));
else if (WIFSIGNALED(status))
++errors, printf("Test17: coproc(\"cat\") received signal %d\n", WTERMSIG(status));
else if (WIFEXITED(status) && WEXITSTATUS(status) != EXIT_SUCCESS)
++errors, printf("Test18: coproc(\"cat\") exited %d\n", WEXITSTATUS(status));
}
}
/* Test coproc_open("cat") - searches path, locating binary executable */
if ((pid = coproc_open(&to, &from, &err, "cat", argv, NULL, NULL, NULL)) == -1)
++errors, printf("Test19: coproc_open(\"cat\") failed (%s)\n", strerror(errno));
else
{
if (write_timeout(to, 5, 0) == -1 || write(to, "abc\n", 4) != 4)
++errors, printf("Test20: write_timeout(to) or write(to, \"abc\\n\") failed (%s)\n", strerror(errno));
else if (write_timeout(to, 5, 0) == -1 || write(to, "def\n", 4) != 4)
++errors, printf("Test21: write_timeout(to) or write(to, \"def\\n\") failed (%s)\n", strerror(errno));
else if (write_timeout(to, 5, 0) == -1 || write(to, "ghi\n", 4) != 4)
++errors, printf("Test22: write_timeout(to) or write(to, \"ghi\\n\") failed (%s)\n", strerror(errno));
else
{
close(to);
to = -1;
if (read_timeout(from, 5, 0) == -1)
++errors, printf("Test23: read_timeout(from) failed (%s)\n", strerror(errno));
else if ((bytes = read(from, buf, 4)) != 4)
{
++errors, printf("Test24: read(from) failed (returned %d, not %d) ", (int)bytes, 4);
print_error_details(buf, (int)bytes, "abc\\n");
}
else if (memcmp(buf, "abc\n", 4))
++errors, printf("Test25: read(from) failed (read \"%.4s\", not \"%.4s\")\n", buf, "abc\n");
else if (read_timeout(from, 5, 0) == -1)
++errors, printf("Test26: read_timeout(from) failed (%s)\n", strerror(errno));
else if ((bytes = read(from, buf, 4)) != 4)
{
++errors, printf("Test27: read(from) failed (returned %d, not %d) ", (int)bytes, 4);
print_error_details(buf, (int)bytes, "def\\n");
}
else if (memcmp(buf, "def\n", 4))
++errors, printf("Test28: read(from) failed (read \"%.4s\", not \"%.4s\")\n", buf, "def\n");
else if (read_timeout(from, 5, 0) == -1)
++errors, printf("Test29: read_timeout(from) failed (%s)\n", strerror(errno));
else if ((bytes = read(from, buf, 4)) != 4)
{
++errors, printf("Test30: read(from) failed (returned %d, not %d) ", (int)bytes, 4);
print_error_details(buf, (int)bytes, "ghi\\n");
}
else if (memcmp(buf, "ghi\n", 4))
++errors, printf("Test31: read(from) failed (read \"%.4s\", not \"%.4s\")\n", buf, "ghi\n");
else if (read_timeout(from, 5, 0) == -1)
++errors, printf("Test32: read_timeout(from) failed (%s)\n", strerror(errno));
else if ((bytes = read(from, buf, 4)) != 0)
{
++errors, printf("Test33: read(from) failed (returned %d, not %d) ", (int)bytes, 0);
print_error_details(buf, (int)bytes, "");
}
if ((status = coproc_close(pid, &to, &from, &err)) == -1)
++errors, printf("Test34: coproc_close() failed (%s)\n", strerror(errno));
else if (WIFSIGNALED(status))
++errors, printf("Test35: coproc(\"cat\") received signal %d\n", WTERMSIG(status));
else if (WIFEXITED(status) && WEXITSTATUS(status) != EXIT_SUCCESS)