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