WebDAVFileSystem.cpp 73 KB

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