Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

  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
/*	$NetBSD: crontab.c,v 1.15 2018/03/06 21:21:27 htodd Exp $	*/

/* Copyright 1988,1990,1993,1994 by Paul Vixie
 * All rights reserved
 */

/*
 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
 * Copyright (c) 1997,2000 by Internet Software Consortium, Inc.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include <sys/cdefs.h>
#if !defined(lint) && !defined(LINT)
#if 0
static char rcsid[] = "Id: crontab.c,v 1.12 2004/01/23 18:56:42 vixie Exp";
#else
__RCSID("$NetBSD: crontab.c,v 1.15 2018/03/06 21:21:27 htodd Exp $");
#endif
#endif

/* crontab - install and manage per-user crontab files
 * vix 02may87 [RCS has the rest of the log]
 * vix 26jan87 [original]
 */

#define	MAIN_PROGRAM

#include "cron.h"

#define NHEADER_LINES 3

enum opt_t	{ opt_unknown, opt_list, opt_delete, opt_edit, opt_replace };

#if DEBUGGING
static const char	*Options[] = {
    "???", "list", "delete", "edit", "replace" };
static const char	*getoptargs = "u:lerx:";
#else
static const char	*getoptargs = "u:ler";
#endif

static	PID_T		Pid;
static	char		User[MAX_UNAME], RealUser[MAX_UNAME];
static	char		Filename[MAX_FNAME], TempFilename[MAX_FNAME];
static	FILE		*NewCrontab;
static	int		CheckErrorCount;
static	enum opt_t	Option;
static	struct passwd	*pw;
static	void		list_cmd(void),
			delete_cmd(void),
			edit_cmd(void),
			poke_daemon(void),
			check_error(const char *),
			parse_args(int c, char *v[]);
static	int		replace_cmd(void);
static  int		allowed(const char *, const char *, const char *);
static  int		in_file(const char *, FILE *, int);
static  int 		relinquish_priv(void);
static  int 		regain_priv(void);

static __dead void
usage(const char *msg) {
	(void)fprintf(stderr, "%s: usage error: %s\n", getprogname(), msg);
	(void)fprintf(stderr, "usage:\t%s [-u user] file\n", getprogname());
	(void)fprintf(stderr, "\t%s [-u user] [ -e | -l | -r ]\n", getprogname());
	(void)fprintf(stderr, "\t\t(default operation is replace, per 1003.2)\n");
	(void)fprintf(stderr, "\t-e\t(edit user's crontab)\n");
	(void)fprintf(stderr, "\t-l\t(list user's crontab)\n");
	(void)fprintf(stderr, "\t-r\t(delete user's crontab)\n");
	exit(ERROR_EXIT);
}

static uid_t euid, ruid;
static gid_t egid, rgid;

int
main(int argc, char *argv[]) {
	int exitstatus;

	setprogname(argv[0]);
	Pid = getpid();
	(void)setlocale(LC_ALL, "");

	euid = geteuid();
	egid = getegid();
	ruid = getuid();
	rgid = getgid();

	if (euid == ruid && ruid != 0)
		errx(ERROR_EXIT, "Not installed setuid root");

	(void)setvbuf(stderr, NULL, _IOLBF, 0);
	parse_args(argc, argv);		/* sets many globals, opens a file */
	set_cron_cwd();
	if (!allowed(RealUser, CRON_ALLOW, CRON_DENY)) {
		(void)fprintf(stderr,
			"You `%s' are not allowed to use this program `%s'\n",
			User, getprogname());
		(void)fprintf(stderr, "See crontab(1) for more information\n");
		log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
		exit(ERROR_EXIT);
	}
	exitstatus = OK_EXIT;
	switch (Option) {
	case opt_unknown:
		usage("unrecognized option");
		exitstatus = ERROR_EXIT;
		break;
	case opt_list:
		list_cmd();
		break;
	case opt_delete:
		delete_cmd();
		break;
	case opt_edit:
		edit_cmd();
		break;
	case opt_replace:
		if (replace_cmd() < 0)
			exitstatus = ERROR_EXIT;
		break;
	default:
		abort();
	}
	exit(exitstatus);
	/*NOTREACHED*/
}

static void
get_time(const struct stat *st, struct timespec *ts)
{
	ts[0].tv_sec = st->st_atime;
	ts[0].tv_nsec = st->st_atimensec;
	ts[1].tv_sec = st->st_mtime;
	ts[1].tv_nsec = st->st_mtimensec;
}

static int
change_time(const char *name, const struct timespec *ts)
{
#if defined(HAVE_UTIMENSAT)
	return utimensat(AT_FDCWD, name, ts, 0);
#elif defined(HAVE_UTIMES)
	struct timeval tv[2];
	TIMESPEC_TO_TIMEVAL(&tv[0], &ts[0]);
	TIMESPEC_TO_TIMEVAL(&tv[1], &ts[1]);
	return utimes(name, tv);
#else
	struct utimbuf ut;
	ut.actime = ts[0].tv_sec;
	ut.modtime = ts[1].tv_sec;
	return utime(name, &ut);
#endif
}

static int
compare_time(const struct stat *st, const struct timespec *ts2)
{
	struct timespec ts1[2];
	get_time(st, ts1);

	return ts1[1].tv_sec == ts2[1].tv_sec
#if defined(HAVE_UTIMENSAT)
	    && ts1[1].tv_nsec == ts2[1].tv_nsec
#elif defined(HAVE_UTIMES)
	    && ts1[1].tv_nsec / 1000 == ts2[1].tv_nsec / 1000
#endif
	;
}

static void
parse_args(int argc, char *argv[]) {
	int argch;

	if (!(pw = getpwuid(getuid()))) {
		errx(ERROR_EXIT,
		    "your UID isn't in the passwd file. bailingo out");
	}
	if (strlen(pw->pw_name) >= sizeof User) {
		errx(ERROR_EXIT, "username too long");
	}
	(void)strlcpy(User, pw->pw_name, sizeof(User));
	(void)strlcpy(RealUser, User, sizeof(RealUser));
	Filename[0] = '\0';
	Option = opt_unknown;
	while (-1 != (argch = getopt(argc, argv, getoptargs))) {
		switch (argch) {
#if DEBUGGING
		case 'x':
			if (!set_debug_flags(optarg))
				usage("bad debug option");
			break;
#endif
		case 'u':
			if (MY_UID(pw) != ROOT_UID) {
				errx(ERROR_EXIT,
				    "must be privileged to use -u");
			}
			if (!(pw = getpwnam(optarg))) {
				errx(ERROR_EXIT, "user `%s' unknown", optarg);
			}
			if (strlen(optarg) >= sizeof User)
				usage("username too long");
			(void) strlcpy(User, optarg, sizeof(User));
			break;
		case 'l':
			if (Option != opt_unknown)
				usage("only one operation permitted");
			Option = opt_list;
			break;
		case 'r':
			if (Option != opt_unknown)
				usage("only one operation permitted");
			Option = opt_delete;
			break;
		case 'e':
			if (Option != opt_unknown)
				usage("only one operation permitted");
			Option = opt_edit;
			break;
		default:
			usage("unrecognized option");
		}
	}

	endpwent();

	if (Option != opt_unknown) {
		if (argv[optind] != NULL)
			usage("no arguments permitted after this option");
	} else {
		if (argv[optind] != NULL) {
			Option = opt_replace;
			if (strlen(argv[optind]) >= sizeof Filename)
				usage("filename too long");
			(void)strlcpy(Filename, argv[optind], sizeof(Filename));
		} else
			usage("file name must be specified for replace");
	}

	if (Option == opt_replace) {
		/* we have to open the file here because we're going to
		 * chdir(2) into /var/cron before we get around to
		 * reading the file.
		 */
		if (!strcmp(Filename, "-"))
			NewCrontab = stdin;
		else {
			/* relinquish the setuid status of the binary during
			 * the open, lest nonroot users read files they should
			 * not be able to read.  we can't use access() here
			 * since there's a race condition.  thanks go out to
			 * Arnt Gulbrandsen <agulbra@pvv.unit.no> for spotting
			 * the race.
			 */

			if (relinquish_priv() < OK) {
				err(ERROR_EXIT, "swapping uids");
			}
			if (!(NewCrontab = fopen(Filename, "r"))) {
				err(ERROR_EXIT, "cannot open `%s'", Filename);
			}
			if (regain_priv() < OK) {
				err(ERROR_EXIT, "swapping uids back");
			}
		}
	}

	Debug(DMISC, ("user=%s, file=%s, option=%s\n",
		      User, Filename, Options[(int)Option]));
}

static void
skip_header(int *pch, FILE *f)
{
	int ch;
	int x;

	/* ignore the top few comments since we probably put them there.
	 */
	for (x = 0;  x < NHEADER_LINES;  x++) {
		ch = get_char(f);
		if (EOF == ch)
			break;
		if ('#' != ch)
			break;
		while (EOF != (ch = get_char(f)))
			if (ch == '\n')
				break;
		if (EOF == ch)
			break;
	}
	if (ch == '\n')
		ch = get_char(f);

	*pch = ch;
}

static void
list_cmd(void) {
	char n[MAX_FNAME];
	FILE *f;
	int ch;

	log_it(RealUser, Pid, "LIST", User);
	if (!glue_strings(n, sizeof n, SPOOL_DIR, User, '/')) {
		errx(ERROR_EXIT, "path too long");
	}
	if (!(f = fopen(n, "r"))) {
		if (errno == ENOENT)
			errx(ERROR_EXIT, "no crontab for `%s'", User);
		else
			err(ERROR_EXIT, "Cannot open `%s'", n);
	}

	/* file is open. copy to stdout, close.
	 */
	Set_LineNum(1);
	skip_header(&ch, f);
	for (; EOF != ch;  ch = get_char(f))
		(void)putchar(ch);
	(void)fclose(f);
}

static void
delete_cmd(void) {
	char n[MAX_FNAME];

	log_it(RealUser, Pid, "DELETE", User);
	if (!glue_strings(n, sizeof n, SPOOL_DIR, User, '/')) {
		errx(ERROR_EXIT, "path too long");
	}
	if (unlink(n) != 0) {
		if (errno == ENOENT)
			errx(ERROR_EXIT, "no crontab for `%s'", User);
		else
			err(ERROR_EXIT, "cannot unlink `%s'", n);
	}
	poke_daemon();
}

static void
check_error(const char *msg) {
	CheckErrorCount++;
	(void)fprintf(stderr, "\"%s\":%d: %s\n", Filename, LineNumber-1, msg);
}

static void
edit_cmd(void) {
	char n[MAX_FNAME], q[MAX_TEMPSTR];
	const char *editor;
	FILE *f;
	int ch, t, x;
	sig_t oint, oabrt, oquit, ohup;
	struct stat statbuf;
	WAIT_T waiter;
	PID_T pid, xpid;
	struct timespec ts[2];

	log_it(RealUser, Pid, "BEGIN EDIT", User);
	if (!glue_strings(n, sizeof n, SPOOL_DIR, User, '/')) {
		errx(ERROR_EXIT, "path too long");
	}
	if (!(f = fopen(n, "r"))) {
		if (errno != ENOENT) {
			err(ERROR_EXIT, "cannot open `%s'", n);
		}
		warnx("no crontab for `%s' - using an empty one", User);
		if (!(f = fopen(_PATH_DEVNULL, "r"))) {
			err(ERROR_EXIT, "cannot open `%s'", _PATH_DEVNULL);
		}
	}

	if (fstat(fileno(f), &statbuf) < 0) {
		warn("cannot stat crontab file");
		goto fatal;
	}
	get_time(&statbuf, ts);

	/* Turn off signals. */
	ohup = signal(SIGHUP, SIG_IGN);
	oint = signal(SIGINT, SIG_IGN);
	oquit = signal(SIGQUIT, SIG_IGN);
	oabrt = signal(SIGABRT, SIG_IGN);

	if (!glue_strings(Filename, sizeof Filename, _PATH_TMP,
	    "crontab.XXXXXXXXXX", '/')) {
		warnx("path too long");
		goto fatal;
	}
	if (-1 == (t = mkstemp(Filename))) {
		warn("cannot create `%s'", Filename);
		goto fatal;
	}
#ifdef HAS_FCHOWN
	x = fchown(t, MY_UID(pw), MY_GID(pw));
#else
	x = chown(Filename, MY_UID(pw), MY_GID(pw));
#endif
	if (x < 0) {
		warn("cannot chown `%s'", Filename);
		goto fatal;
	}
	if (!(NewCrontab = fdopen(t, "r+"))) {
		warn("cannot open fd");
		goto fatal;
	}

	Set_LineNum(1);

	skip_header(&ch, f);

	/* copy the rest of the crontab (if any) to the temp file.
	 */
	for (; EOF != ch; ch = get_char(f))
		(void)putc(ch, NewCrontab);
	(void)fclose(f);
	if (fflush(NewCrontab) < OK) {
		err(ERROR_EXIT, "cannot flush output for `%s'", Filename);
	}
#ifdef HAVE_FUTIMENS
	if (futimens(t, ts) == -1)
#else
	if (change_time(Filename, ts) == -1)
#endif
		err(ERROR_EXIT, "cannot set time info for `%s'", Filename);
 again:
	rewind(NewCrontab);
	if (ferror(NewCrontab)) {
		warn("error while writing new crontab to `%s'", Filename);
 fatal:
		(void)unlink(Filename);
		exit(ERROR_EXIT);
	}

	if (((editor = getenv("VISUAL")) == NULL || *editor == '\0') &&
	    ((editor = getenv("EDITOR")) == NULL || *editor == '\0')) {
		editor = EDITOR;
	}

	/* we still have the file open.  editors will generally rewrite the
	 * original file rather than renaming/unlinking it and starting a
	 * new one; even backup files are supposed to be made by copying
	 * rather than by renaming.  if some editor does not support this,
	 * then don't use it.  the security problems are more severe if we
	 * close and reopen the file around the edit.
	 */

	switch (pid = fork()) {
	case -1:
		warn("cannot fork");
		goto fatal;
	case 0:
		/* child */
		if (setgid(MY_GID(pw)) < 0) {
			err(ERROR_EXIT, "cannot setgid(getgid())");
		}
		if (setuid(MY_UID(pw)) < 0) {
			err(ERROR_EXIT, "cannot setuid(getuid())");
		}
		if (close_all(3)) {
			err(ERROR_EXIT, "cannot close files");
		}
		if (chdir(_PATH_TMP) < 0) {
			err(ERROR_EXIT, "cannot chdir to `%s'", _PATH_TMP);
		}
		if (!glue_strings(q, sizeof q, editor, Filename, ' ')) {
			errx(ERROR_EXIT, "editor command line too long");
		}
		(void)execlp(_PATH_BSHELL, _PATH_BSHELL, "-c", q, (char *)0);
		err(ERROR_EXIT, "cannot start `%s'", editor);
		/*NOTREACHED*/
	default:
		/* parent */
		break;
	}

	/* parent */
	for (;;) {
		xpid = waitpid(pid, &waiter, WUNTRACED);
		if (xpid == -1) {
			if (errno != EINTR)
				warn("waitpid() failed waiting for PID %ld "
				    "from `%s'", (long)pid, editor);
		} else if (xpid != pid) {
			warnx("wrong PID (%ld != %ld) from `%s'",
			    (long)xpid, (long)pid, editor);
			goto fatal;
		} else if (WIFSTOPPED(waiter)) {
			(void)kill(getpid(), WSTOPSIG(waiter));
		} else if (WIFEXITED(waiter) && WEXITSTATUS(waiter)) {
			warnx("`%s' exited with status %d\n",
			    editor, WEXITSTATUS(waiter));
			goto fatal;
		} else if (WIFSIGNALED(waiter)) {
			warnx("`%s' killed; signal %d (%score dumped)",
			    editor, WTERMSIG(waiter),
			    WCOREDUMP(waiter) ? "" : "no ");
			goto fatal;
		} else
			break;
	}
	(void)signal(SIGHUP, ohup);
	(void)signal(SIGINT, oint);
	(void)signal(SIGQUIT, oquit);
	(void)signal(SIGABRT, oabrt);

	if (fstat(t, &statbuf) < 0) {
		warn("cannot stat `%s'", Filename);
		goto fatal;
	}
	if (compare_time(&statbuf, ts)) {
		warnx("no changes made to crontab");
		goto remove;
	}
	warnx("installing new crontab");
	switch (replace_cmd()) {
	case 0:
		break;
	case -1:
		for (;;) {
			(void)fpurge(stdin);
			(void)printf("Do you want to retry the same edit? ");
			(void)fflush(stdout);
			q[0] = '\0';
			(void) fgets(q, (int)sizeof(q), stdin);
			switch (q[0]) {
			case 'y':
			case 'Y':
				goto again;
			case 'n':
			case 'N':
				goto abandon;
			default:
				(void)printf("Enter Y or N\n");
			}
		}
		/*NOTREACHED*/
	case -2:
	abandon:
		warnx("edits left in `%s'", Filename);
		goto done;
	default:
		warnx("panic: bad switch() in replace_cmd()");
		goto fatal;
	}
 remove:
	(void)unlink(Filename);
 done:
	log_it(RealUser, Pid, "END EDIT", User);
}

static size_t
getmaxtabsize(void)
{
	char n2[MAX_FNAME];
	FILE *fmaxtabsize;
	size_t maxtabsize;

	/* Make sure that the crontab is not an unreasonable size.
	 *
	 * XXX This is subject to a race condition--the user could
	 * add stuff to the file after we've checked the size but
	 * before we slurp it in and write it out. We can't just move
	 * the test to test the temp file we later create, because by
	 * that time we've already filled up the crontab disk. Probably
	 * the right thing to do is to do a bytecount in the copy loop
	 * rather than stating the file we're about to read.
	 */
	(void)snprintf(n2, sizeof(n2), "%s/%s", CRONDIR, MAXTABSIZE_FILE);
	if ((fmaxtabsize = fopen(n2, "r")) != NULL)  {
		if (fgets(n2, (int)sizeof(n2), fmaxtabsize) == NULL)  {
			maxtabsize = 0;
		} else {
			maxtabsize = (size_t)atoi(n2);
		}
		(void)fclose(fmaxtabsize);
	} else {
		maxtabsize = MAXTABSIZE_DEFAULT;
	}
	return maxtabsize;
}

static int
checkmaxtabsize(FILE *fp, size_t maxtabsize)
{
	struct	stat statbuf;

	if (fstat(fileno(fp), &statbuf))  {
		warn("error stat'ing crontab input");
		return 0;
	}
	if ((uintmax_t)statbuf.st_size > (uintmax_t)maxtabsize)  {
		warnx("%ju bytes is larger than the maximum size of %ju bytes",
		    (uintmax_t)statbuf.st_size, (uintmax_t)maxtabsize);
		return 0;
	}
	return 1;
}

static void
cleanTempFile(void)
{

	if (TempFilename[0]) {
		(void) unlink(TempFilename);
		TempFilename[0] = '\0';
	}
}

static __dead void
bail(int signo)
{

	cleanTempFile();
	errx(ERROR_EXIT, "Exiting on signal %d", signo);
}

/* returns	0	on success
 *		-1	on syntax error
 *		-2	on install error
 */
static int
replace_cmd(void) {
	char n[MAX_FNAME], envstr[MAX_ENVSTR];
	int lastch;
	FILE *tmp = NULL;
	int ch, eof, fd;
	int error = 0;
	entry *e;
	sig_t oint, oabrt, oquit, ohup;
	uid_t file_owner;
	time_t now = time(NULL);
	char **envp = env_init();
	size_t i, maxtabsize;

	if (envp == NULL) {
		warn("Cannot allocate memory.");
		return (-2);
	}

	if (!glue_strings(TempFilename, sizeof TempFilename, SPOOL_DIR,
	    "tmp.XXXXXXXXXX", '/')) {
		TempFilename[0] = '\0';
		warnx("path too long");
		return (-2);
	}

	/* Interruptible while doing I/O */
	ohup = signal(SIGHUP, bail);
	oint = signal(SIGINT, bail);
	oquit = signal(SIGQUIT, bail);
	oabrt = signal(SIGABRT, bail);

	if ((fd = mkstemp(TempFilename)) == -1 || !(tmp = fdopen(fd, "w+"))) {
		warn("cannot create `%s'", TempFilename);
		if (fd != -1)
			(void)close(fd);
		error = -2;
		goto done;
	}

	maxtabsize = getmaxtabsize();

	/* This does not work for stdin, so we'll also check later */
	if (!checkmaxtabsize(NewCrontab, maxtabsize)) {
		error = -2;
		goto done;
	}

	/* write a signature at the top of the file.
	 *
	 * VERY IMPORTANT: make sure NHEADER_LINES agrees with this code.
	 */
	(void)fprintf(tmp,
	    "# DO NOT EDIT THIS FILE - edit the master and reinstall.\n");
	(void)fprintf(tmp,
	    "# (%s installed on %-24.24s)\n", Filename, ctime(&now));
	(void)fprintf(tmp,
	    "# (Cron version %s -- %s)\n", CRON_VERSION,
	    "$NetBSD: crontab.c,v 1.15 2018/03/06 21:21:27 htodd Exp $");

	/* copy the crontab to the tmp
	 */
	(void)rewind(NewCrontab);
	Set_LineNum(1);
	lastch = EOF;
	for (i = 0; i < maxtabsize && EOF != (ch = get_char(NewCrontab)); i++)
		(void)putc(lastch = (char)ch, tmp);

	/* Non-Interruptible while installing */
	(void)signal(SIGHUP, SIG_IGN);
	(void)signal(SIGINT, SIG_IGN);
	(void)signal(SIGQUIT, SIG_IGN);
	(void)signal(SIGABRT, SIG_IGN);

	if (i == maxtabsize) {
		warnx("is larger than the maximum size of %ju bytes",
		    (uintmax_t)maxtabsize);
		error = -2;
		goto done;
	}

	if (lastch != EOF && lastch != '\n') {
		warnx("missing trailing newline in `%s'", Filename);
		error = -1;
		goto done;
	}

	if (ferror(NewCrontab)) {
		warn("error while reading `%s'", Filename);
		error = -2;
		goto done;
	}

	(void)ftruncate(fileno(tmp), ftell(tmp));
	/* XXX this should be a NOOP - is */
	(void)fflush(tmp);

	if (ferror(tmp)) {
		warn("error while writing new crontab to `%s'", TempFilename);
		error = -2;
		goto done;
	}

	/* check the syntax of the file being installed.
	 */

	/* BUG: was reporting errors after the EOF if there were any errors
	 * in the file proper -- kludged it by stopping after first error.
	 *		vix 31mar87
	 */
	Set_LineNum(1 - NHEADER_LINES);
	CheckErrorCount = 0;  eof = FALSE;
	rewind(tmp);
	while (!CheckErrorCount && !eof) {
		switch (load_env(envstr, tmp)) {
		case ERR:
			/* check for data before the EOF */
			if (envstr[0] != '\0') {
				Set_LineNum(LineNumber + 1);
				check_error("premature EOF");
			}
			eof = TRUE;
			break;
		case FALSE:
			e = load_entry(tmp, check_error, pw, envp);
			if (e)
				free(e);
			break;
		case TRUE:
			break;
		}
	}

	if (CheckErrorCount != 0) {
		warnx("errors in crontab file, can't install.");
		error = -1;
		goto done;
	}

	file_owner = (getgid() == getegid()) ? ROOT_UID : pw->pw_uid;

#ifdef HAVE_FCHOWN
	error = fchown(fileno(tmp), file_owner, (uid_t)-1);
#else
	error = chown(TempFilename, file_owner, (gid_t)-1);
#endif

	if (fclose(tmp) == EOF) {
		warn("error closing file");
		error = -2;
		tmp = NULL;
		goto done;
	}
	tmp = NULL;

	if (error < OK) {
		warn("cannot chown `%s'", TempFilename);
		error = -2;
		goto done;
	}

	if (!glue_strings(n, sizeof n, SPOOL_DIR, User, '/')) {
		warnx("path too long");
		error = -2;
		goto done;
	}
	if (rename(TempFilename, n)) {
		warn("error renaming `%s' to `%s'", TempFilename, n);
		error = -2;
		goto done;
	}
	TempFilename[0] = '\0';
	log_it(RealUser, Pid, "REPLACE", User);

	poke_daemon();

done:
	(void)signal(SIGHUP, ohup);
	(void)signal(SIGINT, oint);
	(void)signal(SIGQUIT, oquit);
	(void)signal(SIGABRT, oabrt);
	if (tmp != NULL)
		(void)fclose(tmp);
	cleanTempFile();
	return (error);
}

static void
poke_daemon(void) {
	struct timespec ts[2];
	(void) clock_gettime(CLOCK_REALTIME, ts);
	ts[1] = ts[0];
	if (change_time(SPOOL_DIR, ts) == -1)
		warn("can't update times on spooldir %s", SPOOL_DIR);
}

/* int allowed(const char *username, const char *allow_file, const char *deny_file)
 *	returns TRUE if (allow_file exists and user is listed)
 *	or (deny_file exists and user is NOT listed).
 *	root is always allowed.
 */
static int
allowed(const char *username, const char *allow_file, const char *deny_file) {
	FILE	*fp;
	int	isallowed;

	if (strcmp(username, ROOT_USER) == 0)
		return (TRUE);
#ifdef ALLOW_ONLY_ROOT
	isallowed = FALSE;
#else
	isallowed = TRUE;
#endif
	if ((fp = fopen(allow_file, "r")) != NULL) {
		isallowed = in_file(username, fp, FALSE);
		(void)fclose(fp);
	} else if ((fp = fopen(deny_file, "r")) != NULL) {
		isallowed = !in_file(username, fp, FALSE);
		(void)fclose(fp);
	}
	return (isallowed);
}
/* int in_file(const char *string, FILE *file, int error)
 *	return TRUE if one of the lines in file matches string exactly,
 *	FALSE if no lines match, and error on error.
 */
static int
in_file(const char *string, FILE *file, int error)
{
	char line[MAX_TEMPSTR];
	char *endp;

	if (fseek(file, 0L, SEEK_SET))
		return (error);
	while (fgets(line, MAX_TEMPSTR, file)) {
		if (line[0] != '\0') {
			endp = &line[strlen(line) - 1];
			if (*endp != '\n')
				return (error);
			*endp = '\0';
			if (0 == strcmp(line, string))
				return (TRUE);
		}
	}
	if (ferror(file))
		return (error);
	return (FALSE);
}

#ifdef HAVE_SAVED_UIDS

static int relinquish_priv(void) {
	return (setegid(rgid) || seteuid(ruid)) ? -1 : 0;
}

static int regain_priv(void) {
	return (setegid(egid) || seteuid(euid)) ? -1 : 0;
}

#else /*HAVE_SAVED_UIDS*/

static int relinquish_priv(void) {
	return (setregid(egid, rgid) || setreuid(euid, ruid)) ? -1 : 0;
}

static int regain_priv(void) {
	return (setregid(rgid, egid) || setreuid(ruid, euid)) ? -1 : 0;
}
#endif /*HAVE_SAVED_UIDS*/