WebDAVFileSystem.cpp 91 KB

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