File: utils.c

package info (click to toggle)
super 3.11.6-1
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 660 kB
  • ctags: 592
  • sloc: ansic: 7,338; sh: 183; makefile: 175
file content (1546 lines) | stat: -rw-r--r-- 40,763 bytes parent folder | download
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
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
static char rcsid[] = "$Id: utils.c,v 1.89 1998/04/07 08:04:06 will Exp $";
#include "super.h"

/* Variables table flag -- !0 means has been created */
static int created_variables_table = 0;

/* an expandable input buffer */
struct Ebuf {
    char *buf;
    int l;
    int nalloc;
};
/* checksize of Ebuf; grow an Ebuf */
static char *checksize __P((struct Ebuf *cb, int N));
static char *grow __P((struct Ebuf *cb, int N));

/* The input, cleaned input, and variable expansion buffers */
static struct Ebuf ebuf = { NULL, 0, 0 };
static struct Ebuf ebuf_clean = { NULL, 0, 0 };
static struct Ebuf variablebuf = { NULL, 0, 0 };


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Get environment variable */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char *
Getenv(s)
char *s;
{
    /* Like getenv(), but returns ptr to the <name> in "name=xxxx",
     * not just the xxxx.
     */
    char **envp; 
    int l;
    extern char **environ;

    if (!s)
	return (char *) NULL;
    l = strlen(s);
    for (envp=environ; *envp ; envp++)
	if (strncmp(*envp, s, l) == 0  &&  *(*envp+l) == '=')
	    return *envp;
    return (char *) NULL;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Get login directory of a user */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
getlogdir(user, buf)
char *user;
char *buf;
{
    /* Gets the login directory of the named user, and puts it into buf.
     * The "user" argument can either be a username or a uid in text form.
     * If user==NULL || *user == '\0', the current user is obtained.
     * Best if buf is MAXPATHLEN long.
     * 0 is returned on success; -1 on error.
     */
 
    struct passwd *pass;
    char *p;
 
    buf[0] = '\0';
    if (user != NULL && *user != '\0') {
	/* Name or uid given; use getpwentry */
	pass = getpwentry(1, user);
    } else {
	/* No user given; use current uid */
	pass = getpwuid(userinfo.orig_uid);
    }
 
    if (pass == (struct passwd *) NULL)
	return -1;
 
    (void) strcpy(buf, pass->pw_dir);
 
    return 0;
}
 
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Copies in to out, prefixing with "^" and suffixing with "$"
 * if these are missing.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
anchor(in, out)
char *in;
char *out;
{
    void re_anchor __P((char *, char *));
    if (need_re_anchor)
	re_anchor(in, out);
    else
	(void) strcpy(out, in);
}

void
re_anchor(in, out)
char *in;
char *out;
{
    int i;
    i = (*in != '^');
    if (i)
	out[0] = '^';
    (void) strcpy(out+i, in);
    i = strlen(out);
    if (out[i-1] != '$')
	out[i++] = '$';
    out[i] = '\0';
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Grow an expandable buffer */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
static char *
grow(cb, nb)
struct Ebuf *cb;
int nb;			/* amount to grow, bytes */
{
    if (cb->buf)
	cb->buf = realloc(cb->buf, cb->nalloc += nb);
    else
	cb->buf = malloc(cb->nalloc += nb);

    return cb->buf;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Grow buffer if less than N bytes free */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
static char *
checksize(cb, N)
struct Ebuf *cb;
int N;
{
    if (cb->nalloc - cb->l  <  N)
	return grow(cb, 2*N);
    else
	return cb->buf;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Check if string s1 ends with string s2 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char
*ends(s1, s2)
char *s1, *s2;
/* If s1 ends with string s2, a pointer to the ending of s1 is returned;
 * else null
 */
{
    int l1, l2;
    l1 = strlen(s1);
    l2 = strlen(s2);
    if (l1 < l2)
	return NULL;
    else if (strcmp(s1+l1-l2, s2) == 0)
	return s1+l1-l2;
    else
	return NULL;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Copy the input buffer to outbuf (default clean_buf),
 * cleaning out comments and the backslash-newline-whitespace parts; the
 * latter become plain whitespace if the backslash is preceded by letter,
 * digit, or underscore; otherwise, they are deleted.
 * Comments are also deleted.
 * Return a ptr to the string in the cleaned buffer.

 * Returns null pointer on malloc error.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char *
clean_buf(buf, outbuf)
char *buf;		/* input buffer */
char *outbuf;		/* output buffer; NULL means to use the
			 * ebuf_clean buffer.  If non-null, you must make
			 * sure it's >= buf in size.
			 */
{
    register char *s, *t;
    char inquote = '\0';

    if (outbuf) {
	t = outbuf;

    } else {
	if (!(t = outbuf = checksize(&ebuf_clean, ebuf.nalloc))) {
	    Error(1, 0,
		"%t\n\tFailed to malloc space for clean copy of input text\n");
	    return NULL;
	}
    }

    /* Copy s (input buffer) to t (clean input buffer);
     * delete comments, delete backslash-newline-whitespace
     * or replace w/ ' '
     */
    for (s = buf; *s; ) {
	/* Assert not in comment */
	if (*s == '\\' && *(s+1) == '\n') {
	    /* At continued line; skip over backslash-newline-whitespace;
	     * make it a blank if following digit,letter,_  .
	     */
	    if ( (s > buf) && (isalnum(*(s-1)) || *(s-1) == '_') )
		*t++ = ' ';
	    s += 2;
	    while (isspace(*s))
		s++;
	    /* s has been left positioned at next character to process */

	} else if (inquote) {
	    /* In a quote */
	    if (*s == inquote) {
		/* end of quote */
		inquote = '\0';
	    }
	    *t++ = *s++;

	} else if (my_qm[*(unsigned char *)s]) {
	    /* Begin quote */
	    inquote = *t++ = *s++;

	} else if (my_cc[*(unsigned char *)s]) {
	    /* Begin comment; skip over until EOL */
	    char last_noncmt = (s > buf) ? *(s-1) : '\0';

	    while (*s && *s != '\n')
		s++;
	    if (*s && *(s-1) == '\\') {
		/* At continued line.  Ignore comment part, and
		 * look at last non-comment char before
		 * backslash-newline-whitespace; then process as above.
		 */
		if ( (s > buf) && (isalnum(last_noncmt) || last_noncmt == '_') )
		    *t++ = ' ';
		s++;
		while (isspace(*s))
		    s++;
	    }
	    /* s has been left positioned at next character to process */

	} else {
	    /* Ordinary character */
	    *t++ = *s++;
	    /* s has been left positioned at next character to process */
	}
    }
    *t = '\0';

    return outbuf;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Do fgets to get one logical line: join lines that are terminated
 * with backslash-newline.  Don't discard backslash or newline (so that
 * we can print the exact text, if desired).
 * The result is stored in "ebuf" and a pointer to the string
 * is returned.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char *
fillbuffer(fp, all_indented, nl)
FILE *fp;
int *all_indented;	/* Returned !0 if continued lines are all indented */
int *nl;		/* Returned with number of lines read in */
{
    char c, *s;
    ebuf.l = 0;	/* clear the extensible buffer */

    /* Collect lines until we have a non-zero buffer (which happens with
     * the first line, of course) and it isn't terminated "\\\n".
     */

    if (nl) *nl = 0;
    *all_indented = 1;
    UNTIL(ebuf.l && !(s=ends(ebuf.buf, "\\\n"))) {
	
	if (!checksize(&ebuf, 1024)) {
	    /* Needed to, but couldn't increase the allocated space */
	    return NULL;
	}
	if (!fgets(ebuf.buf+ebuf.l, ebuf.nalloc - ebuf.l, fp))
	    return NULL;
	c = *(ebuf.buf + ebuf.l) ;
	if (nl)
	    (*nl)++;
	if (ebuf.l != 0 && !(isspace(c) || c == '#')) {
	    /* Continued line not indented. */
	    *all_indented = 0;
	}
	ebuf.l += strlen(ebuf.buf+ebuf.l);
    }
    return ebuf.buf;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Open a file; chain it to the previous opened list.
 * Returns NULL pointer on malloc error, stat error, fopen error,
 *	ownership error, etc.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
FileList *
file_open(parent, name, allow_missing)
FileList *parent;
char *name;
int allow_missing;	/* silently ignore missing files if parent != null. */
{
    char *s;

    FileList *fl;
    struct stat st;
    static int nobody_uid = -999;
    static struct passwd *nobodypw;
    int uid, euid;

    if (nobody_uid == -999) {
	nobodypw = getpwnam("nobody");
	nobody_uid = nobodypw ? nobodypw->pw_uid : 65534;
    }

    fl = (FileList *) malloc(sizeof(FileList));
    if (!fl) {
	Error(0, 0,
	"%tFailed to malloc list member space for include file <%s>\n", name);
	return NULL;
    }

    if (!(fl->givenname = malloc(strlen(name)+1)) ) {
	Error(0, 0, "%tFailed to malloc space for filename <%s>\n", name);
	return NULL;
    }
    strcpy(fl->givenname, name);

    if (*name != '/' && parent != NULL) {
	/* it must be relative to the superfile directory */

	int l1, l2;

	s = strrchr(superfile, '/');
	if (s) {
	    l1 = s + 1 - superfile;
	    l2 = strlen(name);
	    if (!(fl->fullname = malloc(l1+l2+1)) ) {
		Error(0, 0,
		    "%tFailed to malloc space for expanded filename of <%s>\n",
		    name);
		return NULL;
	    }

	    sprintf(fl->fullname, "%.*s%s", l1, superfile,
			(strncmp("./", name, 2) == 0) ? name+2 : name);
	} else {
	    fl->fullname = fl->givenname;
	}
    } else {
	/* accept the name as is */
	fl->fullname = fl->givenname;
    }

    if (debug)
	if (parent == NULL)
	    fprintf(stderr, "\tOpening file %s\n", fl->fullname);
	else
	    fprintf(stderr, "\tLine %d: opening include file %s\n",
		parent->line, fl->fullname);

    /* For any file:
     *	If we are running as root:
     *		make sure that the super.tab file is owned by
     *		root or nobody, and is not writable by group/world.
     *	Otherwise, if our real uid differs from that under which we
     *		started the program, make sure the super file is owned
     *		by ourselves and not group/world writable.
     */
    if (stat(fl->fullname, &st) == -1) {
	if (errno == ENOENT && allow_missing) {
	    if (debug)
		fprintf(stderr, "\tIgnoring missing file %s\n", fl->fullname);
	} else {
	    Error(1, 0, "Couldn't stat super.tab %sfile `%s': ",
		    parent == NULL ? "" : "include ", fl->fullname);
	}
	if (fl->fullname != fl->givenname)
	    free(fl->fullname);
	free(fl->givenname);
	free(fl);
	if (errno == ENOENT && allow_missing) {
	    return parent;
	} else {
	    return NULL;
	}
    }
    euid = geteuid();
    uid = userinfo.orig_uid;
    if (euid == 0 && uid == 0) {
	/* Being run by root */
	if (st.st_uid != 0 && st.st_uid != nobody_uid) {
	    Error(0, 0, "super.tab %sfile `%s' isn't owned by root \
or nobody,\n\tbut we are being run by root.  Bailing out.\n",
		parent == NULL ? "" : "include ", fl->fullname);
	    if (debug || it_came_from_cmdline) {
		Error(0, 0,
		  "If this weren't debug mode, super would have quit here.\n");
	    } else {
		return NULL;
	    }
	}
	if (st.st_mode & (S_IWGRP || S_IWOTH)) {
	    Error(0, 0, "super.tab %sfile `%s' is owned by root \
or nobody,\n\tbut is group- or world-writeable.  Bailing out.\n",
		parent == NULL ? "" : "include ", fl->fullname);
	    if (debug || it_came_from_cmdline) {
		Error(0, 0,
		  "If this weren't debug mode, super would have quit here.\n");
	    } else {
		return NULL;
	    }
	}

    } else if (euid == 0) {
	/* Running as root, original user someone else */
	if (st.st_uid != 0 && st.st_uid != nobody_uid) {
	    Error(0, 0, "super.tab %sfile `%s' isn't owned by root \
or nobody,\n\tbut our euid==0.   %s to uid=%d.\n",
		parent == NULL ? "" : "include ", fl->fullname,
		(debug || it_came_from_cmdline) ?
		    "If this weren't debug mode, we'd revert" : "Reverting",
		userinfo.orig_uid);
	    if (!debug)
		setuid(uid);
	}
	if (st.st_mode & (S_IWGRP || S_IWOTH)) {
	    Error(0, 0, "super.tab %sfile `%s' is owned by root \
or nobody,\n\tbut is group- or world-writeable.  %s to uid=%d.\n",
		parent == NULL ? "" : "include ", fl->fullname,
		(debug || it_came_from_cmdline) ?
		    "If this weren't debug mode, we'd revert" : "Reverting",
		userinfo.orig_uid);
	    if (!debug)
		setuid(uid);
	}

    } else if (uid != userinfo.caller.pw_uid) {
	/* Real uid has changed -- make sure uid is owner of superfile. */
	if (st.st_uid != uid) {
	    Error(0, 0, "super.tab %sfile `%s' isn't owned by uid %d.\n",
		parent == NULL ? "" : "include ", fl->fullname, uid);
	    if (debug || it_came_from_cmdline) {
		Error(0, 0,
		    "If this weren't debug mode, super would quit here.\n");
	    } else {
		return NULL;
	    }
	}
	if (st.st_mode & (S_IWGRP || S_IWOTH)) {
	    if (userinfo.orig_uid == 0) {
		Error(0, 0,
	    "super.tab %sfile `%s' is group or world-writable.  Bailing out.\n",
		    parent == NULL ? "" : "include ", fl->fullname);
		if (debug || it_came_from_cmdline) {
		    Error(0, 0,
			"If this weren't debug mode, super would have quit here.\n");
		} else {
		    return NULL;
		}
	    }
	}
    }


    if ((fl->fp = fopen(fl->fullname, "r")) == NULL) {
	Error(1, 0, "%t\n\tCouldn't open super.tab %sfile `%s': ",
		parent == NULL ? "" : "include ", fl->fullname);
	return NULL;
    }

    fl->line = 1;
    fl->nl = 0;
    fl->prev = parent;

    return fl;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Close a file; return previous in list, or NULL when all done */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
FileList *
file_close(curr)
FileList *curr;
{
    FileList *parent;

    if (!curr)
	return (FileList *) NULL;

    parent = curr->prev;

    if (debug) {
	fprintf(stderr, "\tClosing %sfile %s.\n",
		parent == NULL ? "" : "include ", curr->fullname);
	if (parent)
	    fprintf(stderr, "\tReturning to %s file %s, line %d\n",
		parent->prev == NULL ? "top-level" : "include ",
		parent->fullname, parent->line);
    }

    fclose(curr->fp);

    if (curr->fullname != curr->givenname)
	free(curr->fullname);
    free(curr->givenname);
    free(curr);

    return parent;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Initialize an StrArray */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
StrInit(a)
StrArray *a;
{
    a->n = 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Get address of string element of StrArray */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char *
StrEltGetPtr(a, ielt)
StrArray *a;	/* StrArray with element to fill */
int ielt;	/* Element to return */
    /* Returns NULL if no such element (or if unused) */
{
    if (ielt >= 0 && ielt < a->n && a->str[ielt].used)
	return a->str[ielt].s;
    else
	return NULL;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Put string into element of StrArray.
 * Returns -1 on malloc/realloc failure, 0 otherwise.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
StrEltCpy(a, ielt, str)
StrArray *a;	/* StrArray with element to fill */
int ielt;	/* Element to be filled */
char *str;	/* what to put into ielt'th place */
{
    int l = strlen(str);
    if (StrNalloc(a, ielt) == -1)
	return -1;

    a->str[ielt].used = 1;
    if (a->str[ielt].n == 0) {
	a->str[ielt].s = malloc(l+1);
	a->str[ielt].n = l+1;
    } else if (a->str[ielt].n < l+1) {
	a->str[ielt].s = realloc(a->str[ielt].s, l+1);
	a->str[ielt].n = l+1;
    }
    if (!a->str[ielt].s)
	return -1;
    strcpy(a->str[ielt].s, str);
    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Returns number of elements of StrArray */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
StrNElts(a)
StrArray *a;
{
    return a->n;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Return number of in-use elements of StrArray */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
StrLastInUse(a)
StrArray *a;	/* StrArray with element to fill */
{
    int i;
    int last;

    for (i=0, last = -1; i < a->n; i++) {
	if (a->str[i].used)
	    last = i;
    }

    return last;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Marks all elements of StrArray as unused */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
StrEltsUnused(a)
StrArray *a;
{
    int i;
    for (i=0; i < a->n; i++)
	a->str[i].used = 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Makes StrArray large enough to have an ielt'th element.
 * Returns -1 on malloc/realloc failure, 0 otherwise.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
StrNalloc(a, ielt)
StrArray *a;	/* StrArray that must have an ielt'th element */
int ielt;
{
    int i;

    if (ielt >= a->n) {
	/* Have to increase the new space */
	unsigned int new_n;
	if (a->n == 0) {
	    new_n = (ielt < 4) ? 4 : 2*ielt ;
	    a->str = (CountedString *) malloc(sizeof(CountedString) * new_n);
	} else {
	    new_n = 2*ielt;
	    a->str = (CountedString *)
		    realloc((void *) a->str, sizeof(CountedString) * new_n);
	}
	if (!a->str)
	    return -1;
	for (i=a->n; i < new_n; i++)
	    a->str[i].n = 0;
	a->n = new_n;
    }
    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Copy up to n-1 characters into "to"; then null-terminate.
 * Return 1 if all characters fitted into "to", else return 0.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
stringcopy(to, from, n)
char *to;       /* buffer to copy into */
char *from;     /* string to copy */
int n;          /* size of to buffer */
{
    int l = strlen(from);
    if (l >= n) {
	strncpy(to, from, n-1);
	to[n-1] = '\0';
	return 0;
    } else {
	strcpy(to, from);
	return 1;
    }
    /* NOTREACHED */
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Opens the logfile. */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
opensuperlog()
{
    extern FILE *error_logfile;	/* to tell Error() where the log is */

    close_writer();		/* in case there is already one running */

    if (*globalinfo.log.filename == '\0') {
	Error(0, 0, "opensuperlog(): logfile name is (nil)\n");
	return;
    }

    globalinfo.log.fp = open_writer(globalinfo.log.user,
				globalinfo.log.filename, &globalinfo.log.pid);

    error_logfile = globalinfo.log.fp;	/* ...so Error() writes here too */
    return;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    /* In order to implement the loguser=xxx option, we (1) create a pipe,
     * (2) fork, in the child setuid to loguid; (3) child opens logfile;
     * (4) child copies from pipe to logfile.  Meanwhile, we return a pointer
     * to a stream to the pipe as the log stream seen by the parent program.
     * This allows us to implement a special uid for the logfile writer,
     * without needing the operating system to offer saved uid's or
     * interprocess file-descriptor passing, etc.
     */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
FILE *
open_writer(user, filename, pid_p)
char *user;
char *filename;
pid_t *pid_p;	/* filled with pid of created logger */
{
    FILE *fp = NULL;
    int fildes[2];
    pid_t child;

    if (pipe(fildes) == -1) {
	(void) Error(1, 0, "Failed to created pipe for logfile; no logging: ");
	return NULL;
    }
    child = fork();
    if (child == -1) {
	(void) Error(1, 0, "Failed to create child for logfile; no logging: ");
	return NULL;

    } else if (child > 0) {
	/* In parent -- close read side, and aim logstream at write side */
	if (pid_p)
	    *pid_p = child;
	(void) close(fildes[0]);
	if (!(fp = fdopen(fildes[1], "w"))) {
	    (void) Error(1, 0,
		"failed to fdopen logfile pipe writer; no logging: ");
	    (void) close(fildes[1]);
	    return NULL;
	}

    } else if (child == 0) {
	/* In child.  Open log file and copy from pipe to log. */
	FILE *input;
	char text[2000];
	(void) close(fildes[1]);
	if (!(input = fdopen(fildes[0], "r"))) {
	    (void) Error(1, 0,
		"failed to fdopen logfile pipe reader; no logging: ");
	    (void) close(fildes[1]);
	    exit(1);
	}
	if (user && *user != '\0') {
	    stringcopy(localinfo.user, user, sizeof(localinfo.user));
	    *localinfo.group = '\0';
	    *localinfo.u_g = '\0';
	    if (set_u_g() == -1) {
		(void) Error(1, 0,
		"failed to setuid %s before opening logfile; no logging: ",
		globalinfo.log.user);
		exit(1);
	    }
	}
	if (!(fp = fopen(globalinfo.log.filename, "a"))) {
	    if (user && *user != '\0')
		(void) Error(1, 0,
		    "failed to open logfile `%s' using uid `%s': ",
		    globalinfo.log.filename, localinfo.user);
	    else
		(void) Error(1, 0,
		    "failed to open logfile `%s': ", globalinfo.log.filename);
	    exit(1);
	}
	while (fgets(text, sizeof(text), input)) {
	    if (fputs(text, fp) == EOF)
		(void) Error(1, 0, "fputs to logfile failed: ");
	}
	(void) fclose(fp);
	exit(0);
    }
    return fp;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Closes the logfile stream, then calls wait(). */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

void
close_writer()
{
    pid_t pid;

    if (!globalinfo.log.fp && globalinfo.log.pid == -1)
	return;

    if (globalinfo.log.fp) {
	if (fclose(globalinfo.log.fp) == EOF)
	    Error(1, 0, "failed to close globalinfo.log.fp: ");
	globalinfo.log.fp = NULL;
    }

    if (globalinfo.log.pid != -1) {
	while ((pid = wait((int *) NULL)) > 0 && pid != globalinfo.log.pid) {
	    Error(0, 0, "wait() surprised! close_writer() received pid %d;\n\t\
expected logger pid = %d; waiting for correct pid...\n",
			pid, globalinfo.log.pid);
	}
	if (pid == -1)
	    Error(1, 0, "while waiting for logger process to exit");
	globalinfo.log.pid = -1;
    }
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    /* Construct a host-unique directory name:
     * xyz.home.caltech.edu -> prefix/xyz.home.caltech.edu/user
     * If hostname is empty string, file is prefix/user.

     * WARNING: the hostname used is that from gethostname().
     * Note that this is not necessarily unique across
     * internet domains, since it is frequently not a
     * fully-qualified domain name.  Therefore you should NOT
     * share the timestamp directory outside the local domain.
     */

    /* returns NULL on error, constructed path otherwise */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char *
makedirname(prefix, hostname, file)
char *prefix, *hostname, *file;
{
    int l;
    char *s, str[MAXPATHLEN];

    l = strlen(prefix) + 1 + strlen(hostname) + 1;
    if (l >= MAXPATHLEN) {
	Error(1, 0,
	"Can't create timestamp directory: it would exceed MAXPATHLEN = %d\n",
	MAXPATHLEN);
	return NULL;
    }

    strcpy(file, prefix);

    if (!*hostname)
	return file;

#ifndef HAVE_LONG_FILE_NAMES
    strncpy(str, hostname, 14);
    str[14] = '\0';	/* in case exactly 14 chars were copied */
#else
    strcpy(str, hostname);
#endif
    for (s = strrchr(str, '.'); s; *s = '\0', s = strrchr(str, '.')) {
	strcat(file, "/");
	strcat(file, s+1);
    }
    strcat(file, "/");
    strcat(file, str);

    return file;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Creates a directory, including any needed directories leading
 * to it.  Returns -1 on stat/mkdir failure; 0 otherwise.
 * WARNING: doesn't check if final component is a directory.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
makedir(dir)
char *dir;	/* path with directories only. */
{
    static struct stat st;
    char *q;
    char path[MAXPATHLEN];

    /* First create directories along way, if necessary */
    strcpy(path, dir);

    for (q=path; q && *q; ) {

	/* skip leading slashes */
	while (*q == '/')
	    q++;

	/* check directory before next slash */
	q = strchr(q, '/');
	if (q)
	    *q = '\0';

	/* Stat directory; if missing, create it */
	if (stat(path, &st) != 0) {
	    if (errno != ENOENT) {
		return Error(1, 0, "Failed to stat directory `%s'\n", path);
	    } else {
		if (mkdir(path, 0700) != 0)
		    return Error(1, 0,
				"Failed to create directory `%s'\n", path);
	    }
	}

	/* Restore slash */
	if (q)
	    *q = '/';
    }

    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Adds a variable definition.
 * Returns 0 on success, -1 on error.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
add_variable(varname, vardefn)
char *varname;
char *vardefn;
{
    /*
     * Allocate space for varname, vardefn, and insert into
     * vars table.
     */
    ENTRY item;
    char *space;
    int ln = strlen(varname);
    int lb = strlen(vardefn);

    if (!created_variables_table) {
	if (!hcreate(1000))
	    return Error(0, 0,
		"%tCouldn't allocate hash table for variable processing\n");
	created_variables_table = 1;
    }

    if (debug > 1)
	fprintf(stderr, "entering add_variable(\"%s\",\"%s\")\n",
		varname, vardefn);

    space = malloc(ln+1 + lb+1);
    if (!space)
	return Error(0, 0,
	    "%tFailed to allocate space for definition of variable `%s'\n",
	    varname);

    item.key = space;
    item.data = space + ln+1;
    strcpy(item.key, varname);
    strcpy(item.data, vardefn);

    if (debug > 1)
	fprintf(stderr, "Adding variable `%s' = `%s'\n", item.key, item.data);

    if (!hsearch(item, ENTER))
	return Error(0, 0,
	"%tFailed to allocate space for hash-table entry for variable `%s'\n",
		varname);

    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Add sysinfo(2) items as variables.  */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
add_sysinfo_variables()
{
    char buf[500];
    add_variable("SI_ARCHITECTURE", "");
#ifdef HAVE_SYSINFO
#ifdef SI_ARCHITECTURE
    if (sysinfo(SI_ARCHITECTURE, buf, sizeof(buf)) != -1) {
	add_variable("SI_ARCHITECTURE", buf);
    }
#endif
#endif

    add_variable("SI_HOSTNAME", "");
#ifdef HAVE_SYSINFO
#ifdef SI_HOSTNAME
    if (sysinfo(SI_HOSTNAME, buf, sizeof(buf)) != -1) {
	add_variable("SI_HOSTNAME", buf);
    }
#endif
#endif

    add_variable("SI_HW_PROVIDER", "");
#ifdef HAVE_SYSINFO
#ifdef SI_HW_PROVIDER
    if (sysinfo(SI_HW_PROVIDER, buf, sizeof(buf)) != -1) {
	add_variable("SI_HW_PROVIDER", buf);
    }
#endif
#endif

    add_variable("SI_HW_SERIAL", "");
#ifdef HAVE_SYSINFO
#ifdef SI_HW_SERIAL
    if (sysinfo(SI_HW_SERIAL, buf, sizeof(buf)) != -1) {
	add_variable("SI_HW_SERIAL", buf);
    }
#endif
#endif

    add_variable("SI_MACHINE", "");
#ifdef HAVE_SYSINFO
#ifdef SI_MACHINE
    if (sysinfo(SI_MACHINE, buf, sizeof(buf)) != -1) {
	add_variable("SI_MACHINE", buf);
    }
#endif
#endif

    add_variable("SI_RELEASE", "");
#ifdef HAVE_SYSINFO
#ifdef SI_RELEASE
    if (sysinfo(SI_RELEASE, buf, sizeof(buf)) != -1) {
	add_variable("SI_RELEASE", buf);
    }
#endif
#endif

    add_variable("SI_VERSION", "");
#ifdef HAVE_SYSINFO
#ifdef SI_VERSION
    if (sysinfo(SI_VERSION, buf, sizeof(buf)) != -1) {
	add_variable("SI_VERSION", buf);
    }
#endif
#endif

    add_variable("SI_SRPC_DOMAIN", "");
#ifdef HAVE_SYSINFO
#ifdef SI_SRPC_DOMAIN
    if (sysinfo(SI_SRPC_DOMAIN, buf, sizeof(buf)) != -1) {
	add_variable("SI_SRPC_DOMAIN", buf);
    }
#endif
#endif

    add_variable("SI_SYSNAME", "");
#ifdef HAVE_SYSINFO
#ifdef SI_SYSNAME
    if (sysinfo(SI_SYSNAME, buf, sizeof(buf)) != -1) {
	add_variable("SI_SYSNAME", buf);
    }
#endif
#endif
}

#ifdef HAVE_UNAME
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Add uname(2) items as variables.  */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
add_uname_variables()
{
    struct utsname uts;

    if (uname(&uts) != -1) {
	add_variable("UNAME_SYSNAME", uts.sysname);
	add_variable("UNAME_NODENAME", uts.nodename);
	add_variable("UNAME_RELEASE", uts.release);
	add_variable("UNAME_VERSION", uts.version);
	add_variable("UNAME_MACHINE", uts.machine);
    } else {
	add_variable("UNAME_SYSNAME", "");
	add_variable("UNAME_NODENAME", "");
	add_variable("UNAME_RELEASE", "");
	add_variable("UNAME_VERSION", "");
	add_variable("UNAME_MACHINE", "");
    }
}
#endif

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Does variable substitution on a string.  */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char *
do_variables(string)
char *string;
{
    char c, *dollar, *varname;
    char *tail=NULL;
    char savechar;
    char key[2];
    int l;
    ENTRY wanted_item, *found_item;

    dollar = strchr(string, '$');	/* Special early return for no vars */
    if (!dollar)
	return string;

    if (debug > 1)
	fprintf(stderr, "Applying variable expansion to: `%s'\n", string);

    if (!created_variables_table) {
	Error(0, 0,
"%tNo variables have been defined, but super.tab file is using some anyway!\n");
	return NULL;
    }

    variablebuf.l = 0;		/* Clear the buffer */

    /* Initialize the buffer to be at least the same size as the input buffer */
    if (!checksize(&variablebuf, ebuf.l)) {
	Error(1, 0, "%tCouldn't increase space for variable processing\n");
	return NULL;
    }

    while (string && *string) {
	/* First, copy up to variable character */
	dollar = strchr(string, '$');
	if (!dollar)
	    l = strlen(string);
	else
	    l = dollar - string;
	strncpy(variablebuf.buf + variablebuf.l, string, l);
	variablebuf.l += l;
	variablebuf.buf[variablebuf.l] = '\0';
	string += l;

	/* Reached end of string? */
	if (!*string)
	    break;

	/* Not at string end; expand variable */

	if ( (c = *(dollar+1)) == '$') {
	    /* $$ is a special macro name */
	    key[0] = c;
	    key[1] = '\0';
	    varname = key;
	    string += 2;
	    savechar = '\0';

	} else if (isalnum(c) || c == '_') {
	    /* Replace $name -> variable defn */
	    for (tail=dollar+2; isalnum(*tail) || *tail == '_'; tail++)
		;
	    varname = dollar+1;
	    /* tail points to one past last char in variable name.
	     * Save this character, then overwrite with null char.
	     */
	    savechar = *tail;
	    *tail = '\0';
	    string = tail;

	} else if (c == '(') {
	    /* Replace $(name) -> variable defn */
	    for (tail=dollar+2; isalnum(*tail) || *tail == '_'; tail++)
		;
	    /* must have reached right paren, and must make sure first
	     * character was alphabetic
	     */
	    if (tail == dollar+2) {
		Error(0, 0, "%tEmpty variable name is illegal: `$()'\n");
		return NULL;

	    } else if (*tail != ')' || !isalpha(*(dollar+2))) {
		Error(0, 0, "%tNot a valid variable name: `%.*s'\n",
				tail+1-dollar, dollar);
		return NULL;
	    }
	    savechar = '\0';
	    *tail = '\0';
	    varname = dollar+2;
	    string = tail+1;

	} else {
	    /* All other $X is error */
	    Error(0, 0,
		"%tIllegal variable name `$%c'.  \n\
(Use `$$' to get a plain `$' passed on to the rest of file parsing.)\n", c);
	    return NULL;
	}

	if (debug > 1) {
	    fprintf(stderr, "Variable name is `%s'\n", varname);
	}
	if (varname) {
	    /* Have a variable requiring expansion */
	    wanted_item.key = varname;
	    found_item = hsearch(wanted_item, FIND);
	    if (!found_item) {
		Error(0, 0, "%t\n\tNo such variable as `$%s'\n",
			wanted_item.key);
		return NULL;
	    }
	    l = strlen(found_item->data);
	    if (!checksize(&variablebuf, ROUNDUP(l+1, 1024))) {
	    Error(1, 0, "%tCouldn't increase space for variable processing\n");
		return NULL;
	    }
	    strcpy(variablebuf.buf+variablebuf.l, found_item->data);
	    variablebuf.l += l;
	    variablebuf.buf[variablebuf.l] = '\0';
	    /* Restore the saved character */
	    if (savechar && tail)
		*tail = savechar;
	}
    }

    if (debug > 1)
	fprintf(stderr, "variable-expanded string is `%s'\n", variablebuf.buf);

    return variablebuf.buf;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* A function for printing one variable's name and value.
 * See hprint() for calling sequence.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
print_variable(indx, key, data)
int indx;
char *key;
char *data;
{
    /* Ignore the variable "$", which is just a cute way of getting
     * "$$" to translate to plain "$".
     */
    if (strcmp(key, "$") != 0)
	printf("\t%s:\t%s\n", key, data);
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Input is string like   "lhs<sep>rhs"
 * If there is no <sep>, null ptr is returned.
 * If lhs == left, then ptr to rhs is returned; else null pointer.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char *
str_val(left, sep, str)
char *left;
int sep;
char *str;
{
    char *s = strchr(str, sep);

    if (!s					/* equal sign? */
	|| strlen(left) != (s - str)		/* not same size as `left'? */
	|| strncmp(left, str, s-str) != 0)	/* lhs != left */
	return NULL;
    
    return s+1;
}


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* re_comp()-style interface to wildmat. */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
static char *shell_pattern;
char *
shell_compile(s)
char *s;
{
    shell_pattern = s;
    return NULL;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* re_exec()-style interface to wildmat. */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
shell_compare(s)
char *s;
{
    extern int wildmat __P((char *str, char *pat));
    return wildmat(s, shell_pattern);
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
init_strqtokS()
{
    unsigned char *p;
    memset(my_qm, '\0', sizeof(my_qm));
    for (p=(unsigned char *) QM; *p; )
	my_qm[*p++] = 1;

    memset(my_cc, '\0', sizeof(my_cc));
    for (p=(unsigned char *) CM; *p; )
	my_cc[*p++] = 1;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Finds the hostname, like gethostname(), then uses canonicalize_hostname
 * to change it to a canonical form.
 * Returns 0 on success, and -1 on error, like gethostname().
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
get_canonical_hostname(buf, len)
char *buf;
int len;
{
    if (gethostname(buf, len) < 0)
	return Error(0, 0, "gethostname(\"%s\", %d) failed\n", buf, len);
    
    return canonicalize_hostname(buf, len);
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Canonicalizes a hostname, if available.
 * Returns 0 on success, and -1 on error, like gethostname().
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
canonicalize_hostname(buf, len)
char *buf;
int len;
{
#ifdef HAVE_GETHOSTBYNAME
    struct hostent *he, *he_nodot, *he_dot;
    char dot_name[80] = "", nodot_name[80] = "";


    if (globalinfo.gethostbyname) {
	if ((l=strlen(buf)) > len - 2 || l > sizeof(dot_name)-1)
	    return Error(0, 0,
			"hostname %s is too long for our buffer!\n", buf);
	/* On systems using DNS, appending a dot should force gethostbyname()
	 * to fully expand and return fqdn.  On systems using NIS, appending a
	 * dot will cause match failure.  So we try both forms, and take the
	 * longer match.
	 */
	he_nodot = gethostbyname(buf);
	if (he_nodot && he_nodot->h_name)
	    strcpy(nodot_name, he_nodot->h_name);
	strcat(buf, ".");
	he_dot = gethostbyname(buf);
	if (he_dot && he_dot->h_name)
	    strcpy(dot_name, he_dot->h_name);
	if (strlen(dot_name) && strlen(nodot_name)) {
	    if ((strlen(dot_name) > len - 1) || (strlen(nodot_name) > len - 1))
	        return Error(0, 0,
		"gethostbyname() returns `%s' which is too long for our buffer!\n",
		    buf);
	    strcpy(buf, strlen(dot_name) > strlen(nodot_name) ?
							dot_name : nodot_name);
	} else if (strlen(dot_name)) {
	    if (strlen(dot_name) > len - 1)
	        return Error(0, 0,
			"gethostbyname() returns `%s' which is too long for our buffer!\n",
			     buf);
	    strcpy(buf, dot_name);
	} else if (strlen(nodot_name)) {
	    if (strlen(nodot_name) > len - 1)
	      return Error(0, 0,
		"gethostbyname() returns `%s' which is too long for our buffer!\n",
			   buf);
	    strcpy(buf, nodot_name);
	} else {
	    return Error(0, 0,
		    "host `%s' not recognized by gethostbyname().\n", buf);
	}
	/* Delete trailing dot, if still present */
	if ((l=strlen(buf)) > 0 && buf[l-1] == '.')
	    buf[l-1] = '\0';
    }
#endif
    
    return 0;
}

/*
 * Downcase a null-terminated string.
 */
void
strtolower(s)
char *s;
{
    for (; *s; s++)
	if (isupper(*s))
	    *s = tolower(*s);
}


#ifndef HAVE_STRTOL
static unsigned long digit_a2d[128] = {0};

/* Initialize the character-to-digit mapping. */
static void
init_digit(void)
{
    int c;
    for (c=0; c < NELEM(digit_a2d); c++)
	digit_a2d[c] = -1;

    for (c = '0' ; c <= '9'; c++)
	digit_a2d[c] = c - '0';

    digit_a2d['a']=digit_a2d['A'] = 10; digit_a2d['b']=digit_a2d['B'] = 11;
    digit_a2d['c']=digit_a2d['C'] = 12; digit_a2d['d']=digit_a2d['D'] = 13;
    digit_a2d['e']=digit_a2d['E'] = 14; digit_a2d['f']=digit_a2d['F'] = 15;
    digit_a2d['g']=digit_a2d['G'] = 16; digit_a2d['h']=digit_a2d['H'] = 17;
    digit_a2d['i']=digit_a2d['I'] = 18; digit_a2d['j']=digit_a2d['J'] = 19;
    digit_a2d['k']=digit_a2d['K'] = 20; digit_a2d['l']=digit_a2d['L'] = 21;
    digit_a2d['m']=digit_a2d['M'] = 22; digit_a2d['n']=digit_a2d['N'] = 23;
    digit_a2d['o']=digit_a2d['O'] = 24; digit_a2d['p']=digit_a2d['P'] = 25;
    digit_a2d['q']=digit_a2d['Q'] = 26; digit_a2d['r']=digit_a2d['R'] = 27;
    digit_a2d['s']=digit_a2d['S'] = 28; digit_a2d['t']=digit_a2d['T'] = 29;
    digit_a2d['u']=digit_a2d['U'] = 30; digit_a2d['v']=digit_a2d['V'] = 31;
    digit_a2d['w']=digit_a2d['W'] = 32; digit_a2d['x']=digit_a2d['X'] = 33;
    digit_a2d['y']=digit_a2d['Y'] = 34; digit_a2d['z']=digit_a2d['Z'] = 35;
}

long
strtol(register const char *str, char **ptr, int base)
{
    long sign=1;
    long value=0;
    long digit;

    if (*digit_a2d == 0)
	init_digit();

    /* skip leading whitespace */
    while (isspace(*str))
        ++str;

    /* Check for optional sign */
    switch (*str) {
    case '-':
	sign = -1;
	str++;
	break;
    case '+':
	str++;
	break;
    }

    /* Determine base */
    if (base == 0) {
        if (*str != '0') {
            base = 10;
        } else if (*++str == 'x' || *str == 'X') {
            base = 16;
            ++str;
        } else {
            base = 8;
        }
    }

    /* Skip 0[xX], if present */
    if (base == 16 && *str == '0')
	if (*++str == 'x' || *str == 'X')
	    ++str;

    /* Convert value */
    while (*str < NELEM(digit_a2d) &&
		(digit=digit_a2d[*str]) < base && digit != -1) {
	value = value*base + digit;
	++str;
    }

    if (ptr)
	*ptr = (char *) str;
    
    return sign*value;
}
#endif

#ifndef HAVE_MEMSET
void *
memset(s, c, n)
void *s;
int c;
int n;
{
    register int i;
    register unsigned char *p = (unsigned char *) s;

    for (i=0; i<n; i++)
	*p++ = (unsigned char) c;
}
#endif

#ifdef HAVE_SYS_ERRLIST
    extern char *sys_errlist[];
    extern int sys_nerr;
#endif

/*
 * Safe strerror(): range-checks the argument.
 * (C standard doesn't guarantee any range checks.)
 */
char
*Strerror(errnum)
int errnum;
{
    static char buf[500];
#ifndef HAVE_SYS_ERRLIST
    sprintf(buf, "Error %d", errnum);
    return buf;
#else
    if (errnum < 0 || errnum > sys_nerr) {
	sprintf(buf, "Error %d (!)", errnum);
	return buf;
    } else {
#ifdef HAVE_STRERROR
	return strerror(errnum);
#else
	return sys_errlist[errnum];
#endif
    }
#endif
}

#ifndef HAVE_STRDUP
char *
strdup(s)
char *s;
{
    char *t = (char *) malloc(strlen(s)+1);
    strcpy(t, s);
    return t;
}
#endif

#ifndef HAVE_VPRINTF
/* Very system-specific.  May not work for you...
 */
void
vfprintf(stream, format, ap)
FILE *stream;
char *format;
va_list ap;
{
    _doprnt(format, ap, stream);
}

void
vsprintf(str, format, ap)
char *str;
char *format;
va_list ap;
{
    FILE fp;
    fp._cnt = 077777;
    fp._base = fp._ptr = str;
    fp._bufsiz = 0;
    fp._flag = _IOSTRG | _IOWRT;
    fp._file = 0;

    _doprnt(format, ap, &fp);
}
#ifndef HAVE_DOPRNT
ERROR -- YOU HAVE NEITHER v?printf() NOR _doprnt().
YOU ARE HOSED UNTIL YOU SUPPLY ONE OF THESE.
#endif
#endif