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@ozlabs.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>
61 #include "pppd-private.h"
64 #include "pathnames.h"
68 extern char *strerror();
71 static void logit(int, const 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, const 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, const char *fmt, va_list args)
143 int width, prec, fillch;
144 int base, len, neg, quoted;
146 unsigned long val = 0;
153 static char hexchars[] = "0123456789abcdef";
154 struct buffer_info bufinfo;
160 for (f = fmt; *f != '%' && *f != 0; ++f)
166 memcpy(buf, fmt, len);
182 width = va_arg(args, int);
186 width = width * 10 + c - '0';
193 prec = va_arg(args, int);
198 prec = prec * 10 + c - '0';
212 lval = va_arg(args, long);
221 val = va_arg(args, unsigned long);
227 --fmt; /* so %lz outputs %lz etc. */
232 i = va_arg(args, int);
241 val = va_arg(args, unsigned int);
245 val = va_arg(args, unsigned int);
250 val = va_arg(args, unsigned int);
254 val = (unsigned long) va_arg(args, void *);
259 str = va_arg(args, char *);
262 num[0] = va_arg(args, int);
267 str = strerror(errno);
270 ip = va_arg(args, u_int32_t);
272 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
273 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
279 str += 4; /* chop off the day name */
280 str[15] = 0; /* chop off year and newline */
282 case 'v': /* "visible" string */
283 case 'q': /* quoted string */
285 p = va_arg(args, unsigned char *);
287 p = (unsigned char *)"<NULL>";
288 if (fillch == '0' && prec >= 0) {
290 termch = -1; /* matches no unsigned char value */
293 if (prec != -1 && n > prec)
295 termch = 0; /* stop on null byte */
297 while (n > 0 && buflen > 0) {
302 if (!quoted && c >= 0x80) {
307 if (quoted && (c == '"' || c == '\\'))
309 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
313 case '\t': OUTCHAR('t'); break;
314 case '\n': OUTCHAR('n'); break;
315 case '\b': OUTCHAR('b'); break;
316 case '\f': OUTCHAR('f'); break;
319 OUTCHAR(hexchars[c >> 4]);
320 OUTCHAR(hexchars[c & 0xf]);
335 case 'P': /* print PPP packet */
337 bufinfo.len = buflen + 1;
338 p = va_arg(args, unsigned char *);
339 n = va_arg(args, int);
340 format_packet(p, n, vslp_printer, &bufinfo);
342 buflen = bufinfo.len - 1;
346 p = va_arg(args, unsigned char *);
347 for (n = prec; n > 0; --n) {
351 OUTCHAR(hexchars[(c >> 4) & 0xf]);
352 OUTCHAR(hexchars[c & 0xf]);
358 --fmt; /* so %z outputs %z etc. */
363 str = num + sizeof(num);
365 while (str > num + neg) {
366 *--str = hexchars[val % base];
368 if (--prec <= 0 && val == 0)
380 len = num + sizeof(num) - 1 - str;
382 for (len = 0; len < buflen && (prec == -1 || len < prec); ++len)
389 if ((n = width - len) > 0) {
397 memcpy(buf, str, len);
406 * vslp_printer - used in processing a %P format
409 vslp_printer(void *arg, char *fmt, ...)
413 struct buffer_info *bi;
417 bi = (struct buffer_info *) arg;
418 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
427 * log_packet - format a packet and log it.
431 log_packet(u_char *p, int len, char *prefix, int level)
433 init_pr_log(prefix, level);
434 format_packet(p, len, pr_log, &level);
441 * format_packet - make a readable representation of a packet,
442 * calling `printer(arg, format, ...)' to output it.
445 format_packet(u_char *p, int len, printer_func printer, void *arg)
449 struct protent *protp;
451 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
455 for (i = 0; (protp = protocols[i]) != NULL; ++i)
456 if (proto == protp->protocol)
459 printer(arg, "[%s", protp->name);
460 n = (*protp->printpkt)(p, len, printer, arg);
465 for (i = 0; (protp = protocols[i]) != NULL; ++i)
466 if (proto == (protp->protocol & ~0x8000))
468 if (protp != 0 && protp->data_name != 0) {
469 printer(arg, "[%s data]", protp->data_name);
471 printer(arg, "%.8B ...", p);
473 printer(arg, "%.*B", len, p);
476 printer(arg, "[proto=0x%x]", proto);
481 printer(arg, "%.32B ...", p);
483 printer(arg, "%.*B", len, p);
485 #endif /* UNIT_TEST */
488 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
491 static char line[256]; /* line to be logged accumulated here */
492 static char *linep; /* current pointer within line */
493 static int llevel; /* level for logging */
496 init_pr_log(const char *prefix, int level)
499 if (prefix != NULL) {
500 strlcpy(line, prefix, sizeof(line));
501 linep = line + strlen(line);
511 log_write(llevel, line);
516 * pr_log - printer routine for outputting to syslog
519 pr_log(void *arg, char *fmt, ...)
528 n = vslprintf(buf, sizeof(buf), fmt, pvar);
532 eol = strchr(buf, '\n');
534 l = (eol == NULL)? n: eol - buf;
535 if (linep + l < line + sizeof(line)) {
537 memcpy(linep, buf, l);
543 eol = strchr(p, '\n');
546 log_write(llevel, line);
550 while (eol != NULL) {
552 log_write(llevel, p);
554 eol = strchr(p, '\n');
557 /* assumes sizeof(buf) <= sizeof(line) */
566 * print_string - print a readable representation of a string using
570 print_string(char *p, int len, printer_func printer, void *arg)
575 for (; len > 0; --len) {
577 if (' ' <= c && c <= '~') {
578 if (c == '\\' || c == '"')
580 printer(arg, "%c", c);
593 printer(arg, "\\%.3o", (unsigned char) c);
601 * logit - does the hard work for fatal et al.
604 logit(int level, const char *fmt, va_list args)
608 vslprintf(buf, sizeof(buf), fmt, args);
609 log_write(level, buf);
614 log_write(int level, char *buf)
616 syslog(level, "%s", buf);
617 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
620 if (n > 0 && buf[n-1] == '\n')
622 if (write(log_to_fd, buf, n) != n
623 || write(log_to_fd, "\n", 1) != 1)
629 log_write(int level, char *buf)
631 printf("<%d>: %s\n", level, buf);
636 * fatal - log an error message and die horribly.
639 fatal(const char *fmt, ...)
645 logit(LOG_ERR, fmt, pvar);
649 die(1); /* as promised */
656 * error - log an error message.
659 error(const char *fmt, ...)
665 logit(LOG_ERR, fmt, pvar);
671 * warn - log a warning message.
674 warn(const char *fmt, ...)
680 logit(LOG_WARNING, fmt, pvar);
685 * notice - log a notice-level message.
688 notice(const char *fmt, ...)
694 logit(LOG_NOTICE, fmt, pvar);
699 * info - log an informational message.
702 info(const char *fmt, ...)
708 logit(LOG_INFO, fmt, pvar);
713 * dbglog - log a debug message.
716 dbglog(const char *fmt, ...)
722 logit(LOG_DEBUG, fmt, pvar);
727 * dump_packet - print out a packet in readable form if it is interesting.
728 * Assumes len >= PPP_HDRLEN.
731 dump_packet(const char *tag, unsigned char *p, int len)
739 * don't print LCP echo request/reply packets if debug <= 1
740 * and the link is up.
742 proto = (p[2] << 8) + p[3];
743 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
744 && len >= PPP_HDRLEN + HEADERLEN) {
745 unsigned char *lcp = p + PPP_HDRLEN;
746 int l = (lcp[2] << 8) + lcp[3];
748 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
749 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
753 dbglog("%s %P", tag, p, len);
759 * complete_read - read a full `count' bytes from fd,
760 * unless end-of-file or an error other than EINTR is encountered.
763 complete_read(int fd, void *buf, size_t count)
769 for (done = 0; done < count; ) {
770 nb = read(fd, ptr, count - done);
772 if (errno == EINTR && !ppp_signaled(SIGTERM))
786 * mkdir_check - helper for mkdir_recursive, creates a directory
787 * but do not error on EEXIST if and only if entry is a directory
788 * The caller must check for errno == ENOENT if appropriate.
791 mkdir_check(const char *path)
795 if (mkdir(path, 0755) >= 0)
798 if (errno == EEXIST) {
799 if (stat(path, &statbuf) < 0)
803 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
806 /* already exists but not a dir, treat as failure */
815 * mkdir_parent - helper for mkdir_recursive, modifies the string in place
816 * Assumes mkdir(path) already failed, so it first creates the parent then
820 mkdir_parent(char *path)
825 slash = strrchr(path, '/');
830 if (mkdir_check(path) < 0) {
831 if (errno != ENOENT) {
835 if (mkdir_parent(path) < 0) {
842 return mkdir_check(path);
846 * mkdir_recursive - recursively create directory if it didn't exist
849 mkdir_recursive(const char *path)
854 // optimistically try on full path first to avoid allocation
855 if (mkdir_check(path) == 0)
862 rc = mkdir_parent(copy);
867 /* Procedures for locking the serial device using a lock file. */
868 static char lock_file[MAXPATHLEN];
871 * lock - create a lock file for the named device
879 result = mklock (dev, (void *) 0);
881 strlcpy(lock_file, dev, sizeof(lock_file));
886 notice("Device %s is locked by pid %d", dev, result);
888 error("Can't create lock file %s", lock_file);
893 char lock_buffer[12];
899 if (stat(dev, &sbuf) < 0) {
900 error("Can't get device number for %s: %m", dev);
903 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
904 error("Can't lock %s: not a character device", dev);
907 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
908 PPP_PATH_LOCKDIR, major(sbuf.st_dev),
909 major(sbuf.st_rdev), minor(sbuf.st_rdev));
912 char lockdev[MAXPATHLEN];
914 if ((p = strstr(dev, "dev/")) != NULL) {
916 strncpy(lockdev, dev, MAXPATHLEN-1);
917 lockdev[MAXPATHLEN-1] = 0;
918 while ((p = strrchr(lockdev, '/')) != NULL) {
923 if ((p = strrchr(dev, '/')) != NULL)
926 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", PPP_PATH_LOCKDIR, dev);
929 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
930 if (errno != EEXIST) {
931 error("Can't create lock file %s: %m", lock_file);
935 /* Read the lock file to find out who has the device locked. */
936 fd = open(lock_file, O_RDONLY, 0);
938 if (errno == ENOENT) /* This is just a timing problem. */
940 error("Can't open existing lock file %s: %m", lock_file);
944 n = read(fd, lock_buffer, 11);
946 n = read(fd, &pid, sizeof(pid));
947 #endif /* LOCK_BINARY */
951 error("Can't read pid from lock file %s", lock_file);
955 /* See if the process still exists. */
958 pid = atoi(lock_buffer);
959 #endif /* LOCK_BINARY */
961 return 1; /* somebody else locked it for us */
963 || (kill(pid, 0) == -1 && errno == ESRCH)) {
964 if (unlink (lock_file) == 0) {
965 notice("Removed stale lock on %s (pid %d)", dev, pid);
968 warn("Couldn't remove stale lock on %s", dev);
970 notice("Device %s is locked by pid %d", dev, pid);
982 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
983 n = write (fd, lock_buffer, siz);
986 n = write(fd, &pid, siz);
989 error("Could not write pid to lock file when locking");
998 * relock - called to update our lockfile when we are about to detach,
999 * thus changing our pid (we fork, the child carries on, and the parent dies).
1000 * Note that this is called by the parent, with pid equal to the pid
1001 * of the child. This avoids a potential race which would exist if
1002 * we had the child rewrite the lockfile (the parent might die first,
1003 * and another process could think the lock was stale if it checked
1004 * between when the parent died and the child rewrote the lockfile).
1010 /* XXX is there a way to do this? */
1015 char lock_buffer[12];
1017 if (lock_file[0] == 0)
1019 fd = open(lock_file, O_WRONLY, 0);
1021 error("Couldn't reopen lock file %s: %m", lock_file);
1028 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1029 n = write (fd, lock_buffer, siz);
1032 n = write(fd, &pid, siz);
1033 #endif /* LOCK_BINARY */
1035 error("Could not write pid to lock file when locking");
1040 #endif /* LOCKLIB */
1044 * unlock - remove our lockfile
1051 (void) rmlock(lock_file, (void *) 0);