2 * psftp.c: (platform-independent) 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);
28 void do_sftp_cleanup();
30 /* ----------------------------------------------------------------------
36 static void *backhandle
;
39 /* ----------------------------------------------------------------------
40 * Higher-level helper functions used in commands.
44 * Determine whether a string is entirely composed of dots.
46 static int is_dots(char *str
)
48 return str
[strspn(str
, ".")] == '\0';
52 * Attempt to canonify a pathname starting from the pwd. If
53 * canonification fails, at least fall back to returning a _valid_
54 * pathname (though it may be ugly, eg /home/simon/../foobar).
56 char *canonify(char *name
)
58 char *fullname
, *canonname
;
59 struct sftp_packet
*pktin
;
60 struct sftp_request
*req
, *rreq
;
63 fullname
= dupstr(name
);
66 if (pwd
[strlen(pwd
) - 1] == '/')
70 fullname
= dupcat(pwd
, slash
, name
, NULL
);
73 sftp_register(req
= fxp_realpath_send(fullname
));
74 rreq
= sftp_find_request(pktin
= sftp_recv());
76 canonname
= fxp_realpath_recv(pktin
, rreq
);
83 * Attempt number 2. Some FXP_REALPATH implementations
84 * (glibc-based ones, in particular) require the _whole_
85 * path to point to something that exists, whereas others
86 * (BSD-based) only require all but the last component to
87 * exist. So if the first call failed, we should strip off
88 * everything from the last slash onwards and try again,
89 * then put the final component back on.
93 * - if the last component is "/." or "/..", then we don't
94 * bother trying this because there's no way it can work.
96 * - if the thing actually ends with a "/", we remove it
97 * before we start. Except if the string is "/" itself
98 * (although I can't see why we'd have got here if so,
99 * because surely "/" would have worked the first
100 * time?), in which case we don't bother.
102 * - if there's no slash in the string at all, give up in
103 * confusion (we expect at least one because of the way
104 * we constructed the string).
110 i
= strlen(fullname
);
111 if (i
> 2 && fullname
[i
- 1] == '/')
112 fullname
[--i
] = '\0'; /* strip trailing / unless at pos 0 */
113 while (i
> 0 && fullname
[--i
] != '/');
116 * Give up on special cases.
118 if (fullname
[i
] != '/' || /* no slash at all */
119 !strcmp(fullname
+ i
, "/.") || /* ends in /. */
120 !strcmp(fullname
+ i
, "/..") || /* ends in /.. */
121 !strcmp(fullname
, "/")) {
126 * Now i points at the slash. Deal with the final special
127 * case i==0 (ie the whole path was "/nonexistentfile").
129 fullname
[i
] = '\0'; /* separate the string */
131 sftp_register(req
= fxp_realpath_send("/"));
133 sftp_register(req
= fxp_realpath_send(fullname
));
135 rreq
= sftp_find_request(pktin
= sftp_recv());
137 canonname
= fxp_realpath_recv(pktin
, rreq
);
140 return fullname
; /* even that failed; give up */
143 * We have a canonical name for all but the last path
144 * component. Concatenate the last component and return.
146 returnname
= dupcat(canonname
,
147 canonname
[strlen(canonname
) - 1] ==
148 '/' ?
"" : "/", fullname
+ i
+ 1, NULL
);
156 * Return a pointer to the portion of str that comes after the last
157 * slash (or backslash or colon, if `local' is TRUE).
159 static char *stripslashes(char *str
, int local
)
164 p
= strchr(str
, ':');
168 p
= strrchr(str
, '/');
172 p
= strrchr(str
, '\\');
180 * qsort comparison routine for fxp_name structures. Sorts by real
183 static int sftp_name_compare(const void *av
, const void *bv
)
185 const struct fxp_name
*const *a
= (const struct fxp_name
*const *) av
;
186 const struct fxp_name
*const *b
= (const struct fxp_name
*const *) bv
;
187 return strcmp((*a
)->filename
, (*b
)->filename
);
191 * Likewise, but for a bare char *.
193 static int bare_name_compare(const void *av
, const void *bv
)
195 const char **a
= (const char **) av
;
196 const char **b
= (const char **) bv
;
197 return strcmp(*a
, *b
);
200 /* ----------------------------------------------------------------------
201 * The meat of the `get' and `put' commands.
203 int sftp_get_file(char *fname
, char *outfname
, int recurse
, int restart
)
205 struct fxp_handle
*fh
;
206 struct sftp_packet
*pktin
;
207 struct sftp_request
*req
, *rreq
;
208 struct fxp_xfer
*xfer
;
214 * In recursive mode, see if we're dealing with a directory.
215 * (If we're not in recursive mode, we need not even check: the
216 * subsequent FXP_OPEN will return a usable error message.)
219 struct fxp_attrs attrs
;
222 sftp_register(req
= fxp_stat_send(fname
));
223 rreq
= sftp_find_request(pktin
= sftp_recv());
225 result
= fxp_stat_recv(pktin
, rreq
, &attrs
);
227 (attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) &&
228 (attrs
.permissions
& 0040000)) {
230 struct fxp_handle
*dirhandle
;
231 int nnames
, namesize
;
232 struct fxp_name
**ournames
;
233 struct fxp_names
*names
;
237 * First, attempt to create the destination directory,
238 * unless it already exists.
240 if (file_type(outfname
) != FILE_TYPE_DIRECTORY
&&
241 !create_directory(outfname
)) {
242 printf("%s: Cannot create directory\n", outfname
);
247 * Now get the list of filenames in the remote
250 sftp_register(req
= fxp_opendir_send(fname
));
251 rreq
= sftp_find_request(pktin
= sftp_recv());
253 dirhandle
= fxp_opendir_recv(pktin
, rreq
);
256 printf("%s: unable to open directory: %s\n",
260 nnames
= namesize
= 0;
265 sftp_register(req
= fxp_readdir_send(dirhandle
));
266 rreq
= sftp_find_request(pktin
= sftp_recv());
268 names
= fxp_readdir_recv(pktin
, rreq
);
271 if (fxp_error_type() == SSH_FX_EOF
)
273 printf("%s: reading directory: %s\n", fname
, fxp_error());
277 if (names
->nnames
== 0) {
278 fxp_free_names(names
);
281 if (nnames
+ names
->nnames
>= namesize
) {
282 namesize
+= names
->nnames
+ 128;
283 ournames
= sresize(ournames
, namesize
, struct fxp_name
*);
285 for (i
= 0; i
< names
->nnames
; i
++)
286 if (!is_dots(names
->names
[i
].filename
))
287 ournames
[nnames
++] = fxp_dup_name(&names
->names
[i
]);
288 fxp_free_names(names
);
290 sftp_register(req
= fxp_close_send(dirhandle
));
291 rreq
= sftp_find_request(pktin
= sftp_recv());
293 fxp_close_recv(pktin
, rreq
);
296 * Sort the names into a clear order. This ought to
297 * make things more predictable when we're doing a
298 * reget of the same directory, just in case two
299 * readdirs on the same remote directory return a
302 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_name_compare
);
305 * If we're in restart mode, find the last filename on
306 * this list that already exists. We may have to do a
307 * reget on _that_ file, but shouldn't have to do
308 * anything on the previous files.
310 * If none of them exists, of course, we start at 0.
316 nextoutfname
= dir_file_cat(outfname
, ournames
[i
]->filename
);
317 ret
= (file_type(nextoutfname
) == FILE_TYPE_NONEXISTENT
);
327 * Now we're ready to recurse. Starting at ournames[i]
328 * and continuing on to the end of the list, we
329 * construct a new source and target file name, and
330 * call sftp_get_file again.
332 for (; i
< nnames
; i
++) {
333 char *nextfname
, *nextoutfname
;
336 nextfname
= dupcat(fname
, "/", ournames
[i
]->filename
, NULL
);
337 nextoutfname
= dir_file_cat(outfname
, ournames
[i
]->filename
);
338 ret
= sftp_get_file(nextfname
, nextoutfname
, recurse
, restart
);
339 restart
= FALSE
; /* after first partial file, do full */
343 for (i
= 0; i
< nnames
; i
++) {
344 fxp_free_name(ournames
[i
]);
352 * Done this recursion level. Free everything.
354 for (i
= 0; i
< nnames
; i
++) {
355 fxp_free_name(ournames
[i
]);
363 sftp_register(req
= fxp_open_send(fname
, SSH_FXF_READ
));
364 rreq
= sftp_find_request(pktin
= sftp_recv());
366 fh
= fxp_open_recv(pktin
, rreq
);
369 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
);
382 sftp_register(req
= fxp_close_send(fh
));
383 rreq
= sftp_find_request(pktin
= sftp_recv());
385 fxp_close_recv(pktin
, rreq
);
392 fseek(fp
, 0L, SEEK_END
);
394 printf("reget: restarting at file position %ld\n", posn
);
395 offset
= uint64_make(0, posn
);
397 offset
= uint64_make(0, 0);
400 printf("remote:%s => local:%s\n", fname
, outfname
);
403 * FIXME: we can use FXP_FSTAT here to get the file size, and
404 * thus put up a progress bar.
407 xfer
= xfer_download_init(fh
, offset
);
408 while (!xfer_done(xfer
)) {
413 xfer_download_queue(xfer
);
415 ret
= xfer_download_gotpkt(xfer
, pktin
);
418 printf("error while reading: %s\n", fxp_error());
422 while (xfer_download_data(xfer
, &vbuf
, &len
)) {
423 unsigned char *buf
= (unsigned char *)vbuf
;
427 wlen
= fwrite(buf
+ wpos
, 1, len
- wpos
, fp
);
429 printf("error while writing local file\n");
431 xfer_set_error(xfer
);
435 if (wpos
< len
) { /* we had an error */
437 xfer_set_error(xfer
);
448 sftp_register(req
= fxp_close_send(fh
));
449 rreq
= sftp_find_request(pktin
= sftp_recv());
451 fxp_close_recv(pktin
, rreq
);
456 int sftp_put_file(char *fname
, char *outfname
, int recurse
, int restart
)
458 struct fxp_handle
*fh
;
459 struct fxp_xfer
*xfer
;
460 struct sftp_packet
*pktin
;
461 struct sftp_request
*req
, *rreq
;
467 * In recursive mode, see if we're dealing with a directory.
468 * (If we're not in recursive mode, we need not even check: the
469 * subsequent fopen will return an error message.)
471 if (recurse
&& file_type(fname
) == FILE_TYPE_DIRECTORY
) {
472 struct fxp_attrs attrs
;
474 int nnames
, namesize
;
475 char *name
, **ournames
;
480 * First, attempt to create the destination directory,
481 * unless it already exists.
483 sftp_register(req
= fxp_stat_send(outfname
));
484 rreq
= sftp_find_request(pktin
= sftp_recv());
486 result
= fxp_stat_recv(pktin
, rreq
, &attrs
);
488 !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) ||
489 !(attrs
.permissions
& 0040000)) {
490 sftp_register(req
= fxp_mkdir_send(outfname
));
491 rreq
= sftp_find_request(pktin
= sftp_recv());
493 result
= fxp_mkdir_recv(pktin
, rreq
);
496 printf("%s: create directory: %s\n", outfname
, fxp_error());
502 * Now get the list of filenames in the local directory.
504 dh
= open_directory(fname
);
506 printf("%s: unable to open directory\n", fname
);
509 nnames
= namesize
= 0;
511 while ((name
= read_filename(dh
)) != NULL
) {
512 if (nnames
>= namesize
) {
514 ournames
= sresize(ournames
, namesize
, char *);
516 ournames
[nnames
++] = name
;
521 * Sort the names into a clear order. This ought to make
522 * things more predictable when we're doing a reput of the
523 * same directory, just in case two readdirs on the same
524 * local directory return a different order.
526 qsort(ournames
, nnames
, sizeof(*ournames
), bare_name_compare
);
529 * If we're in restart mode, find the last filename on this
530 * list that already exists. We may have to do a reput on
531 * _that_ file, but shouldn't have to do anything on the
534 * If none of them exists, of course, we start at 0.
539 nextoutfname
= dupcat(outfname
, "/", ournames
[i
], NULL
);
540 sftp_register(req
= fxp_stat_send(nextoutfname
));
541 rreq
= sftp_find_request(pktin
= sftp_recv());
543 result
= fxp_stat_recv(pktin
, rreq
, &attrs
);
553 * Now we're ready to recurse. Starting at ournames[i]
554 * and continuing on to the end of the list, we
555 * construct a new source and target file name, and
556 * call sftp_put_file again.
558 for (; i
< nnames
; i
++) {
559 char *nextfname
, *nextoutfname
;
562 nextfname
= dir_file_cat(fname
, ournames
[i
]);
563 nextoutfname
= dupcat(outfname
, "/", ournames
[i
], NULL
);
564 ret
= sftp_put_file(nextfname
, nextoutfname
, recurse
, restart
);
565 restart
= FALSE
; /* after first partial file, do full */
569 for (i
= 0; i
< nnames
; i
++) {
578 * Done this recursion level. Free everything.
580 for (i
= 0; i
< nnames
; i
++) {
588 fp
= fopen(fname
, "rb");
590 printf("local: unable to open %s\n", fname
);
594 sftp_register(req
= fxp_open_send(outfname
, SSH_FXF_WRITE
));
596 sftp_register(req
= fxp_open_send(outfname
, SSH_FXF_WRITE
|
597 SSH_FXF_CREAT
| SSH_FXF_TRUNC
));
599 rreq
= sftp_find_request(pktin
= sftp_recv());
601 fh
= fxp_open_recv(pktin
, rreq
);
604 printf("%s: %s\n", outfname
, fxp_error());
610 struct fxp_attrs attrs
;
613 sftp_register(req
= fxp_fstat_send(fh
));
614 rreq
= sftp_find_request(pktin
= sftp_recv());
616 ret
= fxp_fstat_recv(pktin
, rreq
, &attrs
);
619 printf("read size of %s: %s\n", outfname
, fxp_error());
622 if (!(attrs
.flags
& SSH_FILEXFER_ATTR_SIZE
)) {
623 printf("read size of %s: size was not given\n", outfname
);
627 uint64_decimal(offset
, decbuf
);
628 printf("reput: restarting at file position %s\n", decbuf
);
629 if (uint64_compare(offset
, uint64_make(0, LONG_MAX
)) > 0) {
630 printf("reput: remote file is larger than we can deal with\n");
633 if (fseek(fp
, offset
.lo
, SEEK_SET
) != 0)
634 fseek(fp
, 0, SEEK_END
); /* *shrug* */
636 offset
= uint64_make(0, 0);
639 printf("local:%s => remote:%s\n", fname
, outfname
);
642 * FIXME: we can use FXP_FSTAT here to get the file size, and
643 * thus put up a progress bar.
646 xfer
= xfer_upload_init(fh
, offset
);
648 while ((!err
&& !eof
) || !xfer_done(xfer
)) {
652 while (xfer_upload_ready(xfer
) && !err
&& !eof
) {
653 len
= fread(buffer
, 1, sizeof(buffer
), fp
);
655 printf("error while reading local file\n");
657 } else if (len
== 0) {
660 xfer_upload_data(xfer
, buffer
, len
);
664 if (!xfer_done(xfer
)) {
666 ret
= xfer_upload_gotpkt(xfer
, pktin
);
668 printf("error while writing: %s\n", fxp_error());
676 sftp_register(req
= fxp_close_send(fh
));
677 rreq
= sftp_find_request(pktin
= sftp_recv());
679 fxp_close_recv(pktin
, rreq
);
686 /* ----------------------------------------------------------------------
687 * Actual sftp commands.
689 struct sftp_command
{
691 int nwords
, wordssize
;
692 int (*obey
) (struct sftp_command
*); /* returns <0 to quit */
695 int sftp_cmd_null(struct sftp_command
*cmd
)
697 return 1; /* success */
700 int sftp_cmd_unknown(struct sftp_command
*cmd
)
702 printf("psftp: unknown command \"%s\"\n", cmd
->words
[0]);
703 return 0; /* failure */
706 int sftp_cmd_quit(struct sftp_command
*cmd
)
712 * List a directory. If no arguments are given, list pwd; otherwise
713 * list the directory given in words[1].
715 int sftp_cmd_ls(struct sftp_command
*cmd
)
717 struct fxp_handle
*dirh
;
718 struct fxp_names
*names
;
719 struct fxp_name
**ournames
;
720 int nnames
, namesize
;
722 struct sftp_packet
*pktin
;
723 struct sftp_request
*req
, *rreq
;
727 printf("psftp: not connected to a host; use \"open host.name\"\n");
736 cdir
= canonify(dir
);
738 printf("%s: %s\n", dir
, fxp_error());
742 printf("Listing directory %s\n", cdir
);
744 sftp_register(req
= fxp_opendir_send(cdir
));
745 rreq
= sftp_find_request(pktin
= sftp_recv());
747 dirh
= fxp_opendir_recv(pktin
, rreq
);
750 printf("Unable to open %s: %s\n", dir
, fxp_error());
752 nnames
= namesize
= 0;
757 sftp_register(req
= fxp_readdir_send(dirh
));
758 rreq
= sftp_find_request(pktin
= sftp_recv());
760 names
= fxp_readdir_recv(pktin
, rreq
);
763 if (fxp_error_type() == SSH_FX_EOF
)
765 printf("Reading directory %s: %s\n", dir
, fxp_error());
768 if (names
->nnames
== 0) {
769 fxp_free_names(names
);
773 if (nnames
+ names
->nnames
>= namesize
) {
774 namesize
+= names
->nnames
+ 128;
775 ournames
= sresize(ournames
, namesize
, struct fxp_name
*);
778 for (i
= 0; i
< names
->nnames
; i
++)
779 ournames
[nnames
++] = fxp_dup_name(&names
->names
[i
]);
781 fxp_free_names(names
);
783 sftp_register(req
= fxp_close_send(dirh
));
784 rreq
= sftp_find_request(pktin
= sftp_recv());
786 fxp_close_recv(pktin
, rreq
);
789 * Now we have our filenames. Sort them by actual file
790 * name, and then output the longname parts.
792 qsort(ournames
, nnames
, sizeof(*ournames
), sftp_name_compare
);
797 for (i
= 0; i
< nnames
; i
++) {
798 printf("%s\n", ournames
[i
]->longname
);
799 fxp_free_name(ournames
[i
]);
810 * Change directories. We do this by canonifying the new name, then
811 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
813 int sftp_cmd_cd(struct sftp_command
*cmd
)
815 struct fxp_handle
*dirh
;
816 struct sftp_packet
*pktin
;
817 struct sftp_request
*req
, *rreq
;
821 printf("psftp: not connected to a host; use \"open host.name\"\n");
826 dir
= dupstr(homedir
);
828 dir
= canonify(cmd
->words
[1]);
831 printf("%s: %s\n", dir
, fxp_error());
835 sftp_register(req
= fxp_opendir_send(dir
));
836 rreq
= sftp_find_request(pktin
= sftp_recv());
838 dirh
= fxp_opendir_recv(pktin
, rreq
);
841 printf("Directory %s: %s\n", dir
, fxp_error());
846 sftp_register(req
= fxp_close_send(dirh
));
847 rreq
= sftp_find_request(pktin
= sftp_recv());
849 fxp_close_recv(pktin
, rreq
);
853 printf("Remote directory is now %s\n", pwd
);
859 * Print current directory. Easy as pie.
861 int sftp_cmd_pwd(struct sftp_command
*cmd
)
864 printf("psftp: not connected to a host; use \"open host.name\"\n");
868 printf("Remote directory is %s\n", pwd
);
873 * Get a file and save it at the local end. We have two very
874 * similar commands here: `get' and `reget', which differ in that
875 * `reget' checks for the existence of the destination file and
876 * starts from where a previous aborted transfer left off.
878 int sftp_general_get(struct sftp_command
*cmd
, int restart
)
880 char *fname
, *origfname
, *outfname
;
885 printf("psftp: not connected to a host; use \"open host.name\"\n");
890 while (i
< cmd
->nwords
&& cmd
->words
[i
][0] == '-') {
891 if (!strcmp(cmd
->words
[i
], "--")) {
892 /* finish processing options */
895 } else if (!strcmp(cmd
->words
[i
], "-r")) {
898 printf("get: unrecognised option '%s'\n", cmd
->words
[i
]);
904 if (i
>= cmd
->nwords
) {
905 printf("get: expects a filename\n");
909 origfname
= cmd
->words
[i
++];
910 fname
= canonify(origfname
);
912 printf("%s: %s\n", origfname
, fxp_error());
916 outfname
= (i
>= cmd
->nwords ?
917 stripslashes(origfname
, 0) : cmd
->words
[i
++]);
919 ret
= sftp_get_file(fname
, outfname
, recurse
, restart
);
925 int sftp_cmd_get(struct sftp_command
*cmd
)
927 return sftp_general_get(cmd
, 0);
929 int sftp_cmd_reget(struct sftp_command
*cmd
)
931 return sftp_general_get(cmd
, 1);
935 * Send a file and store it at the remote end. We have two very
936 * similar commands here: `put' and `reput', which differ in that
937 * `reput' checks for the existence of the destination file and
938 * starts from where a previous aborted transfer left off.
940 int sftp_general_put(struct sftp_command
*cmd
, int restart
)
942 char *fname
, *origoutfname
, *outfname
;
947 printf("psftp: not connected to a host; use \"open host.name\"\n");
952 while (i
< cmd
->nwords
&& cmd
->words
[i
][0] == '-') {
953 if (!strcmp(cmd
->words
[i
], "--")) {
954 /* finish processing options */
957 } else if (!strcmp(cmd
->words
[i
], "-r")) {
960 printf("put: unrecognised option '%s'\n", cmd
->words
[i
]);
966 if (i
>= cmd
->nwords
) {
967 printf("put: expects a filename\n");
971 fname
= cmd
->words
[i
++];
972 origoutfname
= (i
>= cmd
->nwords ?
973 stripslashes(fname
, 1) : cmd
->words
[i
++]);
974 outfname
= canonify(origoutfname
);
976 printf("%s: %s\n", origoutfname
, fxp_error());
980 ret
= sftp_put_file(fname
, outfname
, recurse
, restart
);
986 int sftp_cmd_put(struct sftp_command
*cmd
)
988 return sftp_general_put(cmd
, 0);
990 int sftp_cmd_reput(struct sftp_command
*cmd
)
992 return sftp_general_put(cmd
, 1);
995 int sftp_cmd_mkdir(struct sftp_command
*cmd
)
998 struct sftp_packet
*pktin
;
999 struct sftp_request
*req
, *rreq
;
1003 printf("psftp: not connected to a host; use \"open host.name\"\n");
1007 if (cmd
->nwords
< 2) {
1008 printf("mkdir: expects a directory\n");
1012 dir
= canonify(cmd
->words
[1]);
1014 printf("%s: %s\n", dir
, fxp_error());
1018 sftp_register(req
= fxp_mkdir_send(dir
));
1019 rreq
= sftp_find_request(pktin
= sftp_recv());
1020 assert(rreq
== req
);
1021 result
= fxp_mkdir_recv(pktin
, rreq
);
1024 printf("mkdir %s: %s\n", dir
, fxp_error());
1033 int sftp_cmd_rmdir(struct sftp_command
*cmd
)
1036 struct sftp_packet
*pktin
;
1037 struct sftp_request
*req
, *rreq
;
1041 printf("psftp: not connected to a host; use \"open host.name\"\n");
1045 if (cmd
->nwords
< 2) {
1046 printf("rmdir: expects a directory\n");
1050 dir
= canonify(cmd
->words
[1]);
1052 printf("%s: %s\n", dir
, fxp_error());
1056 sftp_register(req
= fxp_rmdir_send(dir
));
1057 rreq
= sftp_find_request(pktin
= sftp_recv());
1058 assert(rreq
== req
);
1059 result
= fxp_rmdir_recv(pktin
, rreq
);
1062 printf("rmdir %s: %s\n", dir
, fxp_error());
1071 int sftp_cmd_rm(struct sftp_command
*cmd
)
1074 struct sftp_packet
*pktin
;
1075 struct sftp_request
*req
, *rreq
;
1079 printf("psftp: not connected to a host; use \"open host.name\"\n");
1083 if (cmd
->nwords
< 2) {
1084 printf("rm: expects a filename\n");
1088 fname
= canonify(cmd
->words
[1]);
1090 printf("%s: %s\n", fname
, fxp_error());
1094 sftp_register(req
= fxp_remove_send(fname
));
1095 rreq
= sftp_find_request(pktin
= sftp_recv());
1096 assert(rreq
== req
);
1097 result
= fxp_remove_recv(pktin
, rreq
);
1100 printf("rm %s: %s\n", fname
, fxp_error());
1109 int sftp_cmd_mv(struct sftp_command
*cmd
)
1111 char *srcfname
, *dstfname
;
1112 struct sftp_packet
*pktin
;
1113 struct sftp_request
*req
, *rreq
;
1117 printf("psftp: not connected to a host; use \"open host.name\"\n");
1121 if (cmd
->nwords
< 3) {
1122 printf("mv: expects two filenames\n");
1125 srcfname
= canonify(cmd
->words
[1]);
1127 printf("%s: %s\n", srcfname
, fxp_error());
1131 dstfname
= canonify(cmd
->words
[2]);
1133 printf("%s: %s\n", dstfname
, fxp_error());
1137 sftp_register(req
= fxp_rename_send(srcfname
, dstfname
));
1138 rreq
= sftp_find_request(pktin
= sftp_recv());
1139 assert(rreq
== req
);
1140 result
= fxp_rename_recv(pktin
, rreq
);
1143 char const *error
= fxp_error();
1144 struct fxp_attrs attrs
;
1147 * The move might have failed because dstfname pointed at a
1148 * directory. We check this possibility now: if dstfname
1149 * _is_ a directory, we re-attempt the move by appending
1150 * the basename of srcfname to dstfname.
1152 sftp_register(req
= fxp_stat_send(dstfname
));
1153 rreq
= sftp_find_request(pktin
= sftp_recv());
1154 assert(rreq
== req
);
1155 result
= fxp_stat_recv(pktin
, rreq
, &attrs
);
1158 (attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
) &&
1159 (attrs
.permissions
& 0040000)) {
1161 char *newname
, *newcanon
;
1162 printf("(destination %s is a directory)\n", dstfname
);
1163 p
= srcfname
+ strlen(srcfname
);
1164 while (p
> srcfname
&& p
[-1] != '/') p
--;
1165 newname
= dupcat(dstfname
, "/", p
, NULL
);
1166 newcanon
= canonify(newname
);
1170 dstfname
= newcanon
;
1172 sftp_register(req
= fxp_rename_send(srcfname
, dstfname
));
1173 rreq
= sftp_find_request(pktin
= sftp_recv());
1174 assert(rreq
== req
);
1175 result
= fxp_rename_recv(pktin
, rreq
);
1177 error
= result ? NULL
: fxp_error();
1181 printf("mv %s %s: %s\n", srcfname
, dstfname
, error
);
1187 printf("%s -> %s\n", srcfname
, dstfname
);
1194 int sftp_cmd_chmod(struct sftp_command
*cmd
)
1198 struct fxp_attrs attrs
;
1199 unsigned attrs_clr
, attrs_xor
, oldperms
, newperms
;
1200 struct sftp_packet
*pktin
;
1201 struct sftp_request
*req
, *rreq
;
1204 printf("psftp: not connected to a host; use \"open host.name\"\n");
1208 if (cmd
->nwords
< 3) {
1209 printf("chmod: expects a mode specifier and a filename\n");
1214 * Attempt to parse the mode specifier in cmd->words[1]. We
1215 * don't support the full horror of Unix chmod; instead we
1216 * support a much simpler syntax in which the user can either
1217 * specify an octal number, or a comma-separated sequence of
1218 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
1219 * _only_ be omitted if the only attribute mentioned is t,
1220 * since all others require a user/group/other specification.
1221 * Additionally, the s attribute may not be specified for any
1222 * [ugoa] specifications other than exactly u or exactly g.
1224 attrs_clr
= attrs_xor
= 0;
1225 mode
= cmd
->words
[1];
1226 if (mode
[0] >= '0' && mode
[0] <= '9') {
1227 if (mode
[strspn(mode
, "01234567")]) {
1228 printf("chmod: numeric file modes should"
1229 " contain digits 0-7 only\n");
1233 sscanf(mode
, "%o", &attrs_xor
);
1234 attrs_xor
&= attrs_clr
;
1237 char *modebegin
= mode
;
1238 unsigned subset
, perms
;
1242 while (*mode
&& *mode
!= ',' &&
1243 *mode
!= '+' && *mode
!= '-' && *mode
!= '=') {
1245 case 'u': subset
|= 04700; break; /* setuid, user perms */
1246 case 'g': subset
|= 02070; break; /* setgid, group perms */
1247 case 'o': subset
|= 00007; break; /* just other perms */
1248 case 'a': subset
|= 06777; break; /* all of the above */
1250 printf("chmod: file mode '%.*s' contains unrecognised"
1251 " user/group/other specifier '%c'\n",
1252 (int)strcspn(modebegin
, ","), modebegin
, *mode
);
1257 if (!*mode
|| *mode
== ',') {
1258 printf("chmod: file mode '%.*s' is incomplete\n",
1259 (int)strcspn(modebegin
, ","), modebegin
);
1263 if (!*mode
|| *mode
== ',') {
1264 printf("chmod: file mode '%.*s' is incomplete\n",
1265 (int)strcspn(modebegin
, ","), modebegin
);
1269 while (*mode
&& *mode
!= ',') {
1271 case 'r': perms
|= 00444; break;
1272 case 'w': perms
|= 00222; break;
1273 case 'x': perms
|= 00111; break;
1274 case 't': perms
|= 01000; subset
|= 01000; break;
1276 if ((subset
& 06777) != 04700 &&
1277 (subset
& 06777) != 02070) {
1278 printf("chmod: file mode '%.*s': set[ug]id bit should"
1279 " be used with exactly one of u or g only\n",
1280 (int)strcspn(modebegin
, ","), modebegin
);
1286 printf("chmod: file mode '%.*s' contains unrecognised"
1287 " permission specifier '%c'\n",
1288 (int)strcspn(modebegin
, ","), modebegin
, *mode
);
1293 if (!(subset
& 06777) && (perms
&~ subset
)) {
1294 printf("chmod: file mode '%.*s' contains no user/group/other"
1295 " specifier and permissions other than 't' \n",
1296 (int)strcspn(modebegin
, ","), modebegin
);
1307 attrs_xor
&= ~perms
;
1310 attrs_clr
|= subset
;
1314 if (*mode
) mode
++; /* eat comma */
1318 fname
= canonify(cmd
->words
[2]);
1320 printf("%s: %s\n", fname
, fxp_error());
1324 sftp_register(req
= fxp_stat_send(fname
));
1325 rreq
= sftp_find_request(pktin
= sftp_recv());
1326 assert(rreq
== req
);
1327 result
= fxp_stat_recv(pktin
, rreq
, &attrs
);
1329 if (!result
|| !(attrs
.flags
& SSH_FILEXFER_ATTR_PERMISSIONS
)) {
1330 printf("get attrs for %s: %s\n", fname
,
1331 result ?
"file permissions not provided" : fxp_error());
1336 attrs
.flags
= SSH_FILEXFER_ATTR_PERMISSIONS
; /* perms _only_ */
1337 oldperms
= attrs
.permissions
& 07777;
1338 attrs
.permissions
&= ~attrs_clr
;
1339 attrs
.permissions
^= attrs_xor
;
1340 newperms
= attrs
.permissions
& 07777;
1342 sftp_register(req
= fxp_setstat_send(fname
, attrs
));
1343 rreq
= sftp_find_request(pktin
= sftp_recv());
1344 assert(rreq
== req
);
1345 result
= fxp_setstat_recv(pktin
, rreq
);
1348 printf("set attrs for %s: %s\n", fname
, fxp_error());
1353 printf("%s: %04o -> %04o\n", fname
, oldperms
, newperms
);
1359 static int sftp_cmd_open(struct sftp_command
*cmd
)
1364 printf("psftp: already connected\n");
1368 if (cmd
->nwords
< 2) {
1369 printf("open: expects a host name\n");
1373 if (cmd
->nwords
> 2) {
1374 portnumber
= atoi(cmd
->words
[2]);
1375 if (portnumber
== 0) {
1376 printf("open: invalid port number\n");
1382 if (psftp_connect(cmd
->words
[1], NULL
, portnumber
)) {
1383 back
= NULL
; /* connection is already closed */
1384 return -1; /* this is fatal */
1390 static int sftp_cmd_lcd(struct sftp_command
*cmd
)
1392 char *currdir
, *errmsg
;
1394 if (cmd
->nwords
< 2) {
1395 printf("lcd: expects a local directory name\n");
1399 errmsg
= psftp_lcd(cmd
->words
[1]);
1401 printf("lcd: unable to change directory: %s\n", errmsg
);
1406 currdir
= psftp_getcwd();
1407 printf("New local directory is %s\n", currdir
);
1413 static int sftp_cmd_lpwd(struct sftp_command
*cmd
)
1417 currdir
= psftp_getcwd();
1418 printf("Current local directory is %s\n", currdir
);
1424 static int sftp_cmd_pling(struct sftp_command
*cmd
)
1428 exitcode
= system(cmd
->words
[1]);
1429 return (exitcode
== 0);
1432 static int sftp_cmd_help(struct sftp_command
*cmd
);
1434 static struct sftp_cmd_lookup
{
1437 * For help purposes, there are two kinds of command:
1439 * - primary commands, in which `longhelp' is non-NULL. In
1440 * this case `shorthelp' is descriptive text, and `longhelp'
1441 * is longer descriptive text intended to be printed after
1444 * - alias commands, in which `longhelp' is NULL. In this case
1445 * `shorthelp' is the name of a primary command, which
1446 * contains the help that should double up for this command.
1448 int listed
; /* do we list this in primary help? */
1451 int (*obey
) (struct sftp_command
*);
1454 * List of sftp commands. This is binary-searched so it MUST be
1458 "!", TRUE
, "run a local command",
1460 /* FIXME: this example is crap for non-Windows. */
1461 " Runs a local command. For example, \"!del myfile\".\n",
1465 "bye", TRUE
, "finish your SFTP session",
1467 " Terminates your SFTP session and quits the PSFTP program.\n",
1471 "cd", TRUE
, "change your remote working directory",
1472 " [ <New working directory> ]\n"
1473 " Change the remote working directory for your SFTP session.\n"
1474 " If a new working directory is not supplied, you will be\n"
1475 " returned to your home directory.\n",
1479 "chmod", TRUE
, "change file permissions and modes",
1480 " ( <octal-digits> | <modifiers> ) <filename>\n"
1481 " Change the file permissions on a file or directory.\n"
1482 " <octal-digits> can be any octal Unix permission specifier.\n"
1483 " Alternatively, <modifiers> can include:\n"
1484 " u+r make file readable by owning user\n"
1485 " u+w make file writable by owning user\n"
1486 " u+x make file executable by owning user\n"
1487 " u-r make file not readable by owning user\n"
1488 " [also u-w, u-x]\n"
1489 " g+r make file readable by members of owning group\n"
1490 " [also g+w, g+x, g-r, g-w, g-x]\n"
1491 " o+r make file readable by all other users\n"
1492 " [also o+w, o+x, o-r, o-w, o-x]\n"
1493 " a+r make file readable by absolutely everybody\n"
1494 " [also a+w, a+x, a-r, a-w, a-x]\n"
1495 " u+s enable the Unix set-user-ID bit\n"
1496 " u-s disable the Unix set-user-ID bit\n"
1497 " g+s enable the Unix set-group-ID bit\n"
1498 " g-s disable the Unix set-group-ID bit\n"
1499 " +t enable the Unix \"sticky bit\"\n"
1500 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1501 " more than one user for the same modifier (\"ug+w\"). You can\n"
1502 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1506 "del", TRUE
, "delete a file",
1508 " Delete a file.\n",
1512 "delete", FALSE
, "del", NULL
, sftp_cmd_rm
1515 "dir", TRUE
, "list contents of a remote directory",
1516 " [ <directory-name> ]\n"
1517 " List the contents of a specified directory on the server.\n"
1518 " If <directory-name> is not given, the current working directory\n"
1519 " will be listed.\n",
1523 "exit", TRUE
, "bye", NULL
, sftp_cmd_quit
1526 "get", TRUE
, "download a file from the server to your local machine",
1527 " <filename> [ <local-filename> ]\n"
1528 " Downloads a file on the server and stores it locally under\n"
1529 " the same name, or under a different one if you supply the\n"
1530 " argument <local-filename>.\n",
1534 "help", TRUE
, "give help",
1535 " [ <command> [ <command> ... ] ]\n"
1536 " Give general help if no commands are specified.\n"
1537 " If one or more commands are specified, give specific help on\n"
1538 " those particular commands.\n",
1542 "lcd", TRUE
, "change local working directory",
1543 " <local-directory-name>\n"
1544 " Change the local working directory of the PSFTP program (the\n"
1545 " default location where the \"get\" command will save files).\n",
1549 "lpwd", TRUE
, "print local working directory",
1551 " Print the local working directory of the PSFTP program (the\n"
1552 " default location where the \"get\" command will save files).\n",
1556 "ls", TRUE
, "dir", NULL
,
1560 "mkdir", TRUE
, "create a directory on the remote server",
1561 " <directory-name>\n"
1562 " Creates a directory with the given name on the server.\n",
1566 "mv", TRUE
, "move or rename a file on the remote server",
1567 " <source-filename> <destination-filename>\n"
1568 " Moves or renames the file <source-filename> on the server,\n"
1569 " so that it is accessible under the name <destination-filename>.\n",
1573 "open", TRUE
, "connect to a host",
1574 " [<user>@]<hostname> [<port>]\n"
1575 " Establishes an SFTP connection to a given host. Only usable\n"
1576 " when you did not already specify a host name on the command\n"
1581 "put", TRUE
, "upload a file from your local machine to the server",
1582 " <filename> [ <remote-filename> ]\n"
1583 " Uploads a file to the server and stores it there under\n"
1584 " the same name, or under a different one if you supply the\n"
1585 " argument <remote-filename>.\n",
1589 "pwd", TRUE
, "print your remote working directory",
1591 " Print the current remote working directory for your SFTP session.\n",
1595 "quit", TRUE
, "bye", NULL
,
1599 "reget", TRUE
, "continue downloading a file",
1600 " <filename> [ <local-filename> ]\n"
1601 " Works exactly like the \"get\" command, but the local file\n"
1602 " must already exist. The download will begin at the end of the\n"
1603 " file. This is for resuming a download that was interrupted.\n",
1607 "ren", TRUE
, "mv", NULL
,
1611 "rename", FALSE
, "mv", NULL
,
1615 "reput", TRUE
, "continue uploading a file",
1616 " <filename> [ <remote-filename> ]\n"
1617 " Works exactly like the \"put\" command, but the remote file\n"
1618 " must already exist. The upload will begin at the end of the\n"
1619 " file. This is for resuming an upload that was interrupted.\n",
1623 "rm", TRUE
, "del", NULL
,
1627 "rmdir", TRUE
, "remove a directory on the remote server",
1628 " <directory-name>\n"
1629 " Removes the directory with the given name on the server.\n"
1630 " The directory will not be removed unless it is empty.\n",
1635 const struct sftp_cmd_lookup
*lookup_command(char *name
)
1640 j
= sizeof(sftp_lookup
) / sizeof(*sftp_lookup
);
1643 cmp
= strcmp(name
, sftp_lookup
[k
].name
);
1649 return &sftp_lookup
[k
];
1655 static int sftp_cmd_help(struct sftp_command
*cmd
)
1658 if (cmd
->nwords
== 1) {
1660 * Give short help on each command.
1664 for (i
= 0; i
< sizeof(sftp_lookup
) / sizeof(*sftp_lookup
); i
++) {
1666 if (!sftp_lookup
[i
].listed
)
1668 len
= strlen(sftp_lookup
[i
].name
);
1672 for (i
= 0; i
< sizeof(sftp_lookup
) / sizeof(*sftp_lookup
); i
++) {
1673 const struct sftp_cmd_lookup
*lookup
;
1674 if (!sftp_lookup
[i
].listed
)
1676 lookup
= &sftp_lookup
[i
];
1677 printf("%-*s", maxlen
+2, lookup
->name
);
1678 if (lookup
->longhelp
== NULL
)
1679 lookup
= lookup_command(lookup
->shorthelp
);
1680 printf("%s\n", lookup
->shorthelp
);
1684 * Give long help on specific commands.
1686 for (i
= 1; i
< cmd
->nwords
; i
++) {
1687 const struct sftp_cmd_lookup
*lookup
;
1688 lookup
= lookup_command(cmd
->words
[i
]);
1690 printf("help: %s: command not found\n", cmd
->words
[i
]);
1692 printf("%s", lookup
->name
);
1693 if (lookup
->longhelp
== NULL
)
1694 lookup
= lookup_command(lookup
->shorthelp
);
1695 printf("%s", lookup
->longhelp
);
1702 /* ----------------------------------------------------------------------
1703 * Command line reading and parsing.
1705 struct sftp_command
*sftp_getcmd(FILE *fp
, int mode
, int modeflags
)
1708 struct sftp_command
*cmd
;
1712 cmd
= snew(struct sftp_command
);
1722 line
= fgetline(fp
);
1724 line
= ssh_sftp_get_cmdline("psftp> ");
1727 if (!line
|| !*line
) {
1728 cmd
->obey
= sftp_cmd_quit
;
1729 if ((mode
== 0) || (modeflags
& 1))
1731 return cmd
; /* eof */
1734 line
[strcspn(line
, "\r\n")] = '\0';
1736 if (modeflags
& 1) {
1737 printf("%s\n", line
);
1741 while (*p
&& (*p
== ' ' || *p
== '\t'))
1746 * Special case: the ! command. This is always parsed as
1747 * exactly two words: one containing the !, and the second
1748 * containing everything else on the line.
1750 cmd
->nwords
= cmd
->wordssize
= 2;
1751 cmd
->words
= sresize(cmd
->words
, cmd
->wordssize
, char *);
1752 cmd
->words
[0] = dupstr("!");
1753 cmd
->words
[1] = dupstr(p
+1);
1757 * Parse the command line into words. The syntax is:
1758 * - double quotes are removed, but cause spaces within to be
1759 * treated as non-separating.
1760 * - a double-doublequote pair is a literal double quote, inside
1761 * _or_ outside quotes. Like this:
1763 * firstword "second word" "this has ""quotes"" in" and""this""
1769 * >this has "quotes" in<
1773 /* skip whitespace */
1774 while (*p
&& (*p
== ' ' || *p
== '\t'))
1776 /* mark start of word */
1777 q
= r
= p
; /* q sits at start, r writes word */
1780 if (!quoting
&& (*p
== ' ' || *p
== '\t'))
1781 break; /* reached end of word */
1782 else if (*p
== '"' && p
[1] == '"')
1783 p
+= 2, *r
++ = '"'; /* a literal quote */
1785 p
++, quoting
= !quoting
;
1790 p
++; /* skip over the whitespace */
1792 if (cmd
->nwords
>= cmd
->wordssize
) {
1793 cmd
->wordssize
= cmd
->nwords
+ 16;
1794 cmd
->words
= sresize(cmd
->words
, cmd
->wordssize
, char *);
1796 cmd
->words
[cmd
->nwords
++] = dupstr(q
);
1803 * Now parse the first word and assign a function.
1806 if (cmd
->nwords
== 0)
1807 cmd
->obey
= sftp_cmd_null
;
1809 const struct sftp_cmd_lookup
*lookup
;
1810 lookup
= lookup_command(cmd
->words
[0]);
1812 cmd
->obey
= sftp_cmd_unknown
;
1814 cmd
->obey
= lookup
->obey
;
1820 static int do_sftp_init(void)
1822 struct sftp_packet
*pktin
;
1823 struct sftp_request
*req
, *rreq
;
1826 * Do protocol initialisation.
1830 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
1831 return 1; /* failure */
1835 * Find out where our home directory is.
1837 sftp_register(req
= fxp_realpath_send("."));
1838 rreq
= sftp_find_request(pktin
= sftp_recv());
1839 assert(rreq
== req
);
1840 homedir
= fxp_realpath_recv(pktin
, rreq
);
1844 "Warning: failed to resolve home directory: %s\n",
1846 homedir
= dupstr(".");
1848 printf("Remote working directory is %s\n", homedir
);
1850 pwd
= dupstr(homedir
);
1854 void do_sftp_cleanup()
1858 back
->special(backhandle
, TS_EOF
);
1859 sftp_recvdata(&ch
, 1);
1860 back
->free(backhandle
);
1861 sftp_cleanup_request();
1873 void do_sftp(int mode
, int modeflags
, char *batchfile
)
1883 /* ------------------------------------------------------------------
1884 * Now we're ready to do Real Stuff.
1887 struct sftp_command
*cmd
;
1888 cmd
= sftp_getcmd(NULL
, 0, 0);
1891 ret
= cmd
->obey(cmd
);
1894 for(i
= 0; i
< cmd
->nwords
; i
++)
1895 sfree(cmd
->words
[i
]);
1903 fp
= fopen(batchfile
, "r");
1905 printf("Fatal: unable to open %s\n", batchfile
);
1909 struct sftp_command
*cmd
;
1910 cmd
= sftp_getcmd(fp
, mode
, modeflags
);
1913 ret
= cmd
->obey(cmd
);
1917 if (!(modeflags
& 2))
1926 /* ----------------------------------------------------------------------
1927 * Dirty bits: integration with PuTTY.
1930 static int verbose
= 0;
1933 * Print an error message and perform a fatal exit.
1935 void fatalbox(char *fmt
, ...)
1940 str
= dupvprintf(fmt
, ap
);
1941 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1944 fputs(str2
, stderr
);
1949 void modalfatalbox(char *fmt
, ...)
1954 str
= dupvprintf(fmt
, ap
);
1955 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1958 fputs(str2
, stderr
);
1963 void connection_fatal(void *frontend
, char *fmt
, ...)
1968 str
= dupvprintf(fmt
, ap
);
1969 str2
= dupcat("Fatal: ", str
, "\n", NULL
);
1972 fputs(str2
, stderr
);
1978 void ldisc_send(void *handle
, char *buf
, int len
, int interactive
)
1981 * This is only here because of the calls to ldisc_send(NULL,
1982 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
1983 * ldisc as an ldisc. So if we get called with any real data, I
1984 * want to know about it.
1990 * In psftp, all agent requests should be synchronous, so this is a
1991 * never-called stub.
1993 void agent_schedule_callback(void (*callback
)(void *, void *, int),
1994 void *callback_ctx
, void *data
, int len
)
1996 assert(!"We shouldn't be here");
2000 * Receive a block of data from the SSH link. Block until all data
2003 * To do this, we repeatedly call the SSH protocol module, with our
2004 * own trap in from_backend() to catch the data that comes back. We
2005 * do this until we have enough data.
2008 static unsigned char *outptr
; /* where to put the data */
2009 static unsigned outlen
; /* how much data required */
2010 static unsigned char *pending
= NULL
; /* any spare data */
2011 static unsigned pendlen
= 0, pendsize
= 0; /* length and phys. size of buffer */
2012 int from_backend(void *frontend
, int is_stderr
, const char *data
, int datalen
)
2014 unsigned char *p
= (unsigned char *) data
;
2015 unsigned len
= (unsigned) datalen
;
2018 * stderr data is just spouted to local stderr and otherwise
2023 fwrite(data
, 1, len
, stderr
);
2028 * If this is before the real session begins, just return.
2033 if ((outlen
> 0) && (len
> 0)) {
2034 unsigned used
= outlen
;
2037 memcpy(outptr
, p
, used
);
2045 if (pendsize
< pendlen
+ len
) {
2046 pendsize
= pendlen
+ len
+ 4096;
2047 pending
= sresize(pending
, pendsize
, unsigned char);
2049 memcpy(pending
+ pendlen
, p
, len
);
2055 int sftp_recvdata(char *buf
, int len
)
2057 outptr
= (unsigned char *) buf
;
2061 * See if the pending-input block contains some of what we
2065 unsigned pendused
= pendlen
;
2066 if (pendused
> outlen
)
2068 memcpy(outptr
, pending
, pendused
);
2069 memmove(pending
, pending
+ pendused
, pendlen
- pendused
);
2072 pendlen
-= pendused
;
2082 while (outlen
> 0) {
2083 if (ssh_sftp_loop_iteration() < 0)
2084 return 0; /* doom */
2089 int sftp_senddata(char *buf
, int len
)
2091 back
->send(backhandle
, buf
, len
);
2096 * Short description of parameters.
2098 static void usage(void)
2100 printf("PuTTY Secure File Transfer (SFTP) client\n");
2101 printf("%s\n", ver
);
2102 printf("Usage: psftp [options] [user@]host\n");
2103 printf("Options:\n");
2104 printf(" -b file use specified batchfile\n");
2105 printf(" -bc output batchfile commands\n");
2106 printf(" -be don't stop batchfile processing if errors\n");
2107 printf(" -v show verbose messages\n");
2108 printf(" -load sessname Load settings from saved session\n");
2109 printf(" -l user connect with specified username\n");
2110 printf(" -P port connect to specified port\n");
2111 printf(" -pw passw login with specified password\n");
2112 printf(" -1 -2 force use of particular SSH protocol version\n");
2113 printf(" -C enable compression\n");
2114 printf(" -i key private key file for authentication\n");
2115 printf(" -batch disable all interactive prompts\n");
2116 printf(" -V print version information\n");
2120 static void version(void)
2122 printf("psftp: %s\n", ver
);
2127 * Connect to a host.
2129 static int psftp_connect(char *userhost
, char *user
, int portnumber
)
2131 char *host
, *realhost
;
2135 /* Separate host and username */
2137 host
= strrchr(host
, '@');
2143 printf("psftp: multiple usernames specified; using \"%s\"\n",
2150 * If we haven't loaded session details already (e.g., from -load),
2151 * try looking for a session called "host".
2153 if (!loaded_session
) {
2154 /* Try to load settings for `host' into a temporary config */
2156 cfg2
.host
[0] = '\0';
2157 do_defaults(host
, &cfg2
);
2158 if (cfg2
.host
[0] != '\0') {
2159 /* Settings present and include hostname */
2160 /* Re-load data into the real config. */
2161 do_defaults(host
, &cfg
);
2163 /* Session doesn't exist or mention a hostname. */
2164 /* Use `host' as a bare hostname. */
2165 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
2166 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
2169 /* Patch in hostname `host' to session details. */
2170 strncpy(cfg
.host
, host
, sizeof(cfg
.host
) - 1);
2171 cfg
.host
[sizeof(cfg
.host
) - 1] = '\0';
2175 * Force use of SSH. (If they got the protocol wrong we assume the
2176 * port is useless too.)
2178 if (cfg
.protocol
!= PROT_SSH
) {
2179 cfg
.protocol
= PROT_SSH
;
2184 * If saved session / Default Settings says SSH-1 (`1 only' or `1'),
2185 * then change it to SSH-2, on the grounds that that's more likely to
2186 * work for SFTP. (Can be overridden with `-1' option.)
2187 * But if it says `2 only' or `2', respect which.
2189 if (cfg
.sshprot
!= 2 && cfg
.sshprot
!= 3)
2193 * Enact command-line overrides.
2195 cmdline_run_saved(&cfg
);
2198 * Trim leading whitespace off the hostname if it's there.
2201 int space
= strspn(cfg
.host
, " \t");
2202 memmove(cfg
.host
, cfg
.host
+space
, 1+strlen(cfg
.host
)-space
);
2205 /* See if host is of the form user@host */
2206 if (cfg
.host
[0] != '\0') {
2207 char *atsign
= strrchr(cfg
.host
, '@');
2208 /* Make sure we're not overflowing the user field */
2210 if (atsign
- cfg
.host
< sizeof cfg
.username
) {
2211 strncpy(cfg
.username
, cfg
.host
, atsign
- cfg
.host
);
2212 cfg
.username
[atsign
- cfg
.host
] = '\0';
2214 memmove(cfg
.host
, atsign
+ 1, 1 + strlen(atsign
+ 1));
2219 * Trim a colon suffix off the hostname if it's there.
2221 cfg
.host
[strcspn(cfg
.host
, ":")] = '\0';
2224 * Remove any remaining whitespace from the hostname.
2228 while (cfg
.host
[p2
] != '\0') {
2229 if (cfg
.host
[p2
] != ' ' && cfg
.host
[p2
] != '\t') {
2230 cfg
.host
[p1
] = cfg
.host
[p2
];
2235 cfg
.host
[p1
] = '\0';
2239 if (user
!= NULL
&& user
[0] != '\0') {
2240 strncpy(cfg
.username
, user
, sizeof(cfg
.username
) - 1);
2241 cfg
.username
[sizeof(cfg
.username
) - 1] = '\0';
2243 if (!cfg
.username
[0]) {
2244 if (!console_get_line("login as: ",
2245 cfg
.username
, sizeof(cfg
.username
), FALSE
)) {
2246 fprintf(stderr
, "psftp: no username, aborting\n");
2249 int len
= strlen(cfg
.username
);
2250 if (cfg
.username
[len
- 1] == '\n')
2251 cfg
.username
[len
- 1] = '\0';
2256 cfg
.port
= portnumber
;
2259 * Disable scary things which shouldn't be enabled for simple
2260 * things like SCP and SFTP: agent forwarding, port forwarding,
2263 cfg
.x11_forward
= 0;
2265 cfg
.portfwd
[0] = cfg
.portfwd
[1] = '\0';
2267 /* Set up subsystem name. */
2268 strcpy(cfg
.remote_cmd
, "sftp");
2269 cfg
.ssh_subsys
= TRUE
;
2273 * Set up fallback option, for SSH1 servers or servers with the
2274 * sftp subsystem not enabled but the server binary installed
2275 * in the usual place. We only support fallback on Unix
2276 * systems, and we use a kludgy piece of shellery which should
2277 * try to find sftp-server in various places (the obvious
2278 * systemwide spots /usr/lib and /usr/local/lib, and then the
2279 * user's PATH) and finally give up.
2281 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
2282 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
2285 * the idea being that this will attempt to use either of the
2286 * obvious pathnames and then give up, and when it does give up
2287 * it will print the preferred pathname in the error messages.
2289 cfg
.remote_cmd_ptr2
=
2290 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
2291 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
2293 cfg
.ssh_subsys2
= FALSE
;
2295 back
= &ssh_backend
;
2297 err
= back
->init(NULL
, &backhandle
, &cfg
, cfg
.host
, cfg
.port
, &realhost
,
2298 0, cfg
.tcp_keepalives
);
2300 fprintf(stderr
, "ssh_init: %s\n", err
);
2303 logctx
= log_init(NULL
, &cfg
);
2304 back
->provide_logctx(backhandle
, logctx
);
2305 console_provide_logctx(logctx
);
2306 while (!back
->sendok(backhandle
)) {
2307 if (ssh_sftp_loop_iteration() < 0) {
2308 fprintf(stderr
, "ssh_init: error during SSH connection setup\n");
2312 if (verbose
&& realhost
!= NULL
)
2313 printf("Connected to %s\n", realhost
);
2314 if (realhost
!= NULL
)
2319 void cmdline_error(char *p
, ...)
2322 fprintf(stderr
, "psftp: ");
2324 vfprintf(stderr
, p
, ap
);
2326 fprintf(stderr
, "\n try typing \"psftp -h\" for help\n");
2331 * Main program. Parse arguments etc.
2333 int psftp_main(int argc
, char *argv
[])
2337 char *userhost
, *user
;
2340 char *batchfile
= NULL
;
2343 flags
= FLAG_STDERR
| FLAG_INTERACTIVE
2344 #ifdef FLAG_SYNCAGENT
2348 cmdline_tooltype
= TOOLTYPE_FILETRANSFER
;
2349 ssh_get_line
= &console_get_line
;
2352 userhost
= user
= NULL
;
2354 /* Load Default Settings before doing anything else. */
2355 do_defaults(NULL
, &cfg
);
2356 loaded_session
= FALSE
;
2359 for (i
= 1; i
< argc
; i
++) {
2361 if (argv
[i
][0] != '-') {
2365 userhost
= dupstr(argv
[i
]);
2368 ret
= cmdline_process_param(argv
[i
], i
+1<argc?argv
[i
+1]:NULL
, 1, &cfg
);
2370 cmdline_error("option \"%s\" requires an argument", argv
[i
]);
2371 } else if (ret
== 2) {
2372 i
++; /* skip next argument */
2373 } else if (ret
== 1) {
2374 /* We have our own verbosity in addition to `flags'. */
2375 if (flags
& FLAG_VERBOSE
)
2377 } else if (strcmp(argv
[i
], "-h") == 0 ||
2378 strcmp(argv
[i
], "-?") == 0) {
2380 } else if (strcmp(argv
[i
], "-V") == 0) {
2382 } else if (strcmp(argv
[i
], "-batch") == 0) {
2383 console_batch_mode
= 1;
2384 } else if (strcmp(argv
[i
], "-b") == 0 && i
+ 1 < argc
) {
2386 batchfile
= argv
[++i
];
2387 } else if (strcmp(argv
[i
], "-bc") == 0) {
2388 modeflags
= modeflags
| 1;
2389 } else if (strcmp(argv
[i
], "-be") == 0) {
2390 modeflags
= modeflags
| 2;
2391 } else if (strcmp(argv
[i
], "--") == 0) {
2395 cmdline_error("unknown option \"%s\"", argv
[i
]);
2403 * If the loaded session provides a hostname, and a hostname has not
2404 * otherwise been specified, pop it in `userhost' so that
2405 * `psftp -load sessname' is sufficient to start a session.
2407 if (!userhost
&& cfg
.host
[0] != '\0') {
2408 userhost
= dupstr(cfg
.host
);
2412 * If a user@host string has already been provided, connect to
2417 ret
= psftp_connect(userhost
, user
, portnumber
);
2424 printf("psftp: no hostname specified; use \"open host.name\""
2428 do_sftp(mode
, modeflags
, batchfile
);
2430 if (back
!= NULL
&& back
->socket(backhandle
) != NULL
) {
2432 back
->special(backhandle
, TS_EOF
);
2433 sftp_recvdata(&ch
, 1);
2437 console_provide_logctx(NULL
);