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