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