/[pkg-cron]/trunk/misc.c
ViewVC logotype

Contents of /trunk/misc.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 230 - (show annotations) (download)
Tue Sep 2 00:08:54 2003 UTC (9 years, 8 months ago) by steveg
File MIME type: text/plain
File size: 14519 byte(s)
Add SAVED_UID version of swap_uids,swap_uids_back, also include groupid, all from Solar Designer
1 /* Copyright 1988,1990,1993,1994 by Paul Vixie
2 * All rights reserved
3 *
4 * Distribute freely, except: don't remove my name from the source or
5 * documentation (don't take credit for my work), mark your changes (don't
6 * get me blamed for your possible bugs), don't alter or remove this
7 * notice. May be sold if buildable source is provided to buyer. No
8 * warrantee of any kind, express or implied, is included with this
9 * software; use at your own risk, responsibility for damages (if any) to
10 * anyone resulting from the use of this software rests entirely with the
11 * user.
12 *
13 * Send bug reports, bug fixes, enhancements, requests, flames, etc., and
14 * I'll try to keep a version up to date. I can be reached as follows:
15 * Paul Vixie <paul@vix.com> uunet!decwrl!vixie!paul
16 */
17
18 #if !defined(lint) && !defined(LINT)
19 static char rcsid[] = "$Id: misc.c,v 2.9 1994/01/15 20:43:43 vixie Exp $";
20 #endif
21
22 /* vix 26jan87 [RCS has the rest of the log]
23 * vix 30dec86 [written]
24 */
25
26
27 #include "cron.h"
28 #if SYS_TIME_H
29 # include <sys/time.h>
30 #else
31 # include <time.h>
32 #endif
33 #include <sys/file.h>
34 #include <sys/stat.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <fcntl.h>
38 #if defined(SYSLOG)
39 # include <syslog.h>
40 #endif
41
42
43 #if defined(LOG_DAEMON) && !defined(LOG_CRON)
44 #define LOG_CRON LOG_DAEMON
45 #endif
46
47
48 static int LogFD = ERR;
49
50
51 int
52 strcmp_until(left, right, until)
53 char *left;
54 char *right;
55 int until;
56 {
57 register int diff;
58
59 while (*left && *left != until && *left == *right) {
60 left++;
61 right++;
62 }
63
64 if ((*left=='\0' || *left == until) &&
65 (*right=='\0' || *right == until)) {
66 diff = 0;
67 } else {
68 diff = *left - *right;
69 }
70
71 return diff;
72 }
73
74
75 /* strdtb(s) - delete trailing blanks in string 's' and return new length
76 */
77 int
78 strdtb(s)
79 char *s;
80 {
81 char *x = s;
82
83 /* scan forward to the null
84 */
85 while (*x)
86 x++;
87
88 /* scan backward to either the first character before the string,
89 * or the last non-blank in the string, whichever comes first.
90 */
91 do {x--;}
92 while (x >= s && isspace(*x));
93
94 /* one character beyond where we stopped above is where the null
95 * goes.
96 */
97 *++x = '\0';
98
99 /* the difference between the position of the null character and
100 * the position of the first character of the string is the length.
101 */
102 return x - s;
103 }
104
105
106 int
107 set_debug_flags(flags)
108 char *flags;
109 {
110 /* debug flags are of the form flag[,flag ...]
111 *
112 * if an error occurs, print a message to stdout and return FALSE.
113 * otherwise return TRUE after setting ERROR_FLAGS.
114 */
115
116 #if !DEBUGGING
117
118 printf("this program was compiled without debugging enabled\n");
119 return FALSE;
120
121 #else /* DEBUGGING */
122
123 char *pc = flags;
124
125 DebugFlags = 0;
126
127 while (*pc) {
128 char **test;
129 int mask;
130
131 /* try to find debug flag name in our list.
132 */
133 for ( test = DebugFlagNames, mask = 1;
134 *test && strcmp_until(*test, pc, ',');
135 test++, mask <<= 1
136 )
137 ;
138
139 if (!*test) {
140 fprintf(stderr,
141 "unrecognized debug flag <%s> <%s>\n",
142 flags, pc);
143 return FALSE;
144 }
145
146 DebugFlags |= mask;
147
148 /* skip to the next flag
149 */
150 while (*pc && *pc != ',')
151 pc++;
152 if (*pc == ',')
153 pc++;
154 }
155
156 if (DebugFlags) {
157 int flag;
158
159 fprintf(stderr, "debug flags enabled:");
160
161 for (flag = 0; DebugFlagNames[flag]; flag++)
162 if (DebugFlags & (1 << flag))
163 fprintf(stderr, " %s", DebugFlagNames[flag]);
164 fprintf(stderr, "\n");
165 }
166
167 return TRUE;
168
169 #endif /* DEBUGGING */
170 }
171
172
173 void
174 set_cron_uid()
175 {
176 #if defined(BSD) || defined(POSIX)
177 if (seteuid(ROOT_UID) < OK) {
178 perror("seteuid");
179 exit(ERROR_EXIT);
180 }
181 #else
182 if (setuid(ROOT_UID) < OK) {
183 perror("setuid");
184 exit(ERROR_EXIT);
185 }
186 #endif
187 }
188
189
190 void
191 set_cron_cwd()
192 {
193 struct stat sb;
194
195 /* first check for CRONDIR ("/var/cron" or some such)
196 */
197 if (stat(CRONDIR, &sb) < OK && errno == ENOENT) {
198 perror(CRONDIR);
199 if (OK == mkdir(CRONDIR, 0700)) {
200 fprintf(stderr, "%s: created\n", CRONDIR);
201 stat(CRONDIR, &sb);
202 } else {
203 fprintf(stderr, "%s: ", CRONDIR);
204 perror("mkdir");
205 exit(ERROR_EXIT);
206 }
207 }
208 if (!(sb.st_mode & S_IFDIR)) {
209 fprintf(stderr, "'%s' is not a directory, bailing out.\n",
210 CRONDIR);
211 exit(ERROR_EXIT);
212 }
213 if (chdir(CRONDIR) < OK) {
214 fprintf(stderr, "cannot chdir(%s), bailing out.\n", CRONDIR);
215 perror(CRONDIR);
216 exit(ERROR_EXIT);
217 }
218
219 /* CRONDIR okay (now==CWD), now look at SPOOL_DIR ("tabs" or some such)
220 */
221 if (stat(SPOOL_DIR, &sb) < OK && errno == ENOENT) {
222 perror(SPOOL_DIR);
223 if (OK == mkdir(SPOOL_DIR, 0700)) {
224 fprintf(stderr, "%s: created\n", SPOOL_DIR);
225 stat(SPOOL_DIR, &sb);
226 } else {
227 fprintf(stderr, "%s: ", SPOOL_DIR);
228 perror("mkdir");
229 exit(ERROR_EXIT);
230 }
231 }
232 if (!(sb.st_mode & S_IFDIR)) {
233 fprintf(stderr, "'%s' is not a directory, bailing out.\n",
234 SPOOL_DIR);
235 exit(ERROR_EXIT);
236 }
237 }
238
239
240 /* acquire_daemonlock() - write our PID into /etc/cron.pid, unless
241 * another daemon is already running, which we detect here.
242 *
243 * note: main() calls us twice; once before forking, once after.
244 * we maintain static storage of the file pointer so that we
245 * can rewrite our PID into the PIDFILE after the fork.
246 *
247 * it would be great if fflush() disassociated the file buffer.
248 */
249 void
250 acquire_daemonlock(closeflag)
251 int closeflag;
252 {
253 static FILE *fp = NULL;
254
255 if (closeflag && fp) {
256 fclose(fp);
257 fp = NULL;
258 return;
259 }
260
261 if (!fp) {
262 char pidfile[MAX_FNAME];
263 char buf[MAX_TEMPSTR];
264 int fd, otherpid;
265
266 (void) snprintf(pidfile, MAX_FNAME, PIDFILE, PIDDIR);
267 if ((-1 == (fd = open(pidfile, O_RDWR|O_CREAT, 0644)))
268 || (NULL == (fp = fdopen(fd, "r+")))
269 ) {
270 snprintf(buf, MAX_TEMPSTR, "can't open or create %s: %s",
271 pidfile, strerror(errno));
272 fprintf(stderr, "%s: %s\n", ProgramName, buf);
273 log_it("CRON", getpid(), "DEATH", buf);
274 exit(ERROR_EXIT);
275 }
276
277 if (flock(fd, LOCK_EX|LOCK_NB) < OK) {
278 int save_errno = errno;
279
280 fscanf(fp, "%d", &otherpid);
281 snprintf(buf, MAX_TEMPSTR, "can't lock %s, otherpid may be %d: %s",
282 pidfile, otherpid, strerror(save_errno));
283 fprintf(stderr, "%s: %s\n", ProgramName, buf);
284 log_it("CRON", getpid(), "DEATH", buf);
285 exit(ERROR_EXIT);
286 }
287 snprintf(buf, MAX_TEMPSTR, "pidfile fd = %d", fd);
288 log_it("CRON", getpid(), "INFO", buf);
289 (void) fcntl(fd, F_SETFD, 1);
290 }
291
292 rewind(fp);
293 fprintf(fp, "%d\n", getpid());
294 fflush(fp);
295 (void) ftruncate(fileno(fp), ftell(fp));
296
297 /* abandon fd and fp even though the file is open. we need to
298 * keep it open and locked, but we don't need the handles elsewhere.
299 */
300
301 }
302
303 /* get_char(file) : like getc() but increment LineNumber on newlines
304 */
305 int
306 get_char(file)
307 FILE *file;
308 {
309 int ch;
310
311 ch = getc(file);
312 if (ch == '\n')
313 Set_LineNum(LineNumber + 1);
314 return ch;
315 }
316
317
318 /* unget_char(ch, file) : like ungetc but do LineNumber processing
319 */
320 void
321 unget_char(ch, file)
322 int ch;
323 FILE *file;
324 {
325 ungetc(ch, file);
326 if (ch == '\n')
327 Set_LineNum(LineNumber - 1);
328 }
329
330
331 /* get_string(str, max, file, termstr) : like fgets() but
332 * (1) has terminator string which should include \n
333 * (2) will always leave room for the null
334 * (3) uses get_char() so LineNumber will be accurate
335 * (4) returns EOF or terminating character, whichever
336 */
337 int
338 get_string(string, size, file, terms)
339 char *string;
340 int size;
341 FILE *file;
342 char *terms;
343 {
344 int ch;
345
346 while (EOF != (ch = get_char(file)) && !strchr(terms, ch)) {
347 if (size > 1) {
348 *string++ = (char) ch;
349 size--;
350 }
351 }
352
353 if (size > 0)
354 *string = '\0';
355
356 return ch;
357 }
358
359
360 /* skip_comments(file) : read past comment (if any)
361 */
362 void
363 skip_comments(file)
364 FILE *file;
365 {
366 int ch;
367
368 while (EOF != (ch = get_char(file))) {
369 /* ch is now the first character of a line.
370 */
371
372 while (ch == ' ' || ch == '\t')
373 ch = get_char(file);
374
375 if (ch == EOF)
376 break;
377
378 /* ch is now the first non-blank character of a line.
379 */
380
381 if (ch != '\n' && ch != '#')
382 break;
383
384 /* ch must be a newline or comment as first non-blank
385 * character on a line.
386 */
387
388 while (ch != '\n' && ch != EOF)
389 ch = get_char(file);
390
391 /* ch is now the newline of a line which we're going to
392 * ignore.
393 */
394 }
395 if (ch != EOF)
396 unget_char(ch, file);
397 }
398
399
400 /* int in_file(char *string, FILE *file)
401 * return TRUE if one of the lines in file matches string exactly,
402 * FALSE otherwise.
403 */
404 static int
405 in_file(string, file)
406 char *string;
407 FILE *file;
408 {
409 char line[MAX_TEMPSTR];
410
411 rewind(file);
412 while (fgets(line, MAX_TEMPSTR, file)) {
413 if (line[0] != '\0')
414 line[strlen(line)-1] = '\0';
415 if (0 == strcmp(line, string))
416 return TRUE;
417 }
418 return FALSE;
419 }
420
421
422 /* int allowed(char *username)
423 * returns TRUE if (ALLOW_FILE exists and user is listed)
424 * or (DENY_FILE exists and user is NOT listed)
425 * or (neither file exists but user=="root" so it's okay)
426 */
427 int
428 allowed(username)
429 char *username;
430 {
431 static int init = FALSE;
432 static FILE *allow, *deny;
433
434 if (!init) {
435 init = TRUE;
436 #if defined(ALLOW_FILE) && defined(DENY_FILE)
437 allow = fopen(ALLOW_FILE, "r");
438 deny = fopen(DENY_FILE, "r");
439 Debug(DMISC, ("allow/deny enabled, %d/%d\n", !!allow, !!deny))
440 #else
441 allow = NULL;
442 deny = NULL;
443 #endif
444 }
445
446 if (allow)
447 return (in_file(username, allow));
448 if (deny)
449 return (!in_file(username, deny));
450
451 #if defined(ALLOW_ONLY_ROOT)
452 return (strcmp(username, ROOT_USER) == 0);
453 #else
454 return TRUE;
455 #endif
456 }
457
458
459 void
460 log_it(username, xpid, event, detail)
461 char *username;
462 int xpid;
463 char *event;
464 char *detail;
465 {
466 #if defined(LOG_FILE)
467 PID_T pid = xpid;
468 char *msg;
469 TIME_T now = time((TIME_T) 0);
470 register struct tm *t = localtime(&now);
471 int msg_size;
472 #endif /*LOG_FILE*/
473
474
475 #if defined(LOG_FILE)
476 /* we assume that MAX_TEMPSTR will hold the date, time, &punctuation.
477 */
478 msg_size = strlen(username) + strlen(event) + strlen(detail) + MAX_TEMPSTR;
479 msg = malloc(msg_size);
480 if (msg == NULL) {
481 /* damn, out of mem and we did not test that before... */
482 fprintf(stderr, "%s: Run OUT OF MEMORY while %s\n",
483 ProgramName, __FUNCTION__);
484 return;
485 }
486 if (LogFD < OK) {
487 LogFD = open(LOG_FILE, O_WRONLY|O_APPEND|O_CREAT, 0600);
488 if (LogFD < OK) {
489 fprintf(stderr, "%s: can't open log file\n",
490 ProgramName);
491 perror(LOG_FILE);
492 } else {
493 (void) fcntl(LogFD, F_SETFD, 1);
494 }
495 }
496
497 /* we have to snprintf() it because fprintf() doesn't always write
498 * everything out in one chunk and this has to be atomically appended
499 * to the log file.
500 */
501 snprintf(msg, msg_size, "%s (%02d/%02d-%02d:%02d:%02d-%d) %s (%s)\n",
502 username,
503 t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, pid,
504 event, detail);
505
506 /* we have to run strlen() because snprintf() returns (char*) on old BSD
507 */
508 if (LogFD < OK || write(LogFD, msg, strlen(msg)) < OK) {
509 if (LogFD >= OK)
510 perror(LOG_FILE);
511 fprintf(stderr, "%s: can't write to log file\n", ProgramName);
512 write(STDERR, msg, strlen(msg));
513 }
514
515 free(msg);
516 #endif /*LOG_FILE*/
517
518 #if defined(SYSLOG)
519
520
521 /* we don't use LOG_PID since the pid passed to us by
522 * our client may not be our own. therefore we want to
523 * print the pid ourselves.
524 */
525 /* SteveG says: That comment is not consistent with the
526 code, and makes no sense -- I suspect it's a remnant
527 of a cut-n-paster... */
528 # ifdef LOG_CRON
529 openlog(ProgramName, LOG_PID, LOG_CRON);
530 # else
531 openlog(ProgramName, LOG_PID);
532 # endif
533
534 syslog(LOG_INFO, "(%s) %s (%s)", username, event, detail);
535
536 closelog();
537 #endif /*SYSLOG*/
538
539 #if DEBUGGING
540 if (DebugFlags) {
541 fprintf(stderr, "log_it: (%s %d) %s (%s)\n",
542 username, xpid, event, detail);
543 }
544 #endif
545 }
546
547
548 void
549 log_close() {
550 #if defined(LOG_FILE)
551 if (LogFD != ERR) {
552 close(LogFD);
553 LogFD = ERR;
554 }
555 #endif
556 #if defined(SYSLOG)
557 closelog();
558 #endif
559 }
560
561
562 /* two warnings:
563 * (1) this routine is fairly slow
564 * (2) it returns a pointer to static storage
565 */
566 char *
567 first_word(s, t)
568 register char *s; /* string we want the first word of */
569 register char *t; /* terminators, implicitly including \0 */
570 {
571 static char retbuf[2][MAX_TEMPSTR + 1]; /* sure wish C had GC */
572 static int retsel = 0;
573 register char *rb, *rp;
574
575 /* select a return buffer */
576 retsel = 1-retsel;
577 rb = &retbuf[retsel][0];
578 rp = rb;
579
580 /* skip any leading terminators */
581 while (*s && (NULL != strchr(t, *s))) {
582 s++;
583 }
584
585 /* copy until next terminator or full buffer */
586 while (*s && (NULL == strchr(t, *s)) && (rp < &rb[MAX_TEMPSTR])) {
587 *rp++ = *s++;
588 }
589
590 /* finish the return-string and return it */
591 *rp = '\0';
592 return rb;
593 }
594
595
596 /* warning:
597 * heavily ascii-dependent.
598 */
599 void
600 mkprint(dst, src, len)
601 register char *dst;
602 register unsigned char *src;
603 register int len;
604 {
605 while (len-- > 0)
606 {
607 register unsigned char ch = *src++;
608
609 if (ch < ' ') { /* control character */
610 *dst++ = '^';
611 *dst++ = ch + '@';
612 } else if (ch < 0177) { /* printable */
613 *dst++ = ch;
614 } else if (ch == 0177) { /* delete/rubout */
615 *dst++ = '^';
616 *dst++ = '?';
617 } else { /* parity character */
618 /* well, the following snprintf is paranoid, but that will
619 * keep grep happy */
620 snprintf(dst, 5, "\\%03o", ch);
621 dst += 4;
622 }
623 }
624 *dst = '\0';
625 }
626
627
628 /* warning:
629 * returns a pointer to malloc'd storage, you must call free yourself.
630 */
631 char *
632 mkprints(src, len)
633 register unsigned char *src;
634 register unsigned int len;
635 {
636 register char *dst = malloc(len*4 + 1);
637
638 if (dst)
639 mkprint(dst, src, len);
640
641 return dst;
642 }
643
644
645 #ifdef MAIL_DATE
646 /* Sat, 27 Feb 1993 11:44:51 -0800 (CST)
647 * 1234567890123456789012345678901234567
648 */
649 char *
650 arpadate(clock)
651 time_t *clock;
652 {
653 static char ret[64]; /* zone name might be >3 chars */
654 time_t t = clock ? *clock : time(NULL);
655 struct tm *tm = localtime(&t);
656 char *qmark;
657 size_t len;
658 int hours = tm->tm_gmtoff / 3600;
659 int minutes = (tm->tm_gmtoff - (hours * 3600)) / 60;
660
661 if (minutes < 0)
662 minutes = -minutes;
663
664 /* Defensive coding (almost) never hurts... */
665 len = strftime(ret, sizeof(ret), "%a, %e %b %Y %T ????? (%Z)", tm);
666 if (len == 0) {
667 ret[0] = '?';
668 ret[1] = '\0';
669 return ret;
670 }
671 qmark = strchr(ret, '?');
672 if (qmark && len - (qmark - ret) >= 6) {
673 snprintf(qmark, 6, "% .2d%.2d", hours, minutes);
674 qmark[5] = ' ';
675 }
676 return ret;
677 }
678 #endif /*MAIL_DATE*/
679
680
681 #ifdef HAVE_SAVED_UIDS
682 static uid_t save_euid, save_egid;
683 int swap_uids()
684 {
685 save_euid = geteuid(); save_egid = getegid();
686 return (setegid(getgid()) || seteuid(getuid())) ? -1 : 0;
687 }
688 int swap_uids_back()
689 {
690 return (setegid(save_egid) || seteuid(save_euid)) ? -1 : 0;
691 }
692 #else /*HAVE_SAVED_UIDS*/
693 int swap_uids()
694 {
695 return (setregid(getegid(), getgid()) || setreuid(geteuid(), getuid()))
696 ? -1 : 0;
697 }
698 int swap_uids_back() { return swap_uids(); }
699 #endif /*HAVE_SAVED_UIDS*/

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.5