1
0

WebDAVFileSystem.cpp 88 KB

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