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