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