2 * PLink - a command-line (stdin/stdout) variant of PuTTY.
13 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
18 #define MAX_STDIN_BACKLOG 4096
20 void fatalbox(char *p, ...)
23 fprintf(stderr, "FATAL ERROR: ");
25 vfprintf(stderr, p, ap);
31 void connection_fatal(char *p, ...)
34 fprintf(stderr, "FATAL ERROR: ");
36 vfprintf(stderr, p, ap);
43 static char *password = NULL;
45 HANDLE inhandle, outhandle, errhandle;
46 DWORD orig_console_mode;
50 int term_ldisc(int mode)
54 void ldisc_update(int echo, int edit)
56 /* Update stdin read mode to reflect changes in line discipline. */
59 mode = ENABLE_PROCESSED_INPUT;
61 mode = mode | ENABLE_ECHO_INPUT;
63 mode = mode & ~ENABLE_ECHO_INPUT;
65 mode = mode | ENABLE_LINE_INPUT;
67 mode = mode & ~ENABLE_LINE_INPUT;
68 SetConsoleMode(inhandle, mode);
74 HANDLE event, eventback;
77 static DWORD WINAPI stdin_read_thread(void *param)
79 struct input_data *idata = (struct input_data *) param;
82 inhandle = GetStdHandle(STD_INPUT_HANDLE);
84 while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
85 &idata->len, NULL) && idata->len > 0) {
86 SetEvent(idata->event);
87 WaitForSingleObject(idata->eventback, INFINITE);
91 SetEvent(idata->event);
97 DWORD len, lenwritten;
101 HANDLE event, eventback;
105 static DWORD WINAPI stdout_write_thread(void *param)
107 struct output_data *odata = (struct output_data *) param;
108 HANDLE outhandle, errhandle;
110 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
111 errhandle = GetStdHandle(STD_ERROR_HANDLE);
114 WaitForSingleObject(odata->eventback, INFINITE);
118 WriteFile(odata->is_stderr ? errhandle : outhandle,
119 odata->buffer, odata->len, &odata->lenwritten, NULL);
120 SetEvent(odata->event);
126 bufchain stdout_data, stderr_data;
127 struct output_data odata, edata;
129 void try_output(int is_stderr)
131 struct output_data *data = (is_stderr ? &edata : &odata);
136 bufchain_prefix(is_stderr ? &stderr_data : &stdout_data,
137 &senddata, &sendlen);
138 data->buffer = senddata;
140 SetEvent(data->eventback);
145 int from_backend(int is_stderr, char *data, int len)
147 HANDLE h = (is_stderr ? errhandle : outhandle);
151 bufchain_add(&stderr_data, data, len);
154 bufchain_add(&stdout_data, data, len);
158 osize = bufchain_size(&stdout_data);
159 esize = bufchain_size(&stderr_data);
161 return osize + esize;
165 * Short description of parameters.
167 static void usage(void)
169 printf("PuTTY Link: command-line connection utility\n");
171 printf("Usage: plink [options] [user@]host [command]\n");
172 printf(" (\"host\" can also be a PuTTY saved session name)\n");
173 printf("Options:\n");
174 printf(" -v show verbose messages\n");
175 printf(" -ssh force use of ssh protocol\n");
176 printf(" -P port connect to specified port\n");
177 printf(" -pw passw login with specified password\n");
178 printf(" -m file read remote command(s) from file\n");
179 printf(" -L listen-port:host:port Forward local port to "
181 printf(" -R listen-port:host:port Forward remote port to"
186 char *do_select(SOCKET skt, int startup)
190 events = (FD_CONNECT | FD_READ | FD_WRITE |
191 FD_OOB | FD_CLOSE | FD_ACCEPT);
195 if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
196 switch (WSAGetLastError()) {
198 return "Network is down";
200 return "WSAAsyncSelect(): unknown error";
206 int main(int argc, char **argv)
210 WSAEVENT stdinevent, stdoutevent, stderrevent;
212 DWORD in_threadid, out_threadid, err_threadid;
213 struct input_data idata;
221 char extra_portfwd[sizeof(cfg.portfwd)];
223 ssh_get_line = console_get_line;
226 skcount = sksize = 0;
228 * Initialise port and protocol to sensible defaults. (These
229 * will be overridden by more or less anything.)
231 default_protocol = PROT_SSH;
236 * Process the command line.
238 do_defaults(NULL, &cfg);
239 default_protocol = cfg.protocol;
240 default_port = cfg.port;
243 * Override the default protocol if PLINK_PROTOCOL is set.
245 char *p = getenv("PLINK_PROTOCOL");
248 for (i = 0; backends[i].backend != NULL; i++) {
249 if (!strcmp(backends[i].name, p)) {
250 default_protocol = cfg.protocol = backends[i].protocol;
251 default_port = cfg.port =
252 backends[i].backend->default_port;
261 if (!strcmp(p, "-ssh")) {
262 default_protocol = cfg.protocol = PROT_SSH;
263 default_port = cfg.port = 22;
264 } else if (!strcmp(p, "-telnet")) {
265 default_protocol = cfg.protocol = PROT_TELNET;
266 default_port = cfg.port = 23;
267 } else if (!strcmp(p, "-rlogin")) {
268 default_protocol = cfg.protocol = PROT_RLOGIN;
269 default_port = cfg.port = 513;
270 } else if (!strcmp(p, "-raw")) {
271 default_protocol = cfg.protocol = PROT_RAW;
272 } else if (!strcmp(p, "-batch")) {
273 console_batch_mode = TRUE;
274 } else if (!strcmp(p, "-v")) {
275 flags |= FLAG_VERBOSE;
276 } else if (!strcmp(p, "-log")) {
277 logfile = "putty.log";
278 } else if (!strcmp(p, "-pw") && argc > 1) {
279 --argc, console_password = *++argv;
280 } else if (!strcmp(p, "-l") && argc > 1) {
282 --argc, username = *++argv;
283 strncpy(cfg.username, username, sizeof(cfg.username));
284 cfg.username[sizeof(cfg.username) - 1] = '\0';
285 } else if ((!strcmp(p, "-L") || !strcmp(p, "-R")) && argc > 1) {
288 --argc, fwd = *++argv;
290 /* if multiple forwards, find end of list */
291 if (ptr[0]=='R' || ptr[0]=='L') {
292 for (i = 0; i < sizeof(extra_portfwd) - 2; i++)
293 if (ptr[i]=='\000' && ptr[i+1]=='\000')
295 ptr = ptr + i + 1; /* point to next forward slot */
297 ptr[0] = p[1]; /* insert a 'L' or 'R' at the start */
298 strncpy(ptr+1, fwd, sizeof(extra_portfwd) - i);
299 q = strchr(ptr, ':');
300 if (q) *q = '\t'; /* replace first : with \t */
301 ptr[strlen(ptr)+1] = '\000'; /* append two '\000' */
302 extra_portfwd[sizeof(extra_portfwd) - 1] = '\0';
303 } else if (!strcmp(p, "-m") && argc > 1) {
304 char *filename, *command;
309 --argc, filename = *++argv;
311 cmdlen = cmdsize = 0;
313 fp = fopen(filename, "r");
315 fprintf(stderr, "plink: unable to open command "
316 "file \"%s\"\n", filename);
324 if (cmdlen >= cmdsize) {
325 cmdsize = cmdlen + 512;
326 command = srealloc(command, cmdsize);
328 command[cmdlen++] = d;
330 cfg.remote_cmd_ptr = command;
331 cfg.remote_cmd_ptr2 = NULL;
332 cfg.nopty = TRUE; /* command => no terminal */
333 } else if (!strcmp(p, "-P") && argc > 1) {
334 --argc, portnumber = atoi(*++argv);
340 * If the hostname starts with "telnet:", set the
341 * protocol to Telnet and process the string as a
344 if (!strncmp(q, "telnet:", 7)) {
348 if (q[0] == '/' && q[1] == '/')
350 cfg.protocol = PROT_TELNET;
352 while (*p && *p != ':' && *p != '/')
361 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
362 cfg.host[sizeof(cfg.host) - 1] = '\0';
366 * Before we process the [user@]host string, we
367 * first check for the presence of a protocol
368 * prefix (a protocol name followed by ",").
373 for (i = 0; backends[i].backend != NULL; i++) {
374 j = strlen(backends[i].name);
376 !memcmp(backends[i].name, p, j)) {
377 default_protocol = cfg.protocol =
378 backends[i].protocol;
380 backends[i].backend->default_port;
388 * Three cases. Either (a) there's a nonzero
389 * length string followed by an @, in which
390 * case that's user and the remainder is host.
391 * Or (b) there's only one string, not counting
392 * a potential initial @, and it exists in the
393 * saved-sessions database. Or (c) only one
394 * string and it _doesn't_ exist in the
399 p++, r = NULL; /* discount initial @ */
405 do_defaults(p, &cfg2);
406 if (cfg2.host[0] == '\0') {
407 /* No settings for this host; use defaults */
408 strncpy(cfg.host, p, sizeof(cfg.host) - 1);
409 cfg.host[sizeof(cfg.host) - 1] = '\0';
410 cfg.port = default_port;
413 cfg.remote_cmd_ptr = cfg.remote_cmd;
417 strncpy(cfg.username, p, sizeof(cfg.username) - 1);
418 cfg.username[sizeof(cfg.username) - 1] = '\0';
419 strncpy(cfg.host, r, sizeof(cfg.host) - 1);
420 cfg.host[sizeof(cfg.host) - 1] = '\0';
421 cfg.port = default_port;
427 cmdlen = cmdsize = 0;
432 if (cmdlen >= cmdsize) {
433 cmdsize = cmdlen + 512;
434 command = srealloc(command, cmdsize);
436 command[cmdlen++]=*p++;
438 if (cmdlen >= cmdsize) {
439 cmdsize = cmdlen + 512;
440 command = srealloc(command, cmdsize);
442 command[cmdlen++]=' '; /* always add trailing space */
443 if (--argc) p = *++argv;
445 if (cmdlen) command[--cmdlen]='\0';
446 /* change trailing blank to NUL */
447 cfg.remote_cmd_ptr = command;
448 cfg.remote_cmd_ptr2 = NULL;
449 cfg.nopty = TRUE; /* command => no terminal */
451 break; /* done with cmdline */
461 * Trim leading whitespace off the hostname if it's there.
464 int space = strspn(cfg.host, " \t");
465 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
468 /* See if host is of the form user@host */
469 if (cfg.host[0] != '\0') {
470 char *atsign = strchr(cfg.host, '@');
471 /* Make sure we're not overflowing the user field */
473 if (atsign - cfg.host < sizeof cfg.username) {
474 strncpy(cfg.username, cfg.host, atsign - cfg.host);
475 cfg.username[atsign - cfg.host] = '\0';
477 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
482 * Trim a colon suffix off the hostname if it's there.
484 cfg.host[strcspn(cfg.host, ":")] = '\0';
486 if (!*cfg.remote_cmd_ptr)
487 flags |= FLAG_INTERACTIVE;
490 * Select protocol. This is farmed out into a table in a
491 * separate file to enable an ssh-free variant.
496 for (i = 0; backends[i].backend != NULL; i++)
497 if (backends[i].protocol == cfg.protocol) {
498 back = backends[i].backend;
503 "Internal fault: Unsupported protocol found\n");
509 * Add extra port forwardings (accumulated on command line) to
517 while (cfg.portfwd[i])
518 i += strlen(cfg.portfwd+i) + 1;
520 if (strlen(p)+2 > sizeof(cfg.portfwd)-i) {
521 fprintf(stderr, "Internal fault: not enough space for all"
522 " port forwardings\n");
525 strncpy(cfg.portfwd+i, p, sizeof(cfg.portfwd)-i-1);
526 i += strlen(cfg.portfwd+i) + 1;
527 cfg.portfwd[i] = '\0';
535 if (portnumber != -1)
536 cfg.port = portnumber;
539 * Initialise WinSock.
541 winsock_ver = MAKEWORD(2, 0);
542 if (WSAStartup(winsock_ver, &wsadata)) {
543 MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
544 MB_OK | MB_ICONEXCLAMATION);
547 if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 0) {
548 MessageBox(NULL, "WinSock version is incompatible with 2.0",
549 "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
556 * Start up the connection.
558 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
562 /* nodelay is only useful if stdin is a character device (console) */
563 int nodelay = cfg.tcp_nodelay &&
564 (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
566 error = back->init(cfg.host, cfg.port, &realhost, nodelay);
568 fprintf(stderr, "Unable to open connection:\n%s", error);
575 stdinevent = CreateEvent(NULL, FALSE, FALSE, NULL);
576 stdoutevent = CreateEvent(NULL, FALSE, FALSE, NULL);
577 stderrevent = CreateEvent(NULL, FALSE, FALSE, NULL);
579 inhandle = GetStdHandle(STD_INPUT_HANDLE);
580 outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
581 errhandle = GetStdHandle(STD_ERROR_HANDLE);
582 GetConsoleMode(inhandle, &orig_console_mode);
583 SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
586 * Turn off ECHO and LINE input modes. We don't care if this
587 * call fails, because we know we aren't necessarily running in
590 handles[0] = netevent;
591 handles[1] = stdinevent;
592 handles[2] = stdoutevent;
593 handles[3] = stderrevent;
597 * Create spare threads to write to stdout and stderr, so we
598 * can arrange asynchronous writes.
600 odata.event = stdoutevent;
601 odata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
603 odata.busy = odata.done = 0;
604 if (!CreateThread(NULL, 0, stdout_write_thread,
605 &odata, 0, &out_threadid)) {
606 fprintf(stderr, "Unable to create output thread\n");
609 edata.event = stderrevent;
610 edata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
612 edata.busy = edata.done = 0;
613 if (!CreateThread(NULL, 0, stdout_write_thread,
614 &edata, 0, &err_threadid)) {
615 fprintf(stderr, "Unable to create error output thread\n");
622 if (!sending && back->sendok()) {
624 * Create a separate thread to read from stdin. This is
625 * a total pain, but I can't find another way to do it:
627 * - an overlapped ReadFile or ReadFileEx just doesn't
628 * happen; we get failure from ReadFileEx, and
629 * ReadFile blocks despite being given an OVERLAPPED
630 * structure. Perhaps we can't do overlapped reads
631 * on consoles. WHY THE HELL NOT?
633 * - WaitForMultipleObjects(netevent, console) doesn't
634 * work, because it signals the console when
635 * _anything_ happens, including mouse motions and
636 * other things that don't cause data to be readable
637 * - so we're back to ReadFile blocking.
639 idata.event = stdinevent;
640 idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
641 if (!CreateThread(NULL, 0, stdin_read_thread,
642 &idata, 0, &in_threadid)) {
643 fprintf(stderr, "Unable to create input thread\n");
649 n = WaitForMultipleObjects(4, handles, FALSE, INFINITE);
651 WSANETWORKEVENTS things;
653 extern SOCKET first_socket(int *), next_socket(int *);
654 extern int select_result(WPARAM, LPARAM);
658 * We must not call select_result() for any socket
659 * until we have finished enumerating within the tree.
660 * This is because select_result() may close the socket
661 * and modify the tree.
663 /* Count the active sockets. */
665 for (socket = first_socket(&socketstate);
666 socket != INVALID_SOCKET;
667 socket = next_socket(&socketstate)) i++;
669 /* Expand the buffer if necessary. */
672 sklist = srealloc(sklist, sksize * sizeof(*sklist));
675 /* Retrieve the sockets into sklist. */
677 for (socket = first_socket(&socketstate);
678 socket != INVALID_SOCKET;
679 socket = next_socket(&socketstate)) {
680 sklist[skcount++] = socket;
683 /* Now we're done enumerating; go through the list. */
684 for (i = 0; i < skcount; i++) {
687 wp = (WPARAM) socket;
688 if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
689 static const struct { int bit, mask; } eventtypes[] = {
690 {FD_CONNECT_BIT, FD_CONNECT},
691 {FD_READ_BIT, FD_READ},
692 {FD_CLOSE_BIT, FD_CLOSE},
693 {FD_OOB_BIT, FD_OOB},
694 {FD_WRITE_BIT, FD_WRITE},
695 {FD_ACCEPT_BIT, FD_ACCEPT},
699 noise_ultralight(socket);
700 noise_ultralight(things.lNetworkEvents);
702 for (e = 0; e < lenof(eventtypes); e++)
703 if (things.lNetworkEvents & eventtypes[e].mask) {
705 int err = things.iErrorCode[eventtypes[e].bit];
706 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
707 connopen &= select_result(wp, lp);
713 noise_ultralight(idata.len);
714 if (connopen && back->socket() != NULL) {
716 back->send(idata.buffer, idata.len);
718 back->special(TS_EOF);
723 if (!odata.writeret) {
724 fprintf(stderr, "Unable to write to standard output\n");
727 bufchain_consume(&stdout_data, odata.lenwritten);
728 if (bufchain_size(&stdout_data) > 0)
730 if (connopen && back->socket() != NULL) {
731 back->unthrottle(bufchain_size(&stdout_data) +
732 bufchain_size(&stderr_data));
736 if (!edata.writeret) {
737 fprintf(stderr, "Unable to write to standard output\n");
740 bufchain_consume(&stderr_data, edata.lenwritten);
741 if (bufchain_size(&stderr_data) > 0)
743 if (connopen && back->socket() != NULL) {
744 back->unthrottle(bufchain_size(&stdout_data) +
745 bufchain_size(&stderr_data));
748 if (!reading && back->sendbuffer() < MAX_STDIN_BACKLOG) {
749 SetEvent(idata.eventback);
752 if ((!connopen || back->socket() == NULL) &&
753 bufchain_size(&stdout_data) == 0 &&
754 bufchain_size(&stderr_data) == 0)
755 break; /* we closed the connection */
758 exitcode = back->exitcode();
760 fprintf(stderr, "Remote process exit code unavailable\n");
761 exitcode = 1; /* this is an error condition */