WebDAVFileSystem.cpp 80 KB

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