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.
90 static const char rcsid[] = "$Id: chat.c,v 1.30 2004/01/17 05:47:55 carlsonj Exp $";
102 #include <sys/types.h>
103 #include <sys/stat.h>
133 #define __V(x) (va_alist) va_dcl
139 #define O_NONBLOCK O_NDELAY
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)] :\
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)
159 static int _O = 0; /* Internal state */
160 /*************** Micro getopt() *********************************************/
164 #define MAX_ABORTS 50
165 #define MAX_REPORTS 50
166 #define DEFAULT_CHAT_TIMEOUT 45
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;
184 int have_tty_parameters = 0;
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;
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;
200 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
202 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
203 int clear_abort_next = 0;
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;
210 int say_next = 0, hup_next = 0;
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++ */
244 int main __P((int, char *[]));
250 void *ans = malloc (c);
252 fatal(2, "memory error!");
261 return dup_mem (s, strlen (s) + 1);
264 /* grow a char buffer and keep a pointer offset */
265 char *grow(s, p, len)
270 size_t l = *p - s; /* save p as distance into s */
274 fatal(2, "memory error!");
275 *p = s + l; /* restore p */
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]] ...]]]
284 * Perform a UUCP-dialer-like chat script on stdin and stdout.
294 program_name = *argv;
297 while ((option = OPTION(argc, argv)) != 0) {
324 if ((arg = OPTARG(argc, argv)) != NULL)
325 chat_file = copy_of(arg);
331 if ((arg = OPTARG(argc, argv)) != NULL)
338 arg = OPTARG (argc, argv);
340 if (report_fp != NULL)
342 report_file = copy_of (arg);
343 report_fp = fopen (report_file, "a");
344 if (report_fp != NULL) {
346 fprintf (report_fp, "Opening \"%s\"...\n",
354 if ((arg = OPTARG(argc, argv)) != NULL)
355 phone_num = copy_of(arg);
361 if ((arg = OPTARG(argc, argv)) != NULL)
362 phone_num2 = copy_of(arg);
373 * Default the report file to the stderr location
375 if (report_fp == NULL)
380 openlog("chat", LOG_PID);
382 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
385 setlogmask(LOG_UPTO(LOG_INFO));
387 setlogmask(LOG_UPTO(LOG_WARNING));
393 if (chat_file != NULL) {
394 arg = ARG(argc, argv);
400 while ((arg = ARG(argc, argv)) != NULL) {
403 if ((arg = ARG(argc, argv)) != NULL)
413 * Process a chat script when read from a file.
416 void do_file (chat_file)
420 char *sp, *arg, quote;
424 cfp = fopen (chat_file, "r");
426 fatal(1, "%s -- open failed: %m", chat_file);
431 while (fgets(buf, STR_LEN, cfp) != NULL) {
432 sp = strchr (buf, '\n');
439 /* lines starting with '#' are comments. If a real '#'
440 is to be expected, it should be quoted .... */
444 while (*sp != '\0') {
445 if (*sp == ' ' || *sp == '\t') {
450 if (*sp == '"' || *sp == '\'') {
453 while (*sp != quote) {
455 fatal(1, "unterminated quote (line %d)", linect);
465 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
483 * We got an error parsing the command line.
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);
496 * Send a message to syslog and/or stderr.
498 void msgf __V((const char *fmt, ...))
507 fmt = va_arg(args, char *);
510 vfmtmsg(line, sizeof(line), fmt, args);
512 syslog(LOG_INFO, "%s", line);
514 fprintf(stderr, "%s\n", line);
518 * Print an error message and terminate.
521 void fatal __V((int code, const char *fmt, ...))
531 code = va_arg(args, int);
532 fmt = va_arg(args, char *);
535 vfmtmsg(line, sizeof(line), fmt, args);
537 syslog(LOG_ERR, "%s", line);
539 fprintf(stderr, "%s\n", line);
545 SIGTYPE sigalrm(signo)
551 alarmed = 1; /* Reset alarm to avoid race window */
552 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
554 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
555 fatal(2, "Can't get file mode flags on stdin: %m");
557 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
558 fatal(2, "Can't set file mode flags on stdin: %m");
568 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
569 fatal(2, "Can't get file mode flags on stdin: %m");
571 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
572 fatal(2, "Can't set file mode flags on stdin: %m");
575 SIGTYPE sigint(signo)
581 SIGTYPE sigterm(signo)
587 SIGTYPE sighup(signo)
595 signal(SIGINT, sigint);
596 signal(SIGTERM, sigterm);
597 signal(SIGHUP, sighup);
599 set_tty_parameters();
600 signal(SIGALRM, sigalrm);
605 void set_tty_parameters()
607 #if defined(get_term_param)
610 if (get_term_param (&t) < 0)
611 fatal(2, "Can't get terminal parameters: %m");
613 saved_tty_parameters = t;
614 have_tty_parameters = 1;
616 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
624 if (set_term_param (&t) < 0)
625 fatal(2, "Can't set terminal parameters: %m");
629 void break_sequence()
636 void terminate(status)
639 static int terminating = 0;
646 * Allow the last of the report string to be gathered before we terminate.
648 if (report_gathering) {
651 rep_len = strlen(report_buffer);
652 while (rep_len + 1 <= sizeof(report_buffer)) {
656 if (c < 0 || iscntrl(c))
658 report_buffer[rep_len] = c;
661 report_buffer[rep_len] = 0;
662 fprintf (report_fp, "chat: %s\n", report_buffer);
664 if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
666 fprintf (report_fp, "Closing \"%s\".\n", report_file);
668 report_fp = (FILE *) NULL;
671 #if defined(get_term_param)
672 if (have_tty_parameters) {
673 if (set_term_param (&saved_tty_parameters) < 0)
674 fatal(2, "Can't restore terminal parameters: %m");
682 * 'Clean up' this string.
684 char *clean(s, sending)
686 int sending; /* set to 1 when sending (putting) this string. */
689 char *s1, *p, *phchar;
690 int add_return = sending;
691 size_t len = strlen(s) + 3; /* see len comments below */
693 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
694 #define isalnumx(chr) ((((chr) >= '0') && ((chr) <= '9')) \
695 || (((chr) >= 'a') && ((chr) <= 'z')) \
696 || (((chr) >= 'A') && ((chr) <= 'Z')) \
699 p = s1 = malloc(len);
701 fatal(2, "memory error!");
704 if (cur_chr == '^') {
706 if (cur_chr == '\0') {
717 if (use_env && cur_chr == '$') { /* ARI */
725 phchar = getenv(phchar);
726 *s = c; /* restore */
728 len += strlen(phchar);
729 s1 = grow(s1, &p, len);
736 if (cur_chr != '\\') {
742 if (cur_chr == '\0') {
745 *p++ = '\\'; /* +1 for len */
756 if (sending && *s == '\0')
772 if (sending && phone_num) {
773 len += strlen(phone_num);
774 s1 = grow(s1, &p, len);
775 for (phchar = phone_num; *phchar != '\0'; phchar++)
785 if (sending && phone_num2) {
786 len += strlen(phone_num2);
787 s1 = grow(s1, &p, len);
788 for (phchar = phone_num2; *phchar != '\0'; phchar++)
834 if (isoctal (cur_chr)) {
838 cur_chr |= *s++ - '0';
841 cur_chr |= *s++ - '0';
845 if (cur_chr != 0 || sending) {
846 if (sending && (cur_chr == '\\' || cur_chr == 0))
861 *p++ = '\r'; /* +2 for len */
863 *p = '\0'; /* +3 for len */
868 * A modified version of 'strtok'. This version skips \ sequences.
871 char *expect_strtok (s, term)
874 static char *str = "";
879 * If a string was specified then do initial processing.
885 * If this is the escape flag then reset it and ignore the character.
906 * If this is not in the termination string, continue.
908 if (strchr (term, *str) == (char *) 0) {
914 * This is the terminator. Mark the end of the string and stop.
923 * Process the expect string
932 if (strcmp(s, "HANGUP") == 0) {
937 if (strcmp(s, "ABORT") == 0) {
942 if (strcmp(s, "CLR_ABORT") == 0) {
947 if (strcmp(s, "REPORT") == 0) {
952 if (strcmp(s, "CLR_REPORT") == 0) {
957 if (strcmp(s, "TIMEOUT") == 0) {
962 if (strcmp(s, "ECHO") == 0) {
967 if (strcmp(s, "SAY") == 0) {
973 * Fetch the expect and reply string.
976 expect = expect_strtok (s, "-");
979 if (expect == (char *) 0)
982 reply = expect_strtok (s, "-");
985 * Handle the expect string. If successful then exit.
987 if (get_string (expect))
991 * If there is a sub-reply string then send it. Otherwise any condition
994 if (reply == (char *) 0 || exit_code != 3)
1001 * The expectation did not occur. This is terminal.
1004 msgf("Failed (%s)", fail_reason);
1007 terminate(exit_code);
1011 * Translate the input character to the appropriate string for printing
1018 static char string[10];
1021 meta = (c & 0x80) ? "M-" : "";
1025 sprintf(string, "%s^%c", meta, (int)c + '@');
1027 sprintf(string, "%s^?", meta);
1029 sprintf(string, "%s%c", meta, c);
1035 * process the reply string
1040 char file_data[STR_LEN];
1045 write(2, s, strlen(s));
1052 if (strcmp(s, "OFF") == 0)
1053 signal(SIGHUP, SIG_IGN);
1055 signal(SIGHUP, sighup);
1061 echo = (strcmp(s, "ON") == 0);
1070 if (n_aborts >= MAX_ABORTS)
1071 fatal(2, "Too many ABORT strings");
1075 if (strlen(s1) > strlen(s)
1076 || strlen(s1) + 1 > sizeof(fail_buffer))
1077 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1079 abort_string[n_aborts++] = s1;
1082 msgf("abort on (%v)", s);
1086 if (clear_abort_next) {
1092 clear_abort_next = 0;
1096 if (strlen(s1) > strlen(s)
1097 || strlen(s1) + 1 > sizeof(fail_buffer))
1098 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1101 for (i=0; i < n_aborts; i++) {
1102 if ( strcmp(s1,abort_string[i]) == 0 ) {
1103 free(abort_string[i]);
1104 abort_string[i] = NULL;
1108 msgf("clear abort on (%v)", s);
1113 pack_array(abort_string,old_max);
1121 if (n_reports >= MAX_REPORTS)
1122 fatal(2, "Too many REPORT strings");
1125 if (strlen(s1) > strlen(s)
1126 || strlen(s1) + 1 > sizeof(fail_buffer))
1127 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1129 report_string[n_reports++] = s1;
1132 msgf("report (%v)", s);
1136 if (clear_report_next) {
1142 clear_report_next = 0;
1146 if (strlen(s1) > strlen(s)
1147 || strlen(s1) + 1 > sizeof(fail_buffer))
1148 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1150 old_max = n_reports;
1151 for (i=0; i < n_reports; i++) {
1152 if ( strcmp(s1,report_string[i]) == 0 ) {
1153 free(report_string[i]);
1154 report_string[i] = NULL;
1158 msgf("clear report (%v)", s);
1163 pack_array(report_string,old_max);
1173 timeout = DEFAULT_CHAT_TIMEOUT;
1176 msgf("timeout set to %d seconds", timeout);
1182 * The syntax @filename means read the string to send from the
1186 /* skip the @ and any following white-space */
1188 while (*++fn == ' ' || *fn == '\t')
1195 /* open the file and read until STR_LEN-1 bytes or end-of-file */
1198 fatal(1, "%s -- open failed: %m", fn);
1199 while (n < STR_LEN - 1) {
1200 int nr = fread(&file_data[n], 1, STR_LEN - 1 - n, f);
1202 fatal(1, "%s -- read error", fn);
1209 /* use the string we got as the string to send,
1210 but trim off the final newline if any. */
1211 if (n > 0 && file_data[n-1] == '\n')
1218 if (strcmp(s, "EOT") == 0)
1220 else if (strcmp(s, "BREAK") == 0)
1232 status = read(0, &c, 1);
1236 return ((int)c & 0x7F);
1239 msgf("warning: read() on stdin returned %d", status);
1242 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1243 fatal(2, "Can't get file mode flags on stdin: %m");
1245 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1246 fatal(2, "Can't set file mode flags on stdin: %m");
1258 usleep(10000); /* inter-character typing delay (?) */
1260 status = write(1, &ch, 1);
1267 msgf("warning: write() on stdout returned %d", status);
1270 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1271 fatal(2, "Can't get file mode flags on stdin, %m");
1273 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1274 fatal(2, "Can't set file mode flags on stdin: %m");
1283 if (alarmed || put_char(c) < 0) {
1288 if (errno == EINTR || errno == EWOULDBLOCK)
1289 msgf(" -- write timed out");
1291 msgf(" -- write failed: %m");
1306 msgf("send (??????)");
1308 msgf("send (%v)", s);
1311 alarm(timeout); alarmed = 0;
1314 register char c = *s++;
1317 if (!write_char (c))
1333 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1337 if (!write_char (c))
1349 * Echo a character to stderr.
1350 * When called with -1, a '\n' character is generated when
1351 * the cursor is not at the beginning of a line.
1360 case '\r': /* ignore '\r' */
1372 write(2, s, strlen(s));
1379 * 'Wait for' this string to appear on this file descriptor.
1381 int get_string(string)
1382 register char *string;
1385 int c, printed = 0, len, minlen;
1386 register char *s = temp, *end = s + STR_LEN;
1387 char *logged = temp;
1389 fail_reason = (char *)0;
1390 string = clean(string, 0);
1391 len = strlen(string);
1392 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1395 msgf("expect (%v)", string);
1397 if (len > STR_LEN) {
1398 msgf("expect string is too long");
1412 while ( ! alarmed && (c = get_char()) >= 0) {
1413 int n, abort_len, report_len;
1417 if (verbose && c == '\n') {
1419 msgf(""); /* blank line */
1421 msgf("%0.*v", s - logged, logged);
1427 if (verbose && s >= logged + 80) {
1428 msgf("%0.*v", s - logged, logged);
1434 fputc( '\n', stderr );
1436 fprintf( stderr, "%s", character(c) );
1439 if (!report_gathering) {
1440 for (n = 0; n < n_reports; ++n) {
1441 if ((report_string[n] != (char*) NULL) &&
1442 s - temp >= (report_len = strlen(report_string[n])) &&
1443 strncmp(s - report_len, report_string[n], report_len) == 0) {
1444 time_t time_now = time ((time_t*) NULL);
1445 struct tm* tm_now = localtime (&time_now);
1447 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1448 strcat (report_buffer, report_string[n]);
1450 report_string[n] = (char *) NULL;
1451 report_gathering = 1;
1458 int rep_len = strlen (report_buffer);
1459 report_buffer[rep_len] = c;
1460 report_buffer[rep_len + 1] = '\0';
1463 report_gathering = 0;
1464 fprintf (report_fp, "chat: %s\n", report_buffer);
1468 if (s - temp >= len &&
1469 c == string[len - 1] &&
1470 strncmp(s - len, string, len) == 0) {
1473 msgf("%0.*v", s - logged, logged);
1474 msgf(" -- got it\n");
1482 for (n = 0; n < n_aborts; ++n) {
1483 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1484 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1487 msgf("%0.*v", s - logged, logged);
1494 strcpy(fail_reason = fail_buffer, abort_string[n]);
1500 if (logged < s - minlen) {
1502 msgf("%0.*v", s - logged, logged);
1506 memmove(temp, s, minlen);
1507 logged = temp + (logged - s);
1511 if (alarmed && verbose)
1512 msgf("warning: alarm synchronization problem");
1517 if (verbose && printed) {
1519 msgf(" -- read timed out");
1521 msgf(" -- read failed: %m");
1530 * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1533 #include <sys/param.h>
1534 #if MAXUID > 65536 /* then this is Solaris 2.6 or later */
1540 #include <sys/types.h>
1541 #include <sys/time.h>
1544 usleep -- support routine for 4.2BSD system call emulations
1545 last edit: 29-Oct-1984 D A Gwyn
1548 extern int select();
1551 usleep( usec ) /* returns 0 if ok, else -1 */
1552 long usec; /* delay in microseconds */
1554 static struct { /* `timeval' */
1555 long tv_sec; /* seconds */
1556 long tv_usec; /* microsecs */
1557 } delay; /* _select() timeout */
1559 delay.tv_sec = usec / 1000000L;
1560 delay.tv_usec = usec % 1000000L;
1562 return select(0, (long *)0, (long *)0, (long *)0, &delay);
1567 pack_array (array, end)
1568 char **array; /* The address of the array of string pointers */
1569 int end; /* The index of the next free entry before CLR_ */
1573 for (i = 0; i < end; i++) {
1574 if (array[i] == NULL) {
1575 for (j = i+1; j < end; ++j)
1576 if (array[j] != NULL)
1577 array[i++] = array[j];
1578 for (; i < end; ++i)
1586 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1587 * also specify the length of the output buffer, and we handle the
1588 * %m (error message) format.
1589 * Doesn't do floating-point formats.
1590 * Returns the number of chars put into buf.
1592 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1595 vfmtmsg(buf, buflen, fmt, args)
1602 int width, prec, fillch;
1603 int base, len, neg, quoted;
1604 unsigned long val = 0;
1609 static char hexchars[] = "0123456789abcdef";
1613 while (buflen > 0) {
1614 for (f = fmt; *f != '%' && *f != 0; ++f)
1620 memcpy(buf, fmt, len);
1635 width = va_arg(args, int);
1638 while (isdigit(c)) {
1639 width = width * 10 + c - '0';
1646 prec = va_arg(args, int);
1649 while (isdigit(c)) {
1650 prec = prec * 10 + c - '0';
1661 i = va_arg(args, int);
1670 val = va_arg(args, unsigned int);
1674 val = va_arg(args, unsigned int);
1678 val = (unsigned long) va_arg(args, void *);
1683 str = va_arg(args, char *);
1686 num[0] = va_arg(args, int);
1691 str = strerror(errno);
1693 case 'v': /* "visible" string */
1694 case 'q': /* quoted string */
1696 p = va_arg(args, unsigned char *);
1697 if (fillch == '0' && prec > 0) {
1700 n = strlen((char *)p);
1701 if (prec > 0 && prec < n)
1704 while (n > 0 && buflen > 0) {
1707 if (!quoted && c >= 0x80) {
1712 if (quoted && (c == '"' || c == '\\'))
1714 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1718 case '\t': OUTCHAR('t'); break;
1719 case '\n': OUTCHAR('n'); break;
1720 case '\b': OUTCHAR('b'); break;
1721 case '\f': OUTCHAR('f'); break;
1724 OUTCHAR(hexchars[c >> 4]);
1725 OUTCHAR(hexchars[c & 0xf]);
1742 --fmt; /* so %z outputs %z etc. */
1747 str = num + sizeof(num);
1749 while (str > num + neg) {
1750 *--str = hexchars[val % base];
1752 if (--prec <= 0 && val == 0)
1764 len = num + sizeof(num) - 1 - str;
1767 if (prec > 0 && len > prec)
1773 if ((n = width - len) > 0) {
1781 memcpy(buf, str, len);