chat.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * bare bones chat utility
  4. * inspired by ppp's chat
  5. *
  6. * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
  7. *
  8. * Licensed under GPLv2, see file LICENSE in this source tree.
  9. */
  10. //config:config CHAT
  11. //config: bool "chat"
  12. //config: default y
  13. //config: help
  14. //config: Simple chat utility.
  15. //config:
  16. //config:config FEATURE_CHAT_NOFAIL
  17. //config: bool "Enable NOFAIL expect strings"
  18. //config: depends on CHAT
  19. //config: default y
  20. //config: help
  21. //config: When enabled expect strings which are started with a dash trigger
  22. //config: no-fail mode. That is when expectation is not met within timeout
  23. //config: the script is not terminated but sends next SEND string and waits
  24. //config: for next EXPECT string. This allows to compose far more flexible
  25. //config: scripts.
  26. //config:
  27. //config:config FEATURE_CHAT_TTY_HIFI
  28. //config: bool "Force STDIN to be a TTY"
  29. //config: depends on CHAT
  30. //config: default n
  31. //config: help
  32. //config: Original chat always treats STDIN as a TTY device and sets for it
  33. //config: so-called raw mode. This option turns on such behaviour.
  34. //config:
  35. //config:config FEATURE_CHAT_IMPLICIT_CR
  36. //config: bool "Enable implicit Carriage Return"
  37. //config: depends on CHAT
  38. //config: default y
  39. //config: help
  40. //config: When enabled make chat to terminate all SEND strings with a "\r"
  41. //config: unless "\c" is met anywhere in the string.
  42. //config:
  43. //config:config FEATURE_CHAT_SWALLOW_OPTS
  44. //config: bool "Swallow options"
  45. //config: depends on CHAT
  46. //config: default y
  47. //config: help
  48. //config: Busybox chat require no options. To make it not fail when used
  49. //config: in place of original chat (which has a bunch of options) turn
  50. //config: this on.
  51. //config:
  52. //config:config FEATURE_CHAT_SEND_ESCAPES
  53. //config: bool "Support weird SEND escapes"
  54. //config: depends on CHAT
  55. //config: default y
  56. //config: help
  57. //config: Original chat uses some escape sequences in SEND arguments which
  58. //config: are not sent to device but rather performs special actions.
  59. //config: E.g. "\K" means to send a break sequence to device.
  60. //config: "\d" delays execution for a second, "\p" -- for a 1/100 of second.
  61. //config: Before turning this option on think twice: do you really need them?
  62. //config:
  63. //config:config FEATURE_CHAT_VAR_ABORT_LEN
  64. //config: bool "Support variable-length ABORT conditions"
  65. //config: depends on CHAT
  66. //config: default y
  67. //config: help
  68. //config: Original chat uses fixed 50-bytes length ABORT conditions. Say N here.
  69. //config:
  70. //config:config FEATURE_CHAT_CLR_ABORT
  71. //config: bool "Support revoking of ABORT conditions"
  72. //config: depends on CHAT
  73. //config: default y
  74. //config: help
  75. //config: Support CLR_ABORT directive.
  76. //applet:IF_CHAT(APPLET(chat, BB_DIR_USR_SBIN, BB_SUID_DROP))
  77. //kbuild:lib-$(CONFIG_CHAT) += chat.o
  78. //usage:#define chat_trivial_usage
  79. //usage: "EXPECT [SEND [EXPECT [SEND...]]]"
  80. //usage:#define chat_full_usage "\n\n"
  81. //usage: "Useful for interacting with a modem connected to stdin/stdout.\n"
  82. //usage: "A script consists of one or more \"expect-send\" pairs of strings,\n"
  83. //usage: "each pair is a pair of arguments. Example:\n"
  84. //usage: "chat '' ATZ OK ATD123456 CONNECT '' ogin: pppuser word: ppppass '~'"
  85. #include "libbb.h"
  86. #include "common_bufsiz.h"
  87. // default timeout: 45 sec
  88. #define DEFAULT_CHAT_TIMEOUT 45*1000
  89. // max length of "abort string",
  90. // i.e. device reply which causes termination
  91. #define MAX_ABORT_LEN 50
  92. // possible exit codes
  93. enum {
  94. ERR_OK = 0, // all's well
  95. ERR_MEM, // read too much while expecting
  96. ERR_IO, // signalled or I/O error
  97. ERR_TIMEOUT, // timed out while expecting
  98. ERR_ABORT, // first abort condition was met
  99. // ERR_ABORT2, // second abort condition was met
  100. // ...
  101. };
  102. // exit code
  103. #define exitcode bb_got_signal
  104. // trap for critical signals
  105. static void signal_handler(UNUSED_PARAM int signo)
  106. {
  107. // report I/O error condition
  108. exitcode = ERR_IO;
  109. }
  110. #if !ENABLE_FEATURE_CHAT_IMPLICIT_CR
  111. #define unescape(s, nocr) unescape(s)
  112. #endif
  113. static size_t unescape(char *s, int *nocr)
  114. {
  115. char *start = s;
  116. char *p = s;
  117. while (*s) {
  118. char c = *s;
  119. // do we need special processing?
  120. // standard escapes + \s for space and \N for \0
  121. // \c inhibits terminating \r for commands and is noop for expects
  122. if ('\\' == c) {
  123. c = *++s;
  124. if (c) {
  125. #if ENABLE_FEATURE_CHAT_IMPLICIT_CR
  126. if ('c' == c) {
  127. *nocr = 1;
  128. goto next;
  129. }
  130. #endif
  131. if ('N' == c) {
  132. c = '\0';
  133. } else if ('s' == c) {
  134. c = ' ';
  135. #if ENABLE_FEATURE_CHAT_NOFAIL
  136. // unescape leading dash only
  137. // TODO: and only for expect, not command string
  138. } else if ('-' == c && (start + 1 == s)) {
  139. //c = '-';
  140. #endif
  141. } else {
  142. c = bb_process_escape_sequence((const char **)&s);
  143. s--;
  144. }
  145. }
  146. // ^A becomes \001, ^B -- \002 and so on...
  147. } else if ('^' == c) {
  148. c = *++s-'@';
  149. }
  150. // put unescaped char
  151. *p++ = c;
  152. #if ENABLE_FEATURE_CHAT_IMPLICIT_CR
  153. next:
  154. #endif
  155. // next char
  156. s++;
  157. }
  158. *p = '\0';
  159. return p - start;
  160. }
  161. int chat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  162. int chat_main(int argc UNUSED_PARAM, char **argv)
  163. {
  164. int record_fd = -1;
  165. bool echo = 0;
  166. // collection of device replies which cause unconditional termination
  167. llist_t *aborts = NULL;
  168. // inactivity period
  169. int timeout = DEFAULT_CHAT_TIMEOUT;
  170. // maximum length of abort string
  171. #if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  172. size_t max_abort_len = 0;
  173. #else
  174. #define max_abort_len MAX_ABORT_LEN
  175. #endif
  176. #if ENABLE_FEATURE_CHAT_TTY_HIFI
  177. struct termios tio0, tio;
  178. #endif
  179. // directive names
  180. enum {
  181. DIR_HANGUP = 0,
  182. DIR_ABORT,
  183. #if ENABLE_FEATURE_CHAT_CLR_ABORT
  184. DIR_CLR_ABORT,
  185. #endif
  186. DIR_TIMEOUT,
  187. DIR_ECHO,
  188. DIR_SAY,
  189. DIR_RECORD,
  190. };
  191. // make x* functions fail with correct exitcode
  192. xfunc_error_retval = ERR_IO;
  193. // trap vanilla signals to prevent process from being killed suddenly
  194. bb_signals(0
  195. + (1 << SIGHUP)
  196. + (1 << SIGINT)
  197. + (1 << SIGTERM)
  198. + (1 << SIGPIPE)
  199. , signal_handler);
  200. #if ENABLE_FEATURE_CHAT_TTY_HIFI
  201. //TODO: use set_termios_to_raw()
  202. tcgetattr(STDIN_FILENO, &tio);
  203. tio0 = tio;
  204. cfmakeraw(&tio);
  205. tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
  206. #endif
  207. #if ENABLE_FEATURE_CHAT_SWALLOW_OPTS
  208. getopt32(argv, "vVsSE");
  209. argv += optind;
  210. #else
  211. argv++; // goto first arg
  212. #endif
  213. // handle chat expect-send pairs
  214. while (*argv) {
  215. // directive given? process it
  216. int key = index_in_strings(
  217. "HANGUP\0" "ABORT\0"
  218. #if ENABLE_FEATURE_CHAT_CLR_ABORT
  219. "CLR_ABORT\0"
  220. #endif
  221. "TIMEOUT\0" "ECHO\0" "SAY\0" "RECORD\0"
  222. , *argv
  223. );
  224. if (key >= 0) {
  225. // cache directive value
  226. char *arg = *++argv;
  227. // OFF -> 0, anything else -> 1
  228. bool onoff = (0 != strcmp("OFF", arg));
  229. // process directive
  230. if (DIR_HANGUP == key) {
  231. // turn SIGHUP on/off
  232. signal(SIGHUP, onoff ? signal_handler : SIG_IGN);
  233. } else if (DIR_ABORT == key) {
  234. // append the string to abort conditions
  235. #if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  236. size_t len = strlen(arg);
  237. if (len > max_abort_len)
  238. max_abort_len = len;
  239. #endif
  240. llist_add_to_end(&aborts, arg);
  241. #if ENABLE_FEATURE_CHAT_CLR_ABORT
  242. } else if (DIR_CLR_ABORT == key) {
  243. llist_t *l;
  244. // remove the string from abort conditions
  245. // N.B. gotta refresh maximum length too...
  246. # if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  247. max_abort_len = 0;
  248. # endif
  249. for (l = aborts; l; l = l->link) {
  250. # if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  251. size_t len = strlen(l->data);
  252. # endif
  253. if (strcmp(arg, l->data) == 0) {
  254. llist_unlink(&aborts, l);
  255. continue;
  256. }
  257. # if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  258. if (len > max_abort_len)
  259. max_abort_len = len;
  260. # endif
  261. }
  262. #endif
  263. } else if (DIR_TIMEOUT == key) {
  264. // set new timeout
  265. // -1 means OFF
  266. timeout = atoi(arg) * 1000;
  267. // 0 means default
  268. // >0 means value in msecs
  269. if (!timeout)
  270. timeout = DEFAULT_CHAT_TIMEOUT;
  271. } else if (DIR_ECHO == key) {
  272. // turn echo on/off
  273. // N.B. echo means dumping device input/output to stderr
  274. echo = onoff;
  275. } else if (DIR_RECORD == key) {
  276. // turn record on/off
  277. // N.B. record means dumping device input to a file
  278. // close previous record_fd
  279. if (record_fd > 0)
  280. close(record_fd);
  281. // N.B. do we have to die here on open error?
  282. record_fd = (onoff) ? xopen(arg, O_WRONLY|O_CREAT|O_TRUNC) : -1;
  283. } else if (DIR_SAY == key) {
  284. // just print argument verbatim
  285. // TODO: should we use full_write() to avoid unistd/stdio conflict?
  286. bb_error_msg("%s", arg);
  287. }
  288. // next, please!
  289. argv++;
  290. // ordinary expect-send pair!
  291. } else {
  292. //-----------------------
  293. // do expect
  294. //-----------------------
  295. int expect_len;
  296. size_t buf_len = 0;
  297. size_t max_len = max_abort_len;
  298. struct pollfd pfd;
  299. #if ENABLE_FEATURE_CHAT_NOFAIL
  300. int nofail = 0;
  301. #endif
  302. char *expect = *argv++;
  303. // sanity check: shall we really expect something?
  304. if (!expect)
  305. goto expect_done;
  306. #if ENABLE_FEATURE_CHAT_NOFAIL
  307. // if expect starts with -
  308. if ('-' == *expect) {
  309. // swallow -
  310. expect++;
  311. // and enter nofail mode
  312. nofail++;
  313. }
  314. #endif
  315. #ifdef ___TEST___BUF___ // test behaviour with a small buffer
  316. # undef COMMON_BUFSIZE
  317. # define COMMON_BUFSIZE 6
  318. #endif
  319. // expand escape sequences in expect
  320. expect_len = unescape(expect, &expect_len /*dummy*/);
  321. if (expect_len > max_len)
  322. max_len = expect_len;
  323. // sanity check:
  324. // we should expect more than nothing but not more than input buffer
  325. // TODO: later we'll get rid of fixed-size buffer
  326. if (!expect_len)
  327. goto expect_done;
  328. if (max_len >= COMMON_BUFSIZE) {
  329. exitcode = ERR_MEM;
  330. goto expect_done;
  331. }
  332. // get reply
  333. pfd.fd = STDIN_FILENO;
  334. pfd.events = POLLIN;
  335. while (!exitcode
  336. && poll(&pfd, 1, timeout) > 0
  337. && (pfd.revents & POLLIN)
  338. ) {
  339. llist_t *l;
  340. ssize_t delta;
  341. #define buf bb_common_bufsiz1
  342. setup_common_bufsiz();
  343. // read next char from device
  344. if (safe_read(STDIN_FILENO, buf+buf_len, 1) > 0) {
  345. // dump device input if RECORD fname
  346. if (record_fd > 0) {
  347. full_write(record_fd, buf+buf_len, 1);
  348. }
  349. // dump device input if ECHO ON
  350. if (echo) {
  351. // if (buf[buf_len] < ' ') {
  352. // full_write(STDERR_FILENO, "^", 1);
  353. // buf[buf_len] += '@';
  354. // }
  355. full_write(STDERR_FILENO, buf+buf_len, 1);
  356. }
  357. buf_len++;
  358. // move input frame if we've reached higher bound
  359. if (buf_len > COMMON_BUFSIZE) {
  360. memmove(buf, buf+buf_len-max_len, max_len);
  361. buf_len = max_len;
  362. }
  363. }
  364. // N.B. rule of thumb: values being looked for can
  365. // be found only at the end of input buffer
  366. // this allows to get rid of strstr() and memmem()
  367. // TODO: make expect and abort strings processed uniformly
  368. // abort condition is met? -> bail out
  369. for (l = aborts, exitcode = ERR_ABORT; l; l = l->link, ++exitcode) {
  370. size_t len = strlen(l->data);
  371. delta = buf_len-len;
  372. if (delta >= 0 && !memcmp(buf+delta, l->data, len))
  373. goto expect_done;
  374. }
  375. exitcode = ERR_OK;
  376. // expected reply received? -> goto next command
  377. delta = buf_len - expect_len;
  378. if (delta >= 0 && !memcmp(buf+delta, expect, expect_len))
  379. goto expect_done;
  380. #undef buf
  381. } /* while (have data) */
  382. // device timed out or unexpected reply received
  383. exitcode = ERR_TIMEOUT;
  384. expect_done:
  385. #if ENABLE_FEATURE_CHAT_NOFAIL
  386. // on success and when in nofail mode
  387. // we should skip following subsend-subexpect pairs
  388. if (nofail) {
  389. if (!exitcode) {
  390. // find last send before non-dashed expect
  391. while (*argv && argv[1] && '-' == argv[1][0])
  392. argv += 2;
  393. // skip the pair
  394. // N.B. do we really need this?!
  395. if (!*argv++ || !*argv++)
  396. break;
  397. }
  398. // nofail mode also clears all but IO errors (or signals)
  399. if (ERR_IO != exitcode)
  400. exitcode = ERR_OK;
  401. }
  402. #endif
  403. // bail out unless we expected successfully
  404. if (exitcode)
  405. break;
  406. //-----------------------
  407. // do send
  408. //-----------------------
  409. if (*argv) {
  410. #if ENABLE_FEATURE_CHAT_IMPLICIT_CR
  411. int nocr = 0; // inhibit terminating command with \r
  412. #endif
  413. char *loaded = NULL; // loaded command
  414. size_t len;
  415. char *buf = *argv++;
  416. // if command starts with @
  417. // load "real" command from file named after @
  418. if ('@' == *buf) {
  419. // skip the @ and any following white-space
  420. trim(++buf);
  421. buf = loaded = xmalloc_xopen_read_close(buf, NULL);
  422. }
  423. // expand escape sequences in command
  424. len = unescape(buf, &nocr);
  425. // send command
  426. alarm(timeout);
  427. pfd.fd = STDOUT_FILENO;
  428. pfd.events = POLLOUT;
  429. while (len && !exitcode
  430. && poll(&pfd, 1, -1) > 0
  431. && (pfd.revents & POLLOUT)
  432. ) {
  433. #if ENABLE_FEATURE_CHAT_SEND_ESCAPES
  434. // "\\d" means 1 sec delay, "\\p" means 0.01 sec delay
  435. // "\\K" means send BREAK
  436. char c = *buf;
  437. if ('\\' == c) {
  438. c = *++buf;
  439. if ('d' == c) {
  440. sleep(1);
  441. len--;
  442. continue;
  443. }
  444. if ('p' == c) {
  445. usleep(10000);
  446. len--;
  447. continue;
  448. }
  449. if ('K' == c) {
  450. tcsendbreak(STDOUT_FILENO, 0);
  451. len--;
  452. continue;
  453. }
  454. buf--;
  455. }
  456. if (safe_write(STDOUT_FILENO, buf, 1) != 1)
  457. break;
  458. len--;
  459. buf++;
  460. #else
  461. len -= full_write(STDOUT_FILENO, buf, len);
  462. #endif
  463. } /* while (can write) */
  464. alarm(0);
  465. // report I/O error if there still exists at least one non-sent char
  466. if (len)
  467. exitcode = ERR_IO;
  468. // free loaded command (if any)
  469. if (loaded)
  470. free(loaded);
  471. #if ENABLE_FEATURE_CHAT_IMPLICIT_CR
  472. // or terminate command with \r (if not inhibited)
  473. else if (!nocr)
  474. xwrite(STDOUT_FILENO, "\r", 1);
  475. #endif
  476. // bail out unless we sent command successfully
  477. if (exitcode)
  478. break;
  479. } /* if (*argv) */
  480. }
  481. } /* while (*argv) */
  482. #if ENABLE_FEATURE_CHAT_TTY_HIFI
  483. tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio0);
  484. #endif
  485. return exitcode;
  486. }