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