WebDAVFileSystem.cpp 79 KB

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