1
0

WebDAVFileSystem.cpp 92 KB

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