WebDAVFileSystem.cpp 92 KB

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