2 * Copyright 2000 Sun Microsystems, Inc. All rights reserved.
3 * Use is subject to license terms.
6 * Chat -- a program for automatic session establishment (i.e. dial
7 * the phone and log in).
9 * Standard termination codes:
10 * 0 - successful completion of the script
11 * 1 - invalid argument, expect string too large, etc.
12 * 2 - error on an I/O operation or fatal error condition.
13 * 3 - timeout waiting for a simple string.
14 * 4 - the first string declared as "ABORT"
15 * 5 - the second string declared as "ABORT"
16 * 6 - ... and so on for successive ABORT strings.
18 * This software is in the public domain.
21 * 22-May-99 added environment substitutuion, enabled with -E switch.
22 * Andreas Arens <andras@cityweb.de>.
24 * 12-May-99 added a feature to read data to be sent from a file,
25 * if the send string starts with @. Idea from gpk <gpk@onramp.net>.
27 * added -T and -U option and \T and \U substitution to pass a phone
28 * number into chat script. Two are needed for some ISDN TA applications.
29 * Keith Dart <kdart@cisco.com>
32 * Added SAY keyword to send output to stderr.
33 * This allows to turn ECHO OFF and to output specific, user selected,
34 * text to give progress messages. This best works when stderr
35 * exists (i.e.: pppd in nodetach mode).
37 * Added HANGUP directives to allow for us to be called
38 * back. When HANGUP is set to NO, chat will not hangup at HUP signal.
39 * We rely on timeouts in that case.
41 * Added CLR_ABORT to clear previously set ABORT string. This has been
42 * dictated by the HANGUP above as "NO CARRIER" (for example) must be
43 * an ABORT condition until we know the other host is going to close
44 * the connection for call back. As soon as we have completed the
45 * first stage of the call back sequence, "NO CARRIER" is a valid, non
46 * fatal string. As soon as we got called back (probably get "CONNECT"),
47 * we should re-arm the ABORT "NO CARRIER". Hence the CLR_ABORT command.
48 * Note that CLR_ABORT packs the abort_strings[] array so that we do not
49 * have unused entries not being reclaimed.
51 * In the same vein as above, added CLR_REPORT keyword.
53 * Allow for comments. Line starting with '#' are comments and are
54 * ignored. If a '#' is to be expected as the first character, the
55 * expect string must be quoted.
58 * Francis Demierre <Francis@SwissMail.Com>
59 * Thu May 15 17:15:40 MET DST 1997
62 * Added -r "report file" switch & REPORT keyword.
63 * Robert Geer <bgeer@xmission.com>
65 * Added -s "use stderr" and -S "don't use syslog" switches.
67 * Karl O. Pinc <kop@meme.com>
70 * Added -e "echo" switch & ECHO keyword
71 * Dick Streefland <dicks@tasking.nl>
74 * Considerable updates and modifications by
75 * Al Longyear <longyear@pobox.com>
76 * Paul Mackerras <paulus@cs.anu.edu.au>
79 * The original author is:
81 * Karl Fox <karl@MorningStar.Com>
82 * Morning Star Technologies, Inc.
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
= NULL
;
178 char *report_file
= NULL
;
179 char *chat_file
= NULL
;
180 char *phone_num
= NULL
;
181 char *phone_num2
= NULL
;
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
[50] ;
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 void usage
__P((void));
215 void logf
__P((const char *fmt
, ...));
216 void fatal
__P((int code
, const char *fmt
, ...));
217 SIGTYPE sigalrm
__P((int signo
));
218 SIGTYPE sigint
__P((int signo
));
219 SIGTYPE sigterm
__P((int signo
));
220 SIGTYPE sighup
__P((int signo
));
221 void unalarm
__P((void));
222 void init
__P((void));
223 void set_tty_parameters
__P((void));
224 void echo_stderr
__P((int));
225 void break_sequence
__P((void));
226 void terminate
__P((int status
));
227 void do_file
__P((char *chat_file
));
228 int get_string
__P((register char *string
));
229 int put_string
__P((register char *s
));
230 int write_char
__P((int c
));
231 int put_char
__P((int c
));
232 int get_char
__P((void));
233 void chat_send
__P((register char *s
));
234 char *character
__P((int c
));
235 void chat_expect
__P((register char *s
));
236 char *clean
__P((register char *s
, int sending
));
237 void break_sequence
__P((void));
238 void terminate
__P((int status
));
239 void pack_array
__P((char **array
, int end
));
240 char *expect_strtok
__P((char *, char *));
241 int vfmtmsg
__P((char *, int, const char *, va_list)); /* vsprintf++ */
243 int main
__P((int, char *[]));
249 void *ans
= malloc (c
);
251 fatal(2, "memory error!");
260 return dup_mem (s
, strlen (s
) + 1);
264 * chat [ -v ] [ -E ] [ -T number ] [ -U number ] [ -t timeout ] [ -f chat-file ] \
265 * [ -r report-file ] \
266 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
268 * Perform a UUCP-dialer-like chat script on stdin and stdout.
278 program_name
= *argv
;
281 while ((option
= OPTION(argc
, argv
)) != 0) {
308 if ((arg
= OPTARG(argc
, argv
)) != NULL
)
309 chat_file
= copy_of(arg
);
315 if ((arg
= OPTARG(argc
, argv
)) != NULL
)
322 arg
= OPTARG (argc
, argv
);
324 if (report_fp
!= NULL
)
326 report_file
= copy_of (arg
);
327 report_fp
= fopen (report_file
, "a");
328 if (report_fp
!= NULL
) {
330 fprintf (report_fp
, "Opening \"%s\"...\n",
338 if ((arg
= OPTARG(argc
, argv
)) != NULL
)
339 phone_num
= copy_of(arg
);
345 if ((arg
= OPTARG(argc
, argv
)) != NULL
)
346 phone_num2
= copy_of(arg
);
357 * Default the report file to the stderr location
359 if (report_fp
== NULL
)
364 openlog("chat", LOG_PID
);
366 openlog("chat", LOG_PID
| LOG_NDELAY
, LOG_LOCAL2
);
369 setlogmask(LOG_UPTO(LOG_INFO
));
371 setlogmask(LOG_UPTO(LOG_WARNING
));
377 if (chat_file
!= NULL
) {
378 arg
= ARG(argc
, argv
);
384 while ((arg
= ARG(argc
, argv
)) != NULL
) {
387 if ((arg
= ARG(argc
, argv
)) != NULL
)
397 * Process a chat script when read from a file.
400 void do_file (chat_file
)
404 char *sp
, *arg
, quote
;
408 cfp
= fopen (chat_file
, "r");
410 fatal(1, "%s -- open failed: %m", chat_file
);
415 while (fgets(buf
, STR_LEN
, cfp
) != NULL
) {
416 sp
= strchr (buf
, '\n');
423 /* lines starting with '#' are comments. If a real '#'
424 is to be expected, it should be quoted .... */
428 while (*sp
!= '\0') {
429 if (*sp
== ' ' || *sp
== '\t') {
434 if (*sp
== '"' || *sp
== '\'') {
437 while (*sp
!= quote
) {
439 fatal(1, "unterminated quote (line %d)", linect
);
449 while (*sp
!= '\0' && *sp
!= ' ' && *sp
!= '\t')
467 * We got an error parsing the command line.
472 Usage: %s [-e] [-E] [-v] [-V] [-t timeout] [-r report-file]\n\
473 [-T phone-number] [-U phone-number2] {-f chat-file | chat-script}\n", program_name
);
480 * Send a message to syslog and/or stderr.
482 void logf
__V((const char *fmt
, ...))
491 fmt
= va_arg(args
, char *);
494 vfmtmsg(line
, sizeof(line
), fmt
, args
);
496 syslog(LOG_INFO
, "%s", line
);
498 fprintf(stderr
, "%s\n", line
);
502 * Print an error message and terminate.
505 void fatal
__V((int code
, const char *fmt
, ...))
515 code
= va_arg(args
, int);
516 fmt
= va_arg(args
, char *);
519 vfmtmsg(line
, sizeof(line
), fmt
, args
);
521 syslog(LOG_ERR
, "%s", line
);
523 fprintf(stderr
, "%s\n", line
);
529 SIGTYPE
sigalrm(signo
)
535 alarmed
= 1; /* Reset alarm to avoid race window */
536 signal(SIGALRM
, sigalrm
); /* that can cause hanging in read() */
538 if ((flags
= fcntl(0, F_GETFL
, 0)) == -1)
539 fatal(2, "Can't get file mode flags on stdin: %m");
541 if (fcntl(0, F_SETFL
, flags
| O_NONBLOCK
) == -1)
542 fatal(2, "Can't set file mode flags on stdin: %m");
552 if ((flags
= fcntl(0, F_GETFL
, 0)) == -1)
553 fatal(2, "Can't get file mode flags on stdin: %m");
555 if (fcntl(0, F_SETFL
, flags
& ~O_NONBLOCK
) == -1)
556 fatal(2, "Can't set file mode flags on stdin: %m");
559 SIGTYPE
sigint(signo
)
565 SIGTYPE
sigterm(signo
)
571 SIGTYPE
sighup(signo
)
579 signal(SIGINT
, sigint
);
580 signal(SIGTERM
, sigterm
);
581 signal(SIGHUP
, sighup
);
583 set_tty_parameters();
584 signal(SIGALRM
, sigalrm
);
589 void set_tty_parameters()
591 #if defined(get_term_param)
594 if (get_term_param (&t
) < 0)
595 fatal(2, "Can't get terminal parameters: %m");
597 saved_tty_parameters
= t
;
598 have_tty_parameters
= 1;
600 t
.c_iflag
|= IGNBRK
| ISTRIP
| IGNPAR
;
608 if (set_term_param (&t
) < 0)
609 fatal(2, "Can't set terminal parameters: %m");
613 void break_sequence()
620 void terminate(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
!= NULL
&& 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(s
, sending
)
670 int sending
; /* set to 1 when sending (putting) this string. */
672 char temp
[STR_LEN
], env_str
[STR_LEN
], cur_chr
;
673 register char *s1
, *phchar
;
674 int add_return
= sending
;
675 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
676 #define isalnumx(chr) ((((chr) >= '0') && ((chr) <= '9')) \
677 || (((chr) >= 'a') && ((chr) <= 'z')) \
678 || (((chr) >= 'A') && ((chr) <= 'Z')) \
684 if (cur_chr
== '^') {
686 if (cur_chr
== '\0') {
697 if (use_env
&& cur_chr
== '$') { /* ARI */
702 phchar
= getenv(env_str
);
709 if (cur_chr
!= '\\') {
715 if (cur_chr
== '\0') {
729 if (sending
&& *s
== '\0')
745 if (sending
&& phone_num
) {
746 for (phchar
= phone_num
; *phchar
!= '\0'; phchar
++)
756 if (sending
&& phone_num2
) {
757 for (phchar
= phone_num2
; *phchar
!= '\0'; phchar
++)
803 if (isoctal (cur_chr
)) {
807 cur_chr
|= *s
++ - '0';
810 cur_chr
|= *s
++ - '0';
814 if (cur_chr
!= 0 || sending
) {
815 if (sending
&& (cur_chr
== '\\' || cur_chr
== 0))
832 *s1
++ = '\0'; /* guarantee closure */
833 *s1
++ = '\0'; /* terminate the string */
834 return dup_mem (temp
, (size_t) (s1
- temp
)); /* may have embedded nuls */
838 * A modified version of 'strtok'. This version skips \ sequences.
841 char *expect_strtok (s
, term
)
844 static char *str
= "";
849 * If a string was specified then do initial processing.
855 * If this is the escape flag then reset it and ignore the character.
876 * If this is not in the termination string, continue.
878 if (strchr(term
, *str
) == NULL
) {
884 * This is the terminator. Mark the end of the string and stop.
893 * Process the expect string
902 if (strcmp(s
, "HANGUP") == 0) {
907 if (strcmp(s
, "ABORT") == 0) {
912 if (strcmp(s
, "CLR_ABORT") == 0) {
917 if (strcmp(s
, "REPORT") == 0) {
922 if (strcmp(s
, "CLR_REPORT") == 0) {
927 if (strcmp(s
, "TIMEOUT") == 0) {
932 if (strcmp(s
, "ECHO") == 0) {
937 if (strcmp(s
, "SAY") == 0) {
943 * Fetch the expect and reply string.
946 expect
= expect_strtok (s
, "-");
952 reply
= expect_strtok (s
, "-");
955 * Handle the expect string. If successful then exit.
957 if (get_string (expect
))
961 * If there is a sub-reply string then send it. Otherwise any condition
964 if (reply
== NULL
|| exit_code
!= 3)
971 * The expectation did not occur. This is terminal.
974 logf("Failed (%s)", fail_reason
);
977 terminate(exit_code
);
981 * Translate the input character to the appropriate string for printing
988 static char string
[10];
991 meta
= (c
& 0x80) ? "M-" : "";
995 sprintf(string
, "%s^%c", meta
, (int)c
+ '@');
997 sprintf(string
, "%s^?", meta
);
999 sprintf(string
, "%s%c", meta
, c
);
1005 * process the reply string
1010 char file_data
[STR_LEN
];
1015 write(2, s
, strlen(s
));
1022 if (strcmp(s
, "OFF") == 0)
1023 signal(SIGHUP
, SIG_IGN
);
1025 signal(SIGHUP
, sighup
);
1031 echo
= (strcmp(s
, "ON") == 0);
1040 if (n_aborts
>= MAX_ABORTS
)
1041 fatal(2, "Too many ABORT strings");
1045 if (strlen(s1
) > strlen(s
)
1046 || strlen(s1
) + 1 > sizeof(fail_buffer
))
1047 fatal(1, "Illegal or too-long ABORT string ('%v')", s
);
1049 abort_string
[n_aborts
++] = s1
;
1052 logf("abort on (%v)", s
);
1056 if (clear_abort_next
) {
1062 clear_abort_next
= 0;
1066 if (strlen(s1
) > strlen(s
)
1067 || strlen(s1
) + 1 > sizeof(fail_buffer
))
1068 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s
);
1071 for (i
=0; i
< n_aborts
; i
++) {
1072 if ( strcmp(s1
,abort_string
[i
]) == 0 ) {
1073 free(abort_string
[i
]);
1074 abort_string
[i
] = NULL
;
1078 logf("clear abort on (%v)", s
);
1083 pack_array(abort_string
,old_max
);
1091 if (n_reports
>= MAX_REPORTS
)
1092 fatal(2, "Too many REPORT strings");
1096 if (strlen(s1
) > strlen(s
) || strlen(s1
) > sizeof fail_buffer
- 1)
1097 fatal(1, "Illegal or too-long REPORT string ('%v')", s
);
1099 report_string
[n_reports
++] = s1
;
1102 logf("report (%v)", s
);
1106 if (clear_report_next
) {
1112 clear_report_next
= 0;
1116 if (strlen(s1
) > strlen(s
) || strlen(s1
) > sizeof fail_buffer
- 1)
1117 fatal(1, "Illegal or too-long REPORT string ('%v')", s
);
1119 old_max
= n_reports
;
1120 for (i
=0; i
< n_reports
; i
++) {
1121 if ( strcmp(s1
,report_string
[i
]) == 0 ) {
1122 free(report_string
[i
]);
1123 report_string
[i
] = NULL
;
1127 logf("clear report (%v)", s
);
1132 pack_array(report_string
,old_max
);
1142 timeout
= DEFAULT_CHAT_TIMEOUT
;
1145 logf("timeout set to %d seconds", timeout
);
1151 * The syntax @filename means read the string to send from the
1155 /* skip the @ and any following white-space */
1157 while (*++fn
== ' ' || *fn
== '\t')
1164 /* open the file and read until STR_LEN-1 bytes or end-of-file */
1167 fatal(1, "%s -- open failed: %m", fn
);
1168 while (n
< STR_LEN
- 1) {
1169 int nr
= fread(&file_data
[n
], 1, STR_LEN
- 1 - n
, f
);
1171 fatal(1, "%s -- read error", fn
);
1178 /* use the string we got as the string to send,
1179 but trim off the final newline if any. */
1180 if (n
> 0 && file_data
[n
-1] == '\n')
1187 if (strcmp(s
, "EOT") == 0)
1189 else if (strcmp(s
, "BREAK") == 0)
1201 status
= read(0, &c
, 1);
1205 return ((int)c
& 0x7F);
1208 logf("warning: read() on stdin returned %d", status
);
1212 if ((status
= fcntl(0, F_GETFL
, 0)) == -1)
1213 fatal(2, "Can't get file mode flags on stdin: %m");
1215 if (fcntl(0, F_SETFL
, status
& ~O_NONBLOCK
) == -1)
1216 fatal(2, "Can't set file mode flags on stdin: %m");
1228 usleep(10000); /* inter-character typing delay (?) */
1230 status
= write(1, &ch
, 1);
1237 logf("warning: write() on stdout returned %d", status
);
1241 if ((status
= fcntl(0, F_GETFL
, 0)) == -1)
1242 fatal(2, "Can't get file mode flags on stdin, %m");
1244 if (fcntl(0, F_SETFL
, status
& ~O_NONBLOCK
) == -1)
1245 fatal(2, "Can't set file mode flags on stdin: %m");
1254 if (alarmed
|| put_char(c
) < 0) {
1259 if (errno
== EINTR
|| errno
== EWOULDBLOCK
)
1260 logf(" -- write timed out");
1262 logf(" -- write failed: %m");
1277 logf("send (??????)");
1279 logf("send (%v)", s
);
1282 alarm(timeout
); alarmed
= 0;
1285 register char c
= *s
++;
1288 if (!write_char (c
))
1304 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1308 if (!write_char (c
))
1320 * Echo a character to stderr.
1321 * When called with -1, a '\n' character is generated when
1322 * the cursor is not at the beginning of a line.
1331 case '\r': /* ignore '\r' */
1343 write(2, s
, strlen(s
));
1350 * 'Wait for' this string to appear on this file descriptor.
1352 int get_string(string
)
1353 register char *string
;
1356 int c
, printed
= 0, len
, minlen
;
1357 register char *s
= temp
, *end
= s
+ STR_LEN
;
1358 char *logged
= temp
;
1361 string
= clean(string
, 0);
1362 len
= strlen(string
);
1363 minlen
= (len
> sizeof(fail_buffer
)? len
: sizeof(fail_buffer
)) - 1;
1366 logf("expect (%v)", string
);
1368 if (len
> STR_LEN
) {
1369 logf("expect string is too long");
1383 while ( ! alarmed
&& (c
= get_char()) >= 0) {
1384 int n
, abort_len
, report_len
;
1388 if (verbose
&& c
== '\n') {
1390 logf(""); /* blank line */
1392 logf("%0.*v", s
- logged
, logged
);
1398 if (verbose
&& s
>= logged
+ 80) {
1399 logf("%0.*v", s
- logged
, logged
);
1405 fputc( '\n', stderr
);
1407 fprintf( stderr
, "%s", character(c
) );
1410 if (!report_gathering
) {
1411 for (n
= 0; n
< n_reports
; ++n
) {
1412 if ((report_string
[n
] != (char*) NULL
) &&
1413 s
- temp
>= (report_len
= strlen(report_string
[n
])) &&
1414 strncmp(s
- report_len
, report_string
[n
], report_len
) == 0) {
1415 time_t time_now
= time ((time_t*) NULL
);
1416 struct tm
* tm_now
= localtime (&time_now
);
1418 strftime (report_buffer
, 20, "%b %d %H:%M:%S ", tm_now
);
1419 strcat (report_buffer
, report_string
[n
]);
1421 report_string
[n
] = (char *) NULL
;
1422 report_gathering
= 1;
1429 int rep_len
= strlen (report_buffer
);
1430 report_buffer
[rep_len
] = c
;
1431 report_buffer
[rep_len
+ 1] = '\0';
1434 report_gathering
= 0;
1435 fprintf (report_fp
, "chat: %s\n", report_buffer
);
1439 if (s
- temp
>= len
&&
1440 c
== string
[len
- 1] &&
1441 strncmp(s
- len
, string
, len
) == 0) {
1444 logf("%0.*v", s
- logged
, logged
);
1445 logf(" -- got it\n");
1453 for (n
= 0; n
< n_aborts
; ++n
) {
1454 if (s
- temp
>= (abort_len
= strlen(abort_string
[n
])) &&
1455 strncmp(s
- abort_len
, abort_string
[n
], abort_len
) == 0) {
1458 logf("%0.*v", s
- logged
, logged
);
1465 strcpy(fail_reason
= fail_buffer
, abort_string
[n
]);
1471 if (logged
< s
- minlen
) {
1473 logf("%0.*v", s
- logged
, logged
);
1477 memmove(temp
, s
, minlen
);
1478 logged
= temp
+ (logged
- s
);
1482 if (alarmed
&& verbose
)
1483 logf("warning: alarm synchronization problem");
1488 if (verbose
&& printed
) {
1490 logf(" -- read timed out");
1492 logf(" -- read failed: %m");
1501 * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1504 #include <sys/param.h>
1505 #if MAXUID > 65536 /* then this is Solaris 2.6 or later */
1511 #include <sys/types.h>
1512 #include <sys/time.h>
1515 usleep -- support routine for 4.2BSD system call emulations
1516 last edit: 29-Oct-1984 D A Gwyn
1519 extern int select();
1522 usleep( usec
) /* returns 0 if ok, else -1 */
1523 long usec
; /* delay in microseconds */
1525 static struct { /* `timeval' */
1526 long tv_sec
; /* seconds */
1527 long tv_usec
; /* microsecs */
1528 } delay
; /* _select() timeout */
1530 delay
.tv_sec
= usec
/ 1000000L;
1531 delay
.tv_usec
= usec
% 1000000L;
1533 return select(0, (long *)0, (long *)0, (long *)0, &delay
);
1538 pack_array (array
, end
)
1539 char **array
; /* The address of the array of string pointers */
1540 int end
; /* The index of the next free entry before CLR_ */
1544 for (i
= 0; i
< end
; i
++) {
1545 if (array
[i
] == NULL
) {
1546 for (j
= i
+1; j
< end
; ++j
)
1547 if (array
[j
] != NULL
)
1548 array
[i
++] = array
[j
];
1549 for (; i
< end
; ++i
)
1557 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1558 * also specify the length of the output buffer, and we handle the
1559 * %m (error message) format.
1560 * Doesn't do floating-point formats.
1561 * Returns the number of chars put into buf.
1563 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1566 vfmtmsg(buf
, buflen
, fmt
, args
)
1573 int width
, prec
, fillch
;
1574 int base
, len
, neg
, quoted
;
1575 unsigned long val
= 0;
1580 static char hexchars
[] = "0123456789abcdef";
1584 while (buflen
> 0) {
1585 for (f
= fmt
; *f
!= '%' && *f
!= 0; ++f
)
1591 memcpy(buf
, fmt
, len
);
1606 width
= va_arg(args
, int);
1609 while (isdigit(c
)) {
1610 width
= width
* 10 + c
- '0';
1617 prec
= va_arg(args
, int);
1620 while (isdigit(c
)) {
1621 prec
= prec
* 10 + c
- '0';
1632 i
= va_arg(args
, int);
1641 val
= va_arg(args
, unsigned int);
1645 val
= va_arg(args
, unsigned int);
1649 val
= (unsigned long) va_arg(args
, void *);
1654 str
= va_arg(args
, char *);
1657 num
[0] = va_arg(args
, int);
1662 str
= strerror(errno
);
1664 case 'v': /* "visible" string */
1665 case 'q': /* quoted string */
1667 p
= va_arg(args
, unsigned char *);
1668 if (fillch
== '0' && prec
> 0) {
1671 n
= strlen((char *)p
);
1672 if (prec
> 0 && prec
< n
)
1675 while (n
> 0 && buflen
> 0) {
1678 if (!quoted
&& c
>= 0x80) {
1683 if (quoted
&& (c
== '"' || c
== '\\'))
1685 if (c
< 0x20 || (0x7f <= c
&& c
< 0xa0)) {
1689 case '\t': OUTCHAR('t'); break;
1690 case '\n': OUTCHAR('n'); break;
1691 case '\b': OUTCHAR('b'); break;
1692 case '\f': OUTCHAR('f'); break;
1695 OUTCHAR(hexchars
[c
>> 4]);
1696 OUTCHAR(hexchars
[c
& 0xf]);
1713 --fmt
; /* so %z outputs %z etc. */
1718 str
= num
+ sizeof(num
);
1720 while (str
> num
+ neg
) {
1721 *--str
= hexchars
[val
% base
];
1723 if (--prec
<= 0 && val
== 0)
1735 len
= num
+ sizeof(num
) - 1 - str
;
1738 if (prec
> 0 && len
> prec
)
1744 if ((n
= width
- len
) > 0) {
1752 memcpy(buf
, str
, len
);