2 * psftp.c: front end for PSFTP.
11 #define PUTTY_DO_GLOBALS
20 * Since SFTP is a request-response oriented protocol, it requires
21 * no buffer management: when we send data, we stop and wait for an
22 * acknowledgement _anyway_, and so we can't possibly overfill our
26 static int psftp_connect(char *userhost
, char *user
, int portnumber
);
27 static int do_sftp_init(void);
29 /* ----------------------------------------------------------------------
35 static void *backhandle
;
38 /* ----------------------------------------------------------------------
39 * Higher-level helper functions used in commands.
43 * Attempt to canonify a pathname starting from the pwd. If
44 * canonification fails, at least fall back to returning a _valid_
45 * pathname (though it may be ugly, eg /home/simon/../foobar).
47 char *canonify(char *name
)
49 char *fullname
, *canonname
;
50 struct sftp_packet
*pktin
;
51 struct sftp_request
*req
, *rreq
;
54 fullname
= dupstr(name
);
57 if (pwd
[strlen(pwd
) - 1] == '/')
61 fullname
= dupcat(pwd
, slash
, name
, NULL
);
64 sftp_register(req
= fxp_realpath_send(fullname
));
65 rreq
= sftp_find_request(pktin
= sftp_recv());
67 canonname
= fxp_realpath_recv(pktin
, rreq
);
74 * Attempt number 2. Some FXP_REALPATH implementations
75 * (glibc-based ones, in particular) require the _whole_
76 * path to point to something that exists, whereas others
77 * (BSD-based) only require all but the last component to
78 * exist. So if the first call failed, we should strip off
79 * everything from the last slash onwards and try again,
80 * then put the final component back on.
84 * - if the last component is "/." or "/..", then we don't
85 * bother trying this because there's no way it can work.
87 * - if the thing actually ends with a "/", we remove it
88 * before we start. Except if the string is "/" itself
89 * (although I can't see why we'd have got here if so,
90 * because surely "/" would have worked the first
91 * time?), in which case we don't bother.
93 * - if there's no slash in the string at all, give up in
94 * confusion (we expect at least one because of the way
95 * we constructed the string).
101 i
= strlen(fullname
);
102 if (i
> 2 && fullname
[i
- 1] == '/')
103 fullname
[--i
] = '\0'; /* strip trailing / unless at pos 0 */
104 while (i
> 0 && fullname
[--i
] != '/');
107 * Give up on special cases.
109 if (fullname
[i
] != '/' || /* no slash at all */
110 !strcmp(fullname
+ i
, "/.") || /* ends in /. */
111 !strcmp(fullname
+ i
, "/..") || /* ends in /.. */
112 !strcmp(fullname
, "/")) {
117 * Now i points at the slash. Deal with the final special
118 * case i==0 (ie the whole path was "/nonexistentfile").
120 fullname
[i
] = '\0'; /* separate the string */
122 sftp_register(req
= fxp_realpath_send("/"));
124 sftp_register(req
= fxp_realpath_send(fullname
));
126 rreq
= sftp_find_request(pktin
= sftp_recv());
128 canonname
= fxp_realpath_recv(pktin
, rreq
);
131 return fullname
; /* even that failed; give up */
134 * We have a canonical name for all but the last path
135 * component. Concatenate the last component and return.
137 returnname
= dupcat(canonname
,
138 canonname
[strlen(canonname
) - 1] ==
139 '/' ?
"" : "/", fullname
+ i
+ 1, NULL
);
147 * Return a pointer to the portion of str that comes after the last
148 * slash (or backslash or colon, if `local' is TRUE).
150 static char *stripslashes(char *str
, int local
)
155 p
= strchr(str
, ':');
159 p
= strrchr(str
, '/');
163 p
= strrchr(str
, '\\');
170 /* ----------------------------------------------------------------------
171 * Actual sftp commands.
173 struct sftp_command
{
175 int nwords
, wordssize
;
176 int (*obey
) (struct sftp_command
*); /* returns <0 to quit */
179 int sftp_cmd_null(struct sftp_command
*cmd
)
181 return 1; /* success */
184 int sftp_cmd_unknown(struct sftp_command
*cmd
)
186 printf("psftp: unknown command \"%s\"\n", cmd
->words
[0]);
187 return 0; /* failure */
190 int sftp_cmd_quit(struct sftp_command
*cmd
)
196 * List a directory. If no arguments are given, list pwd; otherwise
197 * list the directory given in words[1].
199 static int sftp_ls_compare(const void *av
, const void *bv
)
201 const struct fxp_name
*const *a
= (const struct fxp_name
*const *) av
;
202 const struct fxp_name
*const *b
= (const struct fxp_name
*const *) bv
;
203 return strcmp((*a
)->filename
, (*b
)->filename
);
205 int sftp_cmd_ls(struct sftp_command
*cmd
)
207 struct fxp_handle
*dirh
;
208 struct fxp_names
*names
;
209 struct fxp_name
**ournames
;
210 int nnames
, namesize
;
212 struct sftp_packet
*pktin
;
213 struct sftp_request
*req
, *rreq
;
217 printf("psftp: not connected to a host; use \"open host.name\"\n");
226 cdir
= canonify(dir
);
228 printf("%s: %s\n", dir
, fxp_error());
232 printf("Listing directory %s\n", cdir
);
234 sftp_register(req
= fxp_opendir_send(cdir
));
235 rreq
= sftp_find_request(pktin
= sftp_recv());
237 dirh
= fxp_opendir_recv(pktin
, rreq
);
240 printf("Unable to open %s: %s\n", dir
, fxp_error());
242 nnames
= namesize
= 0;
247 sftp_register(req
= fxp_readdir_send(dirh
));
248 rreq
= sftp_find_request(pktin
= sftp_recv());
250 names
= fxp_readdir_recv(pktin
, rreq
);
253 if (fxp_error_type() == SSH_FX_EOF
)
255 printf("Reading directory %s: %s\n", dir
, fxp_error());
258 if (names
->nnames
== 0) {
259 fxp_free_names(names
);
263 if (nnames
+ names
->nnames
>= namesize
) {
264 namesize
+= names
->nnames
+ 128;
265 ournames
= sresize(ournames
, namesize
, struct fxp_name
*);
268 for (i
= 0; i
< names
->nnames
; i
++)
269 ournames
[nnames
++] = fxp_dup_name(&names
->names
[i
]);
271 fxp_free_names(names
);
273 sftp_register(req
= fxp_close_send(dirh
));
274 rreq
= sftp_find_request(pktin
= sftp_recv());
276 fxp_close_recv(pktin
, rreq
);
279 * Now we have our filenames. Sort them by actual file
280 * name, and then output the longname parts.
282 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_ls_compare
);
287 for (i
= 0; i
< nnames
; i
++) {
288 printf("%s\n", ournames
[i
]->longname
);
289 fxp_free_name(ournames
[i
]);
300 * Change directories. We do this by canonifying the new name, then
301 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
303 int sftp_cmd_cd(struct sftp_command
*cmd
)
305 struct fxp_handle
*dirh
;
306 struct sftp_packet
*pktin
;
307 struct sftp_request
*req
, *rreq
;
311 printf("psftp: not connected to a host; use \"open host.name\"\n");
316 dir
= dupstr(homedir
);
318 dir
= canonify(cmd
->words
[1]);
321 printf("%s: %s\n", dir
, fxp_error());
325 sftp_register(req
= fxp_opendir_send(dir
));
326 rreq
= sftp_find_request(pktin
= sftp_recv());
328 dirh
= fxp_opendir_recv(pktin
, rreq
);
331 printf("Directory %s: %s\n", dir
, fxp_error());
336 sftp_register(req
= fxp_close_send(dirh
));
337 rreq
= sftp_find_request(pktin
= sftp_recv());
339 fxp_close_recv(pktin
, rreq
);
343 printf("Remote directory is now %s\n", pwd
);
349 * Print current directory. Easy as pie.
351 int sftp_cmd_pwd(struct sftp_command
*cmd
)
354 printf("psftp: not connected to a host; use \"open host.name\"\n");
358 printf("Remote directory is %s\n", pwd
);
363 * Get a file and save it at the local end. We have two very
364 * similar commands here: `get' and `reget', which differ in that
365 * `reget' checks for the existence of the destination file and
366 * starts from where a previous aborted transfer left off.
368 int sftp_general_get(struct sftp_command
*cmd
, int restart
)
370 struct fxp_handle
*fh
;
371 struct sftp_packet
*pktin
;
372 struct sftp_request
*req
, *rreq
;
373 char *fname
, *outfname
;
379 printf("psftp: not connected to a host; use \"open host.name\"\n");
383 if (cmd
->nwords
< 2) {
384 printf("get: expects a filename\n");
388 fname
= canonify(cmd
->words
[1]);
390 printf("%s: %s\n", cmd
->words
[1], fxp_error());
393 outfname
= (cmd
->nwords
== 2 ?
394 stripslashes(cmd
->words
[1], 0) : cmd
->words
[2]);
396 sftp_register(req
= fxp_open_send(fname
, SSH_FXF_READ
));
397 rreq
= sftp_find_request(pktin
= sftp_recv());
399 fh
= fxp_open_recv(pktin
, rreq
);
402 printf("%s: %s\n", fname
, fxp_error());
408 fp
= fopen(outfname
, "rb+");
410 fp
= fopen(outfname
, "wb");
414 printf("local: unable to open %s\n", outfname
);
416 sftp_register(req
= fxp_close_send(fh
));
417 rreq
= sftp_find_request(pktin
= sftp_recv());
419 fxp_close_recv(pktin
, rreq
);
427 fseek(fp
, 0L, SEEK_END
);
429 printf("reget: restarting at file position %ld\n", posn
);
430 offset
= uint64_make(0, posn
);
432 offset
= uint64_make(0, 0);
435 printf("remote:%s => local:%s\n", fname
, outfname
);
438 * FIXME: we can use FXP_FSTAT here to get the file size, and
439 * thus put up a progress bar.
447 sftp_register(req
= fxp_read_send(fh
, offset
, sizeof(buffer
)));
448 rreq
= sftp_find_request(pktin
= sftp_recv());
450 len
= fxp_read_recv(pktin
, rreq
, buffer
, sizeof(buffer
));
452 if ((len
== -1 && fxp_error_type() == SSH_FX_EOF
) || len
== 0)
455 printf("error while reading: %s\n", fxp_error());
462 wlen
= fwrite(buffer
, 1, len
- wpos
, fp
);
464 printf("error while writing local file\n");
470 if (wpos
< len
) { /* we had an error */
474 offset
= uint64_add32(offset
, len
);
479 sftp_register(req
= fxp_close_send(fh
));
480 rreq
= sftp_find_request(pktin
= sftp_recv());
482 fxp_close_recv(pktin
, rreq
);
488 int sftp_cmd_get(struct sftp_command
*cmd
)
490 return sftp_general_get(cmd
, 0);
492 int sftp_cmd_reget(struct sftp_command
*cmd
)
494 return sftp_general_get(cmd
, 1);
498 * Send a file and store it at the remote end. We have two very
499 * similar commands here: `put' and `reput', which differ in that
500 * `reput' checks for the existence of the destination file and
501 * starts from where a previous aborted transfer left off.
503 int sftp_general_put(struct sftp_command
*cmd
, int restart
)
505 struct fxp_handle
*fh
;
506 char *fname
, *origoutfname
, *outfname
;
507 struct sftp_packet
*pktin
;
508 struct sftp_request
*req
, *rreq
;
514 printf("psftp: not connected to a host; use \"open host.name\"\n");
518 if (cmd
->nwords
< 2) {
519 printf("put: expects a filename\n");
523 fname
= cmd
->words
[1];
524 origoutfname
= (cmd
->nwords
== 2 ?
525 stripslashes(cmd
->words
[1], 1) : cmd
->words
[2]);
526 outfname
= canonify(origoutfname
);
528 printf("%s: %s\n", origoutfname
, fxp_error());
532 fp
= fopen(fname
, "rb");
534 printf("local: unable to open %s\n", fname
);
539 sftp_register(req
= fxp_open_send(outfname
, SSH_FXF_WRITE
));
541 sftp_register(req
= fxp_open_send(outfname
, SSH_FXF_WRITE
|
542 SSH_FXF_CREAT
| SSH_FXF_TRUNC
));
544 rreq
= sftp_find_request(pktin
= sftp_recv());
546 fh
= fxp_open_recv(pktin
, rreq
);
549 printf("%s: %s\n", outfname
, fxp_error());
556 struct fxp_attrs attrs
;
559 sftp_register(req
= fxp_fstat_send(fh
));
560 rreq
= sftp_find_request(pktin
= sftp_recv());
562 ret
= fxp_fstat_recv(pktin
, rreq
, &attrs
);
565 printf("read size of %s: %s\n", outfname
, fxp_error());
569 if (!(attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
)) {
570 printf("read size of %s: size was not given\n", outfname
);
575 uint64_decimal(offset
, decbuf
);
576 printf("reput: restarting at file position %s\n", decbuf
);
577 if (uint64_compare(offset
, uint64_make(0, LONG_MAX
)) > 0) {
578 printf("reput: remote file is larger than we can deal with\n");
582 if (fseek(fp
, offset
.lo
, SEEK_SET
) != 0)
583 fseek(fp
, 0, SEEK_END
); /* *shrug* */
585 offset
= uint64_make(0, 0);
588 printf("local:%s => remote:%s\n", fname
, outfname
);
591 * FIXME: we can use FXP_FSTAT here to get the file size, and
592 * thus put up a progress bar.
599 len
= fread(buffer
, 1, sizeof(buffer
), fp
);
601 printf("error while reading local file\n");
604 } else if (len
== 0) {
608 sftp_register(req
= fxp_write_send(fh
, buffer
, offset
, len
));
609 rreq
= sftp_find_request(pktin
= sftp_recv());
611 ret
= fxp_write_recv(pktin
, rreq
);
614 printf("error while writing: %s\n", fxp_error());
618 offset
= uint64_add32(offset
, len
);
621 sftp_register(req
= fxp_close_send(fh
));
622 rreq
= sftp_find_request(pktin
= sftp_recv());
624 fxp_close_recv(pktin
, rreq
);
631 int sftp_cmd_put(struct sftp_command
*cmd
)
633 return sftp_general_put(cmd
, 0);
635 int sftp_cmd_reput(struct sftp_command
*cmd
)
637 return sftp_general_put(cmd
, 1);
640 int sftp_cmd_mkdir(struct sftp_command
*cmd
)
643 struct sftp_packet
*pktin
;
644 struct sftp_request
*req
, *rreq
;
648 printf("psftp: not connected to a host; use \"open host.name\"\n");
652 if (cmd
->nwords
< 2) {
653 printf("mkdir: expects a directory\n");
657 dir
= canonify(cmd
->words
[1]);
659 printf("%s: %s\n", dir
, fxp_error());
663 sftp_register(req
= fxp_mkdir_send(dir
));
664 rreq
= sftp_find_request(pktin
= sftp_recv());
666 result
= fxp_mkdir_recv(pktin
, rreq
);
669 printf("mkdir %s: %s\n", dir
, fxp_error());
678 int sftp_cmd_rmdir(struct sftp_command
*cmd
)
681 struct sftp_packet
*pktin
;
682 struct sftp_request
*req
, *rreq
;
686 printf("psftp: not connected to a host; use \"open host.name\"\n");
690 if (cmd
->nwords
< 2) {
691 printf("rmdir: expects a directory\n");
695 dir
= canonify(cmd
->words
[1]);
697 printf("%s: %s\n", dir
, fxp_error());
701 sftp_register(req
= fxp_rmdir_send(dir
));
702 rreq
= sftp_find_request(pktin
= sftp_recv());
704 result
= fxp_rmdir_recv(pktin
, rreq
);
707 printf("rmdir %s: %s\n", dir
, fxp_error());
716 int sftp_cmd_rm(struct sftp_command
*cmd
)
719 struct sftp_packet
*pktin
;
720 struct sftp_request
*req
, *rreq
;
724 printf("psftp: not connected to a host; use \"open host.name\"\n");
728 if (cmd
->nwords
< 2) {
729 printf("rm: expects a filename\n");
733 fname
= canonify(cmd
->words
[1]);
735 printf("%s: %s\n", fname
, fxp_error());
739 sftp_register(req
= fxp_remove_send(fname
));
740 rreq
= sftp_find_request(pktin
= sftp_recv());
742 result
= fxp_remove_recv(pktin
, rreq
);
745 printf("rm %s: %s\n", fname
, fxp_error());
754 int sftp_cmd_mv(struct sftp_command
*cmd
)
756 char *srcfname
, *dstfname
;
757 struct sftp_packet
*pktin
;
758 struct sftp_request
*req
, *rreq
;
762 printf("psftp: not connected to a host; use \"open host.name\"\n");
766 if (cmd
->nwords
< 3) {
767 printf("mv: expects two filenames\n");
770 srcfname
= canonify(cmd
->words
[1]);
772 printf("%s: %s\n", srcfname
, fxp_error());
776 dstfname
= canonify(cmd
->words
[2]);
778 printf("%s: %s\n", dstfname
, fxp_error());
782 sftp_register(req
= fxp_rename_send(srcfname
, dstfname
));
783 rreq
= sftp_find_request(pktin
= sftp_recv());
785 result
= fxp_rename_recv(pktin
, rreq
);
788 char const *error
= fxp_error();
789 struct fxp_attrs attrs
;
792 * The move might have failed because dstfname pointed at a
793 * directory. We check this possibility now: if dstfname
794 * _is_ a directory, we re-attempt the move by appending
795 * the basename of srcfname to dstfname.
797 sftp_register(req
= fxp_stat_send(dstfname
));
798 rreq
= sftp_find_request(pktin
= sftp_recv());
800 result
= fxp_stat_recv(pktin
, rreq
, &attrs
);
803 (attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) &&
804 (attrs
.permissions
& 0040000)) {
806 char *newname
, *newcanon
;
807 printf("(destination %s is a directory)\n", dstfname
);
808 p
= srcfname
+ strlen(srcfname
);
809 while (p
> srcfname
&& p
[-1] != '/') p
--;
810 newname
= dupcat(dstfname
, "/", p
, NULL
);
811 newcanon
= canonify(newname
);
817 sftp_register(req
= fxp_rename_send(srcfname
, dstfname
));
818 rreq
= sftp_find_request(pktin
= sftp_recv());
820 result
= fxp_rename_recv(pktin
, rreq
);
822 error
= result ? NULL
: fxp_error();
826 printf("mv %s %s: %s\n", srcfname
, dstfname
, error
);
832 printf("%s -> %s\n", srcfname
, dstfname
);
839 int sftp_cmd_chmod(struct sftp_command
*cmd
)
843 struct fxp_attrs attrs
;
844 unsigned attrs_clr
, attrs_xor
, oldperms
, newperms
;
845 struct sftp_packet
*pktin
;
846 struct sftp_request
*req
, *rreq
;
849 printf("psftp: not connected to a host; use \"open host.name\"\n");
853 if (cmd
->nwords
< 3) {
854 printf("chmod: expects a mode specifier and a filename\n");
859 * Attempt to parse the mode specifier in cmd->words[1]. We
860 * don't support the full horror of Unix chmod; instead we
861 * support a much simpler syntax in which the user can either
862 * specify an octal number, or a comma-separated sequence of
863 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
864 * _only_ be omitted if the only attribute mentioned is t,
865 * since all others require a user/group/other specification.
866 * Additionally, the s attribute may not be specified for any
867 * [ugoa] specifications other than exactly u or exactly g.
869 attrs_clr
= attrs_xor
= 0;
870 mode
= cmd
->words
[1];
871 if (mode
[0] >= '0' && mode
[0] <= '9') {
872 if (mode
[strspn(mode
, "01234567")]) {
873 printf("chmod: numeric file modes should"
874 " contain digits 0-7 only\n");
878 sscanf(mode
, "%o", &attrs_xor
);
879 attrs_xor
&= attrs_clr
;
882 char *modebegin
= mode
;
883 unsigned subset
, perms
;
887 while (*mode
&& *mode
!= ',' &&
888 *mode
!= '+' && *mode
!= '-' && *mode
!= '=') {
890 case 'u': subset
|= 04700; break; /* setuid, user perms */
891 case 'g': subset
|= 02070; break; /* setgid, group perms */
892 case 'o': subset
|= 00007; break; /* just other perms */
893 case 'a': subset
|= 06777; break; /* all of the above */
895 printf("chmod: file mode '%.*s' contains unrecognised"
896 " user/group/other specifier '%c'\n",
897 strcspn(modebegin
, ","), modebegin
, *mode
);
902 if (!*mode
|| *mode
== ',') {
903 printf("chmod: file mode '%.*s' is incomplete\n",
904 strcspn(modebegin
, ","), modebegin
);
908 if (!*mode
|| *mode
== ',') {
909 printf("chmod: file mode '%.*s' is incomplete\n",
910 strcspn(modebegin
, ","), modebegin
);
914 while (*mode
&& *mode
!= ',') {
916 case 'r': perms
|= 00444; break;
917 case 'w': perms
|= 00222; break;
918 case 'x': perms
|= 00111; break;
919 case 't': perms
|= 01000; subset
|= 01000; break;
921 if ((subset
& 06777) != 04700 &&
922 (subset
& 06777) != 02070) {
923 printf("chmod: file mode '%.*s': set[ug]id bit should"
924 " be used with exactly one of u or g only\n",
925 strcspn(modebegin
, ","), modebegin
);
931 printf("chmod: file mode '%.*s' contains unrecognised"
932 " permission specifier '%c'\n",
933 strcspn(modebegin
, ","), modebegin
, *mode
);
938 if (!(subset
& 06777) && (perms
&~ subset
)) {
939 printf("chmod: file mode '%.*s' contains no user/group/other"
940 " specifier and permissions other than 't' \n",
941 strcspn(modebegin
, ","), modebegin
);
959 if (*mode
) mode
++; /* eat comma */
963 fname
= canonify(cmd
->words
[2]);
965 printf("%s: %s\n", fname
, fxp_error());
969 sftp_register(req
= fxp_stat_send(fname
));
970 rreq
= sftp_find_request(pktin
= sftp_recv());
972 result
= fxp_stat_recv(pktin
, rreq
, &attrs
);
974 if (!result
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
975 printf("get attrs for %s: %s\n", fname
,
976 result ?
"file permissions not provided" : fxp_error());
981 attrs
.flags
= SSH_FILEXFER_ATTR_PERMISSIONS
; /* perms _only_ */
982 oldperms
= attrs
.permissions
& 07777;
983 attrs
.permissions
&= ~attrs_clr
;
984 attrs
.permissions
^= attrs_xor
;
985 newperms
= attrs
.permissions
& 07777;
987 sftp_register(req
= fxp_setstat_send(fname
, attrs
));
988 rreq
= sftp_find_request(pktin
= sftp_recv());
990 result
= fxp_setstat_recv(pktin
, rreq
);
993 printf("set attrs for %s: %s\n", fname
, fxp_error());
998 printf("%s: %04o -> %04o\n", fname
, oldperms
, newperms
);
1004 static int sftp_cmd_open(struct sftp_command
*cmd
)
1007 printf("psftp: already connected\n");
1011 if (cmd
->nwords
< 2) {
1012 printf("open: expects a host name\n");
1016 if (psftp_connect(cmd
->words
[1], NULL
, 0)) {
1017 back
= NULL
; /* connection is already closed */
1018 return -1; /* this is fatal */
1024 static int sftp_cmd_lcd(struct sftp_command
*cmd
)
1026 char *currdir
, *errmsg
;
1028 if (cmd
->nwords
< 2) {
1029 printf("lcd: expects a local directory name\n");
1033 errmsg
= psftp_lcd(cmd
->words
[1]);
1035 printf("lcd: unable to change directory: %s\n", errmsg
);
1040 currdir
= psftp_getcwd();
1041 printf("New local directory is %s\n", currdir
);
1047 static int sftp_cmd_lpwd(struct sftp_command
*cmd
)
1051 currdir
= psftp_getcwd();
1052 printf("Current local directory is %s\n", currdir
);
1058 static int sftp_cmd_pling(struct sftp_command
*cmd
)
1062 exitcode
= system(cmd
->words
[1]);
1063 return (exitcode
== 0);
1066 static int sftp_cmd_help(struct sftp_command
*cmd
);
1068 static struct sftp_cmd_lookup
{
1071 * For help purposes, there are two kinds of command:
1073 * - primary commands, in which `longhelp' is non-NULL. In
1074 * this case `shorthelp' is descriptive text, and `longhelp'
1075 * is longer descriptive text intended to be printed after
1078 * - alias commands, in which `longhelp' is NULL. In this case
1079 * `shorthelp' is the name of a primary command, which
1080 * contains the help that should double up for this command.
1082 int listed
; /* do we list this in primary help? */
1085 int (*obey
) (struct sftp_command
*);
1088 * List of sftp commands. This is binary-searched so it MUST be
1092 "!", TRUE
, "run a local command",
1094 /* FIXME: this example is crap for non-Windows. */
1095 " Runs a local command. For example, \"!del myfile\".\n",
1099 "bye", TRUE
, "finish your SFTP session",
1101 " Terminates your SFTP session and quits the PSFTP program.\n",
1105 "cd", TRUE
, "change your remote working directory",
1106 " [ <New working directory> ]\n"
1107 " Change the remote working directory for your SFTP session.\n"
1108 " If a new working directory is not supplied, you will be\n"
1109 " returned to your home directory.\n",
1113 "chmod", TRUE
, "change file permissions and modes",
1114 " ( <octal-digits> | <modifiers> ) <filename>\n"
1115 " Change the file permissions on a file or directory.\n"
1116 " <octal-digits> can be any octal Unix permission specifier.\n"
1117 " Alternatively, <modifiers> can include:\n"
1118 " u+r make file readable by owning user\n"
1119 " u+w make file writable by owning user\n"
1120 " u+x make file executable by owning user\n"
1121 " u-r make file not readable by owning user\n"
1122 " [also u-w, u-x]\n"
1123 " g+r make file readable by members of owning group\n"
1124 " [also g+w, g+x, g-r, g-w, g-x]\n"
1125 " o+r make file readable by all other users\n"
1126 " [also o+w, o+x, o-r, o-w, o-x]\n"
1127 " a+r make file readable by absolutely everybody\n"
1128 " [also a+w, a+x, a-r, a-w, a-x]\n"
1129 " u+s enable the Unix set-user-ID bit\n"
1130 " u-s disable the Unix set-user-ID bit\n"
1131 " g+s enable the Unix set-group-ID bit\n"
1132 " g-s disable the Unix set-group-ID bit\n"
1133 " +t enable the Unix \"sticky bit\"\n"
1134 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1135 " more than one user for the same modifier (\"ug+w\"). You can\n"
1136 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1140 "del", TRUE
, "delete a file",
1142 " Delete a file.\n",
1146 "delete", FALSE
, "del", NULL
, sftp_cmd_rm
1149 "dir", TRUE
, "list contents of a remote directory",
1150 " [ <directory-name> ]\n"
1151 " List the contents of a specified directory on the server.\n"
1152 " If <directory-name> is not given, the current working directory\n"
1153 " will be listed.\n",
1157 "exit", TRUE
, "bye", NULL
, sftp_cmd_quit
1160 "get", TRUE
, "download a file from the server to your local machine",
1161 " <filename> [ <local-filename> ]\n"
1162 " Downloads a file on the server and stores it locally under\n"
1163 " the same name, or under a different one if you supply the\n"
1164 " argument <local-filename>.\n",
1168 "help", TRUE
, "give help",
1169 " [ <command> [ <command> ... ] ]\n"
1170 " Give general help if no commands are specified.\n"
1171 " If one or more commands are specified, give specific help on\n"
1172 " those particular commands.\n",
1176 "lcd", TRUE
, "change local working directory",
1177 " <local-directory-name>\n"
1178 " Change the local working directory of the PSFTP program (the\n"
1179 " default location where the \"get\" command will save files).\n",
1183 "lpwd", TRUE
, "print local working directory",
1185 " Print the local working directory of the PSFTP program (the\n"
1186 " default location where the \"get\" command will save files).\n",
1190 "ls", TRUE
, "dir", NULL
,
1194 "mkdir", TRUE
, "create a directory on the remote server",
1195 " <directory-name>\n"
1196 " Creates a directory with the given name on the server.\n",
1200 "mv", TRUE
, "move or rename a file on the remote server",
1201 " <source-filename> <destination-filename>\n"
1202 " Moves or renames the file <source-filename> on the server,\n"
1203 " so that it is accessible under the name <destination-filename>.\n",
1207 "open", TRUE
, "connect to a host",
1208 " [<user>@]<hostname>\n"
1209 " Establishes an SFTP connection to a given host. Only usable\n"
1210 " when you did not already specify a host name on the command\n"
1215 "put", TRUE
, "upload a file from your local machine to the server",
1216 " <filename> [ <remote-filename> ]\n"
1217 " Uploads a file to the server and stores it there under\n"
1218 " the same name, or under a different one if you supply the\n"
1219 " argument <remote-filename>.\n",
1223 "pwd", TRUE
, "print your remote working directory",
1225 " Print the current remote working directory for your SFTP session.\n",
1229 "quit", TRUE
, "bye", NULL
,
1233 "reget", TRUE
, "continue downloading a file",
1234 " <filename> [ <local-filename> ]\n"
1235 " Works exactly like the \"get\" command, but the local file\n"
1236 " must already exist. The download will begin at the end of the\n"
1237 " file. This is for resuming a download that was interrupted.\n",
1241 "ren", TRUE
, "mv", NULL
,
1245 "rename", FALSE
, "mv", NULL
,
1249 "reput", TRUE
, "continue uploading a file",
1250 " <filename> [ <remote-filename> ]\n"
1251 " Works exactly like the \"put\" command, but the remote file\n"
1252 " must already exist. The upload will begin at the end of the\n"
1253 " file. This is for resuming an upload that was interrupted.\n",
1257 "rm", TRUE
, "del", NULL
,
1261 "rmdir", TRUE
, "remove a directory on the remote server",
1262 " <directory-name>\n"
1263 " Removes the directory with the given name on the server.\n"
1264 " The directory will not be removed unless it is empty.\n",
1269 const struct sftp_cmd_lookup
*lookup_command(char *name
)
1274 j
= sizeof(sftp_lookup
) / sizeof(*sftp_lookup
);
1277 cmp
= strcmp(name
, sftp_lookup
[k
].name
);
1283 return &sftp_lookup
[k
];
1289 static int sftp_cmd_help(struct sftp_command
*cmd
)
1292 if (cmd
->nwords
== 1) {
1294 * Give short help on each command.
1298 for (i
= 0; i
< sizeof(sftp_lookup
) / sizeof(*sftp_lookup
); i
++) {
1300 if (!sftp_lookup
[i
].listed
)
1302 len
= strlen(sftp_lookup
[i
].name
);
1306 for (i
= 0; i
< sizeof(sftp_lookup
) / sizeof(*sftp_lookup
); i
++) {
1307 const struct sftp_cmd_lookup
*lookup
;
1308 if (!sftp_lookup
[i
].listed
)
1310 lookup
= &sftp_lookup
[i
];
1311 printf("%-*s", maxlen
+2, lookup
->name
);
1312 if (lookup
->longhelp
== NULL
)
1313 lookup
= lookup_command(lookup
->shorthelp
);
1314 printf("%s\n", lookup
->shorthelp
);
1318 * Give long help on specific commands.
1320 for (i
= 1; i
< cmd
->nwords
; i
++) {
1321 const struct sftp_cmd_lookup
*lookup
;
1322 lookup
= lookup_command(cmd
->words
[i
]);
1324 printf("help: %s: command not found\n", cmd
->words
[i
]);
1326 printf("%s", lookup
->name
);
1327 if (lookup
->longhelp
== NULL
)
1328 lookup
= lookup_command(lookup
->shorthelp
);
1329 printf("%s", lookup
->longhelp
);
1336 /* ----------------------------------------------------------------------
1337 * Command line reading and parsing.
1339 struct sftp_command
*sftp_getcmd(FILE *fp
, int mode
, int modeflags
)
1342 int linelen
, linesize
;
1343 struct sftp_command
*cmd
;
1347 if ((mode
== 0) || (modeflags
& 1)) {
1352 cmd
= snew(struct sftp_command
);
1358 linesize
= linelen
= 0;
1364 line
= sresize(line
, linesize
, char);
1365 ret
= fgets(line
+ linelen
, linesize
- linelen
, fp
);
1367 if (!ret
|| (linelen
== 0 && line
[0] == '\0')) {
1368 cmd
->obey
= sftp_cmd_quit
;
1369 if ((mode
== 0) || (modeflags
& 1))
1371 return cmd
; /* eof */
1373 len
= linelen
+ strlen(line
+ linelen
);
1375 if (line
[linelen
- 1] == '\n') {
1377 line
[linelen
] = '\0';
1381 if (modeflags
& 1) {
1382 printf("%s\n", line
);
1386 while (*p
&& (*p
== ' ' || *p
== '\t'))
1391 * Special case: the ! command. This is always parsed as
1392 * exactly two words: one containing the !, and the second
1393 * containing everything else on the line.
1395 cmd
->nwords
= cmd
->wordssize
= 2;
1396 cmd
->words
= sresize(cmd
->words
, cmd
->wordssize
, char *);
1397 cmd
->words
[0] = "!";
1398 cmd
->words
[1] = p
+1;
1402 * Parse the command line into words. The syntax is:
1403 * - double quotes are removed, but cause spaces within to be
1404 * treated as non-separating.
1405 * - a double-doublequote pair is a literal double quote, inside
1406 * _or_ outside quotes. Like this:
1408 * firstword "second word" "this has ""quotes"" in" and""this""
1414 * >this has "quotes" in<
1418 /* skip whitespace */
1419 while (*p
&& (*p
== ' ' || *p
== '\t'))
1421 /* mark start of word */
1422 q
= r
= p
; /* q sits at start, r writes word */
1425 if (!quoting
&& (*p
== ' ' || *p
== '\t'))
1426 break; /* reached end of word */
1427 else if (*p
== '"' && p
[1] == '"')
1428 p
+= 2, *r
++ = '"'; /* a literal quote */
1430 p
++, quoting
= !quoting
;
1435 p
++; /* skip over the whitespace */
1437 if (cmd
->nwords
>= cmd
->wordssize
) {
1438 cmd
->wordssize
= cmd
->nwords
+ 16;
1439 cmd
->words
= sresize(cmd
->words
, cmd
->wordssize
, char *);
1441 cmd
->words
[cmd
->nwords
++] = q
;
1446 * Now parse the first word and assign a function.
1449 if (cmd
->nwords
== 0)
1450 cmd
->obey
= sftp_cmd_null
;
1452 const struct sftp_cmd_lookup
*lookup
;
1453 lookup
= lookup_command(cmd
->words
[0]);
1455 cmd
->obey
= sftp_cmd_unknown
;
1457 cmd
->obey
= lookup
->obey
;
1463 static int do_sftp_init(void)
1465 struct sftp_packet
*pktin
;
1466 struct sftp_request
*req
, *rreq
;
1469 * Do protocol initialisation.
1473 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
1474 return 1; /* failure */
1478 * Find out where our home directory is.
1480 sftp_register(req
= fxp_realpath_send("."));
1481 rreq
= sftp_find_request(pktin
= sftp_recv());
1482 assert(rreq
== req
);
1483 homedir
= fxp_realpath_recv(pktin
, rreq
);
1487 "Warning: failed to resolve home directory: %s\n",
1489 homedir
= dupstr(".");
1491 printf("Remote working directory is %s\n", homedir
);
1493 pwd
= dupstr(homedir
);
1497 void do_sftp(int mode
, int modeflags
, char *batchfile
)
1507 /* ------------------------------------------------------------------
1508 * Now we're ready to do Real Stuff.
1511 struct sftp_command
*cmd
;
1512 cmd
= sftp_getcmd(stdin
, 0, 0);
1515 if (cmd
->obey(cmd
) < 0)
1519 fp
= fopen(batchfile
, "r");
1521 printf("Fatal: unable to open %s\n", batchfile
);
1525 struct sftp_command
*cmd
;
1526 cmd
= sftp_getcmd(fp
, mode
, modeflags
);
1529 ret
= cmd
->obey(cmd
);
1533 if (!(modeflags
& 2))
1542 /* ----------------------------------------------------------------------
1543 * Dirty bits: integration with PuTTY.
1546 static int verbose
= 0;
1549 * Print an error message and perform a fatal exit.
1551 void fatalbox(char *fmt
, ...)
1556 str
= dupvprintf(fmt
, ap
);
1557 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1560 fputs(str2
, stderr
);
1565 void modalfatalbox(char *fmt
, ...)
1570 str
= dupvprintf(fmt
, ap
);
1571 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1574 fputs(str2
, stderr
);
1579 void connection_fatal(void *frontend
, char *fmt
, ...)
1584 str
= dupvprintf(fmt
, ap
);
1585 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1588 fputs(str2
, stderr
);
1594 void ldisc_send(void *handle
, char *buf
, int len
, int interactive
)
1597 * This is only here because of the calls to ldisc_send(NULL,
1598 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
1599 * ldisc as an ldisc. So if we get called with any real data, I
1600 * want to know about it.
1606 * In psftp, all agent requests should be synchronous, so this is a
1607 * never-called stub.
1609 void agent_schedule_callback(void (*callback
)(void *, void *, int),
1610 void *callback_ctx
, void *data
, int len
)
1612 assert(!"We shouldn't be here");
1616 * Receive a block of data from the SSH link. Block until all data
1619 * To do this, we repeatedly call the SSH protocol module, with our
1620 * own trap in from_backend() to catch the data that comes back. We
1621 * do this until we have enough data.
1624 static unsigned char *outptr
; /* where to put the data */
1625 static unsigned outlen
; /* how much data required */
1626 static unsigned char *pending
= NULL
; /* any spare data */
1627 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
1628 int from_backend(void *frontend
, int is_stderr
, const char *data
, int datalen
)
1630 unsigned char *p
= (unsigned char *) data
;
1631 unsigned len
= (unsigned) datalen
;
1636 * stderr data is just spouted to local stderr and otherwise
1640 fwrite(data
, 1, len
, stderr
);
1645 * If this is before the real session begins, just return.
1651 unsigned used
= outlen
;
1654 memcpy(outptr
, p
, used
);
1662 if (pendsize
< pendlen
+ len
) {
1663 pendsize
= pendlen
+ len
+ 4096;
1664 pending
= sresize(pending
, pendsize
, unsigned char);
1666 memcpy(pending
+ pendlen
, p
, len
);
1672 int sftp_recvdata(char *buf
, int len
)
1674 outptr
= (unsigned char *) buf
;
1678 * See if the pending-input block contains some of what we
1682 unsigned pendused
= pendlen
;
1683 if (pendused
> outlen
)
1685 memcpy(outptr
, pending
, pendused
);
1686 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
1689 pendlen
-= pendused
;
1699 while (outlen
> 0) {
1700 if (ssh_sftp_loop_iteration() < 0)
1701 return 0; /* doom */
1706 int sftp_senddata(char *buf
, int len
)
1708 back
->send(backhandle
, (unsigned char *) buf
, len
);
1713 * Short description of parameters.
1715 static void usage(void)
1717 printf("PuTTY Secure File Transfer (SFTP) client\n");
1718 printf("%s\n", ver
);
1719 printf("Usage: psftp [options] user@host\n");
1720 printf("Options:\n");
1721 printf(" -b file use specified batchfile\n");
1722 printf(" -bc output batchfile commands\n");
1723 printf(" -be don't stop batchfile processing if errors\n");
1724 printf(" -v show verbose messages\n");
1725 printf(" -load sessname Load settings from saved session\n");
1726 printf(" -l user connect with specified username\n");
1727 printf(" -P port connect to specified port\n");
1728 printf(" -pw passw login with specified password\n");
1729 printf(" -1 -2 force use of particular SSH protocol version\n");
1730 printf(" -C enable compression\n");
1731 printf(" -i key private key file for authentication\n");
1732 printf(" -batch disable all interactive prompts\n");
1737 * Connect to a host.
1739 static int psftp_connect(char *userhost
, char *user
, int portnumber
)
1741 char *host
, *realhost
;
1744 /* Separate host and username */
1746 host
= strrchr(host
, '@');
1752 printf("psftp: multiple usernames specified; using \"%s\"\n",
1758 /* Try to load settings for this host */
1759 do_defaults(host
, &cfg
);
1760 if (cfg
.host
[0] == '\0') {
1761 /* No settings for this host; use defaults */
1762 do_defaults(NULL
, &cfg
);
1763 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
1764 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
1768 * Force use of SSH. (If they got the protocol wrong we assume the
1769 * port is useless too.)
1771 if (cfg
.protocol
!= PROT_SSH
) {
1772 cfg
.protocol
= PROT_SSH
;
1777 * Enact command-line overrides.
1779 cmdline_run_saved(&cfg
);
1782 * Trim leading whitespace off the hostname if it's there.
1785 int space
= strspn(cfg
.host
, " \t");
1786 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
1789 /* See if host is of the form user@host */
1790 if (cfg
.host
[0] != '\0') {
1791 char *atsign
= strchr(cfg
.host
, '@');
1792 /* Make sure we're not overflowing the user field */
1794 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
1795 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
1796 cfg
.username
[atsign
- cfg
.host
] = '\0';
1798 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
1803 * Trim a colon suffix off the hostname if it's there.
1805 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
1808 * Remove any remaining whitespace from the hostname.
1812 while (cfg
.host
[p2
] != '\0') {
1813 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
1814 cfg
.host
[p1
] = cfg
.host
[p2
];
1819 cfg
.host
[p1
] = '\0';
1823 if (user
!= NULL
&& user
[0] != '\0') {
1824 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
1825 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
1827 if (!cfg
.username
[0]) {
1828 printf("login as: ");
1830 if (!fgets(cfg
.username
, sizeof(cfg
.username
), stdin
)) {
1831 fprintf(stderr
, "psftp: aborting\n");
1834 int len
= strlen(cfg
.username
);
1835 if (cfg
.username
[len
- 1] == '\n')
1836 cfg
.username
[len
- 1] = '\0';
1841 cfg
.port
= portnumber
;
1843 /* SFTP uses SSH2 by default always */
1847 * Disable scary things which shouldn't be enabled for simple
1848 * things like SCP and SFTP: agent forwarding, port forwarding,
1851 cfg
.x11_forward
= 0;
1853 cfg
.portfwd
[0] = cfg
.portfwd
[1] = '\0';
1855 /* Set up subsystem name. */
1856 strcpy(cfg
.remote_cmd
, "sftp");
1857 cfg
.ssh_subsys
= TRUE
;
1861 * Set up fallback option, for SSH1 servers or servers with the
1862 * sftp subsystem not enabled but the server binary installed
1863 * in the usual place. We only support fallback on Unix
1864 * systems, and we use a kludgy piece of shellery which should
1865 * try to find sftp-server in various places (the obvious
1866 * systemwide spots /usr/lib and /usr/local/lib, and then the
1867 * user's PATH) and finally give up.
1869 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
1870 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
1873 * the idea being that this will attempt to use either of the
1874 * obvious pathnames and then give up, and when it does give up
1875 * it will print the preferred pathname in the error messages.
1877 cfg
.remote_cmd_ptr2
=
1878 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
1879 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
1881 cfg
.ssh_subsys2
= FALSE
;
1883 back
= &ssh_backend
;
1885 err
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
, &realhost
,0);
1887 fprintf(stderr
, "ssh_init: %s\n", err
);
1890 logctx
= log_init(NULL
, &cfg
);
1891 back
->provide_logctx(backhandle
, logctx
);
1892 console_provide_logctx(logctx
);
1893 while (!back
->sendok(backhandle
)) {
1894 if (ssh_sftp_loop_iteration() < 0) {
1895 fprintf(stderr
, "ssh_init: error during SSH connection setup\n");
1899 if (verbose
&& realhost
!= NULL
)
1900 printf("Connected to %s\n", realhost
);
1904 void cmdline_error(char *p
, ...)
1907 fprintf(stderr
, "psftp: ");
1909 vfprintf(stderr
, p
, ap
);
1911 fprintf(stderr
, "\n try typing \"psftp -h\" for help\n");
1916 * Main program. Parse arguments etc.
1918 int psftp_main(int argc
, char *argv
[])
1922 char *userhost
, *user
;
1925 char *batchfile
= NULL
;
1928 flags
= FLAG_STDERR
| FLAG_INTERACTIVE
| FLAG_SYNCAGENT
;
1929 cmdline_tooltype
= TOOLTYPE_FILETRANSFER
;
1930 ssh_get_line
= &console_get_line
;
1933 userhost
= user
= NULL
;
1936 for (i
= 1; i
< argc
; i
++) {
1938 if (argv
[i
][0] != '-') {
1942 userhost
= dupstr(argv
[i
]);
1945 ret
= cmdline_process_param(argv
[i
], i
+1<argc?argv
[i
+1]:NULL
, 1, &cfg
);
1947 cmdline_error("option \"%s\" requires an argument", argv
[i
]);
1948 } else if (ret
== 2) {
1949 i
++; /* skip next argument */
1950 } else if (ret
== 1) {
1951 /* We have our own verbosity in addition to `flags'. */
1952 if (flags
& FLAG_VERBOSE
)
1954 } else if (strcmp(argv
[i
], "-h") == 0 ||
1955 strcmp(argv
[i
], "-?") == 0) {
1957 } else if (strcmp(argv
[i
], "-batch") == 0) {
1958 console_batch_mode
= 1;
1959 } else if (strcmp(argv
[i
], "-b") == 0 && i
+ 1 < argc
) {
1961 batchfile
= argv
[++i
];
1962 } else if (strcmp(argv
[i
], "-bc") == 0) {
1963 modeflags
= modeflags
| 1;
1964 } else if (strcmp(argv
[i
], "-be") == 0) {
1965 modeflags
= modeflags
| 2;
1966 } else if (strcmp(argv
[i
], "--") == 0) {
1970 cmdline_error("unknown option \"%s\"", argv
[i
]);
1978 * If a user@host string has already been provided, connect to
1982 if (psftp_connect(userhost
, user
, portnumber
))
1987 printf("psftp: no hostname specified; use \"open host.name\""
1991 do_sftp(mode
, modeflags
, batchfile
);
1993 if (back
!= NULL
&& back
->socket(backhandle
) != NULL
) {
1995 back
->special(backhandle
, TS_EOF
);
1996 sftp_recvdata(&ch
, 1);