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