1
0

WebDAVFileSystem.cpp 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182
  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. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  776. File->Terminal = Data.FileSystem->FTerminal;
  777. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  778. UnicodeString FileListPath = Data.FileSystem->AbsolutePath(Data.FileList->Directory, false);
  779. if (UnixSamePath(File->FullFileName, FileListPath))
  780. {
  781. File->FileName = PARENTDIRECTORY;
  782. File->FullFileName = UnixCombinePaths(Path, PARENTDIRECTORY);
  783. }
  784. Data.FileList->AddFile(File.release());
  785. }
  786. else
  787. {
  788. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  789. }
  790. }
  791. //---------------------------------------------------------------------------
  792. const char * __fastcall TWebDAVFileSystem::GetProp(
  793. const ne_prop_result_set * Results, const char * Name, const char * NameSpace)
  794. {
  795. ne_propname Prop;
  796. Prop.nspace = (NameSpace == NULL) ? DAV_PROP_NAMESPACE : NameSpace;
  797. Prop.name = Name;
  798. return ne_propset_value(Results, &Prop);
  799. }
  800. //---------------------------------------------------------------------------
  801. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  802. const UnicodeString & Path, const ne_prop_result_set * Results)
  803. {
  804. File->FullFileName = UnixExcludeTrailingBackslash(Path);
  805. // Some servers do not use DAV:collection tag, but indicate the folder by trailing slash only.
  806. // But not all, for example OneDrive does not (it did in the past).
  807. bool Collection = (File->FullFileName != Path);
  808. File->FileName = UnixExtractFileName(File->FullFileName);
  809. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  810. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  811. if (ContentLength != NULL)
  812. {
  813. File->Size = StrToInt64Def(ContentLength, 0);
  814. }
  815. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  816. // We've seen a server (t=24891) that does not set "getlastmodified" for the "this" folder entry.
  817. if (LastModified != NULL)
  818. {
  819. char WeekDay[4] = { L'\0' };
  820. int Year = 0;
  821. char MonthStr[4] = { L'\0' };
  822. int Day = 0;
  823. int Hour = 0;
  824. int Min = 0;
  825. int Sec = 0;
  826. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  827. // Keep is sync with S3
  828. int Filled =
  829. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  830. // we need at least a complete date
  831. if (Filled >= 4)
  832. {
  833. int Month = ParseShortEngMonthName(MonthStr);
  834. if (Month >= 1)
  835. {
  836. TDateTime Modification =
  837. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  838. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  839. File->Modification = ConvertTimestampFromUTC(Modification);
  840. // Should use mfYMDHM or mfMDY when appropriate according to Filled
  841. File->ModificationFmt = mfFull;
  842. }
  843. else
  844. {
  845. File->ModificationFmt = mfNone;
  846. }
  847. }
  848. else
  849. {
  850. File->ModificationFmt = mfNone;
  851. }
  852. }
  853. // optimization
  854. if (!Collection)
  855. {
  856. // See a comment at the Collection declaration.
  857. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  858. if (ResourceType != NULL)
  859. {
  860. // property has XML value
  861. UnicodeString AResourceType = ResourceType;
  862. // this is very poor parsing
  863. if (ContainsText(ResourceType, L"<DAV:collection"))
  864. {
  865. Collection = true;
  866. }
  867. }
  868. }
  869. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  870. // this is MS extension (draft-hopmann-collection-props-00)
  871. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  872. if (IsHidden != NULL)
  873. {
  874. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  875. }
  876. const char * Owner = GetProp(Results, PROP_OWNER);
  877. if (Owner != NULL)
  878. {
  879. File->Owner.Name = Owner;
  880. }
  881. const char * DisplayName = GetProp(Results, PROP_DISPLAY_NAME);
  882. if (DisplayName != NULL)
  883. {
  884. File->DisplayName = StrFromNeon(DisplayName);
  885. // OneDrive caret escaping (we could do this for all files, but let's limit the scope for now).
  886. // In *file* PROPFIND response, the # (and other symbols like comma or plus) is not escaped at all
  887. // (while in directory listing, they are caret-escaped),
  888. // so if we see one in the display name, take the name from there.
  889. // * and % won't help, as OneDrive seem to have bug with % at the end of the filename,
  890. // and the * (and others) is removed from file names.
  891. // Filenames with commas (,) get as many additional characters at the end of the filename as there are commas.
  892. if (FOneDrive &&
  893. (ContainsText(File->FileName, L"^") || ContainsText(File->FileName, L",") || (wcspbrk(File->DisplayName.c_str(), L"&,+#[]%*") != NULL)))
  894. {
  895. File->FileName = File->DisplayName;
  896. File->FullFileName = UnixCombinePaths(UnixExtractFileDir(File->FullFileName), File->FileName);
  897. }
  898. }
  899. const UnicodeString RightsDelimiter(L", ");
  900. UnicodeString HumanRights;
  901. // Proprietary property of mod_dav
  902. // http://www.webdav.org/mod_dav/#imp
  903. const char * Executable = GetProp(Results, PROP_EXECUTABLE, MODDAV_PROP_NAMESPACE);
  904. if (Executable != NULL)
  905. {
  906. if (strcmp(Executable, "T") == NULL)
  907. {
  908. UnicodeString ExecutableRights;
  909. // The "gear" character is supported since Windows 8
  910. if (IsWin8())
  911. {
  912. ExecutableRights = L"\u2699";
  913. }
  914. else
  915. {
  916. ExecutableRights = LoadStr(EXECUTABLE);
  917. }
  918. AddToList(HumanRights, ExecutableRights, RightsDelimiter);
  919. }
  920. }
  921. struct ne_lock * Lock = static_cast<struct ne_lock *>(ne_propset_private(Results));
  922. if ((Lock != NULL) && (Lock->token != NULL))
  923. {
  924. UnicodeString Owner;
  925. if (Lock->owner != NULL)
  926. {
  927. Owner = StrFromNeon(Lock->owner).Trim();
  928. }
  929. UnicodeString LockRights;
  930. if (IsWin8())
  931. {
  932. // The "lock" character is supported since Windows 8
  933. LockRights = L"\uD83D\uDD12" + Owner;
  934. }
  935. else
  936. {
  937. LockRights = LoadStr(LOCKED);
  938. if (!Owner.IsEmpty())
  939. {
  940. LockRights = FORMAT(L"%s (%s)", (LockRights, Owner));
  941. }
  942. }
  943. AddToList(HumanRights, LockRights, RightsDelimiter);
  944. }
  945. File->HumanRights = HumanRights;
  946. }
  947. //---------------------------------------------------------------------------
  948. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  949. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  950. {
  951. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  952. TReadFileData Data;
  953. Data.FileSystem = this;
  954. Data.File = AFile.get();
  955. Data.FileList = NULL;
  956. ClearNeonError();
  957. int Result =
  958. ne_simple_propfind(FNeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  959. NeonPropsResult, &Data);
  960. if (Result == NE_OK)
  961. {
  962. File = AFile.release();
  963. }
  964. return Result;
  965. }
  966. //---------------------------------------------------------------------------
  967. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  968. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  969. {
  970. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  971. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  972. if (IsValidRedirect(NeonStatus, FileName))
  973. {
  974. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  975. }
  976. CheckStatus(NeonStatus);
  977. }
  978. //---------------------------------------------------------------------------
  979. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  980. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  981. {
  982. Action.Recursive();
  983. ClearNeonError();
  984. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  985. RawByteString Path = PathToNeon(FilePath(File));
  986. // WebDAV does not allow non-recursive delete:
  987. // RFC 4918, section 9.6.1:
  988. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  989. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  990. CheckStatus(ne_delete(FNeonSession, Path.c_str()));
  991. // The lock is removed with the file, but if a file with the same name gets created,
  992. // we would try to use obsoleted lock token with it, what the server would reject
  993. // (mod_dav returns "412 Precondition Failed")
  994. DiscardLock(Path);
  995. }
  996. //---------------------------------------------------------------------------
  997. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  998. const UnicodeString & NewName)
  999. {
  1000. // 0 = no overwrite
  1001. return ne_move(FNeonSession, 0, PathToNeon(FileName), PathToNeon(NewName));
  1002. }
  1003. //---------------------------------------------------------------------------
  1004. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1005. const UnicodeString NewName)
  1006. {
  1007. ClearNeonError();
  1008. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1009. UnicodeString Path = FileName;
  1010. int NeonStatus = RenameFileInternal(Path, NewName);
  1011. if (IsValidRedirect(NeonStatus, Path))
  1012. {
  1013. NeonStatus = RenameFileInternal(Path, NewName);
  1014. }
  1015. CheckStatus(NeonStatus);
  1016. // See a comment in DeleteFile
  1017. DiscardLock(PathToNeon(Path));
  1018. }
  1019. //---------------------------------------------------------------------------
  1020. int __fastcall TWebDAVFileSystem::CopyFileInternal(const UnicodeString & FileName,
  1021. const UnicodeString & NewName)
  1022. {
  1023. // 0 = no overwrite
  1024. return ne_copy(FNeonSession, 0, NE_DEPTH_INFINITE, PathToNeon(FileName), PathToNeon(NewName));
  1025. }
  1026. //---------------------------------------------------------------------------
  1027. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1028. const UnicodeString NewName)
  1029. {
  1030. ClearNeonError();
  1031. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1032. UnicodeString Path = FileName;
  1033. int NeonStatus = CopyFileInternal(Path, NewName);
  1034. if (IsValidRedirect(NeonStatus, Path))
  1035. {
  1036. NeonStatus = CopyFileInternal(Path, NewName);
  1037. }
  1038. CheckStatus(NeonStatus);
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
  1042. {
  1043. ClearNeonError();
  1044. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1045. CheckStatus(ne_mkcol(FNeonSession, PathToNeon(DirName)));
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  1049. const UnicodeString PointTo, bool /*Symbolic*/)
  1050. {
  1051. DebugFail();
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1055. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  1056. TChmodSessionAction & /*Action*/)
  1057. {
  1058. DebugFail();
  1059. }
  1060. //---------------------------------------------------------------------------
  1061. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1062. {
  1063. DebugFail();
  1064. return false;
  1065. }
  1066. //---------------------------------------------------------------------------
  1067. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(
  1068. const UnicodeString & DebugUsedArg(Alg), TStrings * DebugUsedArg(FileList), TCalculatedChecksumEvent,
  1069. TFileOperationProgressType *, bool DebugUsedArg(FirstLevel))
  1070. {
  1071. DebugFail();
  1072. }
  1073. //---------------------------------------------------------------------------
  1074. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1075. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1076. TFileOperationProgressType * OperationProgress,
  1077. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1078. int Params)
  1079. {
  1080. // all = "yes to newer"
  1081. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1082. TQueryButtonAlias Aliases[3];
  1083. Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1084. Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1085. Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1086. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1087. QueryParams.Aliases = Aliases;
  1088. QueryParams.AliasesCount = LENOF(Aliases);
  1089. unsigned int Answer;
  1090. {
  1091. TSuspendFileOperationProgress Suspend(OperationProgress);
  1092. Answer =
  1093. FTerminal->ConfirmFileOverwrite(
  1094. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1095. ReverseOperationSide(OperationProgress->Side),
  1096. CopyParam, Params, OperationProgress);
  1097. }
  1098. switch (Answer)
  1099. {
  1100. case qaYes:
  1101. // noop
  1102. break;
  1103. case qaNo:
  1104. throw ESkipFile();
  1105. default:
  1106. DebugFail();
  1107. case qaCancel:
  1108. OperationProgress->SetCancelAtLeast(csCancel);
  1109. Abort();
  1110. break;
  1111. }
  1112. }
  1113. //---------------------------------------------------------------------------
  1114. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1115. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1116. {
  1117. DebugFail();
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1121. TCaptureOutputEvent /*OutputEvent*/)
  1122. {
  1123. DebugFail();
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1127. {
  1128. return NULL;
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. void TWebDAVFileSystem::NeonQuotaResult(
  1132. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1133. {
  1134. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1135. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1136. if (Value != NULL)
  1137. {
  1138. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1139. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1140. if (Value != NULL)
  1141. {
  1142. SpaceAvailable.BytesAvailableToUser =
  1143. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1144. }
  1145. }
  1146. }
  1147. //---------------------------------------------------------------------------
  1148. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1149. TSpaceAvailable & ASpaceAvailable)
  1150. {
  1151. // RFC4331: https://datatracker.ietf.org/doc/html/rfc4331
  1152. // This is known to be supported by:
  1153. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1154. // unconditionally, even when not explicitly requested)
  1155. // Server: Apache/2.2.17 (Fedora)
  1156. // X-Powered-By: PHP/5.5.7
  1157. // X-DAV-Powered-By: OpenDrive
  1158. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1159. // IT Hit WebDAV Server:
  1160. // Server: Microsoft-HTTPAPI/1.0
  1161. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1162. // Yandex disk:
  1163. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1164. // Server: MochiWeb/1.0
  1165. // OneDrive:
  1166. // it sends the properties unconditionally, even when not explicitly requested
  1167. UnicodeString APath = DirectoryPath(Path);
  1168. ne_propname QuotaProps[3];
  1169. memset(QuotaProps, 0, sizeof(QuotaProps));
  1170. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1171. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1172. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1173. QuotaProps[1].name = PROP_QUOTA_USED;
  1174. QuotaProps[2].nspace = NULL;
  1175. QuotaProps[2].name = NULL;
  1176. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1177. CheckStatus(
  1178. ne_simple_propfind(FNeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1179. NeonQuotaResult, &ASpaceAvailable));
  1180. }
  1181. //---------------------------------------------------------------------------
  1182. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1183. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1184. int Params, TFileOperationProgressType * OperationProgress,
  1185. TOnceDoneOperation & OnceDoneOperation)
  1186. {
  1187. Params &= ~cpAppend;
  1188. FTerminal->DoCopyToRemote(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfPreCreateDir, OnceDoneOperation);
  1189. }
  1190. //---------------------------------------------------------------------------
  1191. void __fastcall TWebDAVFileSystem::Source(
  1192. TLocalFileHandle & Handle, const UnicodeString & TargetDir, UnicodeString & DestFileName,
  1193. const TCopyParamType * CopyParam, int Params,
  1194. TFileOperationProgressType * OperationProgress, unsigned int /*Flags*/,
  1195. TUploadSessionAction & Action, bool & ChildError)
  1196. {
  1197. int FD = -1;
  1198. try
  1199. {
  1200. UnicodeString DestFullName = TargetDir + DestFileName;
  1201. TRemoteFile * RemoteFile = NULL;
  1202. try
  1203. {
  1204. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1205. FIgnoreAuthenticationFailure = iafWaiting;
  1206. // this should not throw
  1207. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1208. }
  1209. catch (...)
  1210. {
  1211. if (!FTerminal->Active)
  1212. {
  1213. throw;
  1214. }
  1215. }
  1216. if (RemoteFile != NULL)
  1217. {
  1218. TOverwriteFileParams FileParams;
  1219. FileParams.SourceSize = Handle.Size;
  1220. FileParams.SourceTimestamp = Handle.Modification;
  1221. FileParams.DestSize = RemoteFile->Size;
  1222. FileParams.DestTimestamp = RemoteFile->Modification;
  1223. delete RemoteFile;
  1224. ConfirmOverwrite(Handle.FileName, DestFileName, OperationProgress,
  1225. &FileParams, CopyParam, Params);
  1226. }
  1227. DestFullName = TargetDir + DestFileName;
  1228. // only now, we know the final destination
  1229. // (not really true as we do not support changing file name on overwrite dialog)
  1230. Action.Destination(DestFullName);
  1231. FUploadMimeType = Configuration->GetFileMimeType(DestFileName);
  1232. FILE_OPERATION_LOOP_BEGIN
  1233. {
  1234. SetFilePointer(Handle.Handle, 0, NULL, FILE_BEGIN);
  1235. FD = _open_osfhandle((intptr_t)Handle.Handle, O_BINARY);
  1236. if (FD < 0)
  1237. {
  1238. throw ESkipFile();
  1239. }
  1240. TAutoFlag UploadingFlag(FUploading);
  1241. ClearNeonError();
  1242. CheckStatus(ne_put(FNeonSession, PathToNeon(DestFullName), FD));
  1243. }
  1244. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (Handle.FileName)));
  1245. if (CopyParam->PreserveTime)
  1246. {
  1247. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1248. (StandardTimestamp(Handle.Modification))));
  1249. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Handle.Modification);
  1250. try
  1251. {
  1252. TDateTime ModificationUTC = ConvertTimestampToUTC(Handle.Modification);
  1253. TFormatSettings FormatSettings = GetEngFormatSettings();
  1254. UnicodeString LastModified =
  1255. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1256. UTF8String NeonLastModified(LastModified);
  1257. // second element is "NULL-terminating"
  1258. ne_proppatch_operation Operations[2];
  1259. memset(Operations, 0, sizeof(Operations));
  1260. ne_propname LastModifiedProp;
  1261. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1262. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1263. Operations[0].name = &LastModifiedProp;
  1264. Operations[0].type = ne_propset;
  1265. Operations[0].value = NeonLastModified.c_str();
  1266. int Status = ne_proppatch(FNeonSession, PathToNeon(DestFullName), Operations);
  1267. if (Status == NE_ERROR)
  1268. {
  1269. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1270. (GetNeonError())));
  1271. // Ignore errors as major WebDAV servers (like IIS), do not support
  1272. // changing getlastmodified.
  1273. // The only server we found that supports this is TradeMicro SafeSync.
  1274. // But it announces itself as "Server: Apache",
  1275. // so it's not reliable to autodetect the support.
  1276. // Microsoft Office alegedly uses <Win32LastModifiedTime>
  1277. // https://sabre.io/dav/clients/msoffice/
  1278. // Carot DAV does that too. But we do not know what server does support this.
  1279. TouchAction.Cancel();
  1280. }
  1281. else
  1282. {
  1283. CheckStatus(Status);
  1284. }
  1285. }
  1286. catch (Exception & E)
  1287. {
  1288. TouchAction.Rollback(&E);
  1289. ChildError = true;
  1290. throw;
  1291. }
  1292. }
  1293. }
  1294. __finally
  1295. {
  1296. if (FD >= 0)
  1297. {
  1298. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1299. // but it crashes code guard
  1300. _close(FD);
  1301. Handle.Dismiss();
  1302. }
  1303. }
  1304. }
  1305. //---------------------------------------------------------------------------
  1306. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1307. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1308. int Params, TFileOperationProgressType * OperationProgress,
  1309. TOnceDoneOperation & OnceDoneOperation)
  1310. {
  1311. Params &= ~cpAppend;
  1312. FTerminal->DoCopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, OperationProgress, tfNone, OnceDoneOperation);
  1313. }
  1314. //---------------------------------------------------------------------------
  1315. void TWebDAVFileSystem::NeonCreateRequest(
  1316. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1317. {
  1318. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1319. ne_set_request_private(Request, SESSION_FS_KEY, FileSystem);
  1320. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1321. FileSystem->FNtlmAuthenticationFailed = false;
  1322. }
  1323. //---------------------------------------------------------------------------
  1324. void TWebDAVFileSystem::NeonPreSend(
  1325. ne_request * Request, void * UserData, ne_buffer * Header)
  1326. {
  1327. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1328. FileSystem->FAuthorizationProtocol = L"";
  1329. UnicodeString HeaderBuf(StrFromNeon(AnsiString(Header->data, Header->used)));
  1330. const UnicodeString AuthorizationHeaderName(L"Authorization:");
  1331. int P = HeaderBuf.Pos(AuthorizationHeaderName);
  1332. if (P > 0)
  1333. {
  1334. P += AuthorizationHeaderName.Length();
  1335. int P2 = PosEx(L"\n", HeaderBuf, P);
  1336. if (DebugAlwaysTrue(P2 > 0))
  1337. {
  1338. UnicodeString AuthorizationHeader = HeaderBuf.SubString(P, P2 - P).Trim();
  1339. FileSystem->FAuthorizationProtocol = CutToChar(AuthorizationHeader, L' ', false);
  1340. FileSystem->FLastAuthorizationProtocol = FileSystem->FAuthorizationProtocol;
  1341. }
  1342. }
  1343. if (FileSystem->FDownloading)
  1344. {
  1345. // Needed by IIS server to make it download source code, not code output,
  1346. // and mainly to even allow downloading file with unregistered extensions.
  1347. // Without it files like .001 return 404 (Not found) HTTP code.
  1348. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wdv/e37a9543-9290-4843-8c04-66457c60fa0a
  1349. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wdvse/501879f9-3875-4d7a-ab88-3cecab440034
  1350. // http://lists.manyfish.co.uk/pipermail/neon/2012-April/000582.html
  1351. // It's also supported by Oracle server:
  1352. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1353. // We do not know yet of any server that fails when the header is used,
  1354. // so it's added unconditionally.
  1355. ne_buffer_zappend(Header, "Translate: f\r\n");
  1356. }
  1357. const UnicodeString ContentTypeHeaderPrefix(L"Content-Type: ");
  1358. if (FileSystem->FTerminal->Log->Logging)
  1359. {
  1360. const char * Buffer;
  1361. size_t Size;
  1362. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1363. {
  1364. // all neon request types that use ne_add_request_header
  1365. // use XML content-type, so it's text-based
  1366. DebugAssert(ContainsStr(HeaderBuf, ContentTypeHeaderPrefix + NE_XML_MEDIA_TYPE));
  1367. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1368. }
  1369. }
  1370. if (FileSystem->FUploading)
  1371. {
  1372. ne_set_request_body_provider_pre(Request,
  1373. FileSystem->NeonUploadBodyProvider, FileSystem);
  1374. if (!FileSystem->FUploadMimeType.IsEmpty())
  1375. {
  1376. UnicodeString ContentTypeHeader = ContentTypeHeaderPrefix + FileSystem->FUploadMimeType + L"\r\n";
  1377. ne_buffer_zappend(Header, AnsiString(ContentTypeHeader).c_str());
  1378. }
  1379. }
  1380. FileSystem->FResponse = L"";
  1381. }
  1382. //---------------------------------------------------------------------------
  1383. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1384. const ne_status * /*Status*/)
  1385. {
  1386. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1387. if (!FileSystem->FResponse.IsEmpty())
  1388. {
  1389. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1390. }
  1391. return NE_OK;
  1392. }
  1393. //---------------------------------------------------------------------------
  1394. bool __fastcall TWebDAVFileSystem::IsNtlmAuthentication()
  1395. {
  1396. return
  1397. SameText(FAuthorizationProtocol, L"NTLM") ||
  1398. SameText(FAuthorizationProtocol, L"Negotiate");
  1399. }
  1400. //---------------------------------------------------------------------------
  1401. void __fastcall TWebDAVFileSystem::HttpAuthenticationFailed()
  1402. {
  1403. // NTLM/GSSAPI failed
  1404. if (IsNtlmAuthentication())
  1405. {
  1406. if (FNtlmAuthenticationFailed)
  1407. {
  1408. // Next time do not try Negotiate (NTLM/GSSAPI),
  1409. // otherwise we end up in an endless loop.
  1410. // If the server returns all other challenges in the response, removing the Negotiate
  1411. // protocol will itself ensure that other protocols are tried (we haven't seen this behaviour).
  1412. // IIS will return only Negotiate response if the request was Negotiate, so there's no fallback.
  1413. // We have to retry with a fresh request. That's what FAuthenticationRetry does.
  1414. FTerminal->LogEvent(FORMAT(L"%s challenge failed, will try different challenge", (FAuthorizationProtocol)));
  1415. ne_remove_server_auth(FNeonSession);
  1416. NeonAddAuthentiation(false);
  1417. FAuthenticationRetry = true;
  1418. }
  1419. else
  1420. {
  1421. // The first 401 is expected, the server is using it to send WWW-Authenticate header with data.
  1422. FNtlmAuthenticationFailed = true;
  1423. }
  1424. }
  1425. }
  1426. //---------------------------------------------------------------------------
  1427. void TWebDAVFileSystem::NeonPostHeaders(ne_request * /*Req*/, void * UserData, const ne_status * Status)
  1428. {
  1429. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1430. if (Status->code == HttpUnauthorized)
  1431. {
  1432. FileSystem->HttpAuthenticationFailed();
  1433. }
  1434. }
  1435. //---------------------------------------------------------------------------
  1436. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1437. {
  1438. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1439. ssize_t Result;
  1440. if (FileSystem->CancelTransfer())
  1441. {
  1442. Result = -1;
  1443. }
  1444. else
  1445. {
  1446. Result = 1;
  1447. }
  1448. return Result;
  1449. }
  1450. //---------------------------------------------------------------------------
  1451. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1452. {
  1453. const char * Value = ne_get_response_header(Request, Name);
  1454. if (Value != NULL)
  1455. {
  1456. AddToList(List, StrFromNeon(Value), L"; ");
  1457. }
  1458. }
  1459. //---------------------------------------------------------------------------
  1460. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1461. {
  1462. DebugAssert(UserData == Request);
  1463. TWebDAVFileSystem * FileSystem =
  1464. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1465. bool AuthenticationFailureCode = (Status->code == HttpUnauthorized);
  1466. bool PasswordAuthenticationFailed = AuthenticationFailureCode && FileSystem->FAuthenticationRequested;
  1467. bool AuthenticationFailed = PasswordAuthenticationFailed || (AuthenticationFailureCode && FileSystem->IsNtlmAuthentication());
  1468. bool AuthenticationNeeded = AuthenticationFailureCode && !AuthenticationFailed;
  1469. if (FileSystem->FInitialHandshake)
  1470. {
  1471. UnicodeString Line;
  1472. if (AuthenticationNeeded)
  1473. {
  1474. Line = LoadStr(STATUS_AUTHENTICATE);
  1475. }
  1476. else if (AuthenticationFailed)
  1477. {
  1478. Line = LoadStr(FTP_ACCESS_DENIED);
  1479. }
  1480. else if (Status->klass == 2)
  1481. {
  1482. Line = LoadStr(STATUS_AUTHENTICATED);
  1483. }
  1484. if (!Line.IsEmpty())
  1485. {
  1486. FileSystem->FTerminal->Information(Line, true);
  1487. }
  1488. UnicodeString RemoteSystem;
  1489. // Used by IT Hit WebDAV Server:
  1490. // Server: Microsoft-HTTPAPI/1.0
  1491. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1492. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1493. // Used by OpenDrive:
  1494. // Server: Apache/2.2.17 (Fedora)
  1495. // X-Powered-By: PHP/5.5.7
  1496. // X-DAV-Powered-By: OpenDrive
  1497. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1498. // Used by IIS:
  1499. // Server: Microsoft-IIS/8.5
  1500. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1501. // Not really useful.
  1502. // Can be e.g. "PleskLin"
  1503. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1504. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1505. }
  1506. // When we explicitly fail authentication of request
  1507. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1508. // neon resets its internal password store and tries the next request
  1509. // without calling our authentication hook first
  1510. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1511. // what likely fails, but we do not want to reset out password
  1512. // (as it was not even tried yet for this request).
  1513. if (PasswordAuthenticationFailed)
  1514. {
  1515. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1516. {
  1517. FileSystem->FPassword = RawByteString();
  1518. }
  1519. else
  1520. {
  1521. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1522. }
  1523. }
  1524. return ne_accept_2xx(UserData, Request, Status);
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1528. {
  1529. bool Result = false;
  1530. if ((FUploading || FDownloading) &&
  1531. (FTerminal->OperationProgress != NULL) &&
  1532. (FTerminal->OperationProgress->Cancel != csContinue))
  1533. {
  1534. if (FTerminal->OperationProgress->ClearCancelFile())
  1535. {
  1536. FSkipped = true;
  1537. }
  1538. else
  1539. {
  1540. FCancelled = true;
  1541. }
  1542. Result = true;
  1543. }
  1544. return Result;
  1545. }
  1546. //---------------------------------------------------------------------------
  1547. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1548. {
  1549. ne_request * Request = static_cast<ne_request *>(UserData);
  1550. TWebDAVFileSystem * FileSystem =
  1551. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1552. if (FileSystem->FTerminal->Log->Logging)
  1553. {
  1554. ne_content_type ContentType;
  1555. if (ne_get_content_type(Request, &ContentType) == 0)
  1556. {
  1557. // The main point of the content-type check was to exclude
  1558. // GET responses (with file contents).
  1559. // But this won't work when downloading text files that have text
  1560. // content type on their own, hence the additional not-downloading test.
  1561. if (!FileSystem->FDownloading &&
  1562. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1563. media_type_is_xml(&ContentType)))
  1564. {
  1565. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1566. FileSystem->FResponse += Content;
  1567. }
  1568. ne_free(ContentType.value);
  1569. }
  1570. }
  1571. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1572. return Result;
  1573. }
  1574. //---------------------------------------------------------------------------
  1575. void __fastcall TWebDAVFileSystem::Sink(
  1576. const UnicodeString & FileName, const TRemoteFile * File,
  1577. const UnicodeString & TargetDir, UnicodeString & DestFileName, int Attrs,
  1578. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1579. unsigned int /*Flags*/, TDownloadSessionAction & Action)
  1580. {
  1581. UnicodeString DestFullName = TargetDir + DestFileName;
  1582. if (FileExists(ApiPath(DestFullName)))
  1583. {
  1584. __int64 Size;
  1585. __int64 MTime;
  1586. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL, NULL, NULL, &MTime, NULL, &Size);
  1587. TOverwriteFileParams FileParams;
  1588. FileParams.SourceSize = File->Size;
  1589. FileParams.SourceTimestamp = File->Modification;
  1590. FileParams.DestSize = Size;
  1591. FileParams.DestTimestamp = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1592. ConfirmOverwrite(FileName, DestFileName, OperationProgress, &FileParams, CopyParam, Params);
  1593. }
  1594. UnicodeString ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  1595. Action.Destination(ExpandedDestFullName);
  1596. FILE_OPERATION_LOOP_BEGIN
  1597. {
  1598. HANDLE LocalHandle;
  1599. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress, &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1600. {
  1601. throw ESkipFile();
  1602. }
  1603. bool DeleteLocalFile = true;
  1604. int FD = -1;
  1605. try
  1606. {
  1607. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1608. if (FD < 0)
  1609. {
  1610. throw ESkipFile();
  1611. }
  1612. TAutoFlag DownloadingFlag(FDownloading);
  1613. ClearNeonError();
  1614. CheckStatus(ne_get(FNeonSession, PathToNeon(FileName), FD));
  1615. DeleteLocalFile = false;
  1616. if (CopyParam->PreserveTime)
  1617. {
  1618. FTerminal->UpdateTargetTime(LocalHandle, File->Modification, FTerminal->SessionData->DSTMode);
  1619. }
  1620. }
  1621. __finally
  1622. {
  1623. if (FD >= 0)
  1624. {
  1625. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1626. // but it crashes code guard
  1627. _close(FD);
  1628. }
  1629. else
  1630. {
  1631. CloseHandle(LocalHandle);
  1632. }
  1633. if (DeleteLocalFile)
  1634. {
  1635. FILE_OPERATION_LOOP_BEGIN
  1636. {
  1637. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestFullName)));
  1638. }
  1639. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestFullName)));
  1640. }
  1641. }
  1642. }
  1643. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1644. FTerminal->UpdateTargetAttrs(DestFullName, File, CopyParam, Attrs);
  1645. }
  1646. //---------------------------------------------------------------------------
  1647. // Similar to TS3FileSystem::VerifyCertificate
  1648. bool TWebDAVFileSystem::VerifyCertificate(TNeonCertificateData Data, bool Aux)
  1649. {
  1650. FSessionInfo.CertificateFingerprintSHA1 = Data.FingerprintSHA1;
  1651. FSessionInfo.CertificateFingerprintSHA256 = Data.FingerprintSHA256;
  1652. bool Result;
  1653. if (FTerminal->SessionData->FingerprintScan)
  1654. {
  1655. Result = false;
  1656. }
  1657. else
  1658. {
  1659. FTerminal->LogEvent(0, CertificateVerificationMessage(Data));
  1660. UnicodeString SiteKey = TSessionData::FormatSiteKey(FHostName, FPortNumber);
  1661. Result =
  1662. FTerminal->VerifyCertificate(
  1663. HttpsCertificateStorageKey, SiteKey, Data.FingerprintSHA1, Data.FingerprintSHA256, Data.Subject, Data.Failures);
  1664. if (Result)
  1665. {
  1666. FSessionInfo.CertificateVerifiedManually = true;
  1667. }
  1668. else
  1669. {
  1670. UnicodeString Message;
  1671. Result = NeonWindowsValidateCertificateWithMessage(Data, Message);
  1672. FTerminal->LogEvent(0, Message);
  1673. }
  1674. FSessionInfo.Certificate = CertificateSummary(Data, FHostName);
  1675. if (!Result)
  1676. {
  1677. if (FTerminal->ConfirmCertificate(FSessionInfo, Data.Failures, HttpsCertificateStorageKey, !Aux))
  1678. {
  1679. Result = true;
  1680. FSessionInfo.CertificateVerifiedManually = true;
  1681. }
  1682. }
  1683. if (Result && !Aux)
  1684. {
  1685. CollectTLSSessionInfo();
  1686. }
  1687. }
  1688. return Result;
  1689. }
  1690. //------------------------------------------------------------------------------
  1691. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  1692. {
  1693. // See also TFTPFileSystem::Open().
  1694. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  1695. // can be closed at the time we need it in CollectUsage().
  1696. UnicodeString Message = NeonTlsSessionInfo(FNeonSession, FSessionInfo, FTlsVersionStr);
  1697. FTerminal->LogEvent(0, Message);
  1698. }
  1699. //------------------------------------------------------------------------------
  1700. // A neon-session callback to validate the SSL certificate when the CA
  1701. // is unknown (e.g. a self-signed cert), or there are other SSL
  1702. // certificate problems.
  1703. int TWebDAVFileSystem::DoNeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate, bool Aux)
  1704. {
  1705. TNeonCertificateData Data;
  1706. RetrieveNeonCertificateData(Failures, Certificate, Data);
  1707. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1708. return FileSystem->VerifyCertificate(Data, Aux) ? NE_OK : NE_ERROR;
  1709. }
  1710. //------------------------------------------------------------------------------
  1711. int TWebDAVFileSystem::NeonServerSSLCallbackMain(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1712. {
  1713. return DoNeonServerSSLCallback(UserData, Failures, Certificate, false);
  1714. }
  1715. //------------------------------------------------------------------------------
  1716. int TWebDAVFileSystem::NeonServerSSLCallbackAux(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  1717. {
  1718. return DoNeonServerSSLCallback(UserData, Failures, Certificate, true);
  1719. }
  1720. //------------------------------------------------------------------------------
  1721. void TWebDAVFileSystem::NeonProvideClientCert(void * UserData, ne_session * Sess,
  1722. const ne_ssl_dname * const * /*DNames*/, int /*DNCount*/)
  1723. {
  1724. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1725. FileSystem->FTerminal->LogEvent(LoadStr(NEED_CLIENT_CERTIFICATE));
  1726. X509 * Certificate;
  1727. EVP_PKEY * PrivateKey;
  1728. if (FileSystem->FTerminal->LoadTlsCertificate(Certificate, PrivateKey))
  1729. {
  1730. ne_ssl_client_cert * NeonCertificate = ne_ssl_clicert_create(Certificate, PrivateKey);
  1731. ne_ssl_set_clicert(Sess, NeonCertificate);
  1732. ne_ssl_clicert_free(NeonCertificate);
  1733. }
  1734. }
  1735. //------------------------------------------------------------------------------
  1736. int TWebDAVFileSystem::NeonRequestAuth(
  1737. void * UserData, const char * Realm, int Attempt, char * UserName, char * Password)
  1738. {
  1739. DebugUsedParam(Realm);
  1740. DebugUsedParam(Attempt);
  1741. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1742. TTerminal * Terminal = FileSystem->FTerminal;
  1743. TSessionData * SessionData = Terminal->SessionData;
  1744. bool Result = true;
  1745. // will ask for username only once
  1746. if (FileSystem->FUserName.IsEmpty())
  1747. {
  1748. if (!SessionData->UserName.IsEmpty())
  1749. {
  1750. FileSystem->FUserName = SessionData->UserNameExpanded;
  1751. }
  1752. else
  1753. {
  1754. Terminal->LogEvent(L"Username prompt");
  1755. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  1756. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  1757. {
  1758. // note that we never get here actually
  1759. Result = false;
  1760. }
  1761. }
  1762. }
  1763. UnicodeString APassword;
  1764. if (Result)
  1765. {
  1766. // Some servers (Gallery2 on discontinued g2.pixi.me)
  1767. // return authentication error (401) on PROPFIND request for
  1768. // non-existing files.
  1769. // When we already tried password before, do not try anymore.
  1770. // When we did not try password before (possible only when
  1771. // server does not require authentication for any previous request,
  1772. // such as when read access is not authenticated), try it now,
  1773. // but use special flag for the try, because when it fails
  1774. // we still want to try password for future requests (such as PUT).
  1775. if (!FileSystem->FPassword.IsEmpty())
  1776. {
  1777. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  1778. {
  1779. // Fail PROPFIND /nonexising request...
  1780. Result = false;
  1781. }
  1782. else
  1783. {
  1784. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  1785. }
  1786. }
  1787. else
  1788. {
  1789. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  1790. {
  1791. APassword = NormalizeString(SessionData->Password);
  1792. FileSystem->FStoredPasswordTried = true;
  1793. }
  1794. else
  1795. {
  1796. // Asking for password (or using configured password) the first time,
  1797. // and asking for password.
  1798. // Note that we never get false here actually
  1799. Terminal->LogEvent(L"Password prompt");
  1800. Result =
  1801. Terminal->PromptUser(
  1802. SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  1803. LoadStr(PASSWORD_PROMPT), false, NE_ABUFSIZ, APassword);
  1804. }
  1805. if (Result)
  1806. {
  1807. // While neon remembers the password on its own,
  1808. // we need to keep a copy in case neon store gets reset by
  1809. // 401 response to PROPFIND /nonexisting on G2, see above.
  1810. // Possibly we can do this for G2 servers only.
  1811. FileSystem->FPassword = Terminal->EncryptPassword(APassword);
  1812. }
  1813. }
  1814. }
  1815. if (Result)
  1816. {
  1817. strncpy(UserName, StrToNeon(FileSystem->FUserName), NE_ABUFSIZ);
  1818. strncpy(Password, StrToNeon(APassword), NE_ABUFSIZ);
  1819. }
  1820. FileSystem->FAuthenticationRequested = true;
  1821. return Result ? 0 : -1;
  1822. }
  1823. //------------------------------------------------------------------------------
  1824. void TWebDAVFileSystem::NeonNotifier(void * UserData, ne_session_status Status, const ne_session_status_info * StatusInfo)
  1825. {
  1826. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1827. TFileOperationProgressType * OperationProgress = FileSystem->FTerminal->OperationProgress;
  1828. // We particularly have to filter out response to "put" request,
  1829. // handling that would reset the upload progress back to low number (response is small).
  1830. if (((FileSystem->FUploading && (Status == ne_status_sending)) ||
  1831. (FileSystem->FDownloading && (Status == ne_status_recving))) &&
  1832. DebugAlwaysTrue(OperationProgress != NULL))
  1833. {
  1834. __int64 Progress = StatusInfo->sr.progress;
  1835. __int64 Diff = Progress - OperationProgress->TransferredSize;
  1836. if (Diff > 0)
  1837. {
  1838. OperationProgress->ThrottleToCPSLimit(static_cast<unsigned long>(Diff));
  1839. }
  1840. __int64 Total = StatusInfo->sr.total;
  1841. // Total size unknown
  1842. if (Total < 0)
  1843. {
  1844. if (Diff >= 0)
  1845. {
  1846. OperationProgress->AddTransferred(Diff);
  1847. }
  1848. else
  1849. {
  1850. // Session total has been reset. A new stream started
  1851. OperationProgress->AddTransferred(Progress);
  1852. }
  1853. }
  1854. else
  1855. {
  1856. OperationProgress->SetTransferSize(Total);
  1857. OperationProgress->AddTransferred(Diff);
  1858. }
  1859. }
  1860. }
  1861. //------------------------------------------------------------------------------
  1862. void TWebDAVFileSystem::InitSslSession(ssl_st * Ssl, ne_session * /*Session*/)
  1863. {
  1864. SetupSsl(Ssl, FTerminal->SessionData->MinTlsVersion, FTerminal->SessionData->MaxTlsVersion);
  1865. }
  1866. //---------------------------------------------------------------------------
  1867. void __fastcall TWebDAVFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  1868. {
  1869. // NOOP
  1870. }
  1871. //---------------------------------------------------------------------------
  1872. void __fastcall TWebDAVFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * File)
  1873. {
  1874. ClearNeonError();
  1875. struct ne_lock * Lock = ne_lock_create();
  1876. try
  1877. {
  1878. Lock->uri.path = ne_strdup(PathToNeon(FilePath(File)));
  1879. Lock->depth = NE_DEPTH_INFINITE;
  1880. Lock->timeout = NE_TIMEOUT_INFINITE;
  1881. Lock->owner = ne_strdup(StrToNeon(FTerminal->UserName));
  1882. CheckStatus(ne_lock(FNeonSession, Lock));
  1883. {
  1884. TGuard Guard(FNeonLockStoreSection);
  1885. RequireLockStore();
  1886. ne_lockstore_add(FNeonLockStore, Lock);
  1887. }
  1888. // ownership passed
  1889. Lock = NULL;
  1890. }
  1891. __finally
  1892. {
  1893. if (Lock != NULL)
  1894. {
  1895. ne_lock_destroy(Lock);
  1896. }
  1897. }
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. void __fastcall TWebDAVFileSystem::RequireLockStore()
  1901. {
  1902. // Create store only when needed,
  1903. // to limit the use of cross-thread code in UpdateFromMain
  1904. if (FNeonLockStore == NULL)
  1905. {
  1906. FNeonLockStore = ne_lockstore_create();
  1907. ne_lockstore_register(FNeonLockStore, FNeonSession);
  1908. }
  1909. }
  1910. //---------------------------------------------------------------------------
  1911. void TWebDAVFileSystem::LockResult(void * UserData, const struct ne_lock * Lock,
  1912. const ne_uri * /*Uri*/, const ne_status * /*Status*/)
  1913. {
  1914. // Is NULL on failure (Status is not NULL then)
  1915. if (Lock != NULL)
  1916. {
  1917. RawByteString & LockToken = *static_cast<RawByteString *>(UserData);
  1918. LockToken = Lock->token;
  1919. }
  1920. }
  1921. //---------------------------------------------------------------------------
  1922. struct ne_lock * __fastcall TWebDAVFileSystem::FindLock(const RawByteString & Path)
  1923. {
  1924. ne_uri Uri = {0};
  1925. Uri.path = Path.c_str();
  1926. return ne_lockstore_findbyuri(FNeonLockStore, &Uri);
  1927. }
  1928. //---------------------------------------------------------------------------
  1929. void __fastcall TWebDAVFileSystem::DiscardLock(const RawByteString & Path)
  1930. {
  1931. TGuard Guard(FNeonLockStoreSection);
  1932. if (FNeonLockStore != NULL)
  1933. {
  1934. struct ne_lock * Lock = FindLock(Path);
  1935. if (Lock != NULL)
  1936. {
  1937. ne_lockstore_remove(FNeonLockStore, Lock);
  1938. }
  1939. }
  1940. }
  1941. //---------------------------------------------------------------------------
  1942. void __fastcall TWebDAVFileSystem::UnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  1943. {
  1944. ClearNeonError();
  1945. struct ne_lock * Lock = ne_lock_create();
  1946. try
  1947. {
  1948. RawByteString Path = PathToNeon(FilePath(File));
  1949. RawByteString LockToken;
  1950. struct ne_lock * Lock = NULL;
  1951. {
  1952. TGuard Guard(FNeonLockStoreSection);
  1953. if (FNeonLockStore != NULL)
  1954. {
  1955. Lock = FindLock(Path);
  1956. }
  1957. }
  1958. // we are not aware of the file being locked,
  1959. // though it can be locked from another (previous and already closed)
  1960. // session, so query the server.
  1961. if (Lock == NULL)
  1962. {
  1963. CheckStatus(ne_lock_discover(FNeonSession, Path.c_str(), LockResult, &LockToken));
  1964. }
  1965. if ((Lock == NULL) && (LockToken.IsEmpty()))
  1966. {
  1967. throw Exception(FMTLOAD(NOT_LOCKED, (FileName)));
  1968. }
  1969. else
  1970. {
  1971. struct ne_lock * Unlock;
  1972. if (Lock == NULL)
  1973. {
  1974. DebugAssert(!LockToken.IsEmpty());
  1975. Unlock = ne_lock_create();
  1976. Unlock->uri.path = ne_strdup(Path.c_str());
  1977. Unlock->token = ne_strdup(LockToken.c_str());
  1978. }
  1979. else
  1980. {
  1981. Unlock = Lock;
  1982. }
  1983. CheckStatus(ne_unlock(FNeonSession, Unlock));
  1984. DiscardLock(Path);
  1985. }
  1986. }
  1987. __finally
  1988. {
  1989. ne_lock_destroy(Lock);
  1990. }
  1991. }
  1992. //---------------------------------------------------------------------------
  1993. void __fastcall TWebDAVFileSystem::UpdateFromMain(TCustomFileSystem * AMainFileSystem)
  1994. {
  1995. TWebDAVFileSystem * MainFileSystem = dynamic_cast<TWebDAVFileSystem *>(AMainFileSystem);
  1996. if (DebugAlwaysTrue(MainFileSystem != NULL))
  1997. {
  1998. TGuard Guard(FNeonLockStoreSection);
  1999. TGuard MainGuard(MainFileSystem->FNeonLockStoreSection);
  2000. if (FNeonLockStore != NULL)
  2001. {
  2002. struct ne_lock * Lock;
  2003. while ((Lock = ne_lockstore_first(FNeonLockStore)) != NULL)
  2004. {
  2005. ne_lockstore_remove(FNeonLockStore, Lock);
  2006. }
  2007. }
  2008. if (MainFileSystem->FNeonLockStore != NULL)
  2009. {
  2010. RequireLockStore();
  2011. struct ne_lock * Lock = ne_lockstore_first(MainFileSystem->FNeonLockStore);
  2012. while (Lock != NULL)
  2013. {
  2014. ne_lockstore_add(FNeonLockStore, ne_lock_copy(Lock));
  2015. Lock = ne_lockstore_next(MainFileSystem->FNeonLockStore);
  2016. }
  2017. }
  2018. }
  2019. }
  2020. //------------------------------------------------------------------------------
  2021. void __fastcall TWebDAVFileSystem::ClearCaches()
  2022. {
  2023. // noop
  2024. }
  2025. //---------------------------------------------------------------------------