2 * psftp.c: front end for PSFTP.
13 #define PUTTY_DO_GLOBALS
21 * Since SFTP is a request-response oriented protocol, it requires
22 * no buffer management: when we send data, we stop and wait for an
23 * acknowledgement _anyway_, and so we can't possibly overfill our
27 static int psftp_connect(char *userhost
, char *user
, int portnumber
);
28 static int do_sftp_init(void);
30 /* ----------------------------------------------------------------------
36 static void *backhandle
;
39 /* ----------------------------------------------------------------------
40 * Higher-level helper functions used in commands.
44 * Attempt to canonify a pathname starting from the pwd. If
45 * canonification fails, at least fall back to returning a _valid_
46 * pathname (though it may be ugly, eg /home/simon/../foobar).
48 char *canonify(char *name
)
50 char *fullname
, *canonname
;
53 fullname
= dupstr(name
);
56 if (pwd
[strlen(pwd
) - 1] == '/')
60 fullname
= dupcat(pwd
, slash
, name
, NULL
);
63 canonname
= fxp_realpath(fullname
);
70 * Attempt number 2. Some FXP_REALPATH implementations
71 * (glibc-based ones, in particular) require the _whole_
72 * path to point to something that exists, whereas others
73 * (BSD-based) only require all but the last component to
74 * exist. So if the first call failed, we should strip off
75 * everything from the last slash onwards and try again,
76 * then put the final component back on.
80 * - if the last component is "/." or "/..", then we don't
81 * bother trying this because there's no way it can work.
83 * - if the thing actually ends with a "/", we remove it
84 * before we start. Except if the string is "/" itself
85 * (although I can't see why we'd have got here if so,
86 * because surely "/" would have worked the first
87 * time?), in which case we don't bother.
89 * - if there's no slash in the string at all, give up in
90 * confusion (we expect at least one because of the way
91 * we constructed the string).
98 if (i
> 2 && fullname
[i
- 1] == '/')
99 fullname
[--i
] = '\0'; /* strip trailing / unless at pos 0 */
100 while (i
> 0 && fullname
[--i
] != '/');
103 * Give up on special cases.
105 if (fullname
[i
] != '/' || /* no slash at all */
106 !strcmp(fullname
+ i
, "/.") || /* ends in /. */
107 !strcmp(fullname
+ i
, "/..") || /* ends in /.. */
108 !strcmp(fullname
, "/")) {
113 * Now i points at the slash. Deal with the final special
114 * case i==0 (ie the whole path was "/nonexistentfile").
116 fullname
[i
] = '\0'; /* separate the string */
118 canonname
= fxp_realpath("/");
120 canonname
= fxp_realpath(fullname
);
124 return fullname
; /* even that failed; give up */
127 * We have a canonical name for all but the last path
128 * component. Concatenate the last component and return.
130 returnname
= dupcat(canonname
,
131 canonname
[strlen(canonname
) - 1] ==
132 '/' ?
"" : "/", fullname
+ i
+ 1, NULL
);
140 * Return a pointer to the portion of str that comes after the last
141 * slash (or backslash or colon, if `local' is TRUE).
143 static char *stripslashes(char *str
, int local
)
148 p
= strchr(str
, ':');
152 p
= strrchr(str
, '/');
156 p
= strrchr(str
, '\\');
163 /* ----------------------------------------------------------------------
164 * Actual sftp commands.
166 struct sftp_command
{
168 int nwords
, wordssize
;
169 int (*obey
) (struct sftp_command
*); /* returns <0 to quit */
172 int sftp_cmd_null(struct sftp_command
*cmd
)
174 return 1; /* success */
177 int sftp_cmd_unknown(struct sftp_command
*cmd
)
179 printf("psftp: unknown command \"%s\"\n", cmd
->words
[0]);
180 return 0; /* failure */
183 int sftp_cmd_quit(struct sftp_command
*cmd
)
189 * List a directory. If no arguments are given, list pwd; otherwise
190 * list the directory given in words[1].
192 static int sftp_ls_compare(const void *av
, const void *bv
)
194 const struct fxp_name
*const *a
= (const struct fxp_name
*const *) av
;
195 const struct fxp_name
*const *b
= (const struct fxp_name
*const *) bv
;
196 return strcmp((*a
)->filename
, (*b
)->filename
);
198 int sftp_cmd_ls(struct sftp_command
*cmd
)
200 struct fxp_handle
*dirh
;
201 struct fxp_names
*names
;
202 struct fxp_name
**ournames
;
203 int nnames
, namesize
;
208 printf("psftp: not connected to a host; use \"open host.name\"\n");
217 cdir
= canonify(dir
);
219 printf("%s: %s\n", dir
, fxp_error());
223 printf("Listing directory %s\n", cdir
);
225 dirh
= fxp_opendir(cdir
);
227 printf("Unable to open %s: %s\n", dir
, fxp_error());
229 nnames
= namesize
= 0;
234 names
= fxp_readdir(dirh
);
236 if (fxp_error_type() == SSH_FX_EOF
)
238 printf("Reading directory %s: %s\n", dir
, fxp_error());
241 if (names
->nnames
== 0) {
242 fxp_free_names(names
);
246 if (nnames
+ names
->nnames
>= namesize
) {
247 namesize
+= names
->nnames
+ 128;
249 srealloc(ournames
, namesize
* sizeof(*ournames
));
252 for (i
= 0; i
< names
->nnames
; i
++)
253 ournames
[nnames
++] = fxp_dup_name(&names
->names
[i
]);
255 fxp_free_names(names
);
260 * Now we have our filenames. Sort them by actual file
261 * name, and then output the longname parts.
263 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
268 for (i
= 0; i
< nnames
; i
++) {
269 printf("%s\n", ournames
[i
]->longname
);
270 fxp_free_name(ournames
[i
]);
281 * Change directories. We do this by canonifying the new name, then
282 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
284 int sftp_cmd_cd(struct sftp_command
*cmd
)
286 struct fxp_handle
*dirh
;
290 printf("psftp: not connected to a host; use \"open host.name\"\n");
295 dir
= dupstr(homedir
);
297 dir
= canonify(cmd
->words
[1]);
300 printf("%s: %s\n", dir
, fxp_error());
304 dirh
= fxp_opendir(dir
);
306 printf("Directory %s: %s\n", dir
, fxp_error());
315 printf("Remote directory is now %s\n", pwd
);
321 * Print current directory. Easy as pie.
323 int sftp_cmd_pwd(struct sftp_command
*cmd
)
326 printf("psftp: not connected to a host; use \"open host.name\"\n");
330 printf("Remote directory is %s\n", pwd
);
335 * Get a file and save it at the local end. We have two very
336 * similar commands here: `get' and `reget', which differ in that
337 * `reget' checks for the existence of the destination file and
338 * starts from where a previous aborted transfer left off.
340 int sftp_general_get(struct sftp_command
*cmd
, int restart
)
342 struct fxp_handle
*fh
;
343 char *fname
, *outfname
;
349 printf("psftp: not connected to a host; use \"open host.name\"\n");
353 if (cmd
->nwords
< 2) {
354 printf("get: expects a filename\n");
358 fname
= canonify(cmd
->words
[1]);
360 printf("%s: %s\n", cmd
->words
[1], fxp_error());
363 outfname
= (cmd
->nwords
== 2 ?
364 stripslashes(cmd
->words
[1], 0) : cmd
->words
[2]);
366 fh
= fxp_open(fname
, SSH_FXF_READ
);
368 printf("%s: %s\n", fname
, fxp_error());
374 fp
= fopen(outfname
, "rb+");
376 fp
= fopen(outfname
, "wb");
380 printf("local: unable to open %s\n", outfname
);
388 fseek(fp
, 0L, SEEK_END
);
390 printf("reget: restarting at file position %ld\n", posn
);
391 offset
= uint64_make(0, posn
);
393 offset
= uint64_make(0, 0);
396 printf("remote:%s => local:%s\n", fname
, outfname
);
399 * FIXME: we can use FXP_FSTAT here to get the file size, and
400 * thus put up a progress bar.
408 len
= fxp_read(fh
, buffer
, offset
, sizeof(buffer
));
409 if ((len
== -1 && fxp_error_type() == SSH_FX_EOF
) || len
== 0)
412 printf("error while reading: %s\n", fxp_error());
419 wlen
= fwrite(buffer
, 1, len
- wpos
, fp
);
421 printf("error while writing local file\n");
427 if (wpos
< len
) { /* we had an error */
431 offset
= uint64_add32(offset
, len
);
440 int sftp_cmd_get(struct sftp_command
*cmd
)
442 return sftp_general_get(cmd
, 0);
444 int sftp_cmd_reget(struct sftp_command
*cmd
)
446 return sftp_general_get(cmd
, 1);
450 * Send a file and store it at the remote end. We have two very
451 * similar commands here: `put' and `reput', which differ in that
452 * `reput' checks for the existence of the destination file and
453 * starts from where a previous aborted transfer left off.
455 int sftp_general_put(struct sftp_command
*cmd
, int restart
)
457 struct fxp_handle
*fh
;
458 char *fname
, *origoutfname
, *outfname
;
464 printf("psftp: not connected to a host; use \"open host.name\"\n");
468 if (cmd
->nwords
< 2) {
469 printf("put: expects a filename\n");
473 fname
= cmd
->words
[1];
474 origoutfname
= (cmd
->nwords
== 2 ?
475 stripslashes(cmd
->words
[1], 1) : cmd
->words
[2]);
476 outfname
= canonify(origoutfname
);
478 printf("%s: %s\n", origoutfname
, fxp_error());
482 fp
= fopen(fname
, "rb");
484 printf("local: unable to open %s\n", fname
);
489 fh
= fxp_open(outfname
,
492 fh
= fxp_open(outfname
,
493 SSH_FXF_WRITE
| SSH_FXF_CREAT
| SSH_FXF_TRUNC
);
496 printf("%s: %s\n", outfname
, fxp_error());
503 struct fxp_attrs attrs
;
504 if (!fxp_fstat(fh
, &attrs
)) {
505 printf("read size of %s: %s\n", outfname
, fxp_error());
509 if (!(attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
)) {
510 printf("read size of %s: size was not given\n", outfname
);
515 uint64_decimal(offset
, decbuf
);
516 printf("reput: restarting at file position %s\n", decbuf
);
517 if (uint64_compare(offset
, uint64_make(0, LONG_MAX
)) > 0) {
518 printf("reput: remote file is larger than we can deal with\n");
522 if (fseek(fp
, offset
.lo
, SEEK_SET
) != 0)
523 fseek(fp
, 0, SEEK_END
); /* *shrug* */
525 offset
= uint64_make(0, 0);
528 printf("local:%s => remote:%s\n", fname
, outfname
);
531 * FIXME: we can use FXP_FSTAT here to get the file size, and
532 * thus put up a progress bar.
539 len
= fread(buffer
, 1, sizeof(buffer
), fp
);
541 printf("error while reading local file\n");
544 } else if (len
== 0) {
547 if (!fxp_write(fh
, buffer
, offset
, len
)) {
548 printf("error while writing: %s\n", fxp_error());
552 offset
= uint64_add32(offset
, len
);
561 int sftp_cmd_put(struct sftp_command
*cmd
)
563 return sftp_general_put(cmd
, 0);
565 int sftp_cmd_reput(struct sftp_command
*cmd
)
567 return sftp_general_put(cmd
, 1);
570 int sftp_cmd_mkdir(struct sftp_command
*cmd
)
576 printf("psftp: not connected to a host; use \"open host.name\"\n");
580 if (cmd
->nwords
< 2) {
581 printf("mkdir: expects a directory\n");
585 dir
= canonify(cmd
->words
[1]);
587 printf("%s: %s\n", dir
, fxp_error());
591 result
= fxp_mkdir(dir
);
593 printf("mkdir %s: %s\n", dir
, fxp_error());
602 int sftp_cmd_rmdir(struct sftp_command
*cmd
)
608 printf("psftp: not connected to a host; use \"open host.name\"\n");
612 if (cmd
->nwords
< 2) {
613 printf("rmdir: expects a directory\n");
617 dir
= canonify(cmd
->words
[1]);
619 printf("%s: %s\n", dir
, fxp_error());
623 result
= fxp_rmdir(dir
);
625 printf("rmdir %s: %s\n", dir
, fxp_error());
634 int sftp_cmd_rm(struct sftp_command
*cmd
)
640 printf("psftp: not connected to a host; use \"open host.name\"\n");
644 if (cmd
->nwords
< 2) {
645 printf("rm: expects a filename\n");
649 fname
= canonify(cmd
->words
[1]);
651 printf("%s: %s\n", fname
, fxp_error());
655 result
= fxp_remove(fname
);
657 printf("rm %s: %s\n", fname
, fxp_error());
666 int sftp_cmd_mv(struct sftp_command
*cmd
)
668 char *srcfname
, *dstfname
;
672 printf("psftp: not connected to a host; use \"open host.name\"\n");
676 if (cmd
->nwords
< 3) {
677 printf("mv: expects two filenames\n");
680 srcfname
= canonify(cmd
->words
[1]);
682 printf("%s: %s\n", srcfname
, fxp_error());
686 dstfname
= canonify(cmd
->words
[2]);
688 printf("%s: %s\n", dstfname
, fxp_error());
692 result
= fxp_rename(srcfname
, dstfname
);
694 char const *error
= fxp_error();
695 struct fxp_attrs attrs
;
698 * The move might have failed because dstfname pointed at a
699 * directory. We check this possibility now: if dstfname
700 * _is_ a directory, we re-attempt the move by appending
701 * the basename of srcfname to dstfname.
703 result
= fxp_stat(dstfname
, &attrs
);
705 (attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) &&
706 (attrs
.permissions
& 0040000)) {
708 char *newname
, *newcanon
;
709 printf("(destination %s is a directory)\n", dstfname
);
710 p
= srcfname
+ strlen(srcfname
);
711 while (p
> srcfname
&& p
[-1] != '/') p
--;
712 newname
= dupcat(dstfname
, "/", p
, NULL
);
713 newcanon
= canonify(newname
);
718 result
= fxp_rename(srcfname
, dstfname
);
719 error
= result ? NULL
: fxp_error();
723 printf("mv %s %s: %s\n", srcfname
, dstfname
, error
);
729 printf("%s -> %s\n", srcfname
, dstfname
);
736 int sftp_cmd_chmod(struct sftp_command
*cmd
)
740 struct fxp_attrs attrs
;
741 unsigned attrs_clr
, attrs_xor
, oldperms
, newperms
;
744 printf("psftp: not connected to a host; use \"open host.name\"\n");
748 if (cmd
->nwords
< 3) {
749 printf("chmod: expects a mode specifier and a filename\n");
754 * Attempt to parse the mode specifier in cmd->words[1]. We
755 * don't support the full horror of Unix chmod; instead we
756 * support a much simpler syntax in which the user can either
757 * specify an octal number, or a comma-separated sequence of
758 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
759 * _only_ be omitted if the only attribute mentioned is t,
760 * since all others require a user/group/other specification.
761 * Additionally, the s attribute may not be specified for any
762 * [ugoa] specifications other than exactly u or exactly g.
764 attrs_clr
= attrs_xor
= 0;
765 mode
= cmd
->words
[1];
766 if (mode
[0] >= '0' && mode
[0] <= '9') {
767 if (mode
[strspn(mode
, "01234567")]) {
768 printf("chmod: numeric file modes should"
769 " contain digits 0-7 only\n");
773 sscanf(mode
, "%o", &attrs_xor
);
774 attrs_xor
&= attrs_clr
;
777 char *modebegin
= mode
;
778 unsigned subset
, perms
;
782 while (*mode
&& *mode
!= ',' &&
783 *mode
!= '+' && *mode
!= '-' && *mode
!= '=') {
785 case 'u': subset
|= 04700; break; /* setuid, user perms */
786 case 'g': subset
|= 02070; break; /* setgid, group perms */
787 case 'o': subset
|= 00007; break; /* just other perms */
788 case 'a': subset
|= 06777; break; /* all of the above */
790 printf("chmod: file mode '%.*s' contains unrecognised"
791 " user/group/other specifier '%c'\n",
792 strcspn(modebegin
, ","), modebegin
, *mode
);
797 if (!*mode
|| *mode
== ',') {
798 printf("chmod: file mode '%.*s' is incomplete\n",
799 strcspn(modebegin
, ","), modebegin
);
803 if (!*mode
|| *mode
== ',') {
804 printf("chmod: file mode '%.*s' is incomplete\n",
805 strcspn(modebegin
, ","), modebegin
);
809 while (*mode
&& *mode
!= ',') {
811 case 'r': perms
|= 00444; break;
812 case 'w': perms
|= 00222; break;
813 case 'x': perms
|= 00111; break;
814 case 't': perms
|= 01000; subset
|= 01000; break;
816 if ((subset
& 06777) != 04700 &&
817 (subset
& 06777) != 02070) {
818 printf("chmod: file mode '%.*s': set[ug]id bit should"
819 " be used with exactly one of u or g only\n",
820 strcspn(modebegin
, ","), modebegin
);
826 printf("chmod: file mode '%.*s' contains unrecognised"
827 " permission specifier '%c'\n",
828 strcspn(modebegin
, ","), modebegin
, *mode
);
833 if (!(subset
& 06777) && (perms
&~ subset
)) {
834 printf("chmod: file mode '%.*s' contains no user/group/other"
835 " specifier and permissions other than 't' \n",
836 strcspn(modebegin
, ","), modebegin
);
854 if (*mode
) mode
++; /* eat comma */
858 fname
= canonify(cmd
->words
[2]);
860 printf("%s: %s\n", fname
, fxp_error());
864 result
= fxp_stat(fname
, &attrs
);
865 if (!result
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
866 printf("get attrs for %s: %s\n", fname
,
867 result ?
"file permissions not provided" : fxp_error());
872 attrs
.flags
= SSH_FILEXFER_ATTR_PERMISSIONS
; /* perms _only_ */
873 oldperms
= attrs
.permissions
& 07777;
874 attrs
.permissions
&= ~attrs_clr
;
875 attrs
.permissions
^= attrs_xor
;
876 newperms
= attrs
.permissions
& 07777;
878 result
= fxp_setstat(fname
, attrs
);
881 printf("set attrs for %s: %s\n", fname
, fxp_error());
886 printf("%s: %04o -> %04o\n", fname
, oldperms
, newperms
);
892 static int sftp_cmd_open(struct sftp_command
*cmd
)
895 printf("psftp: already connected\n");
899 if (cmd
->nwords
< 2) {
900 printf("open: expects a host name\n");
904 if (psftp_connect(cmd
->words
[1], NULL
, 0)) {
905 back
= NULL
; /* connection is already closed */
906 return -1; /* this is fatal */
912 static int sftp_cmd_lcd(struct sftp_command
*cmd
)
917 if (cmd
->nwords
< 2) {
918 printf("lcd: expects a local directory name\n");
922 if (!SetCurrentDirectory(cmd
->words
[1])) {
925 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
926 FORMAT_MESSAGE_FROM_SYSTEM
|
927 FORMAT_MESSAGE_IGNORE_INSERTS
,
928 NULL
, GetLastError(),
929 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
930 (LPTSTR
)&message
, 0, NULL
);
931 i
= strcspn((char *)message
, "\n");
932 printf("lcd: unable to change directory: %.*s\n", i
, (LPCTSTR
)message
);
937 currdir
= smalloc(256);
938 len
= GetCurrentDirectory(256, currdir
);
940 currdir
= srealloc(currdir
, len
);
941 GetCurrentDirectory(len
, currdir
);
942 printf("New local directory is %s\n", currdir
);
948 static int sftp_cmd_lpwd(struct sftp_command
*cmd
)
953 currdir
= smalloc(256);
954 len
= GetCurrentDirectory(256, currdir
);
956 currdir
= srealloc(currdir
, len
);
957 GetCurrentDirectory(len
, currdir
);
958 printf("Current local directory is %s\n", currdir
);
964 static int sftp_cmd_pling(struct sftp_command
*cmd
)
968 exitcode
= system(cmd
->words
[1]);
969 return (exitcode
== 0);
972 static int sftp_cmd_help(struct sftp_command
*cmd
);
974 static struct sftp_cmd_lookup
{
977 * For help purposes, there are two kinds of command:
979 * - primary commands, in which `longhelp' is non-NULL. In
980 * this case `shorthelp' is descriptive text, and `longhelp'
981 * is longer descriptive text intended to be printed after
984 * - alias commands, in which `longhelp' is NULL. In this case
985 * `shorthelp' is the name of a primary command, which
986 * contains the help that should double up for this command.
988 int listed
; /* do we list this in primary help? */
991 int (*obey
) (struct sftp_command
*);
994 * List of sftp commands. This is binary-searched so it MUST be
998 "!", TRUE
, "run a local Windows command",
1000 " Runs a local Windows command. For example, \"!del myfile\".\n",
1004 "bye", TRUE
, "finish your SFTP session",
1006 " Terminates your SFTP session and quits the PSFTP program.\n",
1010 "cd", TRUE
, "change your remote working directory",
1011 " [ <New working directory> ]\n"
1012 " Change the remote working directory for your SFTP session.\n"
1013 " If a new working directory is not supplied, you will be\n"
1014 " returned to your home directory.\n",
1018 "chmod", TRUE
, "change file permissions and modes",
1019 " ( <octal-digits> | <modifiers> ) <filename>\n"
1020 " Change the file permissions on a file or directory.\n"
1021 " <octal-digits> can be any octal Unix permission specifier.\n"
1022 " Alternatively, <modifiers> can include:\n"
1023 " u+r make file readable by owning user\n"
1024 " u+w make file writable by owning user\n"
1025 " u+x make file executable by owning user\n"
1026 " u-r make file not readable by owning user\n"
1027 " [also u-w, u-x]\n"
1028 " g+r make file readable by members of owning group\n"
1029 " [also g+w, g+x, g-r, g-w, g-x]\n"
1030 " o+r make file readable by all other users\n"
1031 " [also o+w, o+x, o-r, o-w, o-x]\n"
1032 " a+r make file readable by absolutely everybody\n"
1033 " [also a+w, a+x, a-r, a-w, a-x]\n"
1034 " u+s enable the Unix set-user-ID bit\n"
1035 " u-s disable the Unix set-user-ID bit\n"
1036 " g+s enable the Unix set-group-ID bit\n"
1037 " g-s disable the Unix set-group-ID bit\n"
1038 " +t enable the Unix \"sticky bit\"\n"
1039 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1040 " more than one user for the same modifier (\"ug+w\"). You can\n"
1041 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1045 "del", TRUE
, "delete a file",
1047 " Delete a file.\n",
1051 "delete", FALSE
, "del", NULL
, sftp_cmd_rm
1054 "dir", TRUE
, "list contents of a remote directory",
1055 " [ <directory-name> ]\n"
1056 " List the contents of a specified directory on the server.\n"
1057 " If <directory-name> is not given, the current working directory\n"
1058 " will be listed.\n",
1062 "exit", TRUE
, "bye", NULL
, sftp_cmd_quit
1065 "get", TRUE
, "download a file from the server to your local machine",
1066 " <filename> [ <local-filename> ]\n"
1067 " Downloads a file on the server and stores it locally under\n"
1068 " the same name, or under a different one if you supply the\n"
1069 " argument <local-filename>.\n",
1073 "help", TRUE
, "give help",
1074 " [ <command> [ <command> ... ] ]\n"
1075 " Give general help if no commands are specified.\n"
1076 " If one or more commands are specified, give specific help on\n"
1077 " those particular commands.\n",
1081 "lcd", TRUE
, "change local working directory",
1082 " <local-directory-name>\n"
1083 " Change the local working directory of the PSFTP program (the\n"
1084 " default location where the \"get\" command will save files).\n",
1088 "lpwd", TRUE
, "print local working directory",
1090 " Print the local working directory of the PSFTP program (the\n"
1091 " default location where the \"get\" command will save files).\n",
1095 "ls", TRUE
, "dir", NULL
,
1099 "mkdir", TRUE
, "create a directory on the remote server",
1100 " <directory-name>\n"
1101 " Creates a directory with the given name on the server.\n",
1105 "mv", TRUE
, "move or rename a file on the remote server",
1106 " <source-filename> <destination-filename>\n"
1107 " Moves or renames the file <source-filename> on the server,\n"
1108 " so that it is accessible under the name <destination-filename>.\n",
1112 "open", TRUE
, "connect to a host",
1113 " [<user>@]<hostname>\n"
1114 " Establishes an SFTP connection to a given host. Only usable\n"
1115 " when you did not already specify a host name on the command\n"
1120 "put", TRUE
, "upload a file from your local machine to the server",
1121 " <filename> [ <remote-filename> ]\n"
1122 " Uploads a file to the server and stores it there under\n"
1123 " the same name, or under a different one if you supply the\n"
1124 " argument <remote-filename>.\n",
1128 "pwd", TRUE
, "print your remote working directory",
1130 " Print the current remote working directory for your SFTP session.\n",
1134 "quit", TRUE
, "bye", NULL
,
1138 "reget", TRUE
, "continue downloading a file",
1139 " <filename> [ <local-filename> ]\n"
1140 " Works exactly like the \"get\" command, but the local file\n"
1141 " must already exist. The download will begin at the end of the\n"
1142 " file. This is for resuming a download that was interrupted.\n",
1146 "ren", TRUE
, "mv", NULL
,
1150 "rename", FALSE
, "mv", NULL
,
1154 "reput", TRUE
, "continue uploading a file",
1155 " <filename> [ <remote-filename> ]\n"
1156 " Works exactly like the \"put\" command, but the remote file\n"
1157 " must already exist. The upload will begin at the end of the\n"
1158 " file. This is for resuming an upload that was interrupted.\n",
1162 "rm", TRUE
, "del", NULL
,
1166 "rmdir", TRUE
, "remove a directory on the remote server",
1167 " <directory-name>\n"
1168 " Removes the directory with the given name on the server.\n"
1169 " The directory will not be removed unless it is empty.\n",
1174 const struct sftp_cmd_lookup
*lookup_command(char *name
)
1179 j
= sizeof(sftp_lookup
) / sizeof(*sftp_lookup
);
1182 cmp
= strcmp(name
, sftp_lookup
[k
].name
);
1188 return &sftp_lookup
[k
];
1194 static int sftp_cmd_help(struct sftp_command
*cmd
)
1197 if (cmd
->nwords
== 1) {
1199 * Give short help on each command.
1203 for (i
= 0; i
< sizeof(sftp_lookup
) / sizeof(*sftp_lookup
); i
++) {
1205 if (!sftp_lookup
[i
].listed
)
1207 len
= strlen(sftp_lookup
[i
].name
);
1211 for (i
= 0; i
< sizeof(sftp_lookup
) / sizeof(*sftp_lookup
); i
++) {
1212 const struct sftp_cmd_lookup
*lookup
;
1213 if (!sftp_lookup
[i
].listed
)
1215 lookup
= &sftp_lookup
[i
];
1216 printf("%-*s", maxlen
+2, lookup
->name
);
1217 if (lookup
->longhelp
== NULL
)
1218 lookup
= lookup_command(lookup
->shorthelp
);
1219 printf("%s\n", lookup
->shorthelp
);
1223 * Give long help on specific commands.
1225 for (i
= 1; i
< cmd
->nwords
; i
++) {
1226 const struct sftp_cmd_lookup
*lookup
;
1227 lookup
= lookup_command(cmd
->words
[i
]);
1229 printf("help: %s: command not found\n", cmd
->words
[i
]);
1231 printf("%s", lookup
->name
);
1232 if (lookup
->longhelp
== NULL
)
1233 lookup
= lookup_command(lookup
->shorthelp
);
1234 printf("%s", lookup
->longhelp
);
1241 /* ----------------------------------------------------------------------
1242 * Command line reading and parsing.
1244 struct sftp_command
*sftp_getcmd(FILE *fp
, int mode
, int modeflags
)
1247 int linelen
, linesize
;
1248 struct sftp_command
*cmd
;
1252 if ((mode
== 0) || (modeflags
& 1)) {
1257 cmd
= smalloc(sizeof(struct sftp_command
));
1263 linesize
= linelen
= 0;
1269 line
= srealloc(line
, linesize
);
1270 ret
= fgets(line
+ linelen
, linesize
- linelen
, fp
);
1272 if (!ret
|| (linelen
== 0 && line
[0] == '\0')) {
1273 cmd
->obey
= sftp_cmd_quit
;
1274 if ((mode
== 0) || (modeflags
& 1))
1276 return cmd
; /* eof */
1278 len
= linelen
+ strlen(line
+ linelen
);
1280 if (line
[linelen
- 1] == '\n') {
1282 line
[linelen
] = '\0';
1286 if (modeflags
& 1) {
1287 printf("%s\n", line
);
1291 while (*p
&& (*p
== ' ' || *p
== '\t'))
1296 * Special case: the ! command. This is always parsed as
1297 * exactly two words: one containing the !, and the second
1298 * containing everything else on the line.
1300 cmd
->nwords
= cmd
->wordssize
= 2;
1301 cmd
->words
= srealloc(cmd
->words
, cmd
->wordssize
* sizeof(char *));
1302 cmd
->words
[0] = "!";
1303 cmd
->words
[1] = p
+1;
1307 * Parse the command line into words. The syntax is:
1308 * - double quotes are removed, but cause spaces within to be
1309 * treated as non-separating.
1310 * - a double-doublequote pair is a literal double quote, inside
1311 * _or_ outside quotes. Like this:
1313 * firstword "second word" "this has ""quotes"" in" and""this""
1319 * >this has "quotes" in<
1323 /* skip whitespace */
1324 while (*p
&& (*p
== ' ' || *p
== '\t'))
1326 /* mark start of word */
1327 q
= r
= p
; /* q sits at start, r writes word */
1330 if (!quoting
&& (*p
== ' ' || *p
== '\t'))
1331 break; /* reached end of word */
1332 else if (*p
== '"' && p
[1] == '"')
1333 p
+= 2, *r
++ = '"'; /* a literal quote */
1335 p
++, quoting
= !quoting
;
1340 p
++; /* skip over the whitespace */
1342 if (cmd
->nwords
>= cmd
->wordssize
) {
1343 cmd
->wordssize
= cmd
->nwords
+ 16;
1345 srealloc(cmd
->words
, cmd
->wordssize
* sizeof(char *));
1347 cmd
->words
[cmd
->nwords
++] = q
;
1352 * Now parse the first word and assign a function.
1355 if (cmd
->nwords
== 0)
1356 cmd
->obey
= sftp_cmd_null
;
1358 const struct sftp_cmd_lookup
*lookup
;
1359 lookup
= lookup_command(cmd
->words
[0]);
1361 cmd
->obey
= sftp_cmd_unknown
;
1363 cmd
->obey
= lookup
->obey
;
1369 static int do_sftp_init(void)
1372 * Do protocol initialisation.
1376 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
1377 return 1; /* failure */
1381 * Find out where our home directory is.
1383 homedir
= fxp_realpath(".");
1386 "Warning: failed to resolve home directory: %s\n",
1388 homedir
= dupstr(".");
1390 printf("Remote working directory is %s\n", homedir
);
1392 pwd
= dupstr(homedir
);
1396 void do_sftp(int mode
, int modeflags
, char *batchfile
)
1406 /* ------------------------------------------------------------------
1407 * Now we're ready to do Real Stuff.
1410 struct sftp_command
*cmd
;
1411 cmd
= sftp_getcmd(stdin
, 0, 0);
1414 if (cmd
->obey(cmd
) < 0)
1418 fp
= fopen(batchfile
, "r");
1420 printf("Fatal: unable to open %s\n", batchfile
);
1424 struct sftp_command
*cmd
;
1425 cmd
= sftp_getcmd(fp
, mode
, modeflags
);
1428 ret
= cmd
->obey(cmd
);
1432 if (!(modeflags
& 2))
1441 /* ----------------------------------------------------------------------
1442 * Dirty bits: integration with PuTTY.
1445 static int verbose
= 0;
1448 * Print an error message and perform a fatal exit.
1450 void fatalbox(char *fmt
, ...)
1455 str
= dupvprintf(fmt
, ap
);
1456 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1459 fputs(str2
, stderr
);
1464 void modalfatalbox(char *fmt
, ...)
1469 str
= dupvprintf(fmt
, ap
);
1470 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1473 fputs(str2
, stderr
);
1478 void connection_fatal(void *frontend
, char *fmt
, ...)
1483 str
= dupvprintf(fmt
, ap
);
1484 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1487 fputs(str2
, stderr
);
1493 void ldisc_send(void *handle
, char *buf
, int len
, int interactive
)
1496 * This is only here because of the calls to ldisc_send(NULL,
1497 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
1498 * ldisc as an ldisc. So if we get called with any real data, I
1499 * want to know about it.
1505 * Be told what socket we're supposed to be using.
1507 static SOCKET sftp_ssh_socket
;
1508 char *do_select(SOCKET skt
, int startup
)
1511 sftp_ssh_socket
= skt
;
1513 sftp_ssh_socket
= INVALID_SOCKET
;
1516 extern int select_result(WPARAM
, LPARAM
);
1519 * Receive a block of data from the SSH link. Block until all data
1522 * To do this, we repeatedly call the SSH protocol module, with our
1523 * own trap in from_backend() to catch the data that comes back. We
1524 * do this until we have enough data.
1527 static unsigned char *outptr
; /* where to put the data */
1528 static unsigned outlen
; /* how much data required */
1529 static unsigned char *pending
= NULL
; /* any spare data */
1530 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
1531 int from_backend(void *frontend
, int is_stderr
, const char *data
, int datalen
)
1533 unsigned char *p
= (unsigned char *) data
;
1534 unsigned len
= (unsigned) datalen
;
1539 * stderr data is just spouted to local stderr and otherwise
1543 fwrite(data
, 1, len
, stderr
);
1548 * If this is before the real session begins, just return.
1554 unsigned used
= outlen
;
1557 memcpy(outptr
, p
, used
);
1565 if (pendsize
< pendlen
+ len
) {
1566 pendsize
= pendlen
+ len
+ 4096;
1567 pending
= (pending ?
srealloc(pending
, pendsize
) :
1570 fatalbox("Out of memory");
1572 memcpy(pending
+ pendlen
, p
, len
);
1578 int sftp_recvdata(char *buf
, int len
)
1580 outptr
= (unsigned char *) buf
;
1584 * See if the pending-input block contains some of what we
1588 unsigned pendused
= pendlen
;
1589 if (pendused
> outlen
)
1591 memcpy(outptr
, pending
, pendused
);
1592 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
1595 pendlen
-= pendused
;
1605 while (outlen
> 0) {
1609 FD_SET(sftp_ssh_socket
, &readfds
);
1610 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
1611 return 0; /* doom */
1612 select_result((WPARAM
) sftp_ssh_socket
, (LPARAM
) FD_READ
);
1617 int sftp_senddata(char *buf
, int len
)
1619 back
->send(backhandle
, (unsigned char *) buf
, len
);
1624 * Loop through the ssh connection and authentication process.
1626 static void ssh_sftp_init(void)
1628 if (sftp_ssh_socket
== INVALID_SOCKET
)
1630 while (!back
->sendok(backhandle
)) {
1633 FD_SET(sftp_ssh_socket
, &readfds
);
1634 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
1636 select_result((WPARAM
) sftp_ssh_socket
, (LPARAM
) FD_READ
);
1641 * Initialize the Win$ock driver.
1643 static void init_winsock(void)
1648 winsock_ver
= MAKEWORD(1, 1);
1649 if (WSAStartup(winsock_ver
, &wsadata
)) {
1650 fprintf(stderr
, "Unable to initialise WinSock");
1653 if (LOBYTE(wsadata
.wVersion
) != 1 || HIBYTE(wsadata
.wVersion
) != 1) {
1654 fprintf(stderr
, "WinSock version is incompatible with 1.1");
1660 * Short description of parameters.
1662 static void usage(void)
1664 printf("PuTTY Secure File Transfer (SFTP) client\n");
1665 printf("%s\n", ver
);
1666 printf("Usage: psftp [options] user@host\n");
1667 printf("Options:\n");
1668 printf(" -b file use specified batchfile\n");
1669 printf(" -bc output batchfile commands\n");
1670 printf(" -be don't stop batchfile processing if errors\n");
1671 printf(" -v show verbose messages\n");
1672 printf(" -load sessname Load settings from saved session\n");
1673 printf(" -l user connect with specified username\n");
1674 printf(" -P port connect to specified port\n");
1675 printf(" -pw passw login with specified password\n");
1676 printf(" -1 -2 force use of particular SSH protocol version\n");
1677 printf(" -C enable compression\n");
1678 printf(" -i key private key file for authentication\n");
1679 printf(" -batch disable all interactive prompts\n");
1684 * Connect to a host.
1686 static int psftp_connect(char *userhost
, char *user
, int portnumber
)
1688 char *host
, *realhost
;
1691 /* Separate host and username */
1693 host
= strrchr(host
, '@');
1699 printf("psftp: multiple usernames specified; using \"%s\"\n",
1705 /* Try to load settings for this host */
1706 do_defaults(host
, &cfg
);
1707 if (cfg
.host
[0] == '\0') {
1708 /* No settings for this host; use defaults */
1709 do_defaults(NULL
, &cfg
);
1710 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
1711 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
1715 * Force use of SSH. (If they got the protocol wrong we assume the
1716 * port is useless too.)
1718 if (cfg
.protocol
!= PROT_SSH
) {
1719 cfg
.protocol
= PROT_SSH
;
1724 * Enact command-line overrides.
1726 cmdline_run_saved(&cfg
);
1729 * Trim leading whitespace off the hostname if it's there.
1732 int space
= strspn(cfg
.host
, " \t");
1733 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
1736 /* See if host is of the form user@host */
1737 if (cfg
.host
[0] != '\0') {
1738 char *atsign
= strchr(cfg
.host
, '@');
1739 /* Make sure we're not overflowing the user field */
1741 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
1742 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
1743 cfg
.username
[atsign
- cfg
.host
] = '\0';
1745 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
1750 * Trim a colon suffix off the hostname if it's there.
1752 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
1755 * Remove any remaining whitespace from the hostname.
1759 while (cfg
.host
[p2
] != '\0') {
1760 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
1761 cfg
.host
[p1
] = cfg
.host
[p2
];
1766 cfg
.host
[p1
] = '\0';
1770 if (user
!= NULL
&& user
[0] != '\0') {
1771 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
1772 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
1774 if (!cfg
.username
[0]) {
1775 printf("login as: ");
1777 if (!fgets(cfg
.username
, sizeof(cfg
.username
), stdin
)) {
1778 fprintf(stderr
, "psftp: aborting\n");
1781 int len
= strlen(cfg
.username
);
1782 if (cfg
.username
[len
- 1] == '\n')
1783 cfg
.username
[len
- 1] = '\0';
1788 cfg
.port
= portnumber
;
1790 /* SFTP uses SSH2 by default always */
1794 * Disable scary things which shouldn't be enabled for simple
1795 * things like SCP and SFTP: agent forwarding, port forwarding,
1798 cfg
.x11_forward
= 0;
1800 cfg
.portfwd
[0] = cfg
.portfwd
[1] = '\0';
1802 /* Set up subsystem name. */
1803 strcpy(cfg
.remote_cmd
, "sftp");
1804 cfg
.ssh_subsys
= TRUE
;
1808 * Set up fallback option, for SSH1 servers or servers with the
1809 * sftp subsystem not enabled but the server binary installed
1810 * in the usual place. We only support fallback on Unix
1811 * systems, and we use a kludgy piece of shellery which should
1812 * try to find sftp-server in various places (the obvious
1813 * systemwide spots /usr/lib and /usr/local/lib, and then the
1814 * user's PATH) and finally give up.
1816 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
1817 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
1820 * the idea being that this will attempt to use either of the
1821 * obvious pathnames and then give up, and when it does give up
1822 * it will print the preferred pathname in the error messages.
1824 cfg
.remote_cmd_ptr2
=
1825 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
1826 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
1828 cfg
.ssh_subsys2
= FALSE
;
1830 back
= &ssh_backend
;
1832 err
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
, &realhost
,0);
1834 fprintf(stderr
, "ssh_init: %s\n", err
);
1837 logctx
= log_init(NULL
, &cfg
);
1838 back
->provide_logctx(backhandle
, logctx
);
1839 console_provide_logctx(logctx
);
1841 if (verbose
&& realhost
!= NULL
)
1842 printf("Connected to %s\n", realhost
);
1846 void cmdline_error(char *p
, ...)
1849 fprintf(stderr
, "psftp: ");
1851 vfprintf(stderr
, p
, ap
);
1853 fprintf(stderr
, "\n try typing \"psftp -h\" for help\n");
1858 * Main program. Parse arguments etc.
1860 int main(int argc
, char *argv
[])
1864 char *userhost
, *user
;
1867 char *batchfile
= NULL
;
1870 flags
= FLAG_STDERR
| FLAG_INTERACTIVE
;
1871 cmdline_tooltype
= TOOLTYPE_FILETRANSFER
;
1872 ssh_get_line
= &console_get_line
;
1876 userhost
= user
= NULL
;
1879 for (i
= 1; i
< argc
; i
++) {
1881 if (argv
[i
][0] != '-') {
1885 userhost
= dupstr(argv
[i
]);
1888 ret
= cmdline_process_param(argv
[i
], i
+1<argc?argv
[i
+1]:NULL
, 1, &cfg
);
1890 cmdline_error("option \"%s\" requires an argument", argv
[i
]);
1891 } else if (ret
== 2) {
1892 i
++; /* skip next argument */
1893 } else if (ret
== 1) {
1894 /* We have our own verbosity in addition to `flags'. */
1895 if (flags
& FLAG_VERBOSE
)
1897 } else if (strcmp(argv
[i
], "-h") == 0 ||
1898 strcmp(argv
[i
], "-?") == 0) {
1900 } else if (strcmp(argv
[i
], "-batch") == 0) {
1901 console_batch_mode
= 1;
1902 } else if (strcmp(argv
[i
], "-b") == 0 && i
+ 1 < argc
) {
1904 batchfile
= argv
[++i
];
1905 } else if (strcmp(argv
[i
], "-bc") == 0) {
1906 modeflags
= modeflags
| 1;
1907 } else if (strcmp(argv
[i
], "-be") == 0) {
1908 modeflags
= modeflags
| 2;
1909 } else if (strcmp(argv
[i
], "--") == 0) {
1913 cmdline_error("unknown option \"%s\"", argv
[i
]);
1921 * If a user@host string has already been provided, connect to
1925 if (psftp_connect(userhost
, user
, portnumber
))
1930 printf("psftp: no hostname specified; use \"open host.name\""
1934 do_sftp(mode
, modeflags
, batchfile
);
1936 if (back
!= NULL
&& back
->socket(backhandle
) != NULL
) {
1938 back
->special(backhandle
, TS_EOF
);
1939 sftp_recvdata(&ch
, 1);