]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winplink.c
Add "-serial" to Plink's usage message.
[PuTTY.git] / windows / winplink.c
1 /*
2  * PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8 #include <stdarg.h>
9
10 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
11 #include "putty.h"
12 #include "storage.h"
13 #include "tree234.h"
14
15 #define WM_AGENT_CALLBACK (WM_APP + 4)
16
17 struct agent_callback {
18     void (*callback)(void *, void *, int);
19     void *callback_ctx;
20     void *data;
21     int len;
22 };
23
24 void fatalbox(char *p, ...)
25 {
26     va_list ap;
27     fprintf(stderr, "FATAL ERROR: ");
28     va_start(ap, p);
29     vfprintf(stderr, p, ap);
30     va_end(ap);
31     fputc('\n', stderr);
32     if (logctx) {
33         log_free(logctx);
34         logctx = NULL;
35     }
36     cleanup_exit(1);
37 }
38 void modalfatalbox(char *p, ...)
39 {
40     va_list ap;
41     fprintf(stderr, "FATAL ERROR: ");
42     va_start(ap, p);
43     vfprintf(stderr, p, ap);
44     va_end(ap);
45     fputc('\n', stderr);
46     if (logctx) {
47         log_free(logctx);
48         logctx = NULL;
49     }
50     cleanup_exit(1);
51 }
52 void connection_fatal(void *frontend, char *p, ...)
53 {
54     va_list ap;
55     fprintf(stderr, "FATAL ERROR: ");
56     va_start(ap, p);
57     vfprintf(stderr, p, ap);
58     va_end(ap);
59     fputc('\n', stderr);
60     if (logctx) {
61         log_free(logctx);
62         logctx = NULL;
63     }
64     cleanup_exit(1);
65 }
66 void cmdline_error(char *p, ...)
67 {
68     va_list ap;
69     fprintf(stderr, "plink: ");
70     va_start(ap, p);
71     vfprintf(stderr, p, ap);
72     va_end(ap);
73     fputc('\n', stderr);
74     exit(1);
75 }
76
77 HANDLE inhandle, outhandle, errhandle;
78 struct handle *stdin_handle, *stdout_handle, *stderr_handle;
79 DWORD orig_console_mode;
80 int connopen;
81
82 WSAEVENT netevent;
83
84 static Backend *back;
85 static void *backhandle;
86 static Config cfg;
87
88 int term_ldisc(Terminal *term, int mode)
89 {
90     return FALSE;
91 }
92 void ldisc_update(void *frontend, int echo, int edit)
93 {
94     /* Update stdin read mode to reflect changes in line discipline. */
95     DWORD mode;
96
97     mode = ENABLE_PROCESSED_INPUT;
98     if (echo)
99         mode = mode | ENABLE_ECHO_INPUT;
100     else
101         mode = mode & ~ENABLE_ECHO_INPUT;
102     if (edit)
103         mode = mode | ENABLE_LINE_INPUT;
104     else
105         mode = mode & ~ENABLE_LINE_INPUT;
106     SetConsoleMode(inhandle, mode);
107 }
108
109 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
110
111 int from_backend(void *frontend_handle, int is_stderr,
112                  const char *data, int len)
113 {
114     if (is_stderr) {
115         handle_write(stderr_handle, data, len);
116     } else {
117         handle_write(stdout_handle, data, len);
118     }
119
120     return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
121 }
122
123 int from_backend_untrusted(void *frontend_handle, const char *data, int len)
124 {
125     /*
126      * No "untrusted" output should get here (the way the code is
127      * currently, it's all diverted by FLAG_STDERR).
128      */
129     assert(!"Unexpected call to from_backend_untrusted()");
130     return 0; /* not reached */
131 }
132
133 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
134 {
135     int ret;
136     ret = cmdline_get_passwd_input(p, in, inlen);
137     if (ret == -1)
138         ret = console_get_userpass_input(p, in, inlen);
139     return ret;
140 }
141
142 static DWORD main_thread_id;
143
144 void agent_schedule_callback(void (*callback)(void *, void *, int),
145                              void *callback_ctx, void *data, int len)
146 {
147     struct agent_callback *c = snew(struct agent_callback);
148     c->callback = callback;
149     c->callback_ctx = callback_ctx;
150     c->data = data;
151     c->len = len;
152     PostThreadMessage(main_thread_id, WM_AGENT_CALLBACK, 0, (LPARAM)c);
153 }
154
155 /*
156  *  Short description of parameters.
157  */
158 static void usage(void)
159 {
160     printf("PuTTY Link: command-line connection utility\n");
161     printf("%s\n", ver);
162     printf("Usage: plink [options] [user@]host [command]\n");
163     printf("       (\"host\" can also be a PuTTY saved session name)\n");
164     printf("Options:\n");
165     printf("  -V        print version information and exit\n");
166     printf("  -pgpfp    print PGP key fingerprints and exit\n");
167     printf("  -v        show verbose messages\n");
168     printf("  -load sessname  Load settings from saved session\n");
169     printf("  -ssh -telnet -rlogin -raw -serial\n");
170     printf("            force use of a particular protocol\n");
171     printf("  -P port   connect to specified port\n");
172     printf("  -l user   connect with specified username\n");
173     printf("  -batch    disable all interactive prompts\n");
174     printf("The following options only apply to SSH connections:\n");
175     printf("  -pw passw login with specified password\n");
176     printf("  -D [listen-IP:]listen-port\n");
177     printf("            Dynamic SOCKS-based port forwarding\n");
178     printf("  -L [listen-IP:]listen-port:host:port\n");
179     printf("            Forward local port to remote address\n");
180     printf("  -R [listen-IP:]listen-port:host:port\n");
181     printf("            Forward remote port to local address\n");
182     printf("  -X -x     enable / disable X11 forwarding\n");
183     printf("  -A -a     enable / disable agent forwarding\n");
184     printf("  -t -T     enable / disable pty allocation\n");
185     printf("  -1 -2     force use of particular protocol version\n");
186     printf("  -4 -6     force use of IPv4 or IPv6\n");
187     printf("  -C        enable compression\n");
188     printf("  -i key    private key file for authentication\n");
189     printf("  -noagent  disable use of Pageant\n");
190     printf("  -agent    enable use of Pageant\n");
191     printf("  -m file   read remote command(s) from file\n");
192     printf("  -s        remote command is an SSH subsystem (SSH-2 only)\n");
193     printf("  -N        don't start a shell/command (SSH-2 only)\n");
194     printf("  -nc host:port\n");
195     printf("            open tunnel in place of session (SSH-2 only)\n");
196     printf("  -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
197     printf("            Specify the serial configuration (serial only)\n");
198     exit(1);
199 }
200
201 static void version(void)
202 {
203     printf("plink: %s\n", ver);
204     exit(1);
205 }
206
207 char *do_select(SOCKET skt, int startup)
208 {
209     int events;
210     if (startup) {
211         events = (FD_CONNECT | FD_READ | FD_WRITE |
212                   FD_OOB | FD_CLOSE | FD_ACCEPT);
213     } else {
214         events = 0;
215     }
216     if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
217         switch (p_WSAGetLastError()) {
218           case WSAENETDOWN:
219             return "Network is down";
220           default:
221             return "WSAEventSelect(): unknown error";
222         }
223     }
224     return NULL;
225 }
226
227 int stdin_gotdata(struct handle *h, void *data, int len)
228 {
229     if (len < 0) {
230         /*
231          * Special case: report read error.
232          */
233         char buf[4096];
234         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -len, 0,
235                       buf, lenof(buf), NULL);
236         buf[lenof(buf)-1] = '\0';
237         if (buf[strlen(buf)-1] == '\n')
238             buf[strlen(buf)-1] = '\0';
239         fprintf(stderr, "Unable to read from standard input: %s\n", buf);
240         cleanup_exit(0);
241     }
242     noise_ultralight(len);
243     if (connopen && back->connected(backhandle)) {
244         if (len > 0) {
245             return back->send(backhandle, data, len);
246         } else {
247             back->special(backhandle, TS_EOF);
248             return 0;
249         }
250     } else
251         return 0;
252 }
253
254 void stdouterr_sent(struct handle *h, int new_backlog)
255 {
256     if (new_backlog < 0) {
257         /*
258          * Special case: report write error.
259          */
260         char buf[4096];
261         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, -new_backlog, 0,
262                       buf, lenof(buf), NULL);
263         buf[lenof(buf)-1] = '\0';
264         if (buf[strlen(buf)-1] == '\n')
265             buf[strlen(buf)-1] = '\0';
266         fprintf(stderr, "Unable to write to standard %s: %s\n",
267                 (h == stdout_handle ? "output" : "error"), buf);
268         cleanup_exit(0);
269     }
270     if (connopen && back->connected(backhandle)) {
271         back->unthrottle(backhandle, (handle_backlog(stdout_handle) +
272                                       handle_backlog(stderr_handle)));
273     }
274 }
275
276 int main(int argc, char **argv)
277 {
278     int sending;
279     int portnumber = -1;
280     SOCKET *sklist;
281     int skcount, sksize;
282     int exitcode;
283     int errors;
284     int use_subsystem = 0;
285     long now, next;
286
287     sklist = NULL;
288     skcount = sksize = 0;
289     /*
290      * Initialise port and protocol to sensible defaults. (These
291      * will be overridden by more or less anything.)
292      */
293     default_protocol = PROT_SSH;
294     default_port = 22;
295
296     flags = FLAG_STDERR;
297     /*
298      * Process the command line.
299      */
300     do_defaults(NULL, &cfg);
301     loaded_session = FALSE;
302     default_protocol = cfg.protocol;
303     default_port = cfg.port;
304     errors = 0;
305     {
306         /*
307          * Override the default protocol if PLINK_PROTOCOL is set.
308          */
309         char *p = getenv("PLINK_PROTOCOL");
310         if (p) {
311             const Backend *b = backend_from_name(p);
312             if (b) {
313                 default_protocol = cfg.protocol = b->protocol;
314                 default_port = cfg.port = b->default_port;
315             }
316         }
317     }
318     while (--argc) {
319         char *p = *++argv;
320         if (*p == '-') {
321             int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
322                                             1, &cfg);
323             if (ret == -2) {
324                 fprintf(stderr,
325                         "plink: option \"%s\" requires an argument\n", p);
326                 errors = 1;
327             } else if (ret == 2) {
328                 --argc, ++argv;
329             } else if (ret == 1) {
330                 continue;
331             } else if (!strcmp(p, "-batch")) {
332                 console_batch_mode = 1;
333             } else if (!strcmp(p, "-s")) {
334                 /* Save status to write to cfg later. */
335                 use_subsystem = 1;
336             } else if (!strcmp(p, "-V")) {
337                 version();
338             } else if (!strcmp(p, "-pgpfp")) {
339                 pgp_fingerprints();
340                 exit(1);
341             } else {
342                 fprintf(stderr, "plink: unknown option \"%s\"\n", p);
343                 errors = 1;
344             }
345         } else if (*p) {
346             if (!cfg_launchable(&cfg)) {
347                 char *q = p;
348                 /*
349                  * If the hostname starts with "telnet:", set the
350                  * protocol to Telnet and process the string as a
351                  * Telnet URL.
352                  */
353                 if (!strncmp(q, "telnet:", 7)) {
354                     char c;
355
356                     q += 7;
357                     if (q[0] == '/' && q[1] == '/')
358                         q += 2;
359                     cfg.protocol = PROT_TELNET;
360                     p = q;
361                     while (*p && *p != ':' && *p != '/')
362                         p++;
363                     c = *p;
364                     if (*p)
365                         *p++ = '\0';
366                     if (c == ':')
367                         cfg.port = atoi(p);
368                     else
369                         cfg.port = -1;
370                     strncpy(cfg.host, q, sizeof(cfg.host) - 1);
371                     cfg.host[sizeof(cfg.host) - 1] = '\0';
372                 } else {
373                     char *r, *user, *host;
374                     /*
375                      * Before we process the [user@]host string, we
376                      * first check for the presence of a protocol
377                      * prefix (a protocol name followed by ",").
378                      */
379                     r = strchr(p, ',');
380                     if (r) {
381                         const Backend *b;
382                         *r = '\0';
383                         b = backend_from_name(p);
384                         if (b) {
385                             default_protocol = cfg.protocol = b->protocol;
386                             portnumber = b->default_port;
387                         }
388                         p = r + 1;
389                     }
390
391                     /*
392                      * A nonzero length string followed by an @ is treated
393                      * as a username. (We discount an _initial_ @.) The
394                      * rest of the string (or the whole string if no @)
395                      * is treated as a session name and/or hostname.
396                      */
397                     r = strrchr(p, '@');
398                     if (r == p)
399                         p++, r = NULL; /* discount initial @ */
400                     if (r) {
401                         *r++ = '\0';
402                         user = p, host = r;
403                     } else {
404                         user = NULL, host = p;
405                     }
406
407                     /*
408                      * Now attempt to load a saved session with the
409                      * same name as the hostname.
410                      */
411                     {
412                         Config cfg2;
413                         do_defaults(host, &cfg2);
414                         if (loaded_session || !cfg_launchable(&cfg2)) {
415                             /* No settings for this host; use defaults */
416                             /* (or session was already loaded with -load) */
417                             strncpy(cfg.host, host, sizeof(cfg.host) - 1);
418                             cfg.host[sizeof(cfg.host) - 1] = '\0';
419                             cfg.port = default_port;
420                         } else {
421                             cfg = cfg2;
422                         }
423                     }
424
425                     if (user) {
426                         /* Patch in specified username. */
427                         strncpy(cfg.username, user,
428                                 sizeof(cfg.username) - 1);
429                         cfg.username[sizeof(cfg.username) - 1] = '\0';
430                     }
431
432                 }
433             } else {
434                 char *command;
435                 int cmdlen, cmdsize;
436                 cmdlen = cmdsize = 0;
437                 command = NULL;
438
439                 while (argc) {
440                     while (*p) {
441                         if (cmdlen >= cmdsize) {
442                             cmdsize = cmdlen + 512;
443                             command = sresize(command, cmdsize, char);
444                         }
445                         command[cmdlen++]=*p++;
446                     }
447                     if (cmdlen >= cmdsize) {
448                         cmdsize = cmdlen + 512;
449                         command = sresize(command, cmdsize, char);
450                     }
451                     command[cmdlen++]=' '; /* always add trailing space */
452                     if (--argc) p = *++argv;
453                 }
454                 if (cmdlen) command[--cmdlen]='\0';
455                                        /* change trailing blank to NUL */
456                 cfg.remote_cmd_ptr = command;
457                 cfg.remote_cmd_ptr2 = NULL;
458                 cfg.nopty = TRUE;      /* command => no terminal */
459
460                 break;                 /* done with cmdline */
461             }
462         }
463     }
464
465     if (errors)
466         return 1;
467
468     if (!cfg_launchable(&cfg)) {
469         usage();
470     }
471
472     /*
473      * Trim leading whitespace off the hostname if it's there.
474      */
475     {
476         int space = strspn(cfg.host, " \t");
477         memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
478     }
479
480     /* See if host is of the form user@host */
481     if (cfg_launchable(&cfg)) {
482         char *atsign = strrchr(cfg.host, '@');
483         /* Make sure we're not overflowing the user field */
484         if (atsign) {
485             if (atsign - cfg.host < sizeof cfg.username) {
486                 strncpy(cfg.username, cfg.host, atsign - cfg.host);
487                 cfg.username[atsign - cfg.host] = '\0';
488             }
489             memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
490         }
491     }
492
493     /*
494      * Perform command-line overrides on session configuration.
495      */
496     cmdline_run_saved(&cfg);
497
498     /*
499      * Apply subsystem status.
500      */
501     if (use_subsystem)
502         cfg.ssh_subsys = TRUE;
503
504     /*
505      * Trim a colon suffix off the hostname if it's there.
506      */
507     cfg.host[strcspn(cfg.host, ":")] = '\0';
508
509     /*
510      * Remove any remaining whitespace from the hostname.
511      */
512     {
513         int p1 = 0, p2 = 0;
514         while (cfg.host[p2] != '\0') {
515             if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
516                 cfg.host[p1] = cfg.host[p2];
517                 p1++;
518             }
519             p2++;
520         }
521         cfg.host[p1] = '\0';
522     }
523
524     if (!cfg.remote_cmd_ptr && !*cfg.remote_cmd && !*cfg.ssh_nc_host)
525         flags |= FLAG_INTERACTIVE;
526
527     /*
528      * Select protocol. This is farmed out into a table in a
529      * separate file to enable an ssh-free variant.
530      */
531     back = backend_from_proto(cfg.protocol);
532     if (back == NULL) {
533         fprintf(stderr,
534                 "Internal fault: Unsupported protocol found\n");
535         return 1;
536     }
537
538     /*
539      * Select port.
540      */
541     if (portnumber != -1)
542         cfg.port = portnumber;
543
544     sk_init();
545     if (p_WSAEventSelect == NULL) {
546         fprintf(stderr, "Plink requires WinSock 2\n");
547         return 1;
548     }
549
550     logctx = log_init(NULL, &cfg);
551     console_provide_logctx(logctx);
552
553     /*
554      * Start up the connection.
555      */
556     netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
557     {
558         const char *error;
559         char *realhost;
560         /* nodelay is only useful if stdin is a character device (console) */
561         int nodelay = cfg.tcp_nodelay &&
562             (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
563
564         error = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port,
565                            &realhost, nodelay, cfg.tcp_keepalives);
566         if (error) {
567             fprintf(stderr, "Unable to open connection:\n%s", error);
568             return 1;
569         }
570         back->provide_logctx(backhandle, logctx);
571         sfree(realhost);
572     }
573     connopen = 1;
574
575     inhandle = GetStdHandle(STD_INPUT_HANDLE);
576     outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
577     errhandle = GetStdHandle(STD_ERROR_HANDLE);
578
579     /*
580      * Turn off ECHO and LINE input modes. We don't care if this
581      * call fails, because we know we aren't necessarily running in
582      * a console.
583      */
584     GetConsoleMode(inhandle, &orig_console_mode);
585     SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
586
587     /*
588      * Pass the output handles to the handle-handling subsystem.
589      * (The input one we leave until we're through the
590      * authentication process.)
591      */
592     stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
593     stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
594
595     main_thread_id = GetCurrentThreadId();
596
597     sending = FALSE;
598
599     now = GETTICKCOUNT();
600
601     while (1) {
602         int nhandles;
603         HANDLE *handles;        
604         int n;
605         DWORD ticks;
606
607         if (!sending && back->sendok(backhandle)) {
608             stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
609                                             0);
610             sending = TRUE;
611         }
612
613         if (run_timers(now, &next)) {
614             ticks = next - GETTICKCOUNT();
615             if (ticks < 0) ticks = 0;  /* just in case */
616         } else {
617             ticks = INFINITE;
618         }
619
620         handles = handle_get_events(&nhandles);
621         handles = sresize(handles, nhandles+1, HANDLE);
622         handles[nhandles] = netevent;
623         n = MsgWaitForMultipleObjects(nhandles+1, handles, FALSE, ticks,
624                                       QS_POSTMESSAGE);
625         if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
626             handle_got_event(handles[n - WAIT_OBJECT_0]);
627         } else if (n == WAIT_OBJECT_0 + nhandles) {
628             WSANETWORKEVENTS things;
629             SOCKET socket;
630             extern SOCKET first_socket(int *), next_socket(int *);
631             extern int select_result(WPARAM, LPARAM);
632             int i, socketstate;
633
634             /*
635              * We must not call select_result() for any socket
636              * until we have finished enumerating within the tree.
637              * This is because select_result() may close the socket
638              * and modify the tree.
639              */
640             /* Count the active sockets. */
641             i = 0;
642             for (socket = first_socket(&socketstate);
643                  socket != INVALID_SOCKET;
644                  socket = next_socket(&socketstate)) i++;
645
646             /* Expand the buffer if necessary. */
647             if (i > sksize) {
648                 sksize = i + 16;
649                 sklist = sresize(sklist, sksize, SOCKET);
650             }
651
652             /* Retrieve the sockets into sklist. */
653             skcount = 0;
654             for (socket = first_socket(&socketstate);
655                  socket != INVALID_SOCKET;
656                  socket = next_socket(&socketstate)) {
657                 sklist[skcount++] = socket;
658             }
659
660             /* Now we're done enumerating; go through the list. */
661             for (i = 0; i < skcount; i++) {
662                 WPARAM wp;
663                 socket = sklist[i];
664                 wp = (WPARAM) socket;
665                 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
666                     static const struct { int bit, mask; } eventtypes[] = {
667                         {FD_CONNECT_BIT, FD_CONNECT},
668                         {FD_READ_BIT, FD_READ},
669                         {FD_CLOSE_BIT, FD_CLOSE},
670                         {FD_OOB_BIT, FD_OOB},
671                         {FD_WRITE_BIT, FD_WRITE},
672                         {FD_ACCEPT_BIT, FD_ACCEPT},
673                     };
674                     int e;
675
676                     noise_ultralight(socket);
677                     noise_ultralight(things.lNetworkEvents);
678
679                     for (e = 0; e < lenof(eventtypes); e++)
680                         if (things.lNetworkEvents & eventtypes[e].mask) {
681                             LPARAM lp;
682                             int err = things.iErrorCode[eventtypes[e].bit];
683                             lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
684                             connopen &= select_result(wp, lp);
685                         }
686                 }
687             }
688         } else if (n == WAIT_OBJECT_0 + nhandles + 1) {
689             MSG msg;
690             while (PeekMessage(&msg, INVALID_HANDLE_VALUE,
691                                WM_AGENT_CALLBACK, WM_AGENT_CALLBACK,
692                                PM_REMOVE)) {
693                 struct agent_callback *c = (struct agent_callback *)msg.lParam;
694                 c->callback(c->callback_ctx, c->data, c->len);
695                 sfree(c);
696             }
697         }
698
699         if (n == WAIT_TIMEOUT) {
700             now = next;
701         } else {
702             now = GETTICKCOUNT();
703         }
704
705         sfree(handles);
706
707         if (sending)
708             handle_unthrottle(stdin_handle, back->sendbuffer(backhandle));
709
710         if ((!connopen || !back->connected(backhandle)) &&
711             handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
712             break;                     /* we closed the connection */
713     }
714     exitcode = back->exitcode(backhandle);
715     if (exitcode < 0) {
716         fprintf(stderr, "Remote process exit code unavailable\n");
717         exitcode = 1;                  /* this is an error condition */
718     }
719     cleanup_exit(exitcode);
720     return 0;                          /* placate compiler warning */
721 }