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