2 * utils.c - various utility functions used in pppd.
4 * Copyright (c) 1999-2002 Paul Mackerras. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. The name(s) of the authors of this software must not be used to
14 * endorse or promote products derived from this software without
15 * prior written permission.
17 * 3. Redistributions of any form whatsoever must retain the following
19 * "This product includes software developed by Paul Mackerras
20 * <paulus@samba.org>".
22 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
23 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
24 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
25 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
27 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
28 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
49 #include <sys/param.h>
50 #include <sys/types.h>
53 #include <sys/resource.h>
55 #include <sys/socket.h>
56 #include <netinet/in.h>
58 #include <sys/mkdev.h>
64 #include "pathnames.h"
68 extern char *strerror();
71 static void logit(int, char *, va_list);
72 static void log_write(int, char *);
73 static void vslp_printer(void *, char *, ...);
74 static void format_packet(u_char *, int, printer_func, void *);
82 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
83 * always leaves destination null-terminated (for len > 0).
86 strlcpy(char *dest, const char *src, size_t len)
88 size_t ret = strlen(src);
94 strncpy(dest, src, len - 1);
102 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
103 * always leaves destination null-terminated (for len > 0).
106 strlcat(char *dest, const char *src, size_t len)
108 size_t dlen = strlen(dest);
110 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
115 * slprintf - format a message into a buffer. Like sprintf except we
116 * also specify the length of the output buffer, and we handle
117 * %m (error message), %v (visible string),
118 * %q (quoted string), %t (current time) and %I (IP address) formats.
119 * Doesn't do floating-point formats.
120 * Returns the number of chars put into buf.
123 slprintf(char *buf, int buflen, char *fmt, ...)
129 n = vslprintf(buf, buflen, fmt, args);
135 * vslprintf - like slprintf, takes a va_list instead of a list of args.
137 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
140 vslprintf(char *buf, int buflen, char *fmt, va_list args)
143 int width, prec, fillch;
144 int base, len, neg, quoted;
146 unsigned long val = 0;
147 char *str, *f, *buf0;
152 static char hexchars[] = "0123456789abcdef";
153 struct buffer_info bufinfo;
159 for (f = fmt; *f != '%' && *f != 0; ++f)
165 memcpy(buf, fmt, len);
181 width = va_arg(args, int);
185 width = width * 10 + c - '0';
192 prec = va_arg(args, int);
197 prec = prec * 10 + c - '0';
211 lval = va_arg(args, long);
220 val = va_arg(args, unsigned long);
226 --fmt; /* so %lz outputs %lz etc. */
231 i = va_arg(args, int);
240 val = va_arg(args, unsigned int);
244 val = va_arg(args, unsigned int);
249 val = va_arg(args, unsigned int);
253 val = (unsigned long) va_arg(args, void *);
258 str = va_arg(args, char *);
261 num[0] = va_arg(args, int);
266 str = strerror(errno);
269 ip = va_arg(args, u_int32_t);
271 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
272 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
278 str += 4; /* chop off the day name */
279 str[15] = 0; /* chop off year and newline */
281 case 'v': /* "visible" string */
282 case 'q': /* quoted string */
284 p = va_arg(args, unsigned char *);
286 p = (unsigned char *)"<NULL>";
287 if (fillch == '0' && prec >= 0) {
289 termch = -1; /* matches no unsigned char value */
292 if (prec != -1 && n > prec)
294 termch = 0; /* stop on null byte */
296 while (n > 0 && buflen > 0) {
301 if (!quoted && c >= 0x80) {
306 if (quoted && (c == '"' || c == '\\'))
308 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
312 case '\t': OUTCHAR('t'); break;
313 case '\n': OUTCHAR('n'); break;
314 case '\b': OUTCHAR('b'); break;
315 case '\f': OUTCHAR('f'); break;
318 OUTCHAR(hexchars[c >> 4]);
319 OUTCHAR(hexchars[c & 0xf]);
334 case 'P': /* print PPP packet */
336 bufinfo.len = buflen + 1;
337 p = va_arg(args, unsigned char *);
338 n = va_arg(args, int);
339 format_packet(p, n, vslp_printer, &bufinfo);
341 buflen = bufinfo.len - 1;
345 p = va_arg(args, unsigned char *);
346 for (n = prec; n > 0; --n) {
350 OUTCHAR(hexchars[(c >> 4) & 0xf]);
351 OUTCHAR(hexchars[c & 0xf]);
357 --fmt; /* so %z outputs %z etc. */
362 str = num + sizeof(num);
364 while (str > num + neg) {
365 *--str = hexchars[val % base];
367 if (--prec <= 0 && val == 0)
379 len = num + sizeof(num) - 1 - str;
381 for (len = 0; len < buflen && (prec == -1 || len < prec); ++len)
388 if ((n = width - len) > 0) {
396 memcpy(buf, str, len);
405 * vslp_printer - used in processing a %P format
408 vslp_printer(void *arg, char *fmt, ...)
412 struct buffer_info *bi;
416 bi = (struct buffer_info *) arg;
417 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
426 * log_packet - format a packet and log it.
430 log_packet(u_char *p, int len, char *prefix, int level)
432 init_pr_log(prefix, level);
433 format_packet(p, len, pr_log, &level);
440 * format_packet - make a readable representation of a packet,
441 * calling `printer(arg, format, ...)' to output it.
444 format_packet(u_char *p, int len, printer_func printer, void *arg)
448 struct protent *protp;
450 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
454 for (i = 0; (protp = protocols[i]) != NULL; ++i)
455 if (proto == protp->protocol)
458 printer(arg, "[%s", protp->name);
459 n = (*protp->printpkt)(p, len, printer, arg);
464 for (i = 0; (protp = protocols[i]) != NULL; ++i)
465 if (proto == (protp->protocol & ~0x8000))
467 if (protp != 0 && protp->data_name != 0) {
468 printer(arg, "[%s data]", protp->data_name);
470 printer(arg, "%.8B ...", p);
472 printer(arg, "%.*B", len, p);
475 printer(arg, "[proto=0x%x]", proto);
480 printer(arg, "%.32B ...", p);
482 printer(arg, "%.*B", len, p);
484 #endif /* UNIT_TEST */
487 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
490 static char line[256]; /* line to be logged accumulated here */
491 static char *linep; /* current pointer within line */
492 static int llevel; /* level for logging */
495 init_pr_log(const char *prefix, int level)
498 if (prefix != NULL) {
499 strlcpy(line, prefix, sizeof(line));
500 linep = line + strlen(line);
510 log_write(llevel, line);
515 * pr_log - printer routine for outputting to syslog
518 pr_log(void *arg, char *fmt, ...)
527 n = vslprintf(buf, sizeof(buf), fmt, pvar);
531 eol = strchr(buf, '\n');
533 l = (eol == NULL)? n: eol - buf;
534 if (linep + l < line + sizeof(line)) {
536 memcpy(linep, buf, l);
542 eol = strchr(p, '\n');
545 log_write(llevel, line);
549 while (eol != NULL) {
551 log_write(llevel, p);
553 eol = strchr(p, '\n');
556 /* assumes sizeof(buf) <= sizeof(line) */
565 * print_string - print a readable representation of a string using
569 print_string(char *p, int len, printer_func printer, void *arg)
574 for (; len > 0; --len) {
576 if (' ' <= c && c <= '~') {
577 if (c == '\\' || c == '"')
579 printer(arg, "%c", c);
592 printer(arg, "\\%.3o", (unsigned char) c);
600 * logit - does the hard work for fatal et al.
603 logit(int level, char *fmt, va_list args)
607 vslprintf(buf, sizeof(buf), fmt, args);
608 log_write(level, buf);
613 log_write(int level, char *buf)
615 syslog(level, "%s", buf);
616 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
619 if (n > 0 && buf[n-1] == '\n')
621 if (write(log_to_fd, buf, n) != n
622 || write(log_to_fd, "\n", 1) != 1)
628 log_write(int level, char *buf)
630 printf("<%d>: %s\n", level, buf);
635 * fatal - log an error message and die horribly.
638 fatal(char *fmt, ...)
644 logit(LOG_ERR, fmt, pvar);
648 die(1); /* as promised */
655 * error - log an error message.
658 error(char *fmt, ...)
664 logit(LOG_ERR, fmt, pvar);
670 * warn - log a warning message.
679 logit(LOG_WARNING, fmt, pvar);
684 * notice - log a notice-level message.
687 notice(char *fmt, ...)
693 logit(LOG_NOTICE, fmt, pvar);
698 * info - log an informational message.
707 logit(LOG_INFO, fmt, pvar);
712 * dbglog - log a debug message.
715 dbglog(char *fmt, ...)
721 logit(LOG_DEBUG, fmt, pvar);
726 * dump_packet - print out a packet in readable form if it is interesting.
727 * Assumes len >= PPP_HDRLEN.
730 dump_packet(const char *tag, unsigned char *p, int len)
738 * don't print LCP echo request/reply packets if debug <= 1
739 * and the link is up.
741 proto = (p[2] << 8) + p[3];
742 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
743 && len >= PPP_HDRLEN + HEADERLEN) {
744 unsigned char *lcp = p + PPP_HDRLEN;
745 int l = (lcp[2] << 8) + lcp[3];
747 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
748 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
752 dbglog("%s %P", tag, p, len);
758 * complete_read - read a full `count' bytes from fd,
759 * unless end-of-file or an error other than EINTR is encountered.
762 complete_read(int fd, void *buf, size_t count)
768 for (done = 0; done < count; ) {
769 nb = read(fd, ptr, count - done);
771 if (errno == EINTR && !got_sigterm)
784 /* Procedures for locking the serial device using a lock file. */
785 static char lock_file[MAXPATHLEN];
788 * lock - create a lock file for the named device
796 result = mklock (dev, (void *) 0);
798 strlcpy(lock_file, dev, sizeof(lock_file));
803 notice("Device %s is locked by pid %d", dev, result);
805 error("Can't create lock file %s", lock_file);
810 char lock_buffer[12];
816 if (stat(dev, &sbuf) < 0) {
817 error("Can't get device number for %s: %m", dev);
820 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
821 error("Can't lock %s: not a character device", dev);
824 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
825 PPP_PATH_LOCKDIR, major(sbuf.st_dev),
826 major(sbuf.st_rdev), minor(sbuf.st_rdev));
829 char lockdev[MAXPATHLEN];
831 if ((p = strstr(dev, "dev/")) != NULL) {
833 strncpy(lockdev, dev, MAXPATHLEN-1);
834 lockdev[MAXPATHLEN-1] = 0;
835 while ((p = strrchr(lockdev, '/')) != NULL) {
840 if ((p = strrchr(dev, '/')) != NULL)
843 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", PPP_PATH_LOCKDIR, dev);
846 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
847 if (errno != EEXIST) {
848 error("Can't create lock file %s: %m", lock_file);
852 /* Read the lock file to find out who has the device locked. */
853 fd = open(lock_file, O_RDONLY, 0);
855 if (errno == ENOENT) /* This is just a timing problem. */
857 error("Can't open existing lock file %s: %m", lock_file);
861 n = read(fd, lock_buffer, 11);
863 n = read(fd, &pid, sizeof(pid));
864 #endif /* LOCK_BINARY */
868 error("Can't read pid from lock file %s", lock_file);
872 /* See if the process still exists. */
875 pid = atoi(lock_buffer);
876 #endif /* LOCK_BINARY */
878 return 1; /* somebody else locked it for us */
880 || (kill(pid, 0) == -1 && errno == ESRCH)) {
881 if (unlink (lock_file) == 0) {
882 notice("Removed stale lock on %s (pid %d)", dev, pid);
885 warn("Couldn't remove stale lock on %s", dev);
887 notice("Device %s is locked by pid %d", dev, pid);
899 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
900 n = write (fd, lock_buffer, siz);
903 n = write(fd, &pid, siz);
906 error("Could not write pid to lock file when locking");
915 * relock - called to update our lockfile when we are about to detach,
916 * thus changing our pid (we fork, the child carries on, and the parent dies).
917 * Note that this is called by the parent, with pid equal to the pid
918 * of the child. This avoids a potential race which would exist if
919 * we had the child rewrite the lockfile (the parent might die first,
920 * and another process could think the lock was stale if it checked
921 * between when the parent died and the child rewrote the lockfile).
927 /* XXX is there a way to do this? */
932 char lock_buffer[12];
934 if (lock_file[0] == 0)
936 fd = open(lock_file, O_WRONLY, 0);
938 error("Couldn't reopen lock file %s: %m", lock_file);
945 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
946 n = write (fd, lock_buffer, siz);
949 n = write(fd, &pid, siz);
950 #endif /* LOCK_BINARY */
952 error("Could not write pid to lock file when locking");
961 * unlock - remove our lockfile
968 (void) rmlock(lock_file, (void *) 0);