]> git.ozlabs.org Git - ppp.git/blob - chat/chat.c
pppd: Fix variable reference syntax in Makefile.linux
[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     va_end(args);
516 }
517
518 /*
519  *      Print an error message and terminate.
520  */
521
522 void fatal __V((int code, const char *fmt, ...))
523 {
524     va_list args;
525
526 #ifdef __STDC__
527     va_start(args, fmt);
528 #else
529     int code;
530     char *fmt;
531     va_start(args);
532     code = va_arg(args, int);
533     fmt = va_arg(args, char *);
534 #endif
535
536     vfmtmsg(line, sizeof(line), fmt, args);
537     if (to_log)
538         syslog(LOG_ERR, "%s", line);
539     if (to_stderr)
540         fprintf(stderr, "%s\n", line);
541     va_end(args);
542     terminate(code);
543 }
544
545 int alarmed = 0;
546
547 SIGTYPE sigalrm(signo)
548 int signo;
549 {
550     int flags;
551
552     alarm(1);
553     alarmed = 1;                /* Reset alarm to avoid race window */
554     signal(SIGALRM, sigalrm);   /* that can cause hanging in read() */
555
556     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
557         fatal(2, "Can't get file mode flags on stdin: %m");
558
559     if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
560         fatal(2, "Can't set file mode flags on stdin: %m");
561
562     if (verbose)
563         msgf("alarm");
564 }
565
566 void unalarm()
567 {
568     int flags;
569
570     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
571         fatal(2, "Can't get file mode flags on stdin: %m");
572
573     if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
574         fatal(2, "Can't set file mode flags on stdin: %m");
575 }
576
577 SIGTYPE sigint(signo)
578 int signo;
579 {
580     fatal(2, "SIGINT");
581 }
582
583 SIGTYPE sigterm(signo)
584 int signo;
585 {
586     fatal(2, "SIGTERM");
587 }
588
589 SIGTYPE sighup(signo)
590 int signo;
591 {
592     fatal(2, "SIGHUP");
593 }
594
595 void init()
596 {
597     signal(SIGINT, sigint);
598     signal(SIGTERM, sigterm);
599     signal(SIGHUP, sighup);
600
601     set_tty_parameters();
602     signal(SIGALRM, sigalrm);
603     alarm(0);
604     alarmed = 0;
605 }
606
607 void set_tty_parameters()
608 {
609 #if defined(get_term_param)
610     term_parms t;
611
612     if (get_term_param (&t) < 0)
613         fatal(2, "Can't get terminal parameters: %m");
614
615     saved_tty_parameters = t;
616     have_tty_parameters  = 1;
617
618     t.c_iflag     |= IGNBRK | ISTRIP | IGNPAR;
619     t.c_oflag      = 0;
620     t.c_lflag      = 0;
621     t.c_cc[VERASE] =
622     t.c_cc[VKILL]  = 0;
623     t.c_cc[VMIN]   = 1;
624     t.c_cc[VTIME]  = 0;
625
626     if (set_term_param (&t) < 0)
627         fatal(2, "Can't set terminal parameters: %m");
628 #endif
629 }
630
631 void break_sequence()
632 {
633 #ifdef TERMIOS
634     tcsendbreak (0, 0);
635 #endif
636 }
637
638 void terminate(status)
639 int status;
640 {
641     static int terminating = 0;
642
643     if (terminating)
644         exit(status);
645     terminating = 1;
646     echo_stderr(-1);
647 /*
648  * Allow the last of the report string to be gathered before we terminate.
649  */
650     if (report_gathering) {
651         int c, rep_len;
652
653         rep_len = strlen(report_buffer);
654         while (rep_len + 1 <= sizeof(report_buffer)) {
655             alarm(1);
656             c = get_char();
657             alarm(0);
658             if (c < 0 || iscntrl(c))
659                 break;
660             report_buffer[rep_len] = c;
661             ++rep_len;
662         }
663         report_buffer[rep_len] = 0;
664         fprintf (report_fp, "chat:  %s\n", report_buffer);
665     }
666     if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
667         if (verbose)
668             fprintf (report_fp, "Closing \"%s\".\n", report_file);
669         fclose (report_fp);
670         report_fp = (FILE *) NULL;
671     }
672
673 #if defined(get_term_param)
674     if (have_tty_parameters) {
675         if (set_term_param (&saved_tty_parameters) < 0)
676             fatal(2, "Can't restore terminal parameters: %m");
677     }
678 #endif
679
680     exit(status);
681 }
682
683 /*
684  *      'Clean up' this string.
685  */
686 char *clean(s, sending)
687 register char *s;
688 int sending;  /* set to 1 when sending (putting) this string. */
689 {
690     char cur_chr;
691     char *s1, *p, *phchar;
692     int add_return = sending;
693     size_t len = strlen(s) + 3;         /* see len comments below */
694
695 #define isoctal(chr)    (((chr) >= '0') && ((chr) <= '7'))
696 #define isalnumx(chr)   ((((chr) >= '0') && ((chr) <= '9')) \
697                          || (((chr) >= 'a') && ((chr) <= 'z')) \
698                          || (((chr) >= 'A') && ((chr) <= 'Z')) \
699                          || (chr) == '_')
700
701     p = s1 = malloc(len);
702     if (!p)
703         fatal(2, "memory error!");
704     while (*s) {
705         cur_chr = *s++;
706         if (cur_chr == '^') {
707             cur_chr = *s++;
708             if (cur_chr == '\0') {
709                 *p++ = '^';
710                 break;
711             }
712             cur_chr &= 0x1F;
713             if (cur_chr != 0) {
714                 *p++ = cur_chr;
715             }
716             continue;
717         }
718
719         if (use_env && cur_chr == '$') {                /* ARI */
720             char c;
721
722             phchar = s;
723             while (isalnumx(*s))
724                 s++;
725             c = *s;             /* save */
726             *s = '\0';
727             phchar = getenv(phchar);
728             *s = c;             /* restore */
729             if (phchar) {
730                 len += strlen(phchar);
731                 s1 = grow(s1, &p, len);
732                 while (*phchar)
733                     *p++ = *phchar++;
734             }
735             continue;
736         }
737
738         if (cur_chr != '\\') {
739             *p++ = cur_chr;
740             continue;
741         }
742
743         cur_chr = *s++;
744         if (cur_chr == '\0') {
745             if (sending) {
746                 *p++ = '\\';
747                 *p++ = '\\';    /* +1 for len */
748             }
749             break;
750         }
751
752         switch (cur_chr) {
753         case 'b':
754             *p++ = '\b';
755             break;
756
757         case 'c':
758             if (sending && *s == '\0')
759                 add_return = 0;
760             else
761                 *p++ = cur_chr;
762             break;
763
764         case '\\':
765         case 'K':
766         case 'p':
767         case 'd':
768             if (sending)
769                 *p++ = '\\';
770             *p++ = cur_chr;
771             break;
772
773         case 'T':
774             if (sending && phone_num) {
775                 len += strlen(phone_num);
776                 s1 = grow(s1, &p, len);
777                 for (phchar = phone_num; *phchar != '\0'; phchar++) 
778                     *p++ = *phchar;
779             }
780             else {
781                 *p++ = '\\';
782                 *p++ = 'T';
783             }
784             break;
785
786         case 'U':
787             if (sending && phone_num2) {
788                 len += strlen(phone_num2);
789                 s1 = grow(s1, &p, len);
790                 for (phchar = phone_num2; *phchar != '\0'; phchar++) 
791                     *p++ = *phchar;
792             }
793             else {
794                 *p++ = '\\';
795                 *p++ = 'U';
796             }
797             break;
798
799         case 'q':
800             quiet = 1;
801             break;
802
803         case 'r':
804             *p++ = '\r';
805             break;
806
807         case 'n':
808             *p++ = '\n';
809             break;
810
811         case 's':
812             *p++ = ' ';
813             break;
814
815         case 't':
816             *p++ = '\t';
817             break;
818
819         case 'N':
820             if (sending) {
821                 *p++ = '\\';
822                 *p++ = '\0';
823             }
824             else
825                 *p++ = 'N';
826             break;
827
828         case '$':                       /* ARI */
829             if (use_env) {
830                 *p++ = cur_chr;
831                 break;
832             }
833             /* FALL THROUGH */
834
835         default:
836             if (isoctal (cur_chr)) {
837                 cur_chr &= 0x07;
838                 if (isoctal (*s)) {
839                     cur_chr <<= 3;
840                     cur_chr |= *s++ - '0';
841                     if (isoctal (*s)) {
842                         cur_chr <<= 3;
843                         cur_chr |= *s++ - '0';
844                     }
845                 }
846
847                 if (cur_chr != 0 || sending) {
848                     if (sending && (cur_chr == '\\' || cur_chr == 0))
849                         *p++ = '\\';
850                     *p++ = cur_chr;
851                 }
852                 break;
853             }
854
855             if (sending)
856                 *p++ = '\\';
857             *p++ = cur_chr;
858             break;
859         }
860     }
861
862     if (add_return)
863         *p++ = '\r';    /* +2 for len */
864
865     *p = '\0';          /* +3 for len */
866     return s1;
867 }
868
869 /*
870  * A modified version of 'strtok'. This version skips \ sequences.
871  */
872
873 char *expect_strtok (s, term)
874      char *s, *term;
875 {
876     static  char *str   = "";
877     int     escape_flag = 0;
878     char   *result;
879
880 /*
881  * If a string was specified then do initial processing.
882  */
883     if (s)
884         str = s;
885
886 /*
887  * If this is the escape flag then reset it and ignore the character.
888  */
889     if (*str)
890         result = str;
891     else
892         result = (char *) 0;
893
894     while (*str) {
895         if (escape_flag) {
896             escape_flag = 0;
897             ++str;
898             continue;
899         }
900
901         if (*str == '\\') {
902             ++str;
903             escape_flag = 1;
904             continue;
905         }
906
907 /*
908  * If this is not in the termination string, continue.
909  */
910         if (strchr (term, *str) == (char *) 0) {
911             ++str;
912             continue;
913         }
914
915 /*
916  * This is the terminator. Mark the end of the string and stop.
917  */
918         *str++ = '\0';
919         break;
920     }
921     return (result);
922 }
923
924 /*
925  * Process the expect string
926  */
927
928 void chat_expect (s)
929 char *s;
930 {
931     char *expect;
932     char *reply;
933
934     if (strcmp(s, "HANGUP") == 0) {
935         ++hup_next;
936         return;
937     }
938  
939     if (strcmp(s, "ABORT") == 0) {
940         ++abort_next;
941         return;
942     }
943
944     if (strcmp(s, "CLR_ABORT") == 0) {
945         ++clear_abort_next;
946         return;
947     }
948
949     if (strcmp(s, "REPORT") == 0) {
950         ++report_next;
951         return;
952     }
953
954     if (strcmp(s, "CLR_REPORT") == 0) {
955         ++clear_report_next;
956         return;
957     }
958
959     if (strcmp(s, "TIMEOUT") == 0) {
960         ++timeout_next;
961         return;
962     }
963
964     if (strcmp(s, "ECHO") == 0) {
965         ++echo_next;
966         return;
967     }
968
969     if (strcmp(s, "SAY") == 0) {
970         ++say_next;
971         return;
972     }
973
974 /*
975  * Fetch the expect and reply string.
976  */
977     for (;;) {
978         expect = expect_strtok (s, "-");
979         s      = (char *) 0;
980
981         if (expect == (char *) 0)
982             return;
983
984         reply = expect_strtok (s, "-");
985
986 /*
987  * Handle the expect string. If successful then exit.
988  */
989         if (get_string (expect))
990             return;
991
992 /*
993  * If there is a sub-reply string then send it. Otherwise any condition
994  * is terminal.
995  */
996         if (reply == (char *) 0 || exit_code != 3)
997             break;
998
999         chat_send (reply);
1000     }
1001
1002 /*
1003  * The expectation did not occur. This is terminal.
1004  */
1005     if (fail_reason)
1006         msgf("Failed (%s)", fail_reason);
1007     else
1008         msgf("Failed");
1009     terminate(exit_code);
1010 }
1011
1012 /*
1013  * Translate the input character to the appropriate string for printing
1014  * the data.
1015  */
1016
1017 char *character(c)
1018 int c;
1019 {
1020     static char string[10];
1021     char *meta;
1022
1023     meta = (c & 0x80) ? "M-" : "";
1024     c &= 0x7F;
1025
1026     if (c < 32)
1027         sprintf(string, "%s^%c", meta, (int)c + '@');
1028     else if (c == 127)
1029         sprintf(string, "%s^?", meta);
1030     else
1031         sprintf(string, "%s%c", meta, c);
1032
1033     return (string);
1034 }
1035
1036 /*
1037  *  process the reply string
1038  */
1039 void chat_send (s)
1040 register char *s;
1041 {
1042     char file_data[STR_LEN];
1043
1044     if (say_next) {
1045         say_next = 0;
1046         s = clean(s, 1);
1047         write(2, s, strlen(s));
1048         free(s);
1049         return;
1050     }
1051
1052     if (hup_next) {
1053         hup_next = 0;
1054         if (strcmp(s, "OFF") == 0)
1055            signal(SIGHUP, SIG_IGN);
1056         else
1057            signal(SIGHUP, sighup);
1058         return;
1059     }
1060
1061     if (echo_next) {
1062         echo_next = 0;
1063         echo = (strcmp(s, "ON") == 0);
1064         return;
1065     }
1066
1067     if (abort_next) {
1068         char *s1;
1069         
1070         abort_next = 0;
1071         
1072         if (n_aborts >= MAX_ABORTS)
1073             fatal(2, "Too many ABORT strings");
1074         
1075         s1 = clean(s, 0);
1076         
1077         if (strlen(s1) > strlen(s)
1078             || strlen(s1) + 1 > sizeof(fail_buffer))
1079             fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1080
1081         abort_string[n_aborts++] = s1;
1082
1083         if (verbose)
1084             msgf("abort on (%v)", s);
1085         return;
1086     }
1087
1088     if (clear_abort_next) {
1089         char *s1;
1090         int   i;
1091         int   old_max;
1092         int   pack = 0;
1093         
1094         clear_abort_next = 0;
1095         
1096         s1 = clean(s, 0);
1097         
1098         if (strlen(s1) > strlen(s)
1099             || strlen(s1) + 1 > sizeof(fail_buffer))
1100             fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1101
1102         old_max = n_aborts;
1103         for (i=0; i < n_aborts; i++) {
1104             if ( strcmp(s1,abort_string[i]) == 0 ) {
1105                 free(abort_string[i]);
1106                 abort_string[i] = NULL;
1107                 pack++;
1108                 n_aborts--;
1109                 if (verbose)
1110                     msgf("clear abort on (%v)", s);
1111             }
1112         }
1113         free(s1);
1114         if (pack)
1115             pack_array(abort_string,old_max);
1116         return;
1117     }
1118
1119     if (report_next) {
1120         char *s1;
1121         
1122         report_next = 0;
1123         if (n_reports >= MAX_REPORTS)
1124             fatal(2, "Too many REPORT strings");
1125         
1126         s1 = clean(s, 0);
1127         if (strlen(s1) > strlen(s)
1128             || strlen(s1) + 1 > sizeof(fail_buffer))
1129             fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1130         
1131         report_string[n_reports++] = s1;
1132         
1133         if (verbose)
1134             msgf("report (%v)", s);
1135         return;
1136     }
1137
1138     if (clear_report_next) {
1139         char *s1;
1140         int   i;
1141         int   old_max;
1142         int   pack = 0;
1143         
1144         clear_report_next = 0;
1145         
1146         s1 = clean(s, 0);
1147         
1148         if (strlen(s1) > strlen(s)
1149             || strlen(s1) + 1 > sizeof(fail_buffer))
1150             fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1151
1152         old_max = n_reports;
1153         for (i=0; i < n_reports; i++) {
1154             if ( strcmp(s1,report_string[i]) == 0 ) {
1155                 free(report_string[i]);
1156                 report_string[i] = NULL;
1157                 pack++;
1158                 n_reports--;
1159                 if (verbose)
1160                     msgf("clear report (%v)", s);
1161             }
1162         }
1163         free(s1);
1164         if (pack)
1165             pack_array(report_string,old_max);
1166         
1167         return;
1168     }
1169
1170     if (timeout_next) {
1171         timeout_next = 0;
1172         s = clean(s, 0);
1173         timeout = atoi(s);
1174         
1175         if (timeout <= 0)
1176             timeout = DEFAULT_CHAT_TIMEOUT;
1177
1178         if (verbose)
1179             msgf("timeout set to %d seconds", timeout);
1180
1181         return;
1182     }
1183
1184     /*
1185      * The syntax @filename means read the string to send from the
1186      * file `filename'.
1187      */
1188     if (s[0] == '@') {
1189         /* skip the @ and any following white-space */
1190         char *fn = s;
1191         while (*++fn == ' ' || *fn == '\t')
1192             ;
1193
1194         if (*fn != 0) {
1195             FILE *f;
1196             int n = 0;
1197
1198             /* open the file and read until STR_LEN-1 bytes or end-of-file */
1199             f = fopen(fn, "r");
1200             if (f == NULL)
1201                 fatal(1, "%s -- open failed: %m", fn);
1202             while (n < STR_LEN - 1) {
1203                 int nr = fread(&file_data[n], 1, STR_LEN - 1 - n, f);
1204                 if (nr < 0)
1205                     fatal(1, "%s -- read error", fn);
1206                 if (nr == 0)
1207                     break;
1208                 n += nr;
1209             }
1210             fclose(f);
1211
1212             /* use the string we got as the string to send,
1213                but trim off the final newline if any. */
1214             if (n > 0 && file_data[n-1] == '\n')
1215                 --n;
1216             file_data[n] = 0;
1217             s = file_data;
1218         }
1219     }
1220
1221     if (strcmp(s, "EOT") == 0)
1222         s = "^D\\c";
1223     else if (strcmp(s, "BREAK") == 0)
1224         s = "\\K\\c";
1225
1226     if (!put_string(s))
1227         fatal(1, "Failed");
1228 }
1229
1230 int get_char()
1231 {
1232     int status;
1233     char c;
1234
1235     status = read(0, &c, 1);
1236
1237     switch (status) {
1238     case 1:
1239         return ((int)c & 0x7F);
1240
1241     default:
1242         msgf("warning: read() on stdin returned %d", status);
1243
1244     case -1:
1245         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1246             fatal(2, "Can't get file mode flags on stdin: %m");
1247
1248         if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1249             fatal(2, "Can't set file mode flags on stdin: %m");
1250         
1251         return (-1);
1252     }
1253 }
1254
1255 int put_char(c)
1256 int c;
1257 {
1258     int status;
1259     char ch = c;
1260
1261     usleep(10000);              /* inter-character typing delay (?) */
1262
1263     status = write(1, &ch, 1);
1264
1265     switch (status) {
1266     case 1:
1267         return (0);
1268         
1269     default:
1270         msgf("warning: write() on stdout returned %d", status);
1271         
1272     case -1:
1273         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1274             fatal(2, "Can't get file mode flags on stdin, %m");
1275
1276         if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1277             fatal(2, "Can't set file mode flags on stdin: %m");
1278         
1279         return (-1);
1280     }
1281 }
1282
1283 int write_char (c)
1284 int c;
1285 {
1286     if (alarmed || put_char(c) < 0) {
1287         alarm(0);
1288         alarmed = 0;
1289
1290         if (verbose) {
1291             if (errno == EINTR || errno == EWOULDBLOCK)
1292                 msgf(" -- write timed out");
1293             else
1294                 msgf(" -- write failed: %m");
1295         }
1296         return (0);
1297     }
1298     return (1);
1299 }
1300
1301 int put_string (s)
1302 register char *s;
1303 {
1304     quiet = 0;
1305     s = clean(s, 1);
1306
1307     if (verbose) {
1308         if (quiet)
1309             msgf("send (?????\?)");
1310         else
1311             msgf("send (%v)", s);
1312     }
1313
1314     alarm(timeout); alarmed = 0;
1315
1316     while (*s) {
1317         register char c = *s++;
1318
1319         if (c != '\\') {
1320             if (!write_char (c))
1321                 return 0;
1322             continue;
1323         }
1324
1325         c = *s++;
1326         switch (c) {
1327         case 'd':
1328             sleep(1);
1329             break;
1330
1331         case 'K':
1332             break_sequence();
1333             break;
1334
1335         case 'p':
1336             usleep(10000);      /* 1/100th of a second (arg is microseconds) */
1337             break;
1338
1339         default:
1340             if (!write_char (c))
1341                 return 0;
1342             break;
1343         }
1344     }
1345
1346     alarm(0);
1347     alarmed = 0;
1348     return (1);
1349 }
1350
1351 /*
1352  *      Echo a character to stderr.
1353  *      When called with -1, a '\n' character is generated when
1354  *      the cursor is not at the beginning of a line.
1355  */
1356 void echo_stderr(n)
1357 int n;
1358 {
1359     static int need_lf;
1360     char *s;
1361
1362     switch (n) {
1363     case '\r':          /* ignore '\r' */
1364         break;
1365     case -1:
1366         if (need_lf == 0)
1367             break;
1368         /* fall through */
1369     case '\n':
1370         write(2, "\n", 1);
1371         need_lf = 0;
1372         break;
1373     default:
1374         s = character(n);
1375         write(2, s, strlen(s));
1376         need_lf = 1;
1377         break;
1378     }
1379 }
1380
1381 /*
1382  *      'Wait for' this string to appear on this file descriptor.
1383  */
1384 int get_string(string)
1385 register char *string;
1386 {
1387     char temp[STR_LEN];
1388     int c, printed = 0, len, minlen;
1389     register char *s = temp, *end = s + STR_LEN;
1390     char *logged = temp;
1391
1392     fail_reason = (char *)0;
1393     string = clean(string, 0);
1394     len = strlen(string);
1395     minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1396
1397     if (verbose)
1398         msgf("expect (%v)", string);
1399
1400     if (len > STR_LEN) {
1401         msgf("expect string is too long");
1402         exit_code = 1;
1403         return 0;
1404     }
1405
1406     if (len == 0) {
1407         if (verbose)
1408             msgf("got it");
1409         return (1);
1410     }
1411
1412     alarm(timeout);
1413     alarmed = 0;
1414
1415     while ( ! alarmed && (c = get_char()) >= 0) {
1416         int n, abort_len, report_len;
1417
1418         if (echo)
1419             echo_stderr(c);
1420         if (verbose && c == '\n') {
1421             if (s == logged)
1422                 msgf("");       /* blank line */
1423             else
1424                 msgf("%0.*v", s - logged, logged);
1425             logged = s + 1;
1426         }
1427
1428         *s++ = c;
1429
1430         if (verbose && s >= logged + 80) {
1431             msgf("%0.*v", s - logged, logged);
1432             logged = s;
1433         }
1434
1435         if (Verbose) {
1436            if (c == '\n')
1437                fputc( '\n', stderr );
1438            else if (c != '\r')
1439                fprintf( stderr, "%s", character(c) );
1440         }
1441
1442         if (!report_gathering) {
1443             for (n = 0; n < n_reports; ++n) {
1444                 if ((report_string[n] != (char*) NULL) &&
1445                     s - temp >= (report_len = strlen(report_string[n])) &&
1446                     strncmp(s - report_len, report_string[n], report_len) == 0) {
1447                     time_t time_now   = time ((time_t*) NULL);
1448                     struct tm* tm_now = localtime (&time_now);
1449
1450                     strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1451                     strcat (report_buffer, report_string[n]);
1452
1453                     report_string[n] = (char *) NULL;
1454                     report_gathering = 1;
1455                     break;
1456                 }
1457             }
1458         }
1459         else {
1460             if (!iscntrl (c)) {
1461                 int rep_len = strlen (report_buffer);
1462                 report_buffer[rep_len]     = c;
1463                 report_buffer[rep_len + 1] = '\0';
1464             }
1465             else {
1466                 report_gathering = 0;
1467                 fprintf (report_fp, "chat:  %s\n", report_buffer);
1468             }
1469         }
1470
1471         if (s - temp >= len &&
1472             c == string[len - 1] &&
1473             strncmp(s - len, string, len) == 0) {
1474             if (verbose) {
1475                 if (s > logged)
1476                     msgf("%0.*v", s - logged, logged);
1477                 msgf(" -- got it\n");
1478             }
1479
1480             alarm(0);
1481             alarmed = 0;
1482             return (1);
1483         }
1484
1485         for (n = 0; n < n_aborts; ++n) {
1486             if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1487                 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1488                 if (verbose) {
1489                     if (s > logged)
1490                         msgf("%0.*v", s - logged, logged);
1491                     msgf(" -- failed");
1492                 }
1493
1494                 alarm(0);
1495                 alarmed = 0;
1496                 exit_code = n + 4;
1497                 strcpy(fail_reason = fail_buffer, abort_string[n]);
1498                 return (0);
1499             }
1500         }
1501
1502         if (s >= end) {
1503             if (logged < s - minlen) {
1504                 if (verbose)
1505                     msgf("%0.*v", s - logged, logged);
1506                 logged = s;
1507             }
1508             s -= minlen;
1509             memmove(temp, s, minlen);
1510             logged = temp + (logged - s);
1511             s = temp + minlen;
1512         }
1513
1514         if (alarmed && verbose)
1515             msgf("warning: alarm synchronization problem");
1516     }
1517
1518     alarm(0);
1519     
1520     if (verbose && printed) {
1521         if (alarmed)
1522             msgf(" -- read timed out");
1523         else
1524             msgf(" -- read failed: %m");
1525     }
1526
1527     exit_code = 3;
1528     alarmed   = 0;
1529     return (0);
1530 }
1531
1532 /*
1533  * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1534  */
1535 #ifdef SOL2
1536 #include <sys/param.h>
1537 #if MAXUID > 65536              /* then this is Solaris 2.6 or later */
1538 #undef NO_USLEEP
1539 #endif
1540 #endif /* SOL2 */
1541
1542 #ifdef NO_USLEEP
1543 #include <sys/types.h>
1544 #include <sys/time.h>
1545
1546 /*
1547   usleep -- support routine for 4.2BSD system call emulations
1548   last edit:  29-Oct-1984     D A Gwyn
1549   */
1550
1551 extern int        select();
1552
1553 int
1554 usleep( usec )                            /* returns 0 if ok, else -1 */
1555     long                usec;           /* delay in microseconds */
1556 {
1557     static struct {             /* `timeval' */
1558         long    tv_sec;         /* seconds */
1559         long    tv_usec;        /* microsecs */
1560     } delay;                    /* _select() timeout */
1561
1562     delay.tv_sec  = usec / 1000000L;
1563     delay.tv_usec = usec % 1000000L;
1564
1565     return select(0, (long *)0, (long *)0, (long *)0, &delay);
1566 }
1567 #endif
1568
1569 void
1570 pack_array (array, end)
1571     char **array; /* The address of the array of string pointers */
1572     int    end;   /* The index of the next free entry before CLR_ */
1573 {
1574     int i, j;
1575
1576     for (i = 0; i < end; i++) {
1577         if (array[i] == NULL) {
1578             for (j = i+1; j < end; ++j)
1579                 if (array[j] != NULL)
1580                     array[i++] = array[j];
1581             for (; i < end; ++i)
1582                 array[i] = NULL;
1583             break;
1584         }
1585     }
1586 }
1587
1588 /*
1589  * vfmtmsg - format a message into a buffer.  Like vsprintf except we
1590  * also specify the length of the output buffer, and we handle the
1591  * %m (error message) format.
1592  * Doesn't do floating-point formats.
1593  * Returns the number of chars put into buf.
1594  */
1595 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1596
1597 int
1598 vfmtmsg(buf, buflen, fmt, args)
1599     char *buf;
1600     int buflen;
1601     const char *fmt;
1602     va_list args;
1603 {
1604     int c, i, n;
1605     int width, prec, fillch;
1606     int base, len, neg, quoted;
1607     unsigned long val = 0;
1608     char *str, *buf0;
1609     const char *f;
1610     unsigned char *p;
1611     char num[32];
1612     static char hexchars[] = "0123456789abcdef";
1613
1614     buf0 = buf;
1615     --buflen;
1616     while (buflen > 0) {
1617         for (f = fmt; *f != '%' && *f != 0; ++f)
1618             ;
1619         if (f > fmt) {
1620             len = f - fmt;
1621             if (len > buflen)
1622                 len = buflen;
1623             memcpy(buf, fmt, len);
1624             buf += len;
1625             buflen -= len;
1626             fmt = f;
1627         }
1628         if (*fmt == 0)
1629             break;
1630         c = *++fmt;
1631         width = prec = 0;
1632         fillch = ' ';
1633         if (c == '0') {
1634             fillch = '0';
1635             c = *++fmt;
1636         }
1637         if (c == '*') {
1638             width = va_arg(args, int);
1639             c = *++fmt;
1640         } else {
1641             while (isdigit(c)) {
1642                 width = width * 10 + c - '0';
1643                 c = *++fmt;
1644             }
1645         }
1646         if (c == '.') {
1647             c = *++fmt;
1648             if (c == '*') {
1649                 prec = va_arg(args, int);
1650                 c = *++fmt;
1651             } else {
1652                 while (isdigit(c)) {
1653                     prec = prec * 10 + c - '0';
1654                     c = *++fmt;
1655                 }
1656             }
1657         }
1658         str = 0;
1659         base = 0;
1660         neg = 0;
1661         ++fmt;
1662         switch (c) {
1663         case 'd':
1664             i = va_arg(args, int);
1665             if (i < 0) {
1666                 neg = 1;
1667                 val = -i;
1668             } else
1669                 val = i;
1670             base = 10;
1671             break;
1672         case 'o':
1673             val = va_arg(args, unsigned int);
1674             base = 8;
1675             break;
1676         case 'x':
1677             val = va_arg(args, unsigned int);
1678             base = 16;
1679             break;
1680         case 'p':
1681             val = (unsigned long) va_arg(args, void *);
1682             base = 16;
1683             neg = 2;
1684             break;
1685         case 's':
1686             str = va_arg(args, char *);
1687             break;
1688         case 'c':
1689             num[0] = va_arg(args, int);
1690             num[1] = 0;
1691             str = num;
1692             break;
1693         case 'm':
1694             str = strerror(errno);
1695             break;
1696         case 'v':               /* "visible" string */
1697         case 'q':               /* quoted string */
1698             quoted = c == 'q';
1699             p = va_arg(args, unsigned char *);
1700             if (fillch == '0' && prec > 0) {
1701                 n = prec;
1702             } else {
1703                 n = strlen((char *)p);
1704                 if (prec > 0 && prec < n)
1705                     n = prec;
1706             }
1707             while (n > 0 && buflen > 0) {
1708                 c = *p++;
1709                 --n;
1710                 if (!quoted && c >= 0x80) {
1711                     OUTCHAR('M');
1712                     OUTCHAR('-');
1713                     c -= 0x80;
1714                 }
1715                 if (quoted && (c == '"' || c == '\\'))
1716                     OUTCHAR('\\');
1717                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1718                     if (quoted) {
1719                         OUTCHAR('\\');
1720                         switch (c) {
1721                         case '\t':      OUTCHAR('t');   break;
1722                         case '\n':      OUTCHAR('n');   break;
1723                         case '\b':      OUTCHAR('b');   break;
1724                         case '\f':      OUTCHAR('f');   break;
1725                         default:
1726                             OUTCHAR('x');
1727                             OUTCHAR(hexchars[c >> 4]);
1728                             OUTCHAR(hexchars[c & 0xf]);
1729                         }
1730                     } else {
1731                         if (c == '\t')
1732                             OUTCHAR(c);
1733                         else {
1734                             OUTCHAR('^');
1735                             OUTCHAR(c ^ 0x40);
1736                         }
1737                     }
1738                 } else
1739                     OUTCHAR(c);
1740             }
1741             continue;
1742         default:
1743             *buf++ = '%';
1744             if (c != '%')
1745                 --fmt;          /* so %z outputs %z etc. */
1746             --buflen;
1747             continue;
1748         }
1749         if (base != 0) {
1750             str = num + sizeof(num);
1751             *--str = 0;
1752             while (str > num + neg) {
1753                 *--str = hexchars[val % base];
1754                 val = val / base;
1755                 if (--prec <= 0 && val == 0)
1756                     break;
1757             }
1758             switch (neg) {
1759             case 1:
1760                 *--str = '-';
1761                 break;
1762             case 2:
1763                 *--str = 'x';
1764                 *--str = '0';
1765                 break;
1766             }
1767             len = num + sizeof(num) - 1 - str;
1768         } else {
1769             len = strlen(str);
1770             if (prec > 0 && len > prec)
1771                 len = prec;
1772         }
1773         if (width > 0) {
1774             if (width > buflen)
1775                 width = buflen;
1776             if ((n = width - len) > 0) {
1777                 buflen -= n;
1778                 for (; n > 0; --n)
1779                     *buf++ = fillch;
1780             }
1781         }
1782         if (len > buflen)
1783             len = buflen;
1784         memcpy(buf, str, len);
1785         buf += len;
1786         buflen -= len;
1787     }
1788     *buf = 0;
1789     return buf - buf0;
1790 }