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>
62 static const char rcsid[] = RCSID;
65 extern char *strerror();
68 static void logit __P((int, char *, va_list));
69 static void log_write __P((int, char *));
70 static void vslp_printer __P((void *, char *, ...));
71 static void format_packet __P((u_char *, int, printer_func, void *));
79 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
80 * always leaves destination null-terminated (for len > 0).
83 strlcpy(dest, src, 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(dest, src, len)
111 size_t dlen = strlen(dest);
113 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
118 * slprintf - format a message into a buffer. Like sprintf except we
119 * also specify the length of the output buffer, and we handle
120 * %m (error message), %v (visible string),
121 * %q (quoted string), %t (current time) and %I (IP address) formats.
122 * Doesn't do floating-point formats.
123 * Returns the number of chars put into buf.
126 slprintf __V((char *buf, int buflen, char *fmt, ...))
131 #if defined(__STDC__)
138 buf = va_arg(args, char *);
139 buflen = va_arg(args, int);
140 fmt = va_arg(args, char *);
142 n = vslprintf(buf, buflen, fmt, args);
148 * vslprintf - like slprintf, takes a va_list instead of a list of args.
150 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
153 vslprintf(buf, buflen, fmt, args)
160 int width, prec, fillch;
161 int base, len, neg, quoted;
162 unsigned long val = 0;
163 char *str, *f, *buf0;
168 static char hexchars[] = "0123456789abcdef";
169 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 *);
299 if (fillch == '0' && prec >= 0) {
302 n = strlen((char *)p);
303 if (prec >= 0 && n > prec)
306 while (n > 0 && buflen > 0) {
309 if (!quoted && c >= 0x80) {
314 if (quoted && (c == '"' || c == '\\'))
316 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
320 case '\t': OUTCHAR('t'); break;
321 case '\n': OUTCHAR('n'); break;
322 case '\b': OUTCHAR('b'); break;
323 case '\f': OUTCHAR('f'); break;
326 OUTCHAR(hexchars[c >> 4]);
327 OUTCHAR(hexchars[c & 0xf]);
341 case 'P': /* print PPP packet */
343 bufinfo.len = buflen + 1;
344 p = va_arg(args, unsigned char *);
345 n = va_arg(args, int);
346 format_packet(p, n, vslp_printer, &bufinfo);
348 buflen = bufinfo.len - 1;
351 p = va_arg(args, unsigned char *);
352 for (n = prec; n > 0; --n) {
356 OUTCHAR(hexchars[(c >> 4) & 0xf]);
357 OUTCHAR(hexchars[c & 0xf]);
363 --fmt; /* so %z outputs %z etc. */
368 str = num + sizeof(num);
370 while (str > num + neg) {
371 *--str = hexchars[val % base];
373 if (--prec <= 0 && val == 0)
385 len = num + sizeof(num) - 1 - str;
388 if (prec >= 0 && len > prec)
394 if ((n = width - len) > 0) {
402 memcpy(buf, str, len);
411 * vslp_printer - used in processing a %P format
414 vslp_printer __V((void *arg, char *fmt, ...))
418 struct buffer_info *bi;
420 #if defined(__STDC__)
426 arg = va_arg(pvar, void *);
427 fmt = va_arg(pvar, char *);
430 bi = (struct buffer_info *) arg;
431 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
440 * log_packet - format a packet and log it.
444 log_packet(p, len, prefix, level)
450 init_pr_log(prefix, level);
451 format_packet(p, len, pr_log, &level);
457 * format_packet - make a readable representation of a packet,
458 * calling `printer(arg, format, ...)' to output it.
461 format_packet(p, len, printer, arg)
464 printer_func printer;
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);
507 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
510 static char line[256]; /* line to be logged accumulated here */
511 static char *linep; /* current pointer within line */
512 static int llevel; /* level for logging */
515 init_pr_log(prefix, level)
520 if (prefix != NULL) {
521 strlcpy(line, prefix, sizeof(line));
522 linep = line + strlen(line);
532 log_write(llevel, line);
537 * pr_log - printer routine for outputting to syslog
540 pr_log __V((void *arg, char *fmt, ...))
547 #if defined(__STDC__)
553 arg = va_arg(pvar, void *);
554 fmt = va_arg(pvar, char *);
557 n = vslprintf(buf, sizeof(buf), fmt, pvar);
561 eol = strchr(buf, '\n');
563 l = (eol == NULL)? n: eol - buf;
564 if (linep + l < line + sizeof(line)) {
566 memcpy(linep, buf, l);
572 eol = strchr(p, '\n');
575 log_write(llevel, line);
579 while (eol != NULL) {
581 log_write(llevel, p);
583 eol = strchr(p, '\n');
586 /* assumes sizeof(buf) <= sizeof(line) */
595 * print_string - print a readable representation of a string using
599 print_string(p, len, printer, arg)
602 printer_func printer;
608 for (; len > 0; --len) {
610 if (' ' <= c && c <= '~') {
611 if (c == '\\' || c == '"')
613 printer(arg, "%c", c);
626 printer(arg, "\\%.3o", c);
634 * logit - does the hard work for fatal et al.
637 logit(level, fmt, args)
644 vslprintf(buf, sizeof(buf), fmt, args);
645 log_write(level, buf);
649 log_write(level, buf)
653 syslog(level, "%s", buf);
654 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
657 if (n > 0 && buf[n-1] == '\n')
659 if (write(log_to_fd, buf, n) != n
660 || write(log_to_fd, "\n", 1) != 1)
666 * fatal - log an error message and die horribly.
669 fatal __V((char *fmt, ...))
673 #if defined(__STDC__)
678 fmt = va_arg(pvar, char *);
681 logit(LOG_ERR, fmt, pvar);
684 die(1); /* as promised */
688 * error - log an error message.
691 error __V((char *fmt, ...))
695 #if defined(__STDC__)
700 fmt = va_arg(pvar, char *);
703 logit(LOG_ERR, fmt, pvar);
709 * warn - log a warning message.
712 warn __V((char *fmt, ...))
716 #if defined(__STDC__)
721 fmt = va_arg(pvar, char *);
724 logit(LOG_WARNING, fmt, pvar);
729 * notice - log a notice-level message.
732 notice __V((char *fmt, ...))
736 #if defined(__STDC__)
741 fmt = va_arg(pvar, char *);
744 logit(LOG_NOTICE, fmt, pvar);
749 * info - log an informational message.
752 info __V((char *fmt, ...))
756 #if defined(__STDC__)
761 fmt = va_arg(pvar, char *);
764 logit(LOG_INFO, fmt, pvar);
769 * dbglog - log a debug message.
772 dbglog __V((char *fmt, ...))
776 #if defined(__STDC__)
781 fmt = va_arg(pvar, char *);
784 logit(LOG_DEBUG, fmt, pvar);
789 * dump_packet - print out a packet in readable form if it is interesting.
790 * Assumes len >= PPP_HDRLEN.
793 dump_packet(const char *tag, unsigned char *p, int len)
801 * don't print LCP echo request/reply packets if debug <= 1
802 * and the link is up.
804 proto = (p[2] << 8) + p[3];
805 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
806 && len >= PPP_HDRLEN + HEADERLEN) {
807 unsigned char *lcp = p + PPP_HDRLEN;
808 int l = (lcp[2] << 8) + lcp[3];
810 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
811 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
815 dbglog("%s %P", tag, p, len);
819 * complete_read - read a full `count' bytes from fd,
820 * unless end-of-file or an error other than EINTR is encountered.
823 complete_read(int fd, void *buf, size_t count)
829 for (done = 0; done < count; ) {
830 nb = read(fd, ptr, count - done);
844 /* Procedures for locking the serial device using a lock file. */
847 #define LOCK_DIR "/var/lock"
850 #define LOCK_DIR "/var/spool/locks"
852 #define LOCK_DIR "/var/spool/lock"
855 #endif /* LOCK_DIR */
857 static char lock_file[MAXPATHLEN];
860 * lock - create a lock file for the named device
869 result = mklock (dev, (void *) 0);
871 strlcpy(lock_file, dev, sizeof(lock_file));
876 notice("Device %s is locked by pid %d", dev, result);
878 error("Can't create lock file %s", lock_file);
883 char lock_buffer[12];
889 if (stat(dev, &sbuf) < 0) {
890 error("Can't get device number for %s: %m", dev);
893 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
894 error("Can't lock %s: not a character device", dev);
897 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
898 LOCK_DIR, major(sbuf.st_dev),
899 major(sbuf.st_rdev), minor(sbuf.st_rdev));
902 char lockdev[MAXPATHLEN];
904 if ((p = strstr(dev, "dev/")) != NULL) {
906 strncpy(lockdev, dev, MAXPATHLEN-1);
907 lockdev[MAXPATHLEN-1] = 0;
908 while ((p = strrchr(lockdev, '/')) != NULL) {
913 if ((p = strrchr(dev, '/')) != NULL)
916 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
919 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
920 if (errno != EEXIST) {
921 error("Can't create lock file %s: %m", lock_file);
925 /* Read the lock file to find out who has the device locked. */
926 fd = open(lock_file, O_RDONLY, 0);
928 if (errno == ENOENT) /* This is just a timing problem. */
930 error("Can't open existing lock file %s: %m", lock_file);
934 n = read(fd, lock_buffer, 11);
936 n = read(fd, &pid, sizeof(pid));
937 #endif /* LOCK_BINARY */
941 error("Can't read pid from lock file %s", lock_file);
945 /* See if the process still exists. */
948 pid = atoi(lock_buffer);
949 #endif /* LOCK_BINARY */
951 return 1; /* somebody else locked it for us */
953 || (kill(pid, 0) == -1 && errno == ESRCH)) {
954 if (unlink (lock_file) == 0) {
955 notice("Removed stale lock on %s (pid %d)", dev, pid);
958 warn("Couldn't remove stale lock on %s", dev);
960 notice("Device %s is locked by pid %d", dev, pid);
971 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
972 write (fd, lock_buffer, 11);
974 write(fd, &pid, sizeof (pid));
983 * relock - called to update our lockfile when we are about to detach,
984 * thus changing our pid (we fork, the child carries on, and the parent dies).
985 * Note that this is called by the parent, with pid equal to the pid
986 * of the child. This avoids a potential race which would exist if
987 * we had the child rewrite the lockfile (the parent might die first,
988 * and another process could think the lock was stale if it checked
989 * between when the parent died and the child rewrote the lockfile).
996 /* XXX is there a way to do this? */
1001 char lock_buffer[12];
1003 if (lock_file[0] == 0)
1005 fd = open(lock_file, O_WRONLY, 0);
1007 error("Couldn't reopen lock file %s: %m", lock_file);
1013 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1014 write (fd, lock_buffer, 11);
1016 write(fd, &pid, sizeof(pid));
1017 #endif /* LOCK_BINARY */
1021 #endif /* LOCKLIB */
1025 * unlock - remove our lockfile
1032 (void) rmlock(lock_file, (void *) 0);