/
SFTP.php
3156 lines (2788 loc) · 106 KB
/
SFTP.php
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
<?php
/**
* Pure-PHP implementation of SFTP.
*
* PHP version 5
*
* Supports SFTPv2/3/4/5/6. Defaults to v3.
*
* The API for this library is modeled after the API from PHP's {@link http://php.net/book.ftp FTP extension}.
*
* Here's a short example of how to use this library:
* <code>
* <?php
* include 'vendor/autoload.php';
*
* $sftp = new \phpseclib3\Net\SFTP('www.domain.tld');
* if (!$sftp->login('username', 'password')) {
* exit('Login Failed');
* }
*
* echo $sftp->pwd() . "\r\n";
* $sftp->put('filename.ext', 'hello, world!');
* print_r($sftp->nlist());
* ?>
* </code>
*
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2009 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
declare(strict_types=1);
namespace phpseclib3\Net;
use phpseclib3\Common\Functions\Strings;
use phpseclib3\Exception\BadFunctionCallException;
use phpseclib3\Exception\FileNotFoundException;
use phpseclib3\Exception\RuntimeException;
use phpseclib3\Exception\UnexpectedValueException;
use phpseclib3\Net\SFTP\Attribute;
use phpseclib3\Net\SFTP\FileType;
use phpseclib3\Net\SFTP\OpenFlag;
use phpseclib3\Net\SFTP\OpenFlag5;
use phpseclib3\Net\SFTP\PacketType as SFTPPacketType;
use phpseclib3\Net\SFTP\StatusCode;
use phpseclib3\Net\SSH2\DisconnectReason;
use phpseclib3\Net\SSH2\MessageType as SSH2MessageType;
/**
* Pure-PHP implementations of SFTP.
*
* @author Jim Wigginton <terrafrost@php.net>
*/
class SFTP extends SSH2
{
/**
* SFTP channel constant
*
* \phpseclib3\Net\SSH2::exec() uses 0 and \phpseclib3\Net\SSH2::read() / \phpseclib3\Net\SSH2::write() use 1.
*
* @see \phpseclib3\Net\SSH2::send_channel_packet()
* @see \phpseclib3\Net\SSH2::get_channel_packet()
*/
public const CHANNEL = 0x100;
/**
* Reads data from a local file.
*
* @see \phpseclib3\Net\SFTP::put()
*/
public const SOURCE_LOCAL_FILE = 1;
/**
* Reads data from a string.
*
* @see \phpseclib3\Net\SFTP::put()
*/
// this value isn't really used anymore but i'm keeping it reserved for historical reasons
public const SOURCE_STRING = 2;
/**
* Reads data from callback:
* function callback($length) returns string to proceed, null for EOF
*
* @see \phpseclib3\Net\SFTP::put()
*/
public const SOURCE_CALLBACK = 16;
/**
* Resumes an upload
*
* @see \phpseclib3\Net\SFTP::put()
*/
public const RESUME = 4;
/**
* Append a local file to an already existing remote file
*
* @see \phpseclib3\Net\SFTP::put()
*/
public const RESUME_START = 8;
/**
* The Request ID
*
* The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
* concurrent actions, so it's somewhat academic, here.
*
* @see self::_send_sftp_packet()
*/
private bool $use_request_id = false;
/**
* The Packet Type
*
* The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
* concurrent actions, so it's somewhat academic, here.
*
* @see self::_get_sftp_packet()
*/
private int $packet_type = -1;
/**
* Packet Buffer
*
* @see self::_get_sftp_packet()
*/
private string $packet_buffer = '';
/**
* Extensions supported by the server
*
* @see self::_initChannel()
*/
private array $extensions = [];
/**
* Server SFTP version
*
* @see self::_initChannel()
*/
private int $version;
/**
* Default Server SFTP version
*
* @see self::_initChannel()
*/
private int $defaultVersion;
/**
* Preferred SFTP version
*
* @see self::_initChannel()
*/
private int $preferredVersion = 3;
/**
* Current working directory
*
* @see self::realpath()
* @see self::chdir()
*/
private string|bool $pwd = false;
/**
* Packet Type Log
*
* @see self::getLog()
*/
private array $packet_type_log = [];
/**
* Packet Log
*
* @see self::getLog()
*/
private array $packet_log = [];
/**
* Real-time log file pointer
*
* @see self::_append_log()
* @var resource|closed-resource
*/
private $realtime_log_file;
/**
* Real-time log file size
*
* @see self::_append_log()
*/
private int $realtime_log_size;
/**
* Real-time log file wrap boolean
*
* @see self::_append_log()
*/
private bool $realtime_log_wrap;
/**
* Current log size
*
* Should never exceed self::LOG_MAX_SIZE
*/
private int $log_size;
/**
* Error information
*
* @see self::getSFTPErrors()
* @see self::getLastSFTPError()
*/
private array $sftp_errors = [];
/**
* Stat Cache
*
* Rather than always having to open a directory and close it immediately there after to see if a file is a directory
* we'll cache the results.
*
* @see self::_update_stat_cache()
* @see self::_remove_from_stat_cache()
* @see self::_query_stat_cache()
*/
private array $stat_cache = [];
/**
* Max SFTP Packet Size
*
* @see self::__construct()
* @see self::get()
*/
private int $max_sftp_packet;
/**
* Stat Cache Flag
*
* @see self::disableStatCache()
* @see self::enableStatCache()
*/
private bool $use_stat_cache = true;
/**
* Sort Options
*
* @see self::_comparator()
* @see self::setListOrder()
*/
private array $sortOptions = [];
/**
* Canonicalization Flag
*
* Determines whether or not paths should be canonicalized before being
* passed on to the remote server.
*
* @see self::enablePathCanonicalization()
* @see self::disablePathCanonicalization()
* @see self::realpath()
*/
private bool $canonicalize_paths = true;
/**
* Request Buffers
*
* @see self::_get_sftp_packet()
*/
private array $requestBuffer = [];
/**
* Preserve timestamps on file downloads / uploads
*
* @see self::get()
* @see self::put()
*/
private bool $preserveTime = false;
/**
* Arbitrary Length Packets Flag
*
* Determines whether or not packets of any length should be allowed,
* in cases where the server chooses the packet length (such as
* directory listings). By default, packets are only allowed to be
* 256 * 1024 bytes (SFTP_MAX_MSG_LENGTH from OpenSSH's sftp-common.h)
*
* @see self::enableArbitraryLengthPackets()
* @see self::_get_sftp_packet()
*/
private bool $allow_arbitrary_length_packets = false;
/**
* Was the last packet due to the channels being closed or not?
*
* @see self::get()
* @see self::get_sftp_packet()
*/
private bool $channel_close = false;
/**
* Has the SFTP channel been partially negotiated?
*/
private bool $partial_init = false;
private int $queueSize = 32;
private int $uploadQueueSize = 1024;
/**
* Default Constructor.
*
* Connects to an SFTP server
*/
public function __construct($host, int $port = 22, int $timeout = 10)
{
parent::__construct($host, $port, $timeout);
$this->max_sftp_packet = 1 << 15;
if (defined('NET_SFTP_QUEUE_SIZE')) {
$this->queueSize = NET_SFTP_QUEUE_SIZE;
}
if (defined('NET_SFTP_UPLOAD_QUEUE_SIZE')) {
$this->uploadQueueSize = NET_SFTP_UPLOAD_QUEUE_SIZE;
}
}
/**
* Check a few things before SFTP functions are called
*/
private function precheck(): bool
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
if ($this->pwd === false) {
return $this->init_sftp_connection();
}
return true;
}
/**
* Partially initialize an SFTP connection
*
* @throws UnexpectedValueException on receipt of unexpected packets
*/
private function partial_init_sftp_connection(): bool
{
$response = $this->open_channel(self::CHANNEL, true);
if ($response === true && $this->isTimeout()) {
return false;
}
$packet = Strings::packSSH2(
'CNsbs',
SSH2MessageType::CHANNEL_REQUEST,
$this->server_channels[self::CHANNEL],
'subsystem',
true,
'sftp'
);
$this->send_binary_packet($packet);
$this->channel_status[self::CHANNEL] = SSH2MessageType::CHANNEL_REQUEST;
$response = $this->get_channel_packet(self::CHANNEL, true);
if ($response === false) {
// from PuTTY's psftp.exe
$command = "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n" .
"test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n" .
"exec sftp-server";
// we don't do $this->exec($command, false) because exec() operates on a different channel and plus the SSH_MSG_CHANNEL_OPEN that exec() does
// is redundant
$packet = Strings::packSSH2(
'CNsCs',
SSH2MessageType::CHANNEL_REQUEST,
$this->server_channels[self::CHANNEL],
'exec',
1,
$command
);
$this->send_binary_packet($packet);
$this->channel_status[self::CHANNEL] = SSH2MessageType::CHANNEL_REQUEST;
$response = $this->get_channel_packet(self::CHANNEL, true);
if ($response === false) {
return false;
}
} elseif ($response === true && $this->isTimeout()) {
return false;
}
$this->channel_status[self::CHANNEL] = SSH2MessageType::CHANNEL_DATA;
$this->send_sftp_packet(SFTPPacketType::INIT, "\0\0\0\3");
$response = $this->get_sftp_packet();
if ($this->packet_type != SFTPPacketType::VERSION) {
throw new UnexpectedValueException('Expected PacketType::VERSION. '
. 'Got packet type: ' . $this->packet_type);
}
$this->use_request_id = true;
[$this->defaultVersion] = Strings::unpackSSH2('N', $response);
while (!empty($response)) {
[$key, $value] = Strings::unpackSSH2('ss', $response);
$this->extensions[$key] = $value;
}
$this->partial_init = true;
return true;
}
/**
* (Re)initializes the SFTP channel
*/
private function init_sftp_connection(): bool
{
if (!$this->partial_init && !$this->partial_init_sftp_connection()) {
return false;
}
/*
A Note on SFTPv4/5/6 support:
<http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.1> states the following:
"If the client wishes to interoperate with servers that support noncontiguous version
numbers it SHOULD send '3'"
Given that the server only sends its version number after the client has already done so, the above
seems to be suggesting that v3 should be the default version. This makes sense given that v3 is the
most popular.
<http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.5> states the following;
"If the server did not send the "versions" extension, or the version-from-list was not included, the
server MAY send a status response describing the failure, but MUST then close the channel without
processing any further requests."
So what do you do if you have a client whose initial SSH_FXP_INIT packet says it implements v3 and
a server whose initial SSH_FXP_VERSION reply says it implements v4 and only v4? If it only implements
v4, the "versions" extension is likely not going to have been sent so version re-negotiation as discussed
in draft-ietf-secsh-filexfer-13 would be quite impossible. As such, what \phpseclib3\Net\SFTP would do is close the
channel and reopen it with a new and updated SSH_FXP_INIT packet.
*/
$this->version = $this->defaultVersion;
if (isset($this->extensions['versions']) && (!$this->preferredVersion || $this->preferredVersion != $this->version)) {
$versions = explode(',', $this->extensions['versions']);
$supported = [6, 5, 4];
if ($this->preferredVersion) {
$supported = array_diff($supported, [$this->preferredVersion]);
array_unshift($supported, $this->preferredVersion);
}
foreach ($supported as $ver) {
if (in_array($ver, $versions)) {
if ($ver === $this->version) {
break;
}
$this->version = (int) $ver;
$packet = Strings::packSSH2('ss', 'version-select', "$ver");
$this->send_sftp_packet(SFTPPacketType::EXTENDED, $packet);
$response = $this->get_sftp_packet();
if ($this->packet_type != SFTPPacketType::STATUS) {
throw new UnexpectedValueException('Expected PacketType::STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
[$status] = Strings::unpackSSH2('N', $response);
if ($status != StatusCode::OK) {
$this->logError($response, $status);
throw new UnexpectedValueException('Expected StatusCode::OK. '
. ' Got ' . $status);
}
break;
}
}
}
/*
SFTPv4+ defines a 'newline' extension. SFTPv3 seems to have unofficial support for it via 'newline@vandyke.com',
however, I'm not sure what 'newline@vandyke.com' is supposed to do (the fact that it's unofficial means that it's
not in the official SFTPv3 specs) and 'newline@vandyke.com' / 'newline' are likely not drop-in substitutes for
one another due to the fact that 'newline' comes with a SSH_FXF_TEXT bitmask whereas it seems unlikely that
'newline@vandyke.com' would.
*/
/*
if (isset($this->extensions['newline@vandyke.com'])) {
$this->extensions['newline'] = $this->extensions['newline@vandyke.com'];
unset($this->extensions['newline@vandyke.com']);
}
*/
if ($this->version < 2 || $this->version > 6) {
return false;
}
$this->pwd = true;
try {
$this->pwd = $this->realpath('.');
} catch (\UnexpectedValueException $e) {
if (!$this->canonicalize_paths) {
throw $e;
}
$this->canonicalize_paths = false;
$this->reset_connection(DisconnectReason::CONNECTION_LOST);
}
$this->update_stat_cache($this->pwd, []);
return true;
}
/**
* Disable the stat cache
*/
public function disableStatCache(): void
{
$this->use_stat_cache = false;
}
/**
* Enable the stat cache
*/
public function enableStatCache(): void
{
$this->use_stat_cache = true;
}
/**
* Clear the stat cache
*/
public function clearStatCache(): void
{
$this->stat_cache = [];
}
/**
* Enable path canonicalization
*/
public function enablePathCanonicalization(): void
{
$this->canonicalize_paths = true;
}
/**
* Disable path canonicalization
*
* If this is enabled then $sftp->pwd() will not return the canonicalized absolute path
*/
public function disablePathCanonicalization(): void
{
$this->canonicalize_paths = false;
}
/**
* Enable arbitrary length packets
*/
public function enableArbitraryLengthPackets(): void
{
$this->allow_arbitrary_length_packets = true;
}
/**
* Disable arbitrary length packets
*/
public function disableArbitraryLengthPackets(): void
{
$this->allow_arbitrary_length_packets = false;
}
/**
* Returns the current directory name
*
* @return string|bool
*/
public function pwd()
{
if (!$this->precheck()) {
return false;
}
return $this->pwd;
}
/**
* Logs errors
*/
private function logError(string $response, int $status = -1): void
{
if ($status == -1) {
[$status] = Strings::unpackSSH2('N', $response);
}
$error = StatusCode::getConstantNameByValue($status);
if ($this->version > 2) {
[$message] = Strings::unpackSSH2('s', $response);
$this->sftp_errors[] = "$error: $message";
} else {
$this->sftp_errors[] = $error;
}
}
/**
* Canonicalize the Server-Side Path Name
*
* SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns
* the absolute (canonicalized) path.
*
* If canonicalize_paths has been disabled using disablePathCanonicalization(), $path is returned as-is.
*
* @throws UnexpectedValueException on receipt of unexpected packets
* @see self::chdir()
* @see self::disablePathCanonicalization()
*/
public function realpath(string $path)
{
if ($this->precheck() === false) {
return false;
}
if (!$this->canonicalize_paths) {
if ($this->pwd === true) {
return '.';
}
if (!strlen($path) || $path[0] != '/') {
$path = $this->pwd . '/' . $path;
}
$parts = explode('/', $path);
$afterPWD = $beforePWD = [];
foreach ($parts as $part) {
switch ($part) {
//case '': // some SFTP servers /require/ double /'s. see https://github.com/phpseclib/phpseclib/pull/1137
case '.':
break;
case '..':
if (!empty($afterPWD)) {
array_pop($afterPWD);
} else {
$beforePWD[] = '..';
}
break;
default:
$afterPWD[] = $part;
}
}
$beforePWD = count($beforePWD) ? implode('/', $beforePWD) : '.';
return $beforePWD . '/' . implode('/', $afterPWD);
}
if ($this->pwd === true) {
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.9
$this->send_sftp_packet(SFTPPacketType::REALPATH, Strings::packSSH2('s', $path));
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case SFTPPacketType::NAME:
// although SSH_FXP_NAME is implemented differently in SFTPv3 than it is in SFTPv4+, the following
// should work on all SFTP versions since the only part of the SSH_FXP_NAME packet the following looks
// at is the first part and that part is defined the same in SFTP versions 3 through 6.
[, $filename] = Strings::unpackSSH2('Ns', $response);
return $filename;
case SFTPPacketType::STATUS:
$this->logError($response);
return false;
default:
throw new UnexpectedValueException('Expected PacketType::NAME or PacketType::STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
if (!strlen($path) || $path[0] != '/') {
$path = $this->pwd . '/' . $path;
}
$path = explode('/', $path);
$new = [];
foreach ($path as $dir) {
if (!strlen($dir)) {
continue;
}
switch ($dir) {
case '..':
array_pop($new);
// fall-through
case '.':
break;
default:
$new[] = $dir;
}
}
return '/' . implode('/', $new);
}
/**
* Changes the current directory
*
* @throws UnexpectedValueException on receipt of unexpected packets
*/
public function chdir(string $dir): bool
{
if (!$this->precheck()) {
return false;
}
// assume current dir if $dir is empty
if ($dir === '') {
$dir = './';
// suffix a slash if needed
} elseif ($dir[-1] != '/') {
$dir .= '/';
}
$dir = $this->realpath($dir);
// confirm that $dir is, in fact, a valid directory
if ($this->use_stat_cache && is_array($this->query_stat_cache($dir))) {
$this->pwd = $dir;
return true;
}
// we could do a stat on the alleged $dir to see if it's a directory but that doesn't tell us
// the currently logged in user has the appropriate permissions or not. maybe you could see if
// the file's uid / gid match the currently logged in user's uid / gid but how there's no easy
// way to get those with SFTP
$this->send_sftp_packet(SFTPPacketType::OPENDIR, Strings::packSSH2('s', $dir));
// see \phpseclib3\Net\SFTP::nlist() for a more thorough explanation of the following
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case SFTPPacketType::HANDLE:
$handle = substr($response, 4);
break;
case SFTPPacketType::STATUS:
$this->logError($response);
return false;
default:
throw new UnexpectedValueException('Expected PacketType::HANDLE or PacketType::STATUS' .
'Got packet type: ' . $this->packet_type);
}
if (!$this->close_handle($handle)) {
return false;
}
$this->update_stat_cache($dir, []);
$this->pwd = $dir;
return true;
}
/**
* Returns a list of files in the given directory
*
* @return array|false
*/
public function nlist(string $dir = '.', bool $recursive = false)
{
return $this->nlist_helper($dir, $recursive, '');
}
/**
* Helper method for nlist
*
* @return array|false
*/
private function nlist_helper(string $dir, bool $recursive, string $relativeDir)
{
$files = $this->readlist($dir, false);
// If we get an int back, then that is an "unexpected" status.
// We do not have a file list, so return false.
if (is_int($files)) {
return false;
}
if (!$recursive || $files === false) {
return $files;
}
$result = [];
foreach ($files as $value) {
if ($value == '.' || $value == '..') {
$result[] = $relativeDir . $value;
continue;
}
if (is_array($this->query_stat_cache($this->realpath($dir . '/' . $value)))) {
$temp = $this->nlist_helper($dir . '/' . $value, true, $relativeDir . $value . '/');
$temp = is_array($temp) ? $temp : [];
$result = array_merge($result, $temp);
} else {
$result[] = $relativeDir . $value;
}
}
return $result;
}
/**
* Returns a detailed list of files in the given directory
*
* @return array|false
*/
public function rawlist(string $dir = '.', bool $recursive = false)
{
$files = $this->readlist($dir, true);
// If we get an int back, then that is an "unexpected" status.
// We do not have a file list, so return false.
if (is_int($files)) {
return false;
}
if (!$recursive || $files === false) {
return $files;
}
static $depth = 0;
foreach ($files as $key => $value) {
if ($depth != 0 && $key == '..') {
unset($files[$key]);
continue;
}
$is_directory = false;
if ($key != '.' && $key != '..') {
if ($this->use_stat_cache) {
$is_directory = is_array($this->query_stat_cache($this->realpath($dir . '/' . $key)));
} else {
$stat = $this->lstat($dir . '/' . $key);
$is_directory = $stat && $stat['type'] === FileType::DIRECTORY;
}
}
if ($is_directory) {
$depth++;
$files[$key] = $this->rawlist($dir . '/' . $key, true);
$depth--;
} else {
$files[$key] = (object) $value;
}
}
return $files;
}
/**
* Reads a list, be it detailed or not, of files in the given directory
*
* @return array|int|false array of files, integer status (if known) or false if something else is wrong
* @throws UnexpectedValueException on receipt of unexpected packets
*/
private function readlist(string $dir, bool $raw = true): array|int|false
{
if (!$this->precheck()) {
return false;
}
$dir = $this->realpath($dir . '/');
if ($dir === false) {
return false;
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.2
$this->send_sftp_packet(SFTPPacketType::OPENDIR, Strings::packSSH2('s', $dir));
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case SFTPPacketType::HANDLE:
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.2
// since 'handle' is the last field in the SSH_FXP_HANDLE packet, we'll just remove the first four bytes that
// represent the length of the string and leave it at that
$handle = substr($response, 4);
break;
case SFTPPacketType::STATUS:
// presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
[$status] = Strings::unpackSSH2('N', $response);
$this->logError($response, $status);
return $status;
default:
throw new UnexpectedValueException('Expected PacketType::HANDLE or PacketType::STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
$this->update_stat_cache($dir, []);
$contents = [];
while (true) {
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.2
// why multiple SSH_FXP_READDIR packets would be sent when the response to a single one can span arbitrarily many
// SSH_MSG_CHANNEL_DATA messages is not known to me.
$this->send_sftp_packet(SFTPPacketType::READDIR, Strings::packSSH2('s', $handle));
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case SFTPPacketType::NAME:
[$count] = Strings::unpackSSH2('N', $response);
for ($i = 0; $i < $count; $i++) {
[$shortname] = Strings::unpackSSH2('s', $response);
// SFTPv4 "removed the long filename from the names structure-- it can now be
// built from information available in the attrs structure."
if ($this->version < 4) {
[$longname] = Strings::unpackSSH2('s', $response);
}
$attributes = $this->parseAttributes($response);
if (!isset($attributes['type']) && $this->version < 4) {
$fileType = $this->parseLongname($longname);
if ($fileType) {
$attributes['type'] = $fileType;
}
}
$contents[$shortname] = $attributes + ['filename' => $shortname];
if (isset($attributes['type']) && $attributes['type'] == FileType::DIRECTORY && ($shortname != '.' && $shortname != '..')) {
$this->update_stat_cache($dir . '/' . $shortname, []);
} else {
if ($shortname == '..') {
$temp = $this->realpath($dir . '/..') . '/.';
} else {
$temp = $dir . '/' . $shortname;
}
$this->update_stat_cache($temp, (object) ['lstat' => $attributes]);
}
// SFTPv6 has an optional boolean end-of-list field, but we'll ignore that, since the
// final SSH_FXP_STATUS packet should tell us that, already.
}
break;
case SFTPPacketType::STATUS:
[$status] = Strings::unpackSSH2('N', $response);
if ($status != StatusCode::EOF) {
$this->logError($response, $status);
return $status;
}
break 2;
default:
throw new UnexpectedValueException('Expected PacketType::NAME or PacketType::STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
if (!$this->close_handle($handle)) {
return false;
}
if (count($this->sortOptions)) {
uasort($contents, [&$this, 'comparator']);
}
return $raw ? $contents : array_map('strval', array_keys($contents));
}
/**
* Compares two rawlist entries using parameters set by setListOrder()
*
* Intended for use with uasort()
*/
private function comparator(array $a, array $b): ?int
{
switch (true) {
case $a['filename'] === '.' || $b['filename'] === '.':
if ($a['filename'] === $b['filename']) {
return 0;
}
return $a['filename'] === '.' ? -1 : 1;
case $a['filename'] === '..' || $b['filename'] === '..':
if ($a['filename'] === $b['filename']) {
return 0;
}
return $a['filename'] === '..' ? -1 : 1;
case isset($a['type']) && $a['type'] === FileType::DIRECTORY:
if (!isset($b['type'])) {
return 1;
}
if ($b['type'] !== $a['type']) {
return -1;
}
break;
case isset($b['type']) && $b['type'] === FileType::DIRECTORY:
return 1;
}
foreach ($this->sortOptions as $sort => $order) {
if (!isset($a[$sort]) || !isset($b[$sort])) {
if (isset($a[$sort])) {
return -1;
}
if (isset($b[$sort])) {
return 1;
}
return 0;
}
switch ($sort) {
case 'filename':
$result = strcasecmp($a['filename'], $b['filename']);
if ($result) {
return $order === SORT_DESC ? -$result : $result;
}
break;