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 #include "netif/ppp/ppp_opts.h"
32 #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
48 #include <sys/param.h>
49 #include <sys/types.h>
52 #include <sys/resource.h>
54 #include <sys/socket.h>
55 #include <netinet/in.h>
57 #include <sys/mkdev.h>
61 #include <ctype.h> /* isdigit() */
63 #include "netif/ppp/ppp_impl.h"
65 #include "netif/ppp/fsm.h"
66 #include "netif/ppp/lcp.h"
69 extern char *strerror();
72 static void ppp_logit(int level, const char *fmt, va_list args);
73 static void ppp_log_write(int level, char *buf);
75 static void ppp_vslp_printer(void *arg, const char *fmt, ...);
76 static void ppp_format_packet(const u_char *p, int len,
77 void (*printer) (void *, const char *, ...), void *arg);
83 #endif /* PRINTPKT_SUPPORT */
86 * ppp_strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
87 * always leaves destination null-terminated (for len > 0).
89 size_t ppp_strlcpy(char *dest, const char *src, size_t len) {
90 size_t ret = strlen(src);
96 strncpy(dest, src, len - 1);
104 * ppp_strlcat - like strcat/strncat, doesn't overflow destination buffer,
105 * always leaves destination null-terminated (for len > 0).
107 size_t ppp_strlcat(char *dest, const char *src, size_t len) {
108 size_t dlen = strlen(dest);
110 return dlen + ppp_strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
115 * ppp_slprintf - format a message into a buffer. Like sprintf except we
116 * also specify the length of the output buffer, and we handle
117 * %m (error message), %v (visible string),
118 * %q (quoted string), %t (current time) and %I (IP address) formats.
119 * Doesn't do floating-point formats.
120 * Returns the number of chars put into buf.
122 int ppp_slprintf(char *buf, int buflen, const char *fmt, ...) {
127 n = ppp_vslprintf(buf, buflen, fmt, args);
133 * ppp_vslprintf - like ppp_slprintf, takes a va_list instead of a list of args.
135 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
137 int ppp_vslprintf(char *buf, int buflen, const char *fmt, va_list args) {
139 int width, prec, fillch;
140 int base, len, neg, quoted;
141 unsigned long val = 0;
144 const unsigned char *p;
146 #if 0 /* need port */
148 #endif /* need port */
150 static char hexchars[] = "0123456789abcdef";
152 struct buffer_info bufinfo;
153 #endif /* PRINTPKT_SUPPORT */
158 for (f = fmt; *f != '%' && *f != 0; ++f)
164 memcpy(buf, fmt, len);
180 width = va_arg(args, int);
184 width = width * 10 + c - '0';
191 prec = va_arg(args, int);
196 prec = prec * 10 + c - '0';
210 val = va_arg(args, long);
213 val = (unsigned long)-(long)val;
218 val = va_arg(args, unsigned long);
224 --fmt; /* so %lz outputs %lz etc. */
229 i = va_arg(args, int);
238 val = va_arg(args, unsigned int);
242 val = va_arg(args, unsigned int);
247 val = va_arg(args, unsigned int);
250 #if 0 /* unused (and wrong on LLP64 systems) */
252 val = (unsigned long) va_arg(args, void *);
256 #endif /* unused (and wrong on LLP64 systems) */
258 str = va_arg(args, char *);
261 num[0] = va_arg(args, int);
265 #if 0 /* do we always have strerror() in embedded ? */
267 str = strerror(errno);
269 #endif /* do we always have strerror() in embedded ? */
271 ip = va_arg(args, u32_t);
273 ppp_slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
274 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
277 #if 0 /* need port */
281 str += 4; /* chop off the day name */
282 str[15] = 0; /* chop off year and newline */
284 #endif /* need port */
285 case 'v': /* "visible" string */
286 case 'q': /* quoted string */
288 p = va_arg(args, unsigned char *);
290 p = (const unsigned char *)"<NULL>";
291 if (fillch == '0' && prec >= 0) {
294 n = strlen((const char *)p);
295 if (prec >= 0 && n > prec)
298 while (n > 0 && buflen > 0) {
301 if (!quoted && c >= 0x80) {
306 if (quoted && (c == '"' || c == '\\'))
308 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
312 case '\t': OUTCHAR('t'); break;
313 case '\n': OUTCHAR('n'); break;
314 case '\b': OUTCHAR('b'); break;
315 case '\f': OUTCHAR('f'); break;
318 OUTCHAR(hexchars[c >> 4]);
319 OUTCHAR(hexchars[c & 0xf]);
334 case 'P': /* print PPP packet */
336 bufinfo.len = buflen + 1;
337 p = va_arg(args, unsigned char *);
338 n = va_arg(args, int);
339 ppp_format_packet(p, n, ppp_vslp_printer, &bufinfo);
341 buflen = bufinfo.len - 1;
343 #endif /* PRINTPKT_SUPPORT */
345 p = va_arg(args, unsigned char *);
346 for (n = prec; n > 0; --n) {
350 OUTCHAR(hexchars[(c >> 4) & 0xf]);
351 OUTCHAR(hexchars[c & 0xf]);
357 --fmt; /* so %z outputs %z etc. */
362 str = num + sizeof(num);
364 while (str > num + neg) {
365 *--str = hexchars[val % base];
367 if (--prec <= 0 && val == 0)
381 len = num + sizeof(num) - 1 - str;
384 if (prec >= 0 && len > prec)
390 if ((n = width - len) > 0) {
398 memcpy(buf, str, len);
408 * vslp_printer - used in processing a %P format
410 static void ppp_vslp_printer(void *arg, const char *fmt, ...) {
413 struct buffer_info *bi;
416 bi = (struct buffer_info *) arg;
417 n = ppp_vslprintf(bi->ptr, bi->len, fmt, pvar);
423 #endif /* PRINTPKT_SUPPORT */
427 * log_packet - format a packet and log it.
431 log_packet(p, len, prefix, level)
437 init_pr_log(prefix, level);
438 ppp_format_packet(p, len, pr_log, &level);
445 * ppp_format_packet - make a readable representation of a packet,
446 * calling `printer(arg, format, ...)' to output it.
448 static void ppp_format_packet(const u_char *p, int len,
449 void (*printer) (void *, const char *, ...), void *arg) {
452 const struct protent *protp;
457 for (i = 0; (protp = protocols[i]) != NULL; ++i)
458 if (proto == protp->protocol)
461 printer(arg, "[%s", protp->name);
462 n = (*protp->printpkt)(p, len, printer, arg);
467 for (i = 0; (protp = protocols[i]) != NULL; ++i)
468 if (proto == (protp->protocol & ~0x8000))
470 if (protp != 0 && protp->data_name != 0) {
471 printer(arg, "[%s data]", protp->data_name);
473 printer(arg, "%.8B ...", p);
475 printer(arg, "%.*B", len, p);
478 printer(arg, "[proto=0x%x]", proto);
483 printer(arg, "%.32B ...", p);
485 printer(arg, "%.*B", len, p);
487 #endif /* PRINTPKT_SUPPORT */
491 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
494 static char line[256]; /* line to be logged accumulated here */
495 static char *linep; /* current pointer within line */
496 static int llevel; /* level for logging */
499 init_pr_log(prefix, level)
504 if (prefix != NULL) {
505 ppp_strlcpy(line, prefix, sizeof(line));
506 linep = line + strlen(line);
516 ppp_log_write(llevel, line);
521 * pr_log - printer routine for outputting to log
524 pr_log (void *arg, const char *fmt, ...)
532 n = ppp_vslprintf(buf, sizeof(buf), fmt, pvar);
536 eol = strchr(buf, '\n');
538 l = (eol == NULL)? n: eol - buf;
539 if (linep + l < line + sizeof(line)) {
541 memcpy(linep, buf, l);
547 eol = strchr(p, '\n');
550 ppp_log_write(llevel, line);
554 while (eol != NULL) {
556 ppp_log_write(llevel, p);
558 eol = strchr(p, '\n');
561 /* assumes sizeof(buf) <= sizeof(line) */
571 * ppp_print_string - print a readable representation of a string using
574 void ppp_print_string(const u_char *p, int len, void (*printer) (void *, const char *, ...), void *arg) {
578 for (; len > 0; --len) {
580 if (' ' <= c && c <= '~') {
581 if (c == '\\' || c == '"')
583 printer(arg, "%c", c);
596 printer(arg, "\\%.3o", (u8_t)c);
605 * ppp_logit - does the hard work for fatal et al.
607 static void ppp_logit(int level, const char *fmt, va_list args) {
610 ppp_vslprintf(buf, sizeof(buf), fmt, args);
611 ppp_log_write(level, buf);
614 static void ppp_log_write(int level, char *buf) {
615 LWIP_UNUSED_ARG(level); /* necessary if PPPDEBUG is defined to an empty function */
616 LWIP_UNUSED_ARG(buf);
617 PPPDEBUG(level, ("%s\n", buf) );
619 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
622 if (n > 0 && buf[n-1] == '\n')
624 if (write(log_to_fd, buf, n) != n
625 || write(log_to_fd, "\n", 1) != 1)
632 * ppp_fatal - log an error message and die horribly.
634 void ppp_fatal(const char *fmt, ...) {
638 ppp_logit(LOG_ERR, fmt, pvar);
641 LWIP_ASSERT("ppp_fatal", 0); /* as promised */
645 * ppp_error - log an error message.
647 void ppp_error(const char *fmt, ...) {
651 ppp_logit(LOG_ERR, fmt, pvar);
659 * ppp_warn - log a warning message.
661 void ppp_warn(const char *fmt, ...) {
665 ppp_logit(LOG_WARNING, fmt, pvar);
670 * ppp_notice - log a notice-level message.
672 void ppp_notice(const char *fmt, ...) {
676 ppp_logit(LOG_NOTICE, fmt, pvar);
681 * ppp_info - log an informational message.
683 void ppp_info(const char *fmt, ...) {
687 ppp_logit(LOG_INFO, fmt, pvar);
692 * ppp_dbglog - log a debug message.
694 void ppp_dbglog(const char *fmt, ...) {
698 ppp_logit(LOG_DEBUG, fmt, pvar);
704 * ppp_dump_packet - print out a packet in readable form if it is interesting.
705 * Assumes len >= PPP_HDRLEN.
707 void ppp_dump_packet(ppp_pcb *pcb, const char *tag, unsigned char *p, int len) {
711 * don't print data packets, i.e. IPv4, IPv6, VJ, and compressed packets.
713 proto = (p[0] << 8) + p[1];
714 if (proto < 0xC000 && (proto & ~0x8000) == proto)
718 * don't print valid LCP echo request/reply packets if the link is up.
720 if (proto == PPP_LCP && pcb->phase == PPP_PHASE_RUNNING && len >= 2 + HEADERLEN) {
721 unsigned char *lcp = p + 2;
722 int l = (lcp[2] << 8) + lcp[3];
724 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
725 && l >= HEADERLEN && l <= len - 2)
729 ppp_dbglog("%s %P", tag, p, len);
731 #endif /* PRINTPKT_SUPPORT */
736 * complete_read - read a full `count' bytes from fd,
737 * unless end-of-file or an error other than EINTR is encountered.
740 complete_read(int fd, void *buf, size_t count)
746 for (done = 0; done < count; ) {
747 nb = read(fd, ptr, count - done);
761 /* Procedures for locking the serial device using a lock file. */
764 #define LOCK_DIR "/var/lock"
767 #define LOCK_DIR "/var/spool/locks"
769 #define LOCK_DIR "/var/spool/lock"
772 #endif /* LOCK_DIR */
774 static char lock_file[MAXPATHLEN];
777 * lock - create a lock file for the named device
786 result = mklock (dev, (void *) 0);
788 ppp_strlcpy(lock_file, dev, sizeof(lock_file));
793 ppp_notice("Device %s is locked by pid %d", dev, result);
795 ppp_error("Can't create lock file %s", lock_file);
800 char lock_buffer[12];
806 if (stat(dev, &sbuf) < 0) {
807 ppp_error("Can't get device number for %s: %m", dev);
810 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
811 ppp_error("Can't lock %s: not a character device", dev);
814 ppp_slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
815 LOCK_DIR, major(sbuf.st_dev),
816 major(sbuf.st_rdev), minor(sbuf.st_rdev));
819 char lockdev[MAXPATHLEN];
821 if ((p = strstr(dev, "dev/")) != NULL) {
823 strncpy(lockdev, dev, MAXPATHLEN-1);
824 lockdev[MAXPATHLEN-1] = 0;
825 while ((p = strrchr(lockdev, '/')) != NULL) {
830 if ((p = strrchr(dev, '/')) != NULL)
833 ppp_slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
836 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
837 if (errno != EEXIST) {
838 ppp_error("Can't create lock file %s: %m", lock_file);
842 /* Read the lock file to find out who has the device locked. */
843 fd = open(lock_file, O_RDONLY, 0);
845 if (errno == ENOENT) /* This is just a timing problem. */
847 ppp_error("Can't open existing lock file %s: %m", lock_file);
851 n = read(fd, lock_buffer, 11);
853 n = read(fd, &pid, sizeof(pid));
854 #endif /* LOCK_BINARY */
858 ppp_error("Can't read pid from lock file %s", lock_file);
862 /* See if the process still exists. */
865 pid = atoi(lock_buffer);
866 #endif /* LOCK_BINARY */
868 return 1; /* somebody else locked it for us */
870 || (kill(pid, 0) == -1 && errno == ESRCH)) {
871 if (unlink (lock_file) == 0) {
872 ppp_notice("Removed stale lock on %s (pid %d)", dev, pid);
875 ppp_warn("Couldn't remove stale lock on %s", dev);
877 ppp_notice("Device %s is locked by pid %d", dev, pid);
888 ppp_slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
889 write (fd, lock_buffer, 11);
891 write(fd, &pid, sizeof (pid));
900 * relock - called to update our lockfile when we are about to detach,
901 * thus changing our pid (we fork, the child carries on, and the parent dies).
902 * Note that this is called by the parent, with pid equal to the pid
903 * of the child. This avoids a potential race which would exist if
904 * we had the child rewrite the lockfile (the parent might die first,
905 * and another process could think the lock was stale if it checked
906 * between when the parent died and the child rewrote the lockfile).
913 /* XXX is there a way to do this? */
918 char lock_buffer[12];
920 if (lock_file[0] == 0)
922 fd = open(lock_file, O_WRONLY, 0);
924 ppp_error("Couldn't reopen lock file %s: %m", lock_file);
930 ppp_slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
931 write (fd, lock_buffer, 11);
933 write(fd, &pid, sizeof(pid));
934 #endif /* LOCK_BINARY */
942 * unlock - remove our lockfile
949 (void) rmlock(lock_file, (void *) 0);
959 #endif /* PPP_SUPPORT */