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>
64 extern char *strerror();
67 static void logit __P((int, char *, va_list));
68 static void log_write __P((int, char *));
69 static void vslp_printer __P((void *, char *, ...));
70 static void format_packet __P((u_char *, int, printer_func, void *));
78 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
79 * always leaves destination null-terminated (for len > 0).
82 strlcpy(dest, src, len)
87 size_t ret = strlen(src);
93 strncpy(dest, src, len - 1);
101 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
102 * always leaves destination null-terminated (for len > 0).
105 strlcat(dest, src, len)
110 size_t dlen = strlen(dest);
112 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
117 * slprintf - format a message into a buffer. Like sprintf except we
118 * also specify the length of the output buffer, and we handle
119 * %m (error message), %v (visible string),
120 * %q (quoted string), %t (current time) and %I (IP address) formats.
121 * Doesn't do floating-point formats.
122 * Returns the number of chars put into buf.
125 slprintf __V((char *buf, int buflen, char *fmt, ...))
130 #if defined(__STDC__)
137 buf = va_arg(args, char *);
138 buflen = va_arg(args, int);
139 fmt = va_arg(args, char *);
141 n = vslprintf(buf, buflen, fmt, args);
147 * vslprintf - like slprintf, takes a va_list instead of a list of args.
149 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
152 vslprintf(buf, buflen, fmt, args)
159 int width, prec, fillch;
160 int base, len, neg, quoted;
161 unsigned long val = 0;
162 char *str, *f, *buf0;
167 static char hexchars[] = "0123456789abcdef";
168 struct buffer_info bufinfo;
173 for (f = fmt; *f != '%' && *f != 0; ++f)
179 memcpy(buf, fmt, len);
195 width = va_arg(args, int);
199 width = width * 10 + c - '0';
206 prec = va_arg(args, int);
211 prec = prec * 10 + c - '0';
225 val = va_arg(args, long);
233 val = va_arg(args, unsigned long);
239 --fmt; /* so %lz outputs %lz etc. */
244 i = va_arg(args, int);
253 val = va_arg(args, unsigned int);
257 val = va_arg(args, unsigned int);
262 val = va_arg(args, unsigned int);
266 val = (unsigned long) va_arg(args, void *);
271 str = va_arg(args, char *);
274 num[0] = va_arg(args, int);
279 str = strerror(errno);
282 ip = va_arg(args, u_int32_t);
284 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
285 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
291 str += 4; /* chop off the day name */
292 str[15] = 0; /* chop off year and newline */
294 case 'v': /* "visible" string */
295 case 'q': /* quoted string */
297 p = va_arg(args, unsigned char *);
299 p = (unsigned char *)"<NULL>";
300 if (fillch == '0' && prec >= 0) {
304 n = strlen((char *)p);
306 n = strnlen((char *)p, 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;
392 len = strnlen(str, prec);
397 if ((n = width - len) > 0) {
405 memcpy(buf, str, len);
414 * vslp_printer - used in processing a %P format
417 vslp_printer __V((void *arg, char *fmt, ...))
421 struct buffer_info *bi;
423 #if defined(__STDC__)
429 arg = va_arg(pvar, void *);
430 fmt = va_arg(pvar, char *);
433 bi = (struct buffer_info *) arg;
434 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
443 * log_packet - format a packet and log it.
447 log_packet(p, len, prefix, level)
453 init_pr_log(prefix, level);
454 format_packet(p, len, pr_log, &level);
460 * format_packet - make a readable representation of a packet,
461 * calling `printer(arg, format, ...)' to output it.
464 format_packet(p, len, printer, arg)
467 printer_func printer;
472 struct protent *protp;
474 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
478 for (i = 0; (protp = protocols[i]) != NULL; ++i)
479 if (proto == protp->protocol)
482 printer(arg, "[%s", protp->name);
483 n = (*protp->printpkt)(p, len, printer, arg);
488 for (i = 0; (protp = protocols[i]) != NULL; ++i)
489 if (proto == (protp->protocol & ~0x8000))
491 if (protp != 0 && protp->data_name != 0) {
492 printer(arg, "[%s data]", protp->data_name);
494 printer(arg, "%.8B ...", p);
496 printer(arg, "%.*B", len, p);
499 printer(arg, "[proto=0x%x]", proto);
504 printer(arg, "%.32B ...", p);
506 printer(arg, "%.*B", len, p);
510 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
513 static char line[256]; /* line to be logged accumulated here */
514 static char *linep; /* current pointer within line */
515 static int llevel; /* level for logging */
518 init_pr_log(prefix, level)
523 if (prefix != NULL) {
524 strlcpy(line, prefix, sizeof(line));
525 linep = line + strlen(line);
535 log_write(llevel, line);
540 * pr_log - printer routine for outputting to syslog
543 pr_log __V((void *arg, char *fmt, ...))
550 #if defined(__STDC__)
556 arg = va_arg(pvar, void *);
557 fmt = va_arg(pvar, char *);
560 n = vslprintf(buf, sizeof(buf), fmt, pvar);
564 eol = strchr(buf, '\n');
566 l = (eol == NULL)? n: eol - buf;
567 if (linep + l < line + sizeof(line)) {
569 memcpy(linep, buf, l);
575 eol = strchr(p, '\n');
578 log_write(llevel, line);
582 while (eol != NULL) {
584 log_write(llevel, p);
586 eol = strchr(p, '\n');
589 /* assumes sizeof(buf) <= sizeof(line) */
598 * print_string - print a readable representation of a string using
602 print_string(p, len, printer, arg)
605 printer_func printer;
611 for (; len > 0; --len) {
613 if (' ' <= c && c <= '~') {
614 if (c == '\\' || c == '"')
616 printer(arg, "%c", c);
629 printer(arg, "\\%.3o", (unsigned char) c);
637 * logit - does the hard work for fatal et al.
640 logit(level, fmt, args)
647 vslprintf(buf, sizeof(buf), fmt, args);
648 log_write(level, buf);
652 log_write(level, buf)
656 syslog(level, "%s", buf);
657 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
660 if (n > 0 && buf[n-1] == '\n')
662 if (write(log_to_fd, buf, n) != n
663 || write(log_to_fd, "\n", 1) != 1)
669 * fatal - log an error message and die horribly.
672 fatal __V((char *fmt, ...))
676 #if defined(__STDC__)
681 fmt = va_arg(pvar, char *);
684 logit(LOG_ERR, fmt, pvar);
687 die(1); /* as promised */
691 * error - log an error message.
694 error __V((char *fmt, ...))
698 #if defined(__STDC__)
703 fmt = va_arg(pvar, char *);
706 logit(LOG_ERR, fmt, pvar);
712 * warn - log a warning message.
715 warn __V((char *fmt, ...))
719 #if defined(__STDC__)
724 fmt = va_arg(pvar, char *);
727 logit(LOG_WARNING, fmt, pvar);
732 * notice - log a notice-level message.
735 notice __V((char *fmt, ...))
739 #if defined(__STDC__)
744 fmt = va_arg(pvar, char *);
747 logit(LOG_NOTICE, fmt, pvar);
752 * info - log an informational message.
755 info __V((char *fmt, ...))
759 #if defined(__STDC__)
764 fmt = va_arg(pvar, char *);
767 logit(LOG_INFO, fmt, pvar);
772 * dbglog - log a debug message.
775 dbglog __V((char *fmt, ...))
779 #if defined(__STDC__)
784 fmt = va_arg(pvar, char *);
787 logit(LOG_DEBUG, fmt, pvar);
792 * dump_packet - print out a packet in readable form if it is interesting.
793 * Assumes len >= PPP_HDRLEN.
796 dump_packet(const char *tag, unsigned char *p, int len)
804 * don't print LCP echo request/reply packets if debug <= 1
805 * and the link is up.
807 proto = (p[2] << 8) + p[3];
808 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
809 && len >= PPP_HDRLEN + HEADERLEN) {
810 unsigned char *lcp = p + PPP_HDRLEN;
811 int l = (lcp[2] << 8) + lcp[3];
813 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
814 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
818 dbglog("%s %P", tag, p, len);
822 * complete_read - read a full `count' bytes from fd,
823 * unless end-of-file or an error other than EINTR is encountered.
826 complete_read(int fd, void *buf, size_t count)
832 for (done = 0; done < count; ) {
833 nb = read(fd, ptr, count - done);
847 /* Procedures for locking the serial device using a lock file. */
850 #define LOCK_DIR "/var/lock"
853 #define LOCK_DIR "/var/spool/locks"
855 #define LOCK_DIR "/var/spool/lock"
858 #endif /* LOCK_DIR */
860 static char lock_file[MAXPATHLEN];
863 * lock - create a lock file for the named device
872 result = mklock (dev, (void *) 0);
874 strlcpy(lock_file, dev, sizeof(lock_file));
879 notice("Device %s is locked by pid %d", dev, result);
881 error("Can't create lock file %s", lock_file);
886 char lock_buffer[12];
892 if (stat(dev, &sbuf) < 0) {
893 error("Can't get device number for %s: %m", dev);
896 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
897 error("Can't lock %s: not a character device", dev);
900 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
901 LOCK_DIR, major(sbuf.st_dev),
902 major(sbuf.st_rdev), minor(sbuf.st_rdev));
905 char lockdev[MAXPATHLEN];
907 if ((p = strstr(dev, "dev/")) != NULL) {
909 strncpy(lockdev, dev, MAXPATHLEN-1);
910 lockdev[MAXPATHLEN-1] = 0;
911 while ((p = strrchr(lockdev, '/')) != NULL) {
916 if ((p = strrchr(dev, '/')) != NULL)
919 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
922 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
923 if (errno != EEXIST) {
924 error("Can't create lock file %s: %m", lock_file);
928 /* Read the lock file to find out who has the device locked. */
929 fd = open(lock_file, O_RDONLY, 0);
931 if (errno == ENOENT) /* This is just a timing problem. */
933 error("Can't open existing lock file %s: %m", lock_file);
937 n = read(fd, lock_buffer, 11);
939 n = read(fd, &pid, sizeof(pid));
940 #endif /* LOCK_BINARY */
944 error("Can't read pid from lock file %s", lock_file);
948 /* See if the process still exists. */
951 pid = atoi(lock_buffer);
952 #endif /* LOCK_BINARY */
954 return 1; /* somebody else locked it for us */
956 || (kill(pid, 0) == -1 && errno == ESRCH)) {
957 if (unlink (lock_file) == 0) {
958 notice("Removed stale lock on %s (pid %d)", dev, pid);
961 warn("Couldn't remove stale lock on %s", dev);
963 notice("Device %s is locked by pid %d", dev, pid);
974 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
975 write (fd, lock_buffer, 11);
977 write(fd, &pid, sizeof (pid));
986 * relock - called to update our lockfile when we are about to detach,
987 * thus changing our pid (we fork, the child carries on, and the parent dies).
988 * Note that this is called by the parent, with pid equal to the pid
989 * of the child. This avoids a potential race which would exist if
990 * we had the child rewrite the lockfile (the parent might die first,
991 * and another process could think the lock was stale if it checked
992 * between when the parent died and the child rewrote the lockfile).
999 /* XXX is there a way to do this? */
1004 char lock_buffer[12];
1006 if (lock_file[0] == 0)
1008 fd = open(lock_file, O_WRONLY, 0);
1010 error("Couldn't reopen lock file %s: %m", lock_file);
1016 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1017 write (fd, lock_buffer, 11);
1019 write(fd, &pid, sizeof(pid));
1020 #endif /* LOCK_BINARY */
1024 #endif /* LOCKLIB */
1028 * unlock - remove our lockfile
1035 (void) rmlock(lock_file, (void *) 0);