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