1 /* SPDX-License-Identifier: MIT */
3 * Chat -- a program for automatic session establishment (i.e. dial
4 * the phone and log in).
6 * This version is Copyright 1995-2024 Paul Mackerras <paulus@ozlabs.org>
7 * based on the original public-domain version by Karl Fox.
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:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
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
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.
41 * 22-May-99 added environment substitutuion, enabled with -E switch.
42 * Andreas Arens <andras@cityweb.de>.
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>.
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>
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).
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.
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.
71 * In the same vein as above, added CLR_REPORT keyword.
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.
78 * Francis Demierre <Francis@SwissMail.Com>
79 * Thu May 15 17:15:40 MET DST 1997
82 * Added -r "report file" switch & REPORT keyword.
83 * Robert Geer <bgeer@xmission.com>
85 * Added -s "use stderr" and -S "don't use syslog" switches.
87 * Karl O. Pinc <kop@meme.com>
90 * Added -e "echo" switch & ECHO keyword
91 * Dick Streefland <dicks@tasking.nl>
94 * Considerable updates and modifications by
95 * Al Longyear <longyear@pobox.com>
96 * Paul Mackerras <paulus@cs.anu.edu.au>
99 * The original author is:
101 * Karl Fox <karl@MorningStar.Com>
102 * Morning Star Technologies, Inc.
103 * 1760 Zollinger Road
118 #include <sys/types.h>
119 #include <sys/stat.h>
142 #define O_NONBLOCK O_NDELAY
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)] :\
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)
162 static int _O = 0; /* Internal state */
163 /*************** Micro getopt() *********************************************/
167 #define MAX_ABORTS 50
168 #define MAX_REPORTS 50
169 #define DEFAULT_CHAT_TIMEOUT 45
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;
187 int have_tty_parameters = 0;
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;
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;
203 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
205 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
206 int clear_abort_next = 0;
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;
213 int say_next = 0, hup_next = 0;
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);
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);
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);
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++ */
246 int main (int, char *[]);
248 void *dup_mem(void *b, size_t c)
250 void *ans = malloc (c);
252 fatal(2, "memory error!");
258 void *copy_of (char *s)
260 return dup_mem (s, strlen (s) + 1);
263 /* grow a char buffer and keep a pointer offset */
264 char *grow(char *s, char **p, size_t len)
266 size_t l = *p - s; /* save p as distance into s */
270 fatal(2, "memory error!");
271 *p = s + l; /* restore p */
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]] ...]]]
280 * Perform a UUCP-dialer-like chat script on stdin and stdout.
283 main(int argc, char **argv)
288 program_name = *argv;
291 while ((option = OPTION(argc, argv)) != 0) {
318 if ((arg = OPTARG(argc, argv)) != NULL)
319 chat_file = copy_of(arg);
325 if ((arg = OPTARG(argc, argv)) != NULL)
332 arg = OPTARG (argc, argv);
334 if (report_fp != NULL)
336 report_file = copy_of (arg);
337 report_fp = fopen (report_file, "a");
338 if (report_fp != NULL) {
340 fprintf (report_fp, "Opening \"%s\"...\n",
348 if ((arg = OPTARG(argc, argv)) != NULL)
349 phone_num = copy_of(arg);
355 if ((arg = OPTARG(argc, argv)) != NULL)
356 phone_num2 = copy_of(arg);
367 * Default the report file to the stderr location
369 if (report_fp == NULL)
373 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
376 setlogmask(LOG_UPTO(LOG_INFO));
378 setlogmask(LOG_UPTO(LOG_WARNING));
383 if (chat_file != NULL) {
384 arg = ARG(argc, argv);
390 while ((arg = ARG(argc, argv)) != NULL) {
393 if ((arg = ARG(argc, argv)) != NULL)
404 * Process a chat script when read from a file.
407 void do_file (char *chat_file)
410 char *sp, *arg, quote;
414 cfp = fopen (chat_file, "r");
416 fatal(1, "%s -- open failed: %m", chat_file);
421 while (fgets(buf, STR_LEN, cfp) != NULL) {
422 sp = strchr (buf, '\n');
429 /* lines starting with '#' are comments. If a real '#'
430 is to be expected, it should be quoted .... */
434 while (*sp != '\0') {
435 if (*sp == ' ' || *sp == '\t') {
440 if (*sp == '"' || *sp == '\'') {
443 while (*sp != quote) {
445 fatal(1, "unterminated quote (line %d)", linect);
455 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
475 * We got an error parsing the command line.
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);
488 * Send a message to syslog and/or stderr.
490 void msgf(const char *fmt, ...)
496 vfmtmsg(line, sizeof(line), fmt, args);
498 syslog(LOG_INFO, "%s", line);
500 fprintf(stderr, "%s\n", line);
505 * Print an error message and terminate.
508 void fatal(int code, const char *fmt, ...)
514 vfmtmsg(line, sizeof(line), fmt, args);
516 syslog(LOG_ERR, "%s", line);
518 fprintf(stderr, "%s\n", line);
526 SIGTYPE sigalrm(int signo)
535 const char *fatalsig = NULL;
537 SIGTYPE sigint(int signo)
542 SIGTYPE sigterm(int signo)
544 fatalsig = "SIGTERM";
547 SIGTYPE sighup(int signo)
563 if (alarmsig && verbose) {
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);
583 set_tty_parameters();
584 sa.sa_handler = sigalrm;
585 sigaction(SIGALRM, &sa, NULL);
590 void set_tty_parameters(void)
592 #if defined(get_term_param)
595 if (get_term_param (&t) < 0)
596 fatal(2, "Can't get terminal parameters: %m");
598 saved_tty_parameters = t;
599 have_tty_parameters = 1;
601 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
609 if (set_term_param (&t) < 0)
610 fatal(2, "Can't set terminal parameters: %m");
614 void break_sequence(void)
621 void terminate(int status)
623 static int terminating = 0;
630 * Allow the last of the report string to be gathered before we terminate.
632 if (report_gathering) {
635 rep_len = strlen(report_buffer);
636 while (rep_len + 1 < sizeof(report_buffer)) {
640 if (c < 0 || iscntrl(c))
642 report_buffer[rep_len] = c;
645 report_buffer[rep_len] = 0;
646 fprintf (report_fp, "chat: %s\n", report_buffer);
648 if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
650 fprintf (report_fp, "Closing \"%s\".\n", report_file);
652 report_fp = (FILE *) NULL;
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");
666 * 'Clean up' this string.
668 char *clean(register char *s,
669 int sending) /* set to 1 when sending (putting) this string. */
672 char *s1, *p, *phchar;
673 int add_return = sending;
674 size_t len = strlen(s) + 3; /* see len comments below */
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')) \
682 p = s1 = malloc(len);
684 fatal(2, "memory error!");
687 if (cur_chr == '^') {
689 if (cur_chr == '\0') {
700 if (use_env && cur_chr == '$') { /* ARI */
708 phchar = getenv(phchar);
709 *s = c; /* restore */
711 len += strlen(phchar);
712 s1 = grow(s1, &p, len);
719 if (cur_chr != '\\') {
725 if (cur_chr == '\0') {
728 *p++ = '\\'; /* +1 for len */
739 if (sending && *s == '\0')
755 if (sending && phone_num) {
756 len += strlen(phone_num);
757 s1 = grow(s1, &p, len);
758 for (phchar = phone_num; *phchar != '\0'; phchar++)
768 if (sending && phone_num2) {
769 len += strlen(phone_num2);
770 s1 = grow(s1, &p, len);
771 for (phchar = phone_num2; *phchar != '\0'; phchar++)
817 if (isoctal (cur_chr)) {
821 cur_chr |= *s++ - '0';
824 cur_chr |= *s++ - '0';
828 if (cur_chr != 0 || sending) {
829 if (sending && (cur_chr == '\\' || cur_chr == 0))
844 *p++ = '\r'; /* +2 for len */
846 *p = '\0'; /* +3 for len */
851 * A modified version of 'strtok'. This version skips \ sequences.
854 char *expect_strtok (char *s, char *term)
856 static char *str = "";
861 * If a string was specified then do initial processing.
867 * If this is the escape flag then reset it and ignore the character.
888 * If this is not in the termination string, continue.
890 if (strchr (term, *str) == (char *) 0) {
896 * This is the terminator. Mark the end of the string and stop.
905 * Process the expect string
908 void chat_expect (char *s)
913 if (strcmp(s, "HANGUP") == 0) {
918 if (strcmp(s, "ABORT") == 0) {
923 if (strcmp(s, "CLR_ABORT") == 0) {
928 if (strcmp(s, "REPORT") == 0) {
933 if (strcmp(s, "CLR_REPORT") == 0) {
938 if (strcmp(s, "TIMEOUT") == 0) {
943 if (strcmp(s, "ECHO") == 0) {
948 if (strcmp(s, "SAY") == 0) {
954 * Fetch the expect and reply string.
957 expect = expect_strtok (s, "-");
960 if (expect == (char *) 0)
963 reply = expect_strtok (s, "-");
966 * Handle the expect string. If successful then exit.
968 if (get_string (expect))
972 * If there is a sub-reply string then send it. Otherwise any condition
975 if (reply == (char *) 0 || exit_code != 3)
983 * The expectation did not occur. This is terminal.
986 msgf("Failed (%s)", fail_reason);
989 terminate(exit_code);
993 * Translate the input character to the appropriate string for printing
997 char *character(int c)
999 static char string[10];
1002 meta = (c & 0x80) ? "M-" : "";
1006 sprintf(string, "%s^%c", meta, (int)c + '@');
1008 sprintf(string, "%s^?", meta);
1010 sprintf(string, "%s%c", meta, c);
1016 * process the reply string
1018 int chat_send (register char *s)
1020 char file_data[STR_LEN];
1022 struct sigaction sa;
1028 ret = write(2, s, len) != len;
1035 memset(&sa, 0, sizeof(sa));
1037 if (strcmp(s, "OFF") == 0)
1038 sa.sa_handler = SIG_IGN;
1040 sa.sa_handler = sighup;
1041 sigaction(SIGHUP, &sa, NULL);
1047 echo = (strcmp(s, "ON") == 0);
1056 if (n_aborts >= MAX_ABORTS)
1057 fatal(2, "Too many ABORT strings");
1061 if (strlen(s1) + 1 > sizeof(fail_buffer))
1062 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1064 abort_string[n_aborts++] = s1;
1067 msgf("abort on (%v)", s1);
1071 if (clear_abort_next) {
1077 clear_abort_next = 0;
1081 if (strlen(s1) + 1 > sizeof(fail_buffer))
1082 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
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;
1092 msgf("clear abort on (%v)", s1);
1097 pack_array(abort_string,old_max);
1105 if (n_reports >= MAX_REPORTS)
1106 fatal(2, "Too many REPORT strings");
1109 if (strlen(s1) + 1 > sizeof(fail_buffer))
1110 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1112 report_string[n_reports++] = s1;
1115 msgf("report (%v)", s1);
1119 if (clear_report_next) {
1125 clear_report_next = 0;
1129 if (strlen(s1) + 1 > sizeof(fail_buffer))
1130 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
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;
1140 msgf("clear report (%v)", s1);
1145 pack_array(report_string,old_max);
1156 timeout = DEFAULT_CHAT_TIMEOUT;
1159 msgf("timeout set to %d seconds", timeout);
1165 * The syntax @filename means read the string to send from the
1169 /* skip the @ and any following white-space */
1171 while (*++fn == ' ' || *fn == '\t')
1178 /* open the file and read until STR_LEN-1 bytes or end-of-file */
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);
1185 fatal(1, "%s -- read error", fn);
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')
1201 if (strcmp(s, "EOT") == 0)
1203 else if (strcmp(s, "BREAK") == 0)
1217 status = read(0, &c, 1);
1222 return ((int)c & 0x7F);
1225 msgf("warning: read() on stdin returned %d", status);
1237 usleep(10000); /* inter-character typing delay (?) */
1240 status = write(1, &ch, 1);
1248 msgf("warning: write() on stdout returned %d", status);
1255 int write_char(int c)
1257 if (alarmed || put_char(c) < 0) {
1262 if (errno == EINTR || errno == EWOULDBLOCK)
1263 msgf(" -- write timed out");
1265 msgf(" -- write failed: %m");
1272 int put_string(register char *s)
1282 msgf("send (?????\?)");
1284 msgf("send (%v)", s);
1287 alarm(timeout); alarmed = 0;
1290 register char c = *s++;
1293 if (!write_char (c)) {
1311 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1315 if (!write_char (c)) {
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.
1335 int echo_stderr(int n)
1342 case '\r': /* ignore '\r' */
1349 ret = write(2, "\n", 1) != 1;
1355 ret = write(2, s, len) != len;
1364 * 'Wait for' this string to appear on this file descriptor.
1366 int get_string(register char *string)
1369 int c, printed = 0, len, minlen;
1370 register char *s = temp, *end = s + STR_LEN;
1371 char *s1, *logged = temp;
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;
1379 msgf("expect (%v)", string);
1381 if (len > STR_LEN) {
1382 msgf("expect string is too long");
1398 while ( ! alarmed && (c = get_char()) >= 0) {
1399 int n, abort_len, report_len;
1402 if (echo_stderr(c) != 0) {
1403 fatal(2, "Could not write to stderr, %m");
1406 if (verbose && c == '\n') {
1408 msgf(""); /* blank line */
1410 msgf("%0.*v", s - logged, logged);
1416 if (verbose && s >= logged + 80) {
1417 msgf("%0.*v", s - logged, logged);
1423 fputc( '\n', stderr );
1425 fprintf( stderr, "%s", character(c) );
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);
1436 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1437 strcat (report_buffer, report_string[n]);
1439 free(report_string[n]);
1440 report_string[n] = (char *) NULL;
1441 report_gathering = 1;
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';
1455 report_gathering = 0;
1456 fprintf (report_fp, "chat: %s\n", report_buffer);
1460 if (s - temp >= len &&
1461 c == string[len - 1] &&
1462 strncmp(s - len, string, len) == 0) {
1465 msgf("%0.*v", s - logged, logged);
1466 msgf(" -- got it\n");
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) {
1480 msgf("%0.*v", s - logged, logged);
1487 strcpy(fail_reason = fail_buffer, abort_string[n]);
1494 if (logged < s - minlen) {
1496 msgf("%0.*v", s - logged, logged);
1500 memmove(temp, s, minlen);
1501 logged = temp + (logged - s);
1505 if (alarmed && verbose)
1506 msgf("warning: alarm synchronization problem");
1511 if (verbose && printed) {
1513 msgf(" -- read timed out");
1515 msgf(" -- read failed: %m");
1525 * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1528 #include <sys/param.h>
1529 #if MAXUID > 65536 /* then this is Solaris 2.6 or later */
1535 #include <sys/types.h>
1536 #include <sys/time.h>
1539 usleep -- support routine for 4.2BSD system call emulations
1540 last edit: 29-Oct-1984 D A Gwyn
1543 extern int select();
1545 /* returns 0 if ok, else -1 */
1546 int usleep(long usec) /* delay in microseconds */
1548 static struct { /* `timeval' */
1549 long tv_sec; /* seconds */
1550 long tv_usec; /* microsecs */
1551 } delay; /* _select() timeout */
1553 delay.tv_sec = usec / 1000000L;
1554 delay.tv_usec = usec % 1000000L;
1556 return select(0, (long *)0, (long *)0, (long *)0, &delay);
1561 char **array, /* The address of the array of string pointers */
1562 int end) /* The index of the next free entry before CLR_ */
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)
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.
1585 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1588 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1591 int width, prec, fillch;
1592 int base, len, neg, quoted;
1593 unsigned long val = 0;
1598 static char hexchars[] = "0123456789abcdef";
1602 while (buflen > 0) {
1603 for (f = fmt; *f != '%' && *f != 0; ++f)
1609 memcpy(buf, fmt, len);
1624 width = va_arg(args, int);
1627 while (isdigit(c)) {
1628 width = width * 10 + c - '0';
1635 prec = va_arg(args, int);
1638 while (isdigit(c)) {
1639 prec = prec * 10 + c - '0';
1650 i = va_arg(args, int);
1659 val = va_arg(args, unsigned int);
1663 val = va_arg(args, unsigned int);
1667 val = (unsigned long) va_arg(args, void *);
1672 str = va_arg(args, char *);
1675 num[0] = va_arg(args, int);
1680 str = strerror(errno);
1682 case 'v': /* "visible" string */
1683 case 'q': /* quoted string */
1685 p = va_arg(args, unsigned char *);
1686 if (fillch == '0' && prec > 0) {
1689 n = strlen((char *)p);
1690 if (prec > 0 && prec < n)
1693 while (n > 0 && buflen > 0) {
1696 if (!quoted && c >= 0x80) {
1701 if (quoted && (c == '"' || c == '\\'))
1703 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1707 case '\t': OUTCHAR('t'); break;
1708 case '\n': OUTCHAR('n'); break;
1709 case '\b': OUTCHAR('b'); break;
1710 case '\f': OUTCHAR('f'); break;
1713 OUTCHAR(hexchars[c >> 4]);
1714 OUTCHAR(hexchars[c & 0xf]);
1731 --fmt; /* so %z outputs %z etc. */
1736 str = num + sizeof(num);
1738 while (str > num + neg) {
1739 *--str = hexchars[val % base];
1741 if (--prec <= 0 && val == 0)
1753 len = num + sizeof(num) - 1 - str;
1756 if (prec > 0 && len > prec)
1762 if ((n = width - len) > 0) {
1770 memcpy(buf, str, len);