plink.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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_default();
  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. .nonfatal = console_nonfatal,
  371. .update_specials_menu = nullseat_update_specials_menu,
  372. .get_ttymode = plink_get_ttymode,
  373. .set_busy_status = nullseat_set_busy_status,
  374. .confirm_ssh_host_key = console_confirm_ssh_host_key,
  375. .confirm_weak_crypto_primitive = console_confirm_weak_crypto_primitive,
  376. .confirm_weak_cached_hostkey = console_confirm_weak_cached_hostkey,
  377. .prompt_descriptions = console_prompt_descriptions,
  378. .is_utf8 = nullseat_is_never_utf8,
  379. .echoedit_update = plink_echoedit_update,
  380. .get_x_display = nullseat_get_x_display,
  381. .get_windowid = nullseat_get_windowid,
  382. .get_window_pixel_size = nullseat_get_window_pixel_size,
  383. .stripctrl_new = console_stripctrl_new,
  384. .set_trust_status = console_set_trust_status,
  385. .can_set_trust_status = console_can_set_trust_status,
  386. .has_mixed_input_stream = console_has_mixed_input_stream,
  387. .verbose = cmdline_seat_verbose,
  388. .interactive = plink_seat_interactive,
  389. .get_cursor_position = nullseat_get_cursor_position,
  390. };
  391. static Seat plink_seat[1] = {{ &plink_seat_vt }};
  392. /*
  393. * Handle data from a local tty in PARMRK format.
  394. */
  395. static void from_tty(void *vbuf, unsigned len)
  396. {
  397. char *p, *q, *end, *buf = vbuf;
  398. static enum {NORMAL, FF, FF00} state = NORMAL;
  399. p = buf; end = buf + len;
  400. while (p < end) {
  401. switch (state) {
  402. case NORMAL:
  403. if (*p == '\xff') {
  404. p++;
  405. state = FF;
  406. } else {
  407. q = memchr(p, '\xff', end - p);
  408. if (q == NULL) q = end;
  409. backend_send(backend, p, q - p);
  410. p = q;
  411. }
  412. break;
  413. case FF:
  414. if (*p == '\xff') {
  415. backend_send(backend, p, 1);
  416. p++;
  417. state = NORMAL;
  418. } else if (*p == '\0') {
  419. p++;
  420. state = FF00;
  421. } else abort();
  422. break;
  423. case FF00:
  424. if (*p == '\0') {
  425. backend_special(backend, SS_BRK, 0);
  426. } else {
  427. /*
  428. * Pretend that PARMRK wasn't set. This involves
  429. * faking what INPCK and IGNPAR would have done if
  430. * we hadn't overridden them. Unfortunately, we
  431. * can't do this entirely correctly because INPCK
  432. * distinguishes between framing and parity
  433. * errors, but PARMRK format represents both in
  434. * the same way. We assume that parity errors are
  435. * more common than framing errors, and hence
  436. * treat all input errors as being subject to
  437. * INPCK.
  438. */
  439. if (orig_termios.c_iflag & INPCK) {
  440. /* If IGNPAR is set, we throw away the character. */
  441. if (!(orig_termios.c_iflag & IGNPAR)) {
  442. /* PE/FE get passed on as NUL. */
  443. *p = 0;
  444. backend_send(backend, p, 1);
  445. }
  446. } else {
  447. /* INPCK not set. Assume we got a parity error. */
  448. backend_send(backend, p, 1);
  449. }
  450. }
  451. p++;
  452. state = NORMAL;
  453. }
  454. }
  455. }
  456. static int signalpipe[2];
  457. void sigwinch(int signum)
  458. {
  459. if (write(signalpipe[1], "x", 1) <= 0)
  460. /* not much we can do about it */;
  461. }
  462. /*
  463. * Short description of parameters.
  464. */
  465. static void usage(void)
  466. {
  467. printf("Plink: command-line connection utility\n");
  468. printf("%s\n", ver);
  469. printf("Usage: plink [options] [user@]host [command]\n");
  470. printf(" (\"host\" can also be a PuTTY saved session name)\n");
  471. printf("Options:\n");
  472. printf(" -V print version information and exit\n");
  473. printf(" -pgpfp print PGP key fingerprints and exit\n");
  474. printf(" -v show verbose messages\n");
  475. printf(" -load sessname Load settings from saved session\n");
  476. printf(" -ssh -telnet -rlogin -raw -serial\n");
  477. printf(" force use of a particular protocol\n");
  478. printf(" -ssh-connection\n");
  479. printf(" force use of the bare ssh-connection protocol\n");
  480. printf(" -P port connect to specified port\n");
  481. printf(" -l user connect with specified username\n");
  482. printf(" -batch disable all interactive prompts\n");
  483. printf(" -proxycmd command\n");
  484. printf(" use 'command' as local proxy\n");
  485. printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
  486. printf(" Specify the serial configuration (serial only)\n");
  487. printf("The following options only apply to SSH connections:\n");
  488. printf(" -pwfile file login with password read from specified file\n");
  489. printf(" -D [listen-IP:]listen-port\n");
  490. printf(" Dynamic SOCKS-based port forwarding\n");
  491. printf(" -L [listen-IP:]listen-port:host:port\n");
  492. printf(" Forward local port to remote address\n");
  493. printf(" -R [listen-IP:]listen-port:host:port\n");
  494. printf(" Forward remote port to local address\n");
  495. printf(" -X -x enable / disable X11 forwarding\n");
  496. printf(" -A -a enable / disable agent forwarding\n");
  497. printf(" -t -T enable / disable pty allocation\n");
  498. printf(" -1 -2 force use of particular SSH protocol version\n");
  499. printf(" -4 -6 force use of IPv4 or IPv6\n");
  500. printf(" -C enable compression\n");
  501. printf(" -i key private key file for user authentication\n");
  502. printf(" -noagent disable use of Pageant\n");
  503. printf(" -agent enable use of Pageant\n");
  504. printf(" -no-trivial-auth\n");
  505. printf(" disconnect if SSH authentication succeeds trivially\n");
  506. printf(" -noshare disable use of connection sharing\n");
  507. printf(" -share enable use of connection sharing\n");
  508. printf(" -hostkey keyid\n");
  509. printf(" manually specify a host key (may be repeated)\n");
  510. printf(" -sanitise-stderr, -sanitise-stdout, "
  511. "-no-sanitise-stderr, -no-sanitise-stdout\n");
  512. printf(" do/don't strip control chars from standard "
  513. "output/error\n");
  514. printf(" -no-antispoof omit anti-spoofing prompt after "
  515. "authentication\n");
  516. printf(" -m file read remote command(s) from file\n");
  517. printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
  518. printf(" -N don't start a shell/command (SSH-2 only)\n");
  519. printf(" -nc host:port\n");
  520. printf(" open tunnel in place of session (SSH-2 only)\n");
  521. printf(" -sshlog file\n");
  522. printf(" -sshrawlog file\n");
  523. printf(" log protocol details to a file\n");
  524. printf(" -logoverwrite\n");
  525. printf(" -logappend\n");
  526. printf(" control what happens when a log file already exists\n");
  527. printf(" -shareexists\n");
  528. printf(" test whether a connection-sharing upstream exists\n");
  529. exit(1);
  530. }
  531. static void version(void)
  532. {
  533. char *buildinfo_text = buildinfo("\n");
  534. printf("plink: %s\n%s\n", ver, buildinfo_text);
  535. sfree(buildinfo_text);
  536. exit(0);
  537. }
  538. void frontend_net_error_pending(void) {}
  539. const bool share_can_be_downstream = true;
  540. const bool share_can_be_upstream = true;
  541. const bool buildinfo_gtk_relevant = false;
  542. const unsigned cmdline_tooltype =
  543. TOOLTYPE_HOST_ARG |
  544. TOOLTYPE_HOST_ARG_CAN_BE_SESSION |
  545. TOOLTYPE_HOST_ARG_PROTOCOL_PREFIX |
  546. TOOLTYPE_HOST_ARG_FROM_LAUNCHABLE_LOAD;
  547. static bool seen_stdin_eof = false;
  548. static bool plink_pw_setup(void *vctx, pollwrapper *pw)
  549. {
  550. pollwrap_add_fd_rwx(pw, signalpipe[0], SELECT_R);
  551. if (!seen_stdin_eof &&
  552. backend_connected(backend) &&
  553. backend_sendok(backend) &&
  554. backend_sendbuffer(backend) < MAX_STDIN_BACKLOG) {
  555. /* If we're OK to send, then try to read from stdin. */
  556. pollwrap_add_fd_rwx(pw, STDIN_FILENO, SELECT_R);
  557. }
  558. if (bufchain_size(&stdout_data) > 0) {
  559. /* If we have data for stdout, try to write to stdout. */
  560. pollwrap_add_fd_rwx(pw, STDOUT_FILENO, SELECT_W);
  561. }
  562. if (bufchain_size(&stderr_data) > 0) {
  563. /* If we have data for stderr, try to write to stderr. */
  564. pollwrap_add_fd_rwx(pw, STDERR_FILENO, SELECT_W);
  565. }
  566. return true;
  567. }
  568. static void plink_pw_check(void *vctx, pollwrapper *pw)
  569. {
  570. if (pollwrap_check_fd_rwx(pw, signalpipe[0], SELECT_R)) {
  571. char c[1];
  572. struct winsize size;
  573. if (read(signalpipe[0], c, 1) <= 0)
  574. /* ignore error */;
  575. /* ignore its value; it'll be `x' */
  576. if (ioctl(STDIN_FILENO, TIOCGWINSZ, (void *)&size) >= 0)
  577. backend_size(backend, size.ws_col, size.ws_row);
  578. }
  579. if (pollwrap_check_fd_rwx(pw, STDIN_FILENO, SELECT_R)) {
  580. char buf[4096];
  581. int ret;
  582. if (backend_connected(backend)) {
  583. ret = read(STDIN_FILENO, buf, sizeof(buf));
  584. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  585. if (ret < 0) {
  586. perror("stdin: read");
  587. exit(1);
  588. } else if (ret == 0) {
  589. backend_special(backend, SS_EOF, 0);
  590. seen_stdin_eof = true;
  591. } else {
  592. if (local_tty)
  593. from_tty(buf, ret);
  594. else
  595. backend_send(backend, buf, ret);
  596. }
  597. }
  598. }
  599. if (pollwrap_check_fd_rwx(pw, STDOUT_FILENO, SELECT_W))
  600. try_output(false);
  601. if (pollwrap_check_fd_rwx(pw, STDERR_FILENO, SELECT_W))
  602. try_output(true);
  603. }
  604. static bool plink_continue(void *vctx, bool found_any_fd,
  605. bool ran_any_callback)
  606. {
  607. if (!backend_connected(backend) &&
  608. bufchain_size(&stdout_data) == 0 && bufchain_size(&stderr_data) == 0)
  609. return false; /* terminate main loop */
  610. return true;
  611. }
  612. int main(int argc, char **argv)
  613. {
  614. int exitcode;
  615. bool errors;
  616. enum TriState sanitise_stdout = AUTO, sanitise_stderr = AUTO;
  617. bool use_subsystem = false;
  618. bool just_test_share_exists = false;
  619. struct winsize size;
  620. const struct BackendVtable *backvt;
  621. /*
  622. * Initialise port and protocol to sensible defaults. (These
  623. * will be overridden by more or less anything.)
  624. */
  625. settings_set_default_protocol(PROT_SSH);
  626. settings_set_default_port(22);
  627. bufchain_init(&stdout_data);
  628. bufchain_init(&stderr_data);
  629. bufchain_sink_init(&stdout_bcs, &stdout_data);
  630. bufchain_sink_init(&stderr_bcs, &stderr_data);
  631. stdout_bs = BinarySink_UPCAST(&stdout_bcs);
  632. stderr_bs = BinarySink_UPCAST(&stderr_bcs);
  633. outgoingeof = EOF_NO;
  634. stderr_tty_init();
  635. /*
  636. * Process the command line.
  637. */
  638. conf = conf_new();
  639. do_defaults(NULL, conf);
  640. settings_set_default_protocol(conf_get_int(conf, CONF_protocol));
  641. settings_set_default_port(conf_get_int(conf, CONF_port));
  642. errors = false;
  643. {
  644. /*
  645. * Override the default protocol if PLINK_PROTOCOL is set.
  646. */
  647. char *p = getenv("PLINK_PROTOCOL");
  648. if (p) {
  649. const struct BackendVtable *vt = backend_vt_from_name(p);
  650. if (vt) {
  651. settings_set_default_protocol(vt->protocol);
  652. settings_set_default_port(vt->default_port);
  653. conf_set_int(conf, CONF_protocol, vt->protocol);
  654. conf_set_int(conf, CONF_port, vt->default_port);
  655. }
  656. }
  657. }
  658. while (--argc) {
  659. char *p = *++argv;
  660. int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
  661. 1, conf);
  662. if (ret == -2) {
  663. fprintf(stderr,
  664. "plink: option \"%s\" requires an argument\n", p);
  665. errors = true;
  666. } else if (ret == 2) {
  667. --argc, ++argv;
  668. } else if (ret == 1) {
  669. continue;
  670. } else if (!strcmp(p, "-s")) {
  671. /* Save status to write to conf later. */
  672. use_subsystem = true;
  673. } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
  674. version();
  675. } else if (!strcmp(p, "--help")) {
  676. usage();
  677. exit(0);
  678. } else if (!strcmp(p, "-pgpfp")) {
  679. pgp_fingerprints();
  680. exit(1);
  681. } else if (!strcmp(p, "-o")) {
  682. if (argc <= 1) {
  683. fprintf(stderr,
  684. "plink: option \"-o\" requires an argument\n");
  685. errors = true;
  686. } else {
  687. --argc;
  688. /* Explicitly pass "plink" in place of appname for
  689. * error reporting purposes. appname will have been
  690. * set by be_list.c to something more generic, probably
  691. * "PuTTY". */
  692. provide_xrm_string(*++argv, "plink");
  693. }
  694. } else if (!strcmp(p, "-shareexists")) {
  695. just_test_share_exists = true;
  696. } else if (!strcmp(p, "-fuzznet")) {
  697. conf_set_int(conf, CONF_proxy_type, PROXY_FUZZ);
  698. conf_set_str(conf, CONF_proxy_telnet_command, "%host");
  699. } else if (!strcmp(p, "-sanitise-stdout") ||
  700. !strcmp(p, "-sanitize-stdout")) {
  701. sanitise_stdout = FORCE_ON;
  702. } else if (!strcmp(p, "-no-sanitise-stdout") ||
  703. !strcmp(p, "-no-sanitize-stdout")) {
  704. sanitise_stdout = FORCE_OFF;
  705. } else if (!strcmp(p, "-sanitise-stderr") ||
  706. !strcmp(p, "-sanitize-stderr")) {
  707. sanitise_stderr = FORCE_ON;
  708. } else if (!strcmp(p, "-no-sanitise-stderr") ||
  709. !strcmp(p, "-no-sanitize-stderr")) {
  710. sanitise_stderr = FORCE_OFF;
  711. } else if (!strcmp(p, "-no-antispoof")) {
  712. console_antispoof_prompt = false;
  713. } else if (*p != '-') {
  714. strbuf *cmdbuf = strbuf_new();
  715. while (argc > 0) {
  716. if (cmdbuf->len > 0)
  717. put_byte(cmdbuf, ' '); /* add space separator */
  718. put_dataz(cmdbuf, p);
  719. if (--argc > 0)
  720. p = *++argv;
  721. }
  722. conf_set_str(conf, CONF_remote_cmd, cmdbuf->s);
  723. conf_set_str(conf, CONF_remote_cmd2, "");
  724. conf_set_bool(conf, CONF_nopty, true); /* command => no tty */
  725. strbuf_free(cmdbuf);
  726. break; /* done with cmdline */
  727. } else {
  728. fprintf(stderr, "plink: unknown option \"%s\"\n", p);
  729. errors = true;
  730. }
  731. }
  732. if (errors)
  733. return 1;
  734. if (!cmdline_host_ok(conf)) {
  735. usage();
  736. }
  737. prepare_session(conf);
  738. /*
  739. * Perform command-line overrides on session configuration.
  740. */
  741. cmdline_run_saved(conf);
  742. /*
  743. * If we have no better ideas for the remote username, use the local
  744. * one, as 'ssh' does.
  745. */
  746. if (conf_get_str(conf, CONF_username)[0] == '\0') {
  747. char *user = get_username();
  748. if (user) {
  749. conf_set_str(conf, CONF_username, user);
  750. sfree(user);
  751. }
  752. }
  753. /*
  754. * Apply subsystem status.
  755. */
  756. if (use_subsystem)
  757. conf_set_bool(conf, CONF_ssh_subsys, true);
  758. /*
  759. * Select protocol. This is farmed out into a table in a
  760. * separate file to enable an ssh-free variant.
  761. */
  762. backvt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol));
  763. if (!backvt) {
  764. fprintf(stderr,
  765. "Internal fault: Unsupported protocol found\n");
  766. return 1;
  767. }
  768. if (backvt->flags & BACKEND_NEEDS_TERMINAL) {
  769. fprintf(stderr,
  770. "Plink doesn't support %s, which needs terminal emulation\n",
  771. backvt->displayname_lc);
  772. return 1;
  773. }
  774. /*
  775. * Block SIGPIPE, so that we'll get EPIPE individually on
  776. * particular network connections that go wrong.
  777. */
  778. putty_signal(SIGPIPE, SIG_IGN);
  779. /*
  780. * Set up the pipe we'll use to tell us about SIGWINCH.
  781. */
  782. if (pipe(signalpipe) < 0) {
  783. perror("pipe");
  784. exit(1);
  785. }
  786. /* We don't want the signal handler to block if the pipe's full. */
  787. nonblock(signalpipe[0]);
  788. nonblock(signalpipe[1]);
  789. cloexec(signalpipe[0]);
  790. cloexec(signalpipe[1]);
  791. putty_signal(SIGWINCH, sigwinch);
  792. /*
  793. * Now that we've got the SIGWINCH handler installed, try to find
  794. * out the initial terminal size.
  795. */
  796. if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) >= 0) {
  797. conf_set_int(conf, CONF_width, size.ws_col);
  798. conf_set_int(conf, CONF_height, size.ws_row);
  799. }
  800. /*
  801. * Decide whether to sanitise control sequences out of standard
  802. * output and standard error.
  803. *
  804. * If we weren't given a command-line override, we do this if (a)
  805. * the fd in question is pointing at a terminal, and (b) we aren't
  806. * trying to allocate a terminal as part of the session.
  807. *
  808. * (Rationale: the risk of control sequences is that they cause
  809. * confusion when sent to a local terminal, so if there isn't one,
  810. * no problem. Also, if we allocate a remote terminal, then we
  811. * sent a terminal type, i.e. we told it what kind of escape
  812. * sequences we _like_, i.e. we were expecting to receive some.)
  813. */
  814. if (sanitise_stdout == FORCE_ON ||
  815. (sanitise_stdout == AUTO && isatty(STDOUT_FILENO) &&
  816. conf_get_bool(conf, CONF_nopty))) {
  817. stdout_scc = stripctrl_new(stdout_bs, true, L'\0');
  818. stdout_bs = BinarySink_UPCAST(stdout_scc);
  819. }
  820. if (sanitise_stderr == FORCE_ON ||
  821. (sanitise_stderr == AUTO && isatty(STDERR_FILENO) &&
  822. conf_get_bool(conf, CONF_nopty))) {
  823. stderr_scc = stripctrl_new(stderr_bs, true, L'\0');
  824. stderr_bs = BinarySink_UPCAST(stderr_scc);
  825. }
  826. sk_init();
  827. uxsel_init();
  828. /*
  829. * Plink doesn't provide any way to add forwardings after the
  830. * connection is set up, so if there are none now, we can safely set
  831. * the "simple" flag.
  832. */
  833. if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
  834. !conf_get_bool(conf, CONF_x11_forward) &&
  835. !conf_get_bool(conf, CONF_agentfwd) &&
  836. !conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
  837. conf_set_bool(conf, CONF_ssh_simple, true);
  838. if (just_test_share_exists) {
  839. if (!backvt->test_for_upstream) {
  840. fprintf(stderr, "Connection sharing not supported for this "
  841. "connection type (%s)'\n", backvt->displayname_lc);
  842. return 1;
  843. }
  844. if (backvt->test_for_upstream(conf_get_str(conf, CONF_host),
  845. conf_get_int(conf, CONF_port), conf))
  846. return 0;
  847. else
  848. return 1;
  849. }
  850. /*
  851. * Start up the connection.
  852. */
  853. logctx = log_init(console_cli_logpolicy, conf);
  854. {
  855. char *error, *realhost;
  856. /* nodelay is only useful if stdin is a terminal device */
  857. bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) && isatty(0);
  858. /* This is a good place for a fuzzer to fork us. */
  859. #ifdef __AFL_HAVE_MANUAL_CONTROL
  860. __AFL_INIT();
  861. #endif
  862. error = backend_init(backvt, plink_seat, &backend, logctx, conf,
  863. conf_get_str(conf, CONF_host),
  864. conf_get_int(conf, CONF_port),
  865. &realhost, nodelay,
  866. conf_get_bool(conf, CONF_tcp_keepalives));
  867. if (error) {
  868. fprintf(stderr, "Unable to open connection:\n%s\n", error);
  869. sfree(error);
  870. return 1;
  871. }
  872. ldisc_create(conf, NULL, backend, plink_seat);
  873. sfree(realhost);
  874. }
  875. /*
  876. * Set up the initial console mode. We don't care if this call
  877. * fails, because we know we aren't necessarily running in a
  878. * console.
  879. */
  880. local_tty = (tcgetattr(STDIN_FILENO, &orig_termios) == 0);
  881. atexit(cleanup_termios);
  882. seat_echoedit_update(plink_seat, 1, 1);
  883. cli_main_loop(plink_pw_setup, plink_pw_check, plink_continue, NULL);
  884. exitcode = backend_exitcode(backend);
  885. if (exitcode < 0) {
  886. fprintf(stderr, "Remote process exit code unavailable\n");
  887. exitcode = 1; /* this is an error condition */
  888. }
  889. cleanup_exit(exitcode);
  890. return exitcode; /* shouldn't happen, but placates gcc */
  891. }