]> git.ozlabs.org Git - ppp.git/blob - pppd/utils.c
Fix the rcsid's for non-ansi compilers
[ppp.git] / pppd / utils.c
1 /*
2  * utils.c - various utility functions used in pppd.
3  *
4  * Copyright (c) 1999 The Australian National University.
5  * All rights reserved.
6  *
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.
18  */
19
20 #define RCSID   "$Id: utils.c,v 1.8 1999/08/13 06:46:22 paulus Exp $"
21
22 #include <stdio.h>
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <netdb.h>
32 #include <utmp.h>
33 #include <pwd.h>
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #include <sys/time.h>
38 #include <sys/resource.h>
39 #include <sys/stat.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #ifdef SVR4
43 #include <sys/mkdev.h>
44 #endif
45
46 #include "pppd.h"
47
48 static const char rcsid[] = RCSID;
49
50 #if defined(SUNOS4)
51 extern char *strerror();
52 #endif
53
54 static void pr_log __P((void *, char *, ...));
55 static void logit __P((int, char *, va_list));
56 static void vslp_printer __P((void *, char *, ...));
57 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
58                                void *));
59
60 struct buffer_info {
61     char *ptr;
62     int len;
63 };
64
65 /*
66  * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
67  * always leaves destination null-terminated (for len > 0).
68  */
69 size_t
70 strlcpy(dest, src, len)
71     char *dest;
72     const char *src;
73     size_t len;
74 {
75     size_t ret = strlen(src);
76
77     if (len != 0) {
78         if (ret < len)
79             strcpy(dest, src);
80         else {
81             strncpy(dest, src, len - 1);
82             dest[len-1] = 0;
83         }
84     }
85     return ret;
86 }
87
88 /*
89  * strlcat - like strcat/strncat, doesn't overflow destination buffer,
90  * always leaves destination null-terminated (for len > 0).
91  */
92 size_t
93 strlcat(dest, src, len)
94     char *dest;
95     const char *src;
96     size_t len;
97 {
98     size_t dlen = strlen(dest);
99
100     return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
101 }
102
103
104 /*
105  * slprintf - format a message into a buffer.  Like sprintf except we
106  * also specify the length of the output buffer, and we handle
107  * %r (recursive format), %m (error message), %v (visible string),
108  * %q (quoted string), %t (current time) and %I (IP address) formats.
109  * Doesn't do floating-point formats.
110  * Returns the number of chars put into buf.
111  */
112 int
113 slprintf __V((char *buf, int buflen, char *fmt, ...))
114 {
115     va_list args;
116     int n;
117
118 #if __STDC__
119     va_start(args, fmt);
120 #else
121     char *buf;
122     int buflen;
123     char *fmt;
124     va_start(args);
125     buf = va_arg(args, char *);
126     buflen = va_arg(args, int);
127     fmt = va_arg(args, char *);
128 #endif
129     n = vslprintf(buf, buflen, fmt, args);
130     va_end(args);
131     return n;
132 }
133
134 /*
135  * vslprintf - like slprintf, takes a va_list instead of a list of args.
136  */
137 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
138
139 int
140 vslprintf(buf, buflen, fmt, args)
141     char *buf;
142     int buflen;
143     char *fmt;
144     va_list args;
145 {
146     int c, i, n;
147     int width, prec, fillch;
148     int base, len, neg, quoted;
149     unsigned long val = 0;
150     char *str, *f, *buf0;
151     unsigned char *p;
152     char num[32];
153     time_t t;
154     u_int32_t ip;
155     static char hexchars[] = "0123456789abcdef";
156     struct buffer_info bufinfo;
157
158     buf0 = buf;
159     --buflen;
160     while (buflen > 0) {
161         for (f = fmt; *f != '%' && *f != 0; ++f)
162             ;
163         if (f > fmt) {
164             len = f - fmt;
165             if (len > buflen)
166                 len = buflen;
167             memcpy(buf, fmt, len);
168             buf += len;
169             buflen -= len;
170             fmt = f;
171         }
172         if (*fmt == 0)
173             break;
174         c = *++fmt;
175         width = 0;
176         prec = -1;
177         fillch = ' ';
178         if (c == '0') {
179             fillch = '0';
180             c = *++fmt;
181         }
182         if (c == '*') {
183             width = va_arg(args, int);
184             c = *++fmt;
185         } else {
186             while (isdigit(c)) {
187                 width = width * 10 + c - '0';
188                 c = *++fmt;
189             }
190         }
191         if (c == '.') {
192             c = *++fmt;
193             if (c == '*') {
194                 prec = va_arg(args, int);
195                 c = *++fmt;
196             } else {
197                 prec = 0;
198                 while (isdigit(c)) {
199                     prec = prec * 10 + c - '0';
200                     c = *++fmt;
201                 }
202             }
203         }
204         str = 0;
205         base = 0;
206         neg = 0;
207         ++fmt;
208         switch (c) {
209         case 'd':
210             i = va_arg(args, int);
211             if (i < 0) {
212                 neg = 1;
213                 val = -i;
214             } else
215                 val = i;
216             base = 10;
217             break;
218         case 'o':
219             val = va_arg(args, unsigned int);
220             base = 8;
221             break;
222         case 'x':
223         case 'X':
224             val = va_arg(args, unsigned int);
225             base = 16;
226             break;
227         case 'p':
228             val = (unsigned long) va_arg(args, void *);
229             base = 16;
230             neg = 2;
231             break;
232         case 's':
233             str = va_arg(args, char *);
234             break;
235         case 'c':
236             num[0] = va_arg(args, int);
237             num[1] = 0;
238             str = num;
239             break;
240         case 'm':
241             str = strerror(errno);
242             break;
243         case 'I':
244             ip = va_arg(args, u_int32_t);
245             ip = ntohl(ip);
246             slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
247                      (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
248             str = num;
249             break;
250         case 'r':
251             f = va_arg(args, char *);
252 #ifndef __powerpc__
253             n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
254 #else
255             /* On the powerpc, a va_list is an array of 1 structure */
256             n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
257 #endif
258             buf += n;
259             buflen -= n;
260             continue;
261         case 't':
262             time(&t);
263             str = ctime(&t);
264             str += 4;           /* chop off the day name */
265             str[15] = 0;        /* chop off year and newline */
266             break;
267         case 'v':               /* "visible" string */
268         case 'q':               /* quoted string */
269             quoted = c == 'q';
270             p = va_arg(args, unsigned char *);
271             if (fillch == '0' && prec >= 0) {
272                 n = prec;
273             } else {
274                 n = strlen((char *)p);
275                 if (prec >= 0 && n > prec)
276                     n = prec;
277             }
278             while (n > 0 && buflen > 0) {
279                 c = *p++;
280                 --n;
281                 if (!quoted && c >= 0x80) {
282                     OUTCHAR('M');
283                     OUTCHAR('-');
284                     c -= 0x80;
285                 }
286                 if (quoted && (c == '"' || c == '\\'))
287                     OUTCHAR('\\');
288                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
289                     if (quoted) {
290                         OUTCHAR('\\');
291                         switch (c) {
292                         case '\t':      OUTCHAR('t');   break;
293                         case '\n':      OUTCHAR('n');   break;
294                         case '\b':      OUTCHAR('b');   break;
295                         case '\f':      OUTCHAR('f');   break;
296                         default:
297                             OUTCHAR('x');
298                             OUTCHAR(hexchars[c >> 4]);
299                             OUTCHAR(hexchars[c & 0xf]);
300                         }
301                     } else {
302                         if (c == '\t')
303                             OUTCHAR(c);
304                         else {
305                             OUTCHAR('^');
306                             OUTCHAR(c ^ 0x40);
307                         }
308                     }
309                 } else
310                     OUTCHAR(c);
311             }
312             continue;
313         case 'P':               /* print PPP packet */
314             bufinfo.ptr = buf;
315             bufinfo.len = buflen + 1;
316             p = va_arg(args, unsigned char *);
317             n = va_arg(args, int);
318             format_packet(p, n, vslp_printer, &bufinfo);
319             buf = bufinfo.ptr;
320             buflen = bufinfo.len - 1;
321             continue;
322         case 'B':
323             p = va_arg(args, unsigned char *);
324             for (n = prec; n > 0; --n) {
325                 c = *p++;
326                 if (fillch == ' ')
327                     OUTCHAR(' ');
328                 OUTCHAR(hexchars[(c >> 4) & 0xf]);
329                 OUTCHAR(hexchars[c & 0xf]);
330             }
331             continue;
332         default:
333             *buf++ = '%';
334             if (c != '%')
335                 --fmt;          /* so %z outputs %z etc. */
336             --buflen;
337             continue;
338         }
339         if (base != 0) {
340             str = num + sizeof(num);
341             *--str = 0;
342             while (str > num + neg) {
343                 *--str = hexchars[val % base];
344                 val = val / base;
345                 if (--prec <= 0 && val == 0)
346                     break;
347             }
348             switch (neg) {
349             case 1:
350                 *--str = '-';
351                 break;
352             case 2:
353                 *--str = 'x';
354                 *--str = '0';
355                 break;
356             }
357             len = num + sizeof(num) - 1 - str;
358         } else {
359             len = strlen(str);
360             if (prec >= 0 && len > prec)
361                 len = prec;
362         }
363         if (width > 0) {
364             if (width > buflen)
365                 width = buflen;
366             if ((n = width - len) > 0) {
367                 buflen -= n;
368                 for (; n > 0; --n)
369                     *buf++ = fillch;
370             }
371         }
372         if (len > buflen)
373             len = buflen;
374         memcpy(buf, str, len);
375         buf += len;
376         buflen -= len;
377     }
378     *buf = 0;
379     return buf - buf0;
380 }
381
382 /*
383  * vslp_printer - used in processing a %P format
384  */
385 static void
386 vslp_printer __V((void *arg, char *fmt, ...))
387 {
388     int n;
389     va_list pvar;
390     struct buffer_info *bi;
391
392 #if __STDC__
393     va_start(pvar, fmt);
394 #else
395     void *arg;
396     char *fmt;
397     va_start(pvar);
398     arg = va_arg(pvar, void *);
399     fmt = va_arg(pvar, char *);
400 #endif
401
402     bi = (struct buffer_info *) arg;
403     n = vslprintf(bi->ptr, bi->len, fmt, pvar);
404     va_end(pvar);
405
406     bi->ptr += n;
407     bi->len -= n;
408 }
409
410 /*
411  * log_packet - format a packet and log it.
412  */
413
414 char line[256];                 /* line to be logged accumulated here */
415 char *linep;
416
417 void
418 log_packet(p, len, prefix, level)
419     u_char *p;
420     int len;
421     char *prefix;
422     int level;
423 {
424     strlcpy(line, prefix, sizeof(line));
425     linep = line + strlen(line);
426     format_packet(p, len, pr_log, NULL);
427     if (linep != line)
428         syslog(level, "%s", line);
429 }
430
431 /*
432  * format_packet - make a readable representation of a packet,
433  * calling `printer(arg, format, ...)' to output it.
434  */
435 static void
436 format_packet(p, len, printer, arg)
437     u_char *p;
438     int len;
439     void (*printer) __P((void *, char *, ...));
440     void *arg;
441 {
442     int i, n;
443     u_short proto;
444     struct protent *protp;
445
446     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
447         p += 2;
448         GETSHORT(proto, p);
449         len -= PPP_HDRLEN;
450         for (i = 0; (protp = protocols[i]) != NULL; ++i)
451             if (proto == protp->protocol)
452                 break;
453         if (protp != NULL) {
454             printer(arg, "[%s", protp->name);
455             n = (*protp->printpkt)(p, len, printer, arg);
456             printer(arg, "]");
457             p += n;
458             len -= n;
459         } else {
460             for (i = 0; (protp = protocols[i]) != NULL; ++i)
461                 if (proto == (protp->protocol & ~0x8000))
462                     break;
463             if (protp != 0 && protp->data_name != 0) {
464                 printer(arg, "[%s data]", protp->data_name);
465                 if (len > 8)
466                     printer(arg, "%.8B ...", p);
467                 else
468                     printer(arg, "%.*B", len, p);
469                 len = 0;
470             } else
471                 printer(arg, "[proto=0x%x]", proto);
472         }
473     }
474
475     if (len > 32)
476         printer(arg, "%.32B ...", p);
477     else
478         printer(arg, "%.*B", len, p);
479 }
480
481 static void
482 pr_log __V((void *arg, char *fmt, ...))
483 {
484     int n;
485     va_list pvar;
486     char buf[256];
487
488 #if __STDC__
489     va_start(pvar, fmt);
490 #else
491     void *arg;
492     char *fmt;
493     va_start(pvar);
494     arg = va_arg(pvar, void *);
495     fmt = va_arg(pvar, char *);
496 #endif
497
498     n = vslprintf(buf, sizeof(buf), fmt, pvar);
499     va_end(pvar);
500
501     if (linep + n + 1 > line + sizeof(line)) {
502         syslog(LOG_DEBUG, "%s", line);
503         linep = line;
504     }
505     strlcpy(linep, buf, line + sizeof(line) - linep);
506     linep += n;
507 }
508
509 /*
510  * print_string - print a readable representation of a string using
511  * printer.
512  */
513 void
514 print_string(p, len, printer, arg)
515     char *p;
516     int len;
517     void (*printer) __P((void *, char *, ...));
518     void *arg;
519 {
520     int c;
521
522     printer(arg, "\"");
523     for (; len > 0; --len) {
524         c = *p++;
525         if (' ' <= c && c <= '~') {
526             if (c == '\\' || c == '"')
527                 printer(arg, "\\");
528             printer(arg, "%c", c);
529         } else {
530             switch (c) {
531             case '\n':
532                 printer(arg, "\\n");
533                 break;
534             case '\r':
535                 printer(arg, "\\r");
536                 break;
537             case '\t':
538                 printer(arg, "\\t");
539                 break;
540             default:
541                 printer(arg, "\\%.3o", c);
542             }
543         }
544     }
545     printer(arg, "\"");
546 }
547
548 /*
549  * logit - does the hard work for fatal et al.
550  */
551 static void
552 logit(level, fmt, args)
553     int level;
554     char *fmt;
555     va_list args;
556 {
557     int n;
558     char buf[256];
559
560     n = vslprintf(buf, sizeof(buf), fmt, args);
561     syslog(level, "%s", buf);
562     if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
563         if (buf[n-1] != '\n')
564             buf[n++] = '\n';
565         if (write(log_to_fd, buf, n) != n)
566             log_to_fd = -1;
567     }
568 }
569
570 /*
571  * fatal - log an error message and die horribly.
572  */
573 void
574 fatal __V((char *fmt, ...))
575 {
576     va_list pvar;
577
578 #if __STDC__
579     va_start(pvar, fmt);
580 #else
581     char *fmt;
582     va_start(pvar);
583     fmt = va_arg(pvar, char *);
584 #endif
585
586     logit(LOG_ERR, fmt, pvar);
587     va_end(pvar);
588
589     die(1);                     /* as promised */
590 }
591
592 /*
593  * error - log an error message.
594  */
595 void
596 error __V((char *fmt, ...))
597 {
598     va_list pvar;
599
600 #if __STDC__
601     va_start(pvar, fmt);
602 #else
603     char *fmt;
604     va_start(pvar);
605     fmt = va_arg(pvar, char *);
606 #endif
607
608     logit(LOG_ERR, fmt, pvar);
609     va_end(pvar);
610 }
611
612 /*
613  * warn - log a warning message.
614  */
615 void
616 warn __V((char *fmt, ...))
617 {
618     va_list pvar;
619
620 #if __STDC__
621     va_start(pvar, fmt);
622 #else
623     char *fmt;
624     va_start(pvar);
625     fmt = va_arg(pvar, char *);
626 #endif
627
628     logit(LOG_WARNING, fmt, pvar);
629     va_end(pvar);
630 }
631
632 /*
633  * notice - log a notice-level message.
634  */
635 void
636 notice __V((char *fmt, ...))
637 {
638     va_list pvar;
639
640 #if __STDC__
641     va_start(pvar, fmt);
642 #else
643     char *fmt;
644     va_start(pvar);
645     fmt = va_arg(pvar, char *);
646 #endif
647
648     logit(LOG_NOTICE, fmt, pvar);
649     va_end(pvar);
650 }
651
652 /*
653  * info - log an informational message.
654  */
655 void
656 info __V((char *fmt, ...))
657 {
658     va_list pvar;
659
660 #if __STDC__
661     va_start(pvar, fmt);
662 #else
663     char *fmt;
664     va_start(pvar);
665     fmt = va_arg(pvar, char *);
666 #endif
667
668     logit(LOG_INFO, fmt, pvar);
669     va_end(pvar);
670 }
671
672 /*
673  * dbglog - log a debug message.
674  */
675 void
676 dbglog __V((char *fmt, ...))
677 {
678     va_list pvar;
679
680 #if __STDC__
681     va_start(pvar, fmt);
682 #else
683     char *fmt;
684     va_start(pvar);
685     fmt = va_arg(pvar, char *);
686 #endif
687
688     logit(LOG_DEBUG, fmt, pvar);
689     va_end(pvar);
690 }
691
692 /* Procedures for locking the serial device using a lock file. */
693 #ifndef LOCK_DIR
694 #ifdef _linux_
695 #define LOCK_DIR        "/var/lock"
696 #else
697 #ifdef SVR4
698 #define LOCK_DIR        "/var/spool/locks"
699 #else
700 #define LOCK_DIR        "/var/spool/lock"
701 #endif
702 #endif
703 #endif /* LOCK_DIR */
704
705 static char lock_file[MAXPATHLEN];
706
707 /*
708  * lock - create a lock file for the named device
709  */
710 int
711 lock(dev)
712     char *dev;
713 {
714 #ifdef LOCKLIB
715     int result;
716
717     result = mklock (dev, (void *) 0);
718     if (result == 0) {
719         strlcpy(lock_file, sizeof(lock_file), dev);
720         return 0;
721     }
722
723     if (result > 0)
724         notice("Device %s is locked by pid %d", dev, result);
725     else
726         error("Can't create lock file %s", lock_file);
727     return -1;
728
729 #else /* LOCKLIB */
730
731     char lock_buffer[12];
732     int fd, pid, n;
733
734 #ifdef SVR4
735     struct stat sbuf;
736
737     if (stat(dev, &sbuf) < 0) {
738         error("Can't get device number for %s: %m", dev);
739         return -1;
740     }
741     if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
742         error("Can't lock %s: not a character device", dev);
743         return -1;
744     }
745     slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
746              LOCK_DIR, major(sbuf.st_dev),
747              major(sbuf.st_rdev), minor(sbuf.st_rdev));
748 #else
749     char *p;
750
751     if ((p = strrchr(dev, '/')) != NULL)
752         dev = p + 1;
753     slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
754 #endif
755
756     while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
757         if (errno != EEXIST) {
758             error("Can't create lock file %s: %m", lock_file);
759             break;
760         }
761
762         /* Read the lock file to find out who has the device locked. */
763         fd = open(lock_file, O_RDONLY, 0);
764         if (fd < 0) {
765             if (errno == ENOENT) /* This is just a timing problem. */
766                 continue;
767             error("Can't open existing lock file %s: %m", lock_file);
768             break;
769         }
770 #ifndef LOCK_BINARY
771         n = read(fd, lock_buffer, 11);
772 #else
773         n = read(fd, &pid, sizeof(pid));
774 #endif /* LOCK_BINARY */
775         close(fd);
776         fd = -1;
777         if (n <= 0) {
778             error("Can't read pid from lock file %s", lock_file);
779             break;
780         }
781
782         /* See if the process still exists. */
783 #ifndef LOCK_BINARY
784         lock_buffer[n] = 0;
785         pid = atoi(lock_buffer);
786 #endif /* LOCK_BINARY */
787         if (pid == getpid())
788             return 1;           /* somebody else locked it for us */
789         if (pid == 0
790             || (kill(pid, 0) == -1 && errno == ESRCH)) {
791             if (unlink (lock_file) == 0) {
792                 notice("Removed stale lock on %s (pid %d)", dev, pid);
793                 continue;
794             }
795             warn("Couldn't remove stale lock on %s", dev);
796         } else
797             notice("Device %s is locked by pid %d", dev, pid);
798         break;
799     }
800
801     if (fd < 0) {
802         lock_file[0] = 0;
803         return -1;
804     }
805
806     pid = getpid();
807 #ifndef LOCK_BINARY
808     slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
809     write (fd, lock_buffer, 11);
810 #else
811     write(fd, &pid, sizeof (pid));
812 #endif
813     close(fd);
814     return 0;
815
816 #endif
817 }
818
819 /*
820  * relock - called to update our lockfile when we are about to detach,
821  * thus changing our pid (we fork, the child carries on, and the parent dies).
822  * Note that this is called by the parent, with pid equal to the pid
823  * of the child.  This avoids a potential race which would exist if
824  * we had the child rewrite the lockfile (the parent might die first,
825  * and another process could think the lock was stale if it checked
826  * between when the parent died and the child rewrote the lockfile).
827  */
828 int
829 relock(pid)
830     int pid;
831 {
832 #ifdef LOCKLIB
833     /* XXX is there a way to do this? */
834     return -1;
835 #else /* LOCKLIB */
836
837     int fd;
838     char lock_buffer[12];
839
840     if (lock_file[0] == 0)
841         return -1;
842     fd = open(lock_file, O_WRONLY, 0);
843     if (fd < 0) {
844         error("Couldn't reopen lock file %s: %m", lock_file);
845         lock_file[0] = 0;
846         return -1;
847     }
848
849 #ifndef LOCK_BINARY
850     slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
851     write (fd, lock_buffer, 11);
852 #else
853     write(fd, &pid, sizeof(pid));
854 #endif /* LOCK_BINARY */
855     close(fd);
856     return 0;
857
858 #endif /* LOCKLIB */
859 }
860
861 /*
862  * unlock - remove our lockfile
863  */
864 void
865 unlock()
866 {
867     if (lock_file[0]) {
868 #ifdef LOCKLIB
869         (void) rmlock(lock_file, (void *) 0);
870 #else
871         unlink(lock_file);
872 #endif
873         lock_file[0] = 0;
874     }
875 }
876