FtpFileSystem.cpp 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #ifndef NO_FILEZILLA
  5. //---------------------------------------------------------------------------
  6. #include <list>
  7. #define MPEXT
  8. #include "FtpFileSystem.h"
  9. #include "FileZillaIntf.h"
  10. #include "Common.h"
  11. #include "Exceptions.h"
  12. #include "Terminal.h"
  13. #include "TextsCore.h"
  14. #include "TextsFileZilla.h"
  15. #include "HelpCore.h"
  16. #include "Security.h"
  17. #include <openssl/x509_vfy.h>
  18. //---------------------------------------------------------------------------
  19. #pragma package(smart_init)
  20. //---------------------------------------------------------------------------
  21. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  22. //---------------------------------------------------------------------------
  23. const int DummyCodeClass = 8;
  24. const int DummyTimeoutCode = 801;
  25. const int DummyCancelCode = 802;
  26. const int DummyDisconnectCode = 803;
  27. //---------------------------------------------------------------------------
  28. class TFileZillaImpl : public TFileZillaIntf
  29. {
  30. public:
  31. __fastcall TFileZillaImpl(TFTPFileSystem * FileSystem);
  32. virtual const wchar_t * __fastcall Option(int OptionID) const;
  33. virtual int __fastcall OptionVal(int OptionID) const;
  34. protected:
  35. virtual bool __fastcall DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam);
  36. virtual bool __fastcall HandleStatus(const wchar_t * Status, int Type);
  37. virtual bool __fastcall HandleAsynchRequestOverwrite(
  38. wchar_t * FileName1, size_t FileName1Len, const wchar_t * FileName2,
  39. const wchar_t * Path1, const wchar_t * Path2,
  40. __int64 Size1, __int64 Size2, time_t LocalTime,
  41. bool HasLocalTime, const TRemoteFileTime & RemoteTime, void * UserData, int & RequestResult);
  42. virtual bool __fastcall HandleAsynchRequestVerifyCertificate(
  43. const TFtpsCertificateData & Data, int & RequestResult);
  44. virtual bool __fastcall HandleAsynchRequestNeedPass(
  45. struct TNeedPassRequestData & Data, int & RequestResult);
  46. virtual bool __fastcall HandleListData(const wchar_t * Path, const TListDataEntry * Entries,
  47. unsigned int Count);
  48. virtual bool __fastcall HandleTransferStatus(bool Valid, __int64 TransferSize,
  49. __int64 Bytes, int Percent, int TimeElapsed, int TimeLeft, int TransferRate,
  50. bool FileTransfer);
  51. virtual bool __fastcall HandleReply(int Command, unsigned int Reply);
  52. virtual bool __fastcall HandleCapabilities(TFTPServerCapabilities * ServerCapabilities);
  53. virtual bool __fastcall CheckError(int ReturnCode, const wchar_t * Context);
  54. virtual void PreserveDownloadFileTime(HANDLE Handle, void * UserData);
  55. virtual bool GetFileModificationTimeInUtc(const wchar_t * FileName, struct tm & Time);
  56. private:
  57. TFTPFileSystem * FFileSystem;
  58. };
  59. //---------------------------------------------------------------------------
  60. __fastcall TFileZillaImpl::TFileZillaImpl(TFTPFileSystem * FileSystem) :
  61. TFileZillaIntf(),
  62. FFileSystem(FileSystem)
  63. {
  64. }
  65. //---------------------------------------------------------------------------
  66. const wchar_t * __fastcall TFileZillaImpl::Option(int OptionID) const
  67. {
  68. return FFileSystem->GetOption(OptionID);
  69. }
  70. //---------------------------------------------------------------------------
  71. int __fastcall TFileZillaImpl::OptionVal(int OptionID) const
  72. {
  73. return FFileSystem->GetOptionVal(OptionID);
  74. }
  75. //---------------------------------------------------------------------------
  76. bool __fastcall TFileZillaImpl::DoPostMessage(TMessageType Type, WPARAM wParam, LPARAM lParam)
  77. {
  78. return FFileSystem->PostMessage(Type, wParam, lParam);
  79. }
  80. //---------------------------------------------------------------------------
  81. bool __fastcall TFileZillaImpl::HandleStatus(const wchar_t * Status, int Type)
  82. {
  83. return FFileSystem->HandleStatus(Status, Type);
  84. }
  85. //---------------------------------------------------------------------------
  86. bool __fastcall TFileZillaImpl::HandleAsynchRequestOverwrite(
  87. wchar_t * FileName1, size_t FileName1Len, const wchar_t * FileName2,
  88. const wchar_t * Path1, const wchar_t * Path2,
  89. __int64 Size1, __int64 Size2, time_t LocalTime,
  90. bool HasLocalTime, const TRemoteFileTime & RemoteTime, void * UserData, int & RequestResult)
  91. {
  92. return FFileSystem->HandleAsynchRequestOverwrite(
  93. FileName1, FileName1Len, FileName2, Path1, Path2, Size1, Size2, LocalTime,
  94. HasLocalTime, RemoteTime, UserData, RequestResult);
  95. }
  96. //---------------------------------------------------------------------------
  97. bool __fastcall TFileZillaImpl::HandleAsynchRequestVerifyCertificate(
  98. const TFtpsCertificateData & Data, int & RequestResult)
  99. {
  100. return FFileSystem->HandleAsynchRequestVerifyCertificate(Data, RequestResult);
  101. }
  102. //---------------------------------------------------------------------------
  103. bool __fastcall TFileZillaImpl::HandleAsynchRequestNeedPass(
  104. struct TNeedPassRequestData & Data, int & RequestResult)
  105. {
  106. return FFileSystem->HandleAsynchRequestNeedPass(Data, RequestResult);
  107. }
  108. //---------------------------------------------------------------------------
  109. bool __fastcall TFileZillaImpl::HandleListData(const wchar_t * Path,
  110. const TListDataEntry * Entries, unsigned int Count)
  111. {
  112. return FFileSystem->HandleListData(Path, Entries, Count);
  113. }
  114. //---------------------------------------------------------------------------
  115. bool __fastcall TFileZillaImpl::HandleTransferStatus(bool Valid, __int64 TransferSize,
  116. __int64 Bytes, int Percent, int TimeElapsed, int TimeLeft, int TransferRate,
  117. bool FileTransfer)
  118. {
  119. return FFileSystem->HandleTransferStatus(Valid, TransferSize, Bytes, Percent,
  120. TimeElapsed, TimeLeft, TransferRate, FileTransfer);
  121. }
  122. //---------------------------------------------------------------------------
  123. bool __fastcall TFileZillaImpl::HandleReply(int Command, unsigned int Reply)
  124. {
  125. return FFileSystem->HandleReply(Command, Reply);
  126. }
  127. //---------------------------------------------------------------------------
  128. bool __fastcall TFileZillaImpl::HandleCapabilities(TFTPServerCapabilities * ServerCapabilities)
  129. {
  130. return FFileSystem->HandleCapabilities(ServerCapabilities);
  131. }
  132. //---------------------------------------------------------------------------
  133. bool __fastcall TFileZillaImpl::CheckError(int ReturnCode, const wchar_t * Context)
  134. {
  135. return FFileSystem->CheckError(ReturnCode, Context);
  136. }
  137. //---------------------------------------------------------------------------
  138. void TFileZillaImpl::PreserveDownloadFileTime(HANDLE Handle, void * UserData)
  139. {
  140. return FFileSystem->PreserveDownloadFileTime(Handle, UserData);
  141. }
  142. //---------------------------------------------------------------------------
  143. bool TFileZillaImpl::GetFileModificationTimeInUtc(const wchar_t * FileName, struct tm & Time)
  144. {
  145. return FFileSystem->GetFileModificationTimeInUtc(FileName, Time);
  146. }
  147. //---------------------------------------------------------------------------
  148. //---------------------------------------------------------------------------
  149. class TMessageQueue : public std::list<std::pair<WPARAM, LPARAM> >
  150. {
  151. };
  152. //---------------------------------------------------------------------------
  153. //---------------------------------------------------------------------------
  154. struct TFileTransferData
  155. {
  156. TFileTransferData()
  157. {
  158. Params = 0;
  159. AutoResume = false;
  160. OverwriteResult = -1;
  161. CopyParam = NULL;
  162. }
  163. UnicodeString FileName;
  164. int Params;
  165. bool AutoResume;
  166. int OverwriteResult;
  167. const TCopyParamType * CopyParam;
  168. TDateTime Modification;
  169. };
  170. //---------------------------------------------------------------------------
  171. const int tfFirstLevel = 0x01;
  172. const int tfAutoResume = 0x02;
  173. const wchar_t CertificateStorageKey[] = L"FtpsCertificates";
  174. //---------------------------------------------------------------------------
  175. struct TSinkFileParams
  176. {
  177. UnicodeString TargetDir;
  178. const TCopyParamType * CopyParam;
  179. int Params;
  180. TFileOperationProgressType * OperationProgress;
  181. bool Skipped;
  182. unsigned int Flags;
  183. };
  184. //---------------------------------------------------------------------------
  185. class TFileListHelper
  186. {
  187. public:
  188. TFileListHelper(TFTPFileSystem * FileSystem, TRemoteFileList * FileList,
  189. bool IgnoreFileList) :
  190. FFileSystem(FileSystem),
  191. FFileList(FFileSystem->FFileList),
  192. FIgnoreFileList(FFileSystem->FIgnoreFileList)
  193. {
  194. FFileSystem->FFileList = FileList;
  195. FFileSystem->FIgnoreFileList = IgnoreFileList;
  196. }
  197. ~TFileListHelper()
  198. {
  199. FFileSystem->FFileList = FFileList;
  200. FFileSystem->FIgnoreFileList = FIgnoreFileList;
  201. }
  202. private:
  203. TFTPFileSystem * FFileSystem;
  204. TRemoteFileList * FFileList;
  205. bool FIgnoreFileList;
  206. };
  207. //---------------------------------------------------------------------------
  208. __fastcall TFTPFileSystem::TFTPFileSystem(TTerminal * ATerminal):
  209. TCustomFileSystem(ATerminal),
  210. FFileZillaIntf(NULL),
  211. FQueueCriticalSection(new TCriticalSection),
  212. FTransferStatusCriticalSection(new TCriticalSection),
  213. FQueueEvent(CreateEvent(NULL, true, false, NULL)),
  214. FQueue(new TMessageQueue),
  215. FReply(0),
  216. FCommandReply(0),
  217. FLastCommand(CMD_UNKNOWN),
  218. FLastResponse(new TStringList()),
  219. FLastErrorResponse(new TStringList()),
  220. FLastError(new TStringList()),
  221. FFeatures(new TStringList()),
  222. FFileList(NULL),
  223. FFileListCache(NULL),
  224. FActive(false),
  225. FOpening(false),
  226. FWaitingForReply(false),
  227. FIgnoreFileList(false),
  228. FOnCaptureOutput(NULL),
  229. FFileSystemInfoValid(false),
  230. FDoListAll(false),
  231. FServerCapabilities(NULL)
  232. {
  233. ResetReply();
  234. FListAll = FTerminal->SessionData->FtpListAll;
  235. FFileSystemInfo.ProtocolBaseName = L"FTP";
  236. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  237. FTimeoutStatus = LoadStr(IDS_ERRORMSG_TIMEOUT);
  238. FDisconnectStatus = LoadStr(IDS_STATUSMSG_DISCONNECTED);
  239. FServerCapabilities = new TFTPServerCapabilities();
  240. }
  241. //---------------------------------------------------------------------------
  242. __fastcall TFTPFileSystem::~TFTPFileSystem()
  243. {
  244. assert(FFileList == NULL);
  245. FFileZillaIntf->Destroying();
  246. // to release memory associated with the messages
  247. DiscardMessages();
  248. delete FFileZillaIntf;
  249. FFileZillaIntf = NULL;
  250. delete FQueue;
  251. FQueue = NULL;
  252. CloseHandle(FQueueEvent);
  253. delete FQueueCriticalSection;
  254. FQueueCriticalSection = NULL;
  255. delete FTransferStatusCriticalSection;
  256. FTransferStatusCriticalSection = NULL;
  257. delete FLastResponse;
  258. FLastResponse = NULL;
  259. delete FLastErrorResponse;
  260. FLastErrorResponse = NULL;
  261. delete FLastError;
  262. FLastError = NULL;
  263. delete FFeatures;
  264. FFeatures = NULL;
  265. delete FServerCapabilities;
  266. FServerCapabilities = NULL;
  267. ResetCaches();
  268. }
  269. //---------------------------------------------------------------------------
  270. void __fastcall TFTPFileSystem::Open()
  271. {
  272. // on reconnect, typically there may be pending status messages from previous session
  273. DiscardMessages();
  274. ResetCaches();
  275. FCurrentDirectory = L"";
  276. FHomeDirectory = L"";
  277. TSessionData * Data = FTerminal->SessionData;
  278. FSessionInfo.LoginTime = Now();
  279. switch (Data->Ftps)
  280. {
  281. case ftpsNone:
  282. // noop;
  283. break;
  284. case ftpsImplicit:
  285. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_IMPLICIT);
  286. break;
  287. case ftpsExplicitSsl:
  288. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT_SSL);
  289. break;
  290. case ftpsExplicitTls:
  291. FSessionInfo.SecurityProtocolName = LoadStr(FTPS_EXPLICIT_TLS);
  292. break;
  293. default:
  294. FAIL;
  295. break;
  296. }
  297. FLastDataSent = Now();
  298. FMultineResponse = false;
  299. // initialize FZAPI on the first connect only
  300. if (FFileZillaIntf == NULL)
  301. {
  302. FFileZillaIntf = new TFileZillaImpl(this);
  303. try
  304. {
  305. TFileZillaIntf::TLogLevel LogLevel;
  306. switch (FTerminal->Configuration->ActualLogProtocol)
  307. {
  308. default:
  309. case 0:
  310. case 1:
  311. LogLevel = TFileZillaIntf::LOG_WARNING;
  312. break;
  313. case 2:
  314. LogLevel = TFileZillaIntf::LOG_INFO;
  315. break;
  316. }
  317. FFileZillaIntf->SetDebugLevel(LogLevel);
  318. FFileZillaIntf->Init();
  319. }
  320. catch(...)
  321. {
  322. delete FFileZillaIntf;
  323. FFileZillaIntf = NULL;
  324. throw;
  325. }
  326. }
  327. UnicodeString HostName = Data->HostNameExpanded;
  328. UnicodeString UserName = Data->UserNameExpanded;
  329. UnicodeString Password = Data->Password;
  330. UnicodeString Account = Data->FtpAccount;
  331. UnicodeString Path = Data->RemoteDirectory;
  332. int ServerType;
  333. switch (Data->Ftps)
  334. {
  335. case ftpsImplicit:
  336. ServerType = TFileZillaIntf::SERVER_FTP_SSL_IMPLICIT;
  337. break;
  338. case ftpsExplicitSsl:
  339. ServerType = TFileZillaIntf::SERVER_FTP_SSL_EXPLICIT;
  340. break;
  341. case ftpsExplicitTls:
  342. ServerType = TFileZillaIntf::SERVER_FTP_TLS_EXPLICIT;
  343. break;
  344. default:
  345. assert(Data->Ftps == ftpsNone);
  346. ServerType = TFileZillaIntf::SERVER_FTP;
  347. break;
  348. }
  349. int Pasv = (Data->FtpPasvMode ? 1 : 2);
  350. int TimeZoneOffset = TimeToMinutes(Data->TimeDifference);
  351. int UTF8 = 0;
  352. switch (Data->NotUtf)
  353. {
  354. case asOn:
  355. UTF8 = 2;
  356. break;
  357. case asOff:
  358. UTF8 = 1;
  359. break;
  360. case asAuto:
  361. UTF8 = 0;
  362. break;
  363. }
  364. FPasswordFailed = false;
  365. bool PromptedForCredentials = false;
  366. do
  367. {
  368. FSystem = L"";
  369. FFeatures->Clear();
  370. FFileSystemInfoValid = false;
  371. // TODO: the same for account? it ever used?
  372. // ask for username if it was not specified in advance, even on retry,
  373. // but keep previous one as default,
  374. if (Data->UserNameExpanded.IsEmpty())
  375. {
  376. FTerminal->LogEvent(L"Username prompt (no username provided)");
  377. if (!FPasswordFailed && !PromptedForCredentials)
  378. {
  379. FTerminal->Information(LoadStr(FTP_CREDENTIAL_PROMPT), false);
  380. PromptedForCredentials = true;
  381. }
  382. if (!FTerminal->PromptUser(Data, pkUserName, LoadStr(USERNAME_TITLE), L"",
  383. LoadStr(USERNAME_PROMPT2), true, 0, UserName))
  384. {
  385. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  386. }
  387. else
  388. {
  389. FUserName = UserName;
  390. }
  391. }
  392. // on retry ask for password
  393. if (FPasswordFailed)
  394. {
  395. FTerminal->LogEvent(L"Password prompt (last login attempt failed)");
  396. // on retry ask for new password
  397. Password = L"";
  398. if (!FTerminal->PromptUser(Data, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  399. LoadStr(PASSWORD_PROMPT), false, 0, Password))
  400. {
  401. FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
  402. }
  403. }
  404. FPasswordFailed = false;
  405. TValueRestorer<bool> OpeningRestorer(FOpening);
  406. FOpening = true;
  407. FActive = FFileZillaIntf->Connect(
  408. HostName.c_str(), Data->PortNumber, UserName.c_str(),
  409. Password.c_str(), Account.c_str(), false, Path.c_str(),
  410. ServerType, Pasv, TimeZoneOffset, UTF8, Data->FtpForcePasvIp,
  411. Data->FtpUseMlsd);
  412. assert(FActive);
  413. try
  414. {
  415. // do not wait for FTP response code as Connect is complex operation
  416. GotReply(WaitForCommandReply(false), REPLY_CONNECT, LoadStr(CONNECTION_FAILED));
  417. Shred(Password);
  418. // we have passed, even if we got 530 on the way (if it is possible at all),
  419. // ignore it
  420. assert(!FPasswordFailed);
  421. FPasswordFailed = false;
  422. }
  423. catch(...)
  424. {
  425. if (FPasswordFailed)
  426. {
  427. FTerminal->Information(
  428. LoadStr(Password.IsEmpty() ? FTP_ACCESS_DENIED_EMPTY_PASSWORD : FTP_ACCESS_DENIED),
  429. false);
  430. }
  431. else
  432. {
  433. // see handling of REPLY_CONNECT in GotReply
  434. FTerminal->Closed();
  435. throw;
  436. }
  437. }
  438. }
  439. while (FPasswordFailed);
  440. // see also TWebDAVFileSystem::CollectTLSSessionInfo()
  441. FSessionInfo.CSCipher = FFileZillaIntf->GetCipherName().c_str();
  442. FSessionInfo.SCCipher = FSessionInfo.CSCipher;
  443. UnicodeString TlsVersionStr = FFileZillaIntf->GetTlsVersionStr().c_str();
  444. AddToList(FSessionInfo.SecurityProtocolName, TlsVersionStr, L", ");
  445. }
  446. //---------------------------------------------------------------------------
  447. void __fastcall TFTPFileSystem::Close()
  448. {
  449. assert(FActive);
  450. bool Result;
  451. if (FFileZillaIntf->Close(FOpening))
  452. {
  453. CHECK(FLAGSET(WaitForCommandReply(false), TFileZillaIntf::REPLY_DISCONNECTED));
  454. Result = true;
  455. }
  456. else
  457. {
  458. // See TFileZillaIntf::Close
  459. Result = FOpening;
  460. }
  461. if (ALWAYS_TRUE(Result))
  462. {
  463. assert(FActive);
  464. Discard();
  465. FTerminal->Closed();
  466. }
  467. }
  468. //---------------------------------------------------------------------------
  469. bool __fastcall TFTPFileSystem::GetActive()
  470. {
  471. return FActive;
  472. }
  473. //---------------------------------------------------------------------------
  474. void __fastcall TFTPFileSystem::CollectUsage()
  475. {
  476. if (FFileZillaIntf->UsingMlsd())
  477. {
  478. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPMLSD");
  479. }
  480. else
  481. {
  482. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPLIST");
  483. }
  484. if (FFileZillaIntf->UsingUtf8())
  485. {
  486. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPUTF8");
  487. }
  488. else
  489. {
  490. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPNonUTF8");
  491. }
  492. if (!CurrentDirectory.IsEmpty() && (CurrentDirectory[1] != L'/'))
  493. {
  494. if (IsUnixStyleWindowsPath(CurrentDirectory))
  495. {
  496. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPWindowsPath");
  497. }
  498. else if ((CurrentDirectory.Length() >= 3) && IsLetter(CurrentDirectory[1]) && (CurrentDirectory[2] == L':') && (CurrentDirectory[3] == L'/'))
  499. {
  500. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPRealWindowsPath");
  501. }
  502. else
  503. {
  504. FTerminal->Configuration->Usage->Inc(L"OpenedSessionsFTPOtherPath");
  505. }
  506. }
  507. }
  508. //---------------------------------------------------------------------------
  509. void __fastcall TFTPFileSystem::Idle()
  510. {
  511. if (FActive && !FWaitingForReply)
  512. {
  513. PoolForFatalNonCommandReply();
  514. // Keep session alive
  515. if ((FTerminal->SessionData->FtpPingType != ptOff) &&
  516. (double(Now() - FLastDataSent) > double(FTerminal->SessionData->FtpPingIntervalDT) * 4))
  517. {
  518. FLastDataSent = Now();
  519. TRemoteDirectory * Files = new TRemoteDirectory(FTerminal);
  520. try
  521. {
  522. try
  523. {
  524. Files->Directory = CurrentDirectory;
  525. DoReadDirectory(Files);
  526. }
  527. catch(...)
  528. {
  529. // ignore non-fatal errors
  530. // (i.e. current directory may not exist anymore)
  531. if (!FTerminal->Active)
  532. {
  533. throw;
  534. }
  535. }
  536. }
  537. __finally
  538. {
  539. delete Files;
  540. }
  541. }
  542. }
  543. }
  544. //---------------------------------------------------------------------------
  545. void __fastcall TFTPFileSystem::Discard()
  546. {
  547. // remove all pending messages, to get complete log
  548. // note that we need to retry discard on reconnect, as there still may be another
  549. // "disconnect/timeout/..." status messages coming
  550. DiscardMessages();
  551. assert(FActive);
  552. FActive = false;
  553. }
  554. //---------------------------------------------------------------------------
  555. UnicodeString __fastcall TFTPFileSystem::AbsolutePath(UnicodeString Path, bool /*Local*/)
  556. {
  557. // TODO: improve (handle .. etc.)
  558. if (UnixIsAbsolutePath(Path))
  559. {
  560. return Path;
  561. }
  562. else
  563. {
  564. return ::AbsolutePath(FCurrentDirectory, Path);
  565. }
  566. }
  567. //---------------------------------------------------------------------------
  568. UnicodeString __fastcall TFTPFileSystem::ActualCurrentDirectory()
  569. {
  570. wchar_t CurrentPath[1024];
  571. FFileZillaIntf->GetCurrentPath(CurrentPath, LENOF(CurrentPath));
  572. return UnixExcludeTrailingBackslash(CurrentPath);
  573. }
  574. //---------------------------------------------------------------------------
  575. void __fastcall TFTPFileSystem::EnsureLocation()
  576. {
  577. // if we do not know what's the current directory, do nothing
  578. if (!FCurrentDirectory.IsEmpty())
  579. {
  580. // Make sure that the FZAPI current working directory,
  581. // is actually our working directory.
  582. // It may not be because:
  583. // 1) We did cached directory change
  584. // 2) Listing was requested for non-current directory, which
  585. // makes FZAPI change its current directory (and not restoring it back afterwards)
  586. if (!UnixSamePath(ActualCurrentDirectory(), FCurrentDirectory))
  587. {
  588. FTerminal->LogEvent(FORMAT(L"Synchronizing current directory \"%s\".",
  589. (FCurrentDirectory)));
  590. DoChangeDirectory(FCurrentDirectory);
  591. // make sure FZAPI is aware that we changed current working directory
  592. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  593. }
  594. }
  595. }
  596. //---------------------------------------------------------------------------
  597. void __fastcall TFTPFileSystem::AnyCommand(const UnicodeString Command,
  598. TCaptureOutputEvent OutputEvent)
  599. {
  600. // end-user has right to expect that client current directory is really
  601. // current directory for the server
  602. EnsureLocation();
  603. assert(FOnCaptureOutput == NULL);
  604. FOnCaptureOutput = OutputEvent;
  605. try
  606. {
  607. FFileZillaIntf->CustomCommand(Command.c_str());
  608. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_3XX_CODE);
  609. }
  610. __finally
  611. {
  612. FOnCaptureOutput = NULL;
  613. }
  614. }
  615. //---------------------------------------------------------------------------
  616. void __fastcall TFTPFileSystem::ResetCaches()
  617. {
  618. delete FFileListCache;
  619. FFileListCache = NULL;
  620. }
  621. //---------------------------------------------------------------------------
  622. void __fastcall TFTPFileSystem::AnnounceFileListOperation()
  623. {
  624. ResetCaches();
  625. }
  626. //---------------------------------------------------------------------------
  627. void __fastcall TFTPFileSystem::DoChangeDirectory(const UnicodeString & Directory)
  628. {
  629. UnicodeString Command = FORMAT(L"CWD %s", (Directory));
  630. FFileZillaIntf->CustomCommand(Command.c_str());
  631. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  632. }
  633. //---------------------------------------------------------------------------
  634. void __fastcall TFTPFileSystem::ChangeDirectory(const UnicodeString ADirectory)
  635. {
  636. UnicodeString Directory = ADirectory;
  637. try
  638. {
  639. // For changing directory, we do not make paths absolute, instead we
  640. // delegate this to the server, hence we synchronize current working
  641. // directory with the server and only then we ask for the change with
  642. // relative path.
  643. // But if synchronization fails, typically because current working directory
  644. // no longer exists, we fall back to out own resolution, to give
  645. // user chance to leave the non-existing directory.
  646. EnsureLocation();
  647. }
  648. catch(...)
  649. {
  650. if (FTerminal->Active)
  651. {
  652. Directory = AbsolutePath(Directory, false);
  653. }
  654. else
  655. {
  656. throw;
  657. }
  658. }
  659. DoChangeDirectory(Directory);
  660. // make next ReadCurrentDirectory retrieve actual server-side current directory
  661. FCurrentDirectory = L"";
  662. }
  663. //---------------------------------------------------------------------------
  664. void __fastcall TFTPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  665. {
  666. FCurrentDirectory = UnixExcludeTrailingBackslash(Directory);
  667. }
  668. //---------------------------------------------------------------------------
  669. void __fastcall TFTPFileSystem::ChangeFileProperties(const UnicodeString AFileName,
  670. const TRemoteFile * File, const TRemoteProperties * Properties,
  671. TChmodSessionAction & Action)
  672. {
  673. assert(Properties);
  674. assert(!Properties->Valid.Contains(vpGroup));
  675. assert(!Properties->Valid.Contains(vpOwner));
  676. assert(!Properties->Valid.Contains(vpLastAccess));
  677. assert(!Properties->Valid.Contains(vpModification));
  678. if (Properties->Valid.Contains(vpRights))
  679. {
  680. TRemoteFile * OwnedFile = NULL;
  681. try
  682. {
  683. UnicodeString FileName = AbsolutePath(AFileName, false);
  684. if (File == NULL)
  685. {
  686. ReadFile(FileName, OwnedFile);
  687. File = OwnedFile;
  688. }
  689. if ((File != NULL) && File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  690. {
  691. try
  692. {
  693. FTerminal->ProcessDirectory(AFileName, FTerminal->ChangeFileProperties,
  694. (void*)Properties);
  695. }
  696. catch(...)
  697. {
  698. Action.Cancel();
  699. throw;
  700. }
  701. }
  702. TRights Rights;
  703. if (File != NULL)
  704. {
  705. Rights = *File->Rights;
  706. }
  707. Rights |= Properties->Rights.NumberSet;
  708. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  709. if ((File != NULL) && File->IsDirectory && Properties->AddXToDirectories)
  710. {
  711. Rights.AddExecute();
  712. }
  713. Action.Rights(Rights);
  714. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  715. UnicodeString FilePath = UnixExtractFilePath(FileName);
  716. // FZAPI wants octal number represented as decadic
  717. FFileZillaIntf->Chmod(Rights.NumberDecadic, FileNameOnly.c_str(), FilePath.c_str());
  718. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  719. }
  720. __finally
  721. {
  722. delete OwnedFile;
  723. }
  724. }
  725. else
  726. {
  727. Action.Cancel();
  728. }
  729. }
  730. //---------------------------------------------------------------------------
  731. bool __fastcall TFTPFileSystem::LoadFilesProperties(TStrings * /*FileList*/)
  732. {
  733. FAIL;
  734. return false;
  735. }
  736. //---------------------------------------------------------------------------
  737. void __fastcall TFTPFileSystem::CalculateFilesChecksum(const UnicodeString & /*Alg*/,
  738. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  739. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  740. {
  741. FAIL;
  742. }
  743. //---------------------------------------------------------------------------
  744. bool __fastcall TFTPFileSystem::ConfirmOverwrite(
  745. const UnicodeString & FullFileName, UnicodeString & FileName,
  746. TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
  747. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  748. int Params, bool AutoResume)
  749. {
  750. bool Result;
  751. bool CanAutoResume = FLAGSET(Params, cpNoConfirmation) && AutoResume;
  752. bool DestIsSmaller = (FileParams != NULL) && (FileParams->DestSize < FileParams->SourceSize);
  753. bool DestIsSame = (FileParams != NULL) && (FileParams->DestSize == FileParams->SourceSize);
  754. bool CanResume =
  755. !OperationProgress->AsciiTransfer &&
  756. // when resuming transfer after interrupted connection,
  757. // do nothing (dummy resume) when the files has the same size.
  758. // this is workaround for servers that strangely fails just after successful
  759. // upload.
  760. (DestIsSmaller || (DestIsSame && CanAutoResume));
  761. unsigned int Answer;
  762. if (CanAutoResume && CanResume)
  763. {
  764. if (DestIsSame)
  765. {
  766. assert(CanAutoResume);
  767. Answer = qaSkip;
  768. }
  769. else
  770. {
  771. Answer = qaRetry;
  772. }
  773. }
  774. else
  775. {
  776. // retry = "resume"
  777. // all = "yes to newer"
  778. // ignore = "rename"
  779. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  780. if (CanResume)
  781. {
  782. Answers |= qaRetry;
  783. }
  784. TQueryButtonAlias Aliases[5];
  785. Aliases[0].Button = qaRetry;
  786. Aliases[0].Alias = LoadStr(RESUME_BUTTON);
  787. Aliases[0].GroupWith = qaNo;
  788. Aliases[0].GrouppedShiftState = TShiftState() << ssAlt;
  789. Aliases[1].Button = qaAll;
  790. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  791. Aliases[1].GroupWith = qaYes;
  792. Aliases[1].GrouppedShiftState = TShiftState() << ssCtrl;
  793. Aliases[2].Button = qaIgnore;
  794. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  795. Aliases[2].GroupWith = qaNo;
  796. Aliases[2].GrouppedShiftState = TShiftState() << ssCtrl;
  797. Aliases[3].Button = qaYesToAll;
  798. Aliases[3].GroupWith = qaYes;
  799. Aliases[3].GrouppedShiftState = TShiftState() << ssShift;
  800. Aliases[4].Button = qaNoToAll;
  801. Aliases[4].GroupWith = qaNo;
  802. Aliases[4].GrouppedShiftState = TShiftState() << ssShift;
  803. TQueryParams QueryParams(qpNeverAskAgainCheck);
  804. QueryParams.Aliases = Aliases;
  805. QueryParams.AliasesCount = LENOF(Aliases);
  806. {
  807. TSuspendFileOperationProgress Suspend(OperationProgress);
  808. Answer = FTerminal->ConfirmFileOverwrite(FullFileName, FileParams,
  809. Answers, &QueryParams,
  810. OperationProgress->Side == osLocal ? osRemote : osLocal,
  811. CopyParam, Params, OperationProgress);
  812. }
  813. }
  814. Result = true;
  815. switch (Answer)
  816. {
  817. // resume
  818. case qaRetry:
  819. OverwriteMode = omResume;
  820. assert(FileParams != NULL);
  821. assert(CanResume);
  822. FFileTransferResumed = FileParams->DestSize;
  823. break;
  824. // rename
  825. case qaIgnore:
  826. if (FTerminal->PromptUser(FTerminal->SessionData, pkFileName,
  827. LoadStr(RENAME_TITLE), L"", LoadStr(RENAME_PROMPT2), true, 0, FileName))
  828. {
  829. OverwriteMode = omOverwrite;
  830. }
  831. else
  832. {
  833. if (!OperationProgress->Cancel)
  834. {
  835. OperationProgress->Cancel = csCancel;
  836. }
  837. FFileTransferAbort = ftaCancel;
  838. Result = false;
  839. }
  840. break;
  841. case qaYes:
  842. OverwriteMode = omOverwrite;
  843. break;
  844. case qaCancel:
  845. if (!OperationProgress->Cancel)
  846. {
  847. OperationProgress->Cancel = csCancel;
  848. }
  849. FFileTransferAbort = ftaCancel;
  850. Result = false;
  851. break;
  852. case qaNo:
  853. FFileTransferAbort = ftaSkip;
  854. Result = false;
  855. break;
  856. case qaSkip:
  857. OverwriteMode = omComplete;
  858. break;
  859. default:
  860. FAIL;
  861. Result = false;
  862. break;
  863. }
  864. return Result;
  865. }
  866. //---------------------------------------------------------------------------
  867. void __fastcall TFTPFileSystem::ResetFileTransfer()
  868. {
  869. FFileTransferAbort = ftaNone;
  870. FFileTransferCancelled = false;
  871. FFileTransferResumed = 0;
  872. }
  873. //---------------------------------------------------------------------------
  874. void __fastcall TFTPFileSystem::ReadDirectoryProgress(__int64 Bytes)
  875. {
  876. // with FTP we do not know exactly how many entries we have received,
  877. // instead we know number of bytes received only.
  878. // so we report approximation based on average size of entry.
  879. int Progress = int(Bytes / 80);
  880. if (Progress - FLastReadDirectoryProgress >= 10)
  881. {
  882. bool Cancel = false;
  883. FLastReadDirectoryProgress = Progress;
  884. FTerminal->DoReadDirectoryProgress(Progress, 0, Cancel);
  885. if (Cancel)
  886. {
  887. FTerminal->DoReadDirectoryProgress(-2, 0, Cancel);
  888. FFileZillaIntf->Cancel();
  889. }
  890. }
  891. }
  892. //---------------------------------------------------------------------------
  893. void __fastcall TFTPFileSystem::DoFileTransferProgress(__int64 TransferSize,
  894. __int64 Bytes)
  895. {
  896. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  897. OperationProgress->SetTransferSize(TransferSize);
  898. if (FFileTransferResumed > 0)
  899. {
  900. OperationProgress->AddResumed(FFileTransferResumed);
  901. FFileTransferResumed = 0;
  902. }
  903. __int64 Diff = Bytes - OperationProgress->TransferedSize;
  904. if (ALWAYS_TRUE(Diff >= 0))
  905. {
  906. OperationProgress->AddTransfered(Diff);
  907. }
  908. if (OperationProgress->Cancel == csCancel)
  909. {
  910. FFileTransferCancelled = true;
  911. FFileTransferAbort = ftaCancel;
  912. FFileZillaIntf->Cancel();
  913. }
  914. if (FFileTransferCPSLimit != OperationProgress->CPSLimit)
  915. {
  916. SetCPSLimit(OperationProgress);
  917. }
  918. }
  919. //---------------------------------------------------------------------------
  920. void __fastcall TFTPFileSystem::SetCPSLimit(TFileOperationProgressType * OperationProgress)
  921. {
  922. // Any reason we use separate field intead of directly using OperationProgress->CPSLimit?
  923. // Maybe thread-safety?
  924. FFileTransferCPSLimit = OperationProgress->CPSLimit;
  925. OperationProgress->SetSpeedCounters();
  926. }
  927. //---------------------------------------------------------------------------
  928. void __fastcall TFTPFileSystem::FileTransferProgress(__int64 TransferSize,
  929. __int64 Bytes)
  930. {
  931. TGuard Guard(FTransferStatusCriticalSection);
  932. DoFileTransferProgress(TransferSize, Bytes);
  933. }
  934. //---------------------------------------------------------------------------
  935. void __fastcall TFTPFileSystem::FileTransfer(const UnicodeString & FileName,
  936. const UnicodeString & LocalFile, const UnicodeString & RemoteFile,
  937. const UnicodeString & RemotePath, bool Get, __int64 Size, int Type,
  938. TFileTransferData & UserData, TFileOperationProgressType * OperationProgress)
  939. {
  940. FILE_OPERATION_LOOP_BEGIN
  941. {
  942. FFileZillaIntf->FileTransfer(LocalFile.c_str(), RemoteFile.c_str(),
  943. RemotePath.c_str(), Get, Size, Type, &UserData);
  944. // we may actually catch response code of the listing
  945. // command (when checking for existence of the remote file)
  946. unsigned int Reply = WaitForCommandReply();
  947. GotReply(Reply, FLAGMASK(FFileTransferCancelled, REPLY_ALLOW_CANCEL));
  948. }
  949. FILE_OPERATION_LOOP_END(FMTLOAD(TRANSFER_ERROR, (FileName)));
  950. switch (FFileTransferAbort)
  951. {
  952. case ftaSkip:
  953. THROW_SKIP_FILE_NULL;
  954. case ftaCancel:
  955. Abort();
  956. break;
  957. }
  958. if (!FFileTransferCancelled)
  959. {
  960. // show completion of transfer
  961. // call non-guarded variant to avoid deadlock with keepalives
  962. // (we are not waiting for reply anymore so keepalives are free to proceed)
  963. DoFileTransferProgress(OperationProgress->TransferSize, OperationProgress->TransferSize);
  964. }
  965. }
  966. //---------------------------------------------------------------------------
  967. void __fastcall TFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  968. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  969. int Params, TFileOperationProgressType * OperationProgress,
  970. TOnceDoneOperation & OnceDoneOperation)
  971. {
  972. Params &= ~cpAppend;
  973. UnicodeString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  974. int Index = 0;
  975. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  976. {
  977. UnicodeString FileName = FilesToCopy->Strings[Index];
  978. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  979. bool Success = false;
  980. try
  981. {
  982. try
  983. {
  984. SinkRobust(AbsolutePath(FileName, false), File, FullTargetDir, CopyParam, Params,
  985. OperationProgress, tfFirstLevel);
  986. Success = true;
  987. FLastDataSent = Now();
  988. }
  989. catch(EScpSkipFile & E)
  990. {
  991. TSuspendFileOperationProgress Suspend(OperationProgress);
  992. if (!FTerminal->HandleException(&E))
  993. {
  994. throw;
  995. }
  996. }
  997. }
  998. __finally
  999. {
  1000. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1001. }
  1002. Index++;
  1003. }
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. void __fastcall TFTPFileSystem::SinkRobust(const UnicodeString FileName,
  1007. const TRemoteFile * File, const UnicodeString TargetDir,
  1008. const TCopyParamType * CopyParam, int Params,
  1009. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1010. {
  1011. // the same in TSFTPFileSystem
  1012. bool Retry;
  1013. TDownloadSessionAction Action(FTerminal->ActionLog);
  1014. do
  1015. {
  1016. Retry = false;
  1017. try
  1018. {
  1019. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  1020. Flags, Action);
  1021. }
  1022. catch(Exception & E)
  1023. {
  1024. Retry = true;
  1025. if (FTerminal->Active ||
  1026. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  1027. {
  1028. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1029. throw;
  1030. }
  1031. }
  1032. if (Retry)
  1033. {
  1034. OperationProgress->RollbackTransfer();
  1035. Action.Restart();
  1036. assert(File != NULL);
  1037. if (!File->IsDirectory)
  1038. {
  1039. // prevent overwrite confirmations
  1040. Params |= cpNoConfirmation;
  1041. Flags |= tfAutoResume;
  1042. }
  1043. }
  1044. }
  1045. while (Retry);
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. void __fastcall TFTPFileSystem::Sink(const UnicodeString FileName,
  1049. const TRemoteFile * File, const UnicodeString TargetDir,
  1050. const TCopyParamType * CopyParam, int Params,
  1051. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1052. TDownloadSessionAction & Action)
  1053. {
  1054. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  1055. Action.FileName(FileName);
  1056. TFileMasks::TParams MaskParams;
  1057. assert(File);
  1058. MaskParams.Size = File->Size;
  1059. MaskParams.Modification = File->Modification;
  1060. if (!CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  1061. {
  1062. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  1063. THROW_SKIP_FILE_NULL;
  1064. }
  1065. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  1066. {
  1067. OperationProgress->AddSkippedFileSize(File->Size);
  1068. THROW_SKIP_FILE_NULL;
  1069. }
  1070. FTerminal->LogFileDetails(FileName, File->Modification, File->Size);
  1071. OperationProgress->SetFile(FileName);
  1072. UnicodeString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  1073. osRemote, FLAGSET(Flags, tfFirstLevel));
  1074. UnicodeString DestFullName = TargetDir + DestFileName;
  1075. if (File->IsDirectory)
  1076. {
  1077. Action.Cancel();
  1078. if (!File->IsSymLink)
  1079. {
  1080. FILE_OPERATION_LOOP_BEGIN
  1081. {
  1082. int Attrs = FileGetAttr(ApiPath(DestFullName));
  1083. if (FLAGCLEAR(Attrs, faDirectory))
  1084. {
  1085. EXCEPTION;
  1086. }
  1087. }
  1088. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  1089. FILE_OPERATION_LOOP_BEGIN
  1090. {
  1091. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  1092. }
  1093. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  1094. TSinkFileParams SinkFileParams;
  1095. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  1096. SinkFileParams.CopyParam = CopyParam;
  1097. SinkFileParams.Params = Params;
  1098. SinkFileParams.OperationProgress = OperationProgress;
  1099. SinkFileParams.Skipped = false;
  1100. SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
  1101. FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  1102. // Do not delete directory if some of its files were skip.
  1103. // Throw "skip file" for the directory to avoid attempt to deletion
  1104. // of any parent directory
  1105. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  1106. {
  1107. THROW_SKIP_FILE_NULL;
  1108. }
  1109. }
  1110. else
  1111. {
  1112. // file is symlink to directory, currently do nothing, but it should be
  1113. // reported to user
  1114. }
  1115. }
  1116. else
  1117. {
  1118. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  1119. // Will we use ASCII of BINARY file transfer?
  1120. OperationProgress->SetAsciiTransfer(
  1121. CopyParam->UseAsciiTransfer(FileName, osRemote, MaskParams));
  1122. FTerminal->LogEvent(UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
  1123. L" transfer mode selected.");
  1124. // Suppose same data size to transfer as to write
  1125. OperationProgress->SetTransferSize(File->Size);
  1126. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1127. int Attrs;
  1128. FILE_OPERATION_LOOP_BEGIN
  1129. {
  1130. Attrs = FileGetAttr(ApiPath(DestFullName));
  1131. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
  1132. {
  1133. EXCEPTION;
  1134. }
  1135. }
  1136. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  1137. OperationProgress->TransferingFile = false; // not set with FTP protocol
  1138. ResetFileTransfer();
  1139. TFileTransferData UserData;
  1140. UnicodeString FilePath = UnixExtractFilePath(FileName);
  1141. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1142. {
  1143. // ignore file list
  1144. TFileListHelper Helper(this, NULL, true);
  1145. SetCPSLimit(OperationProgress);
  1146. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1147. // not used for downloads anyway
  1148. FFileTransferRemoveBOM = CopyParam->RemoveBOM;
  1149. UserData.FileName = DestFileName;
  1150. UserData.Params = Params;
  1151. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1152. UserData.CopyParam = CopyParam;
  1153. UserData.Modification = File->Modification;
  1154. FileTransfer(FileName, DestFullName, OnlyFileName,
  1155. FilePath, true, File->Size, TransferType, UserData, OperationProgress);
  1156. }
  1157. // in case dest filename is changed from overwrite dialog
  1158. if (DestFileName != UserData.FileName)
  1159. {
  1160. DestFullName = TargetDir + UserData.FileName;
  1161. Attrs = FileGetAttr(ApiPath(DestFullName));
  1162. }
  1163. Action.Destination(ExpandUNCFileName(DestFullName));
  1164. if (Attrs == -1)
  1165. {
  1166. Attrs = faArchive;
  1167. }
  1168. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  1169. if ((NewAttrs & Attrs) != NewAttrs)
  1170. {
  1171. FILE_OPERATION_LOOP_BEGIN
  1172. {
  1173. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  1174. }
  1175. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  1176. }
  1177. }
  1178. if (FLAGSET(Params, cpDelete))
  1179. {
  1180. // If file is directory, do not delete it recursively, because it should be
  1181. // empty already. If not, it should not be deleted (some files were
  1182. // skipped or some new files were copied to it, while we were downloading)
  1183. int Params = dfNoRecursive;
  1184. FTerminal->DeleteFile(FileName, File, &Params);
  1185. }
  1186. }
  1187. //---------------------------------------------------------------------------
  1188. void __fastcall TFTPFileSystem::SinkFile(UnicodeString FileName,
  1189. const TRemoteFile * File, void * Param)
  1190. {
  1191. TSinkFileParams * Params = (TSinkFileParams *)Param;
  1192. assert(Params->OperationProgress);
  1193. try
  1194. {
  1195. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  1196. Params->Params, Params->OperationProgress, Params->Flags);
  1197. }
  1198. catch(EScpSkipFile & E)
  1199. {
  1200. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  1201. Params->Skipped = true;
  1202. {
  1203. TSuspendFileOperationProgress Suspend(OperationProgress);
  1204. if (!FTerminal->HandleException(&E))
  1205. {
  1206. throw;
  1207. }
  1208. }
  1209. if (OperationProgress->Cancel)
  1210. {
  1211. Abort();
  1212. }
  1213. }
  1214. }
  1215. //---------------------------------------------------------------------------
  1216. void __fastcall TFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1217. const UnicodeString ATargetDir, const TCopyParamType * CopyParam,
  1218. int Params, TFileOperationProgressType * OperationProgress,
  1219. TOnceDoneOperation & OnceDoneOperation)
  1220. {
  1221. assert((FilesToCopy != NULL) && (OperationProgress != NULL));
  1222. Params &= ~cpAppend;
  1223. UnicodeString FileName, FileNameOnly;
  1224. UnicodeString TargetDir = AbsolutePath(ATargetDir, false);
  1225. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  1226. int Index = 0;
  1227. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  1228. {
  1229. bool Success = false;
  1230. FileName = FilesToCopy->Strings[Index];
  1231. FileNameOnly = ExtractFileName(FileName);
  1232. try
  1233. {
  1234. try
  1235. {
  1236. if (FTerminal->SessionData->CacheDirectories)
  1237. {
  1238. FTerminal->DirectoryModified(TargetDir, false);
  1239. if (DirectoryExists(ApiPath(FileName)))
  1240. {
  1241. FTerminal->DirectoryModified(FullTargetDir + FileNameOnly, true);
  1242. }
  1243. }
  1244. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  1245. tfFirstLevel);
  1246. Success = true;
  1247. FLastDataSent = Now();
  1248. }
  1249. catch(EScpSkipFile & E)
  1250. {
  1251. TSuspendFileOperationProgress Suspend(OperationProgress);
  1252. if (!FTerminal->HandleException(&E))
  1253. {
  1254. throw;
  1255. }
  1256. }
  1257. }
  1258. __finally
  1259. {
  1260. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1261. }
  1262. Index++;
  1263. }
  1264. }
  1265. //---------------------------------------------------------------------------
  1266. void __fastcall TFTPFileSystem::SourceRobust(const UnicodeString FileName,
  1267. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1268. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1269. {
  1270. // the same in TSFTPFileSystem
  1271. bool Retry;
  1272. TUploadSessionAction Action(FTerminal->ActionLog);
  1273. do
  1274. {
  1275. Retry = false;
  1276. try
  1277. {
  1278. Source(FileName, TargetDir, CopyParam, Params, OperationProgress,
  1279. Flags, Action);
  1280. }
  1281. catch(Exception & E)
  1282. {
  1283. Retry = true;
  1284. if (FTerminal->Active ||
  1285. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  1286. {
  1287. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1288. throw;
  1289. }
  1290. }
  1291. if (Retry)
  1292. {
  1293. OperationProgress->RollbackTransfer();
  1294. Action.Restart();
  1295. // prevent overwrite confirmations
  1296. // (should not be set for directories!)
  1297. Params |= cpNoConfirmation;
  1298. Flags |= tfAutoResume;
  1299. }
  1300. }
  1301. while (Retry);
  1302. }
  1303. //---------------------------------------------------------------------------
  1304. void __fastcall TFTPFileSystem::Source(const UnicodeString FileName,
  1305. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1306. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  1307. TUploadSessionAction & Action)
  1308. {
  1309. Action.FileName(ExpandUNCFileName(FileName));
  1310. OperationProgress->SetFile(FileName, false);
  1311. if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
  1312. {
  1313. THROW_SKIP_FILE_NULL;
  1314. }
  1315. __int64 Size;
  1316. int Attrs;
  1317. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &Attrs,
  1318. NULL, NULL, NULL, NULL, &Size);
  1319. OperationProgress->SetFileInProgress();
  1320. bool Dir = FLAGSET(Attrs, faDirectory);
  1321. if (Dir)
  1322. {
  1323. Action.Cancel();
  1324. DirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  1325. Attrs, CopyParam, Params, OperationProgress, Flags);
  1326. }
  1327. else
  1328. {
  1329. UnicodeString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  1330. osLocal, FLAGSET(Flags, tfFirstLevel));
  1331. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  1332. OperationProgress->SetLocalSize(Size);
  1333. // Suppose same data size to transfer as to read
  1334. // (not true with ASCII transfer)
  1335. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1336. OperationProgress->TransferingFile = false;
  1337. TDateTime Modification;
  1338. // Inspired by SysUtils::FileAge
  1339. WIN32_FIND_DATA FindData;
  1340. HANDLE Handle = FindFirstFile(FileName.c_str(), &FindData);
  1341. if (Handle != INVALID_HANDLE_VALUE)
  1342. {
  1343. Modification =
  1344. UnixToDateTime(
  1345. ConvertTimestampToUnixSafe(FindData.ftLastWriteTime, dstmUnix),
  1346. dstmUnix);
  1347. FindClose(Handle);
  1348. }
  1349. // Will we use ASCII of BINARY file transfer?
  1350. TFileMasks::TParams MaskParams;
  1351. MaskParams.Size = Size;
  1352. MaskParams.Modification = Modification;
  1353. OperationProgress->SetAsciiTransfer(
  1354. CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
  1355. FTerminal->LogEvent(
  1356. UnicodeString(OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary") +
  1357. L" transfer mode selected.");
  1358. ResetFileTransfer();
  1359. TFileTransferData UserData;
  1360. unsigned int TransferType = (OperationProgress->AsciiTransfer ? 1 : 2);
  1361. {
  1362. // ignore file list
  1363. TFileListHelper Helper(this, NULL, true);
  1364. SetCPSLimit(OperationProgress);
  1365. // not used for uploads anyway
  1366. FFileTransferPreserveTime = CopyParam->PreserveTime;
  1367. FFileTransferRemoveBOM = CopyParam->RemoveBOM;
  1368. // not used for uploads, but we get new name (if any) back in this field
  1369. UserData.FileName = DestFileName;
  1370. UserData.Params = Params;
  1371. UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
  1372. UserData.CopyParam = CopyParam;
  1373. UserData.Modification = Modification;
  1374. FileTransfer(FileName, FileName, DestFileName,
  1375. TargetDir, false, Size, TransferType, UserData, OperationProgress);
  1376. }
  1377. UnicodeString DestFullName = TargetDir + UserData.FileName;
  1378. // only now, we know the final destination
  1379. Action.Destination(DestFullName);
  1380. // we are not able to tell if setting timestamp succeeded,
  1381. // so we log it always (if supported)
  1382. if (FFileTransferPreserveTime &&
  1383. (FServerCapabilities->GetCapability(mfmt_command) == yes))
  1384. {
  1385. TTouchSessionAction TouchAction(FTerminal->ActionLog, DestFullName, Modification);
  1386. }
  1387. }
  1388. /* TODO : Delete also read-only files. */
  1389. if (FLAGSET(Params, cpDelete))
  1390. {
  1391. if (!Dir)
  1392. {
  1393. FILE_OPERATION_LOOP_BEGIN
  1394. {
  1395. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(FileName)));
  1396. }
  1397. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  1398. }
  1399. }
  1400. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1401. {
  1402. FILE_OPERATION_LOOP_BEGIN
  1403. {
  1404. THROWOSIFFALSE(FileSetAttr(ApiPath(FileName), Attrs & ~faArchive) == 0);
  1405. }
  1406. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  1407. }
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. void __fastcall TFTPFileSystem::DirectorySource(const UnicodeString DirectoryName,
  1411. const UnicodeString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  1412. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  1413. {
  1414. UnicodeString DestDirectoryName = CopyParam->ChangeFileName(
  1415. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  1416. FLAGSET(Flags, tfFirstLevel));
  1417. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  1418. OperationProgress->SetFile(DirectoryName);
  1419. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1420. TSearchRecChecked SearchRec;
  1421. bool FindOK;
  1422. FILE_OPERATION_LOOP_BEGIN
  1423. {
  1424. FindOK =
  1425. (FindFirstChecked(DirectoryName + L"*.*", FindAttrs, SearchRec) == 0);
  1426. }
  1427. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1428. bool CreateDir = true;
  1429. try
  1430. {
  1431. while (FindOK && !OperationProgress->Cancel)
  1432. {
  1433. UnicodeString FileName = DirectoryName + SearchRec.Name;
  1434. try
  1435. {
  1436. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1437. {
  1438. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  1439. Flags & ~(tfFirstLevel | tfAutoResume));
  1440. // if any file got uploaded (i.e. there were any file in the
  1441. // directory and at least one was not skipped),
  1442. // do not try to create the directory,
  1443. // as it should be already created by FZAPI during upload
  1444. CreateDir = false;
  1445. }
  1446. }
  1447. catch (EScpSkipFile &E)
  1448. {
  1449. // If ESkipFile occurs, just log it and continue with next file
  1450. TSuspendFileOperationProgress Suspend(OperationProgress);
  1451. // here a message to user was displayed, which was not appropriate
  1452. // when user refused to overwrite the file in subdirectory.
  1453. // hopefully it won't be missing in other situations.
  1454. if (!FTerminal->HandleException(&E))
  1455. {
  1456. throw;
  1457. }
  1458. }
  1459. FILE_OPERATION_LOOP_BEGIN
  1460. {
  1461. FindOK = (FindNextChecked(SearchRec) == 0);
  1462. }
  1463. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  1464. }
  1465. }
  1466. __finally
  1467. {
  1468. FindClose(SearchRec);
  1469. }
  1470. if (CreateDir)
  1471. {
  1472. TRemoteProperties Properties;
  1473. if (CopyParam->PreserveRights)
  1474. {
  1475. Properties.Valid = TValidProperties() << vpRights;
  1476. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  1477. }
  1478. try
  1479. {
  1480. FTerminal->ExceptionOnFail = true;
  1481. try
  1482. {
  1483. FTerminal->CreateDirectory(DestFullName, &Properties);
  1484. }
  1485. __finally
  1486. {
  1487. FTerminal->ExceptionOnFail = false;
  1488. }
  1489. }
  1490. catch(...)
  1491. {
  1492. TRemoteFile * File = NULL;
  1493. // ignore non-fatal error when the directory already exists
  1494. bool Rethrow =
  1495. !FTerminal->Active ||
  1496. !FTerminal->FileExists(UnixExcludeTrailingBackslash(DestFullName), &File) ||
  1497. !File->IsDirectory;
  1498. delete File;
  1499. if (Rethrow)
  1500. {
  1501. throw;
  1502. }
  1503. }
  1504. }
  1505. /* TODO : Delete also read-only directories. */
  1506. /* TODO : Show error message on failure. */
  1507. if (!OperationProgress->Cancel)
  1508. {
  1509. if (FLAGSET(Params, cpDelete))
  1510. {
  1511. RemoveDir(ApiPath(DirectoryName));
  1512. }
  1513. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1514. {
  1515. FILE_OPERATION_LOOP_BEGIN
  1516. {
  1517. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  1518. }
  1519. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  1520. }
  1521. }
  1522. }
  1523. //---------------------------------------------------------------------------
  1524. void __fastcall TFTPFileSystem::CreateDirectory(const UnicodeString ADirName)
  1525. {
  1526. UnicodeString DirName = AbsolutePath(ADirName, false);
  1527. {
  1528. // ignore file list
  1529. TFileListHelper Helper(this, NULL, true);
  1530. FFileZillaIntf->MakeDir(DirName.c_str());
  1531. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1532. }
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. void __fastcall TFTPFileSystem::CreateLink(const UnicodeString /*FileName*/,
  1536. const UnicodeString /*PointTo*/, bool /*Symbolic*/)
  1537. {
  1538. FAIL;
  1539. }
  1540. //---------------------------------------------------------------------------
  1541. void __fastcall TFTPFileSystem::DeleteFile(const UnicodeString AFileName,
  1542. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  1543. {
  1544. UnicodeString FileName = AbsolutePath(AFileName, false);
  1545. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1546. UnicodeString FilePath = UnixExtractFilePath(FileName);
  1547. bool Dir = (File != NULL) && File->IsDirectory && !File->IsSymLink;
  1548. if (Dir && FLAGCLEAR(Params, dfNoRecursive))
  1549. {
  1550. try
  1551. {
  1552. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Params);
  1553. }
  1554. catch(...)
  1555. {
  1556. Action.Cancel();
  1557. throw;
  1558. }
  1559. }
  1560. {
  1561. // ignore file list
  1562. TFileListHelper Helper(this, NULL, true);
  1563. if (Dir)
  1564. {
  1565. // If current remote directory is in the directory being removed,
  1566. // some servers may refuse to delete it
  1567. // This is common as ProcessDirectory above would CWD to
  1568. // the directory to LIST it.
  1569. // EnsureLocation should reset actual current directory to user's working directory.
  1570. // If user's working directory is still below deleted directory, it is
  1571. // perfectly correct to report an error.
  1572. if (UnixIsChildPath(ActualCurrentDirectory(), FileName))
  1573. {
  1574. EnsureLocation();
  1575. }
  1576. FFileZillaIntf->RemoveDir(FileNameOnly.c_str(), FilePath.c_str());
  1577. }
  1578. else
  1579. {
  1580. FFileZillaIntf->Delete(FileNameOnly.c_str(), FilePath.c_str());
  1581. }
  1582. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1583. }
  1584. }
  1585. //---------------------------------------------------------------------------
  1586. void __fastcall TFTPFileSystem::CustomCommandOnFile(const UnicodeString /*FileName*/,
  1587. const TRemoteFile * /*File*/, UnicodeString /*Command*/, int /*Params*/,
  1588. TCaptureOutputEvent /*OutputEvent*/)
  1589. {
  1590. // if ever implemented, do not forget to add EnsureLocation,
  1591. // see AnyCommand for a reason why
  1592. FAIL;
  1593. }
  1594. //---------------------------------------------------------------------------
  1595. void __fastcall TFTPFileSystem::DoStartup()
  1596. {
  1597. TStrings * PostLoginCommands = new TStringList();
  1598. try
  1599. {
  1600. PostLoginCommands->Text = FTerminal->SessionData->PostLoginCommands;
  1601. for (int Index = 0; Index < PostLoginCommands->Count; Index++)
  1602. {
  1603. UnicodeString Command = PostLoginCommands->Strings[Index];
  1604. if (!Command.IsEmpty())
  1605. {
  1606. FFileZillaIntf->CustomCommand(Command.c_str());
  1607. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_3XX_CODE);
  1608. }
  1609. }
  1610. }
  1611. __finally
  1612. {
  1613. delete PostLoginCommands;
  1614. }
  1615. // retrieve initialize working directory to save it as home directory
  1616. ReadCurrentDirectory();
  1617. FHomeDirectory = FCurrentDirectory;
  1618. }
  1619. //---------------------------------------------------------------------------
  1620. void __fastcall TFTPFileSystem::HomeDirectory()
  1621. {
  1622. // FHomeDirectory is an absolute path, so avoid unnecessary overhead
  1623. // of ChangeDirectory, such as EnsureLocation
  1624. DoChangeDirectory(FHomeDirectory);
  1625. FCurrentDirectory = FHomeDirectory;
  1626. // make sure FZAPI is aware that we changed current working directory
  1627. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1628. }
  1629. //---------------------------------------------------------------------------
  1630. bool __fastcall TFTPFileSystem::IsCapable(int Capability) const
  1631. {
  1632. assert(FTerminal);
  1633. switch (Capability)
  1634. {
  1635. case fcResolveSymlink: // sic
  1636. case fcTextMode:
  1637. case fcModeChanging: // but not fcModeChangingUpload
  1638. case fcNewerOnlyUpload:
  1639. case fcAnyCommand: // but not fcShellAnyCommand
  1640. case fcRename:
  1641. case fcRemoteMove:
  1642. case fcRemoveBOMUpload:
  1643. case fcMoveToQueue:
  1644. return true;
  1645. case fcPreservingTimestampUpload:
  1646. return (FServerCapabilities->GetCapability(mfmt_command) == yes);
  1647. case fcModeChangingUpload:
  1648. case fcLoadingAdditionalProperties:
  1649. case fcShellAnyCommand:
  1650. case fcCalculatingChecksum:
  1651. case fcHardLink:
  1652. case fcSymbolicLink:
  1653. case fcCheckingSpaceAvailable:
  1654. case fcUserGroupListing:
  1655. case fcGroupChanging:
  1656. case fcOwnerChanging:
  1657. case fcGroupOwnerChangingByID:
  1658. case fcSecondaryShell:
  1659. case fcRemoteCopy:
  1660. case fcNativeTextMode:
  1661. case fcTimestampChanging:
  1662. case fcIgnorePermErrors:
  1663. case fcRemoveCtrlZUpload:
  1664. return false;
  1665. default:
  1666. FAIL;
  1667. return false;
  1668. }
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. void __fastcall TFTPFileSystem::LookupUsersGroups()
  1672. {
  1673. FAIL;
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. void __fastcall TFTPFileSystem::ReadCurrentDirectory()
  1677. {
  1678. // ask the server for current directory on startup only
  1679. // and immediately after call to CWD,
  1680. // later our current directory may be not synchronized with FZAPI current
  1681. // directory anyway, see comments in EnsureLocation
  1682. if (FCurrentDirectory.IsEmpty())
  1683. {
  1684. FFileZillaIntf->CustomCommand(L"PWD");
  1685. unsigned int Code;
  1686. TStrings * Response = NULL;
  1687. GotReply(WaitForCommandReply(), REPLY_2XX_CODE, L"", &Code, &Response);
  1688. try
  1689. {
  1690. assert(Response != NULL);
  1691. bool Result = false;
  1692. // the only allowed 2XX code to "PWD"
  1693. if ((Code == 257) &&
  1694. (Response->Count == 1))
  1695. {
  1696. UnicodeString Path = Response->Text;
  1697. int P = Path.Pos(L"\"");
  1698. if (P == 0)
  1699. {
  1700. // some systems use single quotes, be tolerant
  1701. P = Path.Pos(L"'");
  1702. }
  1703. if (P != 0)
  1704. {
  1705. Path.Delete(1, P - 1);
  1706. if (Unquote(Path))
  1707. {
  1708. Result = true;
  1709. }
  1710. }
  1711. else
  1712. {
  1713. P = Path.Pos(L" ");
  1714. Path.Delete(P, Path.Length() - P + 1);
  1715. Result = true;
  1716. }
  1717. if (Result)
  1718. {
  1719. FCurrentDirectory = UnixExcludeTrailingBackslash(Path);
  1720. }
  1721. }
  1722. if (Result)
  1723. {
  1724. FFileZillaIntf->SetCurrentPath(FCurrentDirectory.c_str());
  1725. }
  1726. else
  1727. {
  1728. throw Exception(FMTLOAD(FTP_PWD_RESPONSE_ERROR, (Response->Text)));
  1729. }
  1730. }
  1731. __finally
  1732. {
  1733. delete Response;
  1734. }
  1735. }
  1736. }
  1737. //---------------------------------------------------------------------------
  1738. void __fastcall TFTPFileSystem::DoReadDirectory(TRemoteFileList * FileList)
  1739. {
  1740. FileList->Reset();
  1741. // FZAPI does not list parent directory, add it
  1742. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  1743. FLastReadDirectoryProgress = 0;
  1744. TFileListHelper Helper(this, FileList, false);
  1745. // always specify path to list, do not attempt to list "current" dir as:
  1746. // 1) List() lists again the last listed directory, not the current working directory
  1747. // 2) we handle this way the cached directory change
  1748. UnicodeString Directory = AbsolutePath(FileList->Directory, false);
  1749. FFileZillaIntf->List(Directory.c_str());
  1750. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  1751. FLastDataSent = Now();
  1752. }
  1753. //---------------------------------------------------------------------------
  1754. void __fastcall TFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  1755. {
  1756. // whole below "-a" logic is for LIST,
  1757. // if we know we are going to use MLSD, skip it
  1758. if (FFileZillaIntf->UsingMlsd())
  1759. {
  1760. DoReadDirectory(FileList);
  1761. }
  1762. else
  1763. {
  1764. bool GotNoFilesForAll = false;
  1765. bool Repeat;
  1766. do
  1767. {
  1768. Repeat = false;
  1769. try
  1770. {
  1771. FDoListAll = (FListAll == asAuto) || (FListAll == asOn);
  1772. DoReadDirectory(FileList);
  1773. // We got no files with "-a", but again no files w/o "-a",
  1774. // so it was not "-a"'s problem, revert to auto and let it decide the next time
  1775. if (GotNoFilesForAll && (FileList->Count == 0))
  1776. {
  1777. assert(FListAll == asOff);
  1778. FListAll = asAuto;
  1779. }
  1780. else if (FListAll == asAuto)
  1781. {
  1782. // some servers take "-a" as a mask and return empty directory listing
  1783. // (note that it's actually never empty here, there's always at least parent directory,
  1784. // added explicitly by DoReadDirectory)
  1785. if ((FileList->Count == 0) ||
  1786. ((FileList->Count == 1) && FileList->Files[0]->IsParentDirectory))
  1787. {
  1788. Repeat = true;
  1789. FListAll = asOff;
  1790. GotNoFilesForAll = true;
  1791. FTerminal->LogEvent(L"LIST with -a switch returned empty directory listing, will try pure LIST");
  1792. }
  1793. else
  1794. {
  1795. // reading first directory has succeeded, always use "-a"
  1796. FListAll = asOn;
  1797. }
  1798. }
  1799. // use "-a" even for implicit directory reading by FZAPI?
  1800. // (e.g. before file transfer)
  1801. FDoListAll = (FListAll == asOn);
  1802. }
  1803. catch(Exception & E)
  1804. {
  1805. FDoListAll = false;
  1806. // reading the first directory has failed,
  1807. // further try without "-a" only as the server may not support it
  1808. if (FListAll == asAuto)
  1809. {
  1810. FTerminal->LogEvent(L"LIST with -a failed, will try pure LIST");
  1811. if (!FTerminal->Active)
  1812. {
  1813. FTerminal->Reopen(ropNoReadDirectory);
  1814. }
  1815. FListAll = asOff;
  1816. Repeat = true;
  1817. }
  1818. else
  1819. {
  1820. throw;
  1821. }
  1822. }
  1823. }
  1824. while (Repeat);
  1825. }
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. void __fastcall TFTPFileSystem::DoReadFile(const UnicodeString & FileName,
  1829. TRemoteFile *& AFile)
  1830. {
  1831. // end-user has right to expect that client current directory is really
  1832. // current directory for the server
  1833. EnsureLocation();
  1834. TRemoteFileList * FileList = new TRemoteFileList();
  1835. try
  1836. {
  1837. TFileListHelper Helper(this, FileList, false);
  1838. FFileZillaIntf->ListFile(FileName.c_str());
  1839. GotReply(WaitForCommandReply(), REPLY_2XX_CODE | REPLY_ALLOW_CANCEL);
  1840. TRemoteFile * File = FileList->FindFile(UnixExtractFileName(FileName));
  1841. if (File != NULL)
  1842. {
  1843. AFile = File->Duplicate();
  1844. }
  1845. FLastDataSent = Now();
  1846. }
  1847. __finally
  1848. {
  1849. delete FileList;
  1850. }
  1851. }
  1852. //---------------------------------------------------------------------------
  1853. void __fastcall TFTPFileSystem::ReadFile(const UnicodeString FileName,
  1854. TRemoteFile *& File)
  1855. {
  1856. UnicodeString Path = UnixExtractFilePath(FileName);
  1857. UnicodeString NameOnly = UnixExtractFileName(FileName);
  1858. TRemoteFile *AFile = NULL;
  1859. bool Own;
  1860. if (FFileZillaIntf->UsingMlsd())
  1861. {
  1862. DoReadFile(FileName, AFile);
  1863. Own = true;
  1864. }
  1865. else
  1866. {
  1867. // FZAPI does not have efficient way to read properties of one file.
  1868. // In case we need properties of set of files from the same directory,
  1869. // cache the file list for future
  1870. if ((FFileListCache != NULL) &&
  1871. UnixSamePath(Path, FFileListCache->Directory) &&
  1872. (UnixIsAbsolutePath(FFileListCache->Directory) ||
  1873. (FFileListCachePath == CurrentDirectory)))
  1874. {
  1875. AFile = FFileListCache->FindFile(NameOnly);
  1876. }
  1877. // if cache is invalid or file is not in cache, (re)read the directory
  1878. if (AFile == NULL)
  1879. {
  1880. TRemoteFileList * FileListCache = new TRemoteFileList();
  1881. FileListCache->Directory = Path;
  1882. try
  1883. {
  1884. ReadDirectory(FileListCache);
  1885. }
  1886. catch(...)
  1887. {
  1888. delete FileListCache;
  1889. throw;
  1890. }
  1891. // set only after we successfully read the directory,
  1892. // otherwise, when we reconnect from ReadDirectory,
  1893. // the FFileListCache is reset from ResetCache.
  1894. delete FFileListCache;
  1895. FFileListCache = FileListCache;
  1896. FFileListCachePath = GetCurrentDirectory();
  1897. AFile = FFileListCache->FindFile(NameOnly);
  1898. }
  1899. Own = false;
  1900. }
  1901. if (AFile == NULL)
  1902. {
  1903. File = NULL;
  1904. throw Exception(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  1905. }
  1906. assert(AFile != NULL);
  1907. File = Own ? AFile : AFile->Duplicate();
  1908. }
  1909. //---------------------------------------------------------------------------
  1910. void __fastcall TFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  1911. TRemoteFile *& File)
  1912. {
  1913. // Resolving symlinks over FTP is big overhead
  1914. // (involves opening TCPIP connection for retrieving "directory listing").
  1915. // Moreover FZAPI does not support that anyway.
  1916. // Though nowadays we could use MLST to read the symlink.
  1917. File = new TRemoteFile(SymlinkFile);
  1918. try
  1919. {
  1920. File->Terminal = FTerminal;
  1921. File->FileName = UnixExtractFileName(SymlinkFile->LinkTo);
  1922. // FZAPI treats all symlink target as directories
  1923. File->Type = FILETYPE_DIRECTORY;
  1924. }
  1925. catch(...)
  1926. {
  1927. delete File;
  1928. File = NULL;
  1929. throw;
  1930. }
  1931. }
  1932. //---------------------------------------------------------------------------
  1933. void __fastcall TFTPFileSystem::RenameFile(const UnicodeString AFileName,
  1934. const UnicodeString ANewName)
  1935. {
  1936. UnicodeString FileName = AbsolutePath(AFileName, false);
  1937. UnicodeString NewName = AbsolutePath(ANewName, false);
  1938. UnicodeString FileNameOnly = UnixExtractFileName(FileName);
  1939. UnicodeString FilePathOnly = UnixExtractFilePath(FileName);
  1940. UnicodeString NewNameOnly = UnixExtractFileName(NewName);
  1941. UnicodeString NewPathOnly = UnixExtractFilePath(NewName);
  1942. {
  1943. // ignore file list
  1944. TFileListHelper Helper(this, NULL, true);
  1945. FFileZillaIntf->Rename(FileNameOnly.c_str(), NewNameOnly.c_str(),
  1946. FilePathOnly.c_str(), NewPathOnly.c_str());
  1947. GotReply(WaitForCommandReply(), REPLY_2XX_CODE);
  1948. }
  1949. }
  1950. //---------------------------------------------------------------------------
  1951. void __fastcall TFTPFileSystem::CopyFile(const UnicodeString FileName,
  1952. const UnicodeString NewName)
  1953. {
  1954. FAIL;
  1955. }
  1956. //---------------------------------------------------------------------------
  1957. TStrings * __fastcall TFTPFileSystem::GetFixedPaths()
  1958. {
  1959. return NULL;
  1960. }
  1961. //---------------------------------------------------------------------------
  1962. void __fastcall TFTPFileSystem::SpaceAvailable(const UnicodeString /*Path*/,
  1963. TSpaceAvailable & /*ASpaceAvailable*/)
  1964. {
  1965. FAIL;
  1966. }
  1967. //---------------------------------------------------------------------------
  1968. const TSessionInfo & __fastcall TFTPFileSystem::GetSessionInfo()
  1969. {
  1970. return FSessionInfo;
  1971. }
  1972. //---------------------------------------------------------------------------
  1973. const TFileSystemInfo & __fastcall TFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  1974. {
  1975. if (!FFileSystemInfoValid)
  1976. {
  1977. FFileSystemInfo.RemoteSystem = FSystem;
  1978. FFileSystemInfo.RemoteSystem.Unique();
  1979. if (FFeatures->Count == 0)
  1980. {
  1981. FFileSystemInfo.AdditionalInfo = LoadStr(FTP_NO_FEATURE_INFO);
  1982. }
  1983. else
  1984. {
  1985. FFileSystemInfo.AdditionalInfo =
  1986. FORMAT(L"%s\r\n", (LoadStr(FTP_FEATURE_INFO)));
  1987. for (int Index = 0; Index < FFeatures->Count; Index++)
  1988. {
  1989. FFileSystemInfo.AdditionalInfo += FORMAT(L" %s\r\n", (FFeatures->Strings[Index]));
  1990. }
  1991. }
  1992. FTerminal->SaveCapabilities(FFileSystemInfo);
  1993. FFileSystemInfoValid = true;
  1994. }
  1995. return FFileSystemInfo;
  1996. }
  1997. //---------------------------------------------------------------------------
  1998. bool __fastcall TFTPFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  1999. {
  2000. return false;
  2001. }
  2002. //---------------------------------------------------------------------------
  2003. bool __fastcall TFTPFileSystem::GetStoredCredentialsTried()
  2004. {
  2005. return !FTerminal->SessionData->Password.IsEmpty();
  2006. }
  2007. //---------------------------------------------------------------------------
  2008. UnicodeString __fastcall TFTPFileSystem::GetUserName()
  2009. {
  2010. return FUserName;
  2011. }
  2012. //---------------------------------------------------------------------------
  2013. UnicodeString __fastcall TFTPFileSystem::GetCurrentDirectory()
  2014. {
  2015. return FCurrentDirectory;
  2016. }
  2017. //---------------------------------------------------------------------------
  2018. const wchar_t * __fastcall TFTPFileSystem::GetOption(int OptionID) const
  2019. {
  2020. TSessionData * Data = FTerminal->SessionData;
  2021. switch (OptionID)
  2022. {
  2023. case OPTION_PROXYHOST:
  2024. case OPTION_FWHOST:
  2025. FOptionScratch = Data->ProxyHost;
  2026. break;
  2027. case OPTION_PROXYUSER:
  2028. case OPTION_FWUSER:
  2029. FOptionScratch = Data->ProxyUsername;
  2030. break;
  2031. case OPTION_PROXYPASS:
  2032. case OPTION_FWPASS:
  2033. FOptionScratch = Data->ProxyPassword;
  2034. break;
  2035. case OPTION_TRANSFERIP:
  2036. FOptionScratch = FTerminal->Configuration->ExternalIpAddress;
  2037. break;
  2038. case OPTION_ANONPWD:
  2039. case OPTION_TRANSFERIP6:
  2040. FOptionScratch = L"";
  2041. break;
  2042. default:
  2043. FAIL;
  2044. FOptionScratch = L"";
  2045. }
  2046. return FOptionScratch.c_str();
  2047. }
  2048. //---------------------------------------------------------------------------
  2049. int __fastcall TFTPFileSystem::GetOptionVal(int OptionID) const
  2050. {
  2051. TSessionData * Data = FTerminal->SessionData;
  2052. int Result;
  2053. switch (OptionID)
  2054. {
  2055. case OPTION_PROXYTYPE:
  2056. switch (Data->ProxyMethod)
  2057. {
  2058. case ::pmNone:
  2059. Result = 0; // PROXYTYPE_NOPROXY;
  2060. break;
  2061. case pmSocks4:
  2062. Result = 2; // PROXYTYPE_SOCKS4A
  2063. break;
  2064. case pmSocks5:
  2065. Result = 3; // PROXYTYPE_SOCKS5
  2066. break;
  2067. case pmHTTP:
  2068. Result = 4; // PROXYTYPE_HTTP11
  2069. break;
  2070. case pmTelnet:
  2071. case pmCmd:
  2072. default:
  2073. FAIL;
  2074. Result = 0; // PROXYTYPE_NOPROXY;
  2075. break;
  2076. }
  2077. break;
  2078. case OPTION_PROXYPORT:
  2079. case OPTION_FWPORT:
  2080. Result = Data->ProxyPort;
  2081. break;
  2082. case OPTION_PROXYUSELOGON:
  2083. Result = !Data->ProxyUsername.IsEmpty();
  2084. break;
  2085. case OPTION_LOGONTYPE:
  2086. Result = Data->FtpProxyLogonType;
  2087. break;
  2088. case OPTION_TIMEOUTLENGTH:
  2089. Result = Data->Timeout;
  2090. break;
  2091. case OPTION_DEBUGSHOWLISTING:
  2092. Result = true;
  2093. break;
  2094. case OPTION_PASV:
  2095. // should never get here t_server.nPasv being nonzero
  2096. FAIL;
  2097. Result = FALSE;
  2098. break;
  2099. case OPTION_PRESERVEDOWNLOADFILETIME:
  2100. case OPTION_MPEXT_PRESERVEUPLOADFILETIME:
  2101. Result = FFileTransferPreserveTime ? TRUE : FALSE;
  2102. break;
  2103. case OPTION_LIMITPORTRANGE:
  2104. Result = FALSE;
  2105. break;
  2106. case OPTION_PORTRANGELOW:
  2107. case OPTION_PORTRANGEHIGH:
  2108. // should never get here OPTION_LIMITPORTRANGE being zero
  2109. FAIL;
  2110. Result = 0;
  2111. break;
  2112. case OPTION_ENABLE_IPV6:
  2113. Result = ((Data->AddressFamily == afIPv6) ? TRUE : FALSE);
  2114. break;
  2115. case OPTION_KEEPALIVE:
  2116. Result = ((Data->FtpPingType != ptOff) ? TRUE : FALSE);
  2117. break;
  2118. case OPTION_INTERVALLOW:
  2119. case OPTION_INTERVALHIGH:
  2120. Result = Data->FtpPingInterval;
  2121. break;
  2122. case OPTION_VMSALLREVISIONS:
  2123. Result = FALSE;
  2124. break;
  2125. case OPTION_SPEEDLIMIT_DOWNLOAD_TYPE:
  2126. case OPTION_SPEEDLIMIT_UPLOAD_TYPE:
  2127. Result = (FFileTransferCPSLimit == 0 ? 0 : 1);
  2128. break;
  2129. case OPTION_SPEEDLIMIT_DOWNLOAD_VALUE:
  2130. case OPTION_SPEEDLIMIT_UPLOAD_VALUE:
  2131. Result = (FFileTransferCPSLimit / 1024); // FZAPI expects KB/s
  2132. break;
  2133. case OPTION_MPEXT_SHOWHIDDEN:
  2134. Result = (FDoListAll ? TRUE : FALSE);
  2135. break;
  2136. case OPTION_MPEXT_SSLSESSIONREUSE:
  2137. Result = (Data->SslSessionReuse ? TRUE : FALSE);
  2138. break;
  2139. case OPTION_MPEXT_MIN_TLS_VERSION:
  2140. Result = Data->MinTlsVersion;
  2141. break;
  2142. case OPTION_MPEXT_MAX_TLS_VERSION:
  2143. Result = Data->MaxTlsVersion;
  2144. break;
  2145. case OPTION_MPEXT_SNDBUF:
  2146. Result = Data->SendBuf;
  2147. break;
  2148. case OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY:
  2149. Result = Data->FtpTransferActiveImmediately;
  2150. break;
  2151. case OPTION_MPEXT_REMOVE_BOM:
  2152. Result = FFileTransferRemoveBOM ? TRUE : FALSE;
  2153. break;
  2154. default:
  2155. FAIL;
  2156. Result = FALSE;
  2157. break;
  2158. }
  2159. return Result;
  2160. }
  2161. //---------------------------------------------------------------------------
  2162. bool __fastcall TFTPFileSystem::PostMessage(unsigned int Type, WPARAM wParam, LPARAM lParam)
  2163. {
  2164. if (Type == TFileZillaIntf::MSG_TRANSFERSTATUS)
  2165. {
  2166. // Stop here if FileTransferProgress is proceeding,
  2167. // it makes "pause" in queue work.
  2168. // Paused queue item stops in some of the TFileOperationProgressType
  2169. // methods called from FileTransferProgress
  2170. TGuard Guard(FTransferStatusCriticalSection);
  2171. }
  2172. TGuard Guard(FQueueCriticalSection);
  2173. FQueue->push_back(TMessageQueue::value_type(wParam, lParam));
  2174. SetEvent(FQueueEvent);
  2175. return true;
  2176. }
  2177. //---------------------------------------------------------------------------
  2178. bool __fastcall TFTPFileSystem::ProcessMessage()
  2179. {
  2180. bool Result;
  2181. TMessageQueue::value_type Message;
  2182. {
  2183. TGuard Guard(FQueueCriticalSection);
  2184. Result = !FQueue->empty();
  2185. if (Result)
  2186. {
  2187. Message = FQueue->front();
  2188. FQueue->pop_front();
  2189. }
  2190. else
  2191. {
  2192. // now we are perfectly sure that the queue is empty as it is locked,
  2193. // so reset the event
  2194. ResetEvent(FQueueEvent);
  2195. }
  2196. }
  2197. if (Result)
  2198. {
  2199. FFileZillaIntf->HandleMessage(Message.first, Message.second);
  2200. }
  2201. return Result;
  2202. }
  2203. //---------------------------------------------------------------------------
  2204. void __fastcall TFTPFileSystem::DiscardMessages()
  2205. {
  2206. while (ProcessMessage());
  2207. }
  2208. //---------------------------------------------------------------------------
  2209. void __fastcall TFTPFileSystem::WaitForMessages()
  2210. {
  2211. unsigned int Result = WaitForSingleObject(FQueueEvent, INFINITE);
  2212. if (Result != WAIT_OBJECT_0)
  2213. {
  2214. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, (L"ftp#1", IntToStr(int(Result)))));
  2215. }
  2216. }
  2217. //---------------------------------------------------------------------------
  2218. void __fastcall TFTPFileSystem::PoolForFatalNonCommandReply()
  2219. {
  2220. assert(FReply == 0);
  2221. assert(FCommandReply == 0);
  2222. assert(!FWaitingForReply);
  2223. FWaitingForReply = true;
  2224. unsigned int Reply;
  2225. try
  2226. {
  2227. // discard up to one reply
  2228. // (it should not happen here that two replies are posted anyway)
  2229. while (ProcessMessage() && (FReply == 0));
  2230. Reply = FReply;
  2231. }
  2232. __finally
  2233. {
  2234. FReply = 0;
  2235. assert(FCommandReply == 0);
  2236. FCommandReply = 0;
  2237. assert(FWaitingForReply);
  2238. FWaitingForReply = false;
  2239. }
  2240. if (Reply != 0)
  2241. {
  2242. // throws
  2243. GotNonCommandReply(Reply);
  2244. }
  2245. }
  2246. //---------------------------------------------------------------------------
  2247. bool __fastcall TFTPFileSystem::NoFinalLastCode()
  2248. {
  2249. return (FLastCodeClass == 0) || (FLastCodeClass == 1);
  2250. }
  2251. //---------------------------------------------------------------------------
  2252. bool __fastcall TFTPFileSystem::KeepWaitingForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2253. {
  2254. // to keep waiting,
  2255. // non-command reply must be unset,
  2256. // the reply we wait for must be unset or
  2257. // last code must be unset (if we wait for it)
  2258. return
  2259. (FReply == 0) &&
  2260. ((ReplyToAwait == 0) ||
  2261. (WantLastCode && NoFinalLastCode()));
  2262. }
  2263. //---------------------------------------------------------------------------
  2264. void __fastcall TFTPFileSystem::DoWaitForReply(unsigned int & ReplyToAwait, bool WantLastCode)
  2265. {
  2266. try
  2267. {
  2268. while (KeepWaitingForReply(ReplyToAwait, WantLastCode))
  2269. {
  2270. WaitForMessages();
  2271. // wait for the first reply only,
  2272. // i.e. in case two replies are posted get the first only.
  2273. // e.g. when server closes the connection, but posts error message before,
  2274. // sometime it happens that command (like download) fails because of the error
  2275. // and does not catch the disconnection. then asynchronous "disconnect reply"
  2276. // is posted immediately afterwards. leave detection of that to Idle()
  2277. while (ProcessMessage() && KeepWaitingForReply(ReplyToAwait, WantLastCode));
  2278. }
  2279. if (FReply != 0)
  2280. {
  2281. // throws
  2282. GotNonCommandReply(FReply);
  2283. }
  2284. }
  2285. catch(...)
  2286. {
  2287. // even if non-fatal error happens, we must process pending message,
  2288. // so that we "eat" the reply message, so that it gets not mistakenly
  2289. // associated with future connect
  2290. if (FTerminal->Active)
  2291. {
  2292. DoWaitForReply(ReplyToAwait, WantLastCode);
  2293. }
  2294. throw;
  2295. }
  2296. }
  2297. //---------------------------------------------------------------------------
  2298. unsigned int __fastcall TFTPFileSystem::WaitForReply(bool Command, bool WantLastCode)
  2299. {
  2300. assert(FReply == 0);
  2301. assert(FCommandReply == 0);
  2302. assert(!FWaitingForReply);
  2303. ResetReply();
  2304. FWaitingForReply = true;
  2305. unsigned int Reply;
  2306. try
  2307. {
  2308. unsigned int & ReplyToAwait = (Command ? FCommandReply : FReply);
  2309. DoWaitForReply(ReplyToAwait, WantLastCode);
  2310. Reply = ReplyToAwait;
  2311. }
  2312. __finally
  2313. {
  2314. FReply = 0;
  2315. FCommandReply = 0;
  2316. assert(FWaitingForReply);
  2317. FWaitingForReply = false;
  2318. }
  2319. return Reply;
  2320. }
  2321. //---------------------------------------------------------------------------
  2322. unsigned int __fastcall TFTPFileSystem::WaitForCommandReply(bool WantLastCode)
  2323. {
  2324. return WaitForReply(true, WantLastCode);
  2325. }
  2326. //---------------------------------------------------------------------------
  2327. void __fastcall TFTPFileSystem::WaitForFatalNonCommandReply()
  2328. {
  2329. WaitForReply(false, false);
  2330. FAIL;
  2331. }
  2332. //---------------------------------------------------------------------------
  2333. void __fastcall TFTPFileSystem::ResetReply()
  2334. {
  2335. FLastCode = 0;
  2336. FLastCodeClass = 0;
  2337. assert(FLastResponse != NULL);
  2338. FLastResponse->Clear();
  2339. assert(FLastErrorResponse != NULL);
  2340. FLastErrorResponse->Clear();
  2341. assert(FLastError != NULL);
  2342. FLastError->Clear();
  2343. }
  2344. //---------------------------------------------------------------------------
  2345. void __fastcall TFTPFileSystem::GotNonCommandReply(unsigned int Reply)
  2346. {
  2347. assert(FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2348. GotReply(Reply);
  2349. // should never get here as GotReply should raise fatal exception
  2350. FAIL;
  2351. }
  2352. //---------------------------------------------------------------------------
  2353. void __fastcall TFTPFileSystem::GotReply(unsigned int Reply, unsigned int Flags,
  2354. UnicodeString Error, unsigned int * Code, TStrings ** Response)
  2355. {
  2356. try
  2357. {
  2358. if (FLAGSET(Reply, TFileZillaIntf::REPLY_OK))
  2359. {
  2360. assert(Reply == TFileZillaIntf::REPLY_OK);
  2361. // With REPLY_2XX_CODE treat "OK" non-2xx code like an error.
  2362. // REPLY_3XX_CODE has to be always used along with REPLY_2XX_CODE.
  2363. if ((FLAGSET(Flags, REPLY_2XX_CODE) && (FLastCodeClass != 2)) &&
  2364. ((FLAGCLEAR(Flags, REPLY_3XX_CODE) || (FLastCodeClass != 3))))
  2365. {
  2366. GotReply(TFileZillaIntf::REPLY_ERROR, Flags, Error);
  2367. }
  2368. }
  2369. else if (FLAGSET(Reply, TFileZillaIntf::REPLY_CANCEL) &&
  2370. FLAGSET(Flags, REPLY_ALLOW_CANCEL))
  2371. {
  2372. assert(
  2373. (Reply == (TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)) ||
  2374. (Reply == (TFileZillaIntf::REPLY_ABORTED | TFileZillaIntf::REPLY_CANCEL | TFileZillaIntf::REPLY_ERROR)));
  2375. // noop
  2376. }
  2377. // we do not expect these with our usage of FZ
  2378. else if (Reply &
  2379. (TFileZillaIntf::REPLY_WOULDBLOCK | TFileZillaIntf::REPLY_OWNERNOTSET |
  2380. TFileZillaIntf::REPLY_INVALIDPARAM | TFileZillaIntf::REPLY_ALREADYCONNECTED |
  2381. TFileZillaIntf::REPLY_IDLE | TFileZillaIntf::REPLY_NOTINITIALIZED |
  2382. TFileZillaIntf::REPLY_ALREADYINIZIALIZED))
  2383. {
  2384. FTerminal->FatalError(NULL, FMTLOAD(INTERNAL_ERROR, (L"ftp#2", FORMAT(L"0x%x", (int(Reply))))));
  2385. }
  2386. else
  2387. {
  2388. // everything else must be an error or disconnect notification
  2389. assert(
  2390. FLAGSET(Reply, TFileZillaIntf::REPLY_ERROR) ||
  2391. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED));
  2392. // TODO: REPLY_CRITICALERROR ignored
  2393. // REPLY_NOTCONNECTED happens if connection is closed between moment
  2394. // when FZAPI interface method dispatches the command to FZAPI thread
  2395. // and moment when FZAPI thread receives the command
  2396. bool Disconnected =
  2397. FLAGSET(Reply, TFileZillaIntf::REPLY_DISCONNECTED) ||
  2398. FLAGSET(Reply, TFileZillaIntf::REPLY_NOTCONNECTED);
  2399. AnsiString HelpKeyword;
  2400. TStrings * MoreMessages = new TStringList();
  2401. try
  2402. {
  2403. if (Disconnected)
  2404. {
  2405. if (FLAGCLEAR(Flags, REPLY_CONNECT))
  2406. {
  2407. MoreMessages->Add(LoadStr(LOST_CONNECTION));
  2408. Discard();
  2409. FTerminal->Closed();
  2410. }
  2411. else
  2412. {
  2413. // For connection failure, do not report that connection was lost,
  2414. // its obvious.
  2415. // Also do not report to terminal that we are closed as
  2416. // that turns terminal into closed mode, but we want to
  2417. // pretend (at least with failed authentication) to retry
  2418. // with the same connection (as with SSH), so we explicitly
  2419. // close terminal in Open() only after we give up
  2420. Discard();
  2421. }
  2422. }
  2423. if (FLAGSET(Reply, TFileZillaIntf::REPLY_ABORTED))
  2424. {
  2425. MoreMessages->Add(LoadStr(USER_TERMINATED));
  2426. }
  2427. if (FLAGSET(Reply, TFileZillaIntf::REPLY_NOTSUPPORTED))
  2428. {
  2429. MoreMessages->Add(LoadStr(FZ_NOTSUPPORTED));
  2430. }
  2431. if (FLastCode == 530)
  2432. {
  2433. MoreMessages->Add(LoadStr(AUTHENTICATION_FAILED));
  2434. }
  2435. if (FLastCode == 425)
  2436. {
  2437. if (!FTerminal->SessionData->FtpPasvMode)
  2438. {
  2439. MoreMessages->Add(LoadStr(FTP_CANNOT_OPEN_ACTIVE_CONNECTION2));
  2440. HelpKeyword = HELP_FTP_CANNOT_OPEN_ACTIVE_CONNECTION;
  2441. }
  2442. }
  2443. if (FLastCode == DummyTimeoutCode)
  2444. {
  2445. HelpKeyword = HELP_ERRORMSG_TIMEOUT;
  2446. }
  2447. MoreMessages->AddStrings(FLastError);
  2448. // already cleared from WaitForReply, but GotReply can be also called
  2449. // from Closed. then make sure that error from previous command not
  2450. // associated with session closure is not reused
  2451. FLastError->Clear();
  2452. MoreMessages->AddStrings(FLastErrorResponse);
  2453. // see comment for FLastError
  2454. FLastResponse->Clear();
  2455. FLastErrorResponse->Clear();
  2456. if (MoreMessages->Count == 0)
  2457. {
  2458. delete MoreMessages;
  2459. MoreMessages = NULL;
  2460. }
  2461. }
  2462. catch(...)
  2463. {
  2464. delete MoreMessages;
  2465. throw;
  2466. }
  2467. if (Error.IsEmpty() && (MoreMessages != NULL))
  2468. {
  2469. assert(MoreMessages->Count > 0);
  2470. // bit too generic assigning of main instructions, let's see how it works
  2471. Error = MainInstructions(MoreMessages->Strings[0]);
  2472. MoreMessages->Delete(0);
  2473. }
  2474. if (Disconnected)
  2475. {
  2476. // for fatal error, it is essential that there is some message
  2477. assert(!Error.IsEmpty());
  2478. ExtException * E = new ExtException(Error, MoreMessages, true, HelpKeyword);
  2479. try
  2480. {
  2481. FTerminal->FatalError(E, L"");
  2482. }
  2483. __finally
  2484. {
  2485. delete E;
  2486. }
  2487. }
  2488. else
  2489. {
  2490. throw ExtException(Error, MoreMessages, true, HelpKeyword);
  2491. }
  2492. }
  2493. if ((Code != NULL) && (FLastCodeClass != DummyCodeClass))
  2494. {
  2495. *Code = FLastCode;
  2496. }
  2497. if (Response != NULL)
  2498. {
  2499. *Response = FLastResponse;
  2500. FLastResponse = new TStringList();
  2501. // just to be consistent
  2502. delete FLastErrorResponse;
  2503. FLastErrorResponse = new TStringList();
  2504. }
  2505. }
  2506. __finally
  2507. {
  2508. ResetReply();
  2509. }
  2510. }
  2511. //---------------------------------------------------------------------------
  2512. void __fastcall TFTPFileSystem::SetLastCode(int Code)
  2513. {
  2514. FLastCode = Code;
  2515. FLastCodeClass = (Code / 100);
  2516. }
  2517. //---------------------------------------------------------------------------
  2518. void __fastcall TFTPFileSystem::StoreLastResponse(const UnicodeString & Text)
  2519. {
  2520. FLastResponse->Add(Text);
  2521. if (FLastCodeClass >= 4)
  2522. {
  2523. FLastErrorResponse->Add(Text);
  2524. }
  2525. }
  2526. //---------------------------------------------------------------------------
  2527. void __fastcall TFTPFileSystem::HandleReplyStatus(UnicodeString Response)
  2528. {
  2529. int Code;
  2530. if (FOnCaptureOutput != NULL)
  2531. {
  2532. FOnCaptureOutput(Response, false);
  2533. }
  2534. // Two forms of multiline responses were observed
  2535. // (the first is according to the RFC 959):
  2536. // 211-Features:
  2537. // MDTM
  2538. // REST STREAM
  2539. // SIZE
  2540. // 211 End
  2541. // 211-Features:
  2542. // 211-MDTM
  2543. // 211-REST STREAM
  2544. // 211-SIZE
  2545. // 211-AUTH TLS
  2546. // 211-PBSZ
  2547. // 211-PROT
  2548. // 211 End
  2549. bool HasCodePrefix =
  2550. (Response.Length() >= 3) &&
  2551. TryStrToInt(Response.SubString(1, 3), Code) &&
  2552. (Code >= 100) && (Code <= 599) &&
  2553. ((Response.Length() == 3) || (Response[4] == L' ') || (Response[4] == L'-'));
  2554. if (HasCodePrefix && !FMultineResponse)
  2555. {
  2556. FMultineResponse = (Response.Length() >= 4) && (Response[4] == L'-');
  2557. FLastResponse->Clear();
  2558. FLastErrorResponse->Clear();
  2559. SetLastCode(Code);
  2560. if (Response.Length() >= 5)
  2561. {
  2562. StoreLastResponse(Response.SubString(5, Response.Length() - 4));
  2563. }
  2564. }
  2565. else
  2566. {
  2567. int Start;
  2568. // response with code prefix
  2569. if (HasCodePrefix && (FLastCode == Code))
  2570. {
  2571. // End of multiline response?
  2572. if ((Response.Length() <= 3) || (Response[4] == L' '))
  2573. {
  2574. FMultineResponse = false;
  2575. }
  2576. Start = 5;
  2577. }
  2578. else
  2579. {
  2580. Start = (((Response.Length() >= 1) && (Response[1] == L' ')) ? 2 : 1);
  2581. }
  2582. // Intermediate empty lines are being added
  2583. if (FMultineResponse || (Response.Length() >= Start))
  2584. {
  2585. StoreLastResponse(Response.SubString(Start, Response.Length() - Start + 1));
  2586. }
  2587. }
  2588. if (!FMultineResponse)
  2589. {
  2590. if (FLastCode == 220)
  2591. {
  2592. if (FTerminal->Configuration->ShowFtpWelcomeMessage)
  2593. {
  2594. FTerminal->DisplayBanner(FLastResponse->Text);
  2595. }
  2596. }
  2597. else if (FLastCommand == PASS)
  2598. {
  2599. // 530 = "Not logged in."
  2600. if (FLastCode == 530)
  2601. {
  2602. FPasswordFailed = true;
  2603. }
  2604. }
  2605. else if (FLastCommand == SYST)
  2606. {
  2607. assert(FSystem.IsEmpty());
  2608. // Positive reply to "SYST" must be 215, see RFC 959
  2609. if (FLastCode == 215)
  2610. {
  2611. FSystem = FLastResponse->Text.TrimRight();
  2612. // full name is "Personal FTP Server PRO K6.0"
  2613. if ((FListAll == asAuto) &&
  2614. (FSystem.Pos(L"Personal FTP Server") > 0))
  2615. {
  2616. FTerminal->LogEvent(L"Server is known not to support LIST -a");
  2617. FListAll = asOff;
  2618. }
  2619. }
  2620. else
  2621. {
  2622. FSystem = L"";
  2623. }
  2624. }
  2625. else if (FLastCommand == FEAT)
  2626. {
  2627. // Response to FEAT must be multiline, where leading and trailing line
  2628. // is "meaningless". See RFC 2389.
  2629. if ((FLastCode == 211) && (FLastResponse->Count > 2))
  2630. {
  2631. FLastResponse->Delete(0);
  2632. FLastResponse->Delete(FLastResponse->Count - 1);
  2633. FFeatures->Assign(FLastResponse);
  2634. }
  2635. else
  2636. {
  2637. FFeatures->Clear();
  2638. }
  2639. }
  2640. }
  2641. }
  2642. //---------------------------------------------------------------------------
  2643. UnicodeString __fastcall TFTPFileSystem::ExtractStatusMessage(UnicodeString Status)
  2644. {
  2645. // CApiLog::LogMessage
  2646. // (note that the formatting may not be present when LogMessageRaw is used)
  2647. int P1 = Status.Pos(L"): ");
  2648. if (P1 > 0)
  2649. {
  2650. int P2 = Status.Pos(L".cpp(");
  2651. if ((P2 > 0) && (P2 < P1))
  2652. {
  2653. int P3 = Status.Pos(L" caller=0x");
  2654. if ((P3 > 0) && (P3 > P1))
  2655. {
  2656. Status = Status.SubString(P1 + 3, P3 - P1 - 3);
  2657. }
  2658. }
  2659. }
  2660. return Status;
  2661. }
  2662. //---------------------------------------------------------------------------
  2663. bool __fastcall TFTPFileSystem::HandleStatus(const wchar_t * AStatus, int Type)
  2664. {
  2665. TLogLineType LogType = (TLogLineType)-1;
  2666. UnicodeString Status(AStatus);
  2667. switch (Type)
  2668. {
  2669. case TFileZillaIntf::LOG_STATUS:
  2670. FTerminal->Information(Status, true);
  2671. LogType = llMessage;
  2672. break;
  2673. case TFileZillaIntf::LOG_COMMAND:
  2674. if (Status == L"SYST")
  2675. {
  2676. FLastCommand = SYST;
  2677. }
  2678. else if (Status == L"FEAT")
  2679. {
  2680. FLastCommand = FEAT;
  2681. }
  2682. else if (Status.SubString(1, 5) == L"PASS ")
  2683. {
  2684. FLastCommand = PASS;
  2685. }
  2686. else
  2687. {
  2688. FLastCommand = CMD_UNKNOWN;
  2689. }
  2690. LogType = llInput;
  2691. break;
  2692. case TFileZillaIntf::LOG_ERROR:
  2693. case TFileZillaIntf::LOG_APIERROR:
  2694. case TFileZillaIntf::LOG_WARNING:
  2695. // when timeout message occurs, break loop waiting for response code
  2696. // by setting dummy one
  2697. if (Type == TFileZillaIntf::LOG_ERROR)
  2698. {
  2699. if (Status == FTimeoutStatus)
  2700. {
  2701. if (NoFinalLastCode())
  2702. {
  2703. SetLastCode(DummyTimeoutCode);
  2704. }
  2705. }
  2706. else if (Status == FDisconnectStatus)
  2707. {
  2708. if (NoFinalLastCode())
  2709. {
  2710. SetLastCode(DummyDisconnectCode);
  2711. }
  2712. }
  2713. }
  2714. // there can be multiple error messages associated with single failure
  2715. // (such as "cannot open local file..." followed by "download failed")
  2716. Status = ExtractStatusMessage(Status);
  2717. FLastError->Add(Status);
  2718. LogType = llMessage;
  2719. break;
  2720. case TFileZillaIntf::LOG_REPLY:
  2721. HandleReplyStatus(AStatus);
  2722. LogType = llOutput;
  2723. break;
  2724. case TFileZillaIntf::LOG_INFO:
  2725. Status = ExtractStatusMessage(Status);
  2726. LogType = llMessage;
  2727. break;
  2728. case TFileZillaIntf::LOG_DEBUG:
  2729. // used for directory listing only
  2730. LogType = llMessage;
  2731. break;
  2732. default:
  2733. FAIL;
  2734. break;
  2735. }
  2736. if (FTerminal->Log->Logging && (LogType != (TLogLineType)-1))
  2737. {
  2738. FTerminal->Log->Add(LogType, Status);
  2739. }
  2740. return true;
  2741. }
  2742. //---------------------------------------------------------------------------
  2743. TDateTime __fastcall TFTPFileSystem::ConvertLocalTimestamp(time_t Time)
  2744. {
  2745. // This reverses how FZAPI converts FILETIME to time_t,
  2746. // before passing it to FZ_ASYNCREQUEST_OVERWRITE.
  2747. __int64 Timestamp;
  2748. tm * Tm = localtime(&Time);
  2749. if (Tm != NULL)
  2750. {
  2751. SYSTEMTIME SystemTime;
  2752. SystemTime.wYear = static_cast<WORD>(Tm->tm_year + 1900);
  2753. SystemTime.wMonth = static_cast<WORD>(Tm->tm_mon + 1);
  2754. SystemTime.wDayOfWeek = 0;
  2755. SystemTime.wDay = static_cast<WORD>(Tm->tm_mday);
  2756. SystemTime.wHour = static_cast<WORD>(Tm->tm_hour);
  2757. SystemTime.wMinute = static_cast<WORD>(Tm->tm_min);
  2758. SystemTime.wSecond = static_cast<WORD>(Tm->tm_sec);
  2759. SystemTime.wMilliseconds = 0;
  2760. FILETIME LocalTime;
  2761. SystemTimeToFileTime(&SystemTime, &LocalTime);
  2762. FILETIME FileTime;
  2763. LocalFileTimeToFileTime(&LocalTime, &FileTime);
  2764. Timestamp = ConvertTimestampToUnixSafe(FileTime, dstmUnix);
  2765. }
  2766. else
  2767. {
  2768. // incorrect, but at least something
  2769. Timestamp = Time;
  2770. }
  2771. return UnixToDateTime(Timestamp, dstmUnix);
  2772. }
  2773. //---------------------------------------------------------------------------
  2774. bool __fastcall TFTPFileSystem::HandleAsynchRequestOverwrite(
  2775. wchar_t * FileName1, size_t FileName1Len, const wchar_t * /*FileName2*/,
  2776. const wchar_t * /*Path1*/, const wchar_t * Path2,
  2777. __int64 Size1, __int64 Size2, time_t LocalTime,
  2778. bool /*HasLocalTime*/, const TRemoteFileTime & RemoteTime, void * AUserData, int & RequestResult)
  2779. {
  2780. if (!FActive)
  2781. {
  2782. return false;
  2783. }
  2784. else
  2785. {
  2786. TFileTransferData & UserData = *((TFileTransferData *)AUserData);
  2787. if (UserData.OverwriteResult >= 0)
  2788. {
  2789. // on retry, use the same answer as on the first attempt
  2790. RequestResult = UserData.OverwriteResult;
  2791. }
  2792. else
  2793. {
  2794. TFileOperationProgressType * OperationProgress = FTerminal->OperationProgress;
  2795. UnicodeString FileName = FileName1;
  2796. assert(UserData.FileName == FileName);
  2797. TOverwriteMode OverwriteMode = omOverwrite;
  2798. TOverwriteFileParams FileParams;
  2799. bool NoFileParams =
  2800. (Size1 < 0) || (LocalTime == 0) ||
  2801. (Size2 < 0) || !RemoteTime.HasDate;
  2802. if (!NoFileParams)
  2803. {
  2804. FileParams.SourceSize = Size2;
  2805. FileParams.DestSize = Size1;
  2806. if (OperationProgress->Side == osLocal)
  2807. {
  2808. FileParams.SourceTimestamp = ConvertLocalTimestamp(LocalTime);
  2809. RemoteFileTimeToDateTimeAndPrecision(RemoteTime, FileParams.DestTimestamp, FileParams.DestPrecision);
  2810. }
  2811. else
  2812. {
  2813. FileParams.DestTimestamp = ConvertLocalTimestamp(LocalTime);
  2814. RemoteFileTimeToDateTimeAndPrecision(RemoteTime, FileParams.SourceTimestamp, FileParams.SourcePrecision);
  2815. }
  2816. }
  2817. UnicodeString FullFileName = Path2;
  2818. if (OperationProgress->Side == osLocal)
  2819. {
  2820. FullFileName = IncludeTrailingBackslash(FullFileName);
  2821. }
  2822. else
  2823. {
  2824. FullFileName = UnixIncludeTrailingBackslash(FullFileName);
  2825. }
  2826. FullFileName += FileName;
  2827. if (ConfirmOverwrite(FullFileName, FileName, OverwriteMode, OperationProgress,
  2828. (NoFileParams ? NULL : &FileParams), UserData.CopyParam, UserData.Params,
  2829. UserData.AutoResume && UserData.CopyParam->AllowResume(FileParams.SourceSize)))
  2830. {
  2831. switch (OverwriteMode)
  2832. {
  2833. case omOverwrite:
  2834. if (FileName != FileName1)
  2835. {
  2836. wcsncpy(FileName1, FileName.c_str(), FileName1Len);
  2837. FileName1[FileName1Len - 1] = L'\0';
  2838. UserData.FileName = FileName1;
  2839. RequestResult = TFileZillaIntf::FILEEXISTS_RENAME;
  2840. }
  2841. else
  2842. {
  2843. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  2844. }
  2845. break;
  2846. case omResume:
  2847. RequestResult = TFileZillaIntf::FILEEXISTS_RESUME;
  2848. break;
  2849. case omComplete:
  2850. FTerminal->LogEvent(L"File transfer was completed before disconnect");
  2851. RequestResult = TFileZillaIntf::FILEEXISTS_COMPLETE;
  2852. break;
  2853. default:
  2854. FAIL;
  2855. RequestResult = TFileZillaIntf::FILEEXISTS_OVERWRITE;
  2856. break;
  2857. }
  2858. }
  2859. else
  2860. {
  2861. RequestResult = TFileZillaIntf::FILEEXISTS_SKIP;
  2862. }
  2863. }
  2864. // remember the answer for the retries
  2865. UserData.OverwriteResult = RequestResult;
  2866. if (RequestResult == TFileZillaIntf::FILEEXISTS_SKIP)
  2867. {
  2868. // when user chooses not to overwrite, break loop waiting for response code
  2869. // by setting dummy one, as FZAPI won't do anything then
  2870. SetLastCode(DummyTimeoutCode);
  2871. }
  2872. return true;
  2873. }
  2874. }
  2875. //---------------------------------------------------------------------------
  2876. UnicodeString __fastcall FormatContactList(UnicodeString Entry1, UnicodeString Entry2)
  2877. {
  2878. if (!Entry1.IsEmpty() && !Entry2.IsEmpty())
  2879. {
  2880. return FORMAT(L"%s, %s", (Entry1, Entry2));
  2881. }
  2882. else
  2883. {
  2884. return Entry1 + Entry2;
  2885. }
  2886. }
  2887. //---------------------------------------------------------------------------
  2888. UnicodeString __fastcall FormatContact(const TFtpsCertificateData::TContact & Contact)
  2889. {
  2890. UnicodeString Result =
  2891. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 1),
  2892. (FormatContactList(FormatContactList(FormatContactList(
  2893. Contact.Organization, Contact.Unit), Contact.CommonName), Contact.Mail)));
  2894. if ((wcslen(Contact.Country) > 0) ||
  2895. (wcslen(Contact.StateProvince) > 0) ||
  2896. (wcslen(Contact.Town) > 0))
  2897. {
  2898. Result +=
  2899. FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 2),
  2900. (FormatContactList(FormatContactList(
  2901. Contact.Country, Contact.StateProvince), Contact.Town)));
  2902. }
  2903. if (wcslen(Contact.Other) > 0)
  2904. {
  2905. Result += FORMAT(LoadStrPart(VERIFY_CERT_CONTACT, 3), (Contact.Other));
  2906. }
  2907. return Result;
  2908. }
  2909. //---------------------------------------------------------------------------
  2910. UnicodeString __fastcall FormatValidityTime(const TFtpsCertificateData::TValidityTime & ValidityTime)
  2911. {
  2912. return FormatDateTime(L"ddddd tt",
  2913. EncodeDateVerbose(
  2914. (unsigned short)ValidityTime.Year, (unsigned short)ValidityTime.Month,
  2915. (unsigned short)ValidityTime.Day) +
  2916. EncodeTimeVerbose(
  2917. (unsigned short)ValidityTime.Hour, (unsigned short)ValidityTime.Min,
  2918. (unsigned short)ValidityTime.Sec, 0));
  2919. }
  2920. //---------------------------------------------------------------------------
  2921. bool __fastcall VerifyNameMask(UnicodeString Name, UnicodeString Mask)
  2922. {
  2923. bool Result = true;
  2924. int Pos;
  2925. while (Result && (Pos = Mask.Pos(L"*")) > 0)
  2926. {
  2927. // Pos will typically be 1 here, so not actual comparison is done
  2928. Result = SameText(Mask.SubString(1, Pos - 1), Name.SubString(1, Pos - 1));
  2929. if (Result)
  2930. {
  2931. Mask.Delete(1, Pos); // including *
  2932. Name.Delete(1, Pos - 1);
  2933. // remove everything until the next dot
  2934. Pos = Name.Pos(L".");
  2935. if (Pos == 0)
  2936. {
  2937. Pos = Name.Length() + 1;
  2938. }
  2939. Name.Delete(1, Pos - 1);
  2940. }
  2941. }
  2942. if (Result)
  2943. {
  2944. Result = SameText(Mask, Name);
  2945. }
  2946. return Result;
  2947. }
  2948. //---------------------------------------------------------------------------
  2949. bool __fastcall TFTPFileSystem::VerifyCertificateHostName(const TFtpsCertificateData & Data)
  2950. {
  2951. UnicodeString HostName = FTerminal->SessionData->HostNameExpanded;
  2952. UnicodeString CommonName = Data.Subject.CommonName;
  2953. bool NoMask = CommonName.IsEmpty();
  2954. bool Result = !NoMask && VerifyNameMask(HostName, CommonName);
  2955. if (Result)
  2956. {
  2957. FTerminal->LogEvent(FORMAT("Certificate common name \"%s\" matches hostname", (CommonName)));
  2958. }
  2959. else
  2960. {
  2961. if (!NoMask && (FTerminal->Configuration->ActualLogProtocol >= 1))
  2962. {
  2963. FTerminal->LogEvent(FORMAT("Certificate common name \"%s\" does not match hostname", (CommonName)));
  2964. }
  2965. UnicodeString SubjectAltName = Data.SubjectAltName;
  2966. while (!Result && !SubjectAltName.IsEmpty())
  2967. {
  2968. UnicodeString Entry = CutToChar(SubjectAltName, L',', true);
  2969. UnicodeString EntryName = CutToChar(Entry, L':', true);
  2970. if (SameText(EntryName, L"DNS"))
  2971. {
  2972. NoMask = false;
  2973. Result = VerifyNameMask(HostName, Entry);
  2974. if (Result)
  2975. {
  2976. FTerminal->LogEvent(FORMAT("Certificate subject alternative name \"%s\" matches hostname", (Entry)));
  2977. }
  2978. else
  2979. {
  2980. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  2981. {
  2982. FTerminal->LogEvent(FORMAT("Certificate subject alternative name \"%s\" does not match hostname", (Entry)));
  2983. }
  2984. }
  2985. }
  2986. }
  2987. }
  2988. if (!Result && NoMask)
  2989. {
  2990. FTerminal->LogEvent("Certificate has no common name nor subject alternative name, not verifying hostname");
  2991. Result = true;
  2992. }
  2993. return Result;
  2994. }
  2995. //---------------------------------------------------------------------------
  2996. bool __fastcall TFTPFileSystem::HandleAsynchRequestVerifyCertificate(
  2997. const TFtpsCertificateData & Data, int & RequestResult)
  2998. {
  2999. if (!FActive)
  3000. {
  3001. return false;
  3002. }
  3003. else
  3004. {
  3005. FSessionInfo.CertificateFingerprint =
  3006. BytesToHex(RawByteString((const char*)Data.Hash, Data.HashLen), false, L':');
  3007. UnicodeString CertificateSubject = Data.Subject.Organization;
  3008. FTerminal->LogEvent(FORMAT(L"Verifying certificate for \"%s\" with fingerprint %s and %d failures", (CertificateSubject, FSessionInfo.CertificateFingerprint, Data.VerificationResult)));
  3009. bool VerificationResult = false;
  3010. bool TryWindowsSystemCertificateStore = false;
  3011. UnicodeString VerificationResultStr;
  3012. switch (Data.VerificationResult)
  3013. {
  3014. case X509_V_OK:
  3015. VerificationResult = true;
  3016. break;
  3017. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  3018. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_GET_ISSUER_CERT);
  3019. TryWindowsSystemCertificateStore = true;
  3020. break;
  3021. case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
  3022. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE);
  3023. break;
  3024. case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
  3025. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY);
  3026. break;
  3027. case X509_V_ERR_CERT_SIGNATURE_FAILURE:
  3028. VerificationResultStr = LoadStr(CERT_ERR_CERT_SIGNATURE_FAILURE);
  3029. break;
  3030. case X509_V_ERR_CERT_NOT_YET_VALID:
  3031. VerificationResultStr = LoadStr(CERT_ERR_CERT_NOT_YET_VALID);
  3032. break;
  3033. case X509_V_ERR_CERT_HAS_EXPIRED:
  3034. VerificationResultStr = LoadStr(CERT_ERR_CERT_HAS_EXPIRED);
  3035. break;
  3036. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  3037. VerificationResultStr = LoadStr(CERT_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD);
  3038. break;
  3039. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  3040. VerificationResultStr = LoadStr(CERT_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
  3041. break;
  3042. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  3043. VerificationResultStr = LoadStr(CERT_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
  3044. TryWindowsSystemCertificateStore = true;
  3045. break;
  3046. case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  3047. VerificationResultStr = LoadStr(CERT_ERR_SELF_SIGNED_CERT_IN_CHAIN);
  3048. TryWindowsSystemCertificateStore = true;
  3049. break;
  3050. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  3051. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
  3052. TryWindowsSystemCertificateStore = true;
  3053. break;
  3054. case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  3055. VerificationResultStr = LoadStr(CERT_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
  3056. TryWindowsSystemCertificateStore = true;
  3057. break;
  3058. case X509_V_ERR_INVALID_CA:
  3059. VerificationResultStr = LoadStr(CERT_ERR_INVALID_CA);
  3060. break;
  3061. case X509_V_ERR_PATH_LENGTH_EXCEEDED:
  3062. VerificationResultStr = LoadStr(CERT_ERR_PATH_LENGTH_EXCEEDED);
  3063. break;
  3064. case X509_V_ERR_INVALID_PURPOSE:
  3065. VerificationResultStr = LoadStr(CERT_ERR_INVALID_PURPOSE);
  3066. break;
  3067. case X509_V_ERR_CERT_UNTRUSTED:
  3068. VerificationResultStr = LoadStr(CERT_ERR_CERT_UNTRUSTED);
  3069. TryWindowsSystemCertificateStore = true;
  3070. break;
  3071. case X509_V_ERR_CERT_REJECTED:
  3072. VerificationResultStr = LoadStr(CERT_ERR_CERT_REJECTED);
  3073. break;
  3074. case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
  3075. VerificationResultStr = LoadStr(CERT_ERR_KEYUSAGE_NO_CERTSIGN);
  3076. break;
  3077. case X509_V_ERR_CERT_CHAIN_TOO_LONG:
  3078. VerificationResultStr = LoadStr(CERT_ERR_CERT_CHAIN_TOO_LONG);
  3079. break;
  3080. default:
  3081. VerificationResultStr =
  3082. FORMAT(L"%s (%s)",
  3083. (LoadStr(CERT_ERR_UNKNOWN), X509_verify_cert_error_string(Data.VerificationResult)));
  3084. break;
  3085. }
  3086. // TryWindowsSystemCertificateStore is set for the same set of failures
  3087. // as trigger NE_SSL_UNTRUSTED flag in ne_openssl.c's verify_callback()
  3088. if (!VerificationResult && TryWindowsSystemCertificateStore)
  3089. {
  3090. if (WindowsValidateCertificate(Data.Certificate, Data.CertificateLen))
  3091. {
  3092. FTerminal->LogEvent(L"Certificate verified against Windows certificate store");
  3093. VerificationResult = true;
  3094. }
  3095. }
  3096. UnicodeString Summary;
  3097. if (!VerificationResult)
  3098. {
  3099. Summary = VerificationResultStr + L" " + FMTLOAD(CERT_ERRDEPTH, (Data.VerificationDepth + 1));
  3100. }
  3101. if (!VerifyCertificateHostName(Data))
  3102. {
  3103. VerificationResult = false;
  3104. AddToList(Summary, FMTLOAD(CERT_NAME_MISMATCH, (FTerminal->SessionData->HostNameExpanded)), L"\n\n");
  3105. }
  3106. if (VerificationResult)
  3107. {
  3108. Summary = LoadStr(CERT_OK);
  3109. }
  3110. FSessionInfo.Certificate =
  3111. FMTLOAD(CERT_TEXT, (
  3112. FormatContact(Data.Issuer),
  3113. FormatContact(Data.Subject),
  3114. FormatValidityTime(Data.ValidFrom),
  3115. FormatValidityTime(Data.ValidUntil),
  3116. FSessionInfo.CertificateFingerprint,
  3117. Summary));
  3118. RequestResult = 0;
  3119. if (VerificationResult)
  3120. {
  3121. RequestResult = 1;
  3122. }
  3123. if (RequestResult == 0)
  3124. {
  3125. if (FTerminal->VerifyCertificate(CertificateStorageKey,
  3126. FSessionInfo.CertificateFingerprint, CertificateSubject, Data.VerificationResult))
  3127. {
  3128. RequestResult = 1;
  3129. }
  3130. }
  3131. if (RequestResult == 0)
  3132. {
  3133. TClipboardHandler ClipboardHandler;
  3134. ClipboardHandler.Text = FSessionInfo.CertificateFingerprint;
  3135. TQueryButtonAlias Aliases[1];
  3136. Aliases[0].Button = qaRetry;
  3137. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  3138. Aliases[0].OnClick = &ClipboardHandler.Copy;
  3139. TQueryParams Params;
  3140. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  3141. Params.NoBatchAnswers = qaYes | qaRetry;
  3142. Params.Aliases = Aliases;
  3143. Params.AliasesCount = LENOF(Aliases);
  3144. unsigned int Answer = FTerminal->QueryUser(
  3145. FMTLOAD(VERIFY_CERT_PROMPT3, (FSessionInfo.Certificate)),
  3146. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  3147. switch (Answer)
  3148. {
  3149. case qaYes:
  3150. // 2 = always, as used by FZ's VerifyCertDlg.cpp,
  3151. // however FZAPI takes all non-zero values equally
  3152. RequestResult = 2;
  3153. break;
  3154. case qaNo:
  3155. RequestResult = 1;
  3156. break;
  3157. case qaCancel:
  3158. FTerminal->Configuration->Usage->Inc(L"HostNotVerified");
  3159. RequestResult = 0;
  3160. break;
  3161. default:
  3162. FAIL;
  3163. RequestResult = 0;
  3164. break;
  3165. }
  3166. if (RequestResult == 2)
  3167. {
  3168. FTerminal->CacheCertificate(
  3169. CertificateStorageKey, FSessionInfo.CertificateFingerprint, Data.VerificationResult);
  3170. }
  3171. }
  3172. return true;
  3173. }
  3174. }
  3175. //---------------------------------------------------------------------------
  3176. bool __fastcall TFTPFileSystem::HandleAsynchRequestNeedPass(
  3177. struct TNeedPassRequestData & Data, int & RequestResult)
  3178. {
  3179. if (!FActive)
  3180. {
  3181. return false;
  3182. }
  3183. else
  3184. {
  3185. UnicodeString Password = L"";
  3186. if (FTerminal->PromptUser(FTerminal->SessionData, pkPassword, LoadStr(PASSWORD_TITLE), L"",
  3187. LoadStr(PASSWORD_PROMPT), false, 0, Password))
  3188. {
  3189. Data.Password = _wcsdup(Password.c_str());
  3190. RequestResult = TFileZillaIntf::REPLY_OK;
  3191. }
  3192. else
  3193. {
  3194. RequestResult = TFileZillaIntf::REPLY_ABORTED;
  3195. }
  3196. return true;
  3197. }
  3198. }
  3199. //---------------------------------------------------------------------------
  3200. void __fastcall TFTPFileSystem::RemoteFileTimeToDateTimeAndPrecision(const TRemoteFileTime & Source, TDateTime & DateTime, TModificationFmt & ModificationFmt)
  3201. {
  3202. // ModificationFmt must be set after Modification
  3203. if (Source.HasDate)
  3204. {
  3205. DateTime =
  3206. EncodeDateVerbose((unsigned short)Source.Year, (unsigned short)Source.Month,
  3207. (unsigned short)Source.Day);
  3208. if (Source.HasTime)
  3209. {
  3210. DateTime = DateTime +
  3211. EncodeTimeVerbose((unsigned short)Source.Hour, (unsigned short)Source.Minute,
  3212. (unsigned short)Source.Second, 0);
  3213. // not exact as we got year as well, but it is most probably
  3214. // guessed by FZAPI anyway
  3215. ModificationFmt = Source.HasSeconds ? mfFull : mfMDHM;
  3216. }
  3217. else
  3218. {
  3219. ModificationFmt = mfMDY;
  3220. }
  3221. if (Source.Utc)
  3222. {
  3223. DateTime = ConvertTimestampFromUTC(DateTime);
  3224. }
  3225. }
  3226. else
  3227. {
  3228. // With SCP we estimate date to be today, if we have at least time
  3229. DateTime = double(0);
  3230. ModificationFmt = mfNone;
  3231. }
  3232. }
  3233. //---------------------------------------------------------------------------
  3234. bool __fastcall TFTPFileSystem::HandleListData(const wchar_t * Path,
  3235. const TListDataEntry * Entries, unsigned int Count)
  3236. {
  3237. if (!FActive)
  3238. {
  3239. return false;
  3240. }
  3241. else if (FIgnoreFileList)
  3242. {
  3243. // directory listing provided implicitly by FZAPI during certain operations is ignored
  3244. assert(FFileList == NULL);
  3245. return false;
  3246. }
  3247. else
  3248. {
  3249. assert(FFileList != NULL);
  3250. // this can actually fail in real life,
  3251. // when connected to server with case insensitive paths
  3252. assert(UnixSamePath(AbsolutePath(FFileList->Directory, false), Path));
  3253. USEDPARAM(Path);
  3254. for (unsigned int Index = 0; Index < Count; Index++)
  3255. {
  3256. const TListDataEntry * Entry = &Entries[Index];
  3257. TRemoteFile * File = new TRemoteFile();
  3258. try
  3259. {
  3260. File->Terminal = FTerminal;
  3261. File->FileName = Entry->Name;
  3262. try
  3263. {
  3264. int PermissionsLen = wcslen(Entry->Permissions);
  3265. if (PermissionsLen >= 10)
  3266. {
  3267. File->Rights->Text = Entry->Permissions + 1;
  3268. }
  3269. else if ((PermissionsLen == 3) || (PermissionsLen == 4))
  3270. {
  3271. File->Rights->Octal = Entry->Permissions;
  3272. }
  3273. }
  3274. catch(...)
  3275. {
  3276. // ignore permissions errors with FTP
  3277. }
  3278. const wchar_t * Space = wcschr(Entry->OwnerGroup, L' ');
  3279. if (Space != NULL)
  3280. {
  3281. File->Owner.Name = UnicodeString(Entry->OwnerGroup, Space - Entry->OwnerGroup);
  3282. File->Group.Name = Space + 1;
  3283. }
  3284. else
  3285. {
  3286. File->Owner.Name = Entry->OwnerGroup;
  3287. }
  3288. File->Size = Entry->Size;
  3289. if (Entry->Link)
  3290. {
  3291. File->Type = FILETYPE_SYMLINK;
  3292. }
  3293. else if (Entry->Dir)
  3294. {
  3295. File->Type = FILETYPE_DIRECTORY;
  3296. }
  3297. else
  3298. {
  3299. File->Type = FILETYPE_DEFAULT;
  3300. }
  3301. TDateTime Modification;
  3302. TModificationFmt ModificationFmt;
  3303. RemoteFileTimeToDateTimeAndPrecision(Entry->Time, Modification, ModificationFmt);
  3304. File->Modification = Modification;
  3305. File->ModificationFmt = ModificationFmt;
  3306. File->LastAccess = File->Modification;
  3307. File->LinkTo = Entry->LinkTarget;
  3308. File->Complete();
  3309. }
  3310. catch (Exception & E)
  3311. {
  3312. delete File;
  3313. UnicodeString EntryData =
  3314. FORMAT(L"%s/%s/%s/%s/%d/%d/%d/%d/%d/%d/%d/%d/%d/%d",
  3315. (Entry->Name, Entry->Permissions, Entry->OwnerGroup, IntToStr(Entry->Size),
  3316. int(Entry->Dir), int(Entry->Link), Entry->Time.Year, Entry->Time.Month, Entry->Time.Day,
  3317. Entry->Time.Hour, Entry->Time.Minute, int(Entry->Time.HasTime),
  3318. int(Entry->Time.HasSeconds), int(Entry->Time.HasDate)));
  3319. throw ETerminal(&E, FMTLOAD(LIST_LINE_ERROR, (EntryData)), HELP_LIST_LINE_ERROR);
  3320. }
  3321. FFileList->AddFile(File);
  3322. }
  3323. return true;
  3324. }
  3325. }
  3326. //---------------------------------------------------------------------------
  3327. bool __fastcall TFTPFileSystem::HandleTransferStatus(bool Valid, __int64 TransferSize,
  3328. __int64 Bytes, int /*Percent*/, int /*TimeElapsed*/, int /*TimeLeft*/, int /*TransferRate*/,
  3329. bool FileTransfer)
  3330. {
  3331. if (!FActive)
  3332. {
  3333. return false;
  3334. }
  3335. else if (!Valid)
  3336. {
  3337. }
  3338. else if (FileTransfer)
  3339. {
  3340. FileTransferProgress(TransferSize, Bytes);
  3341. }
  3342. else
  3343. {
  3344. ReadDirectoryProgress(Bytes);
  3345. }
  3346. return true;
  3347. }
  3348. //---------------------------------------------------------------------------
  3349. bool __fastcall TFTPFileSystem::HandleReply(int Command, unsigned int Reply)
  3350. {
  3351. if (!FActive)
  3352. {
  3353. return false;
  3354. }
  3355. else
  3356. {
  3357. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3358. {
  3359. FTerminal->LogEvent(FORMAT(L"Got reply %x to the command %d", (int(Reply), Command)));
  3360. }
  3361. // reply with Command 0 is not associated with current operation
  3362. // so do not treat is as a reply
  3363. // (it is typically used asynchronously to notify about disconnects)
  3364. if (Command != 0)
  3365. {
  3366. assert(FCommandReply == 0);
  3367. FCommandReply = Reply;
  3368. }
  3369. else
  3370. {
  3371. assert(FReply == 0);
  3372. FReply = Reply;
  3373. }
  3374. return true;
  3375. }
  3376. }
  3377. //---------------------------------------------------------------------------
  3378. bool __fastcall TFTPFileSystem::HandleCapabilities(
  3379. TFTPServerCapabilities * ServerCapabilities)
  3380. {
  3381. FServerCapabilities->Assign(ServerCapabilities);
  3382. FFileSystemInfoValid = false;
  3383. return true;
  3384. }
  3385. //---------------------------------------------------------------------------
  3386. bool __fastcall TFTPFileSystem::CheckError(int ReturnCode, const wchar_t * Context)
  3387. {
  3388. // we do not expect any FZAPI call to fail as it generally can fail only due to:
  3389. // - invalid parameters
  3390. // - busy FZAPI core
  3391. // the only exception is REPLY_NOTCONNECTED that can happen if
  3392. // connection is closed just between the last call to Idle()
  3393. // and call to any FZAPI command
  3394. // in such case reply without associated command is posted,
  3395. // which we are going to wait for unless we are already waiting
  3396. // on higher level (this typically happens if connection is lost while
  3397. // waiting for user interaction and is detected within call to
  3398. // SetAsyncRequestResult)
  3399. if (FLAGSET(ReturnCode, TFileZillaIntf::REPLY_NOTCONNECTED))
  3400. {
  3401. if (!FWaitingForReply)
  3402. {
  3403. // throws
  3404. WaitForFatalNonCommandReply();
  3405. }
  3406. }
  3407. else
  3408. {
  3409. FTerminal->FatalError(NULL,
  3410. FMTLOAD(INTERNAL_ERROR, (FORMAT(L"fz#%s", (Context)), IntToHex(ReturnCode, 4))));
  3411. FAIL;
  3412. }
  3413. return false;
  3414. }
  3415. //---------------------------------------------------------------------------
  3416. bool __fastcall TFTPFileSystem::Unquote(UnicodeString & Str)
  3417. {
  3418. enum
  3419. {
  3420. INIT,
  3421. QUOTE,
  3422. QUOTED,
  3423. DONE
  3424. } State;
  3425. State = INIT;
  3426. assert((Str.Length() > 0) && ((Str[1] == L'"') || (Str[1] == L'\'')));
  3427. int Index = 1;
  3428. wchar_t Quote;
  3429. while (Index <= Str.Length())
  3430. {
  3431. switch (State)
  3432. {
  3433. case INIT:
  3434. if ((Str[Index] == L'"') || (Str[Index] == L'\''))
  3435. {
  3436. Quote = Str[Index];
  3437. State = QUOTED;
  3438. Str.Delete(Index, 1);
  3439. }
  3440. else
  3441. {
  3442. FAIL;
  3443. // no quoted string
  3444. Str.SetLength(0);
  3445. }
  3446. break;
  3447. case QUOTED:
  3448. if (Str[Index] == Quote)
  3449. {
  3450. State = QUOTE;
  3451. Str.Delete(Index, 1);
  3452. }
  3453. else
  3454. {
  3455. Index++;
  3456. }
  3457. break;
  3458. case QUOTE:
  3459. if (Str[Index] == Quote)
  3460. {
  3461. Index++;
  3462. }
  3463. else
  3464. {
  3465. // end of quoted string, trim the rest
  3466. Str.SetLength(Index - 1);
  3467. State = DONE;
  3468. }
  3469. break;
  3470. }
  3471. }
  3472. return (State == DONE);
  3473. }
  3474. //---------------------------------------------------------------------------
  3475. void __fastcall TFTPFileSystem::PreserveDownloadFileTime(HANDLE Handle, void * UserData)
  3476. {
  3477. TFileTransferData * Data = static_cast<TFileTransferData *>(UserData);
  3478. FILETIME WrTime = DateTimeToFileTime(Data->Modification, dstmUnix);
  3479. SetFileTime(Handle, NULL, NULL, &WrTime);
  3480. }
  3481. //---------------------------------------------------------------------------
  3482. bool __fastcall TFTPFileSystem::GetFileModificationTimeInUtc(const wchar_t * FileName, struct tm & Time)
  3483. {
  3484. bool Result;
  3485. try
  3486. {
  3487. // error-handling-free and DST-mode-inaware copy of TTerminal::OpenLocalFile
  3488. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ,
  3489. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
  3490. if (Handle == INVALID_HANDLE_VALUE)
  3491. {
  3492. Result = false;
  3493. }
  3494. else
  3495. {
  3496. FILETIME MTime;
  3497. if (!GetFileTime(Handle, NULL, NULL, &MTime))
  3498. {
  3499. Result = false;
  3500. }
  3501. else
  3502. {
  3503. TDateTime Modification = ConvertTimestampToUTC(FileTimeToDateTime(MTime));
  3504. unsigned short Year;
  3505. unsigned short Month;
  3506. unsigned short Day;
  3507. Modification.DecodeDate(&Year, &Month, &Day);
  3508. Time.tm_year = Year - 1900;
  3509. Time.tm_mon = Month - 1;
  3510. Time.tm_mday = Day;
  3511. unsigned short Hour;
  3512. unsigned short Min;
  3513. unsigned short Sec;
  3514. unsigned short MSec;
  3515. Modification.DecodeTime(&Hour, &Min, &Sec, &MSec);
  3516. Time.tm_hour = Hour;
  3517. Time.tm_min = Min;
  3518. Time.tm_sec = Sec;
  3519. Result = true;
  3520. }
  3521. CloseHandle(Handle);
  3522. }
  3523. }
  3524. catch (...)
  3525. {
  3526. Result = false;
  3527. }
  3528. return Result;
  3529. }
  3530. //---------------------------------------------------------------------------
  3531. UnicodeString __fastcall GetOpenSSLVersionText()
  3532. {
  3533. return OPENSSL_VERSION_TEXT;
  3534. }
  3535. //---------------------------------------------------------------------------
  3536. #endif NO_FILEZILLA