2 * utils.c - various utility functions used in pppd.
4 * Copyright (c) 1999 The Australian National University.
7 * Redistribution and use in source and binary forms are permitted
8 * provided that the above copyright notice and this paragraph are
9 * duplicated in all such forms and that any documentation,
10 * advertising materials, and other materials related to such
11 * distribution and use acknowledge that the software was developed
12 * by the Australian National University. The name of the University
13 * may not be used to endorse or promote products derived from this
14 * software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 #define RCSID "$Id: utils.c,v 1.13 2001/03/16 02:08:13 paulus Exp $"
35 #include <sys/param.h>
36 #include <sys/types.h>
39 #include <sys/resource.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
44 #include <sys/mkdev.h>
49 static const char rcsid[] = RCSID;
52 extern char *strerror();
55 static void logit __P((int, char *, va_list));
56 static void log_write __P((int, char *));
57 static void vslp_printer __P((void *, char *, ...));
58 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
67 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
68 * always leaves destination null-terminated (for len > 0).
71 strlcpy(dest, src, len)
76 size_t ret = strlen(src);
82 strncpy(dest, src, len - 1);
90 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
91 * always leaves destination null-terminated (for len > 0).
94 strlcat(dest, src, len)
99 size_t dlen = strlen(dest);
101 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
106 * slprintf - format a message into a buffer. Like sprintf except we
107 * also specify the length of the output buffer, and we handle
108 * %r (recursive format), %m (error message), %v (visible string),
109 * %q (quoted string), %t (current time) and %I (IP address) formats.
110 * Doesn't do floating-point formats.
111 * Returns the number of chars put into buf.
114 slprintf __V((char *buf, int buflen, char *fmt, ...))
119 #if defined(__STDC__)
126 buf = va_arg(args, char *);
127 buflen = va_arg(args, int);
128 fmt = va_arg(args, char *);
130 n = vslprintf(buf, buflen, fmt, args);
136 * vslprintf - like slprintf, takes a va_list instead of a list of args.
138 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
141 vslprintf(buf, buflen, fmt, args)
148 int width, prec, fillch;
149 int base, len, neg, quoted;
150 unsigned long val = 0;
151 char *str, *f, *buf0;
156 static char hexchars[] = "0123456789abcdef";
157 struct buffer_info bufinfo;
162 for (f = fmt; *f != '%' && *f != 0; ++f)
168 memcpy(buf, fmt, len);
184 width = va_arg(args, int);
188 width = width * 10 + c - '0';
195 prec = va_arg(args, int);
200 prec = prec * 10 + c - '0';
211 i = va_arg(args, int);
220 val = va_arg(args, unsigned int);
224 val = va_arg(args, unsigned int);
229 val = va_arg(args, unsigned int);
233 val = (unsigned long) va_arg(args, void *);
238 str = va_arg(args, char *);
241 num[0] = va_arg(args, int);
247 str = strerror(errno);
249 slprintf(num, sizeof(num), "err = %d", val);
254 ip = va_arg(args, u_int32_t);
256 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
257 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
261 f = va_arg(args, char *);
263 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
265 /* On the powerpc, a va_list is an array of 1 structure */
266 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
274 str += 4; /* chop off the day name */
275 str[15] = 0; /* chop off year and newline */
277 case 'v': /* "visible" string */
278 case 'q': /* quoted string */
280 p = va_arg(args, unsigned char *);
281 if (fillch == '0' && prec >= 0) {
284 n = strlen((char *)p);
285 if (prec >= 0 && n > prec)
288 while (n > 0 && buflen > 0) {
291 if (!quoted && c >= 0x80) {
296 if (quoted && (c == '"' || c == '\\'))
298 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
302 case '\t': OUTCHAR('t'); break;
303 case '\n': OUTCHAR('n'); break;
304 case '\b': OUTCHAR('b'); break;
305 case '\f': OUTCHAR('f'); break;
308 OUTCHAR(hexchars[c >> 4]);
309 OUTCHAR(hexchars[c & 0xf]);
323 case 'P': /* print PPP packet */
325 bufinfo.len = buflen + 1;
326 p = va_arg(args, unsigned char *);
327 n = va_arg(args, int);
328 format_packet(p, n, vslp_printer, &bufinfo);
330 buflen = bufinfo.len - 1;
333 p = va_arg(args, unsigned char *);
334 for (n = prec; n > 0; --n) {
338 OUTCHAR(hexchars[(c >> 4) & 0xf]);
339 OUTCHAR(hexchars[c & 0xf]);
345 --fmt; /* so %z outputs %z etc. */
350 str = num + sizeof(num);
352 while (str > num + neg) {
353 *--str = hexchars[val % base];
355 if (--prec <= 0 && val == 0)
367 len = num + sizeof(num) - 1 - str;
370 if (prec >= 0 && len > prec)
376 if ((n = width - len) > 0) {
384 memcpy(buf, str, len);
393 * vslp_printer - used in processing a %P format
396 vslp_printer __V((void *arg, char *fmt, ...))
400 struct buffer_info *bi;
402 #if defined(__STDC__)
408 arg = va_arg(pvar, void *);
409 fmt = va_arg(pvar, char *);
412 bi = (struct buffer_info *) arg;
413 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
422 * log_packet - format a packet and log it.
426 log_packet(p, len, prefix, level)
432 init_pr_log(prefix, level);
433 format_packet(p, len, pr_log, &level);
439 * format_packet - make a readable representation of a packet,
440 * calling `printer(arg, format, ...)' to output it.
443 format_packet(p, len, printer, arg)
446 void (*printer) __P((void *, char *, ...));
451 struct protent *protp;
453 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
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);
489 * init_pr_log, end_pr_log - initialize and finish use of pr_log.
492 static char line[256]; /* line to be logged accumulated here */
493 static char *linep; /* current pointer within line */
494 static int llevel; /* level for logging */
497 init_pr_log(prefix, level)
502 if (prefix != NULL) {
503 strlcpy(line, prefix, sizeof(line));
504 linep = line + strlen(line);
514 log_write(llevel, line);
519 * pr_log - printer routine for outputting to syslog
522 pr_log __V((void *arg, char *fmt, ...))
529 #if defined(__STDC__)
535 arg = va_arg(pvar, void *);
536 fmt = va_arg(pvar, char *);
539 n = vslprintf(buf, sizeof(buf), fmt, pvar);
543 eol = strchr(buf, '\n');
545 l = (eol == NULL)? n: eol - buf;
546 if (linep + l < line + sizeof(line)) {
548 memcpy(linep, buf, l);
554 eol = strchr(p, '\n');
557 log_write(llevel, line);
561 while (eol != NULL) {
563 log_write(llevel, p);
565 eol = strchr(p, '\n');
568 /* assumes sizeof(buf) <= sizeof(line) */
577 * print_string - print a readable representation of a string using
581 print_string(p, len, printer, arg)
584 void (*printer) __P((void *, char *, ...));
590 for (; len > 0; --len) {
592 if (' ' <= c && c <= '~') {
593 if (c == '\\' || c == '"')
595 printer(arg, "%c", c);
608 printer(arg, "\\%.3o", c);
616 * logit - does the hard work for fatal et al.
619 logit(level, fmt, args)
629 n = vslprintf(buf, sizeof(buf), fmt, args);
630 log_write(level, buf);
634 log_write(level, buf)
638 syslog(level, "%s", buf);
639 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
642 if (n > 0 && buf[n-1] == '\n')
644 if (write(log_to_fd, buf, n) != n
645 || write(log_to_fd, "\n", 1) != 1)
651 * fatal - log an error message and die horribly.
654 fatal __V((char *fmt, ...))
658 #if defined(__STDC__)
663 fmt = va_arg(pvar, char *);
666 logit(LOG_ERR, fmt, pvar);
669 die(1); /* as promised */
673 * error - log an error message.
676 error __V((char *fmt, ...))
680 #if defined(__STDC__)
685 fmt = va_arg(pvar, char *);
688 logit(LOG_ERR, fmt, pvar);
693 * warn - log a warning message.
696 warn __V((char *fmt, ...))
700 #if defined(__STDC__)
705 fmt = va_arg(pvar, char *);
708 logit(LOG_WARNING, fmt, pvar);
713 * notice - log a notice-level message.
716 notice __V((char *fmt, ...))
720 #if defined(__STDC__)
725 fmt = va_arg(pvar, char *);
728 logit(LOG_NOTICE, fmt, pvar);
733 * info - log an informational message.
736 info __V((char *fmt, ...))
740 #if defined(__STDC__)
745 fmt = va_arg(pvar, char *);
748 logit(LOG_INFO, fmt, pvar);
753 * dbglog - log a debug message.
756 dbglog __V((char *fmt, ...))
760 #if defined(__STDC__)
765 fmt = va_arg(pvar, char *);
768 logit(LOG_DEBUG, fmt, pvar);
772 /* Procedures for locking the serial device using a lock file. */
775 #define LOCK_DIR "/var/lock"
778 #define LOCK_DIR "/var/spool/locks"
780 #define LOCK_DIR "/var/spool/lock"
783 #endif /* LOCK_DIR */
785 static char lock_file[MAXPATHLEN];
788 * lock - create a lock file for the named device
797 result = mklock (dev, (void *) 0);
799 strlcpy(lock_file, sizeof(lock_file), dev);
804 notice("Device %s is locked by pid %d", dev, result);
806 error("Can't create lock file %s", lock_file);
811 char lock_buffer[12];
817 if (stat(dev, &sbuf) < 0) {
818 error("Can't get device number for %s: %m", dev);
821 if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
822 error("Can't lock %s: not a character device", dev);
825 slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
826 LOCK_DIR, major(sbuf.st_dev),
827 major(sbuf.st_rdev), minor(sbuf.st_rdev));
831 if ((p = strrchr(dev, '/')) != NULL)
833 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 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 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 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 notice("Removed stale lock on %s (pid %d)", dev, pid);
875 warn("Couldn't remove stale lock on %s", dev);
877 notice("Device %s is locked by pid %d", dev, pid);
888 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 error("Couldn't reopen lock file %s: %m", lock_file);
930 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);
957 #define _PATH_ERRLOG "/etc/pppmsg"
958 #define _PATH_DIR "/proc/var/fyi/wan"
959 #define _PATH_MSG "daemonstatus"
960 #define _PATH_IP "ipaddress"
961 #define _PATH_MASK "subnetmask"
964 void create_msg(int lognumber)
969 if (strlen(session_path) > 0) {
970 sprintf(path, "%s/%s/%s", _PATH_DIR, session_path, _PATH_MSG);
971 f = fopen(path, "w");
974 f = fopen(_PATH_ERRLOG, "w");
976 error("Failed to create %s: %m", _PATH_ERRLOG);
980 fprintf(f, "%d", lognumber);
985 #define _PATH_INFO "sessinfo"
987 void save_session_info(unsigned char *remote_addr, int sid)
993 sprintf(oldsession, "%02x%02x%02x%02x%02x%02x/%04x", remote_addr[0], remote_addr[1], remote_addr[2],
994 remote_addr[3], remote_addr[4], remote_addr[5], sid);
997 sprintf(path, "%s/%s/%s", _PATH_DIR, session_path, _PATH_INFO);
998 f = fopen(path, "w");
1000 error("Failed to create %s: %m", _PATH_INFO);
1003 int tmp = fprintf(f, "%02x%02x%02x%02x%02x%02x/%04x",