]> git.ozlabs.org Git - ppp.git/blob - pppd/utils.c
pppd: Limit memory accessed by string formats with max length specified
[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                 if (prec == -1)
304                     n = strlen((char *)p);
305                 else
306                     n = strnlen((char *)p, prec);
307             }
308             while (n > 0 && buflen > 0) {
309                 c = *p++;
310                 --n;
311                 if (!quoted && c >= 0x80) {
312                     OUTCHAR('M');
313                     OUTCHAR('-');
314                     c -= 0x80;
315                 }
316                 if (quoted && (c == '"' || c == '\\'))
317                     OUTCHAR('\\');
318                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
319                     if (quoted) {
320                         OUTCHAR('\\');
321                         switch (c) {
322                         case '\t':      OUTCHAR('t');   break;
323                         case '\n':      OUTCHAR('n');   break;
324                         case '\b':      OUTCHAR('b');   break;
325                         case '\f':      OUTCHAR('f');   break;
326                         default:
327                             OUTCHAR('x');
328                             OUTCHAR(hexchars[c >> 4]);
329                             OUTCHAR(hexchars[c & 0xf]);
330                         }
331                     } else {
332                         if (c == '\t')
333                             OUTCHAR(c);
334                         else {
335                             OUTCHAR('^');
336                             OUTCHAR(c ^ 0x40);
337                         }
338                     }
339                 } else
340                     OUTCHAR(c);
341             }
342             continue;
343         case 'P':               /* print PPP packet */
344             bufinfo.ptr = buf;
345             bufinfo.len = buflen + 1;
346             p = va_arg(args, unsigned char *);
347             n = va_arg(args, int);
348             format_packet(p, n, vslp_printer, &bufinfo);
349             buf = bufinfo.ptr;
350             buflen = bufinfo.len - 1;
351             continue;
352         case 'B':
353             p = va_arg(args, unsigned char *);
354             for (n = prec; n > 0; --n) {
355                 c = *p++;
356                 if (fillch == ' ')
357                     OUTCHAR(' ');
358                 OUTCHAR(hexchars[(c >> 4) & 0xf]);
359                 OUTCHAR(hexchars[c & 0xf]);
360             }
361             continue;
362         default:
363             *buf++ = '%';
364             if (c != '%')
365                 --fmt;          /* so %z outputs %z etc. */
366             --buflen;
367             continue;
368         }
369         if (base != 0) {
370             str = num + sizeof(num);
371             *--str = 0;
372             while (str > num + neg) {
373                 *--str = hexchars[val % base];
374                 val = val / base;
375                 if (--prec <= 0 && val == 0)
376                     break;
377             }
378             switch (neg) {
379             case 1:
380                 *--str = '-';
381                 break;
382             case 2:
383                 *--str = 'x';
384                 *--str = '0';
385                 break;
386             }
387             len = num + sizeof(num) - 1 - str;
388         } else {
389             if (prec == -1)
390                 len = strlen(str);
391             else
392                 len = strnlen(str, prec);
393         }
394         if (width > 0) {
395             if (width > buflen)
396                 width = buflen;
397             if ((n = width - len) > 0) {
398                 buflen -= n;
399                 for (; n > 0; --n)
400                     *buf++ = fillch;
401             }
402         }
403         if (len > buflen)
404             len = buflen;
405         memcpy(buf, str, len);
406         buf += len;
407         buflen -= len;
408     }
409     *buf = 0;
410     return buf - buf0;
411 }
412
413 /*
414  * vslp_printer - used in processing a %P format
415  */
416 static void
417 vslp_printer __V((void *arg, char *fmt, ...))
418 {
419     int n;
420     va_list pvar;
421     struct buffer_info *bi;
422
423 #if defined(__STDC__)
424     va_start(pvar, fmt);
425 #else
426     void *arg;
427     char *fmt;
428     va_start(pvar);
429     arg = va_arg(pvar, void *);
430     fmt = va_arg(pvar, char *);
431 #endif
432
433     bi = (struct buffer_info *) arg;
434     n = vslprintf(bi->ptr, bi->len, fmt, pvar);
435     va_end(pvar);
436
437     bi->ptr += n;
438     bi->len -= n;
439 }
440
441 #ifdef unused
442 /*
443  * log_packet - format a packet and log it.
444  */
445
446 void
447 log_packet(p, len, prefix, level)
448     u_char *p;
449     int len;
450     char *prefix;
451     int level;
452 {
453         init_pr_log(prefix, level);
454         format_packet(p, len, pr_log, &level);
455         end_pr_log();
456 }
457 #endif /* unused */
458
459 /*
460  * format_packet - make a readable representation of a packet,
461  * calling `printer(arg, format, ...)' to output it.
462  */
463 static void
464 format_packet(p, len, printer, arg)
465     u_char *p;
466     int len;
467     printer_func printer;
468     void *arg;
469 {
470     int i, n;
471     u_short proto;
472     struct protent *protp;
473
474     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
475         p += 2;
476         GETSHORT(proto, p);
477         len -= PPP_HDRLEN;
478         for (i = 0; (protp = protocols[i]) != NULL; ++i)
479             if (proto == protp->protocol)
480                 break;
481         if (protp != NULL) {
482             printer(arg, "[%s", protp->name);
483             n = (*protp->printpkt)(p, len, printer, arg);
484             printer(arg, "]");
485             p += n;
486             len -= n;
487         } else {
488             for (i = 0; (protp = protocols[i]) != NULL; ++i)
489                 if (proto == (protp->protocol & ~0x8000))
490                     break;
491             if (protp != 0 && protp->data_name != 0) {
492                 printer(arg, "[%s data]", protp->data_name);
493                 if (len > 8)
494                     printer(arg, "%.8B ...", p);
495                 else
496                     printer(arg, "%.*B", len, p);
497                 len = 0;
498             } else
499                 printer(arg, "[proto=0x%x]", proto);
500         }
501     }
502
503     if (len > 32)
504         printer(arg, "%.32B ...", p);
505     else
506         printer(arg, "%.*B", len, p);
507 }
508
509 /*
510  * init_pr_log, end_pr_log - initialize and finish use of pr_log.
511  */
512
513 static char line[256];          /* line to be logged accumulated here */
514 static char *linep;             /* current pointer within line */
515 static int llevel;              /* level for logging */
516
517 void
518 init_pr_log(prefix, level)
519      const char *prefix;
520      int level;
521 {
522         linep = line;
523         if (prefix != NULL) {
524                 strlcpy(line, prefix, sizeof(line));
525                 linep = line + strlen(line);
526         }
527         llevel = level;
528 }
529
530 void
531 end_pr_log()
532 {
533         if (linep != line) {
534                 *linep = 0;
535                 log_write(llevel, line);
536         }
537 }
538
539 /*
540  * pr_log - printer routine for outputting to syslog
541  */
542 void
543 pr_log __V((void *arg, char *fmt, ...))
544 {
545         int l, n;
546         va_list pvar;
547         char *p, *eol;
548         char buf[256];
549
550 #if defined(__STDC__)
551         va_start(pvar, fmt);
552 #else
553         void *arg;
554         char *fmt;
555         va_start(pvar);
556         arg = va_arg(pvar, void *);
557         fmt = va_arg(pvar, char *);
558 #endif
559
560         n = vslprintf(buf, sizeof(buf), fmt, pvar);
561         va_end(pvar);
562
563         p = buf;
564         eol = strchr(buf, '\n');
565         if (linep != line) {
566                 l = (eol == NULL)? n: eol - buf;
567                 if (linep + l < line + sizeof(line)) {
568                         if (l > 0) {
569                                 memcpy(linep, buf, l);
570                                 linep += l;
571                         }
572                         if (eol == NULL)
573                                 return;
574                         p = eol + 1;
575                         eol = strchr(p, '\n');
576                 }
577                 *linep = 0;
578                 log_write(llevel, line);
579                 linep = line;
580         }
581
582         while (eol != NULL) {
583                 *eol = 0;
584                 log_write(llevel, p);
585                 p = eol + 1;
586                 eol = strchr(p, '\n');
587         }
588
589         /* assumes sizeof(buf) <= sizeof(line) */
590         l = buf + n - p;
591         if (l > 0) {
592                 memcpy(line, p, n);
593                 linep = line + l;
594         }
595 }
596
597 /*
598  * print_string - print a readable representation of a string using
599  * printer.
600  */
601 void
602 print_string(p, len, printer, arg)
603     char *p;
604     int len;
605     printer_func printer;
606     void *arg;
607 {
608     int c;
609
610     printer(arg, "\"");
611     for (; len > 0; --len) {
612         c = *p++;
613         if (' ' <= c && c <= '~') {
614             if (c == '\\' || c == '"')
615                 printer(arg, "\\");
616             printer(arg, "%c", c);
617         } else {
618             switch (c) {
619             case '\n':
620                 printer(arg, "\\n");
621                 break;
622             case '\r':
623                 printer(arg, "\\r");
624                 break;
625             case '\t':
626                 printer(arg, "\\t");
627                 break;
628             default:
629                 printer(arg, "\\%.3o", (unsigned char) c);
630             }
631         }
632     }
633     printer(arg, "\"");
634 }
635
636 /*
637  * logit - does the hard work for fatal et al.
638  */
639 static void
640 logit(level, fmt, args)
641     int level;
642     char *fmt;
643     va_list args;
644 {
645     char buf[1024];
646
647     vslprintf(buf, sizeof(buf), fmt, args);
648     log_write(level, buf);
649 }
650
651 static void
652 log_write(level, buf)
653     int level;
654     char *buf;
655 {
656     syslog(level, "%s", buf);
657     if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
658         int n = strlen(buf);
659
660         if (n > 0 && buf[n-1] == '\n')
661             --n;
662         if (write(log_to_fd, buf, n) != n
663             || write(log_to_fd, "\n", 1) != 1)
664             log_to_fd = -1;
665     }
666 }
667
668 /*
669  * fatal - log an error message and die horribly.
670  */
671 void
672 fatal __V((char *fmt, ...))
673 {
674     va_list pvar;
675
676 #if defined(__STDC__)
677     va_start(pvar, fmt);
678 #else
679     char *fmt;
680     va_start(pvar);
681     fmt = va_arg(pvar, char *);
682 #endif
683
684     logit(LOG_ERR, fmt, pvar);
685     va_end(pvar);
686
687     die(1);                     /* as promised */
688 }
689
690 /*
691  * error - log an error message.
692  */
693 void
694 error __V((char *fmt, ...))
695 {
696     va_list pvar;
697
698 #if defined(__STDC__)
699     va_start(pvar, fmt);
700 #else
701     char *fmt;
702     va_start(pvar);
703     fmt = va_arg(pvar, char *);
704 #endif
705
706     logit(LOG_ERR, fmt, pvar);
707     va_end(pvar);
708     ++error_count;
709 }
710
711 /*
712  * warn - log a warning message.
713  */
714 void
715 warn __V((char *fmt, ...))
716 {
717     va_list pvar;
718
719 #if defined(__STDC__)
720     va_start(pvar, fmt);
721 #else
722     char *fmt;
723     va_start(pvar);
724     fmt = va_arg(pvar, char *);
725 #endif
726
727     logit(LOG_WARNING, fmt, pvar);
728     va_end(pvar);
729 }
730
731 /*
732  * notice - log a notice-level message.
733  */
734 void
735 notice __V((char *fmt, ...))
736 {
737     va_list pvar;
738
739 #if defined(__STDC__)
740     va_start(pvar, fmt);
741 #else
742     char *fmt;
743     va_start(pvar);
744     fmt = va_arg(pvar, char *);
745 #endif
746
747     logit(LOG_NOTICE, fmt, pvar);
748     va_end(pvar);
749 }
750
751 /*
752  * info - log an informational message.
753  */
754 void
755 info __V((char *fmt, ...))
756 {
757     va_list pvar;
758
759 #if defined(__STDC__)
760     va_start(pvar, fmt);
761 #else
762     char *fmt;
763     va_start(pvar);
764     fmt = va_arg(pvar, char *);
765 #endif
766
767     logit(LOG_INFO, fmt, pvar);
768     va_end(pvar);
769 }
770
771 /*
772  * dbglog - log a debug message.
773  */
774 void
775 dbglog __V((char *fmt, ...))
776 {
777     va_list pvar;
778
779 #if defined(__STDC__)
780     va_start(pvar, fmt);
781 #else
782     char *fmt;
783     va_start(pvar);
784     fmt = va_arg(pvar, char *);
785 #endif
786
787     logit(LOG_DEBUG, fmt, pvar);
788     va_end(pvar);
789 }
790
791 /*
792  * dump_packet - print out a packet in readable form if it is interesting.
793  * Assumes len >= PPP_HDRLEN.
794  */
795 void
796 dump_packet(const char *tag, unsigned char *p, int len)
797 {
798     int proto;
799
800     if (!debug)
801         return;
802
803     /*
804      * don't print LCP echo request/reply packets if debug <= 1
805      * and the link is up.
806      */
807     proto = (p[2] << 8) + p[3];
808     if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
809         && len >= PPP_HDRLEN + HEADERLEN) {
810         unsigned char *lcp = p + PPP_HDRLEN;
811         int l = (lcp[2] << 8) + lcp[3];
812
813         if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
814             && l >= HEADERLEN && l <= len - PPP_HDRLEN)
815             return;
816     }
817
818     dbglog("%s %P", tag, p, len);
819 }
820
821 /*
822  * complete_read - read a full `count' bytes from fd,
823  * unless end-of-file or an error other than EINTR is encountered.
824  */
825 ssize_t
826 complete_read(int fd, void *buf, size_t count)
827 {
828         size_t done;
829         ssize_t nb;
830         char *ptr = buf;
831
832         for (done = 0; done < count; ) {
833                 nb = read(fd, ptr, count - done);
834                 if (nb < 0) {
835                         if (errno == EINTR)
836                                 continue;
837                         return -1;
838                 }
839                 if (nb == 0)
840                         break;
841                 done += nb;
842                 ptr += nb;
843         }
844         return done;
845 }
846
847 /* Procedures for locking the serial device using a lock file. */
848 #ifndef LOCK_DIR
849 #ifdef __linux__
850 #define LOCK_DIR        "/var/lock"
851 #else
852 #ifdef SVR4
853 #define LOCK_DIR        "/var/spool/locks"
854 #else
855 #define LOCK_DIR        "/var/spool/lock"
856 #endif
857 #endif
858 #endif /* LOCK_DIR */
859
860 static char lock_file[MAXPATHLEN];
861
862 /*
863  * lock - create a lock file for the named device
864  */
865 int
866 lock(dev)
867     char *dev;
868 {
869 #ifdef LOCKLIB
870     int result;
871
872     result = mklock (dev, (void *) 0);
873     if (result == 0) {
874         strlcpy(lock_file, dev, sizeof(lock_file));
875         return 0;
876     }
877
878     if (result > 0)
879         notice("Device %s is locked by pid %d", dev, result);
880     else
881         error("Can't create lock file %s", lock_file);
882     return -1;
883
884 #else /* LOCKLIB */
885
886     char lock_buffer[12];
887     int fd, pid, n;
888
889 #ifdef SVR4
890     struct stat sbuf;
891
892     if (stat(dev, &sbuf) < 0) {
893         error("Can't get device number for %s: %m", dev);
894         return -1;
895     }
896     if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
897         error("Can't lock %s: not a character device", dev);
898         return -1;
899     }
900     slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
901              LOCK_DIR, major(sbuf.st_dev),
902              major(sbuf.st_rdev), minor(sbuf.st_rdev));
903 #else
904     char *p;
905     char lockdev[MAXPATHLEN];
906
907     if ((p = strstr(dev, "dev/")) != NULL) {
908         dev = p + 4;
909         strncpy(lockdev, dev, MAXPATHLEN-1);
910         lockdev[MAXPATHLEN-1] = 0;
911         while ((p = strrchr(lockdev, '/')) != NULL) {
912             *p = '_';
913         }
914         dev = lockdev;
915     } else
916         if ((p = strrchr(dev, '/')) != NULL)
917             dev = p + 1;
918
919     slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
920 #endif
921
922     while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
923         if (errno != EEXIST) {
924             error("Can't create lock file %s: %m", lock_file);
925             break;
926         }
927
928         /* Read the lock file to find out who has the device locked. */
929         fd = open(lock_file, O_RDONLY, 0);
930         if (fd < 0) {
931             if (errno == ENOENT) /* This is just a timing problem. */
932                 continue;
933             error("Can't open existing lock file %s: %m", lock_file);
934             break;
935         }
936 #ifndef LOCK_BINARY
937         n = read(fd, lock_buffer, 11);
938 #else
939         n = read(fd, &pid, sizeof(pid));
940 #endif /* LOCK_BINARY */
941         close(fd);
942         fd = -1;
943         if (n <= 0) {
944             error("Can't read pid from lock file %s", lock_file);
945             break;
946         }
947
948         /* See if the process still exists. */
949 #ifndef LOCK_BINARY
950         lock_buffer[n] = 0;
951         pid = atoi(lock_buffer);
952 #endif /* LOCK_BINARY */
953         if (pid == getpid())
954             return 1;           /* somebody else locked it for us */
955         if (pid == 0
956             || (kill(pid, 0) == -1 && errno == ESRCH)) {
957             if (unlink (lock_file) == 0) {
958                 notice("Removed stale lock on %s (pid %d)", dev, pid);
959                 continue;
960             }
961             warn("Couldn't remove stale lock on %s", dev);
962         } else
963             notice("Device %s is locked by pid %d", dev, pid);
964         break;
965     }
966
967     if (fd < 0) {
968         lock_file[0] = 0;
969         return -1;
970     }
971
972     pid = getpid();
973 #ifndef LOCK_BINARY
974     slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
975     write (fd, lock_buffer, 11);
976 #else
977     write(fd, &pid, sizeof (pid));
978 #endif
979     close(fd);
980     return 0;
981
982 #endif
983 }
984
985 /*
986  * relock - called to update our lockfile when we are about to detach,
987  * thus changing our pid (we fork, the child carries on, and the parent dies).
988  * Note that this is called by the parent, with pid equal to the pid
989  * of the child.  This avoids a potential race which would exist if
990  * we had the child rewrite the lockfile (the parent might die first,
991  * and another process could think the lock was stale if it checked
992  * between when the parent died and the child rewrote the lockfile).
993  */
994 int
995 relock(pid)
996     int pid;
997 {
998 #ifdef LOCKLIB
999     /* XXX is there a way to do this? */
1000     return -1;
1001 #else /* LOCKLIB */
1002
1003     int fd;
1004     char lock_buffer[12];
1005
1006     if (lock_file[0] == 0)
1007         return -1;
1008     fd = open(lock_file, O_WRONLY, 0);
1009     if (fd < 0) {
1010         error("Couldn't reopen lock file %s: %m", lock_file);
1011         lock_file[0] = 0;
1012         return -1;
1013     }
1014
1015 #ifndef LOCK_BINARY
1016     slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1017     write (fd, lock_buffer, 11);
1018 #else
1019     write(fd, &pid, sizeof(pid));
1020 #endif /* LOCK_BINARY */
1021     close(fd);
1022     return 0;
1023
1024 #endif /* LOCKLIB */
1025 }
1026
1027 /*
1028  * unlock - remove our lockfile
1029  */
1030 void
1031 unlock()
1032 {
1033     if (lock_file[0]) {
1034 #ifdef LOCKLIB
1035         (void) rmlock(lock_file, (void *) 0);
1036 #else
1037         unlink(lock_file);
1038 #endif
1039         lock_file[0] = 0;
1040     }
1041 }
1042