forked from rdebath/PuTTY
-
Notifications
You must be signed in to change notification settings - Fork 2
/
psftp.c
3005 lines (2654 loc) · 75.1 KB
/
psftp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* psftp.c: (platform-independent) front end for PSFTP.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <limits.h>
#define PUTTY_DO_GLOBALS
#include "putty.h"
#include "psftp.h"
#include "storage.h"
#include "ssh.h"
#include "sftp.h"
#include "int64.h"
const char *const appname = "PSFTP";
/*
* Since SFTP is a request-response oriented protocol, it requires
* no buffer management: when we send data, we stop and wait for an
* acknowledgement _anyway_, and so we can't possibly overfill our
* send buffer.
*/
static int psftp_connect(char *userhost, char *user, int portnumber);
static int do_sftp_init(void);
void do_sftp_cleanup();
/* ----------------------------------------------------------------------
* sftp client state.
*/
char *pwd, *homedir;
static Backend *back;
static void *backhandle;
static Conf *conf;
int sent_eof = FALSE;
/* ----------------------------------------------------------------------
* Manage sending requests and waiting for replies.
*/
struct sftp_packet *sftp_wait_for_reply(struct sftp_request *req)
{
struct sftp_packet *pktin;
struct sftp_request *rreq;
sftp_register(req);
pktin = sftp_recv();
if (pktin == NULL)
connection_fatal(NULL, "did not receive SFTP response packet "
"from server");
rreq = sftp_find_request(pktin);
if (rreq != req)
connection_fatal(NULL, "unable to understand SFTP response packet "
"from server: %s", fxp_error());
return pktin;
}
/* ----------------------------------------------------------------------
* Higher-level helper functions used in commands.
*/
/*
* Attempt to canonify a pathname starting from the pwd. If
* canonification fails, at least fall back to returning a _valid_
* pathname (though it may be ugly, eg /home/simon/../foobar).
*/
char *canonify(const char *name)
{
char *fullname, *canonname;
struct sftp_packet *pktin;
struct sftp_request *req;
if (name[0] == '/') {
fullname = dupstr(name);
} else {
const char *slash;
if (pwd[strlen(pwd) - 1] == '/')
slash = "";
else
slash = "/";
fullname = dupcat(pwd, slash, name, NULL);
}
req = fxp_realpath_send(fullname);
pktin = sftp_wait_for_reply(req);
canonname = fxp_realpath_recv(pktin, req);
if (canonname) {
sfree(fullname);
return canonname;
} else {
/*
* Attempt number 2. Some FXP_REALPATH implementations
* (glibc-based ones, in particular) require the _whole_
* path to point to something that exists, whereas others
* (BSD-based) only require all but the last component to
* exist. So if the first call failed, we should strip off
* everything from the last slash onwards and try again,
* then put the final component back on.
*
* Special cases:
*
* - if the last component is "/." or "/..", then we don't
* bother trying this because there's no way it can work.
*
* - if the thing actually ends with a "/", we remove it
* before we start. Except if the string is "/" itself
* (although I can't see why we'd have got here if so,
* because surely "/" would have worked the first
* time?), in which case we don't bother.
*
* - if there's no slash in the string at all, give up in
* confusion (we expect at least one because of the way
* we constructed the string).
*/
int i;
char *returnname;
i = strlen(fullname);
if (i > 2 && fullname[i - 1] == '/')
fullname[--i] = '\0'; /* strip trailing / unless at pos 0 */
while (i > 0 && fullname[--i] != '/');
/*
* Give up on special cases.
*/
if (fullname[i] != '/' || /* no slash at all */
!strcmp(fullname + i, "/.") || /* ends in /. */
!strcmp(fullname + i, "/..") || /* ends in /.. */
!strcmp(fullname, "/")) {
return fullname;
}
/*
* Now i points at the slash. Deal with the final special
* case i==0 (ie the whole path was "/nonexistentfile").
*/
fullname[i] = '\0'; /* separate the string */
if (i == 0) {
req = fxp_realpath_send("/");
} else {
req = fxp_realpath_send(fullname);
}
pktin = sftp_wait_for_reply(req);
canonname = fxp_realpath_recv(pktin, req);
if (!canonname) {
/* Even that failed. Restore our best guess at the
* constructed filename and give up */
fullname[i] = '/'; /* restore slash and last component */
return fullname;
}
/*
* We have a canonical name for all but the last path
* component. Concatenate the last component and return.
*/
returnname = dupcat(canonname,
canonname[strlen(canonname) - 1] ==
'/' ? "" : "/", fullname + i + 1, NULL);
sfree(fullname);
sfree(canonname);
return returnname;
}
}
/*
* Return a pointer to the portion of str that comes after the last
* slash (or backslash or colon, if `local' is TRUE).
*
* This function has the annoying strstr() property of taking a const
* char * and returning a char *. You should treat it as if it was a
* pair of overloaded functions, one mapping mutable->mutable and the
* other const->const :-(
*/
static char *stripslashes(const char *str, int local)
{
char *p;
if (local) {
p = strchr(str, ':');
if (p) str = p+1;
}
p = strrchr(str, '/');
if (p) str = p+1;
if (local) {
p = strrchr(str, '\\');
if (p) str = p+1;
}
return (char *)str;
}
/*
* qsort comparison routine for fxp_name structures. Sorts by real
* file name.
*/
static int sftp_name_compare(const void *av, const void *bv)
{
const struct fxp_name *const *a = (const struct fxp_name *const *) av;
const struct fxp_name *const *b = (const struct fxp_name *const *) bv;
return strcmp((*a)->filename, (*b)->filename);
}
/*
* Likewise, but for a bare char *.
*/
static int bare_name_compare(const void *av, const void *bv)
{
const char **a = (const char **) av;
const char **b = (const char **) bv;
return strcmp(*a, *b);
}
static void not_connected(void)
{
printf("psftp: not connected to a host; use \"open host.name\"\n");
}
/* ----------------------------------------------------------------------
* The meat of the `get' and `put' commands.
*/
int sftp_get_file(char *fname, char *outfname, int recurse, int restart)
{
struct fxp_handle *fh;
struct sftp_packet *pktin;
struct sftp_request *req;
struct fxp_xfer *xfer;
uint64 offset;
WFile *file;
int ret, shown_err = FALSE;
struct fxp_attrs attrs;
/*
* In recursive mode, see if we're dealing with a directory.
* (If we're not in recursive mode, we need not even check: the
* subsequent FXP_OPEN will return a usable error message.)
*/
if (recurse) {
int result;
req = fxp_stat_send(fname);
pktin = sftp_wait_for_reply(req);
result = fxp_stat_recv(pktin, req, &attrs);
if (result &&
(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
(attrs.permissions & 0040000)) {
struct fxp_handle *dirhandle;
int nnames, namesize;
struct fxp_name **ournames;
struct fxp_names *names;
int i;
/*
* First, attempt to create the destination directory,
* unless it already exists.
*/
if (file_type(outfname) != FILE_TYPE_DIRECTORY &&
!create_directory(outfname)) {
printf("%s: Cannot create directory\n", outfname);
return 0;
}
/*
* Now get the list of filenames in the remote
* directory.
*/
req = fxp_opendir_send(fname);
pktin = sftp_wait_for_reply(req);
dirhandle = fxp_opendir_recv(pktin, req);
if (!dirhandle) {
printf("%s: unable to open directory: %s\n",
fname, fxp_error());
return 0;
}
nnames = namesize = 0;
ournames = NULL;
while (1) {
int i;
req = fxp_readdir_send(dirhandle);
pktin = sftp_wait_for_reply(req);
names = fxp_readdir_recv(pktin, req);
if (names == NULL) {
if (fxp_error_type() == SSH_FX_EOF)
break;
printf("%s: reading directory: %s\n", fname, fxp_error());
req = fxp_close_send(dirhandle);
pktin = sftp_wait_for_reply(req);
fxp_close_recv(pktin, req);
sfree(ournames);
return 0;
}
if (names->nnames == 0) {
fxp_free_names(names);
break;
}
if (nnames + names->nnames >= namesize) {
namesize += names->nnames + 128;
ournames = sresize(ournames, namesize, struct fxp_name *);
}
for (i = 0; i < names->nnames; i++)
if (strcmp(names->names[i].filename, ".") &&
strcmp(names->names[i].filename, "..")) {
if (!vet_filename(names->names[i].filename)) {
printf("ignoring potentially dangerous server-"
"supplied filename '%s'\n",
names->names[i].filename);
} else {
ournames[nnames++] =
fxp_dup_name(&names->names[i]);
}
}
fxp_free_names(names);
}
req = fxp_close_send(dirhandle);
pktin = sftp_wait_for_reply(req);
fxp_close_recv(pktin, req);
/*
* Sort the names into a clear order. This ought to
* make things more predictable when we're doing a
* reget of the same directory, just in case two
* readdirs on the same remote directory return a
* different order.
*/
if (nnames > 0)
qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare);
/*
* If we're in restart mode, find the last filename on
* this list that already exists. We may have to do a
* reget on _that_ file, but shouldn't have to do
* anything on the previous files.
*
* If none of them exists, of course, we start at 0.
*/
i = 0;
if (restart) {
while (i < nnames) {
char *nextoutfname;
int ret;
nextoutfname = dir_file_cat(outfname,
ournames[i]->filename);
ret = (file_type(nextoutfname) == FILE_TYPE_NONEXISTENT);
sfree(nextoutfname);
if (ret)
break;
i++;
}
if (i > 0)
i--;
}
/*
* Now we're ready to recurse. Starting at ournames[i]
* and continuing on to the end of the list, we
* construct a new source and target file name, and
* call sftp_get_file again.
*/
for (; i < nnames; i++) {
char *nextfname, *nextoutfname;
int ret;
nextfname = dupcat(fname, "/", ournames[i]->filename, NULL);
nextoutfname = dir_file_cat(outfname, ournames[i]->filename);
ret = sftp_get_file(nextfname, nextoutfname, recurse, restart);
restart = FALSE; /* after first partial file, do full */
sfree(nextoutfname);
sfree(nextfname);
if (!ret) {
for (i = 0; i < nnames; i++) {
fxp_free_name(ournames[i]);
}
sfree(ournames);
return 0;
}
}
/*
* Done this recursion level. Free everything.
*/
for (i = 0; i < nnames; i++) {
fxp_free_name(ournames[i]);
}
sfree(ournames);
return 1;
}
}
req = fxp_stat_send(fname);
pktin = sftp_wait_for_reply(req);
if (!fxp_stat_recv(pktin, req, &attrs))
attrs.flags = 0;
req = fxp_open_send(fname, SSH_FXF_READ, NULL);
pktin = sftp_wait_for_reply(req);
fh = fxp_open_recv(pktin, req);
if (!fh) {
printf("%s: open for read: %s\n", fname, fxp_error());
return 0;
}
if (restart) {
file = open_existing_wfile(outfname, NULL);
} else {
file = open_new_file(outfname, GET_PERMISSIONS(attrs));
}
if (!file) {
printf("local: unable to open %s\n", outfname);
req = fxp_close_send(fh);
pktin = sftp_wait_for_reply(req);
fxp_close_recv(pktin, req);
return 0;
}
if (restart) {
char decbuf[30];
if (seek_file(file, uint64_make(0,0) , FROM_END) == -1) {
close_wfile(file);
printf("reget: cannot restart %s - file too large\n",
outfname);
req = fxp_close_send(fh);
pktin = sftp_wait_for_reply(req);
fxp_close_recv(pktin, req);
return 0;
}
offset = get_file_posn(file);
uint64_decimal(offset, decbuf);
printf("reget: restarting at file position %s\n", decbuf);
} else {
offset = uint64_make(0, 0);
}
printf("remote:%s => local:%s\n", fname, outfname);
/*
* FIXME: we can use FXP_FSTAT here to get the file size, and
* thus put up a progress bar.
*/
ret = 1;
xfer = xfer_download_init(fh, offset);
while (!xfer_done(xfer)) {
void *vbuf;
int ret, len;
int wpos, wlen;
xfer_download_queue(xfer);
pktin = sftp_recv();
ret = xfer_download_gotpkt(xfer, pktin);
if (ret <= 0) {
if (!shown_err) {
printf("error while reading: %s\n", fxp_error());
shown_err = TRUE;
}
if (ret == INT_MIN) /* pktin not even freed */
sfree(pktin);
ret = 0;
}
while (xfer_download_data(xfer, &vbuf, &len)) {
unsigned char *buf = (unsigned char *)vbuf;
wpos = 0;
while (wpos < len) {
wlen = write_to_file(file, buf + wpos, len - wpos);
if (wlen <= 0) {
printf("error while writing local file\n");
ret = 0;
xfer_set_error(xfer);
break;
}
wpos += wlen;
}
if (wpos < len) { /* we had an error */
ret = 0;
xfer_set_error(xfer);
}
sfree(vbuf);
}
}
xfer_cleanup(xfer);
close_wfile(file);
req = fxp_close_send(fh);
pktin = sftp_wait_for_reply(req);
fxp_close_recv(pktin, req);
return ret;
}
int sftp_put_file(char *fname, char *outfname, int recurse, int restart)
{
struct fxp_handle *fh;
struct fxp_xfer *xfer;
struct sftp_packet *pktin;
struct sftp_request *req;
uint64 offset;
RFile *file;
int ret, err, eof;
struct fxp_attrs attrs;
long permissions;
/*
* In recursive mode, see if we're dealing with a directory.
* (If we're not in recursive mode, we need not even check: the
* subsequent fopen will return an error message.)
*/
if (recurse && file_type(fname) == FILE_TYPE_DIRECTORY) {
int result;
int nnames, namesize;
char *name, **ournames;
DirHandle *dh;
int i;
/*
* First, attempt to create the destination directory,
* unless it already exists.
*/
req = fxp_stat_send(outfname);
pktin = sftp_wait_for_reply(req);
result = fxp_stat_recv(pktin, req, &attrs);
if (!result ||
!(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) ||
!(attrs.permissions & 0040000)) {
req = fxp_mkdir_send(outfname);
pktin = sftp_wait_for_reply(req);
result = fxp_mkdir_recv(pktin, req);
if (!result) {
printf("%s: create directory: %s\n",
outfname, fxp_error());
return 0;
}
}
/*
* Now get the list of filenames in the local directory.
*/
nnames = namesize = 0;
ournames = NULL;
dh = open_directory(fname);
if (!dh) {
printf("%s: unable to open directory\n", fname);
return 0;
}
while ((name = read_filename(dh)) != NULL) {
if (nnames >= namesize) {
namesize += 128;
ournames = sresize(ournames, namesize, char *);
}
ournames[nnames++] = name;
}
close_directory(dh);
/*
* Sort the names into a clear order. This ought to make
* things more predictable when we're doing a reput of the
* same directory, just in case two readdirs on the same
* local directory return a different order.
*/
if (nnames > 0)
qsort(ournames, nnames, sizeof(*ournames), bare_name_compare);
/*
* If we're in restart mode, find the last filename on this
* list that already exists. We may have to do a reput on
* _that_ file, but shouldn't have to do anything on the
* previous files.
*
* If none of them exists, of course, we start at 0.
*/
i = 0;
if (restart) {
while (i < nnames) {
char *nextoutfname;
nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
req = fxp_stat_send(nextoutfname);
pktin = sftp_wait_for_reply(req);
result = fxp_stat_recv(pktin, req, &attrs);
sfree(nextoutfname);
if (!result)
break;
i++;
}
if (i > 0)
i--;
}
/*
* Now we're ready to recurse. Starting at ournames[i]
* and continuing on to the end of the list, we
* construct a new source and target file name, and
* call sftp_put_file again.
*/
for (; i < nnames; i++) {
char *nextfname, *nextoutfname;
int ret;
nextfname = dir_file_cat(fname, ournames[i]);
nextoutfname = dupcat(outfname, "/", ournames[i], NULL);
ret = sftp_put_file(nextfname, nextoutfname, recurse, restart);
restart = FALSE; /* after first partial file, do full */
sfree(nextoutfname);
sfree(nextfname);
if (!ret) {
for (i = 0; i < nnames; i++) {
sfree(ournames[i]);
}
sfree(ournames);
return 0;
}
}
/*
* Done this recursion level. Free everything.
*/
for (i = 0; i < nnames; i++) {
sfree(ournames[i]);
}
sfree(ournames);
return 1;
}
file = open_existing_file(fname, NULL, NULL, NULL, &permissions);
if (!file) {
printf("local: unable to open %s\n", fname);
return 0;
}
attrs.flags = 0;
PUT_PERMISSIONS(attrs, permissions);
if (restart) {
req = fxp_open_send(outfname, SSH_FXF_WRITE, &attrs);
} else {
req = fxp_open_send(outfname,
SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC,
&attrs);
}
pktin = sftp_wait_for_reply(req);
fh = fxp_open_recv(pktin, req);
if (!fh) {
close_rfile(file);
printf("%s: open for write: %s\n", outfname, fxp_error());
return 0;
}
if (restart) {
char decbuf[30];
struct fxp_attrs attrs;
req = fxp_fstat_send(fh);
pktin = sftp_wait_for_reply(req);
ret = fxp_fstat_recv(pktin, req, &attrs);
if (!ret) {
printf("read size of %s: %s\n", outfname, fxp_error());
goto cleanup;
}
if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) {
printf("read size of %s: size was not given\n", outfname);
ret = 0;
goto cleanup;
}
offset = attrs.size;
uint64_decimal(offset, decbuf);
printf("reput: restarting at file position %s\n", decbuf);
if (seek_file((WFile *)file, offset, FROM_START) != 0)
seek_file((WFile *)file, uint64_make(0,0), FROM_END); /* *shrug* */
} else {
offset = uint64_make(0, 0);
}
printf("local:%s => remote:%s\n", fname, outfname);
/*
* FIXME: we can use FXP_FSTAT here to get the file size, and
* thus put up a progress bar.
*/
ret = 1;
xfer = xfer_upload_init(fh, offset);
err = eof = 0;
while ((!err && !eof) || !xfer_done(xfer)) {
char buffer[4096];
int len, ret;
while (xfer_upload_ready(xfer) && !err && !eof) {
len = read_from_file(file, buffer, sizeof(buffer));
if (len == -1) {
printf("error while reading local file\n");
err = 1;
} else if (len == 0) {
eof = 1;
} else {
xfer_upload_data(xfer, buffer, len);
}
}
if (!xfer_done(xfer)) {
pktin = sftp_recv();
ret = xfer_upload_gotpkt(xfer, pktin);
if (ret <= 0) {
if (ret == INT_MIN) /* pktin not even freed */
sfree(pktin);
if (!err) {
printf("error while writing: %s\n", fxp_error());
err = 1;
}
}
}
}
xfer_cleanup(xfer);
cleanup:
req = fxp_close_send(fh);
pktin = sftp_wait_for_reply(req);
fxp_close_recv(pktin, req);
close_rfile(file);
return ret;
}
/* ----------------------------------------------------------------------
* A remote wildcard matcher, providing a similar interface to the
* local one in psftp.h.
*/
typedef struct SftpWildcardMatcher {
struct fxp_handle *dirh;
struct fxp_names *names;
int namepos;
char *wildcard, *prefix;
} SftpWildcardMatcher;
SftpWildcardMatcher *sftp_begin_wildcard_matching(char *name)
{
struct sftp_packet *pktin;
struct sftp_request *req;
char *wildcard;
char *unwcdir, *tmpdir, *cdir;
int len, check;
SftpWildcardMatcher *swcm;
struct fxp_handle *dirh;
/*
* We don't handle multi-level wildcards; so we expect to find
* a fully specified directory part, followed by a wildcard
* after that.
*/
wildcard = stripslashes(name, 0);
unwcdir = dupstr(name);
len = wildcard - name;
unwcdir[len] = '\0';
if (len > 0 && unwcdir[len-1] == '/')
unwcdir[len-1] = '\0';
tmpdir = snewn(1 + len, char);
check = wc_unescape(tmpdir, unwcdir);
sfree(tmpdir);
if (!check) {
printf("Multiple-level wildcards are not supported\n");
sfree(unwcdir);
return NULL;
}
cdir = canonify(unwcdir);
req = fxp_opendir_send(cdir);
pktin = sftp_wait_for_reply(req);
dirh = fxp_opendir_recv(pktin, req);
if (dirh) {
swcm = snew(SftpWildcardMatcher);
swcm->dirh = dirh;
swcm->names = NULL;
swcm->wildcard = dupstr(wildcard);
swcm->prefix = unwcdir;
} else {
printf("Unable to open %s: %s\n", cdir, fxp_error());
swcm = NULL;
sfree(unwcdir);
}
sfree(cdir);
return swcm;
}
char *sftp_wildcard_get_filename(SftpWildcardMatcher *swcm)
{
struct fxp_name *name;
struct sftp_packet *pktin;
struct sftp_request *req;
while (1) {
if (swcm->names && swcm->namepos >= swcm->names->nnames) {
fxp_free_names(swcm->names);
swcm->names = NULL;
}
if (!swcm->names) {
req = fxp_readdir_send(swcm->dirh);
pktin = sftp_wait_for_reply(req);
swcm->names = fxp_readdir_recv(pktin, req);
if (!swcm->names) {
if (fxp_error_type() != SSH_FX_EOF)
printf("%s: reading directory: %s\n", swcm->prefix,
fxp_error());
return NULL;
} else if (swcm->names->nnames == 0) {
/*
* Another failure mode which we treat as EOF is if
* the server reports success from FXP_READDIR but
* returns no actual names. This is unusual, since
* from most servers you'd expect at least "." and
* "..", but there's nothing forbidding a server from
* omitting those if it wants to.
*/
return NULL;
}
swcm->namepos = 0;
}
assert(swcm->names && swcm->namepos < swcm->names->nnames);
name = &swcm->names->names[swcm->namepos++];
if (!strcmp(name->filename, ".") || !strcmp(name->filename, ".."))
continue; /* expected bad filenames */
if (!vet_filename(name->filename)) {
printf("ignoring potentially dangerous server-"
"supplied filename '%s'\n", name->filename);
continue; /* unexpected bad filename */
}
if (!wc_match(swcm->wildcard, name->filename))
continue; /* doesn't match the wildcard */
/*
* We have a working filename. Return it.
*/
return dupprintf("%s%s%s", swcm->prefix,
(!swcm->prefix[0] ||
swcm->prefix[strlen(swcm->prefix)-1]=='/' ?
"" : "/"),
name->filename);
}
}
void sftp_finish_wildcard_matching(SftpWildcardMatcher *swcm)
{
struct sftp_packet *pktin;
struct sftp_request *req;
req = fxp_close_send(swcm->dirh);
pktin = sftp_wait_for_reply(req);
fxp_close_recv(pktin, req);
if (swcm->names)
fxp_free_names(swcm->names);
sfree(swcm->prefix);
sfree(swcm->wildcard);
sfree(swcm);
}
/*
* General function to match a potential wildcard in a filename
* argument and iterate over every matching file. Used in several
* PSFTP commands (rmdir, rm, chmod, mv).
*/
int wildcard_iterate(char *filename, int (*func)(void *, char *), void *ctx)
{
char *unwcfname, *newname, *cname;
int is_wc, ret;
unwcfname = snewn(strlen(filename)+1, char);
is_wc = !wc_unescape(unwcfname, filename);
if (is_wc) {
SftpWildcardMatcher *swcm = sftp_begin_wildcard_matching(filename);
int matched = FALSE;
sfree(unwcfname);
if (!swcm)
return 0;
ret = 1;
while ( (newname = sftp_wildcard_get_filename(swcm)) != NULL ) {
cname = canonify(newname);
if (!cname) {
printf("%s: canonify: %s\n", newname, fxp_error());
ret = 0;
}
sfree(newname);
matched = TRUE;
ret &= func(ctx, cname);
sfree(cname);
}
if (!matched) {
/* Politely warn the user that nothing matched. */
printf("%s: nothing matched\n", filename);
}
sftp_finish_wildcard_matching(swcm);
} else {
cname = canonify(unwcfname);
if (!cname) {
printf("%s: canonify: %s\n", filename, fxp_error());
ret = 0;
}
ret = func(ctx, cname);
sfree(cname);
sfree(unwcfname);
}
return ret;
}
/*
* Handy helper function.
*/
int is_wildcard(char *name)
{
char *unwcfname = snewn(strlen(name)+1, char);
int is_wc = !wc_unescape(unwcfname, name);
sfree(unwcfname);
return is_wc;
}
/* ----------------------------------------------------------------------
* Actual sftp commands.
*/
struct sftp_command {
char **words;
int nwords, wordssize;
int (*obey) (struct sftp_command *); /* returns <0 to quit */
};
int sftp_cmd_null(struct sftp_command *cmd)
{
return 1; /* success */
}
int sftp_cmd_unknown(struct sftp_command *cmd)
{
printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
return 0; /* failure */
}
int sftp_cmd_quit(struct sftp_command *cmd)
{
return -1;
}
int sftp_cmd_close(struct sftp_command *cmd)
{
if (back == NULL) {
not_connected();
return 0;
}
if (back != NULL && back->connected(backhandle)) {
char ch;
back->special(backhandle, TS_EOF);