WebDAVFileSystem.cpp 79 KB

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