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 <android/log.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 *, ...),
84 #if !defined(ANDROID_CHANGES)
87 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
88 * always leaves destination null-terminated (for len > 0).
91 strlcpy(dest, src, len)
96 size_t ret = strlen(src);
102 strncpy(dest, src, len - 1);
110 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
111 * always leaves destination null-terminated (for len > 0).
114 strlcat(dest, src, len)
119 size_t dlen = strlen(dest);
121 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
127 * slprintf - format a message into a buffer. Like sprintf except we
128 * also specify the length of the output buffer, and we handle
129 * %m (error message), %v (visible string),
130 * %q (quoted string), %t (current time) and %I (IP address) formats.
131 * Doesn't do floating-point formats.
132 * Returns the number of chars put into buf.
135 slprintf __V((char *buf, int buflen, char *fmt, ...))
140 #if defined(__STDC__)
147 buf = va_arg(args, char *);
148 buflen = va_arg(args, int);
149 fmt = va_arg(args, char *);
151 n = vslprintf(buf, buflen, fmt, args);
157 * vslprintf - like slprintf, takes a va_list instead of a list of args.
159 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
162 vslprintf(buf, buflen, fmt, args)
169 int width, prec, fillch;
170 int base, len, neg, quoted;
171 unsigned long val = 0;
172 char *str, *f, *buf0;
177 static char hexchars[] = "0123456789abcdef";
178 struct buffer_info bufinfo;
183 for (f = fmt; *f != '%' && *f != 0; ++f)
189 memcpy(buf, fmt, len);
205 width = va_arg(args, int);
209 width = width * 10 + c - '0';
216 prec = va_arg(args, int);
221 prec = prec * 10 + c - '0';
235 val = va_arg(args, long);
238 val = (unsigned long)(-(long)val);
243 val = va_arg(args, unsigned long);
247 *buf++ = '%'; --buflen;
248 *buf++ = 'l'; --buflen;
249 --fmt; /* so %lz outputs %lz etc. */
254 i = va_arg(args, int);
263 val = va_arg(args, unsigned int);
267 val = va_arg(args, unsigned int);
272 val = va_arg(args, unsigned int);
276 val = (unsigned long) va_arg(args, void *);
281 str = va_arg(args, char *);
284 num[0] = va_arg(args, int);
289 str = strerror(errno);
292 ip = va_arg(args, u_int32_t);
294 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
295 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
298 #if 0 /* not used, and breaks on S/390, apparently */
300 f = va_arg(args, char *);
302 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
304 /* On the powerpc, a va_list is an array of 1 structure */
305 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
314 str += 4; /* chop off the day name */
315 str[15] = 0; /* chop off year and newline */
317 case 'v': /* "visible" string */
318 case 'q': /* quoted string */
320 p = va_arg(args, unsigned char *);
321 if (fillch == '0' && prec >= 0) {
324 n = strlen((char *)p);
325 if (prec >= 0 && n > prec)
328 while (n > 0 && buflen > 0) {
331 if (!quoted && c >= 0x80) {
336 if (quoted && (c == '"' || c == '\\'))
338 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
342 case '\t': OUTCHAR('t'); break;
343 case '\n': OUTCHAR('n'); break;
344 case '\b': OUTCHAR('b'); break;
345 case '\f': OUTCHAR('f'); break;
348 OUTCHAR(hexchars[c >> 4]);
349 OUTCHAR(hexchars[c & 0xf]);
363 case 'P': /* print PPP packet */
365 bufinfo.len = buflen + 1;
366 p = va_arg(args, unsigned char *);
367 n = va_arg(args, int);
368 format_packet(p, n, vslp_printer, &bufinfo);
370 buflen = bufinfo.len - 1;
373 p = va_arg(args, unsigned char *);
374 for (n = prec; n > 0; --n) {
378 OUTCHAR(hexchars[(c >> 4) & 0xf]);
379 OUTCHAR(hexchars[c & 0xf]);
385 --fmt; /* so %z outputs %z etc. */
390 str = num + sizeof(num);
392 while (str > num + neg) {
393 *--str = hexchars[val % base];
395 if (--prec <= 0 && val == 0)
407 len = num + sizeof(num) - 1 - str;
410 if (prec >= 0 && len > prec)
416 if ((n = width - len) > 0) {
424 memcpy(buf, str, len);
433 * vslp_printer - used in processing a %P format
436 vslp_printer __V((void *arg, char *fmt, ...))
440 struct buffer_info *bi;
442 #if defined(__STDC__)
448 arg = va_arg(pvar, void *);
449 fmt = va_arg(pvar, char *);
452 bi = (struct buffer_info *) arg;
453 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
462 * log_packet - format a packet and log it.
466 log_packet(p, len, prefix, level)
472 init_pr_log(prefix, level);
473 format_packet(p, len, pr_log, &level);
479 * format_packet - make a readable representation of a packet,
480 * calling `printer(arg, format, ...)' to output it.
483 format_packet(p, len, printer, arg)
486 void (*printer) __P((void *, char *, ...));
491 struct protent *protp;
493 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
497 for (i = 0; (protp = protocols[i]) != NULL; ++i)
498 if (proto == protp->protocol)
501 printer(arg, "[%s", protp->name);
502 n = (*protp->printpkt)(p, len, printer, arg);
507 for (i = 0; (protp = protocols[i]) != NULL; ++i)
508 if (proto == (protp->protocol & ~0x8000))
510 if (protp != 0 && protp->data_name != 0) {
511 printer(arg, "[%s data]", protp->data_name);
513 printer(arg, "%.8B ...", p);
515 printer(arg, "%.*B", len, p);
518 printer(arg, "[proto=0x%x]", proto);
523 printer(arg, "%.32B ...", p);
525 printer(arg, "%.*B", len, p);
529 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
532 static char line[256]; /* line to be logged accumulated here */
533 static char *linep; /* current pointer within line */
534 static int llevel; /* level for logging */
537 init_pr_log(prefix, level)
542 if (prefix != NULL) {
543 strlcpy(line, prefix, sizeof(line));
544 linep = line + strlen(line);
554 log_write(llevel, line);
559 * pr_log - printer routine for outputting to syslog
562 pr_log __V((void *arg, char *fmt, ...))
569 #if defined(__STDC__)
575 arg = va_arg(pvar, void *);
576 fmt = va_arg(pvar, char *);
579 n = vslprintf(buf, sizeof(buf), fmt, pvar);
583 eol = strchr(buf, '\n');
585 l = (eol == NULL)? n: eol - buf;
586 if (linep + l < line + sizeof(line)) {
588 memcpy(linep, buf, l);
594 eol = strchr(p, '\n');
597 log_write(llevel, line);
601 while (eol != NULL) {
603 log_write(llevel, p);
605 eol = strchr(p, '\n');
608 /* assumes sizeof(buf) <= sizeof(line) */
617 * print_string - print a readable representation of a string using
621 print_string(p, len, printer, arg)
624 void (*printer) __P((void *, char *, ...));
630 for (; len > 0; --len) {
632 if (' ' <= c && c <= '~') {
633 if (c == '\\' || c == '"')
635 printer(arg, "%c", c);
648 printer(arg, "\\%.3o", c);
656 * logit - does the hard work for fatal et al.
659 logit(level, fmt, args)
667 n = vslprintf(buf, sizeof(buf), fmt, args);
668 log_write(level, buf);
671 #ifdef ANDROID_CHANGES
674 #error Syslog.h has been changed! Please fix this table!
677 static int syslog_to_android[] = {
678 [LOG_EMERG] = ANDROID_LOG_FATAL,
679 [LOG_ALERT] = ANDROID_LOG_FATAL,
680 [LOG_CRIT] = ANDROID_LOG_FATAL,
681 [LOG_ERR] = ANDROID_LOG_ERROR,
682 [LOG_WARNING] = ANDROID_LOG_WARN,
683 [LOG_NOTICE] = ANDROID_LOG_INFO,
684 [LOG_INFO] = ANDROID_LOG_INFO,
685 [LOG_DEBUG] = ANDROID_LOG_DEBUG,
691 log_write(level, buf)
695 #ifndef ANDROID_CHANGES
696 syslog(level, "%s", buf);
698 fprintf(stderr, buf);
700 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
703 if (n > 0 && buf[n-1] == '\n')
705 if (write(log_to_fd, buf, n) != n
706 || write(log_to_fd, "\n", 1) != 1)
710 __android_log_write(syslog_to_android[level], LOG_TAG, buf);
715 * fatal - log an error message and die horribly.
718 fatal __V((char *fmt, ...))
722 #if defined(__STDC__)
727 fmt = va_arg(pvar, char *);
730 logit(LOG_ERR, fmt, pvar);
733 die(1); /* as promised */
737 * error - log an error message.
740 error __V((char *fmt, ...))
744 #if defined(__STDC__)
749 fmt = va_arg(pvar, char *);
752 logit(LOG_ERR, fmt, pvar);
758 * warn - log a warning message.
761 warn __V((char *fmt, ...))
765 #if defined(__STDC__)
770 fmt = va_arg(pvar, char *);
773 logit(LOG_WARNING, fmt, pvar);
778 * notice - log a notice-level message.
781 notice __V((char *fmt, ...))
785 #if defined(__STDC__)
790 fmt = va_arg(pvar, char *);
793 logit(LOG_NOTICE, fmt, pvar);
798 * info - log an informational message.
801 info __V((char *fmt, ...))
805 #if defined(__STDC__)
810 fmt = va_arg(pvar, char *);
813 logit(LOG_INFO, fmt, pvar);
818 * dbglog - log a debug message.
821 dbglog __V((char *fmt, ...))
825 #if defined(__STDC__)
830 fmt = va_arg(pvar, char *);
833 logit(LOG_DEBUG, fmt, pvar);
838 * dump_packet - print out a packet in readable form if it is interesting.
839 * Assumes len >= PPP_HDRLEN.
842 dump_packet(const char *tag, unsigned char *p, int len)
850 * don't print LCP echo request/reply packets if debug <= 1
851 * and the link is up.
853 proto = (p[2] << 8) + p[3];
854 if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
855 && len >= PPP_HDRLEN + HEADERLEN) {
856 unsigned char *lcp = p + PPP_HDRLEN;
857 int l = (lcp[2] << 8) + lcp[3];
859 if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
860 && l >= HEADERLEN && l <= len - PPP_HDRLEN)
864 dbglog("%s %P", tag, p, len);
868 * complete_read - read a full `count' bytes from fd,
869 * unless end-of-file or an error other than EINTR is encountered.
872 complete_read(int fd, void *buf, size_t count)
878 for (done = 0; done < count; ) {
879 nb = read(fd, ptr, count - done);
893 /* Procedures for locking the serial device using a lock file. */
896 #define LOCK_DIR "/var/lock"
899 #define LOCK_DIR "/var/spool/locks"
901 #define LOCK_DIR "/var/spool/lock"
904 #endif /* LOCK_DIR */
906 static char lock_file[MAXPATHLEN];
909 * lock - create a lock file for the named device
918 result = mklock (dev, (void *) 0);
920 strlcpy(lock_file, dev, sizeof(lock_file));
925 notice("Device %s is locked by pid %d", dev, result);
927 error("Can't create lock file %s", lock_file);
932 char lock_buffer[12];
938 if (stat(dev, &sbuf) < 0) {
939 error("Can't get device number for %s: %m", dev);
942 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
943 error("Can't lock %s: not a character device", dev);
946 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
947 LOCK_DIR, major(sbuf.st_dev),
948 major(sbuf.st_rdev), minor(sbuf.st_rdev));
951 char lockdev[MAXPATHLEN];
953 if ((p = strstr(dev, "dev/")) != NULL) {
955 strncpy(lockdev, dev, MAXPATHLEN-1);
956 lockdev[MAXPATHLEN-1] = 0;
957 while ((p = strrchr(lockdev, '/')) != NULL) {
962 if ((p = strrchr(dev, '/')) != NULL)
965 slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
968 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
969 if (errno != EEXIST) {
970 error("Can't create lock file %s: %m", lock_file);
974 /* Read the lock file to find out who has the device locked. */
975 fd = open(lock_file, O_RDONLY, 0);
977 if (errno == ENOENT) /* This is just a timing problem. */
979 error("Can't open existing lock file %s: %m", lock_file);
983 n = read(fd, lock_buffer, 11);
985 n = read(fd, &pid, sizeof(pid));
986 #endif /* LOCK_BINARY */
990 error("Can't read pid from lock file %s", lock_file);
994 /* See if the process still exists. */
997 pid = atoi(lock_buffer);
998 #endif /* LOCK_BINARY */
1000 return 1; /* somebody else locked it for us */
1002 || (kill(pid, 0) == -1 && errno == ESRCH)) {
1003 if (unlink (lock_file) == 0) {
1004 notice("Removed stale lock on %s (pid %d)", dev, pid);
1007 warn("Couldn't remove stale lock on %s", dev);
1009 notice("Device %s is locked by pid %d", dev, pid);
1020 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1021 write (fd, lock_buffer, 11);
1023 write(fd, &pid, sizeof (pid));
1032 * relock - called to update our lockfile when we are about to detach,
1033 * thus changing our pid (we fork, the child carries on, and the parent dies).
1034 * Note that this is called by the parent, with pid equal to the pid
1035 * of the child. This avoids a potential race which would exist if
1036 * we had the child rewrite the lockfile (the parent might die first,
1037 * and another process could think the lock was stale if it checked
1038 * between when the parent died and the child rewrote the lockfile).
1045 /* XXX is there a way to do this? */
1050 char lock_buffer[12];
1052 if (lock_file[0] == 0)
1054 fd = open(lock_file, O_WRONLY, 0);
1056 error("Couldn't reopen lock file %s: %m", lock_file);
1062 slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1063 write (fd, lock_buffer, 11);
1065 write(fd, &pid, sizeof(pid));
1066 #endif /* LOCK_BINARY */
1070 #endif /* LOCKLIB */
1074 * unlock - remove our lockfile
1081 (void) rmlock(lock_file, (void *) 0);