forked from redox-os/gawk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.c
4457 lines (3841 loc) · 109 KB
/
io.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
/*
* io.c --- routines for dealing with input and output and records
*/
/*
* Copyright (C) 1986, 1988, 1989, 1991-2018,
* the Free Software Foundation, Inc.
*
* This file is part of GAWK, the GNU implementation of the
* AWK Programming Language.
*
* GAWK 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 3 of the License, or
* (at your option) any later version.
*
* GAWK 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/* For OSF/1 to get struct sockaddr_storage */
#if defined(__osf__) && !defined(_OSF_SOURCE)
#define _OSF_SOURCE
#endif
#include "awk.h"
#ifdef HAVE_SYS_PARAM_H
#undef RE_DUP_MAX /* avoid spurious conflict w/regex.h */
#include <sys/param.h>
#endif /* HAVE_SYS_PARAM_H */
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif /* HAVE_SYS_IOCTL_H */
#ifndef O_ACCMODE
#define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
#endif
#if ! defined(S_ISREG) && defined(S_IFREG)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#ifdef HAVE_STROPTS_H
#include <stropts.h>
#endif
#ifdef HAVE_SOCKETS
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#else
#include <socket.h>
#endif /* HAVE_SYS_SOCKET_H */
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#else /* ! HAVE_NETINET_IN_H */
#include <in.h>
#endif /* HAVE_NETINET_IN_H */
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif /* HAVE_NETDB_H */
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif /* HAVE_SYS_SELECT_H */
#ifndef HAVE_GETADDRINFO
#include "missing_d/getaddrinfo.h"
#endif
#ifndef AI_ADDRCONFIG /* not everyone has this symbol */
#define AI_ADDRCONFIG 0
#endif /* AI_ADDRCONFIG */
#ifndef HAVE_SOCKADDR_STORAGE
#define sockaddr_storage sockaddr /* for older systems */
#endif /* HAVE_SOCKADDR_STORAGE */
#endif /* HAVE_SOCKETS */
#ifndef AF_UNSPEC
#define AF_UNSPEC 0
#endif
#ifndef AF_INET
#define AF_INET 2
#endif
#ifndef AF_INET6
#define AF_INET6 10
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#if defined(HAVE_POPEN_H)
#include "popen.h"
#endif
#ifdef __EMX__
#include <process.h>
#if !defined(_S_IFDIR) && defined(S_IFDIR)
#define _S_IFDIR S_IFDIR
#endif
#if !defined(_S_IRWXU) && defined(S_IRWXU)
#define _S_IRWXU S_IRWXU
#endif
#endif
#ifndef ENFILE
#define ENFILE EMFILE
#endif
#if defined(__DJGPP__)
#define closemaybesocket(fd) close(fd)
#endif
#if defined(VMS)
#include <ssdef.h>
#ifndef SS$_EXBYTLM
#define SS$_EXBYTLM 0x2a14 /* VMS 8.4 seen */
#endif
#include <rmsdef.h>
#define closemaybesocket(fd) close(fd)
#endif
#ifdef HAVE_SOCKETS
#ifndef SHUT_RD
# ifdef SD_RECEIVE
# define SHUT_RD SD_RECEIVE
# else
# define SHUT_RD 0
# endif
#endif
#ifndef SHUT_WR
# ifdef SD_SEND
# define SHUT_WR SD_SEND
# else
# define SHUT_WR 1
# endif
#endif
#ifndef SHUT_RDWR
# ifdef SD_BOTH
# define SHUT_RDWR SD_BOTH
# else
# define SHUT_RDWR 2
# endif
#endif
/* MinGW defines non-trivial macros on pc/socket.h. */
#ifndef FD_TO_SOCKET
# define FD_TO_SOCKET(fd) (fd)
# define closemaybesocket(fd) close(fd)
#endif
#ifndef SOCKET_TO_FD
# define SOCKET_TO_FD(s) (s)
# define SOCKET int
#endif
#else /* HAVE_SOCKETS */
#ifndef closemaybesocket
# define closemaybesocket(fd) close(fd)
#endif
#endif /* HAVE_SOCKETS */
#ifndef HAVE_SETSID
#define setsid() /* nothing */
#endif /* HAVE_SETSID */
#if defined(_AIX)
#undef TANDEM /* AIX defines this in one of its header files */
#endif
#ifdef __DJGPP__
#define PIPES_SIMULATED
#endif
#ifdef __MINGW32__
# ifndef PIPES_SIMULATED
# define pipe(fds) _pipe(fds, 0, O_NOINHERIT)
# endif
#endif
#ifdef HAVE_MPFR
/* increment NR or FNR */
#define INCREMENT_REC(X) (do_mpfr && X == (LONG_MAX - 1)) ? \
(mpz_add_ui(M##X, M##X, 1), X = 0) : X++
#else
#define INCREMENT_REC(X) X++
#endif
/* Several macros to make the code a bit clearer. */
#define at_eof(iop) (((iop)->flag & IOP_AT_EOF) != 0)
#define has_no_data(iop) ((iop)->dataend == NULL)
#define no_data_left(iop) ((iop)->off >= (iop)->dataend)
#define buffer_has_all_data(iop) ((iop)->dataend - (iop)->off == (iop)->public.sbuf.st_size)
/*
* The key point to the design is to split out the code that searches through
* a buffer looking for the record and the terminator into separate routines,
* with a higher-level routine doing the reading of data and buffer management.
* This makes the code easier to manage; the buffering code is the same
* independent of how we find a record. Communication is via the return
* value:
*/
typedef enum recvalues {
REC_OK, /* record and terminator found, recmatch struct filled in */
NOTERM, /* no terminator found, give me more input data */
TERMATEND, /* found terminator at end of buffer */
TERMNEAREND /* found terminator close to end of buffer, for when
the RE might be match more data further in
the file. */
} RECVALUE;
/*
* Between calls to a scanning routine, the state is stored in
* an enum scanstate variable. Not all states apply to all
* variants, but the higher code doesn't really care.
*/
typedef enum scanstate {
NOSTATE, /* scanning not started yet (all) */
INLEADER, /* skipping leading data (RS = "") */
INDATA, /* in body of record (all) */
INTERM /* scanning terminator (RS = "", RS = regexp) */
} SCANSTATE;
/*
* When a record is seen (REC_OK or TERMATEND), the following
* structure is filled in.
*/
struct recmatch {
char *start; /* record start */
size_t len; /* length of record */
char *rt_start; /* start of terminator */
size_t rt_len; /* length of terminator */
};
static int iop_close(IOBUF *iop);
static void close_one(void);
static int close_redir(struct redirect *rp, bool exitwarn, two_way_close_type how);
#ifndef PIPES_SIMULATED
static int wait_any(int interesting);
#endif
static IOBUF *gawk_popen(const char *cmd, struct redirect *rp);
static IOBUF *iop_alloc(int fd, const char *name, int errno_val);
static IOBUF *iop_finish(IOBUF *iop);
static int gawk_pclose(struct redirect *rp);
static int str2mode(const char *mode);
static int two_way_open(const char *str, struct redirect *rp, int extfd);
static bool pty_vs_pipe(const char *command);
static void find_input_parser(IOBUF *iop);
static bool find_output_wrapper(awk_output_buf_t *outbuf);
static void init_output_wrapper(awk_output_buf_t *outbuf);
static bool find_two_way_processor(const char *name, struct redirect *rp);
static RECVALUE rs1scan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state);
static RECVALUE rsnullscan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state);
static RECVALUE rsrescan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state);
static RECVALUE (*matchrec)(IOBUF *iop, struct recmatch *recm, SCANSTATE *state) = rs1scan;
static int get_a_record(char **out, IOBUF *iop, int *errcode, const awk_fieldwidth_info_t **field_width);
static void free_rp(struct redirect *rp);
struct inet_socket_info {
int family; /* AF_UNSPEC, AF_INET, or AF_INET6 */
int protocol; /* SOCK_STREAM or SOCK_DGRAM */
/*
* N.B. If we used 'char *' or 'const char *' pointers to the
* substrings, it would trigger compiler warnings about the casts
* in either inetfile() or devopen(). So we use offset/len to
* avoid that.
*/
struct {
int offset;
int len;
} localport, remotehost, remoteport;
};
static bool inetfile(const char *str, size_t len, struct inet_socket_info *isn);
static NODE *in_PROCINFO(const char *pidx1, const char *pidx2, NODE **full_idx);
static long get_read_timeout(IOBUF *iop);
static ssize_t read_with_timeout(int fd, char *buf, size_t size);
static bool read_can_timeout = false;
static long read_timeout;
static long read_default_timeout;
static struct redirect *red_head = NULL;
static NODE *RS = NULL;
static Regexp *RS_re[2]; /* index 0 - don't ignore case, index 1, do */
static Regexp *RS_regexp;
static const char nonfatal[] = "NONFATAL";
bool RS_is_null;
extern NODE *ARGC_node;
extern NODE *ARGV_node;
extern NODE *ARGIND_node;
extern NODE **fields_arr;
/* init_io --- set up timeout related variables */
void
init_io()
{
long tmout;
/* Only MinGW has a non-trivial implementation of this. */
init_sockets();
/*
* N.B.: all these hacks are to minimize the effect
* on programs that do not care about timeout.
*/
/* Parse the env. variable only once */
tmout = getenv_long("GAWK_READ_TIMEOUT");
if (tmout > 0) {
read_default_timeout = tmout;
read_can_timeout = true;
}
/*
* PROCINFO entries for timeout are dynamic;
* We can't be any more specific than this.
*/
if (PROCINFO_node != NULL)
read_can_timeout = true;
}
#if defined(__DJGPP__) || defined(__MINGW32__) || defined(__EMX__) || defined(__CYGWIN__)
/* binmode --- convert BINMODE to string for fopen */
static const char *
binmode(const char *mode)
{
switch (mode[0]) {
case 'r':
if ((BINMODE & BINMODE_INPUT) != 0)
mode = "rb";
break;
case 'w':
case 'a':
if ((BINMODE & BINMODE_OUTPUT) != 0)
mode = (mode[0] == 'w' ? "wb" : "ab");
break;
}
return mode;
}
#else
#define binmode(mode) (mode)
#endif
#ifdef VMS
/* File pointers have an extra level of indirection, and there are cases where
`stdin' can be null. That can crash gawk if fileno() is used as-is. */
static int vmsrtl_fileno(FILE *);
static int vmsrtl_fileno(fp) FILE *fp; { return fileno(fp); }
#undef fileno
#define fileno(FP) (((FP) && *(FP)) ? vmsrtl_fileno(FP) : -1)
#endif /* VMS */
/* after_beginfile --- reset necessary state after BEGINFILE has run */
void
after_beginfile(IOBUF **curfile)
{
IOBUF *iop;
iop = *curfile;
assert(iop != NULL);
/*
* Input parsers could have been changed by BEGINFILE,
* so delay check until now.
*/
find_input_parser(iop);
if (! iop->valid) {
const char *fname;
int errcode;
bool valid;
fname = iop->public.name;
errcode = iop->errcode;
valid = iop->valid;
errno = 0;
update_ERRNO_int(errcode);
iop_close(iop);
*curfile = NULL;
if (! valid && errcode == EISDIR && ! do_traditional) {
warning(_("command line argument `%s' is a directory: skipped"), fname);
return; /* read next file */
}
fatal(_("cannot open file `%s' for reading (%s)"),
fname, strerror(errcode));
}
}
/* nextfile --- move to the next input data file */
/*
* Return value > 0 ----> run BEGINFILE block
* *curfile = NULL ----> hit EOF, run ENDFILE block
*/
int
nextfile(IOBUF **curfile, bool skipping)
{
static long i = 1;
static bool files = false;
NODE *arg, *tmp;
const char *fname;
int fd = INVALID_HANDLE;
int errcode = 0;
IOBUF *iop = *curfile;
long argc;
if (skipping) { /* for 'nextfile' call */
errcode = 0;
if (iop != NULL) {
errcode = iop->errcode;
(void) iop_close(iop);
}
*curfile = NULL;
return (errcode == 0);
}
if (iop != NULL) {
if (at_eof(iop)) {
assert(iop->public.fd != INVALID_HANDLE);
(void) iop_close(iop);
*curfile = NULL;
return 1; /* run endfile block */
} else
return 0;
}
argc = get_number_si(ARGC_node->var_value);
for (; i < argc; i++) {
tmp = make_number((AWKNUM) i);
(void) force_string(tmp);
arg = in_array(ARGV_node, tmp);
unref(tmp);
if (arg == NULL || arg->stlen == 0)
continue;
arg = force_string(arg);
if (! do_traditional) {
unref(ARGIND_node->var_value);
ARGIND_node->var_value = make_number((AWKNUM) i);
}
if (! arg_assign(arg->stptr, false)) {
files = true;
fname = arg->stptr;
/* manage the awk variables: */
unref(FILENAME_node->var_value);
FILENAME_node->var_value = dupnode(arg);
#ifdef HAVE_MPFR
if (is_mpg_number(FNR_node->var_value))
mpz_set_ui(MFNR, 0);
#endif
FNR = 0;
/* IOBUF management: */
errno = 0;
fd = devopen(fname, binmode("r"));
if (fd == INVALID_HANDLE && errno == EMFILE) {
close_one();
close_one();
fd = devopen(fname, binmode("r"));
}
errcode = errno;
if (! do_traditional)
update_ERRNO_int(errno);
iop = iop_alloc(fd, fname, errcode);
*curfile = iop_finish(iop);
if (iop->public.fd == INVALID_HANDLE)
iop->errcode = errcode;
else if (iop->valid)
iop->errcode = 0;
if (! do_traditional && iop->errcode != 0)
update_ERRNO_int(iop->errcode);
return ++i; /* run beginfile block */
}
}
if (files == false) {
files = true;
/* no args. -- use stdin */
/* FNR is init'ed to 0 */
errno = 0;
if (! do_traditional)
update_ERRNO_int(errno);
unref(FILENAME_node->var_value);
FILENAME_node->var_value = make_string("-", 1);
FILENAME_node->var_value->flags |= USER_INPUT; /* be pedantic */
fname = "-";
iop = iop_alloc(fileno(stdin), fname, 0);
*curfile = iop_finish(iop);
if (iop->public.fd == INVALID_HANDLE) {
errcode = errno;
errno = 0;
update_ERRNO_int(errno);
(void) iop_close(iop);
*curfile = NULL;
fatal(_("cannot open file `%s' for reading (%s)"),
fname, strerror(errcode));
}
return ++i; /* run beginfile block */
}
return -1; /* end of input, run end block or Op_atexit */
}
/* set_FNR --- update internal FNR from awk variable */
void
set_FNR()
{
NODE *n = FNR_node->var_value;
(void) force_number(n);
#ifdef HAVE_MPFR
if (is_mpg_number(n))
FNR = mpg_set_var(FNR_node);
else
#endif
FNR = get_number_si(n);
}
/* set_NR --- update internal NR from awk variable */
void
set_NR()
{
NODE *n = NR_node->var_value;
(void) force_number(n);
#ifdef HAVE_MPFR
if (is_mpg_number(n))
NR = mpg_set_var(NR_node);
else
#endif
NR = get_number_si(n);
}
/* inrec --- This reads in a record from the input file */
bool
inrec(IOBUF *iop, int *errcode)
{
char *begin;
int cnt;
bool retval = true;
const awk_fieldwidth_info_t *field_width = NULL;
if (at_eof(iop) && no_data_left(iop))
cnt = EOF;
else if ((iop->flag & IOP_CLOSED) != 0)
cnt = EOF;
else
cnt = get_a_record(& begin, iop, errcode, & field_width);
/* Note that get_a_record may return -2 when I/O would block */
if (cnt < 0) {
retval = false;
} else {
INCREMENT_REC(NR);
INCREMENT_REC(FNR);
set_record(begin, cnt, field_width);
if (*errcode > 0)
retval = false;
}
return retval;
}
/* remap_std_file --- reopen a standard descriptor on /dev/null */
static int
remap_std_file(int oldfd)
{
int newfd;
int ret = -1;
/*
* Give OS-specific routines in gawkmisc.c a chance to interpret
* "/dev/null" as appropriate for their platforms.
*/
newfd = os_devopen("/dev/null", O_RDWR);
if (newfd == INVALID_HANDLE)
newfd = open("/dev/null", O_RDWR);
if (newfd >= 0) {
/* if oldfd is open, dup2() will close oldfd for us first. */
ret = dup2(newfd, oldfd);
if (ret == 0)
close(newfd);
} else
ret = 0;
return ret;
}
/* iop_close --- close an open IOP */
static int
iop_close(IOBUF *iop)
{
int ret = 0;
if (iop == NULL)
return 0;
errno = 0;
iop->flag &= ~IOP_AT_EOF;
iop->flag |= IOP_CLOSED; /* there may be dangling pointers */
iop->dataend = NULL;
/*
* Closing standard files can cause crufty code elsewhere to lose.
* So we remap the standard file to /dev/null.
* Thanks to Jim Meyering for the suggestion.
*/
if (iop->public.close_func != NULL)
iop->public.close_func(&iop->public);
if (iop->public.fd != INVALID_HANDLE) {
if (iop->public.fd == fileno(stdin)
|| iop->public.fd == fileno(stdout)
|| iop->public.fd == fileno(stderr))
ret = remap_std_file(iop->public.fd);
else
ret = closemaybesocket(iop->public.fd);
}
if (ret == -1)
warning(_("close of fd %d (`%s') failed (%s)"), iop->public.fd,
iop->public.name, strerror(errno));
/*
* Be careful -- $0 may still reference the buffer even though
* an explicit close is being done; in the future, maybe we
* can do this a bit better.
*/
if (iop->buf) {
if ((fields_arr[0]->stptr >= iop->buf)
&& (fields_arr[0]->stptr < (iop->buf + iop->size))) {
NODE *t;
t = make_string(fields_arr[0]->stptr,
fields_arr[0]->stlen);
unref(fields_arr[0]);
fields_arr[0] = t;
/*
* This used to be here:
*
* reset_record();
*
* Don't do that; reset_record() throws away all fields,
* saves FS etc. We just need to make sure memory isn't
* corrupted and that references to $0 and fields work.
*/
}
efree(iop->buf);
iop->buf = NULL;
}
efree(iop);
return ret == -1 ? 1 : 0;
}
/* redflags2str --- turn redirection flags into a string, for debugging */
const char *
redflags2str(int flags)
{
static const struct flagtab redtab[] = {
{ RED_FILE, "RED_FILE" },
{ RED_PIPE, "RED_PIPE" },
{ RED_READ, "RED_READ" },
{ RED_WRITE, "RED_WRITE" },
{ RED_APPEND, "RED_APPEND" },
{ RED_NOBUF, "RED_NOBUF" },
{ RED_EOF, "RED_EOF" },
{ RED_TWOWAY, "RED_TWOWAY" },
{ RED_PTY, "RED_PTY" },
{ RED_SOCKET, "RED_SOCKET" },
{ RED_TCP, "RED_TCP" },
{ 0, NULL }
};
return genflags2str(flags, redtab);
}
/* redirect_string --- Redirection for printf and print commands, use string info */
struct redirect *
redirect_string(const char *str, size_t explen, bool not_string,
int redirtype, int *errflg, int extfd, bool failure_fatal)
{
struct redirect *rp;
int tflag = 0;
int outflag = 0;
const char *direction = "to";
const char *mode;
int fd;
const char *what = NULL;
bool new_rp = false;
#ifdef HAVE_SOCKETS
struct inet_socket_info isi;
#endif
static struct redirect *save_rp = NULL; /* hold onto rp that should
* be freed for reuse
*/
if (do_sandbox)
fatal(_("redirection not allowed in sandbox mode"));
switch (redirtype) {
case redirect_append:
tflag = RED_APPEND;
/* FALL THROUGH */
case redirect_output:
outflag = (RED_FILE|RED_WRITE);
tflag |= outflag;
if (redirtype == redirect_output)
what = ">";
else
what = ">>";
break;
case redirect_pipe:
tflag = (RED_PIPE|RED_WRITE);
what = "|";
break;
case redirect_pipein:
tflag = (RED_PIPE|RED_READ);
what = "|";
break;
case redirect_input:
tflag = (RED_FILE|RED_READ);
what = "<";
break;
case redirect_twoway:
tflag = (RED_READ|RED_WRITE|RED_TWOWAY);
what = "|&";
break;
default:
cant_happen();
}
if (do_lint && not_string)
lintwarn(_("expression in `%s' redirection is a number"),
what);
if (explen < 1 || str == NULL || *str == '\0')
fatal(_("expression for `%s' redirection has null string value"),
what);
if (do_lint && (strncmp(str, "0", explen) == 0
|| strncmp(str, "1", explen) == 0))
lintwarn(_("filename `%.*s' for `%s' redirection may be result of logical expression"),
(int) explen, str, what);
#ifdef HAVE_SOCKETS
/*
* Use /inet4 to force IPv4, /inet6 to force IPv6, and plain
* /inet will be whatever we get back from the system.
*/
if (inetfile(str, explen, & isi)) {
tflag |= RED_SOCKET;
if (isi.protocol == SOCK_STREAM)
tflag |= RED_TCP; /* use shutdown when closing */
}
#endif /* HAVE_SOCKETS */
for (rp = red_head; rp != NULL; rp = rp->next) {
#ifndef PIPES_SIMULATED
/*
* This is an efficiency hack. We want to
* recover the process slot for dead children,
* if at all possible. Messing with signal() for
* SIGCLD leads to lots of headaches. However, if
* we've gotten EOF from a child input pipeline, it's
* a good bet that the child has died. So recover it.
*/
if ((rp->flag & RED_EOF) != 0 && redirtype == redirect_pipein) {
if (rp->pid != -1)
#ifdef __MINGW32__
/* MinGW cannot wait for any process. */
wait_any(rp->pid);
#else
wait_any(0);
#endif
}
#endif /* PIPES_SIMULATED */
/* now check for a match */
if (strlen(rp->value) == explen
&& memcmp(rp->value, str, explen) == 0
&& ((rp->flag & ~(RED_NOBUF|RED_EOF|RED_PTY)) == tflag
|| (outflag != 0
&& (rp->flag & (RED_FILE|RED_WRITE)) == outflag))) {
int rpflag = (rp->flag & ~(RED_NOBUF|RED_EOF|RED_PTY));
int newflag = (tflag & ~(RED_NOBUF|RED_EOF|RED_PTY));
if (do_lint && rpflag != newflag)
lintwarn(
_("unnecessary mixing of `>' and `>>' for file `%.*s'"),
(int) explen, rp->value);
break;
}
}
if (rp == NULL) {
char *newstr;
new_rp = true;
if (save_rp != NULL) {
rp = save_rp;
efree(rp->value);
} else
emalloc(rp, struct redirect *, sizeof(struct redirect), "redirect");
emalloc(newstr, char *, explen + 1, "redirect");
memcpy(newstr, str, explen);
newstr[explen] = '\0';
str = newstr;
rp->value = newstr;
rp->flag = tflag;
init_output_wrapper(& rp->output);
rp->output.name = str;
rp->iop = NULL;
rp->pid = -1;
rp->status = 0;
} else
str = rp->value; /* get \0 terminated string */
save_rp = rp;
while (rp->output.fp == NULL && rp->iop == NULL) {
if (! new_rp && (rp->flag & RED_EOF) != 0) {
/*
* Encountered EOF on file or pipe -- must be cleared
* by explicit close() before reading more
*/
save_rp = NULL;
return rp;
}
mode = NULL;
errno = 0;
switch (redirtype) {
case redirect_output:
mode = binmode("w");
if ((rp->flag & RED_USED) != 0)
mode = (rp->mode[1] == 'b') ? "ab" : "a";
break;
case redirect_append:
mode = binmode("a");
break;
case redirect_pipe:
if (extfd >= 0) {
warning(_("get_file cannot create pipe `%s' with fd %d"), str, extfd);
return NULL;
}
/* synchronize output before new pipe */
(void) flush_io();
os_restore_mode(fileno(stdin));
set_sigpipe_to_default();
/*
* Don't check failure_fatal; see input pipe below.
* Note that the failure happens upon failure to fork,
* using a non-existant program will still succeed the
* popen().
*/
if ((rp->output.fp = popen(str, binmode("w"))) == NULL)
fatal(_("can't open pipe `%s' for output (%s)"),
str, strerror(errno));
ignore_sigpipe();
/* set close-on-exec */
os_close_on_exec(fileno(rp->output.fp), str, "pipe", "to");
rp->flag |= RED_NOBUF;
break;
case redirect_pipein:
if (extfd >= 0) {
warning(_("get_file cannot create pipe `%s' with fd %d"), str, extfd);
return NULL;
}
direction = "from";
if (gawk_popen(str, rp) == NULL)
fatal(_("can't open pipe `%s' for input (%s)"),
str, strerror(errno));
break;
case redirect_input:
direction = "from";
fd = (extfd >= 0) ? extfd : devopen(str, binmode("r"));
if (fd == INVALID_HANDLE && errno == EISDIR) {
*errflg = EISDIR;
/* do not free rp, saving it for reuse (save_rp = rp) */
return NULL;
}
rp->iop = iop_alloc(fd, str, errno);
find_input_parser(rp->iop);
iop_finish(rp->iop);
if (! rp->iop->valid) {
if (! do_traditional && rp->iop->errcode != 0)
update_ERRNO_int(rp->iop->errcode);
iop_close(rp->iop);
rp->iop = NULL;
}
break;
case redirect_twoway:
#ifndef HAVE_SOCKETS
if (extfd >= 0) {
warning(_("get_file socket creation not supported on this platform for `%s' with fd %d"), str, extfd);
return NULL;
}
#endif
direction = "to/from";
if (! two_way_open(str, rp, extfd)) {
if (! failure_fatal || is_non_fatal_redirect(str, explen)) {
*errflg = errno;
/* do not free rp, saving it for reuse (save_rp = rp) */
return NULL;
} else
fatal(_("can't open two way pipe `%s' for input/output (%s)"),
str, strerror(errno));
}
break;
default:
cant_happen();
}
if (mode != NULL) {
errno = 0;
rp->output.mode = mode;
fd = (extfd >= 0) ? extfd : devopen(str, mode);
if (fd > INVALID_HANDLE) {
if (fd == fileno(stdin))
rp->output.fp = stdin;
else if (fd == fileno(stdout))
rp->output.fp = stdout;
else if (fd == fileno(stderr))
rp->output.fp = stderr;
else {
const char *omode = mode;
#if defined(F_GETFL) && defined(O_APPEND)
int fd_flags;
fd_flags = fcntl(fd, F_GETFL);
if (fd_flags != -1 && (fd_flags & O_APPEND) == O_APPEND)
omode = binmode("a");
#endif
os_close_on_exec(fd, str, "file", "");
rp->output.fp = fdopen(fd, (const char *) omode);
rp->mode = (const char *) mode;
/* don't leak file descriptors */
if (rp->output.fp == NULL)
close(fd);
}
if (rp->output.fp != NULL && os_isatty(fd))
rp->flag |= RED_NOBUF;
/* Move rp to the head of the list. */