plink.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. /*
  2. * PLink - a command-line (stdin/stdout) variant of PuTTY.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <errno.h>
  7. #include <assert.h>
  8. #include <stdarg.h>
  9. #include <signal.h>
  10. #include <unistd.h>
  11. #include <fcntl.h>
  12. #include <termios.h>
  13. #include <pwd.h>
  14. #include <sys/ioctl.h>
  15. #include <sys/time.h>
  16. #include "putty.h"
  17. #include "ssh.h"
  18. #include "storage.h"
  19. #include "tree234.h"
  20. #define MAX_STDIN_BACKLOG 4096
  21. static LogContext *logctx;
  22. static struct termios orig_termios;
  23. void cmdline_error(const char *fmt, ...)
  24. {
  25. va_list ap;
  26. va_start(ap, fmt);
  27. console_print_error_msg_fmt_v("plink", fmt, ap);
  28. va_end(ap);
  29. exit(1);
  30. }
  31. static bool local_tty = false; /* do we have a local tty? */
  32. static Backend *backend;
  33. static Conf *conf;
  34. /*
  35. * Default settings that are specific to Unix plink.
  36. */
  37. char *platform_default_s(const char *name)
  38. {
  39. if (!strcmp(name, "TermType"))
  40. return dupstr(getenv("TERM"));
  41. if (!strcmp(name, "SerialLine"))
  42. return dupstr("/dev/ttyS0");
  43. return NULL;
  44. }
  45. bool platform_default_b(const char *name, bool def)
  46. {
  47. return def;
  48. }
  49. int platform_default_i(const char *name, int def)
  50. {
  51. return def;
  52. }
  53. FontSpec *platform_default_fontspec(const char *name)
  54. {
  55. return fontspec_new("");
  56. }
  57. Filename *platform_default_filename(const char *name)
  58. {
  59. if (!strcmp(name, "LogFileName"))
  60. return filename_from_str("putty.log");
  61. else
  62. return filename_from_str("");
  63. }
  64. char *x_get_default(const char *key)
  65. {
  66. return NULL; /* this is a stub */
  67. }
  68. static void plink_echoedit_update(Seat *seat, bool echo, bool edit)
  69. {
  70. /* Update stdin read mode to reflect changes in line discipline. */
  71. struct termios mode;
  72. if (!local_tty) return;
  73. mode = orig_termios;
  74. if (echo)
  75. mode.c_lflag |= ECHO;
  76. else
  77. mode.c_lflag &= ~ECHO;
  78. if (edit) {
  79. mode.c_iflag |= ICRNL;
  80. mode.c_lflag |= ISIG | ICANON;
  81. mode.c_oflag |= OPOST;
  82. } else {
  83. mode.c_iflag &= ~ICRNL;
  84. mode.c_lflag &= ~(ISIG | ICANON);
  85. mode.c_oflag &= ~OPOST;
  86. /* Solaris sets these to unhelpful values */
  87. mode.c_cc[VMIN] = 1;
  88. mode.c_cc[VTIME] = 0;
  89. /* FIXME: perhaps what we do with IXON/IXOFF should be an
  90. * argument to the echoedit_update() method, to allow
  91. * implementation of SSH-2 "xon-xoff" and Rlogin's
  92. * equivalent? */
  93. mode.c_iflag &= ~IXON;
  94. mode.c_iflag &= ~IXOFF;
  95. }
  96. /*
  97. * Mark parity errors and (more important) BREAK on input. This
  98. * is more complex than it need be because POSIX-2001 suggests
  99. * that escaping of valid 0xff in the input stream is dependent on
  100. * IGNPAR being clear even though marking of BREAK isn't. NetBSD
  101. * 2.0 goes one worse and makes it dependent on INPCK too. We
  102. * deal with this by forcing these flags into a useful state and
  103. * then faking the state in which we found them in from_tty() if
  104. * we get passed a parity or framing error.
  105. */
  106. mode.c_iflag = (mode.c_iflag | INPCK | PARMRK) & ~IGNPAR;
  107. tcsetattr(STDIN_FILENO, TCSANOW, &mode);
  108. }
  109. /* Helper function to extract a special character from a termios. */
  110. static char *get_ttychar(struct termios *t, int index)
  111. {
  112. cc_t c = t->c_cc[index];
  113. #if defined(_POSIX_VDISABLE)
  114. if (c == _POSIX_VDISABLE)
  115. return dupstr("");
  116. #endif
  117. return dupprintf("^<%d>", c);
  118. }
  119. static char *plink_get_ttymode(Seat *seat, const char *mode)
  120. {
  121. /*
  122. * Propagate appropriate terminal modes from the local terminal,
  123. * if any.
  124. */
  125. if (!local_tty) return NULL;
  126. #define GET_CHAR(ourname, uxname) \
  127. do { \
  128. if (strcmp(mode, ourname) == 0) \
  129. return get_ttychar(&orig_termios, uxname); \
  130. } while(0)
  131. #define GET_BOOL(ourname, uxname, uxmemb, transform) \
  132. do { \
  133. if (strcmp(mode, ourname) == 0) { \
  134. bool b = (orig_termios.uxmemb & uxname) != 0; \
  135. transform; \
  136. return dupprintf("%d", b); \
  137. } \
  138. } while (0)
  139. /*
  140. * Modes that want to be the same on all terminal devices involved.
  141. */
  142. /* All the special characters supported by SSH */
  143. #if defined(VINTR)
  144. GET_CHAR("INTR", VINTR);
  145. #endif
  146. #if defined(VQUIT)
  147. GET_CHAR("QUIT", VQUIT);
  148. #endif
  149. #if defined(VERASE)
  150. GET_CHAR("ERASE", VERASE);
  151. #endif
  152. #if defined(VKILL)
  153. GET_CHAR("KILL", VKILL);
  154. #endif
  155. #if defined(VEOF)
  156. GET_CHAR("EOF", VEOF);
  157. #endif
  158. #if defined(VEOL)
  159. GET_CHAR("EOL", VEOL);
  160. #endif
  161. #if defined(VEOL2)
  162. GET_CHAR("EOL2", VEOL2);
  163. #endif
  164. #if defined(VSTART)
  165. GET_CHAR("START", VSTART);
  166. #endif
  167. #if defined(VSTOP)
  168. GET_CHAR("STOP", VSTOP);
  169. #endif
  170. #if defined(VSUSP)
  171. GET_CHAR("SUSP", VSUSP);
  172. #endif
  173. #if defined(VDSUSP)
  174. GET_CHAR("DSUSP", VDSUSP);
  175. #endif
  176. #if defined(VREPRINT)
  177. GET_CHAR("REPRINT", VREPRINT);
  178. #endif
  179. #if defined(VWERASE)
  180. GET_CHAR("WERASE", VWERASE);
  181. #endif
  182. #if defined(VLNEXT)
  183. GET_CHAR("LNEXT", VLNEXT);
  184. #endif
  185. #if defined(VFLUSH)
  186. GET_CHAR("FLUSH", VFLUSH);
  187. #endif
  188. #if defined(VSWTCH)
  189. GET_CHAR("SWTCH", VSWTCH);
  190. #endif
  191. #if defined(VSTATUS)
  192. GET_CHAR("STATUS", VSTATUS);
  193. #endif
  194. #if defined(VDISCARD)
  195. GET_CHAR("DISCARD", VDISCARD);
  196. #endif
  197. /* Modes that "configure" other major modes. These should probably be
  198. * considered as user preferences. */
  199. /* Configuration of ICANON */
  200. #if defined(ECHOK)
  201. GET_BOOL("ECHOK", ECHOK, c_lflag, );
  202. #endif
  203. #if defined(ECHOKE)
  204. GET_BOOL("ECHOKE", ECHOKE, c_lflag, );
  205. #endif
  206. #if defined(ECHOE)
  207. GET_BOOL("ECHOE", ECHOE, c_lflag, );
  208. #endif
  209. #if defined(ECHONL)
  210. GET_BOOL("ECHONL", ECHONL, c_lflag, );
  211. #endif
  212. #if defined(XCASE)
  213. GET_BOOL("XCASE", XCASE, c_lflag, );
  214. #endif
  215. #if defined(IUTF8)
  216. GET_BOOL("IUTF8", IUTF8, c_iflag, );
  217. #endif
  218. /* Configuration of ECHO */
  219. #if defined(ECHOCTL)
  220. GET_BOOL("ECHOCTL", ECHOCTL, c_lflag, );
  221. #endif
  222. /* Configuration of IXON/IXOFF */
  223. #if defined(IXANY)
  224. GET_BOOL("IXANY", IXANY, c_iflag, );
  225. #endif
  226. /* Configuration of OPOST */
  227. #if defined(OLCUC)
  228. GET_BOOL("OLCUC", OLCUC, c_oflag, );
  229. #endif
  230. #if defined(ONLCR)
  231. GET_BOOL("ONLCR", ONLCR, c_oflag, );
  232. #endif
  233. #if defined(OCRNL)
  234. GET_BOOL("OCRNL", OCRNL, c_oflag, );
  235. #endif
  236. #if defined(ONOCR)
  237. GET_BOOL("ONOCR", ONOCR, c_oflag, );
  238. #endif
  239. #if defined(ONLRET)
  240. GET_BOOL("ONLRET", ONLRET, c_oflag, );
  241. #endif
  242. /*
  243. * Modes that want to be set in only one place, and that we have
  244. * squashed locally.
  245. */
  246. #if defined(ISIG)
  247. GET_BOOL("ISIG", ISIG, c_lflag, );
  248. #endif
  249. #if defined(ICANON)
  250. GET_BOOL("ICANON", ICANON, c_lflag, );
  251. #endif
  252. #if defined(ECHO)
  253. GET_BOOL("ECHO", ECHO, c_lflag, );
  254. #endif
  255. #if defined(IXON)
  256. GET_BOOL("IXON", IXON, c_iflag, );
  257. #endif
  258. #if defined(IXOFF)
  259. GET_BOOL("IXOFF", IXOFF, c_iflag, );
  260. #endif
  261. #if defined(OPOST)
  262. GET_BOOL("OPOST", OPOST, c_oflag, );
  263. #endif
  264. /*
  265. * We do not propagate the following modes:
  266. * - Parity/serial settings, which are a local affair and don't
  267. * make sense propagated over SSH's 8-bit byte-stream.
  268. * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
  269. * - Things that want to be enabled in one place that we don't
  270. * squash locally.
  271. * IUCLC
  272. * - Status bits.
  273. * PENDIN
  274. * - Things I don't know what to do with. (FIXME)
  275. * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
  276. * INLCR IGNCR ICRNL
  277. */
  278. #undef GET_CHAR
  279. #undef GET_BOOL
  280. /* Fall through to here for unrecognised names, or ones that are
  281. * unsupported on this platform */
  282. return NULL;
  283. }
  284. void cleanup_termios(void)
  285. {
  286. if (local_tty)
  287. tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
  288. }
  289. static bufchain stdout_data, stderr_data;
  290. static bufchain_sink stdout_bcs, stderr_bcs;
  291. static StripCtrlChars *stdout_scc, *stderr_scc;
  292. static BinarySink *stdout_bs, *stderr_bs;
  293. static enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
  294. static size_t output_backlog(void)
  295. {
  296. return bufchain_size(&stdout_data) + bufchain_size(&stderr_data);
  297. }
  298. void try_output(bool is_stderr)
  299. {
  300. bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
  301. int fd = (is_stderr ? STDERR_FILENO : STDOUT_FILENO);
  302. ssize_t ret;
  303. if (bufchain_size(chain) > 0) {
  304. bool prev_nonblock = nonblock(fd);
  305. ptrlen senddata;
  306. do {
  307. senddata = bufchain_prefix(chain);
  308. ret = write(fd, senddata.ptr, senddata.len);
  309. if (ret > 0)
  310. bufchain_consume(chain, ret);
  311. } while (ret == senddata.len && bufchain_size(chain) != 0);
  312. if (!prev_nonblock)
  313. no_nonblock(fd);
  314. if (ret < 0 && errno != EAGAIN) {
  315. perror(is_stderr ? "stderr: write" : "stdout: write");
  316. exit(1);
  317. }
  318. backend_unthrottle(backend, output_backlog());
  319. }
  320. if (outgoingeof == EOF_PENDING && bufchain_size(&stdout_data) == 0) {
  321. close(STDOUT_FILENO);
  322. outgoingeof = EOF_SENT;
  323. }
  324. }
  325. static size_t plink_output(
  326. Seat *seat, SeatOutputType type, const void *data, size_t len)
  327. {
  328. bool is_stderr = type != SEAT_OUTPUT_STDOUT;
  329. assert(is_stderr || outgoingeof == EOF_NO);
  330. BinarySink *bs = is_stderr ? stderr_bs : stdout_bs;
  331. put_data(bs, data, len);
  332. try_output(is_stderr);
  333. return output_backlog();
  334. }
  335. static bool plink_eof(Seat *seat)
  336. {
  337. assert(outgoingeof == EOF_NO);
  338. outgoingeof = EOF_PENDING;
  339. try_output(false);
  340. return false; /* do not respond to incoming EOF with outgoing */
  341. }
  342. static SeatPromptResult plink_get_userpass_input(Seat *seat, prompts_t *p)
  343. {
  344. /* Plink doesn't support Restart Session, so we can just have a
  345. * single static cmdline_get_passwd_input_state that's never reset */
  346. static cmdline_get_passwd_input_state cmdline_state =
  347. CMDLINE_GET_PASSWD_INPUT_STATE_INIT;
  348. SeatPromptResult spr;
  349. spr = cmdline_get_passwd_input(p, &cmdline_state, false);
  350. if (spr.kind == SPRK_INCOMPLETE)
  351. spr = console_get_userpass_input(p);
  352. return spr;
  353. }
  354. static bool plink_seat_interactive(Seat *seat)
  355. {
  356. return (!*conf_get_str(conf, CONF_remote_cmd) &&
  357. !*conf_get_str(conf, CONF_remote_cmd2) &&
  358. !*conf_get_str(conf, CONF_ssh_nc_host));
  359. }
  360. static const SeatVtable plink_seat_vt = {
  361. .output = plink_output,
  362. .eof = plink_eof,
  363. .sent = nullseat_sent,
  364. .banner = nullseat_banner_to_stderr,
  365. .get_userpass_input = plink_get_userpass_input,
  366. .notify_session_started = nullseat_notify_session_started,
  367. .notify_remote_exit = nullseat_notify_remote_exit,
  368. .notify_remote_disconnect = nullseat_notify_remote_disconnect,
  369. .connection_fatal = console_connection_fatal,
  370. .update_specials_menu = nullseat_update_specials_menu,
  371. .get_ttymode = plink_get_ttymode,
  372. .set_busy_status = nullseat_set_busy_status,
  373. .confirm_ssh_host_key = console_confirm_ssh_host_key,
  374. .confirm_weak_crypto_primitive = console_confirm_weak_crypto_primitive,
  375. .confirm_weak_cached_hostkey = console_confirm_weak_cached_hostkey,
  376. .prompt_descriptions = console_prompt_descriptions,
  377. .is_utf8 = nullseat_is_never_utf8,
  378. .echoedit_update = plink_echoedit_update,
  379. .get_x_display = nullseat_get_x_display,
  380. .get_windowid = nullseat_get_windowid,
  381. .get_window_pixel_size = nullseat_get_window_pixel_size,
  382. .stripctrl_new = console_stripctrl_new,
  383. .set_trust_status = console_set_trust_status,
  384. .can_set_trust_status = console_can_set_trust_status,
  385. .has_mixed_input_stream = console_has_mixed_input_stream,
  386. .verbose = cmdline_seat_verbose,
  387. .interactive = plink_seat_interactive,
  388. .get_cursor_position = nullseat_get_cursor_position,
  389. };
  390. static Seat plink_seat[1] = {{ &plink_seat_vt }};
  391. /*
  392. * Handle data from a local tty in PARMRK format.
  393. */
  394. static void from_tty(void *vbuf, unsigned len)
  395. {
  396. char *p, *q, *end, *buf = vbuf;
  397. static enum {NORMAL, FF, FF00} state = NORMAL;
  398. p = buf; end = buf + len;
  399. while (p < end) {
  400. switch (state) {
  401. case NORMAL:
  402. if (*p == '\xff') {
  403. p++;
  404. state = FF;
  405. } else {
  406. q = memchr(p, '\xff', end - p);
  407. if (q == NULL) q = end;
  408. backend_send(backend, p, q - p);
  409. p = q;
  410. }
  411. break;
  412. case FF:
  413. if (*p == '\xff') {
  414. backend_send(backend, p, 1);
  415. p++;
  416. state = NORMAL;
  417. } else if (*p == '\0') {
  418. p++;
  419. state = FF00;
  420. } else abort();
  421. break;
  422. case FF00:
  423. if (*p == '\0') {
  424. backend_special(backend, SS_BRK, 0);
  425. } else {
  426. /*
  427. * Pretend that PARMRK wasn't set. This involves
  428. * faking what INPCK and IGNPAR would have done if
  429. * we hadn't overridden them. Unfortunately, we
  430. * can't do this entirely correctly because INPCK
  431. * distinguishes between framing and parity
  432. * errors, but PARMRK format represents both in
  433. * the same way. We assume that parity errors are
  434. * more common than framing errors, and hence
  435. * treat all input errors as being subject to
  436. * INPCK.
  437. */
  438. if (orig_termios.c_iflag & INPCK) {
  439. /* If IGNPAR is set, we throw away the character. */
  440. if (!(orig_termios.c_iflag & IGNPAR)) {
  441. /* PE/FE get passed on as NUL. */
  442. *p = 0;
  443. backend_send(backend, p, 1);
  444. }
  445. } else {
  446. /* INPCK not set. Assume we got a parity error. */
  447. backend_send(backend, p, 1);
  448. }
  449. }
  450. p++;
  451. state = NORMAL;
  452. }
  453. }
  454. }
  455. static int signalpipe[2];
  456. void sigwinch(int signum)
  457. {
  458. if (write(signalpipe[1], "x", 1) <= 0)
  459. /* not much we can do about it */;
  460. }
  461. /*
  462. * Short description of parameters.
  463. */
  464. static void usage(void)
  465. {
  466. printf("Plink: command-line connection utility\n");
  467. printf("%s\n", ver);
  468. printf("Usage: plink [options] [user@]host [command]\n");
  469. printf(" (\"host\" can also be a PuTTY saved session name)\n");
  470. printf("Options:\n");
  471. printf(" -V print version information and exit\n");
  472. printf(" -pgpfp print PGP key fingerprints and exit\n");
  473. printf(" -v show verbose messages\n");
  474. printf(" -load sessname Load settings from saved session\n");
  475. printf(" -ssh -telnet -rlogin -raw -serial\n");
  476. printf(" force use of a particular protocol\n");
  477. printf(" -ssh-connection\n");
  478. printf(" force use of the bare ssh-connection protocol\n");
  479. printf(" -P port connect to specified port\n");
  480. printf(" -l user connect with specified username\n");
  481. printf(" -batch disable all interactive prompts\n");
  482. printf(" -proxycmd command\n");
  483. printf(" use 'command' as local proxy\n");
  484. printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
  485. printf(" Specify the serial configuration (serial only)\n");
  486. printf("The following options only apply to SSH connections:\n");
  487. printf(" -pwfile file login with password read from specified file\n");
  488. printf(" -D [listen-IP:]listen-port\n");
  489. printf(" Dynamic SOCKS-based port forwarding\n");
  490. printf(" -L [listen-IP:]listen-port:host:port\n");
  491. printf(" Forward local port to remote address\n");
  492. printf(" -R [listen-IP:]listen-port:host:port\n");
  493. printf(" Forward remote port to local address\n");
  494. printf(" -X -x enable / disable X11 forwarding\n");
  495. printf(" -A -a enable / disable agent forwarding\n");
  496. printf(" -t -T enable / disable pty allocation\n");
  497. printf(" -1 -2 force use of particular SSH protocol version\n");
  498. printf(" -4 -6 force use of IPv4 or IPv6\n");
  499. printf(" -C enable compression\n");
  500. printf(" -i key private key file for user authentication\n");
  501. printf(" -noagent disable use of Pageant\n");
  502. printf(" -agent enable use of Pageant\n");
  503. printf(" -no-trivial-auth\n");
  504. printf(" disconnect if SSH authentication succeeds trivially\n");
  505. printf(" -noshare disable use of connection sharing\n");
  506. printf(" -share enable use of connection sharing\n");
  507. printf(" -hostkey keyid\n");
  508. printf(" manually specify a host key (may be repeated)\n");
  509. printf(" -sanitise-stderr, -sanitise-stdout, "
  510. "-no-sanitise-stderr, -no-sanitise-stdout\n");
  511. printf(" do/don't strip control chars from standard "
  512. "output/error\n");
  513. printf(" -no-antispoof omit anti-spoofing prompt after "
  514. "authentication\n");
  515. printf(" -m file read remote command(s) from file\n");
  516. printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
  517. printf(" -N don't start a shell/command (SSH-2 only)\n");
  518. printf(" -nc host:port\n");
  519. printf(" open tunnel in place of session (SSH-2 only)\n");
  520. printf(" -sshlog file\n");
  521. printf(" -sshrawlog file\n");
  522. printf(" log protocol details to a file\n");
  523. printf(" -logoverwrite\n");
  524. printf(" -logappend\n");
  525. printf(" control what happens when a log file already exists\n");
  526. printf(" -shareexists\n");
  527. printf(" test whether a connection-sharing upstream exists\n");
  528. exit(1);
  529. }
  530. static void version(void)
  531. {
  532. char *buildinfo_text = buildinfo("\n");
  533. printf("plink: %s\n%s\n", ver, buildinfo_text);
  534. sfree(buildinfo_text);
  535. exit(0);
  536. }
  537. void frontend_net_error_pending(void) {}
  538. const bool share_can_be_downstream = true;
  539. const bool share_can_be_upstream = true;
  540. const bool buildinfo_gtk_relevant = false;
  541. const unsigned cmdline_tooltype =
  542. TOOLTYPE_HOST_ARG |
  543. TOOLTYPE_HOST_ARG_CAN_BE_SESSION |
  544. TOOLTYPE_HOST_ARG_PROTOCOL_PREFIX |
  545. TOOLTYPE_HOST_ARG_FROM_LAUNCHABLE_LOAD;
  546. static bool seen_stdin_eof = false;
  547. static bool plink_pw_setup(void *vctx, pollwrapper *pw)
  548. {
  549. pollwrap_add_fd_rwx(pw, signalpipe[0], SELECT_R);
  550. if (!seen_stdin_eof &&
  551. backend_connected(backend) &&
  552. backend_sendok(backend) &&
  553. backend_sendbuffer(backend) < MAX_STDIN_BACKLOG) {
  554. /* If we're OK to send, then try to read from stdin. */
  555. pollwrap_add_fd_rwx(pw, STDIN_FILENO, SELECT_R);
  556. }
  557. if (bufchain_size(&stdout_data) > 0) {
  558. /* If we have data for stdout, try to write to stdout. */
  559. pollwrap_add_fd_rwx(pw, STDOUT_FILENO, SELECT_W);
  560. }
  561. if (bufchain_size(&stderr_data) > 0) {
  562. /* If we have data for stderr, try to write to stderr. */
  563. pollwrap_add_fd_rwx(pw, STDERR_FILENO, SELECT_W);
  564. }
  565. return true;
  566. }
  567. static void plink_pw_check(void *vctx, pollwrapper *pw)
  568. {
  569. if (pollwrap_check_fd_rwx(pw, signalpipe[0], SELECT_R)) {
  570. char c[1];
  571. struct winsize size;
  572. if (read(signalpipe[0], c, 1) <= 0)
  573. /* ignore error */;
  574. /* ignore its value; it'll be `x' */
  575. if (ioctl(STDIN_FILENO, TIOCGWINSZ, (void *)&size) >= 0)
  576. backend_size(backend, size.ws_col, size.ws_row);
  577. }
  578. if (pollwrap_check_fd_rwx(pw, STDIN_FILENO, SELECT_R)) {
  579. char buf[4096];
  580. int ret;
  581. if (backend_connected(backend)) {
  582. ret = read(STDIN_FILENO, buf, sizeof(buf));
  583. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  584. if (ret < 0) {
  585. perror("stdin: read");
  586. exit(1);
  587. } else if (ret == 0) {
  588. backend_special(backend, SS_EOF, 0);
  589. seen_stdin_eof = true;
  590. } else {
  591. if (local_tty)
  592. from_tty(buf, ret);
  593. else
  594. backend_send(backend, buf, ret);
  595. }
  596. }
  597. }
  598. if (pollwrap_check_fd_rwx(pw, STDOUT_FILENO, SELECT_W))
  599. try_output(false);
  600. if (pollwrap_check_fd_rwx(pw, STDERR_FILENO, SELECT_W))
  601. try_output(true);
  602. }
  603. static bool plink_continue(void *vctx, bool found_any_fd,
  604. bool ran_any_callback)
  605. {
  606. if (!backend_connected(backend) &&
  607. bufchain_size(&stdout_data) == 0 && bufchain_size(&stderr_data) == 0)
  608. return false; /* terminate main loop */
  609. return true;
  610. }
  611. int main(int argc, char **argv)
  612. {
  613. int exitcode;
  614. bool errors;
  615. enum TriState sanitise_stdout = AUTO, sanitise_stderr = AUTO;
  616. bool use_subsystem = false;
  617. bool just_test_share_exists = false;
  618. struct winsize size;
  619. const struct BackendVtable *backvt;
  620. /*
  621. * Initialise port and protocol to sensible defaults. (These
  622. * will be overridden by more or less anything.)
  623. */
  624. settings_set_default_protocol(PROT_SSH);
  625. settings_set_default_port(22);
  626. bufchain_init(&stdout_data);
  627. bufchain_init(&stderr_data);
  628. bufchain_sink_init(&stdout_bcs, &stdout_data);
  629. bufchain_sink_init(&stderr_bcs, &stderr_data);
  630. stdout_bs = BinarySink_UPCAST(&stdout_bcs);
  631. stderr_bs = BinarySink_UPCAST(&stderr_bcs);
  632. outgoingeof = EOF_NO;
  633. stderr_tty_init();
  634. /*
  635. * Process the command line.
  636. */
  637. conf = conf_new();
  638. do_defaults(NULL, conf);
  639. settings_set_default_protocol(conf_get_int(conf, CONF_protocol));
  640. settings_set_default_port(conf_get_int(conf, CONF_port));
  641. errors = false;
  642. {
  643. /*
  644. * Override the default protocol if PLINK_PROTOCOL is set.
  645. */
  646. char *p = getenv("PLINK_PROTOCOL");
  647. if (p) {
  648. const struct BackendVtable *vt = backend_vt_from_name(p);
  649. if (vt) {
  650. settings_set_default_protocol(vt->protocol);
  651. settings_set_default_port(vt->default_port);
  652. conf_set_int(conf, CONF_protocol, vt->protocol);
  653. conf_set_int(conf, CONF_port, vt->default_port);
  654. }
  655. }
  656. }
  657. while (--argc) {
  658. char *p = *++argv;
  659. int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
  660. 1, conf);
  661. if (ret == -2) {
  662. fprintf(stderr,
  663. "plink: option \"%s\" requires an argument\n", p);
  664. errors = true;
  665. } else if (ret == 2) {
  666. --argc, ++argv;
  667. } else if (ret == 1) {
  668. continue;
  669. } else if (!strcmp(p, "-batch")) {
  670. console_batch_mode = true;
  671. } else if (!strcmp(p, "-s")) {
  672. /* Save status to write to conf later. */
  673. use_subsystem = true;
  674. } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
  675. version();
  676. } else if (!strcmp(p, "--help")) {
  677. usage();
  678. exit(0);
  679. } else if (!strcmp(p, "-pgpfp")) {
  680. pgp_fingerprints();
  681. exit(1);
  682. } else if (!strcmp(p, "-o")) {
  683. if (argc <= 1) {
  684. fprintf(stderr,
  685. "plink: option \"-o\" requires an argument\n");
  686. errors = true;
  687. } else {
  688. --argc;
  689. /* Explicitly pass "plink" in place of appname for
  690. * error reporting purposes. appname will have been
  691. * set by be_list.c to something more generic, probably
  692. * "PuTTY". */
  693. provide_xrm_string(*++argv, "plink");
  694. }
  695. } else if (!strcmp(p, "-shareexists")) {
  696. just_test_share_exists = true;
  697. } else if (!strcmp(p, "-fuzznet")) {
  698. conf_set_int(conf, CONF_proxy_type, PROXY_FUZZ);
  699. conf_set_str(conf, CONF_proxy_telnet_command, "%host");
  700. } else if (!strcmp(p, "-sanitise-stdout") ||
  701. !strcmp(p, "-sanitize-stdout")) {
  702. sanitise_stdout = FORCE_ON;
  703. } else if (!strcmp(p, "-no-sanitise-stdout") ||
  704. !strcmp(p, "-no-sanitize-stdout")) {
  705. sanitise_stdout = FORCE_OFF;
  706. } else if (!strcmp(p, "-sanitise-stderr") ||
  707. !strcmp(p, "-sanitize-stderr")) {
  708. sanitise_stderr = FORCE_ON;
  709. } else if (!strcmp(p, "-no-sanitise-stderr") ||
  710. !strcmp(p, "-no-sanitize-stderr")) {
  711. sanitise_stderr = FORCE_OFF;
  712. } else if (!strcmp(p, "-no-antispoof")) {
  713. console_antispoof_prompt = false;
  714. } else if (*p != '-') {
  715. strbuf *cmdbuf = strbuf_new();
  716. while (argc > 0) {
  717. if (cmdbuf->len > 0)
  718. put_byte(cmdbuf, ' '); /* add space separator */
  719. put_dataz(cmdbuf, p);
  720. if (--argc > 0)
  721. p = *++argv;
  722. }
  723. conf_set_str(conf, CONF_remote_cmd, cmdbuf->s);
  724. conf_set_str(conf, CONF_remote_cmd2, "");
  725. conf_set_bool(conf, CONF_nopty, true); /* command => no tty */
  726. strbuf_free(cmdbuf);
  727. break; /* done with cmdline */
  728. } else {
  729. fprintf(stderr, "plink: unknown option \"%s\"\n", p);
  730. errors = true;
  731. }
  732. }
  733. if (errors)
  734. return 1;
  735. if (!cmdline_host_ok(conf)) {
  736. usage();
  737. }
  738. prepare_session(conf);
  739. /*
  740. * Perform command-line overrides on session configuration.
  741. */
  742. cmdline_run_saved(conf);
  743. /*
  744. * If we have no better ideas for the remote username, use the local
  745. * one, as 'ssh' does.
  746. */
  747. if (conf_get_str(conf, CONF_username)[0] == '\0') {
  748. char *user = get_username();
  749. if (user) {
  750. conf_set_str(conf, CONF_username, user);
  751. sfree(user);
  752. }
  753. }
  754. /*
  755. * Apply subsystem status.
  756. */
  757. if (use_subsystem)
  758. conf_set_bool(conf, CONF_ssh_subsys, true);
  759. /*
  760. * Select protocol. This is farmed out into a table in a
  761. * separate file to enable an ssh-free variant.
  762. */
  763. backvt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol));
  764. if (!backvt) {
  765. fprintf(stderr,
  766. "Internal fault: Unsupported protocol found\n");
  767. return 1;
  768. }
  769. if (backvt->flags & BACKEND_NEEDS_TERMINAL) {
  770. fprintf(stderr,
  771. "Plink doesn't support %s, which needs terminal emulation\n",
  772. backvt->displayname_lc);
  773. return 1;
  774. }
  775. /*
  776. * Block SIGPIPE, so that we'll get EPIPE individually on
  777. * particular network connections that go wrong.
  778. */
  779. putty_signal(SIGPIPE, SIG_IGN);
  780. /*
  781. * Set up the pipe we'll use to tell us about SIGWINCH.
  782. */
  783. if (pipe(signalpipe) < 0) {
  784. perror("pipe");
  785. exit(1);
  786. }
  787. /* We don't want the signal handler to block if the pipe's full. */
  788. nonblock(signalpipe[0]);
  789. nonblock(signalpipe[1]);
  790. cloexec(signalpipe[0]);
  791. cloexec(signalpipe[1]);
  792. putty_signal(SIGWINCH, sigwinch);
  793. /*
  794. * Now that we've got the SIGWINCH handler installed, try to find
  795. * out the initial terminal size.
  796. */
  797. if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) >= 0) {
  798. conf_set_int(conf, CONF_width, size.ws_col);
  799. conf_set_int(conf, CONF_height, size.ws_row);
  800. }
  801. /*
  802. * Decide whether to sanitise control sequences out of standard
  803. * output and standard error.
  804. *
  805. * If we weren't given a command-line override, we do this if (a)
  806. * the fd in question is pointing at a terminal, and (b) we aren't
  807. * trying to allocate a terminal as part of the session.
  808. *
  809. * (Rationale: the risk of control sequences is that they cause
  810. * confusion when sent to a local terminal, so if there isn't one,
  811. * no problem. Also, if we allocate a remote terminal, then we
  812. * sent a terminal type, i.e. we told it what kind of escape
  813. * sequences we _like_, i.e. we were expecting to receive some.)
  814. */
  815. if (sanitise_stdout == FORCE_ON ||
  816. (sanitise_stdout == AUTO && isatty(STDOUT_FILENO) &&
  817. conf_get_bool(conf, CONF_nopty))) {
  818. stdout_scc = stripctrl_new(stdout_bs, true, L'\0');
  819. stdout_bs = BinarySink_UPCAST(stdout_scc);
  820. }
  821. if (sanitise_stderr == FORCE_ON ||
  822. (sanitise_stderr == AUTO && isatty(STDERR_FILENO) &&
  823. conf_get_bool(conf, CONF_nopty))) {
  824. stderr_scc = stripctrl_new(stderr_bs, true, L'\0');
  825. stderr_bs = BinarySink_UPCAST(stderr_scc);
  826. }
  827. sk_init();
  828. uxsel_init();
  829. /*
  830. * Plink doesn't provide any way to add forwardings after the
  831. * connection is set up, so if there are none now, we can safely set
  832. * the "simple" flag.
  833. */
  834. if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
  835. !conf_get_bool(conf, CONF_x11_forward) &&
  836. !conf_get_bool(conf, CONF_agentfwd) &&
  837. !conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
  838. conf_set_bool(conf, CONF_ssh_simple, true);
  839. if (just_test_share_exists) {
  840. if (!backvt->test_for_upstream) {
  841. fprintf(stderr, "Connection sharing not supported for this "
  842. "connection type (%s)'\n", backvt->displayname_lc);
  843. return 1;
  844. }
  845. if (backvt->test_for_upstream(conf_get_str(conf, CONF_host),
  846. conf_get_int(conf, CONF_port), conf))
  847. return 0;
  848. else
  849. return 1;
  850. }
  851. /*
  852. * Start up the connection.
  853. */
  854. logctx = log_init(console_cli_logpolicy, conf);
  855. {
  856. char *error, *realhost;
  857. /* nodelay is only useful if stdin is a terminal device */
  858. bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) && isatty(0);
  859. /* This is a good place for a fuzzer to fork us. */
  860. #ifdef __AFL_HAVE_MANUAL_CONTROL
  861. __AFL_INIT();
  862. #endif
  863. error = backend_init(backvt, plink_seat, &backend, logctx, conf,
  864. conf_get_str(conf, CONF_host),
  865. conf_get_int(conf, CONF_port),
  866. &realhost, nodelay,
  867. conf_get_bool(conf, CONF_tcp_keepalives));
  868. if (error) {
  869. fprintf(stderr, "Unable to open connection:\n%s\n", error);
  870. sfree(error);
  871. return 1;
  872. }
  873. ldisc_create(conf, NULL, backend, plink_seat);
  874. sfree(realhost);
  875. }
  876. /*
  877. * Set up the initial console mode. We don't care if this call
  878. * fails, because we know we aren't necessarily running in a
  879. * console.
  880. */
  881. local_tty = (tcgetattr(STDIN_FILENO, &orig_termios) == 0);
  882. atexit(cleanup_termios);
  883. seat_echoedit_update(plink_seat, 1, 1);
  884. cli_main_loop(plink_pw_setup, plink_pw_check, plink_continue, NULL);
  885. exitcode = backend_exitcode(backend);
  886. if (exitcode < 0) {
  887. fprintf(stderr, "Remote process exit code unavailable\n");
  888. exitcode = 1; /* this is an error condition */
  889. }
  890. cleanup_exit(exitcode);
  891. return exitcode; /* shouldn't happen, but placates gcc */
  892. }