chat.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 (6.3 kb)"
  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 \"expect-send\" argument pairs.\n"
  83. //usage: "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. bool onoff;
  226. // cache directive value
  227. char *arg = *++argv;
  228. if (!arg) {
  229. #if ENABLE_FEATURE_CHAT_TTY_HIFI
  230. tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio0);
  231. #endif
  232. bb_show_usage();
  233. }
  234. // OFF -> 0, anything else -> 1
  235. onoff = (0 != strcmp("OFF", arg));
  236. // process directive
  237. if (DIR_HANGUP == key) {
  238. // turn SIGHUP on/off
  239. signal(SIGHUP, onoff ? signal_handler : SIG_IGN);
  240. } else if (DIR_ABORT == key) {
  241. // append the string to abort conditions
  242. #if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  243. size_t len = strlen(arg);
  244. if (len > max_abort_len)
  245. max_abort_len = len;
  246. #endif
  247. llist_add_to_end(&aborts, arg);
  248. #if ENABLE_FEATURE_CHAT_CLR_ABORT
  249. } else if (DIR_CLR_ABORT == key) {
  250. llist_t *l;
  251. // remove the string from abort conditions
  252. // N.B. gotta refresh maximum length too...
  253. # if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  254. max_abort_len = 0;
  255. # endif
  256. for (l = aborts; l; l = l->link) {
  257. # if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  258. size_t len = strlen(l->data);
  259. # endif
  260. if (strcmp(arg, l->data) == 0) {
  261. llist_unlink(&aborts, l);
  262. continue;
  263. }
  264. # if ENABLE_FEATURE_CHAT_VAR_ABORT_LEN
  265. if (len > max_abort_len)
  266. max_abort_len = len;
  267. # endif
  268. }
  269. #endif
  270. } else if (DIR_TIMEOUT == key) {
  271. // set new timeout
  272. // -1 means OFF
  273. timeout = atoi(arg) * 1000;
  274. // 0 means default
  275. // >0 means value in msecs
  276. if (!timeout)
  277. timeout = DEFAULT_CHAT_TIMEOUT;
  278. } else if (DIR_ECHO == key) {
  279. // turn echo on/off
  280. // N.B. echo means dumping device input/output to stderr
  281. echo = onoff;
  282. } else if (DIR_RECORD == key) {
  283. // turn record on/off
  284. // N.B. record means dumping device input to a file
  285. // close previous record_fd
  286. if (record_fd > 0)
  287. close(record_fd);
  288. // N.B. do we have to die here on open error?
  289. record_fd = (onoff) ? xopen(arg, O_WRONLY|O_CREAT|O_TRUNC) : -1;
  290. } else if (DIR_SAY == key) {
  291. // just print argument verbatim
  292. // TODO: should we use full_write() to avoid unistd/stdio conflict?
  293. bb_simple_error_msg(arg);
  294. }
  295. // next, please!
  296. argv++;
  297. // ordinary expect-send pair!
  298. } else {
  299. //-----------------------
  300. // do expect
  301. //-----------------------
  302. int expect_len;
  303. size_t buf_len = 0;
  304. size_t max_len = max_abort_len;
  305. struct pollfd pfd;
  306. #if ENABLE_FEATURE_CHAT_NOFAIL
  307. int nofail = 0;
  308. #endif
  309. char *expect = *argv++;
  310. // sanity check: shall we really expect something?
  311. if (!expect)
  312. goto expect_done;
  313. #if ENABLE_FEATURE_CHAT_NOFAIL
  314. // if expect starts with -
  315. if ('-' == *expect) {
  316. // swallow -
  317. expect++;
  318. // and enter nofail mode
  319. nofail++;
  320. }
  321. #endif
  322. #ifdef ___TEST___BUF___ // test behaviour with a small buffer
  323. # undef COMMON_BUFSIZE
  324. # define COMMON_BUFSIZE 6
  325. #endif
  326. // expand escape sequences in expect
  327. expect_len = unescape(expect, &expect_len /*dummy*/);
  328. if (expect_len > max_len)
  329. max_len = expect_len;
  330. // sanity check:
  331. // we should expect more than nothing but not more than input buffer
  332. // TODO: later we'll get rid of fixed-size buffer
  333. if (!expect_len)
  334. goto expect_done;
  335. if (max_len >= COMMON_BUFSIZE) {
  336. exitcode = ERR_MEM;
  337. goto expect_done;
  338. }
  339. // get reply
  340. pfd.fd = STDIN_FILENO;
  341. pfd.events = POLLIN;
  342. while (!exitcode
  343. && poll(&pfd, 1, timeout) > 0
  344. && (pfd.revents & POLLIN)
  345. ) {
  346. llist_t *l;
  347. ssize_t delta;
  348. #define buf bb_common_bufsiz1
  349. setup_common_bufsiz();
  350. // read next char from device
  351. if (safe_read(STDIN_FILENO, buf+buf_len, 1) > 0) {
  352. // dump device input if RECORD fname
  353. if (record_fd > 0) {
  354. full_write(record_fd, buf+buf_len, 1);
  355. }
  356. // dump device input if ECHO ON
  357. if (echo) {
  358. // if (buf[buf_len] < ' ') {
  359. // full_write(STDERR_FILENO, "^", 1);
  360. // buf[buf_len] += '@';
  361. // }
  362. full_write(STDERR_FILENO, buf+buf_len, 1);
  363. }
  364. buf_len++;
  365. // move input frame if we've reached higher bound
  366. if (buf_len > COMMON_BUFSIZE) {
  367. memmove(buf, buf+buf_len-max_len, max_len);
  368. buf_len = max_len;
  369. }
  370. }
  371. // N.B. rule of thumb: values being looked for can
  372. // be found only at the end of input buffer
  373. // this allows to get rid of strstr() and memmem()
  374. // TODO: make expect and abort strings processed uniformly
  375. // abort condition is met? -> bail out
  376. for (l = aborts, exitcode = ERR_ABORT; l; l = l->link, ++exitcode) {
  377. size_t len = strlen(l->data);
  378. delta = buf_len-len;
  379. if (delta >= 0 && !memcmp(buf+delta, l->data, len))
  380. goto expect_done;
  381. }
  382. exitcode = ERR_OK;
  383. // expected reply received? -> goto next command
  384. delta = buf_len - expect_len;
  385. if (delta >= 0 && !memcmp(buf+delta, expect, expect_len))
  386. goto expect_done;
  387. #undef buf
  388. } /* while (have data) */
  389. // device timed out or unexpected reply received
  390. exitcode = ERR_TIMEOUT;
  391. expect_done:
  392. #if ENABLE_FEATURE_CHAT_NOFAIL
  393. // on success and when in nofail mode
  394. // we should skip following subsend-subexpect pairs
  395. if (nofail) {
  396. if (!exitcode) {
  397. // find last send before non-dashed expect
  398. while (*argv && argv[1] && '-' == argv[1][0])
  399. argv += 2;
  400. // skip the pair
  401. // N.B. do we really need this?!
  402. if (!*argv++ || !*argv++)
  403. break;
  404. }
  405. // nofail mode also clears all but IO errors (or signals)
  406. if (ERR_IO != exitcode)
  407. exitcode = ERR_OK;
  408. }
  409. #endif
  410. // bail out unless we expected successfully
  411. if (exitcode)
  412. break;
  413. //-----------------------
  414. // do send
  415. //-----------------------
  416. if (*argv) {
  417. #if ENABLE_FEATURE_CHAT_IMPLICIT_CR
  418. int nocr = 0; // inhibit terminating command with \r
  419. #endif
  420. char *loaded = NULL; // loaded command
  421. size_t len;
  422. char *buf = *argv++;
  423. // if command starts with @
  424. // load "real" command from file named after @
  425. if ('@' == *buf) {
  426. // skip the @ and any following white-space
  427. trim(++buf);
  428. buf = loaded = xmalloc_xopen_read_close(buf, NULL);
  429. }
  430. // expand escape sequences in command
  431. len = unescape(buf, &nocr);
  432. // send command
  433. alarm(timeout);
  434. pfd.fd = STDOUT_FILENO;
  435. pfd.events = POLLOUT;
  436. while (len && !exitcode
  437. && poll(&pfd, 1, -1) > 0
  438. && (pfd.revents & POLLOUT)
  439. ) {
  440. #if ENABLE_FEATURE_CHAT_SEND_ESCAPES
  441. // "\\d" means 1 sec delay, "\\p" means 0.01 sec delay
  442. // "\\K" means send BREAK
  443. char c = *buf;
  444. if ('\\' == c) {
  445. c = *++buf;
  446. if ('d' == c) {
  447. sleep(1);
  448. len--;
  449. continue;
  450. }
  451. if ('p' == c) {
  452. usleep(10000);
  453. len--;
  454. continue;
  455. }
  456. if ('K' == c) {
  457. tcsendbreak(STDOUT_FILENO, 0);
  458. len--;
  459. continue;
  460. }
  461. buf--;
  462. }
  463. if (safe_write(STDOUT_FILENO, buf, 1) != 1)
  464. break;
  465. len--;
  466. buf++;
  467. #else
  468. len -= full_write(STDOUT_FILENO, buf, len);
  469. #endif
  470. } /* while (can write) */
  471. alarm(0);
  472. // report I/O error if there still exists at least one non-sent char
  473. if (len)
  474. exitcode = ERR_IO;
  475. // free loaded command (if any)
  476. if (loaded)
  477. free(loaded);
  478. #if ENABLE_FEATURE_CHAT_IMPLICIT_CR
  479. // or terminate command with \r (if not inhibited)
  480. else if (!nocr)
  481. xwrite(STDOUT_FILENO, "\r", 1);
  482. #endif
  483. // bail out unless we sent command successfully
  484. if (exitcode)
  485. break;
  486. } /* if (*argv) */
  487. }
  488. } /* while (*argv) */
  489. #if ENABLE_FEATURE_CHAT_TTY_HIFI
  490. tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio0);
  491. #endif
  492. return exitcode;
  493. }