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