2 * utils.c - various utility functions used in pppd.
4 * Copyright (c) 1999-2024 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. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
18 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
19 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
20 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
21 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
22 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
23 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
24 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
45 #include <sys/param.h>
46 #include <sys/types.h>
49 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
54 #include <sys/mkdev.h>
57 #include "pppd-private.h"
60 #include "pathnames.h"
64 extern char *strerror();
67 static void logit(int, const char *, va_list);
68 static void log_write(int, char *);
69 static void vslp_printer(void *, char *, ...);
70 static void format_packet(u_char *, int, printer_func, void *);
78 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
79 * always leaves destination null-terminated (for len > 0).
82 strlcpy(char *dest, const char *src, size_t len)
84 size_t ret = strlen(src);
90 strncpy(dest, src, len - 1);
98 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
99 * always leaves destination null-terminated (for len > 0).
102 strlcat(char *dest, const char *src, size_t len)
104 size_t dlen = strlen(dest);
106 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
111 * slprintf - format a message into a buffer. Like sprintf except we
112 * also specify the length of the output buffer, and we handle
113 * %m (error message), %v (visible string),
114 * %q (quoted string), %t (current time) and %I (IP address) formats.
115 * Doesn't do floating-point formats.
116 * Returns the number of chars put into buf.
119 slprintf(char *buf, int buflen, const char *fmt, ...)
125 n = vslprintf(buf, buflen, fmt, args);
131 * vslprintf - like slprintf, takes a va_list instead of a list of args.
133 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
136 vslprintf(char *buf, int buflen, const char *fmt, va_list args)
139 int width, prec, fillch;
140 int base, len, neg, quoted;
142 unsigned long long val = 0;
149 static char hexchars[] = "0123456789abcdef";
150 struct buffer_info bufinfo;
156 for (f = fmt; *f != '%' && *f != 0; ++f)
162 memcpy(buf, fmt, len);
178 width = va_arg(args, int);
182 width = width * 10 + c - '0';
189 prec = va_arg(args, int);
194 prec = prec * 10 + c - '0';
211 lval = va_arg(args, long long);
220 val = va_arg(args, unsigned long long);
227 --fmt; /* so %llz outputs %llz etc. */
232 lval = va_arg(args, long);
241 val = va_arg(args, unsigned long);
247 --fmt; /* so %lz outputs %lz etc. */
252 i = va_arg(args, int);
261 val = va_arg(args, unsigned int);
265 val = va_arg(args, unsigned int);
270 val = va_arg(args, unsigned int);
274 val = (unsigned long) va_arg(args, void *);
279 str = va_arg(args, char *);
282 num[0] = va_arg(args, int);
287 str = strerror(errno);
290 ip = va_arg(args, u_int32_t);
292 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
293 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
299 str += 4; /* chop off the day name */
300 str[15] = 0; /* chop off year and newline */
302 case 'v': /* "visible" string */
303 case 'q': /* quoted string */
305 p = va_arg(args, unsigned char *);
307 p = (unsigned char *)"<NULL>";
308 if (fillch == '0' && prec >= 0) {
310 termch = -1; /* matches no unsigned char value */
313 if (prec != -1 && n > prec)
315 termch = 0; /* stop on null byte */
317 while (n > 0 && buflen > 0) {
322 if (!quoted && c >= 0x80) {
327 if (quoted && (c == '"' || c == '\\'))
329 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
333 case '\t': OUTCHAR('t'); break;
334 case '\n': OUTCHAR('n'); break;
335 case '\b': OUTCHAR('b'); break;
336 case '\f': OUTCHAR('f'); break;
339 OUTCHAR(hexchars[c >> 4]);
340 OUTCHAR(hexchars[c & 0xf]);
355 case 'P': /* print PPP packet */
357 bufinfo.len = buflen + 1;
358 p = va_arg(args, unsigned char *);
359 n = va_arg(args, int);
360 format_packet(p, n, vslp_printer, &bufinfo);
362 buflen = bufinfo.len - 1;
366 p = va_arg(args, unsigned char *);
367 for (n = prec; n > 0; --n) {
371 OUTCHAR(hexchars[(c >> 4) & 0xf]);
372 OUTCHAR(hexchars[c & 0xf]);
378 --fmt; /* so %z outputs %z etc. */
383 str = num + sizeof(num);
385 while (str > num + neg) {
386 *--str = hexchars[val % base];
388 if (--prec <= 0 && val == 0)
400 len = num + sizeof(num) - 1 - str;
402 for (len = 0; len < buflen && (prec == -1 || len < prec); ++len)
409 if ((n = width - len) > 0) {
417 memcpy(buf, str, len);
426 * vslp_printer - used in processing a %P format
429 vslp_printer(void *arg, char *fmt, ...)
433 struct buffer_info *bi;
437 bi = (struct buffer_info *) arg;
438 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
447 * log_packet - format a packet and log it.
451 log_packet(u_char *p, int len, char *prefix, int level)
453 init_pr_log(prefix, level);
454 format_packet(p, len, pr_log, &level);
461 * format_packet - make a readable representation of a packet,
462 * calling `printer(arg, format, ...)' to output it.
465 format_packet(u_char *p, int len, printer_func printer, void *arg)
469 struct protent *protp;
471 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
475 for (i = 0; (protp = protocols[i]) != NULL; ++i)
476 if (proto == protp->protocol)
479 printer(arg, "[%s", protp->name);
480 n = (*protp->printpkt)(p, len, printer, arg);
485 for (i = 0; (protp = protocols[i]) != NULL; ++i)
486 if (proto == (protp->protocol & ~0x8000))
488 if (protp != 0 && protp->data_name != 0) {
489 printer(arg, "[%s data]", protp->data_name);
491 printer(arg, "%.8B ...", p);
493 printer(arg, "%.*B", len, p);
496 printer(arg, "[proto=0x%x]", proto);
501 printer(arg, "%.32B ...", p);
503 printer(arg, "%.*B", len, p);
505 #endif /* UNIT_TEST */
508 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
511 static char line[256]; /* line to be logged accumulated here */
512 static char *linep; /* current pointer within line */
513 static int llevel; /* level for logging */
516 init_pr_log(const char *prefix, int level)
519 if (prefix != NULL) {
520 strlcpy(line, prefix, sizeof(line));
521 linep = line + strlen(line);
531 log_write(llevel, line);
536 * pr_log - printer routine for outputting to syslog
539 pr_log(void *arg, char *fmt, ...)
548 n = vslprintf(buf, sizeof(buf), fmt, pvar);
552 eol = strchr(buf, '\n');
554 l = (eol == NULL)? n: eol - buf;
555 if (linep + l < line + sizeof(line)) {
557 memcpy(linep, buf, l);
563 eol = strchr(p, '\n');
566 log_write(llevel, line);
570 while (eol != NULL) {
572 log_write(llevel, p);
574 eol = strchr(p, '\n');
577 /* assumes sizeof(buf) <= sizeof(line) */
586 * print_string - print a readable representation of a string using
590 print_string(char *p, int len, printer_func printer, void *arg)
595 for (; len > 0; --len) {
597 if (' ' <= c && c <= '~') {
598 if (c == '\\' || c == '"')
600 printer(arg, "%c", c);
613 printer(arg, "\\%.3o", (unsigned char) c);
621 * logit - does the hard work for fatal et al.
624 logit(int level, const char *fmt, va_list args)
628 vslprintf(buf, sizeof(buf), fmt, args);
629 log_write(level, buf);
634 log_write(int level, char *buf)
636 syslog(level, "%s", buf);
637 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
640 if (n > 0 && buf[n-1] == '\n')
642 if (write(log_to_fd, buf, n) != n
643 || write(log_to_fd, "\n", 1) != 1)
649 log_write(int level, char *buf)
651 printf("<%d>: %s\n", level, buf);
656 * fatal - log an error message and die horribly.
659 fatal(const char *fmt, ...)
665 logit(LOG_ERR, fmt, pvar);
669 die(1); /* as promised */
676 * error - log an error message.
679 error(const char *fmt, ...)
685 logit(LOG_ERR, fmt, pvar);
691 * warn - log a warning message.
694 warn(const char *fmt, ...)
700 logit(LOG_WARNING, fmt, pvar);
705 * notice - log a notice-level message.
708 notice(const char *fmt, ...)
714 logit(LOG_NOTICE, fmt, pvar);
719 * info - log an informational message.
722 info(const char *fmt, ...)
728 logit(LOG_INFO, fmt, pvar);
733 * dbglog - log a debug message.
736 dbglog(const char *fmt, ...)
742 logit(LOG_DEBUG, fmt, pvar);
747 * dump_packet - print out a packet in readable form if it is interesting.
748 * Assumes len >= PPP_HDRLEN.
751 dump_packet(const char *tag, unsigned char *p, int len)
759 * don't print LCP echo request/reply packets if debug <= 1
760 * and the link is up.
762 proto = (p[2] << 8) + p[3];
763 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
764 && len >= PPP_HDRLEN + HEADERLEN) {
765 unsigned char *lcp = p + PPP_HDRLEN;
766 int l = (lcp[2] << 8) + lcp[3];
768 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
769 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
773 dbglog("%s %P", tag, p, len);
779 * complete_read - read a full `count' bytes from fd,
780 * unless end-of-file or an error other than EINTR is encountered.
783 complete_read(int fd, void *buf, size_t count)
789 for (done = 0; done < count; ) {
790 nb = read(fd, ptr, count - done);
792 if (errno == EINTR && !ppp_signaled(SIGTERM))
806 * mkdir_check - helper for mkdir_recursive, creates a directory
807 * but do not error on EEXIST if and only if entry is a directory
808 * The caller must check for errno == ENOENT if appropriate.
811 mkdir_check(const char *path)
815 if (mkdir(path, 0755) >= 0)
818 if (errno == EEXIST) {
819 if (stat(path, &statbuf) < 0)
823 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
826 /* already exists but not a dir, treat as failure */
835 * mkdir_parent - helper for mkdir_recursive, modifies the string in place
836 * Assumes mkdir(path) already failed, so it first creates the parent then
840 mkdir_parent(char *path)
845 slash = strrchr(path, '/');
850 if (mkdir_check(path) < 0) {
851 if (errno != ENOENT) {
855 if (mkdir_parent(path) < 0) {
862 return mkdir_check(path);
866 * mkdir_recursive - recursively create directory if it didn't exist
869 mkdir_recursive(const char *path)
874 // optimistically try on full path first to avoid allocation
875 if (mkdir_check(path) == 0)
882 rc = mkdir_parent(copy);
887 /* Procedures for locking the serial device using a lock file. */
888 static char lock_file[MAXPATHLEN];
891 * lock - create a lock file for the named device
899 result = mklock (dev, (void *) 0);
901 strlcpy(lock_file, dev, sizeof(lock_file));
906 notice("Device %s is locked by pid %d", dev, result);
908 error("Can't create lock file %s", lock_file);
913 char lock_buffer[12];
919 if (stat(dev, &sbuf) < 0) {
920 error("Can't get device number for %s: %m", dev);
923 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
924 error("Can't lock %s: not a character device", dev);
927 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
928 PPP_PATH_LOCKDIR, major(sbuf.st_dev),
929 major(sbuf.st_rdev), minor(sbuf.st_rdev));
932 char lockdev[MAXPATHLEN];
934 if ((p = strstr(dev, "dev/")) != NULL) {
936 strncpy(lockdev, dev, MAXPATHLEN-1);
937 lockdev[MAXPATHLEN-1] = 0;
938 while ((p = strrchr(lockdev, '/')) != NULL) {
943 if ((p = strrchr(dev, '/')) != NULL)
946 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", PPP_PATH_LOCKDIR, dev);
949 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
950 if (errno != EEXIST) {
951 error("Can't create lock file %s: %m", lock_file);
955 /* Read the lock file to find out who has the device locked. */
956 fd = open(lock_file, O_RDONLY, 0);
958 if (errno == ENOENT) /* This is just a timing problem. */
960 error("Can't open existing lock file %s: %m", lock_file);
964 n = read(fd, lock_buffer, 11);
966 n = read(fd, &pid, sizeof(pid));
967 #endif /* LOCK_BINARY */
971 error("Can't read pid from lock file %s", lock_file);
975 /* See if the process still exists. */
978 pid = atoi(lock_buffer);
979 #endif /* LOCK_BINARY */
981 return 1; /* somebody else locked it for us */
983 || (kill(pid, 0) == -1 && errno == ESRCH)) {
984 if (unlink (lock_file) == 0) {
985 notice("Removed stale lock on %s (pid %d)", dev, pid);
988 warn("Couldn't remove stale lock on %s", dev);
990 notice("Device %s is locked by pid %d", dev, pid);
1002 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1003 n = write (fd, lock_buffer, siz);
1006 n = write(fd, &pid, siz);
1009 error("Could not write pid to lock file when locking");
1018 * relock - called to update our lockfile when we are about to detach,
1019 * thus changing our pid (we fork, the child carries on, and the parent dies).
1020 * Note that this is called by the parent, with pid equal to the pid
1021 * of the child. This avoids a potential race which would exist if
1022 * we had the child rewrite the lockfile (the parent might die first,
1023 * and another process could think the lock was stale if it checked
1024 * between when the parent died and the child rewrote the lockfile).
1030 /* XXX is there a way to do this? */
1035 char lock_buffer[12];
1037 if (lock_file[0] == 0)
1039 fd = open(lock_file, O_WRONLY, 0);
1041 error("Couldn't reopen lock file %s: %m", lock_file);
1048 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1049 n = write (fd, lock_buffer, siz);
1052 n = write(fd, &pid, siz);
1053 #endif /* LOCK_BINARY */
1055 error("Could not write pid to lock file when locking");
1060 #endif /* LOCKLIB */
1064 * unlock - remove our lockfile
1071 (void) rmlock(lock_file, (void *) 0);