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.15 2001/11/09 10:33:04 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>
50 static const char rcsid[] = RCSID;
53 extern char *strerror();
56 static void logit __P((int, char *, va_list));
57 static void log_write __P((int, char *));
58 static void vslp_printer __P((void *, char *, ...));
59 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
68 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
69 * always leaves destination null-terminated (for len > 0).
72 strlcpy(dest, src, len)
77 size_t ret = strlen(src);
83 strncpy(dest, src, len - 1);
91 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
92 * always leaves destination null-terminated (for len > 0).
95 strlcat(dest, src, len)
100 size_t dlen = strlen(dest);
102 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
107 * slprintf - format a message into a buffer. Like sprintf except we
108 * also specify the length of the output buffer, and we handle
109 * %r (recursive format), %m (error message), %v (visible string),
110 * %q (quoted string), %t (current time) and %I (IP address) formats.
111 * Doesn't do floating-point formats.
112 * Returns the number of chars put into buf.
115 slprintf __V((char *buf, int buflen, char *fmt, ...))
120 #if defined(__STDC__)
127 buf = va_arg(args, char *);
128 buflen = va_arg(args, int);
129 fmt = va_arg(args, char *);
131 n = vslprintf(buf, buflen, fmt, args);
137 * vslprintf - like slprintf, takes a va_list instead of a list of args.
139 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
142 vslprintf(buf, buflen, fmt, args)
149 int width, prec, fillch;
150 int base, len, neg, quoted;
151 unsigned long val = 0;
152 char *str, *f, *buf0;
157 static char hexchars[] = "0123456789abcdef";
158 struct buffer_info bufinfo;
163 for (f = fmt; *f != '%' && *f != 0; ++f)
169 memcpy(buf, fmt, len);
185 width = va_arg(args, int);
189 width = width * 10 + c - '0';
196 prec = va_arg(args, int);
201 prec = prec * 10 + c - '0';
212 i = va_arg(args, int);
221 val = va_arg(args, unsigned int);
225 val = va_arg(args, unsigned int);
230 val = va_arg(args, unsigned int);
234 val = (unsigned long) va_arg(args, void *);
239 str = va_arg(args, char *);
242 num[0] = va_arg(args, int);
247 str = strerror(errno);
250 ip = va_arg(args, u_int32_t);
252 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
253 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
257 f = va_arg(args, char *);
259 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
261 /* On the powerpc, a va_list is an array of 1 structure */
262 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
270 str += 4; /* chop off the day name */
271 str[15] = 0; /* chop off year and newline */
273 case 'v': /* "visible" string */
274 case 'q': /* quoted string */
276 p = va_arg(args, unsigned char *);
277 if (fillch == '0' && prec >= 0) {
280 n = strlen((char *)p);
281 if (prec >= 0 && n > prec)
284 while (n > 0 && buflen > 0) {
287 if (!quoted && c >= 0x80) {
292 if (quoted && (c == '"' || c == '\\'))
294 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
298 case '\t': OUTCHAR('t'); break;
299 case '\n': OUTCHAR('n'); break;
300 case '\b': OUTCHAR('b'); break;
301 case '\f': OUTCHAR('f'); break;
304 OUTCHAR(hexchars[c >> 4]);
305 OUTCHAR(hexchars[c & 0xf]);
319 case 'P': /* print PPP packet */
321 bufinfo.len = buflen + 1;
322 p = va_arg(args, unsigned char *);
323 n = va_arg(args, int);
324 format_packet(p, n, vslp_printer, &bufinfo);
326 buflen = bufinfo.len - 1;
329 p = va_arg(args, unsigned char *);
330 for (n = prec; n > 0; --n) {
334 OUTCHAR(hexchars[(c >> 4) & 0xf]);
335 OUTCHAR(hexchars[c & 0xf]);
341 --fmt; /* so %z outputs %z etc. */
346 str = num + sizeof(num);
348 while (str > num + neg) {
349 *--str = hexchars[val % base];
351 if (--prec <= 0 && val == 0)
363 len = num + sizeof(num) - 1 - str;
366 if (prec >= 0 && len > prec)
372 if ((n = width - len) > 0) {
380 memcpy(buf, str, len);
389 * vslp_printer - used in processing a %P format
392 vslp_printer __V((void *arg, char *fmt, ...))
396 struct buffer_info *bi;
398 #if defined(__STDC__)
404 arg = va_arg(pvar, void *);
405 fmt = va_arg(pvar, char *);
408 bi = (struct buffer_info *) arg;
409 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
418 * log_packet - format a packet and log it.
422 log_packet(p, len, prefix, level)
428 init_pr_log(prefix, level);
429 format_packet(p, len, pr_log, &level);
435 * format_packet - make a readable representation of a packet,
436 * calling `printer(arg, format, ...)' to output it.
439 format_packet(p, len, printer, arg)
442 void (*printer) __P((void *, char *, ...));
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);
485 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
488 static char line[256]; /* line to be logged accumulated here */
489 static char *linep; /* current pointer within line */
490 static int llevel; /* level for logging */
493 init_pr_log(prefix, level)
498 if (prefix != NULL) {
499 strlcpy(line, prefix, sizeof(line));
500 linep = line + strlen(line);
510 log_write(llevel, line);
515 * pr_log - printer routine for outputting to syslog
518 pr_log __V((void *arg, char *fmt, ...))
525 #if defined(__STDC__)
531 arg = va_arg(pvar, void *);
532 fmt = va_arg(pvar, char *);
535 n = vslprintf(buf, sizeof(buf), fmt, pvar);
539 eol = strchr(buf, '\n');
541 l = (eol == NULL)? n: eol - buf;
542 if (linep + l < line + sizeof(line)) {
544 memcpy(linep, buf, l);
550 eol = strchr(p, '\n');
553 log_write(llevel, line);
557 while (eol != NULL) {
559 log_write(llevel, p);
561 eol = strchr(p, '\n');
564 /* assumes sizeof(buf) <= sizeof(line) */
573 * print_string - print a readable representation of a string using
577 print_string(p, len, printer, arg)
580 void (*printer) __P((void *, char *, ...));
586 for (; len > 0; --len) {
588 if (' ' <= c && c <= '~') {
589 if (c == '\\' || c == '"')
591 printer(arg, "%c", c);
604 printer(arg, "\\%.3o", c);
612 * logit - does the hard work for fatal et al.
615 logit(level, fmt, args)
623 n = vslprintf(buf, sizeof(buf), fmt, args);
624 log_write(level, buf);
628 log_write(level, buf)
632 syslog(level, "%s", buf);
633 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
636 if (n > 0 && buf[n-1] == '\n')
638 if (write(log_to_fd, buf, n) != n
639 || write(log_to_fd, "\n", 1) != 1)
645 * fatal - log an error message and die horribly.
648 fatal __V((char *fmt, ...))
652 #if defined(__STDC__)
657 fmt = va_arg(pvar, char *);
660 logit(LOG_ERR, fmt, pvar);
663 die(1); /* as promised */
667 * error - log an error message.
670 error __V((char *fmt, ...))
674 #if defined(__STDC__)
679 fmt = va_arg(pvar, char *);
682 logit(LOG_ERR, fmt, pvar);
687 * warn - log a warning message.
690 warn __V((char *fmt, ...))
694 #if defined(__STDC__)
699 fmt = va_arg(pvar, char *);
702 logit(LOG_WARNING, fmt, pvar);
707 * notice - log a notice-level message.
710 notice __V((char *fmt, ...))
714 #if defined(__STDC__)
719 fmt = va_arg(pvar, char *);
722 logit(LOG_NOTICE, fmt, pvar);
727 * info - log an informational message.
730 info __V((char *fmt, ...))
734 #if defined(__STDC__)
739 fmt = va_arg(pvar, char *);
742 logit(LOG_INFO, fmt, pvar);
747 * dbglog - log a debug message.
750 dbglog __V((char *fmt, ...))
754 #if defined(__STDC__)
759 fmt = va_arg(pvar, char *);
762 logit(LOG_DEBUG, fmt, pvar);
767 * dump_packet - print out a packet in readable form if it is interesting.
768 * Assumes len >= PPP_HDRLEN.
771 dump_packet(const char *tag, unsigned char *p, int len)
779 * don't print LCP echo request/reply packets if debug <= 1
780 * and the link is up.
782 proto = (p[2] << 8) + p[3];
783 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
784 && len >= PPP_HDRLEN + HEADERLEN) {
785 unsigned char *lcp = p + PPP_HDRLEN;
786 int l = (lcp[2] << 8) + lcp[3];
788 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
789 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
793 dbglog("%s %P", tag, p, len);
796 /* Procedures for locking the serial device using a lock file. */
799 #define LOCK_DIR "/var/lock"
802 #define LOCK_DIR "/var/spool/locks"
804 #define LOCK_DIR "/var/spool/lock"
807 #endif /* LOCK_DIR */
809 static char lock_file[MAXPATHLEN];
812 * lock - create a lock file for the named device
821 result = mklock (dev, (void *) 0);
823 strlcpy(lock_file, sizeof(lock_file), dev);
828 notice("Device %s is locked by pid %d", dev, result);
830 error("Can't create lock file %s", lock_file);
835 char lock_buffer[12];
841 if (stat(dev, &sbuf) < 0) {
842 error("Can't get device number for %s: %m", dev);
845 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
846 error("Can't lock %s: not a character device", dev);
849 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
850 LOCK_DIR, major(sbuf.st_dev),
851 major(sbuf.st_rdev), minor(sbuf.st_rdev));
855 if ((p = strrchr(dev, '/')) != NULL)
857 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
860 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
861 if (errno != EEXIST) {
862 error("Can't create lock file %s: %m", lock_file);
866 /* Read the lock file to find out who has the device locked. */
867 fd = open(lock_file, O_RDONLY, 0);
869 if (errno == ENOENT) /* This is just a timing problem. */
871 error("Can't open existing lock file %s: %m", lock_file);
875 n = read(fd, lock_buffer, 11);
877 n = read(fd, &pid, sizeof(pid));
878 #endif /* LOCK_BINARY */
882 error("Can't read pid from lock file %s", lock_file);
886 /* See if the process still exists. */
889 pid = atoi(lock_buffer);
890 #endif /* LOCK_BINARY */
892 return 1; /* somebody else locked it for us */
894 || (kill(pid, 0) == -1 && errno == ESRCH)) {
895 if (unlink (lock_file) == 0) {
896 notice("Removed stale lock on %s (pid %d)", dev, pid);
899 warn("Couldn't remove stale lock on %s", dev);
901 notice("Device %s is locked by pid %d", dev, pid);
912 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
913 write (fd, lock_buffer, 11);
915 write(fd, &pid, sizeof (pid));
924 * relock - called to update our lockfile when we are about to detach,
925 * thus changing our pid (we fork, the child carries on, and the parent dies).
926 * Note that this is called by the parent, with pid equal to the pid
927 * of the child. This avoids a potential race which would exist if
928 * we had the child rewrite the lockfile (the parent might die first,
929 * and another process could think the lock was stale if it checked
930 * between when the parent died and the child rewrote the lockfile).
937 /* XXX is there a way to do this? */
942 char lock_buffer[12];
944 if (lock_file[0] == 0)
946 fd = open(lock_file, O_WRONLY, 0);
948 error("Couldn't reopen lock file %s: %m", lock_file);
954 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
955 write (fd, lock_buffer, 11);
957 write(fd, &pid, sizeof(pid));
958 #endif /* LOCK_BINARY */
966 * unlock - remove our lockfile
973 (void) rmlock(lock_file, (void *) 0);