chat.c 14 KB

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