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>
67 extern char *strerror();
70 static void logit(int, char *, va_list);
71 static void log_write(int, char *);
72 static void vslp_printer(void *, char *, ...);
73 static void format_packet(u_char *, int, printer_func, void *);
81 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
82 * always leaves destination null-terminated (for len > 0).
85 strlcpy(char *dest, const char *src, size_t len)
87 size_t ret = strlen(src);
93 strncpy(dest, src, len - 1);
101 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
102 * always leaves destination null-terminated (for len > 0).
105 strlcat(char *dest, const char *src, size_t len)
107 size_t dlen = strlen(dest);
109 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
114 * slprintf - format a message into a buffer. Like sprintf except we
115 * also specify the length of the output buffer, and we handle
116 * %m (error message), %v (visible string),
117 * %q (quoted string), %t (current time) and %I (IP address) formats.
118 * Doesn't do floating-point formats.
119 * Returns the number of chars put into buf.
122 slprintf(char *buf, int buflen, char *fmt, ...)
128 n = vslprintf(buf, buflen, fmt, args);
134 * vslprintf - like slprintf, takes a va_list instead of a list of args.
136 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
139 vslprintf(char *buf, int buflen, char *fmt, va_list args)
142 int width, prec, fillch;
143 int base, len, neg, quoted;
145 unsigned long val = 0;
146 char *str, *f, *buf0;
151 static char hexchars[] = "0123456789abcdef";
152 struct buffer_info bufinfo;
158 for (f = fmt; *f != '%' && *f != 0; ++f)
164 memcpy(buf, fmt, len);
180 width = va_arg(args, int);
184 width = width * 10 + c - '0';
191 prec = va_arg(args, int);
196 prec = prec * 10 + c - '0';
210 lval = va_arg(args, long);
219 val = va_arg(args, unsigned long);
225 --fmt; /* so %lz outputs %lz etc. */
230 i = va_arg(args, int);
239 val = va_arg(args, unsigned int);
243 val = va_arg(args, unsigned int);
248 val = va_arg(args, unsigned int);
252 val = (unsigned long) va_arg(args, void *);
257 str = va_arg(args, char *);
260 num[0] = va_arg(args, int);
265 str = strerror(errno);
268 ip = va_arg(args, u_int32_t);
270 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
271 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
277 str += 4; /* chop off the day name */
278 str[15] = 0; /* chop off year and newline */
280 case 'v': /* "visible" string */
281 case 'q': /* quoted string */
283 p = va_arg(args, unsigned char *);
285 p = (unsigned char *)"<NULL>";
286 if (fillch == '0' && prec >= 0) {
288 termch = -1; /* matches no unsigned char value */
291 if (prec != -1 && n > prec)
293 termch = 0; /* stop on null byte */
295 while (n > 0 && buflen > 0) {
300 if (!quoted && c >= 0x80) {
305 if (quoted && (c == '"' || c == '\\'))
307 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
311 case '\t': OUTCHAR('t'); break;
312 case '\n': OUTCHAR('n'); break;
313 case '\b': OUTCHAR('b'); break;
314 case '\f': OUTCHAR('f'); break;
317 OUTCHAR(hexchars[c >> 4]);
318 OUTCHAR(hexchars[c & 0xf]);
333 case 'P': /* print PPP packet */
335 bufinfo.len = buflen + 1;
336 p = va_arg(args, unsigned char *);
337 n = va_arg(args, int);
338 format_packet(p, n, vslp_printer, &bufinfo);
340 buflen = bufinfo.len - 1;
344 p = va_arg(args, unsigned char *);
345 for (n = prec; n > 0; --n) {
349 OUTCHAR(hexchars[(c >> 4) & 0xf]);
350 OUTCHAR(hexchars[c & 0xf]);
356 --fmt; /* so %z outputs %z etc. */
361 str = num + sizeof(num);
363 while (str > num + neg) {
364 *--str = hexchars[val % base];
366 if (--prec <= 0 && val == 0)
378 len = num + sizeof(num) - 1 - str;
380 for (len = 0; len < buflen && (prec == -1 || len < prec); ++len)
387 if ((n = width - len) > 0) {
395 memcpy(buf, str, len);
404 * vslp_printer - used in processing a %P format
407 vslp_printer(void *arg, char *fmt, ...)
411 struct buffer_info *bi;
415 bi = (struct buffer_info *) arg;
416 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
425 * log_packet - format a packet and log it.
429 log_packet(u_char *p, int len, char *prefix, int level)
431 init_pr_log(prefix, level);
432 format_packet(p, len, pr_log, &level);
439 * format_packet - make a readable representation of a packet,
440 * calling `printer(arg, format, ...)' to output it.
443 format_packet(u_char *p, int len, printer_func printer, void *arg)
447 struct protent *protp;
449 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
453 for (i = 0; (protp = protocols[i]) != NULL; ++i)
454 if (proto == protp->protocol)
457 printer(arg, "[%s", protp->name);
458 n = (*protp->printpkt)(p, len, printer, arg);
463 for (i = 0; (protp = protocols[i]) != NULL; ++i)
464 if (proto == (protp->protocol & ~0x8000))
466 if (protp != 0 && protp->data_name != 0) {
467 printer(arg, "[%s data]", protp->data_name);
469 printer(arg, "%.8B ...", p);
471 printer(arg, "%.*B", len, p);
474 printer(arg, "[proto=0x%x]", proto);
479 printer(arg, "%.32B ...", p);
481 printer(arg, "%.*B", len, p);
483 #endif /* UNIT_TEST */
486 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
489 static char line[256]; /* line to be logged accumulated here */
490 static char *linep; /* current pointer within line */
491 static int llevel; /* level for logging */
494 init_pr_log(const char *prefix, int level)
497 if (prefix != NULL) {
498 strlcpy(line, prefix, sizeof(line));
499 linep = line + strlen(line);
509 log_write(llevel, line);
514 * pr_log - printer routine for outputting to syslog
517 pr_log(void *arg, char *fmt, ...)
526 n = vslprintf(buf, sizeof(buf), fmt, pvar);
530 eol = strchr(buf, '\n');
532 l = (eol == NULL)? n: eol - buf;
533 if (linep + l < line + sizeof(line)) {
535 memcpy(linep, buf, l);
541 eol = strchr(p, '\n');
544 log_write(llevel, line);
548 while (eol != NULL) {
550 log_write(llevel, p);
552 eol = strchr(p, '\n');
555 /* assumes sizeof(buf) <= sizeof(line) */
564 * print_string - print a readable representation of a string using
568 print_string(char *p, int len, printer_func printer, void *arg)
573 for (; len > 0; --len) {
575 if (' ' <= c && c <= '~') {
576 if (c == '\\' || c == '"')
578 printer(arg, "%c", c);
591 printer(arg, "\\%.3o", (unsigned char) c);
599 * logit - does the hard work for fatal et al.
602 logit(int level, char *fmt, va_list args)
606 vslprintf(buf, sizeof(buf), fmt, args);
607 log_write(level, buf);
612 log_write(int level, char *buf)
614 syslog(level, "%s", buf);
615 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
618 if (n > 0 && buf[n-1] == '\n')
620 if (write(log_to_fd, buf, n) != n
621 || write(log_to_fd, "\n", 1) != 1)
627 log_write(int level, char *buf)
629 printf("<%d>: %s\n", level, buf);
634 * fatal - log an error message and die horribly.
637 fatal(char *fmt, ...)
643 logit(LOG_ERR, fmt, pvar);
647 die(1); /* as promised */
654 * error - log an error message.
657 error(char *fmt, ...)
663 logit(LOG_ERR, fmt, pvar);
669 * warn - log a warning message.
678 logit(LOG_WARNING, fmt, pvar);
683 * notice - log a notice-level message.
686 notice(char *fmt, ...)
692 logit(LOG_NOTICE, fmt, pvar);
697 * info - log an informational message.
706 logit(LOG_INFO, fmt, pvar);
711 * dbglog - log a debug message.
714 dbglog(char *fmt, ...)
720 logit(LOG_DEBUG, fmt, pvar);
725 * dump_packet - print out a packet in readable form if it is interesting.
726 * Assumes len >= PPP_HDRLEN.
729 dump_packet(const char *tag, unsigned char *p, int len)
737 * don't print LCP echo request/reply packets if debug <= 1
738 * and the link is up.
740 proto = (p[2] << 8) + p[3];
741 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
742 && len >= PPP_HDRLEN + HEADERLEN) {
743 unsigned char *lcp = p + PPP_HDRLEN;
744 int l = (lcp[2] << 8) + lcp[3];
746 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
747 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
751 dbglog("%s %P", tag, p, len);
757 * complete_read - read a full `count' bytes from fd,
758 * unless end-of-file or an error other than EINTR is encountered.
761 complete_read(int fd, void *buf, size_t count)
767 for (done = 0; done < count; ) {
768 nb = read(fd, ptr, count - done);
770 if (errno == EINTR && !got_sigterm)
783 /* Procedures for locking the serial device using a lock file. */
786 #define LOCK_DIR "/var/lock"
789 #define LOCK_DIR "/var/spool/locks"
791 #define LOCK_DIR "/var/spool/lock"
794 #endif /* LOCK_DIR */
796 static char lock_file[MAXPATHLEN];
799 * lock - create a lock file for the named device
807 result = mklock (dev, (void *) 0);
809 strlcpy(lock_file, dev, sizeof(lock_file));
814 notice("Device %s is locked by pid %d", dev, result);
816 error("Can't create lock file %s", lock_file);
821 char lock_buffer[12];
827 if (stat(dev, &sbuf) < 0) {
828 error("Can't get device number for %s: %m", dev);
831 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
832 error("Can't lock %s: not a character device", dev);
835 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
836 LOCK_DIR, major(sbuf.st_dev),
837 major(sbuf.st_rdev), minor(sbuf.st_rdev));
840 char lockdev[MAXPATHLEN];
842 if ((p = strstr(dev, "dev/")) != NULL) {
844 strncpy(lockdev, dev, MAXPATHLEN-1);
845 lockdev[MAXPATHLEN-1] = 0;
846 while ((p = strrchr(lockdev, '/')) != NULL) {
851 if ((p = strrchr(dev, '/')) != NULL)
854 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
857 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
858 if (errno != EEXIST) {
859 error("Can't create lock file %s: %m", lock_file);
863 /* Read the lock file to find out who has the device locked. */
864 fd = open(lock_file, O_RDONLY, 0);
866 if (errno == ENOENT) /* This is just a timing problem. */
868 error("Can't open existing lock file %s: %m", lock_file);
872 n = read(fd, lock_buffer, 11);
874 n = read(fd, &pid, sizeof(pid));
875 #endif /* LOCK_BINARY */
879 error("Can't read pid from lock file %s", lock_file);
883 /* See if the process still exists. */
886 pid = atoi(lock_buffer);
887 #endif /* LOCK_BINARY */
889 return 1; /* somebody else locked it for us */
891 || (kill(pid, 0) == -1 && errno == ESRCH)) {
892 if (unlink (lock_file) == 0) {
893 notice("Removed stale lock on %s (pid %d)", dev, pid);
896 warn("Couldn't remove stale lock on %s", dev);
898 notice("Device %s is locked by pid %d", dev, pid);
910 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
911 n = write (fd, lock_buffer, siz);
914 n = write(fd, &pid, siz);
917 error("Could not write pid to lock file when locking");
926 * relock - called to update our lockfile when we are about to detach,
927 * thus changing our pid (we fork, the child carries on, and the parent dies).
928 * Note that this is called by the parent, with pid equal to the pid
929 * of the child. This avoids a potential race which would exist if
930 * we had the child rewrite the lockfile (the parent might die first,
931 * and another process could think the lock was stale if it checked
932 * between when the parent died and the child rewrote the lockfile).
938 /* XXX is there a way to do this? */
943 char lock_buffer[12];
945 if (lock_file[0] == 0)
947 fd = open(lock_file, O_WRONLY, 0);
949 error("Couldn't reopen lock file %s: %m", lock_file);
956 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
957 n = write (fd, lock_buffer, siz);
960 n = write(fd, &pid, siz);
961 #endif /* LOCK_BINARY */
963 error("Could not write pid to lock file when locking");
972 * unlock - remove our lockfile
979 (void) rmlock(lock_file, (void *) 0);