File: super.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 (1382 lines) | stat: -rw-r--r-- 42,497 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
static char rcsid[] = "$Id: super.c,v 1.450 1998/04/07 07:30:23 will Exp $";
/* The code should compile with either ANSI C or K&R compilers. */

/*
 *      Copyright (c) 1993 by California Institute of Technology.
 *      Written by William Deich.  Not derived from licensed software.

 *    You may distribute under the terms of either the GNU General Public
 *    License or the Artistic License, as specified in the README file.
 */

#include "super.h"
#include "version.h"

/*
 * Super allows users to execute other programs, particularly
 * scripts, as root (or another user/group), without unduly
 * compromising security.
 * 
 * Use:
 * 
 *     $0 -h, $0 -V
 *		...give usage info or print just the version number.
 *
 *     $0 [-H | -f] [-F superfile] [ -T hh[:mm][/day] ] [-U uid] [-G gid]
 *		...lists allowed commands.
 *
 *     $0 command [args...]
 *		...execute command.
 *
 *     $0 -b
 *		...lists builtin variables (useful when creating super.tab).
 *
 *     $0 [-d | -D] [-F superfile] [-T time] [-U uid] [-G gid] [-M mach] [--] \
 *						[commandname [args...]]
 *		...debug mode.
 *
 *     $0 -c [superfile]
 *		...just check syntax of the superfile.
 * 
 * Options:
 *	-b -- print the "builtin" variables, then exit.
 *	-c [superfile] -- check syntax of superfile, but don't execute anything.
 *	-d -- debug mode: show what would be done,
 *		but don't actually execute a command.
 *	-D -- verbose debug mode: same as -d, plus tell more about variables.
 *	-F superfile -- names the super file to use; for testing only.
 *		No command will actually be executed.
 *	-G gid -- act as if the invoking user was group gid; for testing only.
 *		No command will actually be executed.
 *	-M mach -- act as if the machine (hostname) was mach; for testing only.
 *		No command will actually be executed.
 *	-T hh[:mm][/day] -- act as if the command is executed at the specified
 *		time; for testing only.  No command will actually be executed.
 *	-h -- usage: print usage info, then exit.
 *	-H -- a long-winded listing of allowed commands for this user,
 *		then exit.
 *	-f -- (just the facts, ma'm) a version of -H that prints no extra
 *	      info, just a list of what you can execute, using the format:
 *		Cmd FullPath [initial args]
 *		Cmd FullPath [initial args]
 *		...
 *	      Useful for scripts that want a list of what you may execute.
 *	-U uid -- act as if the invoking user was user uid; for testing only.
 *		No command will actually be executed.
 *	-V -- print version information, then exit.
 * 
 * The super.tab file names each command that super will execute, and
 * says who can use it.  See super.tab.summary for an overview.

 */

char superfile_writable[] = SUPERFILE;	/* The super.tab file -- put it
					 * into a char array so we can
					 * overwrite it later, if nec.
					 */
char *superfile = superfile_writable;	/* The super.tab file */

/* Global info */
GlobalInfo globalinfo = {
	"",		/* owner (required owner of file) */
	NULL,		/* chdir_path (char *) */
	0,		/* relative_path (bool) */
	0,		/* group_slash (bool) */
	MAXENVLEN,	/* maximum length of environment variable defn */
	NULL,		/* additional permitted envvars */
	0,		/* nice_incr (int) */
	0,		/* mask (umask) */
	MAXLEN1ARG,	/* maximum length of a single argument */
	MAXLENARGS,	/* maximum length of all arguments, combined */

	 {		/* Global password requirements */
		0,	/* required (bool) */
		5,	/* timeout (min) */
		0,	/* renewtime (bool) */
		1,	/* perhost (bool) */
		""},	/* user (user who owns file) */


	{0,NULL,NULL},	/* userbefore: list of u/g/h pats before per-cmd pats */
    	{0,NULL,NULL},	/* userafter: list of u/g/h pats after per-cmd pats */
    	{0,NULL},	/* b_a_text: list of original text for above */
	1,		/* user_clear: (bool: clear if new val seen) */

	{{0,0,0,0},	/* timebefore: permitted times before per-cmd pats */
		NULL},
	{{0,0,0,0},	/* timeafter: permitted times after per-cmd pats */
		NULL},
	1,		/* time_clear: clear if new val seen */

	0,		/* use_after: set to !0 when we see <> */

	{ NULL,		/* log: FILE *fp */
	    "",		/* filename */
	    "",		/* user: value of loguid=xxx */
	    0,		/* uid: UID under which we open logfile */
	    -1,		/* pid: PID of the logger process */
	    0,		/* newfile: !0 if logfile given but not yet used */
	    0 },	/* newuid: !0 if loguid given but not yet used */

	"",		/* mailcmd */
	0,		/* mail_success (bool) */
	1,		/* use gethostbyname (bool) */

    	{0},		/* groups[]: gid's of supplementary groups */
    	GROUPS_NOTSET,	/* ngroups: number of supplementary groups */
    	0,		/* groups_added */
	};

/* The list of currently open files */
FileList *currfile = NULL;

/* The struct of what things we've matched */
Conditions matches;

/* The localinfo struct is filled in a bit at a time until it completely
 * describes the caller, the program to invoke, any options
 * set in the control line, etc.
 */
UserInfo userinfo;

LocalInfo localinfo = {
	{NULL, -1, 0, "", 0, 0},	/* Initialize ProgMatch empty */
					/* Other elements that need
					 * start initializers are done
					 * through explict assignment.
					 */
		};

extern char *s_re_comp __P(( char *));	/* regular-expression compiler */
int shell_compare __P(( char * ));	/* s_re_comp()-style i/f to wildmat() */
extern int s_re_exec __P(( char * ));	/* regular-expression comparison */
char *shell_compile __P(( char * ));	/* s_re_exec()-style i/f to wildmat() */


char *prog;				/* this program */
int debug=0;				/* Set by the debug options flag */
int it_came_from_cmdline=0;		/* Set by -F/-T/-U/-G/-M flags */
int check_syntax=0;			/* Set by the -c options flag */

/* Routines used to compile/match user/group/host patterns */
char *(*pat_compile) __P((char *)) = s_re_comp;
int (*pat_compare) __P((char *)) = s_re_exec;
int need_re_anchor = 1;


/* For strqtokS */
unsigned char my_qm[256];		/* our quotemarks */
unsigned char my_cc[256];		/* our comment characters */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
main(argc, argv)
int argc;
char **argv;
{
    int status, n_builtin;
    char *s, *cmd, *path;
    char **arglist, **envp;
    extern char *error_prog;
    int iarg, givehelp, giveversion, verbosity, printvars;

    s = strrchr(argv[0], '/');
    prog = (s && *(s+1)) ? s+1 : argv[0];
    error_prog = ONETRUENAME;	/* same as prog, but used by Error() */

    debug = check_syntax = giveversion = givehelp = printvars = 0;

    error_srcfile = superfile;	/* error messages w/ line nums refer to this */
    error_line = -1;
    if (add_variable("$", "$") == -1)	/* Built-in variable $$ -> "$" */
	return 1;

    if (init_userinfo() == -1)	/* Initialize userinfo struct. */
	return 1;
    init_globalinfo();		/* Initialize globalinfo struct. */
    init_localinfo();		/* Initialize localinfo struct. */

    add_builtin_variables();	/* Define variables that describe this system */

    /* Decide if we were invoked as "super cmd args...", or 
     * as a link: cmd args...
     */
    if (strcmp(prog, ONETRUENAME) == 0) {
	/* Invoked as super [options] cmd args... */
	iarg = do_options(argc, argv, &givehelp, &giveversion,
				&verbosity, &printvars);
	if (iarg < 0 || (argv[0] == NULL && !(givehelp || giveversion))) {
	    /* User screwed up; give minimal help */
	    fprintf(stderr, "Type   %s -h   for usage information.\n", prog);
	    exit(0);
	}
	cmd = argv[iarg];
	argv += iarg;
	/* Check if there was no cmd given after options. */
	if (!cmd || !*cmd) {
	    if (!giveversion)		/* If user didn't give -V, and didn't */
		givehelp = 1;		/* ...give cmd, default is givehelp */
	    cmd = NULL;
	}
	/* Test if we simply print variables, then bail out. */
	if (printvars) {
	    printf("Builtin variables:\n");
	    hprint(print_variable);
	    exit(0);
	}
    } else {
	/* It's been invoked via link to super.  Therefore any options
	 * go to the command, not to super.
	 */
	s = strrchr(argv[0], '/');
	cmd = (s && *(s+1)) ? s+1 : argv[0];
    }

    if (debug)
	debug_hello();

    init_strqtokS();

    if (check_syntax)
	Error(0,0, "Checking syntax of superfile `%s'\n", superfile);

    /* Check if we need to switch to processing a user's super file */
    if (cmd && strchr(cmd, ':'))
	if (user_supertab(cmd) == -1)
	    return 1;

    /* Print version if explicitly requested or if giving help */
    if ((givehelp && verbosity != HELP_FACTS) || giveversion)
	(void) printf("%s version %s patchlevel %s\n",
					    prog, Version, Patchlevel);

    /* If giving version, and not giving help, and there's no command, stop */
    if (giveversion && !givehelp && !cmd)
	exit(0);

    /* Check for permission to execute, and change uid/gid as necessary */
    if ((path = approve(cmd, givehelp, verbosity)) == NULL)
	return 1;
    else if (*path == '\0')
	return 0;

    /* Get the arglist for the command, and null-terminate cmd if not
     * already done so.  Do this before things like get_owner, because
     * newargs() parses paths that look like "command args" and separates
     * out the command part.
     */
    arglist = newargs(path, argv, &n_builtin);

    /* Check argument lengths */
    if (check_arglistlen(argv) != 0)
	return 1;

    /* Determine ownership of the program */
    if (get_owner(path, &localinfo.file_uid, &localinfo.file_gid) != 0)
	return 1;

    /* Sanity check */
    if (check_syntax)
	Error(0, 2,
	    "Abort: shouldn't ever get here when check_syntax is set!\n");

    /* Check that the file to execute has proper ownership */
    if (check_owner() != 0)
	return 1;

    /* If nice increment is negative, we have to do it here, while we
     * are still root (note that the uid= option can be used to run
     * as non-root, and we can't do negative nice's as non-root).  Positive
     * nice increments are done later, just before exec'ing, so that we
     * don't have to do the rest of _this_ program at reduced priority.
     */
    if (localinfo.nice_incr < 0) {
	if (it_came_from_cmdline) {
	    Error(0, 0,
	   "Not applying nice increment = %d because of flag -F/-T/-U/-G/-M.\n",
		rcl_nice_incr());
	} else if (set_nice_incr() == -1) {
	    return 1;
	}
    }

    /* Set uid/gid if necessary */
    status = set_u_g();

    /* Button up for security, and get a modified environment */
    envp = buttonup(cmd);
    if (!envp)
	return 1;

    /* Change directory if requested */
    if (status != -1)
	status = set_chdir();

    /* Set the umask value */
    set_umask();

    if (debug) {
	debug_print(path, arglist, envp, n_builtin);
	if (status == -1) {
	    fprintf(stderr, "\n\t(This command would not be executed \
due to previously-reported problem)\n");
	} else {
	    fprintf(stderr,
	    "\n\t(Your command is ok, but isn't executed in debug mode.)\n");
	}
	return 0;
    } else if (it_came_from_cmdline) {
	debug_print(path, arglist, envp, n_builtin);
	fprintf(stderr,
	"\n\t(Your command is ok, but isn't executed because of one or more \
-F/-T/-U/-G/-M flags.)\n");
	return 0;
    }
    if (status == -1) {
	return 1;
    }

    /* Check password requirements */
    if (check_pass(cmd) != 0)
	return 1;

    /* Log an informational message at LOG_INFO priority, not at
     * the usual error priority.
     */
    {
#ifdef HAVE_SYSLOG
	extern int error_priority;
	int old_pri = error_priority;
	error_priority = LOG_INFO;
#endif
	logmsg(cmd, arglist);
#ifdef HAVE_SYSLOG
	error_priority = old_pri;
#endif
    }
    /* Close the logfile writer, if any: we are done logging, and going
     * to exec the prog.
     */
    close_writer();

    /* If nice increment is positive, we do it here, just before
     * exec'ing.  Negative nice increments were done earlier, before
     * any change-uid's.
     */
    if (localinfo.nice_incr > 0)
	if (set_nice_incr() == -1)
	    return 1;

    /* If print option is set, write message before executing command */
    if (localinfo.print)
	puts(localinfo.print);

    if (execve(path, arglist, envp) == -1) {
#ifdef INTERPRETER_HACK
	if (errno == ENOEXEC) {
	    /* Open the file, check for "#!interpreter [argument]" */
	    FILE *fp;
	    char *interp, *argument, line1[1024];

	    if ((fp = fopen(path, "r")) &&		/* open the file */
		fgets(line1, sizeof(line1), fp) &&	/* read first line */
		(strlen(line1) < sizeof(line1)-1) &&	/* not too long? */
		(strncmp(line1, "#!", 2) == 0) &&	/* begins "#!"? */
		(interp = strtok(line1+2, " \t\n"))) {	/* has interpreter? */

		argument = strtok(NULL, " \t\n");	/* get opt argument */

		/* Adjust the arglist -- recall it has room for this */
		if (argument) {
		    arglist -= 2;
		    arglist[0] = arglist[2];
		    arglist[1] = argument;
		    arglist[2] = path;
		} else {
		    arglist--;
		    arglist[0] = arglist[1];
		    arglist[1] = path;
		}
		(void) execve(interp, arglist, envp);
	    }
	}
#endif
	/* If here, we failed to exec the prog.  Re-open the logfile we
	 * closed above and write a message.
	 */
	if (*globalinfo.log.filename != '\0')
	    opensuperlog();
	(void) Error(1,1, "command `%-.500s': Couldn't exec `%s': ", cmd, path);
    }
    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Set options; return index of arg that follows options, or -1 on error.
 * N.B. The flags are assumed to be initialized BY THE CALLER.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
do_options(argc, argv, givehelp, giveversion, verbosity, printvars)
int argc;
char **argv;
int *givehelp, *giveversion, *verbosity, *printvars;
{
    int iarg;
    char *p, *s, *t;
    short minutes;
    char daynum;
    int takes_optional_superfile;
    long l;
    struct passwd *pw;

    /* In case arguments don't have defaults already assigned */
    debug = check_syntax = *giveversion = *givehelp = *printvars = 0;
    *verbosity = HELP_BASIC;	/* only matters if *givehelp != 0 */

    for (iarg = 1; iarg < argc && argv[iarg][0] == '-'; iarg++) {
	if (strcmp(argv[iarg], "--") == 0) {
	    /* End of options */
	    iarg++;
	    break;
	}
	for (s = &argv[iarg][1]; *s; s++) {
	    takes_optional_superfile = 0;
	    switch (*s) {
	    case 'c':
		check_syntax = 1;
		takes_optional_superfile = 1;
		break;
	    case 'F':
		it_came_from_cmdline = 1;
		takes_optional_superfile = 1;
		break;
	    case 'G':
		it_came_from_cmdline = 1;
		if (*(s+1)) {
		    /* User gave -Ggid */
		    t = s+1;
		    s += strlen(s) - 1;
		} else if ((iarg+1 < argc) && argv[iarg+1][0] != '-') {
		    /* User gave -G gid */
		    iarg++;
		    t = argv[iarg];
		} else {
		    return Error(0, 0, "No gid specified after option -G\n");
		}
		l = findgid(1, localinfo.group);
		if (l == -1)
		    return Error(0,0,"Invalid gid specified after option -G\n");
		else
		    userinfo.orig_gid = l;
		break;
	    case 'M':
		it_came_from_cmdline = 1;
		if (*(s+1)) {
		    /* User gave -Mmach */
		    t = s+1;
		    s += strlen(s) - 1;
		} else if ((iarg+1 < argc) && argv[iarg+1][0] != '-') {
		    /* User gave -M mach */
		    iarg++;
		    t = argv[iarg];
		} else {
		    return Error(0, 0, "No machine specified after option -M\n");
		}
		if (strlen(t) > sizeof(userinfo.hostname)-1)
		    Error(1, 1, "Machine name too long -- max allowed is %d\n",
				sizeof(userinfo.hostname)-1);
		strcpy(userinfo.hostname, t);
		if (canonicalize_hostname(userinfo.hostname,
					    sizeof(userinfo.hostname)) == -1)
		    return 1;
		strcpy(userinfo.lc_hostname, userinfo.hostname);
		strtolower(userinfo.lc_hostname);
		break;
	    case 'T':
		it_came_from_cmdline = 1;
		if (*(s+1)) {
		    /* User gave -Ttime */
		    t = s+1;
		    s += strlen(s) - 1;
		} else if ((iarg+1 < argc) && argv[iarg+1][0] != '-') {
		    /* User gave -T time */
		    iarg++;
		    t = argv[iarg];
		} else {
		    return Error(0, 0, "No time specified after option -T\n");
		}
		if (readtime(t,
			&userinfo.ourtime.min, &userinfo.ourtime.day) != 0)
		    return -1;
		break;
	    case 'U':
		it_came_from_cmdline = 1;
		if (*(s+1)) {
		    /* User gave -Uuid */
		    t = s+1;
		    s += strlen(s) - 1;
		} else if ((iarg+1 < argc) && argv[iarg+1][0] != '-') {
		    /* User gave -U uid */
		    iarg++;
		    t = argv[iarg];
		} else {
		    return Error(0, 0, "No uid specified after option -U\n");
		}
		pw = getpwentry(1, t);
		if (!p)
		    return -1;
		else
		    userinfo.orig_gid = pw->pw_gid;
		break;
	    case 'b': *printvars = 1; break;
	    case 'd':
		debug = 1;
		break;
	    case 'D':
		debug = 2;
		break;
	    case 'V': *giveversion = 1; break;
	    case '?': *givehelp = 1; *verbosity = HELP_USAGE; break;
	    case 'h': *givehelp = 1; *verbosity = HELP_USAGE; break;
	    case 'f': *givehelp = 1; *verbosity = HELP_FACTS; break;
	    case 'H': *givehelp = 1; *verbosity = HELP_FULL; break;
	    default:
		    return Error(0, 0, "Unrecognized option `%c'\n", *s);
	    }
	    /* Check for optional superfile */
	    if (takes_optional_superfile) {
		if (*(s+1)) {
		    /* User gave -Xfile */
		    superfile = s+1;
		    s += strlen(s) - 1;
		} else if ((iarg+1 < argc) && argv[iarg+1][0] != '-') {
		    /* User gave -X file */
		    iarg++;
		    superfile = argv[iarg];
		}
		/* Verify that this user has permission to access the file */
		if (access(superfile, R_OK) == -1)
		    Error(1, 1, "You can't read `%s': ", superfile);
		else
		error_srcfile = superfile;
	    }
	}
    }
    /* Default operation: give help if no args */
    if (argc == 1)
	*givehelp = 1;
    return iarg;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Print the debug startup lines */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
debug_hello()
{
    char *s = dayname(userinfo.ourtime.day);
    fprintf(stderr, "\n\tExecuting: %s -%c:\n", prog, (debug < 2) ? 'd' : 'D');
    fprintf(stderr, "\tYou are: user=%s gid=%d hostname=%s\n\n",
	userinfo.caller.pw_name, userinfo.caller.pw_gid, userinfo.hostname);

    fprintf(stderr, "\tStart time=%d:%02d/%s (hr*60+min=%d daycode=%d)\n",
	userinfo.ourtime.min/60, userinfo.ourtime.min%60, s,
	userinfo.ourtime.min, userinfo.ourtime.day);

}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Print the debug info */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
debug_print(path, arglist, envp, n_builtin)
char *path;
char **arglist;
char **envp;
int n_builtin;
{
    char *s, **p, **sp;
    char *cdpath;
    int isglobal, j, iarg;

    fprintf(stderr,
	  "==============================================================\n");
    fprintf(stderr, "\nSuper file is `%s'\n", superfile);
    fprintf(stderr,
	"\n\tPermitted times for execution (in reverse input order):\n");
    if (globalinfo.timebefore.next != 0 || localinfo.time.next != 0
				    || globalinfo.timeafter.next != 0) {
	for (j = 0; j<3; j++) {
	    TimeList *tl;
	    switch (j) {
	    case 0: isglobal=1; tl = globalinfo.timeafter.next; break;
	    case 1: isglobal=0; tl = localinfo.time.next; break;
	    default: isglobal=1; tl = globalinfo.timebefore.next; break;
	    }
	    for ( ; tl ; tl=tl->next) {
		fprintf(stderr, "\t\t%stime~%d:%02d-%d:%02d/%s (%s)\n",
		    tl->te.invert ? "!" : "",
		    tl->te.begin / 60, tl->te.begin % 60,
		    tl->te.end / 60, tl->te.end % 60, dayname(tl->te.day),
		    isglobal ? "global def" : "per-cmd def");
	    }
	}
    } else {
	    fputs(" (unrestricted)\n", stderr);
    }
    fputs("\n", stderr);

    (void) fprintf(stderr, "\tCommand: <%s>\n", arglist[0]);
    (void) fprintf(stderr, "\tPath: <%s>\n", path);
    for (sp=arglist; *sp; sp++)
	;
    (void) fprintf(stderr, "\tArgc: %d\n", (int) (sp - arglist));
    (void) fprintf(stderr, "\tMax len, 1 arg: %d   Max len, all args: %d\n",
				localinfo.maxlen1arg, localinfo.maxlenargs);
    for (sp=arglist; *sp; sp++) {
	iarg = sp - arglist;
	(void) fprintf(stderr, "\tArgv[%d]:  <%s>\n", iarg, *sp);
	if (iarg > n_builtin) {
	    s = StrEltGetPtr(&localinfo.argpats, iarg-n_builtin);
	    if (s)
		fprintf(stderr, "\t\tMust match pattern: %s\n", s);
	}
    }

    if (localinfo.usr_args[0] < 0) {
	(void) fprintf(stderr,
			    "\tAny number of user-entered args allowed.\n");
    } else if (localinfo.usr_args[0] == localinfo.usr_args[1] &&
		    localinfo.usr_args[0] == 0) {
	(void) fprintf(stderr, "\tNo user-entered args are allowed.\n");
    } else if (localinfo.usr_args[0] == localinfo.usr_args[1]) {
	(void) fprintf(stderr,
		    "\t%d user-entered arg%s required.\n",
		    localinfo.usr_args[0],
		    localinfo.usr_args[0] == 1? " is" : "s are");
    } else {
	(void) fprintf(stderr,
		    "\t%d - %d user-entered args are required.\n",
		    localinfo.usr_args[0], localinfo.usr_args[1]);
    }

    (void) fprintf(stderr, "\tCommand executes with nice increment = %d.\n",
		rcl_nice_incr());

    (void) fprintf(stderr, "\tCommand executes with umask set to 0%o.\n",
		rcl_umask());

    cdpath = localinfo.chdir_path ?
			localinfo.chdir_path : globalinfo.chdir_path;
    (void) fprintf(stderr,
			"\tCommand executes with working directory = %s\n",
			cdpath && *cdpath ? cdpath : "<unchanged>");

    (void) fprintf(stderr,
	"\tMax length of user-supplied env. var's (name+value): ");
    if (localinfo.maxenvlen < 0)
	fprintf(stderr, "unrestricted\n");
    else
	fprintf(stderr, "%d chars\n", localinfo.maxenvlen);
    (void) fprintf(stderr,
	"\tAdditional permitted user's environment variables:\n");
	if (localinfo.env == NULL || localinfo.env[0] == NULL) {
	    fprintf(stderr, "\t\t(none)\n");
	} else {
	    for (p=localinfo.env; *p; p++)
		(void) fprintf(stderr, "\t\t%s\n", *p);
	}

    (void) fprintf(stderr,
			"\tEnvironment variables defined with setenv=var=:\n");
    if (localinfo.setenv[0] == NULL) {
	(void) printf("\t\t(none)\n");
    } else {
	for (p=localinfo.setenv; *p; p++)
	    (void) printf("\t\t%s\n", *p);
    }

    (void) fprintf(stderr,
		    "\tComplete list of environment variables and values:\n");
    if (envp[0] == NULL) {
	(void) printf("\t\t(none)\n");
    } else {
	for (p=envp; *p; p++)
	    (void) printf("\t\t%s\n", *p);
    }
    (void) fprintf(stderr,
		    "\tFile descriptors not to be closed:\n\t\t0,1,2");
    if (localinfo.fdlist)
	(void) fprintf(stderr, ",%s", localinfo.fdlist);
    (void) fprintf(stderr, "\n\n\tID's:\treal effective\n");
    (void) fprintf(stderr, "\tuid\t%d\t%d\n", userinfo.orig_uid, geteuid());
    (void) fprintf(stderr, "\tgid\t%d\t%d\n", userinfo.orig_gid, getegid());
#ifdef HAVE_GETGROUPS
    {
	GETGROUPS_T groups[NGROUPS_MAX];
	int ng = Getgroups(NGROUPS_MAX, groups);
	(void) fprintf(stderr, "\tSupplementary groups list:\n\t\t");
	if (ng == 0) {
	    (void) fprintf(stderr, "(none)");
	} else {
	    for (j=0; j<ng; j++)
		(void) fprintf(stderr, "%d ", (int) groups[j]);
	}
	(void) fputc('\n', stderr);
    }
#endif

    (void) fprintf(stderr, "\n\tPassword required: %s\n",
			    localinfo.passinfo.required ? "yes" : "no");
    if (localinfo.passinfo.required) {
	(void) fprintf(stderr, "\tPassword timeout: %d min\n",
				localinfo.passinfo.timeout);
	(void) fprintf(stderr,
    "\tUpdate timestamp with each use of a password-requiring command? %s\n",
				localinfo.passinfo.renewtime ? "Yes" : "No");
    }

}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Switch to processing a user's super file, and set uid/gid/groups
 * to that user.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
user_supertab(command)
char *command;		/* user:cmd */
{
    char *s, *user, *cmd;
    struct passwd *pass;
 
    /* Split command into user:cmd */
    if ((cmd = strchr(command, ':')) == NULL)
	return 0;		/* No ":" -- no user superfile */

    user = command;
    *cmd++ = '\0';
    if (*user == '\0'  ||  *cmd == '\0')
	return Error(0, 0, "Commands may not begin or end with `:'\n");

    superfile[0] = '\0';
    pass = getpwnam(user);
    if (pass == (struct passwd *) NULL)
	return Error(0, 0, "No such user as `%s' (from command <%s:%s>)\n",
			user, user, cmd);
 
    if (pass->pw_dir[0] == '\0')
	return Error(0, 0, "No home directory for user `%s'?!\n", user);
    (void) strcpy(superfile, pass->pw_dir);
    s = superfile + strlen(superfile) - 1;
    if (*s != '/')
	*(++s) = '/';
    strcpy(s+1, PERUSER_SUPERFILE);
    error_srcfile = superfile;

    if (initgroups(user, pass->pw_gid) == -1)
	return Error(0, 0,
	    "Couldn't set groups to those of user %s (from command <%s:%s>).\n",
	    user, user, cmd);

    if (setgid(pass->pw_gid) == -1)
	return Error(1, 0,
	    "Couldn't set gid to that of user %s (from command <%s:%s>): ",
	    user, user, cmd);

    if (setuid(pass->pw_uid) == -1)
	return Error(1, 0,
	    "Couldn't set uid to user %s (from command <%s:%s>): ",
	    user, user, cmd);

    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Log a super call -- If "args" isn't a null ptr, it's printed inside
 *		parentheses, with whitespace separating the arguments.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

void
logmsg(cmd, args)
char *cmd;
char **args;
{
    char *ec, *logbuf, **ap;
    int e;
    int loglen = strlen(cmd) + 4;

    /* Determine buffer length needed to hold all arguments */
    if (args)
	for (ap = args; *ap; ap++)
	    loglen += strlen(*ap) + 1;

    if (!(logbuf = malloc(loglen)))
	(void) Error(0, 2, "failed to malloc space for logging command\n");

    if (args) {
	sprintf(logbuf, "%s (", cmd);
	for (ap = args; *ap; ) {
	    strcat(logbuf, *ap++);
	    strcat(logbuf, " ");
	}
	logbuf[loglen-3] = ')';
	logbuf[loglen-2] = '\n';
	logbuf[loglen-1] = '\0';
    } else {
	strcpy(logbuf, cmd);
    }

    /* Log the message using Error(), but
     *	- make sure msg doesn't go to stderr;
     *	- if not mail_success, don't let msg go to error_command, either.
     */
    e = error_stderr;
    ec = error_command;
    if (localinfo.mail_success == 0 ||
	    (localinfo.mail_success == -1 && globalinfo.mail_success==0))
	error_command = NULL;
    error_stderr = 0;
    Error(0, 0, logbuf);
    error_stderr = e;
    error_command = ec;
} 

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Get the arglist for the command, and null-terminate cmd if nec */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char **
newargs(path_plus, argv, n_builtin)
char *path_plus;	/* string = "path [options]".  Null-terminate and put
			 * options into front of arglist. */
char **argv;		/* rest of arguments for arglist (placed after
			 * the options from the path_plus string).
			 */
int *n_builtin;		/* returned w/ number of args in path_plus */
{
    int nuser, nalloc, iarg, nargs, nxtra;
    char **arglist, **ap;
    char *s;

    /* Count user-entered args. */
    for (ap = argv; *ap; )
	ap++;

    /* Check number of user-entered args is ok. */
    nargs = ap - argv - 1;
    if (localinfo.usr_args[0] >= 0) {
	if (nargs < localinfo.usr_args[0] || nargs > localinfo.usr_args[1]) {
	    if (localinfo.usr_args[0] == localinfo.usr_args[1] &&
						localinfo.usr_args[0] == 0)
		    (void) Error(0, 2,
			"you may not give any arguments to `%-.500s'\n",
			argv[0]);
	    else if (localinfo.usr_args[0] == localinfo.usr_args[1])
		(void) Error(0, 2,
		    "You must give %d argument%s to `%-.500s'\n",
		    localinfo.usr_args[0],
		    localinfo.usr_args[0] == 1 ? "" : "s", argv[0]);
	    else
		(void) Error(0, 2,
		    "You must give %d - %d arguments to `%-.500s'\n",
			localinfo.usr_args[0], localinfo.usr_args[1], argv[0]);
	}
    }

    /* Check that each user-entered argument matches its pattern, if given */
    for (iarg = 1; iarg <= nargs; iarg++) {
	s = StrEltGetPtr(&localinfo.argpats, iarg);
	if (s && match_pattern(0, 0, argv[iarg], s) != 1)
	    (void) Error(0, 2,
		"Your argument #%d <%s> must match pattern <%s>\n",
		iarg, argv[iarg], s);
    }

    /* Start off with space for user-entered args + 100 args in super.tab.
     * We'll re-alloc if necessary.
     */
    nuser = (ap - argv) + 3;
    nalloc = nuser + 100;
    arglist = (char **) malloc(sizeof(char *) * nalloc);
    if (!arglist)
	(void) Error(1, 2, 
	    "failed to malloc space for %d ptrs\n", nalloc);

    /* Leave room for two extra args at front, in case we are handling
     * the "#! interpreter [opt]" file for OS's that don't support it.
     */
    arglist += 2;

    /* First copy the command to the new arglist */
    arglist[0] = *argv++;

    /* Then copy the extra args from super.tab to the arglist,
     * re-allocing the arglist as the number of args grows.
     */
    s=strqtokS(path_plus, SEP, QM, "", 1); /* Don't put FullPath into arglist */
    for(nxtra=0, ap = &arglist[1], s=strqtokS(NULL, SEP, NULL, NULL, 1);  s;
				s = strqtokS(NULL, SEP, NULL, NULL, 1)) {
	nxtra++;
	if (nuser + nxtra >= nalloc) {
	    char **newarglist;
	    nalloc *= 2;
	    newarglist = (char **) realloc((void *) arglist, nalloc);
	    if (!newarglist)
		(void) Error(1, 2, 
		    "failed to realloc space for %d ptrs\n", nalloc);
	    ap = newarglist + (ap - arglist);
	    arglist = newarglist;
	}
	*ap++ = s;
    }

    /* Now add the user-supplied args at the end */
    *n_builtin = ap - arglist - 1;
    while (*argv)
	*ap++ = *argv++;
    *ap = NULL;

    return arglist;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Get a safe environment for execution of the command */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char **
buttonup(cmd)
char *cmd;		/* name of command being started */
{
    /* Depending on the ability to close-on-exec, either:
     *	close all descriptors save 0,1,2 and the super.tab-specified fd list;
     *	or mark them close-on-exec.
     * Resets all signal-handling to SIG_DFL.
     * Discards all env. variables save for TERM, LINES, COLUMNS, and
     * any variables listed in the super.tab file.
     * Don't allow TERM to have any but [-/:+._a-zA-Z0-9].
     * Don't allow LINES, COLUMNS to have anything but digits.
     * To these are added reasonable values for IFS, PATH, USER, HOME.
     * USER and HOME refer to the uid under which the command is executed;
     * LOGNAME is set to the same as USER, and SUPERCMD is set to cmd.
     * ORIG_USER, ORIG_LOGNAME, and ORIG_HOME refer to the user who invoked
     * super.
     * Returned:
     *  NULL on error;
     *	otherwise, a pointer to the modified environment list.
     */
    int i, fd, maxfd;
    char **p, *s;

    int fd_log;
    static char *env[200];
    static char User[100];		/* USER */
    static char Logname[100];		/* LOGNAME (alias for USER) */
    static char Home[MAXPATHLEN+5];	/* HOME */
    static char OrigUser[100];		/* ORIG_USER */
    static char OrigLogname[100];	/* ORIG_LOGNAME */
    static char OrigHome[MAXPATHLEN+9];	/* ORIG_HOME */
    static char SafePath[1206];		/* SAFE_PATH */
    static char Cmd[1205];		/* SUPERCMD */

#ifndef signal
    /* If signal() isn't a macro, then  declare it explicitly -- it's too
     * much of a mess to figure out whether a given operating system
     * has declared it or not.  (Any __STDC__ system should be declaring
     * it, but there are several OS's that seem to mess this up.)
     */
    SIGNAL_T (*signal())();
#endif

    /* don't close logfile yet */
    fd_log = globalinfo.log.fp ? fileno(globalinfo.log.fp) : -1;
    maxfd = MAXFD;

#ifdef HAVE_FCNTL_H
#ifndef FD_CLOEXEC
#define FD_CLOEXEC 1
#endif
    for (fd=3; fd <= maxfd; fd++)
	if (localinfo.fd[fd] == 0 && fd != fd_log)
	    (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
#else
#ifdef HAVE_IOCTL_FIOCLEX
    for (fd=3; fd <= maxfd; fd++)
	if (localinfo.fd[fd] == 0 && fd != fd_log)
	    (void) ioctl(fd, FIOCLEX, NULL);
#else
    for (fd=3; fd <= maxfd; fd++)
	if (localinfo.fd[fd] == 0 && fd != fd_log)
	    (void) close(fd);
#endif
#endif
    
    for (i=0; i<NSIG; i++)
       (void) signal(i, SIG_DFL);

    s = *localinfo.user ? localinfo.user :
		*localinfo.u_g ? localinfo.u_g : userinfo.caller.pw_name;
    (void) sprintf(OrigUser, "ORIG_USER=%s", userinfo.caller.pw_name);
    (void) sprintf(User, "USER=%s", s);
    (void) sprintf(OrigLogname, "ORIG_LOGNAME=%s", userinfo.caller.pw_name);
    (void) sprintf(Logname, "LOGNAME=%s", s);

    if (strlen(SAFE_PATH) > sizeof(SafePath)-6) {
	Error(0, 0, "%t\n\tRidiculously long SAFE_PATH.\n");
	return NULL;
    }
    /* I've screwed up SAFE_PATH so often (and so have others) that I'm gonna
     * put this check into the code...
     */
    if (strncmp(SAFE_PATH, "PATH=", 5) == 0)
	(void) strcpy(SafePath, SAFE_PATH);
    else
	(void) sprintf(SafePath, "PATH=%s", SAFE_PATH);

    if (strlen(cmd) > sizeof(Cmd)-5) {
	Error(0, 0, "%t\n\tRidiculously long original string.\n");
	return NULL;
    }
    (void) sprintf(Cmd, "SUPERCMD=%s", cmd);

    (void) strcpy(Home, "HOME=");
    (void) getlogdir(s, Home+5);
    (void) sprintf(OrigHome, "ORIG_HOME=%s", userinfo.caller.pw_dir);
    i = 0;
    env[i] = Getenv("TERM");
    if (env[i] && checkenv("TERM", env[i]+5, "^[-/:+._a-zA-Z0-9]*$") != -1) i++;
    env[i] = Getenv("LINES");
    if (env[i] && checkenv("LINES", env[i]+6, "^[0-9]*$") != -1) i++;
    env[i] = Getenv("COLUMNS");
    if (env[i] && checkenv("COLUMNS", env[i]+8, "^[0-9]*$") != -1) i++;
    env[i++] = SAFE_IFS;
    env[i++] = SafePath;
    env[i++] = User;
    env[i++] = Logname;
    env[i++] = Home;
    env[i++] = Cmd;
    env[i++] = OrigUser;
    env[i++] = OrigLogname;
    env[i++] = OrigHome;

    /* Now add the extra environment variables requested in the
     * super.tab file.
     */
    for (p=localinfo.env; p && *p && i < NELEM(env)-1; p++) {
	env[i] = Getenv(*p);
	if (env[i]) {
	    if (strlen(env[i])+1 > localinfo.maxenvlen) {
		Error(0, 0, "%t\n\tDefinition for envvar %s exceeds \
maxenvlen=%d.\n", *p, localinfo.maxenvlen);
		return NULL;
	    }
	    i++;
	}
    }

    for (p = localinfo.setenv; *p && i < NELEM(env)-1 ; )
	env[i++] = *p++;

    if (i >= NELEM(env)-1) {
	Error(0, 0, "%t\n\tAsked to save too many \
environment variables (max allowed %d).\n", NELEM(env)-1);
	return NULL;
    }

    env[i] = (char *) NULL;

    return &env[0];
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Check that all arguments are within the permissible limits. */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
check_arglistlen(argv)
char **argv;
{
    /* Check that all arguments meet the length restrictions.
     * A length restriction < 0 means unlimited size.
     * Returns 0 if all ok; else prints error message and returns 1.
     */
    long totlen;
    long l;
    char **p;

    if (localinfo.maxlen1arg < 0 && localinfo.maxlenargs < 0)
	return 0;

    for (totlen = 0, p = argv; *p; p++) {
	l = (long) strlen(*p) + 1;
	totlen += l;
	if (localinfo.maxlen1arg >= 0 && l > localinfo.maxlen1arg)
	    return Error(0, 0, "Maximum length of each argument = %d chars\n",
							localinfo.maxlen1arg);
    }
    if (localinfo.maxlenargs >= 0 && totlen > localinfo.maxlenargs)
	return Error(0, 0, "Maximum total length of arguments = %d chars\n",
							localinfo.maxlenargs);
    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Take various system information (from sysinfo(), uname(), etc)
 * and turn it into variables.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
add_builtin_variables()
{
    char buf[1000];

    add_variable("HOSTNAME", userinfo.hostname);

    add_sysinfo_variables();	/* Creates empty def'ns if no sysinfo() */

    add_uname_variables();	/* Creates empty def'ns if no uname() */

#ifdef HAVE_GETDOMAINNAME
    if (getdomainname(buf, sizeof(buf)) != -1) {
	add_variable("NIS_DOMAIN", buf);
    }
#else
	add_variable("NIS_DOMAIN", "");
#endif

}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Initialize the globalinfo struct.  Only call this once; thereafter, use
 * option_global_clear_settings().  Note that very little work is done in
 * this routine, because almost all fields are properly initialized in the
 * structure declaration/initialization statement.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
init_globalinfo()
{
    init_umask(1);
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Initialize the localinfo struct.  Only call this once; thereafter, use
 * option_local_clear_settings().
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
init_localinfo()
{
    int i;
    localinfo.info = localinfo.chdir_path =
	    localinfo.die = localinfo.print = NULL;
    localinfo.env = NULL;
    for (i=0; i<=MAXSETENV; i++)
	localinfo.setenv[i]=NULL;
    localinfo.fdlist = NULL;
    localinfo.mask = -1;
    localinfo.maxenvlen = globalinfo.maxenvlen;
    localinfo.env = NULL;
    localinfo.maxlen1arg = globalinfo.maxlen1arg;
    localinfo.maxlenargs = globalinfo.maxlenargs;
    localinfo.file_uid = UID_NOTSET;
    localinfo.file_gid = GID_NOTSET;
    localinfo.nice_incr = globalinfo.nice_incr;
    /* Don't init to global ngroups, because we need to be able to tell
     * later on whether local groups=xxx or global groups=xxx was used.
     */
    localinfo.ngroups = GROUPS_NOTSET;
    localinfo.groups_added = 0;
    StrInit(&localinfo.argpats);
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Look up some of the most basic user information. */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
init_userinfo()
{
    struct passwd *usrpw;
    char *s;

    userinfo.ourtime.start = time(NULL);
#ifdef HAVE_LOCALTIME
    {
	struct tm *tm_p = localtime(&userinfo.ourtime.start);
	userinfo.ourtime.min = tm_p->tm_hour*60 + tm_p->tm_min;
	userinfo.ourtime.day = tm_p->tm_wday;
    }
#else
    userinfo.ourtime.min = (userinfo.ourtime.start/60) % (24*60);
    userinfo.ourtime.day = daynum(userinfo.ourtime.start);
#endif

    /*
     * We want the hostname (fully-qualified if possible), as well as a
     * lower-cased version (to try and deal with mixed case hostnames).
     */
    if (get_canonical_hostname(userinfo.hostname, sizeof(userinfo.hostname))
	    == -1)
	return 1;
    strcpy(userinfo.lc_hostname, userinfo.hostname);
    strtolower(userinfo.lc_hostname);

    userinfo.orig_uid = getuid();
    userinfo.orig_gid = getgid();

    usrpw = getpwuid(userinfo.orig_uid);
    if (!usrpw)
	return Error(0, 0, "Couldn't get your password entry.");
    memcpy(&userinfo.caller, (void *) usrpw, sizeof(struct passwd));

    /* Since the string fields that we need are overwritten by later
     * calls to getpwxxx(), make private copies:
     */
    if (!(s = malloc(strlen(userinfo.caller.pw_name)+1)))
	(void) Error(0, 2, "failed to malloc space for passwd struct field.\n");
    strcpy(s, userinfo.caller.pw_name);
    userinfo.caller.pw_name = s;
    if (!(s = malloc(strlen(userinfo.caller.pw_passwd)+1)))
	(void) Error(0, 2, "failed to malloc space for passwd struct field.\n");
    strcpy(s, userinfo.caller.pw_passwd);
    userinfo.caller.pw_passwd = s;
    if (!(s = malloc(strlen(userinfo.caller.pw_dir)+1)))
	(void) Error(0, 2, "failed to malloc space passwd struct field.\n");
    strcpy(s, userinfo.caller.pw_dir);
    userinfo.caller.pw_dir = s;
    
    error_user = userinfo.caller.pw_name;
    userinfo.orig_mask = umask(022); /* Get orig umask, and set to 022 */
    (void) umask(userinfo.orig_mask);	/* ...so restore curr val */

    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Store the desired umask; set the actual umask; recall the desired umask */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
init_umask(is_global)
int is_global;
{
    if (is_global) {
	globalinfo.mask = userinfo.orig_mask;
    } else {
	localinfo.mask = -1;
    }
}

void
store_umask(mask, is_global)
int mask;
int is_global;
{
    if (is_global)
	globalinfo.mask = mask;
    else
	localinfo.mask = mask;
}

void
set_umask()
{
    umask( (localinfo.mask >= 0) ? localinfo.mask : globalinfo.mask);
}

int
rcl_umask()
{
    return (localinfo.mask >= 0) ? localinfo.mask : globalinfo.mask;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Change directory, if required */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
set_chdir()
{
    char *path = localinfo.chdir_path ?
			localinfo.chdir_path : globalinfo.chdir_path;

    if (!path || !*path)
	return 0;

    if (chdir(path) == -1)
	return Error(1, 0, "Failed to change directory to ``%s'': ", path);
    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Store/set/recall niceness */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

void
store_nice_incr(nice_incr, is_global)
int nice_incr;
int is_global;
{
    if (is_global)
	globalinfo.nice_incr = nice_incr;
    else
	localinfo.nice_incr = nice_incr;
}

int
set_nice_incr()
{
    if (localinfo.nice_incr && nice(localinfo.nice_incr) == -1)
	return Error(1, 0,
		"Failed to apply a ``nice'' increment = %d: ",
		    localinfo.nice_incr);
    return 0;
}

int
rcl_nice_incr()
{
    return localinfo.nice_incr;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Frees all elements in a SimpleList, except the one it's given.
 * The "next" field of that element is set NULL.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
free_SimpleList(sl)
SimpleList *sl;
{
    SimpleList *slp;

    if (!sl || !sl->next)
	return;
    slp = sl->next;
    sl->next = NULL;
    for (sl=sl->next ; sl; sl = slp) {
	slp = sl->next;
	free(sl->pat);
	free(sl);
    }
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Frees all elements in a Simple2List, except the one it's given.
 * The "next" field of that element is set NULL.
 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
free_Simple2List(sl)
Simple2List *sl;
{
    Simple2List *slp;

    if (!sl || !sl->next)
	return;
    slp = sl->next;
    sl->next = NULL;
    for (sl=sl->next ; sl; sl = slp) {
	slp = sl->next;
	free(sl->pat);
	free(sl);
    }
}