2 * main.c - Point-to-Point Protocol main module
4 * Copyright (c) 1989 Carnegie Mellon University.
7 * Redistribution and use in source and binary forms are permitted
8 * provided that the above copyright notice and this paragraph are
9 * duplicated in all such forms and that any documentation,
10 * advertising materials, and other materials related to such
11 * distribution and use acknowledge that the software was developed
12 * by Carnegie Mellon University. The name of the
13 * University may not be used to endorse or promote products derived
14 * from this software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21 static char rcsid[] = "$Id: main.c,v 1.43 1997/11/27 06:09:20 paulus Exp $";
36 #include <sys/param.h>
37 #include <sys/types.h>
40 #include <sys/resource.h>
42 #include <sys/socket.h>
53 #include "pathnames.h"
54 #include "patchlevel.h"
61 extern char *strerror();
66 #endif /* IPX_CHANGE */
72 char ifname[IFNAMSIZ]; /* Interface name */
73 int ifunit; /* Interface unit number */
75 char *progname; /* Name of this program */
76 char hostname[MAXNAMELEN]; /* Our hostname */
77 static char pidfilename[MAXPATHLEN]; /* name of pid file */
78 static char default_devnam[MAXPATHLEN]; /* name of default device */
79 static pid_t pid; /* Our pid */
80 static uid_t uid; /* Our real user-id */
81 static int conn_running; /* we have a [dis]connector running */
83 int ttyfd = -1; /* Serial port file descriptor */
84 mode_t tty_mode = -1; /* Original access permissions to tty */
85 int baud_rate; /* Actual bits/second for serial device */
86 int hungup; /* terminal has been hung up */
87 int privileged; /* we're running as real uid root */
88 int need_holdoff; /* need holdoff period before restarting */
90 int phase; /* where the link is at */
93 int redirect_stderr; /* Connector's stderr should go to file */
95 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
96 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
98 static int n_children; /* # child processes still running */
100 static int locked; /* lock() has succeeded */
102 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
104 /* Prototypes for procedures local to this file. */
106 static void cleanup __P((void));
107 static void close_tty __P((void));
108 static void get_input __P((void));
109 static void calltimeout __P((void));
110 static struct timeval *timeleft __P((struct timeval *));
111 static void kill_my_pg __P((int));
112 static void hup __P((int));
113 static void term __P((int));
114 static void chld __P((int));
115 static void toggle_debug __P((int));
116 static void open_ccp __P((int));
117 static void bad_signal __P((int));
118 static void holdoff_end __P((void *));
119 static int device_script __P((char *, int, int));
120 static void reap_kids __P((void));
121 static void pr_log __P((void *, char *, ...));
123 extern char *ttyname __P((int));
124 extern char *getlogin __P((void));
125 int main __P((int, char *[]));
129 #define O_NONBLOCK O_NDELAY
133 #define setlogmask(x)
137 * PPP Data Link Layer "protocol" table.
138 * One entry per supported protocol.
139 * The last entry must be NULL.
141 struct protent *protocols[] = {
171 struct protent *protp;
174 phase = PHASE_INITIALIZE;
178 strcpy(default_devnam, devnam);
180 /* Initialize syslog facilities */
182 openlog("pppd", LOG_PID);
184 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
185 setlogmask(LOG_UPTO(LOG_INFO));
188 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
189 option_error("Couldn't get hostname: %m");
192 hostname[MAXNAMELEN-1] = 0;
195 privileged = uid == 0;
198 * Initialize to the standard option set, then parse, in order,
199 * the system options file, the user's options file,
200 * the tty's options file, and the command line arguments.
202 for (i = 0; (protp = protocols[i]) != NULL; ++i)
207 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
208 || !options_from_user())
210 scan_args(argc-1, argv+1); /* look for tty name on command line */
211 if (!options_for_tty()
212 || !parse_args(argc-1, argv+1))
216 * Check that we are running as root.
218 if (geteuid() != 0) {
219 option_error("must be root to run %s, since it is not setuid-root",
224 if (!ppp_available()) {
225 option_error(no_ppp_msg);
230 * Check that the options given are valid and consistent.
233 auth_check_options();
234 for (i = 0; (protp = protocols[i]) != NULL; ++i)
235 if (protp->check_options != NULL)
236 (*protp->check_options)();
237 if (demand && connector == 0) {
238 option_error("connect script required for demand-dialling\n");
243 * If the user has specified the default device name explicitly,
244 * pretend they hadn't.
246 if (!default_device && strcmp(devnam, default_devnam) == 0)
248 redirect_stderr = !nodetach || default_device;
251 * Initialize system-dependent stuff and magic number package.
256 setlogmask(LOG_UPTO(LOG_DEBUG));
259 * Detach ourselves from the terminal, if required,
260 * and identify who is running us.
262 if (!default_device && !nodetach && daemon(0, 0) < 0) {
263 perror("Couldn't detach from controlling terminal");
270 if (pw != NULL && pw->pw_name != NULL)
275 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
276 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
279 * Compute mask of all interesting signals and install signal handlers
280 * for each. Only one signal handler may be active at a time. Therefore,
281 * all other signals should be masked when any handler is executing.
284 sigaddset(&mask, SIGHUP);
285 sigaddset(&mask, SIGINT);
286 sigaddset(&mask, SIGTERM);
287 sigaddset(&mask, SIGCHLD);
289 #define SIGNAL(s, handler) { \
290 sa.sa_handler = handler; \
291 if (sigaction(s, &sa, NULL) < 0) { \
292 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
299 SIGNAL(SIGHUP, hup); /* Hangup */
300 SIGNAL(SIGINT, term); /* Interrupt */
301 SIGNAL(SIGTERM, term); /* Terminate */
302 SIGNAL(SIGCHLD, chld);
304 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
305 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
308 * Install a handler for other signals which would otherwise
309 * cause pppd to exit without cleaning up.
311 SIGNAL(SIGABRT, bad_signal);
312 SIGNAL(SIGALRM, bad_signal);
313 SIGNAL(SIGFPE, bad_signal);
314 SIGNAL(SIGILL, bad_signal);
315 SIGNAL(SIGPIPE, bad_signal);
316 SIGNAL(SIGQUIT, bad_signal);
317 SIGNAL(SIGSEGV, bad_signal);
319 SIGNAL(SIGBUS, bad_signal);
322 SIGNAL(SIGEMT, bad_signal);
325 SIGNAL(SIGPOLL, bad_signal);
328 SIGNAL(SIGPROF, bad_signal);
331 SIGNAL(SIGSYS, bad_signal);
334 SIGNAL(SIGTRAP, bad_signal);
337 SIGNAL(SIGVTALRM, bad_signal);
340 SIGNAL(SIGXCPU, bad_signal);
343 SIGNAL(SIGXFSZ, bad_signal);
347 * Apparently we can get a SIGPIPE when we call syslog, if
348 * syslogd has died and been restarted. Ignoring it seems
351 signal(SIGPIPE, SIG_IGN);
354 * If we're doing dial-on-demand, set up the interface now.
358 * Open the loopback channel and set it up to be the ppp interface.
362 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
363 (void) sprintf(ifname, "ppp%d", ifunit);
365 /* write pid to file */
366 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
367 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
368 fprintf(pidfile, "%d\n", pid);
369 (void) fclose(pidfile);
371 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
376 * Configure the interface and mark it up, etc.
387 * Don't do anything until we see some activity.
389 phase = PHASE_DORMANT;
393 wait_loop_output(timeleft(&timo));
400 if (get_loop_output())
406 * Now we want to bring up the link.
409 syslog(LOG_INFO, "Starting link");
413 * Lock the device if we've been asked to.
415 if (lockflag && !default_device) {
416 if (lock(devnam) < 0)
422 * Open the serial device and set it up to be the ppp interface.
423 * First we open it in non-blocking mode so we can set the
424 * various termios flags appropriately. If we aren't dialling
425 * out and we want to use the modem lines, we reopen it later
426 * in order to wait for the carrier detect signal from the modem.
428 while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
430 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
431 if (!persist || errno != EINTR)
434 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
435 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
437 "Couldn't reset non-blocking mode on device: %m");
443 * Do the equivalent of `mesg n' to stop broadcast messages.
445 if (fstat(ttyfd, &statbuf) < 0
446 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
448 "Couldn't restrict write permissions to %s: %m", devnam);
450 tty_mode = statbuf.st_mode;
452 /* run connection script */
453 if (connector && connector[0]) {
454 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
457 * Set line speed, flow control, etc.
458 * On most systems we set CLOCAL for now so that we can talk
459 * to the modem before carrier comes up. But this has the
460 * side effect that we might miss it if CD drops before we
461 * get to clear CLOCAL below. On systems where we can talk
462 * successfully to the modem with CLOCAL clear and CD down,
463 * we can clear CLOCAL at this point.
465 set_up_tty(ttyfd, 1);
467 /* drop dtr to hang up in case modem is off hook */
468 if (!default_device && modem) {
469 setdtr(ttyfd, FALSE);
474 if (device_script(connector, ttyfd, ttyfd) < 0) {
475 syslog(LOG_ERR, "Connect script failed");
476 setdtr(ttyfd, FALSE);
481 syslog(LOG_INFO, "Serial connection established.");
482 sleep(1); /* give it time to set up its terminal */
485 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
486 set_up_tty(ttyfd, 0);
488 /* reopen tty if necessary to wait for carrier */
489 if (connector == NULL && modem) {
490 while ((i = open(devnam, O_RDWR)) < 0) {
492 syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
493 if (!persist || errno != EINTR || hungup || kill_link)
499 /* run welcome script, if any */
500 if (welcomer && welcomer[0]) {
501 if (device_script(welcomer, ttyfd, ttyfd) < 0)
502 syslog(LOG_WARNING, "Welcome script failed");
505 /* set up the serial device as a ppp interface */
506 establish_ppp(ttyfd);
510 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
511 (void) sprintf(ifname, "ppp%d", ifunit);
513 /* write pid to file */
514 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
515 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
516 fprintf(pidfile, "%d\n", pid);
517 (void) fclose(pidfile);
519 syslog(LOG_ERR, "Failed to create pid file %s: %m",
526 * Start opening the connection and wait for
527 * incoming events (reply, timeout, etc.).
529 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
531 lcp_open(0); /* Start protocol */
532 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
533 wait_input(timeleft(&timo));
537 lcp_close(0, "User request");
541 if (phase == PHASE_NETWORK) {
542 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
543 (*ccp_protent.open)(0);
547 reap_kids(); /* Don't leave dead kids lying around */
551 * If we may want to bring the link up again, transfer
552 * the ppp unit back to the loopback. Set the
553 * real serial device back to its normal mode of operation.
558 disestablish_ppp(ttyfd);
561 * Run disconnector script, if requested.
562 * XXX we may not be able to do this if the line has hung up!
564 if (disconnector && !hungup) {
565 set_up_tty(ttyfd, 1);
566 if (device_script(disconnector, ttyfd, ttyfd) < 0) {
567 syslog(LOG_WARNING, "disconnect script failed");
569 syslog(LOG_INFO, "Serial link disconnected.");
582 if (pidfilename[0] != 0
583 && unlink(pidfilename) < 0 && errno != ENOENT)
584 syslog(LOG_WARNING, "unable to delete pid file: %m");
593 if (holdoff > 0 && need_holdoff) {
594 phase = PHASE_HOLDOFF;
595 TIMEOUT(holdoff_end, NULL, holdoff);
597 wait_time(timeleft(&timo));
603 phase = PHASE_DORMANT; /* allow signal to end holdoff */
606 } while (phase == PHASE_HOLDOFF);
615 * holdoff_end - called via a timeout when the holdoff period ends.
621 phase = PHASE_DORMANT;
625 * get_input - called when incoming data is available.
633 struct protent *protp;
635 p = inpacket_buf; /* point to beginning of packet buffer */
637 len = read_packet(inpacket_buf);
642 syslog(LOG_NOTICE, "Modem hangup");
644 lcp_lowerdown(0); /* serial link is no longer available */
649 if (debug /*&& (debugflags & DBG_INPACKET)*/)
650 log_packet(p, len, "rcvd ", LOG_DEBUG);
652 if (len < PPP_HDRLEN) {
653 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
657 p += 2; /* Skip address and control */
658 GETSHORT(protocol, p);
662 * Toss all non-LCP packets unless LCP is OPEN.
664 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
666 "get_input: Received non-LCP packet when LCP not open."));
671 * Until we get past the authentication phase, toss all packets
672 * except LCP, LQR and authentication packets.
674 if (phase <= PHASE_AUTHENTICATE
675 && !(protocol == PPP_LCP || protocol == PPP_LQR
676 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
677 MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
683 * Upcall the proper protocol input routine.
685 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
686 if (protp->protocol == protocol && protp->enabled_flag) {
687 (*protp->input)(0, p, len);
690 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
691 && protp->datainput != NULL) {
692 (*protp->datainput)(0, p, len);
698 syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
699 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
704 * quit - Clean up state and exit (with an error indication).
713 * die - like quit, except we can specify an exit status.
720 syslog(LOG_INFO, "Exit.");
725 * cleanup - restore anything which needs to be restored before we exit
736 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
737 syslog(LOG_WARNING, "unable to delete pid file: %m");
745 * close_tty - restore the terminal device and close it.
750 disestablish_ppp(ttyfd);
752 /* drop dtr to hang up */
754 setdtr(ttyfd, FALSE);
756 * This sleep is in case the serial port has CLOCAL set by default,
757 * and consequently will reassert DTR when we close the device.
764 if (tty_mode != (mode_t) -1)
765 chmod(devnam, tty_mode);
773 struct timeval c_time; /* time at which to call routine */
774 void *c_arg; /* argument to routine */
775 void (*c_func) __P((void *)); /* routine */
776 struct callout *c_next;
779 static struct callout *callout = NULL; /* Callout list */
780 static struct timeval timenow; /* Current time */
783 * timeout - Schedule a timeout.
785 * Note that this timeout takes the number of seconds, NOT hz (as in
789 timeout(func, arg, time)
790 void (*func) __P((void *));
794 struct callout *newp, *p, **pp;
796 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
797 (long) func, (long) arg, time));
802 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
803 syslog(LOG_ERR, "Out of memory in timeout()!");
808 gettimeofday(&timenow, NULL);
809 newp->c_time.tv_sec = timenow.tv_sec + time;
810 newp->c_time.tv_usec = timenow.tv_usec;
813 * Find correct place and link it in.
815 for (pp = &callout; (p = *pp); pp = &p->c_next)
816 if (newp->c_time.tv_sec < p->c_time.tv_sec
817 || (newp->c_time.tv_sec == p->c_time.tv_sec
818 && newp->c_time.tv_usec < p->c_time.tv_sec))
826 * untimeout - Unschedule a timeout.
830 void (*func) __P((void *));
833 struct callout **copp, *freep;
835 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
838 * Find first matching timeout and remove it from the list.
840 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
841 if (freep->c_func == func && freep->c_arg == arg) {
842 *copp = freep->c_next;
843 (void) free((char *) freep);
850 * calltimeout - Call any timeout routines which are now due.
857 while (callout != NULL) {
860 if (gettimeofday(&timenow, NULL) < 0) {
861 syslog(LOG_ERR, "Failed to get time of day: %m");
864 if (!(p->c_time.tv_sec < timenow.tv_sec
865 || (p->c_time.tv_sec == timenow.tv_sec
866 && p->c_time.tv_usec <= timenow.tv_usec)))
867 break; /* no, it's not time yet */
870 (*p->c_func)(p->c_arg);
878 * timeleft - return the length of time until the next timeout is due.
880 static struct timeval *
887 gettimeofday(&timenow, NULL);
888 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
889 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
890 if (tvp->tv_usec < 0) {
891 tvp->tv_usec += 1000000;
895 tvp->tv_sec = tvp->tv_usec = 0;
902 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
908 struct sigaction act, oldact;
910 act.sa_handler = SIG_IGN;
913 sigaction(sig, &act, &oldact);
914 sigaction(sig, &oldact, NULL);
919 * hup - Catch SIGHUP signal.
921 * Indicates that the physical layer has been disconnected.
922 * We don't rely on this indication; if the user has sent this
923 * signal, we just take the link down.
929 syslog(LOG_INFO, "Hangup (SIGHUP)");
932 /* Send the signal to the [dis]connector process(es) also */
938 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
940 * Indicates that we should initiate a graceful disconnect and exit.
947 syslog(LOG_INFO, "Terminating on signal %d.", sig);
948 persist = 0; /* don't try to restart */
951 /* Send the signal to the [dis]connector process(es) also */
957 * chld - Catch SIGCHLD signal.
958 * Calls reap_kids to get status for any dead kids.
969 * toggle_debug - Catch SIGUSR1 signal.
980 setlogmask(LOG_UPTO(LOG_DEBUG));
982 setlogmask(LOG_UPTO(LOG_WARNING));
988 * open_ccp - Catch SIGUSR2 signal.
990 * Try to (re)negotiate compression.
1002 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1008 syslog(LOG_ERR, "Fatal signal %d", sig);
1010 kill_my_pg(SIGTERM);
1016 * device_script - run a program to connect or disconnect the
1020 device_script(program, in, out)
1033 syslog(LOG_ERR, "Failed to create child process: %m");
1058 if (redirect_stderr) {
1060 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
1061 if (errfd >= 0 && errfd != 2) {
1068 execl("/bin/sh", "sh", "-c", program, (char *)0);
1069 syslog(LOG_ERR, "could not exec /bin/sh: %m");
1074 while (waitpid(pid, &status, 0) < 0) {
1077 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1082 return (status == 0 ? 0 : -1);
1087 * run-program - execute a program with given arguments,
1088 * but don't wait for it.
1089 * If the program can't be executed, logs an error unless
1090 * must_exist is 0 and the program file doesn't exist.
1093 run_program(prog, args, must_exist)
1103 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1109 /* Leave the current location */
1110 (void) setsid(); /* No controlling tty. */
1111 (void) umask (S_IRWXG|S_IRWXO);
1112 (void) chdir ("/"); /* no current directory. */
1116 /* Ensure that nothing of our device environment is inherited. */
1122 close (ttyfd); /* tty interface to the ppp device */
1124 /* Don't pass handles to the PPP device, even by accident. */
1125 new_fd = open (_PATH_DEVNULL, O_RDWR);
1128 dup2 (new_fd, 0); /* stdin <- /dev/null */
1131 dup2 (0, 1); /* stdout -> /dev/null */
1132 dup2 (0, 2); /* stderr -> /dev/null */
1136 /* Force the priority back to zero if pppd is running higher. */
1137 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1138 syslog (LOG_WARNING, "can't reset priority to 0: %m");
1141 /* SysV recommends a second fork at this point. */
1143 /* run the program; give it a null environment */
1145 execve(prog, args, nullenv);
1146 if (must_exist || errno != ENOENT)
1147 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1150 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1157 * reap_kids - get status from any dead child processes,
1158 * and log a message for abnormal terminations.
1165 if (n_children == 0)
1167 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1168 if (errno != ECHILD)
1169 syslog(LOG_ERR, "Error waiting for child process: %m");
1174 if (WIFSIGNALED(status)) {
1175 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1176 pid, WTERMSIG(status));
1183 * log_packet - format a packet and log it.
1186 char line[256]; /* line to be logged accumulated here */
1190 log_packet(p, len, prefix, level)
1196 strcpy(line, prefix);
1197 linep = line + strlen(line);
1198 format_packet(p, len, pr_log, NULL);
1200 syslog(level, "%s", line);
1204 * format_packet - make a readable representation of a packet,
1205 * calling `printer(arg, format, ...)' to output it.
1208 format_packet(p, len, printer, arg)
1211 void (*printer) __P((void *, char *, ...));
1217 struct protent *protp;
1219 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1223 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1224 if (proto == protp->protocol)
1226 if (protp != NULL) {
1227 printer(arg, "[%s", protp->name);
1228 n = (*protp->printpkt)(p, len, printer, arg);
1233 printer(arg, "[proto=0x%x]", proto);
1237 for (; len > 0; --len) {
1239 printer(arg, " %.2x", x);
1244 pr_log __V((void *arg, char *fmt, ...))
1251 va_start(pvar, fmt);
1256 arg = va_arg(pvar, void *);
1257 fmt = va_arg(pvar, char *);
1260 vsprintf(buf, fmt, pvar);
1264 if (linep + n + 1 > line + sizeof(line)) {
1265 syslog(LOG_DEBUG, "%s", line);
1273 * print_string - print a readable representation of a string using
1277 print_string(p, len, printer, arg)
1280 void (*printer) __P((void *, char *, ...));
1286 for (; len > 0; --len) {
1288 if (' ' <= c && c <= '~') {
1289 if (c == '\\' || c == '"')
1291 printer(arg, "%c", c);
1295 printer(arg, "\\n");
1298 printer(arg, "\\r");
1301 printer(arg, "\\t");
1304 printer(arg, "\\%.3o", c);
1312 * novm - log an error message saying we ran out of memory, and die.
1318 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1323 * fmtmsg - format a message into a buffer. Like sprintf except we
1324 * also specify the length of the output buffer, and we handle
1325 * %r (recursive format), %m (error message) and %I (IP address) formats.
1326 * Doesn't do floating-point formats.
1327 * Returns the number of chars put into buf.
1330 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1336 va_start(args, fmt);
1342 buf = va_arg(args, char *);
1343 buflen = va_arg(args, int);
1344 fmt = va_arg(args, char *);
1346 n = vfmtmsg(buf, buflen, fmt, args);
1352 * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1354 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1357 vfmtmsg(buf, buflen, fmt, args)
1364 int width, prec, fillch;
1365 int base, len, neg, quoted;
1366 unsigned long val = 0;
1367 char *str, *f, *buf0;
1371 static char hexchars[] = "0123456789abcdef";
1375 while (buflen > 0) {
1376 for (f = fmt; *f != '%' && *f != 0; ++f)
1382 memcpy(buf, fmt, len);
1397 width = va_arg(args, int);
1400 while (isdigit(c)) {
1401 width = width * 10 + c - '0';
1408 prec = va_arg(args, int);
1411 while (isdigit(c)) {
1412 prec = prec * 10 + c - '0';
1423 i = va_arg(args, int);
1432 val = va_arg(args, unsigned int);
1436 val = va_arg(args, unsigned int);
1440 val = (unsigned long) va_arg(args, void *);
1445 str = va_arg(args, char *);
1448 num[0] = va_arg(args, int);
1453 str = strerror(errno);
1456 str = ip_ntoa(va_arg(args, u_int32_t));
1459 f = va_arg(args, char *);
1461 n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1463 /* On the powerpc, a va_list is an array of 1 structure */
1464 n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1472 str += 4; /* chop off the day name */
1473 str[15] = 0; /* chop off year and newline */
1475 case 'v': /* "visible" string */
1476 case 'q': /* quoted string */
1478 p = va_arg(args, unsigned char *);
1479 if (fillch == '0' && prec > 0) {
1482 n = strlen((char *)p);
1483 if (prec > 0 && prec < n)
1486 while (n > 0 && buflen > 0) {
1489 if (!quoted && c >= 0x80) {
1494 if (quoted && (c == '"' || c == '\\'))
1496 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1500 case '\t': OUTCHAR('t'); break;
1501 case '\n': OUTCHAR('n'); break;
1502 case '\b': OUTCHAR('b'); break;
1503 case '\f': OUTCHAR('f'); break;
1506 OUTCHAR(hexchars[c >> 4]);
1507 OUTCHAR(hexchars[c & 0xf]);
1524 --fmt; /* so %z outputs %z etc. */
1529 str = num + sizeof(num);
1531 while (str > num + neg) {
1532 *--str = hexchars[val % base];
1534 if (--prec <= 0 && val == 0)
1546 len = num + sizeof(num) - 1 - str;
1549 if (prec > 0 && len > prec)
1555 if ((n = width - len) > 0) {
1563 memcpy(buf, str, len);