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.10 2000/03/27 01:36:48 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 pr_log __P((void *, char *, ...));
55 static void logit __P((int, char *, va_list));
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);
411 * log_packet - format a packet and log it.
414 char line[256]; /* line to be logged accumulated here */
418 log_packet(p, len, prefix, level)
424 strlcpy(line, prefix, sizeof(line));
425 linep = line + strlen(line);
426 format_packet(p, len, pr_log, NULL);
428 syslog(level, "%s", line);
432 * format_packet - make a readable representation of a packet,
433 * calling `printer(arg, format, ...)' to output it.
436 format_packet(p, len, printer, arg)
439 void (*printer) __P((void *, char *, ...));
444 struct protent *protp;
446 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
450 for (i = 0; (protp = protocols[i]) != NULL; ++i)
451 if (proto == protp->protocol)
454 printer(arg, "[%s", protp->name);
455 n = (*protp->printpkt)(p, len, printer, arg);
460 for (i = 0; (protp = protocols[i]) != NULL; ++i)
461 if (proto == (protp->protocol & ~0x8000))
463 if (protp != 0 && protp->data_name != 0) {
464 printer(arg, "[%s data]", protp->data_name);
466 printer(arg, "%.8B ...", p);
468 printer(arg, "%.*B", len, p);
471 printer(arg, "[proto=0x%x]", proto);
476 printer(arg, "%.32B ...", p);
478 printer(arg, "%.*B", len, p);
482 pr_log __V((void *arg, char *fmt, ...))
488 #if defined(__STDC__)
494 arg = va_arg(pvar, void *);
495 fmt = va_arg(pvar, char *);
498 n = vslprintf(buf, sizeof(buf), fmt, pvar);
501 if (linep + n + 1 > line + sizeof(line)) {
502 syslog(LOG_DEBUG, "%s", line);
505 strlcpy(linep, buf, line + sizeof(line) - linep);
510 * print_string - print a readable representation of a string using
514 print_string(p, len, printer, arg)
517 void (*printer) __P((void *, char *, ...));
523 for (; len > 0; --len) {
525 if (' ' <= c && c <= '~') {
526 if (c == '\\' || c == '"')
528 printer(arg, "%c", c);
541 printer(arg, "\\%.3o", c);
549 * logit - does the hard work for fatal et al.
552 logit(level, fmt, args)
560 n = vslprintf(buf, sizeof(buf), fmt, args);
561 syslog(level, "%s", buf);
562 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
563 if (buf[n-1] != '\n')
565 if (write(log_to_fd, buf, n) != n)
571 * fatal - log an error message and die horribly.
574 fatal __V((char *fmt, ...))
578 #if defined(__STDC__)
583 fmt = va_arg(pvar, char *);
586 logit(LOG_ERR, fmt, pvar);
589 die(1); /* as promised */
593 * error - log an error message.
596 error __V((char *fmt, ...))
600 #if defined(__STDC__)
605 fmt = va_arg(pvar, char *);
608 logit(LOG_ERR, fmt, pvar);
613 * warn - log a warning message.
616 warn __V((char *fmt, ...))
620 #if defined(__STDC__)
625 fmt = va_arg(pvar, char *);
628 logit(LOG_WARNING, fmt, pvar);
633 * notice - log a notice-level message.
636 notice __V((char *fmt, ...))
640 #if defined(__STDC__)
645 fmt = va_arg(pvar, char *);
648 logit(LOG_NOTICE, fmt, pvar);
653 * info - log an informational message.
656 info __V((char *fmt, ...))
660 #if defined(__STDC__)
665 fmt = va_arg(pvar, char *);
668 logit(LOG_INFO, fmt, pvar);
673 * dbglog - log a debug message.
676 dbglog __V((char *fmt, ...))
680 #if defined(__STDC__)
685 fmt = va_arg(pvar, char *);
688 logit(LOG_DEBUG, fmt, pvar);
692 /* Procedures for locking the serial device using a lock file. */
695 #define LOCK_DIR "/var/lock"
698 #define LOCK_DIR "/var/spool/locks"
700 #define LOCK_DIR "/var/spool/lock"
703 #endif /* LOCK_DIR */
705 static char lock_file[MAXPATHLEN];
708 * lock - create a lock file for the named device
717 result = mklock (dev, (void *) 0);
719 strlcpy(lock_file, sizeof(lock_file), dev);
724 notice("Device %s is locked by pid %d", dev, result);
726 error("Can't create lock file %s", lock_file);
731 char lock_buffer[12];
737 if (stat(dev, &sbuf) < 0) {
738 error("Can't get device number for %s: %m", dev);
741 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
742 error("Can't lock %s: not a character device", dev);
745 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
746 LOCK_DIR, major(sbuf.st_dev),
747 major(sbuf.st_rdev), minor(sbuf.st_rdev));
751 if ((p = strrchr(dev, '/')) != NULL)
753 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
756 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
757 if (errno != EEXIST) {
758 error("Can't create lock file %s: %m", lock_file);
762 /* Read the lock file to find out who has the device locked. */
763 fd = open(lock_file, O_RDONLY, 0);
765 if (errno == ENOENT) /* This is just a timing problem. */
767 error("Can't open existing lock file %s: %m", lock_file);
771 n = read(fd, lock_buffer, 11);
773 n = read(fd, &pid, sizeof(pid));
774 #endif /* LOCK_BINARY */
778 error("Can't read pid from lock file %s", lock_file);
782 /* See if the process still exists. */
785 pid = atoi(lock_buffer);
786 #endif /* LOCK_BINARY */
788 return 1; /* somebody else locked it for us */
790 || (kill(pid, 0) == -1 && errno == ESRCH)) {
791 if (unlink (lock_file) == 0) {
792 notice("Removed stale lock on %s (pid %d)", dev, pid);
795 warn("Couldn't remove stale lock on %s", dev);
797 notice("Device %s is locked by pid %d", dev, pid);
808 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
809 write (fd, lock_buffer, 11);
811 write(fd, &pid, sizeof (pid));
820 * relock - called to update our lockfile when we are about to detach,
821 * thus changing our pid (we fork, the child carries on, and the parent dies).
822 * Note that this is called by the parent, with pid equal to the pid
823 * of the child. This avoids a potential race which would exist if
824 * we had the child rewrite the lockfile (the parent might die first,
825 * and another process could think the lock was stale if it checked
826 * between when the parent died and the child rewrote the lockfile).
833 /* XXX is there a way to do this? */
838 char lock_buffer[12];
840 if (lock_file[0] == 0)
842 fd = open(lock_file, O_WRONLY, 0);
844 error("Couldn't reopen lock file %s: %m", lock_file);
850 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
851 write (fd, lock_buffer, 11);
853 write(fd, &pid, sizeof(pid));
854 #endif /* LOCK_BINARY */
862 * unlock - remove our lockfile
869 (void) rmlock(lock_file, (void *) 0);