]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxplink.c
Prevent another segfault. Oops.
[PuTTY.git] / unix / uxplink.c
1 /*
2  * PLink - a 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 #include <unistd.h>
10 #include <fcntl.h>
11 #include <termios.h>
12
13 /* More helpful version of the FD_SET macro, to also handle maxfd. */
14 #define FD_SET_MAX(fd, max, set) do { \
15     FD_SET(fd, &set); \
16     if (max < fd + 1) max = fd + 1; \
17 } while (0)
18
19 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
20 #include "putty.h"
21 #include "storage.h"
22 #include "tree234.h"
23
24 #define MAX_STDIN_BACKLOG 4096
25
26 void fatalbox(char *p, ...)
27 {
28     va_list ap;
29     fprintf(stderr, "FATAL ERROR: ");
30     va_start(ap, p);
31     vfprintf(stderr, p, ap);
32     va_end(ap);
33     fputc('\n', stderr);
34     cleanup_exit(1);
35 }
36 void modalfatalbox(char *p, ...)
37 {
38     va_list ap;
39     fprintf(stderr, "FATAL ERROR: ");
40     va_start(ap, p);
41     vfprintf(stderr, p, ap);
42     va_end(ap);
43     fputc('\n', stderr);
44     cleanup_exit(1);
45 }
46 void connection_fatal(void *frontend, char *p, ...)
47 {
48     va_list ap;
49     fprintf(stderr, "FATAL ERROR: ");
50     va_start(ap, p);
51     vfprintf(stderr, p, ap);
52     va_end(ap);
53     fputc('\n', stderr);
54     cleanup_exit(1);
55 }
56 void cmdline_error(char *p, ...)
57 {
58     va_list ap;
59     fprintf(stderr, "plink: ");
60     va_start(ap, p);
61     vfprintf(stderr, p, ap);
62     va_end(ap);
63     fputc('\n', stderr);
64     exit(1);
65 }
66
67 struct termios orig_termios;
68
69 static Backend *back;
70 static void *backhandle;
71
72 char *x_get_default(char *key)
73 {
74     return NULL;                       /* this is a stub */
75 }
76 int term_ldisc(Terminal *term, int mode)
77 {
78     return FALSE;
79 }
80 void ldisc_update(void *frontend, int echo, int edit)
81 {
82     /* Update stdin read mode to reflect changes in line discipline. */
83     struct termios mode;
84
85     mode = orig_termios;
86
87     if (echo)
88         mode.c_lflag |= ECHO;
89     else
90         mode.c_lflag &= ~ECHO;
91
92     if (edit)
93         mode.c_lflag |= ISIG | ICANON;
94     else
95         mode.c_lflag &= ~(ISIG | ICANON);
96
97     tcsetattr(0, TCSANOW, &mode);
98 }
99
100 void cleanup_termios(void)
101 {
102     tcsetattr(0, TCSANOW, &orig_termios);
103 }
104
105 bufchain stdout_data, stderr_data;
106
107 void try_output(int is_stderr)
108 {
109     bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
110     int fd = (is_stderr ? 2 : 1);
111     void *senddata;
112     int sendlen, ret;
113
114     if (bufchain_size(chain) == 0)
115         return;
116
117     bufchain_prefix(chain, &senddata, &sendlen);
118     ret = write(fd, senddata, sendlen);
119     if (ret > 0)
120         bufchain_consume(chain, ret);
121     else if (ret < 0) {
122         perror(is_stderr ? "stderr: write" : "stdout: write");
123         exit(1);
124     }
125 }
126
127 int from_backend(void *frontend_handle, int is_stderr, char *data, int len)
128 {
129     int osize, esize;
130
131     assert(len > 0);
132
133     if (is_stderr) {
134         bufchain_add(&stderr_data, data, len);
135         try_output(1);
136     } else {
137         bufchain_add(&stdout_data, data, len);
138         try_output(0);
139     }
140
141     osize = bufchain_size(&stdout_data);
142     esize = bufchain_size(&stderr_data);
143
144     return osize + esize;
145 }
146
147 /*
148  * Short description of parameters.
149  */
150 static void usage(void)
151 {
152     printf("PuTTY Link: command-line connection utility\n");
153     printf("%s\n", ver);
154     printf("Usage: plink [options] [user@]host [command]\n");
155     printf("       (\"host\" can also be a PuTTY saved session name)\n");
156     printf("Options:\n");
157     printf("  -v        show verbose messages\n");
158     printf("  -load sessname  Load settings from saved session\n");
159     printf("  -ssh -telnet -rlogin -raw\n");
160     printf("            force use of a particular protocol (default SSH)\n");
161     printf("  -P port   connect to specified port\n");
162     printf("  -l user   connect with specified username\n");
163     printf("  -m file   read remote command(s) from file\n");
164     printf("  -batch    disable all interactive prompts\n");
165     printf("The following options only apply to SSH connections:\n");
166     printf("  -pw passw login with specified password\n");
167     printf("  -L listen-port:host:port   Forward local port to "
168            "remote address\n");
169     printf("  -R listen-port:host:port   Forward remote port to"
170            " local address\n");
171     printf("  -X -x     enable / disable X11 forwarding\n");
172     printf("  -A -a     enable / disable agent forwarding\n");
173     printf("  -t -T     enable / disable pty allocation\n");
174     printf("  -1 -2     force use of particular protocol version\n");
175     printf("  -C        enable compression\n");
176     printf("  -i key    private key file for authentication\n");
177     exit(1);
178 }
179
180 int main(int argc, char **argv)
181 {
182     int sending;
183     int portnumber = -1;
184     int *sklist;
185     int socket;
186     int i, skcount, sksize, socketstate;
187     int connopen;
188     int exitcode;
189     void *logctx;
190     void *ldisc;
191
192     ssh_get_line = console_get_line;
193
194     sklist = NULL;
195     skcount = sksize = 0;
196     /*
197      * Initialise port and protocol to sensible defaults. (These
198      * will be overridden by more or less anything.)
199      */
200     default_protocol = PROT_SSH;
201     default_port = 22;
202
203     flags = FLAG_STDERR;
204     /*
205      * Process the command line.
206      */
207     do_defaults(NULL, &cfg);
208     default_protocol = cfg.protocol;
209     default_port = cfg.port;
210     {
211         /*
212          * Override the default protocol if PLINK_PROTOCOL is set.
213          */
214         char *p = getenv("PLINK_PROTOCOL");
215         int i;
216         if (p) {
217             for (i = 0; backends[i].backend != NULL; i++) {
218                 if (!strcmp(backends[i].name, p)) {
219                     default_protocol = cfg.protocol = backends[i].protocol;
220                     default_port = cfg.port =
221                         backends[i].backend->default_port;
222                     break;
223                 }
224             }
225         }
226     }
227     while (--argc) {
228         char *p = *++argv;
229         if (*p == '-') {
230             int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1);
231             if (ret == -2) {
232                 fprintf(stderr,
233                         "plink: option \"%s\" requires an argument\n", p);
234             } else if (ret == 2) {
235                 --argc, ++argv;
236             } else if (ret == 1) {
237                 continue;
238             } else if (!strcmp(p, "-batch")) {
239                 console_batch_mode = 1;
240             }
241         } else if (*p) {
242             if (!*cfg.host) {
243                 char *q = p;
244                 /*
245                  * If the hostname starts with "telnet:", set the
246                  * protocol to Telnet and process the string as a
247                  * Telnet URL.
248                  */
249                 if (!strncmp(q, "telnet:", 7)) {
250                     char c;
251
252                     q += 7;
253                     if (q[0] == '/' && q[1] == '/')
254                         q += 2;
255                     cfg.protocol = PROT_TELNET;
256                     p = q;
257                     while (*p && *p != ':' && *p != '/')
258                         p++;
259                     c = *p;
260                     if (*p)
261                         *p++ = '\0';
262                     if (c == ':')
263                         cfg.port = atoi(p);
264                     else
265                         cfg.port = -1;
266                     strncpy(cfg.host, q, sizeof(cfg.host) - 1);
267                     cfg.host[sizeof(cfg.host) - 1] = '\0';
268                 } else {
269                     char *r;
270                     /*
271                      * Before we process the [user@]host string, we
272                      * first check for the presence of a protocol
273                      * prefix (a protocol name followed by ",").
274                      */
275                     r = strchr(p, ',');
276                     if (r) {
277                         int i, j;
278                         for (i = 0; backends[i].backend != NULL; i++) {
279                             j = strlen(backends[i].name);
280                             if (j == r - p &&
281                                 !memcmp(backends[i].name, p, j)) {
282                                 default_protocol = cfg.protocol =
283                                     backends[i].protocol;
284                                 portnumber =
285                                     backends[i].backend->default_port;
286                                 p = r + 1;
287                                 break;
288                             }
289                         }
290                     }
291
292                     /*
293                      * Three cases. Either (a) there's a nonzero
294                      * length string followed by an @, in which
295                      * case that's user and the remainder is host.
296                      * Or (b) there's only one string, not counting
297                      * a potential initial @, and it exists in the
298                      * saved-sessions database. Or (c) only one
299                      * string and it _doesn't_ exist in the
300                      * database.
301                      */
302                     r = strrchr(p, '@');
303                     if (r == p)
304                         p++, r = NULL; /* discount initial @ */
305                     if (r == NULL) {
306                         /*
307                          * One string.
308                          */
309                         Config cfg2;
310                         do_defaults(p, &cfg2);
311                         if (cfg2.host[0] == '\0') {
312                             /* No settings for this host; use defaults */
313                             strncpy(cfg.host, p, sizeof(cfg.host) - 1);
314                             cfg.host[sizeof(cfg.host) - 1] = '\0';
315                             cfg.port = default_port;
316                         } else {
317                             cfg = cfg2;
318                             cfg.remote_cmd_ptr = cfg.remote_cmd;
319                         }
320                     } else {
321                         *r++ = '\0';
322                         strncpy(cfg.username, p, sizeof(cfg.username) - 1);
323                         cfg.username[sizeof(cfg.username) - 1] = '\0';
324                         strncpy(cfg.host, r, sizeof(cfg.host) - 1);
325                         cfg.host[sizeof(cfg.host) - 1] = '\0';
326                         cfg.port = default_port;
327                     }
328                 }
329             } else {
330                 char *command;
331                 int cmdlen, cmdsize;
332                 cmdlen = cmdsize = 0;
333                 command = NULL;
334
335                 while (argc) {
336                     while (*p) {
337                         if (cmdlen >= cmdsize) {
338                             cmdsize = cmdlen + 512;
339                             command = srealloc(command, cmdsize);
340                         }
341                         command[cmdlen++]=*p++;
342                     }
343                     if (cmdlen >= cmdsize) {
344                         cmdsize = cmdlen + 512;
345                         command = srealloc(command, cmdsize);
346                     }
347                     command[cmdlen++]=' '; /* always add trailing space */
348                     if (--argc) p = *++argv;
349                 }
350                 if (cmdlen) command[--cmdlen]='\0';
351                                        /* change trailing blank to NUL */
352                 cfg.remote_cmd_ptr = command;
353                 cfg.remote_cmd_ptr2 = NULL;
354                 cfg.nopty = TRUE;      /* command => no terminal */
355
356                 break;                 /* done with cmdline */
357             }
358         }
359     }
360
361     if (!*cfg.host) {
362         usage();
363     }
364
365     /*
366      * Trim leading whitespace off the hostname if it's there.
367      */
368     {
369         int space = strspn(cfg.host, " \t");
370         memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
371     }
372
373     /* See if host is of the form user@host */
374     if (cfg.host[0] != '\0') {
375         char *atsign = strchr(cfg.host, '@');
376         /* Make sure we're not overflowing the user field */
377         if (atsign) {
378             if (atsign - cfg.host < sizeof cfg.username) {
379                 strncpy(cfg.username, cfg.host, atsign - cfg.host);
380                 cfg.username[atsign - cfg.host] = '\0';
381             }
382             memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
383         }
384     }
385
386     /*
387      * Perform command-line overrides on session configuration.
388      */
389     cmdline_run_saved();
390
391     /*
392      * Trim a colon suffix off the hostname if it's there.
393      */
394     cfg.host[strcspn(cfg.host, ":")] = '\0';
395
396     /*
397      * Remove any remaining whitespace from the hostname.
398      */
399     {
400         int p1 = 0, p2 = 0;
401         while (cfg.host[p2] != '\0') {
402             if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
403                 cfg.host[p1] = cfg.host[p2];
404                 p1++;
405             }
406             p2++;
407         }
408         cfg.host[p1] = '\0';
409     }
410
411     if (!*cfg.remote_cmd_ptr)
412         flags |= FLAG_INTERACTIVE;
413
414     /*
415      * Select protocol. This is farmed out into a table in a
416      * separate file to enable an ssh-free variant.
417      */
418     {
419         int i;
420         back = NULL;
421         for (i = 0; backends[i].backend != NULL; i++)
422             if (backends[i].protocol == cfg.protocol) {
423                 back = backends[i].backend;
424                 break;
425             }
426         if (back == NULL) {
427             fprintf(stderr,
428                     "Internal fault: Unsupported protocol found\n");
429             return 1;
430         }
431     }
432
433     /*
434      * Select port.
435      */
436     if (portnumber != -1)
437         cfg.port = portnumber;
438
439     sk_init();
440
441     /*
442      * Start up the connection.
443      */
444     {
445         char *error;
446         char *realhost;
447         /* nodelay is only useful if stdin is a terminal device */
448         int nodelay = cfg.tcp_nodelay && isatty(0);
449
450         error = back->init(NULL, &backhandle, cfg.host, cfg.port,
451                            &realhost, nodelay);
452         if (error) {
453             fprintf(stderr, "Unable to open connection:\n%s\n", error);
454             return 1;
455         }
456         logctx = log_init(NULL);
457         back->provide_logctx(backhandle, logctx);
458         ldisc = ldisc_create(NULL, back, backhandle, NULL);
459         sfree(realhost);
460     }
461     connopen = 1;
462
463     /*
464      * Set up the initial console mode. We don't care if this call
465      * fails, because we know we aren't necessarily running in a
466      * console.
467      */
468     tcgetattr(0, &orig_termios);
469     atexit(cleanup_termios);
470     ldisc_update(NULL, 1, 1);
471     sending = FALSE;
472
473     while (1) {
474         fd_set rset, wset, xset;
475         int maxfd;
476         int rwx;
477         int ret;
478
479         FD_ZERO(&rset);
480         FD_ZERO(&wset);
481         FD_ZERO(&xset);
482         maxfd = 0;
483
484         if (connopen && !sending &&
485             back->socket(backhandle) != NULL &&
486             back->sendok(backhandle) &&
487             back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
488             /* If we're OK to send, then try to read from stdin. */
489             FD_SET_MAX(0, maxfd, rset);
490         }
491
492         if (bufchain_size(&stdout_data) > 0) {
493             /* If we have data for stdout, try to write to stdout. */
494             FD_SET_MAX(1, maxfd, wset);
495         }
496
497         if (bufchain_size(&stderr_data) > 0) {
498             /* If we have data for stderr, try to write to stderr. */
499             FD_SET_MAX(2, maxfd, wset);
500         }
501
502         /* Count the currently active sockets. */
503         i = 0;
504         for (socket = first_socket(&socketstate, &rwx); socket >= 0;
505              socket = next_socket(&socketstate, &rwx)) i++;
506
507         /* Expand the sklist buffer if necessary. */
508         if (i > sksize) {
509             sksize = i + 16;
510             sklist = srealloc(sklist, sksize * sizeof(*sklist));
511         }
512
513         /*
514          * Add all currently open sockets to the select sets, and
515          * store them in sklist as well.
516          */
517         skcount = 0;
518         for (socket = first_socket(&socketstate, &rwx); socket >= 0;
519              socket = next_socket(&socketstate, &rwx)) {
520             sklist[skcount++] = socket;
521             if (rwx & 1)
522                 FD_SET_MAX(socket, maxfd, rset);
523             if (rwx & 2)
524                 FD_SET_MAX(socket, maxfd, wset);
525             if (rwx & 4)
526                 FD_SET_MAX(socket, maxfd, xset);
527         }
528
529         ret = select(maxfd, &rset, &wset, &xset, NULL);
530
531         if (ret < 0) {
532             perror("select");
533             exit(1);
534         }
535
536         for (i = 0; i < skcount; i++) {
537             socket = sklist[i];
538             /*
539              * We must process exceptional notifications before
540              * ordinary readability ones, or we may go straight
541              * past the urgent marker.
542              */
543             if (FD_ISSET(socket, &xset))
544                 select_result(socket, 4);
545             if (FD_ISSET(socket, &rset))
546                 select_result(socket, 1);
547             if (FD_ISSET(socket, &wset))
548                 select_result(socket, 2);
549         }
550
551         if (FD_ISSET(0, &rset)) {
552             char buf[4096];
553             int ret;
554
555             if (connopen && back->socket(backhandle) != NULL) {
556                 ret = read(0, buf, sizeof(buf));
557                 if (ret < 0) {
558                     perror("stdin: read");
559                     exit(1);
560                 } else if (ret == 0) {
561                     back->special(backhandle, TS_EOF);
562                     sending = FALSE;   /* send nothing further after this */
563                 } else {
564                     back->send(backhandle, buf, ret);
565                 }
566             }
567         }
568
569         if (FD_ISSET(1, &wset)) {
570             try_output(0);
571         }
572
573         if (FD_ISSET(2, &wset)) {
574             try_output(1);
575         }
576
577         if ((!connopen || back->socket(backhandle) == NULL) &&
578             bufchain_size(&stdout_data) == 0 &&
579             bufchain_size(&stderr_data) == 0)
580             break;                     /* we closed the connection */
581     }
582     exitcode = back->exitcode(backhandle);
583     if (exitcode < 0) {
584         fprintf(stderr, "Remote process exit code unavailable\n");
585         exitcode = 1;                  /* this is an error condition */
586     }
587     return exitcode;
588 }