WebDAVFileSystem.cpp 81 KB

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