WebDAVFileSystem.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <io.h>
  5. #include <fcntl.h>
  6. #include <wincrypt.h>
  7. #define NE_LFS
  8. #define WINSCP
  9. #include <ne_basic.h>
  10. #include <ne_auth.h>
  11. #include <ne_props.h>
  12. #include <ne_uri.h>
  13. #include <ne_session.h>
  14. #include <ne_request.h>
  15. #include <ne_xml.h>
  16. #include <ne_redirect.h>
  17. #include <ne_xmlreq.h>
  18. #include <ne_locks.h>
  19. #include <expat.h>
  20. #include "WebDAVFileSystem.h"
  21. #include "Interface.h"
  22. #include "Common.h"
  23. #include "Exceptions.h"
  24. #include "Terminal.h"
  25. #include "TextsCore.h"
  26. #include "SecureShell.h"
  27. #include "HelpCore.h"
  28. #include "CoreMain.h"
  29. #include "Security.h"
  30. #include <StrUtils.hpp>
  31. #include <NeonIntf.h>
  32. //---------------------------------------------------------------------------
  33. #pragma package(smart_init)
  34. //---------------------------------------------------------------------------
  35. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  36. //---------------------------------------------------------------------------
  37. #define SESSION_FS_KEY "filesystem"
  38. static const UnicodeString CONST_WEBDAV_PROTOCOL_BASE_NAME = L"WebDAV";
  39. static const int HttpUnauthorized = 401;
  40. //---------------------------------------------------------------------------
  41. #define DAV_PROP_NAMESPACE "DAV:"
  42. #define MODDAV_PROP_NAMESPACE "http://apache.org/dav/props/"
  43. #define PROP_CONTENT_LENGTH "getcontentlength"
  44. #define PROP_LAST_MODIFIED "getlastmodified"
  45. #define PROP_RESOURCE_TYPE "resourcetype"
  46. #define PROP_HIDDEN "ishidden"
  47. #define PROP_QUOTA_AVAILABLE "quota-available-bytes"
  48. #define PROP_QUOTA_USED "quota-used-bytes"
  49. #define PROP_EXECUTABLE "executable"
  50. #define PROP_OWNER "owner"
  51. #define PROP_DISPLAY_NAME "displayname"
  52. //------------------------------------------------------------------------------
  53. //---------------------------------------------------------------------------
  54. // ne_path_escape returns 7-bit string, so it does not really matter if we use
  55. // AnsiString or UTF8String here, though UTF8String might be more safe
  56. static AnsiString PathEscape(const char * Path)
  57. {
  58. char * EscapedPath = ne_path_escape(Path);
  59. AnsiString Result = EscapedPath;
  60. ne_free(EscapedPath);
  61. return Result;
  62. }
  63. //---------------------------------------------------------------------------
  64. static UnicodeString PathUnescape(const char * Path)
  65. {
  66. char * UnescapedPath = ne_path_unescape(Path);
  67. UTF8String UtfResult;
  68. if (UnescapedPath != NULL)
  69. {
  70. UtfResult = UnescapedPath;
  71. ne_free(UnescapedPath);
  72. }
  73. else
  74. {
  75. // OneDrive, particularly in the response to *file* PROPFIND tend to return a malformed URL.
  76. // In such case, take the path as is and we will probably overwrite the name with "display name".
  77. UtfResult = Path;
  78. }
  79. UnicodeString Result = StrFromNeon(UtfResult);
  80. return Result;
  81. }
  82. //---------------------------------------------------------------------------
  83. #define AbsolutePathToNeon(P) PathEscape(StrToNeon(P)).c_str()
  84. #define PathToNeonStatic(THIS, P) AbsolutePathToNeon((THIS)->AbsolutePath(P, false))
  85. #define PathToNeon(P) PathToNeonStatic(this, P)
  86. //---------------------------------------------------------------------------
  87. //---------------------------------------------------------------------------
  88. static bool NeonInitialized = false;
  89. static bool NeonSspiInitialized = false;
  90. //---------------------------------------------------------------------------
  91. void __fastcall NeonInitialize()
  92. {
  93. // Even if this fails, we do not want to interrupt WinSCP starting for that.
  94. // Anyway, it can hardly fail.
  95. // Though it fails on Wine on Debian VM, because of ne_sspi_init():
  96. // sspi: QuerySecurityPackageInfo [failed] [80090305].
  97. // sspi: Unable to get negotiate maximum packet size
  98. int NeonResult = ne_sock_init();
  99. if (NeonResult == 0)
  100. {
  101. NeonInitialized = true;
  102. NeonSspiInitialized = true;
  103. }
  104. else if (NeonResult == -2)
  105. {
  106. NeonInitialized = true;
  107. NeonSspiInitialized = false;
  108. }
  109. else
  110. {
  111. NeonInitialized = false;
  112. NeonSspiInitialized = false;
  113. }
  114. }
  115. //---------------------------------------------------------------------------
  116. void __fastcall NeonFinalize()
  117. {
  118. if (NeonInitialized)
  119. {
  120. ne_sock_exit();
  121. NeonInitialized = false;
  122. }
  123. }
  124. //---------------------------------------------------------------------------
  125. void __fastcall RequireNeon(TTerminal * Terminal)
  126. {
  127. if (!NeonInitialized)
  128. {
  129. throw Exception(LoadStr(NEON_INIT_FAILED2));
  130. }
  131. if (!NeonSspiInitialized)
  132. {
  133. Terminal->LogEvent(L"Warning: SSPI initialization failed.");
  134. }
  135. }
  136. //---------------------------------------------------------------------------
  137. UnicodeString __fastcall NeonVersion()
  138. {
  139. UnicodeString Str = StrFromNeon(ne_version_string());
  140. CutToChar(Str, L' ', true); // "neon"
  141. UnicodeString Result = CutToChar(Str, L':', true);
  142. return Result;
  143. }
  144. //---------------------------------------------------------------------------
  145. UnicodeString __fastcall ExpatVersion()
  146. {
  147. return FORMAT(L"%d.%d.%d", (XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION));
  148. }
  149. //---------------------------------------------------------------------------
  150. //---------------------------------------------------------------------------
  151. TWebDAVFileSystem::TWebDAVFileSystem(TTerminal * ATerminal) :
  152. TCustomFileSystem(ATerminal),
  153. FActive(false),
  154. FHasTrailingSlash(false),
  155. FNeonSession(NULL),
  156. FNeonLockStore(NULL),
  157. FNeonLockStoreSection(new TCriticalSection()),
  158. FUploading(false),
  159. FDownloading(false),
  160. FInitialHandshake(false),
  161. FIgnoreAuthenticationFailure(iafNo)
  162. {
  163. FFileSystemInfo.ProtocolBaseName = CONST_WEBDAV_PROTOCOL_BASE_NAME;
  164. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  165. }
  166. //---------------------------------------------------------------------------
  167. __fastcall TWebDAVFileSystem::~TWebDAVFileSystem()
  168. {
  169. UnregisterFromNeonDebug(FTerminal);
  170. {
  171. TGuard Guard(FNeonLockStoreSection);
  172. if (FNeonLockStore != NULL)
  173. {
  174. ne_lockstore_destroy(FNeonLockStore);
  175. FNeonLockStore = NULL;
  176. }
  177. }
  178. delete FNeonLockStoreSection;
  179. }
  180. //---------------------------------------------------------------------------
  181. void __fastcall TWebDAVFileSystem::Open()
  182. {
  183. RequireNeon(FTerminal);
  184. RegisterForNeonDebug(FTerminal);
  185. FCurrentDirectory = L"";
  186. FHasTrailingSlash = true;
  187. FStoredPasswordTried = false;
  188. FTlsVersionStr = L"";
  189. FCapabilities = 0;
  190. TSessionData * Data = FTerminal->SessionData;
  191. FSessionInfo.LoginTime = Now();
  192. FSessionInfo.CertificateVerifiedManually = false;
  193. UnicodeString HostName = Data->HostNameExpanded;
  194. FOneDrive = SameText(HostName, L"d.docs.live.net");
  195. if (FOneDrive)
  196. {
  197. FTerminal->LogEvent(L"OneDrive host detected.");
  198. }
  199. size_t Port = Data->PortNumber;
  200. UnicodeString ProtocolName = (FTerminal->SessionData->Ftps == ftpsNone) ? HttpProtocol : HttpsProtocol;
  201. UnicodeString Path = Data->RemoteDirectory;
  202. // PathToNeon is not used as we cannot call AbsolutePath here
  203. UnicodeString EscapedPath = StrFromNeon(PathEscape(StrToNeon(Path)).c_str());
  204. UnicodeString Url = FORMAT(L"%s://%s:%d%s", (ProtocolName, HostName, Port, EscapedPath));
  205. FTerminal->Information(LoadStr(STATUS_CONNECT), true);
  206. FActive = false;
  207. try
  208. {
  209. OpenUrl(Url);
  210. }
  211. catch (Exception & E)
  212. {
  213. CloseNeonSession();
  214. FTerminal->Closed();
  215. FTerminal->FatalError(&E, LoadStr(CONNECTION_FAILED));
  216. }
  217. FActive = true;
  218. }
  219. //---------------------------------------------------------------------------
  220. UnicodeString __fastcall TWebDAVFileSystem::ParsePathFromUrl(const UnicodeString & Url)
  221. {
  222. UnicodeString Result;
  223. ne_uri ParsedUri;
  224. if (ne_uri_parse(StrToNeon(Url), &ParsedUri) == 0)
  225. {
  226. Result = PathUnescape(ParsedUri.path);
  227. ne_uri_free(&ParsedUri);
  228. }
  229. return Result;
  230. }
  231. //---------------------------------------------------------------------------
  232. void TWebDAVFileSystem::OpenUrl(const UnicodeString & Url)
  233. {
  234. UnicodeString CorrectedUrl;
  235. NeonClientOpenSessionInternal(CorrectedUrl, Url);
  236. if (CorrectedUrl.IsEmpty())
  237. {
  238. CorrectedUrl = Url;
  239. }
  240. UnicodeString ParsedPath = ParsePathFromUrl(CorrectedUrl);
  241. if (!ParsedPath.IsEmpty())
  242. {
  243. // this is most likely pointless as it get overwritten by
  244. // call to ChangeDirectory() from TTerminal::DoStartup
  245. FCurrentDirectory = ParsedPath;
  246. }
  247. }
  248. //---------------------------------------------------------------------------
  249. void TWebDAVFileSystem::NeonClientOpenSessionInternal(UnicodeString & CorrectedUrl, UnicodeString Url)
  250. {
  251. std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
  252. AttemptedUrls->Add(Url);
  253. while (true)
  254. {
  255. CorrectedUrl = L"";
  256. NeonOpen(CorrectedUrl, Url);
  257. // No error and no corrected URL? We're done here.
  258. if (CorrectedUrl.IsEmpty())
  259. {
  260. break;
  261. }
  262. CloseNeonSession();
  263. CheckRedirectLoop(CorrectedUrl, AttemptedUrls.get());
  264. // Our caller will want to know what our final corrected URL was.
  265. Url = CorrectedUrl;
  266. }
  267. CorrectedUrl = Url;
  268. }
  269. //---------------------------------------------------------------------------
  270. void __fastcall TWebDAVFileSystem::SetSessionTls(ne_session_s * Session, bool Aux)
  271. {
  272. SetNeonTlsInit(Session, InitSslSession);
  273. // When the CA certificate or server certificate has
  274. // verification problems, neon will call our verify function before
  275. // outright rejection of the connection.
  276. ne_ssl_verify_fn Callback = Aux ? NeonServerSSLCallbackAux : NeonServerSSLCallbackMain;
  277. ne_ssl_set_verify(Session, Callback, this);
  278. ne_ssl_trust_default_ca(Session);
  279. }
  280. //---------------------------------------------------------------------------
  281. void __fastcall TWebDAVFileSystem::InitSession(ne_session_s * Session)
  282. {
  283. TSessionData * Data = FTerminal->SessionData;
  284. InitNeonSession(
  285. Session, Data->ProxyMethod, Data->ProxyHost, Data->ProxyPort,
  286. Data->ProxyUsername, Data->ProxyPassword, FTerminal);
  287. ne_set_read_timeout(Session, Data->Timeout);
  288. ne_set_connect_timeout(Session, Data->Timeout);
  289. ne_set_session_private(Session, SESSION_FS_KEY, this);
  290. // Allow ^-escaping in OneDrive
  291. ne_set_session_flag(Session, NE_SESSFLAG_LIBERAL_ESCAPING, Data->WebDavLiberalEscaping || FOneDrive);
  292. }
  293. //---------------------------------------------------------------------------
  294. void TWebDAVFileSystem::NeonOpen(UnicodeString & CorrectedUrl, const UnicodeString & Url)
  295. {
  296. ne_uri uri;
  297. NeonParseUrl(Url, uri);
  298. FHostName = StrFromNeon(uri.host);
  299. FPortNumber = uri.port;
  300. FSessionInfo.CSCipher = UnicodeString();
  301. FSessionInfo.SCCipher = UnicodeString();
  302. bool Ssl = IsTlsUri(uri);
  303. FSessionInfo.SecurityProtocolName = Ssl ? LoadStr(FTPS_IMPLICIT) : UnicodeString();
  304. if (Ssl != (FTerminal->SessionData->Ftps != ftpsNone))
  305. {
  306. FTerminal->LogEvent(FORMAT(L"Warning: %s", (LoadStr(UNENCRYPTED_REDIRECT))));
  307. }
  308. DebugAssert(FNeonSession == NULL);
  309. FNeonSession = CreateNeonSession(uri);
  310. InitSession(FNeonSession);
  311. UTF8String Path = uri.path;
  312. ne_uri_free(&uri);
  313. ne_set_aux_request_init(FNeonSession, NeonAuxRequestInit, this);
  314. UpdateNeonDebugMask();
  315. NeonAddAuthentiation(Ssl);
  316. if (Ssl)
  317. {
  318. SetSessionTls(FNeonSession, false);
  319. ne_ssl_provide_clicert(FNeonSession, NeonProvideClientCert, this);
  320. }
  321. ne_set_notifier(FNeonSession, NeonNotifier, this);
  322. ne_hook_create_request(FNeonSession, NeonCreateRequest, this);
  323. ne_hook_pre_send(FNeonSession, NeonPreSend, this);
  324. ne_hook_post_send(FNeonSession, NeonPostSend, this);
  325. ne_hook_post_headers(FNeonSession, NeonPostHeaders, this);
  326. TAutoFlag Flag(FInitialHandshake);
  327. ExchangeCapabilities(Path.c_str(), CorrectedUrl);
  328. }
  329. //---------------------------------------------------------------------------
  330. void TWebDAVFileSystem::NeonAuxRequestInit(ne_session * Session, ne_request * /*Request*/, void * UserData)
  331. {
  332. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  333. FileSystem->InitSession(Session);
  334. ne_uri uri = {0};
  335. ne_fill_server_uri(Session, &uri);
  336. bool Tls = IsTlsUri(uri);
  337. ne_uri_free(&uri);
  338. if (Tls)
  339. {
  340. FileSystem->SetSessionTls(Session, true);
  341. }
  342. }
  343. //---------------------------------------------------------------------------
  344. void __fastcall TWebDAVFileSystem::NeonAddAuthentiation(bool UseNegotiate)
  345. {
  346. unsigned int NeonAuthTypes = NE_AUTH_BASIC | NE_AUTH_DIGEST | NE_AUTH_PASSPORT;
  347. if (UseNegotiate)
  348. {
  349. NeonAuthTypes |= NE_AUTH_NEGOTIATE;
  350. }
  351. ne_add_server_auth(FNeonSession, NeonAuthTypes, NeonRequestAuth, this);
  352. }
  353. //---------------------------------------------------------------------------
  354. UnicodeString __fastcall TWebDAVFileSystem::GetRedirectUrl()
  355. {
  356. UnicodeString Result = GetNeonRedirectUrl(FNeonSession);
  357. FTerminal->LogEvent(FORMAT(L"Redirected to \"%s\".", (Result)));
  358. return Result;
  359. }
  360. //---------------------------------------------------------------------------
  361. void TWebDAVFileSystem::ExchangeCapabilities(const char * Path, UnicodeString & CorrectedUrl)
  362. {
  363. ClearNeonError();
  364. int NeonStatus;
  365. FAuthenticationRetry = false;
  366. do
  367. {
  368. NeonStatus = ne_options2(FNeonSession, Path, &FCapabilities);
  369. }
  370. while ((NeonStatus == NE_AUTH) && FAuthenticationRetry);
  371. if (NeonStatus == NE_REDIRECT)
  372. {
  373. CorrectedUrl = GetRedirectUrl();
  374. }
  375. else if (NeonStatus == NE_OK)
  376. {
  377. if (FCapabilities > 0)
  378. {
  379. UnicodeString Str;
  380. unsigned int Capability = 0x01;
  381. unsigned int Capabilities = FCapabilities;
  382. while (Capabilities > 0)
  383. {
  384. if (FLAGSET(Capabilities, Capability))
  385. {
  386. AddToList(Str, StrFromNeon(ne_capability_name(Capability)), L", ");
  387. Capabilities -= Capability;
  388. }
  389. Capability <<= 1;
  390. }
  391. FTerminal->LogEvent(FORMAT(L"Server capabilities: %s", (Str)));
  392. FFileSystemInfo.AdditionalInfo +=
  393. LoadStr(WEBDAV_EXTENSION_INFO) + sLineBreak +
  394. L" " + Str + sLineBreak;
  395. }
  396. }
  397. else
  398. {
  399. CheckStatus(NeonStatus);
  400. }
  401. FTerminal->SaveCapabilities(FFileSystemInfo);
  402. }
  403. //---------------------------------------------------------------------------
  404. void __fastcall TWebDAVFileSystem::CloseNeonSession()
  405. {
  406. if (FNeonSession != NULL)
  407. {
  408. DestroyNeonSession(FNeonSession);
  409. FNeonSession = NULL;
  410. }
  411. }
  412. //---------------------------------------------------------------------------
  413. void __fastcall TWebDAVFileSystem::Close()
  414. {
  415. DebugAssert(FActive);
  416. CloseNeonSession();
  417. FTerminal->Closed();
  418. FActive = false;
  419. UnregisterFromNeonDebug(FTerminal);
  420. }
  421. //---------------------------------------------------------------------------
  422. bool __fastcall TWebDAVFileSystem::GetActive()
  423. {
  424. return FActive;
  425. }
  426. //---------------------------------------------------------------------------
  427. void __fastcall TWebDAVFileSystem::CollectUsage()
  428. {
  429. if (!FTlsVersionStr.IsEmpty())
  430. {
  431. FTerminal->CollectTlsUsage(FTlsVersionStr);
  432. }
  433. if (!FTerminal->SessionData->TlsCertificateFile.IsEmpty())
  434. {
  435. Configuration->Usage->Inc(L"OpenedSessionsWebDAVSCertificate");
  436. }
  437. // The Authorization header for passport method is included only in the first request,
  438. // so we have to use FLastAuthorizationProtocol
  439. if (SameText(FLastAuthorizationProtocol, L"Passport1.4"))
  440. {
  441. Configuration->Usage->Inc(L"OpenedSessionsWebDAVSPassport");
  442. }
  443. UnicodeString RemoteSystem = FFileSystemInfo.RemoteSystem;
  444. if (ContainsText(RemoteSystem, L"Microsoft-IIS"))
  445. {
  446. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVIIS");
  447. }
  448. else if (ContainsText(RemoteSystem, L"IT Hit WebDAV Server"))
  449. {
  450. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVITHit");
  451. }
  452. // e.g. brickftp.com
  453. else if (ContainsText(RemoteSystem, L"nginx"))
  454. {
  455. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVNginx");
  456. }
  457. else
  458. {
  459. // We also know OpenDrive, Yandex, iFiles (iOS), Swapper (iOS), SafeSync
  460. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVOther");
  461. }
  462. }
  463. //---------------------------------------------------------------------------
  464. const TSessionInfo & __fastcall TWebDAVFileSystem::GetSessionInfo()
  465. {
  466. return FSessionInfo;
  467. }
  468. //---------------------------------------------------------------------------
  469. const TFileSystemInfo & __fastcall TWebDAVFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  470. {
  471. return FFileSystemInfo;
  472. }
  473. //---------------------------------------------------------------------------
  474. bool __fastcall TWebDAVFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  475. {
  476. return false;
  477. }
  478. //---------------------------------------------------------------------------
  479. bool __fastcall TWebDAVFileSystem::GetStoredCredentialsTried()
  480. {
  481. return FStoredPasswordTried;
  482. }
  483. //---------------------------------------------------------------------------
  484. UnicodeString __fastcall TWebDAVFileSystem::GetUserName()
  485. {
  486. return FUserName;
  487. }
  488. //---------------------------------------------------------------------------
  489. void __fastcall TWebDAVFileSystem::Idle()
  490. {
  491. // noop
  492. }
  493. //---------------------------------------------------------------------------
  494. UnicodeString __fastcall TWebDAVFileSystem::AbsolutePath(const UnicodeString Path, bool /*Local*/)
  495. {
  496. bool AddTrailingBackslash;
  497. if (Path == L"/")
  498. {
  499. // does not really matter as path "/" is still "/" when absolute,
  500. // no slash needed
  501. AddTrailingBackslash = FHasTrailingSlash;
  502. }
  503. else
  504. {
  505. AddTrailingBackslash = (Path[Path.Length()] == L'/');
  506. }
  507. UnicodeString Result = ::AbsolutePath(GetCurrentDirectory(), Path);
  508. // We must preserve trailing slash, because particularly for mod_dav,
  509. // it really matters if the slash in there or not
  510. if (AddTrailingBackslash)
  511. {
  512. Result = UnixIncludeTrailingBackslash(Result);
  513. }
  514. return Result;
  515. }
  516. //---------------------------------------------------------------------------
  517. bool __fastcall TWebDAVFileSystem::IsCapable(int Capability) const
  518. {
  519. DebugAssert(FTerminal);
  520. switch (Capability)
  521. {
  522. case fcRename:
  523. case fcRemoteMove:
  524. case fcMoveToQueue:
  525. case fcPreservingTimestampUpload:
  526. case fcCheckingSpaceAvailable:
  527. // Only to make double-click on file edit/open the file,
  528. // instead of trying to open it as directory
  529. case fcResolveSymlink:
  530. case fcSkipTransfer:
  531. case fcParallelTransfers:
  532. case fcRemoteCopy:
  533. return true;
  534. case fcUserGroupListing:
  535. case fcModeChanging:
  536. case fcModeChangingUpload:
  537. case fcGroupChanging:
  538. case fcOwnerChanging:
  539. case fcAnyCommand:
  540. case fcShellAnyCommand:
  541. case fcHardLink:
  542. case fcSymbolicLink:
  543. case fcTextMode:
  544. case fcNativeTextMode:
  545. case fcNewerOnlyUpload:
  546. case fcTimestampChanging:
  547. case fcLoadingAdditionalProperties:
  548. case fcIgnorePermErrors:
  549. case fcCalculatingChecksum:
  550. case fcSecondaryShell:
  551. case fcGroupOwnerChangingByID:
  552. case fcRemoveCtrlZUpload:
  553. case fcRemoveBOMUpload:
  554. case fcPreservingTimestampDirs:
  555. case fcResumeSupport:
  556. case fcChangePassword:
  557. case fcTransferOut:
  558. case fcTransferIn:
  559. return false;
  560. case fcLocking:
  561. return FLAGSET(FCapabilities, NE_CAP_DAV_CLASS2);
  562. default:
  563. DebugFail();
  564. return false;
  565. }
  566. }
  567. //---------------------------------------------------------------------------
  568. UnicodeString __fastcall TWebDAVFileSystem::GetCurrentDirectory()
  569. {
  570. return FCurrentDirectory;
  571. }
  572. //---------------------------------------------------------------------------
  573. void __fastcall TWebDAVFileSystem::DoStartup()
  574. {
  575. FTerminal->SetExceptionOnFail(true);
  576. // retrieve initialize working directory to save it as home directory
  577. ReadCurrentDirectory();
  578. FTerminal->SetExceptionOnFail(false);
  579. }
  580. //---------------------------------------------------------------------------
  581. void __fastcall TWebDAVFileSystem::ClearNeonError()
  582. {
  583. FCancelled = false;
  584. FSkipped = false;
  585. FAuthenticationRequested = false;
  586. ne_set_error(FNeonSession, "");
  587. }
  588. //---------------------------------------------------------------------------
  589. UnicodeString __fastcall TWebDAVFileSystem::GetNeonError()
  590. {
  591. return ::GetNeonError(FNeonSession);
  592. }
  593. //---------------------------------------------------------------------------
  594. void __fastcall TWebDAVFileSystem::CheckStatus(int NeonStatus)
  595. {
  596. if ((NeonStatus == NE_ERROR) && (FCancelled || FSkipped))
  597. {
  598. if (FCancelled)
  599. {
  600. FCancelled = false;
  601. FSkipped = false; // just in case
  602. Abort();
  603. }
  604. else
  605. {
  606. DebugAssert(FSkipped);
  607. FSkipped = false;
  608. throw ESkipFile();
  609. }
  610. }
  611. else
  612. {
  613. CheckNeonStatus(FNeonSession, NeonStatus, FHostName);
  614. }
  615. }
  616. //---------------------------------------------------------------------------
  617. void __fastcall TWebDAVFileSystem::LookupUsersGroups()
  618. {
  619. DebugFail();
  620. }
  621. //---------------------------------------------------------------------------
  622. void __fastcall TWebDAVFileSystem::ReadCurrentDirectory()
  623. {
  624. if (FCachedDirectoryChange.IsEmpty())
  625. {
  626. FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
  627. }
  628. else
  629. {
  630. FCurrentDirectory = FCachedDirectoryChange;
  631. FCachedDirectoryChange = L"";
  632. }
  633. }
  634. //---------------------------------------------------------------------------
  635. void __fastcall TWebDAVFileSystem::HomeDirectory()
  636. {
  637. ChangeDirectory(L"/");
  638. }
  639. //---------------------------------------------------------------------------
  640. UnicodeString __fastcall TWebDAVFileSystem::DirectoryPath(UnicodeString Path)
  641. {
  642. if (FHasTrailingSlash)
  643. {
  644. Path = ::UnixIncludeTrailingBackslash(Path);
  645. }
  646. return Path;
  647. }
  648. //---------------------------------------------------------------------------
  649. UnicodeString __fastcall TWebDAVFileSystem::FilePath(const TRemoteFile * File)
  650. {
  651. UnicodeString Result = File->FullFileName;
  652. if (File->IsDirectory)
  653. {
  654. Result = DirectoryPath(Result);
  655. }
  656. return Result;
  657. }
  658. //---------------------------------------------------------------------------
  659. void __fastcall TWebDAVFileSystem::TryOpenDirectory(UnicodeString Directory)
  660. {
  661. Directory = DirectoryPath(Directory);
  662. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  663. TRemoteFile * File;
  664. ReadFile(Directory, File);
  665. delete File;
  666. }
  667. //---------------------------------------------------------------------------
  668. void __fastcall TWebDAVFileSystem::AnnounceFileListOperation()
  669. {
  670. // noop
  671. }
  672. //---------------------------------------------------------------------------
  673. void __fastcall TWebDAVFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  674. {
  675. UnicodeString Path = AbsolutePath(ADirectory, false);
  676. // to verify existence of directory try to open it
  677. TryOpenDirectory(Path);
  678. // if open dir did not fail, directory exists -> success.
  679. FCachedDirectoryChange = Path;
  680. }
  681. //---------------------------------------------------------------------------
  682. void __fastcall TWebDAVFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  683. {
  684. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  685. }
  686. //---------------------------------------------------------------------------
  687. struct TReadFileData
  688. {
  689. TWebDAVFileSystem * FileSystem;
  690. TRemoteFile * File;
  691. TRemoteFileList * FileList;
  692. };
  693. //---------------------------------------------------------------------------
  694. int __fastcall TWebDAVFileSystem::ReadDirectoryInternal(
  695. const UnicodeString & Path, TRemoteFileList * FileList)
  696. {
  697. TReadFileData Data;
  698. Data.FileSystem = this;
  699. Data.File = NULL;
  700. Data.FileList = FileList;
  701. ClearNeonError();
  702. ne_propfind_handler * PropFindHandler = ne_propfind_create(FNeonSession, PathToNeon(Path), NE_DEPTH_ONE);
  703. void * DiscoveryContext = ne_lock_register_discovery(PropFindHandler);
  704. int Result;
  705. try
  706. {
  707. Result = ne_propfind_allprop(PropFindHandler, NeonPropsResult, &Data);
  708. }
  709. __finally
  710. {
  711. ne_lock_discovery_free(DiscoveryContext);
  712. ne_propfind_destroy(PropFindHandler);
  713. }
  714. return Result;
  715. }
  716. //---------------------------------------------------------------------------
  717. bool __fastcall TWebDAVFileSystem::IsValidRedirect(int NeonStatus, UnicodeString & Path)
  718. {
  719. bool Result = (NeonStatus == NE_REDIRECT);
  720. if (Result)
  721. {
  722. // What PathToNeon does
  723. UnicodeString OriginalPath = AbsolutePath(Path, false);
  724. // Handle one-step redirect
  725. // (for more steps we would have to implement loop detection).
  726. // This is mainly to handle "folder" => "folder/" redirects of Apache/mod_dav.
  727. UnicodeString RedirectUrl = GetRedirectUrl();
  728. // We should test if the redirect is not for another server,
  729. // though not sure how to do this reliably (domain aliases, IP vs. domain, etc.)
  730. UnicodeString RedirectPath = ParsePathFromUrl(RedirectUrl);
  731. Result =
  732. !RedirectPath.IsEmpty() &&
  733. (RedirectPath != OriginalPath);
  734. if (Result)
  735. {
  736. Path = RedirectPath;
  737. }
  738. }
  739. return Result;
  740. }
  741. //---------------------------------------------------------------------------
  742. void __fastcall TWebDAVFileSystem::ReadDirectory(TRemoteFileList * FileList)
  743. {
  744. UnicodeString Path = DirectoryPath(FileList->Directory);
  745. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  746. int NeonStatus = ReadDirectoryInternal(Path, FileList);
  747. if (IsValidRedirect(NeonStatus, Path))
  748. {
  749. NeonStatus = ReadDirectoryInternal(Path, FileList);
  750. }
  751. CheckStatus(NeonStatus);
  752. }
  753. //---------------------------------------------------------------------------
  754. void __fastcall TWebDAVFileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
  755. TRemoteFile *& /*File*/)
  756. {
  757. // we never set SymLink flag, so we should never get here
  758. DebugFail();
  759. }
  760. //---------------------------------------------------------------------------
  761. void __fastcall TWebDAVFileSystem::ReadFile(const UnicodeString FileName,
  762. TRemoteFile *& File)
  763. {
  764. CustomReadFile(FileName, File, NULL);
  765. }
  766. //---------------------------------------------------------------------------
  767. void TWebDAVFileSystem::NeonPropsResult(
  768. void * UserData, const ne_uri * Uri, const ne_prop_result_set * Results)
  769. {
  770. UnicodeString Path = PathUnescape(Uri->path);
  771. TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
  772. if (Data.FileList != NULL)
  773. {
  774. UnicodeString FileListPath = Data.FileSystem->AbsolutePath(Data.FileList->Directory, false);
  775. if (UnixSamePath(Path, FileListPath))
  776. {
  777. Path = UnixIncludeTrailingBackslash(UnixIncludeTrailingBackslash(Path) + PARENTDIRECTORY);
  778. }
  779. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  780. File->Terminal = Data.FileSystem->FTerminal;
  781. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  782. Data.FileList->AddFile(File.release());
  783. }
  784. else
  785. {
  786. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  787. }
  788. }
  789. //---------------------------------------------------------------------------
  790. const char * __fastcall TWebDAVFileSystem::GetProp(
  791. const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
  792. {
  793. ne_propname Prop;
  794. Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
  795. Prop.name = Name;
  796. return ne_propset_value(Results, &Prop);
  797. }
  798. //---------------------------------------------------------------------------
  799. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  800. const UnicodeString & Path, const ne_prop_result_set * Results)
  801. {
  802. File->FullFileName = UnixExcludeTrailingBackslash(Path);
  803. // Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
  804. // But not all, for example OneDrive does not (it did in the past).
  805. bool Collection = (File->FullFileName != Path);
  806. File->FileName = UnixExtractFileName(File->FullFileName);
  807. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  808. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  809. if (ContentLength != NULL)
  810. {
  811. File->Size = StrToInt64Def(ContentLength, 0);
  812. }
  813. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  814. // We've seen a server (t=24891) that does not set "getlastmodified" for the "this" folder entry.
  815. if (LastModified != NULL)
  816. {
  817. char WeekDay[4] = { L'\0' };
  818. int Year = 0;
  819. char MonthStr[4] = { L'\0' };
  820. int Day = 0;
  821. int Hour = 0;
  822. int Min = 0;
  823. int Sec = 0;
  824. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  825. // Keep is sync with S3
  826. int Filled =
  827. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  828. // we need at least a complete date
  829. if (Filled >= 4)
  830. {
  831. int Month = ParseShortEngMonthName(MonthStr);
  832. if (Month >= 1)
  833. {
  834. TDateTime Modification =
  835. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  836. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  837. File->Modification = ConvertTimestampFromUTC(Modification);
  838. File->ModificationFmt = mfFull;
  839. }
  840. else
  841. {
  842. File->ModificationFmt = mfNone;
  843. }
  844. }
  845. else
  846. {
  847. File->ModificationFmt = mfNone;
  848. }
  849. }
  850. // optimization
  851. if (!Collection)
  852. {
  853. // See a comment at the Collection declaration.
  854. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  855. if (ResourceType != NULL)
  856. {
  857. // property has XML value
  858. UnicodeString AResourceType = ResourceType;
  859. // this is very poor parsing
  860. if (ContainsText(ResourceType, L"<DAV:collection"))
  861. {
  862. Collection = true;
  863. }
  864. }
  865. }
  866. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  867. // this is MS extension (draft-hopmann-collection-props-00)
  868. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  869. if (IsHidden != NULL)
  870. {
  871. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  872. }
  873. const char * Owner = GetProp(Results, PROP_OWNER);
  874. if (Owner != NULL)
  875. {
  876. File->Owner.Name = Owner;
  877. }
  878. const char * DisplayName = GetProp(Results, PROP_DISPLAY_NAME);
  879. if (DisplayName != NULL)
  880. {
  881. File->DisplayName = StrFromNeon(DisplayName);
  882. // OneDrive caret escaping (we could do this for all files, but let's limit the scope for now).
  883. // In *file* PROPFIND response, the # (and other symbols like comma or plus) is not escaped at all
  884. // (while in directory listing, they are caret-escaped),
  885. // so if we see one in the display name, take the name from there.
  886. // * and % won't help, as OneDrive seem to have bug with % as the end of the filename,
  887. // and the * (and others) is removed from file names.
  888. if (FOneDrive && (ContainsText(File->FileName, L"^") || (wcspbrk(File->DisplayName.c_str(), L"&,+#[]%*") != NULL)))
  889. {
  890. File->FileName = File->DisplayName;
  891. File->FullFileName = UnixCombinePaths(UnixExtractFileDir(File->FullFileName), File->FileName);
  892. }
  893. }
  894. const UnicodeString RightsDelimiter(L", ");
  895. UnicodeString HumanRights;
  896. // Proprietary property of mod_dav
  897. // http://www.webdav.org/mod_dav/#imp
  898. const char * Executable = GetProp(Results, PROP_EXECUTABLE, MODDAV_PROP_NAMESPACE);
  899. if (Executable != NULL)
  900. {
  901. if (strcmp(Executable, "T") == NULL)
  902. {
  903. UnicodeString ExecutableRights;
  904. // The "gear" character is supported since Windows 8
  905. if (IsWin8())
  906. {
  907. ExecutableRights = L"\u2699";
  908. }
  909. else
  910. {
  911. ExecutableRights = LoadStr(EXECUTABLE);
  912. }
  913. AddToList(HumanRights, ExecutableRights, RightsDelimiter);
  914. }
  915. }
  916. struct ne_lock * Lock = static_cast<struct ne_lock *>(ne_propset_private(Results));
  917. if ((Lock != NULL) && (Lock->token != NULL))
  918. {
  919. UnicodeString Owner;
  920. if (Lock->owner != NULL)
  921. {
  922. Owner = StrFromNeon(Lock->owner).Trim();
  923. }
  924. UnicodeString LockRights;
  925. if (IsWin8())
  926. {
  927. // The "lock" character is supported since Windows 8
  928. LockRights = L"\uD83D\uDD12" + Owner;
  929. }
  930. else
  931. {
  932. LockRights = LoadStr(LOCKED);
  933. if (!Owner.IsEmpty())
  934. {
  935. LockRights = FORMAT(L"%s (%s)", (LockRights, Owner));
  936. }
  937. }
  938. AddToList(HumanRights, LockRights, RightsDelimiter);
  939. }
  940. File->HumanRights = HumanRights;
  941. }
  942. //---------------------------------------------------------------------------
  943. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  944. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  945. {
  946. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  947. TReadFileData Data;
  948. Data.FileSystem = this;
  949. Data.File = AFile.get();
  950. Data.FileList = NULL;
  951. ClearNeonError();
  952. int Result =
  953. ne_simple_propfind(FNeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  954. NeonPropsResult, &Data);
  955. if (Result == NE_OK)
  956. {
  957. File = AFile.release();
  958. }
  959. return Result;
  960. }
  961. //---------------------------------------------------------------------------
  962. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  963. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  964. {
  965. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  966. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  967. if (IsValidRedirect(NeonStatus, FileName))
  968. {
  969. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  970. }
  971. CheckStatus(NeonStatus);
  972. }
  973. //---------------------------------------------------------------------------
  974. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  975. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  976. {
  977. Action.Recursive();
  978. ClearNeonError();
  979. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  980. RawByteString Path = PathToNeon(FilePath(File));
  981. // WebDAV does not allow non-recursive delete:
  982. // RFC 4918, section 9.6.1:
  983. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  984. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  985. CheckStatus(ne_delete(FNeonSession, Path.c_str()));
  986. // The lock is removed with the file, but if a file with the same name gets created,
  987. // we would try to use obsoleted lock token with it, what the server would reject
  988. // (mod_dav returns "412 Precondition Failed")
  989. DiscardLock(Path);
  990. }
  991. //---------------------------------------------------------------------------
  992. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  993. const UnicodeString & NewName)
  994. {
  995. // 0 = no overwrite
  996. return ne_move(FNeonSession, 0, PathToNeon(FileName), PathToNeon(NewName));
  997. }
  998. //---------------------------------------------------------------------------
  999. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1000. const UnicodeString NewName)
  1001. {
  1002. ClearNeonError();
  1003. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1004. UnicodeString Path = FileName;
  1005. int NeonStatus = RenameFileInternal(Path, NewName);
  1006. if (IsValidRedirect(NeonStatus, Path))
  1007. {
  1008. NeonStatus = RenameFileInternal(Path, NewName);
  1009. }
  1010. CheckStatus(NeonStatus);
  1011. // See a comment in DeleteFile
  1012. DiscardLock(PathToNeon(Path));
  1013. }
  1014. //---------------------------------------------------------------------------
  1015. int __fastcall TWebDAVFileSystem::CopyFileInternal(const UnicodeString & FileName,
  1016. const UnicodeString & NewName)
  1017. {
  1018. // 0 = no overwrite
  1019. return ne_copy(FNeonSession, 0, NE_DEPTH_INFINITE, PathToNeon(FileName), PathToNeon(NewName));
  1020. }
  1021. //---------------------------------------------------------------------------
  1022. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1023. const UnicodeString NewName)
  1024. {
  1025. ClearNeonError();
  1026. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1027. UnicodeString Path = FileName;
  1028. int NeonStatus = CopyFileInternal(Path, NewName);
  1029. if (IsValidRedirect(NeonStatus, Path))
  1030. {
  1031. NeonStatus = CopyFileInternal(Path, NewName);
  1032. }
  1033. CheckStatus(NeonStatus);
  1034. }
  1035. //---------------------------------------------------------------------------
  1036. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
  1037. {
  1038. ClearNeonError();
  1039. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1040. CheckStatus(ne_mkcol(FNeonSession, PathToNeon(DirName)));
  1041. }
  1042. //---------------------------------------------------------------------------
  1043. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  1044. const UnicodeString PointTo, bool /*Symbolic*/)
  1045. {
  1046. DebugFail();
  1047. }
  1048. //---------------------------------------------------------------------------
  1049. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1050. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  1051. TChmodSessionAction & /*Action*/)
  1052. {
  1053. DebugFail();
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1057. {
  1058. DebugFail();
  1059. return false;
  1060. }
  1061. //---------------------------------------------------------------------------
  1062. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
  1063. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  1064. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  1065. {
  1066. DebugFail();
  1067. }
  1068. //---------------------------------------------------------------------------
  1069. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1070. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1071. TFileOperationProgressType * OperationProgress,
  1072. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1073. int Params)
  1074. {
  1075. // all = "yes to newer"
  1076. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1077. TQueryButtonAlias Aliases[3];
  1078. Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1079. Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1080. Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1081. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1082. QueryParams.Aliases = Aliases;
  1083. QueryParams.AliasesCount = LENOF(Aliases);
  1084. unsigned int Answer;
  1085. {
  1086. TSuspendFileOperationProgress Suspend(OperationProgress);
  1087. Answer =
  1088. FTerminal->ConfirmFileOverwrite(
  1089. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1090. ReverseOperationSide(OperationProgress->Side),
  1091. CopyParam, Params, OperationProgress);
  1092. }
  1093. switch (Answer)
  1094. {
  1095. case qaYes:
  1096. // noop
  1097. break;
  1098. case qaNo:
  1099. throw ESkipFile();
  1100. default:
  1101. DebugFail();
  1102. case qaCancel:
  1103. OperationProgress->SetCancelAtLeast(csCancel);
  1104. Abort();
  1105. break;
  1106. }
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1110. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1111. {
  1112. DebugFail();
  1113. }
  1114. //---------------------------------------------------------------------------
  1115. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1116. TCaptureOutputEvent /*OutputEvent*/)
  1117. {
  1118. DebugFail();
  1119. }
  1120. //---------------------------------------------------------------------------
  1121. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1122. {
  1123. return NULL;
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. void TWebDAVFileSystem::NeonQuotaResult(
  1127. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1128. {
  1129. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1130. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1131. if (Value != NULL)
  1132. {
  1133. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1134. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1135. if (Value != NULL)
  1136. {
  1137. SpaceAvailable.BytesAvailableToUser =
  1138. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1139. }
  1140. }
  1141. }
  1142. //---------------------------------------------------------------------------
  1143. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1144. TSpaceAvailable & ASpaceAvailable)
  1145. {
  1146. // RFC4331: https://tools.ietf.org/html/rfc4331
  1147. // This is known to be supported by:
  1148. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1149. // unconditionally, even when not explicitly requested)
  1150. // Server: Apache/2.2.17 (Fedora)
  1151. // X-Powered-By: PHP/5.5.7
  1152. // X-DAV-Powered-By: OpenDrive
  1153. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1154. // IT Hit WebDAV Server:
  1155. // Server: Microsoft-HTTPAPI/1.0
  1156. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1157. // Yandex disk:
  1158. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1159. // Server: MochiWeb/1.0
  1160. // OneDrive:
  1161. // it sends the properties unconditionally, even when not explicitly requested
  1162. UnicodeString APath = DirectoryPath(Path);
  1163. ne_propname QuotaProps[3];
  1164. memset(QuotaProps, 0, sizeof(QuotaProps));
  1165. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1166. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1167. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1168. QuotaProps[1].name = PROP_QUOTA_USED;
  1169. QuotaProps[2].nspace = NULL;
  1170. QuotaProps[2].name = NULL;
  1171. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1172. CheckStatus(
  1173. ne_simple_propfind(FNeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1174. NeonQuotaResult, &ASpaceAvailable));
  1175. }
  1176. //---------------------------------------------------------------------------
  1177. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1178. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1179. int Params, TFileOperationProgressType * OperationProgress,
  1180. TOnceDoneOperation & OnceDoneOperation)
  1181. {
  1182. Params &= ~cpAppend;
  1183. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfPreCreateDir, OnceDoneOperation);
  1184. }
  1185. //---------------------------------------------------------------------------
  1186. void __fastcall TWebDAVFileSystem::Source(
  1187. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1188. const TCopyParamType * CopyParam, int Params,
  1189. TFileOperationProgressType * OperationProgress, unsigned int /*Flags*/,
  1190. TUploadSessionAction & Action, bool & ChildError)
  1191. {
  1192. int FD = -1;
  1193. try
  1194. {
  1195. UnicodeString DestFullName = TargetDir + DestFileName;
  1196. TRemoteFile * RemoteFile = NULL;
  1197. try
  1198. {
  1199. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1200. FIgnoreAuthenticationFailure = iafWaiting;
  1201. // this should not throw
  1202. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1203. }
  1204. catch (...)
  1205. {
  1206. if (!FTerminal->Active)
  1207. {
  1208. throw;
  1209. }
  1210. }
  1211. if (RemoteFile != NULL)
  1212. {
  1213. TOverwriteFileParams FileParams;
  1214. FileParams.SourceSize = Handle.Size;
  1215. FileParams.SourceTimestamp = Handle.Modification;
  1216. FileParams.DestSize = RemoteFile->Size;
  1217. FileParams.DestTimestamp = RemoteFile->Modification;
  1218. delete RemoteFile;
  1219. ConfirmOverwrite(Handle.FileName, DestFileName, OperationProgress,
  1220. &FileParams, CopyParam, Params);
  1221. }
  1222. DestFullName = TargetDir + DestFileName;
  1223. // only now, we know the final destination
  1224. // (not really true as we do not support changing file name on overwrite dialog)
  1225. Action.Destination(DestFullName);
  1226. FUploadMimeType = Configuration->GetFileMimeType(DestFileName);
  1227. FILE_OPERATION_LOOP_BEGIN
  1228. {
  1229. SetFilePointer(Handle.Handle, 0, NULL, FILE_BEGIN);
  1230. FD = _open_osfhandle((intptr_t)Handle.Handle, O_BINARY);
  1231. if (FD < 0)
  1232. {
  1233. throw ESkipFile();
  1234. }
  1235. TAutoFlag UploadingFlag(FUploading);
  1236. ClearNeonError();
  1237. CheckStatus(ne_put(FNeonSession, PathToNeon(DestFullName), FD));
  1238. }
  1239. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (Handle.FileName)));
  1240. if (CopyParam->PreserveTime)
  1241. {
  1242. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1243. (StandardTimestamp(Handle.Modification))));
  1244. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1245. try
  1246. {
  1247. TDateTime ModificationUTC = ConvertTimestampToUTC(Handle.Modification);
  1248. TFormatSettings FormatSettings = GetEngFormatSettings();
  1249. UnicodeString LastModified =
  1250. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1251. UTF8String NeonLastModified(LastModified);
  1252. // second element is "NULL-terminating"
  1253. ne_proppatch_operation Operations[2];
  1254. memset(Operations, 0, sizeof(Operations));
  1255. ne_propname LastModifiedProp;
  1256. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1257. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1258. Operations[0].name = &LastModifiedProp;
  1259. Operations[0].type = ne_propset;
  1260. Operations[0].value = NeonLastModified.c_str();
  1261. int Status = ne_proppatch(FNeonSession, PathToNeon(DestFullName), Operations);
  1262. if (Status == NE_ERROR)
  1263. {
  1264. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1265. (GetNeonError())));
  1266. // Ignore errors as major WebDAV servers (like IIS), do not support
  1267. // changing getlastmodified.
  1268. // The only server we found that supports this is TradeMicro SafeSync.
  1269. // But it announces itself as "Server: Apache",
  1270. // so it's not reliable to autodetect the support.
  1271. // Microsoft Office alegedly uses <Win32LastModifiedTime>
  1272. // https://sabre.io/dav/clients/msoffice/
  1273. // Carot DAV does that too. But we do not know what server does support this.
  1274. TouchAction.Cancel();
  1275. }
  1276. else
  1277. {
  1278. CheckStatus(Status);
  1279. }
  1280. }
  1281. catch (Exception & E)
  1282. {
  1283. TouchAction.Rollback(&E);
  1284. ChildError = true;
  1285. throw;
  1286. }
  1287. }
  1288. }
  1289. __finally
  1290. {
  1291. if (FD >= 0)
  1292. {
  1293. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1294. // but it crashes code guard
  1295. _close(FD);
  1296. Handle.Dismiss();
  1297. }
  1298. }
  1299. }
  1300. //---------------------------------------------------------------------------
  1301. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1302. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1303. int Params, TFileOperationProgressType * OperationProgress,
  1304. TOnceDoneOperation & OnceDoneOperation)
  1305. {
  1306. Params &= ~cpAppend;
  1307. FTerminal->DoCopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfNone, OnceDoneOperation);
  1308. }
  1309. //---------------------------------------------------------------------------
  1310. void TWebDAVFileSystem::NeonCreateRequest(
  1311. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1312. {
  1313. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1314. ne_set_request_private(Request, SESSION_FS_KEY, FileSystem);
  1315. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1316. FileSystem->FNtlmAuthenticationFailed = false;
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. void TWebDAVFileSystem::NeonPreSend(
  1320. ne_request * Request, void * UserData, ne_buffer * Header)
  1321. {
  1322. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1323. FileSystem->FAuthorizationProtocol = L"";
  1324. UnicodeString HeaderBuf(StrFromNeon(AnsiString(Header->data, Header->used)));
  1325. const UnicodeString AuthorizationHeaderName(L"Authorization:");
  1326. int P = HeaderBuf.Pos(AuthorizationHeaderName);
  1327. if (P > 0)
  1328. {
  1329. P += AuthorizationHeaderName.Length();
  1330. int P2 = PosEx(L"\n", HeaderBuf, P);
  1331. if (DebugAlwaysTrue(P2 > 0))
  1332. {
  1333. UnicodeString AuthorizationHeader = HeaderBuf.SubString(P, P2 - P).Trim();
  1334. FileSystem->FAuthorizationProtocol = CutToChar(AuthorizationHeader, L' ', false);
  1335. FileSystem->FLastAuthorizationProtocol = FileSystem->FAuthorizationProtocol;
  1336. }
  1337. }
  1338. if (FileSystem->FDownloading)
  1339. {
  1340. // Needed by IIS server to make it download source code, not code output,
  1341. // and mainly to even allow downloading file with unregistered extensions.
  1342. // Without it files like .001 return 404 (Not found) HTTP code.
  1343. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wdv/e37a9543-9290-4843-8c04-66457c60fa0a
  1344. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wdvse/501879f9-3875-4d7a-ab88-3cecab440034
  1345. // http://lists.manyfish.co.uk/pipermail/neon/2012-April/000582.html
  1346. // It's also supported by Oracle server:
  1347. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1348. // We do not know yet of any server that fails when the header is used,
  1349. // so it's added unconditionally.
  1350. ne_buffer_zappend(Header, "Translate: f\r\n");
  1351. }
  1352. const UnicodeString ContentTypeHeaderPrefix(L"Content-Type: ");
  1353. if (FileSystem->FTerminal->Log->Logging)
  1354. {
  1355. const char * Buffer;
  1356. size_t Size;
  1357. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1358. {
  1359. // all neon request types that use ne_add_request_header
  1360. // use XML content-type, so it's text-based
  1361. DebugAssert(ContainsStr(HeaderBuf, ContentTypeHeaderPrefix + NE_XML_MEDIA_TYPE));
  1362. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1363. }
  1364. }
  1365. if (FileSystem->FUploading)
  1366. {
  1367. ne_set_request_body_provider_pre(Request,
  1368. FileSystem->NeonUploadBodyProvider, FileSystem);
  1369. if (!FileSystem->FUploadMimeType.IsEmpty())
  1370. {
  1371. UnicodeString ContentTypeHeader = ContentTypeHeaderPrefix + FileSystem->FUploadMimeType + L"\r\n";
  1372. ne_buffer_zappend(Header, AnsiString(ContentTypeHeader).c_str());
  1373. }
  1374. }
  1375. FileSystem->FResponse = L"";
  1376. }
  1377. //---------------------------------------------------------------------------
  1378. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1379. const ne_status * /*Status*/)
  1380. {
  1381. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1382. if (!FileSystem->FResponse.IsEmpty())
  1383. {
  1384. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1385. }
  1386. return NE_OK;
  1387. }
  1388. //---------------------------------------------------------------------------
  1389. bool __fastcall TWebDAVFileSystem::IsNtlmAuthentication()
  1390. {
  1391. return
  1392. SameText(FAuthorizationProtocol, L"NTLM") ||
  1393. SameText(FAuthorizationProtocol, L"Negotiate");
  1394. }
  1395. //---------------------------------------------------------------------------
  1396. void __fastcall TWebDAVFileSystem::HttpAuthenticationFailed()
  1397. {
  1398. // NTLM/GSSAPI failed
  1399. if (IsNtlmAuthentication())
  1400. {
  1401. if (FNtlmAuthenticationFailed)
  1402. {
  1403. // Next time do not try Negotiate (NTLM/GSSAPI),
  1404. // otherwise we end up in an endless loop.
  1405. // If the server returns all other challenges in the response, removing the Negotiate
  1406. // protocol will itself ensure that other protocols are tried (we haven't seen this behaviour).
  1407. // IIS will return only Negotiate response if the request was Negotiate, so there's no fallback.
  1408. // We have to retry with a fresh request. That's what FAuthenticationRetry does.
  1409. FTerminal->LogEvent(FORMAT(L"%s challenge failed, will try different challenge", (FAuthorizationProtocol)));
  1410. ne_remove_server_auth(FNeonSession);
  1411. NeonAddAuthentiation(false);
  1412. FAuthenticationRetry = true;
  1413. }
  1414. else
  1415. {
  1416. // The first 401 is expected, the server is using it to send WWW-Authenticate header with data.
  1417. FNtlmAuthenticationFailed = true;
  1418. }
  1419. }
  1420. }
  1421. //---------------------------------------------------------------------------
  1422. void TWebDAVFileSystem::NeonPostHeaders(ne_request * /*Req*/, void * UserData, const ne_status * Status)
  1423. {
  1424. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1425. if (Status->code == HttpUnauthorized)
  1426. {
  1427. FileSystem->HttpAuthenticationFailed();
  1428. }
  1429. }
  1430. //---------------------------------------------------------------------------
  1431. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1432. {
  1433. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1434. ssize_t Result;
  1435. if (FileSystem->CancelTransfer())
  1436. {
  1437. Result = -1;
  1438. }
  1439. else
  1440. {
  1441. Result = 1;
  1442. }
  1443. return Result;
  1444. }
  1445. //---------------------------------------------------------------------------
  1446. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1447. {
  1448. const char * Value = ne_get_response_header(Request, Name);
  1449. if (Value != NULL)
  1450. {
  1451. AddToList(List, StrFromNeon(Value), L"; ");
  1452. }
  1453. }
  1454. //---------------------------------------------------------------------------
  1455. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1456. {
  1457. DebugAssert(UserData == Request);
  1458. TWebDAVFileSystem * FileSystem =
  1459. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1460. bool AuthenticationFailureCode = (Status->code == HttpUnauthorized);
  1461. bool PasswordAuthenticationFailed = AuthenticationFailureCode && FileSystem->FAuthenticationRequested;
  1462. bool AuthenticationFailed = PasswordAuthenticationFailed || (AuthenticationFailureCode && FileSystem->IsNtlmAuthentication());
  1463. bool AuthenticationNeeded = AuthenticationFailureCode && !AuthenticationFailed;
  1464. if (FileSystem->FInitialHandshake)
  1465. {
  1466. UnicodeString Line;
  1467. if (AuthenticationNeeded)
  1468. {
  1469. Line = LoadStr(STATUS_AUTHENTICATE);
  1470. }
  1471. else if (AuthenticationFailed)
  1472. {
  1473. Line = LoadStr(FTP_ACCESS_DENIED);
  1474. }
  1475. else if (Status->klass == 2)
  1476. {
  1477. Line = LoadStr(STATUS_AUTHENTICATED);
  1478. }
  1479. if (!Line.IsEmpty())
  1480. {
  1481. FileSystem->FTerminal->Information(Line, true);
  1482. }
  1483. UnicodeString RemoteSystem;
  1484. // Used by IT Hit WebDAV Server:
  1485. // Server: Microsoft-HTTPAPI/1.0
  1486. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1487. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1488. // Used by OpenDrive:
  1489. // Server: Apache/2.2.17 (Fedora)
  1490. // X-Powered-By: PHP/5.5.7
  1491. // X-DAV-Powered-By: OpenDrive
  1492. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1493. // Used by IIS:
  1494. // Server: Microsoft-IIS/8.5
  1495. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1496. // Not really useful.
  1497. // Can be e.g. "PleskLin"
  1498. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1499. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1500. }
  1501. // When we explicitly fail authentication of request
  1502. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1503. // neon resets its internal password store and tries the next request
  1504. // without calling our authentication hook first
  1505. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1506. // what likely fails, but we do not want to reset out password
  1507. // (as it was not even tried yet for this request).
  1508. if (PasswordAuthenticationFailed)
  1509. {
  1510. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1511. {
  1512. FileSystem->FPassword = RawByteString();
  1513. }
  1514. else
  1515. {
  1516. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1517. }
  1518. }
  1519. return ne_accept_2xx(UserData, Request, Status);
  1520. }
  1521. //---------------------------------------------------------------------------
  1522. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1523. {
  1524. bool Result = false;
  1525. if ((FUploading || FDownloading) &&
  1526. (FTerminal->OperationProgress != NULL) &&
  1527. (FTerminal->OperationProgress->Cancel != csContinue))
  1528. {
  1529. if (FTerminal->OperationProgress->ClearCancelFile())
  1530. {
  1531. FSkipped = true;
  1532. }
  1533. else
  1534. {
  1535. FCancelled = true;
  1536. }
  1537. Result = true;
  1538. }
  1539. return Result;
  1540. }
  1541. //---------------------------------------------------------------------------
  1542. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1543. {
  1544. ne_request * Request = static_cast<ne_request *>(UserData);
  1545. TWebDAVFileSystem * FileSystem =
  1546. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1547. if (FileSystem->FTerminal->Log->Logging)
  1548. {
  1549. ne_content_type ContentType;
  1550. if (ne_get_content_type(Request, &ContentType) == 0)
  1551. {
  1552. // The main point of the content-type check was to exclude
  1553. // GET responses (with file contents).
  1554. // But this won't work when downloading text files that have text
  1555. // content type on their own, hence the additional not-downloading test.
  1556. if (!FileSystem->FDownloading &&
  1557. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1558. media_type_is_xml(&ContentType)))
  1559. {
  1560. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1561. FileSystem->FResponse += Content;
  1562. }
  1563. ne_free(ContentType.value);
  1564. }
  1565. }
  1566. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1567. return Result;
  1568. }
  1569. //---------------------------------------------------------------------------
  1570. void __fastcall TWebDAVFileSystem::Sink(
  1571. const UnicodeString & FileName, const TRemoteFile * File,
  1572. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1573. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1574. unsigned int /*Flags*/, TDownloadSessionAction & Action)
  1575. {
  1576. UnicodeString DestFullName = TargetDir + DestFileName;
  1577. if (FileExists(ApiPath(DestFullName)))
  1578. {
  1579. __int64 Size;
  1580. __int64 MTime;
  1581. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL, NULL, NULL, &MTime, NULL, &Size);
  1582. TOverwriteFileParams FileParams;
  1583. FileParams.SourceSize = File->Size;
  1584. FileParams.SourceTimestamp = File->Modification;
  1585. FileParams.DestSize = Size;
  1586. FileParams.DestTimestamp = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1587. ConfirmOverwrite(FileName, DestFileName, OperationProgress, &FileParams, CopyParam, Params);
  1588. }
  1589. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1590. Action.Destination(ExpandedDestFullName);
  1591. FILE_OPERATION_LOOP_BEGIN
  1592. {
  1593. HANDLE LocalHandle;
  1594. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress, &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1595. {
  1596. throw ESkipFile();
  1597. }
  1598. bool DeleteLocalFile = true;
  1599. int FD = -1;
  1600. try
  1601. {
  1602. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1603. if (FD < 0)
  1604. {
  1605. throw ESkipFile();
  1606. }
  1607. TAutoFlag DownloadingFlag(FDownloading);
  1608. ClearNeonError();
  1609. CheckStatus(ne_get(FNeonSession, PathToNeon(FileName), FD));
  1610. DeleteLocalFile = false;
  1611. if (CopyParam->PreserveTime)
  1612. {
  1613. FTerminal->UpdateTargetTime(LocalHandle, File->Modification, FTerminal->SessionData->DSTMode);
  1614. }
  1615. }
  1616. __finally
  1617. {
  1618. if (FD >= 0)
  1619. {
  1620. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1621. // but it crashes code guard
  1622. _close(FD);
  1623. }
  1624. else
  1625. {
  1626. CloseHandle(LocalHandle);
  1627. }
  1628. if (DeleteLocalFile)
  1629. {
  1630. FILE_OPERATION_LOOP_BEGIN
  1631. {
  1632. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestFullName)));
  1633. }
  1634. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestFullName)));
  1635. }
  1636. }
  1637. }
  1638. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1639. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  1640. }
  1641. //---------------------------------------------------------------------------
  1642. // Similar to TS3FileSystem::VerifyCertificate
  1643. bool TWebDAVFileSystem::VerifyCertificate(TNeonCertificateData Data, bool Aux)
  1644. {
  1645. FSessionInfo.CertificateFingerprintSHA1 = Data.FingerprintSHA1;
  1646. FSessionInfo.CertificateFingerprintSHA256 = Data.FingerprintSHA256;
  1647. bool Result;
  1648. if (FTerminal->SessionData->FingerprintScan)
  1649. {
  1650. Result = false;
  1651. }
  1652. else
  1653. {
  1654. FTerminal->LogEvent(0, CertificateVerificationMessage(Data));
  1655. UnicodeString SiteKey = TSessionData::FormatSiteKey(FHostName, FPortNumber);
  1656. Result =
  1657. FTerminal->VerifyCertificate(
  1658. HttpsCertificateStorageKey, SiteKey, Data.FingerprintSHA1, Data.FingerprintSHA256, Data.Subject, Data.Failures);
  1659. if (Result)
  1660. {
  1661. FSessionInfo.CertificateVerifiedManually = true;
  1662. }
  1663. else
  1664. {
  1665. UnicodeString Message;
  1666. Result = NeonWindowsValidateCertificateWithMessage(Data, Message);
  1667. FTerminal->LogEvent(0, Message);
  1668. }
  1669. FSessionInfo.Certificate = CertificateSummary(Data, FHostName);
  1670. if (!Result)
  1671. {
  1672. if (FTerminal->ConfirmCertificate(FSessionInfo, Data.Failures, HttpsCertificateStorageKey, !Aux))
  1673. {
  1674. Result = true;
  1675. FSessionInfo.CertificateVerifiedManually = true;
  1676. }
  1677. }
  1678. if (Result && !Aux)
  1679. {
  1680. CollectTLSSessionInfo();
  1681. }
  1682. }
  1683. return Result;
  1684. }
  1685. //------------------------------------------------------------------------------
  1686. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  1687. {
  1688. // See also TFTPFileSystem::Open().
  1689. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  1690. // can be closed at the time we need it in CollectUsage().
  1691. UnicodeString Message = NeonTlsSessionInfo(FNeonSession, FSessionInfo, FTlsVersionStr);
  1692. FTerminal->LogEvent(0, Message);
  1693. }
  1694. //------------------------------------------------------------------------------
  1695. // A neon-session callback to validate the SSL certificate when the CA
  1696. // is unknown (e.g. a self-signed cert), or there are other SSL
  1697. // certificate problems.
  1698. int TWebDAVFileSystem::DoNeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate, bool Aux)
  1699. {
  1700. TNeonCertificateData Data;
  1701. RetrieveNeonCertificateData(Failures, Certificate, Data);
  1702. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1703. return FileSystem->VerifyCertificate(Data, Aux) ? NE_OK : NE_ERROR;
  1704. }
  1705. //------------------------------------------------------------------------------
  1706. int TWebDAVFileSystem::NeonServerSSLCallbackMain(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1707. {
  1708. return DoNeonServerSSLCallback(UserData, Failures, Certificate, false);
  1709. }
  1710. //------------------------------------------------------------------------------
  1711. int TWebDAVFileSystem::NeonServerSSLCallbackAux(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1712. {
  1713. return DoNeonServerSSLCallback(UserData, Failures, Certificate, true);
  1714. }
  1715. //------------------------------------------------------------------------------
  1716. void TWebDAVFileSystem::NeonProvideClientCert(void * UserData, ne_session * Sess,
  1717. const ne_ssl_dname * const * /*DNames*/, int /*DNCount*/)
  1718. {
  1719. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1720. FileSystem->FTerminal->LogEvent(LoadStr(NEED_CLIENT_CERTIFICATE));
  1721. X509 * Certificate;
  1722. EVP_PKEY * PrivateKey;
  1723. if (FileSystem->FTerminal->LoadTlsCertificate(Certificate, PrivateKey))
  1724. {
  1725. ne_ssl_client_cert * NeonCertificate = ne_ssl_clicert_create(Certificate, PrivateKey);
  1726. ne_ssl_set_clicert(Sess, NeonCertificate);
  1727. ne_ssl_clicert_free(NeonCertificate);
  1728. }
  1729. }
  1730. //------------------------------------------------------------------------------
  1731. int TWebDAVFileSystem::NeonRequestAuth(
  1732. void * UserData, const char * Realm, int Attempt, char * UserName, char * Password)
  1733. {
  1734. DebugUsedParam(Realm);
  1735. DebugUsedParam(Attempt);
  1736. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1737. TTerminal * Terminal = FileSystem->FTerminal;
  1738. TSessionData * SessionData = Terminal->SessionData;
  1739. bool Result = true;
  1740. // will ask for username only once
  1741. if (FileSystem->FUserName.IsEmpty())
  1742. {
  1743. if (!SessionData->UserName.IsEmpty())
  1744. {
  1745. FileSystem->FUserName = SessionData->UserNameExpanded;
  1746. }
  1747. else
  1748. {
  1749. Terminal->LogEvent(L"Username prompt");
  1750. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  1751. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  1752. {
  1753. // note that we never get here actually
  1754. Result = false;
  1755. }
  1756. }
  1757. }
  1758. UnicodeString APassword;
  1759. if (Result)
  1760. {
  1761. // Some servers (Gallery2 on discontinued g2.pixi.me)
  1762. // return authentication error (401) on PROPFIND request for
  1763. // non-existing files.
  1764. // When we already tried password before, do not try anymore.
  1765. // When we did not try password before (possible only when
  1766. // server does not require authentication for any previous request,
  1767. // such as when read access is not authenticated), try it now,
  1768. // but use special flag for the try, because when it fails
  1769. // we still want to try password for future requests (such as PUT).
  1770. if (!FileSystem->FPassword.IsEmpty())
  1771. {
  1772. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  1773. {
  1774. // Fail PROPFIND /nonexising request...
  1775. Result = false;
  1776. }
  1777. else
  1778. {
  1779. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  1780. }
  1781. }
  1782. else
  1783. {
  1784. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  1785. {
  1786. APassword = NormalizeString(SessionData->Password);
  1787. FileSystem->FStoredPasswordTried = true;
  1788. }
  1789. else
  1790. {
  1791. // Asking for password (or using configured password) the first time,
  1792. // and asking for password.
  1793. // Note that we never get false here actually
  1794. Terminal->LogEvent(L"Password prompt");
  1795. Result =
  1796. Terminal->PromptUser(
  1797. SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  1798. LoadStr(PASSWORD_PROMPT), false, NE_ABUFSIZ, APassword);
  1799. }
  1800. if (Result)
  1801. {
  1802. // While neon remembers the password on its own,
  1803. // we need to keep a copy in case neon store gets reset by
  1804. // 401 response to PROPFIND /nonexisting on G2, see above.
  1805. // Possibly we can do this for G2 servers only.
  1806. FileSystem->FPassword = Terminal->EncryptPassword(APassword);
  1807. }
  1808. }
  1809. }
  1810. if (Result)
  1811. {
  1812. strncpy(UserName, StrToNeon(FileSystem->FUserName), NE_ABUFSIZ);
  1813. strncpy(Password, StrToNeon(APassword), NE_ABUFSIZ);
  1814. }
  1815. FileSystem->FAuthenticationRequested = true;
  1816. return Result ? 0 : -1;
  1817. }
  1818. //------------------------------------------------------------------------------
  1819. void TWebDAVFileSystem::NeonNotifier(void * UserData, ne_session_status Status, const ne_session_status_info * StatusInfo)
  1820. {
  1821. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1822. TFileOperationProgressType * OperationProgress = FileSystem->FTerminal->OperationProgress;
  1823. // We particularly have to filter out response to "put" request,
  1824. // handling that would reset the upload progress back to low number (response is small).
  1825. if (((FileSystem->FUploading && (Status == ne_status_sending)) ||
  1826. (FileSystem->FDownloading && (Status == ne_status_recving))) &&
  1827. DebugAlwaysTrue(OperationProgress != NULL))
  1828. {
  1829. __int64 Progress = StatusInfo->sr.progress;
  1830. __int64 Diff = Progress - OperationProgress->TransferredSize;
  1831. if (Diff > 0)
  1832. {
  1833. OperationProgress->ThrottleToCPSLimit(static_cast<unsigned long>(Diff));
  1834. }
  1835. __int64 Total = StatusInfo->sr.total;
  1836. // Total size unknown
  1837. if (Total < 0)
  1838. {
  1839. if (Diff >= 0)
  1840. {
  1841. OperationProgress->AddTransferred(Diff);
  1842. }
  1843. else
  1844. {
  1845. // Session total has been reset. A new stream started
  1846. OperationProgress->AddTransferred(Progress);
  1847. }
  1848. }
  1849. else
  1850. {
  1851. OperationProgress->SetTransferSize(Total);
  1852. OperationProgress->AddTransferred(Diff);
  1853. }
  1854. }
  1855. }
  1856. //------------------------------------------------------------------------------
  1857. void TWebDAVFileSystem::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  1858. {
  1859. SetupSsl(Ssl, FTerminal->SessionData->MinTlsVersion, FTerminal->SessionData->MaxTlsVersion);
  1860. }
  1861. //---------------------------------------------------------------------------
  1862. void __fastcall TWebDAVFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  1863. {
  1864. // NOOP
  1865. }
  1866. //---------------------------------------------------------------------------
  1867. void __fastcall TWebDAVFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * File)
  1868. {
  1869. ClearNeonError();
  1870. struct ne_lock * Lock = ne_lock_create();
  1871. try
  1872. {
  1873. Lock->uri.path = ne_strdup(PathToNeon(FilePath(File)));
  1874. Lock->depth = NE_DEPTH_INFINITE;
  1875. Lock->timeout = NE_TIMEOUT_INFINITE;
  1876. Lock->owner = ne_strdup(StrToNeon(FTerminal->UserName));
  1877. CheckStatus(ne_lock(FNeonSession, Lock));
  1878. {
  1879. TGuard Guard(FNeonLockStoreSection);
  1880. RequireLockStore();
  1881. ne_lockstore_add(FNeonLockStore, Lock);
  1882. }
  1883. // ownership passed
  1884. Lock = NULL;
  1885. }
  1886. __finally
  1887. {
  1888. if (Lock != NULL)
  1889. {
  1890. ne_lock_destroy(Lock);
  1891. }
  1892. }
  1893. }
  1894. //---------------------------------------------------------------------------
  1895. void __fastcall TWebDAVFileSystem::RequireLockStore()
  1896. {
  1897. // Create store only when needed,
  1898. // to limit the use of cross-thread code in UpdateFromMain
  1899. if (FNeonLockStore == NULL)
  1900. {
  1901. FNeonLockStore = ne_lockstore_create();
  1902. ne_lockstore_register(FNeonLockStore, FNeonSession);
  1903. }
  1904. }
  1905. //---------------------------------------------------------------------------
  1906. void TWebDAVFileSystem::LockResult(void * UserData, const struct ne_lock * Lock,
  1907. const ne_uri * /*Uri*/, const ne_status * /*Status*/)
  1908. {
  1909. // Is NULL on failure (Status is not NULL then)
  1910. if (Lock != NULL)
  1911. {
  1912. RawByteString & LockToken = *static_cast<RawByteString *>(UserData);
  1913. LockToken = Lock->token;
  1914. }
  1915. }
  1916. //---------------------------------------------------------------------------
  1917. struct ne_lock * __fastcall TWebDAVFileSystem::FindLock(const RawByteString & Path)
  1918. {
  1919. ne_uri Uri = {0};
  1920. Uri.path = Path.c_str();
  1921. return ne_lockstore_findbyuri(FNeonLockStore, &Uri);
  1922. }
  1923. //---------------------------------------------------------------------------
  1924. void __fastcall TWebDAVFileSystem::DiscardLock(const RawByteString & Path)
  1925. {
  1926. TGuard Guard(FNeonLockStoreSection);
  1927. if (FNeonLockStore != NULL)
  1928. {
  1929. struct ne_lock * Lock = FindLock(Path);
  1930. if (Lock != NULL)
  1931. {
  1932. ne_lockstore_remove(FNeonLockStore, Lock);
  1933. }
  1934. }
  1935. }
  1936. //---------------------------------------------------------------------------
  1937. void __fastcall TWebDAVFileSystem::UnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  1938. {
  1939. ClearNeonError();
  1940. struct ne_lock * Lock = ne_lock_create();
  1941. try
  1942. {
  1943. RawByteString Path = PathToNeon(FilePath(File));
  1944. RawByteString LockToken;
  1945. struct ne_lock * Lock = NULL;
  1946. {
  1947. TGuard Guard(FNeonLockStoreSection);
  1948. if (FNeonLockStore != NULL)
  1949. {
  1950. Lock = FindLock(Path);
  1951. }
  1952. }
  1953. // we are not aware of the file being locked,
  1954. // though it can be locked from another (previous and already closed)
  1955. // session, so query the server.
  1956. if (Lock == NULL)
  1957. {
  1958. CheckStatus(ne_lock_discover(FNeonSession, Path.c_str(), LockResult, &LockToken));
  1959. }
  1960. if ((Lock == NULL) && (LockToken.IsEmpty()))
  1961. {
  1962. throw Exception(FMTLOAD(NOT_LOCKED, (FileName)));
  1963. }
  1964. else
  1965. {
  1966. struct ne_lock * Unlock;
  1967. if (Lock == NULL)
  1968. {
  1969. DebugAssert(!LockToken.IsEmpty());
  1970. Unlock = ne_lock_create();
  1971. Unlock->uri.path = ne_strdup(Path.c_str());
  1972. Unlock->token = ne_strdup(LockToken.c_str());
  1973. }
  1974. else
  1975. {
  1976. Unlock = Lock;
  1977. }
  1978. CheckStatus(ne_unlock(FNeonSession, Unlock));
  1979. DiscardLock(Path);
  1980. }
  1981. }
  1982. __finally
  1983. {
  1984. ne_lock_destroy(Lock);
  1985. }
  1986. }
  1987. //---------------------------------------------------------------------------
  1988. void __fastcall TWebDAVFileSystem::UpdateFromMain(TCustomFileSystem * AMainFileSystem)
  1989. {
  1990. TWebDAVFileSystem * MainFileSystem = dynamic_cast<TWebDAVFileSystem *>(AMainFileSystem);
  1991. if (DebugAlwaysTrue(MainFileSystem != NULL))
  1992. {
  1993. TGuard Guard(FNeonLockStoreSection);
  1994. TGuard MainGuard(MainFileSystem->FNeonLockStoreSection);
  1995. if (FNeonLockStore != NULL)
  1996. {
  1997. struct ne_lock * Lock;
  1998. while ((Lock = ne_lockstore_first(FNeonLockStore)) != NULL)
  1999. {
  2000. ne_lockstore_remove(FNeonLockStore, Lock);
  2001. }
  2002. }
  2003. if (MainFileSystem->FNeonLockStore != NULL)
  2004. {
  2005. RequireLockStore();
  2006. struct ne_lock * Lock = ne_lockstore_first(MainFileSystem->FNeonLockStore);
  2007. while (Lock != NULL)
  2008. {
  2009. ne_lockstore_add(FNeonLockStore, ne_lock_copy(Lock));
  2010. Lock = ne_lockstore_next(MainFileSystem->FNeonLockStore);
  2011. }
  2012. }
  2013. }
  2014. }
  2015. //------------------------------------------------------------------------------
  2016. void __fastcall TWebDAVFileSystem::ClearCaches()
  2017. {
  2018. // noop
  2019. }
  2020. //---------------------------------------------------------------------------