WebDAVFileSystem.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480
  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. Path = UnixExcludeTrailingBackslash(Path);
  820. TReadFileData & Data = *static_cast<TReadFileData *>(UserData);
  821. if (Data.FileList != NULL)
  822. {
  823. UnicodeString FileListPath = PathToNeonStatic(Data.FileSystem, Data.FileList->Directory);
  824. if (UnixSamePath(Path, FileListPath))
  825. {
  826. Path = UnixIncludeTrailingBackslash(Path) + L"..";
  827. }
  828. std::unique_ptr<TRemoteFile> File(new TRemoteFile(NULL));
  829. File->Terminal = Data.FileSystem->FTerminal;
  830. Data.FileSystem->ParsePropResultSet(File.get(), Path, Results);
  831. Data.FileList->AddFile(File.release());
  832. }
  833. else
  834. {
  835. Data.FileSystem->ParsePropResultSet(Data.File, Path, Results);
  836. }
  837. }
  838. //---------------------------------------------------------------------------
  839. const char * __fastcall TWebDAVFileSystem::GetProp(const ne_prop_result_set * Results, const char * Name)
  840. {
  841. ne_propname Prop;
  842. Prop.nspace = DAV_PROP_NAMESPACE;
  843. Prop.name = Name;
  844. return ne_propset_value(Results, &Prop);
  845. }
  846. //---------------------------------------------------------------------------
  847. void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File,
  848. const UnicodeString & Path, const ne_prop_result_set * Results)
  849. {
  850. File->FullFileName = Path;
  851. File->FileName = UnixExtractFileName(File->FullFileName);
  852. const char * ContentLength = GetProp(Results, PROP_CONTENT_LENGTH);
  853. // some servers, for example iFiles, do not provide "getcontentlength" for folders
  854. if (ContentLength != NULL)
  855. {
  856. File->Size = StrToInt64Def(ContentLength, 0);
  857. }
  858. const char * LastModified = GetProp(Results, PROP_LAST_MODIFIED);
  859. if (ALWAYS_TRUE(LastModified != NULL))
  860. {
  861. char WeekDay[4] = { L'\0' };
  862. int Year = 0;
  863. char MonthStr[4] = { L'\0' };
  864. int Day = 0;
  865. int Hour = 0;
  866. int Min = 0;
  867. int Sec = 0;
  868. #define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
  869. int Filled =
  870. sscanf(LastModified, RFC1123_FORMAT, WeekDay, &Day, MonthStr, &Year, &Hour, &Min, &Sec);
  871. // we need at least a complete date
  872. if (Filled >= 4)
  873. {
  874. int Month = ParseShortEngMonthName(MonthStr);
  875. if (Month >= 1)
  876. {
  877. TDateTime Modification =
  878. EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) +
  879. EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0);
  880. File->Modification = ConvertTimestampFromUTC(Modification);
  881. File->ModificationFmt = mfFull;
  882. }
  883. }
  884. }
  885. bool Collection = false;
  886. const char * ResourceType = GetProp(Results, PROP_RESOURCE_TYPE);
  887. if (ResourceType != NULL)
  888. {
  889. // property has XML value
  890. UnicodeString AResourceType = ResourceType;
  891. // this is very poor parsing
  892. if (ContainsText(ResourceType, L"<DAV:collection"))
  893. {
  894. Collection = true;
  895. }
  896. }
  897. File->Type = Collection ? FILETYPE_DIRECTORY : FILETYPE_DEFAULT;
  898. // this is MS extension (draft-hopmann-collection-props-00)
  899. const char * IsHidden = GetProp(Results, PROP_HIDDEN);
  900. if (IsHidden != NULL)
  901. {
  902. File->IsHidden = (StrToIntDef(IsHidden, 0) != 0);
  903. }
  904. }
  905. //---------------------------------------------------------------------------
  906. int __fastcall TWebDAVFileSystem::CustomReadFileInternal(const UnicodeString FileName,
  907. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  908. {
  909. std::unique_ptr<TRemoteFile> AFile(new TRemoteFile(ALinkedByFile));
  910. TReadFileData Data;
  911. Data.FileSystem = this;
  912. Data.File = AFile.get();
  913. Data.FileList = NULL;
  914. ClearNeonError();
  915. int Result =
  916. ne_simple_propfind(FNeonSession, PathToNeon(FileName), NE_DEPTH_ZERO, NULL,
  917. NeonPropsResult, &Data);
  918. if (Result == NE_OK)
  919. {
  920. File = AFile.release();
  921. }
  922. return Result;
  923. }
  924. //---------------------------------------------------------------------------
  925. void __fastcall TWebDAVFileSystem::CustomReadFile(UnicodeString FileName,
  926. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  927. {
  928. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  929. int NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  930. if (IsValidRedirect(NeonStatus, FileName))
  931. {
  932. NeonStatus = CustomReadFileInternal(FileName, File, ALinkedByFile);
  933. }
  934. CheckStatus(NeonStatus);
  935. }
  936. //---------------------------------------------------------------------------
  937. void __fastcall TWebDAVFileSystem::DeleteFile(const UnicodeString FileName,
  938. const TRemoteFile * File, int /*Params*/, TRmSessionAction & Action)
  939. {
  940. Action.Recursive();
  941. ClearNeonError();
  942. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  943. UnicodeString Path = File->FullFileName;
  944. if (File->IsDirectory)
  945. {
  946. Path = DirectoryPath(Path);
  947. }
  948. // WebDAV does not allow non-recursive delete:
  949. // RFC 4918, section 9.6.1:
  950. // "A client MUST NOT submit a Depth header with a DELETE on a collection with any value but infinity."
  951. // We should check that folder is empty when called with FLAGSET(Params, dfNoRecursive)
  952. CheckStatus(ne_delete(FNeonSession, PathToNeon(Path)));
  953. }
  954. //---------------------------------------------------------------------------
  955. int __fastcall TWebDAVFileSystem::RenameFileInternal(const UnicodeString & FileName,
  956. const UnicodeString & NewName)
  957. {
  958. // 0 = no overwrite
  959. return ne_move(FNeonSession, 0, PathToNeon(FileName), PathToNeon(NewName));
  960. }
  961. //---------------------------------------------------------------------------
  962. void __fastcall TWebDAVFileSystem::RenameFile(const UnicodeString FileName,
  963. const UnicodeString NewName)
  964. {
  965. ClearNeonError();
  966. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  967. UnicodeString Path = FileName;
  968. int NeonStatus = RenameFileInternal(Path, NewName);
  969. if (IsValidRedirect(NeonStatus, Path))
  970. {
  971. NeonStatus = RenameFileInternal(Path, NewName);
  972. }
  973. CheckStatus(NeonStatus);
  974. }
  975. //---------------------------------------------------------------------------
  976. void __fastcall TWebDAVFileSystem::CopyFile(const UnicodeString FileName,
  977. const UnicodeString NewName)
  978. {
  979. FAIL;
  980. }
  981. //---------------------------------------------------------------------------
  982. void __fastcall TWebDAVFileSystem::CreateDirectory(const UnicodeString DirName)
  983. {
  984. ClearNeonError();
  985. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  986. CheckStatus(ne_mkcol(FNeonSession, PathToNeon(DirName)));
  987. }
  988. //---------------------------------------------------------------------------
  989. void __fastcall TWebDAVFileSystem::CreateLink(const UnicodeString FileName,
  990. const UnicodeString PointTo, bool /*Symbolic*/)
  991. {
  992. FAIL;
  993. }
  994. //---------------------------------------------------------------------------
  995. void __fastcall TWebDAVFileSystem::ChangeFileProperties(const UnicodeString FileName,
  996. const TRemoteFile * /*File*/, const TRemoteProperties * /*Properties*/,
  997. TChmodSessionAction & /*Action*/)
  998. {
  999. FAIL;
  1000. }
  1001. //---------------------------------------------------------------------------
  1002. bool __fastcall TWebDAVFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  1003. {
  1004. FAIL;
  1005. return false;
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. void __fastcall TWebDAVFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
  1009. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  1010. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  1011. {
  1012. FAIL;
  1013. }
  1014. //---------------------------------------------------------------------------
  1015. void __fastcall TWebDAVFileSystem::ConfirmOverwrite(
  1016. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  1017. TFileOperationProgressType * OperationProgress,
  1018. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1019. int Params)
  1020. {
  1021. // all = "yes to newer"
  1022. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  1023. TQueryButtonAlias Aliases[3];
  1024. Aliases[0].Button = qaAll;
  1025. Aliases[0].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  1026. Aliases[0].GroupWith = qaYes;
  1027. Aliases[0].GrouppedShiftState = TShiftState() << ssCtrl;
  1028. Aliases[1].Button = qaYesToAll;
  1029. Aliases[1].GroupWith = qaYes;
  1030. Aliases[1].GrouppedShiftState = TShiftState() << ssShift;
  1031. Aliases[2].Button = qaNoToAll;
  1032. Aliases[2].GroupWith = qaNo;
  1033. Aliases[2].GrouppedShiftState = TShiftState() << ssShift;
  1034. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1035. QueryParams.Aliases = Aliases;
  1036. QueryParams.AliasesCount = LENOF(Aliases);
  1037. unsigned int Answer;
  1038. {
  1039. TSuspendFileOperationProgress Suspend(OperationProgress);
  1040. Answer =
  1041. FTerminal->ConfirmFileOverwrite(
  1042. SourceFullFileName, TargetFileName, FileParams, Answers, &QueryParams,
  1043. (OperationProgress->Side == osLocal) ? osRemote : osLocal,
  1044. CopyParam, Params, OperationProgress);
  1045. }
  1046. switch (Answer)
  1047. {
  1048. case qaYes:
  1049. // noop
  1050. break;
  1051. case qaNo:
  1052. THROW_SKIP_FILE_NULL;
  1053. default:
  1054. FAIL;
  1055. case qaCancel:
  1056. if (!OperationProgress->Cancel)
  1057. {
  1058. OperationProgress->Cancel = csCancel;
  1059. }
  1060. Abort();
  1061. break;
  1062. }
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. void __fastcall TWebDAVFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1066. const TRemoteFile * /*File*/, UnicodeString Command, int /*Params*/, TCaptureOutputEvent /*OutputEvent*/)
  1067. {
  1068. FAIL;
  1069. }
  1070. //---------------------------------------------------------------------------
  1071. void __fastcall TWebDAVFileSystem::AnyCommand(const UnicodeString Command,
  1072. TCaptureOutputEvent /*OutputEvent*/)
  1073. {
  1074. FAIL;
  1075. }
  1076. //---------------------------------------------------------------------------
  1077. TStrings * __fastcall TWebDAVFileSystem::GetFixedPaths()
  1078. {
  1079. return NULL;
  1080. }
  1081. //---------------------------------------------------------------------------
  1082. void TWebDAVFileSystem::NeonQuotaResult(
  1083. void * UserData, const ne_uri * /*Uri*/, const ne_prop_result_set * Results)
  1084. {
  1085. TSpaceAvailable & SpaceAvailable = *static_cast<TSpaceAvailable *>(UserData);
  1086. const char * Value = GetProp(Results, PROP_QUOTA_AVAILABLE);
  1087. if (Value != NULL)
  1088. {
  1089. SpaceAvailable.UnusedBytesAvailableToUser = StrToInt64(StrFromNeon(Value));
  1090. const char * Value = GetProp(Results, PROP_QUOTA_USED);
  1091. if (Value != NULL)
  1092. {
  1093. SpaceAvailable.BytesAvailableToUser =
  1094. StrToInt64(StrFromNeon(Value)) + SpaceAvailable.UnusedBytesAvailableToUser;
  1095. }
  1096. }
  1097. }
  1098. //---------------------------------------------------------------------------
  1099. void __fastcall TWebDAVFileSystem::SpaceAvailable(const UnicodeString Path,
  1100. TSpaceAvailable & ASpaceAvailable)
  1101. {
  1102. // RFC4331: http://tools.ietf.org/html/rfc4331
  1103. // This is known to be supported by:
  1104. // OpenDrive: for a root drive only (and contrary to the spec, it sends the properties
  1105. // unconditionally, even when not explicitly requested)
  1106. // Server: Apache/2.2.17 (Fedora)
  1107. // X-Powered-By: PHP/5.5.7
  1108. // X-DAV-Powered-By: OpenDrive
  1109. // WWW-Authenticate: Basic realm="PHP WebDAV"
  1110. // IT Hit WebDAV Server:
  1111. // Server: Microsoft-HTTPAPI/1.0
  1112. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1113. // Yandex disk:
  1114. // WWW-Authenticate: Basic realm="Yandex.Disk"
  1115. // Server: MochiWeb/1.0
  1116. UnicodeString APath = DirectoryPath(Path);
  1117. ne_propname QuotaProps[3];
  1118. memset(QuotaProps, 0, sizeof(QuotaProps));
  1119. QuotaProps[0].nspace = DAV_PROP_NAMESPACE;
  1120. QuotaProps[0].name = PROP_QUOTA_AVAILABLE;
  1121. QuotaProps[1].nspace = DAV_PROP_NAMESPACE;
  1122. QuotaProps[1].name = PROP_QUOTA_USED;
  1123. QuotaProps[2].nspace = NULL;
  1124. QuotaProps[2].name = NULL;
  1125. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  1126. CheckStatus(
  1127. ne_simple_propfind(FNeonSession, PathToNeon(APath), NE_DEPTH_ZERO, QuotaProps,
  1128. NeonQuotaResult, &ASpaceAvailable));
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. void __fastcall TWebDAVFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1132. const UnicodeString ATargetDir, const TCopyParamType * CopyParam,
  1133. int Params, TFileOperationProgressType * OperationProgress,
  1134. TOnceDoneOperation & OnceDoneOperation)
  1135. {
  1136. assert((FilesToCopy != NULL) && (OperationProgress != NULL));
  1137. Params &= ~cpAppend;
  1138. UnicodeString FileName, FileNameOnly;
  1139. UnicodeString TargetDir = AbsolutePath(ATargetDir, false);
  1140. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  1141. intptr_t Index = 0;
  1142. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  1143. {
  1144. bool Success = false;
  1145. FileName = FilesToCopy->Strings[Index];
  1146. FileNameOnly = ExtractFileName(FileName, false);
  1147. try
  1148. {
  1149. try
  1150. {
  1151. if (FTerminal->SessionData->CacheDirectories)
  1152. {
  1153. FTerminal->DirectoryModified(TargetDir, false);
  1154. if (::DirectoryExists(ApiPath(::ExtractFilePath(FileName))))
  1155. {
  1156. FTerminal->DirectoryModified(FullTargetDir + FileNameOnly, true);
  1157. }
  1158. }
  1159. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  1160. tfFirstLevel);
  1161. Success = true;
  1162. }
  1163. catch (EScpSkipFile & E)
  1164. {
  1165. TSuspendFileOperationProgress Suspend(OperationProgress);
  1166. if (!FTerminal->HandleException(&E))
  1167. {
  1168. throw;
  1169. }
  1170. }
  1171. }
  1172. __finally
  1173. {
  1174. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1175. }
  1176. Index++;
  1177. }
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. void __fastcall TWebDAVFileSystem::SourceRobust(const UnicodeString FileName,
  1181. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1182. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1183. {
  1184. // the same in TSFTPFileSystem
  1185. TUploadSessionAction Action(FTerminal->ActionLog);
  1186. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  1187. do
  1188. {
  1189. bool ChildError = false;
  1190. try
  1191. {
  1192. Source(FileName, TargetDir, CopyParam, Params, OperationProgress,
  1193. Flags, Action, ChildError);
  1194. }
  1195. catch (Exception & E)
  1196. {
  1197. if (!RobustLoop.TryReopen(E))
  1198. {
  1199. if (!ChildError)
  1200. {
  1201. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1202. }
  1203. throw;
  1204. }
  1205. }
  1206. if (RobustLoop.ShouldRetry())
  1207. {
  1208. OperationProgress->RollbackTransfer();
  1209. Action.Restart();
  1210. // prevent overwrite confirmations
  1211. // (should not be set for directories!)
  1212. Params |= cpNoConfirmation;
  1213. }
  1214. }
  1215. while (RobustLoop.Retry());
  1216. }
  1217. //---------------------------------------------------------------------------
  1218. void __fastcall TWebDAVFileSystem::Source(const UnicodeString FileName,
  1219. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1220. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1221. TUploadSessionAction & Action, bool & ChildError)
  1222. {
  1223. Action.FileName(ExpandUNCFileName(FileName));
  1224. OperationProgress->SetFile(FileName, false);
  1225. if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
  1226. {
  1227. THROW_SKIP_FILE_NULL;
  1228. }
  1229. HANDLE File;
  1230. __int64 MTime;
  1231. __int64 Size;
  1232. int Attrs;
  1233. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &Attrs,
  1234. &File, NULL, &MTime, NULL, &Size);
  1235. bool Dir = FLAGSET(Attrs, faDirectory);
  1236. int FD = -1;
  1237. try
  1238. {
  1239. OperationProgress->SetFileInProgress();
  1240. if (Dir)
  1241. {
  1242. Action.Cancel();
  1243. DirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  1244. Attrs, CopyParam, Params, OperationProgress, Flags);
  1245. }
  1246. else
  1247. {
  1248. UnicodeString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  1249. osLocal, FLAGSET(Flags, tfFirstLevel));
  1250. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  1251. OperationProgress->SetLocalSize(Size);
  1252. // Suppose same data size to transfer as to read
  1253. // (not true with ASCII transfer)
  1254. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1255. OperationProgress->TransferingFile = false;
  1256. UnicodeString DestFullName = TargetDir + DestFileName;
  1257. TRemoteFile * RemoteFile = NULL;
  1258. try
  1259. {
  1260. TValueRestorer<TIgnoreAuthenticationFailure> IgnoreAuthenticationFailureRestorer(FIgnoreAuthenticationFailure);
  1261. FIgnoreAuthenticationFailure = iafWaiting;
  1262. // this should not throw
  1263. CustomReadFileInternal(DestFullName, RemoteFile, NULL);
  1264. }
  1265. catch (...)
  1266. {
  1267. if (!FTerminal->Active)
  1268. {
  1269. throw;
  1270. }
  1271. }
  1272. TDateTime Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  1273. if (RemoteFile != NULL)
  1274. {
  1275. TOverwriteFileParams FileParams;
  1276. FileParams.SourceSize = Size;
  1277. FileParams.SourceTimestamp = Modification;
  1278. FileParams.DestSize = RemoteFile->Size;
  1279. FileParams.DestTimestamp = RemoteFile->Modification;
  1280. delete RemoteFile;
  1281. ConfirmOverwrite(FileName, DestFileName, OperationProgress,
  1282. &FileParams, CopyParam, Params);
  1283. }
  1284. DestFullName = TargetDir + DestFileName;
  1285. // only now, we know the final destination
  1286. // (not really true as we do not support changing file name on overwrite dialog)
  1287. Action.Destination(DestFullName);
  1288. FILE_OPERATION_LOOP_BEGIN
  1289. {
  1290. SetFilePointer(File, 0, NULL, FILE_BEGIN);
  1291. FD = _open_osfhandle((intptr_t)File, O_BINARY);
  1292. if (FD < 0)
  1293. {
  1294. THROW_SKIP_FILE_NULL;
  1295. }
  1296. TAutoFlag UploadingFlag(FUploading);
  1297. ClearNeonError();
  1298. CheckStatus(ne_put(FNeonSession, PathToNeon(DestFullName), FD));
  1299. }
  1300. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1301. if (CopyParam->PreserveTime)
  1302. {
  1303. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1304. (StandardTimestamp(Modification))));
  1305. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Modification);
  1306. try
  1307. {
  1308. TDateTime ModificationUTC = ConvertTimestampToUTC(Modification);
  1309. TFormatSettings FormatSettings = GetEngFormatSettings();
  1310. UnicodeString LastModified =
  1311. FormatDateTime(L"ddd, d mmm yyyy hh:nn:ss 'GMT'", ModificationUTC, FormatSettings);
  1312. UTF8String NeonLastModified(LastModified);
  1313. // second element is "NULL-terminating"
  1314. ne_proppatch_operation Operations[2];
  1315. memset(Operations, 0, sizeof(Operations));
  1316. ne_propname LastModifiedProp;
  1317. LastModifiedProp.nspace = DAV_PROP_NAMESPACE;
  1318. LastModifiedProp.name = PROP_LAST_MODIFIED;
  1319. Operations[0].name = &LastModifiedProp;
  1320. Operations[0].type = ne_propset;
  1321. Operations[0].value = NeonLastModified.c_str();
  1322. int Status = ne_proppatch(FNeonSession, PathToNeon(DestFullName), Operations);
  1323. if (Status == NE_ERROR)
  1324. {
  1325. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  1326. (GetNeonError())));
  1327. // Ignore errors as major WebDAV servers (like IIS), do not support
  1328. // changing getlastmodified.
  1329. // The only server we found that supports this is TradeMicro SafeSync.
  1330. // But it announces itself as "Server: Apache",
  1331. // so it's not reliably autodetect the support.
  1332. TouchAction.Cancel();
  1333. }
  1334. else
  1335. {
  1336. CheckStatus(Status);
  1337. }
  1338. }
  1339. catch (Exception & E)
  1340. {
  1341. TouchAction.Rollback(&E);
  1342. ChildError = true;
  1343. throw;
  1344. }
  1345. }
  1346. FTerminal->LogFileDone(OperationProgress);
  1347. }
  1348. }
  1349. __finally
  1350. {
  1351. if (FD >= 0)
  1352. {
  1353. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1354. // but it crashes code guard
  1355. _close(FD);
  1356. }
  1357. else if (File != NULL)
  1358. {
  1359. CloseHandle(File);
  1360. }
  1361. }
  1362. // TODO : Delete also read-only files.
  1363. if (FLAGSET(Params, cpDelete))
  1364. {
  1365. if (!Dir)
  1366. {
  1367. FILE_OPERATION_LOOP_BEGIN
  1368. {
  1369. THROWOSIFFALSE(::DeleteFile(ApiPath(FileName).c_str()));
  1370. }
  1371. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  1372. }
  1373. }
  1374. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1375. {
  1376. FILE_OPERATION_LOOP_BEGIN
  1377. {
  1378. THROWOSIFFALSE(FileSetAttr(ApiPath(FileName), Attrs & ~faArchive) == 0);
  1379. }
  1380. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  1381. }
  1382. }
  1383. //---------------------------------------------------------------------------
  1384. void __fastcall TWebDAVFileSystem::DirectorySource(const UnicodeString DirectoryName,
  1385. const UnicodeString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  1386. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1387. {
  1388. UnicodeString DestDirectoryName = CopyParam->ChangeFileName(
  1389. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  1390. FLAGSET(Flags, tfFirstLevel));
  1391. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  1392. // create DestFullName if it does not exist
  1393. if (!FTerminal->FileExists(DestFullName))
  1394. {
  1395. TRemoteProperties Properties;
  1396. if (CopyParam->PreserveRights)
  1397. {
  1398. Properties.Valid = TValidProperties() << vpRights;
  1399. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  1400. }
  1401. FTerminal->CreateDirectory(DestFullName, &Properties);
  1402. }
  1403. OperationProgress->SetFile(DirectoryName);
  1404. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1405. TSearchRecChecked SearchRec;
  1406. bool FindOK;
  1407. FILE_OPERATION_LOOP_BEGIN
  1408. {
  1409. FindOK =
  1410. (FindFirstChecked(DirectoryName + L"*.*", FindAttrs, SearchRec) == 0);
  1411. }
  1412. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1413. try
  1414. {
  1415. while (FindOK && !OperationProgress->Cancel)
  1416. {
  1417. UnicodeString FileName = DirectoryName + SearchRec.Name;
  1418. try
  1419. {
  1420. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1421. {
  1422. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  1423. Flags & ~(tfFirstLevel));
  1424. }
  1425. }
  1426. catch (EScpSkipFile & E)
  1427. {
  1428. // If ESkipFile occurs, just log it and continue with next file
  1429. TSuspendFileOperationProgress Suspend(OperationProgress);
  1430. // here a message to user was displayed, which was not appropriate
  1431. // when user refused to overwrite the file in subdirectory.
  1432. // hopefully it won't be missing in other situations.
  1433. if (!FTerminal->HandleException(&E))
  1434. {
  1435. throw;
  1436. }
  1437. }
  1438. FILE_OPERATION_LOOP_BEGIN
  1439. {
  1440. FindOK = (FindNextChecked(SearchRec) == 0);
  1441. }
  1442. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1443. }
  1444. }
  1445. __finally
  1446. {
  1447. FindClose(SearchRec);
  1448. }
  1449. // TODO : Delete also read-only directories.
  1450. // TODO : Show error message on failure.
  1451. if (!OperationProgress->Cancel)
  1452. {
  1453. if (FLAGSET(Params, cpDelete))
  1454. {
  1455. RemoveDir(ApiPath(DirectoryName));
  1456. }
  1457. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1458. {
  1459. FILE_OPERATION_LOOP_BEGIN
  1460. {
  1461. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  1462. }
  1463. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  1464. }
  1465. }
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. void __fastcall TWebDAVFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1469. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1470. int Params, TFileOperationProgressType * OperationProgress,
  1471. TOnceDoneOperation & OnceDoneOperation)
  1472. {
  1473. Params &= ~cpAppend;
  1474. UnicodeString FullTargetDir = ::IncludeTrailingBackslash(TargetDir);
  1475. int Index = 0;
  1476. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  1477. {
  1478. UnicodeString FileName = FilesToCopy->Strings[Index];
  1479. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  1480. bool Success = false;
  1481. try
  1482. {
  1483. try
  1484. {
  1485. SinkRobust(AbsolutePath(FileName, false), File, FullTargetDir, CopyParam, Params,
  1486. OperationProgress, tfFirstLevel);
  1487. Success = true;
  1488. }
  1489. catch (EScpSkipFile & E)
  1490. {
  1491. TSuspendFileOperationProgress Suspend(OperationProgress);
  1492. if (!FTerminal->HandleException(&E))
  1493. {
  1494. throw;
  1495. }
  1496. }
  1497. }
  1498. __finally
  1499. {
  1500. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1501. }
  1502. Index++;
  1503. }
  1504. }
  1505. //---------------------------------------------------------------------------
  1506. void __fastcall TWebDAVFileSystem::SinkRobust(const UnicodeString FileName,
  1507. const TRemoteFile * File, const UnicodeString TargetDir,
  1508. const TCopyParamType * CopyParam, int Params,
  1509. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1510. {
  1511. // the same in TSFTPFileSystem
  1512. TDownloadSessionAction Action(FTerminal->ActionLog);
  1513. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  1514. do
  1515. {
  1516. bool ChildError = false;
  1517. try
  1518. {
  1519. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  1520. Flags, Action, ChildError);
  1521. }
  1522. catch (Exception & E)
  1523. {
  1524. if (!RobustLoop.TryReopen(E))
  1525. {
  1526. if (!ChildError)
  1527. {
  1528. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1529. }
  1530. throw;
  1531. }
  1532. }
  1533. if (RobustLoop.ShouldRetry())
  1534. {
  1535. OperationProgress->RollbackTransfer();
  1536. Action.Restart();
  1537. assert(File != NULL);
  1538. if (!File->IsDirectory)
  1539. {
  1540. // prevent overwrite confirmations
  1541. Params |= cpNoConfirmation;
  1542. }
  1543. }
  1544. }
  1545. while (RobustLoop.Retry());
  1546. }
  1547. //---------------------------------------------------------------------------
  1548. void TWebDAVFileSystem::NeonCreateRequest(
  1549. ne_request * Request, void * UserData, const char * /*Method*/, const char * /*Uri*/)
  1550. {
  1551. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1552. ne_set_request_private(Request, SESSION_FS_KEY, FileSystem);
  1553. ne_add_response_body_reader(Request, NeonBodyAccepter, NeonBodyReader, Request);
  1554. }
  1555. //---------------------------------------------------------------------------
  1556. void TWebDAVFileSystem::NeonPreSend(
  1557. ne_request * Request, void * UserData, ne_buffer * Header)
  1558. {
  1559. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1560. if (FileSystem->FDownloading)
  1561. {
  1562. // Needed by IIS server to make it download source code, not code output,
  1563. // and mainly to even allow downloading file with unregistered extensions.
  1564. // Without it files like .001 return 404 (Not found) HTTP code.
  1565. // http://msdn.microsoft.com/en-us/library/cc250098.aspx
  1566. // http://msdn.microsoft.com/en-us/library/cc250216.aspx
  1567. // http://lists.manyfish.co.uk/pipermail/neon/2012-April/001452.html
  1568. // It's also supported by Oracle server:
  1569. // https://docs.oracle.com/cd/E19146-01/821-1828/gczya/index.html
  1570. // We do not know yet of any server that fails when the header is used,
  1571. // so it's added unconditionally.
  1572. ne_buffer_zappend(Header, "Translate: f\r\n");
  1573. }
  1574. if (FileSystem->FTerminal->Log->Logging)
  1575. {
  1576. const char * Buffer;
  1577. size_t Size;
  1578. if (ne_get_request_body_buffer(Request, &Buffer, &Size))
  1579. {
  1580. // all neon request types that use ne_add_request_header
  1581. // use XML content-type, so it's text-based
  1582. assert(ContainsStr(AnsiString(Header->data, Header->used), "Content-Type: " NE_XML_MEDIA_TYPE));
  1583. FileSystem->FTerminal->Log->Add(llInput, UnicodeString(UTF8String(Buffer, Size)));
  1584. }
  1585. }
  1586. if (FileSystem->FUploading)
  1587. {
  1588. ne_set_request_body_provider_pre(Request,
  1589. FileSystem->NeonUploadBodyProvider, FileSystem);
  1590. }
  1591. FileSystem->FResponse = L"";
  1592. }
  1593. //---------------------------------------------------------------------------
  1594. int TWebDAVFileSystem::NeonPostSend(ne_request * /*Req*/, void * UserData,
  1595. const ne_status * /*Status*/)
  1596. {
  1597. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1598. if (!FileSystem->FResponse.IsEmpty())
  1599. {
  1600. FileSystem->FTerminal->Log->Add(llOutput, FileSystem->FResponse);
  1601. }
  1602. return NE_OK;
  1603. }
  1604. //---------------------------------------------------------------------------
  1605. ssize_t TWebDAVFileSystem::NeonUploadBodyProvider(void * UserData, char * /*Buffer*/, size_t /*BufLen*/)
  1606. {
  1607. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  1608. ssize_t Result;
  1609. if (FileSystem->CancelTransfer())
  1610. {
  1611. Result = -1;
  1612. }
  1613. else
  1614. {
  1615. Result = 1;
  1616. }
  1617. return Result;
  1618. }
  1619. //---------------------------------------------------------------------------
  1620. static void __fastcall AddHeaderValueToList(UnicodeString & List, ne_request * Request, const char * Name)
  1621. {
  1622. const char * Value;
  1623. Value = ne_get_response_header(Request, Name);
  1624. if (Value != NULL)
  1625. {
  1626. AddToList(List, StrFromNeon(Value), L"; ");
  1627. }
  1628. }
  1629. //---------------------------------------------------------------------------
  1630. int TWebDAVFileSystem::NeonBodyAccepter(void * UserData, ne_request * Request, const ne_status * Status)
  1631. {
  1632. assert(UserData == Request);
  1633. TWebDAVFileSystem * FileSystem =
  1634. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1635. bool AuthenticationFailed = (Status->code == 401) && FileSystem->FAuthenticationRequested;
  1636. bool AuthenticationNeeded = (Status->code == 401) && !FileSystem->FAuthenticationRequested;
  1637. if (FileSystem->FInitialHandshake)
  1638. {
  1639. UnicodeString Line;
  1640. if (AuthenticationNeeded)
  1641. {
  1642. Line = LoadStr(STATUS_AUTHENTICATE);
  1643. }
  1644. else if (AuthenticationFailed)
  1645. {
  1646. Line = LoadStr(FTP_ACCESS_DENIED);
  1647. }
  1648. else if (Status->klass == 2)
  1649. {
  1650. Line = LoadStr(STATUS_AUTHENTICATED);
  1651. }
  1652. if (!Line.IsEmpty())
  1653. {
  1654. FileSystem->FTerminal->Information(Line, true);
  1655. }
  1656. UnicodeString RemoteSystem;
  1657. // Used by IT Hit WebDAV Server:
  1658. // Server: Microsoft-HTTPAPI/1.0
  1659. // X-Engine: IT Hit WebDAV Server .Net v3.8.1877.0 (Evaluation License)
  1660. AddHeaderValueToList(RemoteSystem, Request, "X-Engine");
  1661. // Used by OpenDrive:
  1662. // Server: Apache/2.2.17 (Fedora)
  1663. // X-Powered-By: PHP/5.5.7
  1664. // X-DAV-Powered-By: OpenDrive
  1665. AddHeaderValueToList(RemoteSystem, Request, "X-DAV-Powered-By");
  1666. // Used by IIS:
  1667. // Server: Microsoft-IIS/8.5
  1668. AddHeaderValueToList(RemoteSystem, Request, "Server");
  1669. // Not really useful.
  1670. // Can be e.g. "PleskLin"
  1671. AddHeaderValueToList(RemoteSystem, Request, "X-Powered-By");
  1672. FileSystem->FFileSystemInfo.RemoteSystem = RemoteSystem;
  1673. }
  1674. // When we explicitly fail authentication of request
  1675. // with FIgnoreAuthenticationFailure flag (after it failed with password),
  1676. // neon resets its internal password store and tries the next request
  1677. // without calling our authentication hook first
  1678. // (note AuthenticationFailed vs. AuthenticationNeeded)
  1679. // what likely fails, but we do not want to reset out password
  1680. // (as it was not even tried yet for this request).
  1681. if (AuthenticationFailed)
  1682. {
  1683. if (FileSystem->FIgnoreAuthenticationFailure == iafNo)
  1684. {
  1685. FileSystem->FPassword = RawByteString();
  1686. }
  1687. else
  1688. {
  1689. FileSystem->FIgnoreAuthenticationFailure = iafPasswordFailed;
  1690. }
  1691. }
  1692. return ne_accept_2xx(UserData, Request, Status);
  1693. }
  1694. //---------------------------------------------------------------------------
  1695. bool __fastcall TWebDAVFileSystem::CancelTransfer()
  1696. {
  1697. bool Result = false;
  1698. if ((FUploading || FDownloading) &&
  1699. (FTerminal->OperationProgress != NULL) &&
  1700. (FTerminal->OperationProgress->Cancel != csContinue))
  1701. {
  1702. FCancelled = true;
  1703. Result = true;
  1704. }
  1705. return Result;
  1706. }
  1707. //---------------------------------------------------------------------------
  1708. int TWebDAVFileSystem::NeonBodyReader(void * UserData, const char * Buf, size_t Len)
  1709. {
  1710. ne_request * Request = static_cast<ne_request *>(UserData);
  1711. TWebDAVFileSystem * FileSystem =
  1712. static_cast<TWebDAVFileSystem *>(ne_get_request_private(Request, SESSION_FS_KEY));
  1713. if (FileSystem->FTerminal->Log->Logging)
  1714. {
  1715. ne_content_type ContentType;
  1716. if (ne_get_content_type(Request, &ContentType) == 0)
  1717. {
  1718. // The main point of the content-type check was to exclude
  1719. // GET responses (with file contents).
  1720. // But this won't work when downloading text files that have text
  1721. // content type on their own, hence the additional not-downloading test.
  1722. if (!FileSystem->FDownloading &&
  1723. ((ne_strcasecmp(ContentType.type, "text") == 0) ||
  1724. media_type_is_xml(&ContentType)))
  1725. {
  1726. UnicodeString Content = UnicodeString(UTF8String(Buf, Len)).Trim();
  1727. FileSystem->FResponse += Content;
  1728. }
  1729. ne_free(ContentType.value);
  1730. }
  1731. }
  1732. int Result = FileSystem->CancelTransfer() ? 1 : 0;
  1733. return Result;
  1734. }
  1735. //---------------------------------------------------------------------------
  1736. void __fastcall TWebDAVFileSystem::Sink(const UnicodeString FileName,
  1737. const TRemoteFile * File, const UnicodeString TargetDir,
  1738. const TCopyParamType * CopyParam, int Params,
  1739. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1740. TDownloadSessionAction & Action, bool & ChildError)
  1741. {
  1742. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1743. Action.FileName(FileName);
  1744. assert(File);
  1745. TFileMasks::TParams MaskParams;
  1746. MaskParams.Size = File->Size;
  1747. if (!CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  1748. {
  1749. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  1750. THROW_SKIP_FILE_NULL;
  1751. }
  1752. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  1753. {
  1754. OperationProgress->AddSkippedFileSize(File->Size);
  1755. THROW_SKIP_FILE_NULL;
  1756. }
  1757. FTerminal->LogFileDetails(FileName, TDateTime(), File->Size);
  1758. OperationProgress->SetFile(FileName);
  1759. UnicodeString DestFileName = CopyParam->ChangeFileName(FileNameOnly,
  1760. osRemote, FLAGSET(Flags, tfFirstLevel));
  1761. UnicodeString DestFullName = TargetDir + DestFileName;
  1762. if (File->IsDirectory)
  1763. {
  1764. Action.Cancel();
  1765. if (ALWAYS_TRUE(!File->IsSymLink))
  1766. {
  1767. FILE_OPERATION_LOOP_BEGIN
  1768. {
  1769. int Attrs = FileGetAttr(ApiPath(DestFullName));
  1770. if (FLAGCLEAR(Attrs, faDirectory)) { EXCEPTION; }
  1771. }
  1772. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  1773. FILE_OPERATION_LOOP_BEGIN
  1774. {
  1775. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  1776. }
  1777. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  1778. TSinkFileParams SinkFileParams;
  1779. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  1780. SinkFileParams.CopyParam = CopyParam;
  1781. SinkFileParams.Params = Params;
  1782. SinkFileParams.OperationProgress = OperationProgress;
  1783. SinkFileParams.Skipped = false;
  1784. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  1785. FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  1786. // Do not delete directory if some of its files were skip.
  1787. // Throw "skip file" for the directory to avoid attempt to deletion
  1788. // of any parent directory
  1789. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  1790. {
  1791. THROW_SKIP_FILE_NULL;
  1792. }
  1793. }
  1794. else
  1795. {
  1796. // file is symlink to directory, currently do nothing, but it should be
  1797. // reported to user
  1798. }
  1799. }
  1800. else
  1801. {
  1802. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  1803. if (FileExists(ApiPath(DestFullName)))
  1804. {
  1805. __int64 Size;
  1806. __int64 MTime;
  1807. FTerminal->OpenLocalFile(DestFullName, GENERIC_READ, NULL,
  1808. NULL, NULL, &MTime, NULL, &Size);
  1809. TOverwriteFileParams FileParams;
  1810. FileParams.SourceSize = File->Size;
  1811. FileParams.SourceTimestamp = File->Modification;
  1812. FileParams.DestSize = Size;
  1813. FileParams.DestTimestamp = UnixToDateTime(MTime,
  1814. FTerminal->SessionData->DSTMode);
  1815. ConfirmOverwrite(FileName, DestFileName, OperationProgress,
  1816. &FileParams, CopyParam, Params);
  1817. }
  1818. // Suppose same data size to transfer as to write
  1819. OperationProgress->SetTransferSize(File->Size);
  1820. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1821. int Attrs = -1;
  1822. FILE_OPERATION_LOOP_BEGIN
  1823. {
  1824. Attrs = FileGetAttr(ApiPath(DestFullName));
  1825. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory)) { EXCEPTION; }
  1826. }
  1827. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  1828. OperationProgress->TransferingFile = false; // not set with WebDAV protocol
  1829. UnicodeString FilePath = ::UnixExtractFilePath(FileName);
  1830. if (FilePath.IsEmpty())
  1831. {
  1832. FilePath = L"/";
  1833. }
  1834. Action.Destination(ExpandUNCFileName(DestFullName));
  1835. FILE_OPERATION_LOOP_BEGIN
  1836. {
  1837. HANDLE LocalHandle;
  1838. if (!FTerminal->CreateLocalFile(DestFullName, OperationProgress,
  1839. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  1840. {
  1841. THROW_SKIP_FILE_NULL;
  1842. }
  1843. bool DeleteLocalFile = true;
  1844. int FD = -1;
  1845. try
  1846. {
  1847. FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY);
  1848. if (FD < 0)
  1849. {
  1850. THROW_SKIP_FILE_NULL;
  1851. }
  1852. TAutoFlag DownloadingFlag(FDownloading);
  1853. ClearNeonError();
  1854. CheckStatus(ne_get(FNeonSession, PathToNeon(FileName), FD));
  1855. DeleteLocalFile = false;
  1856. if (CopyParam->PreserveTime)
  1857. {
  1858. TDateTime Modification = File->Modification;
  1859. FILETIME WrTime = DateTimeToFileTime(Modification, FTerminal->SessionData->DSTMode);
  1860. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  1861. (StandardTimestamp(Modification))));
  1862. SetFileTime(LocalHandle, NULL, NULL, &WrTime);
  1863. }
  1864. }
  1865. __finally
  1866. {
  1867. if (FD >= 0)
  1868. {
  1869. // _close calls CloseHandle internally (even doc states, we should not call CloseHandle),
  1870. // but it crashes code guard
  1871. _close(FD);
  1872. }
  1873. else
  1874. {
  1875. CloseHandle(LocalHandle);
  1876. }
  1877. if (DeleteLocalFile)
  1878. {
  1879. FILE_OPERATION_LOOP_BEGIN
  1880. {
  1881. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestFullName)));
  1882. }
  1883. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestFullName)));
  1884. }
  1885. }
  1886. }
  1887. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  1888. if (Attrs == -1)
  1889. {
  1890. Attrs = faArchive;
  1891. }
  1892. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  1893. if ((NewAttrs & Attrs) != NewAttrs)
  1894. {
  1895. FILE_OPERATION_LOOP_BEGIN
  1896. {
  1897. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  1898. }
  1899. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  1900. }
  1901. FTerminal->LogFileDone(OperationProgress);
  1902. }
  1903. if (FLAGSET(Params, cpDelete))
  1904. {
  1905. ChildError = true;
  1906. // If file is directory, do not delete it recursively, because it should be
  1907. // empty already. If not, it should not be deleted (some files were
  1908. // skipped or some new files were copied to it, while we were downloading)
  1909. int Params = dfNoRecursive;
  1910. FTerminal->DeleteFile(FileName, File, &Params);
  1911. ChildError = false;
  1912. }
  1913. }
  1914. //---------------------------------------------------------------------------
  1915. void __fastcall TWebDAVFileSystem::SinkFile(const UnicodeString FileName,
  1916. const TRemoteFile * File, void * Param)
  1917. {
  1918. TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
  1919. assert(Params->OperationProgress);
  1920. try
  1921. {
  1922. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  1923. Params->Params, Params->OperationProgress, Params->Flags);
  1924. }
  1925. catch (EScpSkipFile & E)
  1926. {
  1927. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  1928. Params->Skipped = true;
  1929. {
  1930. TSuspendFileOperationProgress Suspend(OperationProgress);
  1931. if (!FTerminal->HandleException(&E))
  1932. {
  1933. throw;
  1934. }
  1935. }
  1936. if (OperationProgress->Cancel)
  1937. {
  1938. Abort();
  1939. }
  1940. }
  1941. }
  1942. //---------------------------------------------------------------------------
  1943. bool TWebDAVFileSystem::VerifyCertificate(const TWebDAVCertificateData & Data)
  1944. {
  1945. FTerminal->LogEvent(
  1946. FORMAT(L"Verifying certificate for \"%s\" with fingerprint %s and %2.2X failures",
  1947. (Data.Subject, Data.Fingerprint, Data.Failures)));
  1948. int Failures = Data.Failures;
  1949. // We can accept only unknown certificate authority.
  1950. if (FLAGSET(Data.Failures, NE_SSL_UNTRUSTED))
  1951. {
  1952. unsigned char * Certificate;
  1953. size_t CertificateLen = ne_unbase64(Data.AsciiCert.c_str(), &Certificate);
  1954. if (CertificateLen > 0)
  1955. {
  1956. if (WindowsValidateCertificate(Certificate, CertificateLen))
  1957. {
  1958. FTerminal->LogEvent(L"Certificate verified against Windows certificate store");
  1959. Failures &= ~NE_SSL_UNTRUSTED;
  1960. }
  1961. ne_free(Certificate);
  1962. }
  1963. }
  1964. UnicodeString Summary;
  1965. if (Failures == 0)
  1966. {
  1967. Summary = LoadStr(CERT_OK);
  1968. }
  1969. else
  1970. {
  1971. int FailuresToList = Failures;
  1972. if (FLAGSET(FailuresToList, NE_SSL_NOTYETVALID))
  1973. {
  1974. AddToList(Summary, LoadStr(CERT_ERR_CERT_NOT_YET_VALID), L" ");
  1975. FailuresToList &= ~NE_SSL_NOTYETVALID;
  1976. }
  1977. if (FLAGSET(FailuresToList, NE_SSL_EXPIRED))
  1978. {
  1979. AddToList(Summary, LoadStr(CERT_ERR_CERT_HAS_EXPIRED), L" ");
  1980. FailuresToList &= ~NE_SSL_EXPIRED;
  1981. }
  1982. // NEON checks certificate host name on its own
  1983. if (FLAGSET(FailuresToList, NE_SSL_IDMISMATCH))
  1984. {
  1985. AddToList(Summary, FMTLOAD(CERT_NAME_MISMATCH, (FHostName)), L" ");
  1986. FailuresToList &= ~NE_SSL_IDMISMATCH;
  1987. }
  1988. if (FLAGSET(FailuresToList, NE_SSL_UNTRUSTED))
  1989. {
  1990. AddToList(Summary, LoadStr(CERT_ERR_CERT_UNTRUSTED), L" ");
  1991. FailuresToList &= ~NE_SSL_UNTRUSTED;
  1992. }
  1993. if (FLAGSET(FailuresToList, NE_SSL_BADCHAIN))
  1994. {
  1995. AddToList(Summary, LoadStr(CERT_ERR_BAD_CHAIN), L" ");
  1996. FailuresToList &= ~NE_SSL_BADCHAIN;
  1997. }
  1998. // nb, NE_SSL_REVOKED is never used by OpenSSL implementation
  1999. if (FailuresToList != 0)
  2000. {
  2001. AddToList(Summary, LoadStr(CERT_ERR_UNKNOWN), L" ");
  2002. }
  2003. }
  2004. UnicodeString ValidityTimeFormat = L"ddddd tt";
  2005. FSessionInfo.CertificateFingerprint = Data.Fingerprint;
  2006. FSessionInfo.Certificate =
  2007. FMTLOAD(CERT_TEXT, (
  2008. Data.Issuer + L"\n",
  2009. Data.Subject + L"\n",
  2010. FormatDateTime(ValidityTimeFormat, Data.ValidFrom),
  2011. FormatDateTime(ValidityTimeFormat, Data.ValidUntil),
  2012. Data.Fingerprint,
  2013. Summary));
  2014. bool Result = (Failures == 0);
  2015. if (!Result)
  2016. {
  2017. UnicodeString SiteKey = TSessionData::FormatSiteKey(FHostName, FPortNumber);
  2018. if (!Result)
  2019. {
  2020. Result = FTerminal->VerifyCertificate(
  2021. CertificateStorageKey, SiteKey, Data.Fingerprint, Data.Subject, Failures);
  2022. }
  2023. if (!Result)
  2024. {
  2025. TClipboardHandler ClipboardHandler;
  2026. ClipboardHandler.Text = Data.Fingerprint;
  2027. TQueryButtonAlias Aliases[1];
  2028. Aliases[0].Button = qaRetry;
  2029. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  2030. Aliases[0].OnClick = &ClipboardHandler.Copy;
  2031. TQueryParams Params;
  2032. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  2033. Params.NoBatchAnswers = qaYes | qaRetry;
  2034. Params.Aliases = Aliases;
  2035. Params.AliasesCount = LENOF(Aliases);
  2036. unsigned int Answer = FTerminal->QueryUser(
  2037. FMTLOAD(VERIFY_CERT_PROMPT3, (FSessionInfo.Certificate)),
  2038. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  2039. switch (Answer)
  2040. {
  2041. case qaYes:
  2042. FTerminal->CacheCertificate(CertificateStorageKey, SiteKey, Data.Fingerprint, Failures);
  2043. Result = true;
  2044. break;
  2045. case qaNo:
  2046. Result = true;
  2047. break;
  2048. default:
  2049. FAIL;
  2050. case qaCancel:
  2051. FTerminal->Configuration->Usage->Inc(L"HostNotVerified");
  2052. Result = false;
  2053. break;
  2054. }
  2055. }
  2056. }
  2057. if (Result)
  2058. {
  2059. CollectTLSSessionInfo();
  2060. }
  2061. return Result;
  2062. }
  2063. //------------------------------------------------------------------------------
  2064. void __fastcall TWebDAVFileSystem::CollectTLSSessionInfo()
  2065. {
  2066. // See also TFTPFileSystem::Open().
  2067. // Have to cache the value as the connection (the neon HTTP session, not "our" session)
  2068. // can be closed as the time we need it in CollectUsage().
  2069. FTlsVersionStr = StrFromNeon(ne_ssl_get_version(FNeonSession));
  2070. AddToList(FSessionInfo.SecurityProtocolName, FTlsVersionStr, L", ");
  2071. UnicodeString Cipher = StrFromNeon(ne_ssl_get_cipher(FNeonSession));
  2072. FSessionInfo.CSCipher = Cipher;
  2073. FSessionInfo.SCCipher = Cipher;
  2074. // see CAsyncSslSocketLayer::PrintSessionInfo()
  2075. FTerminal->LogEvent(FORMAT(L"Using %s, cipher %s", (FTlsVersionStr, Cipher)));
  2076. }
  2077. //------------------------------------------------------------------------------
  2078. // A neon-session callback to validate the SSL certificate when the CA
  2079. // is unknown (e.g. a self-signed cert), or there are other SSL
  2080. // certificate problems.
  2081. int TWebDAVFileSystem::NeonServerSSLCallback(void * UserData, int Failures, const ne_ssl_certificate * Certificate)
  2082. {
  2083. TWebDAVCertificateData Data;
  2084. char Fingerprint[NE_SSL_DIGESTLEN] = {0};
  2085. if (ne_ssl_cert_digest(Certificate, Fingerprint) != 0)
  2086. {
  2087. strcpy(Fingerprint, "<unknown>");
  2088. }
  2089. Data.Fingerprint = StrFromNeon(Fingerprint);
  2090. char * AsciiCert = ne_ssl_cert_export(Certificate);
  2091. Data.AsciiCert = StrFromNeon(AsciiCert);
  2092. ne_free(AsciiCert);
  2093. char * Subject = ne_ssl_readable_dname(ne_ssl_cert_subject(Certificate));
  2094. Data.Subject = StrFromNeon(Subject);
  2095. ne_free(Subject);
  2096. char * Issuer = ne_ssl_readable_dname(ne_ssl_cert_issuer(Certificate));
  2097. Data.Issuer = StrFromNeon(Issuer);
  2098. ne_free(Issuer);
  2099. Data.Failures = Failures;
  2100. time_t ValidFrom;
  2101. time_t ValidUntil;
  2102. ne_ssl_cert_validity_time(Certificate, &ValidFrom, &ValidUntil);
  2103. Data.ValidFrom = UnixToDateTime(ValidFrom, dstmWin);
  2104. Data.ValidUntil = UnixToDateTime(ValidUntil, dstmWin);
  2105. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2106. return FileSystem->VerifyCertificate(Data) ? NE_OK : NE_ERROR;
  2107. }
  2108. //------------------------------------------------------------------------------
  2109. int TWebDAVFileSystem::NeonRequestAuth(
  2110. void * UserData, const char * /*Realm*/, int /*Attempt*/, char * UserName, char * Password)
  2111. {
  2112. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2113. TTerminal * Terminal = FileSystem->FTerminal;
  2114. TSessionData * SessionData = Terminal->SessionData;
  2115. bool Result = true;
  2116. // will ask for username only once
  2117. if (FileSystem->FUserName.IsEmpty())
  2118. {
  2119. if (!SessionData->UserName.IsEmpty())
  2120. {
  2121. FileSystem->FUserName = SessionData->UserNameExpanded;
  2122. }
  2123. else
  2124. {
  2125. if (!Terminal->PromptUser(SessionData, pkUserName, LoadStr(USERNAME_TITLE), L"",
  2126. LoadStr(USERNAME_PROMPT2), true, NE_ABUFSIZ, FileSystem->FUserName))
  2127. {
  2128. // note that we never get here actually
  2129. Result = false;
  2130. }
  2131. }
  2132. }
  2133. UnicodeString APassword;
  2134. if (Result)
  2135. {
  2136. // Some servers (Gallery2 on https://g2.pixi.me/w/webdav/)
  2137. // return authentication error (401) on PROPFIND request for
  2138. // non-existing files.
  2139. // When we already tried password before, do not try anymore.
  2140. // When we did not try password before (possible only when
  2141. // server does not require authentication for any previous request,
  2142. // such as when read access is not authenticated), try it now,
  2143. // but use special flag for the try, because when it fails
  2144. // we still want to try password for future requests (such as PUT).
  2145. if (!FileSystem->FPassword.IsEmpty())
  2146. {
  2147. if (FileSystem->FIgnoreAuthenticationFailure == iafPasswordFailed)
  2148. {
  2149. // Fail PROPFIND /nonexising request...
  2150. Result = false;
  2151. }
  2152. else
  2153. {
  2154. APassword = Terminal->DecryptPassword(FileSystem->FPassword);
  2155. }
  2156. }
  2157. else
  2158. {
  2159. if (!SessionData->Password.IsEmpty() && !FileSystem->FStoredPasswordTried)
  2160. {
  2161. APassword = SessionData->Password;
  2162. FileSystem->FStoredPasswordTried = true;
  2163. }
  2164. else
  2165. {
  2166. // Asking for password (or using configured password) the first time,
  2167. // and asking for password.
  2168. // Note that we never get false here actually
  2169. Result =
  2170. Terminal->PromptUser(
  2171. SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  2172. LoadStr(PASSWORD_PROMPT), false, NE_ABUFSIZ, APassword);
  2173. }
  2174. if (Result)
  2175. {
  2176. // While neon remembers the password on its own,
  2177. // we need to keep a copy in case neon store gets reset by
  2178. // 401 response to PROPFIND /nonexisting on G2, see above.
  2179. // Possibly we can do this for G2 servers only.
  2180. FileSystem->FPassword = Terminal->EncryptPassword(APassword);
  2181. }
  2182. }
  2183. }
  2184. if (Result)
  2185. {
  2186. strncpy(UserName, StrToNeon(FileSystem->FUserName), NE_ABUFSIZ);
  2187. strncpy(Password, StrToNeon(APassword), NE_ABUFSIZ);
  2188. }
  2189. FileSystem->FAuthenticationRequested = true;
  2190. return Result ? 0 : -1;
  2191. }
  2192. //------------------------------------------------------------------------------
  2193. int TWebDAVFileSystem::NeonProxyAuth(
  2194. void * UserData, const char * /*Realm*/, int Attempt, char * UserName, char * Password)
  2195. {
  2196. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2197. TSessionData * SessionData = FileSystem->FTerminal->SessionData;
  2198. int Result;
  2199. // no point trying too many times as we always return the same credentials
  2200. // (maybe just one would be enough)
  2201. if (Attempt >= 2)
  2202. {
  2203. Result = 1;
  2204. }
  2205. else
  2206. {
  2207. strncpy(UserName, StrToNeon(SessionData->ProxyUsername), NE_ABUFSIZ);
  2208. strncpy(Password, StrToNeon(SessionData->ProxyPassword), NE_ABUFSIZ);
  2209. Result = 0;
  2210. }
  2211. return Result;
  2212. }
  2213. //------------------------------------------------------------------------------
  2214. void TWebDAVFileSystem::NeonNotifier(void * UserData, ne_session_status Status, const ne_session_status_info * StatusInfo)
  2215. {
  2216. TWebDAVFileSystem * FileSystem = static_cast<TWebDAVFileSystem *>(UserData);
  2217. TFileOperationProgressType * OperationProgress = FileSystem->FTerminal->OperationProgress;
  2218. // We particularly have to filter out response to "put" request,
  2219. // handling that would reset the upload progress back to low number (response is small).
  2220. if (((FileSystem->FUploading && (Status == ne_status_sending)) ||
  2221. (FileSystem->FDownloading && (Status == ne_status_recving))) &&
  2222. ALWAYS_TRUE(OperationProgress != NULL))
  2223. {
  2224. __int64 Progress = StatusInfo->sr.progress;
  2225. __int64 Diff = Progress - OperationProgress->TransferedSize;
  2226. if (Diff > 0)
  2227. {
  2228. OperationProgress->ThrottleToCPSLimit(static_cast<unsigned long>(Diff));
  2229. }
  2230. __int64 Total = StatusInfo->sr.total;
  2231. // Total size unknown
  2232. if (Total < 0)
  2233. {
  2234. if (Diff >= 0)
  2235. {
  2236. OperationProgress->AddTransfered(Diff);
  2237. }
  2238. else
  2239. {
  2240. // Session total has been reset. A new stream started
  2241. OperationProgress->AddTransfered(Progress);
  2242. }
  2243. }
  2244. else
  2245. {
  2246. OperationProgress->SetTransferSize(Total);
  2247. OperationProgress->AddTransfered(Diff);
  2248. }
  2249. }
  2250. }
  2251. //------------------------------------------------------------------------------
  2252. void __fastcall TWebDAVFileSystem::NeonDebug(const UnicodeString & Message)
  2253. {
  2254. FTerminal->LogEvent(Message);
  2255. }
  2256. //------------------------------------------------------------------------------
  2257. void __fastcall TWebDAVFileSystem::InitSslSession(ssl_st * Ssl)
  2258. {
  2259. // See also CAsyncSslSocketLayer::InitSSLConnection
  2260. TSessionData * Data = FTerminal->SessionData;
  2261. #define MASK_TLS_VERSION(VERSION, FLAG) ((Data->MinTlsVersion > VERSION) || (Data->MaxTlsVersion < VERSION) ? FLAG : 0)
  2262. int Options =
  2263. MASK_TLS_VERSION(ssl2, SSL_OP_NO_SSLv2) |
  2264. MASK_TLS_VERSION(ssl3, SSL_OP_NO_SSLv3) |
  2265. MASK_TLS_VERSION(tls10, SSL_OP_NO_TLSv1) |
  2266. MASK_TLS_VERSION(tls11, SSL_OP_NO_TLSv1_1) |
  2267. MASK_TLS_VERSION(tls12, SSL_OP_NO_TLSv1_2);
  2268. // SSL_ctrl() with SSL_CTRL_OPTIONS adds flags (not sets)
  2269. SSL_ctrl(Ssl, SSL_CTRL_OPTIONS, Options, NULL);
  2270. }
  2271. //---------------------------------------------------------------------------
  2272. void __fastcall TWebDAVFileSystem::GetSupportedChecksumAlgs(TStrings * /*Algs*/)
  2273. {
  2274. // NOOP
  2275. }
  2276. //------------------------------------------------------------------------------