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.
31 #define RCSID "$Id: utils.c,v 1.25 2008/06/03 12:06:37 paulus Exp $"
46 #include <sys/param.h>
47 #include <sys/types.h>
50 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
55 #include <sys/mkdev.h>
64 extern char *strerror();
67 static void logit __P((int, char *, va_list));
68 static void log_write __P((int, char *));
69 static void vslp_printer __P((void *, char *, ...));
70 static void format_packet __P((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(dest, src, 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(dest, src, len)
110 size_t dlen = strlen(dest);
112 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
117 * slprintf - format a message into a buffer. Like sprintf except we
118 * also specify the length of the output buffer, and we handle
119 * %m (error message), %v (visible string),
120 * %q (quoted string), %t (current time) and %I (IP address) formats.
121 * Doesn't do floating-point formats.
122 * Returns the number of chars put into buf.
125 slprintf __V((char *buf, int buflen, char *fmt, ...))
130 #if defined(__STDC__)
137 buf = va_arg(args, char *);
138 buflen = va_arg(args, int);
139 fmt = va_arg(args, char *);
141 n = vslprintf(buf, buflen, fmt, args);
147 * vslprintf - like slprintf, takes a va_list instead of a list of args.
149 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
152 vslprintf(buf, buflen, fmt, args)
159 int width, prec, fillch;
160 int base, len, neg, quoted;
161 unsigned long val = 0;
162 char *str, *f, *buf0;
167 static char hexchars[] = "0123456789abcdef";
168 struct buffer_info bufinfo;
174 for (f = fmt; *f != '%' && *f != 0; ++f)
180 memcpy(buf, fmt, len);
196 width = va_arg(args, int);
200 width = width * 10 + c - '0';
207 prec = va_arg(args, int);
212 prec = prec * 10 + c - '0';
226 val = va_arg(args, long);
234 val = va_arg(args, unsigned long);
240 --fmt; /* so %lz outputs %lz etc. */
245 i = va_arg(args, int);
254 val = va_arg(args, unsigned int);
258 val = va_arg(args, unsigned int);
263 val = va_arg(args, unsigned int);
267 val = (unsigned long) va_arg(args, void *);
272 str = va_arg(args, char *);
275 num[0] = va_arg(args, int);
280 str = strerror(errno);
283 ip = va_arg(args, u_int32_t);
285 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
286 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
292 str += 4; /* chop off the day name */
293 str[15] = 0; /* chop off year and newline */
295 case 'v': /* "visible" string */
296 case 'q': /* quoted string */
298 p = va_arg(args, unsigned char *);
300 p = (unsigned char *)"<NULL>";
301 if (fillch == '0' && prec >= 0) {
303 termch = -1; /* matches no unsigned char value */
306 if (prec != -1 && n > prec)
308 termch = 0; /* stop on null byte */
310 while (n > 0 && buflen > 0) {
315 if (!quoted && c >= 0x80) {
320 if (quoted && (c == '"' || c == '\\'))
322 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
326 case '\t': OUTCHAR('t'); break;
327 case '\n': OUTCHAR('n'); break;
328 case '\b': OUTCHAR('b'); break;
329 case '\f': OUTCHAR('f'); break;
332 OUTCHAR(hexchars[c >> 4]);
333 OUTCHAR(hexchars[c & 0xf]);
347 case 'P': /* print PPP packet */
349 bufinfo.len = buflen + 1;
350 p = va_arg(args, unsigned char *);
351 n = va_arg(args, int);
352 format_packet(p, n, vslp_printer, &bufinfo);
354 buflen = bufinfo.len - 1;
357 p = va_arg(args, unsigned char *);
358 for (n = prec; n > 0; --n) {
362 OUTCHAR(hexchars[(c >> 4) & 0xf]);
363 OUTCHAR(hexchars[c & 0xf]);
369 --fmt; /* so %z outputs %z etc. */
374 str = num + sizeof(num);
376 while (str > num + neg) {
377 *--str = hexchars[val % base];
379 if (--prec <= 0 && val == 0)
391 len = num + sizeof(num) - 1 - str;
393 for (len = 0; len < buflen && (prec == -1 || len < prec); ++len)
400 if ((n = width - len) > 0) {
408 memcpy(buf, str, len);
417 * vslp_printer - used in processing a %P format
420 vslp_printer __V((void *arg, char *fmt, ...))
424 struct buffer_info *bi;
426 #if defined(__STDC__)
432 arg = va_arg(pvar, void *);
433 fmt = va_arg(pvar, char *);
436 bi = (struct buffer_info *) arg;
437 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
446 * log_packet - format a packet and log it.
450 log_packet(p, len, prefix, level)
456 init_pr_log(prefix, level);
457 format_packet(p, len, pr_log, &level);
463 * format_packet - make a readable representation of a packet,
464 * calling `printer(arg, format, ...)' to output it.
467 format_packet(p, len, printer, arg)
470 printer_func printer;
475 struct protent *protp;
477 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
481 for (i = 0; (protp = protocols[i]) != NULL; ++i)
482 if (proto == protp->protocol)
485 printer(arg, "[%s", protp->name);
486 n = (*protp->printpkt)(p, len, printer, arg);
491 for (i = 0; (protp = protocols[i]) != NULL; ++i)
492 if (proto == (protp->protocol & ~0x8000))
494 if (protp != 0 && protp->data_name != 0) {
495 printer(arg, "[%s data]", protp->data_name);
497 printer(arg, "%.8B ...", p);
499 printer(arg, "%.*B", len, p);
502 printer(arg, "[proto=0x%x]", proto);
507 printer(arg, "%.32B ...", p);
509 printer(arg, "%.*B", len, p);
513 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
516 static char line[256]; /* line to be logged accumulated here */
517 static char *linep; /* current pointer within line */
518 static int llevel; /* level for logging */
521 init_pr_log(prefix, level)
526 if (prefix != NULL) {
527 strlcpy(line, prefix, sizeof(line));
528 linep = line + strlen(line);
538 log_write(llevel, line);
543 * pr_log - printer routine for outputting to syslog
546 pr_log __V((void *arg, char *fmt, ...))
553 #if defined(__STDC__)
559 arg = va_arg(pvar, void *);
560 fmt = va_arg(pvar, char *);
563 n = vslprintf(buf, sizeof(buf), fmt, pvar);
567 eol = strchr(buf, '\n');
569 l = (eol == NULL)? n: eol - buf;
570 if (linep + l < line + sizeof(line)) {
572 memcpy(linep, buf, l);
578 eol = strchr(p, '\n');
581 log_write(llevel, line);
585 while (eol != NULL) {
587 log_write(llevel, p);
589 eol = strchr(p, '\n');
592 /* assumes sizeof(buf) <= sizeof(line) */
601 * print_string - print a readable representation of a string using
605 print_string(p, len, printer, arg)
608 printer_func printer;
614 for (; len > 0; --len) {
616 if (' ' <= c && c <= '~') {
617 if (c == '\\' || c == '"')
619 printer(arg, "%c", c);
632 printer(arg, "\\%.3o", (unsigned char) c);
640 * logit - does the hard work for fatal et al.
643 logit(level, fmt, args)
650 vslprintf(buf, sizeof(buf), fmt, args);
651 log_write(level, buf);
655 log_write(level, buf)
659 syslog(level, "%s", buf);
660 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
663 if (n > 0 && buf[n-1] == '\n')
665 if (write(log_to_fd, buf, n) != n
666 || write(log_to_fd, "\n", 1) != 1)
672 * fatal - log an error message and die horribly.
675 fatal __V((char *fmt, ...))
679 #if defined(__STDC__)
684 fmt = va_arg(pvar, char *);
687 logit(LOG_ERR, fmt, pvar);
690 die(1); /* as promised */
694 * error - log an error message.
697 error __V((char *fmt, ...))
701 #if defined(__STDC__)
706 fmt = va_arg(pvar, char *);
709 logit(LOG_ERR, fmt, pvar);
715 * warn - log a warning message.
718 warn __V((char *fmt, ...))
722 #if defined(__STDC__)
727 fmt = va_arg(pvar, char *);
730 logit(LOG_WARNING, fmt, pvar);
735 * notice - log a notice-level message.
738 notice __V((char *fmt, ...))
742 #if defined(__STDC__)
747 fmt = va_arg(pvar, char *);
750 logit(LOG_NOTICE, fmt, pvar);
755 * info - log an informational message.
758 info __V((char *fmt, ...))
762 #if defined(__STDC__)
767 fmt = va_arg(pvar, char *);
770 logit(LOG_INFO, fmt, pvar);
775 * dbglog - log a debug message.
778 dbglog __V((char *fmt, ...))
782 #if defined(__STDC__)
787 fmt = va_arg(pvar, char *);
790 logit(LOG_DEBUG, fmt, pvar);
795 * dump_packet - print out a packet in readable form if it is interesting.
796 * Assumes len >= PPP_HDRLEN.
799 dump_packet(const char *tag, unsigned char *p, int len)
807 * don't print LCP echo request/reply packets if debug <= 1
808 * and the link is up.
810 proto = (p[2] << 8) + p[3];
811 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
812 && len >= PPP_HDRLEN + HEADERLEN) {
813 unsigned char *lcp = p + PPP_HDRLEN;
814 int l = (lcp[2] << 8) + lcp[3];
816 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
817 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
821 dbglog("%s %P", tag, p, len);
825 * complete_read - read a full `count' bytes from fd,
826 * unless end-of-file or an error other than EINTR is encountered.
829 complete_read(int fd, void *buf, size_t count)
835 for (done = 0; done < count; ) {
836 nb = read(fd, ptr, count - done);
850 /* Procedures for locking the serial device using a lock file. */
853 #define LOCK_DIR "/var/lock"
856 #define LOCK_DIR "/var/spool/locks"
858 #define LOCK_DIR "/var/spool/lock"
861 #endif /* LOCK_DIR */
863 static char lock_file[MAXPATHLEN];
866 * lock - create a lock file for the named device
875 result = mklock (dev, (void *) 0);
877 strlcpy(lock_file, dev, sizeof(lock_file));
882 notice("Device %s is locked by pid %d", dev, result);
884 error("Can't create lock file %s", lock_file);
889 char lock_buffer[12];
895 if (stat(dev, &sbuf) < 0) {
896 error("Can't get device number for %s: %m", dev);
899 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
900 error("Can't lock %s: not a character device", dev);
903 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
904 LOCK_DIR, major(sbuf.st_dev),
905 major(sbuf.st_rdev), minor(sbuf.st_rdev));
908 char lockdev[MAXPATHLEN];
910 if ((p = strstr(dev, "dev/")) != NULL) {
912 strncpy(lockdev, dev, MAXPATHLEN-1);
913 lockdev[MAXPATHLEN-1] = 0;
914 while ((p = strrchr(lockdev, '/')) != NULL) {
919 if ((p = strrchr(dev, '/')) != NULL)
922 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
925 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
926 if (errno != EEXIST) {
927 error("Can't create lock file %s: %m", lock_file);
931 /* Read the lock file to find out who has the device locked. */
932 fd = open(lock_file, O_RDONLY, 0);
934 if (errno == ENOENT) /* This is just a timing problem. */
936 error("Can't open existing lock file %s: %m", lock_file);
940 n = read(fd, lock_buffer, 11);
942 n = read(fd, &pid, sizeof(pid));
943 #endif /* LOCK_BINARY */
947 error("Can't read pid from lock file %s", lock_file);
951 /* See if the process still exists. */
954 pid = atoi(lock_buffer);
955 #endif /* LOCK_BINARY */
957 return 1; /* somebody else locked it for us */
959 || (kill(pid, 0) == -1 && errno == ESRCH)) {
960 if (unlink (lock_file) == 0) {
961 notice("Removed stale lock on %s (pid %d)", dev, pid);
964 warn("Couldn't remove stale lock on %s", dev);
966 notice("Device %s is locked by pid %d", dev, pid);
977 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
978 write (fd, lock_buffer, 11);
980 write(fd, &pid, sizeof (pid));
989 * relock - called to update our lockfile when we are about to detach,
990 * thus changing our pid (we fork, the child carries on, and the parent dies).
991 * Note that this is called by the parent, with pid equal to the pid
992 * of the child. This avoids a potential race which would exist if
993 * we had the child rewrite the lockfile (the parent might die first,
994 * and another process could think the lock was stale if it checked
995 * between when the parent died and the child rewrote the lockfile).
1002 /* XXX is there a way to do this? */
1007 char lock_buffer[12];
1009 if (lock_file[0] == 0)
1011 fd = open(lock_file, O_WRONLY, 0);
1013 error("Couldn't reopen lock file %s: %m", lock_file);
1019 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1020 write (fd, lock_buffer, 11);
1022 write(fd, &pid, sizeof(pid));
1023 #endif /* LOCK_BINARY */
1027 #endif /* LOCKLIB */
1031 * unlock - remove our lockfile
1038 (void) rmlock(lock_file, (void *) 0);