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