/
WebDAVFileSystem.cpp
2198 lines (2045 loc) · 75.8 KB
/
WebDAVFileSystem.cpp
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
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <io.h>
#include <fcntl.h>
#include <wincrypt.h>
#define NE_LFS
#define WINSCP
#include <ne_basic.h>
#include <ne_auth.h>
#include <ne_props.h>
#include <ne_uri.h>
#include <ne_session.h>
#include <ne_request.h>
#include <ne_xml.h>
#include <ne_redirect.h>
#include <ne_xmlreq.h>
#include <ne_locks.h>
#include <expat.h>
#include "WebDAVFileSystem.h"
#include "Interface.h"
#include "Common.h"
#include "Exceptions.h"
#include "Terminal.h"
#include "TextsCore.h"
#include "SecureShell.h"
#include "HelpCore.h"
#include "CoreMain.h"
#include "Security.h"
#include <StrUtils.hpp>
#include <NeonIntf.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
#define FILE_OPERATION_LOOP_TERMINAL FTerminal
//---------------------------------------------------------------------------
#define SESSION_CONTEXT_KEY "sessioncontext"
static const UnicodeString CONST_WEBDAV_PROTOCOL_BASE_NAME = L"WebDAV";
static const int HttpUnauthorized = 401;
//---------------------------------------------------------------------------
#define DAV_PROP_NAMESPACE "DAV:"
#define MODDAV_PROP_NAMESPACE "http://apache.org/dav/props/"
#define PROP_CONTENT_LENGTH "getcontentlength"
#define PROP_LAST_MODIFIED "getlastmodified"
#define PROP_RESOURCE_TYPE "resourcetype"
#define PROP_HIDDEN "ishidden"
#define PROP_QUOTA_AVAILABLE "quota-available-bytes"
#define PROP_QUOTA_USED "quota-used-bytes"
#define PROP_EXECUTABLE "executable"
#define PROP_OWNER "owner"
#define PROP_DISPLAY_NAME "displayname"
//------------------------------------------------------------------------------
//---------------------------------------------------------------------------
// ne_path_escape returns 7-bit string, so it does not really matter if we use
// AnsiString or UTF8String here, though UTF8String might be more safe
static AnsiString PathEscape(const char * Path)
{
char * EscapedPath = ne_path_escape(Path);
AnsiString Result = EscapedPath;
ne_free(EscapedPath);
return Result;
}
//---------------------------------------------------------------------------
static UnicodeString PathUnescape(const char * Path)
{
char * UnescapedPath = ne_path_unescape(Path);
UTF8String UtfResult;
if (UnescapedPath != NULL)
{
UtfResult = UnescapedPath;
ne_free(UnescapedPath);
}
else
{
// OneDrive, particularly in the response to *file* PROPFIND tend to return a malformed URL.
// In such case, take the path as is and we will probably overwrite the name with "display name".
UtfResult = Path;
}
UnicodeString Result = StrFromNeon(UtfResult);
return Result;
}
//---------------------------------------------------------------------------
#define AbsolutePathToNeon(P) PathEscape(StrToNeon(P)).c_str()
#define PathToNeonStatic(THIS, P) AbsolutePathToNeon((THIS)->AbsolutePath(P, false))
#define PathToNeon(P) PathToNeonStatic(this, P)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
static bool NeonInitialized = false;
static bool NeonSspiInitialized = false;
//---------------------------------------------------------------------------
void __fastcall NeonInitialize()
{
// Even if this fails, we do not want to interrupt WinSCP starting for that.
// Anyway, it can hardly fail.
// Though it fails on Wine on Debian VM, because of ne_sspi_init():
// sspi: QuerySecurityPackageInfo [failed] [80090305].
// sspi: Unable to get negotiate maximum packet size
int NeonResult = ne_sock_init();
if (NeonResult == 0)
{
NeonInitialized = true;
NeonSspiInitialized = true;
}
else if (NeonResult == -2)
{
NeonInitialized = true;
NeonSspiInitialized = false;
}
else
{
NeonInitialized = false;
NeonSspiInitialized = false;
}
}
//---------------------------------------------------------------------------
void __fastcall NeonFinalize()
{
if (NeonInitialized)
{
ne_sock_exit();
NeonInitialized = false;
}
}
//---------------------------------------------------------------------------
void __fastcall RequireNeon(TTerminal * Terminal)
{
if (!NeonInitialized)
{
throw Exception(LoadStr(NEON_INIT_FAILED2));
}
if (!NeonSspiInitialized)
{
Terminal->LogEvent(L"Warning: SSPI initialization failed.");
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall NeonVersion()
{
UnicodeString Str = StrFromNeon(ne_version_string());
CutToChar(Str, L' ', true); // "neon"
UnicodeString Result = CutToChar(Str, L':', true);
return Result;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall ExpatVersion()
{
return FORMAT(L"%d.%d.%d", (XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION));
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
TWebDAVFileSystem::TWebDAVFileSystem(TTerminal * ATerminal) :
TCustomFileSystem(ATerminal),
FActive(false),
FHasTrailingSlash(false),
FSessionContext(NULL),
FNeonLockStore(NULL),
FNeonLockStoreSection(new TCriticalSection()),
FUploading(false),
FDownloading(false),
FInitialHandshake(false),
FIgnoreAuthenticationFailure(iafNo)
{
FFileSystemInfo.ProtocolBaseName = CONST_WEBDAV_PROTOCOL_BASE_NAME;
FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
}
//---------------------------------------------------------------------------
__fastcall TWebDAVFileSystem::~TWebDAVFileSystem()
{
UnregisterFromNeonDebug(FTerminal);
{
TGuard Guard(FNeonLockStoreSection);
if (FNeonLockStore != NULL)
{
ne_lockstore_destroy(FNeonLockStore);
FNeonLockStore = NULL;
}
}
delete FNeonLockStoreSection;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::Open()
{
RequireNeon(FTerminal);
RegisterForNeonDebug(FTerminal);
FCurrentDirectory = L"";
FHasTrailingSlash = true;
FStoredPasswordTried = false;
FTlsVersionStr = L"";
FCapabilities = 0;
TSessionData * Data = FTerminal->SessionData;
FSessionInfo.LoginTime = Now();
FSessionInfo.CertificateVerifiedManually = false;
UnicodeString HostName = Data->HostNameExpanded;
FOneDrive = SameText(HostName, L"d.docs.live.net");
if (FOneDrive)
{
FTerminal->LogEvent(L"OneDrive host detected.");
}
size_t Port = Data->PortNumber;
UnicodeString ProtocolName = (FTerminal->SessionData->Ftps == ftpsNone) ? HttpProtocol : HttpsProtocol;
UnicodeString Path = Data->RemoteDirectory;
// PathToNeon is not used as we cannot call AbsolutePath here
UnicodeString EscapedPath = StrFromNeon(PathEscape(StrToNeon(Path)).c_str());
UnicodeString Url = FORMAT(L"%s://%s:%d%s", (ProtocolName, HostName, Port, EscapedPath));
FTerminal->Information(LoadStr(STATUS_CONNECT), true);
FActive = false;
try
{
OpenUrl(Url);
}
catch (Exception & E)
{
CloseNeonSession();
FTerminal->Closed();
FTerminal->FatalError(&E, LoadStr(CONNECTION_FAILED));
}
FActive = true;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TWebDAVFileSystem::ParsePathFromUrl(const UnicodeString & Url)
{
UnicodeString Result;
ne_uri ParsedUri;
if (ne_uri_parse(StrToNeon(Url), &ParsedUri) == 0)
{
Result = PathUnescape(ParsedUri.path);
ne_uri_free(&ParsedUri);
}
return Result;
}
//---------------------------------------------------------------------------
void TWebDAVFileSystem::OpenUrl(const UnicodeString & Url)
{
UnicodeString CorrectedUrl;
NeonClientOpenSessionInternal(CorrectedUrl, Url);
if (CorrectedUrl.IsEmpty())
{
CorrectedUrl = Url;
}
UnicodeString ParsedPath = ParsePathFromUrl(CorrectedUrl);
if (!ParsedPath.IsEmpty())
{
// this is most likely pointless as it get overwritten by
// call to ChangeDirectory() from TTerminal::DoStartup
FCurrentDirectory = ParsedPath;
}
}
//---------------------------------------------------------------------------
void TWebDAVFileSystem::NeonClientOpenSessionInternal(UnicodeString & CorrectedUrl, UnicodeString Url)
{
std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
AttemptedUrls->Add(Url);
while (true)
{
FSessionInfo.CSCipher = EmptyStr;
FSessionInfo.SCCipher = EmptyStr;
UTF8String Path, DiscardQuery;
DebugAssert(FSessionContext == NULL);
FSessionContext = NeonOpen(Url, Path, DiscardQuery);
bool Ssl = IsTlsSession(FSessionContext->NeonSession);
FSessionInfo.SecurityProtocolName = Ssl ? LoadStr(FTPS_IMPLICIT) : EmptyStr;
if (Ssl != (FTerminal->SessionData->Ftps != ftpsNone))
{
FTerminal->LogEvent(FORMAT(L"Warning: %s", (LoadStr(UNENCRYPTED_REDIRECT))));
}
{
CorrectedUrl = EmptyStr;
TAutoFlag Flag(FInitialHandshake);
ExchangeCapabilities(Path.c_str(), CorrectedUrl);
}
// No error and no corrected URL? We're done here.
if (CorrectedUrl.IsEmpty())
{
break;
}
CloseNeonSession();
CheckRedirectLoop(CorrectedUrl, AttemptedUrls.get());
// Our caller will want to know what our final corrected URL was.
Url = CorrectedUrl;
}
CorrectedUrl = Url;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::SetSessionTls(TSessionContext * SessionContext, ne_session_s * Session, bool Aux)
{
ne_ssl_verify_fn Callback = Aux ? NeonServerSSLCallbackAux : NeonServerSSLCallbackMain;
InitNeonTls(Session, InitSslSession, Callback, SessionContext, FTerminal);
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::InitSession(TSessionContext * SessionContext, ne_session_s * Session)
{
TSessionData * Data = FTerminal->SessionData;
InitNeonSession(
Session, Data->ProxyMethod, Data->ProxyHost, Data->ProxyPort,
Data->ProxyUsername, Data->ProxyPassword, FTerminal);
ne_set_read_timeout(Session, Data->Timeout);
ne_set_connect_timeout(Session, Data->Timeout);
ne_set_session_private(Session, SESSION_CONTEXT_KEY, SessionContext);
// Allow ^-escaping in OneDrive
ne_set_session_flag(Session, NE_SESSFLAG_LIBERAL_ESCAPING, Data->WebDavLiberalEscaping || FOneDrive);
}
//---------------------------------------------------------------------------
TWebDAVFileSystem::TSessionContext * TWebDAVFileSystem::NeonOpen(const UnicodeString & Url, UTF8String & Path, UTF8String & Query)
{
ne_uri uri;
NeonParseUrl(Url, uri);
std::unique_ptr<TSessionContext> Result(new TSessionContext());
Result->FileSystem = this;
Result->HostName = StrFromNeon(uri.host);
Result->PortNumber = uri.port;
Result->NtlmAuthenticationFailed = false;
Result->NeonSession = CreateNeonSession(uri);
InitSession(Result.get(), Result->NeonSession);
Path = uri.path;
Query = uri.query;
bool Ssl = IsTlsUri(uri);
ne_uri_free(&uri);
ne_set_aux_request_init(Result->NeonSession, NeonAuxRequestInit, Result.get());
UpdateNeonDebugMask();
NeonAddAuthentiation(Result.get(), Ssl);
if (Ssl)
{
SetSessionTls(Result.get(), Result->NeonSession, false);
ne_ssl_provide_clicert(Result->NeonSession, NeonProvideClientCert, Result.get());
}
ne_set_notifier(Result->NeonSession, NeonNotifier, Result.get());
ne_hook_create_request(Result->NeonSession, NeonCreateRequest, Result.get());
ne_hook_pre_send(Result->NeonSession, NeonPreSend, Result.get());
ne_hook_post_send(Result->NeonSession, NeonPostSend, Result.get());
ne_hook_post_headers(Result->NeonSession, NeonPostHeaders, Result.get());
return Result.release();
}
//---------------------------------------------------------------------------
bool TWebDAVFileSystem::IsTlsSession(ne_session * Session)
{
ne_uri uri = {0};
ne_fill_server_uri(Session, &uri);
bool Result = IsTlsUri(uri);
ne_uri_free(&uri);
return Result;
}
//---------------------------------------------------------------------------
void TWebDAVFileSystem::NeonAuxRequestInit(ne_session * Session, ne_request * /*Request*/, void * UserData)
{
TSessionContext * SessionContext = static_cast<TSessionContext *>(UserData);
TWebDAVFileSystem * FileSystem = SessionContext->FileSystem;
FileSystem->InitSession(SessionContext, Session);
if (FileSystem->IsTlsSession(Session))
{
FileSystem->SetSessionTls(SessionContext, Session, true);
}
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::NeonAddAuthentiation(TSessionContext * SessionContext, bool UseNegotiate)
{
unsigned int NeonAuthTypes = NE_AUTH_BASIC | NE_AUTH_DIGEST | NE_AUTH_PASSPORT;
if (UseNegotiate)
{
NeonAuthTypes |= NE_AUTH_NEGOTIATE;
}
if (FTerminal->SessionData->WebDavAuthLegacy)
{
NeonAuthTypes |= NE_AUTH_LEGACY_DIGEST;
}
ne_add_server_auth(SessionContext->NeonSession, NeonAuthTypes, NeonRequestAuth, SessionContext);
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TWebDAVFileSystem::GetRedirectUrl()
{
UnicodeString Result = GetNeonRedirectUrl(FSessionContext->NeonSession);
FTerminal->LogEvent(FORMAT(L"Redirected to \"%s\".", (Result)));
return Result;
}
//---------------------------------------------------------------------------
void TWebDAVFileSystem::ExchangeCapabilities(const char * Path, UnicodeString & CorrectedUrl)
{
ClearNeonError();
int NeonStatus;
FAuthenticationRetry = false;
do
{
NeonStatus = ne_options2(FSessionContext->NeonSession, Path, &FCapabilities);
}
while ((NeonStatus == NE_AUTH) && FAuthenticationRetry);
if (NeonStatus == NE_REDIRECT)
{
CorrectedUrl = GetRedirectUrl();
}
else if (NeonStatus == NE_OK)
{
if (FCapabilities > 0)
{
UnicodeString Str;
unsigned int Capability = 0x01;
unsigned int Capabilities = FCapabilities;
while (Capabilities > 0)
{
if (FLAGSET(Capabilities, Capability))
{
AddToList(Str, StrFromNeon(ne_capability_name(Capability)), L", ");
Capabilities -= Capability;
}
Capability <<= 1;
}
FTerminal->LogEvent(FORMAT(L"Server capabilities: %s", (Str)));
FFileSystemInfo.AdditionalInfo +=
LoadStr(WEBDAV_EXTENSION_INFO) + sLineBreak +
L" " + Str + sLineBreak;
}
}
else
{
CheckStatus(NeonStatus);
}
FTerminal->SaveCapabilities(FFileSystemInfo);
}
//---------------------------------------------------------------------------
TWebDAVFileSystem::TSessionContext::~TSessionContext()
{
if (NeonSession != NULL)
{
DestroyNeonSession(NeonSession);
}
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::CloseNeonSession()
{
if (FSessionContext != NULL)
{
delete FSessionContext;
FSessionContext = NULL;
}
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::Close()
{
DebugAssert(FActive);
CloseNeonSession();
FTerminal->Closed();
FActive = false;
UnregisterFromNeonDebug(FTerminal);
}
//---------------------------------------------------------------------------
bool __fastcall TWebDAVFileSystem::GetActive()
{
return FActive;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::CollectUsage()
{
if (!FTlsVersionStr.IsEmpty())
{
FTerminal->CollectTlsUsage(FTlsVersionStr);
}
if (!FTerminal->SessionData->TlsCertificateFile.IsEmpty())
{
Configuration->Usage->Inc(L"OpenedSessionsWebDAVSCertificate");
}
// The Authorization header for passport method is included only in the first request,
// so we have to use FLastAuthorizationProtocol
if (SameText(FLastAuthorizationProtocol, L"Passport1.4"))
{
Configuration->Usage->Inc(L"OpenedSessionsWebDAVSPassport");
}
else if (SameText(FLastAuthorizationProtocol, L"Basic"))
{
Configuration->Usage->Inc(L"OpenedSessionsWebDAVAuthBasic");
}
UnicodeString RemoteSystem = FFileSystemInfo.RemoteSystem;
if (ContainsText(RemoteSystem, L"Microsoft-IIS"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVIIS");
}
else if (ContainsText(RemoteSystem, L"IT Hit WebDAV Server"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVITHit");
}
// e.g. brickftp.com
else if (ContainsText(RemoteSystem, L"nginx"))
{
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVNginx");
}
else
{
// We also know OpenDrive, Yandex, iFiles (iOS), Swapper (iOS), SafeSync
FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVOther");
}
}
//---------------------------------------------------------------------------
const TSessionInfo & __fastcall TWebDAVFileSystem::GetSessionInfo()
{
return FSessionInfo;
}
//---------------------------------------------------------------------------
const TFileSystemInfo & __fastcall TWebDAVFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
{
return FFileSystemInfo;
}
//---------------------------------------------------------------------------
bool __fastcall TWebDAVFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
{
return false;
}
//---------------------------------------------------------------------------
bool __fastcall TWebDAVFileSystem::GetStoredCredentialsTried()
{
return FStoredPasswordTried;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TWebDAVFileSystem::GetUserName()
{
return FUserName;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::Idle()
{
// noop
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TWebDAVFileSystem::AbsolutePath(const UnicodeString Path, bool /*Local*/)
{
bool AddTrailingBackslash;
if (Path == L"/")
{
// does not really matter as path "/" is still "/" when absolute,
// no slash needed
AddTrailingBackslash = FHasTrailingSlash;
}
else
{
AddTrailingBackslash = (Path[Path.Length()] == L'/');
}
UnicodeString Result = ::AbsolutePath(GetCurrentDirectory(), Path);
// We must preserve trailing slash, because particularly for mod_dav,
// it really matters if the slash in there or not
if (AddTrailingBackslash)
{
Result = UnixIncludeTrailingBackslash(Result);
}
return Result;
}
//---------------------------------------------------------------------------
bool __fastcall TWebDAVFileSystem::IsCapable(int Capability) const
{
DebugAssert(FTerminal);
switch (Capability)
{
case fcRename:
case fcRemoteMove:
case fcMoveToQueue:
case fcPreservingTimestampUpload:
case fcCheckingSpaceAvailable:
// Only to make double-click on file edit/open the file,
// instead of trying to open it as directory
case fcResolveSymlink:
case fcSkipTransfer:
case fcParallelTransfers:
case fcRemoteCopy:
case fcMoveOverExistingFile:
return true;
case fcUserGroupListing:
case fcModeChanging:
case fcModeChangingUpload:
case fcAclChangingFiles:
case fcGroupChanging:
case fcOwnerChanging:
case fcAnyCommand:
case fcShellAnyCommand:
case fcHardLink:
case fcSymbolicLink:
case fcTextMode:
case fcNativeTextMode:
case fcNewerOnlyUpload:
case fcTimestampChanging:
case fcLoadingAdditionalProperties:
case fcIgnorePermErrors:
case fcCalculatingChecksum:
case fcSecondaryShell:
case fcGroupOwnerChangingByID:
case fcRemoveCtrlZUpload:
case fcRemoveBOMUpload:
case fcPreservingTimestampDirs:
case fcResumeSupport:
case fcChangePassword:
case fcTransferOut:
case fcTransferIn:
case fcParallelFileTransfers:
return false;
case fcLocking:
return FLAGSET(FCapabilities, NE_CAP_DAV_CLASS2);
default:
DebugFail();
return false;
}
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TWebDAVFileSystem::GetCurrentDirectory()
{
return FCurrentDirectory;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::DoStartup()
{
FTerminal->SetExceptionOnFail(true);
// retrieve initialize working directory to save it as home directory
ReadCurrentDirectory();
FTerminal->SetExceptionOnFail(false);
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::ClearNeonError()
{
FCancelled = false;
FSkipped = false;
FAuthenticationRequested = false;
ne_set_error(FSessionContext->NeonSession, "");
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TWebDAVFileSystem::GetNeonError()
{
return ::GetNeonError(FSessionContext->NeonSession);
}
//---------------------------------------------------------------------------
void TWebDAVFileSystem::CheckStatus(int NeonStatus)
{
CheckStatus(FSessionContext, NeonStatus);
}
//---------------------------------------------------------------------------
void TWebDAVFileSystem::CheckStatus(TSessionContext * SessionContext, int NeonStatus)
{
if ((NeonStatus == NE_ERROR) && (FCancelled || FSkipped))
{
if (FCancelled)
{
FCancelled = false;
FSkipped = false; // just in case
Abort();
}
else
{
DebugAssert(FSkipped);
FSkipped = false;
throw ESkipFile();
}
}
else
{
CheckNeonStatus(SessionContext->NeonSession, NeonStatus, SessionContext->HostName);
}
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::LookupUsersGroups()
{
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::ReadCurrentDirectory()
{
if (FCachedDirectoryChange.IsEmpty())
{
FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
}
else
{
FCurrentDirectory = FCachedDirectoryChange;
FCachedDirectoryChange = L"";
}
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::HomeDirectory()
{
ChangeDirectory(L"/");
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TWebDAVFileSystem::DirectoryPath(UnicodeString Path)
{
if (FHasTrailingSlash)
{
Path = ::UnixIncludeTrailingBackslash(Path);
}
return Path;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall TWebDAVFileSystem::FilePath(const TRemoteFile * File)
{
UnicodeString Result = File->FullFileName;
if (File->IsDirectory)
{
Result = DirectoryPath(Result);
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::TryOpenDirectory(UnicodeString Directory)
{
Directory = DirectoryPath(Directory);
FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
TRemoteFile * File;
ReadFile(Directory, File);
delete File;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::AnnounceFileListOperation()
{
// noop
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::ChangeDirectory(const UnicodeString ADirectory)
{
UnicodeString Path = AbsolutePath(ADirectory, false);
// to verify existence of directory try to open it
TryOpenDirectory(Path);
// if open dir did not fail, directory exists -> success.
FCachedDirectoryChange = Path;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::CachedChangeDirectory(const UnicodeString Directory)
{
FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
}
//---------------------------------------------------------------------------
struct TReadFileData
{
TWebDAVFileSystem * FileSystem;
TRemoteFile * File;
TRemoteFileList * FileList;
};
//---------------------------------------------------------------------------
int __fastcall TWebDAVFileSystem::ReadDirectoryInternal(
const UnicodeString & Path, TRemoteFileList * FileList)
{
TReadFileData Data;
Data.FileSystem = this;
Data.File = NULL;
Data.FileList = FileList;
ClearNeonError();
ne_propfind_handler * PropFindHandler = ne_propfind_create(FSessionContext->NeonSession, PathToNeon(Path), NE_DEPTH_ONE);
void * DiscoveryContext = ne_lock_register_discovery(PropFindHandler);
int Result;
try
{
Result = ne_propfind_allprop(PropFindHandler, NeonPropsResult, &Data);
}
__finally
{
ne_lock_discovery_free(DiscoveryContext);
ne_propfind_destroy(PropFindHandler);
}
return Result;
}
//---------------------------------------------------------------------------
bool __fastcall TWebDAVFileSystem::IsValidRedirect(int NeonStatus, UnicodeString & Path)
{
bool Result = (NeonStatus == NE_REDIRECT);
if (Result)
{
// What PathToNeon does
UnicodeString OriginalPath = AbsolutePath(Path, false);
// Handle one-step redirect
// (for more steps we would have to implement loop detection).
// This is mainly to handle "folder" => "folder/" redirects of Apache/mod_dav.
UnicodeString RedirectUrl = GetRedirectUrl();
// We should test if the redirect is not for another server,
// though not sure how to do this reliably (domain aliases, IP vs. domain, etc.)
// If this ever gets implemented, beware of use from Sink(), where we support redirects to another server.
UnicodeString RedirectPath = ParsePathFromUrl(RedirectUrl);
Result =
!RedirectPath.IsEmpty() &&
(RedirectPath != OriginalPath);
if (Result)
{
Path = RedirectPath;
}
}
return Result;
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::ReadDirectory(TRemoteFileList * FileList)
{
UnicodeString Path = DirectoryPath(FileList->Directory);
TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
int NeonStatus = ReadDirectoryInternal(Path, FileList);
if (IsValidRedirect(NeonStatus, Path))
{
NeonStatus = ReadDirectoryInternal(Path, FileList);
}
CheckStatus(NeonStatus);
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
TRemoteFile *& /*File*/)
{
// we never set SymLink flag, so we should never get here
DebugFail();
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::ReadFile(const UnicodeString FileName,
TRemoteFile *& File)
{
CustomReadFile(FileName, File, NULL);
}
//---------------------------------------------------------------------------
void TWebDAVFileSystem::NeonPropsResult(
void * UserData, const ne_uri * Uri, const ne_prop_result_set * Results)
{
UnicodeString Path = PathUnescape(Uri->path);
TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
if (Data.FileList != NULL)
{
std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
File->Terminal = Data.FileSystem->FTerminal;
Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
UnicodeString FileListPath = Data.FileSystem->AbsolutePath(Data.FileList->Directory, false);
if (UnixSamePath(File->FullFileName, FileListPath))
{
File->FileName = PARENTDIRECTORY;
File->FullFileName = UnixCombinePaths(Path, PARENTDIRECTORY);
}
Data.FileList->AddFile(File.release());
}
else
{
Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
}
}
//---------------------------------------------------------------------------
const char * __fastcall TWebDAVFileSystem::GetProp(
const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
{
ne_propname Prop;
Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
Prop.name = Name;
return ne_propset_value(Results, &Prop);
}
//---------------------------------------------------------------------------
void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
const UnicodeString & Path, const ne_prop_result_set * Results)
{
File->FullFileName = UnixExcludeTrailingBackslash(Path);
// Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
// But not all, for example OneDrive does not (it did in the past).
bool Collection = (File->FullFileName != Path);
File->FileName = UnixExtractFileName(File->FullFileName);
const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
// some servers, for example iFiles, do not provide "getcontentlength" for folders
if (ContentLength != NULL)
{
File->Size = StrToInt64Def(ContentLength, 0);
}
const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
// We've seen a server (t=24891) that does not set "getlastmodified" for the "this" folder entry.
if (LastModified != NULL)
{
char WeekDay[4] = { L'\0' };
int Year = 0;
char MonthStr[4] = { L'\0' };
int Day = 0;
int Hour = 0;
int Min = 0;
int Sec = 0;
#define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
// Keep is sync with S3
int Filled =
sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
// we need at least a complete date
if (Filled >= 4)
{
int Month = ParseShortEngMonthName(MonthStr);
if (Month >= 1)
{
TDateTime Modification =
EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
File->Modification = ConvertTimestampFromUTC(Modification);
// Should use mfYMDHM or mfMDY when appropriate according to Filled
File->ModificationFmt = mfFull;
}
else
{
File->ModificationFmt = mfNone;
}
}
else
{
File->ModificationFmt = mfNone;
}
}
// optimization
if (!Collection)
{
// See a comment at the Collection declaration.
const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
if (ResourceType != NULL)
{
// property has XML value
UnicodeString AResourceType = ResourceType;
// this is very poor parsing
if (ContainsText(ResourceType, L"<DAV:collection"))
{
Collection = true;
}
}
}
File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
// this is MS extension (draft-hopmann-collection-props-00)
const char * IsHidden = GetProp(Results, PROP_HIDDEN);
if (IsHidden != NULL)
{
File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
}
const char * Owner = GetProp(Results, PROP_OWNER);
if (Owner != NULL)
{
File->Owner.Name = Owner;
}
const char * DisplayName = GetProp(Results, PROP_DISPLAY_NAME);
if (DisplayName != NULL)
{
File->DisplayName = StrFromNeon(DisplayName);
// OneDrive caret escaping (we could do this for all files, but let's limit the scope for now).
// In *file* PROPFIND response, the # (and other symbols like comma or plus) is not escaped at all
// (while in directory listing, they are caret-escaped),
// so if we see one in the display name, take the name from there.
// * and % won't help, as OneDrive seem to have bug with % at the end of the filename,
// and the * (and others) is removed from file names.
// Filenames with commas (,) get as many additional characters at the end of the filename as there are commas.
if (FOneDrive &&
(ContainsText(File->FileName, L"^") || ContainsText(File->FileName, L",") || (wcspbrk(File->DisplayName.c_str(), L"&,+#[]%*") != NULL)))
{
File->FileName = File->DisplayName;
File->FullFileName = UnixCombinePaths(UnixExtractFileDir(File->FullFileName), File->FileName);
}
}
const UnicodeString RightsDelimiter(L", ");
UnicodeString HumanRights;
// Proprietary property of mod_dav
// http://www.webdav.org/mod_dav/#imp