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. 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 * 3. The name(s) of the authors of this software must not be used to
19 * endorse or promote products derived from this software without
20 * prior written permission.
22 * 4. Redistributions of any form whatsoever must retain the following
24 * "This product includes software developed by Paul Mackerras
25 * <paulus@samba.org>".
27 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
28 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
29 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
30 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
32 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
33 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
36 #define RCSID "$Id: utils.c,v 1.22 2003/04/07 00:01:46 paulus Exp $"
51 #include <sys/param.h>
52 #include <sys/types.h>
55 #include <sys/resource.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
60 #include <sys/mkdev.h>
67 static const char rcsid[] = RCSID;
70 extern char *strerror();
73 static void logit __P((int, char *, va_list));
74 static void log_write __P((int, char *));
75 static void vslp_printer __P((void *, char *, ...));
76 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
85 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
86 * always leaves destination null-terminated (for len > 0).
89 strlcpy(dest, src, len)
94 size_t ret = strlen(src);
100 strncpy(dest, src, len - 1);
108 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
109 * always leaves destination null-terminated (for len > 0).
112 strlcat(dest, src, len)
117 size_t dlen = strlen(dest);
119 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
124 * slprintf - format a message into a buffer. Like sprintf except we
125 * also specify the length of the output buffer, and we handle
126 * %r (recursive format), %m (error message), %v (visible string),
127 * %q (quoted string), %t (current time) and %I (IP address) formats.
128 * Doesn't do floating-point formats.
129 * Returns the number of chars put into buf.
132 slprintf __V((char *buf, int buflen, char *fmt, ...))
137 #if defined(__STDC__)
144 buf = va_arg(args, char *);
145 buflen = va_arg(args, int);
146 fmt = va_arg(args, char *);
148 n = vslprintf(buf, buflen, fmt, args);
154 * vslprintf - like slprintf, takes a va_list instead of a list of args.
156 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
159 vslprintf(buf, buflen, fmt, args)
166 int width, prec, fillch;
167 int base, len, neg, quoted;
168 unsigned long val = 0;
169 char *str, *f, *buf0;
174 static char hexchars[] = "0123456789abcdef";
175 struct buffer_info bufinfo;
180 for (f = fmt; *f != '%' && *f != 0; ++f)
186 memcpy(buf, fmt, len);
202 width = va_arg(args, int);
206 width = width * 10 + c - '0';
213 prec = va_arg(args, int);
218 prec = prec * 10 + c - '0';
232 val = va_arg(args, long);
240 val = va_arg(args, unsigned long);
244 *buf++ = '%'; --buflen;
245 *buf++ = 'l'; --buflen;
246 --fmt; /* so %lz outputs %lz etc. */
251 i = va_arg(args, int);
260 val = va_arg(args, unsigned int);
264 val = va_arg(args, unsigned int);
269 val = va_arg(args, unsigned int);
273 val = (unsigned long) va_arg(args, void *);
278 str = va_arg(args, char *);
281 num[0] = va_arg(args, int);
286 str = strerror(errno);
289 ip = va_arg(args, u_int32_t);
291 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
292 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
296 f = va_arg(args, char *);
298 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
300 /* On the powerpc, a va_list is an array of 1 structure */
301 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
309 str += 4; /* chop off the day name */
310 str[15] = 0; /* chop off year and newline */
312 case 'v': /* "visible" string */
313 case 'q': /* quoted string */
315 p = va_arg(args, unsigned char *);
316 if (fillch == '0' && prec >= 0) {
319 n = strlen((char *)p);
320 if (prec >= 0 && n > prec)
323 while (n > 0 && buflen > 0) {
326 if (!quoted && c >= 0x80) {
331 if (quoted && (c == '"' || c == '\\'))
333 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
337 case '\t': OUTCHAR('t'); break;
338 case '\n': OUTCHAR('n'); break;
339 case '\b': OUTCHAR('b'); break;
340 case '\f': OUTCHAR('f'); break;
343 OUTCHAR(hexchars[c >> 4]);
344 OUTCHAR(hexchars[c & 0xf]);
358 case 'P': /* print PPP packet */
360 bufinfo.len = buflen + 1;
361 p = va_arg(args, unsigned char *);
362 n = va_arg(args, int);
363 format_packet(p, n, vslp_printer, &bufinfo);
365 buflen = bufinfo.len - 1;
368 p = va_arg(args, unsigned char *);
369 for (n = prec; n > 0; --n) {
373 OUTCHAR(hexchars[(c >> 4) & 0xf]);
374 OUTCHAR(hexchars[c & 0xf]);
380 --fmt; /* so %z outputs %z etc. */
385 str = num + sizeof(num);
387 while (str > num + neg) {
388 *--str = hexchars[val % base];
390 if (--prec <= 0 && val == 0)
402 len = num + sizeof(num) - 1 - str;
405 if (prec >= 0 && len > prec)
411 if ((n = width - len) > 0) {
419 memcpy(buf, str, len);
428 * vslp_printer - used in processing a %P format
431 vslp_printer __V((void *arg, char *fmt, ...))
435 struct buffer_info *bi;
437 #if defined(__STDC__)
443 arg = va_arg(pvar, void *);
444 fmt = va_arg(pvar, char *);
447 bi = (struct buffer_info *) arg;
448 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
457 * log_packet - format a packet and log it.
461 log_packet(p, len, prefix, level)
467 init_pr_log(prefix, level);
468 format_packet(p, len, pr_log, &level);
474 * format_packet - make a readable representation of a packet,
475 * calling `printer(arg, format, ...)' to output it.
478 format_packet(p, len, printer, arg)
481 void (*printer) __P((void *, char *, ...));
486 struct protent *protp;
488 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
492 for (i = 0; (protp = protocols[i]) != NULL; ++i)
493 if (proto == protp->protocol)
496 printer(arg, "[%s", protp->name);
497 n = (*protp->printpkt)(p, len, printer, arg);
502 for (i = 0; (protp = protocols[i]) != NULL; ++i)
503 if (proto == (protp->protocol & ~0x8000))
505 if (protp != 0 && protp->data_name != 0) {
506 printer(arg, "[%s data]", protp->data_name);
508 printer(arg, "%.8B ...", p);
510 printer(arg, "%.*B", len, p);
513 printer(arg, "[proto=0x%x]", proto);
518 printer(arg, "%.32B ...", p);
520 printer(arg, "%.*B", len, p);
524 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
527 static char line[256]; /* line to be logged accumulated here */
528 static char *linep; /* current pointer within line */
529 static int llevel; /* level for logging */
532 init_pr_log(prefix, level)
537 if (prefix != NULL) {
538 strlcpy(line, prefix, sizeof(line));
539 linep = line + strlen(line);
549 log_write(llevel, line);
554 * pr_log - printer routine for outputting to syslog
557 pr_log __V((void *arg, char *fmt, ...))
564 #if defined(__STDC__)
570 arg = va_arg(pvar, void *);
571 fmt = va_arg(pvar, char *);
574 n = vslprintf(buf, sizeof(buf), fmt, pvar);
578 eol = strchr(buf, '\n');
580 l = (eol == NULL)? n: eol - buf;
581 if (linep + l < line + sizeof(line)) {
583 memcpy(linep, buf, l);
589 eol = strchr(p, '\n');
592 log_write(llevel, line);
596 while (eol != NULL) {
598 log_write(llevel, p);
600 eol = strchr(p, '\n');
603 /* assumes sizeof(buf) <= sizeof(line) */
612 * print_string - print a readable representation of a string using
616 print_string(p, len, printer, arg)
619 void (*printer) __P((void *, char *, ...));
625 for (; len > 0; --len) {
627 if (' ' <= c && c <= '~') {
628 if (c == '\\' || c == '"')
630 printer(arg, "%c", c);
643 printer(arg, "\\%.3o", c);
651 * logit - does the hard work for fatal et al.
654 logit(level, fmt, args)
662 n = vslprintf(buf, sizeof(buf), fmt, args);
663 log_write(level, buf);
667 log_write(level, buf)
671 syslog(level, "%s", buf);
672 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
675 if (n > 0 && buf[n-1] == '\n')
677 if (write(log_to_fd, buf, n) != n
678 || write(log_to_fd, "\n", 1) != 1)
684 * fatal - log an error message and die horribly.
687 fatal __V((char *fmt, ...))
691 #if defined(__STDC__)
696 fmt = va_arg(pvar, char *);
699 logit(LOG_ERR, fmt, pvar);
702 die(1); /* as promised */
706 * error - log an error message.
709 error __V((char *fmt, ...))
713 #if defined(__STDC__)
718 fmt = va_arg(pvar, char *);
721 logit(LOG_ERR, fmt, pvar);
727 * warn - log a warning message.
730 warn __V((char *fmt, ...))
734 #if defined(__STDC__)
739 fmt = va_arg(pvar, char *);
742 logit(LOG_WARNING, fmt, pvar);
747 * notice - log a notice-level message.
750 notice __V((char *fmt, ...))
754 #if defined(__STDC__)
759 fmt = va_arg(pvar, char *);
762 logit(LOG_NOTICE, fmt, pvar);
767 * info - log an informational message.
770 info __V((char *fmt, ...))
774 #if defined(__STDC__)
779 fmt = va_arg(pvar, char *);
782 logit(LOG_INFO, fmt, pvar);
787 * dbglog - log a debug message.
790 dbglog __V((char *fmt, ...))
794 #if defined(__STDC__)
799 fmt = va_arg(pvar, char *);
802 logit(LOG_DEBUG, fmt, pvar);
807 * dump_packet - print out a packet in readable form if it is interesting.
808 * Assumes len >= PPP_HDRLEN.
811 dump_packet(const char *tag, unsigned char *p, int len)
819 * don't print LCP echo request/reply packets if debug <= 1
820 * and the link is up.
822 proto = (p[2] << 8) + p[3];
823 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
824 && len >= PPP_HDRLEN + HEADERLEN) {
825 unsigned char *lcp = p + PPP_HDRLEN;
826 int l = (lcp[2] << 8) + lcp[3];
828 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
829 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
833 dbglog("%s %P", tag, p, len);
837 * complete_read - read a full `count' bytes from fd,
838 * unless end-of-file or an error other than EINTR is encountered.
841 complete_read(int fd, void *buf, size_t count)
847 for (done = 0; done < count; ) {
848 nb = read(fd, ptr, count - done);
862 /* Procedures for locking the serial device using a lock file. */
865 #define LOCK_DIR "/var/lock"
868 #define LOCK_DIR "/var/spool/locks"
870 #define LOCK_DIR "/var/spool/lock"
873 #endif /* LOCK_DIR */
875 static char lock_file[MAXPATHLEN];
878 * lock - create a lock file for the named device
887 result = mklock (dev, (void *) 0);
889 strlcpy(lock_file, dev, sizeof(lock_file));
894 notice("Device %s is locked by pid %d", dev, result);
896 error("Can't create lock file %s", lock_file);
901 char lock_buffer[12];
907 if (stat(dev, &sbuf) < 0) {
908 error("Can't get device number for %s: %m", dev);
911 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
912 error("Can't lock %s: not a character device", dev);
915 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
916 LOCK_DIR, major(sbuf.st_dev),
917 major(sbuf.st_rdev), minor(sbuf.st_rdev));
920 char lockdev[MAXPATHLEN];
922 if ((p = strstr(dev, "dev/")) != NULL) {
924 strncpy(lockdev, dev, MAXPATHLEN-1);
925 lockdev[MAXPATHLEN-1] = 0;
926 while ((p = strrchr(lockdev, '/')) != NULL) {
931 if ((p = strrchr(dev, '/')) != NULL)
934 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
937 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
938 if (errno != EEXIST) {
939 error("Can't create lock file %s: %m", lock_file);
943 /* Read the lock file to find out who has the device locked. */
944 fd = open(lock_file, O_RDONLY, 0);
946 if (errno == ENOENT) /* This is just a timing problem. */
948 error("Can't open existing lock file %s: %m", lock_file);
952 n = read(fd, lock_buffer, 11);
954 n = read(fd, &pid, sizeof(pid));
955 #endif /* LOCK_BINARY */
959 error("Can't read pid from lock file %s", lock_file);
963 /* See if the process still exists. */
966 pid = atoi(lock_buffer);
967 #endif /* LOCK_BINARY */
969 return 1; /* somebody else locked it for us */
971 || (kill(pid, 0) == -1 && errno == ESRCH)) {
972 if (unlink (lock_file) == 0) {
973 notice("Removed stale lock on %s (pid %d)", dev, pid);
976 warn("Couldn't remove stale lock on %s", dev);
978 notice("Device %s is locked by pid %d", dev, pid);
989 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
990 write (fd, lock_buffer, 11);
992 write(fd, &pid, sizeof (pid));
1001 * relock - called to update our lockfile when we are about to detach,
1002 * thus changing our pid (we fork, the child carries on, and the parent dies).
1003 * Note that this is called by the parent, with pid equal to the pid
1004 * of the child. This avoids a potential race which would exist if
1005 * we had the child rewrite the lockfile (the parent might die first,
1006 * and another process could think the lock was stale if it checked
1007 * between when the parent died and the child rewrote the lockfile).
1014 /* XXX is there a way to do this? */
1019 char lock_buffer[12];
1021 if (lock_file[0] == 0)
1023 fd = open(lock_file, O_WRONLY, 0);
1025 error("Couldn't reopen lock file %s: %m", lock_file);
1031 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1032 write (fd, lock_buffer, 11);
1034 write(fd, &pid, sizeof(pid));
1035 #endif /* LOCK_BINARY */
1039 #endif /* LOCKLIB */
1043 * unlock - remove our lockfile
1050 (void) rmlock(lock_file, (void *) 0);