2 * utils.c - various utility functions used in pppd.
4 * Copyright (c) 1999 The Australian National University.
7 * Redistribution and use in source and binary forms are permitted
8 * provided that the above copyright notice and this paragraph are
9 * duplicated in all such forms and that any documentation,
10 * advertising materials, and other materials related to such
11 * distribution and use acknowledge that the software was developed
12 * by the Australian National University. The name of the University
13 * may not be used to endorse or promote products derived from this
14 * software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 #define RCSID "$Id: utils.c,v 1.11 2001/03/08 05:11:16 paulus Exp $"
34 #include <sys/param.h>
35 #include <sys/types.h>
38 #include <sys/resource.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
43 #include <sys/mkdev.h>
48 static const char rcsid[] = RCSID;
51 extern char *strerror();
54 static void logit __P((int, char *, va_list));
55 static void log_write __P((int, char *));
56 static void vslp_printer __P((void *, char *, ...));
57 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
66 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
67 * always leaves destination null-terminated (for len > 0).
70 strlcpy(dest, src, len)
75 size_t ret = strlen(src);
81 strncpy(dest, src, len - 1);
89 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
90 * always leaves destination null-terminated (for len > 0).
93 strlcat(dest, src, len)
98 size_t dlen = strlen(dest);
100 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
105 * slprintf - format a message into a buffer. Like sprintf except we
106 * also specify the length of the output buffer, and we handle
107 * %r (recursive format), %m (error message), %v (visible string),
108 * %q (quoted string), %t (current time) and %I (IP address) formats.
109 * Doesn't do floating-point formats.
110 * Returns the number of chars put into buf.
113 slprintf __V((char *buf, int buflen, char *fmt, ...))
118 #if defined(__STDC__)
125 buf = va_arg(args, char *);
126 buflen = va_arg(args, int);
127 fmt = va_arg(args, char *);
129 n = vslprintf(buf, buflen, fmt, args);
135 * vslprintf - like slprintf, takes a va_list instead of a list of args.
137 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
140 vslprintf(buf, buflen, fmt, args)
147 int width, prec, fillch;
148 int base, len, neg, quoted;
149 unsigned long val = 0;
150 char *str, *f, *buf0;
155 static char hexchars[] = "0123456789abcdef";
156 struct buffer_info bufinfo;
161 for (f = fmt; *f != '%' && *f != 0; ++f)
167 memcpy(buf, fmt, len);
183 width = va_arg(args, int);
187 width = width * 10 + c - '0';
194 prec = va_arg(args, int);
199 prec = prec * 10 + c - '0';
210 i = va_arg(args, int);
219 val = va_arg(args, unsigned int);
224 val = va_arg(args, unsigned int);
228 val = (unsigned long) va_arg(args, void *);
233 str = va_arg(args, char *);
236 num[0] = va_arg(args, int);
241 str = strerror(errno);
244 ip = va_arg(args, u_int32_t);
246 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
247 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
251 f = va_arg(args, char *);
253 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
255 /* On the powerpc, a va_list is an array of 1 structure */
256 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
264 str += 4; /* chop off the day name */
265 str[15] = 0; /* chop off year and newline */
267 case 'v': /* "visible" string */
268 case 'q': /* quoted string */
270 p = va_arg(args, unsigned char *);
271 if (fillch == '0' && prec >= 0) {
274 n = strlen((char *)p);
275 if (prec >= 0 && n > prec)
278 while (n > 0 && buflen > 0) {
281 if (!quoted && c >= 0x80) {
286 if (quoted && (c == '"' || c == '\\'))
288 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
292 case '\t': OUTCHAR('t'); break;
293 case '\n': OUTCHAR('n'); break;
294 case '\b': OUTCHAR('b'); break;
295 case '\f': OUTCHAR('f'); break;
298 OUTCHAR(hexchars[c >> 4]);
299 OUTCHAR(hexchars[c & 0xf]);
313 case 'P': /* print PPP packet */
315 bufinfo.len = buflen + 1;
316 p = va_arg(args, unsigned char *);
317 n = va_arg(args, int);
318 format_packet(p, n, vslp_printer, &bufinfo);
320 buflen = bufinfo.len - 1;
323 p = va_arg(args, unsigned char *);
324 for (n = prec; n > 0; --n) {
328 OUTCHAR(hexchars[(c >> 4) & 0xf]);
329 OUTCHAR(hexchars[c & 0xf]);
335 --fmt; /* so %z outputs %z etc. */
340 str = num + sizeof(num);
342 while (str > num + neg) {
343 *--str = hexchars[val % base];
345 if (--prec <= 0 && val == 0)
357 len = num + sizeof(num) - 1 - str;
360 if (prec >= 0 && len > prec)
366 if ((n = width - len) > 0) {
374 memcpy(buf, str, len);
383 * vslp_printer - used in processing a %P format
386 vslp_printer __V((void *arg, char *fmt, ...))
390 struct buffer_info *bi;
392 #if defined(__STDC__)
398 arg = va_arg(pvar, void *);
399 fmt = va_arg(pvar, char *);
402 bi = (struct buffer_info *) arg;
403 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
412 * log_packet - format a packet and log it.
416 log_packet(p, len, prefix, level)
422 init_pr_log(prefix, level);
423 format_packet(p, len, pr_log, &level);
429 * format_packet - make a readable representation of a packet,
430 * calling `printer(arg, format, ...)' to output it.
433 format_packet(p, len, printer, arg)
436 void (*printer) __P((void *, char *, ...));
441 struct protent *protp;
443 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
447 for (i = 0; (protp = protocols[i]) != NULL; ++i)
448 if (proto == protp->protocol)
451 printer(arg, "[%s", protp->name);
452 n = (*protp->printpkt)(p, len, printer, arg);
457 for (i = 0; (protp = protocols[i]) != NULL; ++i)
458 if (proto == (protp->protocol & ~0x8000))
460 if (protp != 0 && protp->data_name != 0) {
461 printer(arg, "[%s data]", protp->data_name);
463 printer(arg, "%.8B ...", p);
465 printer(arg, "%.*B", len, p);
468 printer(arg, "[proto=0x%x]", proto);
473 printer(arg, "%.32B ...", p);
475 printer(arg, "%.*B", len, p);
479 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
482 static char line[256]; /* line to be logged accumulated here */
483 static char *linep; /* current pointer within line */
484 static int llevel; /* level for logging */
487 init_pr_log(prefix, level)
492 if (prefix != NULL) {
493 strlcpy(line, prefix, sizeof(line));
494 linep = line + strlen(line);
504 log_write(llevel, line);
509 * pr_log - printer routine for outputting to syslog
512 pr_log __V((void *arg, char *fmt, ...))
519 #if defined(__STDC__)
525 arg = va_arg(pvar, void *);
526 fmt = va_arg(pvar, char *);
529 n = vslprintf(buf, sizeof(buf), fmt, pvar);
533 eol = strchr(buf, '\n');
535 l = (eol == NULL)? n: eol - buf;
536 if (linep + l < line + sizeof(line)) {
538 memcpy(linep, buf, l);
544 eol = strchr(p, '\n');
547 log_write(llevel, line);
551 while (eol != NULL) {
553 log_write(llevel, p);
557 /* assumes sizeof(buf) <= sizeof(line) */
566 * print_string - print a readable representation of a string using
570 print_string(p, len, printer, arg)
573 void (*printer) __P((void *, char *, ...));
579 for (; len > 0; --len) {
581 if (' ' <= c && c <= '~') {
582 if (c == '\\' || c == '"')
584 printer(arg, "%c", c);
597 printer(arg, "\\%.3o", c);
605 * logit - does the hard work for fatal et al.
608 logit(level, fmt, args)
616 n = vslprintf(buf, sizeof(buf), fmt, args);
617 log_write(level, buf);
621 log_write(level, buf)
625 syslog(level, "%s", buf);
626 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
629 if (n > 0 && buf[n-1] == '\n')
631 if (write(log_to_fd, buf, n) != n
632 || write(log_to_fd, "\n", 1) != 1)
638 * fatal - log an error message and die horribly.
641 fatal __V((char *fmt, ...))
645 #if defined(__STDC__)
650 fmt = va_arg(pvar, char *);
653 logit(LOG_ERR, fmt, pvar);
656 die(1); /* as promised */
660 * error - log an error message.
663 error __V((char *fmt, ...))
667 #if defined(__STDC__)
672 fmt = va_arg(pvar, char *);
675 logit(LOG_ERR, fmt, pvar);
680 * warn - log a warning message.
683 warn __V((char *fmt, ...))
687 #if defined(__STDC__)
692 fmt = va_arg(pvar, char *);
695 logit(LOG_WARNING, fmt, pvar);
700 * notice - log a notice-level message.
703 notice __V((char *fmt, ...))
707 #if defined(__STDC__)
712 fmt = va_arg(pvar, char *);
715 logit(LOG_NOTICE, fmt, pvar);
720 * info - log an informational message.
723 info __V((char *fmt, ...))
727 #if defined(__STDC__)
732 fmt = va_arg(pvar, char *);
735 logit(LOG_INFO, fmt, pvar);
740 * dbglog - log a debug message.
743 dbglog __V((char *fmt, ...))
747 #if defined(__STDC__)
752 fmt = va_arg(pvar, char *);
755 logit(LOG_DEBUG, fmt, pvar);
759 /* Procedures for locking the serial device using a lock file. */
762 #define LOCK_DIR "/var/lock"
765 #define LOCK_DIR "/var/spool/locks"
767 #define LOCK_DIR "/var/spool/lock"
770 #endif /* LOCK_DIR */
772 static char lock_file[MAXPATHLEN];
775 * lock - create a lock file for the named device
784 result = mklock (dev, (void *) 0);
786 strlcpy(lock_file, sizeof(lock_file), dev);
791 notice("Device %s is locked by pid %d", dev, result);
793 error("Can't create lock file %s", lock_file);
798 char lock_buffer[12];
804 if (stat(dev, &sbuf) < 0) {
805 error("Can't get device number for %s: %m", dev);
808 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
809 error("Can't lock %s: not a character device", dev);
812 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
813 LOCK_DIR, major(sbuf.st_dev),
814 major(sbuf.st_rdev), minor(sbuf.st_rdev));
818 if ((p = strrchr(dev, '/')) != NULL)
820 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
823 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
824 if (errno != EEXIST) {
825 error("Can't create lock file %s: %m", lock_file);
829 /* Read the lock file to find out who has the device locked. */
830 fd = open(lock_file, O_RDONLY, 0);
832 if (errno == ENOENT) /* This is just a timing problem. */
834 error("Can't open existing lock file %s: %m", lock_file);
838 n = read(fd, lock_buffer, 11);
840 n = read(fd, &pid, sizeof(pid));
841 #endif /* LOCK_BINARY */
845 error("Can't read pid from lock file %s", lock_file);
849 /* See if the process still exists. */
852 pid = atoi(lock_buffer);
853 #endif /* LOCK_BINARY */
855 return 1; /* somebody else locked it for us */
857 || (kill(pid, 0) == -1 && errno == ESRCH)) {
858 if (unlink (lock_file) == 0) {
859 notice("Removed stale lock on %s (pid %d)", dev, pid);
862 warn("Couldn't remove stale lock on %s", dev);
864 notice("Device %s is locked by pid %d", dev, pid);
875 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
876 write (fd, lock_buffer, 11);
878 write(fd, &pid, sizeof (pid));
887 * relock - called to update our lockfile when we are about to detach,
888 * thus changing our pid (we fork, the child carries on, and the parent dies).
889 * Note that this is called by the parent, with pid equal to the pid
890 * of the child. This avoids a potential race which would exist if
891 * we had the child rewrite the lockfile (the parent might die first,
892 * and another process could think the lock was stale if it checked
893 * between when the parent died and the child rewrote the lockfile).
900 /* XXX is there a way to do this? */
905 char lock_buffer[12];
907 if (lock_file[0] == 0)
909 fd = open(lock_file, O_WRONLY, 0);
911 error("Couldn't reopen lock file %s: %m", lock_file);
917 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
918 write (fd, lock_buffer, 11);
920 write(fd, &pid, sizeof(pid));
921 #endif /* LOCK_BINARY */
929 * unlock - remove our lockfile
936 (void) rmlock(lock_file, (void *) 0);