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