WebDAVFileSystem.cpp 79 KB

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