uxplink.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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. #ifndef HAVE_NO_SYS_SELECT_H
  17. #include <sys/select.h>
  18. #endif
  19. #define PUTTY_DO_GLOBALS /* actually _define_ globals */
  20. #include "putty.h"
  21. #include "storage.h"
  22. #include "tree234.h"
  23. #define MAX_STDIN_BACKLOG 4096
  24. static void *logctx;
  25. static struct termios orig_termios;
  26. void fatalbox(const char *p, ...)
  27. {
  28. struct termios cf;
  29. va_list ap;
  30. premsg(&cf);
  31. fprintf(stderr, "FATAL ERROR: ");
  32. va_start(ap, p);
  33. vfprintf(stderr, p, ap);
  34. va_end(ap);
  35. fputc('\n', stderr);
  36. postmsg(&cf);
  37. if (logctx) {
  38. log_free(logctx);
  39. logctx = NULL;
  40. }
  41. cleanup_exit(1);
  42. }
  43. void modalfatalbox(const char *p, ...)
  44. {
  45. struct termios cf;
  46. va_list ap;
  47. premsg(&cf);
  48. fprintf(stderr, "FATAL ERROR: ");
  49. va_start(ap, p);
  50. vfprintf(stderr, p, ap);
  51. va_end(ap);
  52. fputc('\n', stderr);
  53. postmsg(&cf);
  54. if (logctx) {
  55. log_free(logctx);
  56. logctx = NULL;
  57. }
  58. cleanup_exit(1);
  59. }
  60. void nonfatal(const char *p, ...)
  61. {
  62. struct termios cf;
  63. va_list ap;
  64. premsg(&cf);
  65. fprintf(stderr, "ERROR: ");
  66. va_start(ap, p);
  67. vfprintf(stderr, p, ap);
  68. va_end(ap);
  69. fputc('\n', stderr);
  70. postmsg(&cf);
  71. }
  72. void connection_fatal(void *frontend, const char *p, ...)
  73. {
  74. struct termios cf;
  75. va_list ap;
  76. premsg(&cf);
  77. fprintf(stderr, "FATAL ERROR: ");
  78. va_start(ap, p);
  79. vfprintf(stderr, p, ap);
  80. va_end(ap);
  81. fputc('\n', stderr);
  82. postmsg(&cf);
  83. if (logctx) {
  84. log_free(logctx);
  85. logctx = NULL;
  86. }
  87. cleanup_exit(1);
  88. }
  89. void cmdline_error(const char *p, ...)
  90. {
  91. struct termios cf;
  92. va_list ap;
  93. premsg(&cf);
  94. fprintf(stderr, "plink: ");
  95. va_start(ap, p);
  96. vfprintf(stderr, p, ap);
  97. va_end(ap);
  98. fputc('\n', stderr);
  99. postmsg(&cf);
  100. exit(1);
  101. }
  102. static int local_tty = FALSE; /* do we have a local tty? */
  103. static Backend *back;
  104. static void *backhandle;
  105. static Conf *conf;
  106. /*
  107. * Default settings that are specific to Unix plink.
  108. */
  109. char *platform_default_s(const char *name)
  110. {
  111. if (!strcmp(name, "TermType"))
  112. return dupstr(getenv("TERM"));
  113. if (!strcmp(name, "SerialLine"))
  114. return dupstr("/dev/ttyS0");
  115. return NULL;
  116. }
  117. int platform_default_i(const char *name, int def)
  118. {
  119. return def;
  120. }
  121. FontSpec *platform_default_fontspec(const char *name)
  122. {
  123. return fontspec_new("");
  124. }
  125. Filename *platform_default_filename(const char *name)
  126. {
  127. if (!strcmp(name, "LogFileName"))
  128. return filename_from_str("putty.log");
  129. else
  130. return filename_from_str("");
  131. }
  132. char *x_get_default(const char *key)
  133. {
  134. return NULL; /* this is a stub */
  135. }
  136. int term_ldisc(Terminal *term, int mode)
  137. {
  138. return FALSE;
  139. }
  140. void frontend_echoedit_update(void *frontend, int echo, int edit)
  141. {
  142. /* Update stdin read mode to reflect changes in line discipline. */
  143. struct termios mode;
  144. if (!local_tty) return;
  145. mode = orig_termios;
  146. if (echo)
  147. mode.c_lflag |= ECHO;
  148. else
  149. mode.c_lflag &= ~ECHO;
  150. if (edit) {
  151. mode.c_iflag |= ICRNL;
  152. mode.c_lflag |= ISIG | ICANON;
  153. mode.c_oflag |= OPOST;
  154. } else {
  155. mode.c_iflag &= ~ICRNL;
  156. mode.c_lflag &= ~(ISIG | ICANON);
  157. mode.c_oflag &= ~OPOST;
  158. /* Solaris sets these to unhelpful values */
  159. mode.c_cc[VMIN] = 1;
  160. mode.c_cc[VTIME] = 0;
  161. /* FIXME: perhaps what we do with IXON/IXOFF should be an
  162. * argument to frontend_echoedit_update(), to allow
  163. * implementation of SSH-2 "xon-xoff" and Rlogin's
  164. * equivalent? */
  165. mode.c_iflag &= ~IXON;
  166. mode.c_iflag &= ~IXOFF;
  167. }
  168. /*
  169. * Mark parity errors and (more important) BREAK on input. This
  170. * is more complex than it need be because POSIX-2001 suggests
  171. * that escaping of valid 0xff in the input stream is dependent on
  172. * IGNPAR being clear even though marking of BREAK isn't. NetBSD
  173. * 2.0 goes one worse and makes it dependent on INPCK too. We
  174. * deal with this by forcing these flags into a useful state and
  175. * then faking the state in which we found them in from_tty() if
  176. * we get passed a parity or framing error.
  177. */
  178. mode.c_iflag = (mode.c_iflag | INPCK | PARMRK) & ~IGNPAR;
  179. tcsetattr(STDIN_FILENO, TCSANOW, &mode);
  180. }
  181. /* Helper function to extract a special character from a termios. */
  182. static char *get_ttychar(struct termios *t, int index)
  183. {
  184. cc_t c = t->c_cc[index];
  185. #if defined(_POSIX_VDISABLE)
  186. if (c == _POSIX_VDISABLE)
  187. return dupstr("");
  188. #endif
  189. return dupprintf("^<%d>", c);
  190. }
  191. char *get_ttymode(void *frontend, const char *mode)
  192. {
  193. /*
  194. * Propagate appropriate terminal modes from the local terminal,
  195. * if any.
  196. */
  197. if (!local_tty) return NULL;
  198. #define GET_CHAR(ourname, uxname) \
  199. do { \
  200. if (strcmp(mode, ourname) == 0) \
  201. return get_ttychar(&orig_termios, uxname); \
  202. } while(0)
  203. #define GET_BOOL(ourname, uxname, uxmemb, transform) \
  204. do { \
  205. if (strcmp(mode, ourname) == 0) { \
  206. int b = (orig_termios.uxmemb & uxname) != 0; \
  207. transform; \
  208. return dupprintf("%d", b); \
  209. } \
  210. } while (0)
  211. /*
  212. * Modes that want to be the same on all terminal devices involved.
  213. */
  214. /* All the special characters supported by SSH */
  215. #if defined(VINTR)
  216. GET_CHAR("INTR", VINTR);
  217. #endif
  218. #if defined(VQUIT)
  219. GET_CHAR("QUIT", VQUIT);
  220. #endif
  221. #if defined(VERASE)
  222. GET_CHAR("ERASE", VERASE);
  223. #endif
  224. #if defined(VKILL)
  225. GET_CHAR("KILL", VKILL);
  226. #endif
  227. #if defined(VEOF)
  228. GET_CHAR("EOF", VEOF);
  229. #endif
  230. #if defined(VEOL)
  231. GET_CHAR("EOL", VEOL);
  232. #endif
  233. #if defined(VEOL2)
  234. GET_CHAR("EOL2", VEOL2);
  235. #endif
  236. #if defined(VSTART)
  237. GET_CHAR("START", VSTART);
  238. #endif
  239. #if defined(VSTOP)
  240. GET_CHAR("STOP", VSTOP);
  241. #endif
  242. #if defined(VSUSP)
  243. GET_CHAR("SUSP", VSUSP);
  244. #endif
  245. #if defined(VDSUSP)
  246. GET_CHAR("DSUSP", VDSUSP);
  247. #endif
  248. #if defined(VREPRINT)
  249. GET_CHAR("REPRINT", VREPRINT);
  250. #endif
  251. #if defined(VWERASE)
  252. GET_CHAR("WERASE", VWERASE);
  253. #endif
  254. #if defined(VLNEXT)
  255. GET_CHAR("LNEXT", VLNEXT);
  256. #endif
  257. #if defined(VFLUSH)
  258. GET_CHAR("FLUSH", VFLUSH);
  259. #endif
  260. #if defined(VSWTCH)
  261. GET_CHAR("SWTCH", VSWTCH);
  262. #endif
  263. #if defined(VSTATUS)
  264. GET_CHAR("STATUS", VSTATUS);
  265. #endif
  266. #if defined(VDISCARD)
  267. GET_CHAR("DISCARD", VDISCARD);
  268. #endif
  269. /* Modes that "configure" other major modes. These should probably be
  270. * considered as user preferences. */
  271. /* Configuration of ICANON */
  272. #if defined(ECHOK)
  273. GET_BOOL("ECHOK", ECHOK, c_lflag, );
  274. #endif
  275. #if defined(ECHOKE)
  276. GET_BOOL("ECHOKE", ECHOKE, c_lflag, );
  277. #endif
  278. #if defined(ECHOE)
  279. GET_BOOL("ECHOE", ECHOE, c_lflag, );
  280. #endif
  281. #if defined(ECHONL)
  282. GET_BOOL("ECHONL", ECHONL, c_lflag, );
  283. #endif
  284. #if defined(XCASE)
  285. GET_BOOL("XCASE", XCASE, c_lflag, );
  286. #endif
  287. /* Configuration of ECHO */
  288. #if defined(ECHOCTL)
  289. GET_BOOL("ECHOCTL", ECHOCTL, c_lflag, );
  290. #endif
  291. /* Configuration of IXON/IXOFF */
  292. #if defined(IXANY)
  293. GET_BOOL("IXANY", IXANY, c_iflag, );
  294. #endif
  295. /* Configuration of OPOST */
  296. #if defined(OLCUC)
  297. GET_BOOL("OLCUC", OLCUC, c_oflag, );
  298. #endif
  299. #if defined(ONLCR)
  300. GET_BOOL("ONLCR", ONLCR, c_oflag, );
  301. #endif
  302. #if defined(OCRNL)
  303. GET_BOOL("OCRNL", OCRNL, c_oflag, );
  304. #endif
  305. #if defined(ONOCR)
  306. GET_BOOL("ONOCR", ONOCR, c_oflag, );
  307. #endif
  308. #if defined(ONLRET)
  309. GET_BOOL("ONLRET", ONLRET, c_oflag, );
  310. #endif
  311. /*
  312. * Modes that want to be set in only one place, and that we have
  313. * squashed locally.
  314. */
  315. #if defined(ISIG)
  316. GET_BOOL("ISIG", ISIG, c_lflag, );
  317. #endif
  318. #if defined(ICANON)
  319. GET_BOOL("ICANON", ICANON, c_lflag, );
  320. #endif
  321. #if defined(ECHO)
  322. GET_BOOL("ECHO", ECHO, c_lflag, );
  323. #endif
  324. #if defined(IXON)
  325. GET_BOOL("IXON", IXON, c_iflag, );
  326. #endif
  327. #if defined(IXOFF)
  328. GET_BOOL("IXOFF", IXOFF, c_iflag, );
  329. #endif
  330. #if defined(OPOST)
  331. GET_BOOL("OPOST", OPOST, c_oflag, );
  332. #endif
  333. /*
  334. * We do not propagate the following modes:
  335. * - Parity/serial settings, which are a local affair and don't
  336. * make sense propagated over SSH's 8-bit byte-stream.
  337. * IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
  338. * - Things that want to be enabled in one place that we don't
  339. * squash locally.
  340. * IUCLC
  341. * - Status bits.
  342. * PENDIN
  343. * - Things I don't know what to do with. (FIXME)
  344. * ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
  345. * INLCR IGNCR ICRNL
  346. */
  347. #undef GET_CHAR
  348. #undef GET_BOOL
  349. /* Fall through to here for unrecognised names, or ones that are
  350. * unsupported on this platform */
  351. return NULL;
  352. }
  353. void cleanup_termios(void)
  354. {
  355. if (local_tty)
  356. tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
  357. }
  358. bufchain stdout_data, stderr_data;
  359. enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
  360. int try_output(int is_stderr)
  361. {
  362. bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
  363. int fd = (is_stderr ? STDERR_FILENO : STDOUT_FILENO);
  364. void *senddata;
  365. int sendlen, ret;
  366. if (bufchain_size(chain) > 0) {
  367. int prev_nonblock = nonblock(fd);
  368. do {
  369. bufchain_prefix(chain, &senddata, &sendlen);
  370. ret = write(fd, senddata, sendlen);
  371. if (ret > 0)
  372. bufchain_consume(chain, ret);
  373. } while (ret == sendlen && bufchain_size(chain) != 0);
  374. if (!prev_nonblock)
  375. no_nonblock(fd);
  376. if (ret < 0 && errno != EAGAIN) {
  377. perror(is_stderr ? "stderr: write" : "stdout: write");
  378. exit(1);
  379. }
  380. }
  381. if (outgoingeof == EOF_PENDING && bufchain_size(&stdout_data) == 0) {
  382. close(STDOUT_FILENO);
  383. outgoingeof = EOF_SENT;
  384. }
  385. return bufchain_size(&stdout_data) + bufchain_size(&stderr_data);
  386. }
  387. int from_backend(void *frontend_handle, int is_stderr,
  388. const char *data, int len)
  389. {
  390. if (is_stderr) {
  391. bufchain_add(&stderr_data, data, len);
  392. return try_output(TRUE);
  393. } else {
  394. assert(outgoingeof == EOF_NO);
  395. bufchain_add(&stdout_data, data, len);
  396. return try_output(FALSE);
  397. }
  398. }
  399. int from_backend_untrusted(void *frontend_handle, const char *data, int len)
  400. {
  401. /*
  402. * No "untrusted" output should get here (the way the code is
  403. * currently, it's all diverted by FLAG_STDERR).
  404. */
  405. assert(!"Unexpected call to from_backend_untrusted()");
  406. return 0; /* not reached */
  407. }
  408. int from_backend_eof(void *frontend_handle)
  409. {
  410. assert(outgoingeof == EOF_NO);
  411. outgoingeof = EOF_PENDING;
  412. try_output(FALSE);
  413. return FALSE; /* do not respond to incoming EOF with outgoing */
  414. }
  415. int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
  416. {
  417. int ret;
  418. ret = cmdline_get_passwd_input(p, in, inlen);
  419. if (ret == -1)
  420. ret = console_get_userpass_input(p, in, inlen);
  421. return ret;
  422. }
  423. /*
  424. * Handle data from a local tty in PARMRK format.
  425. */
  426. static void from_tty(void *vbuf, unsigned len)
  427. {
  428. char *p, *q, *end, *buf = vbuf;
  429. static enum {NORMAL, FF, FF00} state = NORMAL;
  430. p = buf; end = buf + len;
  431. while (p < end) {
  432. switch (state) {
  433. case NORMAL:
  434. if (*p == '\xff') {
  435. p++;
  436. state = FF;
  437. } else {
  438. q = memchr(p, '\xff', end - p);
  439. if (q == NULL) q = end;
  440. back->send(backhandle, p, q - p);
  441. p = q;
  442. }
  443. break;
  444. case FF:
  445. if (*p == '\xff') {
  446. back->send(backhandle, p, 1);
  447. p++;
  448. state = NORMAL;
  449. } else if (*p == '\0') {
  450. p++;
  451. state = FF00;
  452. } else abort();
  453. break;
  454. case FF00:
  455. if (*p == '\0') {
  456. back->special(backhandle, TS_BRK);
  457. } else {
  458. /*
  459. * Pretend that PARMRK wasn't set. This involves
  460. * faking what INPCK and IGNPAR would have done if
  461. * we hadn't overridden them. Unfortunately, we
  462. * can't do this entirely correctly because INPCK
  463. * distinguishes between framing and parity
  464. * errors, but PARMRK format represents both in
  465. * the same way. We assume that parity errors are
  466. * more common than framing errors, and hence
  467. * treat all input errors as being subject to
  468. * INPCK.
  469. */
  470. if (orig_termios.c_iflag & INPCK) {
  471. /* If IGNPAR is set, we throw away the character. */
  472. if (!(orig_termios.c_iflag & IGNPAR)) {
  473. /* PE/FE get passed on as NUL. */
  474. *p = 0;
  475. back->send(backhandle, p, 1);
  476. }
  477. } else {
  478. /* INPCK not set. Assume we got a parity error. */
  479. back->send(backhandle, p, 1);
  480. }
  481. }
  482. p++;
  483. state = NORMAL;
  484. }
  485. }
  486. }
  487. int signalpipe[2];
  488. void sigwinch(int signum)
  489. {
  490. if (write(signalpipe[1], "x", 1) <= 0)
  491. /* not much we can do about it */;
  492. }
  493. /*
  494. * In Plink our selects are synchronous, so these functions are
  495. * empty stubs.
  496. */
  497. uxsel_id *uxsel_input_add(int fd, int rwx) { return NULL; }
  498. void uxsel_input_remove(uxsel_id *id) { }
  499. /*
  500. * Short description of parameters.
  501. */
  502. static void usage(void)
  503. {
  504. printf("Plink: command-line connection utility\n");
  505. printf("%s\n", ver);
  506. printf("Usage: plink [options] [user@]host [command]\n");
  507. printf(" (\"host\" can also be a PuTTY saved session name)\n");
  508. printf("Options:\n");
  509. printf(" -V print version information and exit\n");
  510. printf(" -pgpfp print PGP key fingerprints and exit\n");
  511. printf(" -v show verbose messages\n");
  512. printf(" -load sessname Load settings from saved session\n");
  513. printf(" -ssh -telnet -rlogin -raw -serial\n");
  514. printf(" force use of a particular protocol\n");
  515. printf(" -P port connect to specified port\n");
  516. printf(" -l user connect with specified username\n");
  517. printf(" -batch disable all interactive prompts\n");
  518. printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
  519. printf(" Specify the serial configuration (serial only)\n");
  520. printf("The following options only apply to SSH connections:\n");
  521. printf(" -pw passw login with specified password\n");
  522. printf(" -D [listen-IP:]listen-port\n");
  523. printf(" Dynamic SOCKS-based port forwarding\n");
  524. printf(" -L [listen-IP:]listen-port:host:port\n");
  525. printf(" Forward local port to remote address\n");
  526. printf(" -R [listen-IP:]listen-port:host:port\n");
  527. printf(" Forward remote port to local address\n");
  528. printf(" -X -x enable / disable X11 forwarding\n");
  529. printf(" -A -a enable / disable agent forwarding\n");
  530. printf(" -t -T enable / disable pty allocation\n");
  531. printf(" -1 -2 force use of particular protocol version\n");
  532. printf(" -4 -6 force use of IPv4 or IPv6\n");
  533. printf(" -C enable compression\n");
  534. printf(" -i key private key file for user authentication\n");
  535. printf(" -noagent disable use of Pageant\n");
  536. printf(" -agent enable use of Pageant\n");
  537. printf(" -hostkey aa:bb:cc:...\n");
  538. printf(" manually specify a host key (may be repeated)\n");
  539. printf(" -m file read remote command(s) from file\n");
  540. printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
  541. printf(" -N don't start a shell/command (SSH-2 only)\n");
  542. printf(" -nc host:port\n");
  543. printf(" open tunnel in place of session (SSH-2 only)\n");
  544. printf(" -sshlog file\n");
  545. printf(" -sshrawlog file\n");
  546. printf(" log protocol details to a file\n");
  547. printf(" -shareexists\n");
  548. printf(" test whether a connection-sharing upstream exists\n");
  549. exit(1);
  550. }
  551. static void version(void)
  552. {
  553. printf("plink: %s\n", ver);
  554. exit(1);
  555. }
  556. void frontend_net_error_pending(void) {}
  557. const int share_can_be_downstream = TRUE;
  558. const int share_can_be_upstream = TRUE;
  559. int main(int argc, char **argv)
  560. {
  561. int sending;
  562. int portnumber = -1;
  563. int *fdlist;
  564. int fd;
  565. int i, fdcount, fdsize, fdstate;
  566. int connopen;
  567. int exitcode;
  568. int errors;
  569. int use_subsystem = 0;
  570. int got_host = FALSE;
  571. int just_test_share_exists = FALSE;
  572. unsigned long now;
  573. struct winsize size;
  574. fdlist = NULL;
  575. fdcount = fdsize = 0;
  576. /*
  577. * Initialise port and protocol to sensible defaults. (These
  578. * will be overridden by more or less anything.)
  579. */
  580. default_protocol = PROT_SSH;
  581. default_port = 22;
  582. bufchain_init(&stdout_data);
  583. bufchain_init(&stderr_data);
  584. outgoingeof = EOF_NO;
  585. flags = FLAG_STDERR | FLAG_STDERR_TTY;
  586. stderr_tty_init();
  587. /*
  588. * Process the command line.
  589. */
  590. conf = conf_new();
  591. do_defaults(NULL, conf);
  592. loaded_session = FALSE;
  593. default_protocol = conf_get_int(conf, CONF_protocol);
  594. default_port = conf_get_int(conf, CONF_port);
  595. errors = 0;
  596. {
  597. /*
  598. * Override the default protocol if PLINK_PROTOCOL is set.
  599. */
  600. char *p = getenv("PLINK_PROTOCOL");
  601. if (p) {
  602. const Backend *b = backend_from_name(p);
  603. if (b) {
  604. default_protocol = b->protocol;
  605. default_port = b->default_port;
  606. conf_set_int(conf, CONF_protocol, default_protocol);
  607. conf_set_int(conf, CONF_port, default_port);
  608. }
  609. }
  610. }
  611. while (--argc) {
  612. char *p = *++argv;
  613. if (*p == '-') {
  614. int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
  615. 1, conf);
  616. if (ret == -2) {
  617. fprintf(stderr,
  618. "plink: option \"%s\" requires an argument\n", p);
  619. errors = 1;
  620. } else if (ret == 2) {
  621. --argc, ++argv;
  622. } else if (ret == 1) {
  623. continue;
  624. } else if (!strcmp(p, "-batch")) {
  625. console_batch_mode = 1;
  626. } else if (!strcmp(p, "-s")) {
  627. /* Save status to write to conf later. */
  628. use_subsystem = 1;
  629. } else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
  630. version();
  631. } else if (!strcmp(p, "--help")) {
  632. usage();
  633. exit(0);
  634. } else if (!strcmp(p, "-pgpfp")) {
  635. pgp_fingerprints();
  636. exit(1);
  637. } else if (!strcmp(p, "-o")) {
  638. if (argc <= 1) {
  639. fprintf(stderr,
  640. "plink: option \"-o\" requires an argument\n");
  641. errors = 1;
  642. } else {
  643. --argc;
  644. provide_xrm_string(*++argv);
  645. }
  646. } else if (!strcmp(p, "-shareexists")) {
  647. just_test_share_exists = TRUE;
  648. } else if (!strcmp(p, "-fuzznet")) {
  649. conf_set_int(conf, CONF_proxy_type, PROXY_FUZZ);
  650. conf_set_str(conf, CONF_proxy_telnet_command,
  651. "%host");
  652. } else {
  653. fprintf(stderr, "plink: unknown option \"%s\"\n", p);
  654. errors = 1;
  655. }
  656. } else if (*p) {
  657. if (!conf_launchable(conf) || !(got_host || loaded_session)) {
  658. char *q = p;
  659. /*
  660. * If the hostname starts with "telnet:", set the
  661. * protocol to Telnet and process the string as a
  662. * Telnet URL.
  663. */
  664. if (!strncmp(q, "telnet:", 7)) {
  665. char c;
  666. q += 7;
  667. if (q[0] == '/' && q[1] == '/')
  668. q += 2;
  669. conf_set_int(conf, CONF_protocol, PROT_TELNET);
  670. p = q;
  671. p += host_strcspn(p, ":/");
  672. c = *p;
  673. if (*p)
  674. *p++ = '\0';
  675. if (c == ':')
  676. conf_set_int(conf, CONF_port, atoi(p));
  677. else
  678. conf_set_int(conf, CONF_port, -1);
  679. conf_set_str(conf, CONF_host, q);
  680. got_host = TRUE;
  681. } else {
  682. char *r, *user, *host;
  683. /*
  684. * Before we process the [user@]host string, we
  685. * first check for the presence of a protocol
  686. * prefix (a protocol name followed by ",").
  687. */
  688. r = strchr(p, ',');
  689. if (r) {
  690. const Backend *b;
  691. *r = '\0';
  692. b = backend_from_name(p);
  693. if (b) {
  694. default_protocol = b->protocol;
  695. conf_set_int(conf, CONF_protocol,
  696. default_protocol);
  697. portnumber = b->default_port;
  698. }
  699. p = r + 1;
  700. }
  701. /*
  702. * A nonzero length string followed by an @ is treated
  703. * as a username. (We discount an _initial_ @.) The
  704. * rest of the string (or the whole string if no @)
  705. * is treated as a session name and/or hostname.
  706. */
  707. r = strrchr(p, '@');
  708. if (r == p)
  709. p++, r = NULL; /* discount initial @ */
  710. if (r) {
  711. *r++ = '\0';
  712. user = p, host = r;
  713. } else {
  714. user = NULL, host = p;
  715. }
  716. /*
  717. * Now attempt to load a saved session with the
  718. * same name as the hostname.
  719. */
  720. {
  721. Conf *conf2 = conf_new();
  722. do_defaults(host, conf2);
  723. if (loaded_session || !conf_launchable(conf2)) {
  724. /* No settings for this host; use defaults */
  725. /* (or session was already loaded with -load) */
  726. conf_set_str(conf, CONF_host, host);
  727. conf_set_int(conf, CONF_port, default_port);
  728. got_host = TRUE;
  729. } else {
  730. conf_copy_into(conf, conf2);
  731. loaded_session = TRUE;
  732. }
  733. conf_free(conf2);
  734. }
  735. if (user) {
  736. /* Patch in specified username. */
  737. conf_set_str(conf, CONF_username, user);
  738. }
  739. }
  740. } else {
  741. char *command;
  742. int cmdlen, cmdsize;
  743. cmdlen = cmdsize = 0;
  744. command = NULL;
  745. while (argc) {
  746. while (*p) {
  747. if (cmdlen >= cmdsize) {
  748. cmdsize = cmdlen + 512;
  749. command = sresize(command, cmdsize, char);
  750. }
  751. command[cmdlen++]=*p++;
  752. }
  753. if (cmdlen >= cmdsize) {
  754. cmdsize = cmdlen + 512;
  755. command = sresize(command, cmdsize, char);
  756. }
  757. command[cmdlen++]=' '; /* always add trailing space */
  758. if (--argc) p = *++argv;
  759. }
  760. if (cmdlen) command[--cmdlen]='\0';
  761. /* change trailing blank to NUL */
  762. conf_set_str(conf, CONF_remote_cmd, command);
  763. conf_set_str(conf, CONF_remote_cmd2, "");
  764. conf_set_int(conf, CONF_nopty, TRUE); /* command => no tty */
  765. break; /* done with cmdline */
  766. }
  767. }
  768. }
  769. if (errors)
  770. return 1;
  771. if (!conf_launchable(conf) || !(got_host || loaded_session)) {
  772. usage();
  773. }
  774. /*
  775. * Muck about with the hostname in various ways.
  776. */
  777. {
  778. char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
  779. char *host = hostbuf;
  780. char *p, *q;
  781. /*
  782. * Trim leading whitespace.
  783. */
  784. host += strspn(host, " \t");
  785. /*
  786. * See if host is of the form user@host, and separate out
  787. * the username if so.
  788. */
  789. if (host[0] != '\0') {
  790. char *atsign = strrchr(host, '@');
  791. if (atsign) {
  792. *atsign = '\0';
  793. conf_set_str(conf, CONF_username, host);
  794. host = atsign + 1;
  795. }
  796. }
  797. /*
  798. * Trim a colon suffix off the hostname if it's there. In
  799. * order to protect unbracketed IPv6 address literals
  800. * against this treatment, we do not do this if there's
  801. * _more_ than one colon.
  802. */
  803. {
  804. char *c = host_strchr(host, ':');
  805. if (c) {
  806. char *d = host_strchr(c+1, ':');
  807. if (!d)
  808. *c = '\0';
  809. }
  810. }
  811. /*
  812. * Remove any remaining whitespace.
  813. */
  814. p = hostbuf;
  815. q = host;
  816. while (*q) {
  817. if (*q != ' ' && *q != '\t')
  818. *p++ = *q;
  819. q++;
  820. }
  821. *p = '\0';
  822. conf_set_str(conf, CONF_host, hostbuf);
  823. sfree(hostbuf);
  824. }
  825. /*
  826. * Perform command-line overrides on session configuration.
  827. */
  828. cmdline_run_saved(conf);
  829. /*
  830. * If we have no better ideas for the remote username, use the local
  831. * one, as 'ssh' does.
  832. */
  833. if (conf_get_str(conf, CONF_username)[0] == '\0') {
  834. char *user = get_username();
  835. if (user) {
  836. conf_set_str(conf, CONF_username, user);
  837. sfree(user);
  838. }
  839. }
  840. /*
  841. * Apply subsystem status.
  842. */
  843. if (use_subsystem)
  844. conf_set_int(conf, CONF_ssh_subsys, TRUE);
  845. if (!*conf_get_str(conf, CONF_remote_cmd) &&
  846. !*conf_get_str(conf, CONF_remote_cmd2) &&
  847. !*conf_get_str(conf, CONF_ssh_nc_host))
  848. flags |= FLAG_INTERACTIVE;
  849. /*
  850. * Select protocol. This is farmed out into a table in a
  851. * separate file to enable an ssh-free variant.
  852. */
  853. back = backend_from_proto(conf_get_int(conf, CONF_protocol));
  854. if (back == NULL) {
  855. fprintf(stderr,
  856. "Internal fault: Unsupported protocol found\n");
  857. return 1;
  858. }
  859. /*
  860. * Select port.
  861. */
  862. if (portnumber != -1)
  863. conf_set_int(conf, CONF_port, portnumber);
  864. /*
  865. * Block SIGPIPE, so that we'll get EPIPE individually on
  866. * particular network connections that go wrong.
  867. */
  868. putty_signal(SIGPIPE, SIG_IGN);
  869. /*
  870. * Set up the pipe we'll use to tell us about SIGWINCH.
  871. */
  872. if (pipe(signalpipe) < 0) {
  873. perror("pipe");
  874. exit(1);
  875. }
  876. /* We don't want the signal handler to block if the pipe's full. */
  877. nonblock(signalpipe[0]);
  878. nonblock(signalpipe[1]);
  879. cloexec(signalpipe[0]);
  880. cloexec(signalpipe[1]);
  881. putty_signal(SIGWINCH, sigwinch);
  882. /*
  883. * Now that we've got the SIGWINCH handler installed, try to find
  884. * out the initial terminal size.
  885. */
  886. if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) >= 0) {
  887. conf_set_int(conf, CONF_width, size.ws_col);
  888. conf_set_int(conf, CONF_height, size.ws_row);
  889. }
  890. sk_init();
  891. uxsel_init();
  892. /*
  893. * Plink doesn't provide any way to add forwardings after the
  894. * connection is set up, so if there are none now, we can safely set
  895. * the "simple" flag.
  896. */
  897. if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
  898. !conf_get_int(conf, CONF_x11_forward) &&
  899. !conf_get_int(conf, CONF_agentfwd) &&
  900. !conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
  901. conf_set_int(conf, CONF_ssh_simple, TRUE);
  902. if (just_test_share_exists) {
  903. if (!back->test_for_upstream) {
  904. fprintf(stderr, "Connection sharing not supported for connection "
  905. "type '%s'\n", back->name);
  906. return 1;
  907. }
  908. if (back->test_for_upstream(conf_get_str(conf, CONF_host),
  909. conf_get_int(conf, CONF_port), conf))
  910. return 0;
  911. else
  912. return 1;
  913. }
  914. /*
  915. * Start up the connection.
  916. */
  917. logctx = log_init(NULL, conf);
  918. console_provide_logctx(logctx);
  919. {
  920. const char *error;
  921. char *realhost;
  922. /* nodelay is only useful if stdin is a terminal device */
  923. int nodelay = conf_get_int(conf, CONF_tcp_nodelay) && isatty(0);
  924. /* This is a good place for a fuzzer to fork us. */
  925. #ifdef __AFL_HAVE_MANUAL_CONTROL
  926. __AFL_INIT();
  927. #endif
  928. error = back->init(NULL, &backhandle, conf,
  929. conf_get_str(conf, CONF_host),
  930. conf_get_int(conf, CONF_port),
  931. &realhost, nodelay,
  932. conf_get_int(conf, CONF_tcp_keepalives));
  933. if (error) {
  934. fprintf(stderr, "Unable to open connection:\n%s\n", error);
  935. return 1;
  936. }
  937. back->provide_logctx(backhandle, logctx);
  938. ldisc_create(conf, NULL, back, backhandle, NULL);
  939. sfree(realhost);
  940. }
  941. connopen = 1;
  942. /*
  943. * Set up the initial console mode. We don't care if this call
  944. * fails, because we know we aren't necessarily running in a
  945. * console.
  946. */
  947. local_tty = (tcgetattr(STDIN_FILENO, &orig_termios) == 0);
  948. atexit(cleanup_termios);
  949. frontend_echoedit_update(NULL, 1, 1);
  950. sending = FALSE;
  951. now = GETTICKCOUNT();
  952. while (1) {
  953. fd_set rset, wset, xset;
  954. int maxfd;
  955. int rwx;
  956. int ret;
  957. unsigned long next;
  958. FD_ZERO(&rset);
  959. FD_ZERO(&wset);
  960. FD_ZERO(&xset);
  961. maxfd = 0;
  962. FD_SET_MAX(signalpipe[0], maxfd, rset);
  963. if (connopen && !sending &&
  964. back->connected(backhandle) &&
  965. back->sendok(backhandle) &&
  966. back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
  967. /* If we're OK to send, then try to read from stdin. */
  968. FD_SET_MAX(STDIN_FILENO, maxfd, rset);
  969. }
  970. if (bufchain_size(&stdout_data) > 0) {
  971. /* If we have data for stdout, try to write to stdout. */
  972. FD_SET_MAX(STDOUT_FILENO, maxfd, wset);
  973. }
  974. if (bufchain_size(&stderr_data) > 0) {
  975. /* If we have data for stderr, try to write to stderr. */
  976. FD_SET_MAX(STDERR_FILENO, maxfd, wset);
  977. }
  978. /* Count the currently active fds. */
  979. i = 0;
  980. for (fd = first_fd(&fdstate, &rwx); fd >= 0;
  981. fd = next_fd(&fdstate, &rwx)) i++;
  982. /* Expand the fdlist buffer if necessary. */
  983. if (i > fdsize) {
  984. fdsize = i + 16;
  985. fdlist = sresize(fdlist, fdsize, int);
  986. }
  987. /*
  988. * Add all currently open fds to the select sets, and store
  989. * them in fdlist as well.
  990. */
  991. fdcount = 0;
  992. for (fd = first_fd(&fdstate, &rwx); fd >= 0;
  993. fd = next_fd(&fdstate, &rwx)) {
  994. fdlist[fdcount++] = fd;
  995. if (rwx & 1)
  996. FD_SET_MAX(fd, maxfd, rset);
  997. if (rwx & 2)
  998. FD_SET_MAX(fd, maxfd, wset);
  999. if (rwx & 4)
  1000. FD_SET_MAX(fd, maxfd, xset);
  1001. }
  1002. if (toplevel_callback_pending()) {
  1003. struct timeval tv;
  1004. tv.tv_sec = 0;
  1005. tv.tv_usec = 0;
  1006. ret = select(maxfd, &rset, &wset, &xset, &tv);
  1007. } else if (run_timers(now, &next)) {
  1008. do {
  1009. unsigned long then;
  1010. long ticks;
  1011. struct timeval tv;
  1012. then = now;
  1013. now = GETTICKCOUNT();
  1014. if (now - then > next - then)
  1015. ticks = 0;
  1016. else
  1017. ticks = next - now;
  1018. tv.tv_sec = ticks / 1000;
  1019. tv.tv_usec = ticks % 1000 * 1000;
  1020. ret = select(maxfd, &rset, &wset, &xset, &tv);
  1021. if (ret == 0)
  1022. now = next;
  1023. else
  1024. now = GETTICKCOUNT();
  1025. } while (ret < 0 && errno == EINTR);
  1026. } else {
  1027. ret = select(maxfd, &rset, &wset, &xset, NULL);
  1028. }
  1029. if (ret < 0) {
  1030. perror("select");
  1031. exit(1);
  1032. }
  1033. for (i = 0; i < fdcount; i++) {
  1034. fd = fdlist[i];
  1035. /*
  1036. * We must process exceptional notifications before
  1037. * ordinary readability ones, or we may go straight
  1038. * past the urgent marker.
  1039. */
  1040. if (FD_ISSET(fd, &xset))
  1041. select_result(fd, 4);
  1042. if (FD_ISSET(fd, &rset))
  1043. select_result(fd, 1);
  1044. if (FD_ISSET(fd, &wset))
  1045. select_result(fd, 2);
  1046. }
  1047. if (FD_ISSET(signalpipe[0], &rset)) {
  1048. char c[1];
  1049. struct winsize size;
  1050. if (read(signalpipe[0], c, 1) <= 0)
  1051. /* ignore error */;
  1052. /* ignore its value; it'll be `x' */
  1053. if (ioctl(STDIN_FILENO, TIOCGWINSZ, (void *)&size) >= 0)
  1054. back->size(backhandle, size.ws_col, size.ws_row);
  1055. }
  1056. if (FD_ISSET(STDIN_FILENO, &rset)) {
  1057. char buf[4096];
  1058. int ret;
  1059. if (connopen && back->connected(backhandle)) {
  1060. ret = read(STDIN_FILENO, buf, sizeof(buf));
  1061. if (ret < 0) {
  1062. perror("stdin: read");
  1063. exit(1);
  1064. } else if (ret == 0) {
  1065. back->special(backhandle, TS_EOF);
  1066. sending = FALSE; /* send nothing further after this */
  1067. } else {
  1068. if (local_tty)
  1069. from_tty(buf, ret);
  1070. else
  1071. back->send(backhandle, buf, ret);
  1072. }
  1073. }
  1074. }
  1075. if (FD_ISSET(STDOUT_FILENO, &wset)) {
  1076. back->unthrottle(backhandle, try_output(FALSE));
  1077. }
  1078. if (FD_ISSET(STDERR_FILENO, &wset)) {
  1079. back->unthrottle(backhandle, try_output(TRUE));
  1080. }
  1081. run_toplevel_callbacks();
  1082. if ((!connopen || !back->connected(backhandle)) &&
  1083. bufchain_size(&stdout_data) == 0 &&
  1084. bufchain_size(&stderr_data) == 0)
  1085. break; /* we closed the connection */
  1086. }
  1087. exitcode = back->exitcode(backhandle);
  1088. if (exitcode < 0) {
  1089. fprintf(stderr, "Remote process exit code unavailable\n");
  1090. exitcode = 1; /* this is an error condition */
  1091. }
  1092. cleanup_exit(exitcode);
  1093. return exitcode; /* shouldn't happen, but placates gcc */
  1094. }