• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #if !defined(__ANDROID__)
79 
80 /*
81  * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
82  * always leaves destination null-terminated (for len > 0).
83  */
84 size_t
strlcpy(dest,src,len)85 strlcpy(dest, src, len)
86     char *dest;
87     const char *src;
88     size_t len;
89 {
90     size_t ret = strlen(src);
91 
92     if (len != 0) {
93 	if (ret < len)
94 	    strcpy(dest, src);
95 	else {
96 	    strncpy(dest, src, len - 1);
97 	    dest[len-1] = 0;
98 	}
99     }
100     return ret;
101 }
102 
103 /*
104  * strlcat - like strcat/strncat, doesn't overflow destination buffer,
105  * always leaves destination null-terminated (for len > 0).
106  */
107 size_t
strlcat(dest,src,len)108 strlcat(dest, src, len)
109     char *dest;
110     const char *src;
111     size_t len;
112 {
113     size_t dlen = strlen(dest);
114 
115     return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
116 }
117 #endif
118 
119 
120 /*
121  * slprintf - format a message into a buffer.  Like sprintf except we
122  * also specify the length of the output buffer, and we handle
123  * %m (error message), %v (visible string),
124  * %q (quoted string), %t (current time) and %I (IP address) formats.
125  * Doesn't do floating-point formats.
126  * Returns the number of chars put into buf.
127  */
128 int
slprintf(char * buf,int buflen,char * fmt,...)129 slprintf __V((char *buf, int buflen, char *fmt, ...))
130 {
131     va_list args;
132     int n;
133 
134 #if defined(__STDC__)
135     va_start(args, fmt);
136 #else
137     char *buf;
138     int buflen;
139     char *fmt;
140     va_start(args);
141     buf = va_arg(args, char *);
142     buflen = va_arg(args, int);
143     fmt = va_arg(args, char *);
144 #endif
145     n = vslprintf(buf, buflen, fmt, args);
146     va_end(args);
147     return n;
148 }
149 
150 /*
151  * vslprintf - like slprintf, takes a va_list instead of a list of args.
152  */
153 #define OUTCHAR(c)	(buflen > 0? (--buflen, *buf++ = (c)): 0)
154 
155 int
vslprintf(buf,buflen,fmt,args)156 vslprintf(buf, buflen, fmt, args)
157     char *buf;
158     int buflen;
159     char *fmt;
160     va_list args;
161 {
162     int c, i, n;
163     int width, prec, fillch;
164     int base, len, neg, quoted;
165     unsigned long val = 0;
166     char *str, *f, *buf0;
167     unsigned char *p;
168     char num[32];
169     time_t t;
170     u_int32_t ip;
171     static char hexchars[] = "0123456789abcdef";
172     struct buffer_info bufinfo;
173 
174     buf0 = buf;
175     --buflen;
176     while (buflen > 0) {
177 	for (f = fmt; *f != '%' && *f != 0; ++f)
178 	    ;
179 	if (f > fmt) {
180 	    len = f - fmt;
181 	    if (len > buflen)
182 		len = buflen;
183 	    memcpy(buf, fmt, len);
184 	    buf += len;
185 	    buflen -= len;
186 	    fmt = f;
187 	}
188 	if (*fmt == 0)
189 	    break;
190 	c = *++fmt;
191 	width = 0;
192 	prec = -1;
193 	fillch = ' ';
194 	if (c == '0') {
195 	    fillch = '0';
196 	    c = *++fmt;
197 	}
198 	if (c == '*') {
199 	    width = va_arg(args, int);
200 	    c = *++fmt;
201 	} else {
202 	    while (isdigit(c)) {
203 		width = width * 10 + c - '0';
204 		c = *++fmt;
205 	    }
206 	}
207 	if (c == '.') {
208 	    c = *++fmt;
209 	    if (c == '*') {
210 		prec = va_arg(args, int);
211 		c = *++fmt;
212 	    } else {
213 		prec = 0;
214 		while (isdigit(c)) {
215 		    prec = prec * 10 + c - '0';
216 		    c = *++fmt;
217 		}
218 	    }
219 	}
220 	str = 0;
221 	base = 0;
222 	neg = 0;
223 	++fmt;
224 	switch (c) {
225 	case 'l':
226 	    c = *fmt++;
227 	    switch (c) {
228 	    case 'd':
229 		val = va_arg(args, long);
230 #if defined(__ANDROID__)
231 		if ((long)val < 0) {
232 		    neg = 1;
233 		    val = (unsigned long)(-(long)val);
234 		}
235 #else
236 		if (val < 0) {
237 		    neg = 1;
238 		    val = -val;
239 		}
240 #endif
241 		base = 10;
242 		break;
243 	    case 'u':
244 		val = va_arg(args, unsigned long);
245 		base = 10;
246 		break;
247 	    default:
248 		OUTCHAR('%');
249 		OUTCHAR('l');
250 		--fmt;		/* so %lz outputs %lz etc. */
251 		continue;
252 	    }
253 	    break;
254 	case 'd':
255 	    i = va_arg(args, int);
256 	    if (i < 0) {
257 		neg = 1;
258 		val = -i;
259 	    } else
260 		val = i;
261 	    base = 10;
262 	    break;
263 	case 'u':
264 	    val = va_arg(args, unsigned int);
265 	    base = 10;
266 	    break;
267 	case 'o':
268 	    val = va_arg(args, unsigned int);
269 	    base = 8;
270 	    break;
271 	case 'x':
272 	case 'X':
273 	    val = va_arg(args, unsigned int);
274 	    base = 16;
275 	    break;
276 	case 'p':
277 	    val = (unsigned long) va_arg(args, void *);
278 	    base = 16;
279 	    neg = 2;
280 	    break;
281 	case 's':
282 	    str = va_arg(args, char *);
283 	    break;
284 	case 'c':
285 	    num[0] = va_arg(args, int);
286 	    num[1] = 0;
287 	    str = num;
288 	    break;
289 	case 'm':
290 	    str = strerror(errno);
291 	    break;
292 	case 'I':
293 	    ip = va_arg(args, u_int32_t);
294 	    ip = ntohl(ip);
295 	    slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
296 		     (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
297 	    str = num;
298 	    break;
299 	case 't':
300 	    time(&t);
301 	    str = ctime(&t);
302 	    str += 4;		/* chop off the day name */
303 	    str[15] = 0;	/* chop off year and newline */
304 	    break;
305 	case 'v':		/* "visible" string */
306 	case 'q':		/* quoted string */
307 	    quoted = c == 'q';
308 	    p = va_arg(args, unsigned char *);
309 	    if (p == NULL)
310 		    p = (unsigned char *)"<NULL>";
311 	    if (fillch == '0' && prec >= 0) {
312 		n = prec;
313 	    } else {
314 		if (prec >= 0) {
315 		    n = strnlen((char *)p, prec);
316 		} else {
317 		    n = strlen((char *)p);
318 		}
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
vslp_printer(void * arg,char * fmt,...)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
log_packet(p,len,prefix,level)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
format_packet(p,len,printer,arg)475 format_packet(p, len, printer, arg)
476     u_char *p;
477     int len;
478     printer_func printer;
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
init_pr_log(prefix,level)529 init_pr_log(prefix, level)
530      const 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
end_pr_log()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
pr_log(void * arg,char * fmt,...)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
print_string(p,len,printer,arg)613 print_string(p, len, printer, arg)
614     char *p;
615     int len;
616     printer_func printer;
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
logit(level,fmt,args)651 logit(level, fmt, args)
652     int level;
653     char *fmt;
654     va_list args;
655 {
656     char buf[1024];
657 
658     vslprintf(buf, sizeof(buf), fmt, args);
659     log_write(level, buf);
660 }
661 
662 static void
log_write(level,buf)663 log_write(level, buf)
664     int level;
665     char *buf;
666 {
667     syslog(level, "%s", buf);
668     if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
669 	int n = strlen(buf);
670 
671 	if (n > 0 && buf[n-1] == '\n')
672 	    --n;
673 	if (write(log_to_fd, buf, n) != n
674 	    || write(log_to_fd, "\n", 1) != 1)
675 	    log_to_fd = -1;
676     }
677 }
678 
679 /*
680  * fatal - log an error message and die horribly.
681  */
682 void
fatal(char * fmt,...)683 fatal __V((char *fmt, ...))
684 {
685     va_list pvar;
686 
687 #if defined(__STDC__)
688     va_start(pvar, fmt);
689 #else
690     char *fmt;
691     va_start(pvar);
692     fmt = va_arg(pvar, char *);
693 #endif
694 
695     logit(LOG_ERR, fmt, pvar);
696     va_end(pvar);
697 
698     die(1);			/* as promised */
699 }
700 
701 /*
702  * error - log an error message.
703  */
704 void
error(char * fmt,...)705 error __V((char *fmt, ...))
706 {
707     va_list pvar;
708 
709 #if defined(__STDC__)
710     va_start(pvar, fmt);
711 #else
712     char *fmt;
713     va_start(pvar);
714     fmt = va_arg(pvar, char *);
715 #endif
716 
717     logit(LOG_ERR, fmt, pvar);
718     va_end(pvar);
719     ++error_count;
720 }
721 
722 /*
723  * warn - log a warning message.
724  */
725 void
warn(char * fmt,...)726 warn __V((char *fmt, ...))
727 {
728     va_list pvar;
729 
730 #if defined(__STDC__)
731     va_start(pvar, fmt);
732 #else
733     char *fmt;
734     va_start(pvar);
735     fmt = va_arg(pvar, char *);
736 #endif
737 
738     logit(LOG_WARNING, fmt, pvar);
739     va_end(pvar);
740 }
741 
742 /*
743  * notice - log a notice-level message.
744  */
745 void
notice(char * fmt,...)746 notice __V((char *fmt, ...))
747 {
748     va_list pvar;
749 
750 #if defined(__STDC__)
751     va_start(pvar, fmt);
752 #else
753     char *fmt;
754     va_start(pvar);
755     fmt = va_arg(pvar, char *);
756 #endif
757 
758     logit(LOG_NOTICE, fmt, pvar);
759     va_end(pvar);
760 }
761 
762 /*
763  * info - log an informational message.
764  */
765 void
info(char * fmt,...)766 info __V((char *fmt, ...))
767 {
768     va_list pvar;
769 
770 #if defined(__STDC__)
771     va_start(pvar, fmt);
772 #else
773     char *fmt;
774     va_start(pvar);
775     fmt = va_arg(pvar, char *);
776 #endif
777 
778     logit(LOG_INFO, fmt, pvar);
779     va_end(pvar);
780 }
781 
782 /*
783  * dbglog - log a debug message.
784  */
785 void
dbglog(char * fmt,...)786 dbglog __V((char *fmt, ...))
787 {
788     va_list pvar;
789 
790 #if defined(__STDC__)
791     va_start(pvar, fmt);
792 #else
793     char *fmt;
794     va_start(pvar);
795     fmt = va_arg(pvar, char *);
796 #endif
797 
798     logit(LOG_DEBUG, fmt, pvar);
799     va_end(pvar);
800 }
801 
802 /*
803  * dump_packet - print out a packet in readable form if it is interesting.
804  * Assumes len >= PPP_HDRLEN.
805  */
806 void
dump_packet(const char * tag,unsigned char * p,int len)807 dump_packet(const char *tag, unsigned char *p, int len)
808 {
809     int proto;
810 
811     if (!debug)
812 	return;
813 
814     /*
815      * don't print LCP echo request/reply packets if debug <= 1
816      * and the link is up.
817      */
818     proto = (p[2] << 8) + p[3];
819     if (debug <= 1 && unsuccess == 0 && proto == PPP_LCP
820 	&& len >= PPP_HDRLEN + HEADERLEN) {
821 	unsigned char *lcp = p + PPP_HDRLEN;
822 	int l = (lcp[2] << 8) + lcp[3];
823 
824 	if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
825 	    && l >= HEADERLEN && l <= len - PPP_HDRLEN)
826 	    return;
827     }
828 
829     dbglog("%s %P", tag, p, len);
830 }
831 
832 /*
833  * complete_read - read a full `count' bytes from fd,
834  * unless end-of-file or an error other than EINTR is encountered.
835  */
836 ssize_t
complete_read(int fd,void * buf,size_t count)837 complete_read(int fd, void *buf, size_t count)
838 {
839 	size_t done;
840 	ssize_t nb;
841 	char *ptr = buf;
842 
843 	for (done = 0; done < count; ) {
844 		nb = read(fd, ptr, count - done);
845 		if (nb < 0) {
846 			if (errno == EINTR)
847 				continue;
848 			return -1;
849 		}
850 		if (nb == 0)
851 			break;
852 		done += nb;
853 		ptr += nb;
854 	}
855 	return done;
856 }
857 
858 /* Procedures for locking the serial device using a lock file. */
859 #ifndef LOCK_DIR
860 #ifdef __linux__
861 #define LOCK_DIR	"/var/lock"
862 #else
863 #ifdef SVR4
864 #define LOCK_DIR	"/var/spool/locks"
865 #else
866 #define LOCK_DIR	"/var/spool/lock"
867 #endif
868 #endif
869 #endif /* LOCK_DIR */
870 
871 static char lock_file[MAXPATHLEN];
872 
873 /*
874  * lock - create a lock file for the named device
875  */
876 int
lock(dev)877 lock(dev)
878     char *dev;
879 {
880 #ifdef LOCKLIB
881     int result;
882 
883     result = mklock (dev, (void *) 0);
884     if (result == 0) {
885 	strlcpy(lock_file, dev, sizeof(lock_file));
886 	return 0;
887     }
888 
889     if (result > 0)
890         notice("Device %s is locked by pid %d", dev, result);
891     else
892 	error("Can't create lock file %s", lock_file);
893     return -1;
894 
895 #else /* LOCKLIB */
896 
897     char lock_buffer[12];
898     int fd, pid, n;
899 
900 #ifdef SVR4
901     struct stat sbuf;
902 
903     if (stat(dev, &sbuf) < 0) {
904 	error("Can't get device number for %s: %m", dev);
905 	return -1;
906     }
907     if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
908 	error("Can't lock %s: not a character device", dev);
909 	return -1;
910     }
911     slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
912 	     LOCK_DIR, major(sbuf.st_dev),
913 	     major(sbuf.st_rdev), minor(sbuf.st_rdev));
914 #else
915     char *p;
916     char lockdev[MAXPATHLEN];
917 
918     if ((p = strstr(dev, "dev/")) != NULL) {
919 	dev = p + 4;
920 	strncpy(lockdev, dev, MAXPATHLEN-1);
921 	lockdev[MAXPATHLEN-1] = 0;
922 	while ((p = strrchr(lockdev, '/')) != NULL) {
923 	    *p = '_';
924 	}
925 	dev = lockdev;
926     } else
927 	if ((p = strrchr(dev, '/')) != NULL)
928 	    dev = p + 1;
929 
930     slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
931 #endif
932 
933     while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
934 	if (errno != EEXIST) {
935 	    error("Can't create lock file %s: %m", lock_file);
936 	    break;
937 	}
938 
939 	/* Read the lock file to find out who has the device locked. */
940 	fd = open(lock_file, O_RDONLY, 0);
941 	if (fd < 0) {
942 	    if (errno == ENOENT) /* This is just a timing problem. */
943 		continue;
944 	    error("Can't open existing lock file %s: %m", lock_file);
945 	    break;
946 	}
947 #ifndef LOCK_BINARY
948 	n = read(fd, lock_buffer, 11);
949 #else
950 	n = read(fd, &pid, sizeof(pid));
951 #endif /* LOCK_BINARY */
952 	close(fd);
953 	fd = -1;
954 	if (n <= 0) {
955 	    error("Can't read pid from lock file %s", lock_file);
956 	    break;
957 	}
958 
959 	/* See if the process still exists. */
960 #ifndef LOCK_BINARY
961 	lock_buffer[n] = 0;
962 	pid = atoi(lock_buffer);
963 #endif /* LOCK_BINARY */
964 	if (pid == getpid())
965 	    return 1;		/* somebody else locked it for us */
966 	if (pid == 0
967 	    || (kill(pid, 0) == -1 && errno == ESRCH)) {
968 	    if (unlink (lock_file) == 0) {
969 		notice("Removed stale lock on %s (pid %d)", dev, pid);
970 		continue;
971 	    }
972 	    warn("Couldn't remove stale lock on %s", dev);
973 	} else
974 	    notice("Device %s is locked by pid %d", dev, pid);
975 	break;
976     }
977 
978     if (fd < 0) {
979 	lock_file[0] = 0;
980 	return -1;
981     }
982 
983     pid = getpid();
984 #ifndef LOCK_BINARY
985     slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
986     write (fd, lock_buffer, 11);
987 #else
988     write(fd, &pid, sizeof (pid));
989 #endif
990     close(fd);
991     return 0;
992 
993 #endif
994 }
995 
996 /*
997  * relock - called to update our lockfile when we are about to detach,
998  * thus changing our pid (we fork, the child carries on, and the parent dies).
999  * Note that this is called by the parent, with pid equal to the pid
1000  * of the child.  This avoids a potential race which would exist if
1001  * we had the child rewrite the lockfile (the parent might die first,
1002  * and another process could think the lock was stale if it checked
1003  * between when the parent died and the child rewrote the lockfile).
1004  */
1005 int
relock(pid)1006 relock(pid)
1007     int pid;
1008 {
1009 #ifdef LOCKLIB
1010     /* XXX is there a way to do this? */
1011     return -1;
1012 #else /* LOCKLIB */
1013 
1014     int fd;
1015     char lock_buffer[12];
1016 
1017     if (lock_file[0] == 0)
1018 	return -1;
1019     fd = open(lock_file, O_WRONLY, 0);
1020     if (fd < 0) {
1021 	error("Couldn't reopen lock file %s: %m", lock_file);
1022 	lock_file[0] = 0;
1023 	return -1;
1024     }
1025 
1026 #ifndef LOCK_BINARY
1027     slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
1028     write (fd, lock_buffer, 11);
1029 #else
1030     write(fd, &pid, sizeof(pid));
1031 #endif /* LOCK_BINARY */
1032     close(fd);
1033     return 0;
1034 
1035 #endif /* LOCKLIB */
1036 }
1037 
1038 /*
1039  * unlock - remove our lockfile
1040  */
1041 void
unlock()1042 unlock()
1043 {
1044     if (lock_file[0]) {
1045 #ifdef LOCKLIB
1046 	(void) rmlock(lock_file, (void *) 0);
1047 #else
1048 	unlink(lock_file);
1049 #endif
1050 	lock_file[0] = 0;
1051     }
1052 }
1053 
1054