xref: /openbsd-src/usr.sbin/pppd/chat/chat.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: chat.c,v 1.12 1999/12/02 02:32:29 d Exp $	*/
2 
3 /*
4  *	Chat -- a program for automatic session establishment (i.e. dial
5  *		the phone and log in).
6  *
7  * Standard termination codes:
8  *  0 - successful completion of the script
9  *  1 - invalid argument, expect string too large, etc.
10  *  2 - error on an I/O operation or fatal error condition.
11  *  3 - timeout waiting for a simple string.
12  *  4 - the first string declared as "ABORT"
13  *  5 - the second string declared as "ABORT"
14  *  6 - ... and so on for successive ABORT strings.
15  *
16  *	This software is in the public domain.
17  *
18  * -----------------
19  *	added -T and -U option and \T and \U substitution to pass a phone
20  *	number into chat script. Two are needed for some ISDN TA applications.
21  *	Keith Dart <kdart@cisco.com>
22  *
23  *
24  *	Added SAY keyword to send output to stderr.
25  *      This allows to turn ECHO OFF and to output specific, user selected,
26  *      text to give progress messages. This best works when stderr
27  *      exists (i.e.: pppd in nodetach mode).
28  *
29  * 	Added HANGUP directives to allow for us to be called
30  *      back. When HANGUP is set to NO, chat will not hangup at HUP signal.
31  *      We rely on timeouts in that case.
32  *
33  *      Added CLR_ABORT to clear previously set ABORT string. This has been
34  *      dictated by the HANGUP above as "NO CARRIER" (for example) must be
35  *      an ABORT condition until we know the other host is going to close
36  *      the connection for call back. As soon as we have completed the
37  *      first stage of the call back sequence, "NO CARRIER" is a valid, non
38  *      fatal string. As soon as we got called back (probably get "CONNECT"),
39  *      we should re-arm the ABORT "NO CARRIER". Hence the CLR_ABORT command.
40  *      Note that CLR_ABORT packs the abort_strings[] array so that we do not
41  *      have unused entries not being reclaimed.
42  *
43  *      In the same vein as above, added CLR_REPORT keyword.
44  *
45  *      Allow for comments. Line starting with '#' are comments and are
46  *      ignored. If a '#' is to be expected as the first character, the
47  *      expect string must be quoted.
48  *
49  *
50  *		Francis Demierre <Francis@SwissMail.Com>
51  * 		Thu May 15 17:15:40 MET DST 1997
52  *
53  *
54  *      Added -r "report file" switch & REPORT keyword.
55  *              Robert Geer <bgeer@xmission.com>
56  *
57  *      Added -s "use stderr" and -S "don't use syslog" switches.
58  *              June 18, 1997
59  *              Karl O. Pinc <kop@meme.com>
60  *
61  *
62  *	Added -e "echo" switch & ECHO keyword
63  *		Dick Streefland <dicks@tasking.nl>
64  *
65  *
66  *	Considerable updates and modifications by
67  *		Al Longyear <longyear@pobox.com>
68  *		Paul Mackerras <paulus@cs.anu.edu.au>
69  *
70  *
71  *	The original author is:
72  *
73  *		Karl Fox <karl@MorningStar.Com>
74  *		Morning Star Technologies, Inc.
75  *		1760 Zollinger Road
76  *		Columbus, OH  43221
77  *		(614)451-1883
78  *
79  *
80  */
81 
82 #ifndef lint
83 #if 0
84 static char rcsid[] = "Id: chat.c,v 1.19 1998/03/24 23:57:48 paulus Exp $";
85 #else
86 static char rcsid[] = "$OpenBSD: chat.c,v 1.12 1999/12/02 02:32:29 d Exp $";
87 #endif
88 #endif
89 
90 #include <stdio.h>
91 #include <ctype.h>
92 #include <time.h>
93 #include <fcntl.h>
94 #include <signal.h>
95 #include <errno.h>
96 #include <string.h>
97 #include <stdlib.h>
98 #include <unistd.h>
99 #include <sys/types.h>
100 #include <sys/stat.h>
101 #include <syslog.h>
102 
103 #ifndef TERMIO
104 #undef	TERMIOS
105 #define TERMIOS
106 #endif
107 
108 #ifdef TERMIO
109 #include <termio.h>
110 #endif
111 #ifdef TERMIOS
112 #include <termios.h>
113 #endif
114 
115 #define	STR_LEN	1024
116 
117 #ifndef SIGTYPE
118 #define SIGTYPE void
119 #endif
120 
121 #undef __P
122 #undef __V
123 
124 #ifdef __STDC__
125 #include <stdarg.h>
126 #define __V(x)	x
127 #define __P(x)	x
128 #else
129 #include <varargs.h>
130 #define __V(x)	(va_alist) va_dcl
131 #define __P(x)	()
132 #define const
133 #endif
134 
135 #ifndef O_NONBLOCK
136 #define O_NONBLOCK	O_NDELAY
137 #endif
138 
139 #ifdef SUNOS
140 extern int sys_nerr;
141 extern char *sys_errlist[];
142 #define memmove(to, from, n)	bcopy(from, to, n)
143 #define strerror(n)		((unsigned)(n) < sys_nerr? sys_errlist[(n)] :\
144 				 "unknown error")
145 #endif
146 
147 #define	MAX_ABORTS		50
148 #define	MAX_REPORTS		50
149 #define	DEFAULT_CHAT_TIMEOUT	45
150 
151 int echo          = 0;
152 int verbose       = 0;
153 int to_log        = 1;
154 int to_stderr     = 0;
155 int Verbose       = 0;
156 int quiet         = 0;
157 int report        = 0;
158 int exit_code     = 0;
159 FILE* report_fp   = (FILE *) 0;
160 char *report_file = (char *) 0;
161 char *chat_file   = (char *) 0;
162 char *phone_num   = (char *) 0;
163 char *phone_num2  = (char *) 0;
164 int timeout       = DEFAULT_CHAT_TIMEOUT;
165 
166 int have_tty_parameters = 0;
167 
168 extern char *__progname;
169 
170 #ifdef TERMIO
171 #define term_parms struct termio
172 #define get_term_param(param) ioctl(0, TCGETA, param)
173 #define set_term_param(param) ioctl(0, TCSETA, param)
174 struct termio saved_tty_parameters;
175 #endif
176 
177 #ifdef TERMIOS
178 #define term_parms struct termios
179 #define get_term_param(param) tcgetattr(0, param)
180 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
181 struct termios saved_tty_parameters;
182 #endif
183 
184 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
185 	fail_buffer[50];
186 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
187 int clear_abort_next = 0;
188 
189 char *report_string[MAX_REPORTS] ;
190 char  report_buffer[50] ;
191 int n_reports = 0, report_next = 0, report_gathering = 0 ;
192 int clear_report_next = 0;
193 
194 int say_next = 0, hup_next = 0;
195 
196 void *dup_mem __P((void *b, size_t c));
197 void *copy_of __P((char *s));
198 void usage __P((void));
199 void logf __P((const char *fmt, ...));
200 void fatal __P((int code, const char *fmt, ...));
201 SIGTYPE sigalrm __P((int signo));
202 SIGTYPE sigint __P((int signo));
203 SIGTYPE sigterm __P((int signo));
204 SIGTYPE sighup __P((int signo));
205 void unalarm __P((void));
206 void init __P((void));
207 void set_tty_parameters __P((void));
208 void echo_stderr __P((int));
209 void break_sequence __P((void));
210 void terminate __P((int status));
211 void do_file __P((char *chat_file));
212 int  get_string __P((register char *string));
213 int  put_string __P((register char *s));
214 int  write_char __P((int c));
215 int  put_char __P((int c));
216 int  get_char __P((void));
217 void chat_send __P((register char *s));
218 char *character __P((int c));
219 void chat_expect __P((register char *s));
220 char *clean __P((register char *s, int sending));
221 void break_sequence __P((void));
222 void terminate __P((int status));
223 void pack_array __P((char **array, int end));
224 char *expect_strtok __P((char *, char *));
225 int vfmtmsg __P((char *, int, const char *, va_list));	/* vsprintf++ */
226 
227 int main __P((int, char *[]));
228 
229 void *dup_mem(b, c)
230 void *b;
231 size_t c;
232 {
233     void *ans = malloc (c);
234     if (!ans)
235 	fatal(2, "memory error!");
236 
237     memcpy (ans, b, c);
238     return ans;
239 }
240 
241 void *copy_of (s)
242 char *s;
243 {
244     return dup_mem (s, strlen (s) + 1);
245 }
246 
247 /*
248  * chat [ -v ] [-T number] [-U number] [ -t timeout ] [ -f chat-file ] \
249  * [ -r report-file ] \
250  *		[...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
251  *
252  *	Perform a UUCP-dialer-like chat script on stdin and stdout.
253  */
254 int
255 main(argc, argv)
256      int argc;
257      char **argv;
258 {
259     int option;
260 
261     tzset();
262 
263     while ((option = getopt(argc, argv, "esSvVt:r:f:T:U:")) != -1) {
264 	switch (option) {
265 	case 'e':
266 	    ++echo;
267 	    break;
268 
269 	case 'v':
270 	    ++verbose;
271 	    break;
272 
273 	case 'V':
274 	    ++Verbose;
275 	    break;
276 
277 	case 's':
278 	    ++to_stderr;
279 	    break;
280 
281 	case 'S':
282 	    to_log = 0;
283 	    break;
284 
285 	case 'f':
286 	    chat_file = copy_of(optarg);
287 	    break;
288 
289 	case 't':
290 	    timeout = atoi(optarg);
291 	    break;
292 
293 	case 'r':
294 	    if (report_fp != NULL)
295 		fclose (report_fp);
296 	    report_file = copy_of (optarg);
297 	    report_fp   = fopen (report_file, "a");
298 	    if (report_fp != NULL) {
299 		if (verbose)
300 		    fprintf (report_fp, "Opening \"%s\"...\n",
301 			     report_file);
302 		report = 1;
303 	    }
304 	    break;
305 
306 	case 'T':
307 	    phone_num = copy_of(optarg);
308 	    break;
309 
310 	case 'U':
311 	    phone_num2 = copy_of(optarg);
312 	    break;
313 
314 	case ':':
315 	    fprintf(stderr, "Option -%c requires an argument\n",
316 		optopt);
317 
318 	default:
319 	    usage();
320 	    break;
321 	}
322     }
323     argc -= optind;
324     argv += optind;
325 /*
326  * Default the report file to the stderr location
327  */
328     if (report_fp == NULL)
329 	report_fp = stderr;
330 
331     if (to_log) {
332 #ifdef ultrix
333 	openlog("chat", LOG_PID);
334 #else
335 	openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
336 
337 	if (verbose)
338 	    setlogmask(LOG_UPTO(LOG_INFO));
339 	else
340 	    setlogmask(LOG_UPTO(LOG_WARNING));
341 #endif
342     }
343 
344     init();
345 
346     if (chat_file != NULL) {
347 	if (argc > 0)
348 	    usage();
349 	else
350 	    do_file (chat_file);
351     } else {
352 	while (argc-- > 0) {
353 	    chat_expect(*argv++);
354 
355 	    if (argc-- > 0) {
356 		chat_send(*argv++);
357 	    }
358 	}
359     }
360 
361     terminate(0);
362     return 0;
363 }
364 
365 /*
366  *  Process a chat script when read from a file.
367  */
368 
369 void do_file (chat_file)
370 char *chat_file;
371 {
372     int linect, sendflg;
373     char *sp, *arg, quote;
374     char buf [STR_LEN];
375     FILE *cfp;
376 
377     cfp = fopen (chat_file, "r");
378     if (cfp == NULL)
379 	fatal(1, "%s -- open failed: %m", chat_file);
380 
381     linect = 0;
382     sendflg = 0;
383 
384     while (fgets(buf, STR_LEN, cfp) != NULL) {
385 	sp = strchr (buf, '\n');
386 	if (sp)
387 	    *sp = '\0';
388 
389 	linect++;
390 	sp = buf;
391 
392         /* lines starting with '#' are comments. If a real '#'
393            is to be expected, it should be quoted .... */
394         if ( *sp == '#' )
395 	    continue;
396 
397 	while (*sp != '\0') {
398 	    if (*sp == ' ' || *sp == '\t') {
399 		++sp;
400 		continue;
401 	    }
402 
403 	    if (*sp == '"' || *sp == '\'') {
404 		quote = *sp++;
405 		arg = sp;
406 		while (*sp != quote) {
407 		    if (*sp == '\0')
408 			fatal(1, "unterminated quote (line %d)", linect);
409 
410 		    if (*sp++ == '\\') {
411 			if (*sp != '\0')
412 			    ++sp;
413 		    }
414 		}
415 	    }
416 	    else {
417 		arg = sp;
418 		while (*sp != '\0' && *sp != ' ' && *sp != '\t')
419 		    ++sp;
420 	    }
421 
422 	    if (*sp != '\0')
423 		*sp++ = '\0';
424 
425 	    if (sendflg)
426 		chat_send (arg);
427 	    else
428 		chat_expect (arg);
429 	    sendflg = !sendflg;
430 	}
431     }
432     fclose (cfp);
433 }
434 
435 /*
436  *	We got an error parsing the command line.
437  */
438 void usage()
439 {
440     fprintf(stderr, "\
441 Usage: %s [-e] [-s] [-S] [-v] [-V] [-t timeout] [-r report-file]\n\
442      [-T phone-number] [-U phone-number2] {-f chat-file | chat-script}\n",
443      __progname);
444     exit(1);
445 }
446 
447 char line[1024];
448 
449 /*
450  * Send a message to syslog and/or stderr.
451  */
452 void logf __V((const char *fmt, ...))
453 {
454     va_list args;
455 
456 #ifdef __STDC__
457     va_start(args, fmt);
458 #else
459     char *fmt;
460     va_start(args);
461     fmt = va_arg(args, char *);
462 #endif
463 
464     vfmtmsg(line, sizeof(line), fmt, args);
465     if (to_log)
466 	syslog(LOG_INFO, "%s", line);
467     if (to_stderr)
468 	fprintf(stderr, "%s\n", line);
469 }
470 
471 /*
472  *	Print an error message and terminate.
473  */
474 
475 void fatal __V((int code, const char *fmt, ...))
476 {
477     va_list args;
478 
479 #ifdef __STDC__
480     va_start(args, fmt);
481 #else
482     int code;
483     char *fmt;
484     va_start(args);
485     code = va_arg(args, int);
486     fmt = va_arg(args, char *);
487 #endif
488 
489     vfmtmsg(line, sizeof(line), fmt, args);
490     if (to_log)
491 	syslog(LOG_ERR, "%s", line);
492     if (to_stderr)
493 	fprintf(stderr, "%s\n", line);
494     terminate(code);
495 }
496 
497 int alarmed = 0;
498 
499 SIGTYPE sigalrm(signo)
500 int signo;
501 {
502     int flags;
503 
504     alarm(1);
505     alarmed = 1;		/* Reset alarm to avoid race window */
506     signal(SIGALRM, sigalrm);	/* that can cause hanging in read() */
507 
508     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
509 	fatal(2, "Can't get file mode flags on stdin: %m");
510 
511     if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
512 	fatal(2, "Can't set file mode flags on stdin: %m");
513 
514     if (verbose)
515 	logf("alarm");
516 }
517 
518 void unalarm()
519 {
520     int flags;
521 
522     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
523 	fatal(2, "Can't get file mode flags on stdin: %m");
524 
525     if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
526 	fatal(2, "Can't set file mode flags on stdin: %m");
527 }
528 
529 SIGTYPE sigint(signo)
530 int signo;
531 {
532     fatal(2, "SIGINT");
533 }
534 
535 SIGTYPE sigterm(signo)
536 int signo;
537 {
538     fatal(2, "SIGTERM");
539 }
540 
541 SIGTYPE sighup(signo)
542 int signo;
543 {
544     fatal(2, "SIGHUP");
545 }
546 
547 void init()
548 {
549     signal(SIGINT, sigint);
550     signal(SIGTERM, sigterm);
551     signal(SIGHUP, sighup);
552 
553     set_tty_parameters();
554     signal(SIGALRM, sigalrm);
555     alarm(0);
556     alarmed = 0;
557 }
558 
559 void set_tty_parameters()
560 {
561 #if defined(get_term_param)
562     term_parms t;
563 
564     if (get_term_param (&t) < 0)
565 	fatal(2, "Can't get terminal parameters: %m");
566 
567     saved_tty_parameters = t;
568     have_tty_parameters  = 1;
569 
570     t.c_iflag     |= IGNBRK | ISTRIP | IGNPAR;
571     t.c_oflag      = 0;
572     t.c_lflag      = 0;
573     t.c_cc[VERASE] =
574     t.c_cc[VKILL]  = 0;
575     t.c_cc[VMIN]   = 1;
576     t.c_cc[VTIME]  = 0;
577 
578     if (set_term_param (&t) < 0)
579 	fatal(2, "Can't set terminal parameters: %m");
580 #endif
581 }
582 
583 void break_sequence()
584 {
585 #ifdef TERMIOS
586     tcsendbreak (0, 0);
587 #endif
588 }
589 
590 void terminate(status)
591 int status;
592 {
593     echo_stderr(-1);
594     if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
595 /*
596  * Allow the last of the report string to be gathered before we terminate.
597  */
598 	if (report_gathering) {
599 	    int c, rep_len;
600 
601 	    rep_len = strlen(report_buffer);
602 	    while (rep_len + 1 <= sizeof(report_buffer)) {
603 		alarm(1);
604 		c = get_char();
605 		alarm(0);
606 		if (c < 0 || iscntrl(c))
607 		    break;
608 		report_buffer[rep_len] = c;
609 		++rep_len;
610 	    }
611 	    report_buffer[rep_len] = 0;
612 	    fprintf (report_fp, "chat:  %s\n", report_buffer);
613 	}
614 	if (verbose)
615 	    fprintf (report_fp, "Closing \"%s\".\n", report_file);
616 	fclose (report_fp);
617 	report_fp = (FILE *) NULL;
618     }
619 
620 #if defined(get_term_param)
621     if (have_tty_parameters) {
622 	if (set_term_param (&saved_tty_parameters) < 0)
623 	    fatal(2, "Can't restore terminal parameters: %m");
624     }
625 #endif
626 
627     exit(status);
628 }
629 
630 /*
631  *	'Clean up' this string.
632  */
633 char *clean(s, sending)
634 register char *s;
635 int sending;  /* set to 1 when sending (putting) this string. */
636 {
637     char *ret, *t, cur_chr;
638     int new_length;
639     register char *s1, *phchar;
640     int add_return = sending;
641 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
642 
643     /* Overestimate new length: */
644     new_length = 0;
645     for (t = s; *t; t++)
646 	if (*t == '^' && *(t+1) != '\0') {
647 	    t++;
648 	    new_length++;
649 	} else if (*t != '\\') {
650 	    new_length++;
651 	} else {
652 	    t++;
653 	    switch (*t) {
654 	    case 'c':
655 	    case 'b':
656 	    case 'r':
657 	    case 'n':
658 	    case 's':
659 	    case 't':
660 		new_length++;
661 		break;
662 	    case 'K':
663 	    case 'p':
664 	    case 'd':
665 	    case '\0':
666 	    case '\\':
667 	    case 'N':
668 		new_length += 2;
669 		break;
670 	    case 'T':
671 		new_length += sending && phone_num ? strlen(phone_num) : 2;
672 		break;
673 	    case 'U':
674 		new_length += sending && phone_num2 ? strlen(phone_num2) : 2;
675 		break;
676 	    default:
677 		if (isoctal(*t)) {
678 		    t++;
679 		    if (isoctal(*t)) {
680 			t++;
681 			if (isoctal(*t))
682 			    t++;
683 		    }
684 		}
685 		t--;
686 		new_length += 2;	/* Could become \\ */
687 	    }
688 	    if (*t == '\0')
689 		break;
690 	}
691 
692     new_length += 3;	/* \r and two nuls */
693 
694     ret = (char *)malloc(new_length);
695 
696     s1 = ret;
697     while (*s) {
698 	cur_chr = *s++;
699 	if (cur_chr == '^') {
700 	    cur_chr = *s++;
701 	    if (cur_chr == '\0') {
702 		*s1++ = '^';
703 		break;
704 	    }
705 	    cur_chr &= 0x1F;
706 	    if (cur_chr != 0) {
707 		*s1++ = cur_chr;
708 	    }
709 	    continue;
710 	}
711 
712 	if (cur_chr != '\\') {
713 	    *s1++ = cur_chr;
714 	    continue;
715 	}
716 
717 	cur_chr = *s++;
718 	if (cur_chr == '\0') {
719 	    if (sending) {
720 		*s1++ = '\\';
721 		*s1++ = '\\';
722 	    }
723 	    break;
724 	}
725 
726 	switch (cur_chr) {
727 	case 'b':
728 	    *s1++ = '\b';
729 	    break;
730 
731 	case 'c':
732 	    if (sending && *s == '\0')
733 		add_return = 0;
734 	    else
735 		*s1++ = cur_chr;
736 	    break;
737 
738 	case '\\':
739 	case 'K':
740 	case 'p':
741 	case 'd':
742 	    if (sending)
743 		*s1++ = '\\';
744 
745 	    *s1++ = cur_chr;
746 	    break;
747 
748 	case 'T':
749 	    if (sending && phone_num) {
750 		for ( phchar = phone_num; *phchar != '\0'; phchar++)
751 		    *s1++ = *phchar;
752 	    }
753 	    else {
754 		*s1++ = '\\';
755 		*s1++ = 'T';
756 	    }
757 	    break;
758 
759 	case 'U':
760 	    if (sending && phone_num2) {
761 		for ( phchar = phone_num2; *phchar != '\0'; phchar++)
762 		    *s1++ = *phchar;
763 	    }
764 	    else {
765 		*s1++ = '\\';
766 		*s1++ = 'U';
767 	    }
768 	    break;
769 
770 	case 'q':
771 	    quiet = 1;
772 	    break;
773 
774 	case 'r':
775 	    *s1++ = '\r';
776 	    break;
777 
778 	case 'n':
779 	    *s1++ = '\n';
780 	    break;
781 
782 	case 's':
783 	    *s1++ = ' ';
784 	    break;
785 
786 	case 't':
787 	    *s1++ = '\t';
788 	    break;
789 
790 	case 'N':
791 	    if (sending) {
792 		*s1++ = '\\';
793 		*s1++ = '\0';
794 	    }
795 	    else
796 		*s1++ = 'N';
797 	    break;
798 
799 	default:
800 	    if (isoctal (cur_chr)) {
801 		cur_chr &= 0x07;
802 		if (isoctal (*s)) {
803 		    cur_chr <<= 3;
804 		    cur_chr |= *s++ - '0';
805 		    if (isoctal (*s)) {
806 			cur_chr <<= 3;
807 			cur_chr |= *s++ - '0';
808 		    }
809 		}
810 
811 		if (cur_chr != 0 || sending) {
812 		    if (sending && (cur_chr == '\\' || cur_chr == 0))
813 			*s1++ = '\\';
814 		    *s1++ = cur_chr;
815 		}
816 		break;
817 	    }
818 
819 	    if (sending)
820 		*s1++ = '\\';
821 	    *s1++ = cur_chr;
822 	    break;
823 	}
824     }
825 
826     if (add_return)
827 	*s1++ = '\r';
828 
829     *s1++ = '\0'; /* guarantee closure */
830     *s1++ = '\0'; /* terminate the string */
831 
832 #ifdef DEBUG
833     fprintf(stderr, "clean(): guessed %d and used %d\n", new_length, s1-ret);
834 #endif
835     if (new_length < s1 - ret)
836 	logf("clean(): new_length too short! %d < %d: \"%s\" -> \"%s\"",
837 	    new_length, s1 - ret, s, ret);
838 
839     return ret;
840 }
841 
842 /*
843  * A modified version of 'strtok'. This version skips \ sequences.
844  */
845 
846 char *expect_strtok (s, term)
847      char *s, *term;
848 {
849     static  char *str   = "";
850     int	    escape_flag = 0;
851     char   *result;
852 
853 /*
854  * If a string was specified then do initial processing.
855  */
856     if (s)
857 	str = s;
858 
859 /*
860  * If this is the escape flag then reset it and ignore the character.
861  */
862     if (*str)
863 	result = str;
864     else
865 	result = (char *) 0;
866 
867     while (*str) {
868 	if (escape_flag) {
869 	    escape_flag = 0;
870 	    ++str;
871 	    continue;
872 	}
873 
874 	if (*str == '\\') {
875 	    ++str;
876 	    escape_flag = 1;
877 	    continue;
878 	}
879 
880 /*
881  * If this is not in the termination string, continue.
882  */
883 	if (strchr (term, *str) == (char *) 0) {
884 	    ++str;
885 	    continue;
886 	}
887 
888 /*
889  * This is the terminator. Mark the end of the string and stop.
890  */
891 	*str++ = '\0';
892 	break;
893     }
894     return (result);
895 }
896 
897 /*
898  * Process the expect string
899  */
900 
901 void chat_expect (s)
902 char *s;
903 {
904     char *expect;
905     char *reply;
906 
907     if (strcmp(s, "HANGUP") == 0) {
908 	++hup_next;
909         return;
910     }
911 
912     if (strcmp(s, "ABORT") == 0) {
913 	++abort_next;
914 	return;
915     }
916 
917     if (strcmp(s, "CLR_ABORT") == 0) {
918 	++clear_abort_next;
919 	return;
920     }
921 
922     if (strcmp(s, "REPORT") == 0) {
923 	++report_next;
924 	return;
925     }
926 
927     if (strcmp(s, "CLR_REPORT") == 0) {
928 	++clear_report_next;
929 	return;
930     }
931 
932     if (strcmp(s, "TIMEOUT") == 0) {
933 	++timeout_next;
934 	return;
935     }
936 
937     if (strcmp(s, "ECHO") == 0) {
938 	++echo_next;
939 	return;
940     }
941 
942     if (strcmp(s, "SAY") == 0) {
943 	++say_next;
944 	return;
945     }
946 
947 /*
948  * Fetch the expect and reply string.
949  */
950     for (;;) {
951 	expect = expect_strtok (s, "-");
952 	s      = (char *) 0;
953 
954 	if (expect == (char *) 0)
955 	    return;
956 
957 	reply = expect_strtok (s, "-");
958 
959 /*
960  * Handle the expect string. If successful then exit.
961  */
962 	if (get_string (expect))
963 	    return;
964 
965 /*
966  * If there is a sub-reply string then send it. Otherwise any condition
967  * is terminal.
968  */
969 	if (reply == (char *) 0 || exit_code != 3)
970 	    break;
971 
972 	chat_send (reply);
973     }
974 
975 /*
976  * The expectation did not occur. This is terminal.
977  */
978     if (fail_reason)
979 	logf("Failed (%s)", fail_reason);
980     else
981 	logf("Failed");
982     terminate(exit_code);
983 }
984 
985 /*
986  * Translate the input character to the appropriate string for printing
987  * the data.
988  */
989 
990 char *character(c)
991 int c;
992 {
993     static char string[10];
994     char *meta;
995 
996     meta = (c & 0x80) ? "M-" : "";
997     c &= 0x7F;
998 
999     if (c < 32)
1000 	sprintf(string, "%s^%c", meta, (int)c + '@');
1001     else if (c == 127)
1002 	sprintf(string, "%s^?", meta);
1003     else
1004 	sprintf(string, "%s%c", meta, c);
1005 
1006     return (string);
1007 }
1008 
1009 /*
1010  *  process the reply string
1011  */
1012 void chat_send (s)
1013 register char *s;
1014 {
1015     if (say_next) {
1016 	say_next = 0;
1017 	s = clean(s,0);
1018 	write(2, s, strlen(s));
1019         free(s);
1020 	return;
1021     }
1022 
1023     if (hup_next) {
1024         hup_next = 0;
1025 	if (strcmp(s, "OFF") == 0)
1026            signal(SIGHUP, SIG_IGN);
1027         else
1028            signal(SIGHUP, sighup);
1029         return;
1030     }
1031 
1032     if (echo_next) {
1033 	echo_next = 0;
1034 	echo = (strcmp(s, "ON") == 0);
1035 	return;
1036     }
1037 
1038     if (abort_next) {
1039 	char *s1;
1040 
1041 	abort_next = 0;
1042 
1043 	if (n_aborts >= MAX_ABORTS)
1044 	    fatal(2, "Too many ABORT strings");
1045 
1046 	s1 = clean(s, 0);
1047 
1048 	if (strlen(s1) > strlen(s)
1049 	    || strlen(s1) + 1 > sizeof(fail_buffer))
1050 	    fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1051 
1052 	abort_string[n_aborts++] = s1;
1053 
1054 	if (verbose)
1055 	    logf("abort on (%v)", s);
1056 	return;
1057     }
1058 
1059     if (clear_abort_next) {
1060 	char *s1;
1061 	int   i;
1062         int   old_max;
1063 	int   pack = 0;
1064 
1065 	clear_abort_next = 0;
1066 
1067 	s1 = clean(s, 0);
1068 
1069 	if (strlen(s1) > strlen(s)
1070 	    || strlen(s1) + 1 > sizeof(fail_buffer))
1071 	    fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1072 
1073         old_max = n_aborts;
1074 	for (i=0; i < n_aborts; i++) {
1075 	    if ( strcmp(s1,abort_string[i]) == 0 ) {
1076 		free(abort_string[i]);
1077 		abort_string[i] = NULL;
1078 		pack++;
1079 		n_aborts--;
1080 		if (verbose)
1081 		    logf("clear abort on (%v)", s);
1082 	    }
1083 	}
1084         free(s1);
1085 	if (pack)
1086 	    pack_array(abort_string,old_max);
1087 	return;
1088     }
1089 
1090     if (report_next) {
1091 	char *s1;
1092 
1093 	report_next = 0;
1094 	if (n_reports >= MAX_REPORTS)
1095 	    fatal(2, "Too many REPORT strings");
1096 
1097 	s1 = clean(s, 0);
1098 
1099 	if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1100 	    fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1101 
1102 	report_string[n_reports++] = s1;
1103 
1104 	if (verbose)
1105 	    logf("report (%v)", s);
1106 	return;
1107     }
1108 
1109     if (clear_report_next) {
1110 	char *s1;
1111 	int   i;
1112 	int   old_max;
1113 	int   pack = 0;
1114 
1115 	clear_report_next = 0;
1116 
1117 	s1 = clean(s, 0);
1118 
1119 	if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1120 	    fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1121 
1122 	old_max = n_reports;
1123 	for (i=0; i < n_reports; i++) {
1124 	    if ( strcmp(s1,report_string[i]) == 0 ) {
1125 		free(report_string[i]);
1126 		report_string[i] = NULL;
1127 		pack++;
1128 		n_reports--;
1129 		if (verbose)
1130 		    logf("clear report (%v)", s);
1131 	    }
1132 	}
1133         free(s1);
1134         if (pack)
1135 	    pack_array(report_string,old_max);
1136 
1137 	return;
1138     }
1139 
1140     if (timeout_next) {
1141 	timeout_next = 0;
1142 	timeout = atoi(s);
1143 
1144 	if (timeout <= 0)
1145 	    timeout = DEFAULT_CHAT_TIMEOUT;
1146 
1147 	if (verbose)
1148 	    logf("timeout set to %d seconds", timeout);
1149 
1150 	return;
1151     }
1152 
1153     if (strcmp(s, "EOT") == 0)
1154 	s = "^D\\c";
1155     else if (strcmp(s, "BREAK") == 0)
1156 	s = "\\K\\c";
1157 
1158     if (!put_string(s))
1159 	fatal(1, "Failed");
1160 }
1161 
1162 int get_char()
1163 {
1164     int status;
1165     char c;
1166 
1167     status = read(0, &c, 1);
1168 
1169     switch (status) {
1170     case 1:
1171 	return ((int)c & 0x7F);
1172 
1173     default:
1174 	logf("warning: read() on stdin returned %d", status);
1175 
1176     case -1:
1177 	if ((status = fcntl(0, F_GETFL, 0)) == -1)
1178 	    fatal(2, "Can't get file mode flags on stdin: %m");
1179 
1180 	if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1181 	    fatal(2, "Can't set file mode flags on stdin: %m");
1182 
1183 	return (-1);
1184     }
1185 }
1186 
1187 int put_char(c)
1188 int c;
1189 {
1190     int status;
1191     char ch = c;
1192 
1193     usleep(10000);		/* inter-character typing delay (?) */
1194 
1195     status = write(1, &ch, 1);
1196 
1197     switch (status) {
1198     case 1:
1199 	return (0);
1200 
1201     default:
1202 	logf("warning: write() on stdout returned %d", status);
1203 
1204     case -1:
1205 	if ((status = fcntl(0, F_GETFL, 0)) == -1)
1206 	    fatal(2, "Can't get file mode flags on stdin, %m");
1207 
1208 	if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1209 	    fatal(2, "Can't set file mode flags on stdin: %m");
1210 
1211 	return (-1);
1212     }
1213 }
1214 
1215 int write_char (c)
1216 int c;
1217 {
1218     if (alarmed || put_char(c) < 0) {
1219 	alarm(0);
1220 	alarmed = 0;
1221 
1222 	if (verbose) {
1223 	    if (errno == EINTR || errno == EWOULDBLOCK)
1224 		logf(" -- write timed out");
1225 	    else
1226 		logf(" -- write failed: %m");
1227 	}
1228 	return (0);
1229     }
1230     return (1);
1231 }
1232 
1233 int put_string (s)
1234 register char *s;
1235 {
1236     quiet = 0;
1237     s = clean(s, 1);
1238 
1239     if (verbose) {
1240 	if (quiet)
1241 	    logf("send (??????)");
1242 	else
1243 	    logf("send (%v)", s);
1244     }
1245 
1246     alarm(timeout); alarmed = 0;
1247 
1248     while (*s) {
1249 	register char c = *s++;
1250 
1251 	if (c != '\\') {
1252 	    if (!write_char (c))
1253 		return 0;
1254 	    continue;
1255 	}
1256 
1257 	c = *s++;
1258 	switch (c) {
1259 	case 'd':
1260 	    sleep(1);
1261 	    break;
1262 
1263 	case 'K':
1264 	    break_sequence();
1265 	    break;
1266 
1267 	case 'p':
1268 	    usleep(10000); 	/* 1/100th of a second (arg is microseconds) */
1269 	    break;
1270 
1271 	default:
1272 	    if (!write_char (c))
1273 		return 0;
1274 	    break;
1275 	}
1276     }
1277 
1278     alarm(0);
1279     alarmed = 0;
1280     return (1);
1281 }
1282 
1283 /*
1284  *	Echo a character to stderr.
1285  *	When called with -1, a '\n' character is generated when
1286  *	the cursor is not at the beginning of a line.
1287  */
1288 void echo_stderr(n)
1289 int n;
1290 {
1291     static int need_lf;
1292     char *s;
1293 
1294     switch (n) {
1295     case '\r':		/* ignore '\r' */
1296 	break;
1297     case -1:
1298 	if (need_lf == 0)
1299 	    break;
1300 	/* fall through */
1301     case '\n':
1302 	write(2, "\n", 1);
1303 	need_lf = 0;
1304 	break;
1305     default:
1306 	s = character(n);
1307 	write(2, s, strlen(s));
1308 	need_lf = 1;
1309 	break;
1310     }
1311 }
1312 
1313 /*
1314  *	'Wait for' this string to appear on this file descriptor.
1315  */
1316 int get_string(string)
1317 register char *string;
1318 {
1319     char temp[STR_LEN];
1320     int c, printed = 0, len, minlen;
1321     register char *s = temp, *end = s + STR_LEN;
1322     char *logged = temp;
1323 
1324     fail_reason = (char *)0;
1325     string = clean(string, 0);
1326     len = strlen(string);
1327     minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1328 
1329     if (verbose)
1330 	logf("expect (%v)", string);
1331 
1332     if (len > STR_LEN) {
1333 	logf("expect string is too long");
1334 	exit_code = 1;
1335 	return 0;
1336     }
1337 
1338     if (len == 0) {
1339 	if (verbose)
1340 	    logf("got it");
1341 	return (1);
1342     }
1343 
1344     alarm(timeout);
1345     alarmed = 0;
1346 
1347     while ( ! alarmed && (c = get_char()) >= 0) {
1348 	int n, abort_len, report_len;
1349 
1350 	if (echo)
1351 	    echo_stderr(c);
1352 	if (verbose && c == '\n') {
1353 	    if (s == logged)
1354 		logf("");	/* blank line */
1355 	    else
1356 		logf("%0.*v", s - logged, logged);
1357 	    logged = s + 1;
1358 	}
1359 
1360 	*s++ = c;
1361 
1362 	if (verbose && s >= logged + 80) {
1363 	    logf("%0.*v", s - logged, logged);
1364 	    logged = s;
1365 	}
1366 
1367 	if (Verbose) {
1368 	   if (c == '\n')
1369 	       fputc( '\n', stderr );
1370 	   else if (c != '\r')
1371 	       fprintf( stderr, "%s", character(c) );
1372 	}
1373 
1374 	if (!report_gathering) {
1375 	    for (n = 0; n < n_reports; ++n) {
1376 		if ((report_string[n] != (char*) NULL) &&
1377 		    s - temp >= (report_len = strlen(report_string[n])) &&
1378 		    strncmp(s - report_len, report_string[n], report_len) == 0) {
1379 		    time_t time_now   = time ((time_t*) NULL);
1380 		    struct tm* tm_now = localtime (&time_now);
1381 
1382 		    strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1383 		    strcat (report_buffer, report_string[n]);
1384 
1385 		    report_string[n] = (char *) NULL;
1386 		    report_gathering = 1;
1387 		    break;
1388 		}
1389 	    }
1390 	}
1391 	else {
1392 	    if (!iscntrl (c)) {
1393 		int rep_len = strlen (report_buffer);
1394 		report_buffer[rep_len]     = c;
1395 		report_buffer[rep_len + 1] = '\0';
1396 	    }
1397 	    else {
1398 		report_gathering = 0;
1399 		fprintf (report_fp, "chat:  %s\n", report_buffer);
1400 	    }
1401 	}
1402 
1403 	if (s - temp >= len &&
1404 	    c == string[len - 1] &&
1405 	    strncmp(s - len, string, len) == 0) {
1406 	    if (verbose) {
1407 		if (s > logged)
1408 		    logf("%0.*v", s - logged, logged);
1409 		logf(" -- got it\n");
1410 	    }
1411 
1412 	    alarm(0);
1413 	    alarmed = 0;
1414 	    return (1);
1415 	}
1416 
1417 	for (n = 0; n < n_aborts; ++n) {
1418 	    if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1419 		strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1420 		if (verbose) {
1421 		    if (s > logged)
1422 			logf("%0.*v", s - logged, logged);
1423 		    logf(" -- failed");
1424 		}
1425 
1426 		alarm(0);
1427 		alarmed = 0;
1428 		exit_code = n + 4;
1429 		strcpy(fail_reason = fail_buffer, abort_string[n]);
1430 		return (0);
1431 	    }
1432 	}
1433 
1434 	if (s >= end) {
1435 	    if (logged < s - minlen) {
1436 		logf("%0.*v", s - logged, logged);
1437 		logged = s;
1438 	    }
1439 	    s -= minlen;
1440 	    memmove(temp, s, minlen);
1441 	    logged = temp + (logged - s);
1442 	    s = temp + minlen;
1443 	}
1444 
1445 	if (alarmed && verbose)
1446 	    logf("warning: alarm synchronization problem");
1447     }
1448 
1449     alarm(0);
1450 
1451     if (verbose && printed) {
1452 	if (alarmed)
1453 	    logf(" -- read timed out");
1454 	else
1455 	    logf(" -- read failed: %m");
1456     }
1457 
1458     exit_code = 3;
1459     alarmed   = 0;
1460     return (0);
1461 }
1462 
1463 /*
1464  * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1465  */
1466 #ifdef SOL2
1467 #include <sys/param.h>
1468 #if MAXUID > 65536		/* then this is Solaris 2.6 or later */
1469 #undef NO_USLEEP
1470 #endif
1471 #endif /* SOL2 */
1472 
1473 #ifdef NO_USLEEP
1474 #include <sys/types.h>
1475 #include <sys/time.h>
1476 
1477 /*
1478   usleep -- support routine for 4.2BSD system call emulations
1479   last edit:  29-Oct-1984     D A Gwyn
1480   */
1481 
1482 extern int	  select();
1483 
1484 int
1485 usleep( usec )				  /* returns 0 if ok, else -1 */
1486     long		usec;		/* delay in microseconds */
1487 {
1488     static struct {		/* `timeval' */
1489 	long	tv_sec;		/* seconds */
1490 	long	tv_usec;	/* microsecs */
1491     } delay;	    		/* _select() timeout */
1492 
1493     delay.tv_sec  = usec / 1000000L;
1494     delay.tv_usec = usec % 1000000L;
1495 
1496     return select(0, (long *)0, (long *)0, (long *)0, &delay);
1497 }
1498 #endif
1499 
1500 void
1501 pack_array (array, end)
1502     char **array; /* The address of the array of string pointers */
1503     int    end;   /* The index of the next free entry before CLR_ */
1504 {
1505     int i, j;
1506 
1507     for (i = 0; i < end; i++) {
1508 	if (array[i] == NULL) {
1509 	    for (j = i+1; j < end; ++j)
1510 		if (array[j] != NULL)
1511 		    array[i++] = array[j];
1512 	    for (; i < end; ++i)
1513 		array[i] = NULL;
1514 	    break;
1515 	}
1516     }
1517 }
1518 
1519 /*
1520  * vfmtmsg - format a message into a buffer.  Like vsprintf except we
1521  * also specify the length of the output buffer, and we handle the
1522  * %m (error message) format.
1523  * Doesn't do floating-point formats.
1524  * Returns the number of chars put into buf.
1525  */
1526 #define OUTCHAR(c)	(buflen > 0? (--buflen, *buf++ = (c)): 0)
1527 
1528 int
1529 vfmtmsg(buf, buflen, fmt, args)
1530     char *buf;
1531     int buflen;
1532     const char *fmt;
1533     va_list args;
1534 {
1535     int c, i, n;
1536     int width, prec, fillch;
1537     int base, len, neg, quoted;
1538     unsigned long val = 0;
1539     char *str, *buf0;
1540     const char *f;
1541     unsigned char *p;
1542     char num[32];
1543     static char hexchars[] = "0123456789abcdef";
1544 
1545     buf0 = buf;
1546     --buflen;
1547     while (buflen > 0) {
1548 	for (f = fmt; *f != '%' && *f != 0; ++f)
1549 	    ;
1550 	if (f > fmt) {
1551 	    len = f - fmt;
1552 	    if (len > buflen)
1553 		len = buflen;
1554 	    memcpy(buf, fmt, len);
1555 	    buf += len;
1556 	    buflen -= len;
1557 	    fmt = f;
1558 	}
1559 	if (*fmt == 0)
1560 	    break;
1561 	c = *++fmt;
1562 	width = prec = 0;
1563 	fillch = ' ';
1564 	if (c == '0') {
1565 	    fillch = '0';
1566 	    c = *++fmt;
1567 	}
1568 	if (c == '*') {
1569 	    width = va_arg(args, int);
1570 	    c = *++fmt;
1571 	} else {
1572 	    while (isdigit(c)) {
1573 		width = width * 10 + c - '0';
1574 		c = *++fmt;
1575 	    }
1576 	}
1577 	if (c == '.') {
1578 	    c = *++fmt;
1579 	    if (c == '*') {
1580 		prec = va_arg(args, int);
1581 		c = *++fmt;
1582 	    } else {
1583 		while (isdigit(c)) {
1584 		    prec = prec * 10 + c - '0';
1585 		    c = *++fmt;
1586 		}
1587 	    }
1588 	}
1589 	str = 0;
1590 	base = 0;
1591 	neg = 0;
1592 	++fmt;
1593 	switch (c) {
1594 	case 'd':
1595 	    i = va_arg(args, int);
1596 	    if (i < 0) {
1597 		neg = 1;
1598 		val = -i;
1599 	    } else
1600 		val = i;
1601 	    base = 10;
1602 	    break;
1603 	case 'o':
1604 	    val = va_arg(args, unsigned int);
1605 	    base = 8;
1606 	    break;
1607 	case 'x':
1608 	    val = va_arg(args, unsigned int);
1609 	    base = 16;
1610 	    break;
1611 	case 'p':
1612 	    val = (unsigned long) va_arg(args, void *);
1613 	    base = 16;
1614 	    neg = 2;
1615 	    break;
1616 	case 's':
1617 	    str = va_arg(args, char *);
1618 	    break;
1619 	case 'c':
1620 	    num[0] = va_arg(args, int);
1621 	    num[1] = 0;
1622 	    str = num;
1623 	    break;
1624 	case 'm':
1625 	    str = strerror(errno);
1626 	    break;
1627 	case 'v':		/* "visible" string */
1628 	case 'q':		/* quoted string */
1629 	    quoted = c == 'q';
1630 	    p = va_arg(args, unsigned char *);
1631 	    if (fillch == '0' && prec > 0) {
1632 		n = prec;
1633 	    } else {
1634 		n = strlen((char *)p);
1635 		if (prec > 0 && prec < n)
1636 		    n = prec;
1637 	    }
1638 	    while (n > 0 && buflen > 0) {
1639 		c = *p++;
1640 		--n;
1641 		if (!quoted && c >= 0x80) {
1642 		    OUTCHAR('M');
1643 		    OUTCHAR('-');
1644 		    c -= 0x80;
1645 		}
1646 		if (quoted && (c == '"' || c == '\\'))
1647 		    OUTCHAR('\\');
1648 		if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1649 		    if (quoted) {
1650 			OUTCHAR('\\');
1651 			switch (c) {
1652 			case '\t':	OUTCHAR('t');	break;
1653 			case '\n':	OUTCHAR('n');	break;
1654 			case '\b':	OUTCHAR('b');	break;
1655 			case '\f':	OUTCHAR('f');	break;
1656 			default:
1657 			    OUTCHAR('x');
1658 			    OUTCHAR(hexchars[c >> 4]);
1659 			    OUTCHAR(hexchars[c & 0xf]);
1660 			}
1661 		    } else {
1662 			if (c == '\t')
1663 			    OUTCHAR(c);
1664 			else {
1665 			    OUTCHAR('^');
1666 			    OUTCHAR(c ^ 0x40);
1667 			}
1668 		    }
1669 		} else
1670 		    OUTCHAR(c);
1671 	    }
1672 	    continue;
1673 	default:
1674 	    *buf++ = '%';
1675 	    if (c != '%')
1676 		--fmt;		/* so %z outputs %z etc. */
1677 	    --buflen;
1678 	    continue;
1679 	}
1680 	if (base != 0) {
1681 	    str = num + sizeof(num);
1682 	    *--str = 0;
1683 	    while (str > num + neg) {
1684 		*--str = hexchars[val % base];
1685 		val = val / base;
1686 		if (--prec <= 0 && val == 0)
1687 		    break;
1688 	    }
1689 	    switch (neg) {
1690 	    case 1:
1691 		*--str = '-';
1692 		break;
1693 	    case 2:
1694 		*--str = 'x';
1695 		*--str = '0';
1696 		break;
1697 	    }
1698 	    len = num + sizeof(num) - 1 - str;
1699 	} else {
1700 	    len = strlen(str);
1701 	    if (prec > 0 && len > prec)
1702 		len = prec;
1703 	}
1704 	if (width > 0) {
1705 	    if (width > buflen)
1706 		width = buflen;
1707 	    if ((n = width - len) > 0) {
1708 		buflen -= n;
1709 		for (; n > 0; --n)
1710 		    *buf++ = fillch;
1711 	    }
1712 	}
1713 	if (len > buflen)
1714 	    len = buflen;
1715 	memcpy(buf, str, len);
1716 	buf += len;
1717 	buflen -= len;
1718     }
1719     *buf = 0;
1720     return buf - buf0;
1721 }
1722