WebDAVFileSystem.cpp 72 KB

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