WebDAVFileSystem.cpp 80 KB

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