First cut at speeding up SFTP. Generic download-management code in
[u/mdw/putty] / psftp.c
CommitLineData
4c7f0d61 1/*
2 * psftp.c: front end for PSFTP.
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);
fa3db767 28
4c7f0d61 29/* ----------------------------------------------------------------------
4c7f0d61 30 * sftp client state.
31 */
32
33char *pwd, *homedir;
6b78788a 34static Backend *back;
35static void *backhandle;
3ea863a3 36static Config cfg;
4c7f0d61 37
38/* ----------------------------------------------------------------------
39 * Higher-level helper functions used in commands.
40 */
41
42/*
f9e162aa 43 * Attempt to canonify a pathname starting from the pwd. If
44 * canonification fails, at least fall back to returning a _valid_
45 * pathname (though it may be ugly, eg /home/simon/../foobar).
4c7f0d61 46 */
32874aea 47char *canonify(char *name)
48{
f9e162aa 49 char *fullname, *canonname;
1bc24185 50 struct sftp_packet *pktin;
51 struct sftp_request *req, *rreq;
4a8fc3c4 52
f9e162aa 53 if (name[0] == '/') {
54 fullname = dupstr(name);
55 } else {
4a8fc3c4 56 char *slash;
32874aea 57 if (pwd[strlen(pwd) - 1] == '/')
4a8fc3c4 58 slash = "";
59 else
60 slash = "/";
61 fullname = dupcat(pwd, slash, name, NULL);
f9e162aa 62 }
4a8fc3c4 63
1bc24185 64 sftp_register(req = fxp_realpath_send(fullname));
65 rreq = sftp_find_request(pktin = sftp_recv());
66 assert(rreq == req);
7b7de4f4 67 canonname = fxp_realpath_recv(pktin, rreq);
4a8fc3c4 68
f9e162aa 69 if (canonname) {
70 sfree(fullname);
71 return canonname;
50d7e054 72 } else {
32874aea 73 /*
74 * Attempt number 2. Some FXP_REALPATH implementations
75 * (glibc-based ones, in particular) require the _whole_
76 * path to point to something that exists, whereas others
77 * (BSD-based) only require all but the last component to
78 * exist. So if the first call failed, we should strip off
79 * everything from the last slash onwards and try again,
80 * then put the final component back on.
81 *
82 * Special cases:
83 *
84 * - if the last component is "/." or "/..", then we don't
85 * bother trying this because there's no way it can work.
86 *
87 * - if the thing actually ends with a "/", we remove it
88 * before we start. Except if the string is "/" itself
89 * (although I can't see why we'd have got here if so,
90 * because surely "/" would have worked the first
91 * time?), in which case we don't bother.
92 *
93 * - if there's no slash in the string at all, give up in
94 * confusion (we expect at least one because of the way
95 * we constructed the string).
96 */
97
98 int i;
99 char *returnname;
100
101 i = strlen(fullname);
102 if (i > 2 && fullname[i - 1] == '/')
103 fullname[--i] = '\0'; /* strip trailing / unless at pos 0 */
104 while (i > 0 && fullname[--i] != '/');
105
106 /*
107 * Give up on special cases.
108 */
109 if (fullname[i] != '/' || /* no slash at all */
110 !strcmp(fullname + i, "/.") || /* ends in /. */
111 !strcmp(fullname + i, "/..") || /* ends in /.. */
112 !strcmp(fullname, "/")) {
113 return fullname;
114 }
115
116 /*
117 * Now i points at the slash. Deal with the final special
118 * case i==0 (ie the whole path was "/nonexistentfile").
119 */
120 fullname[i] = '\0'; /* separate the string */
121 if (i == 0) {
1bc24185 122 sftp_register(req = fxp_realpath_send("/"));
32874aea 123 } else {
1bc24185 124 sftp_register(req = fxp_realpath_send(fullname));
32874aea 125 }
1bc24185 126 rreq = sftp_find_request(pktin = sftp_recv());
127 assert(rreq == req);
7b7de4f4 128 canonname = fxp_realpath_recv(pktin, rreq);
32874aea 129
130 if (!canonname)
131 return fullname; /* even that failed; give up */
132
133 /*
134 * We have a canonical name for all but the last path
135 * component. Concatenate the last component and return.
136 */
137 returnname = dupcat(canonname,
138 canonname[strlen(canonname) - 1] ==
139 '/' ? "" : "/", fullname + i + 1, NULL);
140 sfree(fullname);
141 sfree(canonname);
142 return returnname;
50d7e054 143 }
4c7f0d61 144}
145
dcf8495c 146/*
147 * Return a pointer to the portion of str that comes after the last
148 * slash (or backslash or colon, if `local' is TRUE).
149 */
150static char *stripslashes(char *str, int local)
151{
152 char *p;
153
154 if (local) {
155 p = strchr(str, ':');
156 if (p) str = p+1;
157 }
158
159 p = strrchr(str, '/');
160 if (p) str = p+1;
161
162 if (local) {
163 p = strrchr(str, '\\');
164 if (p) str = p+1;
165 }
166
167 return str;
168}
169
4c7f0d61 170/* ----------------------------------------------------------------------
171 * Actual sftp commands.
172 */
173struct sftp_command {
174 char **words;
175 int nwords, wordssize;
32874aea 176 int (*obey) (struct sftp_command *); /* returns <0 to quit */
4c7f0d61 177};
178
32874aea 179int sftp_cmd_null(struct sftp_command *cmd)
180{
df49ff19 181 return 1; /* success */
4c7f0d61 182}
183
32874aea 184int sftp_cmd_unknown(struct sftp_command *cmd)
185{
4c7f0d61 186 printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
df49ff19 187 return 0; /* failure */
4c7f0d61 188}
189
32874aea 190int sftp_cmd_quit(struct sftp_command *cmd)
191{
4c7f0d61 192 return -1;
193}
194
195/*
196 * List a directory. If no arguments are given, list pwd; otherwise
197 * list the directory given in words[1].
198 */
32874aea 199static int sftp_ls_compare(const void *av, const void *bv)
200{
7d2c1789 201 const struct fxp_name *const *a = (const struct fxp_name *const *) av;
202 const struct fxp_name *const *b = (const struct fxp_name *const *) bv;
203 return strcmp((*a)->filename, (*b)->filename);
4c7f0d61 204}
32874aea 205int sftp_cmd_ls(struct sftp_command *cmd)
206{
4c7f0d61 207 struct fxp_handle *dirh;
208 struct fxp_names *names;
7d2c1789 209 struct fxp_name **ournames;
4c7f0d61 210 int nnames, namesize;
211 char *dir, *cdir;
1bc24185 212 struct sftp_packet *pktin;
213 struct sftp_request *req, *rreq;
4c7f0d61 214 int i;
215
fa3db767 216 if (back == NULL) {
217 printf("psftp: not connected to a host; use \"open host.name\"\n");
218 return 0;
219 }
220
4c7f0d61 221 if (cmd->nwords < 2)
222 dir = ".";
223 else
224 dir = cmd->words[1];
225
226 cdir = canonify(dir);
227 if (!cdir) {
228 printf("%s: %s\n", dir, fxp_error());
229 return 0;
230 }
231
232 printf("Listing directory %s\n", cdir);
233
1bc24185 234 sftp_register(req = fxp_opendir_send(cdir));
235 rreq = sftp_find_request(pktin = sftp_recv());
236 assert(rreq == req);
7b7de4f4 237 dirh = fxp_opendir_recv(pktin, rreq);
1bc24185 238
4c7f0d61 239 if (dirh == NULL) {
240 printf("Unable to open %s: %s\n", dir, fxp_error());
241 } else {
242 nnames = namesize = 0;
243 ournames = NULL;
244
245 while (1) {
246
1bc24185 247 sftp_register(req = fxp_readdir_send(dirh));
248 rreq = sftp_find_request(pktin = sftp_recv());
249 assert(rreq == req);
7b7de4f4 250 names = fxp_readdir_recv(pktin, rreq);
1bc24185 251
4c7f0d61 252 if (names == NULL) {
253 if (fxp_error_type() == SSH_FX_EOF)
254 break;
255 printf("Reading directory %s: %s\n", dir, fxp_error());
256 break;
257 }
258 if (names->nnames == 0) {
259 fxp_free_names(names);
260 break;
261 }
262
263 if (nnames + names->nnames >= namesize) {
264 namesize += names->nnames + 128;
3d88e64d 265 ournames = sresize(ournames, namesize, struct fxp_name *);
4c7f0d61 266 }
267
268 for (i = 0; i < names->nnames; i++)
7d2c1789 269 ournames[nnames++] = fxp_dup_name(&names->names[i]);
4c7f0d61 270
4c7f0d61 271 fxp_free_names(names);
272 }
1bc24185 273 sftp_register(req = fxp_close_send(dirh));
274 rreq = sftp_find_request(pktin = sftp_recv());
275 assert(rreq == req);
7b7de4f4 276 fxp_close_recv(pktin, rreq);
4c7f0d61 277
278 /*
279 * Now we have our filenames. Sort them by actual file
280 * name, and then output the longname parts.
281 */
282 qsort(ournames, nnames, sizeof(*ournames), sftp_ls_compare);
283
284 /*
285 * And print them.
286 */
7d2c1789 287 for (i = 0; i < nnames; i++) {
288 printf("%s\n", ournames[i]->longname);
289 fxp_free_name(ournames[i]);
290 }
291 sfree(ournames);
4c7f0d61 292 }
293
294 sfree(cdir);
295
df49ff19 296 return 1;
4c7f0d61 297}
298
299/*
300 * Change directories. We do this by canonifying the new name, then
301 * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
302 */
32874aea 303int sftp_cmd_cd(struct sftp_command *cmd)
304{
4c7f0d61 305 struct fxp_handle *dirh;
1bc24185 306 struct sftp_packet *pktin;
307 struct sftp_request *req, *rreq;
4c7f0d61 308 char *dir;
309
fa3db767 310 if (back == NULL) {
311 printf("psftp: not connected to a host; use \"open host.name\"\n");
312 return 0;
313 }
314
4c7f0d61 315 if (cmd->nwords < 2)
f9e162aa 316 dir = dupstr(homedir);
4c7f0d61 317 else
318 dir = canonify(cmd->words[1]);
319
320 if (!dir) {
321 printf("%s: %s\n", dir, fxp_error());
322 return 0;
323 }
324
1bc24185 325 sftp_register(req = fxp_opendir_send(dir));
326 rreq = sftp_find_request(pktin = sftp_recv());
327 assert(rreq == req);
7b7de4f4 328 dirh = fxp_opendir_recv(pktin, rreq);
1bc24185 329
4c7f0d61 330 if (!dirh) {
331 printf("Directory %s: %s\n", dir, fxp_error());
332 sfree(dir);
333 return 0;
334 }
335
1bc24185 336 sftp_register(req = fxp_close_send(dirh));
337 rreq = sftp_find_request(pktin = sftp_recv());
338 assert(rreq == req);
7b7de4f4 339 fxp_close_recv(pktin, rreq);
4c7f0d61 340
341 sfree(pwd);
342 pwd = dir;
343 printf("Remote directory is now %s\n", pwd);
344
df49ff19 345 return 1;
4c7f0d61 346}
347
348/*
4f2b387f 349 * Print current directory. Easy as pie.
350 */
351int sftp_cmd_pwd(struct sftp_command *cmd)
352{
fa3db767 353 if (back == NULL) {
354 printf("psftp: not connected to a host; use \"open host.name\"\n");
355 return 0;
356 }
357
4f2b387f 358 printf("Remote directory is %s\n", pwd);
df49ff19 359 return 1;
4f2b387f 360}
361
362/*
d92624dc 363 * Get a file and save it at the local end. We have two very
364 * similar commands here: `get' and `reget', which differ in that
365 * `reget' checks for the existence of the destination file and
366 * starts from where a previous aborted transfer left off.
4c7f0d61 367 */
d92624dc 368int sftp_general_get(struct sftp_command *cmd, int restart)
32874aea 369{
4c7f0d61 370 struct fxp_handle *fh;
1bc24185 371 struct sftp_packet *pktin;
372 struct sftp_request *req, *rreq;
c606c42d 373 struct fxp_xfer *xfer;
4c7f0d61 374 char *fname, *outfname;
375 uint64 offset;
376 FILE *fp;
df49ff19 377 int ret;
4c7f0d61 378
fa3db767 379 if (back == NULL) {
380 printf("psftp: not connected to a host; use \"open host.name\"\n");
381 return 0;
382 }
383
4c7f0d61 384 if (cmd->nwords < 2) {
385 printf("get: expects a filename\n");
386 return 0;
387 }
388
389 fname = canonify(cmd->words[1]);
390 if (!fname) {
391 printf("%s: %s\n", cmd->words[1], fxp_error());
392 return 0;
393 }
dcf8495c 394 outfname = (cmd->nwords == 2 ?
395 stripslashes(cmd->words[1], 0) : cmd->words[2]);
4c7f0d61 396
1bc24185 397 sftp_register(req = fxp_open_send(fname, SSH_FXF_READ));
398 rreq = sftp_find_request(pktin = sftp_recv());
399 assert(rreq == req);
7b7de4f4 400 fh = fxp_open_recv(pktin, rreq);
1bc24185 401
4c7f0d61 402 if (!fh) {
403 printf("%s: %s\n", fname, fxp_error());
404 sfree(fname);
405 return 0;
406 }
d92624dc 407
408 if (restart) {
409 fp = fopen(outfname, "rb+");
410 } else {
411 fp = fopen(outfname, "wb");
412 }
413
4c7f0d61 414 if (!fp) {
415 printf("local: unable to open %s\n", outfname);
1bc24185 416
417 sftp_register(req = fxp_close_send(fh));
418 rreq = sftp_find_request(pktin = sftp_recv());
419 assert(rreq == req);
7b7de4f4 420 fxp_close_recv(pktin, rreq);
1bc24185 421
4c7f0d61 422 sfree(fname);
423 return 0;
424 }
425
d92624dc 426 if (restart) {
427 long posn;
428 fseek(fp, 0L, SEEK_END);
429 posn = ftell(fp);
430 printf("reget: restarting at file position %ld\n", posn);
431 offset = uint64_make(0, posn);
432 } else {
433 offset = uint64_make(0, 0);
434 }
4c7f0d61 435
d92624dc 436 printf("remote:%s => local:%s\n", fname, outfname);
4c7f0d61 437
438 /*
439 * FIXME: we can use FXP_FSTAT here to get the file size, and
440 * thus put up a progress bar.
441 */
df49ff19 442 ret = 1;
c606c42d 443 xfer = xfer_download_init(fh, offset);
444 while (!xfer_download_done(xfer)) {
445 void *vbuf;
446 int ret, len;
4c7f0d61 447 int wpos, wlen;
448
c606c42d 449 xfer_download_queue(xfer);
450 pktin = sftp_recv();
451 ret = xfer_download_gotpkt(xfer, pktin);
452
453 if (ret < 0) {
454 printf("error while reading: %s\n", fxp_error());
455 ret = 0;
4c7f0d61 456 }
32874aea 457
c606c42d 458 while (xfer_download_data(xfer, &vbuf, &len)) {
459 unsigned char *buf = (unsigned char *)vbuf;
460
461 wpos = 0;
462 while (wpos < len) {
463 wlen = fwrite(buf + wpos, 1, len - wpos, fp);
464 if (wlen <= 0) {
465 printf("error while writing local file\n");
466 ret = 0;
467 xfer_set_error(xfer);
468 }
469 wpos += wlen;
470 }
471 if (wpos < len) { /* we had an error */
df49ff19 472 ret = 0;
c606c42d 473 xfer_set_error(xfer);
4c7f0d61 474 }
df49ff19 475 }
4c7f0d61 476 }
477
c606c42d 478 xfer_cleanup(xfer);
479
4c7f0d61 480 fclose(fp);
1bc24185 481
482 sftp_register(req = fxp_close_send(fh));
483 rreq = sftp_find_request(pktin = sftp_recv());
484 assert(rreq == req);
7b7de4f4 485 fxp_close_recv(pktin, rreq);
1bc24185 486
4c7f0d61 487 sfree(fname);
488
df49ff19 489 return ret;
4c7f0d61 490}
d92624dc 491int sftp_cmd_get(struct sftp_command *cmd)
492{
493 return sftp_general_get(cmd, 0);
494}
495int sftp_cmd_reget(struct sftp_command *cmd)
496{
497 return sftp_general_get(cmd, 1);
498}
4c7f0d61 499
500/*
d92624dc 501 * Send a file and store it at the remote end. We have two very
502 * similar commands here: `put' and `reput', which differ in that
503 * `reput' checks for the existence of the destination file and
504 * starts from where a previous aborted transfer left off.
4c7f0d61 505 */
d92624dc 506int sftp_general_put(struct sftp_command *cmd, int restart)
32874aea 507{
4c7f0d61 508 struct fxp_handle *fh;
509 char *fname, *origoutfname, *outfname;
1bc24185 510 struct sftp_packet *pktin;
511 struct sftp_request *req, *rreq;
4c7f0d61 512 uint64 offset;
513 FILE *fp;
df49ff19 514 int ret;
4c7f0d61 515
fa3db767 516 if (back == NULL) {
517 printf("psftp: not connected to a host; use \"open host.name\"\n");
518 return 0;
519 }
520
4c7f0d61 521 if (cmd->nwords < 2) {
522 printf("put: expects a filename\n");
523 return 0;
524 }
525
526 fname = cmd->words[1];
dcf8495c 527 origoutfname = (cmd->nwords == 2 ?
528 stripslashes(cmd->words[1], 1) : cmd->words[2]);
4c7f0d61 529 outfname = canonify(origoutfname);
f9e162aa 530 if (!outfname) {
4c7f0d61 531 printf("%s: %s\n", origoutfname, fxp_error());
532 return 0;
533 }
534
535 fp = fopen(fname, "rb");
536 if (!fp) {
537 printf("local: unable to open %s\n", fname);
4c7f0d61 538 sfree(outfname);
539 return 0;
540 }
d92624dc 541 if (restart) {
1bc24185 542 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE));
d92624dc 543 } else {
1bc24185 544 sftp_register(req = fxp_open_send(outfname, SSH_FXF_WRITE |
545 SSH_FXF_CREAT | SSH_FXF_TRUNC));
d92624dc 546 }
1bc24185 547 rreq = sftp_find_request(pktin = sftp_recv());
548 assert(rreq == req);
7b7de4f4 549 fh = fxp_open_recv(pktin, rreq);
1bc24185 550
4c7f0d61 551 if (!fh) {
552 printf("%s: %s\n", outfname, fxp_error());
553 sfree(outfname);
554 return 0;
555 }
556
d92624dc 557 if (restart) {
558 char decbuf[30];
559 struct fxp_attrs attrs;
1bc24185 560 int ret;
561
562 sftp_register(req = fxp_fstat_send(fh));
563 rreq = sftp_find_request(pktin = sftp_recv());
564 assert(rreq == req);
7b7de4f4 565 ret = fxp_fstat_recv(pktin, rreq, &attrs);
1bc24185 566
567 if (!ret) {
d92624dc 568 printf("read size of %s: %s\n", outfname, fxp_error());
569 sfree(outfname);
570 return 0;
571 }
572 if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
573 printf("read size of %s: size was not given\n", outfname);
574 sfree(outfname);
575 return 0;
576 }
577 offset = attrs.size;
578 uint64_decimal(offset, decbuf);
579 printf("reput: restarting at file position %s\n", decbuf);
580 if (uint64_compare(offset, uint64_make(0, LONG_MAX)) > 0) {
581 printf("reput: remote file is larger than we can deal with\n");
582 sfree(outfname);
583 return 0;
584 }
585 if (fseek(fp, offset.lo, SEEK_SET) != 0)
586 fseek(fp, 0, SEEK_END); /* *shrug* */
587 } else {
588 offset = uint64_make(0, 0);
589 }
4c7f0d61 590
d92624dc 591 printf("local:%s => remote:%s\n", fname, outfname);
4c7f0d61 592
593 /*
594 * FIXME: we can use FXP_FSTAT here to get the file size, and
595 * thus put up a progress bar.
596 */
df49ff19 597 ret = 1;
4c7f0d61 598 while (1) {
599 char buffer[4096];
1bc24185 600 int len, ret;
4c7f0d61 601
f9e162aa 602 len = fread(buffer, 1, sizeof(buffer), fp);
4c7f0d61 603 if (len == -1) {
604 printf("error while reading local file\n");
df49ff19 605 ret = 0;
4c7f0d61 606 break;
607 } else if (len == 0) {
608 break;
609 }
1bc24185 610
611 sftp_register(req = fxp_write_send(fh, buffer, offset, len));
612 rreq = sftp_find_request(pktin = sftp_recv());
613 assert(rreq == req);
7b7de4f4 614 ret = fxp_write_recv(pktin, rreq);
1bc24185 615
616 if (!ret) {
4c7f0d61 617 printf("error while writing: %s\n", fxp_error());
df49ff19 618 ret = 0;
4c7f0d61 619 break;
620 }
621 offset = uint64_add32(offset, len);
622 }
623
1bc24185 624 sftp_register(req = fxp_close_send(fh));
625 rreq = sftp_find_request(pktin = sftp_recv());
626 assert(rreq == req);
7b7de4f4 627 fxp_close_recv(pktin, rreq);
1bc24185 628
4c7f0d61 629 fclose(fp);
630 sfree(outfname);
631
df49ff19 632 return ret;
4c7f0d61 633}
d92624dc 634int sftp_cmd_put(struct sftp_command *cmd)
635{
636 return sftp_general_put(cmd, 0);
637}
638int sftp_cmd_reput(struct sftp_command *cmd)
639{
640 return sftp_general_put(cmd, 1);
641}
4c7f0d61 642
9954aaa3 643int sftp_cmd_mkdir(struct sftp_command *cmd)
644{
645 char *dir;
1bc24185 646 struct sftp_packet *pktin;
647 struct sftp_request *req, *rreq;
9954aaa3 648 int result;
649
fa3db767 650 if (back == NULL) {
651 printf("psftp: not connected to a host; use \"open host.name\"\n");
652 return 0;
653 }
9954aaa3 654
655 if (cmd->nwords < 2) {
656 printf("mkdir: expects a directory\n");
657 return 0;
658 }
659
660 dir = canonify(cmd->words[1]);
661 if (!dir) {
662 printf("%s: %s\n", dir, fxp_error());
663 return 0;
664 }
665
1bc24185 666 sftp_register(req = fxp_mkdir_send(dir));
667 rreq = sftp_find_request(pktin = sftp_recv());
668 assert(rreq == req);
7b7de4f4 669 result = fxp_mkdir_recv(pktin, rreq);
1bc24185 670
9954aaa3 671 if (!result) {
672 printf("mkdir %s: %s\n", dir, fxp_error());
673 sfree(dir);
674 return 0;
675 }
676
d92624dc 677 sfree(dir);
df49ff19 678 return 1;
9954aaa3 679}
680
681int sftp_cmd_rmdir(struct sftp_command *cmd)
682{
683 char *dir;
1bc24185 684 struct sftp_packet *pktin;
685 struct sftp_request *req, *rreq;
9954aaa3 686 int result;
687
fa3db767 688 if (back == NULL) {
689 printf("psftp: not connected to a host; use \"open host.name\"\n");
690 return 0;
691 }
9954aaa3 692
693 if (cmd->nwords < 2) {
694 printf("rmdir: expects a directory\n");
695 return 0;
696 }
697
698 dir = canonify(cmd->words[1]);
699 if (!dir) {
700 printf("%s: %s\n", dir, fxp_error());
701 return 0;
702 }
703
1bc24185 704 sftp_register(req = fxp_rmdir_send(dir));
705 rreq = sftp_find_request(pktin = sftp_recv());
706 assert(rreq == req);
7b7de4f4 707 result = fxp_rmdir_recv(pktin, rreq);
1bc24185 708
9954aaa3 709 if (!result) {
710 printf("rmdir %s: %s\n", dir, fxp_error());
711 sfree(dir);
712 return 0;
713 }
714
d92624dc 715 sfree(dir);
df49ff19 716 return 1;
9954aaa3 717}
718
719int sftp_cmd_rm(struct sftp_command *cmd)
720{
721 char *fname;
1bc24185 722 struct sftp_packet *pktin;
723 struct sftp_request *req, *rreq;
9954aaa3 724 int result;
725
fa3db767 726 if (back == NULL) {
727 printf("psftp: not connected to a host; use \"open host.name\"\n");
728 return 0;
729 }
730
9954aaa3 731 if (cmd->nwords < 2) {
732 printf("rm: expects a filename\n");
733 return 0;
734 }
735
736 fname = canonify(cmd->words[1]);
737 if (!fname) {
738 printf("%s: %s\n", fname, fxp_error());
739 return 0;
740 }
741
1bc24185 742 sftp_register(req = fxp_remove_send(fname));
743 rreq = sftp_find_request(pktin = sftp_recv());
744 assert(rreq == req);
7b7de4f4 745 result = fxp_remove_recv(pktin, rreq);
1bc24185 746
9954aaa3 747 if (!result) {
748 printf("rm %s: %s\n", fname, fxp_error());
749 sfree(fname);
750 return 0;
751 }
752
d92624dc 753 sfree(fname);
df49ff19 754 return 1;
d92624dc 755}
756
757int sftp_cmd_mv(struct sftp_command *cmd)
758{
759 char *srcfname, *dstfname;
1bc24185 760 struct sftp_packet *pktin;
761 struct sftp_request *req, *rreq;
d92624dc 762 int result;
763
fa3db767 764 if (back == NULL) {
765 printf("psftp: not connected to a host; use \"open host.name\"\n");
766 return 0;
767 }
768
d92624dc 769 if (cmd->nwords < 3) {
770 printf("mv: expects two filenames\n");
9954aaa3 771 return 0;
d92624dc 772 }
773 srcfname = canonify(cmd->words[1]);
774 if (!srcfname) {
775 printf("%s: %s\n", srcfname, fxp_error());
776 return 0;
777 }
778
779 dstfname = canonify(cmd->words[2]);
780 if (!dstfname) {
781 printf("%s: %s\n", dstfname, fxp_error());
782 return 0;
783 }
9954aaa3 784
1bc24185 785 sftp_register(req = fxp_rename_send(srcfname, dstfname));
786 rreq = sftp_find_request(pktin = sftp_recv());
787 assert(rreq == req);
7b7de4f4 788 result = fxp_rename_recv(pktin, rreq);
1bc24185 789
d92624dc 790 if (!result) {
791 char const *error = fxp_error();
792 struct fxp_attrs attrs;
793
794 /*
795 * The move might have failed because dstfname pointed at a
796 * directory. We check this possibility now: if dstfname
797 * _is_ a directory, we re-attempt the move by appending
798 * the basename of srcfname to dstfname.
799 */
1bc24185 800 sftp_register(req = fxp_stat_send(dstfname));
801 rreq = sftp_find_request(pktin = sftp_recv());
802 assert(rreq == req);
7b7de4f4 803 result = fxp_stat_recv(pktin, rreq, &attrs);
1bc24185 804
d92624dc 805 if (result &&
806 (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
807 (attrs.permissions & 0040000)) {
808 char *p;
809 char *newname, *newcanon;
810 printf("(destination %s is a directory)\n", dstfname);
811 p = srcfname + strlen(srcfname);
812 while (p > srcfname && p[-1] != '/') p--;
813 newname = dupcat(dstfname, "/", p, NULL);
814 newcanon = canonify(newname);
815 sfree(newname);
816 if (newcanon) {
817 sfree(dstfname);
818 dstfname = newcanon;
1bc24185 819
820 sftp_register(req = fxp_rename_send(srcfname, dstfname));
821 rreq = sftp_find_request(pktin = sftp_recv());
822 assert(rreq == req);
7b7de4f4 823 result = fxp_rename_recv(pktin, rreq);
1bc24185 824
d92624dc 825 error = result ? NULL : fxp_error();
826 }
827 }
828 if (error) {
829 printf("mv %s %s: %s\n", srcfname, dstfname, error);
830 sfree(srcfname);
831 sfree(dstfname);
832 return 0;
833 }
834 }
835 printf("%s -> %s\n", srcfname, dstfname);
836
837 sfree(srcfname);
838 sfree(dstfname);
df49ff19 839 return 1;
9954aaa3 840}
841
d92624dc 842int sftp_cmd_chmod(struct sftp_command *cmd)
843{
844 char *fname, *mode;
845 int result;
846 struct fxp_attrs attrs;
847 unsigned attrs_clr, attrs_xor, oldperms, newperms;
1bc24185 848 struct sftp_packet *pktin;
849 struct sftp_request *req, *rreq;
d92624dc 850
fa3db767 851 if (back == NULL) {
852 printf("psftp: not connected to a host; use \"open host.name\"\n");
853 return 0;
854 }
855
d92624dc 856 if (cmd->nwords < 3) {
857 printf("chmod: expects a mode specifier and a filename\n");
858 return 0;
859 }
860
861 /*
862 * Attempt to parse the mode specifier in cmd->words[1]. We
863 * don't support the full horror of Unix chmod; instead we
864 * support a much simpler syntax in which the user can either
865 * specify an octal number, or a comma-separated sequence of
866 * [ugoa]*[-+=][rwxst]+. (The initial [ugoa] sequence may
867 * _only_ be omitted if the only attribute mentioned is t,
868 * since all others require a user/group/other specification.
869 * Additionally, the s attribute may not be specified for any
870 * [ugoa] specifications other than exactly u or exactly g.
871 */
872 attrs_clr = attrs_xor = 0;
873 mode = cmd->words[1];
874 if (mode[0] >= '0' && mode[0] <= '9') {
875 if (mode[strspn(mode, "01234567")]) {
876 printf("chmod: numeric file modes should"
877 " contain digits 0-7 only\n");
878 return 0;
879 }
880 attrs_clr = 07777;
881 sscanf(mode, "%o", &attrs_xor);
882 attrs_xor &= attrs_clr;
883 } else {
884 while (*mode) {
885 char *modebegin = mode;
886 unsigned subset, perms;
887 int action;
888
889 subset = 0;
890 while (*mode && *mode != ',' &&
891 *mode != '+' && *mode != '-' && *mode != '=') {
892 switch (*mode) {
893 case 'u': subset |= 04700; break; /* setuid, user perms */
894 case 'g': subset |= 02070; break; /* setgid, group perms */
895 case 'o': subset |= 00007; break; /* just other perms */
896 case 'a': subset |= 06777; break; /* all of the above */
897 default:
898 printf("chmod: file mode '%.*s' contains unrecognised"
899 " user/group/other specifier '%c'\n",
b51259f6 900 (int)strcspn(modebegin, ","), modebegin, *mode);
d92624dc 901 return 0;
902 }
903 mode++;
904 }
905 if (!*mode || *mode == ',') {
906 printf("chmod: file mode '%.*s' is incomplete\n",
b51259f6 907 (int)strcspn(modebegin, ","), modebegin);
d92624dc 908 return 0;
909 }
910 action = *mode++;
911 if (!*mode || *mode == ',') {
912 printf("chmod: file mode '%.*s' is incomplete\n",
b51259f6 913 (int)strcspn(modebegin, ","), modebegin);
d92624dc 914 return 0;
915 }
916 perms = 0;
917 while (*mode && *mode != ',') {
918 switch (*mode) {
919 case 'r': perms |= 00444; break;
920 case 'w': perms |= 00222; break;
921 case 'x': perms |= 00111; break;
922 case 't': perms |= 01000; subset |= 01000; break;
923 case 's':
924 if ((subset & 06777) != 04700 &&
925 (subset & 06777) != 02070) {
926 printf("chmod: file mode '%.*s': set[ug]id bit should"
927 " be used with exactly one of u or g only\n",
b51259f6 928 (int)strcspn(modebegin, ","), modebegin);
d92624dc 929 return 0;
930 }
931 perms |= 06000;
932 break;
933 default:
934 printf("chmod: file mode '%.*s' contains unrecognised"
935 " permission specifier '%c'\n",
b51259f6 936 (int)strcspn(modebegin, ","), modebegin, *mode);
d92624dc 937 return 0;
938 }
939 mode++;
940 }
941 if (!(subset & 06777) && (perms &~ subset)) {
942 printf("chmod: file mode '%.*s' contains no user/group/other"
943 " specifier and permissions other than 't' \n",
b51259f6 944 (int)strcspn(modebegin, ","), modebegin);
d92624dc 945 return 0;
946 }
947 perms &= subset;
948 switch (action) {
949 case '+':
950 attrs_clr |= perms;
951 attrs_xor |= perms;
952 break;
953 case '-':
954 attrs_clr |= perms;
955 attrs_xor &= ~perms;
956 break;
957 case '=':
958 attrs_clr |= subset;
959 attrs_xor |= perms;
960 break;
961 }
962 if (*mode) mode++; /* eat comma */
963 }
964 }
965
966 fname = canonify(cmd->words[2]);
967 if (!fname) {
968 printf("%s: %s\n", fname, fxp_error());
969 return 0;
970 }
971
1bc24185 972 sftp_register(req = fxp_stat_send(fname));
973 rreq = sftp_find_request(pktin = sftp_recv());
974 assert(rreq == req);
7b7de4f4 975 result = fxp_stat_recv(pktin, rreq, &attrs);
1bc24185 976
d92624dc 977 if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) {
978 printf("get attrs for %s: %s\n", fname,
979 result ? "file permissions not provided" : fxp_error());
980 sfree(fname);
981 return 0;
982 }
983
984 attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS; /* perms _only_ */
985 oldperms = attrs.permissions & 07777;
986 attrs.permissions &= ~attrs_clr;
987 attrs.permissions ^= attrs_xor;
988 newperms = attrs.permissions & 07777;
989
1bc24185 990 sftp_register(req = fxp_setstat_send(fname, attrs));
991 rreq = sftp_find_request(pktin = sftp_recv());
992 assert(rreq == req);
7b7de4f4 993 result = fxp_setstat_recv(pktin, rreq);
d92624dc 994
995 if (!result) {
996 printf("set attrs for %s: %s\n", fname, fxp_error());
997 sfree(fname);
998 return 0;
999 }
1000
1001 printf("%s: %04o -> %04o\n", fname, oldperms, newperms);
1002
1003 sfree(fname);
df49ff19 1004 return 1;
d92624dc 1005}
9954aaa3 1006
fa3db767 1007static int sftp_cmd_open(struct sftp_command *cmd)
1008{
1009 if (back != NULL) {
1010 printf("psftp: already connected\n");
1011 return 0;
1012 }
1013
1014 if (cmd->nwords < 2) {
1015 printf("open: expects a host name\n");
1016 return 0;
1017 }
1018
1019 if (psftp_connect(cmd->words[1], NULL, 0)) {
1020 back = NULL; /* connection is already closed */
1021 return -1; /* this is fatal */
1022 }
1023 do_sftp_init();
df49ff19 1024 return 1;
fa3db767 1025}
1026
3af97463 1027static int sftp_cmd_lcd(struct sftp_command *cmd)
1028{
d6cc41e6 1029 char *currdir, *errmsg;
3af97463 1030
1031 if (cmd->nwords < 2) {
1032 printf("lcd: expects a local directory name\n");
1033 return 0;
1034 }
1035
d6cc41e6 1036 errmsg = psftp_lcd(cmd->words[1]);
1037 if (errmsg) {
1038 printf("lcd: unable to change directory: %s\n", errmsg);
1039 sfree(errmsg);
3af97463 1040 return 0;
1041 }
1042
d6cc41e6 1043 currdir = psftp_getcwd();
3af97463 1044 printf("New local directory is %s\n", currdir);
1045 sfree(currdir);
1046
1047 return 1;
1048}
1049
1050static int sftp_cmd_lpwd(struct sftp_command *cmd)
1051{
1052 char *currdir;
3af97463 1053
d6cc41e6 1054 currdir = psftp_getcwd();
3af97463 1055 printf("Current local directory is %s\n", currdir);
1056 sfree(currdir);
1057
1058 return 1;
1059}
1060
1061static int sftp_cmd_pling(struct sftp_command *cmd)
1062{
1063 int exitcode;
1064
1065 exitcode = system(cmd->words[1]);
1066 return (exitcode == 0);
1067}
1068
bf5240cd 1069static int sftp_cmd_help(struct sftp_command *cmd);
1070
4c7f0d61 1071static struct sftp_cmd_lookup {
1072 char *name;
bf5240cd 1073 /*
1074 * For help purposes, there are two kinds of command:
1075 *
1076 * - primary commands, in which `longhelp' is non-NULL. In
1077 * this case `shorthelp' is descriptive text, and `longhelp'
1078 * is longer descriptive text intended to be printed after
1079 * the command name.
1080 *
1081 * - alias commands, in which `longhelp' is NULL. In this case
1082 * `shorthelp' is the name of a primary command, which
1083 * contains the help that should double up for this command.
1084 */
3af97463 1085 int listed; /* do we list this in primary help? */
bf5240cd 1086 char *shorthelp;
1087 char *longhelp;
32874aea 1088 int (*obey) (struct sftp_command *);
4c7f0d61 1089} sftp_lookup[] = {
1090 /*
1091 * List of sftp commands. This is binary-searched so it MUST be
1092 * in ASCII order.
1093 */
32874aea 1094 {
d6cc41e6 1095 "!", TRUE, "run a local command",
3af97463 1096 "<command>\n"
d6cc41e6 1097 /* FIXME: this example is crap for non-Windows. */
1098 " Runs a local command. For example, \"!del myfile\".\n",
3af97463 1099 sftp_cmd_pling
1100 },
1101 {
1102 "bye", TRUE, "finish your SFTP session",
bf5240cd 1103 "\n"
1104 " Terminates your SFTP session and quits the PSFTP program.\n",
1105 sftp_cmd_quit
1106 },
1107 {
3af97463 1108 "cd", TRUE, "change your remote working directory",
bf5240cd 1109 " [ <New working directory> ]\n"
1110 " Change the remote working directory for your SFTP session.\n"
1111 " If a new working directory is not supplied, you will be\n"
1112 " returned to your home directory.\n",
1113 sftp_cmd_cd
1114 },
1115 {
3af97463 1116 "chmod", TRUE, "change file permissions and modes",
bf5240cd 1117 " ( <octal-digits> | <modifiers> ) <filename>\n"
1118 " Change the file permissions on a file or directory.\n"
1119 " <octal-digits> can be any octal Unix permission specifier.\n"
1120 " Alternatively, <modifiers> can include:\n"
1121 " u+r make file readable by owning user\n"
1122 " u+w make file writable by owning user\n"
1123 " u+x make file executable by owning user\n"
1124 " u-r make file not readable by owning user\n"
1125 " [also u-w, u-x]\n"
1126 " g+r make file readable by members of owning group\n"
1127 " [also g+w, g+x, g-r, g-w, g-x]\n"
1128 " o+r make file readable by all other users\n"
1129 " [also o+w, o+x, o-r, o-w, o-x]\n"
1130 " a+r make file readable by absolutely everybody\n"
1131 " [also a+w, a+x, a-r, a-w, a-x]\n"
1132 " u+s enable the Unix set-user-ID bit\n"
1133 " u-s disable the Unix set-user-ID bit\n"
1134 " g+s enable the Unix set-group-ID bit\n"
1135 " g-s disable the Unix set-group-ID bit\n"
1136 " +t enable the Unix \"sticky bit\"\n"
1137 " You can give more than one modifier for the same user (\"g-rwx\"), and\n"
1138 " more than one user for the same modifier (\"ug+w\"). You can\n"
1139 " use commas to separate different modifiers (\"u+rwx,g+s\").\n",
1140 sftp_cmd_chmod
1141 },
1142 {
3af97463 1143 "del", TRUE, "delete a file",
bf5240cd 1144 " <filename>\n"
1145 " Delete a file.\n",
1146 sftp_cmd_rm
1147 },
1148 {
3af97463 1149 "delete", FALSE, "del", NULL, sftp_cmd_rm
bf5240cd 1150 },
1151 {
3af97463 1152 "dir", TRUE, "list contents of a remote directory",
bf5240cd 1153 " [ <directory-name> ]\n"
1154 " List the contents of a specified directory on the server.\n"
1155 " If <directory-name> is not given, the current working directory\n"
1156 " will be listed.\n",
1157 sftp_cmd_ls
1158 },
1159 {
3af97463 1160 "exit", TRUE, "bye", NULL, sftp_cmd_quit
bf5240cd 1161 },
1162 {
3af97463 1163 "get", TRUE, "download a file from the server to your local machine",
bf5240cd 1164 " <filename> [ <local-filename> ]\n"
1165 " Downloads a file on the server and stores it locally under\n"
1166 " the same name, or under a different one if you supply the\n"
1167 " argument <local-filename>.\n",
1168 sftp_cmd_get
1169 },
1170 {
3af97463 1171 "help", TRUE, "give help",
bf5240cd 1172 " [ <command> [ <command> ... ] ]\n"
1173 " Give general help if no commands are specified.\n"
1174 " If one or more commands are specified, give specific help on\n"
1175 " those particular commands.\n",
1176 sftp_cmd_help
1177 },
1178 {
3af97463 1179 "lcd", TRUE, "change local working directory",
1180 " <local-directory-name>\n"
1181 " Change the local working directory of the PSFTP program (the\n"
1182 " default location where the \"get\" command will save files).\n",
1183 sftp_cmd_lcd
1184 },
1185 {
1186 "lpwd", TRUE, "print local working directory",
1187 "\n"
1188 " Print the local working directory of the PSFTP program (the\n"
1189 " default location where the \"get\" command will save files).\n",
1190 sftp_cmd_lpwd
1191 },
1192 {
1193 "ls", TRUE, "dir", NULL,
bf5240cd 1194 sftp_cmd_ls
1195 },
1196 {
3af97463 1197 "mkdir", TRUE, "create a directory on the remote server",
bf5240cd 1198 " <directory-name>\n"
1199 " Creates a directory with the given name on the server.\n",
1200 sftp_cmd_mkdir
1201 },
1202 {
3af97463 1203 "mv", TRUE, "move or rename a file on the remote server",
bf5240cd 1204 " <source-filename> <destination-filename>\n"
1205 " Moves or renames the file <source-filename> on the server,\n"
1206 " so that it is accessible under the name <destination-filename>.\n",
1207 sftp_cmd_mv
1208 },
1209 {
3af97463 1210 "open", TRUE, "connect to a host",
fa3db767 1211 " [<user>@]<hostname>\n"
1212 " Establishes an SFTP connection to a given host. Only usable\n"
1213 " when you did not already specify a host name on the command\n"
1214 " line.\n",
1215 sftp_cmd_open
1216 },
1217 {
56542985 1218 "put", TRUE, "upload a file from your local machine to the server",
1219 " <filename> [ <remote-filename> ]\n"
1220 " Uploads a file to the server and stores it there under\n"
1221 " the same name, or under a different one if you supply the\n"
1222 " argument <remote-filename>.\n",
1223 sftp_cmd_put
1224 },
1225 {
3af97463 1226 "pwd", TRUE, "print your remote working directory",
4f2b387f 1227 "\n"
1228 " Print the current remote working directory for your SFTP session.\n",
1229 sftp_cmd_pwd
1230 },
1231 {
3af97463 1232 "quit", TRUE, "bye", NULL,
bf5240cd 1233 sftp_cmd_quit
1234 },
1235 {
3af97463 1236 "reget", TRUE, "continue downloading a file",
bf5240cd 1237 " <filename> [ <local-filename> ]\n"
1238 " Works exactly like the \"get\" command, but the local file\n"
1239 " must already exist. The download will begin at the end of the\n"
1240 " file. This is for resuming a download that was interrupted.\n",
1241 sftp_cmd_reget
1242 },
1243 {
3af97463 1244 "ren", TRUE, "mv", NULL,
bf5240cd 1245 sftp_cmd_mv
1246 },
1247 {
3af97463 1248 "rename", FALSE, "mv", NULL,
bf5240cd 1249 sftp_cmd_mv
1250 },
1251 {
3af97463 1252 "reput", TRUE, "continue uploading a file",
bf5240cd 1253 " <filename> [ <remote-filename> ]\n"
1254 " Works exactly like the \"put\" command, but the remote file\n"
1255 " must already exist. The upload will begin at the end of the\n"
1256 " file. This is for resuming an upload that was interrupted.\n",
1257 sftp_cmd_reput
1258 },
1259 {
3af97463 1260 "rm", TRUE, "del", NULL,
bf5240cd 1261 sftp_cmd_rm
1262 },
1263 {
3af97463 1264 "rmdir", TRUE, "remove a directory on the remote server",
bf5240cd 1265 " <directory-name>\n"
1266 " Removes the directory with the given name on the server.\n"
1267 " The directory will not be removed unless it is empty.\n",
1268 sftp_cmd_rmdir
1269 }
1270};
1271
1272const struct sftp_cmd_lookup *lookup_command(char *name)
1273{
1274 int i, j, k, cmp;
1275
1276 i = -1;
1277 j = sizeof(sftp_lookup) / sizeof(*sftp_lookup);
1278 while (j - i > 1) {
1279 k = (j + i) / 2;
1280 cmp = strcmp(name, sftp_lookup[k].name);
1281 if (cmp < 0)
1282 j = k;
1283 else if (cmp > 0)
1284 i = k;
1285 else {
1286 return &sftp_lookup[k];
1287 }
1288 }
1289 return NULL;
1290}
1291
1292static int sftp_cmd_help(struct sftp_command *cmd)
1293{
1294 int i;
1295 if (cmd->nwords == 1) {
1296 /*
1297 * Give short help on each command.
1298 */
1299 int maxlen;
1300 maxlen = 0;
1301 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
3af97463 1302 int len;
1303 if (!sftp_lookup[i].listed)
1304 continue;
1305 len = strlen(sftp_lookup[i].name);
bf5240cd 1306 if (maxlen < len)
1307 maxlen = len;
1308 }
1309 for (i = 0; i < sizeof(sftp_lookup) / sizeof(*sftp_lookup); i++) {
1310 const struct sftp_cmd_lookup *lookup;
3af97463 1311 if (!sftp_lookup[i].listed)
1312 continue;
bf5240cd 1313 lookup = &sftp_lookup[i];
1314 printf("%-*s", maxlen+2, lookup->name);
1315 if (lookup->longhelp == NULL)
1316 lookup = lookup_command(lookup->shorthelp);
1317 printf("%s\n", lookup->shorthelp);
1318 }
1319 } else {
1320 /*
1321 * Give long help on specific commands.
1322 */
1323 for (i = 1; i < cmd->nwords; i++) {
1324 const struct sftp_cmd_lookup *lookup;
1325 lookup = lookup_command(cmd->words[i]);
1326 if (!lookup) {
1327 printf("help: %s: command not found\n", cmd->words[i]);
1328 } else {
1329 printf("%s", lookup->name);
1330 if (lookup->longhelp == NULL)
1331 lookup = lookup_command(lookup->shorthelp);
1332 printf("%s", lookup->longhelp);
1333 }
1334 }
1335 }
df49ff19 1336 return 1;
bf5240cd 1337}
4c7f0d61 1338
1339/* ----------------------------------------------------------------------
1340 * Command line reading and parsing.
1341 */
9954aaa3 1342struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags)
32874aea 1343{
4c7f0d61 1344 char *line;
1345 int linelen, linesize;
1346 struct sftp_command *cmd;
1347 char *p, *q, *r;
1348 int quoting;
1349
df49ff19 1350 if ((mode == 0) || (modeflags & 1)) {
1351 printf("psftp> ");
1352 }
4c7f0d61 1353 fflush(stdout);
1354
3d88e64d 1355 cmd = snew(struct sftp_command);
4c7f0d61 1356 cmd->words = NULL;
1357 cmd->nwords = 0;
1358 cmd->wordssize = 0;
1359
1360 line = NULL;
1361 linesize = linelen = 0;
1362 while (1) {
1363 int len;
1364 char *ret;
1365
1366 linesize += 512;
3d88e64d 1367 line = sresize(line, linesize, char);
9954aaa3 1368 ret = fgets(line + linelen, linesize - linelen, fp);
4c7f0d61 1369
1370 if (!ret || (linelen == 0 && line[0] == '\0')) {
1371 cmd->obey = sftp_cmd_quit;
d13c2ee9 1372 if ((mode == 0) || (modeflags & 1))
1373 printf("quit\n");
4c7f0d61 1374 return cmd; /* eof */
1375 }
32874aea 1376 len = linelen + strlen(line + linelen);
4c7f0d61 1377 linelen += len;
32874aea 1378 if (line[linelen - 1] == '\n') {
4c7f0d61 1379 linelen--;
1380 line[linelen] = '\0';
1381 break;
1382 }
1383 }
df49ff19 1384 if (modeflags & 1) {
1385 printf("%s\n", line);
1386 }
4c7f0d61 1387
4c7f0d61 1388 p = line;
3af97463 1389 while (*p && (*p == ' ' || *p == '\t'))
1390 p++;
1391
1392 if (*p == '!') {
1393 /*
1394 * Special case: the ! command. This is always parsed as
1395 * exactly two words: one containing the !, and the second
1396 * containing everything else on the line.
1397 */
1398 cmd->nwords = cmd->wordssize = 2;
3d88e64d 1399 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
3af97463 1400 cmd->words[0] = "!";
1401 cmd->words[1] = p+1;
1402 } else {
1403
1404 /*
1405 * Parse the command line into words. The syntax is:
1406 * - double quotes are removed, but cause spaces within to be
1407 * treated as non-separating.
1408 * - a double-doublequote pair is a literal double quote, inside
1409 * _or_ outside quotes. Like this:
1410 *
1411 * firstword "second word" "this has ""quotes"" in" and""this""
1412 *
1413 * becomes
1414 *
1415 * >firstword<
1416 * >second word<
1417 * >this has "quotes" in<
1418 * >and"this"<
1419 */
4c7f0d61 1420 while (*p) {
3af97463 1421 /* skip whitespace */
1422 while (*p && (*p == ' ' || *p == '\t'))
1423 p++;
1424 /* mark start of word */
1425 q = r = p; /* q sits at start, r writes word */
1426 quoting = 0;
1427 while (*p) {
1428 if (!quoting && (*p == ' ' || *p == '\t'))
1429 break; /* reached end of word */
1430 else if (*p == '"' && p[1] == '"')
1431 p += 2, *r++ = '"'; /* a literal quote */
1432 else if (*p == '"')
1433 p++, quoting = !quoting;
1434 else
1435 *r++ = *p++;
1436 }
1437 if (*p)
1438 p++; /* skip over the whitespace */
1439 *r = '\0';
1440 if (cmd->nwords >= cmd->wordssize) {
1441 cmd->wordssize = cmd->nwords + 16;
3d88e64d 1442 cmd->words = sresize(cmd->words, cmd->wordssize, char *);
3af97463 1443 }
1444 cmd->words[cmd->nwords++] = q;
4c7f0d61 1445 }
4c7f0d61 1446 }
1447
1448 /*
1449 * Now parse the first word and assign a function.
1450 */
1451
1452 if (cmd->nwords == 0)
1453 cmd->obey = sftp_cmd_null;
1454 else {
bf5240cd 1455 const struct sftp_cmd_lookup *lookup;
1456 lookup = lookup_command(cmd->words[0]);
1457 if (!lookup)
1458 cmd->obey = sftp_cmd_unknown;
1459 else
1460 cmd->obey = lookup->obey;
4c7f0d61 1461 }
1462
1463 return cmd;
1464}
1465
774204f5 1466static int do_sftp_init(void)
32874aea 1467{
1bc24185 1468 struct sftp_packet *pktin;
1469 struct sftp_request *req, *rreq;
1470
4c7f0d61 1471 /*
1472 * Do protocol initialisation.
1473 */
1474 if (!fxp_init()) {
1475 fprintf(stderr,
32874aea 1476 "Fatal: unable to initialise SFTP: %s\n", fxp_error());
774204f5 1477 return 1; /* failure */
4c7f0d61 1478 }
1479
1480 /*
1481 * Find out where our home directory is.
1482 */
1bc24185 1483 sftp_register(req = fxp_realpath_send("."));
1484 rreq = sftp_find_request(pktin = sftp_recv());
1485 assert(rreq == req);
7b7de4f4 1486 homedir = fxp_realpath_recv(pktin, rreq);
1bc24185 1487
4c7f0d61 1488 if (!homedir) {
1489 fprintf(stderr,
1490 "Warning: failed to resolve home directory: %s\n",
1491 fxp_error());
1492 homedir = dupstr(".");
1493 } else {
1494 printf("Remote working directory is %s\n", homedir);
1495 }
1496 pwd = dupstr(homedir);
774204f5 1497 return 0;
fa3db767 1498}
1499
1500void do_sftp(int mode, int modeflags, char *batchfile)
1501{
1502 FILE *fp;
df49ff19 1503 int ret;
4c7f0d61 1504
9954aaa3 1505 /*
1506 * Batch mode?
4c7f0d61 1507 */
9954aaa3 1508 if (mode == 0) {
1509
1510 /* ------------------------------------------------------------------
1511 * Now we're ready to do Real Stuff.
1512 */
1513 while (1) {
df49ff19 1514 struct sftp_command *cmd;
1515 cmd = sftp_getcmd(stdin, 0, 0);
1516 if (!cmd)
1517 break;
1518 if (cmd->obey(cmd) < 0)
1519 break;
bf5240cd 1520 }
9954aaa3 1521 } else {
1522 fp = fopen(batchfile, "r");
1523 if (!fp) {
bf5240cd 1524 printf("Fatal: unable to open %s\n", batchfile);
1525 return;
9954aaa3 1526 }
1527 while (1) {
bf5240cd 1528 struct sftp_command *cmd;
1529 cmd = sftp_getcmd(fp, mode, modeflags);
1530 if (!cmd)
1531 break;
df49ff19 1532 ret = cmd->obey(cmd);
1533 if (ret < 0)
bf5240cd 1534 break;
df49ff19 1535 if (ret == 0) {
bf5240cd 1536 if (!(modeflags & 2))
9954aaa3 1537 break;
bf5240cd 1538 }
9954aaa3 1539 }
bf5240cd 1540 fclose(fp);
9954aaa3 1541
4c7f0d61 1542 }
4a8fc3c4 1543}
4c7f0d61 1544
4a8fc3c4 1545/* ----------------------------------------------------------------------
1546 * Dirty bits: integration with PuTTY.
1547 */
1548
1549static int verbose = 0;
1550
7bedb13c 1551/*
4a8fc3c4 1552 * Print an error message and perform a fatal exit.
1553 */
1554void fatalbox(char *fmt, ...)
1555{
57356d63 1556 char *str, *str2;
4a8fc3c4 1557 va_list ap;
1558 va_start(ap, fmt);
57356d63 1559 str = dupvprintf(fmt, ap);
1560 str2 = dupcat("Fatal: ", str, "\n", NULL);
1561 sfree(str);
4a8fc3c4 1562 va_end(ap);
57356d63 1563 fputs(str2, stderr);
1564 sfree(str2);
4a8fc3c4 1565
93b581bd 1566 cleanup_exit(1);
4a8fc3c4 1567}
1709795f 1568void modalfatalbox(char *fmt, ...)
1569{
57356d63 1570 char *str, *str2;
1709795f 1571 va_list ap;
1572 va_start(ap, fmt);
57356d63 1573 str = dupvprintf(fmt, ap);
1574 str2 = dupcat("Fatal: ", str, "\n", NULL);
1575 sfree(str);
1709795f 1576 va_end(ap);
57356d63 1577 fputs(str2, stderr);
1578 sfree(str2);
1709795f 1579
1580 cleanup_exit(1);
1581}
a8327734 1582void connection_fatal(void *frontend, char *fmt, ...)
4a8fc3c4 1583{
57356d63 1584 char *str, *str2;
4a8fc3c4 1585 va_list ap;
1586 va_start(ap, fmt);
57356d63 1587 str = dupvprintf(fmt, ap);
1588 str2 = dupcat("Fatal: ", str, "\n", NULL);
1589 sfree(str);
4a8fc3c4 1590 va_end(ap);
57356d63 1591 fputs(str2, stderr);
1592 sfree(str2);
4a8fc3c4 1593
93b581bd 1594 cleanup_exit(1);
4a8fc3c4 1595}
1596
6b78788a 1597void ldisc_send(void *handle, char *buf, int len, int interactive)
32874aea 1598{
4a8fc3c4 1599 /*
1600 * This is only here because of the calls to ldisc_send(NULL,
1601 * 0) in ssh.c. Nothing in PSFTP actually needs to use the
1602 * ldisc as an ldisc. So if we get called with any real data, I
1603 * want to know about it.
4c7f0d61 1604 */
4a8fc3c4 1605 assert(len == 0);
1606}
1607
1608/*
c44bf5bd 1609 * In psftp, all agent requests should be synchronous, so this is a
1610 * never-called stub.
1611 */
1612void agent_schedule_callback(void (*callback)(void *, void *, int),
1613 void *callback_ctx, void *data, int len)
1614{
1615 assert(!"We shouldn't be here");
1616}
1617
1618/*
4a8fc3c4 1619 * Receive a block of data from the SSH link. Block until all data
1620 * is available.
1621 *
1622 * To do this, we repeatedly call the SSH protocol module, with our
1623 * own trap in from_backend() to catch the data that comes back. We
1624 * do this until we have enough data.
1625 */
1626
32874aea 1627static unsigned char *outptr; /* where to put the data */
1628static unsigned outlen; /* how much data required */
4a8fc3c4 1629static unsigned char *pending = NULL; /* any spare data */
32874aea 1630static unsigned pendlen = 0, pendsize = 0; /* length and phys. size of buffer */
9fab77dc 1631int from_backend(void *frontend, int is_stderr, const char *data, int datalen)
32874aea 1632{
1633 unsigned char *p = (unsigned char *) data;
1634 unsigned len = (unsigned) datalen;
4a8fc3c4 1635
2b0c045b 1636 assert(len > 0);
1637
4a8fc3c4 1638 /*
1639 * stderr data is just spouted to local stderr and otherwise
1640 * ignored.
1641 */
1642 if (is_stderr) {
1643 fwrite(data, 1, len, stderr);
5471d09a 1644 return 0;
4a8fc3c4 1645 }
1646
1647 /*
1648 * If this is before the real session begins, just return.
1649 */
1650 if (!outptr)
5471d09a 1651 return 0;
4a8fc3c4 1652
1653 if (outlen > 0) {
32874aea 1654 unsigned used = outlen;
1655 if (used > len)
1656 used = len;
1657 memcpy(outptr, p, used);
1658 outptr += used;
1659 outlen -= used;
1660 p += used;
1661 len -= used;
4a8fc3c4 1662 }
1663
1664 if (len > 0) {
32874aea 1665 if (pendsize < pendlen + len) {
1666 pendsize = pendlen + len + 4096;
3d88e64d 1667 pending = sresize(pending, pendsize, unsigned char);
32874aea 1668 }
1669 memcpy(pending + pendlen, p, len);
1670 pendlen += len;
4a8fc3c4 1671 }
5471d09a 1672
1673 return 0;
4a8fc3c4 1674}
32874aea 1675int sftp_recvdata(char *buf, int len)
1676{
1677 outptr = (unsigned char *) buf;
4a8fc3c4 1678 outlen = len;
1679
1680 /*
1681 * See if the pending-input block contains some of what we
1682 * need.
1683 */
1684 if (pendlen > 0) {
32874aea 1685 unsigned pendused = pendlen;
1686 if (pendused > outlen)
1687 pendused = outlen;
4a8fc3c4 1688 memcpy(outptr, pending, pendused);
32874aea 1689 memmove(pending, pending + pendused, pendlen - pendused);
4a8fc3c4 1690 outptr += pendused;
1691 outlen -= pendused;
32874aea 1692 pendlen -= pendused;
1693 if (pendlen == 0) {
1694 pendsize = 0;
1695 sfree(pending);
1696 pending = NULL;
1697 }
1698 if (outlen == 0)
1699 return 1;
4a8fc3c4 1700 }
1701
1702 while (outlen > 0) {
d6cc41e6 1703 if (ssh_sftp_loop_iteration() < 0)
32874aea 1704 return 0; /* doom */
4a8fc3c4 1705 }
1706
1707 return 1;
1708}
32874aea 1709int sftp_senddata(char *buf, int len)
1710{
51470298 1711 back->send(backhandle, (unsigned char *) buf, len);
4a8fc3c4 1712 return 1;
1713}
1714
1715/*
4a8fc3c4 1716 * Short description of parameters.
1717 */
1718static void usage(void)
1719{
1720 printf("PuTTY Secure File Transfer (SFTP) client\n");
1721 printf("%s\n", ver);
1722 printf("Usage: psftp [options] user@host\n");
1723 printf("Options:\n");
9954aaa3 1724 printf(" -b file use specified batchfile\n");
1725 printf(" -bc output batchfile commands\n");
1726 printf(" -be don't stop batchfile processing if errors\n");
4a8fc3c4 1727 printf(" -v show verbose messages\n");
e2a197cf 1728 printf(" -load sessname Load settings from saved session\n");
1729 printf(" -l user connect with specified username\n");
4a8fc3c4 1730 printf(" -P port connect to specified port\n");
1731 printf(" -pw passw login with specified password\n");
e2a197cf 1732 printf(" -1 -2 force use of particular SSH protocol version\n");
1733 printf(" -C enable compression\n");
1734 printf(" -i key private key file for authentication\n");
1735 printf(" -batch disable all interactive prompts\n");
93b581bd 1736 cleanup_exit(1);
4a8fc3c4 1737}
1738
1739/*
fa3db767 1740 * Connect to a host.
4a8fc3c4 1741 */
fa3db767 1742static int psftp_connect(char *userhost, char *user, int portnumber)
4a8fc3c4 1743{
fa3db767 1744 char *host, *realhost;
cbe2d68f 1745 const char *err;
b51259f6 1746 void *logctx;
4a8fc3c4 1747
1748 /* Separate host and username */
1749 host = userhost;
1750 host = strrchr(host, '@');
1751 if (host == NULL) {
1752 host = userhost;
1753 } else {
1754 *host++ = '\0';
1755 if (user) {
32874aea 1756 printf("psftp: multiple usernames specified; using \"%s\"\n",
1757 user);
4a8fc3c4 1758 } else
1759 user = userhost;
1760 }
1761
1762 /* Try to load settings for this host */
1763 do_defaults(host, &cfg);
1764 if (cfg.host[0] == '\0') {
1765 /* No settings for this host; use defaults */
32874aea 1766 do_defaults(NULL, &cfg);
1767 strncpy(cfg.host, host, sizeof(cfg.host) - 1);
1768 cfg.host[sizeof(cfg.host) - 1] = '\0';
f133db8e 1769 }
1770
1771 /*
1772 * Force use of SSH. (If they got the protocol wrong we assume the
1773 * port is useless too.)
1774 */
1775 if (cfg.protocol != PROT_SSH) {
1776 cfg.protocol = PROT_SSH;
1777 cfg.port = 22;
4a8fc3c4 1778 }
1779
449925a6 1780 /*
c0a81592 1781 * Enact command-line overrides.
1782 */
5555d393 1783 cmdline_run_saved(&cfg);
c0a81592 1784
1785 /*
449925a6 1786 * Trim leading whitespace off the hostname if it's there.
1787 */
1788 {
1789 int space = strspn(cfg.host, " \t");
1790 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
1791 }
1792
1793 /* See if host is of the form user@host */
1794 if (cfg.host[0] != '\0') {
1795 char *atsign = strchr(cfg.host, '@');
1796 /* Make sure we're not overflowing the user field */
1797 if (atsign) {
1798 if (atsign - cfg.host < sizeof cfg.username) {
1799 strncpy(cfg.username, cfg.host, atsign - cfg.host);
1800 cfg.username[atsign - cfg.host] = '\0';
1801 }
1802 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
1803 }
1804 }
1805
1806 /*
1807 * Trim a colon suffix off the hostname if it's there.
1808 */
1809 cfg.host[strcspn(cfg.host, ":")] = '\0';
1810
cae0c023 1811 /*
1812 * Remove any remaining whitespace from the hostname.
1813 */
1814 {
1815 int p1 = 0, p2 = 0;
1816 while (cfg.host[p2] != '\0') {
1817 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
1818 cfg.host[p1] = cfg.host[p2];
1819 p1++;
1820 }
1821 p2++;
1822 }
1823 cfg.host[p1] = '\0';
1824 }
1825
4a8fc3c4 1826 /* Set username */
1827 if (user != NULL && user[0] != '\0') {
32874aea 1828 strncpy(cfg.username, user, sizeof(cfg.username) - 1);
1829 cfg.username[sizeof(cfg.username) - 1] = '\0';
4a8fc3c4 1830 }
1831 if (!cfg.username[0]) {
1832 printf("login as: ");
f55eceed 1833 fflush(stdout);
4a8fc3c4 1834 if (!fgets(cfg.username, sizeof(cfg.username), stdin)) {
1835 fprintf(stderr, "psftp: aborting\n");
93b581bd 1836 cleanup_exit(1);
4a8fc3c4 1837 } else {
1838 int len = strlen(cfg.username);
32874aea 1839 if (cfg.username[len - 1] == '\n')
1840 cfg.username[len - 1] = '\0';
4a8fc3c4 1841 }
1842 }
1843
4a8fc3c4 1844 if (portnumber)
1845 cfg.port = portnumber;
1846
1847 /* SFTP uses SSH2 by default always */
1848 cfg.sshprot = 2;
1849
d27b4a18 1850 /*
1851 * Disable scary things which shouldn't be enabled for simple
1852 * things like SCP and SFTP: agent forwarding, port forwarding,
1853 * X forwarding.
1854 */
1855 cfg.x11_forward = 0;
1856 cfg.agentfwd = 0;
1857 cfg.portfwd[0] = cfg.portfwd[1] = '\0';
1858
bebf22d0 1859 /* Set up subsystem name. */
4a8fc3c4 1860 strcpy(cfg.remote_cmd, "sftp");
1861 cfg.ssh_subsys = TRUE;
1862 cfg.nopty = TRUE;
1863
bebf22d0 1864 /*
1865 * Set up fallback option, for SSH1 servers or servers with the
1866 * sftp subsystem not enabled but the server binary installed
1867 * in the usual place. We only support fallback on Unix
248c0c5a 1868 * systems, and we use a kludgy piece of shellery which should
1869 * try to find sftp-server in various places (the obvious
1870 * systemwide spots /usr/lib and /usr/local/lib, and then the
1871 * user's PATH) and finally give up.
bebf22d0 1872 *
248c0c5a 1873 * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server
1874 * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server
1875 * exec sftp-server
bebf22d0 1876 *
1877 * the idea being that this will attempt to use either of the
1878 * obvious pathnames and then give up, and when it does give up
1879 * it will print the preferred pathname in the error messages.
1880 */
1881 cfg.remote_cmd_ptr2 =
248c0c5a 1882 "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
1883 "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
1884 "exec sftp-server";
bebf22d0 1885 cfg.ssh_subsys2 = FALSE;
1886
4a8fc3c4 1887 back = &ssh_backend;
1888
86916870 1889 err = back->init(NULL, &backhandle, &cfg, cfg.host, cfg.port, &realhost,0);
4a8fc3c4 1890 if (err != NULL) {
fa3db767 1891 fprintf(stderr, "ssh_init: %s\n", err);
4a8fc3c4 1892 return 1;
1893 }
c229ef97 1894 logctx = log_init(NULL, &cfg);
a8327734 1895 back->provide_logctx(backhandle, logctx);
d3fef4a5 1896 console_provide_logctx(logctx);
d6cc41e6 1897 while (!back->sendok(backhandle)) {
1898 if (ssh_sftp_loop_iteration() < 0) {
1899 fprintf(stderr, "ssh_init: error during SSH connection setup\n");
1900 return 1;
1901 }
1902 }
4a8fc3c4 1903 if (verbose && realhost != NULL)
1904 printf("Connected to %s\n", realhost);
fa3db767 1905 return 0;
1906}
1907
c0a81592 1908void cmdline_error(char *p, ...)
1909{
1910 va_list ap;
86256dc6 1911 fprintf(stderr, "psftp: ");
c0a81592 1912 va_start(ap, p);
1913 vfprintf(stderr, p, ap);
1914 va_end(ap);
86256dc6 1915 fprintf(stderr, "\n try typing \"psftp -h\" for help\n");
c0a81592 1916 exit(1);
1917}
1918
fa3db767 1919/*
1920 * Main program. Parse arguments etc.
1921 */
d6cc41e6 1922int psftp_main(int argc, char *argv[])
fa3db767 1923{
1924 int i;
1925 int portnumber = 0;
1926 char *userhost, *user;
1927 int mode = 0;
1928 int modeflags = 0;
1929 char *batchfile = NULL;
86256dc6 1930 int errors = 0;
fa3db767 1931
b51259f6 1932 flags = FLAG_STDERR | FLAG_INTERACTIVE
1933#ifdef FLAG_SYNCAGENT
1934 | FLAG_SYNCAGENT
1935#endif
1936 ;
c0a81592 1937 cmdline_tooltype = TOOLTYPE_FILETRANSFER;
ff2ae367 1938 ssh_get_line = &console_get_line;
fa3db767 1939 sk_init();
1940
1941 userhost = user = NULL;
1942
86256dc6 1943 errors = 0;
fa3db767 1944 for (i = 1; i < argc; i++) {
c0a81592 1945 int ret;
fa3db767 1946 if (argv[i][0] != '-') {
c0a81592 1947 if (userhost)
1948 usage();
1949 else
1950 userhost = dupstr(argv[i]);
1951 continue;
1952 }
5555d393 1953 ret = cmdline_process_param(argv[i], i+1<argc?argv[i+1]:NULL, 1, &cfg);
c0a81592 1954 if (ret == -2) {
1955 cmdline_error("option \"%s\" requires an argument", argv[i]);
1956 } else if (ret == 2) {
1957 i++; /* skip next argument */
1958 } else if (ret == 1) {
1959 /* We have our own verbosity in addition to `flags'. */
1960 if (flags & FLAG_VERBOSE)
1961 verbose = 1;
fa3db767 1962 } else if (strcmp(argv[i], "-h") == 0 ||
1963 strcmp(argv[i], "-?") == 0) {
1964 usage();
c0a81592 1965 } else if (strcmp(argv[i], "-batch") == 0) {
1966 console_batch_mode = 1;
fa3db767 1967 } else if (strcmp(argv[i], "-b") == 0 && i + 1 < argc) {
1968 mode = 1;
1969 batchfile = argv[++i];
d13c2ee9 1970 } else if (strcmp(argv[i], "-bc") == 0) {
fa3db767 1971 modeflags = modeflags | 1;
d13c2ee9 1972 } else if (strcmp(argv[i], "-be") == 0) {
fa3db767 1973 modeflags = modeflags | 2;
1974 } else if (strcmp(argv[i], "--") == 0) {
1975 i++;
1976 break;
1977 } else {
86256dc6 1978 cmdline_error("unknown option \"%s\"", argv[i]);
fa3db767 1979 }
1980 }
1981 argc -= i;
1982 argv += i;
1983 back = NULL;
1984
1985 /*
1986 * If a user@host string has already been provided, connect to
1987 * it now.
1988 */
1989 if (userhost) {
1990 if (psftp_connect(userhost, user, portnumber))
1991 return 1;
774204f5 1992 if (do_sftp_init())
1993 return 1;
fa3db767 1994 } else {
1995 printf("psftp: no hostname specified; use \"open host.name\""
1996 " to connect\n");
1997 }
4c7f0d61 1998
9954aaa3 1999 do_sftp(mode, modeflags, batchfile);
4a8fc3c4 2000
51470298 2001 if (back != NULL && back->socket(backhandle) != NULL) {
4a8fc3c4 2002 char ch;
51470298 2003 back->special(backhandle, TS_EOF);
4a8fc3c4 2004 sftp_recvdata(&ch, 1);
2005 }
4a8fc3c4 2006 random_save_seed();
2007
4c7f0d61 2008 return 0;
2009}