WebDAVFileSystem.cpp 88 KB

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