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