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);
292 str += 4; /* chop off the day name */
293 str[15] = 0; /* chop off year and newline */
295 case 'v': /* "visible" string */
296 case 'q': /* quoted string */
298 p = va_arg(args, unsigned char *);
300 p = (unsigned char *)"<NULL>";
301 if (fillch == '0' && prec >= 0) {
304 n = strlen((char *)p);
305 if (prec >= 0 && n > prec)
308 while (n > 0 && buflen > 0) {
311 if (!quoted && c >= 0x80) {
316 if (quoted && (c == '"' || c == '\\'))
318 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
322 case '\t': OUTCHAR('t'); break;
323 case '\n': OUTCHAR('n'); break;
324 case '\b': OUTCHAR('b'); break;
325 case '\f': OUTCHAR('f'); break;
328 OUTCHAR(hexchars[c >> 4]);
329 OUTCHAR(hexchars[c & 0xf]);
343 case 'P': /* print PPP packet */
345 bufinfo.len = buflen + 1;
346 p = va_arg(args, unsigned char *);
347 n = va_arg(args, int);
348 format_packet(p, n, vslp_printer, &bufinfo);
350 buflen = bufinfo.len - 1;
353 p = va_arg(args, unsigned char *);
354 for (n = prec; n > 0; --n) {
358 OUTCHAR(hexchars[(c >> 4) & 0xf]);
359 OUTCHAR(hexchars[c & 0xf]);
365 --fmt; /* so %z outputs %z etc. */
370 str = num + sizeof(num);
372 while (str > num + neg) {
373 *--str = hexchars[val % base];
375 if (--prec <= 0 && val == 0)
387 len = num + sizeof(num) - 1 - str;
390 if (prec >= 0 && len > prec)
396 if ((n = width - len) > 0) {
404 memcpy(buf, str, len);
413 * vslp_printer - used in processing a %P format
416 vslp_printer __V((void *arg, char *fmt, ...))
420 struct buffer_info *bi;
422 #if defined(__STDC__)
428 arg = va_arg(pvar, void *);
429 fmt = va_arg(pvar, char *);
432 bi = (struct buffer_info *) arg;
433 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
442 * log_packet - format a packet and log it.
446 log_packet(p, len, prefix, level)
452 init_pr_log(prefix, level);
453 format_packet(p, len, pr_log, &level);
459 * format_packet - make a readable representation of a packet,
460 * calling `printer(arg, format, ...)' to output it.
463 format_packet(p, len, printer, arg)
466 printer_func printer;
471 struct protent *protp;
473 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
477 for (i = 0; (protp = protocols[i]) != NULL; ++i)
478 if (proto == protp->protocol)
481 printer(arg, "[%s", protp->name);
482 n = (*protp->printpkt)(p, len, printer, arg);
487 for (i = 0; (protp = protocols[i]) != NULL; ++i)
488 if (proto == (protp->protocol & ~0x8000))
490 if (protp != 0 && protp->data_name != 0) {
491 printer(arg, "[%s data]", protp->data_name);
493 printer(arg, "%.8B ...", p);
495 printer(arg, "%.*B", len, p);
498 printer(arg, "[proto=0x%x]", proto);
503 printer(arg, "%.32B ...", p);
505 printer(arg, "%.*B", len, p);
509 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
512 static char line[256]; /* line to be logged accumulated here */
513 static char *linep; /* current pointer within line */
514 static int llevel; /* level for logging */
517 init_pr_log(prefix, level)
522 if (prefix != NULL) {
523 strlcpy(line, prefix, sizeof(line));
524 linep = line + strlen(line);
534 log_write(llevel, line);
539 * pr_log - printer routine for outputting to syslog
542 pr_log __V((void *arg, char *fmt, ...))
549 #if defined(__STDC__)
555 arg = va_arg(pvar, void *);
556 fmt = va_arg(pvar, char *);
559 n = vslprintf(buf, sizeof(buf), fmt, pvar);
563 eol = strchr(buf, '\n');
565 l = (eol == NULL)? n: eol - buf;
566 if (linep + l < line + sizeof(line)) {
568 memcpy(linep, buf, l);
574 eol = strchr(p, '\n');
577 log_write(llevel, line);
581 while (eol != NULL) {
583 log_write(llevel, p);
585 eol = strchr(p, '\n');
588 /* assumes sizeof(buf) <= sizeof(line) */
597 * print_string - print a readable representation of a string using
601 print_string(p, len, printer, arg)
604 printer_func printer;
610 for (; len > 0; --len) {
612 if (' ' <= c && c <= '~') {
613 if (c == '\\' || c == '"')
615 printer(arg, "%c", c);
628 printer(arg, "\\%.3o", (unsigned char) c);
636 * logit - does the hard work for fatal et al.
639 logit(level, fmt, args)
646 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);
711 * warn - log a warning message.
714 warn __V((char *fmt, ...))
718 #if defined(__STDC__)
723 fmt = va_arg(pvar, char *);
726 logit(LOG_WARNING, fmt, pvar);
731 * notice - log a notice-level message.
734 notice __V((char *fmt, ...))
738 #if defined(__STDC__)
743 fmt = va_arg(pvar, char *);
746 logit(LOG_NOTICE, fmt, pvar);
751 * info - log an informational message.
754 info __V((char *fmt, ...))
758 #if defined(__STDC__)
763 fmt = va_arg(pvar, char *);
766 logit(LOG_INFO, fmt, pvar);
771 * dbglog - log a debug message.
774 dbglog __V((char *fmt, ...))
778 #if defined(__STDC__)
783 fmt = va_arg(pvar, char *);
786 logit(LOG_DEBUG, fmt, pvar);
791 * dump_packet - print out a packet in readable form if it is interesting.
792 * Assumes len >= PPP_HDRLEN.
795 dump_packet(const char *tag, unsigned char *p, int len)
803 * don't print LCP echo request/reply packets if debug <= 1
804 * and the link is up.
806 proto = (p[2] << 8) + p[3];
807 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
808 && len >= PPP_HDRLEN + HEADERLEN) {
809 unsigned char *lcp = p + PPP_HDRLEN;
810 int l = (lcp[2] << 8) + lcp[3];
812 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
813 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
817 dbglog("%s %P", tag, p, len);
821 * complete_read - read a full `count' bytes from fd,
822 * unless end-of-file or an error other than EINTR is encountered.
825 complete_read(int fd, void *buf, size_t count)
831 for (done = 0; done < count; ) {
832 nb = read(fd, ptr, count - done);
846 /* Procedures for locking the serial device using a lock file. */
849 #define LOCK_DIR "/var/lock"
852 #define LOCK_DIR "/var/spool/locks"
854 #define LOCK_DIR "/var/spool/lock"
857 #endif /* LOCK_DIR */
859 static char lock_file[MAXPATHLEN];
862 * lock - create a lock file for the named device
871 result = mklock (dev, (void *) 0);
873 strlcpy(lock_file, dev, sizeof(lock_file));
878 notice("Device %s is locked by pid %d", dev, result);
880 error("Can't create lock file %s", lock_file);
885 char lock_buffer[12];
891 if (stat(dev, &sbuf) < 0) {
892 error("Can't get device number for %s: %m", dev);
895 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
896 error("Can't lock %s: not a character device", dev);
899 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
900 LOCK_DIR, major(sbuf.st_dev),
901 major(sbuf.st_rdev), minor(sbuf.st_rdev));
904 char lockdev[MAXPATHLEN];
906 if ((p = strstr(dev, "dev/")) != NULL) {
908 strncpy(lockdev, dev, MAXPATHLEN-1);
909 lockdev[MAXPATHLEN-1] = 0;
910 while ((p = strrchr(lockdev, '/')) != NULL) {
915 if ((p = strrchr(dev, '/')) != NULL)
918 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
921 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
922 if (errno != EEXIST) {
923 error("Can't create lock file %s: %m", lock_file);
927 /* Read the lock file to find out who has the device locked. */
928 fd = open(lock_file, O_RDONLY, 0);
930 if (errno == ENOENT) /* This is just a timing problem. */
932 error("Can't open existing lock file %s: %m", lock_file);
936 n = read(fd, lock_buffer, 11);
938 n = read(fd, &pid, sizeof(pid));
939 #endif /* LOCK_BINARY */
943 error("Can't read pid from lock file %s", lock_file);
947 /* See if the process still exists. */
950 pid = atoi(lock_buffer);
951 #endif /* LOCK_BINARY */
953 return 1; /* somebody else locked it for us */
955 || (kill(pid, 0) == -1 && errno == ESRCH)) {
956 if (unlink (lock_file) == 0) {
957 notice("Removed stale lock on %s (pid %d)", dev, pid);
960 warn("Couldn't remove stale lock on %s", dev);
962 notice("Device %s is locked by pid %d", dev, pid);
973 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
974 write (fd, lock_buffer, 11);
976 write(fd, &pid, sizeof (pid));
985 * relock - called to update our lockfile when we are about to detach,
986 * thus changing our pid (we fork, the child carries on, and the parent dies).
987 * Note that this is called by the parent, with pid equal to the pid
988 * of the child. This avoids a potential race which would exist if
989 * we had the child rewrite the lockfile (the parent might die first,
990 * and another process could think the lock was stale if it checked
991 * between when the parent died and the child rewrote the lockfile).
998 /* XXX is there a way to do this? */
1003 char lock_buffer[12];
1005 if (lock_file[0] == 0)
1007 fd = open(lock_file, O_WRONLY, 0);
1009 error("Couldn't reopen lock file %s: %m", lock_file);
1015 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1016 write (fd, lock_buffer, 11);
1018 write(fd, &pid, sizeof(pid));
1019 #endif /* LOCK_BINARY */
1023 #endif /* LOCKLIB */
1027 * unlock - remove our lockfile
1034 (void) rmlock(lock_file, (void *) 0);