Introduce a new checkbox and command-line option to inhibit use of
[u/mdw/putty] / psftp.c
CommitLineData
4c7f0d61 1/*
f4ff9455 2 * psftp.c: (platform-independent) front end for PSFTP.
4c7f0d61 3 */
4
5#include <stdio.h>
6#include <stdlib.h>
f9e162aa 7#include <stdarg.h>
4c7f0d61 8#include <assert.h>
d92624dc 9#include <limits.h>
4c7f0d61 10
4a8fc3c4 11#define PUTTY_DO_GLOBALS
12#include "putty.h"
d6cc41e6 13#include "psftp.h"
4a8fc3c4 14#include "storage.h"
15#include "ssh.h"
4c7f0d61 16#include "sftp.h"
17#include "int64.h"
18
5471d09a 19/*
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
23 * send buffer.
24 */
25
fa3db767 26static int psftp_connect(char *userhost, char *user, int portnumber);
07534184 27static int do_sftp_init(void);
679539d7 28void do_sftp_cleanup();
fa3db767 29
4c7f0d61 30/* ----------------------------------------------------------------------
4c7f0d61 31 * sftp client state.
32 */
33
34char *pwd, *homedir;
6b78788a 35static Backend *back;
36static void *backhandle;
3ea863a3 37static Config cfg;
4c7f0d61 38
39/* ----------------------------------------------------------------------
40 * Higher-level helper functions used in commands.
41 */
42
43/*
f9e162aa 44 * Attempt to canonify a pathname starting from the pwd. If
45 * canonification fails, at least fall back to returning a _valid_
46 * pathname (though it may be ugly, eg /home/simon/../foobar).
4c7f0d61 47 */
32874aea 48char *canonify(char *name)
49{
f9e162aa 50 char *fullname, *canonname;
1bc24185 51 struct sftp_packet *pktin;
52 struct sftp_request *req, *rreq;
4a8fc3c4 53
f9e162aa 54 if (name[0] == '/') {
55 fullname = dupstr(name);
56 } else {
4a8fc3c4 57 char *slash;
32874aea 58 if (pwd[strlen(pwd) - 1] == '/')
4a8fc3c4 59 slash = "";
60 else
61 slash = "/";
62 fullname = dupcat(pwd, slash, name, NULL);
f9e162aa 63 }
4a8fc3c4 64
1bc24185 65 sftp_register(req = fxp_realpath_send(fullname));
66 rreq = sftp_find_request(pktin = sftp_recv());
67 assert(rreq == req);
7b7de4f4 68 canonname = fxp_realpath_recv(pktin, rreq);
4a8fc3c4 69
f9e162aa 70 if (canonname) {
71 sfree(fullname);
72 return canonname;
50d7e054 73 } else {
32874aea 74 /*
75 * Attempt number 2. Some FXP_REALPATH implementations
76 * (glibc-based ones, in particular) require the _whole_
77 * path to point to something that exists, whereas others
78 * (BSD-based) only require all but the last component to
79 * exist. So if the first call failed, we should strip off
80 * everything from the last slash onwards and try again,
81 * then put the final component back on.
82 *
83 * Special cases:
84 *
85 * - if the last component is "/." or "/..", then we don't
86 * bother trying this because there's no way it can work.
87 *
88 * - if the thing actually ends with a "/", we remove it
89 * before we start. Except if the string is "/" itself
90 * (although I can't see why we'd have got here if so,
91 * because surely "/" would have worked the first
92 * time?), in which case we don't bother.
93 *
94 * - if there's no slash in the string at all, give up in
95 * confusion (we expect at least one because of the way
96 * we constructed the string).
97 */
98
99 int i;
100 char *returnname;
101
102 i = strlen(fullname);
103 if (i > 2 && fullname[i - 1] == '/')
104 fullname[--i] = '\0'; /* strip trailing / unless at pos 0 */
105 while (i > 0 && fullname[--i] != '/');
106
107 /*
108 * Give up on special cases.
109 */
110 if (fullname[i] != '/' || /* no slash at all */
111 !strcmp(fullname + i, "/.") || /* ends in /. */
112 !strcmp(fullname + i, "/..") || /* ends in /.. */
113 !strcmp(fullname, "/")) {
114 return fullname;
115 }
116
117 /*
118 * Now i points at the slash. Deal with the final special
119 * case i==0 (ie the whole path was "/nonexistentfile").
120 */
121 fullname[i] = '\0'; /* separate the string */
122 if (i == 0) {
1bc24185 123 sftp_register(req = fxp_realpath_send("/"));
32874aea 124 } else {
1bc24185 125 sftp_register(req = fxp_realpath_send(fullname));
32874aea 126 }
1bc24185 127 rreq = sftp_find_request(pktin = sftp_recv());
128 assert(rreq == req);
7b7de4f4 129 canonname = fxp_realpath_recv(pktin, rreq);
32874aea 130
131 if (!canonname)
132 return fullname; /* even that failed; give up */
133
134 /*
135 * We have a canonical name for all but the last path
136 * component. Concatenate the last component and return.
137 */
138 returnname = dupcat(canonname,
139 canonname[strlen(canonname) - 1] ==
140 '/' ? "" : "/", fullname + i + 1, NULL);
141 sfree(fullname);
142 sfree(canonname);
143 return returnname;
50d7e054 144 }
4c7f0d61 145}
146
dcf8495c 147/*
148 * Return a pointer to the portion of str that comes after the last
149 * slash (or backslash or colon, if `local' is TRUE).
150 */
151static char *stripslashes(char *str, int local)
152{
153 char *p;
154
155 if (local) {
156 p = strchr(str, ':');
157 if (p) str = p+1;
158 }
159
160 p = strrchr(str, '/');
161 if (p) str = p+1;
162
163 if (local) {
164 p = strrchr(str, '\\');
165 if (p) str = p+1;
166 }
167
168 return str;
169}
170
4c7f0d61 171/*
93e86a8b 172 * qsort comparison routine for fxp_name structures. Sorts by real
173 * file name.
4c7f0d61 174 */
93e86a8b 175static int sftp_name_compare(const void *av, const void *bv)
32874aea 176{
7d2c1789 177 const struct fxp_name *const *a = (const struct fxp_name *const *) av;
178 const struct fxp_name *const *b = (const struct fxp_name *const *) bv;
179 return strcmp((*a)->filename, (*b)->filename);
4c7f0d61 180}
4c7f0d61 181
182/*
93e86a8b 183 * Likewise, but for a bare char *.
4f2b387f 184 */
93e86a8b 185static int bare_name_compare(const void *av, const void *bv)
4f2b387f 186{
93e86a8b 187 const char **a = (const char **) av;
188 const char **b = (const char **) bv;
189 return strcmp(*a, *b);
4f2b387f 190}
191
38f0c08e 192static void not_connected(void)
193{
194 printf("psftp: not connected to a host; use \"open host.name\"\n");
195}
196
93e86a8b 197/* ----------------------------------------------------------------------
198 * The meat of the `get' and `put' commands.
4c7f0d61 199 */
5079ee6d 200int sftp_get_file(char *fname, char *outfname, int recurse, int restart)
32874aea 201{
4c7f0d61 202 struct fxp_handle *fh;
1bc24185 203 struct sftp_packet *pktin;
204 struct sftp_request *req, *rreq;
c606c42d 205 struct fxp_xfer *xfer;
4c7f0d61 206 uint64 offset;
207 FILE *fp;
479fe1ba 208 int ret, shown_err = FALSE;
4c7f0d61 209
93e86a8b 210 /*
211 * In recursive mode, see if we're dealing with a directory.
212 * (If we're not in recursive mode, we need not even check: the
213 * subsequent FXP_OPEN will return a usable error message.)
214 */
5079ee6d 215 if (recurse) {
93e86a8b 216 struct fxp_attrs attrs;
217 int result;
fa3db767 218
5079ee6d 219 sftp_register(req = fxp_stat_send(fname));
220 rreq = sftp_find_request(pktin = sftp_recv());
221 assert(rreq == req);
222 result = fxp_stat_recv(pktin, rreq, &attrs);
9c77ddf6 223
5079ee6d 224 if (result &&
225 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
226 (attrs.permissions & 0040000)) {
93e86a8b 227
228 struct fxp_handle *dirhandle;
229 int nnames, namesize;
230 struct fxp_name **ournames;
231 struct fxp_names *names;
232 int i;
233
234 /*
235 * First, attempt to create the destination directory,
5079ee6d 236 * unless it already exists.
93e86a8b 237 */
5079ee6d 238 if (file_type(outfname) != FILE_TYPE_DIRECTORY &&
93e86a8b 239 !create_directory(outfname)) {
240 printf("%s: Cannot create directory\n", outfname);
241 return 0;
242 }
4c7f0d61 243
93e86a8b 244 /*
245 * Now get the list of filenames in the remote
246 * directory.
247 */
248 sftp_register(req = fxp_opendir_send(fname));
249 rreq = sftp_find_request(pktin = sftp_recv());
250 assert(rreq == req);
251 dirhandle = fxp_opendir_recv(pktin, rreq);
252
253 if (!dirhandle) {
254 printf("%s: unable to open directory: %s\n",
255 fname, fxp_error());
256 return 0;
257 }
258 nnames = namesize = 0;
259 ournames = NULL;
260 while (1) {
261 int i;
262
263 sftp_register(req = fxp_readdir_send(dirhandle));
264 rreq = sftp_find_request(pktin = sftp_recv());
265 assert(rreq == req);
266 names = fxp_readdir_recv(pktin, rreq);
267
268 if (names == NULL) {
269 if (fxp_error_type() == SSH_FX_EOF)
270 break;
271 printf("%s: reading directory: %s\n", fname, fxp_error());
272 sfree(ournames);
273 return 0;
274 }
275 if (names->nnames == 0) {
276 fxp_free_names(names);
277 break;
278 }
279 if (nnames + names->nnames >= namesize) {
280 namesize += names->nnames + 128;
281 ournames = sresize(ournames, namesize, struct fxp_name *);
282 }
283 for (i = 0; i < names->nnames; i++)
e9d14678 284 if (strcmp(names->names[i].filename, ".") &&
5079ee6d 285 strcmp(names->names[i].filename, "..")) {
e9d14678 286 if (!vet_filename(names->names[i].filename)) {
287 printf("ignoring potentially dangerous server-"
288 "supplied filename '%s'\n",
289 names->names[i].filename);
290 } else {
291 ournames[nnames++] =
292 fxp_dup_name(&names->names[i]);
293 }
294 }
93e86a8b 295 fxp_free_names(names);
296 }
297 sftp_register(req = fxp_close_send(dirhandle));
298 rreq = sftp_find_request(pktin = sftp_recv());
299 assert(rreq == req);
300 fxp_close_recv(pktin, rreq);
301
302 /*
303 * Sort the names into a clear order. This ought to
304 * make things more predictable when we're doing a
305 * reget of the same directory, just in case two
306 * readdirs on the same remote directory return a
307 * different order.
308 */
309 qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
310
311 /*
312 * If we're in restart mode, find the last filename on
313 * this list that already exists. We may have to do a
314 * reget on _that_ file, but shouldn't have to do
315 * anything on the previous files.
316 *
317 * If none of them exists, of course, we start at 0.
318 */
319 i = 0;
320 while (i < nnames) {
321 char *nextoutfname;
322 int ret;
9c77ddf6 323 if (outfname)
324 nextoutfname = dir_file_cat(outfname,
325 ournames[i]->filename);
326 else
327 nextoutfname = dupstr(ournames[i]->filename);
93e86a8b 328 ret = (file_type(nextoutfname) == FILE_TYPE_NONEXISTENT);
329 sfree(nextoutfname);
330 if (ret)
331 break;
332 i++;
333 }
334 if (i > 0)
335 i--;
336
337 /*
338 * Now we're ready to recurse. Starting at ournames[i]
339 * and continuing on to the end of the list, we
340 * construct a new source and target file name, and
341 * call sftp_get_file again.
342 */
343 for (; i < nnames; i++) {
344 char *nextfname, *nextoutfname;
345 int ret;
346
347 nextfname = dupcat(fname, "/", ournames[i]->filename, NULL);
9c77ddf6 348 if (outfname)
349 nextoutfname = dir_file_cat(outfname,
350 ournames[i]->filename);
351 else
352 nextoutfname = dupstr(ournames[i]->filename);
5079ee6d 353 ret = sftp_get_file(nextfname, nextoutfname, recurse, restart);
93e86a8b 354 restart = FALSE; /* after first partial file, do full */
355 sfree(nextoutfname);
356 sfree(nextfname);
357 if (!ret) {
358 for (i = 0; i < nnames; i++) {
359 fxp_free_name(ournames[i]);
360 }
361 sfree(ournames);
362 return 0;
363 }
364 }
365
366 /*
367 * Done this recursion level. Free everything.
368 */
369 for (i = 0; i < nnames; i++) {
370 fxp_free_name(ournames[i]);
371 }
372 sfree(ournames);
373
374 return 1;
375 }
4c7f0d61 376 }
4c7f0d61 377
1bc24185 378 sftp_register(req = fxp_open_send(fname, SSH_FXF_READ));
379 rreq = sftp_find_request(pktin = sftp_recv());
380 assert(rreq == req);
7b7de4f4 381 fh = fxp_open_recv(pktin, rreq);
1bc24185 382
4c7f0d61 383 if (!fh) {
384 printf("%s: %s\n", fname, fxp_error());
4c7f0d61 385 return 0;
386 }
d92624dc 387
388 if (restart) {
389 fp = fopen(outfname, "rb+");
390 } else {
391 fp = fopen(outfname, "wb");
392 }
393
4c7f0d61 394 if (!fp) {
395 printf("local: unable to open %s\n", outfname);
1bc24185 396
397 sftp_register(req = fxp_close_send(fh));
398 rreq = sftp_find_request(pktin = sftp_recv());
399 assert(rreq == req);
7b7de4f4 400 fxp_close_recv(pktin, rreq);
1bc24185 401
4c7f0d61 402 return 0;
403 }
404
d92624dc 405 if (restart) {
406 long posn;
407 fseek(fp, 0L, SEEK_END);
408 posn = ftell(fp);
409 printf("reget: restarting at file position %ld\n", posn);
410 offset = uint64_make(0, posn);
411 } else {
412 offset = uint64_make(0, 0);
413 }
4c7f0d61 414
d92624dc 415 printf("remote:%s => local:%s\n", fname, outfname);
4c7f0d61 416
417 /*
418 * FIXME: we can use FXP_FSTAT here to get the file size, and
419 * thus put up a progress bar.
420 */
df49ff19 421 ret = 1;
c606c42d 422 xfer = xfer_download_init(fh, offset);
df0870fc 423 while (!xfer_done(xfer)) {
c606c42d 424 void *vbuf;
425 int ret, len;
4c7f0d61 426 int wpos, wlen;
427
c606c42d 428 xfer_download_queue(xfer);
429 pktin = sftp_recv();
430 ret = xfer_download_gotpkt(xfer, pktin);
431
432 if (ret < 0) {
479fe1ba 433 if (!shown_err) {
434 printf("error while reading: %s\n", fxp_error());
435 shown_err = TRUE;
436 }
c606c42d 437 ret = 0;
4c7f0d61 438 }
32874aea 439
c606c42d 440 while (xfer_download_data(xfer, &vbuf, &len)) {
441 unsigned char *buf = (unsigned char *)vbuf;
442
443 wpos = 0;
444 while (wpos < len) {
445 wlen = fwrite(buf + wpos, 1, len - wpos, fp);
446 if (wlen <= 0) {
447 printf("error while writing local file\n");
448 ret = 0;
449 xfer_set_error(xfer);
450 }
451 wpos += wlen;
452 }
453 if (wpos < len) { /* we had an error */
df49ff19 454 ret = 0;
c606c42d 455 xfer_set_error(xfer);
4c7f0d61 456 }
9ff4e23d 457
458 sfree(vbuf);
df49ff19 459 }
4c7f0d61 460 }
461
c606c42d 462 xfer_cleanup(xfer);
463
4c7f0d61 464 fclose(fp);
1bc24185 465
466 sftp_register(req = fxp_close_send(fh));
467 rreq = sftp_find_request(pktin = sftp_recv());
468 assert(rreq == req);
7b7de4f4 469 fxp_close_recv(pktin, rreq);
1bc24185 470
df49ff19 471 return ret;
4c7f0d61 472}
473
5079ee6d 474int sftp_put_file(char *fname, char *outfname, int recurse, int restart)
32874aea 475{
4c7f0d61 476 struct fxp_handle *fh;
df0870fc 477 struct fxp_xfer *xfer;
1bc24185 478 struct sftp_packet *pktin;
479 struct sftp_request *req, *rreq;
4c7f0d61 480 uint64 offset;
481 FILE *fp;
df0870fc 482 int ret, err, eof;
4c7f0d61 483
93e86a8b 484 /*
485 * In recursive mode, see if we're dealing with a directory.
486 * (If we're not in recursive mode, we need not even check: the
487 * subsequent fopen will return an error message.)
488 */
5079ee6d 489 if (recurse && file_type(fname) == FILE_TYPE_DIRECTORY) {
93e86a8b 490 struct fxp_attrs attrs;
491 int result;
492 int nnames, namesize;
493 char *name, **ournames;
494 DirHandle *dh;
495 int i;
4c7f0d61 496
5079ee6d 497 /*
498 * First, attempt to create the destination directory,
499 * unless it already exists.
500 */
501 sftp_register(req = fxp_stat_send(outfname));
502 rreq = sftp_find_request(pktin = sftp_recv());
503 assert(rreq == req);
504 result = fxp_stat_recv(pktin, rreq, &attrs);
505 if (!result ||
506 !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
507 !(attrs.permissions & 0040000)) {
508 sftp_register(req = fxp_mkdir_send(outfname));
93e86a8b 509 rreq = sftp_find_request(pktin = sftp_recv());
510 assert(rreq == req);
5079ee6d 511 result = fxp_mkdir_recv(pktin, rreq);
93e86a8b 512
5079ee6d 513 if (!result) {
514 printf("%s: create directory: %s\n",
515 outfname, fxp_error());
516 return 0;
93e86a8b 517 }
518 }
519
520 /*
521 * Now get the list of filenames in the local directory.
522 */
93e86a8b 523 nnames = namesize = 0;
524 ournames = NULL;
9c77ddf6 525
5079ee6d 526 dh = open_directory(fname);
527 if (!dh) {
528 printf("%s: unable to open directory\n", fname);
529 return 0;
9c77ddf6 530 }
5079ee6d 531 while ((name = read_filename(dh)) != NULL) {
532 if (nnames >= namesize) {
533 namesize += 128;
534 ournames = sresize(ournames, namesize, char *);
535 }
536 ournames[nnames++] = name;
93e86a8b 537 }
5079ee6d 538 close_directory(dh);
93e86a8b 539
540 /*
541 * Sort the names into a clear order. This ought to make
542 * things more predictable when we're doing a reput of the
543 * same directory, just in case two readdirs on the same
544 * local directory return a different order.
545 */
546 qsort(ournames, nnames, sizeof(*ournames), bare_name_compare);
547
548 /*
549 * If we're in restart mode, find the last filename on this
550 * list that already exists. We may have to do a reput on
551 * _that_ file, but shouldn't have to do anything on the
552 * previous files.
553 *
554 * If none of them exists, of course, we start at 0.
555 */
556 i = 0;
557 while (i < nnames) {
558 char *nextoutfname;
559 nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
560 sftp_register(req = fxp_stat_send(nextoutfname));
561 rreq = sftp_find_request(pktin = sftp_recv());
562 assert(rreq == req);
563 result = fxp_stat_recv(pktin, rreq, &attrs);
564 sfree(nextoutfname);
565 if (!result)
566 break;
567 i++;
568 }
569 if (i > 0)
570 i--;
571
572 /*
573 * Now we're ready to recurse. Starting at ournames[i]
574 * and continuing on to the end of the list, we
575 * construct a new source and target file name, and
576 * call sftp_put_file again.
577 */
578 for (; i < nnames; i++) {
579 char *nextfname, *nextoutfname;
580 int ret;
581
9c77ddf6 582 if (fname)
583 nextfname = dir_file_cat(fname, ournames[i]);
584 else
585 nextfname = dupstr(ournames[i]);
93e86a8b 586 nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
5079ee6d 587 ret = sftp_put_file(nextfname, nextoutfname, recurse, restart);
93e86a8b 588 restart = FALSE; /* after first partial file, do full */
589 sfree(nextoutfname);
590 sfree(nextfname);
591 if (!ret) {
592 for (i = 0; i < nnames; i++) {
593 sfree(ournames[i]);
594 }
595 sfree(ournames);
596 return 0;
597 }
598 }
599
600 /*
601 * Done this recursion level. Free everything.
602 */
603 for (i = 0; i < nnames; i++) {
604 sfree(ournames[i]);
605 }
606 sfree(ournames);
607
608 return 1;
4c7f0d61 609 }
610
611 fp = fopen(fname, "rb");
612 if (!fp) {
613 printf("local: unable to open %s\n", fname);
4c7f0d61 614 return 0;
615 }
d92624dc 616 if (restart) {
1bc24185 617 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE));
d92624dc 618 } else {
1bc24185 619 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE |
620 SSH_FXF_CREAT | SSH_FXF_TRUNC));
d92624dc 621 }
1bc24185 622 rreq = sftp_find_request(pktin = sftp_recv());
623 assert(rreq == req);
7b7de4f4 624 fh = fxp_open_recv(pktin, rreq);
1bc24185 625
4c7f0d61 626 if (!fh) {
627 printf("%s: %s\n", outfname, fxp_error());
4c7f0d61 628 return 0;
629 }
630
d92624dc 631 if (restart) {
632 char decbuf[30];
633 struct fxp_attrs attrs;
1bc24185 634 int ret;
635
636 sftp_register(req = fxp_fstat_send(fh));
637 rreq = sftp_find_request(pktin = sftp_recv());
638 assert(rreq == req);
7b7de4f4 639 ret = fxp_fstat_recv(pktin, rreq, &attrs);
1bc24185 640
641 if (!ret) {
d92624dc 642 printf("read size of %s: %s\n", outfname, fxp_error());
d92624dc 643 return 0;
644 }
645 if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
646 printf("read size of %s: size was not given\n", outfname);
d92624dc 647 return 0;
648 }
649 offset = attrs.size;
650 uint64_decimal(offset, decbuf);
651 printf("reput: restarting at file position %s\n", decbuf);
652 if (uint64_compare(offset, uint64_make(0, LONG_MAX)) > 0) {
653 printf("reput: remote file is larger than we can deal with\n");
d92624dc 654 return 0;
655 }
656 if (fseek(fp, offset.lo, SEEK_SET) != 0)
657 fseek(fp, 0, SEEK_END); /* *shrug* */
658 } else {
659 offset = uint64_make(0, 0);
660 }
4c7f0d61 661
d92624dc 662 printf("local:%s => remote:%s\n", fname, outfname);
4c7f0d61 663
664 /*
665 * FIXME: we can use FXP_FSTAT here to get the file size, and
666 * thus put up a progress bar.
667 */
df49ff19 668 ret = 1;
df0870fc 669 xfer = xfer_upload_init(fh, offset);
670 err = eof = 0;
671 while ((!err && !eof) || !xfer_done(xfer)) {
4c7f0d61 672 char buffer[4096];
1bc24185 673 int len, ret;
4c7f0d61 674
df0870fc 675 while (xfer_upload_ready(xfer) && !err && !eof) {
676 len = fread(buffer, 1, sizeof(buffer), fp);
677 if (len == -1) {
678 printf("error while reading local file\n");
679 err = 1;
680 } else if (len == 0) {
681 eof = 1;
682 } else {
683 xfer_upload_data(xfer, buffer, len);
684 }
4c7f0d61 685 }
1bc24185 686
2dbd915a 687 if (!xfer_done(xfer)) {
688 pktin = sftp_recv();
689 ret = xfer_upload_gotpkt(xfer, pktin);
690 if (!ret) {
691 printf("error while writing: %s\n", fxp_error());
692 err = 1;
693 }
4c7f0d61 694 }
4c7f0d61 695 }
696
df0870fc 697 xfer_cleanup(xfer);
698
1bc24185 699 sftp_register(req = fxp_close_send(fh));
700 rreq = sftp_find_request(pktin = sftp_recv());
701 assert(rreq == req);
7b7de4f4 702 fxp_close_recv(pktin, rreq);
1bc24185 703
4c7f0d61 704 fclose(fp);
93e86a8b 705
706 return ret;
707}
708
709/* ----------------------------------------------------------------------
5079ee6d 710 * A remote wildcard matcher, providing a similar interface to the
711 * local one in psftp.h.
712 */
713
714typedef struct SftpWildcardMatcher {
715 struct fxp_handle *dirh;
716 struct fxp_names *names;
717 int namepos;
718 char *wildcard, *prefix;
719} SftpWildcardMatcher;
720
721SftpWildcardMatcher *sftp_begin_wildcard_matching(char *name)
722{
723 struct sftp_packet *pktin;
724 struct sftp_request *req, *rreq;
725 char *wildcard;
726 char *unwcdir, *tmpdir, *cdir;
727 int len, check;
728 SftpWildcardMatcher *swcm;
729 struct fxp_handle *dirh;
730
731 /*
732 * We don't handle multi-level wildcards; so we expect to find
733 * a fully specified directory part, followed by a wildcard
734 * after that.
735 */
736 wildcard = stripslashes(name, 0);
737
738 unwcdir = dupstr(name);
739 len = wildcard - name;
740 unwcdir[len] = '\0';
741 if (len > 0 && unwcdir[len-1] == '/')
742 unwcdir[len-1] = '\0';
743 tmpdir = snewn(1 + len, char);
744 check = wc_unescape(tmpdir, unwcdir);
745 sfree(tmpdir);
746
747 if (!check) {
748 printf("Multiple-level wildcards are not supported\n");
749 sfree(unwcdir);
750 return NULL;
751 }
752
753 cdir = canonify(unwcdir);
754
755 sftp_register(req = fxp_opendir_send(cdir));
756 rreq = sftp_find_request(pktin = sftp_recv());
757 assert(rreq == req);
758 dirh = fxp_opendir_recv(pktin, rreq);
759
760 if (dirh) {
761 swcm = snew(SftpWildcardMatcher);
762 swcm->dirh = dirh;
763 swcm->names = NULL;
764 swcm->wildcard = dupstr(wildcard);
765 swcm->prefix = unwcdir;
766 } else {
767 printf("Unable to open %s: %s\n", cdir, fxp_error());
768 swcm = NULL;
769 sfree(unwcdir);
770 }
771
772 sfree(cdir);
773
774 return swcm;
775}
776
777char *sftp_wildcard_get_filename(SftpWildcardMatcher *swcm)
778{
779 struct fxp_name *name;
780 struct sftp_packet *pktin;
781 struct sftp_request *req, *rreq;
782
783 while (1) {
784 if (swcm->names && swcm->namepos >= swcm->names->nnames) {
785 fxp_free_names(swcm->names);
786 swcm->names = NULL;
787 }
788
789 if (!swcm->names) {
790 sftp_register(req = fxp_readdir_send(swcm->dirh));
791 rreq = sftp_find_request(pktin = sftp_recv());
792 assert(rreq == req);
793 swcm->names = fxp_readdir_recv(pktin, rreq);
794
795 if (!swcm->names) {
796 if (fxp_error_type() != SSH_FX_EOF)
797 printf("%s: reading directory: %s\n", swcm->prefix,
798 fxp_error());
799 return NULL;
800 }
801
802 swcm->namepos = 0;
803 }
804
805 assert(swcm->names && swcm->namepos < swcm->names->nnames);
806
807 name = &swcm->names->names[swcm->namepos++];
808
809 if (!strcmp(name->filename, ".") || !strcmp(name->filename, ".."))
810 continue; /* expected bad filenames */
811
812 if (!vet_filename(name->filename)) {
813 printf("ignoring potentially dangerous server-"
814 "supplied filename '%s'\n", name->filename);
815 continue; /* unexpected bad filename */
816 }
817
818 if (!wc_match(swcm->wildcard, name->filename))
819 continue; /* doesn't match the wildcard */
820
821 /*
822 * We have a working filename. Return it.
823 */
824 return dupprintf("%s%s%s", swcm->prefix,
83567e43 825 (!swcm->prefix[0] ||
826 swcm->prefix[strlen(swcm->prefix)-1]=='/' ?
827 "" : "/"),
5079ee6d 828 name->filename);
829 }
830}
831
832void sftp_finish_wildcard_matching(SftpWildcardMatcher *swcm)
833{
834 struct sftp_packet *pktin;
835 struct sftp_request *req, *rreq;
836
837 sftp_register(req = fxp_close_send(swcm->dirh));
838 rreq = sftp_find_request(pktin = sftp_recv());
839 assert(rreq == req);
840 fxp_close_recv(pktin, rreq);
841
842 if (swcm->names)
843 fxp_free_names(swcm->names);
844
845 sfree(swcm->prefix);
846 sfree(swcm->wildcard);
847
848 sfree(swcm);
849}
850
83567e43 851/*
852 * General function to match a potential wildcard in a filename
853 * argument and iterate over every matching file. Used in several
854 * PSFTP commands (rmdir, rm, chmod, mv).
855 */
856int wildcard_iterate(char *filename, int (*func)(void *, char *), void *ctx)
857{
858 char *unwcfname, *newname, *cname;
859 int is_wc, ret;
860
861 unwcfname = snewn(strlen(filename)+1, char);
862 is_wc = !wc_unescape(unwcfname, filename);
863
864 if (is_wc) {
865 SftpWildcardMatcher *swcm = sftp_begin_wildcard_matching(filename);
866 int matched = FALSE;
867 sfree(unwcfname);
868
869 if (!swcm)
870 return 0;
871
872 ret = 1;
873
874 while ( (newname = sftp_wildcard_get_filename(swcm)) != NULL ) {
875 cname = canonify(newname);
876 if (!cname) {
877 printf("%s: %s\n", newname, fxp_error());
878 ret = 0;
879 }
880 matched = TRUE;
881 ret &= func(ctx, cname);
882 sfree(cname);
883 }
884
885 if (!matched) {
886 /* Politely warn the user that nothing matched. */
887 printf("%s: nothing matched\n", filename);
888 }
889
890 sftp_finish_wildcard_matching(swcm);
891 } else {
892 cname = canonify(unwcfname);
893 if (!cname) {
894 printf("%s: %s\n", filename, fxp_error());
895 ret = 0;
896 }
897 ret = func(ctx, cname);
898 sfree(cname);
899 sfree(unwcfname);
900 }
901
902 return ret;
903}
904
905/*
906 * Handy helper function.
907 */
908int is_wildcard(char *name)
909{
910 char *unwcfname = snewn(strlen(name)+1, char);
911 int is_wc = !wc_unescape(unwcfname, name);
912 sfree(unwcfname);
913 return is_wc;
914}
915
5079ee6d 916/* ----------------------------------------------------------------------
93e86a8b 917 * Actual sftp commands.
918 */
919struct sftp_command {
920 char **words;
921 int nwords, wordssize;
922 int (*obey) (struct sftp_command *); /* returns <0 to quit */
923};
924
925int sftp_cmd_null(struct sftp_command *cmd)
926{
927 return 1; /* success */
928}
929
930int sftp_cmd_unknown(struct sftp_command *cmd)
931{
932 printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
933 return 0; /* failure */
934}
935
936int sftp_cmd_quit(struct sftp_command *cmd)
937{
938 return -1;
939}
940
b614ce89 941int sftp_cmd_close(struct sftp_command *cmd)
942{
943 if (back == NULL) {
38f0c08e 944 not_connected();
b614ce89 945 return 0;
946 }
947
948 if (back != NULL && back->socket(backhandle) != NULL) {
949 char ch;
950 back->special(backhandle, TS_EOF);
951 sftp_recvdata(&ch, 1);
952 }
953 do_sftp_cleanup();
954
955 return 0;
956}
957
93e86a8b 958/*
959 * List a directory. If no arguments are given, list pwd; otherwise
960 * list the directory given in words[1].
961 */
962int sftp_cmd_ls(struct sftp_command *cmd)
963{
964 struct fxp_handle *dirh;
965 struct fxp_names *names;
966 struct fxp_name **ournames;
967 int nnames, namesize;
3394416c 968 char *dir, *cdir, *unwcdir, *wildcard;
93e86a8b 969 struct sftp_packet *pktin;
970 struct sftp_request *req, *rreq;
971 int i;
972
973 if (back == NULL) {
38f0c08e 974 not_connected();
93e86a8b 975 return 0;
976 }
977
978 if (cmd->nwords < 2)
979 dir = ".";
980 else
981 dir = cmd->words[1];
982
3394416c 983 unwcdir = snewn(1 + strlen(dir), char);
984 if (wc_unescape(unwcdir, dir)) {
985 dir = unwcdir;
986 wildcard = NULL;
987 } else {
988 char *tmpdir;
989 int len, check;
990
991 wildcard = stripslashes(dir, 0);
992 unwcdir = dupstr(dir);
993 len = wildcard - dir;
994 unwcdir[len] = '\0';
995 if (len > 0 && unwcdir[len-1] == '/')
996 unwcdir[len-1] = '\0';
997 tmpdir = snewn(1 + len, char);
998 check = wc_unescape(tmpdir, unwcdir);
999 sfree(tmpdir);
1000 if (!check) {
1001 printf("Multiple-level wildcards are not supported\n");
1002 sfree(unwcdir);
1003 return 0;
1004 }
1005 dir = unwcdir;
1006 }
1007
93e86a8b 1008 cdir = canonify(dir);
1009 if (!cdir) {
1010 printf("%s: %s\n", dir, fxp_error());
3394416c 1011 sfree(unwcdir);
93e86a8b 1012 return 0;
1013 }
1014
1015 printf("Listing directory %s\n", cdir);
1016
1017 sftp_register(req = fxp_opendir_send(cdir));
1018 rreq = sftp_find_request(pktin = sftp_recv());
1019 assert(rreq == req);
1020 dirh = fxp_opendir_recv(pktin, rreq);
1021
1022 if (dirh == NULL) {
1023 printf("Unable to open %s: %s\n", dir, fxp_error());
1024 } else {
1025 nnames = namesize = 0;
1026 ournames = NULL;
1027
1028 while (1) {
1029
1030 sftp_register(req = fxp_readdir_send(dirh));
1031 rreq = sftp_find_request(pktin = sftp_recv());
1032 assert(rreq == req);
1033 names = fxp_readdir_recv(pktin, rreq);
1034
1035 if (names == NULL) {
1036 if (fxp_error_type() == SSH_FX_EOF)
1037 break;
1038 printf("Reading directory %s: %s\n", dir, fxp_error());
1039 break;
1040 }
1041 if (names->nnames == 0) {
1042 fxp_free_names(names);
1043 break;
1044 }
1045
1046 if (nnames + names->nnames >= namesize) {
1047 namesize += names->nnames + 128;
1048 ournames = sresize(ournames, namesize, struct fxp_name *);
1049 }
1050
1051 for (i = 0; i < names->nnames; i++)
3394416c 1052 if (!wildcard || wc_match(wildcard, names->names[i].filename))
1053 ournames[nnames++] = fxp_dup_name(&names->names[i]);
93e86a8b 1054
1055 fxp_free_names(names);
1056 }
1057 sftp_register(req = fxp_close_send(dirh));
1058 rreq = sftp_find_request(pktin = sftp_recv());
1059 assert(rreq == req);
1060 fxp_close_recv(pktin, rreq);
1061
1062 /*
1063 * Now we have our filenames. Sort them by actual file
1064 * name, and then output the longname parts.
1065 */
1066 qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
1067
1068 /*
1069 * And print them.
1070 */
1071 for (i = 0; i < nnames; i++) {
1072 printf("%s\n", ournames[i]->longname);
1073 fxp_free_name(ournames[i]);
1074 }
1075 sfree(ournames);
1076 }
1077
1078 sfree(cdir);
3394416c 1079 sfree(unwcdir);
93e86a8b 1080
1081 return 1;
1082}
1083
1084/*
1085 * Change directories. We do this by canonifying the new name, then
1086 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
1087 */
1088int sftp_cmd_cd(struct sftp_command *cmd)
1089{
1090 struct fxp_handle *dirh;
1091 struct sftp_packet *pktin;
1092 struct sftp_request *req, *rreq;
1093 char *dir;
1094
1095 if (back == NULL) {
38f0c08e 1096 not_connected();
93e86a8b 1097 return 0;
1098 }
1099
1100 if (cmd->nwords < 2)
1101 dir = dupstr(homedir);
1102 else
1103 dir = canonify(cmd->words[1]);
1104
1105 if (!dir) {
1106 printf("%s: %s\n", dir, fxp_error());
1107 return 0;
1108 }
1109
1110 sftp_register(req = fxp_opendir_send(dir));
1111 rreq = sftp_find_request(pktin = sftp_recv());
1112 assert(rreq == req);
1113 dirh = fxp_opendir_recv(pktin, rreq);
1114
1115 if (!dirh) {
1116 printf("Directory %s: %s\n", dir, fxp_error());
1117 sfree(dir);
1118 return 0;
1119 }
1120
1121 sftp_register(req = fxp_close_send(dirh));
1122 rreq = sftp_find_request(pktin = sftp_recv());
1123 assert(rreq == req);
1124 fxp_close_recv(pktin, rreq);
1125
1126 sfree(pwd);
1127 pwd = dir;
1128 printf("Remote directory is now %s\n", pwd);
1129
1130 return 1;
1131}
1132
1133/*
1134 * Print current directory. Easy as pie.
1135 */
1136int sftp_cmd_pwd(struct sftp_command *cmd)
1137{
1138 if (back == NULL) {
38f0c08e 1139 not_connected();
93e86a8b 1140 return 0;
1141 }
1142
1143 printf("Remote directory is %s\n", pwd);
1144 return 1;
1145}
1146
1147/*
9c77ddf6 1148 * Get a file and save it at the local end. We have three very
1149 * similar commands here. The basic one is `get'; `reget' differs
1150 * in that it checks for the existence of the destination file and
1151 * starts from where a previous aborted transfer left off; `mget'
1152 * differs in that it interprets all its arguments as files to
1153 * transfer (never as a different local name for a remote file) and
1154 * can handle wildcards.
93e86a8b 1155 */
9c77ddf6 1156int sftp_general_get(struct sftp_command *cmd, int restart, int multiple)
93e86a8b 1157{
5079ee6d 1158 char *fname, *unwcfname, *origfname, *origwfname, *outfname;
93e86a8b 1159 int i, ret;
1160 int recurse = FALSE;
1161
1162 if (back == NULL) {
38f0c08e 1163 not_connected();
93e86a8b 1164 return 0;
1165 }
1166
1167 i = 1;
1168 while (i < cmd->nwords && cmd->words[i][0] == '-') {
1169 if (!strcmp(cmd->words[i], "--")) {
1170 /* finish processing options */
1171 i++;
1172 break;
1173 } else if (!strcmp(cmd->words[i], "-r")) {
1174 recurse = TRUE;
1175 } else {
9033711a 1176 printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
93e86a8b 1177 return 0;
1178 }
1179 i++;
1180 }
1181
1182 if (i >= cmd->nwords) {
9033711a 1183 printf("%s: expects a filename\n", cmd->words[0]);
93e86a8b 1184 return 0;
1185 }
1186
5079ee6d 1187 ret = 1;
9c77ddf6 1188 do {
5079ee6d 1189 SftpWildcardMatcher *swcm;
1190
9c77ddf6 1191 origfname = cmd->words[i++];
5079ee6d 1192 unwcfname = snewn(strlen(origfname)+1, char);
93e86a8b 1193
5079ee6d 1194 if (multiple && !wc_unescape(unwcfname, origfname)) {
1195 swcm = sftp_begin_wildcard_matching(origfname);
1196 if (!swcm) {
1197 sfree(unwcfname);
1198 continue;
1199 }
1200 origwfname = sftp_wildcard_get_filename(swcm);
1201 if (!origwfname) {
1202 /* Politely warn the user that nothing matched. */
1203 printf("%s: nothing matched\n", origfname);
1204 sftp_finish_wildcard_matching(swcm);
1205 sfree(unwcfname);
1206 continue;
1207 }
9c77ddf6 1208 } else {
5079ee6d 1209 origwfname = origfname;
1210 swcm = NULL;
1211 }
1212
1213 while (origwfname) {
1214 fname = canonify(origwfname);
1215
9c77ddf6 1216 if (!fname) {
5079ee6d 1217 printf("%s: %s\n", origwfname, fxp_error());
9c77ddf6 1218 sfree(unwcfname);
1219 return 0;
1220 }
93e86a8b 1221
9c77ddf6 1222 if (!multiple && i < cmd->nwords)
1223 outfname = cmd->words[i++];
1224 else
5079ee6d 1225 outfname = stripslashes(origwfname, 0);
93e86a8b 1226
5079ee6d 1227 ret = sftp_get_file(fname, outfname, recurse, restart);
9c77ddf6 1228
1229 sfree(fname);
5079ee6d 1230
1231 if (swcm) {
1232 sfree(origwfname);
1233 origwfname = sftp_wildcard_get_filename(swcm);
1234 } else {
1235 origwfname = NULL;
1236 }
9c77ddf6 1237 }
1238 sfree(unwcfname);
5079ee6d 1239 if (swcm)
1240 sftp_finish_wildcard_matching(swcm);
9c77ddf6 1241 if (!ret)
1242 return ret;
1243
1244 } while (multiple && i < cmd->nwords);
93e86a8b 1245
1246 return ret;
1247}
1248int sftp_cmd_get(struct sftp_command *cmd)
1249{
9c77ddf6 1250 return sftp_general_get(cmd, 0, 0);
1251}
1252int sftp_cmd_mget(struct sftp_command *cmd)
1253{
1254 return sftp_general_get(cmd, 0, 1);
93e86a8b 1255}
1256int sftp_cmd_reget(struct sftp_command *cmd)
1257{
9c77ddf6 1258 return sftp_general_get(cmd, 1, 0);
93e86a8b 1259}
1260
1261/*
9c77ddf6 1262 * Send a file and store it at the remote end. We have three very
1263 * similar commands here. The basic one is `put'; `reput' differs
1264 * in that it checks for the existence of the destination file and
1265 * starts from where a previous aborted transfer left off; `mput'
1266 * differs in that it interprets all its arguments as files to
1267 * transfer (never as a different remote name for a local file) and
1268 * can handle wildcards.
93e86a8b 1269 */
9c77ddf6 1270int sftp_general_put(struct sftp_command *cmd, int restart, int multiple)
93e86a8b 1271{
5079ee6d 1272 char *fname, *wfname, *origoutfname, *outfname;
93e86a8b 1273 int i, ret;
1274 int recurse = FALSE;
1275
1276 if (back == NULL) {
38f0c08e 1277 not_connected();
93e86a8b 1278 return 0;
1279 }
1280
1281 i = 1;
1282 while (i < cmd->nwords && cmd->words[i][0] == '-') {
1283 if (!strcmp(cmd->words[i], "--")) {
1284 /* finish processing options */
1285 i++;
1286 break;
1287 } else if (!strcmp(cmd->words[i], "-r")) {
1288 recurse = TRUE;
1289 } else {
9033711a 1290 printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]);
93e86a8b 1291 return 0;
1292 }
1293 i++;
1294 }
1295
1296 if (i >= cmd->nwords) {
9033711a 1297 printf("%s: expects a filename\n", cmd->words[0]);
93e86a8b 1298 return 0;
1299 }
1300
5079ee6d 1301 ret = 1;
9c77ddf6 1302 do {
5079ee6d 1303 WildcardMatcher *wcm;
9c77ddf6 1304 fname = cmd->words[i++];
93e86a8b 1305
9c77ddf6 1306 if (multiple && test_wildcard(fname, FALSE) == WCTYPE_WILDCARD) {
5079ee6d 1307 wcm = begin_wildcard_matching(fname);
1308 wfname = wildcard_get_filename(wcm);
1309 if (!wfname) {
1310 /* Politely warn the user that nothing matched. */
1311 printf("%s: nothing matched\n", fname);
1312 finish_wildcard_matching(wcm);
1313 continue;
1314 }
9c77ddf6 1315 } else {
5079ee6d 1316 wfname = fname;
1317 wcm = NULL;
1318 }
1319
1320 while (wfname) {
9c77ddf6 1321 if (!multiple && i < cmd->nwords)
1322 origoutfname = cmd->words[i++];
1323 else
5079ee6d 1324 origoutfname = stripslashes(wfname, 1);
9c77ddf6 1325
1326 outfname = canonify(origoutfname);
1327 if (!outfname) {
1328 printf("%s: %s\n", origoutfname, fxp_error());
5079ee6d 1329 if (wcm) {
1330 sfree(wfname);
1331 finish_wildcard_matching(wcm);
1332 }
9c77ddf6 1333 return 0;
1334 }
5079ee6d 1335 ret = sftp_put_file(wfname, outfname, recurse, restart);
9c77ddf6 1336 sfree(outfname);
5079ee6d 1337
1338 if (wcm) {
1339 sfree(wfname);
1340 wfname = wildcard_get_filename(wcm);
1341 } else {
1342 wfname = NULL;
1343 }
9c77ddf6 1344 }
5079ee6d 1345
1346 if (wcm)
1347 finish_wildcard_matching(wcm);
1348
9c77ddf6 1349 if (!ret)
1350 return ret;
93e86a8b 1351
9c77ddf6 1352 } while (multiple && i < cmd->nwords);
4c7f0d61 1353
df49ff19 1354 return ret;
4c7f0d61 1355}
d92624dc 1356int sftp_cmd_put(struct sftp_command *cmd)
1357{
9c77ddf6 1358 return sftp_general_put(cmd, 0, 0);
1359}
1360int sftp_cmd_mput(struct sftp_command *cmd)
1361{
1362 return sftp_general_put(cmd, 0, 1);
d92624dc 1363}
1364int sftp_cmd_reput(struct sftp_command *cmd)
1365{
9c77ddf6 1366 return sftp_general_put(cmd, 1, 0);
d92624dc 1367}
4c7f0d61 1368
9954aaa3 1369int sftp_cmd_mkdir(struct sftp_command *cmd)
1370{
1371 char *dir;
1bc24185 1372 struct sftp_packet *pktin;
1373 struct sftp_request *req, *rreq;
9954aaa3 1374 int result;
83567e43 1375 int i, ret;
9954aaa3 1376
fa3db767 1377 if (back == NULL) {
38f0c08e 1378 not_connected();
fa3db767 1379 return 0;
1380 }
9954aaa3 1381
1382 if (cmd->nwords < 2) {
1383 printf("mkdir: expects a directory\n");
1384 return 0;
1385 }
1386
83567e43 1387 ret = 1;
1388 for (i = 1; i < cmd->nwords; i++) {
1389 dir = canonify(cmd->words[i]);
1390 if (!dir) {
1391 printf("%s: %s\n", dir, fxp_error());
1392 return 0;
1393 }
1394
1395 sftp_register(req = fxp_mkdir_send(dir));
1396 rreq = sftp_find_request(pktin = sftp_recv());
1397 assert(rreq == req);
1398 result = fxp_mkdir_recv(pktin, rreq);
1399
1400 if (!result) {
1401 printf("mkdir %s: %s\n", dir, fxp_error());
83567e43 1402 ret = 0;
f68363d2 1403 } else
1404 printf("mkdir %s: OK\n", dir);
83567e43 1405
1406 sfree(dir);
9954aaa3 1407 }
1408
83567e43 1409 return ret;
1410}
1411
1412static int sftp_action_rmdir(void *vctx, char *dir)
1413{
1414 struct sftp_packet *pktin;
1415 struct sftp_request *req, *rreq;
1416 int result;
1417
1418 sftp_register(req = fxp_rmdir_send(dir));
1bc24185 1419 rreq = sftp_find_request(pktin = sftp_recv());
1420 assert(rreq == req);
83567e43 1421 result = fxp_rmdir_recv(pktin, rreq);
1bc24185 1422
9954aaa3 1423 if (!result) {
83567e43 1424 printf("rmdir %s: %s\n", dir, fxp_error());
9954aaa3 1425 return 0;
1426 }
1427
f68363d2 1428 printf("rmdir %s: OK\n", dir);
1429
df49ff19 1430 return 1;
9954aaa3 1431}
1432
1433int sftp_cmd_rmdir(struct sftp_command *cmd)
1434{
83567e43 1435 int i, ret;
9954aaa3 1436
fa3db767 1437 if (back == NULL) {
38f0c08e 1438 not_connected();
fa3db767 1439 return 0;
1440 }
9954aaa3 1441
1442 if (cmd->nwords < 2) {
1443 printf("rmdir: expects a directory\n");
1444 return 0;
1445 }
1446
83567e43 1447 ret = 1;
1448 for (i = 1; i < cmd->nwords; i++)
1449 ret &= wildcard_iterate(cmd->words[i], sftp_action_rmdir, NULL);
9954aaa3 1450
83567e43 1451 return ret;
1452}
1453
1454static int sftp_action_rm(void *vctx, char *fname)
1455{
1456 struct sftp_packet *pktin;
1457 struct sftp_request *req, *rreq;
1458 int result;
1459
1460 sftp_register(req = fxp_remove_send(fname));
1bc24185 1461 rreq = sftp_find_request(pktin = sftp_recv());
1462 assert(rreq == req);
83567e43 1463 result = fxp_remove_recv(pktin, rreq);
1bc24185 1464
9954aaa3 1465 if (!result) {
83567e43 1466 printf("rm %s: %s\n", fname, fxp_error());
9954aaa3 1467 return 0;
1468 }
1469
f68363d2 1470 printf("rm %s: OK\n", fname);
1471
df49ff19 1472 return 1;
9954aaa3 1473}
1474
1475int sftp_cmd_rm(struct sftp_command *cmd)
1476{
83567e43 1477 int i, ret;
9954aaa3 1478
fa3db767 1479 if (back == NULL) {
38f0c08e 1480 not_connected();
fa3db767 1481 return 0;
1482 }
1483
9954aaa3 1484 if (cmd->nwords < 2) {
1485 printf("rm: expects a filename\n");
1486 return 0;
1487 }
1488
83567e43 1489 ret = 1;
1490 for (i = 1; i < cmd->nwords; i++)
1491 ret &= wildcard_iterate(cmd->words[i], sftp_action_rm, NULL);
1492
1493 return ret;
1494}
1495
1496static int check_is_dir(char *dstfname)
1497{
1498 struct sftp_packet *pktin;
1499 struct sftp_request *req, *rreq;
1500 struct fxp_attrs attrs;
1501 int result;
1502
1503 sftp_register(req = fxp_stat_send(dstfname));
1504 rreq = sftp_find_request(pktin = sftp_recv());
1505 assert(rreq == req);
1506 result = fxp_stat_recv(pktin, rreq, &attrs);
1507
1508 if (result &&
1509 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
1510 (attrs.permissions & 0040000))
1511 return TRUE;
1512 else
1513 return FALSE;
1514}
1515
1516struct sftp_context_mv {
1517 char *dstfname;
1518 int dest_is_dir;
1519};
1520
1521static int sftp_action_mv(void *vctx, char *srcfname)
1522{
1523 struct sftp_context_mv *ctx = (struct sftp_context_mv *)vctx;
1524 struct sftp_packet *pktin;
1525 struct sftp_request *req, *rreq;
1526 const char *error;
1527 char *finalfname, *newcanon = NULL;
1528 int ret, result;
1529
1530 if (ctx->dest_is_dir) {
1531 char *p;
1532 char *newname;
1533
1534 p = srcfname + strlen(srcfname);
1535 while (p > srcfname && p[-1] != '/') p--;
1536 newname = dupcat(ctx->dstfname, "/", p, NULL);
1537 newcanon = canonify(newname);
1538 if (!newcanon) {
1539 printf("%s: %s\n", newname, fxp_error());
1540 sfree(newname);
1541 return 0;
1542 }
1543 sfree(newname);
1544
1545 finalfname = newcanon;
1546 } else {
1547 finalfname = ctx->dstfname;
9954aaa3 1548 }
1549
83567e43 1550 sftp_register(req = fxp_rename_send(srcfname, finalfname));
1bc24185 1551 rreq = sftp_find_request(pktin = sftp_recv());
1552 assert(rreq == req);
83567e43 1553 result = fxp_rename_recv(pktin, rreq);
1bc24185 1554
83567e43 1555 error = result ? NULL : fxp_error();
1556
1557 if (error) {
1558 printf("mv %s %s: %s\n", srcfname, finalfname, error);
1559 ret = 0;
1560 } else {
1561 printf("%s -> %s\n", srcfname, finalfname);
1562 ret = 1;
9954aaa3 1563 }
1564
83567e43 1565 sfree(newcanon);
1566 return ret;
d92624dc 1567}
1568
1569int sftp_cmd_mv(struct sftp_command *cmd)
1570{
83567e43 1571 struct sftp_context_mv actx, *ctx = &actx;
1572 int i, ret;
d92624dc 1573
fa3db767 1574 if (back == NULL) {
38f0c08e 1575 not_connected();
fa3db767 1576 return 0;
1577 }
1578
d92624dc 1579 if (cmd->nwords < 3) {
1580 printf("mv: expects two filenames\n");
9954aaa3 1581 return 0;
d92624dc 1582 }
83567e43 1583
1584 ctx->dstfname = canonify(cmd->words[cmd->nwords-1]);
1585 if (!ctx->dstfname) {
1586 printf("%s: %s\n", ctx->dstfname, fxp_error());
d92624dc 1587 return 0;
1588 }
1589
83567e43 1590 /*
1591 * If there's more than one source argument, or one source
1592 * argument which is a wildcard, we _require_ that the
1593 * destination is a directory.
1594 */
1595 ctx->dest_is_dir = check_is_dir(ctx->dstfname);
1596 if ((cmd->nwords > 3 || is_wildcard(cmd->words[1])) && !ctx->dest_is_dir) {
1597 printf("mv: multiple or wildcard arguments require the destination"
1598 " to be a directory\n");
c4acc08c 1599 sfree(ctx->dstfname);
d92624dc 1600 return 0;
1601 }
9954aaa3 1602
83567e43 1603 /*
1604 * Now iterate over the source arguments.
1605 */
1606 ret = 1;
1607 for (i = 1; i < cmd->nwords-1; i++)
1608 ret &= wildcard_iterate(cmd->words[i], sftp_action_mv, ctx);
1609
c4acc08c 1610 sfree(ctx->dstfname);
83567e43 1611 return ret;
1612}
1613
1614struct sftp_context_chmod {
1615 unsigned attrs_clr, attrs_xor;
1616};
1617
1618static int sftp_action_chmod(void *vctx, char *fname)
1619{
1620 struct fxp_attrs attrs;
1621 struct sftp_packet *pktin;
1622 struct sftp_request *req, *rreq;
1623 int result;
1624 unsigned oldperms, newperms;
1625 struct sftp_context_chmod *ctx = (struct sftp_context_chmod *)vctx;
1626
1627 sftp_register(req = fxp_stat_send(fname));
1bc24185 1628 rreq = sftp_find_request(pktin = sftp_recv());
1629 assert(rreq == req);
83567e43 1630 result = fxp_stat_recv(pktin, rreq, &attrs);
1bc24185 1631
83567e43 1632 if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
1633 printf("get attrs for %s: %s\n", fname,
1634 result ? "file permissions not provided" : fxp_error());
83567e43 1635 return 0;
1636 }
d92624dc 1637
83567e43 1638 attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS; /* perms _only_ */
1639 oldperms = attrs.permissions & 07777;
1640 attrs.permissions &= ~ctx->attrs_clr;
1641 attrs.permissions ^= ctx->attrs_xor;
1642 newperms = attrs.permissions & 07777;
1bc24185 1643
83567e43 1644 if (oldperms == newperms)
1645 return 1; /* no need to do anything! */
1bc24185 1646
83567e43 1647 sftp_register(req = fxp_setstat_send(fname, attrs));
1648 rreq = sftp_find_request(pktin = sftp_recv());
1649 assert(rreq == req);
1650 result = fxp_setstat_recv(pktin, rreq);
1bc24185 1651
83567e43 1652 if (!result) {
1653 printf("set attrs for %s: %s\n", fname, fxp_error());
83567e43 1654 return 0;
d92624dc 1655 }
d92624dc 1656
83567e43 1657 printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
1658
df49ff19 1659 return 1;
9954aaa3 1660}
1661
d92624dc 1662int sftp_cmd_chmod(struct sftp_command *cmd)
1663{
83567e43 1664 char *mode;
1665 int i, ret;
1666 struct sftp_context_chmod actx, *ctx = &actx;
d92624dc 1667
fa3db767 1668 if (back == NULL) {
38f0c08e 1669 not_connected();
fa3db767 1670 return 0;
1671 }
1672
d92624dc 1673 if (cmd->nwords < 3) {
1674 printf("chmod: expects a mode specifier and a filename\n");
1675 return 0;
1676 }
1677
1678 /*
1679 * Attempt to parse the mode specifier in cmd->words[1]. We
1680 * don't support the full horror of Unix chmod; instead we
1681 * support a much simpler syntax in which the user can either
1682 * specify an octal number, or a comma-separated sequence of
1683 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
1684 * _only_ be omitted if the only attribute mentioned is t,
1685 * since all others require a user/group/other specification.
1686 * Additionally, the s attribute may not be specified for any
1687 * [ugoa] specifications other than exactly u or exactly g.
1688 */
83567e43 1689 ctx->attrs_clr = ctx->attrs_xor = 0;
d92624dc 1690 mode = cmd->words[1];
1691 if (mode[0] >= '0' && mode[0] <= '9') {
1692 if (mode[strspn(mode, "01234567")]) {
1693 printf("chmod: numeric file modes should"
1694 " contain digits 0-7 only\n");
1695 return 0;
1696 }
83567e43 1697 ctx->attrs_clr = 07777;
1698 sscanf(mode, "%o", &ctx->attrs_xor);
1699 ctx->attrs_xor &= ctx->attrs_clr;
d92624dc 1700 } else {
1701 while (*mode) {
1702 char *modebegin = mode;
1703 unsigned subset, perms;
1704 int action;
1705
1706 subset = 0;
1707 while (*mode && *mode != ',' &&
1708 *mode != '+' && *mode != '-' && *mode != '=') {
1709 switch (*mode) {
1710 case 'u': subset |= 04700; break; /* setuid, user perms */
1711 case 'g': subset |= 02070; break; /* setgid, group perms */
1712 case 'o': subset |= 00007; break; /* just other perms */
1713 case 'a': subset |= 06777; break; /* all of the above */
1714 default:
1715 printf("chmod: file mode '%.*s' contains unrecognised"
1716 " user/group/other specifier '%c'\n",
b51259f6 1717 (int)strcspn(modebegin, ","), modebegin, *mode);
d92624dc 1718 return 0;
1719 }
1720 mode++;
1721 }
1722 if (!*mode || *mode == ',') {
1723 printf("chmod: file mode '%.*s' is incomplete\n",
b51259f6 1724 (int)strcspn(modebegin, ","), modebegin);
d92624dc 1725 return 0;
1726 }
1727 action = *mode++;
1728 if (!*mode || *mode == ',') {
1729 printf("chmod: file mode '%.*s' is incomplete\n",
b51259f6 1730 (int)strcspn(modebegin, ","), modebegin);
d92624dc 1731 return 0;
1732 }
1733 perms = 0;
1734 while (*mode && *mode != ',') {
1735 switch (*mode) {
1736 case 'r': perms |= 00444; break;
1737 case 'w': perms |= 00222; break;
1738 case 'x': perms |= 00111; break;
1739 case 't': perms |= 01000; subset |= 01000; break;
1740 case 's':
1741 if ((subset & 06777) != 04700 &&
1742 (subset & 06777) != 02070) {
1743 printf("chmod: file mode '%.*s': set[ug]id bit should"
1744 " be used with exactly one of u or g only\n",
b51259f6 1745 (int)strcspn(modebegin, ","), modebegin);
d92624dc 1746 return 0;
1747 }
1748 perms |= 06000;
1749 break;
1750 default:
1751 printf("chmod: file mode '%.*s' contains unrecognised"
1752 " permission specifier '%c'\n",
b51259f6 1753 (int)strcspn(modebegin, ","), modebegin, *mode);
d92624dc 1754 return 0;
1755 }
1756 mode++;
1757 }
1758 if (!(subset & 06777) && (perms &~ subset)) {
1759 printf("chmod: file mode '%.*s' contains no user/group/other"
1760 " specifier and permissions other than 't' \n",
b51259f6 1761 (int)strcspn(modebegin, ","), modebegin);
d92624dc 1762 return 0;
1763 }
1764 perms &= subset;
1765 switch (action) {
1766 case '+':
83567e43 1767 ctx->attrs_clr |= perms;
1768 ctx->attrs_xor |= perms;
d92624dc 1769 break;
1770 case '-':
83567e43 1771 ctx->attrs_clr |= perms;
1772 ctx->attrs_xor &= ~perms;
d92624dc 1773 break;
1774 case '=':
83567e43 1775 ctx->attrs_clr |= subset;
1776 ctx->attrs_xor |= perms;
d92624dc 1777 break;
1778 }
1779 if (*mode) mode++; /* eat comma */
1780 }
1781 }
1782
83567e43 1783 ret = 1;
1784 for (i = 2; i < cmd->nwords; i++)
1785 ret &= wildcard_iterate(cmd->words[i], sftp_action_chmod, ctx);
d92624dc 1786
83567e43 1787 return ret;
d92624dc 1788}
9954aaa3 1789
fa3db767 1790static int sftp_cmd_open(struct sftp_command *cmd)
1791{
f11233cb 1792 int portnumber;
1793
fa3db767 1794 if (back != NULL) {
1795 printf("psftp: already connected\n");
1796 return 0;
1797 }
1798
1799 if (cmd->nwords < 2) {
1800 printf("open: expects a host name\n");
1801 return 0;
1802 }
1803
f11233cb 1804 if (cmd->nwords > 2) {
1805 portnumber = atoi(cmd->words[2]);
1806 if (portnumber == 0) {
1807 printf("open: invalid port number\n");
1808 return 0;
1809 }
1810 } else
1811 portnumber = 0;
1812
1813 if (psftp_connect(cmd->words[1], NULL, portnumber)) {
fa3db767 1814 back = NULL; /* connection is already closed */
1815 return -1; /* this is fatal */
1816 }
1817 do_sftp_init();
df49ff19 1818 return 1;
fa3db767 1819}
1820
3af97463 1821static int sftp_cmd_lcd(struct sftp_command *cmd)
1822{
d6cc41e6 1823 char *currdir, *errmsg;
3af97463 1824
1825 if (cmd->nwords < 2) {
1826 printf("lcd: expects a local directory name\n");
1827 return 0;
1828 }
1829
d6cc41e6 1830 errmsg = psftp_lcd(cmd->words[1]);
1831 if (errmsg) {
1832 printf("lcd: unable to change directory: %s\n", errmsg);
1833 sfree(errmsg);
3af97463 1834 return 0;
1835 }
1836
d6cc41e6 1837 currdir = psftp_getcwd();
3af97463 1838 printf("New local directory is %s\n", currdir);
1839 sfree(currdir);
1840
1841 return 1;
1842}
1843
1844static int sftp_cmd_lpwd(struct sftp_command *cmd)
1845{
1846 char *currdir;
3af97463 1847
d6cc41e6 1848 currdir = psftp_getcwd();
3af97463 1849 printf("Current local directory is %s\n", currdir);
1850 sfree(currdir);
1851
1852 return 1;
1853}
1854
1855static int sftp_cmd_pling(struct sftp_command *cmd)
1856{
1857 int exitcode;
1858
1859 exitcode = system(cmd->words[1]);
1860 return (exitcode == 0);
1861}
1862
bf5240cd 1863static int sftp_cmd_help(struct sftp_command *cmd);
1864
4c7f0d61 1865static struct sftp_cmd_lookup {
1866 char *name;
bf5240cd 1867 /*
1868 * For help purposes, there are two kinds of command:
1869 *
1870 * - primary commands, in which `longhelp' is non-NULL. In
1871 * this case `shorthelp' is descriptive text, and `longhelp'
1872 * is longer descriptive text intended to be printed after
1873 * the command name.
1874 *
1875 * - alias commands, in which `longhelp' is NULL. In this case
1876 * `shorthelp' is the name of a primary command, which
1877 * contains the help that should double up for this command.
1878 */
3af97463 1879 int listed; /* do we list this in primary help? */
bf5240cd 1880 char *shorthelp;
1881 char *longhelp;
32874aea 1882 int (*obey) (struct sftp_command *);
4c7f0d61 1883} sftp_lookup[] = {
1884 /*
1885 * List of sftp commands. This is binary-searched so it MUST be
1886 * in ASCII order.
1887 */
32874aea 1888 {
d6cc41e6 1889 "!", TRUE, "run a local command",
3af97463 1890 "<command>\n"
d6cc41e6 1891 /* FIXME: this example is crap for non-Windows. */
1892 " Runs a local command. For example, \"!del myfile\".\n",
3af97463 1893 sftp_cmd_pling
1894 },
1895 {
1896 "bye", TRUE, "finish your SFTP session",
bf5240cd 1897 "\n"
1898 " Terminates your SFTP session and quits the PSFTP program.\n",
1899 sftp_cmd_quit
1900 },
1901 {
3af97463 1902 "cd", TRUE, "change your remote working directory",
c1b8799b 1903 " [ <new working directory> ]\n"
bf5240cd 1904 " Change the remote working directory for your SFTP session.\n"
1905 " If a new working directory is not supplied, you will be\n"
1906 " returned to your home directory.\n",
1907 sftp_cmd_cd
1908 },
1909 {
3af97463 1910 "chmod", TRUE, "change file permissions and modes",
c1b8799b 1911 " <modes> <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
1912 " Change the file permissions on one or more remote files or\n"
1913 " directories.\n"
1914 " <modes> can be any octal Unix permission specifier.\n"
1915 " Alternatively, <modes> can include the following modifiers:\n"
bf5240cd 1916 " u+r make file readable by owning user\n"
1917 " u+w make file writable by owning user\n"
1918 " u+x make file executable by owning user\n"
1919 " u-r make file not readable by owning user\n"
1920 " [also u-w, u-x]\n"
1921 " g+r make file readable by members of owning group\n"
1922 " [also g+w, g+x, g-r, g-w, g-x]\n"
1923 " o+r make file readable by all other users\n"
1924 " [also o+w, o+x, o-r, o-w, o-x]\n"
1925 " a+r make file readable by absolutely everybody\n"
1926 " [also a+w, a+x, a-r, a-w, a-x]\n"
1927 " u+s enable the Unix set-user-ID bit\n"
1928 " u-s disable the Unix set-user-ID bit\n"
1929 " g+s enable the Unix set-group-ID bit\n"
1930 " g-s disable the Unix set-group-ID bit\n"
1931 " +t enable the Unix \"sticky bit\"\n"
1932 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1933 " more than one user for the same modifier (\"ug+w\"). You can\n"
1934 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1935 sftp_cmd_chmod
1936 },
1937 {
b614ce89 1938 "close", TRUE, "finish your SFTP session but do not quit PSFTP",
1939 "\n"
1940 " Terminates your SFTP session, but does not quit the PSFTP\n"
1941 " program. You can then use \"open\" to start another SFTP\n"
1942 " session, to the same server or to a different one.\n",
1943 sftp_cmd_close
1944 },
1945 {
c1b8799b 1946 "del", TRUE, "delete files on the remote server",
1947 " <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
1948 " Delete a file or files from the server.\n",
bf5240cd 1949 sftp_cmd_rm
1950 },
1951 {
3af97463 1952 "delete", FALSE, "del", NULL, sftp_cmd_rm
bf5240cd 1953 },
1954 {
c1b8799b 1955 "dir", TRUE, "list remote files",
9033711a 1956 " [ <directory-name> ]/[ <wildcard> ]\n"
bf5240cd 1957 " List the contents of a specified directory on the server.\n"
1958 " If <directory-name> is not given, the current working directory\n"
9033711a 1959 " is assumed.\n"
1960 " If <wildcard> is given, it is treated as a set of files to\n"
1961 " list; otherwise, all files are listed.\n",
bf5240cd 1962 sftp_cmd_ls
1963 },
1964 {
3af97463 1965 "exit", TRUE, "bye", NULL, sftp_cmd_quit
bf5240cd 1966 },
1967 {
3af97463 1968 "get", TRUE, "download a file from the server to your local machine",
9033711a 1969 " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
bf5240cd 1970 " Downloads a file on the server and stores it locally under\n"
1971 " the same name, or under a different one if you supply the\n"
9033711a 1972 " argument <local-filename>.\n"
1973 " If -r specified, recursively fetch a directory.\n",
bf5240cd 1974 sftp_cmd_get
1975 },
1976 {
3af97463 1977 "help", TRUE, "give help",
bf5240cd 1978 " [ <command> [ <command> ... ] ]\n"
1979 " Give general help if no commands are specified.\n"
1980 " If one or more commands are specified, give specific help on\n"
1981 " those particular commands.\n",
1982 sftp_cmd_help
1983 },
1984 {
3af97463 1985 "lcd", TRUE, "change local working directory",
1986 " <local-directory-name>\n"
1987 " Change the local working directory of the PSFTP program (the\n"
1988 " default location where the \"get\" command will save files).\n",
1989 sftp_cmd_lcd
1990 },
1991 {
1992 "lpwd", TRUE, "print local working directory",
1993 "\n"
1994 " Print the local working directory of the PSFTP program (the\n"
1995 " default location where the \"get\" command will save files).\n",
1996 sftp_cmd_lpwd
1997 },
1998 {
1999 "ls", TRUE, "dir", NULL,
bf5240cd 2000 sftp_cmd_ls
2001 },
2002 {
9c77ddf6 2003 "mget", TRUE, "download multiple files at once",
9033711a 2004 " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
9c77ddf6 2005 " Downloads many files from the server, storing each one under\n"
2006 " the same name it has on the server side. You can use wildcards\n"
9033711a 2007 " such as \"*.c\" to specify lots of files at once.\n"
2008 " If -r specified, recursively fetch files and directories.\n",
9c77ddf6 2009 sftp_cmd_mget
2010 },
2011 {
c1b8799b 2012 "mkdir", TRUE, "create directories on the remote server",
2013 " <directory-name> [ <directory-name>... ]\n"
2014 " Creates directories with the given names on the server.\n",
bf5240cd 2015 sftp_cmd_mkdir
2016 },
2017 {
9c77ddf6 2018 "mput", TRUE, "upload multiple files at once",
96515f61 2019 " [ -r ] [ -- ] <filename-or-wildcard> [ <filename-or-wildcard>... ]\n"
9c77ddf6 2020 " Uploads many files to the server, storing each one under the\n"
2021 " same name it has on the client side. You can use wildcards\n"
9033711a 2022 " such as \"*.c\" to specify lots of files at once.\n"
2023 " If -r specified, recursively store files and directories.\n",
9c77ddf6 2024 sftp_cmd_mput
2025 },
2026 {
c1b8799b 2027 "mv", TRUE, "move or rename file(s) on the remote server",
2028 " <source> [ <source>... ] <destination>\n"
2029 " Moves or renames <source>(s) on the server to <destination>,\n"
2030 " also on the server.\n"
2031 " If <destination> specifies an existing directory, then <source>\n"
2032 " may be a wildcard, and multiple <source>s may be given; all\n"
2033 " source files are moved into <destination>.\n"
2034 " Otherwise, <source> must specify a single file, which is moved\n"
2035 " or renamed so that it is accessible under the name <destination>.\n",
bf5240cd 2036 sftp_cmd_mv
2037 },
2038 {
3af97463 2039 "open", TRUE, "connect to a host",
f11233cb 2040 " [<user>@]<hostname> [<port>]\n"
fa3db767 2041 " Establishes an SFTP connection to a given host. Only usable\n"
c1b8799b 2042 " when you are not already connected to a server.\n",
fa3db767 2043 sftp_cmd_open
2044 },
2045 {
56542985 2046 "put", TRUE, "upload a file from your local machine to the server",
9033711a 2047 " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
56542985 2048 " Uploads a file to the server and stores it there under\n"
2049 " the same name, or under a different one if you supply the\n"
9033711a 2050 " argument <remote-filename>.\n"
2051 " If -r specified, recursively store a directory.\n",
56542985 2052 sftp_cmd_put
2053 },
2054 {
3af97463 2055 "pwd", TRUE, "print your remote working directory",
4f2b387f 2056 "\n"
2057 " Print the current remote working directory for your SFTP session.\n",
2058 sftp_cmd_pwd
2059 },
2060 {
3af97463 2061 "quit", TRUE, "bye", NULL,
bf5240cd 2062 sftp_cmd_quit
2063 },
2064 {
c1b8799b 2065 "reget", TRUE, "continue downloading files",
9033711a 2066 " [ -r ] [ -- ] <filename> [ <local-filename> ]\n"
bf5240cd 2067 " Works exactly like the \"get\" command, but the local file\n"
2068 " must already exist. The download will begin at the end of the\n"
9033711a 2069 " file. This is for resuming a download that was interrupted.\n"
2070 " If -r specified, resume interrupted \"get -r\".\n",
bf5240cd 2071 sftp_cmd_reget
2072 },
2073 {
3af97463 2074 "ren", TRUE, "mv", NULL,
bf5240cd 2075 sftp_cmd_mv
2076 },
2077 {
3af97463 2078 "rename", FALSE, "mv", NULL,
bf5240cd 2079 sftp_cmd_mv
2080 },
2081 {
c1b8799b 2082 "reput", TRUE, "continue uploading files",
9033711a 2083 " [ -r ] [ -- ] <filename> [ <remote-filename> ]\n"
bf5240cd 2084 " Works exactly like the \"put\" command, but the remote file\n"
2085 " must already exist. The upload will begin at the end of the\n"
9033711a 2086 " file. This is for resuming an upload that was interrupted.\n"
2087 " If -r specified, resume interrupted \"put -r\".\n",
bf5240cd 2088 sftp_cmd_reput
2089 },
2090 {
3af97463 2091 "rm", TRUE, "del", NULL,
bf5240cd 2092 sftp_cmd_rm
2093 },
2094 {
c1b8799b 2095 "rmdir", TRUE, "remove directories on the remote server",
2096 " <directory-name> [ <directory-name>... ]\n"
bf5240cd 2097 " Removes the directory with the given name on the server.\n"
c1b8799b 2098 " The directory will not be removed unless it is empty.\n"
2099 " Wildcards may be used to specify multiple directories.\n",
bf5240cd 2100 sftp_cmd_rmdir
2101 }
2102};
2103
2104const struct sftp_cmd_lookup *lookup_command(char *name)
2105{
2106 int i, j, k, cmp;
2107
2108 i = -1;
2109 j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
2110 while (j - i > 1) {
2111 k = (j + i) / 2;
2112 cmp = strcmp(name, sftp_lookup[k].name);
2113 if (cmp < 0)
2114 j = k;
2115 else if (cmp > 0)
2116 i = k;
2117 else {
2118 return &sftp_lookup[k];
2119 }
2120 }
2121 return NULL;
2122}
2123
2124static int sftp_cmd_help(struct sftp_command *cmd)
2125{
2126 int i;
2127 if (cmd->nwords == 1) {
2128 /*
2129 * Give short help on each command.
2130 */
2131 int maxlen;
2132 maxlen = 0;
2133 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
3af97463 2134 int len;
2135 if (!sftp_lookup[i].listed)
2136 continue;
2137 len = strlen(sftp_lookup[i].name);
bf5240cd 2138 if (maxlen < len)
2139 maxlen = len;
2140 }
2141 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
2142 const struct sftp_cmd_lookup *lookup;
3af97463 2143 if (!sftp_lookup[i].listed)
2144 continue;
bf5240cd 2145 lookup = &sftp_lookup[i];
2146 printf("%-*s", maxlen+2, lookup->name);
2147 if (lookup->longhelp == NULL)
2148 lookup = lookup_command(lookup->shorthelp);
2149 printf("%s\n", lookup->shorthelp);
2150 }
2151 } else {
2152 /*
2153 * Give long help on specific commands.
2154 */
2155 for (i = 1; i < cmd->nwords; i++) {
2156 const struct sftp_cmd_lookup *lookup;
2157 lookup = lookup_command(cmd->words[i]);
2158 if (!lookup) {
2159 printf("help: %s: command not found\n", cmd->words[i]);
2160 } else {
2161 printf("%s", lookup->name);
2162 if (lookup->longhelp == NULL)
2163 lookup = lookup_command(lookup->shorthelp);
2164 printf("%s", lookup->longhelp);
2165 }
2166 }
2167 }
df49ff19 2168 return 1;
bf5240cd 2169}
4c7f0d61 2170
2171/* ----------------------------------------------------------------------
2172 * Command line reading and parsing.
2173 */
9954aaa3 2174struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
32874aea 2175{
4c7f0d61 2176 char *line;
4c7f0d61 2177 struct sftp_command *cmd;
2178 char *p, *q, *r;
2179 int quoting;
2180
3d88e64d 2181 cmd = snew(struct sftp_command);
4c7f0d61 2182 cmd->words = NULL;
2183 cmd->nwords = 0;
2184 cmd->wordssize = 0;
2185
2186 line = NULL;
39934deb 2187
2188 if (fp) {
2189 if (modeflags & 1)
2190 printf("psftp> ");
2191 line = fgetline(fp);
2192 } else {
65857773 2193 line = ssh_sftp_get_cmdline("psftp> ", back == NULL);
4c7f0d61 2194 }
39934deb 2195
2196 if (!line || !*line) {
2197 cmd->obey = sftp_cmd_quit;
2198 if ((mode == 0) || (modeflags & 1))
2199 printf("quit\n");
2200 return cmd; /* eof */
2201 }
2202
2203 line[strcspn(line, "\r\n")] = '\0';
2204
df49ff19 2205 if (modeflags & 1) {
2206 printf("%s\n", line);
2207 }
4c7f0d61 2208
4c7f0d61 2209 p = line;
3af97463 2210 while (*p && (*p == ' ' || *p == '\t'))
2211 p++;
2212
2213 if (*p == '!') {
2214 /*
2215 * Special case: the ! command. This is always parsed as
2216 * exactly two words: one containing the !, and the second
2217 * containing everything else on the line.
2218 */
2219 cmd->nwords = cmd->wordssize = 2;
3d88e64d 2220 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
679539d7 2221 cmd->words[0] = dupstr("!");
2222 cmd->words[1] = dupstr(p+1);
3af97463 2223 } else {
2224
2225 /*
2226 * Parse the command line into words. The syntax is:
2227 * - double quotes are removed, but cause spaces within to be
2228 * treated as non-separating.
2229 * - a double-doublequote pair is a literal double quote, inside
2230 * _or_ outside quotes. Like this:
2231 *
2232 * firstword "second word" "this has ""quotes"" in" and""this""
2233 *
2234 * becomes
2235 *
2236 * >firstword<
2237 * >second word<
2238 * >this has "quotes" in<
2239 * >and"this"<
2240 */
4c7f0d61 2241 while (*p) {
3af97463 2242 /* skip whitespace */
2243 while (*p && (*p == ' ' || *p == '\t'))
2244 p++;
2245 /* mark start of word */
2246 q = r = p; /* q sits at start, r writes word */
2247 quoting = 0;
2248 while (*p) {
2249 if (!quoting && (*p == ' ' || *p == '\t'))
2250 break; /* reached end of word */
2251 else if (*p == '"' && p[1] == '"')
2252 p += 2, *r++ = '"'; /* a literal quote */
2253 else if (*p == '"')
2254 p++, quoting = !quoting;
2255 else
2256 *r++ = *p++;
2257 }
2258 if (*p)
2259 p++; /* skip over the whitespace */
2260 *r = '\0';
2261 if (cmd->nwords >= cmd->wordssize) {
2262 cmd->wordssize = cmd->nwords + 16;
3d88e64d 2263 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
3af97463 2264 }
679539d7 2265 cmd->words[cmd->nwords++] = dupstr(q);
4c7f0d61 2266 }
4c7f0d61 2267 }
2268
39934deb 2269 sfree(line);
2270
4c7f0d61 2271 /*
2272 * Now parse the first word and assign a function.
2273 */
2274
2275 if (cmd->nwords == 0)
2276 cmd->obey = sftp_cmd_null;
2277 else {
bf5240cd 2278 const struct sftp_cmd_lookup *lookup;
2279 lookup = lookup_command(cmd->words[0]);
2280 if (!lookup)
2281 cmd->obey = sftp_cmd_unknown;
2282 else
2283 cmd->obey = lookup->obey;
4c7f0d61 2284 }
2285
2286 return cmd;
2287}
2288
774204f5 2289static int do_sftp_init(void)
32874aea 2290{
1bc24185 2291 struct sftp_packet *pktin;
2292 struct sftp_request *req, *rreq;
2293
4c7f0d61 2294 /*
2295 * Do protocol initialisation.
2296 */
2297 if (!fxp_init()) {
2298 fprintf(stderr,
32874aea 2299 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
774204f5 2300 return 1; /* failure */
4c7f0d61 2301 }
2302
2303 /*
2304 * Find out where our home directory is.
2305 */
1bc24185 2306 sftp_register(req = fxp_realpath_send("."));
2307 rreq = sftp_find_request(pktin = sftp_recv());
2308 assert(rreq == req);
7b7de4f4 2309 homedir = fxp_realpath_recv(pktin, rreq);
1bc24185 2310
4c7f0d61 2311 if (!homedir) {
2312 fprintf(stderr,
2313 "Warning: failed to resolve home directory: %s\n",
2314 fxp_error());
2315 homedir = dupstr(".");
2316 } else {
2317 printf("Remote working directory is %s\n", homedir);
2318 }
2319 pwd = dupstr(homedir);
774204f5 2320 return 0;
fa3db767 2321}
2322
679539d7 2323void do_sftp_cleanup()
2324{
2325 char ch;
f11233cb 2326 if (back) {
2327 back->special(backhandle, TS_EOF);
2328 sftp_recvdata(&ch, 1);
2329 back->free(backhandle);
2330 sftp_cleanup_request();
65857773 2331 back = NULL;
2332 backhandle = NULL;
f11233cb 2333 }
679539d7 2334 if (pwd) {
2335 sfree(pwd);
2336 pwd = NULL;
2337 }
2338 if (homedir) {
2339 sfree(homedir);
2340 homedir = NULL;
2341 }
2342}
2343
fa3db767 2344void do_sftp(int mode, int modeflags, char *batchfile)
2345{
2346 FILE *fp;
df49ff19 2347 int ret;
4c7f0d61 2348
9954aaa3 2349 /*
2350 * Batch mode?
4c7f0d61 2351 */
9954aaa3 2352 if (mode == 0) {
2353
2354 /* ------------------------------------------------------------------
2355 * Now we're ready to do Real Stuff.
2356 */
2357 while (1) {
df49ff19 2358 struct sftp_command *cmd;
39934deb 2359 cmd = sftp_getcmd(NULL, 0, 0);
df49ff19 2360 if (!cmd)
2361 break;
679539d7 2362 ret = cmd->obey(cmd);
2363 if (cmd->words) {
2364 int i;
2365 for(i = 0; i < cmd->nwords; i++)
2366 sfree(cmd->words[i]);
2367 sfree(cmd->words);
2368 }
2369 sfree(cmd);
2370 if (ret < 0)
df49ff19 2371 break;
bf5240cd 2372 }
9954aaa3 2373 } else {
2374 fp = fopen(batchfile, "r");
2375 if (!fp) {
bf5240cd 2376 printf("Fatal: unable to open %s\n", batchfile);
2377 return;
9954aaa3 2378 }
2379 while (1) {
bf5240cd 2380 struct sftp_command *cmd;
2381 cmd = sftp_getcmd(fp, mode, modeflags);
2382 if (!cmd)
2383 break;
df49ff19 2384 ret = cmd->obey(cmd);
2385 if (ret < 0)
bf5240cd 2386 break;
df49ff19 2387 if (ret == 0) {
bf5240cd 2388 if (!(modeflags & 2))
9954aaa3 2389 break;
bf5240cd 2390 }
9954aaa3 2391 }
bf5240cd 2392 fclose(fp);
9954aaa3 2393
4c7f0d61 2394 }
4a8fc3c4 2395}
4c7f0d61 2396
4a8fc3c4 2397/* ----------------------------------------------------------------------
2398 * Dirty bits: integration with PuTTY.
2399 */
2400
2401static int verbose = 0;
2402
7bedb13c 2403/*
4a8fc3c4 2404 * Print an error message and perform a fatal exit.
2405 */
2406void fatalbox(char *fmt, ...)
2407{
57356d63 2408 char *str, *str2;
4a8fc3c4 2409 va_list ap;
2410 va_start(ap, fmt);
57356d63 2411 str = dupvprintf(fmt, ap);
2412 str2 = dupcat("Fatal: ", str, "\n", NULL);
2413 sfree(str);
4a8fc3c4 2414 va_end(ap);
57356d63 2415 fputs(str2, stderr);
2416 sfree(str2);
4a8fc3c4 2417
93b581bd 2418 cleanup_exit(1);
4a8fc3c4 2419}
1709795f 2420void modalfatalbox(char *fmt, ...)
2421{
57356d63 2422 char *str, *str2;
1709795f 2423 va_list ap;
2424 va_start(ap, fmt);
57356d63 2425 str = dupvprintf(fmt, ap);
2426 str2 = dupcat("Fatal: ", str, "\n", NULL);
2427 sfree(str);
1709795f 2428 va_end(ap);
57356d63 2429 fputs(str2, stderr);
2430 sfree(str2);
1709795f 2431
2432 cleanup_exit(1);
2433}
a8327734 2434void connection_fatal(void *frontend, char *fmt, ...)
4a8fc3c4 2435{
57356d63 2436 char *str, *str2;
4a8fc3c4 2437 va_list ap;
2438 va_start(ap, fmt);
57356d63 2439 str = dupvprintf(fmt, ap);
2440 str2 = dupcat("Fatal: ", str, "\n", NULL);
2441 sfree(str);
4a8fc3c4 2442 va_end(ap);
57356d63 2443 fputs(str2, stderr);
2444 sfree(str2);
4a8fc3c4 2445
93b581bd 2446 cleanup_exit(1);
4a8fc3c4 2447}
2448
6b78788a 2449void ldisc_send(void *handle, char *buf, int len, int interactive)
32874aea 2450{
4a8fc3c4 2451 /*
2452 * This is only here because of the calls to ldisc_send(NULL,
2453 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
2454 * ldisc as an ldisc. So if we get called with any real data, I
2455 * want to know about it.
4c7f0d61 2456 */
4a8fc3c4 2457 assert(len == 0);
2458}
2459
2460/*
c44bf5bd 2461 * In psftp, all agent requests should be synchronous, so this is a
2462 * never-called stub.
2463 */
2464void agent_schedule_callback(void (*callback)(void *, void *, int),
2465 void *callback_ctx, void *data, int len)
2466{
2467 assert(!"We shouldn't be here");
2468}
2469
2470/*
4a8fc3c4 2471 * Receive a block of data from the SSH link. Block until all data
2472 * is available.
2473 *
2474 * To do this, we repeatedly call the SSH protocol module, with our
2475 * own trap in from_backend() to catch the data that comes back. We
2476 * do this until we have enough data.
2477 */
2478
32874aea 2479static unsigned char *outptr; /* where to put the data */
2480static unsigned outlen; /* how much data required */
4a8fc3c4 2481static unsigned char *pending = NULL; /* any spare data */
32874aea 2482static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
9fab77dc 2483int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
32874aea 2484{
2485 unsigned char *p = (unsigned char *) data;
2486 unsigned len = (unsigned) datalen;
4a8fc3c4 2487
2488 /*
2489 * stderr data is just spouted to local stderr and otherwise
2490 * ignored.
2491 */
2492 if (is_stderr) {
bfa5400d 2493 if (len > 0)
2494 fwrite(data, 1, len, stderr);
5471d09a 2495 return 0;
4a8fc3c4 2496 }
2497
2498 /*
2499 * If this is before the real session begins, just return.
2500 */
2501 if (!outptr)
5471d09a 2502 return 0;
4a8fc3c4 2503
bfa5400d 2504 if ((outlen > 0) && (len > 0)) {
32874aea 2505 unsigned used = outlen;
2506 if (used > len)
2507 used = len;
2508 memcpy(outptr, p, used);
2509 outptr += used;
2510 outlen -= used;
2511 p += used;
2512 len -= used;
4a8fc3c4 2513 }
2514
2515 if (len > 0) {
32874aea 2516 if (pendsize < pendlen + len) {
2517 pendsize = pendlen + len + 4096;
3d88e64d 2518 pending = sresize(pending, pendsize, unsigned char);
32874aea 2519 }
2520 memcpy(pending + pendlen, p, len);
2521 pendlen += len;
4a8fc3c4 2522 }
5471d09a 2523
2524 return 0;
4a8fc3c4 2525}
edd0cb8a 2526int from_backend_untrusted(void *frontend_handle, const char *data, int len)
2527{
2528 /*
2529 * No "untrusted" output should get here (the way the code is
2530 * currently, it's all diverted by FLAG_STDERR).
2531 */
2532 assert(!"Unexpected call to from_backend_untrusted()");
2533 return 0; /* not reached */
2534}
32874aea 2535int sftp_recvdata(char *buf, int len)
2536{
2537 outptr = (unsigned char *) buf;
4a8fc3c4 2538 outlen = len;
2539
2540 /*
2541 * See if the pending-input block contains some of what we
2542 * need.
2543 */
2544 if (pendlen > 0) {
32874aea 2545 unsigned pendused = pendlen;
2546 if (pendused > outlen)
2547 pendused = outlen;
4a8fc3c4 2548 memcpy(outptr, pending, pendused);
32874aea 2549 memmove(pending, pending + pendused, pendlen - pendused);
4a8fc3c4 2550 outptr += pendused;
2551 outlen -= pendused;
32874aea 2552 pendlen -= pendused;
2553 if (pendlen == 0) {
2554 pendsize = 0;
2555 sfree(pending);
2556 pending = NULL;
2557 }
2558 if (outlen == 0)
2559 return 1;
4a8fc3c4 2560 }
2561
2562 while (outlen > 0) {
d6cc41e6 2563 if (ssh_sftp_loop_iteration() < 0)
32874aea 2564 return 0; /* doom */
4a8fc3c4 2565 }
2566
2567 return 1;
2568}
32874aea 2569int sftp_senddata(char *buf, int len)
2570{
776792d7 2571 back->send(backhandle, buf, len);
4a8fc3c4 2572 return 1;
2573}
2574
2575/*
4a8fc3c4 2576 * Short description of parameters.
2577 */
2578static void usage(void)
2579{
2580 printf("PuTTY Secure File Transfer (SFTP) client\n");
2581 printf("%s\n", ver);
90767715 2582 printf("Usage: psftp [options] [user@]host\n");
4a8fc3c4 2583 printf("Options:\n");
2285d016 2584 printf(" -V print version information and exit\n");
2585 printf(" -pgpfp print PGP key fingerprints and exit\n");
9954aaa3 2586 printf(" -b file use specified batchfile\n");
2587 printf(" -bc output batchfile commands\n");
2588 printf(" -be don't stop batchfile processing if errors\n");
4a8fc3c4 2589 printf(" -v show verbose messages\n");
e2a197cf 2590 printf(" -load sessname Load settings from saved session\n");
2591 printf(" -l user connect with specified username\n");
4a8fc3c4 2592 printf(" -P port connect to specified port\n");
2593 printf(" -pw passw login with specified password\n");
e2a197cf 2594 printf(" -1 -2 force use of particular SSH protocol version\n");
05581745 2595 printf(" -4 -6 force use of IPv4 or IPv6\n");
e2a197cf 2596 printf(" -C enable compression\n");
2597 printf(" -i key private key file for authentication\n");
2598 printf(" -batch disable all interactive prompts\n");
93b581bd 2599 cleanup_exit(1);
4a8fc3c4 2600}
2601
dc108ebc 2602static void version(void)
2603{
2604 printf("psftp: %s\n", ver);
2605 cleanup_exit(1);
2606}
2607
4a8fc3c4 2608/*
fa3db767 2609 * Connect to a host.
4a8fc3c4 2610 */
fa3db767 2611static int psftp_connect(char *userhost, char *user, int portnumber)
4a8fc3c4 2612{
fa3db767 2613 char *host, *realhost;
cbe2d68f 2614 const char *err;
b51259f6 2615 void *logctx;
4a8fc3c4 2616
2617 /* Separate host and username */
2618 host = userhost;
2619 host = strrchr(host, '@');
2620 if (host == NULL) {
2621 host = userhost;
2622 } else {
2623 *host++ = '\0';
2624 if (user) {
32874aea 2625 printf("psftp: multiple usernames specified; using \"%s\"\n",
2626 user);
4a8fc3c4 2627 } else
2628 user = userhost;
2629 }
2630
18e62ad8 2631 /*
2632 * If we haven't loaded session details already (e.g., from -load),
2633 * try looking for a session called "host".
2634 */
2635 if (!loaded_session) {
2636 /* Try to load settings for `host' into a temporary config */
2637 Config cfg2;
2638 cfg2.host[0] = '\0';
2639 do_defaults(host, &cfg2);
2640 if (cfg2.host[0] != '\0') {
2641 /* Settings present and include hostname */
2642 /* Re-load data into the real config. */
2643 do_defaults(host, &cfg);
2644 } else {
2645 /* Session doesn't exist or mention a hostname. */
2646 /* Use `host' as a bare hostname. */
2647 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
2648 cfg.host[sizeof(cfg.host) - 1] = '\0';
2649 }
2650 } else {
2651 /* Patch in hostname `host' to session details. */
32874aea 2652 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
2653 cfg.host[sizeof(cfg.host) - 1] = '\0';
f133db8e 2654 }
2655
2656 /*
2657 * Force use of SSH. (If they got the protocol wrong we assume the
2658 * port is useless too.)
2659 */
2660 if (cfg.protocol != PROT_SSH) {
2661 cfg.protocol = PROT_SSH;
2662 cfg.port = 22;
4a8fc3c4 2663 }
2664
449925a6 2665 /*
4123fa9a 2666 * If saved session / Default Settings says SSH-1 (`1 only' or `1'),
2667 * then change it to SSH-2, on the grounds that that's more likely to
2668 * work for SFTP. (Can be overridden with `-1' option.)
2669 * But if it says `2 only' or `2', respect which.
2670 */
2671 if (cfg.sshprot != 2 && cfg.sshprot != 3)
2672 cfg.sshprot = 2;
2673
2674 /*
c0a81592 2675 * Enact command-line overrides.
2676 */
5555d393 2677 cmdline_run_saved(&cfg);
c0a81592 2678
2679 /*
449925a6 2680 * Trim leading whitespace off the hostname if it's there.
2681 */
2682 {
2683 int space = strspn(cfg.host, " \t");
2684 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
2685 }
2686
2687 /* See if host is of the form user@host */
2688 if (cfg.host[0] != '\0') {
5dd103a8 2689 char *atsign = strrchr(cfg.host, '@');
449925a6 2690 /* Make sure we're not overflowing the user field */
2691 if (atsign) {
2692 if (atsign - cfg.host < sizeof cfg.username) {
2693 strncpy(cfg.username, cfg.host, atsign - cfg.host);
2694 cfg.username[atsign - cfg.host] = '\0';
2695 }
2696 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
2697 }
2698 }
2699
2700 /*
2701 * Trim a colon suffix off the hostname if it's there.
2702 */
2703 cfg.host[strcspn(cfg.host, ":")] = '\0';
2704
cae0c023 2705 /*
2706 * Remove any remaining whitespace from the hostname.
2707 */
2708 {
2709 int p1 = 0, p2 = 0;
2710 while (cfg.host[p2] != '\0') {
2711 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
2712 cfg.host[p1] = cfg.host[p2];
2713 p1++;
2714 }
2715 p2++;
2716 }
2717 cfg.host[p1] = '\0';
2718 }
2719
4a8fc3c4 2720 /* Set username */
2721 if (user != NULL && user[0] != '\0') {
32874aea 2722 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
2723 cfg.username[sizeof(cfg.username) - 1] = '\0';
4a8fc3c4 2724 }
2725 if (!cfg.username[0]) {
edd0cb8a 2726 /* FIXME: leave this to ssh.c? */
2727 int ret;
2728 prompts_t *p = new_prompts(NULL);
2729 p->to_server = TRUE;
2730 p->name = dupstr("SSH login name");
2731 add_prompt(p, dupstr("login as: "), TRUE, lenof(cfg.username));
2732 ret = get_userpass_input(p, NULL, 0);
2733 assert(ret >= 0);
2734 if (!ret) {
2735 free_prompts(p);
b5af97b3 2736 fprintf(stderr, "psftp: no username, aborting\n");
93b581bd 2737 cleanup_exit(1);
4a8fc3c4 2738 } else {
edd0cb8a 2739 memcpy(cfg.username, p->prompts[0]->result, lenof(cfg.username));
2740 free_prompts(p);
4a8fc3c4 2741 }
2742 }
2743
4a8fc3c4 2744 if (portnumber)
2745 cfg.port = portnumber;
2746
d27b4a18 2747 /*
2748 * Disable scary things which shouldn't be enabled for simple
2749 * things like SCP and SFTP: agent forwarding, port forwarding,
2750 * X forwarding.
2751 */
2752 cfg.x11_forward = 0;
2753 cfg.agentfwd = 0;
2754 cfg.portfwd[0] = cfg.portfwd[1] = '\0';
2755
bebf22d0 2756 /* Set up subsystem name. */
4a8fc3c4 2757 strcpy(cfg.remote_cmd, "sftp");
2758 cfg.ssh_subsys = TRUE;
2759 cfg.nopty = TRUE;
2760
bebf22d0 2761 /*
2e85c969 2762 * Set up fallback option, for SSH-1 servers or servers with the
bebf22d0 2763 * sftp subsystem not enabled but the server binary installed
2764 * in the usual place. We only support fallback on Unix
248c0c5a 2765 * systems, and we use a kludgy piece of shellery which should
2766 * try to find sftp-server in various places (the obvious
2767 * systemwide spots /usr/lib and /usr/local/lib, and then the
2768 * user's PATH) and finally give up.
bebf22d0 2769 *
248c0c5a 2770 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
2771 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
2772 * exec sftp-server
bebf22d0 2773 *
2774 * the idea being that this will attempt to use either of the
2775 * obvious pathnames and then give up, and when it does give up
2776 * it will print the preferred pathname in the error messages.
2777 */
2778 cfg.remote_cmd_ptr2 =
248c0c5a 2779 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
2780 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
2781 "exec sftp-server";
bebf22d0 2782 cfg.ssh_subsys2 = FALSE;
2783
4a8fc3c4 2784 back = &ssh_backend;
2785
79bf227b 2786 err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,
2787 0, cfg.tcp_keepalives);
4a8fc3c4 2788 if (err != NULL) {
fa3db767 2789 fprintf(stderr, "ssh_init: %s\n", err);
4a8fc3c4 2790 return 1;
2791 }
c229ef97 2792 logctx = log_init(NULL, &cfg);
a8327734 2793 back->provide_logctx(backhandle, logctx);
d3fef4a5 2794 console_provide_logctx(logctx);
d6cc41e6 2795 while (!back->sendok(backhandle)) {
2796 if (ssh_sftp_loop_iteration() < 0) {
2797 fprintf(stderr, "ssh_init: error during SSH connection setup\n");
2798 return 1;
2799 }
2800 }
4a8fc3c4 2801 if (verbose && realhost != NULL)
2802 printf("Connected to %s\n", realhost);
679539d7 2803 if (realhost != NULL)
2804 sfree(realhost);
fa3db767 2805 return 0;
2806}
2807
c0a81592 2808void cmdline_error(char *p, ...)
2809{
2810 va_list ap;
86256dc6 2811 fprintf(stderr, "psftp: ");
c0a81592 2812 va_start(ap, p);
2813 vfprintf(stderr, p, ap);
2814 va_end(ap);
86256dc6 2815 fprintf(stderr, "\n try typing \"psftp -h\" for help\n");
c0a81592 2816 exit(1);
2817}
2818
fa3db767 2819/*
2820 * Main program. Parse arguments etc.
2821 */
d6cc41e6 2822int psftp_main(int argc, char *argv[])
fa3db767 2823{
2824 int i;
2825 int portnumber = 0;
2826 char *userhost, *user;
2827 int mode = 0;
2828 int modeflags = 0;
2829 char *batchfile = NULL;
86256dc6 2830 int errors = 0;
fa3db767 2831
b51259f6 2832 flags = FLAG_STDERR | FLAG_INTERACTIVE
2833#ifdef FLAG_SYNCAGENT
2834 | FLAG_SYNCAGENT
2835#endif
2836 ;
c0a81592 2837 cmdline_tooltype = TOOLTYPE_FILETRANSFER;
fa3db767 2838 sk_init();
2839
2840 userhost = user = NULL;
2841
18e62ad8 2842 /* Load Default Settings before doing anything else. */
2843 do_defaults(NULL, &cfg);
2844 loaded_session = FALSE;
2845
86256dc6 2846 errors = 0;
fa3db767 2847 for (i = 1; i < argc; i++) {
c0a81592 2848 int ret;
fa3db767 2849 if (argv[i][0] != '-') {
c0a81592 2850 if (userhost)
2851 usage();
2852 else
2853 userhost = dupstr(argv[i]);
2854 continue;
2855 }
5555d393 2856 ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
c0a81592 2857 if (ret == -2) {
2858 cmdline_error("option \"%s\" requires an argument", argv[i]);
2859 } else if (ret == 2) {
2860 i++; /* skip next argument */
2861 } else if (ret == 1) {
2862 /* We have our own verbosity in addition to `flags'. */
2863 if (flags & FLAG_VERBOSE)
2864 verbose = 1;
fa3db767 2865 } else if (strcmp(argv[i], "-h") == 0 ||
2866 strcmp(argv[i], "-?") == 0) {
2867 usage();
2285d016 2868 } else if (strcmp(argv[i], "-pgpfp") == 0) {
2869 pgp_fingerprints();
2870 return 1;
dc108ebc 2871 } else if (strcmp(argv[i], "-V") == 0) {
2872 version();
c0a81592 2873 } else if (strcmp(argv[i], "-batch") == 0) {
2874 console_batch_mode = 1;
fa3db767 2875 } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
2876 mode = 1;
2877 batchfile = argv[++i];
d13c2ee9 2878 } else if (strcmp(argv[i], "-bc") == 0) {
fa3db767 2879 modeflags = modeflags | 1;
d13c2ee9 2880 } else if (strcmp(argv[i], "-be") == 0) {
fa3db767 2881 modeflags = modeflags | 2;
2882 } else if (strcmp(argv[i], "--") == 0) {
2883 i++;
2884 break;
2885 } else {
86256dc6 2886 cmdline_error("unknown option \"%s\"", argv[i]);
fa3db767 2887 }
2888 }
2889 argc -= i;
2890 argv += i;
2891 back = NULL;
2892
2893 /*
e1bb41d1 2894 * If the loaded session provides a hostname, and a hostname has not
2895 * otherwise been specified, pop it in `userhost' so that
2896 * `psftp -load sessname' is sufficient to start a session.
2897 */
2898 if (!userhost && cfg.host[0] != '\0') {
2899 userhost = dupstr(cfg.host);
2900 }
2901
2902 /*
fa3db767 2903 * If a user@host string has already been provided, connect to
2904 * it now.
2905 */
2906 if (userhost) {
679539d7 2907 int ret;
2908 ret = psftp_connect(userhost, user, portnumber);
2909 sfree(userhost);
2910 if (ret)
fa3db767 2911 return 1;
774204f5 2912 if (do_sftp_init())
2913 return 1;
fa3db767 2914 } else {
2915 printf("psftp: no hostname specified; use \"open host.name\""
679539d7 2916 " to connect\n");
fa3db767 2917 }
4c7f0d61 2918
9954aaa3 2919 do_sftp(mode, modeflags, batchfile);
4a8fc3c4 2920
51470298 2921 if (back != NULL && back->socket(backhandle) != NULL) {
4a8fc3c4 2922 char ch;
51470298 2923 back->special(backhandle, TS_EOF);
4a8fc3c4 2924 sftp_recvdata(&ch, 1);
2925 }
b614ce89 2926 do_sftp_cleanup();
4a8fc3c4 2927 random_save_seed();
679539d7 2928 cmdline_cleanup();
2929 console_provide_logctx(NULL);
679539d7 2930 sk_cleanup();
4a8fc3c4 2931
4c7f0d61 2932 return 0;
2933}