1
0

WebDAVFileSystem.cpp 86 KB

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