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.25 2008/06/03 12:06:37 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, printer_func, void *));
79 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
80 * always leaves destination null-terminated (for len > 0).
83 strlcpy(dest, src, len)
88 size_t ret = strlen(src);
94 strncpy(dest, src, len - 1);
102 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
103 * always leaves destination null-terminated (for len > 0).
106 strlcat(dest, src, len)
111 size_t dlen = strlen(dest);
113 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
118 * slprintf - format a message into a buffer. Like sprintf except we
119 * also specify the length of the output buffer, and we handle
120 * %m (error message), %v (visible string),
121 * %q (quoted string), %t (current time) and %I (IP address) formats.
122 * Doesn't do floating-point formats.
123 * Returns the number of chars put into buf.
126 slprintf __V((char *buf, int buflen, char *fmt, ...))
131 #if defined(__STDC__)
138 buf = va_arg(args, char *);
139 buflen = va_arg(args, int);
140 fmt = va_arg(args, char *);
142 n = vslprintf(buf, buflen, fmt, args);
148 * vslprintf - like slprintf, takes a va_list instead of a list of args.
150 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
153 vslprintf(buf, buflen, fmt, args)
160 int width, prec, fillch;
161 int base, len, neg, quoted;
162 unsigned long val = 0;
163 char *str, *f, *buf0;
168 static char hexchars[] = "0123456789abcdef";
169 struct buffer_info bufinfo;
174 for (f = fmt; *f != '%' && *f != 0; ++f)
180 memcpy(buf, fmt, len);
196 width = va_arg(args, int);
200 width = width * 10 + c - '0';
207 prec = va_arg(args, int);
212 prec = prec * 10 + c - '0';
226 val = va_arg(args, long);
234 val = va_arg(args, unsigned long);
240 --fmt; /* so %lz outputs %lz etc. */
245 i = va_arg(args, int);
254 val = va_arg(args, unsigned int);
258 val = va_arg(args, unsigned int);
263 val = va_arg(args, unsigned int);
267 val = (unsigned long) va_arg(args, void *);
272 str = va_arg(args, char *);
275 num[0] = va_arg(args, int);
280 str = strerror(errno);
283 ip = va_arg(args, u_int32_t);
285 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
286 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
289 #if 0 /* not used, and breaks on S/390, apparently */
291 f = va_arg(args, char *);
293 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
295 /* On the powerpc, a va_list is an array of 1 structure */
296 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
305 str += 4; /* chop off the day name */
306 str[15] = 0; /* chop off year and newline */
308 case 'v': /* "visible" string */
309 case 'q': /* quoted string */
311 p = va_arg(args, unsigned char *);
312 if (fillch == '0' && prec >= 0) {
315 n = strlen((char *)p);
316 if (prec >= 0 && n > prec)
319 while (n > 0 && buflen > 0) {
322 if (!quoted && c >= 0x80) {
327 if (quoted && (c == '"' || c == '\\'))
329 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
333 case '\t': OUTCHAR('t'); break;
334 case '\n': OUTCHAR('n'); break;
335 case '\b': OUTCHAR('b'); break;
336 case '\f': OUTCHAR('f'); break;
339 OUTCHAR(hexchars[c >> 4]);
340 OUTCHAR(hexchars[c & 0xf]);
354 case 'P': /* print PPP packet */
356 bufinfo.len = buflen + 1;
357 p = va_arg(args, unsigned char *);
358 n = va_arg(args, int);
359 format_packet(p, n, vslp_printer, &bufinfo);
361 buflen = bufinfo.len - 1;
364 p = va_arg(args, unsigned char *);
365 for (n = prec; n > 0; --n) {
369 OUTCHAR(hexchars[(c >> 4) & 0xf]);
370 OUTCHAR(hexchars[c & 0xf]);
376 --fmt; /* so %z outputs %z etc. */
381 str = num + sizeof(num);
383 while (str > num + neg) {
384 *--str = hexchars[val % base];
386 if (--prec <= 0 && val == 0)
398 len = num + sizeof(num) - 1 - str;
401 if (prec >= 0 && len > prec)
407 if ((n = width - len) > 0) {
415 memcpy(buf, str, len);
424 * vslp_printer - used in processing a %P format
427 vslp_printer __V((void *arg, char *fmt, ...))
431 struct buffer_info *bi;
433 #if defined(__STDC__)
439 arg = va_arg(pvar, void *);
440 fmt = va_arg(pvar, char *);
443 bi = (struct buffer_info *) arg;
444 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
453 * log_packet - format a packet and log it.
457 log_packet(p, len, prefix, level)
463 init_pr_log(prefix, level);
464 format_packet(p, len, pr_log, &level);
470 * format_packet - make a readable representation of a packet,
471 * calling `printer(arg, format, ...)' to output it.
474 format_packet(p, len, printer, arg)
477 printer_func printer;
482 struct protent *protp;
484 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
488 for (i = 0; (protp = protocols[i]) != NULL; ++i)
489 if (proto == protp->protocol)
492 printer(arg, "[%s", protp->name);
493 n = (*protp->printpkt)(p, len, printer, arg);
498 for (i = 0; (protp = protocols[i]) != NULL; ++i)
499 if (proto == (protp->protocol & ~0x8000))
501 if (protp != 0 && protp->data_name != 0) {
502 printer(arg, "[%s data]", protp->data_name);
504 printer(arg, "%.8B ...", p);
506 printer(arg, "%.*B", len, p);
509 printer(arg, "[proto=0x%x]", proto);
514 printer(arg, "%.32B ...", p);
516 printer(arg, "%.*B", len, p);
520 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
523 static char line[256]; /* line to be logged accumulated here */
524 static char *linep; /* current pointer within line */
525 static int llevel; /* level for logging */
528 init_pr_log(prefix, level)
533 if (prefix != NULL) {
534 strlcpy(line, prefix, sizeof(line));
535 linep = line + strlen(line);
545 log_write(llevel, line);
550 * pr_log - printer routine for outputting to syslog
553 pr_log __V((void *arg, char *fmt, ...))
560 #if defined(__STDC__)
566 arg = va_arg(pvar, void *);
567 fmt = va_arg(pvar, char *);
570 n = vslprintf(buf, sizeof(buf), fmt, pvar);
574 eol = strchr(buf, '\n');
576 l = (eol == NULL)? n: eol - buf;
577 if (linep + l < line + sizeof(line)) {
579 memcpy(linep, buf, l);
585 eol = strchr(p, '\n');
588 log_write(llevel, line);
592 while (eol != NULL) {
594 log_write(llevel, p);
596 eol = strchr(p, '\n');
599 /* assumes sizeof(buf) <= sizeof(line) */
608 * print_string - print a readable representation of a string using
612 print_string(p, len, printer, arg)
615 printer_func printer;
621 for (; len > 0; --len) {
623 if (' ' <= c && c <= '~') {
624 if (c == '\\' || c == '"')
626 printer(arg, "%c", c);
639 printer(arg, "\\%.3o", c);
647 * logit - does the hard work for fatal et al.
650 logit(level, fmt, args)
658 n = vslprintf(buf, sizeof(buf), fmt, args);
659 log_write(level, buf);
663 log_write(level, buf)
667 syslog(level, "%s", buf);
668 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
671 if (n > 0 && buf[n-1] == '\n')
673 if (write(log_to_fd, buf, n) != n
674 || write(log_to_fd, "\n", 1) != 1)
680 * fatal - log an error message and die horribly.
683 fatal __V((char *fmt, ...))
687 #if defined(__STDC__)
692 fmt = va_arg(pvar, char *);
695 logit(LOG_ERR, fmt, pvar);
698 die(1); /* as promised */
702 * error - log an error message.
705 error __V((char *fmt, ...))
709 #if defined(__STDC__)
714 fmt = va_arg(pvar, char *);
717 logit(LOG_ERR, fmt, pvar);
723 * warn - log a warning message.
726 warn __V((char *fmt, ...))
730 #if defined(__STDC__)
735 fmt = va_arg(pvar, char *);
738 logit(LOG_WARNING, fmt, pvar);
743 * notice - log a notice-level message.
746 notice __V((char *fmt, ...))
750 #if defined(__STDC__)
755 fmt = va_arg(pvar, char *);
758 logit(LOG_NOTICE, fmt, pvar);
763 * info - log an informational message.
766 info __V((char *fmt, ...))
770 #if defined(__STDC__)
775 fmt = va_arg(pvar, char *);
778 logit(LOG_INFO, fmt, pvar);
783 * dbglog - log a debug message.
786 dbglog __V((char *fmt, ...))
790 #if defined(__STDC__)
795 fmt = va_arg(pvar, char *);
798 logit(LOG_DEBUG, fmt, pvar);
803 * dump_packet - print out a packet in readable form if it is interesting.
804 * Assumes len >= PPP_HDRLEN.
807 dump_packet(const char *tag, unsigned char *p, int len)
815 * don't print LCP echo request/reply packets if debug <= 1
816 * and the link is up.
818 proto = (p[2] << 8) + p[3];
819 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
820 && len >= PPP_HDRLEN + HEADERLEN) {
821 unsigned char *lcp = p + PPP_HDRLEN;
822 int l = (lcp[2] << 8) + lcp[3];
824 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
825 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
829 dbglog("%s %P", tag, p, len);
833 * complete_read - read a full `count' bytes from fd,
834 * unless end-of-file or an error other than EINTR is encountered.
837 complete_read(int fd, void *buf, size_t count)
843 for (done = 0; done < count; ) {
844 nb = read(fd, ptr, count - done);
858 /* Procedures for locking the serial device using a lock file. */
861 #define LOCK_DIR "/var/lock"
864 #define LOCK_DIR "/var/spool/locks"
866 #define LOCK_DIR "/var/spool/lock"
869 #endif /* LOCK_DIR */
871 static char lock_file[MAXPATHLEN];
874 * lock - create a lock file for the named device
883 result = mklock (dev, (void *) 0);
885 strlcpy(lock_file, dev, sizeof(lock_file));
890 notice("Device %s is locked by pid %d", dev, result);
892 error("Can't create lock file %s", lock_file);
897 char lock_buffer[12];
903 if (stat(dev, &sbuf) < 0) {
904 error("Can't get device number for %s: %m", dev);
907 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
908 error("Can't lock %s: not a character device", dev);
911 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
912 LOCK_DIR, major(sbuf.st_dev),
913 major(sbuf.st_rdev), minor(sbuf.st_rdev));
916 char lockdev[MAXPATHLEN];
918 if ((p = strstr(dev, "dev/")) != NULL) {
920 strncpy(lockdev, dev, MAXPATHLEN-1);
921 lockdev[MAXPATHLEN-1] = 0;
922 while ((p = strrchr(lockdev, '/')) != NULL) {
927 if ((p = strrchr(dev, '/')) != NULL)
930 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
933 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
934 if (errno != EEXIST) {
935 error("Can't create lock file %s: %m", lock_file);
939 /* Read the lock file to find out who has the device locked. */
940 fd = open(lock_file, O_RDONLY, 0);
942 if (errno == ENOENT) /* This is just a timing problem. */
944 error("Can't open existing lock file %s: %m", lock_file);
948 n = read(fd, lock_buffer, 11);
950 n = read(fd, &pid, sizeof(pid));
951 #endif /* LOCK_BINARY */
955 error("Can't read pid from lock file %s", lock_file);
959 /* See if the process still exists. */
962 pid = atoi(lock_buffer);
963 #endif /* LOCK_BINARY */
965 return 1; /* somebody else locked it for us */
967 || (kill(pid, 0) == -1 && errno == ESRCH)) {
968 if (unlink (lock_file) == 0) {
969 notice("Removed stale lock on %s (pid %d)", dev, pid);
972 warn("Couldn't remove stale lock on %s", dev);
974 notice("Device %s is locked by pid %d", dev, pid);
985 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
986 write (fd, lock_buffer, 11);
988 write(fd, &pid, sizeof (pid));
997 * relock - called to update our lockfile when we are about to detach,
998 * thus changing our pid (we fork, the child carries on, and the parent dies).
999 * Note that this is called by the parent, with pid equal to the pid
1000 * of the child. This avoids a potential race which would exist if
1001 * we had the child rewrite the lockfile (the parent might die first,
1002 * and another process could think the lock was stale if it checked
1003 * between when the parent died and the child rewrote the lockfile).
1010 /* XXX is there a way to do this? */
1015 char lock_buffer[12];
1017 if (lock_file[0] == 0)
1019 fd = open(lock_file, O_WRONLY, 0);
1021 error("Couldn't reopen lock file %s: %m", lock_file);
1027 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1028 write (fd, lock_buffer, 11);
1030 write(fd, &pid, sizeof(pid));
1031 #endif /* LOCK_BINARY */
1035 #endif /* LOCKLIB */
1039 * unlock - remove our lockfile
1046 (void) rmlock(lock_file, (void *) 0);