| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198 |
- //---------------------------------------------------------------------------
- #include <vcl.h>
- #pragma hdrstop
- #include "SftpFileSystem.h"
- #include <sftp.h>
- #include "PuttyIntf.h"
- #include "Common.h"
- #include "Interface.h"
- #include "Terminal.h"
- #include "TextsCore.h"
- #include <memory>
- //---------------------------------------------------------------------------
- #pragma package(smart_init)
- //---------------------------------------------------------------------------
- #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
- FILE_OPERATION_LOOP_CUSTOM(FTerminal, ALLOW_SKIP, MESSAGE, OPERATION)
- //---------------------------------------------------------------------------
- // additional constants for SFTP protocol not defined in Putty's sftp.h
- #define SSH_FXP_READLINK 19
- #define SSH_FXP_SYMLINK 20
- #define SSH_FILEXFER_ATTR_ACCESSTIME 0x00000008
- #define SSH_FILEXFER_ATTR_CREATETIME 0x00000010
- #define SSH_FILEXFER_ATTR_MODIFYTIME 0x00000020
- #define SSH_FILEXFER_ATTR_OWNERGROUP 0x00000080
- #define SSH_FILEXFER_ATTR_SUBSECOND_TIMES 0x00000100
- #define SSH_FILEXFER_TYPE_REGULAR 1
- #define SSH_FILEXFER_TYPE_DIRECTORY 2
- #define SSH_FILEXFER_TYPE_SYMLINK 3
- #define SSH_FILEXFER_TYPE_SPECIAL 4
- #define SSH_FILEXFER_TYPE_UNKNOWN 5
- #define SSH_FXF_TEXT 0x00000040
- #define SFTP_MAX_PACKET_LEN 102400
- //---------------------------------------------------------------------------
- const int SFTPMinVersion = 0;
- const int SFTPMaxVersion = 4;
- const int SFTPNoMessageNumber = -1;
- const int asNo = 0;
- const int asOK = 1 << SSH_FX_OK;
- const int asEOF = 1 << SSH_FX_EOF;
- const int asOpUnsupported = 1 << SSH_FX_OP_UNSUPPORTED;
- const int asNoSuchFile = 1 << SSH_FX_NO_SUCH_FILE;
- const int asAll = 0xFFFF;
- //---------------------------------------------------------------------------
- #define GET_32BIT(cp) \
- (((unsigned long)(unsigned char)(cp)[0] << 24) | \
- ((unsigned long)(unsigned char)(cp)[1] << 16) | \
- ((unsigned long)(unsigned char)(cp)[2] << 8) | \
- ((unsigned long)(unsigned char)(cp)[3]))
- #define PUT_32BIT(cp, value) { \
- (cp)[0] = (unsigned char)((value) >> 24); \
- (cp)[1] = (unsigned char)((value) >> 16); \
- (cp)[2] = (unsigned char)((value) >> 8); \
- (cp)[3] = (unsigned char)(value); }
- #define THROW_SKIP_FILE_NULL THROW_SKIP_FILE(NULL, "")
- //---------------------------------------------------------------------------
- #define SFTP_PACKET_ALLOC_DELTA 256
- //---------------------------------------------------------------------------
- #pragma warn -inl
- //---------------------------------------------------------------------------
- class TSFTPPacket
- {
- public:
- TSFTPPacket()
- {
- Init();
- }
- TSFTPPacket(const TSFTPPacket & Source)
- {
- Init();
- *this = Source;
- }
- TSFTPPacket(unsigned char AType)
- {
- Init();
- ChangeType(AType);
- }
- ~TSFTPPacket()
- {
- delete[] FData;
- if (FReservedBy) FReservedBy->UnreserveResponse(this);
- }
- void ChangeType(unsigned char AType)
- {
- FPosition = 0;
- FLength = 0;
- Capacity = 0;
- FType = AType;
- AddByte(FType);
- if (FType != SSH_FXP_INIT)
- {
- AssignNumber();
- AddCardinal(FMessageNumber);
- }
- }
- void Reuse()
- {
- AssignNumber();
-
- assert(Length >= 5);
- // duplicated in AddCardinal()
- unsigned char Buf[4];
- PUT_32BIT(Buf, FMessageNumber);
- memcpy(FData + 1, Buf, sizeof(Buf));
- }
- void AddByte(unsigned char Value)
- {
- Add(&Value, sizeof(Value));
- }
- void AddCardinal(unsigned long Value)
- {
- // duplicated in Reuse()
- unsigned char Buf[4];
- PUT_32BIT(Buf, Value);
- Add(&Buf, sizeof(Buf));
- }
- void AddInt64(__int64 Value)
- {
- AddCardinal((unsigned long)(Value >> 32));
- AddCardinal((unsigned long)(Value & 0xFFFFFFFF));
- }
- void AddData(const void * Data, int ALength)
- {
- AddCardinal(ALength);
- Add(Data, ALength);
- }
- void AddString(const AnsiString Value)
- {
- AddCardinal(Value.Length());
- Add(Value.c_str(), Value.Length());
- }
- void AddProperties(unsigned short * Rights, AnsiString * Owner,
- AnsiString * Group, unsigned long * MTime, unsigned long * ATime,
- bool IsDirectory, int Version)
- {
- int Flags = 0;
- if (Rights != NULL)
- {
- Flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
- }
- if ((Owner != NULL) || (Group != NULL))
- {
- Flags |= SSH_FILEXFER_ATTR_OWNERGROUP;
- }
- if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
- {
- Flags |= SSH_FILEXFER_ATTR_ACMODTIME;
- }
- if ((Version >= 4) && (ATime != NULL))
- {
- Flags |= SSH_FILEXFER_ATTR_ACCESSTIME;
- }
- if ((Version >= 4) && (MTime != NULL))
- {
- Flags |= SSH_FILEXFER_ATTR_MODIFYTIME;
- }
- AddCardinal(Flags);
- if (Version >= 4)
- {
- AddByte(static_cast<unsigned char>(IsDirectory ?
- SSH_FILEXFER_TYPE_DIRECTORY : SSH_FILEXFER_TYPE_REGULAR));
- }
- if ((Owner != NULL) || (Group != NULL))
- {
- assert(Version >= 4);
- AddString(Owner != NULL ? *Owner : AnsiString());
- AddString(Group != NULL ? *Group : AnsiString());
- }
- if (Rights != NULL)
- {
- AddCardinal(*Rights);
- }
- if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
- {
- AddCardinal(ATime != NULL ? *ATime : *MTime);
- AddCardinal(MTime != NULL ? *MTime : *ATime);
- }
- if ((Version >= 4) && (ATime != NULL))
- {
- AddInt64(*ATime);
- }
- if ((Version >= 4) && (MTime != NULL))
- {
- AddInt64(*MTime);
- }
- }
- void AddProperties(const TRemoteProperties * Properties,
- unsigned short BaseRights, bool IsDirectory, int Version)
- {
- enum { valNone = 0, valRights = 0x01, valOwner = 0x02, valGroup = 0x04 }
- Valid = valNone;
- unsigned short RightsNum = 0;
- AnsiString Owner;
- AnsiString Group;
- if (Properties != NULL)
- {
- if (Properties->Valid.Contains(vpGroup))
- {
- Valid |= valGroup;
- Group = Properties->Group;
- }
- if (Properties->Valid.Contains(vpOwner))
- {
- Valid |= valOwner;
- Owner = Properties->Owner;
- }
- if (Properties->Valid.Contains(vpRights))
- {
- Valid |= valRights;
- TRights Rights = BaseRights;
- Rights |= Properties->Rights.NumberSet;
- Rights &= (unsigned short)~Properties->Rights.NumberUnset;
- if (IsDirectory && Properties->AddXToDirectories)
- {
- Rights.AddExecute();
- }
- RightsNum = Rights;
- }
- }
- AddProperties(
- Valid & valRights ? &RightsNum : NULL,
- Valid & valOwner ? &Owner : NULL,
- Valid & valGroup ? &Group : NULL,
- NULL, NULL, IsDirectory, Version);
- }
- char GetByte()
- {
- assert(FPosition <= FLength - sizeof(char));
- char Result = FData[FPosition];
- FPosition++;
- return Result;
- }
- unsigned long GetCardinal()
- {
- unsigned long Result;
- assert(FPosition <= FLength - sizeof(Result));
- Result = GET_32BIT(FData + FPosition);
- FPosition += sizeof(Result);
- return Result;
- }
- __int64 GetInt64()
- {
- __int64 Hi = GetCardinal();
- __int64 Lo = GetCardinal();
- return (Hi << 32) + Lo;
- }
- AnsiString GetString()
- {
- AnsiString Result;
- unsigned long Len = GetCardinal();
- Result.SetLength(Len);
- assert(FLength >= Len && FPosition <= FLength - Len);
- memcpy(Result.c_str(), FData + FPosition, Len);
- FPosition += Len;
- return Result;
- }
- void GetFile(TRemoteFile * File, int Version)
- {
- assert(File);
- unsigned int Flags;
- AnsiString ListingStr;
- unsigned long Permissions;
- bool ParsingFailed = false;
- if (Type != SSH_FXP_ATTRS)
- {
- File->FileName = GetString();
- if (Version < 4)
- {
- ListingStr = GetString();
- }
- }
- Flags = GetCardinal();
- if (Version >= 4)
- {
- char FXType = GetByte();
- char Types[] = "-DLSU";
- if (FXType < 1 || FXType > (char)strlen(Types))
- {
- throw Exception(FMTLOAD(SFTP_UNKNOWN_FILE_TYPE, (int(FXType))));
- }
- File->Type = Types[FXType-1];
- }
- if (Flags & SSH_FILEXFER_ATTR_SIZE)
- {
- File->Size = GetInt64();
- }
- if (Flags & SSH_FILEXFER_ATTR_UIDGID)
- {
- assert(Version < 4);
- GetCardinal(); // skip UID
- GetCardinal(); // skip GUID
- }
- if (Flags & SSH_FILEXFER_ATTR_OWNERGROUP)
- {
- assert(Version >= 4);
- File->Owner = GetString();
- File->Group = GetString();
- }
- if (Flags & SSH_FILEXFER_ATTR_PERMISSIONS)
- {
- Permissions = GetCardinal();
- }
- if (Version < 4)
- {
- if (Flags & SSH_FILEXFER_ATTR_ACMODTIME)
- {
- File->LastAccess = UnixToDateTime(GetCardinal());
- File->Modification = UnixToDateTime(GetCardinal());
- }
- }
- else
- {
- if (Flags & SSH_FILEXFER_ATTR_ACCESSTIME)
- {
- File->LastAccess = UnixToDateTime((unsigned long)GetInt64());
- }
- if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
- {
- GetCardinal(); // skip access time subseconds
- }
- if (Flags & SSH_FILEXFER_ATTR_CREATETIME)
- {
- GetInt64(); // skip create time
- }
- if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
- {
- GetCardinal(); // skip create time subseconds
- }
- if (Flags & SSH_FILEXFER_ATTR_MODIFYTIME)
- {
- File->Modification = UnixToDateTime((unsigned long)GetInt64());
- }
- if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
- {
- GetCardinal(); // skip modification time subseconds
- }
- }
- if ((Version < 4) && (Type != SSH_FXP_ATTRS))
- {
- try
- {
- // update permissions and user/group name
- // modification time and filename is ignored
- File->ListingStr = ListingStr;
- }
- catch(...)
- {
- // ignore any error while parsing listing line,
- // SFTP specification do not recommend to parse it
- ParsingFailed = true;
- }
- }
- if (Type == SSH_FXP_ATTRS || Version >= 4 || ParsingFailed)
- {
- File->Rights->Number = (unsigned short)(Permissions & 0777);
- if (Version < 4)
- {
- File->Type = (Permissions & 0040000 ? FILETYPE_DIRECTORY : '-');
- }
- }
- // TODO: read extended attributes (Flags & SSH_FILEXFER_ATTR_EXTENDED)
- // Format: Count=Cardinal, Count*(Name=String, Value=String)
- }
- void DataUpdated(int ALength)
- {
- FPosition = 0;
- FLength = ALength;
- FType = GetByte();
- if (FType != SSH_FXP_VERSION)
- {
- FMessageNumber = GetCardinal();
- }
- else
- {
- FMessageNumber = SFTPNoMessageNumber;
- }
- }
- AnsiString __fastcall Dump() const
- {
- AnsiString Result;
- for (unsigned int Index = 0; Index < Length; Index++)
- {
- Result += IntToHex(int((unsigned char)Data[Index]), 2) + ",";
- if (((Index + 1) % 25) == 0)
- {
- Result += "\n";
- }
- }
- return Result;
- }
- TSFTPPacket & operator = (const TSFTPPacket & Source)
- {
- Capacity = 0;
- Add(Source.Data, Source.Length);
- DataUpdated(Source.Length);
- FPosition = Source.FPosition;
- return *this;
- }
- __property unsigned int Length = { read = FLength };
- __property char * Data = { read = FData };
- __property char * NextData = { read = GetNextData };
- __property char * Content = { read = GetContent };
- __property unsigned int ContentLength = { read = GetContentLength };
- __property unsigned int Capacity = { read = FCapacity, write = SetCapacity };
- __property unsigned char Type = { read = FType };
- __property unsigned char RequestType = { read = GetRequestType };
- __property unsigned int MessageNumber = { read = FMessageNumber, write = FMessageNumber };
- __property TSFTPFileSystem * ReservedBy = { read = FReservedBy, write = FReservedBy };
- __property AnsiString TypeName = { read = GetTypeName };
- private:
- char * FData;
- unsigned int FLength;
- unsigned int FCapacity;
- unsigned int FPosition;
- unsigned char FType;
- unsigned int FMessageNumber;
- TSFTPFileSystem * FReservedBy;
- static int FMessageCounter;
- void Init()
- {
- FData = NULL;
- FCapacity = 0;
- FLength = 0;
- FPosition = 0;
- FMessageNumber = SFTPNoMessageNumber;
- FType = -1;
- FReservedBy = NULL;
- }
- void AssignNumber()
- {
- FMessageNumber = (FMessageCounter << 8) + FType;
- FMessageCounter++;
- }
- unsigned char GetRequestType()
- {
- if (FMessageNumber != SFTPNoMessageNumber)
- {
- return (unsigned char)(FMessageNumber & 0xFF);
- }
- else
- {
- assert(Type == SSH_FXP_VERSION);
- return SSH_FXP_INIT;
- }
- }
- void Add(const void * AData, int ALength)
- {
- if (Length + ALength > Capacity)
- {
- Capacity = Length + ALength + SFTP_PACKET_ALLOC_DELTA;
- }
- memcpy(FData + Length, AData, ALength);
- FLength += ALength;
- }
- void SetCapacity(unsigned int ACapacity)
- {
- if (ACapacity != Capacity)
- {
- FCapacity = ACapacity;
- if (FCapacity > 0)
- {
- char * NData = new char[FCapacity];
- if (FData)
- {
- memcpy(NData, FData, (FLength < FCapacity ? FLength : FCapacity));
- delete[] FData;
- }
- FData = NData;
- }
- else
- {
- if (FData) delete[] FData;
- FData = NULL;
- }
- if (FLength > FCapacity) FLength = FCapacity;
- }
- }
- AnsiString GetTypeName() const
- {
- #define TYPE_CASE(TYPE) case TYPE: return #TYPE
- switch (Type) {
- TYPE_CASE(SSH_FXP_INIT);
- TYPE_CASE(SSH_FXP_VERSION);
- TYPE_CASE(SSH_FXP_OPEN);
- TYPE_CASE(SSH_FXP_CLOSE);
- TYPE_CASE(SSH_FXP_READ);
- TYPE_CASE(SSH_FXP_WRITE);
- TYPE_CASE(SSH_FXP_LSTAT);
- TYPE_CASE(SSH_FXP_FSTAT);
- TYPE_CASE(SSH_FXP_SETSTAT);
- TYPE_CASE(SSH_FXP_FSETSTAT);
- TYPE_CASE(SSH_FXP_OPENDIR);
- TYPE_CASE(SSH_FXP_READDIR);
- TYPE_CASE(SSH_FXP_REMOVE);
- TYPE_CASE(SSH_FXP_MKDIR);
- TYPE_CASE(SSH_FXP_RMDIR);
- TYPE_CASE(SSH_FXP_REALPATH);
- TYPE_CASE(SSH_FXP_STAT);
- TYPE_CASE(SSH_FXP_RENAME);
- TYPE_CASE(SSH_FXP_READLINK);
- TYPE_CASE(SSH_FXP_SYMLINK);
- TYPE_CASE(SSH_FXP_STATUS);
- TYPE_CASE(SSH_FXP_HANDLE);
- TYPE_CASE(SSH_FXP_DATA);
- TYPE_CASE(SSH_FXP_NAME);
- TYPE_CASE(SSH_FXP_ATTRS);
- TYPE_CASE(SSH_FXP_EXTENDED);
- TYPE_CASE(SSH_FXP_EXTENDED_REPLY);
- default:
- return FORMAT("Unknown message (%d)", (int(Type)));
- }
- }
- char * GetContent()
- {
- return Data + sizeof(Byte) + (FType != SSH_FXP_VERSION ? sizeof(Cardinal) : 0);
- }
- unsigned int GetContentLength()
- {
- return Length - sizeof(Byte) - (FType != SSH_FXP_VERSION ? sizeof(Cardinal) : 0);
- }
- char * GetNextData()
- {
- return FPosition < FLength ? FData + FPosition : NULL;
- }
- };
- //---------------------------------------------------------------------------
- int TSFTPPacket::FMessageCounter = 0;
- //---------------------------------------------------------------------------
- class TSFTPQueue
- {
- public:
- __fastcall TSFTPQueue(TSFTPFileSystem * AFileSystem)
- {
- FFileSystem = AFileSystem;
- assert(FFileSystem);
- FRequests = new TList();
- FResponses = new TList();
- }
- __fastcall ~TSFTPQueue()
- {
- try
- {
- if (FFileSystem->FTerminal->Active)
- {
- Dispose();
- }
- }
- __finally
- {
- TSFTPPacket * Request;
- TSFTPPacket * Response;
- assert(FResponses->Count == FRequests->Count);
- for (int Index = 0; Index < FRequests->Count; Index++)
- {
- Request = static_cast<TSFTPPacket*>(FRequests->Items[Index]);
- assert(Request);
- delete Request;
- Response = static_cast<TSFTPPacket*>(FResponses->Items[Index]);
- assert(Response);
- delete Response;
- }
- delete FRequests;
- delete FResponses;
- }
- }
- bool __fastcall Init(int QueueLen)
- {
- bool Result = false;
- while ((QueueLen > 0) && SendRequest())
- {
- Result = true;
- QueueLen--;
- }
- return Result;
- }
- void __fastcall Dispose()
- {
- assert(FFileSystem->FTerminal->Active);
- TSFTPPacket * Request;
- TSFTPPacket * Response;
- while (FRequests->Count)
- {
- assert(FResponses->Count);
- Request = static_cast<TSFTPPacket*>(FRequests->Items[0]);
- assert(Request);
- Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
- assert(Response);
- try
- {
- FFileSystem->ReceiveResponse(Request, Response);
- }
- catch(Exception & E)
- {
- if (FFileSystem->FTerminal->Active)
- {
- FFileSystem->FTerminal->LogEvent("Error while disposing the SFTP queue.");
- HandleExtendedException(&E);
- }
- else
- {
- FFileSystem->FTerminal->LogEvent("Fatal error while disposing the SFTP queue.");
- throw;
- }
- }
- FRequests->Delete(0);
- delete Request;
- FResponses->Delete(0);
- delete Response;
- }
- }
- bool __fastcall ReceivePacket(TSFTPPacket * Packet,
- int ExpectedType = -1, int AllowStatus = -1)
- {
- assert(FRequests->Count);
- bool Result;
- TSFTPPacket * Request = NULL;
- TSFTPPacket * Response = NULL;
- try
- {
- Request = static_cast<TSFTPPacket*>(FRequests->Items[0]);
- FRequests->Delete(0);
- assert(Request);
- Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
- FResponses->Delete(0);
- assert(Response);
- FFileSystem->ReceiveResponse(Request, Response,
- ExpectedType, AllowStatus);
- if (Packet)
- {
- *Packet = *Response;
- }
- Result = SendNext(Response);
- if (Result)
- {
- Result = SendRequest();
- }
- }
- __finally
- {
- delete Request;
- delete Response;
- }
- return Result;
- }
- bool __fastcall Next(int ExpectedType = -1, int AllowStatus = -1)
- {
- return ReceivePacket(NULL, ExpectedType, AllowStatus);
- }
- protected:
- virtual bool __fastcall InitRequest(TSFTPPacket * Request) = 0;
- virtual bool __fastcall SendNext(TSFTPPacket * Request) = 0;
- virtual void __fastcall SendPacket(TSFTPPacket * Packet)
- {
- FFileSystem->SendPacket(Packet);
- }
- protected:
- TList * FRequests;
- TList * FResponses;
- TSFTPFileSystem * FFileSystem;
- private:
- bool __fastcall SendRequest()
- {
- TSFTPPacket * Request = NULL;
- try
- {
- Request = new TSFTPPacket();
- if (!InitRequest(Request))
- {
- delete Request;
- Request = NULL;
- }
- }
- catch(...)
- {
- delete Request;
- throw;
- }
- if (Request != NULL)
- {
- TSFTPPacket * Response = new TSFTPPacket();
- FRequests->Add(Request);
- FResponses->Add(Response);
- SendPacket(Request);
- FFileSystem->ReserveResponse(Request, Response);
- }
- return (Request != NULL);
- }
- };
- //---------------------------------------------------------------------------
- class TSFTPTransferQueue : public TSFTPQueue
- {
- public:
- TSFTPTransferQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
- {
- }
- protected:
- __int64 FTransfered;
- AnsiString FHandle;
- unsigned long FBlockSize;
- };
- //---------------------------------------------------------------------------
- class TSFTPDownloadQueue : public TSFTPTransferQueue
- {
- public:
- TSFTPDownloadQueue(TSFTPFileSystem * AFileSystem) :
- TSFTPTransferQueue(AFileSystem)
- {
- }
- bool __fastcall Init(int QueueLen, const AnsiString AHandle,
- unsigned long ABlockSize, __int64 ATransfered)
- {
- FHandle = AHandle;
- FBlockSize = ABlockSize;
- FTransfered = ATransfered;
- return TSFTPTransferQueue::Init(QueueLen);
- }
- void __fastcall InitFillGapRequest(__int64 Offset, unsigned long Missing,
- TSFTPPacket * Packet)
- {
- InitRequest(Packet, Offset, Missing);
- }
- protected:
- virtual bool __fastcall InitRequest(TSFTPPacket * Request)
- {
- InitRequest(Request, FTransfered, FBlockSize);
- FTransfered += FBlockSize;
- return true;
- }
- void __fastcall InitRequest(TSFTPPacket * Request, __int64 Offset,
- unsigned long Size)
- {
- Request->ChangeType(SSH_FXP_READ);
- Request->AddString(FHandle);
- Request->AddInt64(Offset);
- Request->AddCardinal(Size);
- }
- virtual bool __fastcall SendNext(TSFTPPacket * Request)
- {
- return (Request->Type == SSH_FXP_DATA);
- }
- };
- //---------------------------------------------------------------------------
- class TSFTPUploadQueue : public TSFTPTransferQueue
- {
- public:
- TSFTPUploadQueue(TSFTPFileSystem * AFileSystem) :
- TSFTPTransferQueue(AFileSystem)
- {
- FFile = NULL;
- OperationProgress = NULL;
- FLastBlockSize = 0;
- }
- bool __fastcall Init(int QueueLen, const AnsiString AFileName,
- HANDLE AFile, TFileOperationProgressType * AOperationProgress,
- const AnsiString AHandle, unsigned long ABlockSize, __int64 ATransfered)
- {
- FFileName = AFileName;
- FFile = AFile;
- OperationProgress = AOperationProgress;
- FHandle = AHandle;
- FBlockSize = ABlockSize;
- FTransfered = ATransfered;
- return TSFTPTransferQueue::Init(QueueLen);
- }
- protected:
- virtual bool __fastcall InitRequest(TSFTPPacket * Request)
- {
- TTerminal * FTerminal = FFileSystem->FTerminal;
- // Buffer for one block of data
- TFileBuffer BlockBuf;
- FILE_OPERATION_LOOP(FMTLOAD(READ_ERROR, (FFileName)),
- BlockBuf.LoadFile(FFile, FBlockSize, false);
- );
- bool Result = (BlockBuf.Size != 0);
- if (Result)
- {
- OperationProgress->AddLocalyUsed(BlockBuf.Size);
- // We do ASCII transfer: convert EOL of current block
- if (OperationProgress->AsciiTransfer)
- {
- __int64 PrevBufSize = BlockBuf.Size;
- BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
- FFileSystem->GetEOL(), cpRemoveCtrlZ);
- // update transfer size with difference arised from EOL conversion
- OperationProgress->SetTransferSize(OperationProgress->TransferSize -
- PrevBufSize + BlockBuf.Size);
- }
- Request->ChangeType(SSH_FXP_WRITE);
- Request->AddString(FHandle);
- Request->AddInt64(FTransfered);
- Request->AddData(BlockBuf.Data, BlockBuf.Size);
- FLastBlockSize = BlockBuf.Size;
- FTransfered += BlockBuf.Size;
- }
- return Result;
- }
- virtual void __fastcall SendPacket(TSFTPPacket * Packet)
- {
- TSFTPTransferQueue::SendPacket(Packet);
- OperationProgress->AddTransfered(FLastBlockSize);
- }
- virtual bool __fastcall SendNext(TSFTPPacket * Request)
- {
- return true;
- }
- private:
- HANDLE FFile;
- TFileOperationProgressType * OperationProgress;
- AnsiString FFileName;
- unsigned long FLastBlockSize;
- };
- //---------------------------------------------------------------------------
- #pragma warn .inl
- //---------------------------------------------------------------------------
- class TSFTPBusy
- {
- public:
- __fastcall TSFTPBusy(TSFTPFileSystem * FileSystem)
- {
- FFileSystem = FileSystem;
- assert(FFileSystem != NULL);
- FFileSystem->BusyStart();
- }
- __fastcall ~TSFTPBusy()
- {
- FFileSystem->BusyEnd();
- }
- private:
- TSFTPFileSystem * FFileSystem;
- };
- //===========================================================================
- struct TOpenRemoteFileParams
- {
- int LocalFileAttrs;
- AnsiString RemoteFileName;
- TFileOperationProgressType * OperationProgress;
- const TCopyParamType * CopyParam;
- int Params;
- bool Resume;
- TSFTPOverwriteMode OverwriteMode;
- __int64 DestFileSize; // output
- AnsiString RemoteFileHandle; // output
- TOverwriteFileParams * FileParams;
- };
- //---------------------------------------------------------------------------
- struct TSinkFileParams
- {
- AnsiString TargetDir;
- const TCopyParamType * CopyParam;
- int Params;
- TFileOperationProgressType * OperationProgress;
- bool Skipped;
- int Level;
- };
- //===========================================================================
- __fastcall TSFTPFileSystem::TSFTPFileSystem(TTerminal * ATerminal):
- TCustomFileSystem(ATerminal)
- {
- FPacketReservations = new TList();
- FPacketNumbers = VarArrayCreate(OPENARRAY(int, (0, 1)), varInteger);
- FPreviousLoggedPacket = 0;
- FNotLoggedPackets = 0;
- FBusy = 0;
- FAvoidBusy = false;
- FExtensions = new TStringList();
- }
- //---------------------------------------------------------------------------
- __fastcall TSFTPFileSystem::~TSFTPFileSystem()
- {
- delete FPacketReservations;
- delete FExtensions;
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::GetProtocolName() const
- {
- return FMTLOAD(SFTP_PROTOCOL_NAME, (FVersion));
- }
- //---------------------------------------------------------------------------
- bool __fastcall TSFTPFileSystem::IsCapable(int Capability) const
- {
- assert(FTerminal);
- switch (Capability) {
- case fcUserGroupListing:
- case fcAnyCommand:
- case fcHardLink:
- return false;
- case fcOwnerChanging:
- case fcGroupChanging:
- return (FVersion >= 4);
- case fcSymbolicLink:
- case fcResolveSymlink:
- return (FVersion >= 3);
- case fcModeChanging:
- return true;
- case fcTextMode:
- return (FVersion >= 4) ||
- strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0;
- case fcNativeTextMode:
- return (FVersion >= 4);
- case fcRename:
- return (FVersion >= 2);
- default:
- assert(false);
- return false;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::KeepAlive()
- {
- TSFTPPacket Packet(SSH_FXP_REALPATH);
- Packet.AddString("/");
- SendPacketAndReceiveResponse(&Packet, &Packet);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::AdditionalInfo(TStrings * AdditionalInfo,
- bool Initial)
- {
- if (Initial)
- {
- if (!IsCapable(fcRename))
- {
- AdditionalInfo->Add(LoadStr(FS_RENAME_NOT_SUPPORTED));
- AdditionalInfo->Add("");
- }
- if (FExtensions->Count > 0)
- {
- AnsiString Name;
- AnsiString Value;
- AnsiString Line;
- AdditionalInfo->Add(LoadStr(SFTP_EXTENSION_INFO));
- for (int Index = 0; Index < FExtensions->Count; Index++)
- {
- AnsiString Name = FExtensions->Names[Index];
- AnsiString Value = FExtensions->Values[Name];
- AnsiString Line;
- if (Value.IsEmpty())
- {
- Line = Name;
- }
- else
- {
- if (!IsDisplayableStr(Value))
- {
- Value = "0x" + StrToHex(Value);
- }
- Line = FORMAT("%s=%s", (Name, Value));
- }
- AdditionalInfo->Add(FORMAT(" %s", (Line)));;
- }
- }
- else
- {
- AdditionalInfo->Add(LoadStr(SFTP_NO_EXTENSION_INFO));
- }
- }
- }
- //---------------------------------------------------------------------------
- struct TUnicodeEmitParams
- {
- WideString Buffer;
- int Pos;
- int Len;
- };
- //---------------------------------------------------------------------------
- extern "C" void UnicodeEmit(void * AParams, long int Output)
- {
- if (Output == 0xFFFFL) // see Putty's charset\internal.h
- {
- throw Exception(LoadStr(DECODE_UTF_ERROR));
- }
- TUnicodeEmitParams * Params = (TUnicodeEmitParams *)AParams;
- if (Params->Pos >= Params->Len)
- {
- Params->Len += 50;
- Params->Buffer.SetLength(Params->Len);
- }
- Params->Buffer[Params->Pos + 1] = (wchar_t)Output;
- Params->Pos++;
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::DecodeUTF(const AnsiString UTF)
- {
- charset_state State;
- char * Str;
- TUnicodeEmitParams Params;
- AnsiString Result;
- State.s0 = 0;
- Str = UTF.c_str();
- Params.Pos = 0;
- Params.Len = UTF.Length();
- Params.Buffer.SetLength(Params.Len);
- while (*Str)
- {
- read_utf8(NULL, (unsigned char)*Str, &State, UnicodeEmit, &Params);
- Str++;
- }
- Params.Buffer.SetLength(Params.Pos);
- return Params.Buffer;
- }
- //---------------------------------------------------------------------------
- inline void __fastcall TSFTPFileSystem::BusyStart()
- {
- if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
- {
- Busy(true);
- }
- FBusy++;
- assert(FBusy < 10);
- }
- //---------------------------------------------------------------------------
- inline void __fastcall TSFTPFileSystem::BusyEnd()
- {
- assert(FBusy > 0);
- FBusy--;
- if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
- {
- Busy(false);
- }
- }
- //---------------------------------------------------------------------------
- unsigned long __fastcall TSFTPFileSystem::MaxTransferBlockSize(unsigned long Overhead)
- {
- unsigned long MaxPacketSize = FTerminal->MaxPacketSize();
- unsigned long Result = TFileOperationProgressType::StaticBlockSize();
- if (MaxPacketSize > 0)
- {
- MaxPacketSize -= 4 + 1 + Overhead;
- if (Result > MaxPacketSize)
- {
- Result = MaxPacketSize;
- }
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
- {
- BusyStart();
- try
- {
- if (FTerminal->IsLogging())
- {
- if ((FPreviousLoggedPacket != SSH_FXP_READ &&
- FPreviousLoggedPacket != SSH_FXP_WRITE) ||
- (Packet->Type != FPreviousLoggedPacket))
- {
- if (FNotLoggedPackets)
- {
- FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
- (FNotLoggedPackets)));
- FNotLoggedPackets = 0;
- }
- FTerminal->Log->Add(llInput, FORMAT("Type: %s, Size: %d, Number: %d",
- (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
- FPreviousLoggedPacket = Packet->Type;
- }
- else
- {
- FNotLoggedPackets++;
- }
- }
- char LenBuf[4];
- PUT_32BIT(LenBuf, Packet->Length);
- FTerminal->Send(LenBuf, sizeof(LenBuf));
- FTerminal->Send(Packet->Data, Packet->Length);
- }
- __finally
- {
- BusyEnd();
- }
- }
- //---------------------------------------------------------------------------
- unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
- int AllowStatus)
- {
- unsigned long Code = Packet->GetCardinal();
- static int Messages[] = {
- SFTP_STATUS_OK,
- SFTP_STATUS_EOF,
- SFTP_STATUS_NO_SUCH_FILE,
- SFTP_STATUS_PERMISSION_DENIED,
- SFTP_STATUS_FAILURE,
- SFTP_STATUS_BAD_MESSAGE,
- SFTP_STATUS_NO_CONNECTION,
- SFTP_STATUS_CONNECTION_LOST,
- SFTP_STATUS_OP_UNSUPPORTED,
- SFTP_STATUS_INVALID_HANDLE,
- SFTP_STATUS_NO_SUCH_PATH,
- SFTP_STATUS_FILE_ALREADY_EXISTS,
- SFTP_STATUS_WRITE_PROTECT,
- SFTP_STATUS_NO_MEDIA,
- };
- int Message;
- if ((AllowStatus & (0x01 << Code)) == 0)
- {
- if (Code >= sizeof(Messages) / sizeof(*Messages))
- {
- Message = SFTP_STATUS_UNKNOWN;
- }
- else
- {
- Message = Messages[Code];
- }
- AnsiString ServerMessage;
- AnsiString LanguageTag;
- if (FVersion >= 3)
- {
- ServerMessage = DecodeUTF(Packet->GetString());
- LanguageTag = Packet->GetString();
- }
- else
- {
- ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
- }
- if (LanguageTag.IsEmpty())
- {
- LanguageTag = "*";
- }
- if (FTerminal->IsLogging())
- {
- FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d, Message: %d, Server: %s, Language: %s ",
- (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
- }
- AnsiString Error = FMTLOAD(SFTP_ERROR_FORMAT, (LoadStr(Message), int(Code),
- ServerMessage, LanguageTag, int(Packet->RequestType)));
- FTerminal->TerminalError(NULL, Error);
- return 0;
- }
- else
- {
- if (!FNotLoggedPackets || Code)
- {
- FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d", ((int)Code)));
- }
- return Code;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
- {
- for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
- {
- FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
- }
- TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
- if (Packet)
- {
- assert(Packet->ReservedBy == this);
- Packet->ReservedBy = NULL;
- }
- FPacketReservations->Delete(Reservation);
- }
- //---------------------------------------------------------------------------
- int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
- int ExpectedType, int AllowStatus)
- {
- TSFTPBusy Busy(this);
- int Result = SSH_FX_OK;
- int Reservation = FPacketReservations->IndexOf(Packet);
- if (Reservation < 0 || Packet->Capacity == 0)
- {
- bool IsReserved;
- do
- {
- IsReserved = false;
- assert(Packet);
- char LenBuf[5];
- LenBuf[sizeof(LenBuf) - 1] = '\0';
- FTerminal->Receive(LenBuf, sizeof(LenBuf) - 1);
- int Length = GET_32BIT(LenBuf);
- if (Length > SFTP_MAX_PACKET_LEN)
- {
- AnsiString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
- int(Length), SFTP_MAX_PACKET_LEN));
- if (ExpectedType == SSH_FXP_VERSION)
- {
- AnsiString LenString = LenBuf;
- if (!IsDisplayableStr(LenString))
- {
- LenString = "0x" + StrToHex(LenString);
- }
- Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
- (Message, LenString));
- }
- FTerminal->FatalError(Message);
- }
- Packet->Capacity = Length;
- FTerminal->Receive(Packet->Data, Length);
- Packet->DataUpdated(Length);
- if (FTerminal->IsLogging())
- {
- if ((FPreviousLoggedPacket != SSH_FXP_READ &&
- FPreviousLoggedPacket != SSH_FXP_WRITE) ||
- (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA))
- {
- if (FNotLoggedPackets)
- {
- FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
- (FNotLoggedPackets)));
- FNotLoggedPackets = 0;
- }
- FTerminal->Log->Add(llOutput, FORMAT("Type: %s, Size: %d, Number: %d",
- (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
- }
- else
- {
- FNotLoggedPackets++;
- }
- }
- if (Reservation < 0 ||
- Packet->MessageNumber != (unsigned long)FPacketNumbers.GetElement(Reservation))
- {
- TSFTPPacket * ReservedPacket;
- unsigned long MessageNumber;
- for (int Index = 0; Index < FPacketReservations->Count; Index++)
- {
- MessageNumber = FPacketNumbers.GetElement(Index);
- if (MessageNumber == Packet->MessageNumber)
- {
- ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
- IsReserved = true;
- if (ReservedPacket)
- {
- *ReservedPacket = *Packet;
- }
- else
- {
- RemoveReservation(Index);
- }
- break;
- }
- }
- }
- }
- while (IsReserved);
- }
- if (ExpectedType >= 0)
- {
- if (Packet->Type == SSH_FXP_STATUS)
- {
- Result = GotStatusPacket(Packet, (AllowStatus >= 0 ? AllowStatus : asOK));
- }
- else if (ExpectedType != Packet->Type)
- {
- FTerminal->FatalError(FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
- }
- }
- if (Reservation >= 0)
- {
- // order might have changed, when reserved, but not longer needed packet
- // was receive in above loop
- Reservation = FPacketReservations->IndexOf(Packet);
- assert(Reservation >= 0);
- assert(Packet->MessageNumber == (unsigned long)FPacketNumbers.GetElement(Reservation));
- RemoveReservation(Reservation);
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
- TSFTPPacket * Response)
- {
- assert(FPacketReservations->IndexOf(Response) < 0);
- // mark response as not received yet
- Response->Capacity = 0;
- Response->ReservedBy = this;
- FPacketReservations->Add(Response);
- if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
- {
- FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
- }
- FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
- {
- int Reservation = FPacketReservations->IndexOf(Response);
- if (Reservation >= 0)
- {
- FPacketReservations->Items[Reservation] = NULL;
- }
- }
- //---------------------------------------------------------------------------
- int __fastcall TSFTPFileSystem::ReceiveResponse(
- const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
- int AllowStatus)
- {
- int Result;
- unsigned int MessageNumber = Packet->MessageNumber;
- TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
- try
- {
- Result = ReceivePacket(AResponse, ExpectedType, AllowStatus);
- if (MessageNumber != AResponse->MessageNumber)
- {
- FTerminal->FatalError(FMTLOAD(SFTP_MESSAGE_NUMBER,
- ((int)AResponse->MessageNumber, (int)MessageNumber)));
- }
- }
- __finally
- {
- if (!Response) delete AResponse;
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
- const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
- int AllowStatus)
- {
- int Result;
- TSFTPBusy Busy(this);
- SendPacket(Packet);
- Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
- return Result;
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path)
- {
- try
- {
- FTerminal->LogEvent(FORMAT("Getting real path for '%s'",
- (Path)));
- TSFTPPacket Packet(SSH_FXP_REALPATH);
- Packet.AddString(Path);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
- if (Packet.GetCardinal() != 1)
- {
- FTerminal->FatalError(LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
- }
- AnsiString RealDir = Packet.GetString();
- // ignore rest of SSH_FXP_NAME packet
- FTerminal->LogEvent(FORMAT("Real path is '%s'", (RealDir)));
- return RealDir;
- }
- catch(Exception & E)
- {
- if (FTerminal->Active)
- {
- throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
- }
- else
- {
- throw;
- }
- }
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path,
- const AnsiString BaseDir)
- {
- AnsiString APath;
- if (TTerminal::IsAbsolutePath(Path))
- {
- APath = Path;
- }
- else
- {
- if (!Path.IsEmpty())
- {
- // this condition/block was outside (before) current block
- // but it dod not work when Path was empty
- if (!BaseDir.IsEmpty())
- {
- APath = UnixIncludeTrailingBackslash(BaseDir);
- }
- APath = APath + Path;
- }
- if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(".");
- }
- return RealPath(APath);
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::LocalCanonify(const AnsiString & Path)
- {
- // TODO: improve (handle .. etc.)
- if (TTerminal::IsAbsolutePath(Path)) return Path;
- else
- {
- return UnixIncludeTrailingBackslash(FCurrentDirectory) + Path;
- }
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::Canonify(AnsiString Path)
- {
- // inspired by canonify() from PSFTP.C
- AnsiString Result;
- FTerminal->LogEvent(FORMAT("Canonifying: \"%s\"", (Path)));
- Path = LocalCanonify(Path);
- try
- {
- Result = RealPath(Path);
- }
- catch(...)
- {
- if (FTerminal->Active)
- {
- AnsiString APath = UnixExcludeTrailingBackslash(Path);
- AnsiString Name = UnixExtractFileName(APath);
- if (Name == "." || Name == "..")
- {
- Result = Path;
- }
- else
- {
- AnsiString FPath = UnixExtractFilePath(APath);
- try
- {
- Result = RealPath(FPath);
- Result = UnixIncludeTrailingBackslash(Result) + Name;
- }
- catch(...)
- {
- if (FTerminal->Active)
- {
- Result = Path;
- }
- else
- {
- throw;
- }
- }
- }
- }
- else
- {
- throw;
- }
- }
- FTerminal->LogEvent(FORMAT("Canonified: \"%s\"", (Result)));
- return Result;
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::AbsolutePath(AnsiString Path)
- {
- return RealPath(Path, CurrentDirectory);
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::GetHomeDirectory()
- {
- if (FHomeDirectory.IsEmpty())
- {
- FHomeDirectory = RealPath(".");
- }
- return FHomeDirectory;
- }
- //---------------------------------------------------------------------------
- TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
- TRemoteFile * ALinkedByFile)
- {
- TRemoteFile * File = new TRemoteFile(ALinkedByFile);
- try
- {
- File->Terminal = FTerminal;
- Packet->GetFile(File, FVersion);
- }
- catch(...)
- {
- delete File;
- throw;
- }
- return File;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SetCurrentDirectory(AnsiString value)
- {
- assert(false);
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::GetCurrentDirectory()
- {
- return FCurrentDirectory;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::DoStartup()
- {
- TSFTPPacket Packet(SSH_FXP_INIT);
- Packet.AddCardinal(SFTPMaxVersion);
- try
- {
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
- }
- catch(Exception &E)
- {
- FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR));
- }
- FVersion = Packet.GetCardinal();
- FTerminal->LogEvent(FORMAT("SFTP version %d negotiated.", (FVersion)));
- if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
- {
- FTerminal->FatalError(FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
- (FVersion, SFTPMinVersion, SFTPMaxVersion)));
- }
- if (FVersion >= 3)
- {
- FEOL = "\r\n";
- AnsiString ExtensionName;
- AnsiString ExtensionData;
- AnsiString ExtensionDisplayData;
- while (Packet.NextData)
- {
- ExtensionName = Packet.GetString();
- ExtensionData = Packet.GetString();
- ExtensionDisplayData = IsDisplayableStr(ExtensionData) ? ExtensionData :
- "0x" + StrToHex(ExtensionData);
- if (ExtensionName == "newline")
- {
- FEOL = ExtensionData;
- FTerminal->LogEvent(FORMAT("Server requests EOL sequence %s.",
- (ExtensionDisplayData)));
- if (FEOL.Length() < 1 || FEOL.Length() > 2)
- {
- FTerminal->FatalError(FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
- }
- }
- else
- {
- FTerminal->LogEvent(FORMAT("Unknown server extension %s=%s",
- (ExtensionName, ExtensionDisplayData)));
- }
- FExtensions->Values[ExtensionName] = ExtensionData;
- }
- Packet.ChangeType(SSH_FXP_EXTENDED);
- Packet.AddString("[email protected]");
- int Status = SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS,
- asOK | asOpUnsupported);
- if (Status == SSH_FX_OK)
- {
- FTerminal->LogEvent("Server recognises WinSCP.");
- }
- else
- {
- FTerminal->LogEvent("Server does not recognise WinSCP.");
- }
- }
- }
- //---------------------------------------------------------------------------
- char * __fastcall TSFTPFileSystem::GetEOL() const
- {
- if (FVersion >= 4)
- {
- assert(!FEOL.IsEmpty());
- return FEOL.c_str();
- }
- else
- {
- return EOLToStr(FTerminal->SessionData->EOLType);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::LookupUserGroups()
- {
- assert(false);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
- {
- if (!FDirectoryToChangeTo.IsEmpty())
- {
- FCurrentDirectory = FDirectoryToChangeTo;
- FDirectoryToChangeTo = "";
- }
- else if (FCurrentDirectory.IsEmpty())
- {
- // this happens only after startup when default remote directory is not specified
- FCurrentDirectory = GetHomeDirectory();
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::HomeDirectory()
- {
- ChangeDirectory(GetHomeDirectory());
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::TryOpenDirectory(const AnsiString Directory)
- {
- FTerminal->LogEvent(FORMAT("Trying to open directory \"%s\".", (Directory)));
- TSFTPPacket Packet(SSH_FXP_OPENDIR);
- Packet.AddString(Directory);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
- AnsiString Handle = Packet.GetString();
- Packet.ChangeType(SSH_FXP_CLOSE);
- Packet.AddString(Handle);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::ChangeDirectory(const AnsiString Directory)
- {
- AnsiString Path, Current;
- Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
- Path = RealPath(Directory, Current);
- // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
- // for invalid paths on some systems, like CygWin)
- TryOpenDirectory(Path);
- // if open dir did not fail, directory exists -> success.
- FDirectoryToChangeTo = Path;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
- {
- FDirectoryToChangeTo = Directory;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
- {
- assert(FileList && !FileList->Directory.IsEmpty());
- AnsiString Directory = LocalCanonify(FileList->Directory);
- FTerminal->LogEvent(FORMAT("Listing directory \"%s\".", (Directory)));
- // moved before SSH_FXP_OPENDIR, so directory listing does not retain
- // old data (e.g. parent directory) when reading fails
- FileList->Clear();
- TSFTPPacket Packet(SSH_FXP_OPENDIR);
- AnsiString Handle;
- try
- {
- Packet.AddString(Directory);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
- Handle = Packet.GetString();
- }
- catch(...)
- {
- if (FTerminal->Active)
- {
- FileList->AddFile(new TRemoteParentDirectory());
- }
- throw;
- }
- TSFTPPacket Response;
- try
- {
- bool isEOF = false;
- int Total = 0;
- TRemoteFile * File;
- Packet.ChangeType(SSH_FXP_READDIR);
- Packet.AddString(Handle);
- SendPacket(&Packet);
- do
- {
- ReceiveResponse(&Packet, &Response);
- if (Response.Type == SSH_FXP_NAME)
- {
- TSFTPPacket ListingPacket = Response;
- Packet.ChangeType(SSH_FXP_READDIR);
- Packet.AddString(Handle);
- SendPacket(&Packet);
- ReserveResponse(&Packet, &Response);
- unsigned int Count = ListingPacket.GetCardinal();
- for (unsigned long Index = 0; Index < Count; Index++)
- {
- File = LoadFile(&ListingPacket, NULL);
- FileList->AddFile(File);
- Total++;
- }
- if (Count == 0)
- {
- FTerminal->LogEvent("Empty directory listing packet. Aborting directory reading.");
- isEOF = true;
- }
- }
- else if (Response.Type == SSH_FXP_STATUS)
- {
- isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
- }
- else
- {
- FTerminal->FatalError(FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
- }
- }
- while (!isEOF);
- if (Total == 0)
- {
- // Empty file list -> probably "permision denied", we
- // at least get link to parent directory ("..")
- try
- {
- FTerminal->ExceptionOnFail = true;
- try
- {
- File = NULL;
- FTerminal->ReadFile(
- UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
- }
- __finally
- {
- FTerminal->ExceptionOnFail = false;
- }
- }
- catch(Exception &E)
- {
- if (E.InheritsFrom(__classid(EFatal))) throw;
- else File = NULL;
- }
- // on some systems even getting ".." fails, we create dummy ".." instead
- bool Failure = (File == NULL);
- if (Failure)
- {
- File = new TRemoteFile();
- File->FileName = PARENTDIRECTORY;
- File->Modification = Now();
- File->Type = FILETYPE_DIRECTORY;
- }
- assert(File && File->IsParentDirectory);
- FileList->AddFile(File);
- if (Failure)
- {
- throw Exception(FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)));
- }
- }
- }
- __finally
- {
- if (FTerminal->Active)
- {
- Packet.ChangeType(SSH_FXP_CLOSE);
- Packet.AddString(Handle);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
- }
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
- TRemoteFile *& File)
- {
- assert(SymlinkFile && SymlinkFile->IsSymLink);
- assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
- AnsiString FileName = LocalCanonify(SymlinkFile->FileName);
- TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
- ReadLinkPacket.AddString(FileName);
- SendPacket(&ReadLinkPacket);
- ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
- // send second request before reading response to first one
- // (performance benefit)
- TSFTPPacket AttrsPacket(SSH_FXP_STAT);
- AttrsPacket.AddString(FileName);
- SendPacket(&AttrsPacket);
- ReserveResponse(&AttrsPacket, &AttrsPacket);
- ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
- if (ReadLinkPacket.GetCardinal() != 1)
- {
- FTerminal->FatalError(LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
- }
- SymlinkFile->LinkTo = ReadLinkPacket.GetString();
- ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
- File = LoadFile(&AttrsPacket, SymlinkFile);
- File->FileName = UnixExtractFileName(SymlinkFile->FileName);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::ReadFile(const AnsiString FileName,
- TRemoteFile *& File)
- {
- CustomReadFile(FileName, File, SSH_FXP_LSTAT);
- }
- //---------------------------------------------------------------------------
- bool __fastcall TSFTPFileSystem::RemoteFileExists(const AnsiString FullPath,
- TRemoteFile ** File)
- {
- bool Result;
- try
- {
- TRemoteFile * AFile;
- CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, true);
- Result = (AFile != NULL);
- if (Result)
- {
- if (File)
- {
- *File = AFile;
- }
- else
- {
- delete AFile;
- }
- }
- }
- catch(...)
- {
- if (!FTerminal->Active)
- {
- throw;
- }
- Result = false;
- }
- return Result;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::CustomReadFile(const AnsiString FileName,
- TRemoteFile *& File, char Type, TRemoteFile * ALinkedByFile,
- bool AllowNonexistence)
- {
- TSFTPPacket Packet(Type);
- Packet.AddString(LocalCanonify(FileName));
- if (FVersion >= 4)
- {
- Packet.AddCardinal(SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
- SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
- SSH_FILEXFER_ATTR_OWNERGROUP);
- }
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS,
- AllowNonexistence ? asNoSuchFile : -1);
- if (Packet.Type == SSH_FXP_ATTRS)
- {
- File = LoadFile(&Packet, ALinkedByFile);
- File->FileName = UnixExtractFileName(FileName);
- }
- else
- {
- assert(AllowNonexistence);
- File = NULL;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::DeleteFile(const AnsiString FileName,
- const TRemoteFile * File, bool Recursive)
- {
- char Type;
- AnsiString RealFileName = LocalCanonify(FileName);
- if (File && File->IsDirectory && !File->IsSymLink)
- {
- if (Recursive)
- {
- FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Recursive);
- }
- Type = SSH_FXP_RMDIR;
- }
- else
- {
- Type = SSH_FXP_REMOVE;
- }
- TSFTPPacket Packet(Type);
- Packet.AddString(RealFileName);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::RenameFile(const AnsiString FileName,
- const AnsiString NewName)
- {
- TSFTPPacket Packet(SSH_FXP_RENAME);
- AnsiString RealName = LocalCanonify(FileName);
- Packet.AddString(RealName);
- Packet.AddString(UnixExtractFilePath(RealName) + NewName);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::CreateDirectory(const AnsiString DirName,
- const TRemoteProperties * Properties)
- {
- TSFTPPacket Packet(SSH_FXP_MKDIR);
- AnsiString CanonifiedName = Canonify(DirName);
- Packet.AddString(CanonifiedName);
- Packet.AddProperties(Properties, 0, true, FVersion);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::CreateLink(const AnsiString FileName,
- const AnsiString PointTo, bool Symbolic)
- {
- USEDPARAM(Symbolic);
- assert(Symbolic); // only symlinks are supported by SFTP
- assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
- TSFTPPacket Packet(SSH_FXP_SYMLINK);
- Packet.AddString(PointTo);
- Packet.AddString(Canonify(FileName));
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::ChangeFileProperties(const AnsiString FileName,
- const TRemoteFile * /*File*/, const TRemoteProperties * Properties)
- {
- assert(Properties);
- TRemoteFile * File;
- AnsiString RealFileName = LocalCanonify(FileName);
- ReadFile(RealFileName, File);
- try
- {
- assert(File);
- if (File->IsDirectory && !File->IsSymLink && Properties->Recursive)
- {
- FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
- (void*)Properties);
- }
- TSFTPPacket Packet(SSH_FXP_SETSTAT);
- Packet.AddString(RealFileName);
- Packet.AddProperties(Properties, *File->Rights, File->IsDirectory, FVersion);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
- }
- __finally
- {
- delete File;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
- const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/)
- {
- assert(false);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::AnyCommand(const AnsiString /*Command*/)
- {
- assert(false);
- }
- //---------------------------------------------------------------------------
- // transfer protocol
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
- const AnsiString TargetDir, const TCopyParamType * CopyParam,
- int Params, TFileOperationProgressType * OperationProgress,
- bool & DisconnectWhenComplete)
- {
- assert(FilesToCopy && OperationProgress);
- AnsiString FileName, FileNameOnly;
- AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
- int Index = 0;
- while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
- {
- bool Success = false;
- FileName = FilesToCopy->Strings[Index];
- FileNameOnly = ExtractFileName(FileName);
- assert(!FAvoidBusy);
- FAvoidBusy = true;
- try
- {
- try
- {
- if (FTerminal->SessionData->CacheDirectories)
- {
- FTerminal->DirectoryModified(TargetDir, false);
- if (DirectoryExists(FileName))
- {
- FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
- FileNameOnly, true);
- }
- }
- SFTPSource(FileName, FullTargetDir, CopyParam, Params, OperationProgress, 0);
- Success = true;
- }
- catch(EScpSkipFile & E)
- {
- SUSPEND_OPERATION (
- if (!FTerminal->HandleException(&E)) throw;
- );
- }
- }
- __finally
- {
- FAvoidBusy = false;
- OperationProgress->Finish(FileNameOnly, Success, DisconnectWhenComplete);
- }
- Index++;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(const AnsiString FileName,
- bool TargetBiggerThanSource, TFileOperationProgressType * OperationProgress,
- TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
- {
- if (OperationProgress->NoToAll)
- {
- THROW_SKIP_FILE_NULL;
- }
- else
- {
- int Answer;
- SUSPEND_OPERATION
- (
- int Answers = qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll;
- if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
- {
- Answers |= qaAppend;
- }
- Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
- Answers, qpNeverAskAgainCheck);
- );
- if (Answer == qaAppend)
- {
- if (TargetBiggerThanSource || OperationProgress->AsciiTransfer)
- {
- OverwriteMode = omAppend;
- }
- else
- {
- SUSPEND_OPERATION
- (
- Answer = FTerminal->DoQueryUser(FORMAT(LoadStr(APPEND_OR_RESUME), (FileName)),
- qaYes | qaNo | qaCancel, 0);
- );
- if (Answer == qaCancel)
- {
- if (!OperationProgress->Cancel)
- {
- OperationProgress->Cancel = csCancel;
- }
- Abort();
- }
- else
- {
- OverwriteMode = ((Answer == qaYes) ? omAppend : omResume);
- }
- }
- }
- else
- {
- OverwriteMode = omOverwrite;
- switch (Answer) {
- case qaNeverAskAgain:
- FTerminal->Configuration->ConfirmOverwriting = false;
- case qaYesToAll:
- OperationProgress->YesToAll = true;
- case qaYes:
- // file overwriting was confirmed, try to open file
- // second time, now without exclusive flag (SSH_FXF_EXCL)
- break;
- case qaAbort:
- if (!OperationProgress->Cancel)
- {
- OperationProgress->Cancel = csCancel;
- }
- Abort();
- break;
- case qaNoToAll:
- OperationProgress->NoToAll = true;
- case qaNo:
- THROW_SKIP_FILE_NULL;
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- bool TSFTPFileSystem::SFTPConfirmResume(const AnsiString DestFileName,
- bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
- {
- bool ResumeTransfer;
- assert(OperationProgress);
- if (PartialBiggerThanSource)
- {
- int Answer;
- SUSPEND_OPERATION
- (
- Answer = FTerminal->DoQueryUser(
- FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
- qaOK | qaAbort, qpAllowContinueOnError, qtWarning);
- )
- if (Answer == qaAbort)
- {
- if (!OperationProgress->Cancel)
- {
- OperationProgress->Cancel = csCancel;
- }
- Abort();
- }
- ResumeTransfer = false;
- }
- else
- {
- int Answer;
- SUSPEND_OPERATION
- (
- Answer = FTerminal->DoQueryUser(
- FMTLOAD(RESUME_TRANSFER, (DestFileName)), qaYes | qaNo | qaAbort,
- qpAllowContinueOnError);
- );
- switch (Answer) {
- case qaYes:
- ResumeTransfer = true;
- break;
- case qaNo:
- ResumeTransfer = false;
- break;
- case qaAbort:
- if (!OperationProgress->Cancel)
- {
- OperationProgress->Cancel = csCancel;
- }
- Abort();
- break;
- }
- }
- return ResumeTransfer;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
- const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, int Level)
- {
- FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
- OperationProgress->SetFile(FileName);
- TOpenRemoteFileParams OpenParams;
- OpenParams.OverwriteMode = omOverwrite;
- HANDLE File;
- unsigned long MTime, ATime;
- __int64 Size;
- FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
- &File, NULL, &MTime, &ATime, &Size);
- if (OpenParams.LocalFileAttrs & faDirectory)
- {
- SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
- OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Level);
- }
- else
- {
- try
- {
- // File is regular file (not directory)
- assert(File);
- AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
- osLocal, Level == 0);
- AnsiString DestFullName = LocalCanonify(TargetDir + DestFileName);
- AnsiString DestPartinalFullName;
- bool ResumeAllowed;
- bool ResumeTransfer = false;
- bool DestFileExists = false;
- TRights DestRights;
- __int64 ResumeOffset;
- FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
- OperationProgress->SetLocalSize(Size);
- // Suppose same data size to transfer as to read
- // (not true with ASCII transfer)
- OperationProgress->SetTransferSize(OperationProgress->LocalSize);
- OperationProgress->TransferingFile = false;
- // Will we use ASCII of BINARY file tranfer?
- OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName));
- FTerminal->LogEvent(
- AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
- " transfer mode selected.");
- ResumeAllowed = !OperationProgress->AsciiTransfer &&
- CopyParam->AllowResume(OperationProgress->LocalSize) &&
- IsCapable(fcRename);
- OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
- TOverwriteFileParams FileParams;
- FileParams.SourceSize = OperationProgress->LocalSize;
- FileParams.SourceTimestamp = UnixToDateTime(MTime);
- if (ResumeAllowed)
- {
- DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
- FTerminal->LogEvent("Checking existence of file.");
- TRemoteFile * File = new TRemoteFile();
- DestFileExists = RemoteFileExists(DestFullName, &File);
- if (DestFileExists)
- {
- OpenParams.DestFileSize = File->Size;
- FileParams.DestSize = OpenParams.DestFileSize;
- FileParams.DestTimestamp = File->Modification;
- DestRights = *File->Rights;
- delete File;
- File = NULL;
- }
- FTerminal->LogEvent("Checking existence of partially transfered file.");
- if (RemoteFileExists(DestPartinalFullName, &File))
- {
- ResumeOffset = File->Size;
- delete File;
- File = NULL;
- ResumeTransfer = SFTPConfirmResume(DestFileName,
- ResumeOffset > OperationProgress->LocalSize, OperationProgress);
- if (!ResumeTransfer)
- {
- DeleteFile(DestPartinalFullName);
- }
- else
- {
- FTerminal->LogEvent("Resuming file transfer.");
- }
- }
- else
- {
- // partial upload file does not exists, check for full file
- if (DestFileExists && FTerminal->Configuration->ConfirmOverwriting &&
- !OperationProgress->YesToAll && !(Params & cpNoConfirmation))
- {
- SFTPConfirmOverwrite(DestFileName,
- OpenParams.DestFileSize >= OperationProgress->LocalSize,
- OperationProgress, OpenParams.OverwriteMode, &FileParams);
- }
- }
- }
- bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
- OpenParams.RemoteFileName = DoResume ? DestPartinalFullName : DestFullName;
- OpenParams.Resume = DoResume;
- OpenParams.OperationProgress = OperationProgress;
- OpenParams.CopyParam = CopyParam;
- OpenParams.Params = Params;
- OpenParams.FileParams = &FileParams;
- FTerminal->LogEvent("Opening remote file.");
- FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
- FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
- &OpenParams);
- bool TransferFinished = false;
- __int64 DestWriteOffset = 0;
- try
- {
- if (OpenParams.OverwriteMode == omAppend)
- {
- FTerminal->LogEvent("Appending file.");
- DestWriteOffset = OpenParams.DestFileSize;
- }
- else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
- {
- if (OpenParams.OverwriteMode == omResume)
- {
- FTerminal->LogEvent("Resuming file transfer (append style).");
- ResumeOffset = OpenParams.DestFileSize;
- }
- FileSeek((THandle)File, ResumeOffset, 0);
- OperationProgress->AddResumed(ResumeOffset);
- }
- // at end of this block queue is disposed
- {
- TSFTPUploadQueue Queue(this);
- unsigned long BlockSize = MaxTransferBlockSize(4);
- int QueueLen = int(OperationProgress->LocalSize / BlockSize);
- if (QueueLen > FTerminal->SessionData->SFTPUploadQueue)
- {
- QueueLen = FTerminal->SessionData->SFTPUploadQueue;
- }
- if (QueueLen < 1)
- {
- QueueLen = 1;
- }
- bool Initialized;
- Initialized = Queue.Init(QueueLen, FileName, File, OperationProgress,
- OpenParams.RemoteFileHandle, BlockSize,
- DestWriteOffset + OperationProgress->TransferedSize);
- if (Initialized)
- {
- while (Queue.Next(SSH_FXP_STATUS))
- {
- if (OperationProgress->Cancel == csCancel)
- {
- Abort();
- }
- }
- }
- }
- TransferFinished = true;
- }
- __finally
- {
- if (FTerminal->Active)
- {
- SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
- OperationProgress, TransferFinished);
- // delete file if transfer was not completed and resuming is not allowed
- if (!TransferFinished && !DoResume)
- {
- DeleteFile(OpenParams.RemoteFileName);
- }
- }
- }
- // originally this was before CLOSE (last __finally statement),
- // on VShell it failed
- if (DoResume)
- {
- FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
- (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
- if (DestFileExists)
- {
- DeleteFile(DestFullName);
- // DestFileExists used to be set to false here. Had it any reason?
- }
- RenameFile(OpenParams.RemoteFileName, DestFileName);
- );
- }
- bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
- if (CopyParam->PreserveTime || SetRights)
- {
- FILE_OPERATION_LOOP(FMTLOAD(PRESERVE_TIME_PERM_ERROR, (DestFileName)),
- TSFTPPacket Packet(SSH_FXP_SETSTAT);
- Packet.AddString(DestFullName);
- unsigned short Rights = 0;
- if (CopyParam->PreserveRights)
- {
- Rights = CopyParam->RemoteFileRights(OpenParams.LocalFileAttrs);
- }
- else if (DoResume && DestFileExists)
- {
- Rights = DestRights.NumberSet;
- }
- Packet.AddProperties(
- SetRights ? &Rights : NULL, NULL, NULL,
- CopyParam->PreserveTime ? &MTime : NULL,
- CopyParam->PreserveTime ? &ATime : NULL, false, FVersion);
- SendPacketAndReceiveResponse(&Packet, NULL, SSH_FXP_STATUS);
- );
- }
- }
- __finally
- {
- CloseHandle(File);
- }
- }
- /* TODO : Delete also read-only files. */
- /* TODO : Show error message on failure. */
- if (Params & cpDelete) Sysutils::DeleteFile(FileName);
- }
- //---------------------------------------------------------------------------
- int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
- {
- TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
- assert(OpenParams);
- TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
- TSFTPPacket OpenRequest;
- int OpenType;
- bool Confirmed = false;
- bool Success = false;
- do
- {
- try
- {
- OpenType = 0;
- OpenRequest.ChangeType(SSH_FXP_OPEN);
- if (FTerminal->Configuration->ConfirmOverwriting &&
- !Confirmed && !OperationProgress->YesToAll && !OpenParams->Resume &&
- !(OpenParams->Params & cpNoConfirmation) &&
- (OpenParams->OverwriteMode == omOverwrite))
- {
- OpenType |= SSH_FXF_EXCL;
- }
- if (!OpenParams->Resume && (OpenParams->OverwriteMode == omOverwrite))
- {
- OpenType |= SSH_FXF_TRUNC;
- }
- if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
- {
- OpenType |= SSH_FXF_TEXT;
- }
- OpenRequest.AddString(OpenParams->RemoteFileName);
- OpenRequest.AddCardinal(SSH_FXF_WRITE | SSH_FXF_CREAT | OpenType );
- OpenRequest.AddProperties(NULL, NULL, NULL, NULL, NULL, false, FVersion);
-
- SendPacketAndReceiveResponse(&OpenRequest, &OpenRequest, SSH_FXP_HANDLE);
- OpenParams->RemoteFileHandle = OpenRequest.GetString();
- Success = true;
- }
- catch(...)
- {
- if (!Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
- {
- bool TargetBiggerThanSource;
- bool ThrowOriginal = false;
- // When exclusive opening of file fails, try to detect if file exists.
- // When file does not exist, failure was probably caused by 'permission denied'
- // or similar error. In this case throw original exception.
- try
- {
- TRemoteFile * File;
- AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
- ReadFile(RealFileName, File);
- OpenParams->DestFileSize = File->Size;
- if (OpenParams->FileParams != NULL)
- {
- OpenParams->FileParams->DestTimestamp = File->Modification;
- OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
- }
- TargetBiggerThanSource = File->Size >= OperationProgress->LocalSize;
- // file exists (otherwise exception was thrown)
- assert(File);
- SAFE_DESTROY(File);
- }
- catch(...)
- {
- if (!FTerminal->Active)
- {
- throw;
- }
- else
- {
- ThrowOriginal = true;
- }
- }
- if (ThrowOriginal)
- {
- throw;
- }
- // confirmation duplicated in SFTPSource for resumable file transfers.
- SFTPConfirmOverwrite(UnixExtractFileName(OpenParams->RemoteFileName),
- TargetBiggerThanSource, OperationProgress, OpenParams->OverwriteMode,
- OpenParams->FileParams);
- Confirmed = true;
- }
- else
- {
- throw;
- }
- }
- }
- while (!Success);
- return 0;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SFTPCloseRemote(const AnsiString Handle,
- const AnsiString FileName, TFileOperationProgressType * OperationProgress,
- bool TransferFinished)
- {
- // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
- FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)),
- try
- {
- TSFTPPacket CloseRequest(SSH_FXP_CLOSE);
- CloseRequest.AddString(Handle);
- SendPacketAndReceiveResponse(&CloseRequest, NULL, SSH_FXP_STATUS);
- }
- catch(...)
- {
- if (!FTerminal->Active || TransferFinished)
- {
- throw;
- }
- }
- );
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SFTPDirectorySource(const AnsiString DirectoryName,
- const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
- int Params, TFileOperationProgressType * OperationProgress, int Level)
- {
- AnsiString DestDirectoryName = CopyParam->ChangeFileName(
- ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal, Level == 0);
- AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
- OperationProgress->SetFile(DirectoryName);
- bool CreateDir = false;
- try
- {
- TryOpenDirectory(DestFullName);
- }
- catch(...)
- {
- if (FTerminal->Active)
- {
- // opening directory failed, it probably does not exists, try to
- // create it
- CreateDir = true;
- }
- else
- {
- throw;
- }
- }
- if (CreateDir)
- {
- TRemoteProperties Properties;
- if (CopyParam->PreserveRights)
- {
- Properties.Valid = TValidProperties() << vpRights;
- Properties.Rights = CopyParam->RemoteFileRights(Attrs);
- }
- FTerminal->CreateDirectory(DestFullName, &Properties);
- }
- int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
- TSearchRec SearchRec;
- bool FindOK;
- FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
- FindOK = (bool)(FindFirst(DirectoryName + "*.*",
- FindAttrs, SearchRec) == 0);
- );
- while (FindOK && !OperationProgress->Cancel)
- {
- AnsiString FileName = DirectoryName + SearchRec.Name;
- try
- {
- if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
- {
- SFTPSource(FileName, DestFullName, CopyParam, Params, OperationProgress,
- Level + 1);
- }
- }
- catch (EScpSkipFile &E)
- {
- // If ESkipFile occurs, just log it and continue with next file
- SUSPEND_OPERATION (
- // here a message to user was displayed, which was not appropriate
- // when user refused to overwrite the file in subdirectory.
- // hopefuly it won't be missing in other situations.
- if (!FTerminal->HandleException(&E)) throw;
- );
- }
- FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
- FindOK = (FindNext(SearchRec) == 0);
- );
- };
- FindClose(SearchRec);
- /* TODO : Delete also read-only directories. */
- /* TODO : Show error message on failure. */
- if ((Params & cpDelete) && !OperationProgress->Cancel) RemoveDir(DirectoryName);
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
- const AnsiString TargetDir, const TCopyParamType * CopyParam,
- int Params, TFileOperationProgressType * OperationProgress,
- bool & DisconnectWhenComplete)
- {
- assert(FilesToCopy && OperationProgress);
- AnsiString FileName, FileNameOnly;
- AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
- const TRemoteFile * File;
- bool Success;
- int Index = 0;
- while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
- {
- Success = false;
- FileName = FilesToCopy->Strings[Index];
- FileNameOnly = UnixExtractFileName(FileName);
- File = (TRemoteFile *)FilesToCopy->Objects[Index];
- assert(!FAvoidBusy);
- FAvoidBusy = true;
- try
- {
- try
- {
- SFTPSink(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
- Params, OperationProgress, 0);
- Success = true;
- }
- catch(EScpSkipFile & E)
- {
- SUSPEND_OPERATION (
- if (!FTerminal->HandleException(&E)) throw;
- );
- }
- catch(...)
- {
- throw;
- }
- }
- __finally
- {
- FAvoidBusy = false;
- OperationProgress->Finish(FileNameOnly, Success, DisconnectWhenComplete);
- }
- Index++;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SFTPSink(const AnsiString FileName,
- const TRemoteFile * File, const AnsiString TargetDir,
- const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, int Level)
- {
- assert(File);
- FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
- AnsiString OnlyFileName = UnixExtractFileName(FileName);
- OperationProgress->SetFile(OnlyFileName);
- AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
- osRemote, Level == 0);
- AnsiString DestFullName = TargetDir + DestFileName;
- if (File->IsDirectory)
- {
- if (!File->IsSymLink)
- {
- FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
- int Attrs = FileGetAttr(DestFullName);
- if ((Attrs & faDirectory) == 0) EXCEPTION;
- );
- FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
- if (!ForceDirectories(DestFullName)) EXCEPTION;
- );
- TSinkFileParams SinkFileParams;
- SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
- SinkFileParams.CopyParam = CopyParam;
- SinkFileParams.Params = Params;
- SinkFileParams.OperationProgress = OperationProgress;
- SinkFileParams.Skipped = false;
- SinkFileParams.Level = Level + 1;
- FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
- // Do not delete directory if some of its files were skip.
- // Throw "skip file" for the directory to avoid attempt to deletion
- // of any parent directory
- if ((Params & cpDelete) && SinkFileParams.Skipped)
- {
- THROW_SKIP_FILE_NULL;
- }
- }
- else
- {
- // file is symlink to directory, currently do nothing, but it should be
- // reported to user
- }
- }
- else
- {
- FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
- AnsiString DestPartinalFullName;
- bool ResumeAllowed;
- bool ResumeTransfer = false;
- __int64 ResumeOffset;
- // Will we use ASCII of BINARY file tranfer?
- OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(DestFileName));
- FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
- " transfer mode selected.");
- // Suppose same data size to transfer as to write
- // (not true with ASCII transfer)
- OperationProgress->SetTransferSize(File->Size);
- OperationProgress->SetLocalSize(OperationProgress->TransferSize);
- // resume has no sense for drag&drop downloads, because files are downloaded
- // to temp directory, but anyway TTerminal does know this, so the condition
- // placement is currently wrong.
- ResumeAllowed = ((Params & cpDragDrop) == 0) &&
- !OperationProgress->AsciiTransfer &&
- CopyParam->AllowResume(OperationProgress->TransferSize);
- OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
- int Attrs;
- FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
- Attrs = FileGetAttr(DestFullName);
- if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
- );
- OperationProgress->TransferingFile = false; // not set with SFTP protocol
- HANDLE LocalHandle = NULL;
- TStream * FileStream = NULL;
- bool DeleteLocalFile = false;
- AnsiString RemoteHandle;
- AnsiString LocalFileName = DestFullName;
- try
- {
- if (ResumeAllowed)
- {
- DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
- LocalFileName = DestPartinalFullName;
- FTerminal->LogEvent("Checking existence of partially transfered file.");
- if (FileExists(DestPartinalFullName))
- {
- FTerminal->OpenLocalFile(DestPartinalFullName, GENERIC_WRITE,
- NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
- ResumeTransfer = SFTPConfirmResume(DestFileName,
- ResumeOffset > OperationProgress->TransferSize, OperationProgress);
- if (!ResumeTransfer)
- {
- CloseHandle(LocalHandle);
- LocalHandle = NULL;
- Sysutils::DeleteFile(DestPartinalFullName);
- }
- else
- {
- FTerminal->LogEvent("Resuming file transfer.");
- FileSeek((THandle)LocalHandle, ResumeOffset, 0);
- OperationProgress->AddResumed(ResumeOffset);
- }
- }
- }
- if ((Attrs >= 0) && FTerminal->Configuration->ConfirmOverwriting &&
- !OperationProgress->YesToAll && !ResumeTransfer &&
- !(Params & cpNoConfirmation))
- {
- __int64 DestFileSize;
- unsigned long MTime;
- FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
- NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
- FTerminal->LogEvent("Checking existence of file.");
- TSFTPOverwriteMode OverwriteMode;
- TOverwriteFileParams FileParams;
- FileParams.SourceSize = OperationProgress->TransferSize;
- FileParams.SourceTimestamp = File->Modification;
- FileParams.DestTimestamp = UnixToDateTime(MTime);
- FileParams.DestSize = DestFileSize;
- SFTPConfirmOverwrite(DestFileName, (DestFileSize >= OperationProgress->TransferSize),
- OperationProgress, OverwriteMode, &FileParams);
- if (OverwriteMode == omOverwrite)
- {
- // is NULL when overwritting read-only file
- if (LocalHandle)
- {
- CloseHandle(LocalHandle);
- LocalHandle = NULL;
- }
- }
- else
- {
- // is NULL when overwritting read-only file, so following will
- // probably fail anyway
- if (LocalHandle == NULL)
- {
- FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
- NULL, &LocalHandle, NULL, NULL, NULL, NULL);
- }
- ResumeAllowed = false;
- FileSeek((THandle)LocalHandle, DestFileSize, 0);
- if (OverwriteMode == omAppend)
- {
- FTerminal->LogEvent("Appending to file.");
- }
- else
- {
- FTerminal->LogEvent("Resuming file transfer (append style).");
- assert(OverwriteMode == omResume);
- OperationProgress->AddResumed(DestFileSize);
- }
- }
- }
- // if not already opened (resume, append...), create new empty file
- if (!LocalHandle)
- {
- if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress, &LocalHandle))
- {
- THROW_SKIP_FILE_NULL;
- }
- }
- assert(LocalHandle);
- DeleteLocalFile = true;
- FTerminal->LogEvent("Opening remote file.");
- FILE_OPERATION_LOOP (FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)),
- TSFTPPacket Packet;
- Packet.ChangeType(SSH_FXP_OPEN);
- Packet.AddString(FileName);
- int OpenType = SSH_FXF_READ;
- if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
- {
- OpenType |= SSH_FXF_TEXT;
- }
- Packet.AddCardinal(OpenType);
- Packet.AddCardinal(0); // no attrs
- if (FVersion >= 4)
- {
- Packet.AddByte(SSH_FILEXFER_TYPE_REGULAR);
- }
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
- RemoteHandle = Packet.GetString();
- );
- FileStream = new THandleStream((THandle)LocalHandle);
- unsigned long BlockSize = MaxTransferBlockSize(
- 4 + 4 + RemoteHandle.Length() + 8);
- // at end of this block queue is disposed
- {
- TSFTPDownloadQueue Queue(this);
- TSFTPPacket DataPacket;
- int QueueLen = int(File->Size / BlockSize) + 1;
- if (QueueLen > FTerminal->SessionData->SFTPDownloadQueue)
- {
- QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
- }
- Queue.Init(QueueLen, RemoteHandle, BlockSize,
- OperationProgress->TransferedSize);
- bool Eof = false;
- bool PrevIncomplete = false;
- int GapFillCount = 0;
- int GapCount = 0;
- unsigned long Missing = 0;
- unsigned long DataLen = 0;
- while (!Eof)
- {
- if (Missing > 0)
- {
- Queue.InitFillGapRequest(OperationProgress->TransferedSize, Missing,
- &DataPacket);
- GapFillCount++;
- SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
- SSH_FXP_DATA, asEOF);
- }
- else
- {
- Queue.ReceivePacket(&DataPacket, SSH_FXP_DATA, asEOF);
- }
- if (DataPacket.Type == SSH_FXP_STATUS)
- {
- // must be SSH_FX_EOF, any other status packet would raise exception
- Eof = true;
- }
- if (!Eof)
- {
- if ((Missing == 0) && PrevIncomplete)
- {
- // This can happen only if last request returned less bytes
- // than expected, but exacly number of bytes missing to last
- // known file size, but actually EOF was not reached.
- // Can happen only when filesize has changed since directory
- // listing and server returns less bytes than requested and
- // fiel has some special file size.
- FTerminal->LogEvent(FORMAT(
- "Received incomplete data packet before end of file, "
- "offset: %s, size: %d, requested: %d",
- (IntToStr(OperationProgress->TransferedSize), int(DataLen),
- int(BlockSize))));
- FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
- }
- // Buffer for one block of data
- TFileBuffer BlockBuf;
- DataLen = DataPacket.GetCardinal();
- PrevIncomplete = false;
- if (Missing > 0)
- {
- assert(DataLen <= Missing);
- Missing -= DataLen;
- }
- else if (DataLen < BlockSize)
- {
- if (OperationProgress->TransferedSize + DataLen !=
- OperationProgress->TransferSize)
- {
- // with native text transfer mode (SFTP>=4), do not bother about
- // getting less than requested, read offset is ignored anyway
- if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
- {
- GapCount++;
- Missing = BlockSize - DataLen;
- }
- }
- else
- {
- PrevIncomplete = true;
- }
- }
- assert(DataLen <= BlockSize);
- BlockBuf.Insert(0, DataPacket.NextData, DataLen);
- OperationProgress->AddTransfered(DataLen);
- if (OperationProgress->AsciiTransfer)
- {
- assert(!ResumeTransfer && !ResumeAllowed);
- unsigned int PrevBlockSize = BlockBuf.Size;
- BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0);
- OperationProgress->SetLocalSize(
- OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
- }
- FILE_OPERATION_LOOP (FMTLOAD(WRITE_ERROR, (LocalFileName)),
- BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
- );
- OperationProgress->AddLocalyUsed(BlockBuf.Size);
- if (OperationProgress->Cancel == csCancel)
- {
- Abort();
- }
- }
- };
- if (GapCount > 0)
- {
- FTerminal->LogEvent(FORMAT(
- "%d requests to fill %d data gaps were issued.",
- (GapFillCount, GapCount)));
- }
- }
- if (CopyParam->PreserveTime)
- {
- FILETIME AcTime = DateTimeToFileTime(File->LastAccess);
- FILETIME WrTime = DateTimeToFileTime(File->Modification);
- SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
- }
- CloseHandle(LocalHandle);
- LocalHandle = NULL;
- if (ResumeAllowed)
- {
- FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
- (ExtractFileName(DestPartinalFullName), DestFileName)),
- if (FileExists(DestFullName))
- {
- if (!Sysutils::DeleteFile(DestFullName)) EXCEPTION;
- }
- if (!Sysutils::RenameFile(DestPartinalFullName, DestFullName))
- {
- EXCEPTION;
- }
- );
- }
- DeleteLocalFile = false;
- if (Attrs == -1)
- {
- Attrs = faArchive;
- }
- int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
- if ((NewAttrs & Attrs) != NewAttrs)
- {
- FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
- FileSetAttr(DestFullName, Attrs | NewAttrs);
- );
- }
- }
- __finally
- {
- if (LocalHandle) CloseHandle(LocalHandle);
- if (FileStream) delete FileStream;
- if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocalyUsed == 0))
- {
- Sysutils::DeleteFile(LocalFileName);
- }
- if (FTerminal->Active && !RemoteHandle.IsEmpty())
- {
- FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (DestFileName)),
- TSFTPPacket CloseRequest(SSH_FXP_CLOSE);
- CloseRequest.AddString(RemoteHandle);
- SendPacketAndReceiveResponse(&CloseRequest, NULL, SSH_FXP_STATUS);
- );
- }
- }
- }
- if (Params & cpDelete)
- {
- // If file is directory, do not delete it recursively, because it should be
- // empty already. If not, it should not be deleted (some files were
- // skipped or some new files were copied to it, while we were downloading)
- bool Recursive = false;
- FTerminal->DeleteFile(FileName, File, &Recursive);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SFTPSinkFile(AnsiString FileName,
- const TRemoteFile * File, void * Param)
- {
- TSinkFileParams * Params = (TSinkFileParams *)Param;
- assert(Params->OperationProgress);
- try
- {
- SFTPSink(FileName, File, Params->TargetDir, Params->CopyParam,
- Params->Params, Params->OperationProgress, Params->Level);
- }
- catch(EScpSkipFile & E)
- {
- TFileOperationProgressType * OperationProgress = Params->OperationProgress;
- Params->Skipped = true;
- SUSPEND_OPERATION (
- if (!FTerminal->HandleException(&E)) throw;
- );
- if (OperationProgress->Cancel)
- {
- Abort();
- }
- }
- }
|