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.17 2002/01/14 15:31:34 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';
213 i = va_arg(args, int);
222 val = va_arg(args, unsigned int);
226 val = va_arg(args, unsigned int);
231 val = va_arg(args, unsigned int);
235 val = (unsigned long) va_arg(args, void *);
240 str = va_arg(args, char *);
243 num[0] = va_arg(args, int);
248 str = strerror(errno);
251 ip = va_arg(args, u_int32_t);
253 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
254 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
258 f = va_arg(args, char *);
260 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
262 /* On the powerpc, a va_list is an array of 1 structure */
263 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
271 str += 4; /* chop off the day name */
272 str[15] = 0; /* chop off year and newline */
274 case 'v': /* "visible" string */
275 case 'q': /* quoted string */
277 p = va_arg(args, unsigned char *);
278 if (fillch == '0' && prec >= 0) {
281 n = strlen((char *)p);
282 if (prec >= 0 && n > prec)
285 while (n > 0 && buflen > 0) {
288 if (!quoted && c >= 0x80) {
293 if (quoted && (c == '"' || c == '\\'))
295 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
299 case '\t': OUTCHAR('t'); break;
300 case '\n': OUTCHAR('n'); break;
301 case '\b': OUTCHAR('b'); break;
302 case '\f': OUTCHAR('f'); break;
305 OUTCHAR(hexchars[c >> 4]);
306 OUTCHAR(hexchars[c & 0xf]);
320 case 'P': /* print PPP packet */
322 bufinfo.len = buflen + 1;
323 p = va_arg(args, unsigned char *);
324 n = va_arg(args, int);
325 format_packet(p, n, vslp_printer, &bufinfo);
327 buflen = bufinfo.len - 1;
330 p = va_arg(args, unsigned char *);
331 for (n = prec; n > 0; --n) {
335 OUTCHAR(hexchars[(c >> 4) & 0xf]);
336 OUTCHAR(hexchars[c & 0xf]);
342 --fmt; /* so %z outputs %z etc. */
347 str = num + sizeof(num);
349 while (str > num + neg) {
350 *--str = hexchars[val % base];
352 if (--prec <= 0 && val == 0)
364 len = num + sizeof(num) - 1 - str;
367 if (prec >= 0 && len > prec)
373 if ((n = width - len) > 0) {
381 memcpy(buf, str, len);
390 * vslp_printer - used in processing a %P format
393 vslp_printer __V((void *arg, char *fmt, ...))
397 struct buffer_info *bi;
399 #if defined(__STDC__)
405 arg = va_arg(pvar, void *);
406 fmt = va_arg(pvar, char *);
409 bi = (struct buffer_info *) arg;
410 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
419 * log_packet - format a packet and log it.
423 log_packet(p, len, prefix, level)
429 init_pr_log(prefix, level);
430 format_packet(p, len, pr_log, &level);
436 * format_packet - make a readable representation of a packet,
437 * calling `printer(arg, format, ...)' to output it.
440 format_packet(p, len, printer, arg)
443 void (*printer) __P((void *, char *, ...));
448 struct protent *protp;
450 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
454 for (i = 0; (protp = protocols[i]) != NULL; ++i)
455 if (proto == protp->protocol)
458 printer(arg, "[%s", protp->name);
459 n = (*protp->printpkt)(p, len, printer, arg);
464 for (i = 0; (protp = protocols[i]) != NULL; ++i)
465 if (proto == (protp->protocol & ~0x8000))
467 if (protp != 0 && protp->data_name != 0) {
468 printer(arg, "[%s data]", protp->data_name);
470 printer(arg, "%.8B ...", p);
472 printer(arg, "%.*B", len, p);
475 printer(arg, "[proto=0x%x]", proto);
480 printer(arg, "%.32B ...", p);
482 printer(arg, "%.*B", len, p);
486 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
489 static char line[256]; /* line to be logged accumulated here */
490 static char *linep; /* current pointer within line */
491 static int llevel; /* level for logging */
494 init_pr_log(prefix, level)
499 if (prefix != NULL) {
500 strlcpy(line, prefix, sizeof(line));
501 linep = line + strlen(line);
511 log_write(llevel, line);
516 * pr_log - printer routine for outputting to syslog
519 pr_log __V((void *arg, char *fmt, ...))
526 #if defined(__STDC__)
532 arg = va_arg(pvar, void *);
533 fmt = va_arg(pvar, char *);
536 n = vslprintf(buf, sizeof(buf), fmt, pvar);
540 eol = strchr(buf, '\n');
542 l = (eol == NULL)? n: eol - buf;
543 if (linep + l < line + sizeof(line)) {
545 memcpy(linep, buf, l);
551 eol = strchr(p, '\n');
554 log_write(llevel, line);
558 while (eol != NULL) {
560 log_write(llevel, p);
562 eol = strchr(p, '\n');
565 /* assumes sizeof(buf) <= sizeof(line) */
574 * print_string - print a readable representation of a string using
578 print_string(p, len, printer, arg)
581 void (*printer) __P((void *, char *, ...));
587 for (; len > 0; --len) {
589 if (' ' <= c && c <= '~') {
590 if (c == '\\' || c == '"')
592 printer(arg, "%c", c);
605 printer(arg, "\\%.3o", c);
613 * logit - does the hard work for fatal et al.
616 logit(level, fmt, args)
624 n = vslprintf(buf, sizeof(buf), fmt, args);
625 log_write(level, buf);
629 log_write(level, buf)
633 syslog(level, "%s", buf);
634 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
637 if (n > 0 && buf[n-1] == '\n')
639 if (write(log_to_fd, buf, n) != n
640 || write(log_to_fd, "\n", 1) != 1)
646 * fatal - log an error message and die horribly.
649 fatal __V((char *fmt, ...))
653 #if defined(__STDC__)
658 fmt = va_arg(pvar, char *);
661 logit(LOG_ERR, fmt, pvar);
664 die(1); /* as promised */
668 * error - log an error message.
671 error __V((char *fmt, ...))
675 #if defined(__STDC__)
680 fmt = va_arg(pvar, char *);
683 logit(LOG_ERR, fmt, pvar);
688 * warn - log a warning message.
691 warn __V((char *fmt, ...))
695 #if defined(__STDC__)
700 fmt = va_arg(pvar, char *);
703 logit(LOG_WARNING, fmt, pvar);
708 * notice - log a notice-level message.
711 notice __V((char *fmt, ...))
715 #if defined(__STDC__)
720 fmt = va_arg(pvar, char *);
723 logit(LOG_NOTICE, fmt, pvar);
728 * info - log an informational message.
731 info __V((char *fmt, ...))
735 #if defined(__STDC__)
740 fmt = va_arg(pvar, char *);
743 logit(LOG_INFO, fmt, pvar);
748 * dbglog - log a debug message.
751 dbglog __V((char *fmt, ...))
755 #if defined(__STDC__)
760 fmt = va_arg(pvar, char *);
763 logit(LOG_DEBUG, fmt, pvar);
768 * dump_packet - print out a packet in readable form if it is interesting.
769 * Assumes len >= PPP_HDRLEN.
772 dump_packet(const char *tag, unsigned char *p, int len)
780 * don't print LCP echo request/reply packets if debug <= 1
781 * and the link is up.
783 proto = (p[2] << 8) + p[3];
784 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
785 && len >= PPP_HDRLEN + HEADERLEN) {
786 unsigned char *lcp = p + PPP_HDRLEN;
787 int l = (lcp[2] << 8) + lcp[3];
789 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
790 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
794 dbglog("%s %P", tag, p, len);
797 /* Procedures for locking the serial device using a lock file. */
800 #define LOCK_DIR "/var/lock"
803 #define LOCK_DIR "/var/spool/locks"
805 #define LOCK_DIR "/var/spool/lock"
808 #endif /* LOCK_DIR */
810 static char lock_file[MAXPATHLEN];
813 * lock - create a lock file for the named device
822 result = mklock (dev, (void *) 0);
824 strlcpy(lock_file, dev, sizeof(lock_file));
829 notice("Device %s is locked by pid %d", dev, result);
831 error("Can't create lock file %s", lock_file);
836 char lock_buffer[12];
842 if (stat(dev, &sbuf) < 0) {
843 error("Can't get device number for %s: %m", dev);
846 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
847 error("Can't lock %s: not a character device", dev);
850 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
851 LOCK_DIR, major(sbuf.st_dev),
852 major(sbuf.st_rdev), minor(sbuf.st_rdev));
855 char lockdev[MAXPATHLEN];
857 if ((p = strstr(dev, "dev/")) != NULL) {
859 strncpy(lockdev, dev, MAXPATHLEN-1);
860 lockdev[MAXPATHLEN-1] = 0;
861 while ((p = strrchr(lockdev, '/')) != NULL) {
866 if ((p = strrchr(dev, '/')) != NULL)
869 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
872 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
873 if (errno != EEXIST) {
874 error("Can't create lock file %s: %m", lock_file);
878 /* Read the lock file to find out who has the device locked. */
879 fd = open(lock_file, O_RDONLY, 0);
881 if (errno == ENOENT) /* This is just a timing problem. */
883 error("Can't open existing lock file %s: %m", lock_file);
887 n = read(fd, lock_buffer, 11);
889 n = read(fd, &pid, sizeof(pid));
890 #endif /* LOCK_BINARY */
894 error("Can't read pid from lock file %s", lock_file);
898 /* See if the process still exists. */
901 pid = atoi(lock_buffer);
902 #endif /* LOCK_BINARY */
904 return 1; /* somebody else locked it for us */
906 || (kill(pid, 0) == -1 && errno == ESRCH)) {
907 if (unlink (lock_file) == 0) {
908 notice("Removed stale lock on %s (pid %d)", dev, pid);
911 warn("Couldn't remove stale lock on %s", dev);
913 notice("Device %s is locked by pid %d", dev, pid);
924 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
925 write (fd, lock_buffer, 11);
927 write(fd, &pid, sizeof (pid));
936 * relock - called to update our lockfile when we are about to detach,
937 * thus changing our pid (we fork, the child carries on, and the parent dies).
938 * Note that this is called by the parent, with pid equal to the pid
939 * of the child. This avoids a potential race which would exist if
940 * we had the child rewrite the lockfile (the parent might die first,
941 * and another process could think the lock was stale if it checked
942 * between when the parent died and the child rewrote the lockfile).
949 /* XXX is there a way to do this? */
954 char lock_buffer[12];
956 if (lock_file[0] == 0)
958 fd = open(lock_file, O_WRONLY, 0);
960 error("Couldn't reopen lock file %s: %m", lock_file);
966 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
967 write (fd, lock_buffer, 11);
969 write(fd, &pid, sizeof(pid));
970 #endif /* LOCK_BINARY */
978 * unlock - remove our lockfile
985 (void) rmlock(lock_file, (void *) 0);