| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587 |
- //---------------------------------------------------------------------------
- #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_ACL 0x00000040
- #define SSH_FILEXFER_ATTR_OWNERGROUP 0x00000080
- #define SSH_FILEXFER_ATTR_SUBSECOND_TIMES 0x00000100
- #define SSH_FILEXFER_ATTR_BITS 0x00000200
- #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
- #define SSH_FILEXFER_ATTR_COMMON \
- (SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_OWNERGROUP | \
- SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACCESSTIME | \
- SSH_FILEXFER_ATTR_MODIFYTIME)
- #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 SSH_FXF_ACCESS_DISPOSITION 0x00000007
- #define SSH_FXF_CREATE_NEW 0x00000000
- #define SSH_FXF_CREATE_TRUNCATE 0x00000001
- #define SSH_FXF_OPEN_EXISTING 0x00000002
- #define SSH_FXF_OPEN_OR_CREATE 0x00000003
- #define SSH_FXF_TRUNCATE_EXISTING 0x00000004
- #define SSH_FXF_ACCESS_APPEND_DATA 0x00000008
- #define SSH_FXF_ACCESS_APPEND_DATA_ATOMIC 0x00000010
- #define SSH_FXF_ACCESS_TEXT_MODE 0x00000020
- #define SSH_FXF_ACCESS_READ_LOCK 0x00000040
- #define SSH_FXF_ACCESS_WRITE_LOCK 0x00000080
- #define SSH_FXF_ACCESS_DELETE_LOCK 0x00000100
- #define ACE4_READ_DATA 0x00000001
- #define ACE4_LIST_DIRECTORY 0x00000001
- #define ACE4_WRITE_DATA 0x00000002
- #define ACE4_ADD_FILE 0x00000002
- #define ACE4_APPEND_DATA 0x00000004
- #define ACE4_ADD_SUBDIRECTORY 0x00000004
- #define ACE4_READ_NAMED_ATTRS 0x00000008
- #define ACE4_WRITE_NAMED_ATTRS 0x00000010
- #define ACE4_EXECUTE 0x00000020
- #define ACE4_DELETE_CHILD 0x00000040
- #define ACE4_READ_ATTRIBUTES 0x00000080
- #define ACE4_WRITE_ATTRIBUTES 0x00000100
- #define ACE4_DELETE 0x00010000
- #define ACE4_READ_ACL 0x00020000
- #define ACE4_WRITE_ACL 0x00040000
- #define ACE4_WRITE_OWNER 0x00080000
- #define ACE4_SYNCHRONIZE 0x00100000
- #define SSH_FILEXFER_ATTR_FLAGS_HIDDEN 0x00000004
- #define SFTP_MAX_PACKET_LEN 102400
- //---------------------------------------------------------------------------
- #define SFTP_EXT_WINSCP "[email protected]"
- #define SFTP_EXT_OWNER_GROUP "owner-group-query@generic-extensions"
- #define SFTP_EXT_OWNER_GROUP_REPLY "owner-group-query-reply@generic-extensions"
- #define SFTP_EXT_SOFTWARE "software@generic-extensions"
- #define SFTP_EXT_SOFTWARE_OS "Microsoft Windows"
- #define SFTP_EXT_NEWLINE "newline"
- #define SFTP_EXT_SUPPORTED "supported"
- //---------------------------------------------------------------------------
- #define OGQ_LIST_OWNERS 0x01
- #define OGQ_LIST_GROUPS 0x02
- //---------------------------------------------------------------------------
- const int SFTPMinVersion = 0;
- const int SFTPMaxVersion = 5;
- 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;
- const int tfFirstLevel = 0x01;
- const int tfNewDirectory = 0x02;
- //---------------------------------------------------------------------------
- #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 SFTP_PACKET_ALLOC_DELTA 256
- //---------------------------------------------------------------------------
- #pragma warn -inl
- //---------------------------------------------------------------------------
- struct TSFTPSupport
- {
- unsigned int AttributeMask;
- unsigned int AttributeBits;
- unsigned int OpenFlags;
- unsigned int AccessMask;
- unsigned int MaxReadSize;
- TStrings * Extensions;
- };
- //---------------------------------------------------------------------------
- class TSFTPPacket
- {
- public:
- TSFTPPacket()
- {
- Init();
- }
- TSFTPPacket(const TSFTPPacket & Source)
- {
- Init();
- *this = Source;
- }
- TSFTPPacket(unsigned char AType)
- {
- Init();
- ChangeType(AType);
- }
- TSFTPPacket(const char * Source, unsigned int Len)
- {
- Init();
- FLength = Len;
- Capacity = FLength;
- memcpy(Data, Source, Len);
- }
- TSFTPPacket(const AnsiString & Source)
- {
- Init();
- FLength = Source.Length();
- Capacity = FLength;
- memcpy(Data, Source.c_str(), Source.Length());
- }
- ~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 != 1) && (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,
- __int64 * Size, bool IsDirectory, int Version)
- {
- int Flags = 0;
- if (Size != NULL)
- {
- Flags |= SSH_FILEXFER_ATTR_SIZE;
- }
- if ((Owner != NULL) || (Group != NULL))
- {
- Flags |= SSH_FILEXFER_ATTR_OWNERGROUP;
- }
- if (Rights != NULL)
- {
- Flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
- }
- 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 (Size != NULL)
- {
- AddInt64(*Size);
- }
- 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, 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, bool ConsiderDST)
- {
- 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();
- // -:regular, D:directory, L:symlink, S:special, U:unknown
- // O:socket, C:char devide, B:block device, F:fifo
- static char* Types = "-DLSUOCBF";
- 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(), ConsiderDST);
- File->Modification = UnixToDateTime(GetCardinal(), ConsiderDST);
- }
- }
- else
- {
- if (Flags & SSH_FILEXFER_ATTR_ACCESSTIME)
- {
- File->LastAccess = UnixToDateTime((unsigned long)GetInt64(), ConsiderDST);
- if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
- {
- GetCardinal(); // skip access time subseconds
- }
- }
- else
- {
- File->LastAccess = Now();
- }
- 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(), ConsiderDST);
- if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
- {
- GetCardinal(); // skip modification time subseconds
- }
- }
- else
- {
- File->Modification = Now();
- }
- }
- if (Flags & SSH_FILEXFER_ATTR_ACL)
- {
- GetString();
- }
- if (Flags & SSH_FILEXFER_ATTR_BITS)
- {
- assert(Version >= 5);
- unsigned long Bits = GetCardinal();
- if (FLAGSET(Bits, SSH_FILEXFER_ATTR_FLAGS_HIDDEN))
- {
- File->IsHidden = true;
- }
- }
- 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 & TRights::rfAllSpecials);
- if (Version < 4)
- {
- File->Type = (Permissions & TRights::rfDirectory ? FILETYPE_DIRECTORY : '-');
- }
- }
- File->Complete();
- // 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 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 * 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.");
- FFileSystem->FTerminal->DoHandleExtendedException(&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->ChangeTransferSize(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;
- unsigned int Flags;
- };
- //===========================================================================
- __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;
- FSupport = new TSFTPSupport();
- FSupport->Extensions = new TStringList();
- FExtensions = new TStringList();
- }
- //---------------------------------------------------------------------------
- __fastcall TSFTPFileSystem::~TSFTPFileSystem()
- {
- delete FSupport->Extensions;
- delete FSupport;
- 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 fcAnyCommand:
- case fcHardLink:
- return false;
- case fcModeChanging:
- case fcNewerOnlyUpload:
- return true;
- case fcRename:
- return (FVersion >= 2);
- case fcSymbolicLink:
- case fcResolveSymlink:
- return (FVersion >= 3);
- case fcOwnerChanging:
- case fcGroupChanging:
- case fcNativeTextMode:
- return (FVersion >= 4);
- case fcTextMode:
- return (FVersion >= 4) ||
- strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0;
- case fcUserGroupListing:
- return SupportsExtension(SFTP_EXT_OWNER_GROUP);
- default:
- assert(false);
- return false;
- }
- }
- //---------------------------------------------------------------------------
- bool __fastcall TSFTPFileSystem::SupportsExtension(const AnsiString & Extension) const
- {
- return (FSupport->Extensions->IndexOf(Extension) >= 0);
- }
- //---------------------------------------------------------------------------
- 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) ||
- FTerminal->Configuration->LogProtocol)
- {
- 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)));
- if (FTerminal->Configuration->LogProtocol)
- {
- FTerminal->Log->Add(llInput, Packet->Dump());
- }
- 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,
- SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
- SFTP_STATUS_QUOTA_EXCEEDED,
- SFTP_STATUS_UNKNOWN_PRINCIPLE
- };
- 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;
- AnsiString AdditionalInfo;
- if (FVersion >= 3)
- {
- ServerMessage = DecodeUTF(Packet->GetString());
- LanguageTag = Packet->GetString();
- if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPLE))
- {
- while (Packet->NextData != NULL)
- {
- if (!AdditionalInfo.IsEmpty())
- {
- AdditionalInfo += ", ";
- }
- AdditionalInfo += Packet->GetString();
- }
- }
- }
- else
- {
- ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
- }
- 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)));
- }
- if (!LanguageTag.IsEmpty())
- {
- LanguageTag = FORMAT("(%s)", (LanguageTag));
- }
- AnsiString Error = FMTLOAD(SFTP_ERROR_FORMAT, (LoadStr(Message) + AdditionalInfo,
- 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) ||
- FTerminal->Configuration->LogProtocol)
- {
- 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)));
- if (FTerminal->Configuration->LogProtocol)
- {
- FTerminal->Log->Add(llOutput, Packet->Dump());
- }
- }
- 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);
- bool TryParent = false;
- try
- {
- Result = RealPath(Path);
- }
- catch(...)
- {
- if (FTerminal->Active)
- {
- TryParent = true;
- }
- else
- {
- throw;
- }
- }
- if (TryParent)
- {
- 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;
- }
- }
- }
- }
- 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, const AnsiString FileName)
- {
- TRemoteFile * File = new TRemoteFile(ALinkedByFile);
- try
- {
- File->Terminal = FTerminal;
- if (!FileName.IsEmpty())
- {
- File->FileName = FileName;
- }
- Packet->GetFile(File, FVersion, FTerminal->SessionData->ConsiderDST);
- }
- 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);
- int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
- if (MaxVersion > SFTPMaxVersion)
- {
- MaxVersion = SFTPMaxVersion;
- }
- Packet.AddCardinal(MaxVersion);
- 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 == SFTP_EXT_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 if (ExtensionName == SFTP_EXT_SUPPORTED)
- {
- TSFTPPacket SupportedStruct(ExtensionData);
- FSupport->AttributeMask = SupportedStruct.GetCardinal();
- FSupport->AttributeBits = SupportedStruct.GetCardinal();
- FSupport->OpenFlags = SupportedStruct.GetCardinal();
- FSupport->AccessMask = SupportedStruct.GetCardinal();
- FSupport->MaxReadSize = SupportedStruct.GetCardinal();
- AnsiString Extension;
- FSupport->Extensions->Clear();
- while (SupportedStruct.NextData)
- {
- Extension = SupportedStruct.GetString();
- FSupport->Extensions->Add(Extension);
- }
- if (FTerminal->IsLogging())
- {
- FTerminal->LogEvent(FORMAT(
- "Server support information:\n"
- " Attribute mask: %s, Attribute bits: %s, Open flags: %s\n"
- " Access mask: %s, Max read size: %s\n"
- " Extensions (%d)\n",
- (IntToHex(__int64(FSupport->AttributeMask), 4),
- IntToHex(__int64(FSupport->AttributeBits), 4),
- IntToHex(__int64(FSupport->OpenFlags), 4),
- IntToHex(__int64(FSupport->AccessMask), 4),
- IntToStr(__int64(FSupport->MaxReadSize)),
- FSupport->Extensions->Count)));
- for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
- {
- FTerminal->LogEvent(
- FORMAT(" %s", (FSupport->Extensions->Strings[Index])));
- }
- }
- }
- else
- {
- FTerminal->LogEvent(FORMAT("Unknown server extension %s=%s",
- (ExtensionName, ExtensionDisplayData)));
- }
- FExtensions->Values[ExtensionName] = ExtensionData;
- }
- Packet.ChangeType(SSH_FXP_EXTENDED);
- Packet.AddString(SFTP_EXT_WINSCP);
- SendPacket(&Packet);
- ReserveResponse(&Packet, &Packet);
- TSFTPPacket PacketSoftware(SSH_FXP_EXTENDED);
- bool SoftwareExt = SupportsExtension(SFTP_EXT_SOFTWARE);
- if (SoftwareExt)
- {
- PacketSoftware.AddString(SFTP_EXT_SOFTWARE);
- PacketSoftware.AddString(FTerminal->Configuration->ProductName);
- PacketSoftware.AddString(FTerminal->Configuration->ProductVersion);
- PacketSoftware.AddString(FTerminal->Configuration->CompanyName);
- PacketSoftware.AddString(SFTP_EXT_SOFTWARE_OS);
- PacketSoftware.AddString(FTerminal->Configuration->OSVersionStr);
- SendPacket(&PacketSoftware);
- ReserveResponse(&PacketSoftware, &PacketSoftware);
- }
- int Status = ReceiveResponse(&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.");
- }
- if (SoftwareExt)
- {
- ReceiveResponse(&PacketSoftware, &PacketSoftware, SSH_FXP_EXTENDED_REPLY,
- asOpUnsupported);
- if ((PacketSoftware.Type != SSH_FXP_EXTENDED_REPLY) ||
- (PacketSoftware.GetString() != SFTP_EXT_SOFTWARE))
- {
- FTerminal->LogEvent(FORMAT("Invalid response to %s", (SFTP_EXT_SOFTWARE)));
- }
- else
- {
- AnsiString Software(PacketSoftware.GetString());
- AnsiString Vendor(PacketSoftware.GetString());
- AnsiString Version(PacketSoftware.GetString());
- AnsiString OS(PacketSoftware.GetString());
- AnsiString OSVersion(PacketSoftware.GetString());
- FTerminal->LogEvent(FORMAT("Server software: %s %s by %s",
- (Software, Version, Vendor)));
- FTerminal->LogEvent(FORMAT("Server OS: %s %s",
- (OS, OSVersion)));
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- char * __fastcall TSFTPFileSystem::GetEOL() const
- {
- if (FVersion >= 4)
- {
- assert(!FEOL.IsEmpty());
- return FEOL.c_str();
- }
- else
- {
- return EOLToStr(FTerminal->SessionData->EOLType);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::LookupUsersGroups()
- {
- assert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
- TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
- TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
- TSFTPPacket * Packet;
- TUsersGroupsList * List;
- TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
- TUsersGroupsList * Lists[] = { FTerminal->FUsers, FTerminal->FGroups };
- char ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
- for (int Index = 0; Index < LENOF(Packets); Index++)
- {
- Packet = Packets[Index];
- Packet->AddString(SFTP_EXT_OWNER_GROUP);
- Packet->AddByte(ListTypes[Index]);
- SendPacket(Packet);
- ReserveResponse(Packet, Packet);
- }
- for (int Index = 0; Index < LENOF(Packets); Index++)
- {
- Packet = Packets[Index];
- ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
- if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
- (Packet->GetString() != SFTP_EXT_OWNER_GROUP_REPLY))
- {
- FTerminal->LogEvent(FORMAT("Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
- }
- else
- {
- List = Lists[Index];
- unsigned long Count = Packet->GetCardinal();
- List->BeginUpdate();
- try
- {
- List->Clear();
- for (unsigned long Item = 0; Item < Count; Item++)
- {
- List->Add(Packet->GetString());
- }
- }
- __finally
- {
- List->EndUpdate();
- }
- }
- }
- }
- //---------------------------------------------------------------------------
- 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(UnixExcludeTrailingBackslash(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;
- Directory = UnixExcludeTrailingBackslash(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 TRemoteParentDirectory();
- }
- 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);
- if (FVersion >= 4)
- {
- AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
- }
- 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);
- // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
- File = LoadFile(&AttrsPacket, SymlinkFile,
- UnixExtractFileName(SymlinkFile->LinkTo));
- }
- //---------------------------------------------------------------------------
- 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, 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);
- AnsiString TargetName;
- if (UnixExtractFilePath(NewName).IsEmpty())
- {
- // rename case (TTerminal::RenameFile)
- TargetName = UnixExtractFilePath(RealName) + NewName;
- }
- else
- {
- // move case (TTerminal::MoveFiles)
- TargetName = NewName;
- }
- Packet.AddString(TargetName);
- if (FVersion >= 5)
- {
- Packet.AddCardinal(0);
- }
- 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(NULL, 0, true, FVersion);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
- // explicitly set permissions after directory creation,
- // permissions specified in SSH_FXP_MKDIR are ignored at least by OpenSSH
- Packet.ChangeType(SSH_FXP_SETSTAT);
- 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);
- bool Buggy = (FTerminal->SessionData->SFTPSymlinkBug == asOn) ||
- ((FTerminal->SessionData->SFTPSymlinkBug == asAuto) &&
- (FTerminal->SshImplementation.Pos("OpenSSH") == 1));
- if (!Buggy)
- {
- Packet.AddString(Canonify(FileName));
- Packet.AddString(PointTo);
- }
- else
- {
- FTerminal->LogEvent("We believe the server has SFTP symlink bug");
- 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,
- tfFirstLevel);
- Success = true;
- }
- catch(EScpSkipFile & E)
- {
- SUSPEND_OPERATION (
- if (!FTerminal->HandleException(&E)) throw;
- );
- }
- }
- __finally
- {
- FAvoidBusy = false;
- OperationProgress->Finish(FileName, 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 | qaAll;
- if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
- {
- Answers |= qaRetry;
- }
- TQueryButtonAlias Aliases[2];
- Aliases[0].Button = qaRetry;
- Aliases[0].Alias = LoadStr(APPEND_BUTTON);
- Aliases[1].Button = qaAll;
- Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
- TQueryParams Params(qpNeverAskAgainCheck);
- Params.Aliases = Aliases;
- Params.AliasesCount = LENOF(Aliases);
- Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
- Answers, &Params,
- OperationProgress->Side == osLocal ? osRemote : osLocal,
- OperationProgress);
- );
- if (Answer == qaRetry)
- {
- 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 qaAbort:
- if (!OperationProgress->Cancel)
- {
- OperationProgress->Cancel = csCancel;
- }
- Abort();
- break;
- 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
- (
- TQueryParams Params(qpAllowContinueOnError);
- Answer = FTerminal->DoQueryUser(
- FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
- qaOK | qaAbort, &Params, qtWarning);
- )
- if (Answer == qaAbort)
- {
- if (!OperationProgress->Cancel)
- {
- OperationProgress->Cancel = csCancel;
- }
- Abort();
- }
- ResumeTransfer = false;
- }
- else if (FTerminal->Configuration->ConfirmResume)
- {
- int Answer;
- SUSPEND_OPERATION
- (
- TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck);
- Answer = FTerminal->DoQueryUser(
- FMTLOAD(RESUME_TRANSFER, (DestFileName)), qaYes | qaNo | qaAbort,
- &Params);
- );
- switch (Answer) {
- case qaNeverAskAgain:
- FTerminal->Configuration->ConfirmResume = false;
- case qaYes:
- ResumeTransfer = true;
- break;
- case qaNo:
- ResumeTransfer = false;
- break;
- case qaAbort:
- if (!OperationProgress->Cancel)
- {
- OperationProgress->Cancel = csCancel;
- }
- Abort();
- break;
- }
- }
- else
- {
- ResumeTransfer = true;
- }
- return ResumeTransfer;
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
- const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, unsigned int Flags)
- {
- AnsiString OnlyFileName = ExtractFileName(FileName);
- if (FLAGCLEAR(Params, cpDelete) &&
- !CopyParam->AllowTransfer(OnlyFileName))
- {
- FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
- THROW_SKIP_FILE_NULL;
- }
- 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, Flags);
- }
- else
- {
- try
- {
- // File is regular file (not directory)
- assert(File);
- AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
- osLocal, FLAGSET(Flags, tfFirstLevel));
- 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 &&
- FLAGCLEAR(Flags, tfNewDirectory) &&
- CopyParam->AllowResume(OperationProgress->LocalSize) &&
- IsCapable(fcRename);
- OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
- TOverwriteFileParams FileParams;
- FileParams.SourceSize = OperationProgress->LocalSize;
- FileParams.SourceTimestamp = UnixToDateTime(MTime,
- FTerminal->SessionData->ConsiderDST);
- 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 &&
- (FLAGSET(Params, cpNewerOnly) ||
- (FTerminal->Configuration->ConfirmOverwriting &&
- !OperationProgress->YesToAll && FLAGCLEAR(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)
- {
- 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,
- 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);
- }
- //---------------------------------------------------------------------------
- AnsiString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
- const AnsiString & FileName, unsigned int OpenType, __int64 Size)
- {
- TSFTPPacket Packet(SSH_FXP_OPEN);
- Packet.AddString(FileName);
- if (FVersion < 5)
- {
- Packet.AddCardinal(OpenType);
- }
- else
- {
- unsigned long Access =
- FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
- FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
- unsigned long Flags;
- if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
- {
- Flags = SSH_FXF_CREATE_NEW;
- }
- else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
- {
- Flags = SSH_FXF_CREATE_TRUNCATE;
- }
- else if (FLAGSET(OpenType, SSH_FXF_CREAT))
- {
- Flags = SSH_FXF_OPEN_OR_CREATE;
- }
- else
- {
- Flags = SSH_FXF_OPEN_EXISTING;
- }
- Flags |=
- FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
- FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
- Packet.AddCardinal(Access);
- Packet.AddCardinal(Flags);
- }
- Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
- Size >= 0 ? &Size : NULL, false, FVersion);
- SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
- return Packet.GetString();
- }
- //---------------------------------------------------------------------------
- int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
- {
- TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
- assert(OpenParams);
- TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
- int OpenType;
- bool Confirmed = false;
- bool Success = false;
- do
- {
- try
- {
- OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
- 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;
- }
- OpenParams->RemoteFileHandle = SFTPOpenRemoteFile(
- OpenParams->RemoteFileName, OpenType, OperationProgress->LocalSize);
- 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, unsigned int Flags)
- {
- AnsiString DestDirectoryName = CopyParam->ChangeFileName(
- ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
- FLAGSET(Flags, tfFirstLevel));
- 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);
- Flags |= tfNewDirectory;
- }
- 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,
- Flags & ~tfFirstLevel);
- }
- }
- 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];
- File = (TRemoteFile *)FilesToCopy->Objects[Index];
- assert(!FAvoidBusy);
- FAvoidBusy = true;
- try
- {
- try
- {
- SFTPSink(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
- Params, OperationProgress, tfFirstLevel);
- Success = true;
- }
- catch(EScpSkipFile & E)
- {
- SUSPEND_OPERATION (
- if (!FTerminal->HandleException(&E)) throw;
- );
- }
- catch(...)
- {
- throw;
- }
- }
- __finally
- {
- FAvoidBusy = false;
- OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
- }
- Index++;
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TSFTPFileSystem::SFTPSink(const AnsiString FileName,
- const TRemoteFile * File, const AnsiString TargetDir,
- const TCopyParamType * CopyParam, int Params,
- TFileOperationProgressType * OperationProgress, unsigned int Flags)
- {
- AnsiString OnlyFileName = UnixExtractFileName(FileName);
- if (FLAGCLEAR(Params, cpDelete) &&
- !CopyParam->AllowTransfer(OnlyFileName))
- {
- FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
- THROW_SKIP_FILE_NULL;
- }
- assert(File);
- FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
- OperationProgress->SetFile(OnlyFileName);
- AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
- osRemote, FLAGSET(Flags, tfFirstLevel));
- 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.Flags = Flags & ~tfFirstLevel;
- 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) && !ResumeTransfer &&
- (FLAGSET(Params, cpNewerOnly) ||
- (FTerminal->Configuration->ConfirmOverwriting &&
- !OperationProgress->YesToAll &&
- FLAGCLEAR(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,
- FTerminal->SessionData->ConsiderDST);
- 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)),
- int OpenType = SSH_FXF_READ;
- if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
- {
- OpenType |= SSH_FXF_TEXT;
- }
- RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
- );
- 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,
- FTerminal->SessionData->ConsiderDST);
- FILETIME WrTime = DateTimeToFileTime(File->Modification,
- FTerminal->SessionData->ConsiderDST);
- 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->Flags);
- }
- catch(EScpSkipFile & E)
- {
- TFileOperationProgressType * OperationProgress = Params->OperationProgress;
- Params->Skipped = true;
- SUSPEND_OPERATION (
- if (!FTerminal->HandleException(&E)) throw;
- );
- if (OperationProgress->Cancel)
- {
- Abort();
- }
- }
- }
|