2 * utils.c - various utility functions used in pppd.
4 * Copyright (c) 1999-2002 Paul Mackerras. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. The name(s) of the authors of this software must not be used to
14 * endorse or promote products derived from this software without
15 * prior written permission.
17 * 3. Redistributions of any form whatsoever must retain the following
19 * "This product includes software developed by Paul Mackerras
20 * <paulus@samba.org>".
22 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
23 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
24 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
25 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
27 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
28 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
31 #define RCSID "$Id: utils.c,v 1.24 2004/11/04 10:02:26 paulus Exp $"
46 #include <sys/param.h>
47 #include <sys/types.h>
50 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
55 #include <sys/mkdev.h>
62 static const char rcsid[] = RCSID;
65 extern char *strerror();
68 static void logit __P((int, char *, va_list));
69 static void log_write __P((int, char *));
70 static void vslp_printer __P((void *, char *, ...));
71 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
80 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
81 * always leaves destination null-terminated (for len > 0).
84 strlcpy(dest, src, len)
89 size_t ret = strlen(src);
95 strncpy(dest, src, len - 1);
103 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
104 * always leaves destination null-terminated (for len > 0).
107 strlcat(dest, src, len)
112 size_t dlen = strlen(dest);
114 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
119 * slprintf - format a message into a buffer. Like sprintf except we
120 * also specify the length of the output buffer, and we handle
121 * %m (error message), %v (visible string),
122 * %q (quoted string), %t (current time) and %I (IP address) formats.
123 * Doesn't do floating-point formats.
124 * Returns the number of chars put into buf.
127 slprintf __V((char *buf, int buflen, char *fmt, ...))
132 #if defined(__STDC__)
139 buf = va_arg(args, char *);
140 buflen = va_arg(args, int);
141 fmt = va_arg(args, char *);
143 n = vslprintf(buf, buflen, fmt, args);
149 * vslprintf - like slprintf, takes a va_list instead of a list of args.
151 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
154 vslprintf(buf, buflen, fmt, args)
161 int width, prec, fillch;
162 int base, len, neg, quoted;
163 unsigned long val = 0;
164 char *str, *f, *buf0;
169 static char hexchars[] = "0123456789abcdef";
170 struct buffer_info bufinfo;
175 for (f = fmt; *f != '%' && *f != 0; ++f)
181 memcpy(buf, fmt, len);
197 width = va_arg(args, int);
201 width = width * 10 + c - '0';
208 prec = va_arg(args, int);
213 prec = prec * 10 + c - '0';
227 val = va_arg(args, long);
235 val = va_arg(args, unsigned long);
239 *buf++ = '%'; --buflen;
240 *buf++ = 'l'; --buflen;
241 --fmt; /* so %lz outputs %lz etc. */
246 i = va_arg(args, int);
255 val = va_arg(args, unsigned int);
259 val = va_arg(args, unsigned int);
264 val = va_arg(args, unsigned int);
268 val = (unsigned long) va_arg(args, void *);
273 str = va_arg(args, char *);
276 num[0] = va_arg(args, int);
281 str = strerror(errno);
284 ip = va_arg(args, u_int32_t);
286 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
287 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
290 #if 0 /* not used, and breaks on S/390, apparently */
292 f = va_arg(args, char *);
294 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
296 /* On the powerpc, a va_list is an array of 1 structure */
297 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
306 str += 4; /* chop off the day name */
307 str[15] = 0; /* chop off year and newline */
309 case 'v': /* "visible" string */
310 case 'q': /* quoted string */
312 p = va_arg(args, unsigned char *);
313 if (fillch == '0' && prec >= 0) {
316 n = strlen((char *)p);
317 if (prec >= 0 && n > prec)
320 while (n > 0 && buflen > 0) {
323 if (!quoted && c >= 0x80) {
328 if (quoted && (c == '"' || c == '\\'))
330 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
334 case '\t': OUTCHAR('t'); break;
335 case '\n': OUTCHAR('n'); break;
336 case '\b': OUTCHAR('b'); break;
337 case '\f': OUTCHAR('f'); break;
340 OUTCHAR(hexchars[c >> 4]);
341 OUTCHAR(hexchars[c & 0xf]);
355 case 'P': /* print PPP packet */
357 bufinfo.len = buflen + 1;
358 p = va_arg(args, unsigned char *);
359 n = va_arg(args, int);
360 format_packet(p, n, vslp_printer, &bufinfo);
362 buflen = bufinfo.len - 1;
365 p = va_arg(args, unsigned char *);
366 for (n = prec; n > 0; --n) {
370 OUTCHAR(hexchars[(c >> 4) & 0xf]);
371 OUTCHAR(hexchars[c & 0xf]);
377 --fmt; /* so %z outputs %z etc. */
382 str = num + sizeof(num);
384 while (str > num + neg) {
385 *--str = hexchars[val % base];
387 if (--prec <= 0 && val == 0)
399 len = num + sizeof(num) - 1 - str;
402 if (prec >= 0 && len > prec)
408 if ((n = width - len) > 0) {
416 memcpy(buf, str, len);
425 * vslp_printer - used in processing a %P format
428 vslp_printer __V((void *arg, char *fmt, ...))
432 struct buffer_info *bi;
434 #if defined(__STDC__)
440 arg = va_arg(pvar, void *);
441 fmt = va_arg(pvar, char *);
444 bi = (struct buffer_info *) arg;
445 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
454 * log_packet - format a packet and log it.
458 log_packet(p, len, prefix, level)
464 init_pr_log(prefix, level);
465 format_packet(p, len, pr_log, &level);
471 * format_packet - make a readable representation of a packet,
472 * calling `printer(arg, format, ...)' to output it.
475 format_packet(p, len, printer, arg)
478 void (*printer) __P((void *, char *, ...));
483 struct protent *protp;
485 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
489 for (i = 0; (protp = protocols[i]) != NULL; ++i)
490 if (proto == protp->protocol)
493 printer(arg, "[%s", protp->name);
494 n = (*protp->printpkt)(p, len, printer, arg);
499 for (i = 0; (protp = protocols[i]) != NULL; ++i)
500 if (proto == (protp->protocol & ~0x8000))
502 if (protp != 0 && protp->data_name != 0) {
503 printer(arg, "[%s data]", protp->data_name);
505 printer(arg, "%.8B ...", p);
507 printer(arg, "%.*B", len, p);
510 printer(arg, "[proto=0x%x]", proto);
515 printer(arg, "%.32B ...", p);
517 printer(arg, "%.*B", len, p);
521 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
524 static char line[256]; /* line to be logged accumulated here */
525 static char *linep; /* current pointer within line */
526 static int llevel; /* level for logging */
529 init_pr_log(prefix, level)
534 if (prefix != NULL) {
535 strlcpy(line, prefix, sizeof(line));
536 linep = line + strlen(line);
546 log_write(llevel, line);
551 * pr_log - printer routine for outputting to syslog
554 pr_log __V((void *arg, char *fmt, ...))
561 #if defined(__STDC__)
567 arg = va_arg(pvar, void *);
568 fmt = va_arg(pvar, char *);
571 n = vslprintf(buf, sizeof(buf), fmt, pvar);
575 eol = strchr(buf, '\n');
577 l = (eol == NULL)? n: eol - buf;
578 if (linep + l < line + sizeof(line)) {
580 memcpy(linep, buf, l);
586 eol = strchr(p, '\n');
589 log_write(llevel, line);
593 while (eol != NULL) {
595 log_write(llevel, p);
597 eol = strchr(p, '\n');
600 /* assumes sizeof(buf) <= sizeof(line) */
609 * print_string - print a readable representation of a string using
613 print_string(p, len, printer, arg)
616 void (*printer) __P((void *, char *, ...));
622 for (; len > 0; --len) {
624 if (' ' <= c && c <= '~') {
625 if (c == '\\' || c == '"')
627 printer(arg, "%c", c);
640 printer(arg, "\\%.3o", c);
648 * logit - does the hard work for fatal et al.
651 logit(level, fmt, args)
659 n = vslprintf(buf, sizeof(buf), fmt, args);
660 log_write(level, buf);
664 log_write(level, buf)
668 syslog(level, "%s", buf);
669 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
672 if (n > 0 && buf[n-1] == '\n')
674 if (write(log_to_fd, buf, n) != n
675 || write(log_to_fd, "\n", 1) != 1)
681 * fatal - log an error message and die horribly.
684 fatal __V((char *fmt, ...))
688 #if defined(__STDC__)
693 fmt = va_arg(pvar, char *);
696 logit(LOG_ERR, fmt, pvar);
699 die(1); /* as promised */
703 * error - log an error message.
706 error __V((char *fmt, ...))
710 #if defined(__STDC__)
715 fmt = va_arg(pvar, char *);
718 logit(LOG_ERR, fmt, pvar);
724 * warn - log a warning message.
727 warn __V((char *fmt, ...))
731 #if defined(__STDC__)
736 fmt = va_arg(pvar, char *);
739 logit(LOG_WARNING, fmt, pvar);
744 * notice - log a notice-level message.
747 notice __V((char *fmt, ...))
751 #if defined(__STDC__)
756 fmt = va_arg(pvar, char *);
759 logit(LOG_NOTICE, fmt, pvar);
764 * info - log an informational message.
767 info __V((char *fmt, ...))
771 #if defined(__STDC__)
776 fmt = va_arg(pvar, char *);
779 logit(LOG_INFO, fmt, pvar);
784 * dbglog - log a debug message.
787 dbglog __V((char *fmt, ...))
791 #if defined(__STDC__)
796 fmt = va_arg(pvar, char *);
799 logit(LOG_DEBUG, fmt, pvar);
804 * dump_packet - print out a packet in readable form if it is interesting.
805 * Assumes len >= PPP_HDRLEN.
808 dump_packet(const char *tag, unsigned char *p, int len)
816 * don't print LCP echo request/reply packets if debug <= 1
817 * and the link is up.
819 proto = (p[2] << 8) + p[3];
820 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
821 && len >= PPP_HDRLEN + HEADERLEN) {
822 unsigned char *lcp = p + PPP_HDRLEN;
823 int l = (lcp[2] << 8) + lcp[3];
825 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
826 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
830 dbglog("%s %P", tag, p, len);
834 * complete_read - read a full `count' bytes from fd,
835 * unless end-of-file or an error other than EINTR is encountered.
838 complete_read(int fd, void *buf, size_t count)
844 for (done = 0; done < count; ) {
845 nb = read(fd, ptr, count - done);
859 /* Procedures for locking the serial device using a lock file. */
862 #define LOCK_DIR "/var/lock"
865 #define LOCK_DIR "/var/spool/locks"
867 #define LOCK_DIR "/var/spool/lock"
870 #endif /* LOCK_DIR */
872 static char lock_file[MAXPATHLEN];
875 * lock - create a lock file for the named device
884 result = mklock (dev, (void *) 0);
886 strlcpy(lock_file, dev, sizeof(lock_file));
891 notice("Device %s is locked by pid %d", dev, result);
893 error("Can't create lock file %s", lock_file);
898 char lock_buffer[12];
904 if (stat(dev, &sbuf) < 0) {
905 error("Can't get device number for %s: %m", dev);
908 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
909 error("Can't lock %s: not a character device", dev);
912 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
913 LOCK_DIR, major(sbuf.st_dev),
914 major(sbuf.st_rdev), minor(sbuf.st_rdev));
917 char lockdev[MAXPATHLEN];
919 if ((p = strstr(dev, "dev/")) != NULL) {
921 strncpy(lockdev, dev, MAXPATHLEN-1);
922 lockdev[MAXPATHLEN-1] = 0;
923 while ((p = strrchr(lockdev, '/')) != NULL) {
928 if ((p = strrchr(dev, '/')) != NULL)
931 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
934 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
935 if (errno != EEXIST) {
936 error("Can't create lock file %s: %m", lock_file);
940 /* Read the lock file to find out who has the device locked. */
941 fd = open(lock_file, O_RDONLY, 0);
943 if (errno == ENOENT) /* This is just a timing problem. */
945 error("Can't open existing lock file %s: %m", lock_file);
949 n = read(fd, lock_buffer, 11);
951 n = read(fd, &pid, sizeof(pid));
952 #endif /* LOCK_BINARY */
956 error("Can't read pid from lock file %s", lock_file);
960 /* See if the process still exists. */
963 pid = atoi(lock_buffer);
964 #endif /* LOCK_BINARY */
966 return 1; /* somebody else locked it for us */
968 || (kill(pid, 0) == -1 && errno == ESRCH)) {
969 if (unlink (lock_file) == 0) {
970 notice("Removed stale lock on %s (pid %d)", dev, pid);
973 warn("Couldn't remove stale lock on %s", dev);
975 notice("Device %s is locked by pid %d", dev, pid);
986 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
987 write (fd, lock_buffer, 11);
989 write(fd, &pid, sizeof (pid));
998 * relock - called to update our lockfile when we are about to detach,
999 * thus changing our pid (we fork, the child carries on, and the parent dies).
1000 * Note that this is called by the parent, with pid equal to the pid
1001 * of the child. This avoids a potential race which would exist if
1002 * we had the child rewrite the lockfile (the parent might die first,
1003 * and another process could think the lock was stale if it checked
1004 * between when the parent died and the child rewrote the lockfile).
1011 /* XXX is there a way to do this? */
1016 char lock_buffer[12];
1018 if (lock_file[0] == 0)
1020 fd = open(lock_file, O_WRONLY, 0);
1022 error("Couldn't reopen lock file %s: %m", lock_file);
1028 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1029 write (fd, lock_buffer, 11);
1031 write(fd, &pid, sizeof(pid));
1032 #endif /* LOCK_BINARY */
1036 #endif /* LOCKLIB */
1040 * unlock - remove our lockfile
1047 (void) rmlock(lock_file, (void *) 0);