WebDAVFileSystem.cpp 73 KB

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