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.18 2002/03/05 15:14:04 dfs Exp $"
35 #include <sys/param.h>
36 #include <sys/types.h>
39 #include <sys/resource.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
44 #include <sys/mkdev.h>
51 static const char rcsid[] = RCSID;
54 extern char *strerror();
57 static void logit __P((int, char *, va_list));
58 static void log_write __P((int, char *));
59 static void vslp_printer __P((void *, char *, ...));
60 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
69 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
70 * always leaves destination null-terminated (for len > 0).
73 strlcpy(dest, src, len)
78 size_t ret = strlen(src);
84 strncpy(dest, src, len - 1);
92 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
93 * always leaves destination null-terminated (for len > 0).
96 strlcat(dest, src, len)
101 size_t dlen = strlen(dest);
103 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
108 * slprintf - format a message into a buffer. Like sprintf except we
109 * also specify the length of the output buffer, and we handle
110 * %r (recursive format), %m (error message), %v (visible string),
111 * %q (quoted string), %t (current time) and %I (IP address) formats.
112 * Doesn't do floating-point formats.
113 * Returns the number of chars put into buf.
116 slprintf __V((char *buf, int buflen, char *fmt, ...))
121 #if defined(__STDC__)
128 buf = va_arg(args, char *);
129 buflen = va_arg(args, int);
130 fmt = va_arg(args, char *);
132 n = vslprintf(buf, buflen, fmt, args);
138 * vslprintf - like slprintf, takes a va_list instead of a list of args.
140 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
143 vslprintf(buf, buflen, fmt, args)
150 int width, prec, fillch;
151 int base, len, neg, quoted;
152 unsigned long val = 0;
153 char *str, *f, *buf0;
158 static char hexchars[] = "0123456789abcdef";
159 struct buffer_info bufinfo;
164 for (f = fmt; *f != '%' && *f != 0; ++f)
170 memcpy(buf, fmt, len);
186 width = va_arg(args, int);
190 width = width * 10 + c - '0';
197 prec = va_arg(args, int);
202 prec = prec * 10 + c - '0';
216 val = va_arg(args, long);
224 val = va_arg(args, unsigned long);
228 *buf++ = '%'; --buflen;
229 *buf++ = 'l'; --buflen;
230 --fmt; /* so %lz outputs %lz etc. */
235 i = va_arg(args, int);
244 val = va_arg(args, unsigned int);
248 val = va_arg(args, unsigned int);
253 val = va_arg(args, unsigned int);
257 val = (unsigned long) va_arg(args, void *);
262 str = va_arg(args, char *);
265 num[0] = va_arg(args, int);
270 str = strerror(errno);
273 ip = va_arg(args, u_int32_t);
275 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
276 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
280 f = va_arg(args, char *);
282 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
284 /* On the powerpc, a va_list is an array of 1 structure */
285 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
293 str += 4; /* chop off the day name */
294 str[15] = 0; /* chop off year and newline */
296 case 'v': /* "visible" string */
297 case 'q': /* quoted string */
299 p = va_arg(args, unsigned char *);
300 if (fillch == '0' && prec >= 0) {
303 n = strlen((char *)p);
304 if (prec >= 0 && n > prec)
307 while (n > 0 && buflen > 0) {
310 if (!quoted && c >= 0x80) {
315 if (quoted && (c == '"' || c == '\\'))
317 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
321 case '\t': OUTCHAR('t'); break;
322 case '\n': OUTCHAR('n'); break;
323 case '\b': OUTCHAR('b'); break;
324 case '\f': OUTCHAR('f'); break;
327 OUTCHAR(hexchars[c >> 4]);
328 OUTCHAR(hexchars[c & 0xf]);
342 case 'P': /* print PPP packet */
344 bufinfo.len = buflen + 1;
345 p = va_arg(args, unsigned char *);
346 n = va_arg(args, int);
347 format_packet(p, n, vslp_printer, &bufinfo);
349 buflen = bufinfo.len - 1;
352 p = va_arg(args, unsigned char *);
353 for (n = prec; n > 0; --n) {
357 OUTCHAR(hexchars[(c >> 4) & 0xf]);
358 OUTCHAR(hexchars[c & 0xf]);
364 --fmt; /* so %z outputs %z etc. */
369 str = num + sizeof(num);
371 while (str > num + neg) {
372 *--str = hexchars[val % base];
374 if (--prec <= 0 && val == 0)
386 len = num + sizeof(num) - 1 - str;
389 if (prec >= 0 && len > prec)
395 if ((n = width - len) > 0) {
403 memcpy(buf, str, len);
412 * vslp_printer - used in processing a %P format
415 vslp_printer __V((void *arg, char *fmt, ...))
419 struct buffer_info *bi;
421 #if defined(__STDC__)
427 arg = va_arg(pvar, void *);
428 fmt = va_arg(pvar, char *);
431 bi = (struct buffer_info *) arg;
432 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
441 * log_packet - format a packet and log it.
445 log_packet(p, len, prefix, level)
451 init_pr_log(prefix, level);
452 format_packet(p, len, pr_log, &level);
458 * format_packet - make a readable representation of a packet,
459 * calling `printer(arg, format, ...)' to output it.
462 format_packet(p, len, printer, arg)
465 void (*printer) __P((void *, char *, ...));
470 struct protent *protp;
472 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
476 for (i = 0; (protp = protocols[i]) != NULL; ++i)
477 if (proto == protp->protocol)
480 printer(arg, "[%s", protp->name);
481 n = (*protp->printpkt)(p, len, printer, arg);
486 for (i = 0; (protp = protocols[i]) != NULL; ++i)
487 if (proto == (protp->protocol & ~0x8000))
489 if (protp != 0 && protp->data_name != 0) {
490 printer(arg, "[%s data]", protp->data_name);
492 printer(arg, "%.8B ...", p);
494 printer(arg, "%.*B", len, p);
497 printer(arg, "[proto=0x%x]", proto);
502 printer(arg, "%.32B ...", p);
504 printer(arg, "%.*B", len, p);
508 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
511 static char line[256]; /* line to be logged accumulated here */
512 static char *linep; /* current pointer within line */
513 static int llevel; /* level for logging */
516 init_pr_log(prefix, level)
521 if (prefix != NULL) {
522 strlcpy(line, prefix, sizeof(line));
523 linep = line + strlen(line);
533 log_write(llevel, line);
538 * pr_log - printer routine for outputting to syslog
541 pr_log __V((void *arg, char *fmt, ...))
548 #if defined(__STDC__)
554 arg = va_arg(pvar, void *);
555 fmt = va_arg(pvar, char *);
558 n = vslprintf(buf, sizeof(buf), fmt, pvar);
562 eol = strchr(buf, '\n');
564 l = (eol == NULL)? n: eol - buf;
565 if (linep + l < line + sizeof(line)) {
567 memcpy(linep, buf, l);
573 eol = strchr(p, '\n');
576 log_write(llevel, line);
580 while (eol != NULL) {
582 log_write(llevel, p);
584 eol = strchr(p, '\n');
587 /* assumes sizeof(buf) <= sizeof(line) */
596 * print_string - print a readable representation of a string using
600 print_string(p, len, printer, arg)
603 void (*printer) __P((void *, char *, ...));
609 for (; len > 0; --len) {
611 if (' ' <= c && c <= '~') {
612 if (c == '\\' || c == '"')
614 printer(arg, "%c", c);
627 printer(arg, "\\%.3o", c);
635 * logit - does the hard work for fatal et al.
638 logit(level, fmt, args)
646 n = vslprintf(buf, sizeof(buf), fmt, args);
647 log_write(level, buf);
651 log_write(level, buf)
655 syslog(level, "%s", buf);
656 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
659 if (n > 0 && buf[n-1] == '\n')
661 if (write(log_to_fd, buf, n) != n
662 || write(log_to_fd, "\n", 1) != 1)
668 * fatal - log an error message and die horribly.
671 fatal __V((char *fmt, ...))
675 #if defined(__STDC__)
680 fmt = va_arg(pvar, char *);
683 logit(LOG_ERR, fmt, pvar);
686 die(1); /* as promised */
690 * error - log an error message.
693 error __V((char *fmt, ...))
697 #if defined(__STDC__)
702 fmt = va_arg(pvar, char *);
705 logit(LOG_ERR, fmt, pvar);
710 * warn - log a warning message.
713 warn __V((char *fmt, ...))
717 #if defined(__STDC__)
722 fmt = va_arg(pvar, char *);
725 logit(LOG_WARNING, fmt, pvar);
730 * notice - log a notice-level message.
733 notice __V((char *fmt, ...))
737 #if defined(__STDC__)
742 fmt = va_arg(pvar, char *);
745 logit(LOG_NOTICE, fmt, pvar);
750 * info - log an informational message.
753 info __V((char *fmt, ...))
757 #if defined(__STDC__)
762 fmt = va_arg(pvar, char *);
765 logit(LOG_INFO, fmt, pvar);
770 * dbglog - log a debug message.
773 dbglog __V((char *fmt, ...))
777 #if defined(__STDC__)
782 fmt = va_arg(pvar, char *);
785 logit(LOG_DEBUG, fmt, pvar);
790 * dump_packet - print out a packet in readable form if it is interesting.
791 * Assumes len >= PPP_HDRLEN.
794 dump_packet(const char *tag, unsigned char *p, int len)
802 * don't print LCP echo request/reply packets if debug <= 1
803 * and the link is up.
805 proto = (p[2] << 8) + p[3];
806 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
807 && len >= PPP_HDRLEN + HEADERLEN) {
808 unsigned char *lcp = p + PPP_HDRLEN;
809 int l = (lcp[2] << 8) + lcp[3];
811 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
812 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
816 dbglog("%s %P", tag, p, len);
819 /* Procedures for locking the serial device using a lock file. */
822 #define LOCK_DIR "/var/lock"
825 #define LOCK_DIR "/var/spool/locks"
827 #define LOCK_DIR "/var/spool/lock"
830 #endif /* LOCK_DIR */
832 static char lock_file[MAXPATHLEN];
835 * lock - create a lock file for the named device
844 result = mklock (dev, (void *) 0);
846 strlcpy(lock_file, dev, sizeof(lock_file));
851 notice("Device %s is locked by pid %d", dev, result);
853 error("Can't create lock file %s", lock_file);
858 char lock_buffer[12];
864 if (stat(dev, &sbuf) < 0) {
865 error("Can't get device number for %s: %m", dev);
868 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
869 error("Can't lock %s: not a character device", dev);
872 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
873 LOCK_DIR, major(sbuf.st_dev),
874 major(sbuf.st_rdev), minor(sbuf.st_rdev));
877 char lockdev[MAXPATHLEN];
879 if ((p = strstr(dev, "dev/")) != NULL) {
881 strncpy(lockdev, dev, MAXPATHLEN-1);
882 lockdev[MAXPATHLEN-1] = 0;
883 while ((p = strrchr(lockdev, '/')) != NULL) {
888 if ((p = strrchr(dev, '/')) != NULL)
891 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
894 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
895 if (errno != EEXIST) {
896 error("Can't create lock file %s: %m", lock_file);
900 /* Read the lock file to find out who has the device locked. */
901 fd = open(lock_file, O_RDONLY, 0);
903 if (errno == ENOENT) /* This is just a timing problem. */
905 error("Can't open existing lock file %s: %m", lock_file);
909 n = read(fd, lock_buffer, 11);
911 n = read(fd, &pid, sizeof(pid));
912 #endif /* LOCK_BINARY */
916 error("Can't read pid from lock file %s", lock_file);
920 /* See if the process still exists. */
923 pid = atoi(lock_buffer);
924 #endif /* LOCK_BINARY */
926 return 1; /* somebody else locked it for us */
928 || (kill(pid, 0) == -1 && errno == ESRCH)) {
929 if (unlink (lock_file) == 0) {
930 notice("Removed stale lock on %s (pid %d)", dev, pid);
933 warn("Couldn't remove stale lock on %s", dev);
935 notice("Device %s is locked by pid %d", dev, pid);
946 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
947 write (fd, lock_buffer, 11);
949 write(fd, &pid, sizeof (pid));
958 * relock - called to update our lockfile when we are about to detach,
959 * thus changing our pid (we fork, the child carries on, and the parent dies).
960 * Note that this is called by the parent, with pid equal to the pid
961 * of the child. This avoids a potential race which would exist if
962 * we had the child rewrite the lockfile (the parent might die first,
963 * and another process could think the lock was stale if it checked
964 * between when the parent died and the child rewrote the lockfile).
971 /* XXX is there a way to do this? */
976 char lock_buffer[12];
978 if (lock_file[0] == 0)
980 fd = open(lock_file, O_WRONLY, 0);
982 error("Couldn't reopen lock file %s: %m", lock_file);
988 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
989 write (fd, lock_buffer, 11);
991 write(fd, &pid, sizeof(pid));
992 #endif /* LOCK_BINARY */
1000 * unlock - remove our lockfile
1007 (void) rmlock(lock_file, (void *) 0);