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