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