WebDAVFileSystem.cpp 71 KB

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