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