1 /* $NetBSD: chat.c,v 1.7 2006/03/23 19:25:09 he Exp $ */
4 * Chat -- a program for automatic session establishment (i.e. dial
5 * the phone and log in).
7 * Standard termination codes:
8 * 0 - successful completion of the script
9 * 1 - invalid argument, expect string too large, etc.
10 * 2 - error on an I/O operation or fatal error condition.
11 * 3 - timeout waiting for a simple string.
12 * 4 - the first string declared as "ABORT"
13 * 5 - the second string declared as "ABORT"
14 * 6 - ... and so on for successive ABORT strings.
16 * This software is in the public domain.
19 * 22-May-99 added environment substitutuion, enabled with -E switch.
20 * Andreas Arens <andras@cityweb.de>.
22 * 12-May-99 added a feature to read data to be sent from a file,
23 * if the send string starts with @. Idea from gpk <gpk@onramp.net>.
25 * added -T and -U option and \T and \U substitution to pass a phone
26 * number into chat script. Two are needed for some ISDN TA applications.
27 * Keith Dart <kdart@cisco.com>
30 * Added SAY keyword to send output to stderr.
31 * This allows to turn ECHO OFF and to output specific, user selected,
32 * text to give progress messages. This best works when stderr
33 * exists (i.e.: pppd in nodetach mode).
35 * Added HANGUP directives to allow for us to be called
36 * back. When HANGUP is set to NO, chat will not hangup at HUP signal.
37 * We rely on timeouts in that case.
39 * Added CLR_ABORT to clear previously set ABORT string. This has been
40 * dictated by the HANGUP above as "NO CARRIER" (for example) must be
41 * an ABORT condition until we know the other host is going to close
42 * the connection for call back. As soon as we have completed the
43 * first stage of the call back sequence, "NO CARRIER" is a valid, non
44 * fatal string. As soon as we got called back (probably get "CONNECT"),
45 * we should re-arm the ABORT "NO CARRIER". Hence the CLR_ABORT command.
46 * Note that CLR_ABORT packs the abort_strings[] array so that we do not
47 * have unused entries not being reclaimed.
49 * In the same vein as above, added CLR_REPORT keyword.
51 * Allow for comments. Line starting with '#' are comments and are
52 * ignored. If a '#' is to be expected as the first character, the
53 * expect string must be quoted.
56 * Francis Demierre <Francis@SwissMail.Com>
57 * Thu May 15 17:15:40 MET DST 1997
60 * Added -r "report file" switch & REPORT keyword.
61 * Robert Geer <bgeer@xmission.com>
63 * Added -s "use stderr" and -S "don't use syslog" switches.
65 * Karl O. Pinc <kop@meme.com>
68 * Added -e "echo" switch & ECHO keyword
69 * Dick Streefland <dicks@tasking.nl>
72 * Considerable updates and modifications by
73 * Al Longyear <longyear@pobox.com>
74 * Paul Mackerras <paulus@cs.anu.edu.au>
77 * The original author is:
79 * Karl Fox <karl@MorningStar.Com>
80 * Morning Star Technologies, Inc.
91 #include <sys/cdefs.h>
94 static const char rcsid
[] = "Id: chat.c,v 1.30 2004/01/17 05:47:55 carlsonj Exp";
96 __RCSID("$NetBSD: chat.c,v 1.7 2006/03/23 19:25:09 he Exp $");
109 #include <sys/types.h>
110 #include <sys/stat.h>
140 #define __V(x) (va_alist) va_dcl
146 #define O_NONBLOCK O_NDELAY
151 extern char *sys_errlist
[];
152 #define memmove(to, from, n) bcopy(from, to, n)
153 #define strerror(n) ((unsigned)(n) < sys_nerr? sys_errlist[(n)] :\
159 #define BUFFER_SIZE 256
160 #define MAX_ABORTS 50
161 #define MAX_REPORTS 50
162 #define DEFAULT_CHAT_TIMEOUT 45
173 FILE* report_fp
= (FILE *) 0;
174 char *report_file
= (char *) 0;
175 char *chat_file
= (char *) 0;
176 char *phone_num
= (char *) 0;
177 char *phone_num2
= (char *) 0;
178 int timeout
= DEFAULT_CHAT_TIMEOUT
;
180 int have_tty_parameters
= 0;
183 #define term_parms struct termio
184 #define get_term_param(param) ioctl(0, TCGETA, param)
185 #define set_term_param(param) ioctl(0, TCSETA, param)
186 struct termio saved_tty_parameters
;
190 #define term_parms struct termios
191 #define get_term_param(param) tcgetattr(0, param)
192 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
193 struct termios saved_tty_parameters
;
196 char *abort_string
[MAX_ABORTS
], *fail_reason
= (char *)0,
197 fail_buffer
[BUFFER_SIZE
];
198 int n_aborts
= 0, abort_next
= 0, timeout_next
= 0, echo_next
= 0;
199 int clear_abort_next
= 0;
201 char *report_string
[MAX_REPORTS
] ;
202 char report_buffer
[BUFFER_SIZE
] ;
203 int n_reports
= 0, report_next
= 0, report_gathering
= 0 ;
204 int clear_report_next
= 0;
206 int say_next
= 0, hup_next
= 0;
208 void *dup_mem
__P((void *b
, size_t c
));
209 void *copy_of
__P((char *s
));
210 char *grow
__P((char *s
, char **p
, size_t len
));
211 void usage
__P((void));
212 void msgf
__P((const char *fmt
, ...));
213 void fatal
__P((int code
, const char *fmt
, ...));
214 SIGTYPE sigalrm
__P((int signo
));
215 SIGTYPE sigint
__P((int signo
));
216 SIGTYPE sigterm
__P((int signo
));
217 SIGTYPE sighup
__P((int signo
));
218 void unalarm
__P((void));
219 void init
__P((void));
220 void set_tty_parameters
__P((void));
221 void echo_stderr
__P((int));
222 void break_sequence
__P((void));
223 void terminate
__P((int status
));
224 void do_file
__P((char *chat_file
));
225 int get_string
__P((register char *string
));
226 int put_string
__P((register char *s
));
227 int write_char
__P((int c
));
228 int put_char
__P((int c
));
229 int get_char
__P((void));
230 void chat_send
__P((register char *s
));
231 char *character
__P((int c
));
232 void chat_expect
__P((register char *s
));
233 char *clean
__P((register char *s
, int sending
));
234 void break_sequence
__P((void));
235 void terminate
__P((int status
));
236 void pack_array
__P((char **array
, int end
));
237 char *expect_strtok
__P((char *, char *));
238 int vfmtmsg
__P((char *, int, const char *, va_list)); /* vsprintf++ */
240 int main
__P((int, char *[]));
246 void *ans
= malloc (c
);
248 fatal(2, "memory error!");
257 return dup_mem (s
, strlen (s
) + 1);
260 /* grow a char buffer and keep a pointer offset */
261 char *grow(s
, p
, 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.
290 program_name
= *argv
;
293 while ((option
= getopt(argc
, argv
, ":eEvVf:t:r:sST:U:")) != -1) {
321 chat_file
= copy_of(optarg
);
328 timeout
= atoi(optarg
);
335 if (report_fp
!= NULL
)
337 report_file
= copy_of (optarg
);
338 report_fp
= fopen (report_file
, "a");
339 if (report_fp
!= NULL
) {
341 fprintf (report_fp
, "Opening \"%s\"...\n",
350 phone_num
= copy_of(optarg
);
357 phone_num2
= copy_of(optarg
);
370 * Default the report file to the stderr location
372 if (report_fp
== NULL
)
377 openlog("chat", LOG_PID
);
379 openlog("chat", LOG_PID
| LOG_NDELAY
, LOG_LOCAL2
);
382 setlogmask(LOG_UPTO(LOG_INFO
));
384 setlogmask(LOG_UPTO(LOG_WARNING
));
390 if (chat_file
!= NULL
) {
396 for (i
= 0; i
< argc
; i
++) {
397 chat_expect(argv
[i
]);
408 * Process a chat script when read from a file.
411 void do_file (chat_file
)
415 char *sp
, *arg
, quote
;
419 cfp
= fopen (chat_file
, "r");
421 fatal(1, "%s -- open failed: %m", chat_file
);
426 while (fgets(buf
, STR_LEN
, cfp
) != NULL
) {
427 sp
= strchr (buf
, '\n');
434 /* lines starting with '#' are comments. If a real '#'
435 is to be expected, it should be quoted .... */
439 while (*sp
!= '\0') {
440 if (*sp
== ' ' || *sp
== '\t') {
445 if (*sp
== '"' || *sp
== '\'') {
448 while (*sp
!= quote
) {
450 fatal(1, "unterminated quote (line %d)", linect
);
460 while (*sp
!= '\0' && *sp
!= ' ' && *sp
!= '\t')
478 * We got an error parsing the command line.
483 Usage: %s [-e] [-E] [-v] [-V] [-t timeout] [-r report-file]\n\
484 [-T phone-number] [-U phone-number2] {-f chat-file | chat-script}\n", program_name
);
491 * Send a message to syslog and/or stderr.
493 void msgf
__V((const char *fmt
, ...))
502 fmt
= va_arg(args
, char *);
505 vfmtmsg(line
, sizeof(line
), fmt
, args
);
508 syslog(LOG_INFO
, "%s", line
);
510 fprintf(stderr
, "%s\n", line
);
514 * Print an error message and terminate.
517 void fatal
__V((int code
, const char *fmt
, ...))
527 code
= va_arg(args
, int);
528 fmt
= va_arg(args
, char *);
531 vfmtmsg(line
, sizeof(line
), fmt
, args
);
534 syslog(LOG_ERR
, "%s", line
);
536 fprintf(stderr
, "%s\n", line
);
542 SIGTYPE
sigalrm(signo
)
548 alarmed
= 1; /* Reset alarm to avoid race window */
549 signal(SIGALRM
, sigalrm
); /* that can cause hanging in read() */
551 if ((flags
= fcntl(0, F_GETFL
, 0)) == -1)
552 fatal(2, "Can't get file mode flags on stdin: %m");
554 if (fcntl(0, F_SETFL
, flags
| O_NONBLOCK
) == -1)
555 fatal(2, "Can't set file mode flags on stdin: %m");
565 if ((flags
= fcntl(0, F_GETFL
, 0)) == -1)
566 fatal(2, "Can't get file mode flags on stdin: %m");
568 if (fcntl(0, F_SETFL
, flags
& ~O_NONBLOCK
) == -1)
569 fatal(2, "Can't set file mode flags on stdin: %m");
572 SIGTYPE
sigint(signo
)
578 SIGTYPE
sigterm(signo
)
584 SIGTYPE
sighup(signo
)
592 signal(SIGINT
, sigint
);
593 signal(SIGTERM
, sigterm
);
594 signal(SIGHUP
, sighup
);
596 set_tty_parameters();
597 signal(SIGALRM
, sigalrm
);
602 void set_tty_parameters()
604 #if defined(get_term_param)
607 if (get_term_param (&t
) < 0)
608 fatal(2, "Can't get terminal parameters: %m");
610 saved_tty_parameters
= t
;
611 have_tty_parameters
= 1;
613 t
.c_iflag
|= IGNBRK
| ISTRIP
| IGNPAR
;
614 t
.c_oflag
|= OPOST
| ONLCR
;
621 if (set_term_param (&t
) < 0)
622 fatal(2, "Can't set terminal parameters: %m");
626 void break_sequence()
633 void terminate(status
)
636 static int terminating
= 0;
643 * Allow the last of the report string to be gathered before we terminate.
645 if (report_gathering
) {
648 rep_len
= strlen(report_buffer
);
649 while (rep_len
< sizeof(report_buffer
) - 1) {
653 if (c
< 0 || iscntrl(c
))
655 report_buffer
[rep_len
] = c
;
658 report_buffer
[rep_len
] = 0;
659 fprintf (report_fp
, "chat: %s\n", report_buffer
);
661 if (report_file
!= (char *) 0 && report_fp
!= (FILE *) NULL
) {
663 fprintf (report_fp
, "Closing \"%s\".\n", report_file
);
665 report_fp
= (FILE *) NULL
;
668 #if defined(get_term_param)
669 if (have_tty_parameters
) {
670 if (set_term_param (&saved_tty_parameters
) < 0)
671 fatal(2, "Can't restore terminal parameters: %m");
679 * 'Clean up' this string.
681 char *clean(s
, sending
)
683 int sending
; /* set to 1 when sending (putting) this string. */
686 char *s1
, *p
, *phchar
;
687 int add_return
= sending
;
688 size_t len
= strlen(s
) + 3; /* see len comments below */
690 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
691 #define isalnumx(chr) ((((chr) >= '0') && ((chr) <= '9')) \
692 || (((chr) >= 'a') && ((chr) <= 'z')) \
693 || (((chr) >= 'A') && ((chr) <= 'Z')) \
696 p
= s1
= malloc(len
);
698 fatal(2, "memory error!");
701 if (cur_chr
== '^') {
703 if (cur_chr
== '\0') {
714 if (use_env
&& cur_chr
== '$') { /* ARI */
722 phchar
= getenv(phchar
);
723 *s
= c
; /* restore */
725 len
+= strlen(phchar
);
726 s1
= grow(s1
, &p
, len
);
733 if (cur_chr
!= '\\') {
739 if (cur_chr
== '\0') {
742 *p
++ = '\\'; /* +1 for len */
753 if (sending
&& *s
== '\0')
769 if (sending
&& phone_num
) {
770 len
+= strlen(phone_num
);
771 s1
= grow(s1
, &p
, len
);
772 for (phchar
= phone_num
; *phchar
!= '\0'; phchar
++)
782 if (sending
&& phone_num2
) {
783 len
+= strlen(phone_num2
);
784 s1
= grow(s1
, &p
, len
);
785 for (phchar
= phone_num2
; *phchar
!= '\0'; phchar
++)
831 if (isoctal (cur_chr
)) {
835 cur_chr
|= *s
++ - '0';
838 cur_chr
|= *s
++ - '0';
842 if (cur_chr
!= 0 || sending
) {
843 if (sending
&& (cur_chr
== '\\' || cur_chr
== 0))
858 *p
++ = '\r'; /* +2 for len */
860 *p
= '\0'; /* +3 for len */
865 * A modified version of 'strtok'. This version skips \ sequences.
868 char *expect_strtok (s
, term
)
871 static char *str
= "";
876 * If a string was specified then do initial processing.
882 * If this is the escape flag then reset it and ignore the character.
903 * If this is not in the termination string, continue.
905 if (strchr (term
, *str
) == (char *) 0) {
911 * This is the terminator. Mark the end of the string and stop.
920 * Process the expect string
929 if (strcmp(s
, "HANGUP") == 0) {
934 if (strcmp(s
, "ABORT") == 0) {
939 if (strcmp(s
, "CLR_ABORT") == 0) {
944 if (strcmp(s
, "REPORT") == 0) {
949 if (strcmp(s
, "CLR_REPORT") == 0) {
954 if (strcmp(s
, "TIMEOUT") == 0) {
959 if (strcmp(s
, "ECHO") == 0) {
964 if (strcmp(s
, "SAY") == 0) {
970 * Fetch the expect and reply string.
973 expect
= expect_strtok (s
, "-");
976 if (expect
== (char *) 0)
979 reply
= expect_strtok (s
, "-");
982 * Handle the expect string. If successful then exit.
984 if (get_string (expect
))
988 * If there is a sub-reply string then send it. Otherwise any condition
991 if (reply
== (char *) 0 || exit_code
!= 3)
998 * The expectation did not occur. This is terminal.
1001 msgf("Failed (%s)", fail_reason
);
1004 terminate(exit_code
);
1008 * Translate the input character to the appropriate string for printing
1015 static char string
[10];
1018 meta
= (c
& 0x80) ? "M-" : "";
1022 snprintf(string
, sizeof(string
), "%s^%c", meta
, (int)c
+ '@');
1024 snprintf(string
, sizeof(string
), "%s^?", meta
);
1026 snprintf(string
, sizeof(string
), "%s%c", meta
, c
);
1032 * process the reply string
1037 char file_data
[STR_LEN
];
1042 write(2, s
, strlen(s
));
1049 if (strcmp(s
, "OFF") == 0)
1050 signal(SIGHUP
, SIG_IGN
);
1052 signal(SIGHUP
, sighup
);
1058 echo
= (strcmp(s
, "ON") == 0);
1067 if (n_aborts
>= MAX_ABORTS
)
1068 fatal(2, "Too many ABORT strings");
1072 if (strlen(s1
) > strlen(s
)
1073 || strlen(s1
) + 1 > sizeof(fail_buffer
))
1074 fatal(1, "Illegal or too-long ABORT string ('%v')", s
);
1076 abort_string
[n_aborts
++] = s1
;
1079 msgf("abort on (%v)", s
);
1083 if (clear_abort_next
) {
1089 clear_abort_next
= 0;
1093 if (strlen(s1
) > strlen(s
)
1094 || strlen(s1
) + 1 > sizeof(fail_buffer
))
1095 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s
);
1098 for (i
=0; i
< n_aborts
; i
++) {
1099 if ( strcmp(s1
,abort_string
[i
]) == 0 ) {
1100 free(abort_string
[i
]);
1101 abort_string
[i
] = NULL
;
1105 msgf("clear abort on (%v)", s
);
1110 pack_array(abort_string
,old_max
);
1118 if (n_reports
>= MAX_REPORTS
)
1119 fatal(2, "Too many REPORT strings");
1122 if (strlen(s1
) > strlen(s
)
1123 || strlen(s1
) + 1 > sizeof(fail_buffer
))
1124 fatal(1, "Illegal or too-long REPORT string ('%v')", s
);
1126 report_string
[n_reports
++] = s1
;
1129 msgf("report (%v)", s
);
1133 if (clear_report_next
) {
1139 clear_report_next
= 0;
1143 if (strlen(s1
) > strlen(s
)
1144 || strlen(s1
) + 1 > sizeof(fail_buffer
))
1145 fatal(1, "Illegal or too-long REPORT string ('%v')", s
);
1147 old_max
= n_reports
;
1148 for (i
=0; i
< n_reports
; i
++) {
1149 if ( strcmp(s1
,report_string
[i
]) == 0 ) {
1150 free(report_string
[i
]);
1151 report_string
[i
] = NULL
;
1155 msgf("clear report (%v)", s
);
1160 pack_array(report_string
,old_max
);
1170 timeout
= DEFAULT_CHAT_TIMEOUT
;
1173 msgf("timeout set to %d seconds", timeout
);
1179 * The syntax @filename means read the string to send from the
1183 /* skip the @ and any following white-space */
1185 while (*++fn
== ' ' || *fn
== '\t')
1192 /* open the file and read until STR_LEN-1 bytes or end-of-file */
1195 fatal(1, "%s -- open failed: %m", fn
);
1196 while (n
< STR_LEN
- 1) {
1197 int nr
= fread(&file_data
[n
], 1, STR_LEN
- 1 - n
, f
);
1199 fatal(1, "%s -- read error", fn
);
1206 /* use the string we got as the string to send,
1207 but trim off the final newline if any. */
1208 if (n
> 0 && file_data
[n
-1] == '\n')
1215 if (strcmp(s
, "EOT") == 0)
1217 else if (strcmp(s
, "BREAK") == 0)
1229 status
= read(0, &c
, 1);
1233 return ((int)c
& 0x7F);
1236 msgf("warning: read() on stdin returned %d", status
);
1239 if ((status
= fcntl(0, F_GETFL
, 0)) == -1)
1240 fatal(2, "Can't get file mode flags on stdin: %m");
1242 if (fcntl(0, F_SETFL
, status
& ~O_NONBLOCK
) == -1)
1243 fatal(2, "Can't set file mode flags on stdin: %m");
1255 usleep(10000); /* inter-character typing delay (?) */
1257 status
= write(1, &ch
, 1);
1264 msgf("warning: write() on stdout returned %d", status
);
1267 if ((status
= fcntl(0, F_GETFL
, 0)) == -1)
1268 fatal(2, "Can't get file mode flags on stdin, %m");
1270 if (fcntl(0, F_SETFL
, status
& ~O_NONBLOCK
) == -1)
1271 fatal(2, "Can't set file mode flags on stdin: %m");
1280 if (alarmed
|| put_char(c
) < 0) {
1285 if (errno
== EINTR
|| errno
== EWOULDBLOCK
)
1286 msgf(" -- write timed out");
1288 msgf(" -- write failed: %m");
1301 s
= ss
= clean(s
, 1);
1305 msgf("send (?????\?)"); /* backslash to avoid trigraph ??) */
1307 msgf("send (%v)", s
);
1310 alarm(timeout
); alarmed
= 0;
1313 register char c
= *s
++;
1316 if (!write_char (c
)) {
1334 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1338 if (!write_char (c
)) {
1353 * Echo a character to stderr.
1354 * When called with -1, a '\n' character is generated when
1355 * the cursor is not at the beginning of a line.
1364 case '\r': /* ignore '\r' */
1376 write(2, s
, strlen(s
));
1383 * 'Wait for' this string to appear on this file descriptor.
1385 int get_string(string
)
1386 register char *string
;
1390 register char *s
= temp
, *end
= s
+ STR_LEN
;
1391 char *logged
= temp
;
1393 fail_reason
= (char *)0;
1394 string
= clean(string
, 0);
1395 len
= strlen(string
);
1396 minlen
= (len
> sizeof(fail_buffer
)? len
: sizeof(fail_buffer
)) - 1;
1399 msgf("expect (%v)", string
);
1401 if (len
> STR_LEN
) {
1402 msgf("expect string is too long");
1418 while ( ! alarmed
&& (c
= get_char()) >= 0) {
1419 int n
, abort_len
, report_len
;
1423 if (verbose
&& c
== '\n') {
1425 msgf(""); /* blank line */
1427 msgf("%0.*v", s
- logged
, logged
);
1433 if (verbose
&& s
>= logged
+ 80) {
1434 msgf("%0.*v", s
- logged
, logged
);
1440 fputc( '\n', stderr
);
1442 fprintf( stderr
, "%s", character(c
) );
1445 if (!report_gathering
) {
1446 for (n
= 0; n
< n_reports
; ++n
) {
1447 if ((report_string
[n
] != (char*) NULL
) &&
1448 s
- temp
>= (report_len
= strlen(report_string
[n
])) &&
1449 strncmp(s
- report_len
, report_string
[n
], report_len
) == 0) {
1450 time_t time_now
= time ((time_t*) NULL
);
1451 struct tm
* tm_now
= localtime (&time_now
);
1453 strftime (report_buffer
, 20, "%b %d %H:%M:%S ", tm_now
);
1454 strcat (report_buffer
, report_string
[n
]);
1455 strlcat(report_buffer
, report_string
[n
],
1456 sizeof(report_buffer
));
1458 report_string
[n
] = (char *) NULL
;
1459 report_gathering
= 1;
1466 int rep_len
= strlen (report_buffer
);
1467 report_buffer
[rep_len
] = c
;
1468 report_buffer
[rep_len
+ 1] = '\0';
1471 report_gathering
= 0;
1472 fprintf (report_fp
, "chat: %s\n", report_buffer
);
1476 if (s
- temp
>= len
&&
1477 c
== string
[len
- 1] &&
1478 strncmp(s
- len
, string
, len
) == 0) {
1481 msgf("%0.*v", s
- logged
, logged
);
1482 msgf(" -- got it\n");
1491 for (n
= 0; n
< n_aborts
; ++n
) {
1492 if (s
- temp
>= (abort_len
= strlen(abort_string
[n
])) &&
1493 strncmp(s
- abort_len
, abort_string
[n
], abort_len
) == 0) {
1496 msgf("%0.*v", s
- logged
, logged
);
1503 strlcpy(fail_buffer
, abort_string
[n
], sizeof(fail_buffer
));
1504 fail_reason
= fail_buffer
;
1511 if (logged
< s
- minlen
) {
1513 msgf("%0.*v", s
- logged
, logged
);
1517 memmove(temp
, s
, minlen
);
1518 logged
= temp
+ (logged
- s
);
1522 if (alarmed
&& verbose
)
1523 msgf("warning: alarm synchronization problem");
1535 * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1538 #include <sys/param.h>
1539 #if MAXUID > 65536 /* then this is Solaris 2.6 or later */
1545 #include <sys/types.h>
1546 #include <sys/time.h>
1549 usleep -- support routine for 4.2BSD system call emulations
1550 last edit: 29-Oct-1984 D A Gwyn
1553 extern int select();
1556 usleep( usec
) /* returns 0 if ok, else -1 */
1557 long usec
; /* delay in microseconds */
1559 static struct { /* `timeval' */
1560 long tv_sec
; /* seconds */
1561 long tv_usec
; /* microsecs */
1562 } delay
; /* _select() timeout */
1564 delay
.tv_sec
= usec
/ 1000000L;
1565 delay
.tv_usec
= usec
% 1000000L;
1567 return select(0, (long *)0, (long *)0, (long *)0, &delay
);
1572 pack_array (array
, end
)
1573 char **array
; /* The address of the array of string pointers */
1574 int end
; /* The index of the next free entry before CLR_ */
1578 for (i
= 0; i
< end
; i
++) {
1579 if (array
[i
] == NULL
) {
1580 for (j
= i
+1; j
< end
; ++j
)
1581 if (array
[j
] != NULL
)
1582 array
[i
++] = array
[j
];
1583 for (; i
< end
; ++i
)
1591 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1592 * also specify the length of the output buffer, and we handle the
1593 * %m (error message) format.
1594 * Doesn't do floating-point formats.
1595 * Returns the number of chars put into buf.
1597 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1600 vfmtmsg(buf
, buflen
, fmt
, args
)
1607 int width
, prec
, fillch
;
1608 int base
, len
, neg
, quoted
;
1609 unsigned long val
= 0;
1614 static char hexchars
[] = "0123456789abcdef";
1618 while (buflen
> 0) {
1619 for (f
= fmt
; *f
!= '%' && *f
!= 0; ++f
)
1625 memcpy(buf
, fmt
, len
);
1640 width
= va_arg(args
, int);
1643 while (isdigit(c
)) {
1644 width
= width
* 10 + c
- '0';
1651 prec
= va_arg(args
, int);
1654 while (isdigit(c
)) {
1655 prec
= prec
* 10 + c
- '0';
1666 i
= va_arg(args
, int);
1675 val
= va_arg(args
, unsigned int);
1679 val
= va_arg(args
, unsigned int);
1683 val
= (unsigned long) va_arg(args
, void *);
1688 str
= va_arg(args
, char *);
1691 num
[0] = va_arg(args
, int);
1696 str
= strerror(errno
);
1698 case 'v': /* "visible" string */
1699 case 'q': /* quoted string */
1701 p
= va_arg(args
, unsigned char *);
1702 if (fillch
== '0' && prec
> 0) {
1705 n
= strlen((char *)p
);
1706 if (prec
> 0 && prec
< n
)
1709 while (n
> 0 && buflen
> 0) {
1712 if (!quoted
&& c
>= 0x80) {
1717 if (quoted
&& (c
== '"' || c
== '\\'))
1719 if (c
< 0x20 || (0x7f <= c
&& c
< 0xa0)) {
1723 case '\t': OUTCHAR('t'); break;
1724 case '\n': OUTCHAR('n'); break;
1725 case '\b': OUTCHAR('b'); break;
1726 case '\f': OUTCHAR('f'); break;
1729 OUTCHAR(hexchars
[c
>> 4]);
1730 OUTCHAR(hexchars
[c
& 0xf]);
1747 --fmt
; /* so %z outputs %z etc. */
1752 str
= num
+ sizeof(num
);
1754 while (str
> num
+ neg
) {
1755 *--str
= hexchars
[val
% base
];
1757 if (--prec
<= 0 && val
== 0)
1769 len
= num
+ sizeof(num
) - 1 - str
;
1772 if (prec
> 0 && len
> prec
)
1778 if ((n
= width
- len
) > 0) {
1786 memcpy(buf
, str
, len
);