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.36 1996/09/14 05:15:41 paulus Exp $";
35 #include <sys/param.h>
36 #include <sys/types.h>
39 #include <sys/resource.h>
41 #include <sys/socket.h>
52 #include "pathnames.h"
53 #include "patchlevel.h"
56 extern char *strerror();
61 #endif /* IPX_CHANGE */
64 char ifname[IFNAMSIZ]; /* Interface name */
65 int ifunit; /* Interface unit number */
67 char *progname; /* Name of this program */
68 char hostname[MAXNAMELEN]; /* Our hostname */
69 static char pidfilename[MAXPATHLEN]; /* name of pid file */
70 static char default_devnam[MAXPATHLEN]; /* name of default device */
71 static pid_t pid; /* Our pid */
72 static uid_t uid; /* Our real user-id */
73 static int conn_running; /* we have a [dis]connector running */
75 int ttyfd = -1; /* Serial port file descriptor */
76 mode_t tty_mode = -1; /* Original access permissions to tty */
77 int baud_rate; /* Actual bits/second for serial device */
78 int hungup; /* terminal has been hung up */
79 int privileged; /* we're running as real uid root */
80 int need_holdoff; /* need holdoff period before restarting */
82 int phase; /* where the link is at */
85 int redirect_stderr; /* Connector's stderr should go to file */
87 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
88 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
90 static int n_children; /* # child processes still running */
92 static int locked; /* lock() has succeeded */
94 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
96 /* Prototypes for procedures local to this file. */
98 static void cleanup __P((void));
99 static void close_tty __P((void));
100 static void get_input __P((void));
101 static void connect_time_expired __P((caddr_t));
102 static void calltimeout __P((void));
103 static struct timeval *timeleft __P((struct timeval *));
104 static void hup __P((int));
105 static void term __P((int));
106 static void chld __P((int));
107 static void toggle_debug __P((int));
108 static void open_ccp __P((int));
109 static void bad_signal __P((int));
110 static void holdoff_end __P((void *));
111 static int device_script __P((char *, int, int));
112 static void reap_kids __P((void));
113 static void pr_log __P((void *, char *, ...));
115 extern char *ttyname __P((int));
116 extern char *getlogin __P((void));
120 #define O_NONBLOCK O_NDELAY
123 #ifdef PRIMITIVE_SYSLOG
124 #define setlogmask(x)
128 * PPP Data Link Layer "protocol" table.
129 * One entry per supported protocol.
130 * The last entry must be NULL.
132 struct protent *protocols[] = {
149 int i, nonblock, fdflags;
156 struct protent *protp;
159 phase = PHASE_INITIALIZE;
163 strcpy(default_devnam, devnam);
165 /* Initialize syslog facilities */
166 #ifdef PRIMITIVE_SYSLOG
167 openlog("pppd", LOG_PID);
169 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
170 setlogmask(LOG_UPTO(LOG_INFO));
173 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
174 syslog(LOG_ERR, "couldn't get hostname: %m");
177 hostname[MAXNAMELEN-1] = 0;
180 privileged = uid == 0;
183 * Initialize to the standard option set, then parse, in order,
184 * the system options file, the user's options file,
185 * the tty's options file, and the command line arguments.
187 for (i = 0; (protp = protocols[i]) != NULL; ++i)
192 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
193 || !options_from_user())
195 scan_args(argc-1, argv+1); /* look for tty name on command line */
196 if (!options_for_tty()
197 || !parse_args(argc-1, argv+1))
200 if (!ppp_available()) {
201 option_error(no_ppp_msg);
206 * Check that the options given are valid and consistent.
209 auth_check_options();
210 for (i = 0; (protp = protocols[i]) != NULL; ++i)
211 if (protp->check_options != NULL)
212 (*protp->check_options)();
213 if (demand && connector == 0) {
214 option_error("connect script required for demand-dialling\n");
219 * If the user has specified the default device name explicitly,
220 * pretend they hadn't.
222 if (!default_device && strcmp(devnam, default_devnam) == 0)
224 redirect_stderr = !nodetach || default_device;
227 * Initialize system-dependent stuff and magic number package.
232 setlogmask(LOG_UPTO(LOG_DEBUG));
235 * Detach ourselves from the terminal, if required,
236 * and identify who is running us.
238 if (!default_device && !nodetach && daemon(0, 0) < 0) {
239 perror("Couldn't detach from controlling terminal");
246 if (pw != NULL && pw->pw_name != NULL)
251 syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
252 VERSION, PATCHLEVEL, p, uid);
255 * Compute mask of all interesting signals and install signal handlers
256 * for each. Only one signal handler may be active at a time. Therefore,
257 * all other signals should be masked when any handler is executing.
260 sigaddset(&mask, SIGHUP);
261 sigaddset(&mask, SIGINT);
262 sigaddset(&mask, SIGTERM);
263 sigaddset(&mask, SIGCHLD);
265 #define SIGNAL(s, handler) { \
266 sa.sa_handler = handler; \
267 if (sigaction(s, &sa, NULL) < 0) { \
268 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
275 SIGNAL(SIGHUP, hup); /* Hangup */
276 SIGNAL(SIGINT, term); /* Interrupt */
277 SIGNAL(SIGTERM, term); /* Terminate */
278 SIGNAL(SIGCHLD, chld);
280 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
281 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
284 * Install a handler for other signals which would otherwise
285 * cause pppd to exit without cleaning up.
287 SIGNAL(SIGABRT, bad_signal);
288 SIGNAL(SIGALRM, bad_signal);
289 SIGNAL(SIGFPE, bad_signal);
290 SIGNAL(SIGILL, bad_signal);
291 SIGNAL(SIGPIPE, bad_signal);
292 SIGNAL(SIGQUIT, bad_signal);
293 SIGNAL(SIGSEGV, bad_signal);
295 SIGNAL(SIGBUS, bad_signal);
298 SIGNAL(SIGEMT, bad_signal);
301 SIGNAL(SIGPOLL, bad_signal);
304 SIGNAL(SIGPROF, bad_signal);
307 SIGNAL(SIGSYS, bad_signal);
310 SIGNAL(SIGTRAP, bad_signal);
313 SIGNAL(SIGVTALRM, bad_signal);
316 SIGNAL(SIGXCPU, bad_signal);
319 SIGNAL(SIGXFSZ, bad_signal);
323 * Apparently we can get a SIGPIPE when we call syslog, if
324 * syslogd has died and been restarted. Ignoring it seems
327 signal(SIGPIPE, SIG_IGN);
330 * If we're doing dial-on-demand, set up the interface now.
334 * Open the loopback channel and set it up to be the ppp interface.
338 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
339 (void) sprintf(ifname, "ppp%d", ifunit);
341 /* write pid to file */
342 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
343 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
344 fprintf(pidfile, "%d\n", pid);
345 (void) fclose(pidfile);
347 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
352 * Configure the interface and mark it up, etc.
363 * Don't do anything until we see some activity.
365 phase = PHASE_DORMANT;
369 wait_loop_output(timeleft(&timo));
376 if (get_loop_output())
382 * Now we want to bring up the link.
385 syslog(LOG_INFO, "Starting link");
389 * Lock the device if we've been asked to.
391 if (lockflag && !default_device) {
392 if (lock(devnam) < 0)
398 * Open the serial device and set it up to be the ppp interface.
399 * If we're dialling out, or we don't want to use the modem lines,
400 * we open it in non-blocking mode, but then we need to clear
401 * the non-blocking I/O bit.
403 nonblock = (connector || !modem)? O_NONBLOCK: 0;
404 if ((ttyfd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
405 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
409 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
410 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
412 "Couldn't reset non-blocking mode on device: %m");
418 * Do the equivalent of `mesg n' to stop broadcast messages.
420 if (fstat(ttyfd, &statbuf) < 0
421 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
423 "Couldn't restrict write permissions to %s: %m", devnam);
425 tty_mode = statbuf.st_mode;
427 /* run connection script */
428 if (connector && connector[0]) {
429 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
431 /* set line speed, flow control, etc.; set CLOCAL for now */
432 set_up_tty(ttyfd, 1);
434 /* drop dtr to hang up in case modem is off hook */
435 if (!default_device && modem) {
436 setdtr(ttyfd, FALSE);
441 if (device_script(connector, ttyfd, ttyfd) < 0) {
442 syslog(LOG_ERR, "Connect script failed");
443 setdtr(ttyfd, FALSE);
447 syslog(LOG_INFO, "Serial connection established.");
448 sleep(1); /* give it time to set up its terminal */
451 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
452 set_up_tty(ttyfd, 0);
454 /* run welcome script, if any */
455 if (welcomer && welcomer[0]) {
456 if (device_script(welcomer, ttyfd, ttyfd) < 0)
457 syslog(LOG_WARNING, "Welcome script failed");
460 /* set up the serial device as a ppp interface */
461 establish_ppp(ttyfd);
465 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
466 (void) sprintf(ifname, "ppp%d", ifunit);
468 /* write pid to file */
469 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
470 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
471 fprintf(pidfile, "%d\n", pid);
472 (void) fclose(pidfile);
474 syslog(LOG_ERR, "Failed to create pid file %s: %m",
481 * Set a timeout to close the connection once the maximum
482 * connect time has expired.
485 TIMEOUT(connect_time_expired, 0, maxconnect);
488 * Start opening the connection and wait for
489 * incoming events (reply, timeout, etc.).
491 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
493 lcp_open(0); /* Start protocol */
494 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
495 wait_input(timeleft(&timo));
499 lcp_close(0, "User request");
503 if (phase == PHASE_NETWORK) {
504 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
505 (*ccp_protent.open)(0);
509 reap_kids(); /* Don't leave dead kids lying around */
513 * If we may want to bring the link up again, transfer
514 * the ppp unit back to the loopback. Set the
515 * real serial device back to its normal mode of operation.
519 disestablish_ppp(ttyfd);
524 disestablish_ppp(ttyfd);
528 * Run disconnector script, if requested.
529 * XXX we may not be able to do this if the line has hung up!
531 if (disconnector && !hungup) {
532 set_up_tty(ttyfd, 1);
533 if (device_script(disconnector, ttyfd, ttyfd) < 0) {
534 syslog(LOG_WARNING, "disconnect script failed");
536 syslog(LOG_INFO, "Serial link disconnected.");
548 if (pidfilename[0] != 0
549 && unlink(pidfilename) < 0 && errno != ENOENT)
550 syslog(LOG_WARNING, "unable to delete pid file: %m");
559 if (holdoff > 0 && need_holdoff) {
560 phase = PHASE_HOLDOFF;
561 TIMEOUT(holdoff_end, NULL, holdoff);
563 wait_time(timeleft(&timo));
569 phase = PHASE_DORMANT; /* allow signal to end holdoff */
572 } while (phase == PHASE_HOLDOFF);
580 * holdoff_end - called via a timeout when the holdoff period ends.
586 phase = PHASE_DORMANT;
590 * get_input - called when incoming data is available.
598 struct protent *protp;
600 p = inpacket_buf; /* point to beginning of packet buffer */
602 len = read_packet(inpacket_buf);
607 syslog(LOG_NOTICE, "Modem hangup");
609 lcp_lowerdown(0); /* serial link is no longer available */
614 if (debug /*&& (debugflags & DBG_INPACKET)*/)
615 log_packet(p, len, "rcvd ");
617 if (len < PPP_HDRLEN) {
618 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
622 p += 2; /* Skip address and control */
623 GETSHORT(protocol, p);
627 * Toss all non-LCP packets unless LCP is OPEN.
629 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
631 "io(): Received non-LCP packet when LCP not open."));
636 * Upcall the proper protocol input routine.
638 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
639 if (protp->protocol == protocol && protp->enabled_flag) {
640 (*protp->input)(0, p, len);
643 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
644 && protp->datainput != NULL) {
645 (*protp->datainput)(0, p, len);
651 syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
652 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
657 * quit - Clean up state and exit (with an error indication).
666 * die - like quit, except we can specify an exit status.
673 syslog(LOG_INFO, "Exit.");
678 * connect_time_expired - log a message and close the connection.
681 connect_time_expired(arg)
684 syslog(LOG_INFO, "Connect time expired");
685 lcp_close(0, "Connect time expired"); /* Close connection */
689 * cleanup - restore anything which needs to be restored before we exit
700 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
701 syslog(LOG_WARNING, "unable to delete pid file: %m");
709 * close_tty - restore the terminal device and close it.
714 disestablish_ppp(ttyfd);
716 /* drop dtr to hang up */
718 setdtr(ttyfd, FALSE);
720 * This sleep is in case the serial port has CLOCAL set by default,
721 * and consequently will reassert DTR when we close the device.
728 if (tty_mode != (mode_t) -1)
729 chmod(devnam, tty_mode);
737 struct timeval c_time; /* time at which to call routine */
738 caddr_t c_arg; /* argument to routine */
739 void (*c_func)(); /* routine */
740 struct callout *c_next;
743 static struct callout *callout = NULL; /* Callout list */
744 static struct timeval timenow; /* Current time */
747 * timeout - Schedule a timeout.
749 * Note that this timeout takes the number of seconds, NOT hz (as in
753 timeout(func, arg, time)
758 struct callout *newp, *p, **pp;
760 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
761 (long) func, (long) arg, time));
766 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
767 syslog(LOG_ERR, "Out of memory in timeout()!");
772 gettimeofday(&timenow, NULL);
773 newp->c_time.tv_sec = timenow.tv_sec + time;
774 newp->c_time.tv_usec = timenow.tv_usec;
777 * Find correct place and link it in.
779 for (pp = &callout; (p = *pp); pp = &p->c_next)
780 if (newp->c_time.tv_sec < p->c_time.tv_sec
781 || (newp->c_time.tv_sec == p->c_time.tv_sec
782 && newp->c_time.tv_usec < p->c_time.tv_sec))
790 * untimeout - Unschedule a timeout.
797 struct callout **copp, *freep;
799 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
802 * Find first matching timeout and remove it from the list.
804 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
805 if (freep->c_func == func && freep->c_arg == arg) {
806 *copp = freep->c_next;
807 (void) free((char *) freep);
814 * calltimeout - Call any timeout routines which are now due.
821 while (callout != NULL) {
824 if (gettimeofday(&timenow, NULL) < 0) {
825 syslog(LOG_ERR, "Failed to get time of day: %m");
828 if (!(p->c_time.tv_sec < timenow.tv_sec
829 || (p->c_time.tv_sec == timenow.tv_sec
830 && p->c_time.tv_usec <= timenow.tv_usec)))
831 break; /* no, it's not time yet */
834 (*p->c_func)(p->c_arg);
842 * timeleft - return the length of time until the next timeout is due.
844 static struct timeval *
851 gettimeofday(&timenow, NULL);
852 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
853 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
854 if (tvp->tv_usec < 0) {
855 tvp->tv_usec += 1000000;
859 tvp->tv_sec = tvp->tv_usec = 0;
866 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
872 struct sigaction act, oldact;
874 act.sa_handler = SIG_IGN;
876 sigaction(sig, &act, &oldact);
877 kill(-getpgrp(), sig);
878 sigaction(sig, &oldact, NULL);
883 * hup - Catch SIGHUP signal.
885 * Indicates that the physical layer has been disconnected.
886 * We don't rely on this indication; if the user has sent this
887 * signal, we just take the link down.
893 syslog(LOG_INFO, "Hangup (SIGHUP)");
896 /* Send the signal to the [dis]connector process(es) also */
902 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
904 * Indicates that we should initiate a graceful disconnect and exit.
911 syslog(LOG_INFO, "Terminating on signal %d.", sig);
912 persist = 0; /* don't try to restart */
915 /* Send the signal to the [dis]connector process(es) also */
921 * chld - Catch SIGCHLD signal.
922 * Calls reap_kids to get status for any dead kids.
933 * toggle_debug - Catch SIGUSR1 signal.
944 setlogmask(LOG_UPTO(LOG_DEBUG));
946 setlogmask(LOG_UPTO(LOG_WARNING));
952 * open_ccp - Catch SIGUSR2 signal.
954 * Try to (re)negotiate compression.
966 * bad_signal - We've caught a fatal signal. Clean up state and exit.
972 syslog(LOG_ERR, "Fatal signal %d", sig);
980 * device_script - run a program to connect or disconnect the
984 device_script(program, in, out)
997 syslog(LOG_ERR, "Failed to create child process: %m");
1022 if (redirect_stderr) {
1024 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
1025 if (errfd >= 0 && errfd != 2) {
1032 execl("/bin/sh", "sh", "-c", program, (char *)0);
1033 syslog(LOG_ERR, "could not exec /bin/sh: %m");
1038 while (waitpid(pid, &status, 0) < 0) {
1041 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1046 return (status == 0 ? 0 : -1);
1051 * run-program - execute a program with given arguments,
1052 * but don't wait for it.
1053 * If the program can't be executed, logs an error unless
1054 * must_exist is 0 and the program file doesn't exist.
1057 run_program(prog, args, must_exist)
1067 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1073 /* Leave the current location */
1074 (void) setsid(); /* No controlling tty. */
1075 (void) umask (S_IRWXG|S_IRWXO);
1076 (void) chdir ("/"); /* no current directory. */
1080 /* Ensure that nothing of our device environment is inherited. */
1086 close (ttyfd); /* tty interface to the ppp device */
1088 /* Don't pass handles to the PPP device, even by accident. */
1089 new_fd = open (_PATH_DEVNULL, O_RDWR);
1092 dup2 (new_fd, 0); /* stdin <- /dev/null */
1095 dup2 (0, 1); /* stdout -> /dev/null */
1096 dup2 (0, 2); /* stderr -> /dev/null */
1100 /* Force the priority back to zero if pppd is running higher. */
1101 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1102 syslog (LOG_WARNING, "can't reset priority to 0: %m");
1105 /* SysV recommends a second fork at this point. */
1107 /* run the program; give it a null environment */
1109 execve(prog, args, nullenv);
1110 if (must_exist || errno != ENOENT)
1111 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1114 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1121 * reap_kids - get status from any dead child processes,
1122 * and log a message for abnormal terminations.
1129 if (n_children == 0)
1131 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1132 if (errno != ECHILD)
1133 syslog(LOG_ERR, "Error waiting for child process: %m");
1138 if (WIFSIGNALED(status)) {
1139 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1140 pid, WTERMSIG(status));
1147 * log_packet - format a packet and log it.
1150 char line[256]; /* line to be logged accumulated here */
1154 log_packet(p, len, prefix)
1159 strcpy(line, prefix);
1160 linep = line + strlen(line);
1161 format_packet(p, len, pr_log, NULL);
1163 syslog(LOG_DEBUG, "%s", line);
1167 * format_packet - make a readable representation of a packet,
1168 * calling `printer(arg, format, ...)' to output it.
1171 format_packet(p, len, printer, arg)
1174 void (*printer) __P((void *, char *, ...));
1180 struct protent *protp;
1182 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1186 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1187 if (proto == protp->protocol)
1189 if (protp != NULL) {
1190 printer(arg, "[%s", protp->name);
1191 n = (*protp->printpkt)(p, len, printer, arg);
1196 printer(arg, "[proto=0x%x]", proto);
1200 for (; len > 0; --len) {
1202 printer(arg, " %.2x", x);
1207 pr_log __V((void *arg, char *fmt, ...))
1214 va_start(pvar, fmt);
1219 arg = va_arg(pvar, void *);
1220 fmt = va_arg(pvar, char *);
1223 vsprintf(buf, fmt, pvar);
1227 if (linep + n + 1 > line + sizeof(line)) {
1228 syslog(LOG_DEBUG, "%s", line);
1236 * print_string - print a readable representation of a string using
1240 print_string(p, len, printer, arg)
1243 void (*printer) __P((void *, char *, ...));
1249 for (; len > 0; --len) {
1251 if (' ' <= c && c <= '~') {
1252 if (c == '\\' || c == '"')
1254 printer(arg, "%c", c);
1258 printer(arg, "\\n");
1261 printer(arg, "\\r");
1264 printer(arg, "\\t");
1267 printer(arg, "\\%.3o", c);
1275 * novm - log an error message saying we ran out of memory, and die.
1281 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1286 * fmtmsg - format a message into a buffer. Like sprintf except we
1287 * also specify the length of the output buffer, and we handle
1288 * %r (recursive format), %m (error message) and %I (IP address) formats.
1289 * Doesn't do floating-point formats.
1290 * Returns the number of chars put into buf.
1293 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1299 va_start(args, fmt);
1305 buf = va_arg(args, char *);
1306 buflen = va_arg(args, int);
1307 fmt = va_arg(args, char *);
1309 n = vfmtmsg(buf, buflen, fmt, args);
1315 * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1317 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1320 vfmtmsg(char *buf, int buflen, char *fmt, va_list args)
1323 int width, prec, fillch;
1324 int base, len, neg, quoted;
1326 char *str, *f, *buf0;
1331 static char hexchars[16] = "0123456789abcdef";
1335 while (buflen > 0) {
1336 for (f = fmt; *f != '%' && *f != 0; ++f)
1342 memcpy(buf, fmt, len);
1357 width = va_arg(args, int);
1360 while (isdigit(c)) {
1361 width = width * 10 + c - '0';
1368 prec = va_arg(args, int);
1371 while (isdigit(c)) {
1372 prec = prec * 10 + c - '0';
1383 i = va_arg(args, int);
1392 val = va_arg(args, unsigned int);
1396 val = va_arg(args, unsigned int);
1400 val = (unsigned long) va_arg(args, void *);
1405 str = va_arg(args, char *);
1408 num[0] = va_arg(args, int);
1413 str = strerror(errno);
1416 str = ip_ntoa(va_arg(args, u_int32_t));
1419 f = va_arg(args, char *);
1421 * XXX We assume a va_list is either a pointer or an array, so
1422 * what gets passed for a va_list is like a void * in some sense.
1424 a = va_arg(args, void *);
1425 n = vfmtmsg(buf, buflen + 1, f, a);
1432 str += 4; /* chop off the day name */
1433 str[15] = 0; /* chop off year and newline */
1435 case 'v': /* "visible" string */
1436 case 'q': /* quoted string */
1438 p = va_arg(args, unsigned char *);
1439 if (fillch == '0' && prec > 0) {
1442 n = strlen((char *)p);
1443 if (prec > 0 && prec < n)
1446 while (n > 0 && buflen > 0) {
1449 if (!quoted && c >= 0x80) {
1454 if (quoted && (c == '"' || c == '\\'))
1456 if (c < 0x20 || 0x7f <= c && c < 0xa0) {
1460 case '\t': OUTCHAR('t'); break;
1461 case '\n': OUTCHAR('n'); break;
1462 case '\b': OUTCHAR('b'); break;
1463 case '\f': OUTCHAR('f'); break;
1466 OUTCHAR(hexchars[c >> 4]);
1467 OUTCHAR(hexchars[c & 0xf]);
1484 --fmt; /* so %z outputs %z etc. */
1489 str = num + sizeof(num);
1491 while (str > num + neg) {
1492 *--str = hexchars[val % base];
1494 if (--prec <= 0 && val == 0)
1506 len = num + sizeof(num) - 1 - str;
1509 if (prec > 0 && len > prec)
1515 if ((n = width - len) > 0) {
1523 memcpy(buf, str, len);