2 * Chat -- a program for automatic session establishment (i.e. dial
3 * the phone and log in).
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.
14 * This software is in the public domain.
17 * 22-May-99 added environment substitutuion, enabled with -E switch.
18 * Andreas Arens <andras@cityweb.de>.
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>.
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>
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).
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.
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.
47 * In the same vein as above, added CLR_REPORT keyword.
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.
54 * Francis Demierre <Francis@SwissMail.Com>
55 * Thu May 15 17:15:40 MET DST 1997
58 * Added -r "report file" switch & REPORT keyword.
59 * Robert Geer <bgeer@xmission.com>
61 * Added -s "use stderr" and -S "don't use syslog" switches.
63 * Karl O. Pinc <kop@meme.com>
66 * Added -e "echo" switch & ECHO keyword
67 * Dick Streefland <dicks@tasking.nl>
70 * Considerable updates and modifications by
71 * Al Longyear <longyear@pobox.com>
72 * Paul Mackerras <paulus@cs.anu.edu.au>
75 * The original author is:
77 * Karl Fox <karl@MorningStar.Com>
78 * Morning Star Technologies, Inc.
94 #include <sys/types.h>
118 #define O_NONBLOCK O_NDELAY
123 extern char *sys_errlist[];
124 #define memmove(to, from, n) bcopy(from, to, n)
125 #define strerror(n) ((unsigned)(n) < sys_nerr? sys_errlist[(n)] :\
129 /*************** Micro getopt() *********************************************/
130 #define OPTION(c,v) (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
131 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
132 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
133 #define OPTARG(c,v) (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
134 (_O=4,(char*)0):(char*)0)
135 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
136 #define ARG(c,v) (c?(--c,*v++):(char*)0)
138 static int _O = 0; /* Internal state */
139 /*************** Micro getopt() *********************************************/
143 #define MAX_ABORTS 50
144 #define MAX_REPORTS 50
145 #define DEFAULT_CHAT_TIMEOUT 45
156 FILE* report_fp = (FILE *) 0;
157 char *report_file = (char *) 0;
158 char *chat_file = (char *) 0;
159 char *phone_num = (char *) 0;
160 char *phone_num2 = (char *) 0;
161 int timeout = DEFAULT_CHAT_TIMEOUT;
163 int have_tty_parameters = 0;
166 #define term_parms struct termio
167 #define get_term_param(param) ioctl(0, TCGETA, param)
168 #define set_term_param(param) ioctl(0, TCSETA, param)
169 struct termio saved_tty_parameters;
173 #define term_parms struct termios
174 #define get_term_param(param) tcgetattr(0, param)
175 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
176 struct termios saved_tty_parameters;
179 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
181 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
182 int clear_abort_next = 0;
184 char *report_string[MAX_REPORTS] ;
185 char report_buffer[256] ;
186 int n_reports = 0, report_next = 0, report_gathering = 0 ;
187 int clear_report_next = 0;
189 int say_next = 0, hup_next = 0;
191 void *dup_mem (void *b, size_t c);
192 void *copy_of (char *s);
193 char *grow (char *s, char **p, size_t len);
195 void msgf (const char *fmt, ...);
196 void fatal (int code, const char *fmt, ...);
197 SIGTYPE sigalrm (int signo);
198 SIGTYPE sigint (int signo);
199 SIGTYPE sigterm (int signo);
200 SIGTYPE sighup (int signo);
203 void set_tty_parameters (void);
204 int echo_stderr (int);
205 void break_sequence (void);
206 void terminate (int status);
207 void do_file (char *chat_file);
208 int get_string (register char *string);
209 int put_string (register char *s);
210 int write_char (int c);
211 int put_char (int c);
213 int chat_send (register char *s);
214 char *character (int c);
215 void chat_expect (register char *s);
216 char *clean (register char *s, int sending);
217 void break_sequence (void);
218 void terminate (int status);
219 void pack_array (char **array, int end);
220 char *expect_strtok (char *, char *);
221 int vfmtmsg (char *, int, const char *, va_list); /* vsprintf++ */
223 int main (int, char *[]);
225 void *dup_mem(void *b, size_t c)
227 void *ans = malloc (c);
229 fatal(2, "memory error!");
235 void *copy_of (char *s)
237 return dup_mem (s, strlen (s) + 1);
240 /* grow a char buffer and keep a pointer offset */
241 char *grow(char *s, char **p, size_t len)
243 size_t l = *p - s; /* save p as distance into s */
247 fatal(2, "memory error!");
248 *p = s + l; /* restore p */
253 * chat [ -v ] [ -E ] [ -T number ] [ -U number ] [ -t timeout ] [ -f chat-file ] \
254 * [ -r report-file ] \
255 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
257 * Perform a UUCP-dialer-like chat script on stdin and stdout.
260 main(int argc, char **argv)
265 program_name = *argv;
268 while ((option = OPTION(argc, argv)) != 0) {
295 if ((arg = OPTARG(argc, argv)) != NULL)
296 chat_file = copy_of(arg);
302 if ((arg = OPTARG(argc, argv)) != NULL)
309 arg = OPTARG (argc, argv);
311 if (report_fp != NULL)
313 report_file = copy_of (arg);
314 report_fp = fopen (report_file, "a");
315 if (report_fp != NULL) {
317 fprintf (report_fp, "Opening \"%s\"...\n",
325 if ((arg = OPTARG(argc, argv)) != NULL)
326 phone_num = copy_of(arg);
332 if ((arg = OPTARG(argc, argv)) != NULL)
333 phone_num2 = copy_of(arg);
344 * Default the report file to the stderr location
346 if (report_fp == NULL)
351 openlog("chat", LOG_PID);
353 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
356 setlogmask(LOG_UPTO(LOG_INFO));
358 setlogmask(LOG_UPTO(LOG_WARNING));
364 if (chat_file != NULL) {
365 arg = ARG(argc, argv);
371 while ((arg = ARG(argc, argv)) != NULL) {
374 if ((arg = ARG(argc, argv)) != NULL)
384 * Process a chat script when read from a file.
387 void do_file (char *chat_file)
390 char *sp, *arg, quote;
394 cfp = fopen (chat_file, "r");
396 fatal(1, "%s -- open failed: %m", chat_file);
401 while (fgets(buf, STR_LEN, cfp) != NULL) {
402 sp = strchr (buf, '\n');
409 /* lines starting with '#' are comments. If a real '#'
410 is to be expected, it should be quoted .... */
414 while (*sp != '\0') {
415 if (*sp == ' ' || *sp == '\t') {
420 if (*sp == '"' || *sp == '\'') {
423 while (*sp != quote) {
425 fatal(1, "unterminated quote (line %d)", linect);
435 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
453 * We got an error parsing the command line.
458 Usage: %s [-e] [-E] [-v] [-V] [-t timeout] [-r report-file]\n\
459 [-T phone-number] [-U phone-number2] {-f chat-file | chat-script}\n", program_name);
466 * Send a message to syslog and/or stderr.
468 void msgf(const char *fmt, ...)
474 vfmtmsg(line, sizeof(line), fmt, args);
476 syslog(LOG_INFO, "%s", line);
478 fprintf(stderr, "%s\n", line);
483 * Print an error message and terminate.
486 void fatal(int code, const char *fmt, ...)
492 vfmtmsg(line, sizeof(line), fmt, args);
494 syslog(LOG_ERR, "%s", line);
496 fprintf(stderr, "%s\n", line);
503 SIGTYPE sigalrm(int signo)
508 alarmed = 1; /* Reset alarm to avoid race window */
509 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
511 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
512 fatal(2, "Can't get file mode flags on stdin: %m");
514 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
515 fatal(2, "Can't set file mode flags on stdin: %m");
525 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
526 fatal(2, "Can't get file mode flags on stdin: %m");
528 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
529 fatal(2, "Can't set file mode flags on stdin: %m");
532 SIGTYPE sigint(int signo)
537 SIGTYPE sigterm(int signo)
542 SIGTYPE sighup(int signo)
549 signal(SIGINT, sigint);
550 signal(SIGTERM, sigterm);
551 signal(SIGHUP, sighup);
553 set_tty_parameters();
554 signal(SIGALRM, sigalrm);
559 void set_tty_parameters(void)
561 #if defined(get_term_param)
564 if (get_term_param (&t) < 0)
565 fatal(2, "Can't get terminal parameters: %m");
567 saved_tty_parameters = t;
568 have_tty_parameters = 1;
570 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
578 if (set_term_param (&t) < 0)
579 fatal(2, "Can't set terminal parameters: %m");
583 void break_sequence(void)
590 void terminate(int status)
592 static int terminating = 0;
599 * Allow the last of the report string to be gathered before we terminate.
601 if (report_gathering) {
604 rep_len = strlen(report_buffer);
605 while (rep_len + 1 <= sizeof(report_buffer)) {
609 if (c < 0 || iscntrl(c))
611 report_buffer[rep_len] = c;
614 report_buffer[rep_len] = 0;
615 fprintf (report_fp, "chat: %s\n", report_buffer);
617 if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
619 fprintf (report_fp, "Closing \"%s\".\n", report_file);
621 report_fp = (FILE *) NULL;
624 #if defined(get_term_param)
625 if (have_tty_parameters) {
626 if (set_term_param (&saved_tty_parameters) < 0)
627 fatal(2, "Can't restore terminal parameters: %m");
635 * 'Clean up' this string.
637 char *clean(register char *s,
638 int sending) /* set to 1 when sending (putting) this string. */
641 char *s1, *p, *phchar;
642 int add_return = sending;
643 size_t len = strlen(s) + 3; /* see len comments below */
645 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
646 #define isalnumx(chr) ((((chr) >= '0') && ((chr) <= '9')) \
647 || (((chr) >= 'a') && ((chr) <= 'z')) \
648 || (((chr) >= 'A') && ((chr) <= 'Z')) \
651 p = s1 = malloc(len);
653 fatal(2, "memory error!");
656 if (cur_chr == '^') {
658 if (cur_chr == '\0') {
669 if (use_env && cur_chr == '$') { /* ARI */
677 phchar = getenv(phchar);
678 *s = c; /* restore */
680 len += strlen(phchar);
681 s1 = grow(s1, &p, len);
688 if (cur_chr != '\\') {
694 if (cur_chr == '\0') {
697 *p++ = '\\'; /* +1 for len */
708 if (sending && *s == '\0')
724 if (sending && phone_num) {
725 len += strlen(phone_num);
726 s1 = grow(s1, &p, len);
727 for (phchar = phone_num; *phchar != '\0'; phchar++)
737 if (sending && phone_num2) {
738 len += strlen(phone_num2);
739 s1 = grow(s1, &p, len);
740 for (phchar = phone_num2; *phchar != '\0'; phchar++)
786 if (isoctal (cur_chr)) {
790 cur_chr |= *s++ - '0';
793 cur_chr |= *s++ - '0';
797 if (cur_chr != 0 || sending) {
798 if (sending && (cur_chr == '\\' || cur_chr == 0))
813 *p++ = '\r'; /* +2 for len */
815 *p = '\0'; /* +3 for len */
820 * A modified version of 'strtok'. This version skips \ sequences.
823 char *expect_strtok (char *s, char *term)
825 static char *str = "";
830 * If a string was specified then do initial processing.
836 * If this is the escape flag then reset it and ignore the character.
857 * If this is not in the termination string, continue.
859 if (strchr (term, *str) == (char *) 0) {
865 * This is the terminator. Mark the end of the string and stop.
874 * Process the expect string
877 void chat_expect (char *s)
882 if (strcmp(s, "HANGUP") == 0) {
887 if (strcmp(s, "ABORT") == 0) {
892 if (strcmp(s, "CLR_ABORT") == 0) {
897 if (strcmp(s, "REPORT") == 0) {
902 if (strcmp(s, "CLR_REPORT") == 0) {
907 if (strcmp(s, "TIMEOUT") == 0) {
912 if (strcmp(s, "ECHO") == 0) {
917 if (strcmp(s, "SAY") == 0) {
923 * Fetch the expect and reply string.
926 expect = expect_strtok (s, "-");
929 if (expect == (char *) 0)
932 reply = expect_strtok (s, "-");
935 * Handle the expect string. If successful then exit.
937 if (get_string (expect))
941 * If there is a sub-reply string then send it. Otherwise any condition
944 if (reply == (char *) 0 || exit_code != 3)
951 * The expectation did not occur. This is terminal.
954 msgf("Failed (%s)", fail_reason);
957 terminate(exit_code);
961 * Translate the input character to the appropriate string for printing
965 char *character(int c)
967 static char string[10];
970 meta = (c & 0x80) ? "M-" : "";
974 sprintf(string, "%s^%c", meta, (int)c + '@');
976 sprintf(string, "%s^?", meta);
978 sprintf(string, "%s%c", meta, c);
984 * process the reply string
986 int chat_send (register char *s)
988 char file_data[STR_LEN];
995 ret = write(2, s, len) != len;
1002 if (strcmp(s, "OFF") == 0)
1003 signal(SIGHUP, SIG_IGN);
1005 signal(SIGHUP, sighup);
1011 echo = (strcmp(s, "ON") == 0);
1020 if (n_aborts >= MAX_ABORTS)
1021 fatal(2, "Too many ABORT strings");
1025 if (strlen(s1) + 1 > sizeof(fail_buffer))
1026 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1028 abort_string[n_aborts++] = s1;
1031 msgf("abort on (%v)", s1);
1035 if (clear_abort_next) {
1041 clear_abort_next = 0;
1045 if (strlen(s1) + 1 > sizeof(fail_buffer))
1046 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1049 for (i=0; i < n_aborts; i++) {
1050 if ( strcmp(s1,abort_string[i]) == 0 ) {
1051 free(abort_string[i]);
1052 abort_string[i] = NULL;
1056 msgf("clear abort on (%v)", s1);
1061 pack_array(abort_string,old_max);
1069 if (n_reports >= MAX_REPORTS)
1070 fatal(2, "Too many REPORT strings");
1073 if (strlen(s1) + 1 > sizeof(fail_buffer))
1074 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1076 report_string[n_reports++] = s1;
1079 msgf("report (%v)", s1);
1083 if (clear_report_next) {
1089 clear_report_next = 0;
1093 if (strlen(s1) + 1 > sizeof(fail_buffer))
1094 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1096 old_max = n_reports;
1097 for (i=0; i < n_reports; i++) {
1098 if ( strcmp(s1,report_string[i]) == 0 ) {
1099 free(report_string[i]);
1100 report_string[i] = NULL;
1104 msgf("clear report (%v)", s1);
1109 pack_array(report_string,old_max);
1120 timeout = DEFAULT_CHAT_TIMEOUT;
1123 msgf("timeout set to %d seconds", timeout);
1129 * The syntax @filename means read the string to send from the
1133 /* skip the @ and any following white-space */
1135 while (*++fn == ' ' || *fn == '\t')
1142 /* open the file and read until STR_LEN-1 bytes or end-of-file */
1145 fatal(1, "%s -- open failed: %m", fn);
1146 while (n < STR_LEN - 1) {
1147 int nr = fread(&file_data[n], 1, STR_LEN - 1 - n, f);
1149 fatal(1, "%s -- read error", fn);
1156 /* use the string we got as the string to send,
1157 but trim off the final newline if any. */
1158 if (n > 0 && file_data[n-1] == '\n')
1165 if (strcmp(s, "EOT") == 0)
1167 else if (strcmp(s, "BREAK") == 0)
1181 status = read(0, &c, 1);
1185 return ((int)c & 0x7F);
1188 msgf("warning: read() on stdin returned %d", status);
1191 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1192 fatal(2, "Can't get file mode flags on stdin: %m");
1194 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1195 fatal(2, "Can't set file mode flags on stdin: %m");
1206 usleep(10000); /* inter-character typing delay (?) */
1208 status = write(1, &ch, 1);
1215 msgf("warning: write() on stdout returned %d", status);
1218 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1219 fatal(2, "Can't get file mode flags on stdin, %m");
1221 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1222 fatal(2, "Can't set file mode flags on stdin: %m");
1228 int write_char(int c)
1230 if (alarmed || put_char(c) < 0) {
1235 if (errno == EINTR || errno == EWOULDBLOCK)
1236 msgf(" -- write timed out");
1238 msgf(" -- write failed: %m");
1245 int put_string(register char *s)
1252 msgf("send (?????\?)");
1254 msgf("send (%v)", s);
1257 alarm(timeout); alarmed = 0;
1260 register char c = *s++;
1263 if (!write_char (c))
1279 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1283 if (!write_char (c))
1295 * Echo a character to stderr.
1296 * When called with -1, a '\n' character is generated when
1297 * the cursor is not at the beginning of a line.
1299 int echo_stderr(int n)
1306 case '\r': /* ignore '\r' */
1313 ret = write(2, "\n", 1) != 1;
1319 ret = write(2, s, len) != len;
1327 * 'Wait for' this string to appear on this file descriptor.
1329 int get_string(register char *string)
1332 int c, printed = 0, len, minlen;
1333 register char *s = temp, *end = s + STR_LEN;
1334 char *logged = temp;
1336 fail_reason = (char *)0;
1337 string = clean(string, 0);
1338 len = strlen(string);
1339 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1342 msgf("expect (%v)", string);
1344 if (len > STR_LEN) {
1345 msgf("expect string is too long");
1359 while ( ! alarmed && (c = get_char()) >= 0) {
1360 int n, abort_len, report_len;
1363 if (echo_stderr(c) != 0) {
1364 fatal(2, "Could not write to stderr, %m");
1367 if (verbose && c == '\n') {
1369 msgf(""); /* blank line */
1371 msgf("%0.*v", s - logged, logged);
1377 if (verbose && s >= logged + 80) {
1378 msgf("%0.*v", s - logged, logged);
1384 fputc( '\n', stderr );
1386 fprintf( stderr, "%s", character(c) );
1389 if (!report_gathering) {
1390 for (n = 0; n < n_reports; ++n) {
1391 if ((report_string[n] != (char*) NULL) &&
1392 s - temp >= (report_len = strlen(report_string[n])) &&
1393 strncmp(s - report_len, report_string[n], report_len) == 0) {
1394 time_t time_now = time ((time_t*) NULL);
1395 struct tm* tm_now = localtime (&time_now);
1397 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1398 strcat (report_buffer, report_string[n]);
1400 report_string[n] = (char *) NULL;
1401 report_gathering = 1;
1408 int rep_len = strlen (report_buffer);
1409 report_buffer[rep_len] = c;
1410 report_buffer[rep_len + 1] = '\0';
1413 report_gathering = 0;
1414 fprintf (report_fp, "chat: %s\n", report_buffer);
1418 if (s - temp >= len &&
1419 c == string[len - 1] &&
1420 strncmp(s - len, string, len) == 0) {
1423 msgf("%0.*v", s - logged, logged);
1424 msgf(" -- got it\n");
1432 for (n = 0; n < n_aborts; ++n) {
1433 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1434 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1437 msgf("%0.*v", s - logged, logged);
1444 strcpy(fail_reason = fail_buffer, abort_string[n]);
1450 if (logged < s - minlen) {
1452 msgf("%0.*v", s - logged, logged);
1456 memmove(temp, s, minlen);
1457 logged = temp + (logged - s);
1461 if (alarmed && verbose)
1462 msgf("warning: alarm synchronization problem");
1467 if (verbose && printed) {
1469 msgf(" -- read timed out");
1471 msgf(" -- read failed: %m");
1480 * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1483 #include <sys/param.h>
1484 #if MAXUID > 65536 /* then this is Solaris 2.6 or later */
1490 #include <sys/types.h>
1491 #include <sys/time.h>
1494 usleep -- support routine for 4.2BSD system call emulations
1495 last edit: 29-Oct-1984 D A Gwyn
1498 extern int select();
1500 /* returns 0 if ok, else -1 */
1501 int usleep(long usec) /* delay in microseconds */
1503 static struct { /* `timeval' */
1504 long tv_sec; /* seconds */
1505 long tv_usec; /* microsecs */
1506 } delay; /* _select() timeout */
1508 delay.tv_sec = usec / 1000000L;
1509 delay.tv_usec = usec % 1000000L;
1511 return select(0, (long *)0, (long *)0, (long *)0, &delay);
1516 char **array, /* The address of the array of string pointers */
1517 int end) /* The index of the next free entry before CLR_ */
1521 for (i = 0; i < end; i++) {
1522 if (array[i] == NULL) {
1523 for (j = i+1; j < end; ++j)
1524 if (array[j] != NULL)
1525 array[i++] = array[j];
1526 for (; i < end; ++i)
1534 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1535 * also specify the length of the output buffer, and we handle the
1536 * %m (error message) format.
1537 * Doesn't do floating-point formats.
1538 * Returns the number of chars put into buf.
1540 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1543 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1546 int width, prec, fillch;
1547 int base, len, neg, quoted;
1548 unsigned long val = 0;
1553 static char hexchars[] = "0123456789abcdef";
1557 while (buflen > 0) {
1558 for (f = fmt; *f != '%' && *f != 0; ++f)
1564 memcpy(buf, fmt, len);
1579 width = va_arg(args, int);
1582 while (isdigit(c)) {
1583 width = width * 10 + c - '0';
1590 prec = va_arg(args, int);
1593 while (isdigit(c)) {
1594 prec = prec * 10 + c - '0';
1605 i = va_arg(args, int);
1614 val = va_arg(args, unsigned int);
1618 val = va_arg(args, unsigned int);
1622 val = (unsigned long) va_arg(args, void *);
1627 str = va_arg(args, char *);
1630 num[0] = va_arg(args, int);
1635 str = strerror(errno);
1637 case 'v': /* "visible" string */
1638 case 'q': /* quoted string */
1640 p = va_arg(args, unsigned char *);
1641 if (fillch == '0' && prec > 0) {
1644 n = strlen((char *)p);
1645 if (prec > 0 && prec < n)
1648 while (n > 0 && buflen > 0) {
1651 if (!quoted && c >= 0x80) {
1656 if (quoted && (c == '"' || c == '\\'))
1658 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1662 case '\t': OUTCHAR('t'); break;
1663 case '\n': OUTCHAR('n'); break;
1664 case '\b': OUTCHAR('b'); break;
1665 case '\f': OUTCHAR('f'); break;
1668 OUTCHAR(hexchars[c >> 4]);
1669 OUTCHAR(hexchars[c & 0xf]);
1686 --fmt; /* so %z outputs %z etc. */
1691 str = num + sizeof(num);
1693 while (str > num + neg) {
1694 *--str = hexchars[val % base];
1696 if (--prec <= 0 && val == 0)
1708 len = num + sizeof(num) - 1 - str;
1711 if (prec > 0 && len > prec)
1717 if ((n = width - len) > 0) {
1725 memcpy(buf, str, len);