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