WebDAVFileSystem.cpp 93 KB

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