WebDAVFileSystem.cpp 91 KB

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