WebDAVFileSystem.cpp 85 KB

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