WebDAVFileSystem.cpp 89 KB

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