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