WebDAVFileSystem.cpp 86 KB

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