WebDAVFileSystem.cpp 93 KB

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