WebDAVFileSystem.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654
  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. #include <openssl/ssl.h>
  33. //---------------------------------------------------------------------------
  34. #pragma package(smart_init)
  35. //---------------------------------------------------------------------------
  36. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  37. //---------------------------------------------------------------------------
  38. const int tfFirstLevel = 0x01;
  39. //---------------------------------------------------------------------------
  40. struct TSinkFileParams
  41. {
  42. UnicodeString TargetDir;
  43. const TCopyParamType * CopyParam;
  44. int Params;
  45. TFileOperationProgressType * OperationProgress;
  46. bool Skipped;
  47. unsigned int Flags;
  48. };
  49. //---------------------------------------------------------------------------
  50. struct TWebDAVCertificateData
  51. {
  52. UnicodeString Subject;
  53. UnicodeString Issuer;
  54. TDateTime ValidFrom;
  55. TDateTime ValidUntil;
  56. UnicodeString Fingerprint;
  57. AnsiString AsciiCert;
  58. int Failures;
  59. };
  60. //---------------------------------------------------------------------------
  61. #define SESSION_FS_KEY "filesystem"
  62. static const char CertificateStorageKey[] = "HttpsCertificates";
  63. static const UnicodeString CONST_WEBDAV_PROTOCOL_BASE_NAME = L"WebDAV";
  64. //---------------------------------------------------------------------------
  65. #define DAV_PROP_NAMESPACE "DAV:"
  66. #define MODDAV_PROP_NAMESPACE "http://apache.org/dav/props/"
  67. #define PROP_CONTENT_LENGTH "getcontentlength"
  68. #define PROP_LAST_MODIFIED "getlastmodified"
  69. #define PROP_RESOURCE_TYPE "resourcetype"
  70. #define PROP_HIDDEN "ishidden"
  71. #define PROP_QUOTA_AVAILABLE "quota-available-bytes"
  72. #define PROP_QUOTA_USED "quota-used-bytes"
  73. #define PROP_EXECUTABLE "executable"
  74. #define PROP_OWNER "owner"
  75. //---------------------------------------------------------------------------
  76. static std::unique_ptr<TCriticalSection> DebugSection(new TCriticalSection);
  77. static std::set<TWebDAVFileSystem *> FileSystems;
  78. //---------------------------------------------------------------------------
  79. extern "C"
  80. {
  81. void ne_debug(void * Context, int Channel, const char * Format, ...)
  82. {
  83. bool DoLog;
  84. if (FLAGSET(Channel, NE_DBG_SOCKET) ||
  85. FLAGSET(Channel, NE_DBG_HTTP) ||
  86. FLAGSET(Channel, NE_DBG_HTTPAUTH) ||
  87. FLAGSET(Channel, NE_DBG_SSL))
  88. {
  89. DoLog = true;
  90. }
  91. else if (FLAGSET(Channel, NE_DBG_XML) ||
  92. FLAGSET(Channel, NE_DBG_WINSCP_HTTP_DETAIL))
  93. {
  94. DoLog = (Configuration->ActualLogProtocol >= 1);
  95. }
  96. else if (FLAGSET(Channel, NE_DBG_LOCKS) ||
  97. FLAGSET(Channel, NE_DBG_XMLPARSE) ||
  98. FLAGSET(Channel, NE_DBG_HTTPBODY))
  99. {
  100. DoLog = (Configuration->ActualLogProtocol >= 2);
  101. }
  102. else
  103. {
  104. DoLog = false;
  105. FAIL;
  106. }
  107. #ifndef _DEBUG
  108. if (DoLog)
  109. #endif
  110. {
  111. va_list Args;
  112. va_start(Args, Format);
  113. UTF8String UTFMessage;
  114. UTFMessage.vprintf(Format, Args);
  115. va_end(Args);
  116. UnicodeString Message = UTFMessage;
  117. if (DoLog)
  118. {
  119. // Note that this gets called for THttp sessions too.
  120. // It does no harm atm.
  121. TWebDAVFileSystem * FileSystem = NULL;
  122. if (Context != NULL)
  123. {
  124. ne_session * Session = static_cast<ne_session *>(Context);
  125. FileSystem =
  126. static_cast<TWebDAVFileSystem *>(ne_get_session_private(Session, SESSION_FS_KEY));
  127. }
  128. else
  129. {
  130. TGuard Guard(DebugSection.get());
  131. if (FileSystems.size() == 1)
  132. {
  133. FileSystem = *FileSystems.begin();
  134. }
  135. }
  136. if (FileSystem != NULL)
  137. {
  138. FileSystem->NeonDebug(Message);
  139. }
  140. }
  141. }
  142. }
  143. } // extern "C"
  144. //------------------------------------------------------------------------------
  145. //---------------------------------------------------------------------------
  146. // ne_path_escape returns 7-bit string, so it does not really matter if we use
  147. // AnsiString or UTF8String here, though UTF8String might be more safe
  148. static AnsiString PathEscape(const char * Path)
  149. {
  150. char * EscapedPath = ne_path_escape(Path);
  151. AnsiString Result = EscapedPath;
  152. ne_free(EscapedPath);
  153. return Result;
  154. }
  155. //---------------------------------------------------------------------------
  156. static UTF8String PathUnescape(const char * Path)
  157. {
  158. char * UnescapedPath = ne_path_unescape(Path);
  159. UTF8String Result = UnescapedPath;
  160. ne_free(UnescapedPath);
  161. return Result;
  162. }
  163. //---------------------------------------------------------------------------
  164. #define AbsolutePathToNeon(P) PathEscape(StrToNeon(P)).c_str()
  165. #define PathToNeonStatic(THIS, P) AbsolutePathToNeon((THIS)->AbsolutePath(P, false))
  166. #define PathToNeon(P) PathToNeonStatic(this, P)
  167. //---------------------------------------------------------------------------
  168. //---------------------------------------------------------------------------
  169. static bool NeonInitialized = false;
  170. static bool NeonSspiInitialized = false;
  171. //---------------------------------------------------------------------------
  172. void __fastcall NeonInitialize()
  173. {
  174. // Even if this fails, we do not want to interrupt WinSCP starting for that.
  175. // Anyway, it can hardly fail.
  176. // Though it fails on Wine on Debian VM, because of ne_sspi_init():
  177. // sspi: QuerySecurityPackageInfo [failed] [80090305].
  178. // sspi: Unable to get negotiate maximum packet size
  179. int NeonResult = ne_sock_init();
  180. if (NeonResult == 0)
  181. {
  182. NeonInitialized = true;
  183. NeonSspiInitialized = true;
  184. }
  185. else if (NeonResult == -2)
  186. {
  187. NeonInitialized = true;
  188. NeonSspiInitialized = false;
  189. }
  190. else
  191. {
  192. NeonInitialized = false;
  193. NeonSspiInitialized = false;
  194. }
  195. }
  196. //---------------------------------------------------------------------------
  197. void __fastcall NeonFinalize()
  198. {
  199. if (NeonInitialized)
  200. {
  201. ne_sock_exit();
  202. NeonInitialized = false;
  203. }
  204. }
  205. //---------------------------------------------------------------------------
  206. UnicodeString __fastcall NeonVersion()
  207. {
  208. UnicodeString Str = StrFromNeon(ne_version_string());
  209. CutToChar(Str, L' ', true); // "neon"
  210. UnicodeString Result = CutToChar(Str, L':', true);
  211. return Result;
  212. }
  213. //---------------------------------------------------------------------------
  214. UnicodeString __fastcall ExpatVersion()
  215. {
  216. return FORMAT(L"%d.%d.%d", (XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION));
  217. }
  218. //---------------------------------------------------------------------------
  219. //---------------------------------------------------------------------------
  220. TWebDAVFileSystem::TWebDAVFileSystem(TTerminal * ATerminal) :
  221. TCustomFileSystem(ATerminal),
  222. FActive(false),
  223. FHasTrailingSlash(false),
  224. FNeonSession(NULL),
  225. FNeonLockStore(NULL),
  226. FNeonLockStoreSection(new TCriticalSection()),
  227. FUploading(false),
  228. FDownloading(false),
  229. FInitialHandshake(false),
  230. FIgnoreAuthenticationFailure(iafNo)
  231. {
  232. FFileSystemInfo.ProtocolBaseName = CONST_WEBDAV_PROTOCOL_BASE_NAME;
  233. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  234. }
  235. //---------------------------------------------------------------------------
  236. __fastcall TWebDAVFileSystem::~TWebDAVFileSystem()
  237. {
  238. UnregisterFromDebug();
  239. {
  240. TGuard Guard(FNeonLockStoreSection);
  241. if (FNeonLockStore != NULL)
  242. {
  243. ne_lockstore_destroy(FNeonLockStore);
  244. FNeonLockStore = NULL;
  245. }
  246. }
  247. delete FNeonLockStoreSection;
  248. }
  249. //---------------------------------------------------------------------------
  250. void __fastcall TWebDAVFileSystem::Open()
  251. {
  252. if (!NeonInitialized)
  253. {
  254. throw Exception(LoadStr(NEON_INIT_FAILED));
  255. }
  256. if (!NeonSspiInitialized)
  257. {
  258. FTerminal->LogEvent(L"Warning: SSPI initialization failed.");
  259. }
  260. RegisterForDebug();
  261. FCurrentDirectory = L"";
  262. FHasTrailingSlash = true;
  263. FStoredPasswordTried = false;
  264. FTlsVersionStr = L"";
  265. FCapabilities = 0;
  266. TSessionData * Data = FTerminal->SessionData;
  267. FSessionInfo.LoginTime = Now();
  268. UnicodeString HostName = Data->HostNameExpanded;
  269. size_t Port = Data->PortNumber;
  270. UnicodeString ProtocolName = (FTerminal->SessionData->Ftps == ftpsNone) ? WebDAVProtocol : WebDAVSProtocol;
  271. UnicodeString Path = Data->RemoteDirectory;
  272. // PathToNeon is not used as we cannot call AbsolutePath here
  273. UnicodeString EscapedPath = StrFromNeon(PathEscape(StrToNeon(Path)).c_str());
  274. UnicodeString Url = FORMAT(L"%s://%s:%d%s", (ProtocolName, HostName, Port, EscapedPath));
  275. FTerminal->Information(LoadStr(STATUS_CONNECT), true);
  276. FActive = false;
  277. try
  278. {
  279. OpenUrl(Url);
  280. }
  281. catch (Exception & E)
  282. {
  283. CloseNeonSession();
  284. FTerminal->Closed();
  285. FTerminal->FatalError(&E, LoadStr(CONNECTION_FAILED));
  286. }
  287. FActive = true;
  288. }
  289. //---------------------------------------------------------------------------
  290. UnicodeString __fastcall TWebDAVFileSystem::ParsePathFromUrl(const UnicodeString & Url)
  291. {
  292. UnicodeString Result;
  293. ne_uri ParsedUri;
  294. if (ne_uri_parse(StrToNeon(Url), &ParsedUri) == 0)
  295. {
  296. Result = StrFromNeon(PathUnescape(ParsedUri.path));
  297. ne_uri_free(&ParsedUri);
  298. }
  299. return Result;
  300. }
  301. //---------------------------------------------------------------------------
  302. void TWebDAVFileSystem::OpenUrl(const UnicodeString & Url)
  303. {
  304. UnicodeString CorrectedUrl;
  305. NeonClientOpenSessionInternal(CorrectedUrl, Url);
  306. if (CorrectedUrl.IsEmpty())
  307. {
  308. CorrectedUrl = Url;
  309. }
  310. UnicodeString ParsedPath = ParsePathFromUrl(CorrectedUrl);
  311. if (!ParsedPath.IsEmpty())
  312. {
  313. // this is most likely pointless as it get overwritten by
  314. // call to ChangeDirectory() from TTerminal::DoStartup
  315. FCurrentDirectory = ParsedPath;
  316. }
  317. }
  318. //---------------------------------------------------------------------------
  319. void TWebDAVFileSystem::NeonClientOpenSessionInternal(UnicodeString & CorrectedUrl, UnicodeString Url)
  320. {
  321. std::unique_ptr<TStringList> AttemptedUrls(CreateSortedStringList());
  322. AttemptedUrls->Add(Url);
  323. while (true)
  324. {
  325. CorrectedUrl = L"";
  326. NeonOpen(CorrectedUrl, Url);
  327. // No error and no corrected URL? We're done here.
  328. if (CorrectedUrl.IsEmpty())
  329. {
  330. break;
  331. }
  332. CloseNeonSession();
  333. CheckRedirectLoop(CorrectedUrl, AttemptedUrls.get());
  334. // Our caller will want to know what our final corrected URL was.
  335. Url = CorrectedUrl;
  336. }
  337. CorrectedUrl = Url;
  338. }
  339. //---------------------------------------------------------------------------
  340. void TWebDAVFileSystem::NeonOpen(UnicodeString & CorrectedUrl, const UnicodeString & Url)
  341. {
  342. ne_uri uri;
  343. NeonParseUrl(Url, uri);
  344. FHostName = StrFromNeon(uri.host);
  345. FPortNumber = uri.port;
  346. FSessionInfo.CSCipher = UnicodeString();
  347. FSessionInfo.SCCipher = UnicodeString();
  348. bool Ssl = IsTlsUri(uri);
  349. FSessionInfo.SecurityProtocolName = Ssl ? LoadStr(FTPS_IMPLICIT) : UnicodeString();
  350. if (Ssl != (FTerminal->SessionData->Ftps != ftpsNone))
  351. {
  352. FTerminal->LogEvent(FORMAT(L"Warning: %s", (LoadStr(UNENCRYPTED_REDIRECT))));
  353. }
  354. TSessionData * Data = FTerminal->SessionData;
  355. DebugAssert(FNeonSession == NULL);
  356. FNeonSession =
  357. CreateNeonSession(
  358. uri, Data->ProxyMethod, Data->ProxyHost, Data->ProxyPort,
  359. Data->ProxyUsername, Data->ProxyPassword);
  360. UTF8String Path = uri.path;
  361. ne_uri_free(&uri);
  362. ne_set_session_private(FNeonSession, SESSION_FS_KEY, this);
  363. // Other flags:
  364. // NE_DBG_FLUSH - used only in native implementation of ne_debug
  365. // NE_DBG_HTTPPLAIN - log credentials in HTTP authentication
  366. ne_debug_mask =
  367. NE_DBG_SOCKET |
  368. NE_DBG_HTTP |
  369. NE_DBG_XML | // detail
  370. NE_DBG_HTTPAUTH |
  371. NE_DBG_LOCKS | // very details
  372. NE_DBG_XMLPARSE | // very details
  373. NE_DBG_HTTPBODY | // very details
  374. NE_DBG_SSL |
  375. FLAGMASK(Configuration->LogSensitive, NE_DBG_HTTPPLAIN);
  376. ne_set_read_timeout(FNeonSession, Data->Timeout);
  377. ne_set_connect_timeout(FNeonSession, Data->Timeout);
  378. unsigned int NeonAuthTypes = NE_AUTH_BASIC | NE_AUTH_DIGEST;
  379. if (Ssl)
  380. {
  381. NeonAuthTypes |= NE_AUTH_NEGOTIATE;
  382. }
  383. ne_add_server_auth(FNeonSession, NeonAuthTypes, NeonRequestAuth, this);
  384. if (Ssl)
  385. {
  386. SetNeonTlsInit(FNeonSession, InitSslSession);
  387. // When the CA certificate or server certificate has
  388. // verification problems, neon will call our verify function before
  389. // outright rejection of the connection.
  390. ne_ssl_set_verify(FNeonSession, NeonServerSSLCallback, this);
  391. ne_ssl_trust_default_ca(FNeonSession);
  392. ne_ssl_provide_clicert(FNeonSession, NeonProvideClientCert, this);
  393. }
  394. ne_set_notifier(FNeonSession, NeonNotifier, this);
  395. ne_hook_create_request(FNeonSession, NeonCreateRequest, this);
  396. ne_hook_pre_send(FNeonSession, NeonPreSend, this);
  397. ne_hook_post_send(FNeonSession, NeonPostSend, this);
  398. TAutoFlag Flag(FInitialHandshake);
  399. ExchangeCapabilities(Path.c_str(), CorrectedUrl);
  400. }
  401. //---------------------------------------------------------------------------
  402. UnicodeString __fastcall TWebDAVFileSystem::GetRedirectUrl()
  403. {
  404. UnicodeString Result = GetNeonRedirectUrl(FNeonSession);
  405. FTerminal->LogEvent(FORMAT(L"Redirected to \"%s\".", (Result)));
  406. return Result;
  407. }
  408. //---------------------------------------------------------------------------
  409. void TWebDAVFileSystem::ExchangeCapabilities(const char * Path, UnicodeString & CorrectedUrl)
  410. {
  411. ClearNeonError();
  412. int NeonStatus = ne_options2(FNeonSession, Path, &FCapabilities);
  413. if (NeonStatus == NE_REDIRECT)
  414. {
  415. CorrectedUrl = GetRedirectUrl();
  416. }
  417. else if (NeonStatus == NE_OK)
  418. {
  419. if (FCapabilities > 0)
  420. {
  421. UnicodeString Str;
  422. unsigned int Capability = 0x01;
  423. unsigned int Capabilities = FCapabilities;
  424. while (Capabilities > 0)
  425. {
  426. if (FLAGSET(Capabilities, Capability))
  427. {
  428. AddToList(Str, StrFromNeon(ne_capability_name(Capability)), L", ");
  429. Capabilities -= Capability;
  430. }
  431. Capability <<= 1;
  432. }
  433. FTerminal->LogEvent(FORMAT(L"Server capabilities: %s", (Str)));
  434. FFileSystemInfo.AdditionalInfo +=
  435. LoadStr(WEBDAV_EXTENSION_INFO) + sLineBreak +
  436. L" " + Str + sLineBreak;
  437. }
  438. }
  439. else
  440. {
  441. CheckStatus(NeonStatus);
  442. }
  443. FTerminal->SaveCapabilities(FFileSystemInfo);
  444. }
  445. //---------------------------------------------------------------------------
  446. void __fastcall TWebDAVFileSystem::CloseNeonSession()
  447. {
  448. if (FNeonSession != NULL)
  449. {
  450. DestroyNeonSession(FNeonSession);
  451. FNeonSession = NULL;
  452. }
  453. }
  454. //---------------------------------------------------------------------------
  455. void __fastcall TWebDAVFileSystem::Close()
  456. {
  457. DebugAssert(FActive);
  458. CloseNeonSession();
  459. FTerminal->Closed();
  460. FActive = false;
  461. UnregisterFromDebug();
  462. }
  463. //---------------------------------------------------------------------------
  464. void __fastcall TWebDAVFileSystem::RegisterForDebug()
  465. {
  466. TGuard Guard(DebugSection.get());
  467. FileSystems.insert(this);
  468. }
  469. //---------------------------------------------------------------------------
  470. void __fastcall TWebDAVFileSystem::UnregisterFromDebug()
  471. {
  472. TGuard Guard(DebugSection.get());
  473. FileSystems.erase(this);
  474. }
  475. //---------------------------------------------------------------------------
  476. bool __fastcall TWebDAVFileSystem::GetActive()
  477. {
  478. return FActive;
  479. }
  480. //---------------------------------------------------------------------------
  481. void __fastcall TWebDAVFileSystem::CollectUsage()
  482. {
  483. if (!FTlsVersionStr.IsEmpty())
  484. {
  485. FTerminal->CollectTlsUsage(FTlsVersionStr);
  486. }
  487. if (!FTerminal->SessionData->TlsCertificateFile.IsEmpty())
  488. {
  489. Configuration->Usage->Inc(L"OpenedSessionsWebDAVSCertificate");
  490. }
  491. UnicodeString RemoteSystem = FFileSystemInfo.RemoteSystem;
  492. if (ContainsText(RemoteSystem, L"Microsoft-IIS"))
  493. {
  494. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVIIS");
  495. }
  496. else if (ContainsText(RemoteSystem, L"IT Hit WebDAV Server"))
  497. {
  498. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVITHit");
  499. }
  500. // e.g. brickftp.com
  501. else if (ContainsText(RemoteSystem, L"nginx"))
  502. {
  503. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVNginx");
  504. }
  505. else
  506. {
  507. // We also know OpenDrive, Yandex, iFiles (iOS), Swapper (iOS), SafeSync
  508. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsWebDAVOther");
  509. }
  510. }
  511. //---------------------------------------------------------------------------
  512. const TSessionInfo & __fastcall TWebDAVFileSystem::GetSessionInfo()
  513. {
  514. return FSessionInfo;
  515. }
  516. //---------------------------------------------------------------------------
  517. const TFileSystemInfo & __fastcall TWebDAVFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  518. {
  519. return FFileSystemInfo;
  520. }
  521. //---------------------------------------------------------------------------
  522. bool __fastcall TWebDAVFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  523. {
  524. return false;
  525. }
  526. //---------------------------------------------------------------------------
  527. bool __fastcall TWebDAVFileSystem::GetStoredCredentialsTried()
  528. {
  529. return FStoredPasswordTried;
  530. }
  531. //---------------------------------------------------------------------------
  532. UnicodeString __fastcall TWebDAVFileSystem::GetUserName()
  533. {
  534. return FUserName;
  535. }
  536. //---------------------------------------------------------------------------
  537. void __fastcall TWebDAVFileSystem::Idle()
  538. {
  539. // noop
  540. }
  541. //---------------------------------------------------------------------------
  542. UnicodeString __fastcall TWebDAVFileSystem::AbsolutePath(const UnicodeString Path, bool /*Local*/)
  543. {
  544. bool AddTrailingBackslash;
  545. if (Path == L"/")
  546. {
  547. // does not really matter as path "/" is still "/" when absolute,
  548. // no slash needed
  549. AddTrailingBackslash = FHasTrailingSlash;
  550. }
  551. else
  552. {
  553. AddTrailingBackslash = (Path[Path.Length()] == L'/');
  554. }
  555. UnicodeString Result = ::AbsolutePath(GetCurrentDirectory(), Path);
  556. // We must preserve trailing slash, because particularly for mod_dav,
  557. // it really matters if the slash in there or not
  558. if (AddTrailingBackslash)
  559. {
  560. Result = UnixIncludeTrailingBackslash(Result);
  561. }
  562. return Result;
  563. }
  564. //---------------------------------------------------------------------------
  565. bool __fastcall TWebDAVFileSystem::IsCapable(int Capability) const
  566. {
  567. DebugAssert(FTerminal);
  568. switch (Capability)
  569. {
  570. case fcRename:
  571. case fcRemoteMove:
  572. case fcMoveToQueue:
  573. case fcPreservingTimestampUpload:
  574. case fcCheckingSpaceAvailable:
  575. // Only to make double-click on file edit/open the file,
  576. // instead of trying to open it as directory
  577. case fcResolveSymlink:
  578. return true;
  579. case fcUserGroupListing:
  580. case fcModeChanging:
  581. case fcModeChangingUpload:
  582. case fcGroupChanging:
  583. case fcOwnerChanging:
  584. case fcAnyCommand:
  585. case fcShellAnyCommand:
  586. case fcHardLink:
  587. case fcSymbolicLink:
  588. case fcTextMode:
  589. case fcNativeTextMode:
  590. case fcNewerOnlyUpload:
  591. case fcTimestampChanging:
  592. case fcLoadingAdditionalProperties:
  593. case fcIgnorePermErrors:
  594. case fcCalculatingChecksum:
  595. case fcSecondaryShell:
  596. case fcGroupOwnerChangingByID:
  597. case fcRemoveCtrlZUpload:
  598. case fcRemoveBOMUpload:
  599. case fcRemoteCopy:
  600. case fcPreservingTimestampDirs:
  601. return false;
  602. case fcLocking:
  603. return FLAGSET(FCapabilities, NE_CAP_DAV_CLASS2);
  604. default:
  605. FAIL;
  606. return false;
  607. }
  608. }
  609. //---------------------------------------------------------------------------
  610. UnicodeString __fastcall TWebDAVFileSystem::GetCurrentDirectory()
  611. {
  612. return FCurrentDirectory;
  613. }
  614. //---------------------------------------------------------------------------
  615. void __fastcall TWebDAVFileSystem::DoStartup()
  616. {
  617. FTerminal->SetExceptionOnFail(true);
  618. // retrieve initialize working directory to save it as home directory
  619. ReadCurrentDirectory();
  620. FTerminal->SetExceptionOnFail(false);
  621. }
  622. //---------------------------------------------------------------------------
  623. void __fastcall TWebDAVFileSystem::ClearNeonError()
  624. {
  625. FCancelled = false;
  626. FAuthenticationRequested = false;
  627. ne_set_error(FNeonSession, "");
  628. }
  629. //---------------------------------------------------------------------------
  630. UnicodeString __fastcall TWebDAVFileSystem::GetNeonError()
  631. {
  632. return ::GetNeonError(FNeonSession);
  633. }
  634. //---------------------------------------------------------------------------
  635. void __fastcall TWebDAVFileSystem::CheckStatus(int NeonStatus)
  636. {
  637. if ((NeonStatus == NE_ERROR) && FCancelled)
  638. {
  639. FCancelled = false;
  640. Abort();
  641. }
  642. else
  643. {
  644. CheckNeonStatus(FNeonSession, NeonStatus, FHostName);
  645. }
  646. }
  647. //---------------------------------------------------------------------------
  648. void __fastcall TWebDAVFileSystem::LookupUsersGroups()
  649. {
  650. FAIL;
  651. }
  652. //---------------------------------------------------------------------------
  653. void __fastcall TWebDAVFileSystem::ReadCurrentDirectory()
  654. {
  655. if (FCachedDirectoryChange.IsEmpty())
  656. {
  657. FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
  658. }
  659. else
  660. {
  661. FCurrentDirectory = FCachedDirectoryChange;
  662. FCachedDirectoryChange = L"";
  663. }
  664. }
  665. //---------------------------------------------------------------------------
  666. void __fastcall TWebDAVFileSystem::HomeDirectory()
  667. {
  668. ChangeDirectory(L"/");
  669. }
  670. //---------------------------------------------------------------------------
  671. UnicodeString __fastcall TWebDAVFileSystem::DirectoryPath(UnicodeString Path)
  672. {
  673. if (FHasTrailingSlash)
  674. {
  675. Path = ::UnixIncludeTrailingBackslash(Path);
  676. }
  677. return Path;
  678. }
  679. //---------------------------------------------------------------------------
  680. UnicodeString __fastcall TWebDAVFileSystem::FilePath(const TRemoteFile * File)
  681. {
  682. UnicodeString Result = File->FullFileName;
  683. if (File->IsDirectory)
  684. {
  685. Result = DirectoryPath(Result);
  686. }
  687. return Result;
  688. }
  689. //---------------------------------------------------------------------------
  690. void __fastcall TWebDAVFileSystem::TryOpenDirectory(UnicodeString Directory)
  691. {
  692. Directory = DirectoryPath(Directory);
  693. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  694. TRemoteFile * File;
  695. ReadFile(Directory, File);
  696. delete File;
  697. }
  698. //---------------------------------------------------------------------------
  699. void __fastcall TWebDAVFileSystem::AnnounceFileListOperation()
  700. {
  701. // noop
  702. }
  703. //---------------------------------------------------------------------------
  704. void __fastcall TWebDAVFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  705. {
  706. UnicodeString Path = AbsolutePath(ADirectory, false);
  707. // to verify existence of directory try to open it
  708. TryOpenDirectory(Path);
  709. // if open dir did not fail, directory exists -> success.
  710. FCachedDirectoryChange = Path;
  711. }
  712. //---------------------------------------------------------------------------
  713. void __fastcall TWebDAVFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  714. {
  715. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  716. }
  717. //---------------------------------------------------------------------------
  718. struct TReadFileData
  719. {
  720. TWebDAVFileSystem * FileSystem;
  721. TRemoteFile * File;
  722. TRemoteFileList * FileList;
  723. };
  724. //---------------------------------------------------------------------------
  725. int __fastcall TWebDAVFileSystem::ReadDirectoryInternal(
  726. const UnicodeString & Path, TRemoteFileList * FileList)
  727. {
  728. TReadFileData Data;
  729. Data.FileSystem = this;
  730. Data.File = NULL;
  731. Data.FileList = FileList;
  732. ClearNeonError();
  733. ne_propfind_handler * PropFindHandler = ne_propfind_create(FNeonSession, PathToNeon(Path), NE_DEPTH_ONE);
  734. void * DiscoveryContext = ne_lock_register_discovery(PropFindHandler);
  735. int Result;
  736. try
  737. {
  738. Result = ne_propfind_allprop(PropFindHandler, NeonPropsResult, &Data);
  739. }
  740. __finally
  741. {
  742. ne_lock_discovery_free(DiscoveryContext);
  743. ne_propfind_destroy(PropFindHandler);
  744. }
  745. return Result;
  746. }
  747. //---------------------------------------------------------------------------
  748. bool __fastcall TWebDAVFileSystem::IsValidRedirect(int NeonStatus, UnicodeString & Path)
  749. {
  750. bool Result = (NeonStatus == NE_REDIRECT);
  751. if (Result)
  752. {
  753. // What PathToNeon does
  754. UnicodeString OriginalPath = AbsolutePath(Path, false);
  755. // Handle one-step redirect
  756. // (for more steps we would have to implement loop detection).
  757. // This is mainly to handle "folder" => "folder/" redirects of Apache/mod_dav.
  758. UnicodeString RedirectUrl = GetRedirectUrl();
  759. // We should test if the redirect is not for another server,
  760. // though not sure how to do this reliably (domain aliases, IP vs. domain, etc.)
  761. UnicodeString RedirectPath = ParsePathFromUrl(RedirectUrl);
  762. Result =
  763. !RedirectPath.IsEmpty() &&
  764. (RedirectPath != OriginalPath);
  765. if (Result)
  766. {
  767. Path = RedirectPath;
  768. }
  769. }
  770. return Result;
  771. }
  772. //---------------------------------------------------------------------------
  773. void __fastcall TWebDAVFileSystem::ReadDirectory(TRemoteFileList * FileList)
  774. {
  775. UnicodeString Path = DirectoryPath(FileList->Directory);
  776. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  777. int NeonStatus = ReadDirectoryInternal(Path, FileList);
  778. if (IsValidRedirect(NeonStatus, Path))
  779. {
  780. NeonStatus = ReadDirectoryInternal(Path, FileList);
  781. }
  782. CheckStatus(NeonStatus);
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall TWebDAVFileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
  786. TRemoteFile *& /*File*/)
  787. {
  788. // we never set SymLink flag, so we should never get here
  789. FAIL;
  790. }
  791. //---------------------------------------------------------------------------
  792. void __fastcall TWebDAVFileSystem::ReadFile(const UnicodeString FileName,
  793. TRemoteFile *& File)
  794. {
  795. CustomReadFile(FileName, File, NULL);
  796. }
  797. //---------------------------------------------------------------------------
  798. void TWebDAVFileSystem::NeonPropsResult(
  799. void * UserData, const ne_uri * Uri, const ne_prop_result_set * Results)
  800. {
  801. UnicodeString Path = StrFromNeon(PathUnescape(Uri->path).c_str());
  802. TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
  803. if (Data.FileList != NULL)
  804. {
  805. UnicodeString FileListPath = Data.FileSystem->AbsolutePath(Data.FileList->Directory, false);
  806. if (UnixSamePath(Path, FileListPath))
  807. {
  808. Path = UnixIncludeTrailingBackslash(UnixIncludeTrailingBackslash(Path) + L"..");
  809. }
  810. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  811. File->Terminal = Data.FileSystem->FTerminal;
  812. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  813. Data.FileList->AddFile(File.release());
  814. }
  815. else
  816. {
  817. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  818. }
  819. }
  820. //---------------------------------------------------------------------------
  821. const char * __fastcall TWebDAVFileSystem::GetProp(
  822. const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
  823. {
  824. ne_propname Prop;
  825. Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
  826. Prop.name = Name;
  827. return ne_propset_value(Results, &Prop);
  828. }
  829. //---------------------------------------------------------------------------
  830. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  831. const UnicodeString & Path, const ne_prop_result_set * Results)
  832. {
  833. File->FullFileName = UnixExcludeTrailingBackslash(Path);
  834. // Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
  835. // It seems that all servers actually use the trailing slash, including IIS, mod_Dav, IT Hit, OpenDrive, etc.
  836. bool Collection = (File->FullFileName != Path);
  837. File->FileName = UnixExtractFileName(File->FullFileName);
  838. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  839. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  840. if (ContentLength != NULL)
  841. {
  842. File->Size = StrToInt64Def(ContentLength, 0);
  843. }
  844. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  845. if (ALWAYS_TRUE(LastModified != NULL))
  846. {
  847. char WeekDay[4] = { L'\0' };
  848. int Year = 0;
  849. char MonthStr[4] = { L'\0' };
  850. int Day = 0;
  851. int Hour = 0;
  852. int Min = 0;
  853. int Sec = 0;
  854. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  855. int Filled =
  856. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  857. // we need at least a complete date
  858. if (Filled >= 4)
  859. {
  860. int Month = ParseShortEngMonthName(MonthStr);
  861. if (Month >= 1)
  862. {
  863. TDateTime Modification =
  864. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  865. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  866. File->Modification = ConvertTimestampFromUTC(Modification);
  867. File->ModificationFmt = mfFull;
  868. }
  869. }
  870. }
  871. // optimization
  872. if (!Collection)
  873. {
  874. // This is possibly redundant code as all servers we know (see a comment above)
  875. // indicate the folder by trailing slash too
  876. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  877. if (ResourceType != NULL)
  878. {
  879. // property has XML value
  880. UnicodeString AResourceType = ResourceType;
  881. // this is very poor parsing
  882. if (ContainsText(ResourceType, L"<DAV:collection"))
  883. {
  884. Collection = true;
  885. }
  886. }
  887. }
  888. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  889. // this is MS extension (draft-hopmann-collection-props-00)
  890. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  891. if (IsHidden != NULL)
  892. {
  893. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  894. }
  895. const char * Owner = GetProp(Results, PROP_OWNER);
  896. if (Owner != NULL)
  897. {
  898. File->Owner.Name = Owner;
  899. }
  900. const UnicodeString RightsDelimiter(L", ");
  901. UnicodeString HumanRights;
  902. // Proprietary property of mod_dav
  903. // http://www.webdav.org/mod_dav/#imp
  904. const char * Executable = GetProp(Results, PROP_EXECUTABLE, MODDAV_PROP_NAMESPACE);
  905. if (Executable != NULL)
  906. {
  907. if (strcmp(Executable, "T") == NULL)
  908. {
  909. UnicodeString ExecutableRights;
  910. // The "gear" character is supported since Windows 8
  911. if (IsWin8())
  912. {
  913. ExecutableRights = L"\u2699";
  914. }
  915. else
  916. {
  917. ExecutableRights = LoadStr(EXECUTABLE);
  918. }
  919. AddToList(HumanRights, ExecutableRights, RightsDelimiter);
  920. }
  921. }
  922. struct ne_lock * Lock = static_cast<struct ne_lock *>(ne_propset_private(Results));
  923. if ((Lock != NULL) && (Lock->token != NULL))
  924. {
  925. UnicodeString Owner;
  926. if (Lock->owner != NULL)
  927. {
  928. Owner = StrFromNeon(Lock->owner).Trim();
  929. }
  930. UnicodeString LockRights;
  931. if (IsWin8())
  932. {
  933. // The "lock" character is supported since Windows 8
  934. LockRights = L"\uD83D\uDD12" + Owner;
  935. }
  936. else
  937. {
  938. LockRights = LoadStr(LOCKED);
  939. if (!Owner.IsEmpty())
  940. {
  941. LockRights = FORMAT(L"%s (%s)", (LockRights, Owner));
  942. }
  943. }
  944. AddToList(HumanRights, LockRights, RightsDelimiter);
  945. }
  946. File->HumanRights = HumanRights;
  947. }
  948. //---------------------------------------------------------------------------
  949. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  950. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  951. {
  952. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  953. TReadFileData Data;
  954. Data.FileSystem = this;
  955. Data.File = AFile.get();
  956. Data.FileList = NULL;
  957. ClearNeonError();
  958. int Result =
  959. ne_simple_propfind(FNeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  960. NeonPropsResult, &Data);
  961. if (Result == NE_OK)
  962. {
  963. File = AFile.release();
  964. }
  965. return Result;
  966. }
  967. //---------------------------------------------------------------------------
  968. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  969. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  970. {
  971. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  972. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  973. if (IsValidRedirect(NeonStatus, FileName))
  974. {
  975. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  976. }
  977. CheckStatus(NeonStatus);
  978. }
  979. //---------------------------------------------------------------------------
  980. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  981. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  982. {
  983. Action.Recursive();
  984. ClearNeonError();
  985. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  986. RawByteString Path = PathToNeon(FilePath(File));
  987. // WebDAV does not allow non-recursive delete:
  988. // RFC 4918, section 9.6.1:
  989. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  990. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  991. CheckStatus(ne_delete(FNeonSession, Path.c_str()));
  992. // The lock is removed with the file, but if a file with the same name gets created,
  993. // we would try to use obsoleted lock token with it, what the server would reject
  994. // (mod_dav returns "412 Precondition Failed")
  995. DiscardLock(Path);
  996. }
  997. //---------------------------------------------------------------------------
  998. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  999. const UnicodeString & NewName)
  1000. {
  1001. // 0 = no overwrite
  1002. return ne_move(FNeonSession, 0, PathToNeon(FileName), PathToNeon(NewName));
  1003. }
  1004. //---------------------------------------------------------------------------
  1005. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName,
  1006. const UnicodeString NewName)
  1007. {
  1008. ClearNeonError();
  1009. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1010. UnicodeString Path = FileName;
  1011. int NeonStatus = RenameFileInternal(Path, NewName);
  1012. if (IsValidRedirect(NeonStatus, Path))
  1013. {
  1014. NeonStatus = RenameFileInternal(Path, NewName);
  1015. }
  1016. CheckStatus(NeonStatus);
  1017. // See a comment in DeleteFile
  1018. DiscardLock(PathToNeon(Path));
  1019. }
  1020. //---------------------------------------------------------------------------
  1021. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName,
  1022. const UnicodeString NewName)
  1023. {
  1024. FAIL;
  1025. }
  1026. //---------------------------------------------------------------------------
  1027. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString DirName)
  1028. {
  1029. ClearNeonError();
  1030. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1031. CheckStatus(ne_mkcol(FNeonSession, PathToNeon(DirName)));
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  1035. const UnicodeString PointTo, bool /*Symbolic*/)
  1036. {
  1037. FAIL;
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1041. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  1042. TChmodSessionAction & /*Action*/)
  1043. {
  1044. FAIL;
  1045. }
  1046. //---------------------------------------------------------------------------
  1047. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1048. {
  1049. FAIL;
  1050. return false;
  1051. }
  1052. //---------------------------------------------------------------------------
  1053. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
  1054. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  1055. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  1056. {
  1057. FAIL;
  1058. }
  1059. //---------------------------------------------------------------------------
  1060. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1061. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1062. TFileOperationProgressType * OperationProgress,
  1063. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1064. int Params)
  1065. {
  1066. // all = "yes to newer"
  1067. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1068. TQueryButtonAlias Aliases[3];
  1069. Aliases[0].Button = qaAll;
  1070. Aliases[0].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  1071. Aliases[0].GroupWith = qaYes;
  1072. Aliases[0].GrouppedShiftState = TShiftState() << ssCtrl;
  1073. Aliases[1].Button = qaYesToAll;
  1074. Aliases[1].GroupWith = qaYes;
  1075. Aliases[1].GrouppedShiftState = TShiftState() << ssShift;
  1076. Aliases[2].Button = qaNoToAll;
  1077. Aliases[2].GroupWith = qaNo;
  1078. Aliases[2].GrouppedShiftState = TShiftState() << ssShift;
  1079. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1080. QueryParams.Aliases = Aliases;
  1081. QueryParams.AliasesCount = LENOF(Aliases);
  1082. unsigned int Answer;
  1083. {
  1084. TSuspendFileOperationProgress Suspend(OperationProgress);
  1085. Answer =
  1086. FTerminal->ConfirmFileOverwrite(
  1087. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1088. (OperationProgress->Side == osLocal) ? osRemote : osLocal,
  1089. CopyParam, Params, OperationProgress);
  1090. }
  1091. switch (Answer)
  1092. {
  1093. case qaYes:
  1094. // noop
  1095. break;
  1096. case qaNo:
  1097. THROW_SKIP_FILE_NULL;
  1098. default:
  1099. FAIL;
  1100. case qaCancel:
  1101. if (!OperationProgress->Cancel)
  1102. {
  1103. OperationProgress->Cancel = csCancel;
  1104. }
  1105. Abort();
  1106. break;
  1107. }
  1108. }
  1109. //---------------------------------------------------------------------------
  1110. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1111. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1112. {
  1113. FAIL;
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1117. TCaptureOutputEvent /*OutputEvent*/)
  1118. {
  1119. FAIL;
  1120. }
  1121. //---------------------------------------------------------------------------
  1122. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1123. {
  1124. return NULL;
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. void TWebDAVFileSystem::NeonQuotaResult(
  1128. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1129. {
  1130. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1131. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1132. if (Value != NULL)
  1133. {
  1134. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1135. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1136. if (Value != NULL)
  1137. {
  1138. SpaceAvailable.BytesAvailableToUser =
  1139. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1140. }
  1141. }
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1145. TSpaceAvailable & ASpaceAvailable)
  1146. {
  1147. // RFC4331: http://tools.ietf.org/html/rfc4331
  1148. // This is known to be supported by:
  1149. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1150. // unconditionally, even when not explicitly requested)
  1151. // Server: Apache/2.2.17 (Fedora)
  1152. // X-Powered-By: PHP/5.5.7
  1153. // X-DAV-Powered-By: OpenDrive
  1154. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1155. // IT Hit WebDAV Server:
  1156. // Server: Microsoft-HTTPAPI/1.0
  1157. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1158. // Yandex disk:
  1159. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1160. // Server: MochiWeb/1.0
  1161. UnicodeString APath = DirectoryPath(Path);
  1162. ne_propname QuotaProps[3];
  1163. memset(QuotaProps, 0, sizeof(QuotaProps));
  1164. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1165. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1166. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1167. QuotaProps[1].name = PROP_QUOTA_USED;
  1168. QuotaProps[2].nspace = NULL;
  1169. QuotaProps[2].name = NULL;
  1170. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1171. CheckStatus(
  1172. ne_simple_propfind(FNeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1173. NeonQuotaResult, &ASpaceAvailable));
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1177. const UnicodeString ATargetDir, const TCopyParamType * CopyParam,
  1178. int Params, TFileOperationProgressType * OperationProgress,
  1179. TOnceDoneOperation & OnceDoneOperation)
  1180. {
  1181. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  1182. Params &= ~cpAppend;
  1183. UnicodeString FileName, FileNameOnly;
  1184. UnicodeString TargetDir = AbsolutePath(ATargetDir, false);
  1185. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  1186. intptr_t Index = 0;
  1187. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  1188. {
  1189. bool Success = false;
  1190. FileName = FilesToCopy->Strings[Index];
  1191. FileNameOnly = ExtractFileName(FileName, false);
  1192. try
  1193. {
  1194. try
  1195. {
  1196. if (FTerminal->SessionData->CacheDirectories)
  1197. {
  1198. FTerminal->DirectoryModified(TargetDir, false);
  1199. if (::DirectoryExists(ApiPath(::ExtractFilePath(FileName))))
  1200. {
  1201. FTerminal->DirectoryModified(FullTargetDir + FileNameOnly, true);
  1202. }
  1203. }
  1204. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  1205. tfFirstLevel);
  1206. Success = true;
  1207. }
  1208. catch (EScpSkipFile & E)
  1209. {
  1210. TSuspendFileOperationProgress Suspend(OperationProgress);
  1211. if (!FTerminal->HandleException(&E))
  1212. {
  1213. throw;
  1214. }
  1215. }
  1216. }
  1217. __finally
  1218. {
  1219. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1220. }
  1221. Index++;
  1222. }
  1223. }
  1224. //---------------------------------------------------------------------------
  1225. void __fastcall TWebDAVFileSystem::SourceRobust(const UnicodeString FileName,
  1226. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1227. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1228. {
  1229. // the same in TSFTPFileSystem
  1230. TUploadSessionAction Action(FTerminal->ActionLog);
  1231. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  1232. do
  1233. {
  1234. bool ChildError = false;
  1235. try
  1236. {
  1237. Source(FileName, TargetDir, CopyParam, Params, OperationProgress,
  1238. Flags, Action, ChildError);
  1239. }
  1240. catch (Exception & E)
  1241. {
  1242. if (!RobustLoop.TryReopen(E))
  1243. {
  1244. if (!ChildError)
  1245. {
  1246. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1247. }
  1248. throw;
  1249. }
  1250. }
  1251. if (RobustLoop.ShouldRetry())
  1252. {
  1253. OperationProgress->RollbackTransfer();
  1254. Action.Restart();
  1255. // prevent overwrite confirmations
  1256. // (should not be set for directories!)
  1257. Params |= cpNoConfirmation;
  1258. }
  1259. }
  1260. while (RobustLoop.Retry());
  1261. }
  1262. //---------------------------------------------------------------------------
  1263. void __fastcall TWebDAVFileSystem::Source(const UnicodeString FileName,
  1264. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1265. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1266. TUploadSessionAction & Action, bool & ChildError)
  1267. {
  1268. Action.FileName(ExpandUNCFileName(FileName));
  1269. OperationProgress->SetFile(FileName, false);
  1270. if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
  1271. {
  1272. THROW_SKIP_FILE_NULL;
  1273. }
  1274. HANDLE File;
  1275. __int64 MTime;
  1276. __int64 Size;
  1277. int Attrs;
  1278. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &Attrs,
  1279. &File, NULL, &MTime, NULL, &Size);
  1280. bool Dir = FLAGSET(Attrs, faDirectory);
  1281. int FD = -1;
  1282. try
  1283. {
  1284. OperationProgress->SetFileInProgress();
  1285. if (Dir)
  1286. {
  1287. Action.Cancel();
  1288. DirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  1289. Attrs, CopyParam, Params, OperationProgress, Flags);
  1290. }
  1291. else
  1292. {
  1293. UnicodeString DestFileName =
  1294. FTerminal->ChangeFileName(
  1295. CopyParam, ExtractFileName(FileName), osLocal,
  1296. FLAGSET(Flags, tfFirstLevel));
  1297. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  1298. OperationProgress->SetLocalSize(Size);
  1299. // Suppose same data size to transfer as to read
  1300. // (not true with ASCII transfer)
  1301. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1302. OperationProgress->TransferingFile = false;
  1303. UnicodeString DestFullName = TargetDir + DestFileName;
  1304. TRemoteFile * RemoteFile = NULL;
  1305. try
  1306. {
  1307. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1308. FIgnoreAuthenticationFailure = iafWaiting;
  1309. // this should not throw
  1310. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1311. }
  1312. catch (...)
  1313. {
  1314. if (!FTerminal->Active)
  1315. {
  1316. throw;
  1317. }
  1318. }
  1319. TDateTime Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1320. if (RemoteFile != NULL)
  1321. {
  1322. TOverwriteFileParams FileParams;
  1323. FileParams.SourceSize = Size;
  1324. FileParams.SourceTimestamp = Modification;
  1325. FileParams.DestSize = RemoteFile->Size;
  1326. FileParams.DestTimestamp = RemoteFile->Modification;
  1327. delete RemoteFile;
  1328. ConfirmOverwrite(FileName, DestFileName, OperationProgress,
  1329. &FileParams, CopyParam, Params);
  1330. }
  1331. DestFullName = TargetDir + DestFileName;
  1332. // only now, we know the final destination
  1333. // (not really true as we do not support changing file name on overwrite dialog)
  1334. Action.Destination(DestFullName);
  1335. FILE_OPERATION_LOOP_BEGIN
  1336. {
  1337. SetFilePointer(File, 0, NULL, FILE_BEGIN);
  1338. FD = _open_osfhandle((intptr_t)File, O_BINARY);
  1339. if (FD < 0)
  1340. {
  1341. THROW_SKIP_FILE_NULL;
  1342. }
  1343. TAutoFlag UploadingFlag(FUploading);
  1344. ClearNeonError();
  1345. CheckStatus(ne_put(FNeonSession, PathToNeon(DestFullName), FD));
  1346. }
  1347. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1348. if (CopyParam->PreserveTime)
  1349. {
  1350. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1351. (StandardTimestamp(Modification))));
  1352. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Modification);
  1353. try
  1354. {
  1355. TDateTime ModificationUTC = ConvertTimestampToUTC(Modification);
  1356. TFormatSettings FormatSettings = GetEngFormatSettings();
  1357. UnicodeString LastModified =
  1358. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1359. UTF8String NeonLastModified(LastModified);
  1360. // second element is "NULL-terminating"
  1361. ne_proppatch_operation Operations[2];
  1362. memset(Operations, 0, sizeof(Operations));
  1363. ne_propname LastModifiedProp;
  1364. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1365. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1366. Operations[0].name = &LastModifiedProp;
  1367. Operations[0].type = ne_propset;
  1368. Operations[0].value = NeonLastModified.c_str();
  1369. int Status = ne_proppatch(FNeonSession, PathToNeon(DestFullName), Operations);
  1370. if (Status == NE_ERROR)
  1371. {
  1372. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1373. (GetNeonError())));
  1374. // Ignore errors as major WebDAV servers (like IIS), do not support
  1375. // changing getlastmodified.
  1376. // The only server we found that supports this is TradeMicro SafeSync.
  1377. // But it announces itself as "Server: Apache",
  1378. // so it's not reliably autodetect the support.
  1379. TouchAction.Cancel();
  1380. }
  1381. else
  1382. {
  1383. CheckStatus(Status);
  1384. }
  1385. }
  1386. catch (Exception & E)
  1387. {
  1388. TouchAction.Rollback(&E);
  1389. ChildError = true;
  1390. throw;
  1391. }
  1392. }
  1393. FTerminal->LogFileDone(OperationProgress);
  1394. }
  1395. }
  1396. __finally
  1397. {
  1398. if (FD >= 0)
  1399. {
  1400. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1401. // but it crashes code guard
  1402. _close(FD);
  1403. }
  1404. else if (File != NULL)
  1405. {
  1406. CloseHandle(File);
  1407. }
  1408. }
  1409. // TODO : Delete also read-only files.
  1410. if (FLAGSET(Params, cpDelete))
  1411. {
  1412. if (!Dir)
  1413. {
  1414. FILE_OPERATION_LOOP_BEGIN
  1415. {
  1416. THROWOSIFFALSE(::DeleteFile(ApiPath(FileName).c_str()));
  1417. }
  1418. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  1419. }
  1420. }
  1421. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1422. {
  1423. FILE_OPERATION_LOOP_BEGIN
  1424. {
  1425. THROWOSIFFALSE(FileSetAttr(ApiPath(FileName), Attrs & ~faArchive) == 0);
  1426. }
  1427. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  1428. }
  1429. }
  1430. //---------------------------------------------------------------------------
  1431. void __fastcall TWebDAVFileSystem::DirectorySource(const UnicodeString DirectoryName,
  1432. const UnicodeString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  1433. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1434. {
  1435. UnicodeString DestDirectoryName =
  1436. FTerminal->ChangeFileName(
  1437. CopyParam, ExtractFileName(ExcludeTrailingBackslash(DirectoryName)),
  1438. osLocal, FLAGSET(Flags, tfFirstLevel));
  1439. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  1440. // create DestFullName if it does not exist
  1441. if (!FTerminal->FileExists(DestFullName))
  1442. {
  1443. TRemoteProperties Properties;
  1444. if (CopyParam->PreserveRights)
  1445. {
  1446. Properties.Valid = TValidProperties() << vpRights;
  1447. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  1448. }
  1449. FTerminal->CreateDirectory(DestFullName, &Properties);
  1450. }
  1451. OperationProgress->SetFile(DirectoryName);
  1452. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1453. TSearchRecChecked SearchRec;
  1454. bool FindOK;
  1455. FILE_OPERATION_LOOP_BEGIN
  1456. {
  1457. FindOK =
  1458. (FindFirstChecked(DirectoryName + L"*.*", FindAttrs, SearchRec) == 0);
  1459. }
  1460. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1461. try
  1462. {
  1463. while (FindOK && !OperationProgress->Cancel)
  1464. {
  1465. UnicodeString FileName = DirectoryName + SearchRec.Name;
  1466. try
  1467. {
  1468. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1469. {
  1470. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  1471. Flags & ~(tfFirstLevel));
  1472. }
  1473. }
  1474. catch (EScpSkipFile & E)
  1475. {
  1476. // If ESkipFile occurs, just log it and continue with next file
  1477. TSuspendFileOperationProgress Suspend(OperationProgress);
  1478. // here a message to user was displayed, which was not appropriate
  1479. // when user refused to overwrite the file in subdirectory.
  1480. // hopefully it won't be missing in other situations.
  1481. if (!FTerminal->HandleException(&E))
  1482. {
  1483. throw;
  1484. }
  1485. }
  1486. FILE_OPERATION_LOOP_BEGIN
  1487. {
  1488. FindOK = (FindNextChecked(SearchRec) == 0);
  1489. }
  1490. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1491. }
  1492. }
  1493. __finally
  1494. {
  1495. FindClose(SearchRec);
  1496. }
  1497. // TODO : Delete also read-only directories.
  1498. // TODO : Show error message on failure.
  1499. if (!OperationProgress->Cancel)
  1500. {
  1501. if (FLAGSET(Params, cpDelete))
  1502. {
  1503. RemoveDir(ApiPath(DirectoryName));
  1504. }
  1505. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1506. {
  1507. FILE_OPERATION_LOOP_BEGIN
  1508. {
  1509. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  1510. }
  1511. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  1512. }
  1513. }
  1514. }
  1515. //---------------------------------------------------------------------------
  1516. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1517. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1518. int Params, TFileOperationProgressType * OperationProgress,
  1519. TOnceDoneOperation & OnceDoneOperation)
  1520. {
  1521. Params &= ~cpAppend;
  1522. UnicodeString FullTargetDir = ::IncludeTrailingBackslash(TargetDir);
  1523. int Index = 0;
  1524. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  1525. {
  1526. UnicodeString FileName = FilesToCopy->Strings[Index];
  1527. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  1528. bool Success = false;
  1529. try
  1530. {
  1531. try
  1532. {
  1533. SinkRobust(AbsolutePath(FileName, false), File, FullTargetDir, CopyParam, Params,
  1534. OperationProgress, tfFirstLevel);
  1535. Success = true;
  1536. }
  1537. catch (EScpSkipFile & E)
  1538. {
  1539. TSuspendFileOperationProgress Suspend(OperationProgress);
  1540. if (!FTerminal->HandleException(&E))
  1541. {
  1542. throw;
  1543. }
  1544. }
  1545. }
  1546. __finally
  1547. {
  1548. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1549. }
  1550. Index++;
  1551. }
  1552. }
  1553. //---------------------------------------------------------------------------
  1554. void __fastcall TWebDAVFileSystem::SinkRobust(const UnicodeString FileName,
  1555. const TRemoteFile * File, const UnicodeString TargetDir,
  1556. const TCopyParamType * CopyParam, int Params,
  1557. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1558. {
  1559. // the same in TSFTPFileSystem
  1560. TDownloadSessionAction Action(FTerminal->ActionLog);
  1561. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  1562. do
  1563. {
  1564. bool ChildError = false;
  1565. try
  1566. {
  1567. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  1568. Flags, Action, ChildError);
  1569. }
  1570. catch (Exception & E)
  1571. {
  1572. if (!RobustLoop.TryReopen(E))
  1573. {
  1574. if (!ChildError)
  1575. {
  1576. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1577. }
  1578. throw;
  1579. }
  1580. }
  1581. if (RobustLoop.ShouldRetry())
  1582. {
  1583. OperationProgress->RollbackTransfer();
  1584. Action.Restart();
  1585. DebugAssert(File != NULL);
  1586. if (!File->IsDirectory)
  1587. {
  1588. // prevent overwrite confirmations
  1589. Params |= cpNoConfirmation;
  1590. }
  1591. }
  1592. }
  1593. while (RobustLoop.Retry());
  1594. }
  1595. //---------------------------------------------------------------------------
  1596. void TWebDAVFileSystem::NeonCreateRequest(
  1597. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1598. {
  1599. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1600. ne_set_request_private(Request, SESSION_FS_KEY, FileSystem);
  1601. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1602. }
  1603. //---------------------------------------------------------------------------
  1604. void TWebDAVFileSystem::NeonPreSend(
  1605. ne_request * Request, void * UserData, ne_buffer * Header)
  1606. {
  1607. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1608. if (FileSystem->FDownloading)
  1609. {
  1610. // Needed by IIS server to make it download source code, not code output,
  1611. // and mainly to even allow downloading file with unregistered extensions.
  1612. // Without it files like .001 return 404 (Not found) HTTP code.
  1613. // http://msdn.microsoft.com/en-us/library/cc250098.aspx
  1614. // http://msdn.microsoft.com/en-us/library/cc250216.aspx
  1615. // http://lists.manyfish.co.uk/pipermail/neon/2012-April/001452.html
  1616. // It's also supported by Oracle server:
  1617. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1618. // We do not know yet of any server that fails when the header is used,
  1619. // so it's added unconditionally.
  1620. ne_buffer_zappend(Header, "Translate: f\r\n");
  1621. }
  1622. if (FileSystem->FTerminal->Log->Logging)
  1623. {
  1624. const char * Buffer;
  1625. size_t Size;
  1626. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1627. {
  1628. // all neon request types that use ne_add_request_header
  1629. // use XML content-type, so it's text-based
  1630. DebugAssert(ContainsStr(AnsiString(Header->data, Header->used), "Content-Type: " NE_XML_MEDIA_TYPE));
  1631. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1632. }
  1633. }
  1634. if (FileSystem->FUploading)
  1635. {
  1636. ne_set_request_body_provider_pre(Request,
  1637. FileSystem->NeonUploadBodyProvider, FileSystem);
  1638. }
  1639. FileSystem->FResponse = L"";
  1640. }
  1641. //---------------------------------------------------------------------------
  1642. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1643. const ne_status * /*Status*/)
  1644. {
  1645. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1646. if (!FileSystem->FResponse.IsEmpty())
  1647. {
  1648. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1649. }
  1650. return NE_OK;
  1651. }
  1652. //---------------------------------------------------------------------------
  1653. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1654. {
  1655. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1656. ssize_t Result;
  1657. if (FileSystem->CancelTransfer())
  1658. {
  1659. Result = -1;
  1660. }
  1661. else
  1662. {
  1663. Result = 1;
  1664. }
  1665. return Result;
  1666. }
  1667. //---------------------------------------------------------------------------
  1668. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1669. {
  1670. const char * Value = ne_get_response_header(Request, Name);
  1671. if (Value != NULL)
  1672. {
  1673. AddToList(List, StrFromNeon(Value), L"; ");
  1674. }
  1675. }
  1676. //---------------------------------------------------------------------------
  1677. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1678. {
  1679. DebugAssert(UserData == Request);
  1680. TWebDAVFileSystem * FileSystem =
  1681. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1682. bool AuthenticationFailed = (Status->code == 401) && FileSystem->FAuthenticationRequested;
  1683. bool AuthenticationNeeded = (Status->code == 401) && !FileSystem->FAuthenticationRequested;
  1684. if (FileSystem->FInitialHandshake)
  1685. {
  1686. UnicodeString Line;
  1687. if (AuthenticationNeeded)
  1688. {
  1689. Line = LoadStr(STATUS_AUTHENTICATE);
  1690. }
  1691. else if (AuthenticationFailed)
  1692. {
  1693. Line = LoadStr(FTP_ACCESS_DENIED);
  1694. }
  1695. else if (Status->klass == 2)
  1696. {
  1697. Line = LoadStr(STATUS_AUTHENTICATED);
  1698. }
  1699. if (!Line.IsEmpty())
  1700. {
  1701. FileSystem->FTerminal->Information(Line, true);
  1702. }
  1703. UnicodeString RemoteSystem;
  1704. // Used by IT Hit WebDAV Server:
  1705. // Server: Microsoft-HTTPAPI/1.0
  1706. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1707. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1708. // Used by OpenDrive:
  1709. // Server: Apache/2.2.17 (Fedora)
  1710. // X-Powered-By: PHP/5.5.7
  1711. // X-DAV-Powered-By: OpenDrive
  1712. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1713. // Used by IIS:
  1714. // Server: Microsoft-IIS/8.5
  1715. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1716. // Not really useful.
  1717. // Can be e.g. "PleskLin"
  1718. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1719. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1720. }
  1721. // When we explicitly fail authentication of request
  1722. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1723. // neon resets its internal password store and tries the next request
  1724. // without calling our authentication hook first
  1725. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1726. // what likely fails, but we do not want to reset out password
  1727. // (as it was not even tried yet for this request).
  1728. if (AuthenticationFailed)
  1729. {
  1730. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1731. {
  1732. FileSystem->FPassword = RawByteString();
  1733. }
  1734. else
  1735. {
  1736. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1737. }
  1738. }
  1739. return ne_accept_2xx(UserData, Request, Status);
  1740. }
  1741. //---------------------------------------------------------------------------
  1742. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1743. {
  1744. bool Result = false;
  1745. if ((FUploading || FDownloading) &&
  1746. (FTerminal->OperationProgress != NULL) &&
  1747. (FTerminal->OperationProgress->Cancel != csContinue))
  1748. {
  1749. FCancelled = true;
  1750. Result = true;
  1751. }
  1752. return Result;
  1753. }
  1754. //---------------------------------------------------------------------------
  1755. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1756. {
  1757. ne_request * Request = static_cast<ne_request *>(UserData);
  1758. TWebDAVFileSystem * FileSystem =
  1759. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1760. if (FileSystem->FTerminal->Log->Logging)
  1761. {
  1762. ne_content_type ContentType;
  1763. if (ne_get_content_type(Request, &ContentType) == 0)
  1764. {
  1765. // The main point of the content-type check was to exclude
  1766. // GET responses (with file contents).
  1767. // But this won't work when downloading text files that have text
  1768. // content type on their own, hence the additional not-downloading test.
  1769. if (!FileSystem->FDownloading &&
  1770. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1771. media_type_is_xml(&ContentType)))
  1772. {
  1773. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1774. FileSystem->FResponse += Content;
  1775. }
  1776. ne_free(ContentType.value);
  1777. }
  1778. }
  1779. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1780. return Result;
  1781. }
  1782. //---------------------------------------------------------------------------
  1783. void __fastcall TWebDAVFileSystem::Sink(const UnicodeString FileName,
  1784. const TRemoteFile * File, const UnicodeString TargetDir,
  1785. const TCopyParamType * CopyParam, int Params,
  1786. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1787. TDownloadSessionAction & Action, bool & ChildError)
  1788. {
  1789. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1790. Action.FileName(FileName);
  1791. DebugAssert(File);
  1792. TFileMasks::TParams MaskParams;
  1793. MaskParams.Size = File->Size;
  1794. UnicodeString BaseFileName = FTerminal->GetBaseFileName(FileName);
  1795. if (!CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams))
  1796. {
  1797. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  1798. THROW_SKIP_FILE_NULL;
  1799. }
  1800. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  1801. {
  1802. OperationProgress->AddSkippedFileSize(File->Size);
  1803. THROW_SKIP_FILE_NULL;
  1804. }
  1805. FTerminal->LogFileDetails(FileName, TDateTime(), File->Size);
  1806. OperationProgress->SetFile(FileName);
  1807. UnicodeString DestFileName =
  1808. FTerminal->ChangeFileName(
  1809. CopyParam, FileNameOnly, osRemote, FLAGSET(Flags, tfFirstLevel));
  1810. UnicodeString DestFullName = TargetDir + DestFileName;
  1811. if (File->IsDirectory)
  1812. {
  1813. Action.Cancel();
  1814. if (ALWAYS_TRUE(!File->IsSymLink))
  1815. {
  1816. FILE_OPERATION_LOOP_BEGIN
  1817. {
  1818. int Attrs = FileGetAttr(ApiPath(DestFullName));
  1819. if (FLAGCLEAR(Attrs, faDirectory)) { EXCEPTION; }
  1820. }
  1821. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  1822. FILE_OPERATION_LOOP_BEGIN
  1823. {
  1824. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  1825. }
  1826. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  1827. TSinkFileParams SinkFileParams;
  1828. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  1829. SinkFileParams.CopyParam = CopyParam;
  1830. SinkFileParams.Params = Params;
  1831. SinkFileParams.OperationProgress = OperationProgress;
  1832. SinkFileParams.Skipped = false;
  1833. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  1834. FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  1835. // Do not delete directory if some of its files were skip.
  1836. // Throw "skip file" for the directory to avoid attempt to deletion
  1837. // of any parent directory
  1838. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  1839. {
  1840. THROW_SKIP_FILE_NULL;
  1841. }
  1842. }
  1843. else
  1844. {
  1845. // file is symlink to directory, currently do nothing, but it should be
  1846. // reported to user
  1847. }
  1848. }
  1849. else
  1850. {
  1851. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  1852. if (FileExists(ApiPath(DestFullName)))
  1853. {
  1854. __int64 Size;
  1855. __int64 MTime;
  1856. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL,
  1857. NULL, NULL, &MTime, NULL, &Size);
  1858. TOverwriteFileParams FileParams;
  1859. FileParams.SourceSize = File->Size;
  1860. FileParams.SourceTimestamp = File->Modification;
  1861. FileParams.DestSize = Size;
  1862. FileParams.DestTimestamp = UnixToDateTime(MTime,
  1863. FTerminal->SessionData->DSTMode);
  1864. ConfirmOverwrite(FileName, DestFileName, OperationProgress,
  1865. &FileParams, CopyParam, Params);
  1866. }
  1867. // Suppose same data size to transfer as to write
  1868. OperationProgress->SetTransferSize(File->Size);
  1869. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1870. int Attrs = -1;
  1871. FILE_OPERATION_LOOP_BEGIN
  1872. {
  1873. Attrs = FileGetAttr(ApiPath(DestFullName));
  1874. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory)) { EXCEPTION; }
  1875. }
  1876. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  1877. OperationProgress->TransferingFile = false; // not set with WebDAV protocol
  1878. UnicodeString FilePath = ::UnixExtractFilePath(FileName);
  1879. if (FilePath.IsEmpty())
  1880. {
  1881. FilePath = L"/";
  1882. }
  1883. Action.Destination(ExpandUNCFileName(DestFullName));
  1884. FILE_OPERATION_LOOP_BEGIN
  1885. {
  1886. HANDLE LocalHandle;
  1887. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress,
  1888. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1889. {
  1890. THROW_SKIP_FILE_NULL;
  1891. }
  1892. bool DeleteLocalFile = true;
  1893. int FD = -1;
  1894. try
  1895. {
  1896. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1897. if (FD < 0)
  1898. {
  1899. THROW_SKIP_FILE_NULL;
  1900. }
  1901. TAutoFlag DownloadingFlag(FDownloading);
  1902. ClearNeonError();
  1903. CheckStatus(ne_get(FNeonSession, PathToNeon(FileName), FD));
  1904. DeleteLocalFile = false;
  1905. if (CopyParam->PreserveTime)
  1906. {
  1907. TDateTime Modification = File->Modification;
  1908. FILETIME WrTime = DateTimeToFileTime(Modification, FTerminal->SessionData->DSTMode);
  1909. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1910. (StandardTimestamp(Modification))));
  1911. SetFileTime(LocalHandle, NULL, NULL, &WrTime);
  1912. }
  1913. }
  1914. __finally
  1915. {
  1916. if (FD >= 0)
  1917. {
  1918. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1919. // but it crashes code guard
  1920. _close(FD);
  1921. }
  1922. else
  1923. {
  1924. CloseHandle(LocalHandle);
  1925. }
  1926. if (DeleteLocalFile)
  1927. {
  1928. FILE_OPERATION_LOOP_BEGIN
  1929. {
  1930. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestFullName)));
  1931. }
  1932. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestFullName)));
  1933. }
  1934. }
  1935. }
  1936. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1937. if (Attrs == -1)
  1938. {
  1939. Attrs = faArchive;
  1940. }
  1941. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  1942. if ((NewAttrs & Attrs) != NewAttrs)
  1943. {
  1944. FILE_OPERATION_LOOP_BEGIN
  1945. {
  1946. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  1947. }
  1948. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  1949. }
  1950. FTerminal->LogFileDone(OperationProgress);
  1951. }
  1952. if (FLAGSET(Params, cpDelete))
  1953. {
  1954. ChildError = true;
  1955. // If file is directory, do not delete it recursively, because it should be
  1956. // empty already. If not, it should not be deleted (some files were
  1957. // skipped or some new files were copied to it, while we were downloading)
  1958. int Params = dfNoRecursive;
  1959. FTerminal->DeleteFile(FileName, File, &Params);
  1960. ChildError = false;
  1961. }
  1962. }
  1963. //---------------------------------------------------------------------------
  1964. void __fastcall TWebDAVFileSystem::SinkFile(const UnicodeString FileName,
  1965. const TRemoteFile * File, void * Param)
  1966. {
  1967. TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
  1968. DebugAssert(Params->OperationProgress);
  1969. try
  1970. {
  1971. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  1972. Params->Params, Params->OperationProgress, Params->Flags);
  1973. }
  1974. catch (EScpSkipFile & E)
  1975. {
  1976. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  1977. Params->Skipped = true;
  1978. {
  1979. TSuspendFileOperationProgress Suspend(OperationProgress);
  1980. if (!FTerminal->HandleException(&E))
  1981. {
  1982. throw;
  1983. }
  1984. }
  1985. if (OperationProgress->Cancel)
  1986. {
  1987. Abort();
  1988. }
  1989. }
  1990. }
  1991. //---------------------------------------------------------------------------
  1992. bool TWebDAVFileSystem::VerifyCertificate(const TWebDAVCertificateData & Data)
  1993. {
  1994. FTerminal->LogEvent(
  1995. FORMAT(L"Verifying certificate for \"%s\" with fingerprint %s and %2.2X failures",
  1996. (Data.Subject, Data.Fingerprint, Data.Failures)));
  1997. int Failures = Data.Failures;
  1998. if (NeonWindowsValidateCertificate(Failures, Data.AsciiCert))
  1999. {
  2000. FTerminal->LogEvent(L"Certificate verified against Windows certificate store");
  2001. }
  2002. UnicodeString Summary;
  2003. if (Failures == 0)
  2004. {
  2005. Summary = LoadStr(CERT_OK);
  2006. }
  2007. else
  2008. {
  2009. Summary = NeonCertificateFailuresErrorStr(Failures, FHostName);
  2010. }
  2011. UnicodeString ValidityTimeFormat = L"ddddd tt";
  2012. FSessionInfo.CertificateFingerprint = Data.Fingerprint;
  2013. FSessionInfo.Certificate =
  2014. FMTLOAD(CERT_TEXT, (
  2015. Data.Issuer + L"\n",
  2016. Data.Subject + L"\n",
  2017. FormatDateTime(ValidityTimeFormat, Data.ValidFrom),
  2018. FormatDateTime(ValidityTimeFormat, Data.ValidUntil),
  2019. Data.Fingerprint,
  2020. Summary));
  2021. bool Result = (Failures == 0);
  2022. if (!Result)
  2023. {
  2024. UnicodeString SiteKey = TSessionData::FormatSiteKey(FHostName, FPortNumber);
  2025. if (!Result)
  2026. {
  2027. Result = FTerminal->VerifyCertificate(
  2028. CertificateStorageKey, SiteKey, Data.Fingerprint, Data.Subject, Failures);
  2029. }
  2030. if (!Result)
  2031. {
  2032. TClipboardHandler ClipboardHandler;
  2033. ClipboardHandler.Text = Data.Fingerprint;
  2034. TQueryButtonAlias Aliases[1];
  2035. Aliases[0].Button = qaRetry;
  2036. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  2037. Aliases[0].OnClick = &ClipboardHandler.Copy;
  2038. TQueryParams Params;
  2039. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  2040. Params.NoBatchAnswers = qaYes | qaRetry;
  2041. Params.Aliases = Aliases;
  2042. Params.AliasesCount = LENOF(Aliases);
  2043. unsigned int Answer = FTerminal->QueryUser(
  2044. FMTLOAD(VERIFY_CERT_PROMPT3, (FSessionInfo.Certificate)),
  2045. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  2046. switch (Answer)
  2047. {
  2048. case qaYes:
  2049. FTerminal->CacheCertificate(CertificateStorageKey, SiteKey, Data.Fingerprint, Failures);
  2050. Result = true;
  2051. break;
  2052. case qaNo:
  2053. Result = true;
  2054. break;
  2055. default:
  2056. FAIL;
  2057. case qaCancel:
  2058. FTerminal->Configuration->Usage->Inc(L"HostNotVerified");
  2059. Result = false;
  2060. break;
  2061. }
  2062. }
  2063. if (Result)
  2064. {
  2065. FTerminal->Configuration->RememberLastFingerprint(
  2066. FTerminal->SessionData->SiteKey, TlsFingerprintType, FSessionInfo.CertificateFingerprint);
  2067. }
  2068. }
  2069. if (Result)
  2070. {
  2071. CollectTLSSessionInfo();
  2072. }
  2073. return Result;
  2074. }
  2075. //------------------------------------------------------------------------------
  2076. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  2077. {
  2078. // See also TFTPFileSystem::Open().
  2079. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  2080. // can be closed as the time we need it in CollectUsage().
  2081. FTlsVersionStr = StrFromNeon(ne_ssl_get_version(FNeonSession));
  2082. AddToList(FSessionInfo.SecurityProtocolName, FTlsVersionStr, L", ");
  2083. UnicodeString Cipher = StrFromNeon(ne_ssl_get_cipher(FNeonSession));
  2084. FSessionInfo.CSCipher = Cipher;
  2085. FSessionInfo.SCCipher = Cipher;
  2086. // see CAsyncSslSocketLayer::PrintSessionInfo()
  2087. FTerminal->LogEvent(FORMAT(L"Using %s, cipher %s", (FTlsVersionStr, Cipher)));
  2088. }
  2089. //------------------------------------------------------------------------------
  2090. // A neon-session callback to validate the SSL certificate when the CA
  2091. // is unknown (e.g. a self-signed cert), or there are other SSL
  2092. // certificate problems.
  2093. int TWebDAVFileSystem::NeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  2094. {
  2095. TWebDAVCertificateData Data;
  2096. char Fingerprint[NE_SSL_DIGESTLEN] = {0};
  2097. if (ne_ssl_cert_digest(Certificate, Fingerprint) != 0)
  2098. {
  2099. strcpy(Fingerprint, "<unknown>");
  2100. }
  2101. Data.Fingerprint = StrFromNeon(Fingerprint);
  2102. Data.AsciiCert = NeonExportCertificate(Certificate);
  2103. char * Subject = ne_ssl_readable_dname(ne_ssl_cert_subject(Certificate));
  2104. Data.Subject = StrFromNeon(Subject);
  2105. ne_free(Subject);
  2106. char * Issuer = ne_ssl_readable_dname(ne_ssl_cert_issuer(Certificate));
  2107. Data.Issuer = StrFromNeon(Issuer);
  2108. ne_free(Issuer);
  2109. Data.Failures = Failures;
  2110. time_t ValidFrom;
  2111. time_t ValidUntil;
  2112. ne_ssl_cert_validity_time(Certificate, &ValidFrom, &ValidUntil);
  2113. Data.ValidFrom = UnixToDateTime(ValidFrom, dstmWin);
  2114. Data.ValidUntil = UnixToDateTime(ValidUntil, dstmWin);
  2115. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2116. return FileSystem->VerifyCertificate(Data) ? NE_OK : NE_ERROR;
  2117. }
  2118. //------------------------------------------------------------------------------
  2119. void TWebDAVFileSystem::NeonProvideClientCert(void * UserData, ne_session * Sess,
  2120. const ne_ssl_dname * const * /*DNames*/, int /*DNCount*/)
  2121. {
  2122. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2123. FileSystem->FTerminal->LogEvent(LoadStr(NEED_CLIENT_CERTIFICATE));
  2124. X509 * Certificate;
  2125. EVP_PKEY * PrivateKey;
  2126. if (FileSystem->FTerminal->LoadTlsCertificate(Certificate, PrivateKey))
  2127. {
  2128. ne_ssl_client_cert * NeonCertificate = ne_ssl_clicert_create(Certificate, PrivateKey);
  2129. ne_ssl_set_clicert(Sess, NeonCertificate);
  2130. ne_ssl_clicert_free(NeonCertificate);
  2131. }
  2132. }
  2133. //------------------------------------------------------------------------------
  2134. int TWebDAVFileSystem::NeonRequestAuth(
  2135. void * UserData, const char * /*Realm*/, int /*Attempt*/, char * UserName, char * Password)
  2136. {
  2137. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2138. TTerminal * Terminal = FileSystem->FTerminal;
  2139. TSessionData * SessionData = Terminal->SessionData;
  2140. bool Result = true;
  2141. // will ask for username only once
  2142. if (FileSystem->FUserName.IsEmpty())
  2143. {
  2144. if (!SessionData->UserName.IsEmpty())
  2145. {
  2146. FileSystem->FUserName = SessionData->UserNameExpanded;
  2147. }
  2148. else
  2149. {
  2150. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  2151. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  2152. {
  2153. // note that we never get here actually
  2154. Result = false;
  2155. }
  2156. }
  2157. }
  2158. UnicodeString APassword;
  2159. if (Result)
  2160. {
  2161. // Some servers (Gallery2 on https://g2.pixi.me/w/webdav/)
  2162. // return authentication error (401) on PROPFIND request for
  2163. // non-existing files.
  2164. // When we already tried password before, do not try anymore.
  2165. // When we did not try password before (possible only when
  2166. // server does not require authentication for any previous request,
  2167. // such as when read access is not authenticated), try it now,
  2168. // but use special flag for the try, because when it fails
  2169. // we still want to try password for future requests (such as PUT).
  2170. if (!FileSystem->FPassword.IsEmpty())
  2171. {
  2172. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  2173. {
  2174. // Fail PROPFIND /nonexising request...
  2175. Result = false;
  2176. }
  2177. else
  2178. {
  2179. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  2180. }
  2181. }
  2182. else
  2183. {
  2184. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  2185. {
  2186. APassword = SessionData->Password;
  2187. FileSystem->FStoredPasswordTried = true;
  2188. }
  2189. else
  2190. {
  2191. // Asking for password (or using configured password) the first time,
  2192. // and asking for password.
  2193. // Note that we never get false here actually
  2194. Result =
  2195. Terminal->PromptUser(
  2196. SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  2197. LoadStr(PASSWORD_PROMPT), false, NE_ABUFSIZ, APassword);
  2198. }
  2199. if (Result)
  2200. {
  2201. // While neon remembers the password on its own,
  2202. // we need to keep a copy in case neon store gets reset by
  2203. // 401 response to PROPFIND /nonexisting on G2, see above.
  2204. // Possibly we can do this for G2 servers only.
  2205. FileSystem->FPassword = Terminal->EncryptPassword(APassword);
  2206. }
  2207. }
  2208. }
  2209. if (Result)
  2210. {
  2211. strncpy(UserName, StrToNeon(FileSystem->FUserName), NE_ABUFSIZ);
  2212. strncpy(Password, StrToNeon(APassword), NE_ABUFSIZ);
  2213. }
  2214. FileSystem->FAuthenticationRequested = true;
  2215. return Result ? 0 : -1;
  2216. }
  2217. //------------------------------------------------------------------------------
  2218. void TWebDAVFileSystem::NeonNotifier(void * UserData, ne_session_status Status, const ne_session_status_info * StatusInfo)
  2219. {
  2220. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2221. TFileOperationProgressType * OperationProgress = FileSystem->FTerminal->OperationProgress;
  2222. // We particularly have to filter out response to "put" request,
  2223. // handling that would reset the upload progress back to low number (response is small).
  2224. if (((FileSystem->FUploading && (Status == ne_status_sending)) ||
  2225. (FileSystem->FDownloading && (Status == ne_status_recving))) &&
  2226. ALWAYS_TRUE(OperationProgress != NULL))
  2227. {
  2228. __int64 Progress = StatusInfo->sr.progress;
  2229. __int64 Diff = Progress - OperationProgress->TransferedSize;
  2230. if (Diff > 0)
  2231. {
  2232. OperationProgress->ThrottleToCPSLimit(static_cast<unsigned long>(Diff));
  2233. }
  2234. __int64 Total = StatusInfo->sr.total;
  2235. // Total size unknown
  2236. if (Total < 0)
  2237. {
  2238. if (Diff >= 0)
  2239. {
  2240. OperationProgress->AddTransfered(Diff);
  2241. }
  2242. else
  2243. {
  2244. // Session total has been reset. A new stream started
  2245. OperationProgress->AddTransfered(Progress);
  2246. }
  2247. }
  2248. else
  2249. {
  2250. OperationProgress->SetTransferSize(Total);
  2251. OperationProgress->AddTransfered(Diff);
  2252. }
  2253. }
  2254. }
  2255. //------------------------------------------------------------------------------
  2256. void __fastcall TWebDAVFileSystem::NeonDebug(const UnicodeString & Message)
  2257. {
  2258. FTerminal->LogEvent(Message);
  2259. }
  2260. //------------------------------------------------------------------------------
  2261. void TWebDAVFileSystem::InitSslSession(ssl_st * Ssl, ne_session * Session)
  2262. {
  2263. TWebDAVFileSystem * FileSystem =
  2264. static_cast<TWebDAVFileSystem *>(ne_get_session_private(Session, SESSION_FS_KEY));
  2265. FileSystem->InitSslSessionImpl(Ssl);
  2266. }
  2267. //------------------------------------------------------------------------------
  2268. void __fastcall TWebDAVFileSystem::InitSslSessionImpl(ssl_st * Ssl)
  2269. {
  2270. // See also CAsyncSslSocketLayer::InitSSLConnection
  2271. TSessionData * Data = FTerminal->SessionData;
  2272. #define MASK_TLS_VERSION(VERSION, FLAG) ((Data->MinTlsVersion > VERSION) || (Data->MaxTlsVersion < VERSION) ? FLAG : 0)
  2273. int Options =
  2274. MASK_TLS_VERSION(ssl2, SSL_OP_NO_SSLv2) |
  2275. MASK_TLS_VERSION(ssl3, SSL_OP_NO_SSLv3) |
  2276. MASK_TLS_VERSION(tls10, SSL_OP_NO_TLSv1) |
  2277. MASK_TLS_VERSION(tls11, SSL_OP_NO_TLSv1_1) |
  2278. MASK_TLS_VERSION(tls12, SSL_OP_NO_TLSv1_2);
  2279. // SSL_ctrl() with SSL_CTRL_OPTIONS adds flags (not sets)
  2280. SSL_ctrl(Ssl, SSL_CTRL_OPTIONS, Options, NULL);
  2281. }
  2282. //---------------------------------------------------------------------------
  2283. void __fastcall TWebDAVFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  2284. {
  2285. // NOOP
  2286. }
  2287. //---------------------------------------------------------------------------
  2288. void __fastcall TWebDAVFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * File)
  2289. {
  2290. ClearNeonError();
  2291. struct ne_lock * Lock = ne_lock_create();
  2292. try
  2293. {
  2294. Lock->uri.path = ne_strdup(PathToNeon(FilePath(File)));
  2295. Lock->depth = NE_DEPTH_INFINITE;
  2296. Lock->timeout = NE_TIMEOUT_INFINITE;
  2297. Lock->owner = ne_strdup(StrToNeon(FTerminal->UserName));
  2298. CheckStatus(ne_lock(FNeonSession, Lock));
  2299. {
  2300. TGuard Guard(FNeonLockStoreSection);
  2301. RequireLockStore();
  2302. ne_lockstore_add(FNeonLockStore, Lock);
  2303. }
  2304. // ownership passed
  2305. Lock = NULL;
  2306. }
  2307. __finally
  2308. {
  2309. if (Lock != NULL)
  2310. {
  2311. ne_lock_destroy(Lock);
  2312. }
  2313. }
  2314. }
  2315. //---------------------------------------------------------------------------
  2316. void __fastcall TWebDAVFileSystem::RequireLockStore()
  2317. {
  2318. // Create store only when needed,
  2319. // to limit the use of cross-thread code in UpdateFromMain
  2320. if (FNeonLockStore == NULL)
  2321. {
  2322. FNeonLockStore = ne_lockstore_create();
  2323. ne_lockstore_register(FNeonLockStore, FNeonSession);
  2324. }
  2325. }
  2326. //---------------------------------------------------------------------------
  2327. void TWebDAVFileSystem::LockResult(void * UserData, const struct ne_lock * Lock,
  2328. const ne_uri * /*Uri*/, const ne_status * /*Status*/)
  2329. {
  2330. // Is NULL on failure (Status is not NULL then)
  2331. if (Lock != NULL)
  2332. {
  2333. RawByteString & LockToken = *static_cast<RawByteString *>(UserData);
  2334. LockToken = Lock->token;
  2335. }
  2336. }
  2337. //---------------------------------------------------------------------------
  2338. struct ne_lock * __fastcall TWebDAVFileSystem::FindLock(const RawByteString & Path)
  2339. {
  2340. ne_uri Uri = {0};
  2341. Uri.path = Path.c_str();
  2342. return ne_lockstore_findbyuri(FNeonLockStore, &Uri);
  2343. }
  2344. //---------------------------------------------------------------------------
  2345. void __fastcall TWebDAVFileSystem::DiscardLock(const RawByteString & Path)
  2346. {
  2347. TGuard Guard(FNeonLockStoreSection);
  2348. if (FNeonLockStore != NULL)
  2349. {
  2350. struct ne_lock * Lock = FindLock(Path);
  2351. if (Lock != NULL)
  2352. {
  2353. ne_lockstore_remove(FNeonLockStore, Lock);
  2354. }
  2355. }
  2356. }
  2357. //---------------------------------------------------------------------------
  2358. void __fastcall TWebDAVFileSystem::UnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  2359. {
  2360. ClearNeonError();
  2361. struct ne_lock * Lock = ne_lock_create();
  2362. try
  2363. {
  2364. RawByteString Path = PathToNeon(FilePath(File));
  2365. RawByteString LockToken;
  2366. struct ne_lock * Lock = NULL;
  2367. {
  2368. TGuard Guard(FNeonLockStoreSection);
  2369. if (FNeonLockStore != NULL)
  2370. {
  2371. Lock = FindLock(Path);
  2372. }
  2373. }
  2374. // we are not aware of the file being locked,
  2375. // though it can be locked from another (previous and already closed)
  2376. // session, so query the server.
  2377. if (Lock == NULL)
  2378. {
  2379. CheckStatus(ne_lock_discover(FNeonSession, Path.c_str(), LockResult, &LockToken));
  2380. }
  2381. if ((Lock == NULL) && (LockToken.IsEmpty()))
  2382. {
  2383. throw Exception(FMTLOAD(NOT_LOCKED, (FileName)));
  2384. }
  2385. else
  2386. {
  2387. struct ne_lock * Unlock;
  2388. if (Lock == NULL)
  2389. {
  2390. DebugAssert(!LockToken.IsEmpty());
  2391. Unlock = ne_lock_create();
  2392. Unlock->uri.path = ne_strdup(Path.c_str());
  2393. Unlock->token = ne_strdup(LockToken.c_str());
  2394. }
  2395. else
  2396. {
  2397. Unlock = Lock;
  2398. }
  2399. CheckStatus(ne_unlock(FNeonSession, Unlock));
  2400. DiscardLock(Path);
  2401. }
  2402. }
  2403. __finally
  2404. {
  2405. ne_lock_destroy(Lock);
  2406. }
  2407. }
  2408. //---------------------------------------------------------------------------
  2409. void __fastcall TWebDAVFileSystem::UpdateFromMain(TCustomFileSystem * AMainFileSystem)
  2410. {
  2411. TWebDAVFileSystem * MainFileSystem = dynamic_cast<TWebDAVFileSystem *>(AMainFileSystem);
  2412. if (ALWAYS_TRUE(MainFileSystem != NULL))
  2413. {
  2414. TGuard Guard(FNeonLockStoreSection);
  2415. TGuard MainGuard(MainFileSystem->FNeonLockStoreSection);
  2416. if (FNeonLockStore != NULL)
  2417. {
  2418. struct ne_lock * Lock;
  2419. while ((Lock = ne_lockstore_first(FNeonLockStore)) != NULL)
  2420. {
  2421. ne_lockstore_remove(FNeonLockStore, Lock);
  2422. }
  2423. }
  2424. if (ALWAYS_TRUE(MainFileSystem->FNeonLockStore != NULL))
  2425. {
  2426. RequireLockStore();
  2427. struct ne_lock * Lock = ne_lockstore_first(MainFileSystem->FNeonLockStore);
  2428. while (Lock != NULL)
  2429. {
  2430. ne_lockstore_add(FNeonLockStore, ne_lock_copy(Lock));
  2431. Lock = ne_lockstore_next(MainFileSystem->FNeonLockStore);
  2432. }
  2433. }
  2434. }
  2435. }
  2436. //------------------------------------------------------------------------------