-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfsplugin_impl.hpp
More file actions
1225 lines (1124 loc) · 52.4 KB
/
Copy pathfsplugin_impl.hpp
File metadata and controls
1225 lines (1124 loc) · 52.4 KB
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
// PluginCore: the WFX logic layer. Every decision the plugin makes --
// device naming, caching, the download write scheme (direct, or
// temp-then-rename when overwriting), mtime preservation in both
// directions, and the shell commands used for the
// mutating operations the sync protocol doesn't cover -- lives here, so
// that fsplugin.cpp can be a mechanical extern "C" shim over it.
// Works entirely in UTF-8 std::string; UTF-16 conversion is the shim's
// job, not this one's.
#ifndef ADB_WFX_FSPLUGIN_IMPL_HPP
#define ADB_WFX_FSPLUGIN_IMPL_HPP
#include "adbclient.hpp"
#include "adbproto.hpp"
#include "adbutils.hpp"
#include "sdk.h"
#include "utils.hpp"
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <fcntl.h>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
// One directory entry, UTF-8. Deliberately decoupled from DirEntry (the
// ADB wire type): FindResult is what the SDK-facing shim renders into a
// WIN32_FIND_DATAW, and shouldn't need to know anything about the sync
// protocol.
struct FindResult {
std::string name;
uint64_t size = 0;
int64_t mtime = 0;
uint32_t unixMode = 0;
bool isDir = false;
};
// ---------------------------------------------------------------------
// fsplugin.cpp helpers.
//
// These serve the extern "C" shim, not PluginCore -- but this project's
// header-only-module rule (only fsplugin.cpp and tests/*.cpp are
// translation units) means they have to live in a header to be testable
// directly, without dlopen'ing the built plugin. They live here, next to
// FindResult, rather than in a header of their own, because YAGNI: one
// small set of free functions doesn't earn a third header.
//
// The ones that would otherwise read fsplugin.cpp's globals (the DC
// callback pointers, the plugin number) take them as explicit parameters
// instead, purely so they can be driven from a test with a fake callback
// -- fsplugin.cpp itself just passes its globals at each call site.
// ---------------------------------------------------------------------
constexpr int TRANSFER_PERCENT_MIN = 0;
constexpr int TRANSFER_PERCENT_MAX = 100;
// done*100/total, clamped to 0..100. Computed entirely in uint64_t --
// done*100 alone can reach roughly 2^64/100, far past any real transfer
// size -- so a multi-gigabyte done/total pair cannot overflow before the
// division the way it would in a 32-bit intermediate. total == 0 (nothing
// to transfer, or the total is genuinely unknown) yields 0 rather than
// dividing by zero.
inline int computeTransferPercent(uint64_t done, uint64_t total) {
if (total == 0) {
return TRANSFER_PERCENT_MIN;
}
uint64_t percent = (done * static_cast<uint64_t>(TRANSFER_PERCENT_MAX)) / total;
if (percent > static_cast<uint64_t>(TRANSFER_PERCENT_MAX)) {
return TRANSFER_PERCENT_MAX;
}
return static_cast<int>(percent);
}
// Fills findData from entry, the shape WIN32_FIND_DATAW takes at the SDK
// boundary. Every entry gets FILE_ATTRIBUTE_UNIX_MODE with the POSIX mode
// packed into dwReserved0 (so Double Commander can show real
// permissions); directories additionally get FILE_ATTRIBUTE_DIRECTORY.
// Creation and last-access time are both set to the same value as the
// last-write time -- the sync protocol carries only one timestamp per
// entry, so there is nothing else to put there.
//
// Returns false, leaving *findData zeroed, when entry.name does not fit
// MAX_PATH UTF-16 units: the caller must skip the entry rather than use a
// truncated name that could refer to something else entirely.
inline bool fillFindData(const FindResult& entry, WIN32_FIND_DATAW* findData) {
*findData = WIN32_FIND_DATAW{};
if (!utf8ToWideBuf(entry.name, findData->cFileName, MAX_PATH)) {
*findData = WIN32_FIND_DATAW{};
return false;
}
findData->dwFileAttributes = static_cast<DWORD>(FILE_ATTRIBUTE_UNIX_MODE);
if (entry.isDir) {
findData->dwFileAttributes |= static_cast<DWORD>(FILE_ATTRIBUTE_DIRECTORY);
}
findData->dwReserved0 = static_cast<DWORD>(entry.unixMode);
findData->nFileSizeLow = static_cast<DWORD>(entry.size & 0xFFFFFFFFULL);
findData->nFileSizeHigh = static_cast<DWORD>(entry.size >> 32);
FILETIME writeTime = timeToFileTime(static_cast<time_t>(entry.mtime));
findData->ftLastWriteTime = writeTime;
findData->ftCreationTime = writeTime;
findData->ftLastAccessTime = writeTime;
return true;
}
// One FsFindFirstW/FsFindNextW/FsFindClose cycle's state: the full
// listing (PluginCore::listDirectory has no notion of paging) plus how
// far FsFindNextW has consumed it. fsplugin.cpp hands a FindHandle* to
// Double Commander as an opaque HANDLE.
struct FindHandle {
std::vector<FindResult> entries;
size_t index = 0;
};
// Fills findData from the next entry in handle's listing that actually
// fits a WIN32_FIND_DATAW (fillFindData above skips one whose name
// doesn't fit MAX_PATH rather than truncate it), advancing handle->index
// past every entry it looks at -- including skipped ones, so a name that
// doesn't fit can never be looked at twice. Returns false once the
// listing is exhausted. Shared by FsFindFirstW and FsFindNextW so this
// skip-and-advance logic exists in exactly one place.
inline bool advanceFindData(FindHandle* handle, WIN32_FIND_DATAW* findData) {
while (handle->index < handle->entries.size()) {
const FindResult& entry = handle->entries[handle->index];
++handle->index;
if (fillFindData(entry, findData)) {
return true;
}
}
return false;
}
// Raises warning (if non-empty) as an RT_MsgOK dialog via requestProc --
// used for listDirectory's *warning output (e.g. "device unauthorized",
// see PluginCore::listDirectory above), which must reach the user even
// when the rest of the listing came back fine. A null requestProc (DC
// didn't supply one) or an empty warning are both silent no-ops.
inline void reportWarning(tRequestProcW requestProc, int pluginNr, const std::string& warning) {
if (warning.empty() || requestProc == nullptr) {
return;
}
std::vector<WCHAR> title = utf8ToWide("ADB");
std::vector<WCHAR> text = utf8ToWide(warning);
WCHAR noReturnBuffer[1] = {0};
requestProc(pluginNr, RT_MsgOK, title.data(), text.data(), noReturnBuffer, 0);
}
// Raises message (if non-empty) via logProc as MSGTYPE_IMPORTANTERROR --
// the shim's only channel for the free-text failure reasons PluginCore
// produces (a cross-device move, a device's shell stderr, a transport
// error, ...). Without this, every one of those reasons went nowhere and
// the user saw only Double Commander's generic "cannot copy/delete/
// rename". A null logProc or an empty
// message are both silent no-ops.
inline void reportError(tLogProcW logProc, int pluginNr, const std::string& message) {
if (message.empty() || logProc == nullptr) {
return;
}
std::vector<WCHAR> wideMessage = utf8ToWide(message);
logProc(pluginNr, MSGTYPE_IMPORTANTERROR, wideMessage.data());
}
// Bridges DC's tProgressProcW to the ProgressFn AdbClient/PluginCore
// expect: sourceName/targetName are DC's own WCHAR* arguments to
// FsGetFileW/FsPutFileW, valid for the lifetime of that call, so they are
// captured by pointer rather than re-converted. A non-zero return from
// progressProc means "abort", which is why the result is inverted before
// returning it as ProgressFn's "keep going" boolean. A null progressProc
// (DC didn't supply one) always means "keep going".
inline ProgressFn makeProgressFn(tProgressProcW progressProc, int pluginNr, WCHAR* sourceName,
WCHAR* targetName) {
return [progressProc, pluginNr, sourceName, targetName](uint64_t done, uint64_t total) -> bool {
if (progressProc == nullptr) {
return true;
}
int percent = computeTransferPercent(done, total);
int abortRequested = progressProc(pluginNr, sourceName, targetName, percent);
return abortRequested == 0;
};
}
// The FS_STATUS_OP_* values (sdk.h) that mutate the remote filesystem --
// the operations after which a directory's cached listing (PluginCore's
// ListingCache) can no longer be trusted. Read-only operations (LIST,
// SEARCH, CALCSIZE, ...) are deliberately excluded: clearing the cache at
// the start of every one of those would defeat the cache entirely, since
// DC brackets a plain directory listing in FsStatusInfo(START, LIST) /
// FsStatusInfo(END, LIST) too. tests/test_fsplugin_helpers.cpp enumerates
// every FS_STATUS_OP_* constant against this function, so a future
// mutating operation added to the SDK's vocabulary without a case here
// fails loudly instead of silently serving a stale listing.
inline bool isWriteOperation(int operation) {
switch (operation) {
case FS_STATUS_OP_PUT_SINGLE:
case FS_STATUS_OP_PUT_MULTI:
case FS_STATUS_OP_PUT_MULTI_THREAD:
case FS_STATUS_OP_RENMOV_SINGLE:
case FS_STATUS_OP_RENMOV_MULTI:
case FS_STATUS_OP_DELETE:
case FS_STATUS_OP_ATTRIB:
case FS_STATUS_OP_MKDIR:
case FS_STATUS_OP_SYNC_PUT:
case FS_STATUS_OP_SYNC_DELETE:
return true;
default:
return false;
}
}
// FsSetTimeW's shim-level guard: a zero-filled FILETIME (both fields 0)
// means "not provided" in this SDK -- utils.hpp's fileTimeToTime treats
// it the same way for the reverse direction ("a zero FILETIME means
// unknown") -- not epoch 0. Without this check, fileTimeToTime(*ft)
// returns time_t 0 indistinguishably from a genuine Unix-epoch mtime, and
// FsSetTimeW would stamp the file 1970-01-01 whenever LastWriteTime comes
// in null or zeroed: silently wrong dates from the very export that
// exists to protect them. A null pointer
// counts as unset too, so callers don't need a separate null check.
inline bool isUnsetFileTime(const FILETIME* ft) {
return ft == nullptr || (ft->dwLowDateTime == 0 && ft->dwHighDateTime == 0);
}
namespace plugincore_detail {
// Separates a device's model from its serial in the display name shown at
// the WFX root: "<model> (<serial>)". serialFromDisplayName below must be
// the exact inverse of pasting this in.
constexpr const char* DISPLAY_NAME_SERIAL_OPEN = " (";
constexpr char DISPLAY_NAME_SERIAL_CLOSE = ')';
// "YYYYMMDDhhmm.ss\0" -- the buffer for touch -t's fallback argument.
constexpr size_t TOUCH_T_TIMESTAMP_BUFFER_SIZE = 16;
// A downloaded file gets read/write owner-only permissions, whether it
// was written straight to its final name or through a temp file that
// rename() then carried into place (rename preserves the mode, so both
// paths land on the same result). This plugin doesn't attempt to mirror
// POSIX file modes onto the local macOS filesystem for downloads.
constexpr mode_t DOWNLOAD_FILE_MODE = S_IRUSR | S_IWUSR;
// The largest single path component (a bare file name, no directories)
// the local filesystem accepts, in bytes -- NAME_MAX on APFS and HFS+.
// Only tempDownloadPath needs it: it is the one place this plugin
// invents a local name rather than using the one Double Commander
// handed it.
constexpr size_t MAX_FILE_NAME_BYTES = 255;
// What tempDownloadPath appends before the pid. Named so the length
// arithmetic that keeps the temp name inside MAX_FILE_NAME_BYTES cannot
// drift away from the string it is measuring.
constexpr const char* TEMP_DOWNLOAD_SUFFIX = ".adbwfx.tmp.";
// The largest length not exceeding maxBytes at which s can be cut
// without splitting a UTF-8 character in half. Backs up over
// continuation bytes (10xxxxxx) to the start of the character they
// belong to. Local file names on APFS are UTF-8, and half a character is
// not a name worth asking it to store -- nor one a user could recognise
// if a crash ever left it on disk.
inline size_t utf8TruncatedLength(const std::string& s, size_t maxBytes) {
if (s.size() <= maxBytes) {
return s.size();
}
size_t n = maxBytes;
while (n > 0 && (static_cast<unsigned char>(s[n]) & 0xC0) == 0x80) {
--n;
}
return n;
}
// Trims a run of trailing '\n'/'\r' bytes. Android's shell: gives no exit
// status on this transport, so "was there any output at all" is how
// rm/mv/mkdir/touch's success is detected -- and their success output is a
// trailing newline, not truly empty, so this has to run before the
// emptiness check.
inline std::string trimTrailingNewlines(const std::string& s) {
size_t end = s.size();
while (end > 0 && (s[end - 1] == '\n' || s[end - 1] == '\r')) {
--end;
}
return s.substr(0, end);
}
// The WFX directory that contains wfxPath, e.g.
// "/SERIAL/sdcard/DCIM/a.jpg" -> "/SERIAL/sdcard/DCIM". Falls back to "/"
// for a path with no further separator (a bare device root's child).
inline std::string parentWfxDir(const std::string& wfxPath) {
size_t pos = wfxPath.find_last_of('/');
if (pos == std::string::npos || pos == 0) {
return "/";
}
return wfxPath.substr(0, pos);
}
inline bool localFileExists(const std::string& path) {
struct stat st;
return ::stat(path.c_str(), &st) == 0;
}
// Where getFile downloads to when it is about to overwrite an existing
// local file: the bytes land here and rename() carries them into place,
// so a transfer that fails or is cancelled halfway leaves the previous
// copy untouched instead of a truncated one. It has to sit in the same
// directory as the target for that rename to be atomic (a different
// directory could be a different volume, where rename fails outright),
// which means a file manager watching that directory can see it -- hence
// the leading dot, which keeps it out of any panel not showing hidden
// files. The pid suffix is cheap insurance against two plugin instances
// racing on the same target.
//
// Downloads to a name that does not exist yet skip this entirely and are
// written straight to the final name; see getFile.
inline std::string tempDownloadPath(const std::string& localPath) {
size_t slash = localPath.find_last_of('/');
std::string dir = (slash == std::string::npos) ? std::string() : localPath.substr(0, slash + 1);
std::string base = (slash == std::string::npos) ? localPath : localPath.substr(slash + 1);
// The dot and the suffix make the temp component longer than the
// target's own name, so a target whose name already sits near the
// filesystem's per-component limit would produce a temp name open()
// rejects with ENAMETOOLONG -- failing an overwrite that has nothing
// wrong with it. Shorten the middle to fit; the pid suffix, not the
// (possibly truncated) name, is what keeps the temp name distinct,
// and the file exists only until the rename.
std::string suffix = std::string(TEMP_DOWNLOAD_SUFFIX) + std::to_string(::getpid());
size_t budget = (MAX_FILE_NAME_BYTES > suffix.size() + 1)
? MAX_FILE_NAME_BYTES - suffix.size() - 1 // -1 for the leading dot
: 0;
if (base.size() > budget) {
base.resize(utf8TruncatedLength(base, budget));
}
return dir + "." + base + suffix;
}
// Formats mtime (seconds since the Unix epoch) as touch -t's
// [[CC]YY]MMDDhhmm[.ss] argument, in UTC via gmtime_r -- deliberately NOT
// localtime_r. This is only reached as setModificationTime's fallback for
// when Android's toybox touch rejects "-d @<epoch>"; converting through
// the *local* timezone here would silently shift every uploaded or
// renamed date by the machine's UTC offset, which is exactly the class of
// correctness bug this whole project exists to eliminate. The other half
// of that agreement lives at the call site: touch -t reads its argument
// in the *device's* local time, so setModificationTime prefixes the
// command with TZ=UTC. Change one and you must change the other.
//
// Returns false (leaving *out untouched) when epochSeconds is out of
// gmtime_r's representable range, rather than silently building a shell
// command around whatever garbage a zero-initialized struct tm would
// format as (e.g. "190001000000.00").
inline bool formatTouchTArg(int64_t epochSeconds, std::string* out) {
time_t t = static_cast<time_t>(epochSeconds);
struct tm utc {};
if (::gmtime_r(&t, &utc) == nullptr) {
return false;
}
// Every field is range-checked before it reaches snprintf, and a value
// outside its range fails the whole call rather than being formatted.
//
// The year is the one that matters in practice: touch -t's argument has
// exactly four digits for it, so a year of 10000 or more cannot be
// expressed at all -- "%04d" would widen the field and hand the device a
// timestamp whose digits mean something else entirely. glibc's gmtime_r
// succeeds for such years (only the tm_year overflow itself makes it
// return nullptr above), so the guard has to live here.
//
// The rest are checked for the same reason the year is: this builds a
// shell command, and every one of these is only ever as trustworthy as
// the libc that filled the struct in. It also happens to be what lets
// gcc see that each conversion writes exactly the width it declares --
// without it, -Wformat-truncation cannot rule out an 11-digit int and
// the build fails under -Werror.
const int year = utc.tm_year + 1900;
const int month = utc.tm_mon + 1;
if (year < 1 || year > 9999 || month < 1 || month > 12 ||
utc.tm_mday < 1 || utc.tm_mday > 31 ||
utc.tm_hour < 0 || utc.tm_hour > 23 ||
utc.tm_min < 0 || utc.tm_min > 59 ||
// A leap second legitimately reports 60 here.
utc.tm_sec < 0 || utc.tm_sec > 60) {
return false;
}
char buf[TOUCH_T_TIMESTAMP_BUFFER_SIZE];
std::snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d.%02d", year, month, utc.tm_mday,
utc.tm_hour, utc.tm_min, utc.tm_sec);
*out = buf;
return true;
}
} // namespace plugincore_detail
// Which touch form setModificationTime may use. Android's toybox touch
// has historically rejected "-d @<epoch>", so the default tries that
// first and falls back to "-t" only when it complains. TouchTOnly goes
// straight to the fallback: on a device whose touch DOES accept -d that
// is the only way to exercise the -t path at all, and the -t path is
// where the whole TZ=UTC question lives -- an untested fallback that is
// three hours wrong on a non-UTC phone is exactly what this project
// cannot ship. tests/device_driver.cpp's "settime-t" selects it.
enum class TouchStrategy { EpochThenFallback, TouchTOnly };
class PluginCore {
public:
explicit PluginCore(AdbClient& client) : client_(client) {}
// Same, with the listing cache's clock and TTL injected -- for tests
// that need to prove expiry without sleeping through it.
PluginCore(AdbClient& client, ClockFn clock, int64_t cacheTtlSeconds)
: client_(client), cache_(std::move(clock), cacheTtlSeconds) {}
// Returns entries for a WFX directory path. Root ("/") returns one
// entry per usable device; every other path lists the device's
// on-device directory via the sync protocol, through the cache.
bool listDirectory(const std::string& wfxDir, std::vector<FindResult>* out,
std::string* warning, std::string* error) {
out->clear();
if (warning != nullptr) {
warning->clear();
}
if (error != nullptr) {
error->clear();
}
RemotePath rp = parseWfxPath(wfxDir);
if (rp.isRoot) {
return listRootDevices(out, warning, error);
}
std::vector<DirEntry> cached;
if (cache_.get(wfxDir, &cached)) {
appendEntries(cached, out);
return true;
}
// adbd's do_list answers a failed opendir() with a plain DONE and
// zero DENTs -- it never sends FAIL. A path that does not exist,
// a path that is actually a file, and a directory that is
// genuinely empty are therefore indistinguishable at the LIST
// level: all three come back as a successful empty listing, get
// cached as empty, and leave Double Commander showing a blank
// panel with no explanation for what is usually a typo. STAT
// first and name the problem.
//
// The one case this still cannot separate from "empty" is a
// directory that exists but cannot be opened (/data, /data/data
// on an unrooted phone): the sync protocol offers nothing to
// distinguish it by short of guessing at mode bits and a uid the
// client does not know.
if (!checkIsDirectory(rp.serial, rp.path, error)) {
return false;
}
std::vector<DirEntry> entries;
AdbError err = client_.syncList(rp.serial, rp.path, &entries);
if (!err.ok) {
if (error != nullptr) {
*error = err.message;
}
return false;
}
resolveSymlinkTargets(rp.serial, rp.path, &entries);
cache_.put(wfxDir, entries);
appendEntries(entries, out);
return true;
}
// "<model> (<serial>)" when a model is known, else the bare serial.
static std::string displayNameForDevice(const DeviceInfo& d) {
if (!d.model.empty()) {
return d.model + plugincore_detail::DISPLAY_NAME_SERIAL_OPEN + d.serial +
plugincore_detail::DISPLAY_NAME_SERIAL_CLOSE;
}
return d.serial;
}
// The exact inverse of displayNameForDevice: pulls the serial back out
// of "<model> (<serial>)", or returns the whole string when it never
// had a "(<serial>)" suffix (the no-model case).
static std::string serialFromDisplayName(const std::string& displayName) {
if (displayName.empty() || displayName.back() != plugincore_detail::DISPLAY_NAME_SERIAL_CLOSE) {
return displayName;
}
size_t openPos = displayName.rfind(plugincore_detail::DISPLAY_NAME_SERIAL_OPEN);
if (openPos == std::string::npos) {
return displayName;
}
size_t start = openPos + std::strlen(plugincore_detail::DISPLAY_NAME_SERIAL_OPEN);
size_t end = displayName.size() - 1; // exclude the trailing ')'
if (end <= start) {
return displayName;
}
return displayName.substr(start, end - start);
}
int getFile(const std::string& wfxRemote, const std::string& localPath, int copyFlags,
const ProgressFn& progress, std::string* error) {
if (error != nullptr) {
error->clear();
}
if (copyFlags & FS_COPYFLAGS_RESUME) {
return FS_FILE_NOTSUPPORTED;
}
RemotePath rp = parseWfxPath(wfxRemote);
DirEntry remoteInfo;
bool exists = false;
AdbError statErr = client_.syncStat(rp.serial, rp.path, &remoteInfo, &exists);
if (!statErr.ok) {
if (error != nullptr) {
*error = statErr.message;
}
return FS_FILE_READERROR;
}
if (!exists) {
return FS_FILE_NOTFOUND;
}
// The STAT above is adbd's lstat, so for a symlink it describes
// the LINK -- a 21-byte size and the link's own mtime -- while
// syncRecv below downloads the TARGET. Left uncorrected that
// makes the progress percentage meaningless and stamps the
// downloaded file with the link's date, which is exactly the
// class of silently-wrong mtime this project exists to
// eliminate. Re-stat through the link and use the target's
// numbers. Best-effort: a dangling link keeps the lstat values
// and syncRecv reports the real error.
if (remoteInfo.isSymlink()) {
DirEntry target;
bool targetExists = false;
AdbError targetErr =
client_.syncStat(rp.serial, throughSymlink(rp.path), &target, &targetExists);
if (targetErr.ok && targetExists) {
remoteInfo = target;
}
}
bool targetExists = plugincore_detail::localFileExists(localPath);
if (!(copyFlags & FS_COPYFLAGS_OVERWRITE) && targetExists) {
return FS_FILE_EXISTS;
}
// Two ways to write the download, picked by what is at stake.
//
// Nothing at the target name: write straight to it. There is no
// previous copy for a failed transfer to destroy, and every
// failure path below unlinks what it wrote, so the only file that
// can survive under the real name is a complete one. This keeps a
// file manager's panel from flashing a temp name that exists for
// the length of the copy and then disappears, which is what the
// user actually sees on every download.
//
// A file already at the target name (overwrite): go through the
// temp file and rename() it into place, so a transfer that fails
// or is cancelled halfway leaves the existing copy intact. That
// guarantee is worth more than a hidden entry in the panel, and
// tempDownloadPath's leading dot keeps even that out of sight.
const bool viaTempFile = targetExists;
const std::string writePath =
viaTempFile ? plugincore_detail::tempDownloadPath(localPath) : localPath;
int fd = ::open(writePath.c_str(), O_WRONLY | O_CREAT | O_TRUNC,
plugincore_detail::DOWNLOAD_FILE_MODE);
if (fd < 0) {
if (error != nullptr) {
*error = std::string("failed to create local file: ") + std::strerror(errno);
}
return FS_FILE_WRITEERROR;
}
AdbError recvErr = client_.syncRecv(rp.serial, rp.path, fd, remoteInfo.size, progress);
::close(fd);
if (!recvErr.ok) {
// Removes the temp file, or -- on the direct path -- the
// partial file sitting under the real name, which must never
// be left behind masquerading as a complete download.
::unlink(writePath.c_str());
if (recvErr.message == ADB_CANCELLED) {
return FS_FILE_USERABORT;
}
if (error != nullptr) {
*error = recvErr.message;
}
return FS_FILE_READERROR;
}
if (viaTempFile && ::rename(writePath.c_str(), localPath.c_str()) != 0) {
std::string renameError = std::strerror(errno);
::unlink(writePath.c_str());
if (error != nullptr) {
*error = "failed to move downloaded file into place: " + renameError;
}
return FS_FILE_WRITEERROR;
}
// The headline requirement of the entire project: the local
// file's mtime comes from the remote, not from the moment the
// download finished. Set on the final path, after any rename, so
// rename() (which does not touch mtime on this filesystem) can
// never race it away.
struct timespec times[2];
times[0].tv_sec = 0;
times[0].tv_nsec = UTIME_OMIT; // leave atime alone
times[1].tv_sec = static_cast<time_t>(remoteInfo.mtime);
times[1].tv_nsec = 0;
if (::utimensat(AT_FDCWD, localPath.c_str(), times, 0) != 0) {
// A file left behind with a silently-wrong mtime is exactly
// the class of defect this project exists to eliminate, and
// worse than a failed getFile leaving nothing behind: remove
// it so a failed copy cannot masquerade as a complete one.
std::string utimeError = std::strerror(errno);
::unlink(localPath.c_str());
if (error != nullptr) {
*error = "downloaded but failed to set local modification time, file removed: " +
utimeError;
}
return FS_FILE_WRITEERROR;
}
if (copyFlags & FS_COPYFLAGS_MOVE) {
std::string deleteError;
if (!deleteFile(wfxRemote, &deleteError)) {
// The one path in this class where FS_FILE_OK and a
// non-empty *error coexist, and fsplugin.cpp's
// FsGetFileW reports *error for exactly that reason.
//
// The code stays OK because the download really did
// succeed: the local file is complete and correctly
// stamped, and an error code here would have Double
// Commander treat a good transfer as a failed one. But
// the user asked for a move and got a copy -- the source
// is still on the device -- so this cannot pass in
// silence. The fallback text matters: reportError is a
// no-op on an empty message, and a device that failed
// without saying why would otherwise silently lose the
// only notice the user gets.
if (error != nullptr) {
*error = "downloaded, but failed to delete the source from the device "
"(copied, not moved): " +
(deleteError.empty() ? std::string("unknown error") : deleteError);
}
}
}
return FS_FILE_OK;
}
int putFile(const std::string& localPath, const std::string& wfxRemote, int copyFlags,
const ProgressFn& progress, std::string* error) {
if (error != nullptr) {
error->clear();
}
if (copyFlags & FS_COPYFLAGS_RESUME) {
return FS_FILE_NOTSUPPORTED;
}
RemotePath rp = parseWfxPath(wfxRemote);
struct stat localStat;
if (::stat(localPath.c_str(), &localStat) != 0) {
if (error != nullptr) {
*error = std::string("failed to read local file: ") + std::strerror(errno);
}
return FS_FILE_READERROR;
}
if (!(copyFlags & FS_COPYFLAGS_OVERWRITE)) {
DirEntry remoteInfo;
bool exists = false;
AdbError statErr = client_.syncStat(rp.serial, rp.path, &remoteInfo, &exists);
if (!statErr.ok) {
if (error != nullptr) {
*error = statErr.message;
}
return FS_FILE_WRITEERROR;
}
if (exists) {
return FS_FILE_EXISTS;
}
}
int fd = ::open(localPath.c_str(), O_RDONLY);
if (fd < 0) {
if (error != nullptr) {
*error = std::string("failed to open local file: ") + std::strerror(errno);
}
return FS_FILE_READERROR;
}
// The other half of the headline requirement: the local file's
// real mtime is what gets sent -- never time(nullptr).
AdbError sendErr = client_.syncSend(rp.serial, fd, static_cast<uint64_t>(localStat.st_size),
rp.path, static_cast<uint32_t>(localStat.st_mode),
static_cast<int64_t>(localStat.st_mtime), progress);
::close(fd);
if (!sendErr.ok) {
if (sendErr.message == ADB_CANCELLED) {
// A cancelled send may already have written a partial
// file remotely (syncSend only cancels between DATA
// chunks, never mid-chunk) -- drop any cached listing of
// its directory so it isn't hidden behind stale state.
invalidatePathAndParent(wfxRemote);
return FS_FILE_USERABORT;
}
if (error != nullptr) {
*error = sendErr.message;
}
return FS_FILE_WRITEERROR;
}
invalidatePathAndParent(wfxRemote);
if (copyFlags & FS_COPYFLAGS_MOVE) {
if (::unlink(localPath.c_str()) != 0) {
// The mirror image of getFile's remote-delete failure,
// and the other path where FS_FILE_OK travels with a
// non-empty *error for FsPutFileW to report. The upload
// landed, so the code stays OK -- but the user asked for
// a move and the local file is still here, so saying
// nothing would leave them with a silent duplicate.
if (error != nullptr) {
*error = std::string("uploaded, but failed to delete the local source "
"(copied, not moved): ") +
std::strerror(errno);
}
}
}
return FS_FILE_OK;
}
bool deleteFile(const std::string& wfxRemote, std::string* error) {
RemotePath rp = parseWfxPath(wfxRemote);
return runMutatingShellCommand(rp, "rm -f " + shellQuote(rp.path), wfxRemote, error);
}
bool removeDir(const std::string& wfxRemote, std::string* error) {
RemotePath rp = parseWfxPath(wfxRemote);
return runMutatingShellCommand(rp, "rm -rf " + shellQuote(rp.path), wfxRemote, error);
}
bool makeDir(const std::string& wfxRemote, std::string* error) {
RemotePath rp = parseWfxPath(wfxRemote);
return runMutatingShellCommand(rp, "mkdir -p " + shellQuote(rp.path), wfxRemote, error);
}
// Double Commander funnels BOTH of its internal operations through
// the single FsRenMovFileW entry point: F6 inside one device arrives
// with move=true, F5 inside one device with move=false (a copy that
// never leaves the phone). Everything up to the branch at the bottom
// -- the cross-device rejection, the refuse-to-overwrite check -- is
// common to the two; only the last step differs.
//
// crossDevice and targetExists, if non-null, are both cleared at the
// start and each set to true only for its own specific failure --
// "wfxFrom and wfxTo name different devices" for the former, "the
// target exists and overwrite is false" for the latter -- so
// fsplugin.cpp can map each to the SDK code Double Commander actually
// needs (FS_FILE_NOTSUPPORTED, the one case its own copy+delete
// fallback can fix; FS_FILE_EXISTS, matching the code getFile/putFile
// already return for the identical situation) without string-matching
// *error. Every other failure leaves both false: retrying via that
// fallback would not fix a genuine error (permission denied, a
// dropped transport), and for a multi-gigabyte file wastes minutes
// attributing the failure to the wrong step.
bool renameOrMove(const std::string& wfxFrom, const std::string& wfxTo, bool move,
bool overwrite, std::string* error, bool* crossDevice = nullptr,
bool* targetExists = nullptr) {
if (error != nullptr) {
error->clear();
}
if (crossDevice != nullptr) {
*crossDevice = false;
}
if (targetExists != nullptr) {
*targetExists = false;
}
RemotePath rpFrom = parseWfxPath(wfxFrom);
RemotePath rpTo = parseWfxPath(wfxTo);
if (rpFrom.serial != rpTo.serial) {
// The sync/shell protocol is scoped to one host:transport:
// device at a time; there is no remote-to-remote copy
// primitive to build a cross-device move on top of (that
// would need a download-then-upload, which is out of scope
// here). Reject explicitly rather than silently running mv
// on the wrong device and reporting success.
if (error != nullptr) {
*error = move ? "cannot move between devices" : "cannot copy between devices";
}
if (crossDevice != nullptr) {
*crossDevice = true;
}
return false;
}
if (!overwrite) {
// "mv -n" against an existing target exits 0 and prints
// nothing on this shell -- indistinguishable, via
// runMutatingShellCommand-style "empty output means success"
// logic, from a rename that actually happened. This
// transport gives no exit status to lean on, so the only
// reliable way to honor "don't
// overwrite" is to check first and never send -n at all.
// The same holds for "cp -n", and there it is worse still: a
// silently skipped copy leaves a stale file at the target
// that reads as the fresh one.
DirEntry targetInfo;
bool targetAlreadyExists = false;
AdbError statErr =
client_.syncStat(rpTo.serial, rpTo.path, &targetInfo, &targetAlreadyExists);
if (!statErr.ok) {
if (error != nullptr) {
*error = statErr.message;
}
return false;
}
if (targetAlreadyExists) {
if (error != nullptr) {
*error = "target already exists";
}
if (targetExists != nullptr) {
*targetExists = true;
}
return false;
}
}
return move ? runDeviceMove(rpFrom, rpTo, wfxFrom, wfxTo, error)
: runDeviceCopy(rpFrom, rpTo, wfxTo, error);
}
bool setModificationTime(const std::string& wfxRemote, int64_t mtime, std::string* error,
TouchStrategy strategy = TouchStrategy::EpochThenFallback) {
if (error != nullptr) {
error->clear();
}
RemotePath rp = parseWfxPath(wfxRemote);
// `touch -c` is deliberately silent about a file that isn't
// there, and this transport carries no exit status -- so
// "produced no output" would otherwise read as success for a path
// that was never touched. -c is still what gets sent (dropping it
// would make touch CREATE the missing file, which is worse); the
// existence question is answered here instead.
DirEntry info;
bool exists = false;
AdbError statErr = client_.syncStat(rp.serial, rp.path, &info, &exists);
if (!statErr.ok) {
if (error != nullptr) {
*error = statErr.message;
}
return false;
}
if (!exists) {
if (error != nullptr) {
*error = "cannot set the time of " + rp.path + ": no such file or directory";
}
return false;
}
std::string quoted = shellQuote(rp.path);
if (strategy == TouchStrategy::EpochThenFallback) {
std::string epochCommand = "touch -c -d @" + std::to_string(mtime) + " " + quoted;
std::string epochOutput;
AdbError epochErr = client_.shellCommand(rp.serial, epochCommand, &epochOutput);
if (!epochErr.ok) {
if (error != nullptr) {
*error = epochErr.message;
}
return false;
}
if (plugincore_detail::trimTrailingNewlines(epochOutput).empty()) {
invalidatePathAndParent(wfxRemote);
return true;
}
}
// Fallback: Android's toybox touch has historically rejected the
// "-d @<epoch>" form.
std::string tTimestamp;
if (!plugincore_detail::formatTouchTArg(mtime, &tTimestamp)) {
if (error != nullptr) {
*error = "modification time is out of range";
}
return false;
}
// TZ=UTC is not decoration. POSIX touch -t interprets its
// argument in the *shell's* local time, and that shell is on the
// phone -- so a phone set to UTC+3 would land every fallback
// stamp three hours off. formatTouchTArg deliberately formats in
// UTC (gmtime_r); this assignment prefix, which toybox's sh
// honours like any other, is what makes the two agree.
std::string tCommand = "TZ=UTC touch -c -t " + tTimestamp + " " + quoted;
std::string tOutput;
AdbError tErr = client_.shellCommand(rp.serial, tCommand, &tOutput);
if (!tErr.ok) {
if (error != nullptr) {
*error = tErr.message;
}
return false;
}
std::string trimmed = plugincore_detail::trimTrailingNewlines(tOutput);
if (!trimmed.empty()) {
if (error != nullptr) {
*error = trimmed;
}
return false;
}
invalidatePathAndParent(wfxRemote);
return true;
}
ListingCache& cache() {
return cache_;
}
private:
// parseRemotePath alone takes the WFX path's first component as the
// literal serial -- it has no idea about the "<model> (<serial>)"
// display names listDirectory("/") invents for the root entries. Every
// operation that turns a WFX path into a device to talk to MUST go
// through this instead of calling parseRemotePath directly, or a
// device with a known model can never be opened (host:transport:
// would be sent the display name, not the serial). A no-op for a bare
// serial, so nothing that already worked regresses.
static RemotePath parseWfxPath(const std::string& wfxPath) {
RemotePath rp = parseRemotePath(wfxPath);
rp.serial = serialFromDisplayName(rp.serial);
return rp;
}
bool listRootDevices(std::vector<FindResult>* out, std::string* warning, std::string* error) {
std::vector<DeviceInfo> devices;
AdbError err = client_.listDevices(&devices);
if (!err.ok) {
if (error != nullptr) {
*error = err.message;
}
return false;
}
std::string warnings;
for (const DeviceInfo& d : devices) {
if (!deviceStateIsUsable(d.state)) {
if (!warnings.empty()) {
warnings += "\n";
}
warnings += deviceStateMessage(d);
continue;
}
FindResult r;
r.name = displayNameForDevice(d);
r.isDir = true;
out->push_back(std::move(r));
}
if (warning != nullptr) {
*warning = warnings;
}
return true;
}
// Rejects, with a message that says which, a listing target that does
// not exist or is not a directory. A symlink is resolved through
// before being judged (see resolveSymlinkTargets): /sdcard is a
// symlink on every modern device and must of course still open.
bool checkIsDirectory(const std::string& serial, const std::string& path, std::string* error) {
DirEntry info;
bool exists = false;
AdbError err = client_.syncStat(serial, path, &info, &exists);
if (!err.ok) {
if (error != nullptr) {
*error = err.message;
}
return false;
}
if (!exists) {
if (error != nullptr) {
*error = "cannot open " + path + ": no such file or directory";
}
return false;
}
if (info.isDir()) {
return true;
}
if (info.isSymlink()) {
DirEntry target;
bool targetExists = false;