WebDAVFileSystem.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800
  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(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. return false;
  648. case fcLocking:
  649. return FLAGSET(FCapabilities, NE_CAP_DAV_CLASS2);
  650. default:
  651. DebugFail();
  652. return false;
  653. }
  654. }
  655. //---------------------------------------------------------------------------
  656. UnicodeString __fastcall TWebDAVFileSystem::GetCurrentDirectory()
  657. {
  658. return FCurrentDirectory;
  659. }
  660. //---------------------------------------------------------------------------
  661. void __fastcall TWebDAVFileSystem::DoStartup()
  662. {
  663. FTerminal->SetExceptionOnFail(true);
  664. // retrieve initialize working directory to save it as home directory
  665. ReadCurrentDirectory();
  666. FTerminal->SetExceptionOnFail(false);
  667. }
  668. //---------------------------------------------------------------------------
  669. void __fastcall TWebDAVFileSystem::ClearNeonError()
  670. {
  671. FCancelled = false;
  672. FAuthenticationRequested = false;
  673. ne_set_error(FNeonSession, "");
  674. }
  675. //---------------------------------------------------------------------------
  676. UnicodeString __fastcall TWebDAVFileSystem::GetNeonError()
  677. {
  678. return ::GetNeonError(FNeonSession);
  679. }
  680. //---------------------------------------------------------------------------
  681. void __fastcall TWebDAVFileSystem::CheckStatus(int NeonStatus)
  682. {
  683. if ((NeonStatus == NE_ERROR) && FCancelled)
  684. {
  685. FCancelled = false;
  686. Abort();
  687. }
  688. else
  689. {
  690. CheckNeonStatus(FNeonSession, NeonStatus, FHostName);
  691. }
  692. }
  693. //---------------------------------------------------------------------------
  694. void __fastcall TWebDAVFileSystem::LookupUsersGroups()
  695. {
  696. DebugFail();
  697. }
  698. //---------------------------------------------------------------------------
  699. void __fastcall TWebDAVFileSystem::ReadCurrentDirectory()
  700. {
  701. if (FCachedDirectoryChange.IsEmpty())
  702. {
  703. FCurrentDirectory = FCurrentDirectory.IsEmpty() ? UnicodeString(L"/") : FCurrentDirectory;
  704. }
  705. else
  706. {
  707. FCurrentDirectory = FCachedDirectoryChange;
  708. FCachedDirectoryChange = L"";
  709. }
  710. }
  711. //---------------------------------------------------------------------------
  712. void __fastcall TWebDAVFileSystem::HomeDirectory()
  713. {
  714. ChangeDirectory(L"/");
  715. }
  716. //---------------------------------------------------------------------------
  717. UnicodeString __fastcall TWebDAVFileSystem::DirectoryPath(UnicodeString Path)
  718. {
  719. if (FHasTrailingSlash)
  720. {
  721. Path = ::UnixIncludeTrailingBackslash(Path);
  722. }
  723. return Path;
  724. }
  725. //---------------------------------------------------------------------------
  726. UnicodeString __fastcall TWebDAVFileSystem::FilePath(const TRemoteFile * File)
  727. {
  728. UnicodeString Result = File->FullFileName;
  729. if (File->IsDirectory)
  730. {
  731. Result = DirectoryPath(Result);
  732. }
  733. return Result;
  734. }
  735. //---------------------------------------------------------------------------
  736. void __fastcall TWebDAVFileSystem::TryOpenDirectory(UnicodeString Directory)
  737. {
  738. Directory = DirectoryPath(Directory);
  739. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  740. TRemoteFile * File;
  741. ReadFile(Directory, File);
  742. delete File;
  743. }
  744. //---------------------------------------------------------------------------
  745. void __fastcall TWebDAVFileSystem::AnnounceFileListOperation()
  746. {
  747. // noop
  748. }
  749. //---------------------------------------------------------------------------
  750. void __fastcall TWebDAVFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  751. {
  752. UnicodeString Path = AbsolutePath(ADirectory, false);
  753. // to verify existence of directory try to open it
  754. TryOpenDirectory(Path);
  755. // if open dir did not fail, directory exists -> success.
  756. FCachedDirectoryChange = Path;
  757. }
  758. //---------------------------------------------------------------------------
  759. void __fastcall TWebDAVFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  760. {
  761. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  762. }
  763. //---------------------------------------------------------------------------
  764. struct TReadFileData
  765. {
  766. TWebDAVFileSystem * FileSystem;
  767. TRemoteFile * File;
  768. TRemoteFileList * FileList;
  769. };
  770. //---------------------------------------------------------------------------
  771. int __fastcall TWebDAVFileSystem::ReadDirectoryInternal(
  772. const UnicodeString & Path, TRemoteFileList * FileList)
  773. {
  774. TReadFileData Data;
  775. Data.FileSystem = this;
  776. Data.File = NULL;
  777. Data.FileList = FileList;
  778. ClearNeonError();
  779. ne_propfind_handler * PropFindHandler = ne_propfind_create(FNeonSession, PathToNeon(Path), NE_DEPTH_ONE);
  780. void * DiscoveryContext = ne_lock_register_discovery(PropFindHandler);
  781. int Result;
  782. try
  783. {
  784. Result = ne_propfind_allprop(PropFindHandler, NeonPropsResult, &Data);
  785. }
  786. __finally
  787. {
  788. ne_lock_discovery_free(DiscoveryContext);
  789. ne_propfind_destroy(PropFindHandler);
  790. }
  791. return Result;
  792. }
  793. //---------------------------------------------------------------------------
  794. bool __fastcall TWebDAVFileSystem::IsValidRedirect(int NeonStatus, UnicodeString & Path)
  795. {
  796. bool Result = (NeonStatus == NE_REDIRECT);
  797. if (Result)
  798. {
  799. // What PathToNeon does
  800. UnicodeString OriginalPath = AbsolutePath(Path, false);
  801. // Handle one-step redirect
  802. // (for more steps we would have to implement loop detection).
  803. // This is mainly to handle "folder" => "folder/" redirects of Apache/mod_dav.
  804. UnicodeString RedirectUrl = GetRedirectUrl();
  805. // We should test if the redirect is not for another server,
  806. // though not sure how to do this reliably (domain aliases, IP vs. domain, etc.)
  807. UnicodeString RedirectPath = ParsePathFromUrl(RedirectUrl);
  808. Result =
  809. !RedirectPath.IsEmpty() &&
  810. (RedirectPath != OriginalPath);
  811. if (Result)
  812. {
  813. Path = RedirectPath;
  814. }
  815. }
  816. return Result;
  817. }
  818. //---------------------------------------------------------------------------
  819. void __fastcall TWebDAVFileSystem::ReadDirectory(TRemoteFileList * FileList)
  820. {
  821. UnicodeString Path = DirectoryPath(FileList->Directory);
  822. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  823. int NeonStatus = ReadDirectoryInternal(Path, FileList);
  824. if (IsValidRedirect(NeonStatus, Path))
  825. {
  826. NeonStatus = ReadDirectoryInternal(Path, FileList);
  827. }
  828. CheckStatus(NeonStatus);
  829. }
  830. //---------------------------------------------------------------------------
  831. void __fastcall TWebDAVFileSystem::ReadSymlink(TRemoteFile * /*SymlinkFile*/,
  832. TRemoteFile *& /*File*/)
  833. {
  834. // we never set SymLink flag, so we should never get here
  835. DebugFail();
  836. }
  837. //---------------------------------------------------------------------------
  838. void __fastcall TWebDAVFileSystem::ReadFile(const UnicodeString FileName,
  839. TRemoteFile *& File)
  840. {
  841. CustomReadFile(FileName, File, NULL);
  842. }
  843. //---------------------------------------------------------------------------
  844. void TWebDAVFileSystem::NeonPropsResult(
  845. void * UserData, const ne_uri * Uri, const ne_prop_result_set * Results)
  846. {
  847. UnicodeString Path = StrFromNeon(PathUnescape(Uri->path).c_str());
  848. TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
  849. if (Data.FileList != NULL)
  850. {
  851. UnicodeString FileListPath = Data.FileSystem->AbsolutePath(Data.FileList->Directory, false);
  852. if (UnixSamePath(Path, FileListPath))
  853. {
  854. Path = UnixIncludeTrailingBackslash(UnixIncludeTrailingBackslash(Path) + L"..");
  855. }
  856. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  857. File->Terminal = Data.FileSystem->FTerminal;
  858. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  859. Data.FileList->AddFile(File.release());
  860. }
  861. else
  862. {
  863. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  864. }
  865. }
  866. //---------------------------------------------------------------------------
  867. const char * __fastcall TWebDAVFileSystem::GetProp(
  868. const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
  869. {
  870. ne_propname Prop;
  871. Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
  872. Prop.name = Name;
  873. return ne_propset_value(Results, &Prop);
  874. }
  875. //---------------------------------------------------------------------------
  876. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  877. const UnicodeString & Path, const ne_prop_result_set * Results)
  878. {
  879. File->FullFileName = UnixExcludeTrailingBackslash(Path);
  880. // Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
  881. // It seems that all servers actually use the trailing slash, including IIS, mod_Dav, IT Hit, OpenDrive, etc.
  882. bool Collection = (File->FullFileName != Path);
  883. File->FileName = UnixExtractFileName(File->FullFileName);
  884. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  885. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  886. if (ContentLength != NULL)
  887. {
  888. File->Size = StrToInt64Def(ContentLength, 0);
  889. }
  890. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  891. if (DebugAlwaysTrue(LastModified != NULL))
  892. {
  893. char WeekDay[4] = { L'\0' };
  894. int Year = 0;
  895. char MonthStr[4] = { L'\0' };
  896. int Day = 0;
  897. int Hour = 0;
  898. int Min = 0;
  899. int Sec = 0;
  900. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  901. int Filled =
  902. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  903. // we need at least a complete date
  904. if (Filled >= 4)
  905. {
  906. int Month = ParseShortEngMonthName(MonthStr);
  907. if (Month >= 1)
  908. {
  909. TDateTime Modification =
  910. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  911. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  912. File->Modification = ConvertTimestampFromUTC(Modification);
  913. File->ModificationFmt = mfFull;
  914. }
  915. }
  916. }
  917. // optimization
  918. if (!Collection)
  919. {
  920. // This is possibly redundant code as all servers we know (see a comment above)
  921. // indicate the folder by trailing slash too
  922. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  923. if (ResourceType != NULL)
  924. {
  925. // property has XML value
  926. UnicodeString AResourceType = ResourceType;
  927. // this is very poor parsing
  928. if (ContainsText(ResourceType, L"<DAV:collection"))
  929. {
  930. Collection = true;
  931. }
  932. }
  933. }
  934. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  935. // this is MS extension (draft-hopmann-collection-props-00)
  936. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  937. if (IsHidden != NULL)
  938. {
  939. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  940. }
  941. const char * Owner = GetProp(Results, PROP_OWNER);
  942. if (Owner != NULL)
  943. {
  944. File->Owner.Name = Owner;
  945. }
  946. const UnicodeString RightsDelimiter(L", ");
  947. UnicodeString HumanRights;
  948. // Proprietary property of mod_dav
  949. // http://www.webdav.org/mod_dav/#imp
  950. const char * Executable = GetProp(Results, PROP_EXECUTABLE, MODDAV_PROP_NAMESPACE);
  951. if (Executable != NULL)
  952. {
  953. if (strcmp(Executable, "T") == NULL)
  954. {
  955. UnicodeString ExecutableRights;
  956. // The "gear" character is supported since Windows 8
  957. if (IsWin8())
  958. {
  959. ExecutableRights = L"\u2699";
  960. }
  961. else
  962. {
  963. ExecutableRights = LoadStr(EXECUTABLE);
  964. }
  965. AddToList(HumanRights, ExecutableRights, RightsDelimiter);
  966. }
  967. }
  968. struct ne_lock * Lock = static_cast<struct ne_lock *>(ne_propset_private(Results));
  969. if ((Lock != NULL) && (Lock->token != NULL))
  970. {
  971. UnicodeString Owner;
  972. if (Lock->owner != NULL)
  973. {
  974. Owner = StrFromNeon(Lock->owner).Trim();
  975. }
  976. UnicodeString LockRights;
  977. if (IsWin8())
  978. {
  979. // The "lock" character is supported since Windows 8
  980. LockRights = L"\uD83D\uDD12" + Owner;
  981. }
  982. else
  983. {
  984. LockRights = LoadStr(LOCKED);
  985. if (!Owner.IsEmpty())
  986. {
  987. LockRights = FORMAT(L"%s (%s)", (LockRights, Owner));
  988. }
  989. }
  990. AddToList(HumanRights, LockRights, RightsDelimiter);
  991. }
  992. File->HumanRights = HumanRights;
  993. }
  994. //---------------------------------------------------------------------------
  995. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  996. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  997. {
  998. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  999. TReadFileData Data;
  1000. Data.FileSystem = this;
  1001. Data.File = AFile.get();
  1002. Data.FileList = NULL;
  1003. ClearNeonError();
  1004. int Result =
  1005. ne_simple_propfind(FNeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  1006. NeonPropsResult, &Data);
  1007. if (Result == NE_OK)
  1008. {
  1009. File = AFile.release();
  1010. }
  1011. return Result;
  1012. }
  1013. //---------------------------------------------------------------------------
  1014. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  1015. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  1016. {
  1017. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1018. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  1019. if (IsValidRedirect(NeonStatus, FileName))
  1020. {
  1021. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  1022. }
  1023. CheckStatus(NeonStatus);
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  1027. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  1028. {
  1029. Action.Recursive();
  1030. ClearNeonError();
  1031. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1032. RawByteString Path = PathToNeon(FilePath(File));
  1033. // WebDAV does not allow non-recursive delete:
  1034. // RFC 4918, section 9.6.1:
  1035. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  1036. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  1037. CheckStatus(ne_delete(FNeonSession, Path.c_str()));
  1038. // The lock is removed with the file, but if a file with the same name gets created,
  1039. // we would try to use obsoleted lock token with it, what the server would reject
  1040. // (mod_dav returns "412 Precondition Failed")
  1041. DiscardLock(Path);
  1042. }
  1043. //---------------------------------------------------------------------------
  1044. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  1045. const UnicodeString & NewName)
  1046. {
  1047. // 0 = no overwrite
  1048. return ne_move(FNeonSession, 0, PathToNeon(FileName), PathToNeon(NewName));
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName,
  1052. const UnicodeString NewName)
  1053. {
  1054. ClearNeonError();
  1055. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1056. UnicodeString Path = FileName;
  1057. int NeonStatus = RenameFileInternal(Path, NewName);
  1058. if (IsValidRedirect(NeonStatus, Path))
  1059. {
  1060. NeonStatus = RenameFileInternal(Path, NewName);
  1061. }
  1062. CheckStatus(NeonStatus);
  1063. // See a comment in DeleteFile
  1064. DiscardLock(PathToNeon(Path));
  1065. }
  1066. //---------------------------------------------------------------------------
  1067. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName,
  1068. const UnicodeString NewName)
  1069. {
  1070. DebugFail();
  1071. }
  1072. //---------------------------------------------------------------------------
  1073. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString DirName)
  1074. {
  1075. ClearNeonError();
  1076. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1077. CheckStatus(ne_mkcol(FNeonSession, PathToNeon(DirName)));
  1078. }
  1079. //---------------------------------------------------------------------------
  1080. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  1081. const UnicodeString PointTo, bool /*Symbolic*/)
  1082. {
  1083. DebugFail();
  1084. }
  1085. //---------------------------------------------------------------------------
  1086. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1087. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  1088. TChmodSessionAction & /*Action*/)
  1089. {
  1090. DebugFail();
  1091. }
  1092. //---------------------------------------------------------------------------
  1093. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1094. {
  1095. DebugFail();
  1096. return false;
  1097. }
  1098. //---------------------------------------------------------------------------
  1099. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
  1100. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  1101. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  1102. {
  1103. DebugFail();
  1104. }
  1105. //---------------------------------------------------------------------------
  1106. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1107. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1108. TFileOperationProgressType * OperationProgress,
  1109. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1110. int Params)
  1111. {
  1112. // all = "yes to newer"
  1113. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1114. TQueryButtonAlias Aliases[3];
  1115. Aliases[0].Button = qaAll;
  1116. Aliases[0].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  1117. Aliases[0].GroupWith = qaYes;
  1118. Aliases[0].GrouppedShiftState = TShiftState() << ssCtrl;
  1119. Aliases[1].Button = qaYesToAll;
  1120. Aliases[1].GroupWith = qaYes;
  1121. Aliases[1].GrouppedShiftState = TShiftState() << ssShift;
  1122. Aliases[2].Button = qaNoToAll;
  1123. Aliases[2].GroupWith = qaNo;
  1124. Aliases[2].GrouppedShiftState = TShiftState() << ssShift;
  1125. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1126. QueryParams.Aliases = Aliases;
  1127. QueryParams.AliasesCount = LENOF(Aliases);
  1128. unsigned int Answer;
  1129. {
  1130. TSuspendFileOperationProgress Suspend(OperationProgress);
  1131. Answer =
  1132. FTerminal->ConfirmFileOverwrite(
  1133. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1134. (OperationProgress->Side == osLocal) ? osRemote : osLocal,
  1135. CopyParam, Params, OperationProgress);
  1136. }
  1137. switch (Answer)
  1138. {
  1139. case qaYes:
  1140. // noop
  1141. break;
  1142. case qaNo:
  1143. THROW_SKIP_FILE_NULL;
  1144. default:
  1145. DebugFail();
  1146. case qaCancel:
  1147. if (!OperationProgress->Cancel)
  1148. {
  1149. OperationProgress->Cancel = csCancel;
  1150. }
  1151. Abort();
  1152. break;
  1153. }
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1157. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1158. {
  1159. DebugFail();
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1163. TCaptureOutputEvent /*OutputEvent*/)
  1164. {
  1165. DebugFail();
  1166. }
  1167. //---------------------------------------------------------------------------
  1168. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1169. {
  1170. return NULL;
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. void TWebDAVFileSystem::NeonQuotaResult(
  1174. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1175. {
  1176. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1177. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1178. if (Value != NULL)
  1179. {
  1180. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1181. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1182. if (Value != NULL)
  1183. {
  1184. SpaceAvailable.BytesAvailableToUser =
  1185. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1186. }
  1187. }
  1188. }
  1189. //---------------------------------------------------------------------------
  1190. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1191. TSpaceAvailable & ASpaceAvailable)
  1192. {
  1193. // RFC4331: http://tools.ietf.org/html/rfc4331
  1194. // This is known to be supported by:
  1195. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1196. // unconditionally, even when not explicitly requested)
  1197. // Server: Apache/2.2.17 (Fedora)
  1198. // X-Powered-By: PHP/5.5.7
  1199. // X-DAV-Powered-By: OpenDrive
  1200. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1201. // IT Hit WebDAV Server:
  1202. // Server: Microsoft-HTTPAPI/1.0
  1203. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1204. // Yandex disk:
  1205. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1206. // Server: MochiWeb/1.0
  1207. // OneDrive:
  1208. // it sends the properties unconditionally, even when not explicitly requested
  1209. UnicodeString APath = DirectoryPath(Path);
  1210. ne_propname QuotaProps[3];
  1211. memset(QuotaProps, 0, sizeof(QuotaProps));
  1212. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1213. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1214. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1215. QuotaProps[1].name = PROP_QUOTA_USED;
  1216. QuotaProps[2].nspace = NULL;
  1217. QuotaProps[2].name = NULL;
  1218. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1219. CheckStatus(
  1220. ne_simple_propfind(FNeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1221. NeonQuotaResult, &ASpaceAvailable));
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1225. const UnicodeString ATargetDir, const TCopyParamType * CopyParam,
  1226. int Params, TFileOperationProgressType * OperationProgress,
  1227. TOnceDoneOperation & OnceDoneOperation)
  1228. {
  1229. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  1230. Params &= ~cpAppend;
  1231. UnicodeString FileName, FileNameOnly;
  1232. UnicodeString TargetDir = AbsolutePath(ATargetDir, false);
  1233. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  1234. intptr_t Index = 0;
  1235. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  1236. {
  1237. bool Success = false;
  1238. FileName = FilesToCopy->Strings[Index];
  1239. FileNameOnly = ExtractFileName(FileName, false);
  1240. try
  1241. {
  1242. try
  1243. {
  1244. if (FTerminal->SessionData->CacheDirectories)
  1245. {
  1246. FTerminal->DirectoryModified(TargetDir, false);
  1247. if (::DirectoryExists(ApiPath(::ExtractFilePath(FileName))))
  1248. {
  1249. FTerminal->DirectoryModified(FullTargetDir + FileNameOnly, true);
  1250. }
  1251. }
  1252. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  1253. tfFirstLevel);
  1254. Success = true;
  1255. }
  1256. catch (EScpSkipFile & E)
  1257. {
  1258. TSuspendFileOperationProgress Suspend(OperationProgress);
  1259. if (!FTerminal->HandleException(&E))
  1260. {
  1261. throw;
  1262. }
  1263. }
  1264. }
  1265. __finally
  1266. {
  1267. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1268. }
  1269. Index++;
  1270. }
  1271. }
  1272. //---------------------------------------------------------------------------
  1273. void __fastcall TWebDAVFileSystem::SourceRobust(const UnicodeString FileName,
  1274. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1275. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1276. {
  1277. // the same in TSFTPFileSystem
  1278. TUploadSessionAction Action(FTerminal->ActionLog);
  1279. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  1280. do
  1281. {
  1282. bool ChildError = false;
  1283. try
  1284. {
  1285. Source(FileName, TargetDir, CopyParam, Params, OperationProgress,
  1286. Flags, Action, ChildError);
  1287. }
  1288. catch (Exception & E)
  1289. {
  1290. if (!RobustLoop.TryReopen(E))
  1291. {
  1292. if (!ChildError)
  1293. {
  1294. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1295. }
  1296. throw;
  1297. }
  1298. }
  1299. if (RobustLoop.ShouldRetry())
  1300. {
  1301. OperationProgress->RollbackTransfer();
  1302. Action.Restart();
  1303. // prevent overwrite confirmations
  1304. // (should not be set for directories!)
  1305. Params |= cpNoConfirmation;
  1306. }
  1307. }
  1308. while (RobustLoop.Retry());
  1309. }
  1310. //---------------------------------------------------------------------------
  1311. void __fastcall TWebDAVFileSystem::Source(const UnicodeString FileName,
  1312. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1313. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1314. TUploadSessionAction & Action, bool & ChildError)
  1315. {
  1316. Action.FileName(ExpandUNCFileName(FileName));
  1317. OperationProgress->SetFile(FileName, false);
  1318. if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
  1319. {
  1320. THROW_SKIP_FILE_NULL;
  1321. }
  1322. HANDLE File;
  1323. __int64 MTime;
  1324. __int64 Size;
  1325. int Attrs;
  1326. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &Attrs,
  1327. &File, NULL, &MTime, NULL, &Size);
  1328. bool Dir = FLAGSET(Attrs, faDirectory);
  1329. int FD = -1;
  1330. try
  1331. {
  1332. OperationProgress->SetFileInProgress();
  1333. if (Dir)
  1334. {
  1335. Action.Cancel();
  1336. DirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  1337. Attrs, CopyParam, Params, OperationProgress, Flags);
  1338. }
  1339. else
  1340. {
  1341. UnicodeString DestFileName =
  1342. FTerminal->ChangeFileName(
  1343. CopyParam, ExtractFileName(FileName), osLocal,
  1344. FLAGSET(Flags, tfFirstLevel));
  1345. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  1346. OperationProgress->SetLocalSize(Size);
  1347. // Suppose same data size to transfer as to read
  1348. // (not true with ASCII transfer)
  1349. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1350. OperationProgress->TransferingFile = false;
  1351. UnicodeString DestFullName = TargetDir + DestFileName;
  1352. TRemoteFile * RemoteFile = NULL;
  1353. try
  1354. {
  1355. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1356. FIgnoreAuthenticationFailure = iafWaiting;
  1357. // this should not throw
  1358. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1359. }
  1360. catch (...)
  1361. {
  1362. if (!FTerminal->Active)
  1363. {
  1364. throw;
  1365. }
  1366. }
  1367. TDateTime Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1368. if (RemoteFile != NULL)
  1369. {
  1370. TOverwriteFileParams FileParams;
  1371. FileParams.SourceSize = Size;
  1372. FileParams.SourceTimestamp = Modification;
  1373. FileParams.DestSize = RemoteFile->Size;
  1374. FileParams.DestTimestamp = RemoteFile->Modification;
  1375. delete RemoteFile;
  1376. ConfirmOverwrite(FileName, DestFileName, OperationProgress,
  1377. &FileParams, CopyParam, Params);
  1378. }
  1379. DestFullName = TargetDir + DestFileName;
  1380. // only now, we know the final destination
  1381. // (not really true as we do not support changing file name on overwrite dialog)
  1382. Action.Destination(DestFullName);
  1383. FILE_OPERATION_LOOP_BEGIN
  1384. {
  1385. SetFilePointer(File, 0, NULL, FILE_BEGIN);
  1386. FD = _open_osfhandle((intptr_t)File, O_BINARY);
  1387. if (FD < 0)
  1388. {
  1389. THROW_SKIP_FILE_NULL;
  1390. }
  1391. TAutoFlag UploadingFlag(FUploading);
  1392. ClearNeonError();
  1393. CheckStatus(ne_put(FNeonSession, PathToNeon(DestFullName), FD));
  1394. }
  1395. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1396. if (CopyParam->PreserveTime)
  1397. {
  1398. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1399. (StandardTimestamp(Modification))));
  1400. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Modification);
  1401. try
  1402. {
  1403. TDateTime ModificationUTC = ConvertTimestampToUTC(Modification);
  1404. TFormatSettings FormatSettings = GetEngFormatSettings();
  1405. UnicodeString LastModified =
  1406. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1407. UTF8String NeonLastModified(LastModified);
  1408. // second element is "NULL-terminating"
  1409. ne_proppatch_operation Operations[2];
  1410. memset(Operations, 0, sizeof(Operations));
  1411. ne_propname LastModifiedProp;
  1412. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1413. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1414. Operations[0].name = &LastModifiedProp;
  1415. Operations[0].type = ne_propset;
  1416. Operations[0].value = NeonLastModified.c_str();
  1417. int Status = ne_proppatch(FNeonSession, PathToNeon(DestFullName), Operations);
  1418. if (Status == NE_ERROR)
  1419. {
  1420. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1421. (GetNeonError())));
  1422. // Ignore errors as major WebDAV servers (like IIS), do not support
  1423. // changing getlastmodified.
  1424. // The only server we found that supports this is TradeMicro SafeSync.
  1425. // But it announces itself as "Server: Apache",
  1426. // so it's not reliable to autodetect the support.
  1427. // Microsoft Office alegedly uses <Win32LastModifiedTime>
  1428. // http://sabre.io/dav/clients/msoffice/
  1429. // Carot DAV does that too. But we do not know what server does support this.
  1430. TouchAction.Cancel();
  1431. }
  1432. else
  1433. {
  1434. CheckStatus(Status);
  1435. }
  1436. }
  1437. catch (Exception & E)
  1438. {
  1439. TouchAction.Rollback(&E);
  1440. ChildError = true;
  1441. throw;
  1442. }
  1443. }
  1444. FTerminal->LogFileDone(OperationProgress);
  1445. }
  1446. }
  1447. __finally
  1448. {
  1449. if (FD >= 0)
  1450. {
  1451. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1452. // but it crashes code guard
  1453. _close(FD);
  1454. }
  1455. else if (File != NULL)
  1456. {
  1457. CloseHandle(File);
  1458. }
  1459. }
  1460. // TODO : Delete also read-only files.
  1461. if (FLAGSET(Params, cpDelete))
  1462. {
  1463. if (!Dir)
  1464. {
  1465. FILE_OPERATION_LOOP_BEGIN
  1466. {
  1467. THROWOSIFFALSE(::DeleteFile(ApiPath(FileName).c_str()));
  1468. }
  1469. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  1470. }
  1471. }
  1472. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1473. {
  1474. FILE_OPERATION_LOOP_BEGIN
  1475. {
  1476. THROWOSIFFALSE(FileSetAttr(ApiPath(FileName), Attrs & ~faArchive) == 0);
  1477. }
  1478. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  1479. }
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. void __fastcall TWebDAVFileSystem::DirectorySource(const UnicodeString DirectoryName,
  1483. const UnicodeString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  1484. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1485. {
  1486. UnicodeString DestDirectoryName =
  1487. FTerminal->ChangeFileName(
  1488. CopyParam, ExtractFileName(ExcludeTrailingBackslash(DirectoryName)),
  1489. osLocal, FLAGSET(Flags, tfFirstLevel));
  1490. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  1491. // create DestFullName if it does not exist
  1492. if (!FTerminal->FileExists(DestFullName))
  1493. {
  1494. TRemoteProperties Properties;
  1495. if (CopyParam->PreserveRights)
  1496. {
  1497. Properties.Valid = TValidProperties() << vpRights;
  1498. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  1499. }
  1500. FTerminal->CreateDirectory(DestFullName, &Properties);
  1501. }
  1502. OperationProgress->SetFile(DirectoryName);
  1503. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1504. TSearchRecChecked SearchRec;
  1505. bool FindOK;
  1506. FILE_OPERATION_LOOP_BEGIN
  1507. {
  1508. FindOK =
  1509. (FindFirstChecked(DirectoryName + L"*.*", FindAttrs, SearchRec) == 0);
  1510. }
  1511. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1512. try
  1513. {
  1514. while (FindOK && !OperationProgress->Cancel)
  1515. {
  1516. UnicodeString FileName = DirectoryName + SearchRec.Name;
  1517. try
  1518. {
  1519. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1520. {
  1521. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  1522. Flags & ~(tfFirstLevel));
  1523. }
  1524. }
  1525. catch (EScpSkipFile & E)
  1526. {
  1527. // If ESkipFile occurs, just log it and continue with next file
  1528. TSuspendFileOperationProgress Suspend(OperationProgress);
  1529. // here a message to user was displayed, which was not appropriate
  1530. // when user refused to overwrite the file in subdirectory.
  1531. // hopefully it won't be missing in other situations.
  1532. if (!FTerminal->HandleException(&E))
  1533. {
  1534. throw;
  1535. }
  1536. }
  1537. FILE_OPERATION_LOOP_BEGIN
  1538. {
  1539. FindOK = (FindNextChecked(SearchRec) == 0);
  1540. }
  1541. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1542. }
  1543. }
  1544. __finally
  1545. {
  1546. FindClose(SearchRec);
  1547. }
  1548. // TODO : Delete also read-only directories.
  1549. // TODO : Show error message on failure.
  1550. if (!OperationProgress->Cancel)
  1551. {
  1552. if (FLAGSET(Params, cpDelete))
  1553. {
  1554. RemoveDir(ApiPath(DirectoryName));
  1555. }
  1556. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1557. {
  1558. FILE_OPERATION_LOOP_BEGIN
  1559. {
  1560. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  1561. }
  1562. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  1563. }
  1564. }
  1565. }
  1566. //---------------------------------------------------------------------------
  1567. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1568. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1569. int Params, TFileOperationProgressType * OperationProgress,
  1570. TOnceDoneOperation & OnceDoneOperation)
  1571. {
  1572. Params &= ~cpAppend;
  1573. UnicodeString FullTargetDir = ::IncludeTrailingBackslash(TargetDir);
  1574. int Index = 0;
  1575. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  1576. {
  1577. UnicodeString FileName = FilesToCopy->Strings[Index];
  1578. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  1579. bool Success = false;
  1580. try
  1581. {
  1582. try
  1583. {
  1584. SinkRobust(AbsolutePath(FileName, false), File, FullTargetDir, CopyParam, Params,
  1585. OperationProgress, tfFirstLevel);
  1586. Success = true;
  1587. }
  1588. catch (EScpSkipFile & E)
  1589. {
  1590. TSuspendFileOperationProgress Suspend(OperationProgress);
  1591. if (!FTerminal->HandleException(&E))
  1592. {
  1593. throw;
  1594. }
  1595. }
  1596. }
  1597. __finally
  1598. {
  1599. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1600. }
  1601. Index++;
  1602. }
  1603. }
  1604. //---------------------------------------------------------------------------
  1605. void __fastcall TWebDAVFileSystem::SinkRobust(const UnicodeString FileName,
  1606. const TRemoteFile * File, const UnicodeString TargetDir,
  1607. const TCopyParamType * CopyParam, int Params,
  1608. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1609. {
  1610. // the same in TSFTPFileSystem
  1611. TDownloadSessionAction Action(FTerminal->ActionLog);
  1612. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  1613. do
  1614. {
  1615. bool ChildError = false;
  1616. try
  1617. {
  1618. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  1619. Flags, Action, ChildError);
  1620. }
  1621. catch (Exception & E)
  1622. {
  1623. if (!RobustLoop.TryReopen(E))
  1624. {
  1625. if (!ChildError)
  1626. {
  1627. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1628. }
  1629. throw;
  1630. }
  1631. }
  1632. if (RobustLoop.ShouldRetry())
  1633. {
  1634. OperationProgress->RollbackTransfer();
  1635. Action.Restart();
  1636. DebugAssert(File != NULL);
  1637. if (!File->IsDirectory)
  1638. {
  1639. // prevent overwrite confirmations
  1640. Params |= cpNoConfirmation;
  1641. }
  1642. }
  1643. }
  1644. while (RobustLoop.Retry());
  1645. }
  1646. //---------------------------------------------------------------------------
  1647. void TWebDAVFileSystem::NeonCreateRequest(
  1648. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1649. {
  1650. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1651. ne_set_request_private(Request, SESSION_FS_KEY, FileSystem);
  1652. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1653. FileSystem->FNtlmAuthenticationFailed = false;
  1654. }
  1655. //---------------------------------------------------------------------------
  1656. void TWebDAVFileSystem::NeonPreSend(
  1657. ne_request * Request, void * UserData, ne_buffer * Header)
  1658. {
  1659. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1660. FileSystem->FAuthorizationProtocol = L"";
  1661. UnicodeString HeaderBuf(StrFromNeon(AnsiString(Header->data, Header->used)));
  1662. const UnicodeString AuthorizationHeaderName(L"Authorization:");
  1663. int P = HeaderBuf.Pos(AuthorizationHeaderName);
  1664. if (P > 0)
  1665. {
  1666. P += AuthorizationHeaderName.Length();
  1667. int P2 = PosEx(L"\n", HeaderBuf, P);
  1668. if (DebugAlwaysTrue(P2 > 0))
  1669. {
  1670. UnicodeString AuthorizationHeader = HeaderBuf.SubString(P, P2 - P).Trim();
  1671. FileSystem->FAuthorizationProtocol = CutToChar(AuthorizationHeader, L' ', false);
  1672. FileSystem->FLastAuthorizationProtocol = FileSystem->FAuthorizationProtocol;
  1673. }
  1674. }
  1675. if (FileSystem->FDownloading)
  1676. {
  1677. // Needed by IIS server to make it download source code, not code output,
  1678. // and mainly to even allow downloading file with unregistered extensions.
  1679. // Without it files like .001 return 404 (Not found) HTTP code.
  1680. // http://msdn.microsoft.com/en-us/library/cc250098.aspx
  1681. // http://msdn.microsoft.com/en-us/library/cc250216.aspx
  1682. // http://lists.manyfish.co.uk/pipermail/neon/2012-April/001452.html
  1683. // It's also supported by Oracle server:
  1684. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1685. // We do not know yet of any server that fails when the header is used,
  1686. // so it's added unconditionally.
  1687. ne_buffer_zappend(Header, "Translate: f\r\n");
  1688. }
  1689. if (FileSystem->FTerminal->Log->Logging)
  1690. {
  1691. const char * Buffer;
  1692. size_t Size;
  1693. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1694. {
  1695. // all neon request types that use ne_add_request_header
  1696. // use XML content-type, so it's text-based
  1697. DebugAssert(ContainsStr(HeaderBuf, L"Content-Type: " NE_XML_MEDIA_TYPE));
  1698. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1699. }
  1700. }
  1701. if (FileSystem->FUploading)
  1702. {
  1703. ne_set_request_body_provider_pre(Request,
  1704. FileSystem->NeonUploadBodyProvider, FileSystem);
  1705. }
  1706. FileSystem->FResponse = L"";
  1707. }
  1708. //---------------------------------------------------------------------------
  1709. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1710. const ne_status * /*Status*/)
  1711. {
  1712. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1713. if (!FileSystem->FResponse.IsEmpty())
  1714. {
  1715. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1716. }
  1717. return NE_OK;
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. bool __fastcall TWebDAVFileSystem::IsNtlmAuthentication()
  1721. {
  1722. return
  1723. SameText(FAuthorizationProtocol, L"NTLM") ||
  1724. SameText(FAuthorizationProtocol, L"Negotiate");
  1725. }
  1726. //---------------------------------------------------------------------------
  1727. void __fastcall TWebDAVFileSystem::HttpAuthenticationFailed()
  1728. {
  1729. // NTLM/GSSAPI failed
  1730. if (IsNtlmAuthentication())
  1731. {
  1732. if (FNtlmAuthenticationFailed)
  1733. {
  1734. // Next time do not try Negotiate (NTLM/GSSAPI),
  1735. // otherwise we end up in an endless loop.
  1736. // If the server returns all other challenges in the response, removing the Negotiate
  1737. // protocol will itself ensure that other protocols are tried (we haven't seen this behaviour).
  1738. // IIS will return only Negotiate response if the request was Negotiate, so there's no fallback.
  1739. // We have to retry with a fresh request. That's what FAuthenticationRetry does.
  1740. FTerminal->LogEvent(FORMAT(L"%s challenge failed, will try different challenge", (FAuthorizationProtocol)));
  1741. ne_remove_server_auth(FNeonSession);
  1742. NeonAddAuthentiation(false);
  1743. FAuthenticationRetry = true;
  1744. }
  1745. else
  1746. {
  1747. // The first 401 is expected, the server is using it to send WWW-Authenticate header with data.
  1748. FNtlmAuthenticationFailed = true;
  1749. }
  1750. }
  1751. }
  1752. //---------------------------------------------------------------------------
  1753. void TWebDAVFileSystem::NeonPostHeaders(ne_request * /*Req*/, void * UserData, const ne_status * Status)
  1754. {
  1755. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1756. if (Status->code == HttpUnauthorized)
  1757. {
  1758. FileSystem->HttpAuthenticationFailed();
  1759. }
  1760. }
  1761. //---------------------------------------------------------------------------
  1762. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1763. {
  1764. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1765. ssize_t Result;
  1766. if (FileSystem->CancelTransfer())
  1767. {
  1768. Result = -1;
  1769. }
  1770. else
  1771. {
  1772. Result = 1;
  1773. }
  1774. return Result;
  1775. }
  1776. //---------------------------------------------------------------------------
  1777. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1778. {
  1779. const char * Value = ne_get_response_header(Request, Name);
  1780. if (Value != NULL)
  1781. {
  1782. AddToList(List, StrFromNeon(Value), L"; ");
  1783. }
  1784. }
  1785. //---------------------------------------------------------------------------
  1786. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1787. {
  1788. DebugAssert(UserData == Request);
  1789. TWebDAVFileSystem * FileSystem =
  1790. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1791. bool AuthenticationFailureCode = (Status->code == HttpUnauthorized);
  1792. bool PasswordAuthenticationFailed = AuthenticationFailureCode && FileSystem->FAuthenticationRequested;
  1793. bool AuthenticationFailed = PasswordAuthenticationFailed || (AuthenticationFailureCode && FileSystem->IsNtlmAuthentication());
  1794. bool AuthenticationNeeded = AuthenticationFailureCode && !AuthenticationFailed;
  1795. if (FileSystem->FInitialHandshake)
  1796. {
  1797. UnicodeString Line;
  1798. if (AuthenticationNeeded)
  1799. {
  1800. Line = LoadStr(STATUS_AUTHENTICATE);
  1801. }
  1802. else if (AuthenticationFailed)
  1803. {
  1804. Line = LoadStr(FTP_ACCESS_DENIED);
  1805. }
  1806. else if (Status->klass == 2)
  1807. {
  1808. Line = LoadStr(STATUS_AUTHENTICATED);
  1809. }
  1810. if (!Line.IsEmpty())
  1811. {
  1812. FileSystem->FTerminal->Information(Line, true);
  1813. }
  1814. UnicodeString RemoteSystem;
  1815. // Used by IT Hit WebDAV Server:
  1816. // Server: Microsoft-HTTPAPI/1.0
  1817. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1818. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1819. // Used by OpenDrive:
  1820. // Server: Apache/2.2.17 (Fedora)
  1821. // X-Powered-By: PHP/5.5.7
  1822. // X-DAV-Powered-By: OpenDrive
  1823. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1824. // Used by IIS:
  1825. // Server: Microsoft-IIS/8.5
  1826. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1827. // Not really useful.
  1828. // Can be e.g. "PleskLin"
  1829. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1830. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1831. }
  1832. // When we explicitly fail authentication of request
  1833. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1834. // neon resets its internal password store and tries the next request
  1835. // without calling our authentication hook first
  1836. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1837. // what likely fails, but we do not want to reset out password
  1838. // (as it was not even tried yet for this request).
  1839. if (PasswordAuthenticationFailed)
  1840. {
  1841. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1842. {
  1843. FileSystem->FPassword = RawByteString();
  1844. }
  1845. else
  1846. {
  1847. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1848. }
  1849. }
  1850. return ne_accept_2xx(UserData, Request, Status);
  1851. }
  1852. //---------------------------------------------------------------------------
  1853. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1854. {
  1855. bool Result = false;
  1856. if ((FUploading || FDownloading) &&
  1857. (FTerminal->OperationProgress != NULL) &&
  1858. (FTerminal->OperationProgress->Cancel != csContinue))
  1859. {
  1860. FCancelled = true;
  1861. Result = true;
  1862. }
  1863. return Result;
  1864. }
  1865. //---------------------------------------------------------------------------
  1866. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1867. {
  1868. ne_request * Request = static_cast<ne_request *>(UserData);
  1869. TWebDAVFileSystem * FileSystem =
  1870. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1871. if (FileSystem->FTerminal->Log->Logging)
  1872. {
  1873. ne_content_type ContentType;
  1874. if (ne_get_content_type(Request, &ContentType) == 0)
  1875. {
  1876. // The main point of the content-type check was to exclude
  1877. // GET responses (with file contents).
  1878. // But this won't work when downloading text files that have text
  1879. // content type on their own, hence the additional not-downloading test.
  1880. if (!FileSystem->FDownloading &&
  1881. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1882. media_type_is_xml(&ContentType)))
  1883. {
  1884. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1885. FileSystem->FResponse += Content;
  1886. }
  1887. ne_free(ContentType.value);
  1888. }
  1889. }
  1890. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1891. return Result;
  1892. }
  1893. //---------------------------------------------------------------------------
  1894. void __fastcall TWebDAVFileSystem::Sink(const UnicodeString FileName,
  1895. const TRemoteFile * File, const UnicodeString TargetDir,
  1896. const TCopyParamType * CopyParam, int Params,
  1897. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1898. TDownloadSessionAction & Action, bool & ChildError)
  1899. {
  1900. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1901. Action.FileName(FileName);
  1902. DebugAssert(File);
  1903. TFileMasks::TParams MaskParams;
  1904. MaskParams.Size = File->Size;
  1905. MaskParams.Modification = File->Modification;
  1906. UnicodeString BaseFileName = FTerminal->GetBaseFileName(FileName);
  1907. if (!CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams))
  1908. {
  1909. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  1910. THROW_SKIP_FILE_NULL;
  1911. }
  1912. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  1913. {
  1914. OperationProgress->AddSkippedFileSize(File->Size);
  1915. THROW_SKIP_FILE_NULL;
  1916. }
  1917. FTerminal->LogFileDetails(FileName, TDateTime(), File->Size);
  1918. OperationProgress->SetFile(FileName);
  1919. UnicodeString DestFileName =
  1920. FTerminal->ChangeFileName(
  1921. CopyParam, FileNameOnly, osRemote, FLAGSET(Flags, tfFirstLevel));
  1922. UnicodeString DestFullName = TargetDir + DestFileName;
  1923. if (File->IsDirectory)
  1924. {
  1925. Action.Cancel();
  1926. if (DebugAlwaysTrue(FTerminal->CanRecurseToDirectory(File)))
  1927. {
  1928. FILE_OPERATION_LOOP_BEGIN
  1929. {
  1930. int Attrs = FileGetAttrFix(ApiPath(DestFullName));
  1931. if (FLAGCLEAR(Attrs, faDirectory)) { EXCEPTION; }
  1932. }
  1933. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  1934. FILE_OPERATION_LOOP_BEGIN
  1935. {
  1936. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  1937. }
  1938. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  1939. TSinkFileParams SinkFileParams;
  1940. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  1941. SinkFileParams.CopyParam = CopyParam;
  1942. SinkFileParams.Params = Params;
  1943. SinkFileParams.OperationProgress = OperationProgress;
  1944. SinkFileParams.Skipped = false;
  1945. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  1946. FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  1947. // Do not delete directory if some of its files were skip.
  1948. // Throw "skip file" for the directory to avoid attempt to deletion
  1949. // of any parent directory
  1950. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  1951. {
  1952. THROW_SKIP_FILE_NULL;
  1953. }
  1954. }
  1955. else
  1956. {
  1957. // file is symlink to directory, currently do nothing, but it should be
  1958. // reported to user
  1959. }
  1960. }
  1961. else
  1962. {
  1963. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  1964. if (FileExists(ApiPath(DestFullName)))
  1965. {
  1966. __int64 Size;
  1967. __int64 MTime;
  1968. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL,
  1969. NULL, NULL, &MTime, NULL, &Size);
  1970. TOverwriteFileParams FileParams;
  1971. FileParams.SourceSize = File->Size;
  1972. FileParams.SourceTimestamp = File->Modification;
  1973. FileParams.DestSize = Size;
  1974. FileParams.DestTimestamp = UnixToDateTime(MTime,
  1975. FTerminal->SessionData->DSTMode);
  1976. ConfirmOverwrite(FileName, DestFileName, OperationProgress,
  1977. &FileParams, CopyParam, Params);
  1978. }
  1979. // Suppose same data size to transfer as to write
  1980. OperationProgress->SetTransferSize(File->Size);
  1981. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1982. int Attrs = -1;
  1983. FILE_OPERATION_LOOP_BEGIN
  1984. {
  1985. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  1986. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory)) { EXCEPTION; }
  1987. }
  1988. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  1989. OperationProgress->TransferingFile = false; // not set with WebDAV protocol
  1990. UnicodeString FilePath = ::UnixExtractFilePath(FileName);
  1991. if (FilePath.IsEmpty())
  1992. {
  1993. FilePath = L"/";
  1994. }
  1995. Action.Destination(ExpandUNCFileName(DestFullName));
  1996. FILE_OPERATION_LOOP_BEGIN
  1997. {
  1998. HANDLE LocalHandle;
  1999. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress,
  2000. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  2001. {
  2002. THROW_SKIP_FILE_NULL;
  2003. }
  2004. bool DeleteLocalFile = true;
  2005. int FD = -1;
  2006. try
  2007. {
  2008. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  2009. if (FD < 0)
  2010. {
  2011. THROW_SKIP_FILE_NULL;
  2012. }
  2013. TAutoFlag DownloadingFlag(FDownloading);
  2014. ClearNeonError();
  2015. CheckStatus(ne_get(FNeonSession, PathToNeon(FileName), FD));
  2016. DeleteLocalFile = false;
  2017. if (CopyParam->PreserveTime)
  2018. {
  2019. TDateTime Modification = File->Modification;
  2020. FILETIME WrTime = DateTimeToFileTime(Modification, FTerminal->SessionData->DSTMode);
  2021. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  2022. (StandardTimestamp(Modification))));
  2023. SetFileTime(LocalHandle, NULL, NULL, &WrTime);
  2024. }
  2025. }
  2026. __finally
  2027. {
  2028. if (FD >= 0)
  2029. {
  2030. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  2031. // but it crashes code guard
  2032. _close(FD);
  2033. }
  2034. else
  2035. {
  2036. CloseHandle(LocalHandle);
  2037. }
  2038. if (DeleteLocalFile)
  2039. {
  2040. FILE_OPERATION_LOOP_BEGIN
  2041. {
  2042. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestFullName)));
  2043. }
  2044. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestFullName)));
  2045. }
  2046. }
  2047. }
  2048. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  2049. if (Attrs == -1)
  2050. {
  2051. Attrs = faArchive;
  2052. }
  2053. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  2054. if ((NewAttrs & Attrs) != NewAttrs)
  2055. {
  2056. FILE_OPERATION_LOOP_BEGIN
  2057. {
  2058. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  2059. }
  2060. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  2061. }
  2062. FTerminal->LogFileDone(OperationProgress);
  2063. }
  2064. if (FLAGSET(Params, cpDelete))
  2065. {
  2066. ChildError = true;
  2067. // If file is directory, do not delete it recursively, because it should be
  2068. // empty already. If not, it should not be deleted (some files were
  2069. // skipped or some new files were copied to it, while we were downloading)
  2070. int Params = dfNoRecursive;
  2071. FTerminal->DeleteFile(FileName, File, &Params);
  2072. ChildError = false;
  2073. }
  2074. }
  2075. //---------------------------------------------------------------------------
  2076. void __fastcall TWebDAVFileSystem::SinkFile(const UnicodeString FileName,
  2077. const TRemoteFile * File, void * Param)
  2078. {
  2079. TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
  2080. DebugAssert(Params->OperationProgress);
  2081. try
  2082. {
  2083. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  2084. Params->Params, Params->OperationProgress, Params->Flags);
  2085. }
  2086. catch (EScpSkipFile & E)
  2087. {
  2088. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  2089. Params->Skipped = true;
  2090. {
  2091. TSuspendFileOperationProgress Suspend(OperationProgress);
  2092. if (!FTerminal->HandleException(&E))
  2093. {
  2094. throw;
  2095. }
  2096. }
  2097. if (OperationProgress->Cancel)
  2098. {
  2099. Abort();
  2100. }
  2101. }
  2102. }
  2103. //---------------------------------------------------------------------------
  2104. bool TWebDAVFileSystem::VerifyCertificate(const TWebDAVCertificateData & Data, bool Aux)
  2105. {
  2106. FSessionInfo.CertificateFingerprint = Data.Fingerprint;
  2107. bool Result;
  2108. if (FTerminal->SessionData->FingerprintScan)
  2109. {
  2110. Result = false;
  2111. }
  2112. else
  2113. {
  2114. FTerminal->LogEvent(
  2115. FORMAT(L"Verifying certificate for \"%s\" with fingerprint %s and %2.2X failures",
  2116. (Data.Subject, Data.Fingerprint, Data.Failures)));
  2117. int Failures = Data.Failures;
  2118. UnicodeString SiteKey = TSessionData::FormatSiteKey(FHostName, FPortNumber);
  2119. Result =
  2120. FTerminal->VerifyCertificate(CertificateStorageKey, SiteKey, Data.Fingerprint, Data.Subject, Failures);
  2121. if (!Result)
  2122. {
  2123. UnicodeString WindowsCertificateError;
  2124. if (NeonWindowsValidateCertificate(Failures, Data.AsciiCert, WindowsCertificateError))
  2125. {
  2126. FTerminal->LogEvent(L"Certificate verified against Windows certificate store");
  2127. // There can be also other flags, not just the NE_SSL_UNTRUSTED.
  2128. Result = (Failures == 0);
  2129. }
  2130. else
  2131. {
  2132. FTerminal->LogEvent(
  2133. FORMAT(L"Certificate failed to verify against Windows certificate store: %s", (DefaultStr(WindowsCertificateError, L"no details"))));
  2134. }
  2135. }
  2136. UnicodeString Summary;
  2137. if (Failures == 0)
  2138. {
  2139. Summary = LoadStr(CERT_OK);
  2140. }
  2141. else
  2142. {
  2143. Summary = NeonCertificateFailuresErrorStr(Failures, FHostName);
  2144. }
  2145. UnicodeString ValidityTimeFormat = L"ddddd tt";
  2146. FSessionInfo.Certificate =
  2147. FMTLOAD(CERT_TEXT, (
  2148. Data.Issuer + L"\n",
  2149. Data.Subject + L"\n",
  2150. FormatDateTime(ValidityTimeFormat, Data.ValidFrom),
  2151. FormatDateTime(ValidityTimeFormat, Data.ValidUntil),
  2152. Data.Fingerprint,
  2153. Summary));
  2154. if (!Result)
  2155. {
  2156. TClipboardHandler ClipboardHandler;
  2157. ClipboardHandler.Text = Data.Fingerprint;
  2158. TQueryButtonAlias Aliases[1];
  2159. Aliases[0].Button = qaRetry;
  2160. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  2161. Aliases[0].OnClick = &ClipboardHandler.Copy;
  2162. TQueryParams Params;
  2163. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  2164. Params.NoBatchAnswers = qaYes | qaRetry;
  2165. Params.Aliases = Aliases;
  2166. Params.AliasesCount = LENOF(Aliases);
  2167. unsigned int Answer = FTerminal->QueryUser(
  2168. FMTLOAD(VERIFY_CERT_PROMPT3, (FSessionInfo.Certificate)),
  2169. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  2170. switch (Answer)
  2171. {
  2172. case qaYes:
  2173. FTerminal->CacheCertificate(CertificateStorageKey, SiteKey, Data.Fingerprint, Failures);
  2174. Result = true;
  2175. break;
  2176. case qaNo:
  2177. Result = true;
  2178. break;
  2179. default:
  2180. DebugFail();
  2181. case qaCancel:
  2182. FTerminal->Configuration->Usage->Inc(L"HostNotVerified");
  2183. Result = false;
  2184. break;
  2185. }
  2186. if (Result && !Aux)
  2187. {
  2188. FTerminal->Configuration->RememberLastFingerprint(
  2189. FTerminal->SessionData->SiteKey, TlsFingerprintType, FSessionInfo.CertificateFingerprint);
  2190. }
  2191. }
  2192. if (Result && !Aux)
  2193. {
  2194. CollectTLSSessionInfo();
  2195. }
  2196. }
  2197. return Result;
  2198. }
  2199. //------------------------------------------------------------------------------
  2200. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  2201. {
  2202. // See also TFTPFileSystem::Open().
  2203. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  2204. // can be closed as the time we need it in CollectUsage().
  2205. FTlsVersionStr = StrFromNeon(ne_ssl_get_version(FNeonSession));
  2206. AddToList(FSessionInfo.SecurityProtocolName, FTlsVersionStr, L", ");
  2207. char * Buf = ne_ssl_get_cipher(FNeonSession);
  2208. UnicodeString Cipher = StrFromNeon(Buf);
  2209. ne_free(Buf);
  2210. FSessionInfo.CSCipher = Cipher;
  2211. FSessionInfo.SCCipher = Cipher;
  2212. // see CAsyncSslSocketLayer::PrintSessionInfo()
  2213. FTerminal->LogEvent(FORMAT(L"Using %s, cipher %s", (FTlsVersionStr, Cipher)));
  2214. }
  2215. //------------------------------------------------------------------------------
  2216. // A neon-session callback to validate the SSL certificate when the CA
  2217. // is unknown (e.g. a self-signed cert), or there are other SSL
  2218. // certificate problems.
  2219. int TWebDAVFileSystem::DoNeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate, bool Aux)
  2220. {
  2221. TWebDAVCertificateData Data;
  2222. char Fingerprint[NE_SSL_DIGESTLEN] = {0};
  2223. if (ne_ssl_cert_digest(Certificate, Fingerprint) != 0)
  2224. {
  2225. strcpy(Fingerprint, "<unknown>");
  2226. }
  2227. Data.Fingerprint = StrFromNeon(Fingerprint);
  2228. Data.AsciiCert = NeonExportCertificate(Certificate);
  2229. char * Subject = ne_ssl_readable_dname(ne_ssl_cert_subject(Certificate));
  2230. Data.Subject = StrFromNeon(Subject);
  2231. ne_free(Subject);
  2232. char * Issuer = ne_ssl_readable_dname(ne_ssl_cert_issuer(Certificate));
  2233. Data.Issuer = StrFromNeon(Issuer);
  2234. ne_free(Issuer);
  2235. Data.Failures = Failures;
  2236. time_t ValidFrom;
  2237. time_t ValidUntil;
  2238. ne_ssl_cert_validity_time(Certificate, &ValidFrom, &ValidUntil);
  2239. Data.ValidFrom = UnixToDateTime(ValidFrom, dstmWin);
  2240. Data.ValidUntil = UnixToDateTime(ValidUntil, dstmWin);
  2241. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2242. return FileSystem->VerifyCertificate(Data, Aux) ? NE_OK : NE_ERROR;
  2243. }
  2244. //------------------------------------------------------------------------------
  2245. int TWebDAVFileSystem::NeonServerSSLCallbackMain(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  2246. {
  2247. return DoNeonServerSSLCallback(UserData, Failures, Certificate, false);
  2248. }
  2249. //------------------------------------------------------------------------------
  2250. int TWebDAVFileSystem::NeonServerSSLCallbackAux(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  2251. {
  2252. return DoNeonServerSSLCallback(UserData, Failures, Certificate, true);
  2253. }
  2254. //------------------------------------------------------------------------------
  2255. void TWebDAVFileSystem::NeonProvideClientCert(void * UserData, ne_session * Sess,
  2256. const ne_ssl_dname * const * /*DNames*/, int /*DNCount*/)
  2257. {
  2258. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2259. FileSystem->FTerminal->LogEvent(LoadStr(NEED_CLIENT_CERTIFICATE));
  2260. X509 * Certificate;
  2261. EVP_PKEY * PrivateKey;
  2262. if (FileSystem->FTerminal->LoadTlsCertificate(Certificate, PrivateKey))
  2263. {
  2264. ne_ssl_client_cert * NeonCertificate = ne_ssl_clicert_create(Certificate, PrivateKey);
  2265. ne_ssl_set_clicert(Sess, NeonCertificate);
  2266. ne_ssl_clicert_free(NeonCertificate);
  2267. }
  2268. }
  2269. //------------------------------------------------------------------------------
  2270. int TWebDAVFileSystem::NeonRequestAuth(
  2271. void * UserData, const char * Realm, int Attempt, char * UserName, char * Password)
  2272. {
  2273. DebugUsedParam(Realm);
  2274. DebugUsedParam(Attempt);
  2275. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2276. TTerminal * Terminal = FileSystem->FTerminal;
  2277. TSessionData * SessionData = Terminal->SessionData;
  2278. bool Result = true;
  2279. // will ask for username only once
  2280. if (FileSystem->FUserName.IsEmpty())
  2281. {
  2282. if (!SessionData->UserName.IsEmpty())
  2283. {
  2284. FileSystem->FUserName = SessionData->UserNameExpanded;
  2285. }
  2286. else
  2287. {
  2288. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  2289. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  2290. {
  2291. // note that we never get here actually
  2292. Result = false;
  2293. }
  2294. }
  2295. }
  2296. UnicodeString APassword;
  2297. if (Result)
  2298. {
  2299. // Some servers (Gallery2 on https://g2.pixi.me/w/webdav/)
  2300. // return authentication error (401) on PROPFIND request for
  2301. // non-existing files.
  2302. // When we already tried password before, do not try anymore.
  2303. // When we did not try password before (possible only when
  2304. // server does not require authentication for any previous request,
  2305. // such as when read access is not authenticated), try it now,
  2306. // but use special flag for the try, because when it fails
  2307. // we still want to try password for future requests (such as PUT).
  2308. if (!FileSystem->FPassword.IsEmpty())
  2309. {
  2310. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  2311. {
  2312. // Fail PROPFIND /nonexising request...
  2313. Result = false;
  2314. }
  2315. else
  2316. {
  2317. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  2318. }
  2319. }
  2320. else
  2321. {
  2322. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  2323. {
  2324. APassword = SessionData->Password;
  2325. FileSystem->FStoredPasswordTried = true;
  2326. }
  2327. else
  2328. {
  2329. // Asking for password (or using configured password) the first time,
  2330. // and asking for password.
  2331. // Note that we never get false here actually
  2332. Result =
  2333. Terminal->PromptUser(
  2334. SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  2335. LoadStr(PASSWORD_PROMPT), false, NE_ABUFSIZ, APassword);
  2336. }
  2337. if (Result)
  2338. {
  2339. // While neon remembers the password on its own,
  2340. // we need to keep a copy in case neon store gets reset by
  2341. // 401 response to PROPFIND /nonexisting on G2, see above.
  2342. // Possibly we can do this for G2 servers only.
  2343. FileSystem->FPassword = Terminal->EncryptPassword(APassword);
  2344. }
  2345. }
  2346. }
  2347. if (Result)
  2348. {
  2349. strncpy(UserName, StrToNeon(FileSystem->FUserName), NE_ABUFSIZ);
  2350. strncpy(Password, StrToNeon(APassword), NE_ABUFSIZ);
  2351. }
  2352. FileSystem->FAuthenticationRequested = true;
  2353. return Result ? 0 : -1;
  2354. }
  2355. //------------------------------------------------------------------------------
  2356. void TWebDAVFileSystem::NeonNotifier(void * UserData, ne_session_status Status, const ne_session_status_info * StatusInfo)
  2357. {
  2358. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2359. TFileOperationProgressType * OperationProgress = FileSystem->FTerminal->OperationProgress;
  2360. // We particularly have to filter out response to "put" request,
  2361. // handling that would reset the upload progress back to low number (response is small).
  2362. if (((FileSystem->FUploading && (Status == ne_status_sending)) ||
  2363. (FileSystem->FDownloading && (Status == ne_status_recving))) &&
  2364. DebugAlwaysTrue(OperationProgress != NULL))
  2365. {
  2366. __int64 Progress = StatusInfo->sr.progress;
  2367. __int64 Diff = Progress - OperationProgress->TransferedSize;
  2368. if (Diff > 0)
  2369. {
  2370. OperationProgress->ThrottleToCPSLimit(static_cast<unsigned long>(Diff));
  2371. }
  2372. __int64 Total = StatusInfo->sr.total;
  2373. // Total size unknown
  2374. if (Total < 0)
  2375. {
  2376. if (Diff >= 0)
  2377. {
  2378. OperationProgress->AddTransfered(Diff);
  2379. }
  2380. else
  2381. {
  2382. // Session total has been reset. A new stream started
  2383. OperationProgress->AddTransfered(Progress);
  2384. }
  2385. }
  2386. else
  2387. {
  2388. OperationProgress->SetTransferSize(Total);
  2389. OperationProgress->AddTransfered(Diff);
  2390. }
  2391. }
  2392. }
  2393. //------------------------------------------------------------------------------
  2394. void __fastcall TWebDAVFileSystem::NeonDebug(const UnicodeString & Message)
  2395. {
  2396. FTerminal->LogEvent(Message);
  2397. }
  2398. //------------------------------------------------------------------------------
  2399. void TWebDAVFileSystem::InitSslSession(ssl_st * Ssl, ne_session * Session)
  2400. {
  2401. TWebDAVFileSystem * FileSystem =
  2402. static_cast<TWebDAVFileSystem *>(ne_get_session_private(Session, SESSION_FS_KEY));
  2403. FileSystem->InitSslSessionImpl(Ssl);
  2404. }
  2405. //------------------------------------------------------------------------------
  2406. void __fastcall TWebDAVFileSystem::InitSslSessionImpl(ssl_st * Ssl)
  2407. {
  2408. // See also CAsyncSslSocketLayer::InitSSLConnection
  2409. TSessionData * Data = FTerminal->SessionData;
  2410. #define MASK_TLS_VERSION(VERSION, FLAG) ((Data->MinTlsVersion > VERSION) || (Data->MaxTlsVersion < VERSION) ? FLAG : 0)
  2411. int Options =
  2412. MASK_TLS_VERSION(ssl2, SSL_OP_NO_SSLv2) |
  2413. MASK_TLS_VERSION(ssl3, SSL_OP_NO_SSLv3) |
  2414. MASK_TLS_VERSION(tls10, SSL_OP_NO_TLSv1) |
  2415. MASK_TLS_VERSION(tls11, SSL_OP_NO_TLSv1_1) |
  2416. MASK_TLS_VERSION(tls12, SSL_OP_NO_TLSv1_2);
  2417. // SSL_ctrl() with SSL_CTRL_OPTIONS adds flags (not sets)
  2418. SSL_ctrl(Ssl, SSL_CTRL_OPTIONS, Options, NULL);
  2419. }
  2420. //---------------------------------------------------------------------------
  2421. void __fastcall TWebDAVFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  2422. {
  2423. // NOOP
  2424. }
  2425. //---------------------------------------------------------------------------
  2426. void __fastcall TWebDAVFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * File)
  2427. {
  2428. ClearNeonError();
  2429. struct ne_lock * Lock = ne_lock_create();
  2430. try
  2431. {
  2432. Lock->uri.path = ne_strdup(PathToNeon(FilePath(File)));
  2433. Lock->depth = NE_DEPTH_INFINITE;
  2434. Lock->timeout = NE_TIMEOUT_INFINITE;
  2435. Lock->owner = ne_strdup(StrToNeon(FTerminal->UserName));
  2436. CheckStatus(ne_lock(FNeonSession, Lock));
  2437. {
  2438. TGuard Guard(FNeonLockStoreSection);
  2439. RequireLockStore();
  2440. ne_lockstore_add(FNeonLockStore, Lock);
  2441. }
  2442. // ownership passed
  2443. Lock = NULL;
  2444. }
  2445. __finally
  2446. {
  2447. if (Lock != NULL)
  2448. {
  2449. ne_lock_destroy(Lock);
  2450. }
  2451. }
  2452. }
  2453. //---------------------------------------------------------------------------
  2454. void __fastcall TWebDAVFileSystem::RequireLockStore()
  2455. {
  2456. // Create store only when needed,
  2457. // to limit the use of cross-thread code in UpdateFromMain
  2458. if (FNeonLockStore == NULL)
  2459. {
  2460. FNeonLockStore = ne_lockstore_create();
  2461. ne_lockstore_register(FNeonLockStore, FNeonSession);
  2462. }
  2463. }
  2464. //---------------------------------------------------------------------------
  2465. void TWebDAVFileSystem::LockResult(void * UserData, const struct ne_lock * Lock,
  2466. const ne_uri * /*Uri*/, const ne_status * /*Status*/)
  2467. {
  2468. // Is NULL on failure (Status is not NULL then)
  2469. if (Lock != NULL)
  2470. {
  2471. RawByteString & LockToken = *static_cast<RawByteString *>(UserData);
  2472. LockToken = Lock->token;
  2473. }
  2474. }
  2475. //---------------------------------------------------------------------------
  2476. struct ne_lock * __fastcall TWebDAVFileSystem::FindLock(const RawByteString & Path)
  2477. {
  2478. ne_uri Uri = {0};
  2479. Uri.path = Path.c_str();
  2480. return ne_lockstore_findbyuri(FNeonLockStore, &Uri);
  2481. }
  2482. //---------------------------------------------------------------------------
  2483. void __fastcall TWebDAVFileSystem::DiscardLock(const RawByteString & Path)
  2484. {
  2485. TGuard Guard(FNeonLockStoreSection);
  2486. if (FNeonLockStore != NULL)
  2487. {
  2488. struct ne_lock * Lock = FindLock(Path);
  2489. if (Lock != NULL)
  2490. {
  2491. ne_lockstore_remove(FNeonLockStore, Lock);
  2492. }
  2493. }
  2494. }
  2495. //---------------------------------------------------------------------------
  2496. void __fastcall TWebDAVFileSystem::UnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  2497. {
  2498. ClearNeonError();
  2499. struct ne_lock * Lock = ne_lock_create();
  2500. try
  2501. {
  2502. RawByteString Path = PathToNeon(FilePath(File));
  2503. RawByteString LockToken;
  2504. struct ne_lock * Lock = NULL;
  2505. {
  2506. TGuard Guard(FNeonLockStoreSection);
  2507. if (FNeonLockStore != NULL)
  2508. {
  2509. Lock = FindLock(Path);
  2510. }
  2511. }
  2512. // we are not aware of the file being locked,
  2513. // though it can be locked from another (previous and already closed)
  2514. // session, so query the server.
  2515. if (Lock == NULL)
  2516. {
  2517. CheckStatus(ne_lock_discover(FNeonSession, Path.c_str(), LockResult, &LockToken));
  2518. }
  2519. if ((Lock == NULL) && (LockToken.IsEmpty()))
  2520. {
  2521. throw Exception(FMTLOAD(NOT_LOCKED, (FileName)));
  2522. }
  2523. else
  2524. {
  2525. struct ne_lock * Unlock;
  2526. if (Lock == NULL)
  2527. {
  2528. DebugAssert(!LockToken.IsEmpty());
  2529. Unlock = ne_lock_create();
  2530. Unlock->uri.path = ne_strdup(Path.c_str());
  2531. Unlock->token = ne_strdup(LockToken.c_str());
  2532. }
  2533. else
  2534. {
  2535. Unlock = Lock;
  2536. }
  2537. CheckStatus(ne_unlock(FNeonSession, Unlock));
  2538. DiscardLock(Path);
  2539. }
  2540. }
  2541. __finally
  2542. {
  2543. ne_lock_destroy(Lock);
  2544. }
  2545. }
  2546. //---------------------------------------------------------------------------
  2547. void __fastcall TWebDAVFileSystem::UpdateFromMain(TCustomFileSystem * AMainFileSystem)
  2548. {
  2549. TWebDAVFileSystem * MainFileSystem = dynamic_cast<TWebDAVFileSystem *>(AMainFileSystem);
  2550. if (DebugAlwaysTrue(MainFileSystem != NULL))
  2551. {
  2552. TGuard Guard(FNeonLockStoreSection);
  2553. TGuard MainGuard(MainFileSystem->FNeonLockStoreSection);
  2554. if (FNeonLockStore != NULL)
  2555. {
  2556. struct ne_lock * Lock;
  2557. while ((Lock = ne_lockstore_first(FNeonLockStore)) != NULL)
  2558. {
  2559. ne_lockstore_remove(FNeonLockStore, Lock);
  2560. }
  2561. }
  2562. if (DebugAlwaysTrue(MainFileSystem->FNeonLockStore != NULL))
  2563. {
  2564. RequireLockStore();
  2565. struct ne_lock * Lock = ne_lockstore_first(MainFileSystem->FNeonLockStore);
  2566. while (Lock != NULL)
  2567. {
  2568. ne_lockstore_add(FNeonLockStore, ne_lock_copy(Lock));
  2569. Lock = ne_lockstore_next(MainFileSystem->FNeonLockStore);
  2570. }
  2571. }
  2572. }
  2573. }
  2574. //------------------------------------------------------------------------------