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.
93 #pragma ident "%Z%%M% %I% %E% SMI"
95 static const char rcsid
[] = "$Id: chat.c,v 1.26 1999/12/23 01:39:54 paulus Exp $";
106 #include <sys/types.h>
107 #include <sys/stat.h>
137 #define __V(x) (va_alist) va_dcl
143 #define O_NONBLOCK O_NDELAY
148 extern char *sys_errlist
[];
149 #define memmove(to, from, n) bcopy(from, to, n)
150 #define strerror(n) ((unsigned)(n) < sys_nerr? sys_errlist[(n)] :\
154 /*************** Micro getopt() *********************************************/
155 #define OPTION(c,v) (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
156 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
157 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
158 #define OPTARG(c,v) (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
159 (_O=4,(char*)0):(char*)0)
160 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
161 #define ARG(c,v) (c?(--c,*v++):(char*)0)
163 static int _O
= 0; /* Internal state */
164 /*************** Micro getopt() *********************************************/
168 #define MAX_ABORTS 50
169 #define MAX_REPORTS 50
170 #define DEFAULT_CHAT_TIMEOUT 45
181 FILE *report_fp
= NULL
;
182 char *report_file
= NULL
;
183 char *chat_file
= NULL
;
184 char *phone_num
= NULL
;
185 char *phone_num2
= NULL
;
186 int timeout
= DEFAULT_CHAT_TIMEOUT
;
188 int have_tty_parameters
= 0;
191 #define term_parms struct termio
192 #define get_term_param(param) ioctl(0, TCGETA, param)
193 #define set_term_param(param) ioctl(0, TCSETA, param)
194 struct termio saved_tty_parameters
;
198 #define term_parms struct termios
199 #define get_term_param(param) tcgetattr(0, param)
200 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
201 struct termios saved_tty_parameters
;
204 char *abort_string
[MAX_ABORTS
], *fail_reason
= (char *)0,
206 int n_aborts
= 0, abort_next
= 0, timeout_next
= 0, echo_next
= 0;
207 int clear_abort_next
= 0;
209 char *report_string
[MAX_REPORTS
] ;
210 char report_buffer
[50] ;
211 int n_reports
= 0, report_next
= 0, report_gathering
= 0 ;
212 int clear_report_next
= 0;
214 int say_next
= 0, hup_next
= 0;
216 void *dup_mem
__P((void *b
, size_t c
));
217 void *copy_of
__P((char *s
));
218 void usage
__P((void));
219 void logf
__P((const char *fmt
, ...));
220 void fatal
__P((int code
, const char *fmt
, ...));
221 SIGTYPE sigalrm
__P((int signo
));
222 SIGTYPE sigint
__P((int signo
));
223 SIGTYPE sigterm
__P((int signo
));
224 SIGTYPE sighup
__P((int signo
));
225 void unalarm
__P((void));
226 void init
__P((void));
227 void set_tty_parameters
__P((void));
228 void echo_stderr
__P((int));
229 void break_sequence
__P((void));
230 void terminate
__P((int status
));
231 void do_file
__P((char *chat_file
));
232 int get_string
__P((register char *string
));
233 int put_string
__P((register char *s
));
234 int write_char
__P((int c
));
235 int put_char
__P((int c
));
236 int get_char
__P((void));
237 void chat_send
__P((register char *s
));
238 char *character
__P((int c
));
239 void chat_expect
__P((register char *s
));
240 char *clean
__P((register char *s
, int sending
));
241 void break_sequence
__P((void));
242 void terminate
__P((int status
));
243 void pack_array
__P((char **array
, int end
));
244 char *expect_strtok
__P((char *, char *));
245 int vfmtmsg
__P((char *, int, const char *, va_list)); /* vsprintf++ */
247 int main
__P((int, char *[]));
253 void *ans
= malloc (c
);
255 fatal(2, "memory error!");
264 return dup_mem (s
, strlen (s
) + 1);
268 * chat [ -v ] [ -E ] [ -T number ] [ -U number ] [ -t timeout ] [ -f chat-file ] \
269 * [ -r report-file ] \
270 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
272 * Perform a UUCP-dialer-like chat script on stdin and stdout.
282 program_name
= *argv
;
285 while ((option
= OPTION(argc
, argv
)) != 0) {
312 if ((arg
= OPTARG(argc
, argv
)) != NULL
)
313 chat_file
= copy_of(arg
);
319 if ((arg
= OPTARG(argc
, argv
)) != NULL
)
326 arg
= OPTARG (argc
, argv
);
328 if (report_fp
!= NULL
)
330 report_file
= copy_of (arg
);
331 report_fp
= fopen (report_file
, "a");
332 if (report_fp
!= NULL
) {
334 fprintf (report_fp
, "Opening \"%s\"...\n",
342 if ((arg
= OPTARG(argc
, argv
)) != NULL
)
343 phone_num
= copy_of(arg
);
349 if ((arg
= OPTARG(argc
, argv
)) != NULL
)
350 phone_num2
= copy_of(arg
);
361 * Default the report file to the stderr location
363 if (report_fp
== NULL
)
368 openlog("chat", LOG_PID
);
370 openlog("chat", LOG_PID
| LOG_NDELAY
, LOG_LOCAL2
);
373 setlogmask(LOG_UPTO(LOG_INFO
));
375 setlogmask(LOG_UPTO(LOG_WARNING
));
381 if (chat_file
!= NULL
) {
382 arg
= ARG(argc
, argv
);
388 while ((arg
= ARG(argc
, argv
)) != NULL
) {
391 if ((arg
= ARG(argc
, argv
)) != NULL
)
401 * Process a chat script when read from a file.
404 void do_file (chat_file
)
408 char *sp
, *arg
, quote
;
412 cfp
= fopen (chat_file
, "r");
414 fatal(1, "%s -- open failed: %m", chat_file
);
419 while (fgets(buf
, STR_LEN
, cfp
) != NULL
) {
420 sp
= strchr (buf
, '\n');
427 /* lines starting with '#' are comments. If a real '#'
428 is to be expected, it should be quoted .... */
432 while (*sp
!= '\0') {
433 if (*sp
== ' ' || *sp
== '\t') {
438 if (*sp
== '"' || *sp
== '\'') {
441 while (*sp
!= quote
) {
443 fatal(1, "unterminated quote (line %d)", linect
);
453 while (*sp
!= '\0' && *sp
!= ' ' && *sp
!= '\t')
471 * We got an error parsing the command line.
476 Usage: %s [-e] [-E] [-v] [-V] [-t timeout] [-r report-file]\n\
477 [-T phone-number] [-U phone-number2] {-f chat-file | chat-script}\n", program_name
);
484 * Send a message to syslog and/or stderr.
486 void logf
__V((const char *fmt
, ...))
495 fmt
= va_arg(args
, char *);
498 vfmtmsg(line
, sizeof(line
), fmt
, args
);
500 syslog(LOG_INFO
, "%s", line
);
502 fprintf(stderr
, "%s\n", line
);
506 * Print an error message and terminate.
509 void fatal
__V((int code
, const char *fmt
, ...))
519 code
= va_arg(args
, int);
520 fmt
= va_arg(args
, char *);
523 vfmtmsg(line
, sizeof(line
), fmt
, args
);
525 syslog(LOG_ERR
, "%s", line
);
527 fprintf(stderr
, "%s\n", line
);
533 SIGTYPE
sigalrm(signo
)
539 alarmed
= 1; /* Reset alarm to avoid race window */
540 signal(SIGALRM
, sigalrm
); /* that can cause hanging in read() */
542 if ((flags
= fcntl(0, F_GETFL
, 0)) == -1)
543 fatal(2, "Can't get file mode flags on stdin: %m");
545 if (fcntl(0, F_SETFL
, flags
| O_NONBLOCK
) == -1)
546 fatal(2, "Can't set file mode flags on stdin: %m");
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");
563 SIGTYPE
sigint(signo
)
569 SIGTYPE
sigterm(signo
)
575 SIGTYPE
sighup(signo
)
583 signal(SIGINT
, sigint
);
584 signal(SIGTERM
, sigterm
);
585 signal(SIGHUP
, sighup
);
587 set_tty_parameters();
588 signal(SIGALRM
, sigalrm
);
593 void set_tty_parameters()
595 #if defined(get_term_param)
598 if (get_term_param (&t
) < 0)
599 fatal(2, "Can't get terminal parameters: %m");
601 saved_tty_parameters
= t
;
602 have_tty_parameters
= 1;
604 t
.c_iflag
|= IGNBRK
| ISTRIP
| IGNPAR
;
612 if (set_term_param (&t
) < 0)
613 fatal(2, "Can't set terminal parameters: %m");
617 void break_sequence()
624 void terminate(status
)
627 static int terminating
= 0;
634 * Allow the last of the report string to be gathered before we terminate.
636 if (report_gathering
) {
639 rep_len
= strlen(report_buffer
);
640 while (rep_len
+ 1 <= sizeof(report_buffer
)) {
644 if (c
< 0 || iscntrl(c
))
646 report_buffer
[rep_len
] = c
;
649 report_buffer
[rep_len
] = 0;
650 fprintf (report_fp
, "chat: %s\n", report_buffer
);
652 if (report_file
!= NULL
&& report_fp
!= (FILE *) NULL
) {
654 fprintf (report_fp
, "Closing \"%s\".\n", report_file
);
656 report_fp
= (FILE *) NULL
;
659 #if defined(get_term_param)
660 if (have_tty_parameters
) {
661 if (set_term_param (&saved_tty_parameters
) < 0)
662 fatal(2, "Can't restore terminal parameters: %m");
670 * 'Clean up' this string.
672 char *clean(s
, sending
)
674 int sending
; /* set to 1 when sending (putting) this string. */
676 char temp
[STR_LEN
], env_str
[STR_LEN
], cur_chr
;
677 register char *s1
, *phchar
;
678 int add_return
= sending
;
679 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
680 #define isalnumx(chr) ((((chr) >= '0') && ((chr) <= '9')) \
681 || (((chr) >= 'a') && ((chr) <= 'z')) \
682 || (((chr) >= 'A') && ((chr) <= 'Z')) \
688 if (cur_chr
== '^') {
690 if (cur_chr
== '\0') {
701 if (use_env
&& cur_chr
== '$') { /* ARI */
706 phchar
= getenv(env_str
);
713 if (cur_chr
!= '\\') {
719 if (cur_chr
== '\0') {
733 if (sending
&& *s
== '\0')
749 if (sending
&& phone_num
) {
750 for (phchar
= phone_num
; *phchar
!= '\0'; phchar
++)
760 if (sending
&& phone_num2
) {
761 for (phchar
= phone_num2
; *phchar
!= '\0'; phchar
++)
807 if (isoctal (cur_chr
)) {
811 cur_chr
|= *s
++ - '0';
814 cur_chr
|= *s
++ - '0';
818 if (cur_chr
!= 0 || sending
) {
819 if (sending
&& (cur_chr
== '\\' || cur_chr
== 0))
836 *s1
++ = '\0'; /* guarantee closure */
837 *s1
++ = '\0'; /* terminate the string */
838 return dup_mem (temp
, (size_t) (s1
- temp
)); /* may have embedded nuls */
842 * A modified version of 'strtok'. This version skips \ sequences.
845 char *expect_strtok (s
, term
)
848 static char *str
= "";
853 * If a string was specified then do initial processing.
859 * If this is the escape flag then reset it and ignore the character.
880 * If this is not in the termination string, continue.
882 if (strchr(term
, *str
) == NULL
) {
888 * This is the terminator. Mark the end of the string and stop.
897 * Process the expect string
906 if (strcmp(s
, "HANGUP") == 0) {
911 if (strcmp(s
, "ABORT") == 0) {
916 if (strcmp(s
, "CLR_ABORT") == 0) {
921 if (strcmp(s
, "REPORT") == 0) {
926 if (strcmp(s
, "CLR_REPORT") == 0) {
931 if (strcmp(s
, "TIMEOUT") == 0) {
936 if (strcmp(s
, "ECHO") == 0) {
941 if (strcmp(s
, "SAY") == 0) {
947 * Fetch the expect and reply string.
950 expect
= expect_strtok (s
, "-");
956 reply
= expect_strtok (s
, "-");
959 * Handle the expect string. If successful then exit.
961 if (get_string (expect
))
965 * If there is a sub-reply string then send it. Otherwise any condition
968 if (reply
== NULL
|| exit_code
!= 3)
975 * The expectation did not occur. This is terminal.
978 logf("Failed (%s)", fail_reason
);
981 terminate(exit_code
);
985 * Translate the input character to the appropriate string for printing
992 static char string
[10];
995 meta
= (c
& 0x80) ? "M-" : "";
999 sprintf(string
, "%s^%c", meta
, (int)c
+ '@');
1001 sprintf(string
, "%s^?", meta
);
1003 sprintf(string
, "%s%c", meta
, c
);
1009 * process the reply string
1014 char file_data
[STR_LEN
];
1019 write(2, s
, strlen(s
));
1026 if (strcmp(s
, "OFF") == 0)
1027 signal(SIGHUP
, SIG_IGN
);
1029 signal(SIGHUP
, sighup
);
1035 echo
= (strcmp(s
, "ON") == 0);
1044 if (n_aborts
>= MAX_ABORTS
)
1045 fatal(2, "Too many ABORT strings");
1049 if (strlen(s1
) > strlen(s
)
1050 || strlen(s1
) + 1 > sizeof(fail_buffer
))
1051 fatal(1, "Illegal or too-long ABORT string ('%v')", s
);
1053 abort_string
[n_aborts
++] = s1
;
1056 logf("abort on (%v)", s
);
1060 if (clear_abort_next
) {
1066 clear_abort_next
= 0;
1070 if (strlen(s1
) > strlen(s
)
1071 || strlen(s1
) + 1 > sizeof(fail_buffer
))
1072 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s
);
1075 for (i
=0; i
< n_aborts
; i
++) {
1076 if ( strcmp(s1
,abort_string
[i
]) == 0 ) {
1077 free(abort_string
[i
]);
1078 abort_string
[i
] = NULL
;
1082 logf("clear abort on (%v)", s
);
1087 pack_array(abort_string
,old_max
);
1095 if (n_reports
>= MAX_REPORTS
)
1096 fatal(2, "Too many REPORT strings");
1100 if (strlen(s1
) > strlen(s
) || strlen(s1
) > sizeof fail_buffer
- 1)
1101 fatal(1, "Illegal or too-long REPORT string ('%v')", s
);
1103 report_string
[n_reports
++] = s1
;
1106 logf("report (%v)", s
);
1110 if (clear_report_next
) {
1116 clear_report_next
= 0;
1120 if (strlen(s1
) > strlen(s
) || strlen(s1
) > sizeof fail_buffer
- 1)
1121 fatal(1, "Illegal or too-long REPORT string ('%v')", s
);
1123 old_max
= n_reports
;
1124 for (i
=0; i
< n_reports
; i
++) {
1125 if ( strcmp(s1
,report_string
[i
]) == 0 ) {
1126 free(report_string
[i
]);
1127 report_string
[i
] = NULL
;
1131 logf("clear report (%v)", s
);
1136 pack_array(report_string
,old_max
);
1146 timeout
= DEFAULT_CHAT_TIMEOUT
;
1149 logf("timeout set to %d seconds", timeout
);
1155 * The syntax @filename means read the string to send from the
1159 /* skip the @ and any following white-space */
1161 while (*++fn
== ' ' || *fn
== '\t')
1168 /* open the file and read until STR_LEN-1 bytes or end-of-file */
1171 fatal(1, "%s -- open failed: %m", fn
);
1172 while (n
< STR_LEN
- 1) {
1173 int nr
= fread(&file_data
[n
], 1, STR_LEN
- 1 - n
, f
);
1175 fatal(1, "%s -- read error", fn
);
1182 /* use the string we got as the string to send,
1183 but trim off the final newline if any. */
1184 if (n
> 0 && file_data
[n
-1] == '\n')
1191 if (strcmp(s
, "EOT") == 0)
1193 else if (strcmp(s
, "BREAK") == 0)
1205 status
= read(0, &c
, 1);
1209 return ((int)c
& 0x7F);
1212 logf("warning: read() on stdin returned %d", status
);
1215 if ((status
= fcntl(0, F_GETFL
, 0)) == -1)
1216 fatal(2, "Can't get file mode flags on stdin: %m");
1218 if (fcntl(0, F_SETFL
, status
& ~O_NONBLOCK
) == -1)
1219 fatal(2, "Can't set file mode flags on stdin: %m");
1231 usleep(10000); /* inter-character typing delay (?) */
1233 status
= write(1, &ch
, 1);
1240 logf("warning: write() on stdout returned %d", status
);
1243 if ((status
= fcntl(0, F_GETFL
, 0)) == -1)
1244 fatal(2, "Can't get file mode flags on stdin, %m");
1246 if (fcntl(0, F_SETFL
, status
& ~O_NONBLOCK
) == -1)
1247 fatal(2, "Can't set file mode flags on stdin: %m");
1256 if (alarmed
|| put_char(c
) < 0) {
1261 if (errno
== EINTR
|| errno
== EWOULDBLOCK
)
1262 logf(" -- write timed out");
1264 logf(" -- write failed: %m");
1279 logf("send (??????)");
1281 logf("send (%v)", s
);
1284 alarm(timeout
); alarmed
= 0;
1287 register char c
= *s
++;
1290 if (!write_char (c
))
1306 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1310 if (!write_char (c
))
1322 * Echo a character to stderr.
1323 * When called with -1, a '\n' character is generated when
1324 * the cursor is not at the beginning of a line.
1333 case '\r': /* ignore '\r' */
1345 write(2, s
, strlen(s
));
1352 * 'Wait for' this string to appear on this file descriptor.
1354 int get_string(string
)
1355 register char *string
;
1358 int c
, printed
= 0, len
, minlen
;
1359 register char *s
= temp
, *end
= s
+ STR_LEN
;
1360 char *logged
= temp
;
1363 string
= clean(string
, 0);
1364 len
= strlen(string
);
1365 minlen
= (len
> sizeof(fail_buffer
)? len
: sizeof(fail_buffer
)) - 1;
1368 logf("expect (%v)", string
);
1370 if (len
> STR_LEN
) {
1371 logf("expect string is too long");
1385 while ( ! alarmed
&& (c
= get_char()) >= 0) {
1386 int n
, abort_len
, report_len
;
1390 if (verbose
&& c
== '\n') {
1392 logf(""); /* blank line */
1394 logf("%0.*v", s
- logged
, logged
);
1400 if (verbose
&& s
>= logged
+ 80) {
1401 logf("%0.*v", s
- logged
, logged
);
1407 fputc( '\n', stderr
);
1409 fprintf( stderr
, "%s", character(c
) );
1412 if (!report_gathering
) {
1413 for (n
= 0; n
< n_reports
; ++n
) {
1414 if ((report_string
[n
] != (char*) NULL
) &&
1415 s
- temp
>= (report_len
= strlen(report_string
[n
])) &&
1416 strncmp(s
- report_len
, report_string
[n
], report_len
) == 0) {
1417 time_t time_now
= time ((time_t*) NULL
);
1418 struct tm
* tm_now
= localtime (&time_now
);
1420 strftime (report_buffer
, 20, "%b %d %H:%M:%S ", tm_now
);
1421 strcat (report_buffer
, report_string
[n
]);
1423 report_string
[n
] = (char *) NULL
;
1424 report_gathering
= 1;
1431 int rep_len
= strlen (report_buffer
);
1432 report_buffer
[rep_len
] = c
;
1433 report_buffer
[rep_len
+ 1] = '\0';
1436 report_gathering
= 0;
1437 fprintf (report_fp
, "chat: %s\n", report_buffer
);
1441 if (s
- temp
>= len
&&
1442 c
== string
[len
- 1] &&
1443 strncmp(s
- len
, string
, len
) == 0) {
1446 logf("%0.*v", s
- logged
, logged
);
1447 logf(" -- got it\n");
1455 for (n
= 0; n
< n_aborts
; ++n
) {
1456 if (s
- temp
>= (abort_len
= strlen(abort_string
[n
])) &&
1457 strncmp(s
- abort_len
, abort_string
[n
], abort_len
) == 0) {
1460 logf("%0.*v", s
- logged
, logged
);
1467 strcpy(fail_reason
= fail_buffer
, abort_string
[n
]);
1473 if (logged
< s
- minlen
) {
1475 logf("%0.*v", s
- logged
, logged
);
1479 memmove(temp
, s
, minlen
);
1480 logged
= temp
+ (logged
- s
);
1484 if (alarmed
&& verbose
)
1485 logf("warning: alarm synchronization problem");
1490 if (verbose
&& printed
) {
1492 logf(" -- read timed out");
1494 logf(" -- read failed: %m");
1503 * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1506 #include <sys/param.h>
1507 #if MAXUID > 65536 /* then this is Solaris 2.6 or later */
1513 #include <sys/types.h>
1514 #include <sys/time.h>
1517 usleep -- support routine for 4.2BSD system call emulations
1518 last edit: 29-Oct-1984 D A Gwyn
1521 extern int select();
1524 usleep( usec
) /* returns 0 if ok, else -1 */
1525 long usec
; /* delay in microseconds */
1527 static struct { /* `timeval' */
1528 long tv_sec
; /* seconds */
1529 long tv_usec
; /* microsecs */
1530 } delay
; /* _select() timeout */
1532 delay
.tv_sec
= usec
/ 1000000L;
1533 delay
.tv_usec
= usec
% 1000000L;
1535 return select(0, (long *)0, (long *)0, (long *)0, &delay
);
1540 pack_array (array
, end
)
1541 char **array
; /* The address of the array of string pointers */
1542 int end
; /* The index of the next free entry before CLR_ */
1546 for (i
= 0; i
< end
; i
++) {
1547 if (array
[i
] == NULL
) {
1548 for (j
= i
+1; j
< end
; ++j
)
1549 if (array
[j
] != NULL
)
1550 array
[i
++] = array
[j
];
1551 for (; i
< end
; ++i
)
1559 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1560 * also specify the length of the output buffer, and we handle the
1561 * %m (error message) format.
1562 * Doesn't do floating-point formats.
1563 * Returns the number of chars put into buf.
1565 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1568 vfmtmsg(buf
, buflen
, fmt
, args
)
1575 int width
, prec
, fillch
;
1576 int base
, len
, neg
, quoted
;
1577 unsigned long val
= 0;
1582 static char hexchars
[] = "0123456789abcdef";
1586 while (buflen
> 0) {
1587 for (f
= fmt
; *f
!= '%' && *f
!= 0; ++f
)
1593 memcpy(buf
, fmt
, len
);
1608 width
= va_arg(args
, int);
1611 while (isdigit(c
)) {
1612 width
= width
* 10 + c
- '0';
1619 prec
= va_arg(args
, int);
1622 while (isdigit(c
)) {
1623 prec
= prec
* 10 + c
- '0';
1634 i
= va_arg(args
, int);
1643 val
= va_arg(args
, unsigned int);
1647 val
= va_arg(args
, unsigned int);
1651 val
= (unsigned long) va_arg(args
, void *);
1656 str
= va_arg(args
, char *);
1659 num
[0] = va_arg(args
, int);
1664 str
= strerror(errno
);
1666 case 'v': /* "visible" string */
1667 case 'q': /* quoted string */
1669 p
= va_arg(args
, unsigned char *);
1670 if (fillch
== '0' && prec
> 0) {
1673 n
= strlen((char *)p
);
1674 if (prec
> 0 && prec
< n
)
1677 while (n
> 0 && buflen
> 0) {
1680 if (!quoted
&& c
>= 0x80) {
1685 if (quoted
&& (c
== '"' || c
== '\\'))
1687 if (c
< 0x20 || (0x7f <= c
&& c
< 0xa0)) {
1691 case '\t': OUTCHAR('t'); break;
1692 case '\n': OUTCHAR('n'); break;
1693 case '\b': OUTCHAR('b'); break;
1694 case '\f': OUTCHAR('f'); break;
1697 OUTCHAR(hexchars
[c
>> 4]);
1698 OUTCHAR(hexchars
[c
& 0xf]);
1715 --fmt
; /* so %z outputs %z etc. */
1720 str
= num
+ sizeof(num
);
1722 while (str
> num
+ neg
) {
1723 *--str
= hexchars
[val
% base
];
1725 if (--prec
<= 0 && val
== 0)
1737 len
= num
+ sizeof(num
) - 1 - str
;
1740 if (prec
> 0 && len
> prec
)
1746 if ((n
= width
- len
) > 0) {
1754 memcpy(buf
, str
, len
);