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 /* ----------------------------------------------------------------------
37 * Higher-level helper functions used in commands.
41 * Attempt to canonify a pathname starting from the pwd. If
42 * canonification fails, at least fall back to returning a _valid_
43 * pathname (though it may be ugly, eg /home/simon/../foobar).
45 char *canonify(char *name
)
47 char *fullname
, *canonname
;
50 fullname
= dupstr(name
);
53 if (pwd
[strlen(pwd
) - 1] == '/')
57 fullname
= dupcat(pwd
, slash
, name
, NULL
);
60 canonname
= fxp_realpath(fullname
);
67 * Attempt number 2. Some FXP_REALPATH implementations
68 * (glibc-based ones, in particular) require the _whole_
69 * path to point to something that exists, whereas others
70 * (BSD-based) only require all but the last component to
71 * exist. So if the first call failed, we should strip off
72 * everything from the last slash onwards and try again,
73 * then put the final component back on.
77 * - if the last component is "/." or "/..", then we don't
78 * bother trying this because there's no way it can work.
80 * - if the thing actually ends with a "/", we remove it
81 * before we start. Except if the string is "/" itself
82 * (although I can't see why we'd have got here if so,
83 * because surely "/" would have worked the first
84 * time?), in which case we don't bother.
86 * - if there's no slash in the string at all, give up in
87 * confusion (we expect at least one because of the way
88 * we constructed the string).
95 if (i
> 2 && fullname
[i
- 1] == '/')
96 fullname
[--i
] = '\0'; /* strip trailing / unless at pos 0 */
97 while (i
> 0 && fullname
[--i
] != '/');
100 * Give up on special cases.
102 if (fullname
[i
] != '/' || /* no slash at all */
103 !strcmp(fullname
+ i
, "/.") || /* ends in /. */
104 !strcmp(fullname
+ i
, "/..") || /* ends in /.. */
105 !strcmp(fullname
, "/")) {
110 * Now i points at the slash. Deal with the final special
111 * case i==0 (ie the whole path was "/nonexistentfile").
113 fullname
[i
] = '\0'; /* separate the string */
115 canonname
= fxp_realpath("/");
117 canonname
= fxp_realpath(fullname
);
121 return fullname
; /* even that failed; give up */
124 * We have a canonical name for all but the last path
125 * component. Concatenate the last component and return.
127 returnname
= dupcat(canonname
,
128 canonname
[strlen(canonname
) - 1] ==
129 '/' ?
"" : "/", fullname
+ i
+ 1, NULL
);
137 * Return a pointer to the portion of str that comes after the last
138 * slash (or backslash or colon, if `local' is TRUE).
140 static char *stripslashes(char *str
, int local
)
145 p
= strchr(str
, ':');
149 p
= strrchr(str
, '/');
153 p
= strrchr(str
, '\\');
160 /* ----------------------------------------------------------------------
161 * Actual sftp commands.
163 struct sftp_command
{
165 int nwords
, wordssize
;
166 int (*obey
) (struct sftp_command
*); /* returns <0 to quit */
169 int sftp_cmd_null(struct sftp_command
*cmd
)
171 return 1; /* success */
174 int sftp_cmd_unknown(struct sftp_command
*cmd
)
176 printf("psftp: unknown command \"%s\"\n", cmd
->words
[0]);
177 return 0; /* failure */
180 int sftp_cmd_quit(struct sftp_command
*cmd
)
186 * List a directory. If no arguments are given, list pwd; otherwise
187 * list the directory given in words[1].
189 static int sftp_ls_compare(const void *av
, const void *bv
)
191 const struct fxp_name
*const *a
= (const struct fxp_name
*const *) av
;
192 const struct fxp_name
*const *b
= (const struct fxp_name
*const *) bv
;
193 return strcmp((*a
)->filename
, (*b
)->filename
);
195 int sftp_cmd_ls(struct sftp_command
*cmd
)
197 struct fxp_handle
*dirh
;
198 struct fxp_names
*names
;
199 struct fxp_name
**ournames
;
200 int nnames
, namesize
;
205 printf("psftp: not connected to a host; use \"open host.name\"\n");
214 cdir
= canonify(dir
);
216 printf("%s: %s\n", dir
, fxp_error());
220 printf("Listing directory %s\n", cdir
);
222 dirh
= fxp_opendir(cdir
);
224 printf("Unable to open %s: %s\n", dir
, fxp_error());
226 nnames
= namesize
= 0;
231 names
= fxp_readdir(dirh
);
233 if (fxp_error_type() == SSH_FX_EOF
)
235 printf("Reading directory %s: %s\n", dir
, fxp_error());
238 if (names
->nnames
== 0) {
239 fxp_free_names(names
);
243 if (nnames
+ names
->nnames
>= namesize
) {
244 namesize
+= names
->nnames
+ 128;
246 srealloc(ournames
, namesize
* sizeof(*ournames
));
249 for (i
= 0; i
< names
->nnames
; i
++)
250 ournames
[nnames
++] = fxp_dup_name(&names
->names
[i
]);
252 fxp_free_names(names
);
257 * Now we have our filenames. Sort them by actual file
258 * name, and then output the longname parts.
260 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
265 for (i
= 0; i
< nnames
; i
++) {
266 printf("%s\n", ournames
[i
]->longname
);
267 fxp_free_name(ournames
[i
]);
278 * Change directories. We do this by canonifying the new name, then
279 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
281 int sftp_cmd_cd(struct sftp_command
*cmd
)
283 struct fxp_handle
*dirh
;
287 printf("psftp: not connected to a host; use \"open host.name\"\n");
292 dir
= dupstr(homedir
);
294 dir
= canonify(cmd
->words
[1]);
297 printf("%s: %s\n", dir
, fxp_error());
301 dirh
= fxp_opendir(dir
);
303 printf("Directory %s: %s\n", dir
, fxp_error());
312 printf("Remote directory is now %s\n", pwd
);
318 * Print current directory. Easy as pie.
320 int sftp_cmd_pwd(struct sftp_command
*cmd
)
323 printf("psftp: not connected to a host; use \"open host.name\"\n");
327 printf("Remote directory is %s\n", pwd
);
332 * Get a file and save it at the local end. We have two very
333 * similar commands here: `get' and `reget', which differ in that
334 * `reget' checks for the existence of the destination file and
335 * starts from where a previous aborted transfer left off.
337 int sftp_general_get(struct sftp_command
*cmd
, int restart
)
339 struct fxp_handle
*fh
;
340 char *fname
, *outfname
;
346 printf("psftp: not connected to a host; use \"open host.name\"\n");
350 if (cmd
->nwords
< 2) {
351 printf("get: expects a filename\n");
355 fname
= canonify(cmd
->words
[1]);
357 printf("%s: %s\n", cmd
->words
[1], fxp_error());
360 outfname
= (cmd
->nwords
== 2 ?
361 stripslashes(cmd
->words
[1], 0) : cmd
->words
[2]);
363 fh
= fxp_open(fname
, SSH_FXF_READ
);
365 printf("%s: %s\n", fname
, fxp_error());
371 fp
= fopen(outfname
, "rb+");
373 fp
= fopen(outfname
, "wb");
377 printf("local: unable to open %s\n", outfname
);
385 fseek(fp
, 0L, SEEK_END
);
387 printf("reget: restarting at file position %ld\n", posn
);
388 offset
= uint64_make(0, posn
);
390 offset
= uint64_make(0, 0);
393 printf("remote:%s => local:%s\n", fname
, outfname
);
396 * FIXME: we can use FXP_FSTAT here to get the file size, and
397 * thus put up a progress bar.
405 len
= fxp_read(fh
, buffer
, offset
, sizeof(buffer
));
406 if ((len
== -1 && fxp_error_type() == SSH_FX_EOF
) || len
== 0)
409 printf("error while reading: %s\n", fxp_error());
416 wlen
= fwrite(buffer
, 1, len
- wpos
, fp
);
418 printf("error while writing local file\n");
424 if (wpos
< len
) { /* we had an error */
428 offset
= uint64_add32(offset
, len
);
437 int sftp_cmd_get(struct sftp_command
*cmd
)
439 return sftp_general_get(cmd
, 0);
441 int sftp_cmd_reget(struct sftp_command
*cmd
)
443 return sftp_general_get(cmd
, 1);
447 * Send a file and store it at the remote end. We have two very
448 * similar commands here: `put' and `reput', which differ in that
449 * `reput' checks for the existence of the destination file and
450 * starts from where a previous aborted transfer left off.
452 int sftp_general_put(struct sftp_command
*cmd
, int restart
)
454 struct fxp_handle
*fh
;
455 char *fname
, *origoutfname
, *outfname
;
461 printf("psftp: not connected to a host; use \"open host.name\"\n");
465 if (cmd
->nwords
< 2) {
466 printf("put: expects a filename\n");
470 fname
= cmd
->words
[1];
471 origoutfname
= (cmd
->nwords
== 2 ?
472 stripslashes(cmd
->words
[1], 1) : cmd
->words
[2]);
473 outfname
= canonify(origoutfname
);
475 printf("%s: %s\n", origoutfname
, fxp_error());
479 fp
= fopen(fname
, "rb");
481 printf("local: unable to open %s\n", fname
);
486 fh
= fxp_open(outfname
,
489 fh
= fxp_open(outfname
,
490 SSH_FXF_WRITE
| SSH_FXF_CREAT
| SSH_FXF_TRUNC
);
493 printf("%s: %s\n", outfname
, fxp_error());
500 struct fxp_attrs attrs
;
501 if (!fxp_fstat(fh
, &attrs
)) {
502 printf("read size of %s: %s\n", outfname
, fxp_error());
506 if (!(attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
)) {
507 printf("read size of %s: size was not given\n", outfname
);
512 uint64_decimal(offset
, decbuf
);
513 printf("reput: restarting at file position %s\n", decbuf
);
514 if (uint64_compare(offset
, uint64_make(0, LONG_MAX
)) > 0) {
515 printf("reput: remote file is larger than we can deal with\n");
519 if (fseek(fp
, offset
.lo
, SEEK_SET
) != 0)
520 fseek(fp
, 0, SEEK_END
); /* *shrug* */
522 offset
= uint64_make(0, 0);
525 printf("local:%s => remote:%s\n", fname
, outfname
);
528 * FIXME: we can use FXP_FSTAT here to get the file size, and
529 * thus put up a progress bar.
536 len
= fread(buffer
, 1, sizeof(buffer
), fp
);
538 printf("error while reading local file\n");
541 } else if (len
== 0) {
544 if (!fxp_write(fh
, buffer
, offset
, len
)) {
545 printf("error while writing: %s\n", fxp_error());
549 offset
= uint64_add32(offset
, len
);
558 int sftp_cmd_put(struct sftp_command
*cmd
)
560 return sftp_general_put(cmd
, 0);
562 int sftp_cmd_reput(struct sftp_command
*cmd
)
564 return sftp_general_put(cmd
, 1);
567 int sftp_cmd_mkdir(struct sftp_command
*cmd
)
573 printf("psftp: not connected to a host; use \"open host.name\"\n");
577 if (cmd
->nwords
< 2) {
578 printf("mkdir: expects a directory\n");
582 dir
= canonify(cmd
->words
[1]);
584 printf("%s: %s\n", dir
, fxp_error());
588 result
= fxp_mkdir(dir
);
590 printf("mkdir %s: %s\n", dir
, fxp_error());
599 int sftp_cmd_rmdir(struct sftp_command
*cmd
)
605 printf("psftp: not connected to a host; use \"open host.name\"\n");
609 if (cmd
->nwords
< 2) {
610 printf("rmdir: expects a directory\n");
614 dir
= canonify(cmd
->words
[1]);
616 printf("%s: %s\n", dir
, fxp_error());
620 result
= fxp_rmdir(dir
);
622 printf("rmdir %s: %s\n", dir
, fxp_error());
631 int sftp_cmd_rm(struct sftp_command
*cmd
)
637 printf("psftp: not connected to a host; use \"open host.name\"\n");
641 if (cmd
->nwords
< 2) {
642 printf("rm: expects a filename\n");
646 fname
= canonify(cmd
->words
[1]);
648 printf("%s: %s\n", fname
, fxp_error());
652 result
= fxp_remove(fname
);
654 printf("rm %s: %s\n", fname
, fxp_error());
663 int sftp_cmd_mv(struct sftp_command
*cmd
)
665 char *srcfname
, *dstfname
;
669 printf("psftp: not connected to a host; use \"open host.name\"\n");
673 if (cmd
->nwords
< 3) {
674 printf("mv: expects two filenames\n");
677 srcfname
= canonify(cmd
->words
[1]);
679 printf("%s: %s\n", srcfname
, fxp_error());
683 dstfname
= canonify(cmd
->words
[2]);
685 printf("%s: %s\n", dstfname
, fxp_error());
689 result
= fxp_rename(srcfname
, dstfname
);
691 char const *error
= fxp_error();
692 struct fxp_attrs attrs
;
695 * The move might have failed because dstfname pointed at a
696 * directory. We check this possibility now: if dstfname
697 * _is_ a directory, we re-attempt the move by appending
698 * the basename of srcfname to dstfname.
700 result
= fxp_stat(dstfname
, &attrs
);
702 (attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) &&
703 (attrs
.permissions
& 0040000)) {
705 char *newname
, *newcanon
;
706 printf("(destination %s is a directory)\n", dstfname
);
707 p
= srcfname
+ strlen(srcfname
);
708 while (p
> srcfname
&& p
[-1] != '/') p
--;
709 newname
= dupcat(dstfname
, "/", p
, NULL
);
710 newcanon
= canonify(newname
);
715 result
= fxp_rename(srcfname
, dstfname
);
716 error
= result ? NULL
: fxp_error();
720 printf("mv %s %s: %s\n", srcfname
, dstfname
, error
);
726 printf("%s -> %s\n", srcfname
, dstfname
);
733 int sftp_cmd_chmod(struct sftp_command
*cmd
)
737 struct fxp_attrs attrs
;
738 unsigned attrs_clr
, attrs_xor
, oldperms
, newperms
;
741 printf("psftp: not connected to a host; use \"open host.name\"\n");
745 if (cmd
->nwords
< 3) {
746 printf("chmod: expects a mode specifier and a filename\n");
751 * Attempt to parse the mode specifier in cmd->words[1]. We
752 * don't support the full horror of Unix chmod; instead we
753 * support a much simpler syntax in which the user can either
754 * specify an octal number, or a comma-separated sequence of
755 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
756 * _only_ be omitted if the only attribute mentioned is t,
757 * since all others require a user/group/other specification.
758 * Additionally, the s attribute may not be specified for any
759 * [ugoa] specifications other than exactly u or exactly g.
761 attrs_clr
= attrs_xor
= 0;
762 mode
= cmd
->words
[1];
763 if (mode
[0] >= '0' && mode
[0] <= '9') {
764 if (mode
[strspn(mode
, "01234567")]) {
765 printf("chmod: numeric file modes should"
766 " contain digits 0-7 only\n");
770 sscanf(mode
, "%o", &attrs_xor
);
771 attrs_xor
&= attrs_clr
;
774 char *modebegin
= mode
;
775 unsigned subset
, perms
;
779 while (*mode
&& *mode
!= ',' &&
780 *mode
!= '+' && *mode
!= '-' && *mode
!= '=') {
782 case 'u': subset
|= 04700; break; /* setuid, user perms */
783 case 'g': subset
|= 02070; break; /* setgid, group perms */
784 case 'o': subset
|= 00007; break; /* just other perms */
785 case 'a': subset
|= 06777; break; /* all of the above */
787 printf("chmod: file mode '%.*s' contains unrecognised"
788 " user/group/other specifier '%c'\n",
789 strcspn(modebegin
, ","), modebegin
, *mode
);
794 if (!*mode
|| *mode
== ',') {
795 printf("chmod: file mode '%.*s' is incomplete\n",
796 strcspn(modebegin
, ","), modebegin
);
800 if (!*mode
|| *mode
== ',') {
801 printf("chmod: file mode '%.*s' is incomplete\n",
802 strcspn(modebegin
, ","), modebegin
);
806 while (*mode
&& *mode
!= ',') {
808 case 'r': perms
|= 00444; break;
809 case 'w': perms
|= 00222; break;
810 case 'x': perms
|= 00111; break;
811 case 't': perms
|= 01000; subset
|= 01000; break;
813 if ((subset
& 06777) != 04700 &&
814 (subset
& 06777) != 02070) {
815 printf("chmod: file mode '%.*s': set[ug]id bit should"
816 " be used with exactly one of u or g only\n",
817 strcspn(modebegin
, ","), modebegin
);
823 printf("chmod: file mode '%.*s' contains unrecognised"
824 " permission specifier '%c'\n",
825 strcspn(modebegin
, ","), modebegin
, *mode
);
830 if (!(subset
& 06777) && (perms
&~ subset
)) {
831 printf("chmod: file mode '%.*s' contains no user/group/other"
832 " specifier and permissions other than 't' \n",
833 strcspn(modebegin
, ","), modebegin
, *mode
);
851 if (*mode
) mode
++; /* eat comma */
855 fname
= canonify(cmd
->words
[2]);
857 printf("%s: %s\n", fname
, fxp_error());
861 result
= fxp_stat(fname
, &attrs
);
862 if (!result
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
863 printf("get attrs for %s: %s\n", fname
,
864 result ?
"file permissions not provided" : fxp_error());
869 attrs
.flags
= SSH_FILEXFER_ATTR_PERMISSIONS
; /* perms _only_ */
870 oldperms
= attrs
.permissions
& 07777;
871 attrs
.permissions
&= ~attrs_clr
;
872 attrs
.permissions
^= attrs_xor
;
873 newperms
= attrs
.permissions
& 07777;
875 result
= fxp_setstat(fname
, attrs
);
878 printf("set attrs for %s: %s\n", fname
, fxp_error());
883 printf("%s: %04o -> %04o\n", fname
, oldperms
, newperms
);
889 static int sftp_cmd_open(struct sftp_command
*cmd
)
892 printf("psftp: already connected\n");
896 if (cmd
->nwords
< 2) {
897 printf("open: expects a host name\n");
901 if (psftp_connect(cmd
->words
[1], NULL
, 0)) {
902 back
= NULL
; /* connection is already closed */
903 return -1; /* this is fatal */
909 static int sftp_cmd_lcd(struct sftp_command
*cmd
)
914 if (cmd
->nwords
< 2) {
915 printf("lcd: expects a local directory name\n");
919 if (!SetCurrentDirectory(cmd
->words
[1])) {
922 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
923 FORMAT_MESSAGE_FROM_SYSTEM
|
924 FORMAT_MESSAGE_IGNORE_INSERTS
,
925 NULL
, GetLastError(),
926 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
927 (LPTSTR
)&message
, 0, NULL
);
928 i
= strcspn((char *)message
, "\n");
929 printf("lcd: unable to change directory: %.*s\n", i
, (LPCTSTR
)message
);
934 currdir
= smalloc(256);
935 len
= GetCurrentDirectory(256, currdir
);
937 currdir
= srealloc(currdir
, len
);
938 GetCurrentDirectory(len
, currdir
);
939 printf("New local directory is %s\n", currdir
);
945 static int sftp_cmd_lpwd(struct sftp_command
*cmd
)
950 currdir
= smalloc(256);
951 len
= GetCurrentDirectory(256, currdir
);
953 currdir
= srealloc(currdir
, len
);
954 GetCurrentDirectory(len
, currdir
);
955 printf("Current local directory is %s\n", currdir
);
961 static int sftp_cmd_pling(struct sftp_command
*cmd
)
965 exitcode
= system(cmd
->words
[1]);
966 return (exitcode
== 0);
969 static int sftp_cmd_help(struct sftp_command
*cmd
);
971 static struct sftp_cmd_lookup
{
974 * For help purposes, there are two kinds of command:
976 * - primary commands, in which `longhelp' is non-NULL. In
977 * this case `shorthelp' is descriptive text, and `longhelp'
978 * is longer descriptive text intended to be printed after
981 * - alias commands, in which `longhelp' is NULL. In this case
982 * `shorthelp' is the name of a primary command, which
983 * contains the help that should double up for this command.
985 int listed
; /* do we list this in primary help? */
988 int (*obey
) (struct sftp_command
*);
991 * List of sftp commands. This is binary-searched so it MUST be
995 "!", TRUE
, "run a local Windows command",
997 " Runs a local Windows command. For example, \"!del myfile\".\n",
1001 "bye", TRUE
, "finish your SFTP session",
1003 " Terminates your SFTP session and quits the PSFTP program.\n",
1007 "cd", TRUE
, "change your remote working directory",
1008 " [ <New working directory> ]\n"
1009 " Change the remote working directory for your SFTP session.\n"
1010 " If a new working directory is not supplied, you will be\n"
1011 " returned to your home directory.\n",
1015 "chmod", TRUE
, "change file permissions and modes",
1016 " ( <octal-digits> | <modifiers> ) <filename>\n"
1017 " Change the file permissions on a file or directory.\n"
1018 " <octal-digits> can be any octal Unix permission specifier.\n"
1019 " Alternatively, <modifiers> can include:\n"
1020 " u+r make file readable by owning user\n"
1021 " u+w make file writable by owning user\n"
1022 " u+x make file executable by owning user\n"
1023 " u-r make file not readable by owning user\n"
1024 " [also u-w, u-x]\n"
1025 " g+r make file readable by members of owning group\n"
1026 " [also g+w, g+x, g-r, g-w, g-x]\n"
1027 " o+r make file readable by all other users\n"
1028 " [also o+w, o+x, o-r, o-w, o-x]\n"
1029 " a+r make file readable by absolutely everybody\n"
1030 " [also a+w, a+x, a-r, a-w, a-x]\n"
1031 " u+s enable the Unix set-user-ID bit\n"
1032 " u-s disable the Unix set-user-ID bit\n"
1033 " g+s enable the Unix set-group-ID bit\n"
1034 " g-s disable the Unix set-group-ID bit\n"
1035 " +t enable the Unix \"sticky bit\"\n"
1036 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1037 " more than one user for the same modifier (\"ug+w\"). You can\n"
1038 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1042 "del", TRUE
, "delete a file",
1044 " Delete a file.\n",
1048 "delete", FALSE
, "del", NULL
, sftp_cmd_rm
1051 "dir", TRUE
, "list contents of a remote directory",
1052 " [ <directory-name> ]\n"
1053 " List the contents of a specified directory on the server.\n"
1054 " If <directory-name> is not given, the current working directory\n"
1055 " will be listed.\n",
1059 "exit", TRUE
, "bye", NULL
, sftp_cmd_quit
1062 "get", TRUE
, "download a file from the server to your local machine",
1063 " <filename> [ <local-filename> ]\n"
1064 " Downloads a file on the server and stores it locally under\n"
1065 " the same name, or under a different one if you supply the\n"
1066 " argument <local-filename>.\n",
1070 "help", TRUE
, "give help",
1071 " [ <command> [ <command> ... ] ]\n"
1072 " Give general help if no commands are specified.\n"
1073 " If one or more commands are specified, give specific help on\n"
1074 " those particular commands.\n",
1078 "lcd", TRUE
, "change local working directory",
1079 " <local-directory-name>\n"
1080 " Change the local working directory of the PSFTP program (the\n"
1081 " default location where the \"get\" command will save files).\n",
1085 "lpwd", TRUE
, "print local working directory",
1087 " Print the local working directory of the PSFTP program (the\n"
1088 " default location where the \"get\" command will save files).\n",
1092 "ls", TRUE
, "dir", NULL
,
1096 "mkdir", TRUE
, "create a directory on the remote server",
1097 " <directory-name>\n"
1098 " Creates a directory with the given name on the server.\n",
1102 "mv", TRUE
, "move or rename a file on the remote server",
1103 " <source-filename> <destination-filename>\n"
1104 " Moves or renames the file <source-filename> on the server,\n"
1105 " so that it is accessible under the name <destination-filename>.\n",
1109 "open", TRUE
, "connect to a host",
1110 " [<user>@]<hostname>\n"
1111 " Establishes an SFTP connection to a given host. Only usable\n"
1112 " when you did not already specify a host name on the command\n"
1117 "put", TRUE
, "upload a file from your local machine to the server",
1118 " <filename> [ <remote-filename> ]\n"
1119 " Uploads a file to the server and stores it there under\n"
1120 " the same name, or under a different one if you supply the\n"
1121 " argument <remote-filename>.\n",
1125 "pwd", TRUE
, "print your remote working directory",
1127 " Print the current remote working directory for your SFTP session.\n",
1131 "quit", TRUE
, "bye", NULL
,
1135 "reget", TRUE
, "continue downloading a file",
1136 " <filename> [ <local-filename> ]\n"
1137 " Works exactly like the \"get\" command, but the local file\n"
1138 " must already exist. The download will begin at the end of the\n"
1139 " file. This is for resuming a download that was interrupted.\n",
1143 "ren", TRUE
, "mv", NULL
,
1147 "rename", FALSE
, "mv", NULL
,
1151 "reput", TRUE
, "continue uploading a file",
1152 " <filename> [ <remote-filename> ]\n"
1153 " Works exactly like the \"put\" command, but the remote file\n"
1154 " must already exist. The upload will begin at the end of the\n"
1155 " file. This is for resuming an upload that was interrupted.\n",
1159 "rm", TRUE
, "del", NULL
,
1163 "rmdir", TRUE
, "remove a directory on the remote server",
1164 " <directory-name>\n"
1165 " Removes the directory with the given name on the server.\n"
1166 " The directory will not be removed unless it is empty.\n",
1171 const struct sftp_cmd_lookup
*lookup_command(char *name
)
1176 j
= sizeof(sftp_lookup
) / sizeof(*sftp_lookup
);
1179 cmp
= strcmp(name
, sftp_lookup
[k
].name
);
1185 return &sftp_lookup
[k
];
1191 static int sftp_cmd_help(struct sftp_command
*cmd
)
1194 if (cmd
->nwords
== 1) {
1196 * Give short help on each command.
1200 for (i
= 0; i
< sizeof(sftp_lookup
) / sizeof(*sftp_lookup
); i
++) {
1202 if (!sftp_lookup
[i
].listed
)
1204 len
= strlen(sftp_lookup
[i
].name
);
1208 for (i
= 0; i
< sizeof(sftp_lookup
) / sizeof(*sftp_lookup
); i
++) {
1209 const struct sftp_cmd_lookup
*lookup
;
1210 if (!sftp_lookup
[i
].listed
)
1212 lookup
= &sftp_lookup
[i
];
1213 printf("%-*s", maxlen
+2, lookup
->name
);
1214 if (lookup
->longhelp
== NULL
)
1215 lookup
= lookup_command(lookup
->shorthelp
);
1216 printf("%s\n", lookup
->shorthelp
);
1220 * Give long help on specific commands.
1222 for (i
= 1; i
< cmd
->nwords
; i
++) {
1223 const struct sftp_cmd_lookup
*lookup
;
1224 lookup
= lookup_command(cmd
->words
[i
]);
1226 printf("help: %s: command not found\n", cmd
->words
[i
]);
1228 printf("%s", lookup
->name
);
1229 if (lookup
->longhelp
== NULL
)
1230 lookup
= lookup_command(lookup
->shorthelp
);
1231 printf("%s", lookup
->longhelp
);
1238 /* ----------------------------------------------------------------------
1239 * Command line reading and parsing.
1241 struct sftp_command
*sftp_getcmd(FILE *fp
, int mode
, int modeflags
)
1244 int linelen
, linesize
;
1245 struct sftp_command
*cmd
;
1249 if ((mode
== 0) || (modeflags
& 1)) {
1254 cmd
= smalloc(sizeof(struct sftp_command
));
1260 linesize
= linelen
= 0;
1266 line
= srealloc(line
, linesize
);
1267 ret
= fgets(line
+ linelen
, linesize
- linelen
, fp
);
1269 if (!ret
|| (linelen
== 0 && line
[0] == '\0')) {
1270 cmd
->obey
= sftp_cmd_quit
;
1271 if ((mode
== 0) || (modeflags
& 1))
1273 return cmd
; /* eof */
1275 len
= linelen
+ strlen(line
+ linelen
);
1277 if (line
[linelen
- 1] == '\n') {
1279 line
[linelen
] = '\0';
1283 if (modeflags
& 1) {
1284 printf("%s\n", line
);
1288 while (*p
&& (*p
== ' ' || *p
== '\t'))
1293 * Special case: the ! command. This is always parsed as
1294 * exactly two words: one containing the !, and the second
1295 * containing everything else on the line.
1297 cmd
->nwords
= cmd
->wordssize
= 2;
1298 cmd
->words
= srealloc(cmd
->words
, cmd
->wordssize
* sizeof(char *));
1299 cmd
->words
[0] = "!";
1300 cmd
->words
[1] = p
+1;
1304 * Parse the command line into words. The syntax is:
1305 * - double quotes are removed, but cause spaces within to be
1306 * treated as non-separating.
1307 * - a double-doublequote pair is a literal double quote, inside
1308 * _or_ outside quotes. Like this:
1310 * firstword "second word" "this has ""quotes"" in" and""this""
1316 * >this has "quotes" in<
1320 /* skip whitespace */
1321 while (*p
&& (*p
== ' ' || *p
== '\t'))
1323 /* mark start of word */
1324 q
= r
= p
; /* q sits at start, r writes word */
1327 if (!quoting
&& (*p
== ' ' || *p
== '\t'))
1328 break; /* reached end of word */
1329 else if (*p
== '"' && p
[1] == '"')
1330 p
+= 2, *r
++ = '"'; /* a literal quote */
1332 p
++, quoting
= !quoting
;
1337 p
++; /* skip over the whitespace */
1339 if (cmd
->nwords
>= cmd
->wordssize
) {
1340 cmd
->wordssize
= cmd
->nwords
+ 16;
1342 srealloc(cmd
->words
, cmd
->wordssize
* sizeof(char *));
1344 cmd
->words
[cmd
->nwords
++] = q
;
1349 * Now parse the first word and assign a function.
1352 if (cmd
->nwords
== 0)
1353 cmd
->obey
= sftp_cmd_null
;
1355 const struct sftp_cmd_lookup
*lookup
;
1356 lookup
= lookup_command(cmd
->words
[0]);
1358 cmd
->obey
= sftp_cmd_unknown
;
1360 cmd
->obey
= lookup
->obey
;
1366 static int do_sftp_init(void)
1369 * Do protocol initialisation.
1373 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
1374 return 1; /* failure */
1378 * Find out where our home directory is.
1380 homedir
= fxp_realpath(".");
1383 "Warning: failed to resolve home directory: %s\n",
1385 homedir
= dupstr(".");
1387 printf("Remote working directory is %s\n", homedir
);
1389 pwd
= dupstr(homedir
);
1393 void do_sftp(int mode
, int modeflags
, char *batchfile
)
1403 /* ------------------------------------------------------------------
1404 * Now we're ready to do Real Stuff.
1407 struct sftp_command
*cmd
;
1408 cmd
= sftp_getcmd(stdin
, 0, 0);
1411 if (cmd
->obey(cmd
) < 0)
1415 fp
= fopen(batchfile
, "r");
1417 printf("Fatal: unable to open %s\n", batchfile
);
1421 struct sftp_command
*cmd
;
1422 cmd
= sftp_getcmd(fp
, mode
, modeflags
);
1425 ret
= cmd
->obey(cmd
);
1429 if (!(modeflags
& 2))
1438 /* ----------------------------------------------------------------------
1439 * Dirty bits: integration with PuTTY.
1442 static int verbose
= 0;
1445 * Print an error message and perform a fatal exit.
1447 void fatalbox(char *fmt
, ...)
1449 char str
[0x100]; /* Make the size big enough */
1452 strcpy(str
, "Fatal:");
1453 vsprintf(str
+ strlen(str
), fmt
, ap
);
1460 void connection_fatal(char *fmt
, ...)
1462 char str
[0x100]; /* Make the size big enough */
1465 strcpy(str
, "Fatal:");
1466 vsprintf(str
+ strlen(str
), fmt
, ap
);
1474 void ldisc_send(char *buf
, int len
, int interactive
)
1477 * This is only here because of the calls to ldisc_send(NULL,
1478 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
1479 * ldisc as an ldisc. So if we get called with any real data, I
1480 * want to know about it.
1486 * Be told what socket we're supposed to be using.
1488 static SOCKET sftp_ssh_socket
;
1489 char *do_select(SOCKET skt
, int startup
)
1492 sftp_ssh_socket
= skt
;
1494 sftp_ssh_socket
= INVALID_SOCKET
;
1497 extern int select_result(WPARAM
, LPARAM
);
1500 * Receive a block of data from the SSH link. Block until all data
1503 * To do this, we repeatedly call the SSH protocol module, with our
1504 * own trap in from_backend() to catch the data that comes back. We
1505 * do this until we have enough data.
1508 static unsigned char *outptr
; /* where to put the data */
1509 static unsigned outlen
; /* how much data required */
1510 static unsigned char *pending
= NULL
; /* any spare data */
1511 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
1512 int from_backend(int is_stderr
, char *data
, int datalen
)
1514 unsigned char *p
= (unsigned char *) data
;
1515 unsigned len
= (unsigned) datalen
;
1520 * stderr data is just spouted to local stderr and otherwise
1524 fwrite(data
, 1, len
, stderr
);
1529 * If this is before the real session begins, just return.
1535 unsigned used
= outlen
;
1538 memcpy(outptr
, p
, used
);
1546 if (pendsize
< pendlen
+ len
) {
1547 pendsize
= pendlen
+ len
+ 4096;
1548 pending
= (pending ?
srealloc(pending
, pendsize
) :
1551 fatalbox("Out of memory");
1553 memcpy(pending
+ pendlen
, p
, len
);
1559 int sftp_recvdata(char *buf
, int len
)
1561 outptr
= (unsigned char *) buf
;
1565 * See if the pending-input block contains some of what we
1569 unsigned pendused
= pendlen
;
1570 if (pendused
> outlen
)
1572 memcpy(outptr
, pending
, pendused
);
1573 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
1576 pendlen
-= pendused
;
1586 while (outlen
> 0) {
1590 FD_SET(sftp_ssh_socket
, &readfds
);
1591 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
1592 return 0; /* doom */
1593 select_result((WPARAM
) sftp_ssh_socket
, (LPARAM
) FD_READ
);
1598 int sftp_senddata(char *buf
, int len
)
1600 back
->send((unsigned char *) buf
, len
);
1605 * Loop through the ssh connection and authentication process.
1607 static void ssh_sftp_init(void)
1609 if (sftp_ssh_socket
== INVALID_SOCKET
)
1611 while (!back
->sendok()) {
1614 FD_SET(sftp_ssh_socket
, &readfds
);
1615 if (select(1, &readfds
, NULL
, NULL
, NULL
) < 0)
1617 select_result((WPARAM
) sftp_ssh_socket
, (LPARAM
) FD_READ
);
1622 * Initialize the Win$ock driver.
1624 static void init_winsock(void)
1629 winsock_ver
= MAKEWORD(1, 1);
1630 if (WSAStartup(winsock_ver
, &wsadata
)) {
1631 fprintf(stderr
, "Unable to initialise WinSock");
1634 if (LOBYTE(wsadata
.wVersion
) != 1 || HIBYTE(wsadata
.wVersion
) != 1) {
1635 fprintf(stderr
, "WinSock version is incompatible with 1.1");
1641 * Short description of parameters.
1643 static void usage(void)
1645 printf("PuTTY Secure File Transfer (SFTP) client\n");
1646 printf("%s\n", ver
);
1647 printf("Usage: psftp [options] user@host\n");
1648 printf("Options:\n");
1649 printf(" -b file use specified batchfile\n");
1650 printf(" -bc output batchfile commands\n");
1651 printf(" -be don't stop batchfile processing if errors\n");
1652 printf(" -v show verbose messages\n");
1653 printf(" -P port connect to specified port\n");
1654 printf(" -pw passw login with specified password\n");
1659 * Connect to a host.
1661 static int psftp_connect(char *userhost
, char *user
, int portnumber
)
1663 char *host
, *realhost
;
1666 /* Separate host and username */
1668 host
= strrchr(host
, '@');
1674 printf("psftp: multiple usernames specified; using \"%s\"\n",
1680 /* Try to load settings for this host */
1681 do_defaults(host
, &cfg
);
1682 if (cfg
.host
[0] == '\0') {
1683 /* No settings for this host; use defaults */
1684 do_defaults(NULL
, &cfg
);
1685 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
1686 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
1691 * Trim leading whitespace off the hostname if it's there.
1694 int space
= strspn(cfg
.host
, " \t");
1695 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
1698 /* See if host is of the form user@host */
1699 if (cfg
.host
[0] != '\0') {
1700 char *atsign
= strchr(cfg
.host
, '@');
1701 /* Make sure we're not overflowing the user field */
1703 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
1704 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
1705 cfg
.username
[atsign
- cfg
.host
] = '\0';
1707 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
1712 * Trim a colon suffix off the hostname if it's there.
1714 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
1717 if (user
!= NULL
&& user
[0] != '\0') {
1718 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
1719 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
1721 if (!cfg
.username
[0]) {
1722 printf("login as: ");
1723 if (!fgets(cfg
.username
, sizeof(cfg
.username
), stdin
)) {
1724 fprintf(stderr
, "psftp: aborting\n");
1727 int len
= strlen(cfg
.username
);
1728 if (cfg
.username
[len
- 1] == '\n')
1729 cfg
.username
[len
- 1] = '\0';
1733 if (cfg
.protocol
!= PROT_SSH
)
1737 cfg
.port
= portnumber
;
1739 /* SFTP uses SSH2 by default always */
1743 * Disable scary things which shouldn't be enabled for simple
1744 * things like SCP and SFTP: agent forwarding, port forwarding,
1747 cfg
.x11_forward
= 0;
1749 cfg
.portfwd
[0] = cfg
.portfwd
[1] = '\0';
1751 /* Set up subsystem name. */
1752 strcpy(cfg
.remote_cmd
, "sftp");
1753 cfg
.ssh_subsys
= TRUE
;
1757 * Set up fallback option, for SSH1 servers or servers with the
1758 * sftp subsystem not enabled but the server binary installed
1759 * in the usual place. We only support fallback on Unix
1760 * systems, and we use a kludgy piece of shellery which should
1761 * try to find sftp-server in various places (the obvious
1762 * systemwide spots /usr/lib and /usr/local/lib, and then the
1763 * user's PATH) and finally give up.
1765 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
1766 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
1769 * the idea being that this will attempt to use either of the
1770 * obvious pathnames and then give up, and when it does give up
1771 * it will print the preferred pathname in the error messages.
1773 cfg
.remote_cmd_ptr2
=
1774 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
1775 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
1777 cfg
.ssh_subsys2
= FALSE
;
1779 back
= &ssh_backend
;
1781 err
= back
->init(cfg
.host
, cfg
.port
, &realhost
, 0);
1783 fprintf(stderr
, "ssh_init: %s\n", err
);
1787 if (verbose
&& realhost
!= NULL
)
1788 printf("Connected to %s\n", realhost
);
1793 * Main program. Parse arguments etc.
1795 int main(int argc
, char *argv
[])
1799 char *userhost
, *user
;
1802 char *batchfile
= NULL
;
1804 flags
= FLAG_STDERR
| FLAG_INTERACTIVE
;
1805 ssh_get_line
= &console_get_line
;
1809 userhost
= user
= NULL
;
1811 for (i
= 1; i
< argc
; i
++) {
1812 if (argv
[i
][0] != '-') {
1816 userhost
= dupstr(argv
[i
]);
1817 } else if (strcmp(argv
[i
], "-v") == 0) {
1818 verbose
= 1, flags
|= FLAG_VERBOSE
;
1819 } else if (strcmp(argv
[i
], "-h") == 0 ||
1820 strcmp(argv
[i
], "-?") == 0) {
1822 } else if (strcmp(argv
[i
], "-l") == 0 && i
+ 1 < argc
) {
1824 } else if (strcmp(argv
[i
], "-P") == 0 && i
+ 1 < argc
) {
1825 portnumber
= atoi(argv
[++i
]);
1826 } else if (strcmp(argv
[i
], "-pw") == 0 && i
+ 1 < argc
) {
1827 console_password
= argv
[++i
];
1828 } else if (strcmp(argv
[i
], "-b") == 0 && i
+ 1 < argc
) {
1830 batchfile
= argv
[++i
];
1831 } else if (strcmp(argv
[i
], "-bc") == 0) {
1832 modeflags
= modeflags
| 1;
1833 } else if (strcmp(argv
[i
], "-batch") == 0) {
1834 console_batch_mode
= TRUE
;
1835 } else if (strcmp(argv
[i
], "-be") == 0) {
1836 modeflags
= modeflags
| 2;
1837 } else if (strcmp(argv
[i
], "--") == 0) {
1849 * If a user@host string has already been provided, connect to
1853 if (psftp_connect(userhost
, user
, portnumber
))
1858 printf("psftp: no hostname specified; use \"open host.name\""
1862 do_sftp(mode
, modeflags
, batchfile
);
1864 if (back
!= NULL
&& back
->socket() != NULL
) {
1866 back
->special(TS_EOF
);
1867 sftp_recvdata(&ch
, 1);