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 $"
32 #define LOG_TAG "pppd"
47 #include <sys/param.h>
48 #include <sys/types.h>
51 #include <sys/resource.h>
53 #include <sys/socket.h>
54 #include <netinet/in.h>
56 #include <sys/mkdev.h>
63 #ifdef ANDROID_CHANGES
64 #include <cutils/logd.h>
67 static const char rcsid[] = RCSID;
70 extern char *strerror();
73 static void logit __P((int, char *, va_list));
74 static void log_write __P((int, char *));
75 static void vslp_printer __P((void *, char *, ...));
76 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
85 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
86 * always leaves destination null-terminated (for len > 0).
89 strlcpy(dest, src, len)
94 size_t ret = strlen(src);
100 strncpy(dest, src, len - 1);
108 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
109 * always leaves destination null-terminated (for len > 0).
112 strlcat(dest, src, len)
117 size_t dlen = strlen(dest);
119 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
124 * slprintf - format a message into a buffer. Like sprintf except we
125 * also specify the length of the output buffer, and we handle
126 * %m (error message), %v (visible string),
127 * %q (quoted string), %t (current time) and %I (IP address) formats.
128 * Doesn't do floating-point formats.
129 * Returns the number of chars put into buf.
132 slprintf __V((char *buf, int buflen, char *fmt, ...))
137 #if defined(__STDC__)
144 buf = va_arg(args, char *);
145 buflen = va_arg(args, int);
146 fmt = va_arg(args, char *);
148 n = vslprintf(buf, buflen, fmt, args);
154 * vslprintf - like slprintf, takes a va_list instead of a list of args.
156 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
159 vslprintf(buf, buflen, fmt, args)
166 int width, prec, fillch;
167 int base, len, neg, quoted;
168 unsigned long val = 0;
169 char *str, *f, *buf0;
174 static char hexchars[] = "0123456789abcdef";
175 struct buffer_info bufinfo;
180 for (f = fmt; *f != '%' && *f != 0; ++f)
186 memcpy(buf, fmt, len);
202 width = va_arg(args, int);
206 width = width * 10 + c - '0';
213 prec = va_arg(args, int);
218 prec = prec * 10 + c - '0';
232 val = va_arg(args, long);
235 val = (unsigned long)(-(long)val);
240 val = va_arg(args, unsigned long);
244 *buf++ = '%'; --buflen;
245 *buf++ = 'l'; --buflen;
246 --fmt; /* so %lz outputs %lz etc. */
251 i = va_arg(args, int);
260 val = va_arg(args, unsigned int);
264 val = va_arg(args, unsigned int);
269 val = va_arg(args, unsigned int);
273 val = (unsigned long) va_arg(args, void *);
278 str = va_arg(args, char *);
281 num[0] = va_arg(args, int);
286 str = strerror(errno);
289 ip = va_arg(args, u_int32_t);
291 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
292 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
295 #if 0 /* not used, and breaks on S/390, apparently */
297 f = va_arg(args, char *);
299 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
301 /* On the powerpc, a va_list is an array of 1 structure */
302 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
311 str += 4; /* chop off the day name */
312 str[15] = 0; /* chop off year and newline */
314 case 'v': /* "visible" string */
315 case 'q': /* quoted string */
317 p = va_arg(args, unsigned char *);
318 if (fillch == '0' && prec >= 0) {
321 n = strlen((char *)p);
322 if (prec >= 0 && n > prec)
325 while (n > 0 && buflen > 0) {
328 if (!quoted && c >= 0x80) {
333 if (quoted && (c == '"' || c == '\\'))
335 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
339 case '\t': OUTCHAR('t'); break;
340 case '\n': OUTCHAR('n'); break;
341 case '\b': OUTCHAR('b'); break;
342 case '\f': OUTCHAR('f'); break;
345 OUTCHAR(hexchars[c >> 4]);
346 OUTCHAR(hexchars[c & 0xf]);
360 case 'P': /* print PPP packet */
362 bufinfo.len = buflen + 1;
363 p = va_arg(args, unsigned char *);
364 n = va_arg(args, int);
365 format_packet(p, n, vslp_printer, &bufinfo);
367 buflen = bufinfo.len - 1;
370 p = va_arg(args, unsigned char *);
371 for (n = prec; n > 0; --n) {
375 OUTCHAR(hexchars[(c >> 4) & 0xf]);
376 OUTCHAR(hexchars[c & 0xf]);
382 --fmt; /* so %z outputs %z etc. */
387 str = num + sizeof(num);
389 while (str > num + neg) {
390 *--str = hexchars[val % base];
392 if (--prec <= 0 && val == 0)
404 len = num + sizeof(num) - 1 - str;
407 if (prec >= 0 && len > prec)
413 if ((n = width - len) > 0) {
421 memcpy(buf, str, len);
430 * vslp_printer - used in processing a %P format
433 vslp_printer __V((void *arg, char *fmt, ...))
437 struct buffer_info *bi;
439 #if defined(__STDC__)
445 arg = va_arg(pvar, void *);
446 fmt = va_arg(pvar, char *);
449 bi = (struct buffer_info *) arg;
450 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
459 * log_packet - format a packet and log it.
463 log_packet(p, len, prefix, level)
469 init_pr_log(prefix, level);
470 format_packet(p, len, pr_log, &level);
476 * format_packet - make a readable representation of a packet,
477 * calling `printer(arg, format, ...)' to output it.
480 format_packet(p, len, printer, arg)
483 void (*printer) __P((void *, char *, ...));
488 struct protent *protp;
490 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
494 for (i = 0; (protp = protocols[i]) != NULL; ++i)
495 if (proto == protp->protocol)
498 printer(arg, "[%s", protp->name);
499 n = (*protp->printpkt)(p, len, printer, arg);
504 for (i = 0; (protp = protocols[i]) != NULL; ++i)
505 if (proto == (protp->protocol & ~0x8000))
507 if (protp != 0 && protp->data_name != 0) {
508 printer(arg, "[%s data]", protp->data_name);
510 printer(arg, "%.8B ...", p);
512 printer(arg, "%.*B", len, p);
515 printer(arg, "[proto=0x%x]", proto);
520 printer(arg, "%.32B ...", p);
522 printer(arg, "%.*B", len, p);
526 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
529 static char line[256]; /* line to be logged accumulated here */
530 static char *linep; /* current pointer within line */
531 static int llevel; /* level for logging */
534 init_pr_log(prefix, level)
539 if (prefix != NULL) {
540 strlcpy(line, prefix, sizeof(line));
541 linep = line + strlen(line);
551 log_write(llevel, line);
556 * pr_log - printer routine for outputting to syslog
559 pr_log __V((void *arg, char *fmt, ...))
566 #if defined(__STDC__)
572 arg = va_arg(pvar, void *);
573 fmt = va_arg(pvar, char *);
576 n = vslprintf(buf, sizeof(buf), fmt, pvar);
580 eol = strchr(buf, '\n');
582 l = (eol == NULL)? n: eol - buf;
583 if (linep + l < line + sizeof(line)) {
585 memcpy(linep, buf, l);
591 eol = strchr(p, '\n');
594 log_write(llevel, line);
598 while (eol != NULL) {
600 log_write(llevel, p);
602 eol = strchr(p, '\n');
605 /* assumes sizeof(buf) <= sizeof(line) */
614 * print_string - print a readable representation of a string using
618 print_string(p, len, printer, arg)
621 void (*printer) __P((void *, char *, ...));
627 for (; len > 0; --len) {
629 if (' ' <= c && c <= '~') {
630 if (c == '\\' || c == '"')
632 printer(arg, "%c", c);
645 printer(arg, "\\%.3o", c);
653 * logit - does the hard work for fatal et al.
656 logit(level, fmt, args)
664 n = vslprintf(buf, sizeof(buf), fmt, args);
665 log_write(level, buf);
668 #ifdef ANDROID_CHANGES
671 #error Syslog.h has been changed! Please fix this table!
674 static int syslog_to_android[] = {
675 [LOG_EMERG] = ANDROID_LOG_FATAL,
676 [LOG_ALERT] = ANDROID_LOG_FATAL,
677 [LOG_CRIT] = ANDROID_LOG_FATAL,
678 [LOG_ERR] = ANDROID_LOG_ERROR,
679 [LOG_WARNING] = ANDROID_LOG_WARN,
680 [LOG_NOTICE] = ANDROID_LOG_INFO,
681 [LOG_INFO] = ANDROID_LOG_INFO,
682 [LOG_DEBUG] = ANDROID_LOG_DEBUG,
688 log_write(level, buf)
692 #ifndef ANDROID_CHANGES
693 syslog(level, "%s", buf);
695 fprintf(stderr, buf);
697 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
700 if (n > 0 && buf[n-1] == '\n')
702 if (write(log_to_fd, buf, n) != n
703 || write(log_to_fd, "\n", 1) != 1)
707 __android_log_write(syslog_to_android[level], LOG_TAG, buf);
712 * fatal - log an error message and die horribly.
715 fatal __V((char *fmt, ...))
719 #if defined(__STDC__)
724 fmt = va_arg(pvar, char *);
727 logit(LOG_ERR, fmt, pvar);
730 die(1); /* as promised */
734 * error - log an error message.
737 error __V((char *fmt, ...))
741 #if defined(__STDC__)
746 fmt = va_arg(pvar, char *);
749 logit(LOG_ERR, fmt, pvar);
755 * warn - log a warning message.
758 warn __V((char *fmt, ...))
762 #if defined(__STDC__)
767 fmt = va_arg(pvar, char *);
770 logit(LOG_WARNING, fmt, pvar);
775 * notice - log a notice-level message.
778 notice __V((char *fmt, ...))
782 #if defined(__STDC__)
787 fmt = va_arg(pvar, char *);
790 logit(LOG_NOTICE, fmt, pvar);
795 * info - log an informational message.
798 info __V((char *fmt, ...))
802 #if defined(__STDC__)
807 fmt = va_arg(pvar, char *);
810 logit(LOG_INFO, fmt, pvar);
815 * dbglog - log a debug message.
818 dbglog __V((char *fmt, ...))
822 #if defined(__STDC__)
827 fmt = va_arg(pvar, char *);
830 logit(LOG_DEBUG, fmt, pvar);
835 * dump_packet - print out a packet in readable form if it is interesting.
836 * Assumes len >= PPP_HDRLEN.
839 dump_packet(const char *tag, unsigned char *p, int len)
847 * don't print LCP echo request/reply packets if debug <= 1
848 * and the link is up.
850 proto = (p[2] << 8) + p[3];
851 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
852 && len >= PPP_HDRLEN + HEADERLEN) {
853 unsigned char *lcp = p + PPP_HDRLEN;
854 int l = (lcp[2] << 8) + lcp[3];
856 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
857 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
861 dbglog("%s %P", tag, p, len);
865 * complete_read - read a full `count' bytes from fd,
866 * unless end-of-file or an error other than EINTR is encountered.
869 complete_read(int fd, void *buf, size_t count)
875 for (done = 0; done < count; ) {
876 nb = read(fd, ptr, count - done);
890 /* Procedures for locking the serial device using a lock file. */
893 #define LOCK_DIR "/var/lock"
896 #define LOCK_DIR "/var/spool/locks"
898 #define LOCK_DIR "/var/spool/lock"
901 #endif /* LOCK_DIR */
903 static char lock_file[MAXPATHLEN];
906 * lock - create a lock file for the named device
915 result = mklock (dev, (void *) 0);
917 strlcpy(lock_file, dev, sizeof(lock_file));
922 notice("Device %s is locked by pid %d", dev, result);
924 error("Can't create lock file %s", lock_file);
929 char lock_buffer[12];
935 if (stat(dev, &sbuf) < 0) {
936 error("Can't get device number for %s: %m", dev);
939 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
940 error("Can't lock %s: not a character device", dev);
943 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
944 LOCK_DIR, major(sbuf.st_dev),
945 major(sbuf.st_rdev), minor(sbuf.st_rdev));
948 char lockdev[MAXPATHLEN];
950 if ((p = strstr(dev, "dev/")) != NULL) {
952 strncpy(lockdev, dev, MAXPATHLEN-1);
953 lockdev[MAXPATHLEN-1] = 0;
954 while ((p = strrchr(lockdev, '/')) != NULL) {
959 if ((p = strrchr(dev, '/')) != NULL)
962 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
965 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
966 if (errno != EEXIST) {
967 error("Can't create lock file %s: %m", lock_file);
971 /* Read the lock file to find out who has the device locked. */
972 fd = open(lock_file, O_RDONLY, 0);
974 if (errno == ENOENT) /* This is just a timing problem. */
976 error("Can't open existing lock file %s: %m", lock_file);
980 n = read(fd, lock_buffer, 11);
982 n = read(fd, &pid, sizeof(pid));
983 #endif /* LOCK_BINARY */
987 error("Can't read pid from lock file %s", lock_file);
991 /* See if the process still exists. */
994 pid = atoi(lock_buffer);
995 #endif /* LOCK_BINARY */
997 return 1; /* somebody else locked it for us */
999 || (kill(pid, 0) == -1 && errno == ESRCH)) {
1000 if (unlink (lock_file) == 0) {
1001 notice("Removed stale lock on %s (pid %d)", dev, pid);
1004 warn("Couldn't remove stale lock on %s", dev);
1006 notice("Device %s is locked by pid %d", dev, pid);
1017 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1018 write (fd, lock_buffer, 11);
1020 write(fd, &pid, sizeof (pid));
1029 * relock - called to update our lockfile when we are about to detach,
1030 * thus changing our pid (we fork, the child carries on, and the parent dies).
1031 * Note that this is called by the parent, with pid equal to the pid
1032 * of the child. This avoids a potential race which would exist if
1033 * we had the child rewrite the lockfile (the parent might die first,
1034 * and another process could think the lock was stale if it checked
1035 * between when the parent died and the child rewrote the lockfile).
1042 /* XXX is there a way to do this? */
1047 char lock_buffer[12];
1049 if (lock_file[0] == 0)
1051 fd = open(lock_file, O_WRONLY, 0);
1053 error("Couldn't reopen lock file %s: %m", lock_file);
1059 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1060 write (fd, lock_buffer, 11);
1062 write(fd, &pid, sizeof(pid));
1063 #endif /* LOCK_BINARY */
1067 #endif /* LOCKLIB */
1071 * unlock - remove our lockfile
1078 (void) rmlock(lock_file, (void *) 0);