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