WebDAVFileSystem.cpp 79 KB

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