2 * Copyright (c) 1997-1999 Erez Zadok
3 * Copyright (c) 1990 Jan-Simon Pendry
4 * Copyright (c) 1990 Imperial College of Science, Technology & Medicine
5 * Copyright (c) 1990 The Regents of the University of California.
8 * This code is derived from software contributed to Berkeley by
9 * Jan-Simon Pendry at Imperial College, London.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgment:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41 * $Id: xutil.c,v 1.8 1999/09/30 21:01:42 ezk Exp $
47 #endif /* HAVE_CONFIG_H */
52 * Logfp is the default logging device, and is initialized to stderr by
53 * default in dplog/plog below, and in
54 * amd/amfs_program.c:amfs_program_exec().
58 static char *am_progname = "unknown"; /* "amd" */
59 static char am_hostname[MAXHOSTNAMELEN + 1] = "unknown"; /* Hostname */
60 pid_t am_mypid = -1; /* process ID */
61 serv_state amd_state; /* amd's state */
62 int foreground = 1; /* 1 == this is the top-level server */
69 #endif /* HAVE_SYSLOG */
70 int xlog_level = XLOG_ALL & ~XLOG_MAP & ~XLOG_STATS;
71 int xlog_level_init = ~0;
72 static int amd_program_number = AMQ_PROGRAM;
74 time_t clock_valid = 0;
75 time_t xclock_valid = 0;
79 static int orig_mem_bytes;
80 #endif /* DEBUG_MEM */
82 /* forward definitions */
83 static void real_plog(int lvl, char *fmt, va_list vargs);
87 * List of debug options.
89 struct opt_tab dbg_opt[] =
91 {"all", D_ALL}, /* All */
92 {"amq", D_AMQ}, /* Register for AMQ program */
93 {"daemon", D_DAEMON}, /* Enter daemon mode */
94 {"fork", D_FORK}, /* Fork server (nofork = don't fork) */
95 {"full", D_FULL}, /* Program trace */
96 /* info service specific debugging (hesiod, nis, etc) */
99 {"mem", D_MEM}, /* Trace memory allocations */
100 # endif /* DEBUG_MEM */
101 {"mtab", D_MTAB}, /* Use local mtab file */
102 {"str", D_STR}, /* Debug string munging */
103 {"test", D_TEST}, /* Full debug - but no daemon */
104 {"trace", D_TRACE}, /* Protocol trace */
110 * List of log options
112 struct opt_tab xlog_opt[] =
114 {"all", XLOG_ALL}, /* All messages */
116 {"debug", XLOG_DEBUG}, /* Debug messages */
117 #endif /* DEBUG */ /* DEBUG */
118 {"error", XLOG_ERROR}, /* Non-fatal system errors */
119 {"fatal", XLOG_FATAL}, /* Fatal errors */
120 {"info", XLOG_INFO}, /* Information */
121 {"map", XLOG_MAP}, /* Map errors */
122 {"stats", XLOG_STATS}, /* Additional statistical information */
123 {"user", XLOG_USER}, /* Non-fatal user errors */
124 {"warn", XLOG_WARNING}, /* Warnings */
125 {"warning", XLOG_WARNING}, /* Warnings */
131 am_set_progname(char *pn)
138 am_get_progname(void)
145 am_set_hostname(char *hn)
147 strncpy(am_hostname, hn, MAXHOSTNAMELEN);
148 am_hostname[MAXHOSTNAMELEN] = '\0';
153 am_get_hostname(void)
174 * Avoid malloc's which return NULL for malloc(0)
180 p = (voidp) malloc((unsigned) len);
182 #if defined(DEBUG) && defined(DEBUG_MEM)
184 plog(XLOG_DEBUG, "Allocated size %d; block %#x", len, p);
185 #endif /* defined(DEBUG) && defined(DEBUG_MEM) */
189 plog(XLOG_ERROR, "Retrying memory allocation");
194 plog(XLOG_FATAL, "Out of memory");
203 /* like xmalloc, but zeros out the bytes */
207 voidp p = xmalloc(len);
216 xrealloc(voidp ptr, int len)
218 #if defined(DEBUG) && defined(DEBUG_MEM)
219 amuDebug(D_MEM) plog(XLOG_DEBUG, "Reallocated size %d; block %#x", len, ptr);
220 #endif /* defined(DEBUG) && defined(DEBUG_MEM) */
226 ptr = (voidp) realloc(ptr, (unsigned) len);
228 ptr = (voidp) xmalloc((unsigned) len);
231 plog(XLOG_FATAL, "Out of memory in realloc");
239 #if defined(DEBUG) && defined(DEBUG_MEM)
241 dxfree(char *file, int line, voidp ptr)
244 plog(XLOG_DEBUG, "Free in %s:%d: block %#x", file, line, ptr);
245 /* this is the only place that must NOT use XFREE()!!! */
247 ptr = NULL; /* paranoid */
249 #endif /* defined(DEBUG) && defined(DEBUG_MEM) */
256 struct mallinfo mi = mallinfo();
257 u_long uordbytes = mi.uordblks * 4096;
259 if (mem_bytes != uordbytes) {
260 if (orig_mem_bytes == 0)
261 mem_bytes = orig_mem_bytes = uordbytes;
263 fprintf(logfp, "%s[%ld]: ", am_get_progname(), (long) am_mypid);
264 if (mem_bytes < uordbytes) {
265 fprintf(logfp, "ALLOC: %ld bytes", uordbytes - mem_bytes);
267 fprintf(logfp, "FREE: %ld bytes", mem_bytes - uordbytes);
269 mem_bytes = uordbytes;
270 fprintf(logfp, ", making %d missing\n", mem_bytes - orig_mem_bytes);
275 #endif /* DEBUG_MEM */
279 * Take a log format string and expand occurrences of %m
280 * with the current error code taken from errno. Make sure
281 * 'e' never gets longer than maxlen characters.
284 expand_error(char *f, char *e, int maxlen)
291 for (p = f, q = e; (*q = *p) && len < maxlen; len++, q++, p++) {
292 if (p[0] == '%' && p[1] == 'm') {
294 if (error < 0 || error >= sys_nerr)
298 errstr = strerror(error);
299 #else /* not HAVE_STRERROR */
300 errstr = sys_errlist[error];
301 #endif /* not HAVE_STRERROR */
305 sprintf(q, "Error %d", error);
306 len += strlen(q) - 1;
311 e[maxlen-1] = '\0'; /* null terminate, to be sure */
316 * Output the time of day and hostname to the logfile
319 show_time_host_and_name(int lvl)
321 static time_t last_t = 0;
322 static char *last_ctime = 0;
323 time_t t = clocktime();
327 last_ctime = ctime(&t);
359 fprintf(logfp, "%15.15s %s %s[%ld]/%s ",
360 last_ctime + 4, am_get_hostname(),
369 * Switch on/off debug options
372 debug_option(char *opt)
374 return cmdoption(opt, dbg_opt, &debug_flags);
379 dplog(char *fmt, ...)
384 logfp = stderr; /* initialize before possible first use */
387 real_plog(XLOG_DEBUG, fmt, ap);
394 plog(int lvl, char *fmt, ...)
399 logfp = stderr; /* initialize before possible first use */
402 real_plog(lvl, fmt, ap);
408 real_plog(int lvl, char *fmt, va_list vargs)
413 static char last_msg[1024];
414 static int last_count = 0, last_lvl = 0;
416 if (!(xlog_level & lvl))
421 #endif /* DEBUG_MEM */
423 expand_error(fmt, efmt, 1024);
425 #ifdef HAVE_VSNPRINTF
426 vsnprintf(ptr, 1024, efmt, vargs);
427 #else /* not HAVE_VSNPRINTF */
429 * XXX: ptr is 1024 bytes long. It is possible to write into it
430 * more than 1024 bytes, if efmt is already large, and vargs expand
431 * as well. This is not as safe as using vsnprintf().
433 vsprintf(ptr, efmt, vargs);
434 msg[1023] = '\0'; /* null terminate, to be sure */
435 #endif /* not HAVE_VSNPRINTF */
443 switch (lvl) { /* from mike <mcooper@usc.edu> */
472 syslog(lvl, "%s", msg);
475 #endif /* HAVE_SYSLOG */
481 * mimic syslog behavior: only write repeated strings if they differ
483 switch (last_count) {
484 case 0: /* never printed at all */
486 strncpy(last_msg, msg, 1024);
488 show_time_host_and_name(lvl); /* mimic syslog header */
489 fwrite(msg, ptr - msg, 1, logfp);
493 case 1: /* item printed once, if same, don't repeat */
494 if (STREQ(last_msg, msg)) {
496 } else { /* last msg printed once, new one differs */
497 /* last_count remains at 1 */
498 strncpy(last_msg, msg, 1024);
500 show_time_host_and_name(lvl); /* mimic syslog header */
501 fwrite(msg, ptr - msg, 1, logfp);
508 * Don't allow repetitions longer than 100, so you can see when something
511 show_time_host_and_name(last_lvl);
512 sprintf(last_msg, "last message repeated %d times\n", last_count);
513 fwrite(last_msg, strlen(last_msg), 1, logfp);
515 last_count = 0; /* start from scratch */
518 default: /* item repeated multiple times */
519 if (STREQ(last_msg, msg)) {
521 } else { /* last msg repeated+skipped, new one differs */
522 show_time_host_and_name(last_lvl);
523 sprintf(last_msg, "last message repeated %d times\n", last_count);
524 fwrite(last_msg, strlen(last_msg), 1, logfp);
525 strncpy(last_msg, msg, 1024);
528 show_time_host_and_name(lvl); /* mimic syslog header */
529 fwrite(msg, ptr - msg, 1, logfp);
539 * Display current debug options
542 show_opts(int ch, struct opt_tab *opts)
547 fprintf(stderr, "\t[-%c {no}", ch);
548 for (i = 0; opts[i].opt; i++) {
549 fprintf(stderr, "%c%s", s, opts[i].opt);
552 fputs("}]\n", stderr);
557 cmdoption(char *s, struct opt_tab *optb, int *flags)
565 struct opt_tab *dp, *dpn = 0;
572 /* check for "no" prefix to options */
573 if (s[0] == 'n' && s[1] == 'o') {
582 * Scan the array of debug options to find the
583 * corresponding flag value. If it is found
584 * then set (or clear) the flag (depending on
585 * whether the option was prefixed with "no").
587 for (dp = optb; dp->opt; dp++) {
588 if (STREQ(opt, dp->opt))
590 if (opt != s && !dpn && STREQ(s, dp->opt))
594 if (dp->opt || dpn) {
605 * This will log to stderr when parsing the command line
606 * since any -l option will not yet have taken effect.
608 plog(XLOG_USER, "option \"%s\" not recognized", s);
624 * Switch on/off logging options
627 switch_option(char *opt)
630 int rc = cmdoption(opt, xlog_opt, &xl);
636 * Keep track of initial log level, and
637 * don't allow options to be turned off.
639 if (xlog_level_init == ~0)
640 xlog_level_init = xl;
642 xl |= xlog_level_init;
650 * get syslog facility to use.
651 * logfile can be "syslog", "syslog:daemon", "syslog:local7", etc.
654 get_syslog_facility(const char *logfile)
658 /* parse facility string */
659 facstr = strchr(logfile, ':');
660 if (!facstr) /* log file was "syslog" */
663 if (!facstr || facstr[0] == '\0') { /* log file was "syslog:" */
664 plog(XLOG_WARNING, "null syslog facility, using LOG_DAEMON");
669 if (STREQ(facstr, "kern"))
671 #endif /* not LOG_KERN */
673 if (STREQ(facstr, "user"))
675 #endif /* not LOG_USER */
677 if (STREQ(facstr, "mail"))
679 #endif /* not LOG_MAIL */
681 if (STREQ(facstr, "daemon"))
685 if (STREQ(facstr, "auth"))
687 #endif /* not LOG_AUTH */
689 if (STREQ(facstr, "syslog"))
691 #endif /* not LOG_SYSLOG */
693 if (STREQ(facstr, "lpr"))
695 #endif /* not LOG_LPR */
697 if (STREQ(facstr, "news"))
699 #endif /* not LOG_NEWS */
701 if (STREQ(facstr, "uucp"))
703 #endif /* not LOG_UUCP */
705 if (STREQ(facstr, "cron"))
707 #endif /* not LOG_CRON */
709 if (STREQ(facstr, "local0"))
711 #endif /* not LOG_LOCAL0 */
713 if (STREQ(facstr, "local1"))
715 #endif /* not LOG_LOCAL1 */
717 if (STREQ(facstr, "local2"))
719 #endif /* not LOG_LOCAL2 */
721 if (STREQ(facstr, "local3"))
723 #endif /* not LOG_LOCAL3 */
725 if (STREQ(facstr, "local4"))
727 #endif /* not LOG_LOCAL4 */
729 if (STREQ(facstr, "local5"))
731 #endif /* not LOG_LOCAL5 */
733 if (STREQ(facstr, "local6"))
735 #endif /* not LOG_LOCAL6 */
737 if (STREQ(facstr, "local7"))
739 #endif /* not LOG_LOCAL7 */
741 /* didn't match anything else */
742 plog(XLOG_WARNING, "unknown syslog facility \"%s\", using LOG_DAEMON", facstr);
745 #endif /* not LOG_DAEMON */
749 * Change current logfile
752 switch_to_logfile(char *logfile, int old_umask)
754 FILE *new_logfp = stderr;
759 #endif /* HAVE_SYSLOG */
761 if (STREQ(logfile, "/dev/stderr"))
763 else if (NSTREQ(logfile, "syslog", strlen("syslog"))) {
768 openlog(am_get_progname(),
772 # endif /* LOG_CONS */
775 # endif /* LOG_NOWAIT */
777 , get_syslog_facility(logfile)
778 # endif /* LOG_DAEMON */
780 #else /* not HAVE_SYSLOG */
781 plog(XLOG_WARNING, "syslog option not supported, logging unchanged");
782 #endif /* not HAVE_SYSLOG */
785 (void) umask(old_umask);
786 new_logfp = fopen(logfile, "a");
792 * If we couldn't open a new file, then continue using the old.
794 if (!new_logfp && logfile) {
795 plog(XLOG_USER, "%s: Can't open logfile: %m", logfile);
800 * Close the previous file
802 if (logfp && logfp != stderr)
803 (void) fclose(logfp);
806 plog(XLOG_INFO, "switched to logfile \"%s\"", logfile);
817 /* find which instance of amd to unregister */
818 pmap_unset(get_amd_program_number(), AMQ_VERSION);
826 if (amd_state != Start) {
827 if (amd_state != Done)
833 plog(XLOG_INFO, "Finishing with status %d", rc);
836 dlog("background process exiting with status %d", rc);
844 /* return the rpc program number under which amd was used */
846 get_amd_program_number(void)
848 return amd_program_number;
852 /* set the rpc program number used for amd */
854 set_amd_program_number(int program)
856 amd_program_number = program;
861 * Release the controlling tty of the process pid.
863 * Algorithm: try these in order, if available, until one of them
864 * succeeds: setsid(), ioctl(fd, TIOCNOTTY, 0).
865 * Do not use setpgid(): on some OSs it may release the controlling tty,
866 * even if the man page does not mention it, but on other OSs it does not.
867 * Also avoid setpgrp(): it works on some systems, and on others it is
868 * identical to setpgid().
871 amu_release_controlling_tty(void)
875 #endif /* TIOCNOTTY */
878 /* XXX: one day maybe use vhangup(2) */
880 plog(XLOG_WARNING, "Could not release controlling tty using setsid(): %m");
882 plog(XLOG_INFO, "released controlling tty using setsid()");
885 #endif /* HAVE_SETSID */
888 fd = open("/dev/tty", O_RDWR);
890 /* not an error if already no controlling tty */
892 plog(XLOG_WARNING, "Could not open controlling tty: %m");
894 if (ioctl(fd, TIOCNOTTY, 0) < 0 && errno != ENOTTY)
895 plog(XLOG_WARNING, "Could not disassociate tty (TIOCNOTTY): %m");
897 plog(XLOG_INFO, "released controlling tty using ioctl(TIOCNOTTY)");
901 #endif /* not TIOCNOTTY */
903 plog(XLOG_ERROR, "unable to release controlling tty");