-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.c
3789 lines (3266 loc) · 92 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-2011 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
#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 */
#if defined(HAVE_POPEN_H)
#include "popen.h"
#endif
#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
#ifdef __EMX__
#include <process.h>
#endif
#ifndef ENFILE
#define ENFILE EMFILE
#endif
#ifdef HAVE_SOCKETS
#ifndef SHUT_RD
#define SHUT_RD 0
#endif
#ifndef SHUT_WR
#define SHUT_WR 1
#endif
#ifndef SHUT_RDWR
#define SHUT_RDWR 2
#endif
#endif /* HAVE_SOCKETS */
#if defined(GAWK_AIX)
#undef TANDEM /* AIX defines this in one of its header files */
#endif
#if defined(__DJGPP__) || defined(__MINGW32__)
#define PIPES_SIMULATED
#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
typedef enum { CLOSE_ALL, CLOSE_TO, CLOSE_FROM } two_way_close_type;
/* 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)
/*
* 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);
struct redirect *redirect(NODE *redir_exp, int redirtype, int *errflg);
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);
static int 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);
static void free_rp(struct redirect *rp);
static int inetfile(const char *str, int *length, int *family);
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_yes_case; /* regexp for RS when ignoring case */
static Regexp *RS_re_no_case; /* regexp for RS when not ignoring case */
static Regexp *RS_regexp;
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;
/*
* 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 & 1) != 0)
mode = "rb";
break;
case 'w':
case 'a':
if ((BINMODE & 2) != 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);
arg->stptr[arg->stlen] = '\0';
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"));
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 |= MAYBE_NUM; /* 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 */
int
inrec(IOBUF *iop, int *errcode)
{
char *begin;
int cnt;
int retval = 0;
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);
if (cnt == EOF) {
retval = 1;
if (*errcode > 0)
update_ERRNO_int(*errcode);
} else {
INCREMENT_REC(NR);
INCREMENT_REC(FNR);
set_record(begin, cnt);
}
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 = close(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 --- Redirection for printf and print commands */
struct redirect *
redirect(NODE *redir_exp, int redirtype, int *errflg)
{
struct redirect *rp;
char *str;
int tflag = 0;
int outflag = 0;
const char *direction = "to";
const char *mode;
int fd;
const char *what = NULL;
bool new_rp = false;
int len; /* used with /inet */
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 && (redir_exp->flags & STRCUR) == 0)
lintwarn(_("expression in `%s' redirection only has numeric value"),
what);
redir_exp = force_string(redir_exp);
str = redir_exp->stptr;
if (str == NULL || *str == '\0')
fatal(_("expression for `%s' redirection has null string value"),
what);
if (do_lint && (strncmp(str, "0", redir_exp->stlen) == 0
|| strncmp(str, "1", redir_exp->stlen) == 0))
lintwarn(_("filename `%s' for `%s' redirection may be result of logical expression"),
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, & len, NULL)) {
tflag |= RED_SOCKET;
if (strncmp(str + len, "tcp/", 4) == 0)
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) && redirtype == redirect_pipein) {
if (rp->pid != -1)
wait_any(0);
}
#endif /* PIPES_SIMULATED */
/* now check for a match */
if (strlen(rp->value) == redir_exp->stlen
&& memcmp(rp->value, str, redir_exp->stlen) == 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) redir_exp->stlen, rp->value);
break;
}
}
if (rp == NULL) {
new_rp = true;
if (save_rp != NULL) {
rp = save_rp;
efree(rp->value);
} else
emalloc(rp, struct redirect *, sizeof(struct redirect), "redirect");
emalloc(str, char *, redir_exp->stlen + 1, "redirect");
memcpy(str, redir_exp->stptr, redir_exp->stlen);
str[redir_exp->stlen] = '\0';
rp->value = str;
rp->flag = tflag;
init_output_wrapper(& rp->output);
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) {
/*
* 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:
/* synchronize output before new pipe */
(void) flush_io();
os_restore_mode(fileno(stdin));
if ((rp->output.fp = popen(str, binmode("w"))) == NULL)
fatal(_("can't open pipe `%s' for output (%s)"),
str, strerror(errno));
/* set close-on-exec */
os_close_on_exec(fileno(rp->output.fp), str, "pipe", "to");
rp->flag |= RED_NOBUF;
break;
case redirect_pipein:
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 = 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:
direction = "to/from";
if (! two_way_open(str, rp)) {
#ifdef HAVE_SOCKETS
if (inetfile(str, NULL, NULL)) {
*errflg = errno;
/* do not free rp, saving it for reuse (save_rp = rp) */
return NULL;
} else
#endif
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 = 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. */
if (! new_rp && red_head != rp) {
if ((rp->prev->next = rp->next) != NULL)
rp->next->prev = rp->prev;
red_head->prev = rp;
rp->prev = NULL;
rp->next = red_head;
red_head = rp;
}
}
find_output_wrapper(& rp->output);
}
if (rp->output.fp == NULL && rp->iop == NULL) {
/* too many files open -- close one and try again */
if (errno == EMFILE || errno == ENFILE)
close_one();
#if defined __MINGW32__
else if (errno == 0) /* HACK! */
close_one();
#endif
#ifdef VMS
/* Alpha/VMS V7.1's C RTL is returning this instead
of EMFILE (haven't tried other post-V6.2 systems) */
#define SS$_EXQUOTA 0x001C
else if (errno == EIO && vaxc$errno == SS$_EXQUOTA)
close_one();
#endif
else {
/*
* Some other reason for failure.
*
* On redirection of input from a file,
* just return an error, so e.g. getline
* can return -1. For output to file,
* complain. The shell will complain on
* a bad command to a pipe.
*/
if (errflg != NULL)
*errflg = errno;
if ( redirtype == redirect_output
|| redirtype == redirect_append) {
/* multiple messages make life easier for translators */
if (*direction == 'f')
fatal(_("can't redirect from `%s' (%s)"),
str, strerror(errno));
else
fatal(_("can't redirect to `%s' (%s)"),
str, strerror(errno));
} else {
/* do not free rp, saving it for reuse (save_rp = rp) */
return NULL;
}
}
}
}
if (new_rp) {
/*
* It opened successfully, hook it into the list.
* Maintain the list in most-recently-used first order.
*/
if (red_head != NULL)
red_head->prev = rp;
rp->prev = NULL;
rp->next = red_head;
red_head = rp;
}
save_rp = NULL;
return rp;
}
/* getredirect --- find the struct redirect for this file or pipe */
struct redirect *
getredirect(const char *str, int len)
{
struct redirect *rp;
for (rp = red_head; rp != NULL; rp = rp->next)
if (strlen(rp->value) == len && memcmp(rp->value, str, len) == 0)
return rp;
return NULL;
}
/* close_one --- temporarily close an open file to re-use the fd */
static void
close_one()
{
struct redirect *rp;
struct redirect *rplast = NULL;
static bool warned = false;
if (do_lint && ! warned) {
warned = true;
lintwarn(_("reached system limit for open files: starting to multiplex file descriptors"));
}
/* go to end of list first, to pick up least recently used entry */
for (rp = red_head; rp != NULL; rp = rp->next)
rplast = rp;
/* now work back up through the list */
for (rp = rplast; rp != NULL; rp = rp->prev) {
/* don't close standard files! */
if (rp->output.fp == NULL || rp->output.fp == stderr || rp->output.fp == stdout)
continue;
if ((rp->flag & (RED_FILE|RED_WRITE)) == (RED_FILE|RED_WRITE)) {
rp->flag |= RED_USED;
errno = 0;
if (rp->output.gawk_fclose(rp->output.fp, rp->output.opaque) != 0)
warning(_("close of `%s' failed (%s)."),
rp->value, strerror(errno));
rp->output.fp = NULL;
break;
}
}
if (rp == NULL)
/* surely this is the only reason ??? */