WebDAVFileSystem.cpp 79 KB

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