WebDAVFileSystem.cpp 77 KB

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