WebDAVFileSystem.cpp 79 KB

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