2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
14 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
19 #define MAX_STDIN_BACKLOG 4096
21 void fatalbox(char *p, ...)
24 fprintf(stderr, "FATAL ERROR: ");
26 vfprintf(stderr, p, ap);
32 void connection_fatal(char *p, ...)
35 fprintf(stderr, "FATAL ERROR: ");
37 vfprintf(stderr, p, ap);
44 static char *password = NULL;
46 HANDLE inhandle, outhandle, errhandle;
47 DWORD orig_console_mode;
51 int term_ldisc(int mode)
55 void ldisc_update(int echo, int edit)
57 /* Update stdin read mode to reflect changes in line discipline. */
60 mode = ENABLE_PROCESSED_INPUT;
62 mode = mode | ENABLE_ECHO_INPUT;
64 mode = mode & ~ENABLE_ECHO_INPUT;
66 mode = mode | ENABLE_LINE_INPUT;
68 mode = mode & ~ENABLE_LINE_INPUT;
69 SetConsoleMode(inhandle, mode);
75 HANDLE event, eventback;
78 static DWORD WINAPI stdin_read_thread(void *param)
80 struct input_data *idata = (struct input_data *) param;
83 inhandle = GetStdHandle(STD_INPUT_HANDLE);
85 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
86 &idata->len, NULL) && idata->len > 0) {
87 SetEvent(idata->event);
88 WaitForSingleObject(idata->eventback, INFINITE);
92 SetEvent(idata->event);
98 DWORD len, lenwritten;
102 HANDLE event, eventback;
106 static DWORD WINAPI stdout_write_thread(void *param)
108 struct output_data *odata = (struct output_data *) param;
109 HANDLE outhandle, errhandle;
111 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
112 errhandle = GetStdHandle(STD_ERROR_HANDLE);
115 WaitForSingleObject(odata->eventback, INFINITE);
119 WriteFile(odata->is_stderr ? errhandle : outhandle,
120 odata->buffer, odata->len, &odata->lenwritten, NULL);
121 SetEvent(odata->event);
127 bufchain stdout_data, stderr_data;
128 struct output_data odata, edata;
130 void try_output(int is_stderr)
132 struct output_data *data = (is_stderr ? &edata : &odata);
137 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
138 &senddata, &sendlen);
139 data->buffer = senddata;
141 SetEvent(data->eventback);
146 int from_backend(int is_stderr, char *data, int len)
148 HANDLE h = (is_stderr ? errhandle : outhandle);
154 bufchain_add(&stderr_data, data, len);
157 bufchain_add(&stdout_data, data, len);
161 osize = bufchain_size(&stdout_data);
162 esize = bufchain_size(&stderr_data);
164 return osize + esize;
168 * Short description of parameters.
170 static void usage(void)
172 printf("PuTTY Link: command-line connection utility\n");
174 printf("Usage: plink [options] [user@]host [command]\n");
175 printf(" (\"host\" can also be a PuTTY saved session name)\n");
176 printf("Options:\n");
177 printf(" -v show verbose messages\n");
178 printf(" -ssh force use of ssh protocol\n");
179 printf(" -P port connect to specified port\n");
180 printf(" -pw passw login with specified password\n");
181 printf(" -m file read remote command(s) from file\n");
182 printf(" -L listen-port:host:port Forward local port to "
184 printf(" -R listen-port:host:port Forward remote port to"
189 char *do_select(SOCKET skt, int startup)
193 events = (FD_CONNECT | FD_READ | FD_WRITE |
194 FD_OOB | FD_CLOSE | FD_ACCEPT);
198 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
199 switch (WSAGetLastError()) {
201 return "Network is down";
203 return "WSAAsyncSelect(): unknown error";
209 int main(int argc, char **argv)
213 WSAEVENT stdinevent, stdoutevent, stderrevent;
215 DWORD in_threadid, out_threadid, err_threadid;
216 struct input_data idata;
224 char extra_portfwd[sizeof(cfg.portfwd)];
226 ssh_get_line = console_get_line;
229 skcount = sksize = 0;
231 * Initialise port and protocol to sensible defaults. (These
232 * will be overridden by more or less anything.)
234 default_protocol = PROT_SSH;
239 * Process the command line.
241 do_defaults(NULL, &cfg);
242 default_protocol = cfg.protocol;
243 default_port = cfg.port;
246 * Override the default protocol if PLINK_PROTOCOL is set.
248 char *p = getenv("PLINK_PROTOCOL");
251 for (i = 0; backends[i].backend != NULL; i++) {
252 if (!strcmp(backends[i].name, p)) {
253 default_protocol = cfg.protocol = backends[i].protocol;
254 default_port = cfg.port =
255 backends[i].backend->default_port;
264 if (!strcmp(p, "-ssh")) {
265 default_protocol = cfg.protocol = PROT_SSH;
266 default_port = cfg.port = 22;
267 } else if (!strcmp(p, "-telnet")) {
268 default_protocol = cfg.protocol = PROT_TELNET;
269 default_port = cfg.port = 23;
270 } else if (!strcmp(p, "-rlogin")) {
271 default_protocol = cfg.protocol = PROT_RLOGIN;
272 default_port = cfg.port = 513;
273 } else if (!strcmp(p, "-raw")) {
274 default_protocol = cfg.protocol = PROT_RAW;
275 } else if (!strcmp(p, "-batch")) {
276 console_batch_mode = TRUE;
277 } else if (!strcmp(p, "-v")) {
278 flags |= FLAG_VERBOSE;
279 } else if (!strcmp(p, "-log")) {
280 logfile = "putty.log";
281 } else if (!strcmp(p, "-pw") && argc > 1) {
282 --argc, console_password = *++argv;
283 } else if (!strcmp(p, "-l") && argc > 1) {
285 --argc, username = *++argv;
286 strncpy(cfg.username, username, sizeof(cfg.username));
287 cfg.username[sizeof(cfg.username) - 1] = '\0';
288 } else if ((!strcmp(p, "-L") || !strcmp(p, "-R")) && argc > 1) {
291 --argc, fwd = *++argv;
293 /* if multiple forwards, find end of list */
294 if (ptr[0]=='R' || ptr[0]=='L') {
295 for (i = 0; i < sizeof(extra_portfwd) - 2; i++)
296 if (ptr[i]=='\000' && ptr[i+1]=='\000')
298 ptr = ptr + i + 1; /* point to next forward slot */
300 ptr[0] = p[1]; /* insert a 'L' or 'R' at the start */
301 strncpy(ptr+1, fwd, sizeof(extra_portfwd) - i);
302 q = strchr(ptr, ':');
303 if (q) *q = '\t'; /* replace first : with \t */
304 ptr[strlen(ptr)+1] = '\000'; /* append two '\000' */
305 extra_portfwd[sizeof(extra_portfwd) - 1] = '\0';
306 } else if (!strcmp(p, "-m") && argc > 1) {
307 char *filename, *command;
312 --argc, filename = *++argv;
314 cmdlen = cmdsize = 0;
316 fp = fopen(filename, "r");
318 fprintf(stderr, "plink: unable to open command "
319 "file \"%s\"\n", filename);
327 if (cmdlen >= cmdsize) {
328 cmdsize = cmdlen + 512;
329 command = srealloc(command, cmdsize);
331 command[cmdlen++] = d;
333 cfg.remote_cmd_ptr = command;
334 cfg.remote_cmd_ptr2 = NULL;
335 cfg.nopty = TRUE; /* command => no terminal */
336 } else if (!strcmp(p, "-P") && argc > 1) {
337 --argc, portnumber = atoi(*++argv);
343 * If the hostname starts with "telnet:", set the
344 * protocol to Telnet and process the string as a
347 if (!strncmp(q, "telnet:", 7)) {
351 if (q[0] == '/' && q[1] == '/')
353 cfg.protocol = PROT_TELNET;
355 while (*p && *p != ':' && *p != '/')
364 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
365 cfg.host[sizeof(cfg.host) - 1] = '\0';
369 * Before we process the [user@]host string, we
370 * first check for the presence of a protocol
371 * prefix (a protocol name followed by ",").
376 for (i = 0; backends[i].backend != NULL; i++) {
377 j = strlen(backends[i].name);
379 !memcmp(backends[i].name, p, j)) {
380 default_protocol = cfg.protocol =
381 backends[i].protocol;
383 backends[i].backend->default_port;
391 * Three cases. Either (a) there's a nonzero
392 * length string followed by an @, in which
393 * case that's user and the remainder is host.
394 * Or (b) there's only one string, not counting
395 * a potential initial @, and it exists in the
396 * saved-sessions database. Or (c) only one
397 * string and it _doesn't_ exist in the
402 p++, r = NULL; /* discount initial @ */
408 do_defaults(p, &cfg2);
409 if (cfg2.host[0] == '\0') {
410 /* No settings for this host; use defaults */
411 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
412 cfg.host[sizeof(cfg.host) - 1] = '\0';
413 cfg.port = default_port;
416 cfg.remote_cmd_ptr = cfg.remote_cmd;
420 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
421 cfg.username[sizeof(cfg.username) - 1] = '\0';
422 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
423 cfg.host[sizeof(cfg.host) - 1] = '\0';
424 cfg.port = default_port;
430 cmdlen = cmdsize = 0;
435 if (cmdlen >= cmdsize) {
436 cmdsize = cmdlen + 512;
437 command = srealloc(command, cmdsize);
439 command[cmdlen++]=*p++;
441 if (cmdlen >= cmdsize) {
442 cmdsize = cmdlen + 512;
443 command = srealloc(command, cmdsize);
445 command[cmdlen++]=' '; /* always add trailing space */
446 if (--argc) p = *++argv;
448 if (cmdlen) command[--cmdlen]='\0';
449 /* change trailing blank to NUL */
450 cfg.remote_cmd_ptr = command;
451 cfg.remote_cmd_ptr2 = NULL;
452 cfg.nopty = TRUE; /* command => no terminal */
454 break; /* done with cmdline */
464 * Trim leading whitespace off the hostname if it's there.
467 int space = strspn(cfg.host, " \t");
468 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
471 /* See if host is of the form user@host */
472 if (cfg.host[0] != '\0') {
473 char *atsign = strchr(cfg.host, '@');
474 /* Make sure we're not overflowing the user field */
476 if (atsign - cfg.host < sizeof cfg.username) {
477 strncpy(cfg.username, cfg.host, atsign - cfg.host);
478 cfg.username[atsign - cfg.host] = '\0';
480 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
485 * Trim a colon suffix off the hostname if it's there.
487 cfg.host[strcspn(cfg.host, ":")] = '\0';
489 if (!*cfg.remote_cmd_ptr)
490 flags |= FLAG_INTERACTIVE;
493 * Select protocol. This is farmed out into a table in a
494 * separate file to enable an ssh-free variant.
499 for (i = 0; backends[i].backend != NULL; i++)
500 if (backends[i].protocol == cfg.protocol) {
501 back = backends[i].backend;
506 "Internal fault: Unsupported protocol found\n");
512 * Add extra port forwardings (accumulated on command line) to
520 while (cfg.portfwd[i])
521 i += strlen(cfg.portfwd+i) + 1;
523 if (strlen(p)+2 > sizeof(cfg.portfwd)-i) {
524 fprintf(stderr, "Internal fault: not enough space for all"
525 " port forwardings\n");
528 strncpy(cfg.portfwd+i, p, sizeof(cfg.portfwd)-i-1);
529 i += strlen(cfg.portfwd+i) + 1;
530 cfg.portfwd[i] = '\0';
538 if (portnumber != -1)
539 cfg.port = portnumber;
542 * Initialise WinSock.
544 winsock_ver = MAKEWORD(2, 0);
545 if (WSAStartup(winsock_ver, &wsadata)) {
546 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
547 MB_OK | MB_ICONEXCLAMATION);
550 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
551 MessageBox(NULL, "WinSock version is incompatible with 2.0",
552 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
559 * Start up the connection.
561 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
565 /* nodelay is only useful if stdin is a character device (console) */
566 int nodelay = cfg.tcp_nodelay &&
567 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
569 error = back->init(cfg.host, cfg.port, &realhost, nodelay);
571 fprintf(stderr, "Unable to open connection:\n%s", error);
578 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
579 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
580 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
582 inhandle = GetStdHandle(STD_INPUT_HANDLE);
583 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
584 errhandle = GetStdHandle(STD_ERROR_HANDLE);
585 GetConsoleMode(inhandle, &orig_console_mode);
586 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
589 * Turn off ECHO and LINE input modes. We don't care if this
590 * call fails, because we know we aren't necessarily running in
593 handles[0] = netevent;
594 handles[1] = stdinevent;
595 handles[2] = stdoutevent;
596 handles[3] = stderrevent;
600 * Create spare threads to write to stdout and stderr, so we
601 * can arrange asynchronous writes.
603 odata.event = stdoutevent;
604 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
606 odata.busy = odata.done = 0;
607 if (!CreateThread(NULL, 0, stdout_write_thread,
608 &odata, 0, &out_threadid)) {
609 fprintf(stderr, "Unable to create output thread\n");
612 edata.event = stderrevent;
613 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
615 edata.busy = edata.done = 0;
616 if (!CreateThread(NULL, 0, stdout_write_thread,
617 &edata, 0, &err_threadid)) {
618 fprintf(stderr, "Unable to create error output thread\n");
625 if (!sending && back->sendok()) {
627 * Create a separate thread to read from stdin. This is
628 * a total pain, but I can't find another way to do it:
630 * - an overlapped ReadFile or ReadFileEx just doesn't
631 * happen; we get failure from ReadFileEx, and
632 * ReadFile blocks despite being given an OVERLAPPED
633 * structure. Perhaps we can't do overlapped reads
634 * on consoles. WHY THE HELL NOT?
636 * - WaitForMultipleObjects(netevent, console) doesn't
637 * work, because it signals the console when
638 * _anything_ happens, including mouse motions and
639 * other things that don't cause data to be readable
640 * - so we're back to ReadFile blocking.
642 idata.event = stdinevent;
643 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
644 if (!CreateThread(NULL, 0, stdin_read_thread,
645 &idata, 0, &in_threadid)) {
646 fprintf(stderr, "Unable to create input thread\n");
652 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
654 WSANETWORKEVENTS things;
656 extern SOCKET first_socket(int *), next_socket(int *);
657 extern int select_result(WPARAM, LPARAM);
661 * We must not call select_result() for any socket
662 * until we have finished enumerating within the tree.
663 * This is because select_result() may close the socket
664 * and modify the tree.
666 /* Count the active sockets. */
668 for (socket = first_socket(&socketstate);
669 socket != INVALID_SOCKET;
670 socket = next_socket(&socketstate)) i++;
672 /* Expand the buffer if necessary. */
675 sklist = srealloc(sklist, sksize * sizeof(*sklist));
678 /* Retrieve the sockets into sklist. */
680 for (socket = first_socket(&socketstate);
681 socket != INVALID_SOCKET;
682 socket = next_socket(&socketstate)) {
683 sklist[skcount++] = socket;
686 /* Now we're done enumerating; go through the list. */
687 for (i = 0; i < skcount; i++) {
690 wp = (WPARAM) socket;
691 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
692 static const struct { int bit, mask; } eventtypes[] = {
693 {FD_CONNECT_BIT, FD_CONNECT},
694 {FD_READ_BIT, FD_READ},
695 {FD_CLOSE_BIT, FD_CLOSE},
696 {FD_OOB_BIT, FD_OOB},
697 {FD_WRITE_BIT, FD_WRITE},
698 {FD_ACCEPT_BIT, FD_ACCEPT},
702 noise_ultralight(socket);
703 noise_ultralight(things.lNetworkEvents);
705 for (e = 0; e < lenof(eventtypes); e++)
706 if (things.lNetworkEvents & eventtypes[e].mask) {
708 int err = things.iErrorCode[eventtypes[e].bit];
709 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
710 connopen &= select_result(wp, lp);
716 noise_ultralight(idata.len);
717 if (connopen && back->socket() != NULL) {
719 back->send(idata.buffer, idata.len);
721 back->special(TS_EOF);
726 if (!odata.writeret) {
727 fprintf(stderr, "Unable to write to standard output\n");
730 bufchain_consume(&stdout_data, odata.lenwritten);
731 if (bufchain_size(&stdout_data) > 0)
733 if (connopen && back->socket() != NULL) {
734 back->unthrottle(bufchain_size(&stdout_data) +
735 bufchain_size(&stderr_data));
739 if (!edata.writeret) {
740 fprintf(stderr, "Unable to write to standard output\n");
743 bufchain_consume(&stderr_data, edata.lenwritten);
744 if (bufchain_size(&stderr_data) > 0)
746 if (connopen && back->socket() != NULL) {
747 back->unthrottle(bufchain_size(&stdout_data) +
748 bufchain_size(&stderr_data));
751 if (!reading && back->sendbuffer() < MAX_STDIN_BACKLOG) {
752 SetEvent(idata.eventback);
755 if ((!connopen || back->socket() == NULL) &&
756 bufchain_size(&stdout_data) == 0 &&
757 bufchain_size(&stderr_data) == 0)
758 break; /* we closed the connection */
761 exitcode = back->exitcode();
763 fprintf(stderr, "Remote process exit code unavailable\n");
764 exitcode = 1; /* this is an error condition */