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