]> git.ozlabs.org Git - ppp.git/blob - pppd/utils.c
Makefile.am: Add explicit openssl directory to pppd include path
[ppp.git] / pppd / utils.c
1 /*
2  * utils.c - various utility functions used in pppd.
3  *
4  * Copyright (c) 1999-2002 Paul Mackerras. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. The name(s) of the authors of this software must not be used to
14  *    endorse or promote products derived from this software without
15  *    prior written permission.
16  *
17  * 3. Redistributions of any form whatsoever must retain the following
18  *    acknowledgment:
19  *    "This product includes software developed by Paul Mackerras
20  *     <paulus@ozlabs.org>".
21  *
22  * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
23  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
24  * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
25  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
27  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
28  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <ctype.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <signal.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <syslog.h>
45 #include <netdb.h>
46 #include <time.h>
47 #include <utmp.h>
48 #include <pwd.h>
49 #include <sys/param.h>
50 #include <sys/types.h>
51 #include <sys/wait.h>
52 #include <sys/time.h>
53 #include <sys/resource.h>
54 #include <sys/stat.h>
55 #include <sys/socket.h>
56 #include <netinet/in.h>
57 #ifdef SVR4
58 #include <sys/mkdev.h>
59 #endif
60
61 #include "pppd-private.h"
62 #include "fsm.h"
63 #include "lcp.h"
64 #include "pathnames.h"
65
66
67 #if defined(SUNOS4)
68 extern char *strerror();
69 #endif
70
71 static void logit(int, const char *, va_list);
72 static void log_write(int, char *);
73 static void vslp_printer(void *, char *, ...);
74 static void format_packet(u_char *, int, printer_func, void *);
75
76 struct buffer_info {
77     char *ptr;
78     int len;
79 };
80
81 /*
82  * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
83  * always leaves destination null-terminated (for len > 0).
84  */
85 size_t
86 strlcpy(char *dest, const char *src, size_t len)
87 {
88     size_t ret = strlen(src);
89
90     if (len != 0) {
91         if (ret < len)
92             strcpy(dest, src);
93         else {
94             strncpy(dest, src, len - 1);
95             dest[len-1] = 0;
96         }
97     }
98     return ret;
99 }
100
101 /*
102  * strlcat - like strcat/strncat, doesn't overflow destination buffer,
103  * always leaves destination null-terminated (for len > 0).
104  */
105 size_t
106 strlcat(char *dest, const char *src, size_t len)
107 {
108     size_t dlen = strlen(dest);
109
110     return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
111 }
112
113
114 /*
115  * slprintf - format a message into a buffer.  Like sprintf except we
116  * also specify the length of the output buffer, and we handle
117  * %m (error message), %v (visible string),
118  * %q (quoted string), %t (current time) and %I (IP address) formats.
119  * Doesn't do floating-point formats.
120  * Returns the number of chars put into buf.
121  */
122 int
123 slprintf(char *buf, int buflen, const char *fmt, ...)
124 {
125     va_list args;
126     int n;
127
128     va_start(args, fmt);
129     n = vslprintf(buf, buflen, fmt, args);
130     va_end(args);
131     return n;
132 }
133
134 /*
135  * vslprintf - like slprintf, takes a va_list instead of a list of args.
136  */
137 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
138
139 int
140 vslprintf(char *buf, int buflen, const char *fmt, va_list args)
141 {
142     int c, i, n;
143     int width, prec, fillch;
144     int base, len, neg, quoted;
145     long lval = 0;
146     unsigned long val = 0;
147     char *str, *buf0;
148     const char *f;
149     unsigned char *p;
150     char num[32];
151     time_t t;
152     u_int32_t ip;
153     static char hexchars[] = "0123456789abcdef";
154     struct buffer_info bufinfo;
155     int termch;
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 'l':
209             c = *fmt++;
210             switch (c) {
211             case 'd':
212                 lval = va_arg(args, long);
213                 if (lval < 0) {
214                     neg = 1;
215                     val = -lval;
216                 } else
217                     val = lval;
218                 base = 10;
219                 break;
220             case 'u':
221                 val = va_arg(args, unsigned long);
222                 base = 10;
223                 break;
224             default:
225                 OUTCHAR('%');
226                 OUTCHAR('l');
227                 --fmt;          /* so %lz outputs %lz etc. */
228                 continue;
229             }
230             break;
231         case 'd':
232             i = va_arg(args, int);
233             if (i < 0) {
234                 neg = 1;
235                 val = -i;
236             } else
237                 val = i;
238             base = 10;
239             break;
240         case 'u':
241             val = va_arg(args, unsigned int);
242             base = 10;
243             break;
244         case 'o':
245             val = va_arg(args, unsigned int);
246             base = 8;
247             break;
248         case 'x':
249         case 'X':
250             val = va_arg(args, unsigned int);
251             base = 16;
252             break;
253         case 'p':
254             val = (unsigned long) va_arg(args, void *);
255             base = 16;
256             neg = 2;
257             break;
258         case 's':
259             str = va_arg(args, char *);
260             break;
261         case 'c':
262             num[0] = va_arg(args, int);
263             num[1] = 0;
264             str = num;
265             break;
266         case 'm':
267             str = strerror(errno);
268             break;
269         case 'I':
270             ip = va_arg(args, u_int32_t);
271             ip = ntohl(ip);
272             slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
273                      (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
274             str = num;
275             break;
276         case 't':
277             time(&t);
278             str = ctime(&t);
279             str += 4;           /* chop off the day name */
280             str[15] = 0;        /* chop off year and newline */
281             break;
282         case 'v':               /* "visible" string */
283         case 'q':               /* quoted string */
284             quoted = c == 'q';
285             p = va_arg(args, unsigned char *);
286             if (p == NULL)
287                     p = (unsigned char *)"<NULL>";
288             if (fillch == '0' && prec >= 0) {
289                 n = prec;
290                 termch = -1;    /* matches no unsigned char value */
291             } else {
292                 n = buflen;
293                 if (prec != -1 && n > prec)
294                     n = prec;
295                 termch = 0;     /* stop on null byte */
296             }
297             while (n > 0 && buflen > 0) {
298                 c = *p++;
299                 if (c == termch)
300                     break;
301                 --n;
302                 if (!quoted && c >= 0x80) {
303                     OUTCHAR('M');
304                     OUTCHAR('-');
305                     c -= 0x80;
306                 }
307                 if (quoted && (c == '"' || c == '\\'))
308                     OUTCHAR('\\');
309                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
310                     if (quoted) {
311                         OUTCHAR('\\');
312                         switch (c) {
313                         case '\t':      OUTCHAR('t');   break;
314                         case '\n':      OUTCHAR('n');   break;
315                         case '\b':      OUTCHAR('b');   break;
316                         case '\f':      OUTCHAR('f');   break;
317                         default:
318                             OUTCHAR('x');
319                             OUTCHAR(hexchars[c >> 4]);
320                             OUTCHAR(hexchars[c & 0xf]);
321                         }
322                     } else {
323                         if (c == '\t')
324                             OUTCHAR(c);
325                         else {
326                             OUTCHAR('^');
327                             OUTCHAR(c ^ 0x40);
328                         }
329                     }
330                 } else
331                     OUTCHAR(c);
332             }
333             continue;
334 #ifndef UNIT_TEST
335         case 'P':               /* print PPP packet */
336             bufinfo.ptr = buf;
337             bufinfo.len = buflen + 1;
338             p = va_arg(args, unsigned char *);
339             n = va_arg(args, int);
340             format_packet(p, n, vslp_printer, &bufinfo);
341             buf = bufinfo.ptr;
342             buflen = bufinfo.len - 1;
343             continue;
344 #endif
345         case 'B':
346             p = va_arg(args, unsigned char *);
347             for (n = prec; n > 0; --n) {
348                 c = *p++;
349                 if (fillch == ' ')
350                     OUTCHAR(' ');
351                 OUTCHAR(hexchars[(c >> 4) & 0xf]);
352                 OUTCHAR(hexchars[c & 0xf]);
353             }
354             continue;
355         default:
356             *buf++ = '%';
357             if (c != '%')
358                 --fmt;          /* so %z outputs %z etc. */
359             --buflen;
360             continue;
361         }
362         if (base != 0) {
363             str = num + sizeof(num);
364             *--str = 0;
365             while (str > num + neg) {
366                 *--str = hexchars[val % base];
367                 val = val / base;
368                 if (--prec <= 0 && val == 0)
369                     break;
370             }
371             switch (neg) {
372             case 1:
373                 *--str = '-';
374                 break;
375             case 2:
376                 *--str = 'x';
377                 *--str = '0';
378                 break;
379             }
380             len = num + sizeof(num) - 1 - str;
381         } else {
382             for (len = 0; len < buflen && (prec == -1 || len < prec); ++len)
383                 if (str[len] == 0)
384                     break;
385         }
386         if (width > 0) {
387             if (width > buflen)
388                 width = buflen;
389             if ((n = width - len) > 0) {
390                 buflen -= n;
391                 for (; n > 0; --n)
392                     *buf++ = fillch;
393             }
394         }
395         if (len > buflen)
396             len = buflen;
397         memcpy(buf, str, len);
398         buf += len;
399         buflen -= len;
400     }
401     *buf = 0;
402     return buf - buf0;
403 }
404
405 /*
406  * vslp_printer - used in processing a %P format
407  */
408 static void
409 vslp_printer(void *arg, char *fmt, ...)
410 {
411     int n;
412     va_list pvar;
413     struct buffer_info *bi;
414
415     va_start(pvar, fmt);
416
417     bi = (struct buffer_info *) arg;
418     n = vslprintf(bi->ptr, bi->len, fmt, pvar);
419     va_end(pvar);
420
421     bi->ptr += n;
422     bi->len -= n;
423 }
424
425 #ifdef unused
426 /*
427  * log_packet - format a packet and log it.
428  */
429
430 void
431 log_packet(u_char *p, int len, char *prefix, int level)
432 {
433         init_pr_log(prefix, level);
434         format_packet(p, len, pr_log, &level);
435         end_pr_log();
436 }
437 #endif /* unused */
438
439 #ifndef UNIT_TEST
440 /*
441  * format_packet - make a readable representation of a packet,
442  * calling `printer(arg, format, ...)' to output it.
443  */
444 static void
445 format_packet(u_char *p, int len, printer_func printer, void *arg)
446 {
447     int i, n;
448     u_short proto;
449     struct protent *protp;
450
451     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
452         p += 2;
453         GETSHORT(proto, p);
454         len -= PPP_HDRLEN;
455         for (i = 0; (protp = protocols[i]) != NULL; ++i)
456             if (proto == protp->protocol)
457                 break;
458         if (protp != NULL) {
459             printer(arg, "[%s", protp->name);
460             n = (*protp->printpkt)(p, len, printer, arg);
461             printer(arg, "]");
462             p += n;
463             len -= n;
464         } else {
465             for (i = 0; (protp = protocols[i]) != NULL; ++i)
466                 if (proto == (protp->protocol & ~0x8000))
467                     break;
468             if (protp != 0 && protp->data_name != 0) {
469                 printer(arg, "[%s data]", protp->data_name);
470                 if (len > 8)
471                     printer(arg, "%.8B ...", p);
472                 else
473                     printer(arg, "%.*B", len, p);
474                 len = 0;
475             } else
476                 printer(arg, "[proto=0x%x]", proto);
477         }
478     }
479
480     if (len > 32)
481         printer(arg, "%.32B ...", p);
482     else
483         printer(arg, "%.*B", len, p);
484 }
485 #endif  /* UNIT_TEST */
486
487 /*
488  * init_pr_log, end_pr_log - initialize and finish use of pr_log.
489  */
490
491 static char line[256];          /* line to be logged accumulated here */
492 static char *linep;             /* current pointer within line */
493 static int llevel;              /* level for logging */
494
495 void
496 init_pr_log(const char *prefix, int level)
497 {
498         linep = line;
499         if (prefix != NULL) {
500                 strlcpy(line, prefix, sizeof(line));
501                 linep = line + strlen(line);
502         }
503         llevel = level;
504 }
505
506 void
507 end_pr_log(void)
508 {
509         if (linep != line) {
510                 *linep = 0;
511                 log_write(llevel, line);
512         }
513 }
514
515 /*
516  * pr_log - printer routine for outputting to syslog
517  */
518 void
519 pr_log(void *arg, char *fmt, ...)
520 {
521         int l, n;
522         va_list pvar;
523         char *p, *eol;
524         char buf[256];
525
526         va_start(pvar, fmt);
527
528         n = vslprintf(buf, sizeof(buf), fmt, pvar);
529         va_end(pvar);
530
531         p = buf;
532         eol = strchr(buf, '\n');
533         if (linep != line) {
534                 l = (eol == NULL)? n: eol - buf;
535                 if (linep + l < line + sizeof(line)) {
536                         if (l > 0) {
537                                 memcpy(linep, buf, l);
538                                 linep += l;
539                         }
540                         if (eol == NULL)
541                                 return;
542                         p = eol + 1;
543                         eol = strchr(p, '\n');
544                 }
545                 *linep = 0;
546                 log_write(llevel, line);
547                 linep = line;
548         }
549
550         while (eol != NULL) {
551                 *eol = 0;
552                 log_write(llevel, p);
553                 p = eol + 1;
554                 eol = strchr(p, '\n');
555         }
556
557         /* assumes sizeof(buf) <= sizeof(line) */
558         l = buf + n - p;
559         if (l > 0) {
560                 memcpy(line, p, n);
561                 linep = line + l;
562         }
563 }
564
565 /*
566  * print_string - print a readable representation of a string using
567  * printer.
568  */
569 void
570 print_string(char *p, int len, printer_func printer, void *arg)
571 {
572     int c;
573
574     printer(arg, "\"");
575     for (; len > 0; --len) {
576         c = *p++;
577         if (' ' <= c && c <= '~') {
578             if (c == '\\' || c == '"')
579                 printer(arg, "\\");
580             printer(arg, "%c", c);
581         } else {
582             switch (c) {
583             case '\n':
584                 printer(arg, "\\n");
585                 break;
586             case '\r':
587                 printer(arg, "\\r");
588                 break;
589             case '\t':
590                 printer(arg, "\\t");
591                 break;
592             default:
593                 printer(arg, "\\%.3o", (unsigned char) c);
594             }
595         }
596     }
597     printer(arg, "\"");
598 }
599
600 /*
601  * logit - does the hard work for fatal et al.
602  */
603 static void
604 logit(int level, const char *fmt, va_list args)
605 {
606     char buf[1024];
607
608     vslprintf(buf, sizeof(buf), fmt, args);
609     log_write(level, buf);
610 }
611
612 #ifndef UNIT_TEST
613 static void
614 log_write(int level, char *buf)
615 {
616     syslog(level, "%s", buf);
617     if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
618         int n = strlen(buf);
619
620         if (n > 0 && buf[n-1] == '\n')
621             --n;
622         if (write(log_to_fd, buf, n) != n
623             || write(log_to_fd, "\n", 1) != 1)
624             log_to_fd = -1;
625     }
626 }
627 #else
628 static void
629 log_write(int level, char *buf)
630 {
631     printf("<%d>: %s\n", level, buf);
632 }
633 #endif
634
635 /*
636  * fatal - log an error message and die horribly.
637  */
638 void
639 fatal(const char *fmt, ...)
640 {
641     va_list pvar;
642
643     va_start(pvar, fmt);
644
645     logit(LOG_ERR, fmt, pvar);
646     va_end(pvar);
647
648 #ifndef UNIT_TEST
649     die(1);                     /* as promised */
650 #else
651     exit(-1);
652 #endif
653 }
654
655 /*
656  * error - log an error message.
657  */
658 void
659 error(const char *fmt, ...)
660 {
661     va_list pvar;
662
663     va_start(pvar, fmt);
664
665     logit(LOG_ERR, fmt, pvar);
666     va_end(pvar);
667     ++error_count;
668 }
669
670 /*
671  * warn - log a warning message.
672  */
673 void
674 warn(const char *fmt, ...)
675 {
676     va_list pvar;
677
678     va_start(pvar, fmt);
679
680     logit(LOG_WARNING, fmt, pvar);
681     va_end(pvar);
682 }
683
684 /*
685  * notice - log a notice-level message.
686  */
687 void
688 notice(const char *fmt, ...)
689 {
690     va_list pvar;
691
692     va_start(pvar, fmt);
693
694     logit(LOG_NOTICE, fmt, pvar);
695     va_end(pvar);
696 }
697
698 /*
699  * info - log an informational message.
700  */
701 void
702 info(const char *fmt, ...)
703 {
704     va_list pvar;
705
706     va_start(pvar, fmt);
707
708     logit(LOG_INFO, fmt, pvar);
709     va_end(pvar);
710 }
711
712 /*
713  * dbglog - log a debug message.
714  */
715 void
716 dbglog(const char *fmt, ...)
717 {
718     va_list pvar;
719
720     va_start(pvar, fmt);
721
722     logit(LOG_DEBUG, fmt, pvar);
723     va_end(pvar);
724 }
725
726 /*
727  * dump_packet - print out a packet in readable form if it is interesting.
728  * Assumes len >= PPP_HDRLEN.
729  */
730 void
731 dump_packet(const char *tag, unsigned char *p, int len)
732 {
733     int proto;
734
735     if (!debug)
736         return;
737
738     /*
739      * don't print LCP echo request/reply packets if debug <= 1
740      * and the link is up.
741      */
742     proto = (p[2] << 8) + p[3];
743     if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
744         && len >= PPP_HDRLEN + HEADERLEN) {
745         unsigned char *lcp = p + PPP_HDRLEN;
746         int l = (lcp[2] << 8) + lcp[3];
747
748         if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
749             && l >= HEADERLEN && l <= len - PPP_HDRLEN)
750             return;
751     }
752
753     dbglog("%s %P", tag, p, len);
754 }
755
756
757 #ifndef UNIT_TEST
758 /*
759  * complete_read - read a full `count' bytes from fd,
760  * unless end-of-file or an error other than EINTR is encountered.
761  */
762 ssize_t
763 complete_read(int fd, void *buf, size_t count)
764 {
765         size_t done;
766         ssize_t nb;
767         char *ptr = buf;
768
769         for (done = 0; done < count; ) {
770                 nb = read(fd, ptr, count - done);
771                 if (nb < 0) {
772                         if (errno == EINTR && !ppp_signaled(SIGTERM))
773                                 continue;
774                         return -1;
775                 }
776                 if (nb == 0)
777                         break;
778                 done += nb;
779                 ptr += nb;
780         }
781         return done;
782 }
783 #endif
784
785 /*
786  * mkdir_check - helper for mkdir_recursive, creates a directory
787  * but do not error on EEXIST if and only if entry is a directory
788  * The caller must check for errno == ENOENT if appropriate.
789  */
790 static int
791 mkdir_check(const char *path)
792 {
793     struct stat statbuf;
794
795     if (mkdir(path, 0755) >= 0)
796         return 0;
797
798     if (errno == EEXIST) {
799         if (stat(path, &statbuf) < 0)
800             /* got raced? */
801             return -1;
802
803         if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
804             return 0;
805
806         /* already exists but not a dir, treat as failure */
807         errno = EEXIST;
808         return -1;
809     }
810
811     return -1;
812 }
813
814 /*
815  * mkdir_parent - helper for mkdir_recursive, modifies the string in place
816  * Assumes mkdir(path) already failed, so it first creates the parent then
817  * full path again.
818  */
819 static int
820 mkdir_parent(char *path)
821 {
822     char *slash;
823     int rc;
824
825     slash = strrchr(path, '/');
826     if (!slash)
827         return -1;
828
829     *slash = 0;
830     if (mkdir_check(path) < 0) {
831         if (errno != ENOENT) {
832             *slash = '/';
833             return -1;
834         }
835         if (mkdir_parent(path) < 0) {
836             *slash = '/';
837             return -1;
838         }
839     }
840     *slash = '/';
841
842     return mkdir_check(path);
843 }
844
845 /*
846  * mkdir_recursive - recursively create directory if it didn't exist
847  */
848 int
849 mkdir_recursive(const char *path)
850 {
851     char *copy;
852     int rc;
853
854     // optimistically try on full path first to avoid allocation
855     if (mkdir_check(path) == 0)
856         return 0;
857
858     copy = strdup(path);
859     if (!copy)
860         return -1;
861
862     rc = mkdir_parent(copy);
863     free(copy);
864     return rc;
865 }
866
867 /* Procedures for locking the serial device using a lock file. */
868 static char lock_file[MAXPATHLEN];
869
870 /*
871  * lock - create a lock file for the named device
872  */
873 int
874 lock(char *dev)
875 {
876 #ifdef LOCKLIB
877     int result;
878
879     result = mklock (dev, (void *) 0);
880     if (result == 0) {
881         strlcpy(lock_file, dev, sizeof(lock_file));
882         return 0;
883     }
884
885     if (result > 0)
886         notice("Device %s is locked by pid %d", dev, result);
887     else
888         error("Can't create lock file %s", lock_file);
889     return -1;
890
891 #else /* LOCKLIB */
892
893     char lock_buffer[12];
894     int fd, pid, n, siz;
895
896 #ifdef SVR4
897     struct stat sbuf;
898
899     if (stat(dev, &sbuf) < 0) {
900         error("Can't get device number for %s: %m", dev);
901         return -1;
902     }
903     if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
904         error("Can't lock %s: not a character device", dev);
905         return -1;
906     }
907     slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
908              PPP_PATH_LOCKDIR, major(sbuf.st_dev),
909              major(sbuf.st_rdev), minor(sbuf.st_rdev));
910 #else
911     char *p;
912     char lockdev[MAXPATHLEN];
913
914     if ((p = strstr(dev, "dev/")) != NULL) {
915         dev = p + 4;
916         strncpy(lockdev, dev, MAXPATHLEN-1);
917         lockdev[MAXPATHLEN-1] = 0;
918         while ((p = strrchr(lockdev, '/')) != NULL) {
919             *p = '_';
920         }
921         dev = lockdev;
922     } else
923         if ((p = strrchr(dev, '/')) != NULL)
924             dev = p + 1;
925
926     slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", PPP_PATH_LOCKDIR, dev);
927 #endif
928
929     while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
930         if (errno != EEXIST) {
931             error("Can't create lock file %s: %m", lock_file);
932             break;
933         }
934
935         /* Read the lock file to find out who has the device locked. */
936         fd = open(lock_file, O_RDONLY, 0);
937         if (fd < 0) {
938             if (errno == ENOENT) /* This is just a timing problem. */
939                 continue;
940             error("Can't open existing lock file %s: %m", lock_file);
941             break;
942         }
943 #ifndef LOCK_BINARY
944         n = read(fd, lock_buffer, 11);
945 #else
946         n = read(fd, &pid, sizeof(pid));
947 #endif /* LOCK_BINARY */
948         close(fd);
949         fd = -1;
950         if (n <= 0) {
951             error("Can't read pid from lock file %s", lock_file);
952             break;
953         }
954
955         /* See if the process still exists. */
956 #ifndef LOCK_BINARY
957         lock_buffer[n] = 0;
958         pid = atoi(lock_buffer);
959 #endif /* LOCK_BINARY */
960         if (pid == getpid())
961             return 1;           /* somebody else locked it for us */
962         if (pid == 0
963             || (kill(pid, 0) == -1 && errno == ESRCH)) {
964             if (unlink (lock_file) == 0) {
965                 notice("Removed stale lock on %s (pid %d)", dev, pid);
966                 continue;
967             }
968             warn("Couldn't remove stale lock on %s", dev);
969         } else
970             notice("Device %s is locked by pid %d", dev, pid);
971         break;
972     }
973
974     if (fd < 0) {
975         lock_file[0] = 0;
976         return -1;
977     }
978
979     pid = getpid();
980 #ifndef LOCK_BINARY
981     siz = 11;
982     slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
983     n = write (fd, lock_buffer, siz);
984 #else
985     siz = sizeof (pid);
986     n = write(fd, &pid, siz);
987 #endif
988     if (n != siz) {
989         error("Could not write pid to lock file when locking");
990     }
991     close(fd);
992     return 0;
993
994 #endif
995 }
996
997 /*
998  * relock - called to update our lockfile when we are about to detach,
999  * thus changing our pid (we fork, the child carries on, and the parent dies).
1000  * Note that this is called by the parent, with pid equal to the pid
1001  * of the child.  This avoids a potential race which would exist if
1002  * we had the child rewrite the lockfile (the parent might die first,
1003  * and another process could think the lock was stale if it checked
1004  * between when the parent died and the child rewrote the lockfile).
1005  */
1006 int
1007 relock(int pid)
1008 {
1009 #ifdef LOCKLIB
1010     /* XXX is there a way to do this? */
1011     return -1;
1012 #else /* LOCKLIB */
1013
1014     int fd, n, siz;
1015     char lock_buffer[12];
1016
1017     if (lock_file[0] == 0)
1018         return -1;
1019     fd = open(lock_file, O_WRONLY, 0);
1020     if (fd < 0) {
1021         error("Couldn't reopen lock file %s: %m", lock_file);
1022         lock_file[0] = 0;
1023         return -1;
1024     }
1025
1026 #ifndef LOCK_BINARY
1027     siz = 11;
1028     slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1029     n = write (fd, lock_buffer, siz);
1030 #else
1031     siz = sizeof(pid);
1032     n = write(fd, &pid, siz);
1033 #endif /* LOCK_BINARY */
1034     if (n != siz) {
1035         error("Could not write pid to lock file when locking");
1036     }
1037     close(fd);
1038     return 0;
1039
1040 #endif /* LOCKLIB */
1041 }
1042
1043 /*
1044  * unlock - remove our lockfile
1045  */
1046 void
1047 unlock(void)
1048 {
1049     if (lock_file[0]) {
1050 #ifdef LOCKLIB
1051         (void) rmlock(lock_file, (void *) 0);
1052 #else
1053         unlink(lock_file);
1054 #endif
1055         lock_file[0] = 0;
1056     }
1057 }
1058