2 * psftp.c: front end for PSFTP.
12 #define PUTTY_DO_GLOBALS
19 /* ----------------------------------------------------------------------
20 * String handling routines.
26 char *p = smalloc(len + 1);
31 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
32 char *dupcat(char *s1, ...)
41 sn = va_arg(ap, char *);
54 sn = va_arg(ap, char *);
65 /* ----------------------------------------------------------------------
71 /* ----------------------------------------------------------------------
72 * Higher-level helper functions used in commands.
76 * Attempt to canonify a pathname starting from the pwd. If
77 * canonification fails, at least fall back to returning a _valid_
78 * pathname (though it may be ugly, eg /home/simon/../foobar).
80 char *canonify(char *name)
82 char *fullname, *canonname;
85 fullname = dupstr(name);
88 if (pwd[strlen(pwd) - 1] == '/')
92 fullname = dupcat(pwd, slash, name, NULL);
95 canonname = fxp_realpath(fullname);
102 * Attempt number 2. Some FXP_REALPATH implementations
103 * (glibc-based ones, in particular) require the _whole_
104 * path to point to something that exists, whereas others
105 * (BSD-based) only require all but the last component to
106 * exist. So if the first call failed, we should strip off
107 * everything from the last slash onwards and try again,
108 * then put the final component back on.
112 * - if the last component is "/." or "/..", then we don't
113 * bother trying this because there's no way it can work.
115 * - if the thing actually ends with a "/", we remove it
116 * before we start. Except if the string is "/" itself
117 * (although I can't see why we'd have got here if so,
118 * because surely "/" would have worked the first
119 * time?), in which case we don't bother.
121 * - if there's no slash in the string at all, give up in
122 * confusion (we expect at least one because of the way
123 * we constructed the string).
129 i = strlen(fullname);
130 if (i > 2 && fullname[i - 1] == '/')
131 fullname[--i] = '\0'; /* strip trailing / unless at pos 0 */
132 while (i > 0 && fullname[--i] != '/');
135 * Give up on special cases.
137 if (fullname[i] != '/' || /* no slash at all */
138 !strcmp(fullname + i, "/.") || /* ends in /. */
139 !strcmp(fullname + i, "/..") || /* ends in /.. */
140 !strcmp(fullname, "/")) {
145 * Now i points at the slash. Deal with the final special
146 * case i==0 (ie the whole path was "/nonexistentfile").
148 fullname[i] = '\0'; /* separate the string */
150 canonname = fxp_realpath("/");
152 canonname = fxp_realpath(fullname);
156 return fullname; /* even that failed; give up */
159 * We have a canonical name for all but the last path
160 * component. Concatenate the last component and return.
162 returnname = dupcat(canonname,
163 canonname[strlen(canonname) - 1] ==
164 '/' ? "" : "/", fullname + i + 1, NULL);
171 /* ----------------------------------------------------------------------
172 * Actual sftp commands.
174 struct sftp_command {
176 int nwords, wordssize;
177 int (*obey) (struct sftp_command *); /* returns <0 to quit */
180 int sftp_cmd_null(struct sftp_command *cmd)
185 int sftp_cmd_unknown(struct sftp_command *cmd)
187 printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
191 int sftp_cmd_quit(struct sftp_command *cmd)
197 * List a directory. If no arguments are given, list pwd; otherwise
198 * list the directory given in words[1].
200 static int sftp_ls_compare(const void *av, const void *bv)
202 const struct fxp_name *a = (const struct fxp_name *) av;
203 const struct fxp_name *b = (const struct fxp_name *) bv;
204 return strcmp(a->filename, b->filename);
206 int sftp_cmd_ls(struct sftp_command *cmd)
208 struct fxp_handle *dirh;
209 struct fxp_names *names;
210 struct fxp_name *ournames;
211 int nnames, namesize;
220 cdir = canonify(dir);
222 printf("%s: %s\n", dir, fxp_error());
226 printf("Listing directory %s\n", cdir);
228 dirh = fxp_opendir(cdir);
230 printf("Unable to open %s: %s\n", dir, fxp_error());
232 nnames = namesize = 0;
237 names = fxp_readdir(dirh);
239 if (fxp_error_type() == SSH_FX_EOF)
241 printf("Reading directory %s: %s\n", dir, fxp_error());
244 if (names->nnames == 0) {
245 fxp_free_names(names);
249 if (nnames + names->nnames >= namesize) {
250 namesize += names->nnames + 128;
252 srealloc(ournames, namesize * sizeof(*ournames));
255 for (i = 0; i < names->nnames; i++)
256 ournames[nnames++] = names->names[i];
258 names->nnames = 0; /* prevent free_names */
259 fxp_free_names(names);
264 * Now we have our filenames. Sort them by actual file
265 * name, and then output the longname parts.
267 qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
272 for (i = 0; i < nnames; i++)
273 printf("%s\n", ournames[i].longname);
282 * Change directories. We do this by canonifying the new name, then
283 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
285 int sftp_cmd_cd(struct sftp_command *cmd)
287 struct fxp_handle *dirh;
291 dir = dupstr(homedir);
293 dir = canonify(cmd->words[1]);
296 printf("%s: %s\n", dir, fxp_error());
300 dirh = fxp_opendir(dir);
302 printf("Directory %s: %s\n", dir, fxp_error());
311 printf("Remote directory is now %s\n", pwd);
317 * Get a file and save it at the local end.
319 int sftp_cmd_get(struct sftp_command *cmd)
321 struct fxp_handle *fh;
322 char *fname, *outfname;
326 if (cmd->nwords < 2) {
327 printf("get: expects a filename\n");
331 fname = canonify(cmd->words[1]);
333 printf("%s: %s\n", cmd->words[1], fxp_error());
336 outfname = (cmd->nwords == 2 ? cmd->words[1] : cmd->words[2]);
338 fh = fxp_open(fname, SSH_FXF_READ);
340 printf("%s: %s\n", fname, fxp_error());
344 fp = fopen(outfname, "wb");
346 printf("local: unable to open %s\n", outfname);
352 printf("remote:%s => local:%s\n", fname, outfname);
354 offset = uint64_make(0, 0);
357 * FIXME: we can use FXP_FSTAT here to get the file size, and
358 * thus put up a progress bar.
365 len = fxp_read(fh, buffer, offset, sizeof(buffer));
366 if ((len == -1 && fxp_error_type() == SSH_FX_EOF) || len == 0)
369 printf("error while reading: %s\n", fxp_error());
375 wlen = fwrite(buffer, 1, len - wpos, fp);
377 printf("error while writing local file\n");
382 if (wpos < len) /* we had an error */
384 offset = uint64_add32(offset, len);
395 * Send a file and store it at the remote end.
397 int sftp_cmd_put(struct sftp_command *cmd)
399 struct fxp_handle *fh;
400 char *fname, *origoutfname, *outfname;
404 if (cmd->nwords < 2) {
405 printf("put: expects a filename\n");
409 fname = cmd->words[1];
410 origoutfname = (cmd->nwords == 2 ? cmd->words[1] : cmd->words[2]);
411 outfname = canonify(origoutfname);
413 printf("%s: %s\n", origoutfname, fxp_error());
417 fp = fopen(fname, "rb");
419 printf("local: unable to open %s\n", fname);
423 fh = fxp_open(outfname, SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC);
425 printf("%s: %s\n", outfname, fxp_error());
430 printf("local:%s => remote:%s\n", fname, outfname);
432 offset = uint64_make(0, 0);
435 * FIXME: we can use FXP_FSTAT here to get the file size, and
436 * thus put up a progress bar.
442 len = fread(buffer, 1, sizeof(buffer), fp);
444 printf("error while reading local file\n");
446 } else if (len == 0) {
449 if (!fxp_write(fh, buffer, offset, len)) {
450 printf("error while writing: %s\n", fxp_error());
453 offset = uint64_add32(offset, len);
463 static struct sftp_cmd_lookup {
465 int (*obey) (struct sftp_command *);
468 * List of sftp commands. This is binary-searched so it MUST be
472 "bye", sftp_cmd_quit}, {
473 "cd", sftp_cmd_cd}, {
474 "dir", sftp_cmd_ls}, {
475 "exit", sftp_cmd_quit}, {
476 "get", sftp_cmd_get}, {
477 "ls", sftp_cmd_ls}, {
478 "put", sftp_cmd_put}, {
479 "quit", sftp_cmd_quit},};
481 /* ----------------------------------------------------------------------
482 * Command line reading and parsing.
484 struct sftp_command *sftp_getcmd(void)
487 int linelen, linesize;
488 struct sftp_command *cmd;
495 cmd = smalloc(sizeof(struct sftp_command));
501 linesize = linelen = 0;
507 line = srealloc(line, linesize);
508 ret = fgets(line + linelen, linesize - linelen, stdin);
510 if (!ret || (linelen == 0 && line[0] == '\0')) {
511 cmd->obey = sftp_cmd_quit;
513 return cmd; /* eof */
515 len = linelen + strlen(line + linelen);
517 if (line[linelen - 1] == '\n') {
519 line[linelen] = '\0';
525 * Parse the command line into words. The syntax is:
526 * - double quotes are removed, but cause spaces within to be
527 * treated as non-separating.
528 * - a double-doublequote pair is a literal double quote, inside
529 * _or_ outside quotes. Like this:
531 * firstword "second word" "this has ""quotes"" in" sodoes""this""
537 * >this has "quotes" in<
542 /* skip whitespace */
543 while (*p && (*p == ' ' || *p == '\t'))
545 /* mark start of word */
546 q = r = p; /* q sits at start, r writes word */
549 if (!quoting && (*p == ' ' || *p == '\t'))
550 break; /* reached end of word */
551 else if (*p == '"' && p[1] == '"')
552 p += 2, *r++ = '"'; /* a literal quote */
554 p++, quoting = !quoting;
559 p++; /* skip over the whitespace */
561 if (cmd->nwords >= cmd->wordssize) {
562 cmd->wordssize = cmd->nwords + 16;
564 srealloc(cmd->words, cmd->wordssize * sizeof(char *));
566 cmd->words[cmd->nwords++] = q;
570 * Now parse the first word and assign a function.
573 if (cmd->nwords == 0)
574 cmd->obey = sftp_cmd_null;
578 cmd->obey = sftp_cmd_unknown;
581 j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
584 cmp = strcmp(cmd->words[0], sftp_lookup[k].name);
590 cmd->obey = sftp_lookup[k].obey;
602 * Do protocol initialisation.
606 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
611 * Find out where our home directory is.
613 homedir = fxp_realpath(".");
616 "Warning: failed to resolve home directory: %s\n",
618 homedir = dupstr(".");
620 printf("Remote working directory is %s\n", homedir);
622 pwd = dupstr(homedir);
624 /* ------------------------------------------------------------------
625 * Now we're ready to do Real Stuff.
628 struct sftp_command *cmd;
632 if (cmd->obey(cmd) < 0)
637 /* ----------------------------------------------------------------------
638 * Dirty bits: integration with PuTTY.
641 static int verbose = 0;
643 void verify_ssh_host_key(char *host, int port, char *keytype,
644 char *keystr, char *fingerprint)
650 static const char absentmsg[] =
651 "The server's host key is not cached in the registry. You\n"
652 "have no guarantee that the server is the computer you\n"
654 "The server's key fingerprint is:\n"
656 "If you trust this host, enter \"y\" to add the key to\n"
657 "PuTTY's cache and carry on connecting.\n"
658 "If you want to carry on connecting just once, without\n"
659 "adding the key to the cache, enter \"n\".\n"
660 "If you do not trust this host, press Return to abandon the\n"
662 "Store key in cache? (y/n) ";
664 static const char wrongmsg[] =
665 "WARNING - POTENTIAL SECURITY BREACH!\n"
666 "The server's host key does not match the one PuTTY has\n"
667 "cached in the registry. This means that either the\n"
668 "server administrator has changed the host key, or you\n"
669 "have actually connected to another computer pretending\n"
670 "to be the server.\n"
671 "The new key fingerprint is:\n"
673 "If you were expecting this change and trust the new key,\n"
674 "enter \"y\" to update PuTTY's cache and continue connecting.\n"
675 "If you want to carry on connecting but without updating\n"
676 "the cache, enter \"n\".\n"
677 "If you want to abandon the connection completely, press\n"
678 "Return to cancel. Pressing Return is the ONLY guaranteed\n"
680 "Update cached key? (y/n, Return cancels connection) ";
682 static const char abandoned[] = "Connection abandoned.\n";
687 * Verify the key against the registry.
689 ret = verify_host_key(host, port, keytype, keystr);
691 if (ret == 0) /* success - key matched OK */
694 if (ret == 2) { /* key was different */
695 fprintf(stderr, wrongmsg, fingerprint);
698 if (ret == 1) { /* key was absent */
699 fprintf(stderr, absentmsg, fingerprint);
703 hin = GetStdHandle(STD_INPUT_HANDLE);
704 GetConsoleMode(hin, &savemode);
705 SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
706 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
707 ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
708 SetConsoleMode(hin, savemode);
710 if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') {
711 if (line[0] == 'y' || line[0] == 'Y')
712 store_host_key(host, port, keytype, keystr);
714 fprintf(stderr, abandoned);
720 * Print an error message and perform a fatal exit.
722 void fatalbox(char *fmt, ...)
724 char str[0x100]; /* Make the size big enough */
727 strcpy(str, "Fatal:");
728 vsprintf(str + strlen(str), fmt, ap);
731 fprintf(stderr, str);
735 void connection_fatal(char *fmt, ...)
737 char str[0x100]; /* Make the size big enough */
740 strcpy(str, "Fatal:");
741 vsprintf(str + strlen(str), fmt, ap);
744 fprintf(stderr, str);
749 void logevent(char *string)
753 void ldisc_send(char *buf, int len)
756 * This is only here because of the calls to ldisc_send(NULL,
757 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
758 * ldisc as an ldisc. So if we get called with any real data, I
759 * want to know about it.
765 * Be told what socket we're supposed to be using.
767 static SOCKET sftp_ssh_socket;
768 char *do_select(SOCKET skt, int startup)
771 sftp_ssh_socket = skt;
773 sftp_ssh_socket = INVALID_SOCKET;
776 extern int select_result(WPARAM, LPARAM);
779 * Receive a block of data from the SSH link. Block until all data
782 * To do this, we repeatedly call the SSH protocol module, with our
783 * own trap in from_backend() to catch the data that comes back. We
784 * do this until we have enough data.
787 static unsigned char *outptr; /* where to put the data */
788 static unsigned outlen; /* how much data required */
789 static unsigned char *pending = NULL; /* any spare data */
790 static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
791 void from_backend(int is_stderr, char *data, int datalen)
793 unsigned char *p = (unsigned char *) data;
794 unsigned len = (unsigned) datalen;
797 * stderr data is just spouted to local stderr and otherwise
801 fwrite(data, 1, len, stderr);
806 * If this is before the real session begins, just return.
812 unsigned used = outlen;
815 memcpy(outptr, p, used);
823 if (pendsize < pendlen + len) {
824 pendsize = pendlen + len + 4096;
825 pending = (pending ? srealloc(pending, pendsize) :
828 fatalbox("Out of memory");
830 memcpy(pending + pendlen, p, len);
834 int sftp_recvdata(char *buf, int len)
836 outptr = (unsigned char *) buf;
840 * See if the pending-input block contains some of what we
844 unsigned pendused = pendlen;
845 if (pendused > outlen)
847 memcpy(outptr, pending, pendused);
848 memmove(pending, pending + pendused, pendlen - pendused);
865 FD_SET(sftp_ssh_socket, &readfds);
866 if (select(1, &readfds, NULL, NULL, NULL) < 0)
868 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
873 int sftp_senddata(char *buf, int len)
875 back->send((unsigned char *) buf, len);
880 * Loop through the ssh connection and authentication process.
882 static void ssh_sftp_init(void)
884 if (sftp_ssh_socket == INVALID_SOCKET)
886 while (!back->sendok()) {
889 FD_SET(sftp_ssh_socket, &readfds);
890 if (select(1, &readfds, NULL, NULL, NULL) < 0)
892 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
896 static char *password = NULL;
897 static int get_line(const char *prompt, char *str, int maxlen, int is_pw)
900 DWORD savemode, newmode, i;
903 static int tried_once = 0;
908 strncpy(str, password, maxlen);
909 str[maxlen - 1] = '\0';
915 hin = GetStdHandle(STD_INPUT_HANDLE);
916 hout = GetStdHandle(STD_OUTPUT_HANDLE);
917 if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE) {
918 fprintf(stderr, "Cannot get standard input/output handles\n");
922 GetConsoleMode(hin, &savemode);
923 newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
925 newmode &= ~ENABLE_ECHO_INPUT;
927 newmode |= ENABLE_ECHO_INPUT;
928 SetConsoleMode(hin, newmode);
930 WriteFile(hout, prompt, strlen(prompt), &i, NULL);
931 ReadFile(hin, str, maxlen - 1, &i, NULL);
933 SetConsoleMode(hin, savemode);
935 if ((int) i > maxlen)
942 WriteFile(hout, "\r\n", 2, &i, NULL);
948 * Initialize the Win$ock driver.
950 static void init_winsock(void)
955 winsock_ver = MAKEWORD(1, 1);
956 if (WSAStartup(winsock_ver, &wsadata)) {
957 fprintf(stderr, "Unable to initialise WinSock");
960 if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1) {
961 fprintf(stderr, "WinSock version is incompatible with 1.1");
967 * Short description of parameters.
969 static void usage(void)
971 printf("PuTTY Secure File Transfer (SFTP) client\n");
973 printf("Usage: psftp [options] user@host\n");
974 printf("Options:\n");
975 printf(" -v show verbose messages\n");
976 printf(" -P port connect to specified port\n");
977 printf(" -pw passw login with specified password\n");
982 * Main program. Parse arguments etc.
984 int main(int argc, char *argv[])
988 char *user, *host, *userhost, *realhost;
992 ssh_get_line = &get_line;
996 userhost = user = NULL;
998 for (i = 1; i < argc; i++) {
999 if (argv[i][0] != '-') {
1003 userhost = dupstr(argv[i]);
1004 } else if (strcmp(argv[i], "-v") == 0) {
1005 verbose = 1, flags |= FLAG_VERBOSE;
1006 } else if (strcmp(argv[i], "-h") == 0 ||
1007 strcmp(argv[i], "-?") == 0) {
1009 } else if (strcmp(argv[i], "-l") == 0 && i + 1 < argc) {
1011 } else if (strcmp(argv[i], "-P") == 0 && i + 1 < argc) {
1012 portnumber = atoi(argv[++i]);
1013 } else if (strcmp(argv[i], "-pw") == 0 && i + 1 < argc) {
1014 password = argv[++i];
1015 } else if (strcmp(argv[i], "--") == 0) {
1026 if (argc > 0 || !userhost)
1029 /* Separate host and username */
1031 host = strrchr(host, '@');
1037 printf("psftp: multiple usernames specified; using \"%s\"\n",
1043 /* Try to load settings for this host */
1044 do_defaults(host, &cfg);
1045 if (cfg.host[0] == '\0') {
1046 /* No settings for this host; use defaults */
1047 do_defaults(NULL, &cfg);
1048 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
1049 cfg.host[sizeof(cfg.host) - 1] = '\0';
1054 if (user != NULL && user[0] != '\0') {
1055 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
1056 cfg.username[sizeof(cfg.username) - 1] = '\0';
1058 if (!cfg.username[0]) {
1059 printf("login as: ");
1060 if (!fgets(cfg.username, sizeof(cfg.username), stdin)) {
1061 fprintf(stderr, "psftp: aborting\n");
1064 int len = strlen(cfg.username);
1065 if (cfg.username[len - 1] == '\n')
1066 cfg.username[len - 1] = '\0';
1070 if (cfg.protocol != PROT_SSH)
1074 cfg.port = portnumber;
1076 /* SFTP uses SSH2 by default always */
1079 /* Set up subsystem name. FIXME: fudge for SSH1. */
1080 strcpy(cfg.remote_cmd, "sftp");
1081 cfg.ssh_subsys = TRUE;
1084 back = &ssh_backend;
1086 err = back->init(cfg.host, cfg.port, &realhost);
1088 fprintf(stderr, "ssh_init: %s", err);
1092 if (verbose && realhost != NULL)
1093 printf("Connected to %s\n", realhost);
1097 if (back != NULL && back->socket() != NULL) {
1099 back->special(TS_EOF);
1100 sftp_recvdata(&ch, 1);