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);
519 * Print an error message and terminate.
522 void fatal __V((int code, const char *fmt, ...))
532 code = va_arg(args, int);
533 fmt = va_arg(args, char *);
536 vfmtmsg(line, sizeof(line), fmt, args);
538 syslog(LOG_ERR, "%s", line);
540 fprintf(stderr, "%s\n", line);
547 SIGTYPE sigalrm(signo)
553 alarmed = 1; /* Reset alarm to avoid race window */
554 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
556 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
557 fatal(2, "Can't get file mode flags on stdin: %m");
559 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
560 fatal(2, "Can't set file mode flags on stdin: %m");
570 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
571 fatal(2, "Can't get file mode flags on stdin: %m");
573 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
574 fatal(2, "Can't set file mode flags on stdin: %m");
577 SIGTYPE sigint(signo)
583 SIGTYPE sigterm(signo)
589 SIGTYPE sighup(signo)
597 signal(SIGINT, sigint);
598 signal(SIGTERM, sigterm);
599 signal(SIGHUP, sighup);
601 set_tty_parameters();
602 signal(SIGALRM, sigalrm);
607 void set_tty_parameters()
609 #if defined(get_term_param)
612 if (get_term_param (&t) < 0)
613 fatal(2, "Can't get terminal parameters: %m");
615 saved_tty_parameters = t;
616 have_tty_parameters = 1;
618 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
626 if (set_term_param (&t) < 0)
627 fatal(2, "Can't set terminal parameters: %m");
631 void break_sequence()
638 void terminate(status)
641 static int terminating = 0;
648 * Allow the last of the report string to be gathered before we terminate.
650 if (report_gathering) {
653 rep_len = strlen(report_buffer);
654 while (rep_len + 1 <= sizeof(report_buffer)) {
658 if (c < 0 || iscntrl(c))
660 report_buffer[rep_len] = c;
663 report_buffer[rep_len] = 0;
664 fprintf (report_fp, "chat: %s\n", report_buffer);
666 if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
668 fprintf (report_fp, "Closing \"%s\".\n", report_file);
670 report_fp = (FILE *) NULL;
673 #if defined(get_term_param)
674 if (have_tty_parameters) {
675 if (set_term_param (&saved_tty_parameters) < 0)
676 fatal(2, "Can't restore terminal parameters: %m");
684 * 'Clean up' this string.
686 char *clean(s, sending)
688 int sending; /* set to 1 when sending (putting) this string. */
691 char *s1, *p, *phchar;
692 int add_return = sending;
693 size_t len = strlen(s) + 3; /* see len comments below */
695 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
696 #define isalnumx(chr) ((((chr) >= '0') && ((chr) <= '9')) \
697 || (((chr) >= 'a') && ((chr) <= 'z')) \
698 || (((chr) >= 'A') && ((chr) <= 'Z')) \
701 p = s1 = malloc(len);
703 fatal(2, "memory error!");
706 if (cur_chr == '^') {
708 if (cur_chr == '\0') {
719 if (use_env && cur_chr == '$') { /* ARI */
727 phchar = getenv(phchar);
728 *s = c; /* restore */
730 len += strlen(phchar);
731 s1 = grow(s1, &p, len);
738 if (cur_chr != '\\') {
744 if (cur_chr == '\0') {
747 *p++ = '\\'; /* +1 for len */
758 if (sending && *s == '\0')
774 if (sending && phone_num) {
775 len += strlen(phone_num);
776 s1 = grow(s1, &p, len);
777 for (phchar = phone_num; *phchar != '\0'; phchar++)
787 if (sending && phone_num2) {
788 len += strlen(phone_num2);
789 s1 = grow(s1, &p, len);
790 for (phchar = phone_num2; *phchar != '\0'; phchar++)
836 if (isoctal (cur_chr)) {
840 cur_chr |= *s++ - '0';
843 cur_chr |= *s++ - '0';
847 if (cur_chr != 0 || sending) {
848 if (sending && (cur_chr == '\\' || cur_chr == 0))
863 *p++ = '\r'; /* +2 for len */
865 *p = '\0'; /* +3 for len */
870 * A modified version of 'strtok'. This version skips \ sequences.
873 char *expect_strtok (s, term)
876 static char *str = "";
881 * If a string was specified then do initial processing.
887 * If this is the escape flag then reset it and ignore the character.
908 * If this is not in the termination string, continue.
910 if (strchr (term, *str) == (char *) 0) {
916 * This is the terminator. Mark the end of the string and stop.
925 * Process the expect string
934 if (strcmp(s, "HANGUP") == 0) {
939 if (strcmp(s, "ABORT") == 0) {
944 if (strcmp(s, "CLR_ABORT") == 0) {
949 if (strcmp(s, "REPORT") == 0) {
954 if (strcmp(s, "CLR_REPORT") == 0) {
959 if (strcmp(s, "TIMEOUT") == 0) {
964 if (strcmp(s, "ECHO") == 0) {
969 if (strcmp(s, "SAY") == 0) {
975 * Fetch the expect and reply string.
978 expect = expect_strtok (s, "-");
981 if (expect == (char *) 0)
984 reply = expect_strtok (s, "-");
987 * Handle the expect string. If successful then exit.
989 if (get_string (expect))
993 * If there is a sub-reply string then send it. Otherwise any condition
996 if (reply == (char *) 0 || exit_code != 3)
1003 * The expectation did not occur. This is terminal.
1006 msgf("Failed (%s)", fail_reason);
1009 terminate(exit_code);
1013 * Translate the input character to the appropriate string for printing
1020 static char string[10];
1023 meta = (c & 0x80) ? "M-" : "";
1027 sprintf(string, "%s^%c", meta, (int)c + '@');
1029 sprintf(string, "%s^?", meta);
1031 sprintf(string, "%s%c", meta, c);
1037 * process the reply string
1042 char file_data[STR_LEN];
1047 write(2, s, strlen(s));
1054 if (strcmp(s, "OFF") == 0)
1055 signal(SIGHUP, SIG_IGN);
1057 signal(SIGHUP, sighup);
1063 echo = (strcmp(s, "ON") == 0);
1072 if (n_aborts >= MAX_ABORTS)
1073 fatal(2, "Too many ABORT strings");
1077 if (strlen(s1) > strlen(s)
1078 || strlen(s1) + 1 > sizeof(fail_buffer))
1079 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1081 abort_string[n_aborts++] = s1;
1084 msgf("abort on (%v)", s);
1088 if (clear_abort_next) {
1094 clear_abort_next = 0;
1098 if (strlen(s1) > strlen(s)
1099 || strlen(s1) + 1 > sizeof(fail_buffer))
1100 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1103 for (i=0; i < n_aborts; i++) {
1104 if ( strcmp(s1,abort_string[i]) == 0 ) {
1105 free(abort_string[i]);
1106 abort_string[i] = NULL;
1110 msgf("clear abort on (%v)", s);
1115 pack_array(abort_string,old_max);
1123 if (n_reports >= MAX_REPORTS)
1124 fatal(2, "Too many REPORT strings");
1127 if (strlen(s1) > strlen(s)
1128 || strlen(s1) + 1 > sizeof(fail_buffer))
1129 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1131 report_string[n_reports++] = s1;
1134 msgf("report (%v)", s);
1138 if (clear_report_next) {
1144 clear_report_next = 0;
1148 if (strlen(s1) > strlen(s)
1149 || strlen(s1) + 1 > sizeof(fail_buffer))
1150 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1152 old_max = n_reports;
1153 for (i=0; i < n_reports; i++) {
1154 if ( strcmp(s1,report_string[i]) == 0 ) {
1155 free(report_string[i]);
1156 report_string[i] = NULL;
1160 msgf("clear report (%v)", s);
1165 pack_array(report_string,old_max);
1176 timeout = DEFAULT_CHAT_TIMEOUT;
1179 msgf("timeout set to %d seconds", timeout);
1185 * The syntax @filename means read the string to send from the
1189 /* skip the @ and any following white-space */
1191 while (*++fn == ' ' || *fn == '\t')
1198 /* open the file and read until STR_LEN-1 bytes or end-of-file */
1201 fatal(1, "%s -- open failed: %m", fn);
1202 while (n < STR_LEN - 1) {
1203 int nr = fread(&file_data[n], 1, STR_LEN - 1 - n, f);
1205 fatal(1, "%s -- read error", fn);
1212 /* use the string we got as the string to send,
1213 but trim off the final newline if any. */
1214 if (n > 0 && file_data[n-1] == '\n')
1221 if (strcmp(s, "EOT") == 0)
1223 else if (strcmp(s, "BREAK") == 0)
1235 status = read(0, &c, 1);
1239 return ((int)c & 0x7F);
1242 msgf("warning: read() on stdin returned %d", status);
1245 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1246 fatal(2, "Can't get file mode flags on stdin: %m");
1248 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1249 fatal(2, "Can't set file mode flags on stdin: %m");
1261 usleep(10000); /* inter-character typing delay (?) */
1263 status = write(1, &ch, 1);
1270 msgf("warning: write() on stdout returned %d", status);
1273 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1274 fatal(2, "Can't get file mode flags on stdin, %m");
1276 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1277 fatal(2, "Can't set file mode flags on stdin: %m");
1286 if (alarmed || put_char(c) < 0) {
1291 if (errno == EINTR || errno == EWOULDBLOCK)
1292 msgf(" -- write timed out");
1294 msgf(" -- write failed: %m");
1309 msgf("send (?????\?)");
1311 msgf("send (%v)", s);
1314 alarm(timeout); alarmed = 0;
1317 register char c = *s++;
1320 if (!write_char (c))
1336 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1340 if (!write_char (c))
1352 * Echo a character to stderr.
1353 * When called with -1, a '\n' character is generated when
1354 * the cursor is not at the beginning of a line.
1363 case '\r': /* ignore '\r' */
1375 write(2, s, strlen(s));
1382 * 'Wait for' this string to appear on this file descriptor.
1384 int get_string(string)
1385 register char *string;
1388 int c, printed = 0, len, minlen;
1389 register char *s = temp, *end = s + STR_LEN;
1390 char *logged = temp;
1392 fail_reason = (char *)0;
1393 string = clean(string, 0);
1394 len = strlen(string);
1395 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1398 msgf("expect (%v)", string);
1400 if (len > STR_LEN) {
1401 msgf("expect string is too long");
1415 while ( ! alarmed && (c = get_char()) >= 0) {
1416 int n, abort_len, report_len;
1420 if (verbose && c == '\n') {
1422 msgf(""); /* blank line */
1424 msgf("%0.*v", s - logged, logged);
1430 if (verbose && s >= logged + 80) {
1431 msgf("%0.*v", s - logged, logged);
1437 fputc( '\n', stderr );
1439 fprintf( stderr, "%s", character(c) );
1442 if (!report_gathering) {
1443 for (n = 0; n < n_reports; ++n) {
1444 if ((report_string[n] != (char*) NULL) &&
1445 s - temp >= (report_len = strlen(report_string[n])) &&
1446 strncmp(s - report_len, report_string[n], report_len) == 0) {
1447 time_t time_now = time ((time_t*) NULL);
1448 struct tm* tm_now = localtime (&time_now);
1450 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1451 strcat (report_buffer, report_string[n]);
1453 report_string[n] = (char *) NULL;
1454 report_gathering = 1;
1461 int rep_len = strlen (report_buffer);
1462 report_buffer[rep_len] = c;
1463 report_buffer[rep_len + 1] = '\0';
1466 report_gathering = 0;
1467 fprintf (report_fp, "chat: %s\n", report_buffer);
1471 if (s - temp >= len &&
1472 c == string[len - 1] &&
1473 strncmp(s - len, string, len) == 0) {
1476 msgf("%0.*v", s - logged, logged);
1477 msgf(" -- got it\n");
1485 for (n = 0; n < n_aborts; ++n) {
1486 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1487 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1490 msgf("%0.*v", s - logged, logged);
1497 strcpy(fail_reason = fail_buffer, abort_string[n]);
1503 if (logged < s - minlen) {
1505 msgf("%0.*v", s - logged, logged);
1509 memmove(temp, s, minlen);
1510 logged = temp + (logged - s);
1514 if (alarmed && verbose)
1515 msgf("warning: alarm synchronization problem");
1520 if (verbose && printed) {
1522 msgf(" -- read timed out");
1524 msgf(" -- read failed: %m");
1533 * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1536 #include <sys/param.h>
1537 #if MAXUID > 65536 /* then this is Solaris 2.6 or later */
1543 #include <sys/types.h>
1544 #include <sys/time.h>
1547 usleep -- support routine for 4.2BSD system call emulations
1548 last edit: 29-Oct-1984 D A Gwyn
1551 extern int select();
1554 usleep( usec ) /* returns 0 if ok, else -1 */
1555 long usec; /* delay in microseconds */
1557 static struct { /* `timeval' */
1558 long tv_sec; /* seconds */
1559 long tv_usec; /* microsecs */
1560 } delay; /* _select() timeout */
1562 delay.tv_sec = usec / 1000000L;
1563 delay.tv_usec = usec % 1000000L;
1565 return select(0, (long *)0, (long *)0, (long *)0, &delay);
1570 pack_array (array, end)
1571 char **array; /* The address of the array of string pointers */
1572 int end; /* The index of the next free entry before CLR_ */
1576 for (i = 0; i < end; i++) {
1577 if (array[i] == NULL) {
1578 for (j = i+1; j < end; ++j)
1579 if (array[j] != NULL)
1580 array[i++] = array[j];
1581 for (; i < end; ++i)
1589 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1590 * also specify the length of the output buffer, and we handle the
1591 * %m (error message) format.
1592 * Doesn't do floating-point formats.
1593 * Returns the number of chars put into buf.
1595 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1598 vfmtmsg(buf, buflen, fmt, args)
1605 int width, prec, fillch;
1606 int base, len, neg, quoted;
1607 unsigned long val = 0;
1612 static char hexchars[] = "0123456789abcdef";
1616 while (buflen > 0) {
1617 for (f = fmt; *f != '%' && *f != 0; ++f)
1623 memcpy(buf, fmt, len);
1638 width = va_arg(args, int);
1641 while (isdigit(c)) {
1642 width = width * 10 + c - '0';
1649 prec = va_arg(args, int);
1652 while (isdigit(c)) {
1653 prec = prec * 10 + c - '0';
1664 i = va_arg(args, int);
1673 val = va_arg(args, unsigned int);
1677 val = va_arg(args, unsigned int);
1681 val = (unsigned long) va_arg(args, void *);
1686 str = va_arg(args, char *);
1689 num[0] = va_arg(args, int);
1694 str = strerror(errno);
1696 case 'v': /* "visible" string */
1697 case 'q': /* quoted string */
1699 p = va_arg(args, unsigned char *);
1700 if (fillch == '0' && prec > 0) {
1703 n = strlen((char *)p);
1704 if (prec > 0 && prec < n)
1707 while (n > 0 && buflen > 0) {
1710 if (!quoted && c >= 0x80) {
1715 if (quoted && (c == '"' || c == '\\'))
1717 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1721 case '\t': OUTCHAR('t'); break;
1722 case '\n': OUTCHAR('n'); break;
1723 case '\b': OUTCHAR('b'); break;
1724 case '\f': OUTCHAR('f'); break;
1727 OUTCHAR(hexchars[c >> 4]);
1728 OUTCHAR(hexchars[c & 0xf]);
1745 --fmt; /* so %z outputs %z etc. */
1750 str = num + sizeof(num);
1752 while (str > num + neg) {
1753 *--str = hexchars[val % base];
1755 if (--prec <= 0 && val == 0)
1767 len = num + sizeof(num) - 1 - str;
1770 if (prec > 0 && len > prec)
1776 if ((n = width - len) > 0) {
1784 memcpy(buf, str, len);