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