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