SftpFileSystem.cpp 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SftpFileSystem.h"
  5. #include "PuttyIntf.h"
  6. #include "Common.h"
  7. #include "Interface.h"
  8. #include "Terminal.h"
  9. #include "TextsCore.h"
  10. #include "HelpCore.h"
  11. #include <memory>
  12. //---------------------------------------------------------------------------
  13. #pragma package(smart_init)
  14. //---------------------------------------------------------------------------
  15. #define FILE_OPERATION_LOOP_EX(ALLOW_SKIP, MESSAGE, OPERATION) \
  16. FILE_OPERATION_LOOP_CUSTOM(FTerminal, ALLOW_SKIP, MESSAGE, OPERATION)
  17. //---------------------------------------------------------------------------
  18. #define SSH_FX_OK 0
  19. #define SSH_FX_EOF 1
  20. #define SSH_FX_NO_SUCH_FILE 2
  21. #define SSH_FX_OP_UNSUPPORTED 8
  22. #define SSH_FXP_INIT 1
  23. #define SSH_FXP_VERSION 2
  24. #define SSH_FXP_OPEN 3
  25. #define SSH_FXP_CLOSE 4
  26. #define SSH_FXP_READ 5
  27. #define SSH_FXP_WRITE 6
  28. #define SSH_FXP_LSTAT 7
  29. #define SSH_FXP_FSTAT 8
  30. #define SSH_FXP_SETSTAT 9
  31. #define SSH_FXP_FSETSTAT 10
  32. #define SSH_FXP_OPENDIR 11
  33. #define SSH_FXP_READDIR 12
  34. #define SSH_FXP_REMOVE 13
  35. #define SSH_FXP_MKDIR 14
  36. #define SSH_FXP_RMDIR 15
  37. #define SSH_FXP_REALPATH 16
  38. #define SSH_FXP_STAT 17
  39. #define SSH_FXP_RENAME 18
  40. #define SSH_FXP_READLINK 19
  41. #define SSH_FXP_SYMLINK 20
  42. #define SSH_FXP_STATUS 101
  43. #define SSH_FXP_HANDLE 102
  44. #define SSH_FXP_DATA 103
  45. #define SSH_FXP_NAME 104
  46. #define SSH_FXP_ATTRS 105
  47. #define SSH_FXP_EXTENDED 200
  48. #define SSH_FXP_EXTENDED_REPLY 201
  49. #define SSH_FXP_ATTRS 105
  50. #define SSH_FILEXFER_ATTR_SIZE 0x00000001
  51. #define SSH_FILEXFER_ATTR_UIDGID 0x00000002
  52. #define SSH_FILEXFER_ATTR_PERMISSIONS 0x00000004
  53. #define SSH_FILEXFER_ATTR_ACMODTIME 0x00000008
  54. #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
  55. #define SSH_FILEXFER_ATTR_ACCESSTIME 0x00000008
  56. #define SSH_FILEXFER_ATTR_CREATETIME 0x00000010
  57. #define SSH_FILEXFER_ATTR_MODIFYTIME 0x00000020
  58. #define SSH_FILEXFER_ATTR_ACL 0x00000040
  59. #define SSH_FILEXFER_ATTR_OWNERGROUP 0x00000080
  60. #define SSH_FILEXFER_ATTR_SUBSECOND_TIMES 0x00000100
  61. #define SSH_FILEXFER_ATTR_BITS 0x00000200
  62. #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
  63. #define SSH_FILEXFER_ATTR_COMMON \
  64. (SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_OWNERGROUP | \
  65. SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACCESSTIME | \
  66. SSH_FILEXFER_ATTR_MODIFYTIME)
  67. #define SSH_FILEXFER_TYPE_REGULAR 1
  68. #define SSH_FILEXFER_TYPE_DIRECTORY 2
  69. #define SSH_FILEXFER_TYPE_SYMLINK 3
  70. #define SSH_FILEXFER_TYPE_SPECIAL 4
  71. #define SSH_FILEXFER_TYPE_UNKNOWN 5
  72. #define SSH_FXF_READ 0x00000001
  73. #define SSH_FXF_WRITE 0x00000002
  74. #define SSH_FXF_APPEND 0x00000004
  75. #define SSH_FXF_CREAT 0x00000008
  76. #define SSH_FXF_TRUNC 0x00000010
  77. #define SSH_FXF_EXCL 0x00000020
  78. #define SSH_FXF_TEXT 0x00000040
  79. #define SSH_FXF_ACCESS_DISPOSITION 0x00000007
  80. #define SSH_FXF_CREATE_NEW 0x00000000
  81. #define SSH_FXF_CREATE_TRUNCATE 0x00000001
  82. #define SSH_FXF_OPEN_EXISTING 0x00000002
  83. #define SSH_FXF_OPEN_OR_CREATE 0x00000003
  84. #define SSH_FXF_TRUNCATE_EXISTING 0x00000004
  85. #define SSH_FXF_ACCESS_APPEND_DATA 0x00000008
  86. #define SSH_FXF_ACCESS_APPEND_DATA_ATOMIC 0x00000010
  87. #define SSH_FXF_ACCESS_TEXT_MODE 0x00000020
  88. #define SSH_FXF_ACCESS_READ_LOCK 0x00000040
  89. #define SSH_FXF_ACCESS_WRITE_LOCK 0x00000080
  90. #define SSH_FXF_ACCESS_DELETE_LOCK 0x00000100
  91. #define ACE4_READ_DATA 0x00000001
  92. #define ACE4_LIST_DIRECTORY 0x00000001
  93. #define ACE4_WRITE_DATA 0x00000002
  94. #define ACE4_ADD_FILE 0x00000002
  95. #define ACE4_APPEND_DATA 0x00000004
  96. #define ACE4_ADD_SUBDIRECTORY 0x00000004
  97. #define ACE4_READ_NAMED_ATTRS 0x00000008
  98. #define ACE4_WRITE_NAMED_ATTRS 0x00000010
  99. #define ACE4_EXECUTE 0x00000020
  100. #define ACE4_DELETE_CHILD 0x00000040
  101. #define ACE4_READ_ATTRIBUTES 0x00000080
  102. #define ACE4_WRITE_ATTRIBUTES 0x00000100
  103. #define ACE4_DELETE 0x00010000
  104. #define ACE4_READ_ACL 0x00020000
  105. #define ACE4_WRITE_ACL 0x00040000
  106. #define ACE4_WRITE_OWNER 0x00080000
  107. #define ACE4_SYNCHRONIZE 0x00100000
  108. #define SSH_FILEXFER_ATTR_FLAGS_HIDDEN 0x00000004
  109. #define SFTP_MAX_PACKET_LEN 102400
  110. //---------------------------------------------------------------------------
  111. #define SFTP_EXT_OWNER_GROUP "owner-group-query@generic-extensions"
  112. #define SFTP_EXT_OWNER_GROUP_REPLY "owner-group-query-reply@generic-extensions"
  113. #define SFTP_EXT_NEWLINE "newline"
  114. #define SFTP_EXT_SUPPORTED "supported"
  115. #define SFTP_EXT_SUPPORTED2 "supported2"
  116. #define SFTP_EXT_FSROOTS "[email protected]"
  117. #define SFTP_EXT_VENDOR_ID "vendor-id"
  118. //---------------------------------------------------------------------------
  119. #define OGQ_LIST_OWNERS 0x01
  120. #define OGQ_LIST_GROUPS 0x02
  121. //---------------------------------------------------------------------------
  122. const int SFTPMinVersion = 0;
  123. const int SFTPMaxVersion = 5;
  124. const int SFTPNoMessageNumber = -1;
  125. const int asNo = 0;
  126. const int asOK = 1 << SSH_FX_OK;
  127. const int asEOF = 1 << SSH_FX_EOF;
  128. const int asOpUnsupported = 1 << SSH_FX_OP_UNSUPPORTED;
  129. const int asNoSuchFile = 1 << SSH_FX_NO_SUCH_FILE;
  130. const int asAll = 0xFFFF;
  131. const int tfFirstLevel = 0x01;
  132. const int tfNewDirectory = 0x02;
  133. //---------------------------------------------------------------------------
  134. #define GET_32BIT(cp) \
  135. (((unsigned long)(unsigned char)(cp)[0] << 24) | \
  136. ((unsigned long)(unsigned char)(cp)[1] << 16) | \
  137. ((unsigned long)(unsigned char)(cp)[2] << 8) | \
  138. ((unsigned long)(unsigned char)(cp)[3]))
  139. #define PUT_32BIT(cp, value) { \
  140. (cp)[0] = (unsigned char)((value) >> 24); \
  141. (cp)[1] = (unsigned char)((value) >> 16); \
  142. (cp)[2] = (unsigned char)((value) >> 8); \
  143. (cp)[3] = (unsigned char)(value); }
  144. //---------------------------------------------------------------------------
  145. #define SFTP_PACKET_ALLOC_DELTA 256
  146. //---------------------------------------------------------------------------
  147. #pragma warn -inl
  148. //---------------------------------------------------------------------------
  149. struct TSFTPSupport
  150. {
  151. TSFTPSupport() :
  152. AttribExtensions(new TStringList()),
  153. Extensions(new TStringList())
  154. {
  155. Reset();
  156. }
  157. ~TSFTPSupport()
  158. {
  159. delete AttribExtensions;
  160. delete Extensions;
  161. }
  162. void Reset()
  163. {
  164. AttributeMask = 0;
  165. AttributeBits = 0;
  166. OpenFlags = 0;
  167. AccessMask = 0;
  168. MaxReadSize = 0;
  169. OpenBlockMasks = 0;
  170. BlockMasks = 0;
  171. AttribExtensions->Clear();
  172. Extensions->Clear();
  173. }
  174. unsigned int AttributeMask;
  175. unsigned int AttributeBits;
  176. unsigned int OpenFlags;
  177. unsigned int AccessMask;
  178. unsigned int MaxReadSize;
  179. unsigned int OpenBlockMasks;
  180. unsigned int BlockMasks;
  181. TStrings * AttribExtensions;
  182. TStrings * Extensions;
  183. };
  184. //---------------------------------------------------------------------------
  185. class TSFTPPacket
  186. {
  187. public:
  188. TSFTPPacket()
  189. {
  190. Init();
  191. }
  192. TSFTPPacket(const TSFTPPacket & Source)
  193. {
  194. Init();
  195. *this = Source;
  196. }
  197. TSFTPPacket(unsigned char AType)
  198. {
  199. Init();
  200. ChangeType(AType);
  201. }
  202. TSFTPPacket(const char * Source, unsigned int Len)
  203. {
  204. Init();
  205. FLength = Len;
  206. Capacity = FLength;
  207. memcpy(Data, Source, Len);
  208. }
  209. TSFTPPacket(const AnsiString & Source)
  210. {
  211. Init();
  212. FLength = Source.Length();
  213. Capacity = FLength;
  214. memcpy(Data, Source.c_str(), Source.Length());
  215. }
  216. ~TSFTPPacket()
  217. {
  218. if (FData != NULL)
  219. {
  220. delete[] (FData - FSendPrefixLen);
  221. }
  222. if (FReservedBy) FReservedBy->UnreserveResponse(this);
  223. }
  224. void ChangeType(unsigned char AType)
  225. {
  226. FPosition = 0;
  227. FLength = 0;
  228. Capacity = 0;
  229. FType = AType;
  230. AddByte(FType);
  231. if ((FType != 1) && (FType != SSH_FXP_INIT))
  232. {
  233. AssignNumber();
  234. AddCardinal(FMessageNumber);
  235. }
  236. }
  237. void Reuse()
  238. {
  239. AssignNumber();
  240. assert(Length >= 5);
  241. // duplicated in AddCardinal()
  242. unsigned char Buf[4];
  243. PUT_32BIT(Buf, FMessageNumber);
  244. memcpy(FData + 1, Buf, sizeof(Buf));
  245. }
  246. void AddByte(unsigned char Value)
  247. {
  248. Add(&Value, sizeof(Value));
  249. }
  250. void AddCardinal(unsigned long Value)
  251. {
  252. // duplicated in Reuse()
  253. unsigned char Buf[4];
  254. PUT_32BIT(Buf, Value);
  255. Add(&Buf, sizeof(Buf));
  256. }
  257. void AddInt64(__int64 Value)
  258. {
  259. AddCardinal((unsigned long)(Value >> 32));
  260. AddCardinal((unsigned long)(Value & 0xFFFFFFFF));
  261. }
  262. void AddData(const void * Data, int ALength)
  263. {
  264. AddCardinal(ALength);
  265. Add(Data, ALength);
  266. }
  267. void AddString(const AnsiString Value)
  268. {
  269. AddCardinal(Value.Length());
  270. Add(Value.c_str(), Value.Length());
  271. }
  272. inline void AddUtfString(const AnsiString Value)
  273. {
  274. AddString(TSFTPFileSystem::EncodeUTF(Value));
  275. }
  276. inline void AddString(const AnsiString Value, bool Utf)
  277. {
  278. if (Utf)
  279. {
  280. AddUtfString(Value);
  281. }
  282. else
  283. {
  284. AddString(Value);
  285. }
  286. }
  287. // now purposeless alias to AddString
  288. inline void AddPathString(const AnsiString Value, bool Utf)
  289. {
  290. AddString(Value, Utf);
  291. }
  292. void AddProperties(unsigned short * Rights, AnsiString * Owner,
  293. AnsiString * Group, __int64 * MTime, __int64 * ATime,
  294. __int64 * Size, bool IsDirectory, int Version, bool Utf)
  295. {
  296. int Flags = 0;
  297. if (Size != NULL)
  298. {
  299. Flags |= SSH_FILEXFER_ATTR_SIZE;
  300. }
  301. if ((Owner != NULL) || (Group != NULL))
  302. {
  303. Flags |= SSH_FILEXFER_ATTR_OWNERGROUP;
  304. }
  305. if (Rights != NULL)
  306. {
  307. Flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
  308. }
  309. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  310. {
  311. Flags |= SSH_FILEXFER_ATTR_ACMODTIME;
  312. }
  313. if ((Version >= 4) && (ATime != NULL))
  314. {
  315. Flags |= SSH_FILEXFER_ATTR_ACCESSTIME;
  316. }
  317. if ((Version >= 4) && (MTime != NULL))
  318. {
  319. Flags |= SSH_FILEXFER_ATTR_MODIFYTIME;
  320. }
  321. AddCardinal(Flags);
  322. if (Version >= 4)
  323. {
  324. AddByte(static_cast<unsigned char>(IsDirectory ?
  325. SSH_FILEXFER_TYPE_DIRECTORY : SSH_FILEXFER_TYPE_REGULAR));
  326. }
  327. if (Size != NULL)
  328. {
  329. AddInt64(*Size);
  330. }
  331. if ((Owner != NULL) || (Group != NULL))
  332. {
  333. assert(Version >= 4);
  334. AddString(Owner != NULL ? *Owner : AnsiString(), Utf);
  335. AddString(Group != NULL ? *Group : AnsiString(), Utf);
  336. }
  337. if (Rights != NULL)
  338. {
  339. AddCardinal(*Rights);
  340. }
  341. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  342. {
  343. // any way to reflect sbSignedTS here?
  344. // (note that casting __int64 > 2^31 < 2^32 to unsigned long is wrapped,
  345. // thus we never can set time after 2038, even if the server supports it)
  346. AddCardinal(static_cast<unsigned long>(ATime != NULL ? *ATime : *MTime));
  347. AddCardinal(static_cast<unsigned long>(MTime != NULL ? *MTime : *ATime));
  348. }
  349. if ((Version >= 4) && (ATime != NULL))
  350. {
  351. AddInt64(*ATime);
  352. }
  353. if ((Version >= 4) && (MTime != NULL))
  354. {
  355. AddInt64(*MTime);
  356. }
  357. }
  358. void AddProperties(const TRemoteProperties * Properties,
  359. unsigned short BaseRights, bool IsDirectory, int Version, bool Utf)
  360. {
  361. enum { valNone = 0, valRights = 0x01, valOwner = 0x02, valGroup = 0x04,
  362. valMTime = 0x08, valATime = 0x10 } Valid = valNone;
  363. unsigned short RightsNum = 0;
  364. AnsiString Owner;
  365. AnsiString Group;
  366. __int64 MTime;
  367. __int64 ATime;
  368. if (Properties != NULL)
  369. {
  370. if (Properties->Valid.Contains(vpGroup))
  371. {
  372. Valid |= valGroup;
  373. Group = Properties->Group;
  374. }
  375. if (Properties->Valid.Contains(vpOwner))
  376. {
  377. Valid |= valOwner;
  378. Owner = Properties->Owner;
  379. }
  380. if (Properties->Valid.Contains(vpRights))
  381. {
  382. Valid |= valRights;
  383. TRights Rights = BaseRights;
  384. Rights |= Properties->Rights.NumberSet;
  385. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  386. if (IsDirectory && Properties->AddXToDirectories)
  387. {
  388. Rights.AddExecute();
  389. }
  390. RightsNum = Rights;
  391. }
  392. if (Properties->Valid.Contains(vpLastAccess))
  393. {
  394. Valid |= valATime;
  395. ATime = Properties->LastAccess;
  396. }
  397. if (Properties->Valid.Contains(vpModification))
  398. {
  399. Valid |= valMTime;
  400. MTime = Properties->Modification;
  401. }
  402. }
  403. AddProperties(
  404. Valid & valRights ? &RightsNum : NULL,
  405. Valid & valOwner ? &Owner : NULL,
  406. Valid & valGroup ? &Group : NULL,
  407. Valid & valMTime ? &MTime : NULL,
  408. Valid & valATime ? &ATime : NULL,
  409. NULL, IsDirectory, Version, Utf);
  410. }
  411. char GetByte()
  412. {
  413. Need(sizeof(char));
  414. char Result = FData[FPosition];
  415. FPosition++;
  416. return Result;
  417. }
  418. unsigned long GetCardinal()
  419. {
  420. unsigned long Result;
  421. Need(sizeof(Result));
  422. Result = GET_32BIT(FData + FPosition);
  423. FPosition += sizeof(Result);
  424. return Result;
  425. }
  426. unsigned long GetSmallCardinal()
  427. {
  428. unsigned long Result;
  429. Need(2);
  430. Result = (FData[FPosition] << 8) + FData[FPosition + 1];
  431. FPosition += 2;
  432. return Result;
  433. }
  434. __int64 GetInt64()
  435. {
  436. __int64 Hi = GetCardinal();
  437. __int64 Lo = GetCardinal();
  438. return (Hi << 32) + Lo;
  439. }
  440. AnsiString GetString()
  441. {
  442. AnsiString Result;
  443. unsigned long Len = GetCardinal();
  444. Need(Len);
  445. // cannot happen anyway as Need() would raise exception
  446. assert(Len < SFTP_MAX_PACKET_LEN);
  447. Result.SetLength(Len);
  448. memcpy(Result.c_str(), FData + FPosition, Len);
  449. FPosition += Len;
  450. return Result;
  451. }
  452. inline AnsiString GetUtfString()
  453. {
  454. return TSFTPFileSystem::DecodeUTF(GetString());
  455. }
  456. inline AnsiString GetString(bool Utf)
  457. {
  458. return (Utf ? GetUtfString() : GetString());
  459. }
  460. // now purposeless alias to GetString
  461. inline AnsiString GetPathString(bool Utf)
  462. {
  463. return GetString(Utf);
  464. }
  465. void GetFile(TRemoteFile * File, int Version, bool ConsiderDST, bool Utf, bool SignedTS)
  466. {
  467. assert(File);
  468. unsigned int Flags;
  469. AnsiString ListingStr;
  470. unsigned long Permissions;
  471. bool ParsingFailed = false;
  472. if (Type != SSH_FXP_ATTRS)
  473. {
  474. File->FileName = GetPathString(Utf);
  475. if (Version < 4)
  476. {
  477. ListingStr = GetString();
  478. }
  479. }
  480. Flags = GetCardinal();
  481. if (Version >= 4)
  482. {
  483. char FXType = GetByte();
  484. // -:regular, D:directory, L:symlink, S:special, U:unknown
  485. // O:socket, C:char devide, B:block device, F:fifo
  486. static char* Types = "-DLSUOCBF";
  487. if (FXType < 1 || FXType > (char)strlen(Types))
  488. {
  489. throw Exception(FMTLOAD(SFTP_UNKNOWN_FILE_TYPE, (int(FXType))));
  490. }
  491. File->Type = Types[FXType-1];
  492. }
  493. if (Flags & SSH_FILEXFER_ATTR_SIZE)
  494. {
  495. File->Size = GetInt64();
  496. }
  497. // SSH-2.0-3.2.0 F-SECURE SSH - Process Software MultiNet
  498. // sets SSH_FILEXFER_ATTR_UIDGID for v4, but does not include the UID/GUID
  499. if ((Flags & SSH_FILEXFER_ATTR_UIDGID) && (Version < 4))
  500. {
  501. GetCardinal(); // skip UID
  502. GetCardinal(); // skip GUID
  503. }
  504. if (Flags & SSH_FILEXFER_ATTR_OWNERGROUP)
  505. {
  506. assert(Version >= 4);
  507. File->Owner = GetString(Utf);
  508. File->Group = GetString(Utf);
  509. }
  510. if (Flags & SSH_FILEXFER_ATTR_PERMISSIONS)
  511. {
  512. Permissions = GetCardinal();
  513. }
  514. if (Version < 4)
  515. {
  516. if (Flags & SSH_FILEXFER_ATTR_ACMODTIME)
  517. {
  518. File->LastAccess = UnixToDateTime(
  519. SignedTS ?
  520. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  521. static_cast<__int64>(GetCardinal()),
  522. ConsiderDST);
  523. File->Modification = UnixToDateTime(
  524. SignedTS ?
  525. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  526. static_cast<__int64>(GetCardinal()),
  527. ConsiderDST);
  528. }
  529. }
  530. else
  531. {
  532. if (Flags & SSH_FILEXFER_ATTR_ACCESSTIME)
  533. {
  534. File->LastAccess = UnixToDateTime(GetInt64(), ConsiderDST);
  535. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  536. {
  537. GetCardinal(); // skip access time subseconds
  538. }
  539. }
  540. else
  541. {
  542. File->LastAccess = Now();
  543. }
  544. if (Flags & SSH_FILEXFER_ATTR_CREATETIME)
  545. {
  546. GetInt64(); // skip create time
  547. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  548. {
  549. GetCardinal(); // skip create time subseconds
  550. }
  551. }
  552. if (Flags & SSH_FILEXFER_ATTR_MODIFYTIME)
  553. {
  554. File->Modification = UnixToDateTime(GetInt64(), ConsiderDST);
  555. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  556. {
  557. GetCardinal(); // skip modification time subseconds
  558. }
  559. }
  560. else
  561. {
  562. File->Modification = Now();
  563. }
  564. }
  565. if (Flags & SSH_FILEXFER_ATTR_ACL)
  566. {
  567. GetString();
  568. }
  569. if (Flags & SSH_FILEXFER_ATTR_BITS)
  570. {
  571. // while SSH_FILEXFER_ATTR_BITS is defined for SFTP5 only, vandyke 2.3.3 sets it
  572. // for SFTP4 as well
  573. unsigned long Bits = GetCardinal();
  574. if (FLAGSET(Bits, SSH_FILEXFER_ATTR_FLAGS_HIDDEN))
  575. {
  576. File->IsHidden = true;
  577. }
  578. }
  579. if ((Version < 4) && (Type != SSH_FXP_ATTRS))
  580. {
  581. try
  582. {
  583. // update permissions and user/group name
  584. // modification time and filename is ignored
  585. File->ListingStr = ListingStr;
  586. }
  587. catch(...)
  588. {
  589. // ignore any error while parsing listing line,
  590. // SFTP specification do not recommend to parse it
  591. ParsingFailed = true;
  592. }
  593. }
  594. if (Type == SSH_FXP_ATTRS || Version >= 4 || ParsingFailed)
  595. {
  596. File->Rights->Number = (unsigned short)(Permissions & TRights::rfAllSpecials);
  597. if (Version < 4)
  598. {
  599. File->Type = (Permissions & TRights::rfDirectory ? FILETYPE_DIRECTORY : '-');
  600. }
  601. }
  602. if (Flags & SSH_FILEXFER_ATTR_EXTENDED)
  603. {
  604. unsigned int ExtendedCount = GetCardinal();
  605. for (unsigned int Index = 0; Index < ExtendedCount; Index++)
  606. {
  607. GetString(); // skip extended_type
  608. GetString(); // skip extended_data
  609. }
  610. }
  611. File->Complete();
  612. }
  613. char * GetNextData(unsigned int Size = 0)
  614. {
  615. if (Size > 0)
  616. {
  617. Need(Size);
  618. }
  619. return FPosition < FLength ? FData + FPosition : NULL;
  620. }
  621. void DataUpdated(int ALength)
  622. {
  623. FPosition = 0;
  624. FLength = ALength;
  625. FType = GetByte();
  626. if (FType != SSH_FXP_VERSION)
  627. {
  628. FMessageNumber = GetCardinal();
  629. }
  630. else
  631. {
  632. FMessageNumber = SFTPNoMessageNumber;
  633. }
  634. }
  635. void LoadFromFile(const AnsiString FileName)
  636. {
  637. TStringList * DumpLines = new TStringList();
  638. AnsiString Dump;
  639. try
  640. {
  641. DumpLines->LoadFromFile(FileName);
  642. Dump = DumpLines->Text;
  643. }
  644. __finally
  645. {
  646. delete DumpLines;
  647. }
  648. Capacity = 20480;
  649. char Byte[3];
  650. memset(Byte, '\0', sizeof(Byte));
  651. int Index = 1;
  652. unsigned int Length = 0;
  653. while (Index < Dump.Length())
  654. {
  655. char C = Dump[Index];
  656. if (((C >= '0') && (C <= '9')) || ((C >= 'A') && (C <= 'Z')))
  657. {
  658. if (Byte[0] == '\0')
  659. {
  660. Byte[0] = C;
  661. }
  662. else
  663. {
  664. Byte[1] = C;
  665. assert(Length < Capacity);
  666. Data[Length] = static_cast<unsigned char>(HexToInt(Byte));
  667. Length++;
  668. memset(Byte, '\0', sizeof(Byte));
  669. }
  670. }
  671. Index++;
  672. }
  673. DataUpdated(Length);
  674. }
  675. AnsiString __fastcall Dump() const
  676. {
  677. AnsiString Result;
  678. for (unsigned int Index = 0; Index < Length; Index++)
  679. {
  680. Result += CharToHex(Data[Index]) + ",";
  681. if (((Index + 1) % 25) == 0)
  682. {
  683. Result += "\n";
  684. }
  685. }
  686. return Result;
  687. }
  688. TSFTPPacket & operator = (const TSFTPPacket & Source)
  689. {
  690. Capacity = 0;
  691. Add(Source.Data, Source.Length);
  692. DataUpdated(Source.Length);
  693. FPosition = Source.FPosition;
  694. return *this;
  695. }
  696. __property unsigned int Length = { read = FLength };
  697. __property char * Data = { read = FData };
  698. __property char * SendData = { read = GetSendData };
  699. __property unsigned int SendLength = { read = GetSendLength };
  700. __property unsigned int Capacity = { read = FCapacity, write = SetCapacity };
  701. __property unsigned char Type = { read = FType };
  702. __property unsigned char RequestType = { read = GetRequestType };
  703. __property unsigned int MessageNumber = { read = FMessageNumber, write = FMessageNumber };
  704. __property TSFTPFileSystem * ReservedBy = { read = FReservedBy, write = FReservedBy };
  705. __property AnsiString TypeName = { read = GetTypeName };
  706. private:
  707. char * FData;
  708. unsigned int FLength;
  709. unsigned int FCapacity;
  710. unsigned int FPosition;
  711. unsigned char FType;
  712. unsigned int FMessageNumber;
  713. TSFTPFileSystem * FReservedBy;
  714. static int FMessageCounter;
  715. static const FSendPrefixLen = 4;
  716. void Init()
  717. {
  718. FData = NULL;
  719. FCapacity = 0;
  720. FLength = 0;
  721. FPosition = 0;
  722. FMessageNumber = SFTPNoMessageNumber;
  723. FType = -1;
  724. FReservedBy = NULL;
  725. }
  726. void AssignNumber()
  727. {
  728. // this is not strictly thread-safe, but as it is accessed from multiple
  729. // threads only for multiple connection, it is not problem if two threads get
  730. // the same number
  731. FMessageNumber = (FMessageCounter << 8) + FType;
  732. FMessageCounter++;
  733. }
  734. unsigned char GetRequestType()
  735. {
  736. if (FMessageNumber != SFTPNoMessageNumber)
  737. {
  738. return (unsigned char)(FMessageNumber & 0xFF);
  739. }
  740. else
  741. {
  742. assert(Type == SSH_FXP_VERSION);
  743. return SSH_FXP_INIT;
  744. }
  745. }
  746. inline void Add(const void * AData, int ALength)
  747. {
  748. if (Length + ALength > Capacity)
  749. {
  750. Capacity = Length + ALength + SFTP_PACKET_ALLOC_DELTA;
  751. }
  752. memcpy(FData + Length, AData, ALength);
  753. FLength += ALength;
  754. }
  755. void SetCapacity(unsigned int ACapacity)
  756. {
  757. if (ACapacity != Capacity)
  758. {
  759. FCapacity = ACapacity;
  760. if (FCapacity > 0)
  761. {
  762. char * NData = (new char[FCapacity + FSendPrefixLen]) + FSendPrefixLen;
  763. if (FData)
  764. {
  765. memcpy(NData - FSendPrefixLen, FData - FSendPrefixLen,
  766. (FLength < FCapacity ? FLength : FCapacity) + FSendPrefixLen);
  767. delete[] (FData - FSendPrefixLen);
  768. }
  769. FData = NData;
  770. }
  771. else
  772. {
  773. if (FData) delete[] (FData - FSendPrefixLen);
  774. FData = NULL;
  775. }
  776. if (FLength > FCapacity) FLength = FCapacity;
  777. }
  778. }
  779. AnsiString GetTypeName() const
  780. {
  781. #define TYPE_CASE(TYPE) case TYPE: return #TYPE
  782. switch (Type) {
  783. TYPE_CASE(SSH_FXP_INIT);
  784. TYPE_CASE(SSH_FXP_VERSION);
  785. TYPE_CASE(SSH_FXP_OPEN);
  786. TYPE_CASE(SSH_FXP_CLOSE);
  787. TYPE_CASE(SSH_FXP_READ);
  788. TYPE_CASE(SSH_FXP_WRITE);
  789. TYPE_CASE(SSH_FXP_LSTAT);
  790. TYPE_CASE(SSH_FXP_FSTAT);
  791. TYPE_CASE(SSH_FXP_SETSTAT);
  792. TYPE_CASE(SSH_FXP_FSETSTAT);
  793. TYPE_CASE(SSH_FXP_OPENDIR);
  794. TYPE_CASE(SSH_FXP_READDIR);
  795. TYPE_CASE(SSH_FXP_REMOVE);
  796. TYPE_CASE(SSH_FXP_MKDIR);
  797. TYPE_CASE(SSH_FXP_RMDIR);
  798. TYPE_CASE(SSH_FXP_REALPATH);
  799. TYPE_CASE(SSH_FXP_STAT);
  800. TYPE_CASE(SSH_FXP_RENAME);
  801. TYPE_CASE(SSH_FXP_READLINK);
  802. TYPE_CASE(SSH_FXP_SYMLINK);
  803. TYPE_CASE(SSH_FXP_STATUS);
  804. TYPE_CASE(SSH_FXP_HANDLE);
  805. TYPE_CASE(SSH_FXP_DATA);
  806. TYPE_CASE(SSH_FXP_NAME);
  807. TYPE_CASE(SSH_FXP_ATTRS);
  808. TYPE_CASE(SSH_FXP_EXTENDED);
  809. TYPE_CASE(SSH_FXP_EXTENDED_REPLY);
  810. default:
  811. return FORMAT("Unknown message (%d)", (int(Type)));
  812. }
  813. }
  814. char * GetSendData() const
  815. {
  816. char * Result = FData - FSendPrefixLen;
  817. // this is not strictly const-object operation
  818. PUT_32BIT(Result, Length);
  819. return Result;
  820. }
  821. unsigned int GetSendLength() const
  822. {
  823. return FSendPrefixLen + Length;
  824. }
  825. inline void Need(unsigned int Size)
  826. {
  827. if (FPosition + Size > FLength)
  828. {
  829. throw Exception(FMTLOAD(SFTP_PACKET_ERROR, (int(FPosition), int(Size), int(FLength))));
  830. }
  831. }
  832. };
  833. //---------------------------------------------------------------------------
  834. int TSFTPPacket::FMessageCounter = 0;
  835. //---------------------------------------------------------------------------
  836. class TSFTPQueue
  837. {
  838. public:
  839. __fastcall TSFTPQueue(TSFTPFileSystem * AFileSystem)
  840. {
  841. FFileSystem = AFileSystem;
  842. assert(FFileSystem);
  843. FRequests = new TList();
  844. FResponses = new TList();
  845. FMissedRequests = 0;
  846. }
  847. __fastcall ~TSFTPQueue()
  848. {
  849. try
  850. {
  851. if (FFileSystem->FTerminal->Active)
  852. {
  853. Dispose();
  854. }
  855. }
  856. __finally
  857. {
  858. TSFTPQueuePacket * Request;
  859. TSFTPPacket * Response;
  860. assert(FResponses->Count == FRequests->Count);
  861. for (int Index = 0; Index < FRequests->Count; Index++)
  862. {
  863. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[Index]);
  864. assert(Request);
  865. delete Request;
  866. Response = static_cast<TSFTPPacket*>(FResponses->Items[Index]);
  867. assert(Response);
  868. delete Response;
  869. }
  870. delete FRequests;
  871. delete FResponses;
  872. }
  873. }
  874. bool __fastcall Init(int QueueLen)
  875. {
  876. bool Result = false;
  877. while ((QueueLen > 0) && SendRequest())
  878. {
  879. Result = true;
  880. QueueLen--;
  881. }
  882. FMissedRequests = QueueLen;
  883. return Result;
  884. }
  885. void __fastcall Dispose()
  886. {
  887. assert(FFileSystem->FTerminal->Active);
  888. TSFTPQueuePacket * Request;
  889. TSFTPPacket * Response;
  890. while (FRequests->Count)
  891. {
  892. assert(FResponses->Count);
  893. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[0]);
  894. assert(Request);
  895. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  896. assert(Response);
  897. try
  898. {
  899. FFileSystem->ReceiveResponse(Request, Response);
  900. }
  901. catch(Exception & E)
  902. {
  903. if (FFileSystem->FTerminal->Active)
  904. {
  905. FFileSystem->FTerminal->LogEvent("Error while disposing the SFTP queue.");
  906. FFileSystem->FTerminal->DoHandleExtendedException(&E);
  907. }
  908. else
  909. {
  910. FFileSystem->FTerminal->LogEvent("Fatal error while disposing the SFTP queue.");
  911. throw;
  912. }
  913. }
  914. FRequests->Delete(0);
  915. delete Request;
  916. FResponses->Delete(0);
  917. delete Response;
  918. }
  919. }
  920. bool __fastcall ReceivePacket(TSFTPPacket * Packet,
  921. int ExpectedType = -1, int AllowStatus = -1, void ** Token = NULL)
  922. {
  923. assert(FRequests->Count);
  924. bool Result;
  925. TSFTPQueuePacket * Request = NULL;
  926. TSFTPPacket * Response = NULL;
  927. try
  928. {
  929. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[0]);
  930. FRequests->Delete(0);
  931. assert(Request);
  932. if (Token != NULL)
  933. {
  934. *Token = Request->Token;
  935. }
  936. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  937. FResponses->Delete(0);
  938. assert(Response);
  939. FFileSystem->ReceiveResponse(Request, Response,
  940. ExpectedType, AllowStatus);
  941. if (Packet)
  942. {
  943. *Packet = *Response;
  944. }
  945. Result = !End(Response);
  946. if (Result)
  947. {
  948. FMissedRequests++;
  949. while ((FMissedRequests > 0) && SendRequest())
  950. {
  951. FMissedRequests--;
  952. }
  953. }
  954. }
  955. __finally
  956. {
  957. delete Request;
  958. delete Response;
  959. }
  960. return Result;
  961. }
  962. bool __fastcall Next(int ExpectedType = -1, int AllowStatus = -1)
  963. {
  964. return ReceivePacket(NULL, ExpectedType, AllowStatus);
  965. }
  966. protected:
  967. class TSFTPQueuePacket : public TSFTPPacket
  968. {
  969. public:
  970. TSFTPQueuePacket() :
  971. TSFTPPacket()
  972. {
  973. Token = NULL;
  974. }
  975. void * Token;
  976. };
  977. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request) = 0;
  978. virtual bool __fastcall End(TSFTPPacket * Response) = 0;
  979. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  980. {
  981. FFileSystem->SendPacket(Packet);
  982. }
  983. protected:
  984. TList * FRequests;
  985. TList * FResponses;
  986. TSFTPFileSystem * FFileSystem;
  987. int FMissedRequests;
  988. private:
  989. bool __fastcall SendRequest()
  990. {
  991. TSFTPQueuePacket * Request = NULL;
  992. try
  993. {
  994. Request = new TSFTPQueuePacket();
  995. if (!InitRequest(Request))
  996. {
  997. delete Request;
  998. Request = NULL;
  999. }
  1000. }
  1001. catch(...)
  1002. {
  1003. delete Request;
  1004. throw;
  1005. }
  1006. if (Request != NULL)
  1007. {
  1008. TSFTPPacket * Response = new TSFTPPacket();
  1009. FRequests->Add(Request);
  1010. FResponses->Add(Response);
  1011. SendPacket(Request);
  1012. FFileSystem->ReserveResponse(Request, Response);
  1013. }
  1014. return (Request != NULL);
  1015. }
  1016. };
  1017. //---------------------------------------------------------------------------
  1018. class TSFTPTransferQueue : public TSFTPQueue
  1019. {
  1020. public:
  1021. TSFTPTransferQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  1022. {
  1023. }
  1024. protected:
  1025. __int64 FTransfered;
  1026. AnsiString FHandle;
  1027. };
  1028. //---------------------------------------------------------------------------
  1029. class TSFTPDownloadQueue : public TSFTPTransferQueue
  1030. {
  1031. public:
  1032. TSFTPDownloadQueue(TSFTPFileSystem * AFileSystem) :
  1033. TSFTPTransferQueue(AFileSystem)
  1034. {
  1035. }
  1036. bool __fastcall Init(int QueueLen, const AnsiString AHandle,__int64 ATransfered,
  1037. TFileOperationProgressType * AOperationProgress)
  1038. {
  1039. FHandle = AHandle;
  1040. FTransfered = ATransfered;
  1041. OperationProgress = AOperationProgress;
  1042. return TSFTPTransferQueue::Init(QueueLen);
  1043. }
  1044. void __fastcall InitFillGapRequest(__int64 Offset, unsigned long Missing,
  1045. TSFTPPacket * Packet)
  1046. {
  1047. InitRequest(Packet, Offset, Missing);
  1048. }
  1049. bool __fastcall ReceivePacket(TSFTPPacket * Packet, unsigned long & BlockSize)
  1050. {
  1051. void * Token;
  1052. bool Result = TSFTPTransferQueue::ReceivePacket(Packet, SSH_FXP_DATA, asEOF, &Token);
  1053. BlockSize = reinterpret_cast<unsigned long>(Token);
  1054. return Result;
  1055. }
  1056. protected:
  1057. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1058. {
  1059. unsigned int BlockSize = FFileSystem->DownloadBlockSize(OperationProgress);
  1060. InitRequest(Request, FTransfered, BlockSize);
  1061. Request->Token = reinterpret_cast<void*>(BlockSize);
  1062. FTransfered += BlockSize;
  1063. return true;
  1064. }
  1065. void __fastcall InitRequest(TSFTPPacket * Request, __int64 Offset,
  1066. unsigned long Size)
  1067. {
  1068. Request->ChangeType(SSH_FXP_READ);
  1069. Request->AddString(FHandle);
  1070. Request->AddInt64(Offset);
  1071. Request->AddCardinal(Size);
  1072. }
  1073. virtual bool __fastcall End(TSFTPPacket * Response)
  1074. {
  1075. return (Response->Type != SSH_FXP_DATA);
  1076. }
  1077. private:
  1078. TFileOperationProgressType * OperationProgress;
  1079. };
  1080. //---------------------------------------------------------------------------
  1081. class TSFTPUploadQueue : public TSFTPTransferQueue
  1082. {
  1083. public:
  1084. TSFTPUploadQueue(TSFTPFileSystem * AFileSystem) :
  1085. TSFTPTransferQueue(AFileSystem)
  1086. {
  1087. FFile = NULL;
  1088. OperationProgress = NULL;
  1089. FLastBlockSize = 0;
  1090. FEnd = false;
  1091. }
  1092. bool __fastcall Init(int QueueLen, const AnsiString AFileName,
  1093. HANDLE AFile, TFileOperationProgressType * AOperationProgress,
  1094. const AnsiString AHandle, __int64 ATransfered)
  1095. {
  1096. FFileName = AFileName;
  1097. FFile = AFile;
  1098. OperationProgress = AOperationProgress;
  1099. FHandle = AHandle;
  1100. FTransfered = ATransfered;
  1101. return TSFTPTransferQueue::Init(QueueLen);
  1102. }
  1103. protected:
  1104. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1105. {
  1106. TTerminal * FTerminal = FFileSystem->FTerminal;
  1107. // Buffer for one block of data
  1108. TFileBuffer BlockBuf;
  1109. unsigned long BlockSize = GetBlockSize();
  1110. bool Result = (BlockSize > 0);
  1111. if (Result)
  1112. {
  1113. FILE_OPERATION_LOOP(FMTLOAD(READ_ERROR, (FFileName)),
  1114. BlockBuf.LoadFile(FFile, BlockSize, false);
  1115. );
  1116. FEnd = (BlockBuf.Size == 0);
  1117. Result = !FEnd;
  1118. if (Result)
  1119. {
  1120. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1121. // We do ASCII transfer: convert EOL of current block
  1122. if (OperationProgress->AsciiTransfer)
  1123. {
  1124. __int64 PrevBufSize = BlockBuf.Size;
  1125. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1126. FFileSystem->GetEOL(), cpRemoveCtrlZ);
  1127. // update transfer size with difference arised from EOL conversion
  1128. OperationProgress->ChangeTransferSize(OperationProgress->TransferSize -
  1129. PrevBufSize + BlockBuf.Size);
  1130. }
  1131. Request->ChangeType(SSH_FXP_WRITE);
  1132. Request->AddString(FHandle);
  1133. Request->AddInt64(FTransfered);
  1134. Request->AddData(BlockBuf.Data, BlockBuf.Size);
  1135. FLastBlockSize = BlockBuf.Size;
  1136. FTransfered += BlockBuf.Size;
  1137. }
  1138. }
  1139. return Result;
  1140. }
  1141. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1142. {
  1143. TSFTPTransferQueue::SendPacket(Packet);
  1144. OperationProgress->AddTransfered(FLastBlockSize);
  1145. }
  1146. inline int __fastcall GetBlockSize()
  1147. {
  1148. return FFileSystem->UploadBlockSize(FHandle, OperationProgress);
  1149. }
  1150. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1151. {
  1152. return FEnd;
  1153. }
  1154. private:
  1155. HANDLE FFile;
  1156. TFileOperationProgressType * OperationProgress;
  1157. AnsiString FFileName;
  1158. unsigned long FLastBlockSize;
  1159. bool FEnd;
  1160. };
  1161. //---------------------------------------------------------------------------
  1162. #pragma warn .inl
  1163. //---------------------------------------------------------------------------
  1164. class TSFTPBusy
  1165. {
  1166. public:
  1167. __fastcall TSFTPBusy(TSFTPFileSystem * FileSystem)
  1168. {
  1169. FFileSystem = FileSystem;
  1170. assert(FFileSystem != NULL);
  1171. FFileSystem->BusyStart();
  1172. }
  1173. __fastcall ~TSFTPBusy()
  1174. {
  1175. FFileSystem->BusyEnd();
  1176. }
  1177. private:
  1178. TSFTPFileSystem * FFileSystem;
  1179. };
  1180. //===========================================================================
  1181. struct TOpenRemoteFileParams
  1182. {
  1183. int LocalFileAttrs;
  1184. AnsiString RemoteFileName;
  1185. TFileOperationProgressType * OperationProgress;
  1186. const TCopyParamType * CopyParam;
  1187. int Params;
  1188. bool Resume;
  1189. TSFTPOverwriteMode OverwriteMode;
  1190. __int64 DestFileSize; // output
  1191. AnsiString RemoteFileHandle; // output
  1192. TOverwriteFileParams * FileParams;
  1193. bool Confirmed;
  1194. };
  1195. //---------------------------------------------------------------------------
  1196. struct TSinkFileParams
  1197. {
  1198. AnsiString TargetDir;
  1199. const TCopyParamType * CopyParam;
  1200. int Params;
  1201. TFileOperationProgressType * OperationProgress;
  1202. bool Skipped;
  1203. unsigned int Flags;
  1204. };
  1205. //===========================================================================
  1206. __fastcall TSFTPFileSystem::TSFTPFileSystem(TTerminal * ATerminal):
  1207. TCustomFileSystem(ATerminal)
  1208. {
  1209. FPacketReservations = new TList();
  1210. FPacketNumbers = VarArrayCreate(OPENARRAY(int, (0, 1)), varInteger);
  1211. FPreviousLoggedPacket = 0;
  1212. FNotLoggedPackets = 0;
  1213. FBusy = 0;
  1214. FAvoidBusy = false;
  1215. FUtfStrings = false;
  1216. FUtfNever = false;
  1217. FSignedTS = false;
  1218. FSupport = new TSFTPSupport();
  1219. FExtensions = new TStringList();
  1220. FFixedPaths = NULL;
  1221. }
  1222. //---------------------------------------------------------------------------
  1223. __fastcall TSFTPFileSystem::~TSFTPFileSystem()
  1224. {
  1225. delete FSupport;
  1226. // there must be no valid packet reservation at the end
  1227. for (int i = 0; i < FPacketReservations->Count; i++)
  1228. {
  1229. assert(FPacketReservations->Items[i] == NULL);
  1230. }
  1231. delete FPacketReservations;
  1232. delete FExtensions;
  1233. delete FFixedPaths;
  1234. }
  1235. //---------------------------------------------------------------------------
  1236. AnsiString __fastcall TSFTPFileSystem::GetProtocolName() const
  1237. {
  1238. return FMTLOAD(SFTP_PROTOCOL_NAME, (FVersion));
  1239. }
  1240. //---------------------------------------------------------------------------
  1241. bool __fastcall TSFTPFileSystem::IsCapable(int Capability) const
  1242. {
  1243. assert(FTerminal);
  1244. switch (Capability) {
  1245. case fcAnyCommand:
  1246. case fcHardLink:
  1247. case fcRemoteCopy:
  1248. return false;
  1249. case fcModeChanging:
  1250. case fcNewerOnlyUpload:
  1251. case fcTimestampChanging:
  1252. return true;
  1253. case fcRename:
  1254. case fcRemoteMove:
  1255. return (FVersion >= 2);
  1256. case fcSymbolicLink:
  1257. case fcResolveSymlink:
  1258. return (FVersion >= 3);
  1259. case fcOwnerChanging:
  1260. case fcGroupChanging:
  1261. case fcNativeTextMode:
  1262. return (FVersion >= 4);
  1263. case fcTextMode:
  1264. return (FVersion >= 4) ||
  1265. strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0;
  1266. case fcUserGroupListing:
  1267. return SupportsExtension(SFTP_EXT_OWNER_GROUP);
  1268. default:
  1269. assert(false);
  1270. return false;
  1271. }
  1272. }
  1273. //---------------------------------------------------------------------------
  1274. bool __fastcall TSFTPFileSystem::SupportsExtension(const AnsiString & Extension) const
  1275. {
  1276. return (FSupport->Extensions->IndexOf(Extension) >= 0);
  1277. }
  1278. //---------------------------------------------------------------------------
  1279. void __fastcall TSFTPFileSystem::KeepAlive()
  1280. {
  1281. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1282. Packet.AddPathString("/", FUtfStrings);
  1283. SendPacketAndReceiveResponse(&Packet, &Packet);
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. void __fastcall TSFTPFileSystem::AdditionalInfo(TStrings * AdditionalInfo,
  1287. bool Initial)
  1288. {
  1289. if (Initial)
  1290. {
  1291. if (!IsCapable(fcRename))
  1292. {
  1293. AdditionalInfo->Add(LoadStr(FS_RENAME_NOT_SUPPORTED));
  1294. AdditionalInfo->Add("");
  1295. }
  1296. if (FExtensions->Count > 0)
  1297. {
  1298. AnsiString Name;
  1299. AnsiString Value;
  1300. AnsiString Line;
  1301. AdditionalInfo->Add(LoadStr(SFTP_EXTENSION_INFO));
  1302. for (int Index = 0; Index < FExtensions->Count; Index++)
  1303. {
  1304. AnsiString Name = FExtensions->Names[Index];
  1305. AnsiString Value = FExtensions->Values[Name];
  1306. AnsiString Line;
  1307. if (Value.IsEmpty())
  1308. {
  1309. Line = Name;
  1310. }
  1311. else
  1312. {
  1313. if (!IsDisplayableStr(Value))
  1314. {
  1315. Value = "0x" + StrToHex(Value);
  1316. }
  1317. Line = FORMAT("%s=%s", (Name, Value));
  1318. }
  1319. AdditionalInfo->Add(FORMAT(" %s", (Line)));;
  1320. }
  1321. }
  1322. else
  1323. {
  1324. AdditionalInfo->Add(LoadStr(SFTP_NO_EXTENSION_INFO));
  1325. }
  1326. }
  1327. }
  1328. //---------------------------------------------------------------------------
  1329. struct TUnicodeEmitParams
  1330. {
  1331. WideString Buffer;
  1332. int Pos;
  1333. int Len;
  1334. };
  1335. //---------------------------------------------------------------------------
  1336. extern "C" void UnicodeEmit(void * AParams, long int Output)
  1337. {
  1338. if (Output == 0xFFFFL) // see Putty's charset\internal.h
  1339. {
  1340. throw Exception(LoadStr(DECODE_UTF_ERROR));
  1341. }
  1342. TUnicodeEmitParams * Params = (TUnicodeEmitParams *)AParams;
  1343. if (Params->Pos >= Params->Len)
  1344. {
  1345. Params->Len += 50;
  1346. Params->Buffer.SetLength(Params->Len);
  1347. }
  1348. Params->Pos++;
  1349. Params->Buffer[Params->Pos] = (wchar_t)Output;
  1350. }
  1351. //---------------------------------------------------------------------------
  1352. AnsiString __fastcall TSFTPFileSystem::DecodeUTF(const AnsiString UTF)
  1353. {
  1354. charset_state State;
  1355. char * Str;
  1356. TUnicodeEmitParams Params;
  1357. AnsiString Result;
  1358. State.s0 = 0;
  1359. Str = UTF.c_str();
  1360. Params.Pos = 0;
  1361. Params.Len = UTF.Length();
  1362. Params.Buffer.SetLength(Params.Len);
  1363. while (*Str)
  1364. {
  1365. read_utf8(NULL, (unsigned char)*Str, &State, UnicodeEmit, &Params);
  1366. Str++;
  1367. }
  1368. Params.Buffer.SetLength(Params.Pos);
  1369. return Params.Buffer;
  1370. }
  1371. //---------------------------------------------------------------------------
  1372. struct TUnicodeEmitParams2
  1373. {
  1374. AnsiString Buffer;
  1375. int Pos;
  1376. int Len;
  1377. };
  1378. //---------------------------------------------------------------------------
  1379. extern "C" void UnicodeEmit2(void * AParams, long int Output)
  1380. {
  1381. if (Output == 0xFFFFL) // see Putty's charset\internal.h
  1382. {
  1383. throw Exception(LoadStr(DECODE_UTF_ERROR));
  1384. }
  1385. TUnicodeEmitParams2 * Params = (TUnicodeEmitParams2 *)AParams;
  1386. if (Params->Pos >= Params->Len)
  1387. {
  1388. Params->Len += 50;
  1389. Params->Buffer.SetLength(Params->Len);
  1390. }
  1391. Params->Pos++;
  1392. Params->Buffer[Params->Pos] = (unsigned char)Output;
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. AnsiString __fastcall TSFTPFileSystem::EncodeUTF(const WideString Source)
  1396. {
  1397. charset_state State;
  1398. wchar_t * Str;
  1399. TUnicodeEmitParams2 Params;
  1400. AnsiString Result;
  1401. State.s0 = 0;
  1402. Str = Source.c_bstr();
  1403. Params.Pos = 0;
  1404. Params.Len = Source.Length();
  1405. Params.Buffer.SetLength(Params.Len);
  1406. while (*Str)
  1407. {
  1408. write_utf8(NULL, (wchar_t)*Str, &State, UnicodeEmit2, &Params);
  1409. Str++;
  1410. }
  1411. Params.Buffer.SetLength(Params.Pos);
  1412. return Params.Buffer;
  1413. }
  1414. //---------------------------------------------------------------------------
  1415. inline void __fastcall TSFTPFileSystem::BusyStart()
  1416. {
  1417. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1418. {
  1419. Busy(true);
  1420. }
  1421. FBusy++;
  1422. assert(FBusy < 10);
  1423. }
  1424. //---------------------------------------------------------------------------
  1425. inline void __fastcall TSFTPFileSystem::BusyEnd()
  1426. {
  1427. assert(FBusy > 0);
  1428. FBusy--;
  1429. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1430. {
  1431. Busy(false);
  1432. }
  1433. }
  1434. //---------------------------------------------------------------------------
  1435. unsigned long __fastcall TSFTPFileSystem::TransferBlockSize(unsigned long Overhead,
  1436. TFileOperationProgressType * OperationProgress, unsigned long MaxPacketSize)
  1437. {
  1438. const unsigned long MinPacketSize = 4096;
  1439. // size + message number + type
  1440. const unsigned long SFTPPacketOverhead = 4 + 4 + 1;
  1441. unsigned long AMaxPacketSize = FTerminal->MaxPacketSize();
  1442. bool MaxPacketSizeValid = (AMaxPacketSize > 0);
  1443. unsigned long Result = OperationProgress->CPS();
  1444. if ((MaxPacketSize > 0) &&
  1445. ((MaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1446. {
  1447. AMaxPacketSize = MaxPacketSize;
  1448. MaxPacketSizeValid = true;
  1449. }
  1450. if ((FMaxPacketSize > 0) &&
  1451. ((FMaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1452. {
  1453. AMaxPacketSize = FMaxPacketSize;
  1454. MaxPacketSizeValid = true;
  1455. }
  1456. if (Result == 0)
  1457. {
  1458. Result = OperationProgress->StaticBlockSize();
  1459. }
  1460. if (Result < MinPacketSize)
  1461. {
  1462. Result = MinPacketSize;
  1463. }
  1464. if (MaxPacketSizeValid)
  1465. {
  1466. Overhead += SFTPPacketOverhead;
  1467. if (AMaxPacketSize < Overhead)
  1468. {
  1469. // do not send another request
  1470. // (generally should happen only if upload buffer if full)
  1471. Result = 0;
  1472. }
  1473. else
  1474. {
  1475. AMaxPacketSize -= Overhead;
  1476. if (Result > AMaxPacketSize)
  1477. {
  1478. Result = AMaxPacketSize;
  1479. }
  1480. }
  1481. }
  1482. return Result;
  1483. }
  1484. //---------------------------------------------------------------------------
  1485. unsigned long __fastcall TSFTPFileSystem::UploadBlockSize(const AnsiString & Handle,
  1486. TFileOperationProgressType * OperationProgress)
  1487. {
  1488. // handle length + offset + data size
  1489. const unsigned long UploadPacketOverhead =
  1490. sizeof(unsigned long) + sizeof(__int64) + sizeof(unsigned long);
  1491. int RemainingSendBuffer = FTerminal->RemainingSendBuffer();
  1492. unsigned long Result;
  1493. if (RemainingSendBuffer <= 0)
  1494. {
  1495. Result = 0;
  1496. }
  1497. else
  1498. {
  1499. Result = TransferBlockSize(UploadPacketOverhead + Handle.Length(), OperationProgress,
  1500. RemainingSendBuffer);
  1501. }
  1502. return Result;
  1503. }
  1504. //---------------------------------------------------------------------------
  1505. unsigned long __fastcall TSFTPFileSystem::DownloadBlockSize(
  1506. TFileOperationProgressType * OperationProgress)
  1507. {
  1508. unsigned long Result = TransferBlockSize(sizeof(unsigned long), OperationProgress);
  1509. if ((FSupport->MaxReadSize > 0) && (Result > FSupport->MaxReadSize))
  1510. {
  1511. Result = FSupport->MaxReadSize;
  1512. }
  1513. return Result;
  1514. }
  1515. //---------------------------------------------------------------------------
  1516. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  1517. {
  1518. BusyStart();
  1519. try
  1520. {
  1521. if (FTerminal->IsLogging())
  1522. {
  1523. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1524. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1525. (Packet->Type != FPreviousLoggedPacket) ||
  1526. (FTerminal->Configuration->LogProtocol >= 1))
  1527. {
  1528. if (FNotLoggedPackets)
  1529. {
  1530. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1531. (FNotLoggedPackets)));
  1532. FNotLoggedPackets = 0;
  1533. }
  1534. FTerminal->Log->Add(llInput, FORMAT("Type: %s, Size: %d, Number: %d",
  1535. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1536. if (FTerminal->Configuration->LogProtocol >= 2)
  1537. {
  1538. FTerminal->Log->Add(llInput, Packet->Dump());
  1539. }
  1540. FPreviousLoggedPacket = Packet->Type;
  1541. }
  1542. else
  1543. {
  1544. FNotLoggedPackets++;
  1545. }
  1546. }
  1547. FTerminal->Send(Packet->SendData, Packet->SendLength);
  1548. }
  1549. __finally
  1550. {
  1551. BusyEnd();
  1552. }
  1553. }
  1554. //---------------------------------------------------------------------------
  1555. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
  1556. int AllowStatus)
  1557. {
  1558. unsigned long Code = Packet->GetCardinal();
  1559. static int Messages[] = {
  1560. SFTP_STATUS_OK,
  1561. SFTP_STATUS_EOF,
  1562. SFTP_STATUS_NO_SUCH_FILE,
  1563. SFTP_STATUS_PERMISSION_DENIED,
  1564. SFTP_STATUS_FAILURE,
  1565. SFTP_STATUS_BAD_MESSAGE,
  1566. SFTP_STATUS_NO_CONNECTION,
  1567. SFTP_STATUS_CONNECTION_LOST,
  1568. SFTP_STATUS_OP_UNSUPPORTED,
  1569. SFTP_STATUS_INVALID_HANDLE,
  1570. SFTP_STATUS_NO_SUCH_PATH,
  1571. SFTP_STATUS_FILE_ALREADY_EXISTS,
  1572. SFTP_STATUS_WRITE_PROTECT,
  1573. SFTP_STATUS_NO_MEDIA,
  1574. SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
  1575. SFTP_STATUS_QUOTA_EXCEEDED,
  1576. SFTP_STATUS_UNKNOWN_PRINCIPAL,
  1577. SFTP_STATUS_LOCK_CONFLICT,
  1578. SFTP_STATUS_DIR_NOT_EMPTY,
  1579. SFTP_STATUS_NOT_A_DIRECTORY,
  1580. SFTP_STATUS_INVALID_FILENAME,
  1581. SFTP_STATUS_LINK_LOOP,
  1582. SFTP_STATUS_CANNOT_DELETE,
  1583. SFTP_STATUS_INVALID_PARAMETER,
  1584. SFTP_STATUS_FILE_IS_A_DIRECTORY,
  1585. SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT,
  1586. SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED,
  1587. SFTP_STATUS_DELETE_PENDING,
  1588. SFTP_STATUS_FILE_CORRUPT
  1589. };
  1590. int Message;
  1591. if ((AllowStatus & (0x01 << Code)) == 0)
  1592. {
  1593. if (Code >= LENOF(Messages))
  1594. {
  1595. Message = SFTP_STATUS_UNKNOWN;
  1596. }
  1597. else
  1598. {
  1599. Message = Messages[Code];
  1600. }
  1601. AnsiString ServerMessage;
  1602. AnsiString LanguageTag;
  1603. AnsiString AdditionalInfo;
  1604. if (FVersion >= 3)
  1605. {
  1606. // message is in UTF only since SFTP specification 01 (specification 00
  1607. // is also version 3)
  1608. // (in other words, always use UTF unless server is know to be buggy)
  1609. ServerMessage = Packet->GetString(!FUtfNever);
  1610. LanguageTag = Packet->GetString();
  1611. if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPAL))
  1612. {
  1613. while (Packet->GetNextData() != NULL)
  1614. {
  1615. if (!AdditionalInfo.IsEmpty())
  1616. {
  1617. AdditionalInfo += ", ";
  1618. }
  1619. AdditionalInfo += Packet->GetString();
  1620. }
  1621. }
  1622. }
  1623. else
  1624. {
  1625. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  1626. }
  1627. if (FTerminal->IsLogging())
  1628. {
  1629. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d, Message: %d, Server: %s, Language: %s ",
  1630. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  1631. }
  1632. if (!LanguageTag.IsEmpty())
  1633. {
  1634. LanguageTag = FORMAT("(%s)", (LanguageTag));
  1635. }
  1636. AnsiString Error = FMTLOAD(SFTP_ERROR_FORMAT, (LoadStr(Message) + AdditionalInfo,
  1637. int(Code), ServerMessage, LanguageTag, int(Packet->RequestType)));
  1638. FTerminal->TerminalError(NULL, Error);
  1639. return 0;
  1640. }
  1641. else
  1642. {
  1643. if (!FNotLoggedPackets || Code)
  1644. {
  1645. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d", ((int)Code)));
  1646. }
  1647. return Code;
  1648. }
  1649. }
  1650. //---------------------------------------------------------------------------
  1651. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  1652. {
  1653. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  1654. {
  1655. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  1656. }
  1657. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  1658. if (Packet)
  1659. {
  1660. assert(Packet->ReservedBy == this);
  1661. Packet->ReservedBy = NULL;
  1662. }
  1663. FPacketReservations->Delete(Reservation);
  1664. }
  1665. //---------------------------------------------------------------------------
  1666. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  1667. int ExpectedType, int AllowStatus)
  1668. {
  1669. TSFTPBusy Busy(this);
  1670. int Result = SSH_FX_OK;
  1671. int Reservation = FPacketReservations->IndexOf(Packet);
  1672. if (Reservation < 0 || Packet->Capacity == 0)
  1673. {
  1674. bool IsReserved;
  1675. do
  1676. {
  1677. IsReserved = false;
  1678. assert(Packet);
  1679. char LenBuf[5];
  1680. LenBuf[sizeof(LenBuf) - 1] = '\0';
  1681. FTerminal->Receive(LenBuf, sizeof(LenBuf) - 1);
  1682. int Length = GET_32BIT(LenBuf);
  1683. if (Length > SFTP_MAX_PACKET_LEN)
  1684. {
  1685. AnsiString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  1686. int(Length), SFTP_MAX_PACKET_LEN));
  1687. if (ExpectedType == SSH_FXP_VERSION)
  1688. {
  1689. AnsiString LenString = LenBuf;
  1690. if (!IsDisplayableStr(LenString))
  1691. {
  1692. LenString = "0x" + StrToHex(LenString);
  1693. }
  1694. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  1695. (Message, LenString));
  1696. }
  1697. FTerminal->FatalError(Message);
  1698. }
  1699. Packet->Capacity = Length;
  1700. FTerminal->Receive(Packet->Data, Length);
  1701. Packet->DataUpdated(Length);
  1702. if (FTerminal->IsLogging())
  1703. {
  1704. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1705. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1706. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA) ||
  1707. (FTerminal->Configuration->LogProtocol >= 1))
  1708. {
  1709. if (FNotLoggedPackets)
  1710. {
  1711. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1712. (FNotLoggedPackets)));
  1713. FNotLoggedPackets = 0;
  1714. }
  1715. FTerminal->Log->Add(llOutput, FORMAT("Type: %s, Size: %d, Number: %d",
  1716. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1717. if (FTerminal->Configuration->LogProtocol >= 2)
  1718. {
  1719. FTerminal->Log->Add(llOutput, Packet->Dump());
  1720. }
  1721. }
  1722. else
  1723. {
  1724. FNotLoggedPackets++;
  1725. }
  1726. }
  1727. if (Reservation < 0 ||
  1728. Packet->MessageNumber != (unsigned long)FPacketNumbers.GetElement(Reservation))
  1729. {
  1730. TSFTPPacket * ReservedPacket;
  1731. unsigned long MessageNumber;
  1732. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  1733. {
  1734. MessageNumber = FPacketNumbers.GetElement(Index);
  1735. if (MessageNumber == Packet->MessageNumber)
  1736. {
  1737. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  1738. IsReserved = true;
  1739. if (ReservedPacket)
  1740. {
  1741. FTerminal->LogEvent("Storing reserved response");
  1742. *ReservedPacket = *Packet;
  1743. }
  1744. else
  1745. {
  1746. FTerminal->LogEvent("Discarding reserved response");
  1747. RemoveReservation(Index);
  1748. }
  1749. break;
  1750. }
  1751. }
  1752. }
  1753. }
  1754. while (IsReserved);
  1755. }
  1756. // before we removed the reservation after check for packet type,
  1757. // but if it raises exception, removal is unnecessarily
  1758. // postponed until the packet is removed
  1759. // (and it have not worked anyway until recent fix to UnreserveResponse)
  1760. if (Reservation >= 0)
  1761. {
  1762. // order might have changed, when reserved, but no longer needed packet
  1763. // was received in above loop
  1764. Reservation = FPacketReservations->IndexOf(Packet);
  1765. assert(Reservation >= 0);
  1766. assert(Packet->MessageNumber == (unsigned long)FPacketNumbers.GetElement(Reservation));
  1767. RemoveReservation(Reservation);
  1768. }
  1769. if (ExpectedType >= 0)
  1770. {
  1771. if (Packet->Type == SSH_FXP_STATUS)
  1772. {
  1773. if (AllowStatus < 0)
  1774. {
  1775. AllowStatus = (ExpectedType == SSH_FXP_STATUS ? asOK : asNo);
  1776. }
  1777. Result = GotStatusPacket(Packet, AllowStatus);
  1778. }
  1779. else if (ExpectedType != Packet->Type)
  1780. {
  1781. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  1782. }
  1783. }
  1784. return Result;
  1785. }
  1786. //---------------------------------------------------------------------------
  1787. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  1788. TSFTPPacket * Response)
  1789. {
  1790. if (Response != NULL)
  1791. {
  1792. assert(FPacketReservations->IndexOf(Response) < 0);
  1793. // mark response as not received yet
  1794. Response->Capacity = 0;
  1795. Response->ReservedBy = this;
  1796. }
  1797. FPacketReservations->Add(Response);
  1798. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  1799. {
  1800. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  1801. }
  1802. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  1803. }
  1804. //---------------------------------------------------------------------------
  1805. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  1806. {
  1807. int Reservation = FPacketReservations->IndexOf(Response);
  1808. if (Response->Capacity != 0)
  1809. {
  1810. // added check for already received packet
  1811. // (it happens when the reserved response is received out of order,
  1812. // unexpectedly soon, and then receivepacket() on the packet
  1813. // is not actually called, due to exception)
  1814. RemoveReservation(Reservation);
  1815. }
  1816. else
  1817. {
  1818. if (Reservation >= 0)
  1819. {
  1820. // we probably do not remove the item at all, because
  1821. // we must remember that the respose was expected, so we skip it
  1822. // in receivepacket()
  1823. FPacketReservations->Items[Reservation] = NULL;
  1824. }
  1825. }
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. int __fastcall TSFTPFileSystem::ReceiveResponse(
  1829. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1830. int AllowStatus)
  1831. {
  1832. int Result;
  1833. unsigned int MessageNumber = Packet->MessageNumber;
  1834. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  1835. try
  1836. {
  1837. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus);
  1838. if (MessageNumber != AResponse->MessageNumber)
  1839. {
  1840. FTerminal->FatalError(FMTLOAD(SFTP_MESSAGE_NUMBER,
  1841. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  1842. }
  1843. }
  1844. __finally
  1845. {
  1846. if (!Response) delete AResponse;
  1847. }
  1848. return Result;
  1849. }
  1850. //---------------------------------------------------------------------------
  1851. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  1852. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1853. int AllowStatus)
  1854. {
  1855. int Result;
  1856. TSFTPBusy Busy(this);
  1857. SendPacket(Packet);
  1858. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  1859. return Result;
  1860. }
  1861. //---------------------------------------------------------------------------
  1862. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path)
  1863. {
  1864. try
  1865. {
  1866. FTerminal->LogEvent(FORMAT("Getting real path for '%s'",
  1867. (Path)));
  1868. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1869. Packet.AddPathString(Path, FUtfStrings);
  1870. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  1871. if (Packet.GetCardinal() != 1)
  1872. {
  1873. FTerminal->FatalError(LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  1874. }
  1875. AnsiString RealDir = Packet.GetPathString(FUtfStrings);
  1876. // ignore rest of SSH_FXP_NAME packet
  1877. FTerminal->LogEvent(FORMAT("Real path is '%s'", (RealDir)));
  1878. return RealDir;
  1879. }
  1880. catch(Exception & E)
  1881. {
  1882. if (FTerminal->Active)
  1883. {
  1884. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  1885. }
  1886. else
  1887. {
  1888. throw;
  1889. }
  1890. }
  1891. }
  1892. //---------------------------------------------------------------------------
  1893. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path,
  1894. const AnsiString BaseDir)
  1895. {
  1896. AnsiString APath;
  1897. if (TTerminal::IsAbsolutePath(Path))
  1898. {
  1899. APath = Path;
  1900. }
  1901. else
  1902. {
  1903. if (!Path.IsEmpty())
  1904. {
  1905. // this condition/block was outside (before) current block
  1906. // but it dod not work when Path was empty
  1907. if (!BaseDir.IsEmpty())
  1908. {
  1909. APath = UnixIncludeTrailingBackslash(BaseDir);
  1910. }
  1911. APath = APath + Path;
  1912. }
  1913. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(".");
  1914. }
  1915. return RealPath(APath);
  1916. }
  1917. //---------------------------------------------------------------------------
  1918. AnsiString __fastcall TSFTPFileSystem::LocalCanonify(const AnsiString & Path)
  1919. {
  1920. // TODO: improve (handle .. etc.)
  1921. if (TTerminal::IsAbsolutePath(Path)) return Path;
  1922. else
  1923. {
  1924. return UnixIncludeTrailingBackslash(FCurrentDirectory) + Path;
  1925. }
  1926. }
  1927. //---------------------------------------------------------------------------
  1928. AnsiString __fastcall TSFTPFileSystem::Canonify(AnsiString Path)
  1929. {
  1930. // inspired by canonify() from PSFTP.C
  1931. AnsiString Result;
  1932. FTerminal->LogEvent(FORMAT("Canonifying: \"%s\"", (Path)));
  1933. Path = LocalCanonify(Path);
  1934. bool TryParent = false;
  1935. try
  1936. {
  1937. Result = RealPath(Path);
  1938. }
  1939. catch(...)
  1940. {
  1941. if (FTerminal->Active)
  1942. {
  1943. TryParent = true;
  1944. }
  1945. else
  1946. {
  1947. throw;
  1948. }
  1949. }
  1950. if (TryParent)
  1951. {
  1952. AnsiString APath = UnixExcludeTrailingBackslash(Path);
  1953. AnsiString Name = UnixExtractFileName(APath);
  1954. if (Name == "." || Name == "..")
  1955. {
  1956. Result = Path;
  1957. }
  1958. else
  1959. {
  1960. AnsiString FPath = UnixExtractFilePath(APath);
  1961. try
  1962. {
  1963. Result = RealPath(FPath);
  1964. Result = UnixIncludeTrailingBackslash(Result) + Name;
  1965. }
  1966. catch(...)
  1967. {
  1968. if (FTerminal->Active)
  1969. {
  1970. Result = Path;
  1971. }
  1972. else
  1973. {
  1974. throw;
  1975. }
  1976. }
  1977. }
  1978. }
  1979. FTerminal->LogEvent(FORMAT("Canonified: \"%s\"", (Result)));
  1980. return Result;
  1981. }
  1982. //---------------------------------------------------------------------------
  1983. AnsiString __fastcall TSFTPFileSystem::AbsolutePath(AnsiString Path)
  1984. {
  1985. return RealPath(Path, CurrentDirectory);
  1986. }
  1987. //---------------------------------------------------------------------------
  1988. AnsiString __fastcall TSFTPFileSystem::GetHomeDirectory()
  1989. {
  1990. if (FHomeDirectory.IsEmpty())
  1991. {
  1992. FHomeDirectory = RealPath(".");
  1993. }
  1994. return FHomeDirectory;
  1995. }
  1996. //---------------------------------------------------------------------------
  1997. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  1998. TRemoteFile * ALinkedByFile, const AnsiString FileName)
  1999. {
  2000. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  2001. try
  2002. {
  2003. File->Terminal = FTerminal;
  2004. if (!FileName.IsEmpty())
  2005. {
  2006. File->FileName = FileName;
  2007. }
  2008. Packet->GetFile(File, FVersion, FTerminal->SessionData->ConsiderDST, FUtfStrings, FSignedTS);
  2009. }
  2010. catch(...)
  2011. {
  2012. delete File;
  2013. throw;
  2014. }
  2015. return File;
  2016. }
  2017. //---------------------------------------------------------------------------
  2018. void __fastcall TSFTPFileSystem::SetCurrentDirectory(AnsiString value)
  2019. {
  2020. assert(false);
  2021. }
  2022. //---------------------------------------------------------------------------
  2023. AnsiString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  2024. {
  2025. return FCurrentDirectory;
  2026. }
  2027. //---------------------------------------------------------------------------
  2028. void __fastcall TSFTPFileSystem::DoStartup()
  2029. {
  2030. TSFTPPacket Packet(SSH_FXP_INIT);
  2031. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  2032. if (MaxVersion > SFTPMaxVersion)
  2033. {
  2034. MaxVersion = SFTPMaxVersion;
  2035. }
  2036. Packet.AddCardinal(MaxVersion);
  2037. try
  2038. {
  2039. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  2040. }
  2041. catch(Exception &E)
  2042. {
  2043. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR));
  2044. }
  2045. FVersion = Packet.GetCardinal();
  2046. FTerminal->LogEvent(FORMAT("SFTP version %d negotiated.", (FVersion)));
  2047. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  2048. {
  2049. FTerminal->FatalError(FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  2050. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  2051. }
  2052. if (FVersion >= 3)
  2053. {
  2054. FEOL = "\r\n";
  2055. AnsiString ExtensionName;
  2056. AnsiString ExtensionData;
  2057. AnsiString ExtensionDisplayData;
  2058. while (Packet.GetNextData() != NULL)
  2059. {
  2060. ExtensionName = Packet.GetString();
  2061. ExtensionData = Packet.GetString();
  2062. ExtensionDisplayData = IsDisplayableStr(ExtensionData) ? ExtensionData :
  2063. "0x" + StrToHex(ExtensionData);
  2064. if (ExtensionName == SFTP_EXT_NEWLINE)
  2065. {
  2066. FEOL = ExtensionData;
  2067. FTerminal->LogEvent(FORMAT("Server requests EOL sequence %s.",
  2068. (ExtensionDisplayData)));
  2069. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2070. {
  2071. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2072. }
  2073. }
  2074. else if ((ExtensionName == SFTP_EXT_SUPPORTED) || (ExtensionName == SFTP_EXT_SUPPORTED2))
  2075. {
  2076. FSupport->Reset();
  2077. TSFTPPacket SupportedStruct(ExtensionData);
  2078. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2079. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2080. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2081. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2082. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2083. if (ExtensionName == SFTP_EXT_SUPPORTED)
  2084. {
  2085. while (SupportedStruct.GetNextData() != NULL)
  2086. {
  2087. FSupport->Extensions->Add(SupportedStruct.GetString());
  2088. }
  2089. }
  2090. else
  2091. {
  2092. FSupport->OpenBlockMasks = SupportedStruct.GetSmallCardinal();
  2093. FSupport->BlockMasks = SupportedStruct.GetSmallCardinal();
  2094. unsigned int ExtensionCount;
  2095. ExtensionCount = SupportedStruct.GetCardinal();
  2096. for (unsigned int i = 0; i < ExtensionCount; i++)
  2097. {
  2098. FSupport->AttribExtensions->Add(SupportedStruct.GetString());
  2099. }
  2100. ExtensionCount = SupportedStruct.GetCardinal();
  2101. for (unsigned int i = 0; i < ExtensionCount; i++)
  2102. {
  2103. FSupport->Extensions->Add(SupportedStruct.GetString());
  2104. }
  2105. }
  2106. if (FTerminal->IsLogging())
  2107. {
  2108. FTerminal->LogEvent(FORMAT(
  2109. "Server support information:\n"
  2110. " Attribute mask: %x, Attribute bits: %x, Open flags: %x\n"
  2111. " Access mask: %x, Open block masks: %x, Block masks: %x, Max read size: %d\n",
  2112. (int(FSupport->AttributeMask),
  2113. int(FSupport->AttributeBits),
  2114. int(FSupport->OpenFlags),
  2115. int(FSupport->AccessMask),
  2116. int(FSupport->OpenBlockMasks),
  2117. int(FSupport->BlockMasks),
  2118. int(FSupport->MaxReadSize))));
  2119. FTerminal->LogEvent(FORMAT( " Attribute extensions (%d)\n", (FSupport->AttribExtensions->Count)));
  2120. for (int Index = 0; Index < FSupport->AttribExtensions->Count; Index++)
  2121. {
  2122. FTerminal->LogEvent(
  2123. FORMAT(" %s", (FSupport->AttribExtensions->Strings[Index])));
  2124. }
  2125. FTerminal->LogEvent(FORMAT( " Extensions (%d)\n", (FSupport->Extensions->Count)));
  2126. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2127. {
  2128. FTerminal->LogEvent(
  2129. FORMAT(" %s", (FSupport->Extensions->Strings[Index])));
  2130. }
  2131. }
  2132. }
  2133. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2134. {
  2135. TSFTPPacket VendorIdStruct(ExtensionData);
  2136. AnsiString VendorName(VendorIdStruct.GetString());
  2137. AnsiString ProductName(VendorIdStruct.GetString());
  2138. AnsiString ProductVersion(VendorIdStruct.GetString());
  2139. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2140. FTerminal->LogEvent(FORMAT("Server software: %s %s (%d) by %s",
  2141. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2142. }
  2143. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2144. {
  2145. FTerminal->LogEvent("File system roots:\n");
  2146. assert(FFixedPaths == NULL);
  2147. FFixedPaths = new TStringList();
  2148. try
  2149. {
  2150. TSFTPPacket RootsPacket(ExtensionData);
  2151. while (RootsPacket.GetNextData() != NULL)
  2152. {
  2153. unsigned long Dummy = RootsPacket.GetCardinal();
  2154. if (Dummy != 1)
  2155. {
  2156. break;
  2157. }
  2158. else
  2159. {
  2160. char Drive = RootsPacket.GetByte();
  2161. char MaybeType = RootsPacket.GetByte();
  2162. FTerminal->LogEvent(FORMAT(" %s: (type %d)", (Drive, (int)MaybeType)));
  2163. FFixedPaths->Add(FORMAT("%s:", (Drive)));
  2164. }
  2165. }
  2166. }
  2167. catch(Exception & E)
  2168. {
  2169. FFixedPaths->Clear();
  2170. FTerminal->LogEvent(FORMAT("Failed to decode %s extension",
  2171. (SFTP_EXT_FSROOTS)));
  2172. FTerminal->HandleException(&E);
  2173. }
  2174. }
  2175. else
  2176. {
  2177. FTerminal->LogEvent(FORMAT("Unknown server extension %s=%s",
  2178. (ExtensionName, ExtensionDisplayData)));
  2179. }
  2180. FExtensions->Values[ExtensionName] = ExtensionData;
  2181. }
  2182. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  2183. {
  2184. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  2185. Packet.AddString(SFTP_EXT_VENDOR_ID);
  2186. Packet.AddString(FTerminal->Configuration->CompanyName);
  2187. Packet.AddString(FTerminal->Configuration->ProductName);
  2188. Packet.AddString(FTerminal->Configuration->ProductVersion);
  2189. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  2190. SendPacket(&Packet);
  2191. // we are not interested in the response, do not wait for it
  2192. ReserveResponse(&Packet, NULL);
  2193. }
  2194. }
  2195. if (FVersion < 4)
  2196. {
  2197. // currently enable the bug for all servers (really known on OpenSSH)
  2198. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  2199. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  2200. if (FSignedTS)
  2201. {
  2202. FTerminal->LogEvent("We believe the server has signed timestamps bug");
  2203. }
  2204. }
  2205. // use UTF when forced or ...
  2206. // when "auto" and version is at least 4 and the server is not know not to use UTF
  2207. FUtfNever = (FTerminal->SshImplementation.Pos("Foxit-WAC-Server") == 1) ||
  2208. (FTerminal->SessionData->SFTPBug[sbUtf] == asOn);
  2209. FUtfStrings =
  2210. (FTerminal->SessionData->SFTPBug[sbUtf] == asOff) ||
  2211. ((FTerminal->SessionData->SFTPBug[sbUtf] == asAuto) &&
  2212. (FVersion >= 4) && !FUtfNever);
  2213. if (FUtfStrings)
  2214. {
  2215. FTerminal->LogEvent("We will use UTF-8 strings when appropriate");
  2216. }
  2217. else if (FUtfNever)
  2218. {
  2219. FTerminal->LogEvent("We will never use UTF-8 strings");
  2220. }
  2221. else
  2222. {
  2223. FTerminal->LogEvent("We will use UTF-8 strings for status messages only");
  2224. }
  2225. FMaxPacketSize = FTerminal->SessionData->SFTPMaxPacketSize;
  2226. if (FMaxPacketSize == 0)
  2227. {
  2228. if (FTerminal->SshImplementation.Pos("OpenSSH") == 1)
  2229. {
  2230. FMaxPacketSize = 4 + (256 * 1024); // len + 256kB payload
  2231. FTerminal->LogEvent(FORMAT("Limiting packet size to OpenSSH limit of %d bytes",
  2232. (int(FMaxPacketSize))));
  2233. }
  2234. }
  2235. }
  2236. //---------------------------------------------------------------------------
  2237. char * __fastcall TSFTPFileSystem::GetEOL() const
  2238. {
  2239. if (FVersion >= 4)
  2240. {
  2241. assert(!FEOL.IsEmpty());
  2242. return FEOL.c_str();
  2243. }
  2244. else
  2245. {
  2246. return EOLToStr(FTerminal->SessionData->EOLType);
  2247. }
  2248. }
  2249. //---------------------------------------------------------------------------
  2250. void __fastcall TSFTPFileSystem::LookupUsersGroups()
  2251. {
  2252. assert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
  2253. TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
  2254. TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
  2255. TSFTPPacket * Packet;
  2256. TUsersGroupsList * List;
  2257. TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
  2258. TUsersGroupsList * Lists[] = { FTerminal->FUsers, FTerminal->FGroups };
  2259. char ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
  2260. for (int Index = 0; Index < LENOF(Packets); Index++)
  2261. {
  2262. Packet = Packets[Index];
  2263. Packet->AddString(SFTP_EXT_OWNER_GROUP);
  2264. Packet->AddByte(ListTypes[Index]);
  2265. SendPacket(Packet);
  2266. ReserveResponse(Packet, Packet);
  2267. }
  2268. for (int Index = 0; Index < LENOF(Packets); Index++)
  2269. {
  2270. Packet = Packets[Index];
  2271. ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
  2272. if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
  2273. (Packet->GetString() != SFTP_EXT_OWNER_GROUP_REPLY))
  2274. {
  2275. FTerminal->LogEvent(FORMAT("Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
  2276. }
  2277. else
  2278. {
  2279. List = Lists[Index];
  2280. unsigned long Count = Packet->GetCardinal();
  2281. List->BeginUpdate();
  2282. try
  2283. {
  2284. List->Clear();
  2285. for (unsigned long Item = 0; Item < Count; Item++)
  2286. {
  2287. List->Add(Packet->GetString(!FUtfNever));
  2288. }
  2289. }
  2290. __finally
  2291. {
  2292. List->EndUpdate();
  2293. }
  2294. }
  2295. }
  2296. }
  2297. //---------------------------------------------------------------------------
  2298. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  2299. {
  2300. if (!FDirectoryToChangeTo.IsEmpty())
  2301. {
  2302. FCurrentDirectory = FDirectoryToChangeTo;
  2303. FDirectoryToChangeTo = "";
  2304. }
  2305. else if (FCurrentDirectory.IsEmpty())
  2306. {
  2307. // this happens only after startup when default remote directory is not specified
  2308. FCurrentDirectory = GetHomeDirectory();
  2309. }
  2310. }
  2311. //---------------------------------------------------------------------------
  2312. void __fastcall TSFTPFileSystem::HomeDirectory()
  2313. {
  2314. ChangeDirectory(GetHomeDirectory());
  2315. }
  2316. //---------------------------------------------------------------------------
  2317. void __fastcall TSFTPFileSystem::TryOpenDirectory(const AnsiString Directory)
  2318. {
  2319. FTerminal->LogEvent(FORMAT("Trying to open directory \"%s\".", (Directory)));
  2320. TRemoteFile * File;
  2321. CustomReadFile(Directory, File, SSH_FXP_LSTAT, NULL, asOpUnsupported);
  2322. if (File == NULL)
  2323. {
  2324. // File can be NULL only when server does not support SSH_FXP_LSTAT.
  2325. // Fallback to legacy solution, which in turn does not allow entering
  2326. // traverse-only (chmod 110) directories.
  2327. // This is workaround for http://www.ftpshell.com/
  2328. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2329. Packet.AddPathString(UnixExcludeTrailingBackslash(Directory), FUtfStrings);
  2330. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2331. AnsiString Handle = Packet.GetString();
  2332. Packet.ChangeType(SSH_FXP_CLOSE);
  2333. Packet.AddString(Handle);
  2334. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  2335. }
  2336. else
  2337. {
  2338. delete File;
  2339. }
  2340. }
  2341. //---------------------------------------------------------------------------
  2342. void __fastcall TSFTPFileSystem::ChangeDirectory(const AnsiString Directory)
  2343. {
  2344. AnsiString Path, Current;
  2345. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  2346. Path = RealPath(Directory, Current);
  2347. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  2348. // for invalid paths on some systems, like CygWin)
  2349. TryOpenDirectory(Path);
  2350. // if open dir did not fail, directory exists -> success.
  2351. FDirectoryToChangeTo = Path;
  2352. }
  2353. //---------------------------------------------------------------------------
  2354. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  2355. {
  2356. FDirectoryToChangeTo = Directory;
  2357. }
  2358. //---------------------------------------------------------------------------
  2359. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  2360. {
  2361. assert(FileList && !FileList->Directory.IsEmpty());
  2362. AnsiString Directory;
  2363. Directory = UnixExcludeTrailingBackslash(LocalCanonify(FileList->Directory));
  2364. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".", (Directory)));
  2365. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  2366. // old data (e.g. parent directory) when reading fails
  2367. FileList->Clear();
  2368. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2369. AnsiString Handle;
  2370. try
  2371. {
  2372. Packet.AddPathString(Directory, FUtfStrings);
  2373. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2374. Handle = Packet.GetString();
  2375. }
  2376. catch(...)
  2377. {
  2378. if (FTerminal->Active)
  2379. {
  2380. FileList->AddFile(new TRemoteParentDirectory());
  2381. }
  2382. throw;
  2383. }
  2384. TSFTPPacket Response;
  2385. try
  2386. {
  2387. bool isEOF = false;
  2388. int Total = 0;
  2389. TRemoteFile * File;
  2390. Packet.ChangeType(SSH_FXP_READDIR);
  2391. Packet.AddString(Handle);
  2392. SendPacket(&Packet);
  2393. do
  2394. {
  2395. ReceiveResponse(&Packet, &Response);
  2396. if (Response.Type == SSH_FXP_NAME)
  2397. {
  2398. TSFTPPacket ListingPacket = Response;
  2399. Packet.ChangeType(SSH_FXP_READDIR);
  2400. Packet.AddString(Handle);
  2401. SendPacket(&Packet);
  2402. ReserveResponse(&Packet, &Response);
  2403. unsigned int Count = ListingPacket.GetCardinal();
  2404. for (unsigned long Index = 0; Index < Count; Index++)
  2405. {
  2406. File = LoadFile(&ListingPacket, NULL, "");
  2407. // security fix
  2408. // (LastDelimiter works for MBCS)
  2409. if (((File->FileName.Length() > 2) && IsDots(File->FileName)) ||
  2410. (File->FileName.LastDelimiter("/\\") > 0))
  2411. {
  2412. FTerminal->LogEvent(FORMAT("Ignored suspicious file '%s'", (File->FileName)));
  2413. delete File;
  2414. }
  2415. else
  2416. {
  2417. FileList->AddFile(File);
  2418. Total++;
  2419. }
  2420. if (Total % 10 == 0)
  2421. {
  2422. FTerminal->DoReadDirectoryProgress(Total);
  2423. }
  2424. }
  2425. if (Count == 0)
  2426. {
  2427. FTerminal->LogEvent("Empty directory listing packet. Aborting directory reading.");
  2428. isEOF = true;
  2429. }
  2430. }
  2431. else if (Response.Type == SSH_FXP_STATUS)
  2432. {
  2433. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  2434. }
  2435. else
  2436. {
  2437. FTerminal->FatalError(FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  2438. }
  2439. }
  2440. while (!isEOF);
  2441. if (Total == 0)
  2442. {
  2443. // Empty file list -> probably "permision denied", we
  2444. // at least get link to parent directory ("..")
  2445. try
  2446. {
  2447. FTerminal->ExceptionOnFail = true;
  2448. try
  2449. {
  2450. File = NULL;
  2451. FTerminal->ReadFile(
  2452. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  2453. }
  2454. __finally
  2455. {
  2456. FTerminal->ExceptionOnFail = false;
  2457. }
  2458. }
  2459. catch(Exception &E)
  2460. {
  2461. if (E.InheritsFrom(__classid(EFatal))) throw;
  2462. else File = NULL;
  2463. }
  2464. // on some systems even getting ".." fails, we create dummy ".." instead
  2465. bool Failure = (File == NULL);
  2466. if (Failure)
  2467. {
  2468. File = new TRemoteParentDirectory();
  2469. }
  2470. assert(File && File->IsParentDirectory);
  2471. FileList->AddFile(File);
  2472. if (Failure)
  2473. {
  2474. throw Exception(FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)));
  2475. }
  2476. }
  2477. }
  2478. __finally
  2479. {
  2480. if (FTerminal->Active)
  2481. {
  2482. Packet.ChangeType(SSH_FXP_CLOSE);
  2483. Packet.AddString(Handle);
  2484. SendPacket(&Packet);
  2485. // we are not interested in the response, do not wait for it
  2486. ReserveResponse(&Packet, NULL);
  2487. }
  2488. }
  2489. }
  2490. //---------------------------------------------------------------------------
  2491. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  2492. TRemoteFile *& File)
  2493. {
  2494. assert(SymlinkFile && SymlinkFile->IsSymLink);
  2495. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2496. AnsiString FileName = LocalCanonify(SymlinkFile->FileName);
  2497. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  2498. ReadLinkPacket.AddPathString(FileName, FUtfStrings);
  2499. SendPacket(&ReadLinkPacket);
  2500. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  2501. // send second request before reading response to first one
  2502. // (performance benefit)
  2503. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  2504. AttrsPacket.AddPathString(FileName, FUtfStrings);
  2505. if (FVersion >= 4)
  2506. {
  2507. AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
  2508. }
  2509. SendPacket(&AttrsPacket);
  2510. ReserveResponse(&AttrsPacket, &AttrsPacket);
  2511. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  2512. if (ReadLinkPacket.GetCardinal() != 1)
  2513. {
  2514. FTerminal->FatalError(LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2515. }
  2516. SymlinkFile->LinkTo = ReadLinkPacket.GetPathString(FUtfStrings);
  2517. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  2518. // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
  2519. File = LoadFile(&AttrsPacket, SymlinkFile,
  2520. UnixExtractFileName(SymlinkFile->LinkTo));
  2521. }
  2522. //---------------------------------------------------------------------------
  2523. void __fastcall TSFTPFileSystem::ReadFile(const AnsiString FileName,
  2524. TRemoteFile *& File)
  2525. {
  2526. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  2527. }
  2528. //---------------------------------------------------------------------------
  2529. bool __fastcall TSFTPFileSystem::RemoteFileExists(const AnsiString FullPath,
  2530. TRemoteFile ** File)
  2531. {
  2532. bool Result;
  2533. try
  2534. {
  2535. TRemoteFile * AFile;
  2536. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, asNoSuchFile);
  2537. Result = (AFile != NULL);
  2538. if (Result)
  2539. {
  2540. if (File)
  2541. {
  2542. *File = AFile;
  2543. }
  2544. else
  2545. {
  2546. delete AFile;
  2547. }
  2548. }
  2549. }
  2550. catch(...)
  2551. {
  2552. if (!FTerminal->Active)
  2553. {
  2554. throw;
  2555. }
  2556. Result = false;
  2557. }
  2558. return Result;
  2559. }
  2560. //---------------------------------------------------------------------------
  2561. void __fastcall TSFTPFileSystem::CustomReadFile(const AnsiString FileName,
  2562. TRemoteFile *& File, char Type, TRemoteFile * ALinkedByFile,
  2563. int AllowStatus)
  2564. {
  2565. TSFTPPacket Packet(Type);
  2566. Packet.AddPathString(LocalCanonify(FileName), FUtfStrings);
  2567. if (FVersion >= 4)
  2568. {
  2569. Packet.AddCardinal(SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  2570. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  2571. SSH_FILEXFER_ATTR_OWNERGROUP);
  2572. }
  2573. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS,
  2574. AllowStatus);
  2575. if (Packet.Type == SSH_FXP_ATTRS)
  2576. {
  2577. File = LoadFile(&Packet, ALinkedByFile, UnixExtractFileName(FileName));
  2578. }
  2579. else
  2580. {
  2581. assert(AllowStatus > 0);
  2582. File = NULL;
  2583. }
  2584. }
  2585. //---------------------------------------------------------------------------
  2586. void __fastcall TSFTPFileSystem::DeleteFile(const AnsiString FileName,
  2587. const TRemoteFile * File, bool Recursive)
  2588. {
  2589. char Type;
  2590. AnsiString RealFileName = LocalCanonify(FileName);
  2591. if (File && File->IsDirectory && !File->IsSymLink)
  2592. {
  2593. if (Recursive)
  2594. {
  2595. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Recursive);
  2596. }
  2597. Type = SSH_FXP_RMDIR;
  2598. }
  2599. else
  2600. {
  2601. Type = SSH_FXP_REMOVE;
  2602. }
  2603. TSFTPPacket Packet(Type);
  2604. Packet.AddPathString(RealFileName, FUtfStrings);
  2605. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2606. }
  2607. //---------------------------------------------------------------------------
  2608. void __fastcall TSFTPFileSystem::RenameFile(const AnsiString FileName,
  2609. const AnsiString NewName)
  2610. {
  2611. TSFTPPacket Packet(SSH_FXP_RENAME);
  2612. AnsiString RealName = LocalCanonify(FileName);
  2613. Packet.AddPathString(RealName, FUtfStrings);
  2614. AnsiString TargetName;
  2615. if (UnixExtractFilePath(NewName).IsEmpty())
  2616. {
  2617. // rename case (TTerminal::RenameFile)
  2618. TargetName = UnixExtractFilePath(RealName) + NewName;
  2619. }
  2620. else
  2621. {
  2622. TargetName = LocalCanonify(NewName);
  2623. }
  2624. Packet.AddPathString(TargetName, FUtfStrings);
  2625. if (FVersion >= 5)
  2626. {
  2627. Packet.AddCardinal(0);
  2628. }
  2629. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2630. }
  2631. //---------------------------------------------------------------------------
  2632. void __fastcall TSFTPFileSystem::CopyFile(const AnsiString /*FileName*/,
  2633. const AnsiString /*NewName*/)
  2634. {
  2635. assert(false);
  2636. }
  2637. //---------------------------------------------------------------------------
  2638. void __fastcall TSFTPFileSystem::CreateDirectory(const AnsiString DirName,
  2639. const TRemoteProperties * Properties)
  2640. {
  2641. TSFTPPacket Packet(SSH_FXP_MKDIR);
  2642. AnsiString CanonifiedName = Canonify(DirName);
  2643. Packet.AddPathString(CanonifiedName, FUtfStrings);
  2644. Packet.AddProperties(NULL, 0, true, FVersion, FUtfStrings);
  2645. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2646. // explicitly set permissions after directory creation,
  2647. // permissions specified in SSH_FXP_MKDIR are ignored at least by OpenSSH
  2648. try
  2649. {
  2650. Packet.ChangeType(SSH_FXP_SETSTAT);
  2651. Packet.AddPathString(CanonifiedName, FUtfStrings);
  2652. Packet.AddProperties(Properties, 0, true, FVersion, FUtfStrings);
  2653. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2654. }
  2655. catch(Exception & E)
  2656. {
  2657. if (FTerminal->Active)
  2658. {
  2659. throw ECommand(&E, FMTLOAD(CHANGE_PROPERTIES_ERROR, (DirName)));
  2660. }
  2661. else
  2662. {
  2663. throw;
  2664. }
  2665. }
  2666. }
  2667. //---------------------------------------------------------------------------
  2668. void __fastcall TSFTPFileSystem::CreateLink(const AnsiString FileName,
  2669. const AnsiString PointTo, bool Symbolic)
  2670. {
  2671. USEDPARAM(Symbolic);
  2672. assert(Symbolic); // only symlinks are supported by SFTP
  2673. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2674. TSFTPPacket Packet(SSH_FXP_SYMLINK);
  2675. bool Buggy = (FTerminal->SessionData->SFTPBug[sbSymlink] == asOn) ||
  2676. ((FTerminal->SessionData->SFTPBug[sbSymlink] == asAuto) &&
  2677. (FTerminal->SshImplementation.Pos("OpenSSH") == 1));
  2678. if (!Buggy)
  2679. {
  2680. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  2681. Packet.AddPathString(PointTo, FUtfStrings);
  2682. }
  2683. else
  2684. {
  2685. FTerminal->LogEvent("We believe the server has SFTP symlink bug");
  2686. Packet.AddPathString(PointTo, FUtfStrings);
  2687. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  2688. }
  2689. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2690. }
  2691. //---------------------------------------------------------------------------
  2692. void __fastcall TSFTPFileSystem::ChangeFileProperties(const AnsiString FileName,
  2693. const TRemoteFile * /*File*/, const TRemoteProperties * Properties)
  2694. {
  2695. assert(Properties);
  2696. TRemoteFile * File;
  2697. AnsiString RealFileName = LocalCanonify(FileName);
  2698. ReadFile(RealFileName, File);
  2699. try
  2700. {
  2701. assert(File);
  2702. if (File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  2703. {
  2704. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  2705. (void*)Properties);
  2706. }
  2707. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  2708. Packet.AddPathString(RealFileName, FUtfStrings);
  2709. Packet.AddProperties(Properties, *File->Rights, File->IsDirectory, FVersion, FUtfStrings);
  2710. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2711. }
  2712. __finally
  2713. {
  2714. delete File;
  2715. }
  2716. }
  2717. //---------------------------------------------------------------------------
  2718. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  2719. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/,
  2720. TLogAddLineEvent /*OutputEvent*/)
  2721. {
  2722. assert(false);
  2723. }
  2724. //---------------------------------------------------------------------------
  2725. void __fastcall TSFTPFileSystem::AnyCommand(const AnsiString /*Command*/,
  2726. TLogAddLineEvent /*OutputEvent*/)
  2727. {
  2728. assert(false);
  2729. }
  2730. //---------------------------------------------------------------------------
  2731. AnsiString __fastcall TSFTPFileSystem::FileUrl(const AnsiString FileName)
  2732. {
  2733. assert(FileName.Length() > 0);
  2734. return AnsiString("sftp://") + FTerminal->SessionData->SessionName +
  2735. (FileName[1] == '/' ? "" : "/") + FileName;
  2736. }
  2737. //---------------------------------------------------------------------------
  2738. TStrings * __fastcall TSFTPFileSystem::GetFixedPaths()
  2739. {
  2740. return FFixedPaths;
  2741. }
  2742. //---------------------------------------------------------------------------
  2743. // transfer protocol
  2744. //---------------------------------------------------------------------------
  2745. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  2746. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  2747. int Params, TFileOperationProgressType * OperationProgress,
  2748. bool & DisconnectWhenComplete)
  2749. {
  2750. assert(FilesToCopy && OperationProgress);
  2751. AnsiString FileName, FileNameOnly;
  2752. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  2753. int Index = 0;
  2754. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  2755. {
  2756. bool Success = false;
  2757. FileName = FilesToCopy->Strings[Index];
  2758. FileNameOnly = ExtractFileName(FileName);
  2759. assert(!FAvoidBusy);
  2760. FAvoidBusy = true;
  2761. try
  2762. {
  2763. try
  2764. {
  2765. if (FTerminal->SessionData->CacheDirectories)
  2766. {
  2767. FTerminal->DirectoryModified(TargetDir, false);
  2768. if (DirectoryExists(FileName))
  2769. {
  2770. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  2771. FileNameOnly, true);
  2772. }
  2773. }
  2774. SFTPSource(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  2775. tfFirstLevel);
  2776. Success = true;
  2777. }
  2778. catch(EScpSkipFile & E)
  2779. {
  2780. SUSPEND_OPERATION (
  2781. if (!FTerminal->HandleException(&E)) throw;
  2782. );
  2783. }
  2784. }
  2785. __finally
  2786. {
  2787. FAvoidBusy = false;
  2788. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  2789. }
  2790. Index++;
  2791. }
  2792. }
  2793. //---------------------------------------------------------------------------
  2794. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(const AnsiString FileName,
  2795. bool TargetBiggerThanSource, TFileOperationProgressType * OperationProgress,
  2796. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  2797. {
  2798. bool CanAlternateResume = !TargetBiggerThanSource && !OperationProgress->AsciiTransfer;
  2799. if (OperationProgress->NoToAll)
  2800. {
  2801. THROW_SKIP_FILE_NULL;
  2802. }
  2803. else if (CanAlternateResume && OperationProgress->AlternateResumeAlways)
  2804. {
  2805. OverwriteMode = omResume;
  2806. }
  2807. else
  2808. {
  2809. int Answer;
  2810. SUSPEND_OPERATION
  2811. (
  2812. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll;
  2813. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  2814. {
  2815. Answers |= qaRetry;
  2816. }
  2817. TQueryButtonAlias Aliases[2];
  2818. Aliases[0].Button = qaRetry;
  2819. Aliases[0].Alias = LoadStr(APPEND_BUTTON);
  2820. Aliases[1].Button = qaAll;
  2821. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  2822. TQueryParams Params(qpNeverAskAgainCheck);
  2823. Params.Aliases = Aliases;
  2824. Params.AliasesCount = LENOF(Aliases);
  2825. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  2826. Answers, &Params,
  2827. OperationProgress->Side == osLocal ? osRemote : osLocal,
  2828. OperationProgress);
  2829. );
  2830. if (Answer == qaRetry)
  2831. {
  2832. if (!CanAlternateResume)
  2833. {
  2834. OverwriteMode = omAppend;
  2835. }
  2836. else
  2837. {
  2838. TQueryParams Params(0, HELP_APPEND_OR_RESUME);
  2839. SUSPEND_OPERATION
  2840. (
  2841. Answer = FTerminal->DoQueryUser(FORMAT(LoadStr(APPEND_OR_RESUME), (FileName)),
  2842. qaYes | qaNo | qaNoToAll | qaCancel, &Params);
  2843. );
  2844. switch (Answer)
  2845. {
  2846. case qaYes:
  2847. OverwriteMode = omAppend;
  2848. break;
  2849. case qaNo:
  2850. OverwriteMode = omResume;
  2851. break;
  2852. case qaNoToAll:
  2853. OverwriteMode = omResume;
  2854. OperationProgress->AlternateResumeAlways = true;
  2855. break;
  2856. default: assert(false); //fallthru
  2857. case qaCancel:
  2858. if (!OperationProgress->Cancel)
  2859. {
  2860. OperationProgress->Cancel = csCancel;
  2861. }
  2862. Abort();
  2863. break;
  2864. }
  2865. }
  2866. }
  2867. else
  2868. {
  2869. OverwriteMode = omOverwrite;
  2870. switch (Answer)
  2871. {
  2872. case qaCancel:
  2873. if (!OperationProgress->Cancel)
  2874. {
  2875. OperationProgress->Cancel = csCancel;
  2876. }
  2877. Abort();
  2878. break;
  2879. case qaNo:
  2880. THROW_SKIP_FILE_NULL;
  2881. }
  2882. }
  2883. }
  2884. }
  2885. //---------------------------------------------------------------------------
  2886. bool TSFTPFileSystem::SFTPConfirmResume(const AnsiString DestFileName,
  2887. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  2888. {
  2889. bool ResumeTransfer;
  2890. assert(OperationProgress);
  2891. if (PartialBiggerThanSource)
  2892. {
  2893. int Answer;
  2894. SUSPEND_OPERATION
  2895. (
  2896. TQueryParams Params(qpAllowContinueOnError, HELP_PARTIAL_BIGGER_THAN_SOURCE);
  2897. Answer = FTerminal->DoQueryUser(
  2898. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)),
  2899. qaOK | qaAbort, &Params, qtWarning);
  2900. )
  2901. if (Answer == qaAbort)
  2902. {
  2903. if (!OperationProgress->Cancel)
  2904. {
  2905. OperationProgress->Cancel = csCancel;
  2906. }
  2907. Abort();
  2908. }
  2909. ResumeTransfer = false;
  2910. }
  2911. else if (FTerminal->Configuration->ConfirmResume)
  2912. {
  2913. int Answer;
  2914. SUSPEND_OPERATION
  2915. (
  2916. TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck,
  2917. HELP_RESUME_TRANSFER);
  2918. // "abort" replaced with "cancel" to unify with "append/resume" query
  2919. Answer = FTerminal->DoQueryUser(
  2920. FMTLOAD(RESUME_TRANSFER, (DestFileName)), qaYes | qaNo | qaCancel,
  2921. &Params);
  2922. );
  2923. switch (Answer) {
  2924. case qaNeverAskAgain:
  2925. FTerminal->Configuration->ConfirmResume = false;
  2926. case qaYes:
  2927. ResumeTransfer = true;
  2928. break;
  2929. case qaNo:
  2930. ResumeTransfer = false;
  2931. break;
  2932. case qaCancel:
  2933. if (!OperationProgress->Cancel)
  2934. {
  2935. OperationProgress->Cancel = csCancel;
  2936. }
  2937. Abort();
  2938. break;
  2939. }
  2940. }
  2941. else
  2942. {
  2943. ResumeTransfer = true;
  2944. }
  2945. return ResumeTransfer;
  2946. }
  2947. //---------------------------------------------------------------------------
  2948. void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
  2949. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  2950. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  2951. {
  2952. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  2953. OperationProgress->SetFile(FileName);
  2954. TOpenRemoteFileParams OpenParams;
  2955. OpenParams.OverwriteMode = omOverwrite;
  2956. HANDLE File;
  2957. __int64 MTime, ATime;
  2958. __int64 Size;
  2959. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
  2960. &File, NULL, &MTime, &ATime, &Size);
  2961. bool Dir = FLAGSET(OpenParams.LocalFileAttrs, faDirectory);
  2962. if (FLAGCLEAR(Params, cpDelete) &&
  2963. !CopyParam->AllowTransfer(FileName, osLocal, Dir))
  2964. {
  2965. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  2966. THROW_SKIP_FILE_NULL;
  2967. }
  2968. if (Dir)
  2969. {
  2970. SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  2971. OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
  2972. }
  2973. else
  2974. {
  2975. try
  2976. {
  2977. // File is regular file (not directory)
  2978. assert(File);
  2979. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  2980. osLocal, FLAGSET(Flags, tfFirstLevel));
  2981. AnsiString DestFullName = LocalCanonify(TargetDir + DestFileName);
  2982. AnsiString DestPartinalFullName;
  2983. bool ResumeAllowed;
  2984. bool ResumeTransfer = false;
  2985. bool DestFileExists = false;
  2986. TRights DestRights;
  2987. __int64 ResumeOffset;
  2988. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  2989. OperationProgress->SetLocalSize(Size);
  2990. // Suppose same data size to transfer as to read
  2991. // (not true with ASCII transfer)
  2992. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  2993. OperationProgress->TransferingFile = false;
  2994. // Will we use ASCII of BINARY file tranfer?
  2995. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName, osLocal));
  2996. FTerminal->LogEvent(
  2997. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  2998. " transfer mode selected.");
  2999. ResumeAllowed = !OperationProgress->AsciiTransfer &&
  3000. FLAGCLEAR(Flags, tfNewDirectory) &&
  3001. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  3002. IsCapable(fcRename);
  3003. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  3004. TOverwriteFileParams FileParams;
  3005. FileParams.SourceSize = OperationProgress->LocalSize;
  3006. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  3007. FTerminal->SessionData->ConsiderDST);
  3008. if (ResumeAllowed)
  3009. {
  3010. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3011. FTerminal->LogEvent("Checking existence of file.");
  3012. TRemoteFile * File = new TRemoteFile();
  3013. DestFileExists = RemoteFileExists(DestFullName, &File);
  3014. if (DestFileExists)
  3015. {
  3016. OpenParams.DestFileSize = File->Size;
  3017. FileParams.DestSize = OpenParams.DestFileSize;
  3018. FileParams.DestTimestamp = File->Modification;
  3019. DestRights = *File->Rights;
  3020. delete File;
  3021. File = NULL;
  3022. }
  3023. FTerminal->LogEvent("Checking existence of partially transfered file.");
  3024. if (RemoteFileExists(DestPartinalFullName, &File))
  3025. {
  3026. ResumeOffset = File->Size;
  3027. delete File;
  3028. File = NULL;
  3029. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->LocalSize);
  3030. if (FLAGCLEAR(Params, cpNoConfirmation))
  3031. {
  3032. ResumeTransfer = SFTPConfirmResume(DestFileName,
  3033. PartialBiggerThanSource, OperationProgress);
  3034. }
  3035. else
  3036. {
  3037. ResumeTransfer = !PartialBiggerThanSource;
  3038. }
  3039. if (!ResumeTransfer)
  3040. {
  3041. DeleteFile(DestPartinalFullName);
  3042. }
  3043. else
  3044. {
  3045. FTerminal->LogEvent("Resuming file transfer.");
  3046. }
  3047. }
  3048. else
  3049. {
  3050. // partial upload file does not exists, check for full file
  3051. if (DestFileExists &&
  3052. (FLAGSET(Params, cpNewerOnly) ||
  3053. (FTerminal->Configuration->ConfirmOverwriting &&
  3054. !OperationProgress->YesToAll && FLAGCLEAR(Params, cpNoConfirmation))))
  3055. {
  3056. SFTPConfirmOverwrite(DestFileName,
  3057. OpenParams.DestFileSize >= OperationProgress->LocalSize,
  3058. OperationProgress, OpenParams.OverwriteMode, &FileParams);
  3059. }
  3060. }
  3061. }
  3062. // will the transfer be resumable?
  3063. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  3064. if (DoResume && DestFileExists)
  3065. {
  3066. FILE_OPERATION_LOOP(FMTLOAD(DELETE_BEFORE_RESUME_ERROR,
  3067. (UnixExtractFileName(DestFullName), DestFullName)),
  3068. DeleteFile(DestFullName);
  3069. );
  3070. }
  3071. OpenParams.RemoteFileName = DoResume ? DestPartinalFullName : DestFullName;
  3072. OpenParams.Resume = DoResume;
  3073. OpenParams.OperationProgress = OperationProgress;
  3074. OpenParams.CopyParam = CopyParam;
  3075. OpenParams.Params = Params;
  3076. OpenParams.FileParams = &FileParams;
  3077. OpenParams.Confirmed = false;
  3078. FTerminal->LogEvent("Opening remote file.");
  3079. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
  3080. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  3081. &OpenParams);
  3082. bool TransferFinished = false;
  3083. __int64 DestWriteOffset = 0;
  3084. TSFTPPacket CloseRequest;
  3085. bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
  3086. bool SetProperties = (CopyParam->PreserveTime || SetRights);
  3087. TSFTPPacket PropertiesRequest(SSH_FXP_SETSTAT);
  3088. TSFTPPacket PropertiesResponse;
  3089. if (SetProperties)
  3090. {
  3091. PropertiesRequest.AddPathString(DestFullName, FUtfStrings);
  3092. unsigned short Rights = 0;
  3093. if (CopyParam->PreserveRights)
  3094. {
  3095. Rights = CopyParam->RemoteFileRights(OpenParams.LocalFileAttrs);
  3096. }
  3097. else if (DoResume && DestFileExists)
  3098. {
  3099. Rights = DestRights.NumberSet;
  3100. }
  3101. PropertiesRequest.AddProperties(
  3102. SetRights ? &Rights : NULL, NULL, NULL,
  3103. CopyParam->PreserveTime ? &MTime : NULL,
  3104. CopyParam->PreserveTime ? &ATime : NULL,
  3105. NULL, false, FVersion, FUtfStrings);
  3106. }
  3107. try
  3108. {
  3109. if (OpenParams.OverwriteMode == omAppend)
  3110. {
  3111. FTerminal->LogEvent("Appending file.");
  3112. DestWriteOffset = OpenParams.DestFileSize;
  3113. }
  3114. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  3115. {
  3116. if (OpenParams.OverwriteMode == omResume)
  3117. {
  3118. FTerminal->LogEvent("Resuming file transfer (append style).");
  3119. ResumeOffset = OpenParams.DestFileSize;
  3120. }
  3121. FileSeek((THandle)File, ResumeOffset, 0);
  3122. OperationProgress->AddResumed(ResumeOffset);
  3123. }
  3124. // at end of this block queue is disposed
  3125. {
  3126. TSFTPUploadQueue Queue(this);
  3127. // no need to limit upload queue len by file size, the queue
  3128. // will take care of it itself
  3129. int QueueLen = FTerminal->SessionData->SFTPUploadQueue;
  3130. bool Initialized;
  3131. Initialized = Queue.Init(QueueLen, FileName, File, OperationProgress,
  3132. OpenParams.RemoteFileHandle,
  3133. DestWriteOffset + OperationProgress->TransferedSize);
  3134. if (Initialized)
  3135. {
  3136. while (Queue.Next(SSH_FXP_STATUS))
  3137. {
  3138. if (OperationProgress->Cancel)
  3139. {
  3140. Abort();
  3141. }
  3142. }
  3143. }
  3144. // send close request before waiting for pending read responses
  3145. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3146. OperationProgress, false, true, &CloseRequest);
  3147. OpenParams.RemoteFileHandle = "";
  3148. // when resuming is disabled, we can send "set properties"
  3149. // request before waiting for pending read/close responses
  3150. if (SetProperties && !DoResume)
  3151. {
  3152. SendPacket(&PropertiesRequest);
  3153. ReserveResponse(&PropertiesRequest, &PropertiesResponse);
  3154. }
  3155. }
  3156. TransferFinished = true;
  3157. }
  3158. __finally
  3159. {
  3160. if (FTerminal->Active)
  3161. {
  3162. // if file transfer was finished, the close request was already sent
  3163. if (!OpenParams.RemoteFileHandle.IsEmpty())
  3164. {
  3165. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3166. OperationProgress, TransferFinished, true, &CloseRequest);
  3167. }
  3168. // wait for the response
  3169. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3170. OperationProgress, TransferFinished, false, &CloseRequest);
  3171. // delete file if transfer was not completed, resuming was not allowed and
  3172. // we were not appending (incl. alternate resume),
  3173. // shortly after plain transfer completes (eq. !ResumeAllowed)
  3174. if (!TransferFinished && !DoResume && (OpenParams.OverwriteMode == omOverwrite))
  3175. {
  3176. DeleteFile(OpenParams.RemoteFileName);
  3177. }
  3178. }
  3179. }
  3180. // originally this was before CLOSE (last __finally statement),
  3181. // on VShell it failed
  3182. if (DoResume)
  3183. {
  3184. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  3185. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  3186. RenameFile(OpenParams.RemoteFileName, DestFileName);
  3187. );
  3188. }
  3189. if (SetProperties)
  3190. {
  3191. // when resuming is enabled, the set properties request was not sent yet
  3192. if (DoResume)
  3193. {
  3194. SendPacket(&PropertiesRequest);
  3195. }
  3196. bool Resend = false;
  3197. FILE_OPERATION_LOOP(FMTLOAD(PRESERVE_TIME_PERM_ERROR, (DestFileName)),
  3198. TSFTPPacket DummyResponse;
  3199. TSFTPPacket * Response = &PropertiesResponse;
  3200. if (Resend)
  3201. {
  3202. PropertiesRequest.Reuse();
  3203. SendPacket(&PropertiesRequest);
  3204. // ReceiveResponse currently cannot receive twice into same packet,
  3205. // so DummyResponse is temporary workaround
  3206. Response = &DummyResponse;
  3207. }
  3208. Resend = true;
  3209. ReceiveResponse(&PropertiesRequest, Response, SSH_FXP_STATUS);
  3210. );
  3211. }
  3212. }
  3213. __finally
  3214. {
  3215. CloseHandle(File);
  3216. }
  3217. }
  3218. /* TODO : Delete also read-only files. */
  3219. /* TODO : Show error message on failure. */
  3220. if (FLAGSET(Params, cpDelete))
  3221. {
  3222. Sysutils::DeleteFile(FileName);
  3223. }
  3224. else if (CopyParam->ClearArchive && FLAGSET(OpenParams.LocalFileAttrs, faArchive))
  3225. {
  3226. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  3227. THROWIFFALSE(FileSetAttr(FileName, OpenParams.LocalFileAttrs & ~faArchive) == 0);
  3228. )
  3229. }
  3230. }
  3231. //---------------------------------------------------------------------------
  3232. AnsiString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
  3233. const AnsiString & FileName, unsigned int OpenType, __int64 Size)
  3234. {
  3235. TSFTPPacket Packet(SSH_FXP_OPEN);
  3236. Packet.AddPathString(FileName, FUtfStrings);
  3237. if (FVersion < 5)
  3238. {
  3239. Packet.AddCardinal(OpenType);
  3240. }
  3241. else
  3242. {
  3243. unsigned long Access =
  3244. FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
  3245. FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
  3246. unsigned long Flags;
  3247. if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
  3248. {
  3249. Flags = SSH_FXF_CREATE_NEW;
  3250. }
  3251. else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
  3252. {
  3253. Flags = SSH_FXF_CREATE_TRUNCATE;
  3254. }
  3255. else if (FLAGSET(OpenType, SSH_FXF_CREAT))
  3256. {
  3257. Flags = SSH_FXF_OPEN_OR_CREATE;
  3258. }
  3259. else
  3260. {
  3261. Flags = SSH_FXF_OPEN_EXISTING;
  3262. }
  3263. Flags |=
  3264. FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
  3265. FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
  3266. Packet.AddCardinal(Access);
  3267. Packet.AddCardinal(Flags);
  3268. }
  3269. Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
  3270. Size >= 0 ? &Size : NULL, false, FVersion, FUtfStrings);
  3271. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3272. return Packet.GetString();
  3273. }
  3274. //---------------------------------------------------------------------------
  3275. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  3276. {
  3277. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  3278. assert(OpenParams);
  3279. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  3280. int OpenType;
  3281. bool Success = false;
  3282. do
  3283. {
  3284. try
  3285. {
  3286. OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
  3287. if (FTerminal->Configuration->ConfirmOverwriting &&
  3288. !OpenParams->Confirmed && !OperationProgress->YesToAll && !OpenParams->Resume &&
  3289. !(OpenParams->Params & cpNoConfirmation) &&
  3290. (OpenParams->OverwriteMode == omOverwrite))
  3291. {
  3292. OpenType |= SSH_FXF_EXCL;
  3293. }
  3294. if (!OpenParams->Resume && (OpenParams->OverwriteMode == omOverwrite))
  3295. {
  3296. OpenType |= SSH_FXF_TRUNC;
  3297. }
  3298. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  3299. {
  3300. OpenType |= SSH_FXF_TEXT;
  3301. }
  3302. OpenParams->RemoteFileHandle = SFTPOpenRemoteFile(
  3303. OpenParams->RemoteFileName, OpenType, OperationProgress->LocalSize);
  3304. Success = true;
  3305. }
  3306. catch(Exception & E)
  3307. {
  3308. if (!OpenParams->Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  3309. {
  3310. bool TargetBiggerThanSource;
  3311. bool ThrowOriginal = false;
  3312. // When exclusive opening of file fails, try to detect if file exists.
  3313. // When file does not exist, failure was probably caused by 'permission denied'
  3314. // or similar error. In this case throw original exception.
  3315. try
  3316. {
  3317. TRemoteFile * File;
  3318. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  3319. ReadFile(RealFileName, File);
  3320. OpenParams->DestFileSize = File->Size;
  3321. if (OpenParams->FileParams != NULL)
  3322. {
  3323. OpenParams->FileParams->DestTimestamp = File->Modification;
  3324. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  3325. }
  3326. TargetBiggerThanSource = File->Size >= OperationProgress->LocalSize;
  3327. // file exists (otherwise exception was thrown)
  3328. assert(File);
  3329. SAFE_DESTROY(File);
  3330. }
  3331. catch(...)
  3332. {
  3333. if (!FTerminal->Active)
  3334. {
  3335. throw;
  3336. }
  3337. else
  3338. {
  3339. ThrowOriginal = true;
  3340. }
  3341. }
  3342. if (ThrowOriginal)
  3343. {
  3344. throw;
  3345. }
  3346. // confirmation duplicated in SFTPSource for resumable file transfers.
  3347. SFTPConfirmOverwrite(UnixExtractFileName(OpenParams->RemoteFileName),
  3348. TargetBiggerThanSource, OperationProgress, OpenParams->OverwriteMode,
  3349. OpenParams->FileParams);
  3350. OpenParams->Confirmed = true;
  3351. if (FTerminal->SessionData->OverwrittenToRecycleBin)
  3352. {
  3353. FTerminal->RecycleFile(OpenParams->RemoteFileName, NULL);
  3354. }
  3355. }
  3356. else if (FTerminal->Active)
  3357. {
  3358. // if file overwritting was confirmed, it means that the file already exists,
  3359. // if not, check now
  3360. if (!OpenParams->Confirmed)
  3361. {
  3362. bool ThrowOriginal = false;
  3363. // When file does not exist, failure was probably caused by 'permission denied'
  3364. // or similar error. In this case throw original exception.
  3365. try
  3366. {
  3367. TRemoteFile * File;
  3368. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  3369. ReadFile(RealFileName, File);
  3370. SAFE_DESTROY(File);
  3371. }
  3372. catch(...)
  3373. {
  3374. if (!FTerminal->Active)
  3375. {
  3376. throw;
  3377. }
  3378. else
  3379. {
  3380. ThrowOriginal = true;
  3381. }
  3382. }
  3383. if (ThrowOriginal)
  3384. {
  3385. throw;
  3386. }
  3387. }
  3388. // now we know that the file exists
  3389. if (FTerminal->FileOperationLoopQuery(E, OperationProgress,
  3390. FMTLOAD(SFTP_OVERWRITE_FILE_ERROR, (OpenParams->RemoteFileName)),
  3391. true, LoadStr(SFTP_OVERWRITE_DELETE_BUTTON)))
  3392. {
  3393. bool Recursive = false;
  3394. FTerminal->DeleteFile(OpenParams->RemoteFileName, NULL, &Recursive);
  3395. }
  3396. }
  3397. else
  3398. {
  3399. throw;
  3400. }
  3401. }
  3402. }
  3403. while (!Success);
  3404. return 0;
  3405. }
  3406. //---------------------------------------------------------------------------
  3407. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const AnsiString Handle,
  3408. const AnsiString FileName, TFileOperationProgressType * OperationProgress,
  3409. bool TransferFinished, bool Request, TSFTPPacket * Packet)
  3410. {
  3411. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  3412. FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)),
  3413. try
  3414. {
  3415. TSFTPPacket CloseRequest;
  3416. TSFTPPacket * P = (Packet == NULL ? &CloseRequest : Packet);
  3417. if (Request)
  3418. {
  3419. P->ChangeType(SSH_FXP_CLOSE);
  3420. P->AddString(Handle);
  3421. SendPacket(P);
  3422. ReserveResponse(P, Packet);
  3423. }
  3424. else
  3425. {
  3426. assert(Packet != NULL);
  3427. ReceiveResponse(P, Packet, SSH_FXP_STATUS);
  3428. }
  3429. }
  3430. catch(...)
  3431. {
  3432. if (!FTerminal->Active || TransferFinished)
  3433. {
  3434. throw;
  3435. }
  3436. }
  3437. );
  3438. }
  3439. //---------------------------------------------------------------------------
  3440. void __fastcall TSFTPFileSystem::SFTPDirectorySource(const AnsiString DirectoryName,
  3441. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  3442. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3443. {
  3444. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  3445. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  3446. FLAGSET(Flags, tfFirstLevel));
  3447. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  3448. OperationProgress->SetFile(DirectoryName);
  3449. bool CreateDir = false;
  3450. try
  3451. {
  3452. TryOpenDirectory(DestFullName);
  3453. }
  3454. catch(...)
  3455. {
  3456. if (FTerminal->Active)
  3457. {
  3458. // opening directory failed, it probably does not exists, try to
  3459. // create it
  3460. CreateDir = true;
  3461. }
  3462. else
  3463. {
  3464. throw;
  3465. }
  3466. }
  3467. if (CreateDir)
  3468. {
  3469. TRemoteProperties Properties;
  3470. if (CopyParam->PreserveRights)
  3471. {
  3472. Properties.Valid = TValidProperties() << vpRights;
  3473. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  3474. }
  3475. FTerminal->CreateDirectory(DestFullName, &Properties);
  3476. Flags |= tfNewDirectory;
  3477. }
  3478. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  3479. TSearchRec SearchRec;
  3480. bool FindOK;
  3481. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  3482. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  3483. FindAttrs, SearchRec) == 0);
  3484. );
  3485. while (FindOK && !OperationProgress->Cancel)
  3486. {
  3487. AnsiString FileName = DirectoryName + SearchRec.Name;
  3488. try
  3489. {
  3490. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  3491. {
  3492. SFTPSource(FileName, DestFullName, CopyParam, Params, OperationProgress,
  3493. Flags & ~tfFirstLevel);
  3494. }
  3495. }
  3496. catch (EScpSkipFile &E)
  3497. {
  3498. // If ESkipFile occurs, just log it and continue with next file
  3499. SUSPEND_OPERATION (
  3500. // here a message to user was displayed, which was not appropriate
  3501. // when user refused to overwrite the file in subdirectory.
  3502. // hopefuly it won't be missing in other situations.
  3503. if (!FTerminal->HandleException(&E)) throw;
  3504. );
  3505. }
  3506. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  3507. FindOK = (FindNext(SearchRec) == 0);
  3508. );
  3509. };
  3510. FindClose(SearchRec);
  3511. /* TODO : Delete also read-only directories. */
  3512. /* TODO : Show error message on failure. */
  3513. if (!OperationProgress->Cancel)
  3514. {
  3515. if (FLAGSET(Params, cpDelete))
  3516. {
  3517. RemoveDir(DirectoryName);
  3518. }
  3519. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  3520. {
  3521. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  3522. THROWIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  3523. )
  3524. }
  3525. }
  3526. }
  3527. //---------------------------------------------------------------------------
  3528. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  3529. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  3530. int Params, TFileOperationProgressType * OperationProgress,
  3531. bool & DisconnectWhenComplete)
  3532. {
  3533. assert(FilesToCopy && OperationProgress);
  3534. AnsiString FileName, FileNameOnly;
  3535. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  3536. const TRemoteFile * File;
  3537. bool Success;
  3538. int Index = 0;
  3539. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  3540. {
  3541. Success = false;
  3542. FileName = FilesToCopy->Strings[Index];
  3543. File = (TRemoteFile *)FilesToCopy->Objects[Index];
  3544. assert(!FAvoidBusy);
  3545. FAvoidBusy = true;
  3546. try
  3547. {
  3548. try
  3549. {
  3550. SFTPSink(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
  3551. Params, OperationProgress, tfFirstLevel);
  3552. Success = true;
  3553. }
  3554. catch(EScpSkipFile & E)
  3555. {
  3556. SUSPEND_OPERATION (
  3557. if (!FTerminal->HandleException(&E)) throw;
  3558. );
  3559. }
  3560. catch(...)
  3561. {
  3562. throw;
  3563. }
  3564. }
  3565. __finally
  3566. {
  3567. FAvoidBusy = false;
  3568. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  3569. }
  3570. Index++;
  3571. }
  3572. }
  3573. //---------------------------------------------------------------------------
  3574. void __fastcall TSFTPFileSystem::SFTPSink(const AnsiString FileName,
  3575. const TRemoteFile * File, const AnsiString TargetDir,
  3576. const TCopyParamType * CopyParam, int Params,
  3577. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3578. {
  3579. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  3580. if (FLAGCLEAR(Params, cpDelete) &&
  3581. !CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory))
  3582. {
  3583. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  3584. THROW_SKIP_FILE_NULL;
  3585. }
  3586. assert(File);
  3587. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  3588. OperationProgress->SetFile(OnlyFileName);
  3589. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  3590. osRemote, FLAGSET(Flags, tfFirstLevel));
  3591. AnsiString DestFullName = TargetDir + DestFileName;
  3592. if (File->IsDirectory)
  3593. {
  3594. if (!File->IsSymLink)
  3595. {
  3596. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  3597. int Attrs = FileGetAttr(DestFullName);
  3598. if ((Attrs & faDirectory) == 0) EXCEPTION;
  3599. );
  3600. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  3601. if (!ForceDirectories(DestFullName)) EXCEPTION;
  3602. );
  3603. TSinkFileParams SinkFileParams;
  3604. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  3605. SinkFileParams.CopyParam = CopyParam;
  3606. SinkFileParams.Params = Params;
  3607. SinkFileParams.OperationProgress = OperationProgress;
  3608. SinkFileParams.Skipped = false;
  3609. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  3610. FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
  3611. // Do not delete directory if some of its files were skip.
  3612. // Throw "skip file" for the directory to avoid attempt to deletion
  3613. // of any parent directory
  3614. if ((Params & cpDelete) && SinkFileParams.Skipped)
  3615. {
  3616. THROW_SKIP_FILE_NULL;
  3617. }
  3618. }
  3619. else
  3620. {
  3621. // file is symlink to directory, currently do nothing, but it should be
  3622. // reported to user
  3623. }
  3624. }
  3625. else
  3626. {
  3627. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  3628. AnsiString DestPartinalFullName;
  3629. bool ResumeAllowed;
  3630. bool ResumeTransfer = false;
  3631. __int64 ResumeOffset;
  3632. // Will we use ASCII of BINARY file tranfer?
  3633. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName, osRemote));
  3634. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  3635. " transfer mode selected.");
  3636. // Suppose same data size to transfer as to write
  3637. // (not true with ASCII transfer)
  3638. OperationProgress->SetTransferSize(File->Size);
  3639. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  3640. // resume has no sense for temporary downloads
  3641. ResumeAllowed = ((Params & cpTemporary) == 0) &&
  3642. !OperationProgress->AsciiTransfer &&
  3643. CopyParam->AllowResume(OperationProgress->TransferSize);
  3644. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  3645. int Attrs;
  3646. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  3647. Attrs = FileGetAttr(DestFullName);
  3648. if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
  3649. );
  3650. OperationProgress->TransferingFile = false; // not set with SFTP protocol
  3651. HANDLE LocalHandle = NULL;
  3652. TStream * FileStream = NULL;
  3653. bool DeleteLocalFile = false;
  3654. AnsiString RemoteHandle;
  3655. AnsiString LocalFileName = DestFullName;
  3656. TSFTPOverwriteMode OverwriteMode = omOverwrite;
  3657. try
  3658. {
  3659. if (ResumeAllowed)
  3660. {
  3661. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3662. LocalFileName = DestPartinalFullName;
  3663. FTerminal->LogEvent("Checking existence of partially transfered file.");
  3664. if (FileExists(DestPartinalFullName))
  3665. {
  3666. FTerminal->OpenLocalFile(DestPartinalFullName, GENERIC_WRITE,
  3667. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  3668. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->TransferSize);
  3669. if (FLAGCLEAR(Params, cpNoConfirmation))
  3670. {
  3671. ResumeTransfer = SFTPConfirmResume(DestFileName,
  3672. PartialBiggerThanSource, OperationProgress);
  3673. }
  3674. else
  3675. {
  3676. ResumeTransfer = !PartialBiggerThanSource;
  3677. }
  3678. if (!ResumeTransfer)
  3679. {
  3680. CloseHandle(LocalHandle);
  3681. LocalHandle = NULL;
  3682. Sysutils::DeleteFile(DestPartinalFullName);
  3683. }
  3684. else
  3685. {
  3686. FTerminal->LogEvent("Resuming file transfer.");
  3687. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  3688. OperationProgress->AddResumed(ResumeOffset);
  3689. }
  3690. }
  3691. }
  3692. if ((Attrs >= 0) && !ResumeTransfer &&
  3693. (FLAGSET(Params, cpNewerOnly) ||
  3694. (FTerminal->Configuration->ConfirmOverwriting &&
  3695. !OperationProgress->YesToAll &&
  3696. FLAGCLEAR(Params, cpNoConfirmation))))
  3697. {
  3698. __int64 DestFileSize;
  3699. __int64 MTime;
  3700. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  3701. NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  3702. FTerminal->LogEvent("Checking existence of file.");
  3703. TOverwriteFileParams FileParams;
  3704. FileParams.SourceSize = OperationProgress->TransferSize;
  3705. FileParams.SourceTimestamp = File->Modification;
  3706. FileParams.DestTimestamp = UnixToDateTime(MTime,
  3707. FTerminal->SessionData->ConsiderDST);
  3708. FileParams.DestSize = DestFileSize;
  3709. SFTPConfirmOverwrite(DestFileName, (DestFileSize >= OperationProgress->TransferSize),
  3710. OperationProgress, OverwriteMode, &FileParams);
  3711. if (OverwriteMode == omOverwrite)
  3712. {
  3713. // is NULL when overwritting read-only file
  3714. if (LocalHandle)
  3715. {
  3716. CloseHandle(LocalHandle);
  3717. LocalHandle = NULL;
  3718. }
  3719. }
  3720. else
  3721. {
  3722. // is NULL when overwritting read-only file, so following will
  3723. // probably fail anyway
  3724. if (LocalHandle == NULL)
  3725. {
  3726. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  3727. NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  3728. }
  3729. ResumeAllowed = false;
  3730. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  3731. if (OverwriteMode == omAppend)
  3732. {
  3733. FTerminal->LogEvent("Appending to file.");
  3734. }
  3735. else
  3736. {
  3737. FTerminal->LogEvent("Resuming file transfer (append style).");
  3738. assert(OverwriteMode == omResume);
  3739. OperationProgress->AddResumed(DestFileSize);
  3740. }
  3741. }
  3742. }
  3743. // if not already opened (resume, append...), create new empty file
  3744. if (!LocalHandle)
  3745. {
  3746. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress,
  3747. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  3748. {
  3749. THROW_SKIP_FILE_NULL;
  3750. }
  3751. }
  3752. assert(LocalHandle);
  3753. DeleteLocalFile = true;
  3754. FTerminal->LogEvent("Opening remote file.");
  3755. FILE_OPERATION_LOOP (FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)),
  3756. int OpenType = SSH_FXF_READ;
  3757. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  3758. {
  3759. OpenType |= SSH_FXF_TEXT;
  3760. }
  3761. RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
  3762. );
  3763. FileStream = new THandleStream((THandle)LocalHandle);
  3764. // at end of this block queue is disposed
  3765. {
  3766. TSFTPDownloadQueue Queue(this);
  3767. TSFTPPacket DataPacket;
  3768. int QueueLen = int(File->Size / DownloadBlockSize(OperationProgress)) + 1;
  3769. if ((QueueLen > FTerminal->SessionData->SFTPDownloadQueue) ||
  3770. (QueueLen < 0))
  3771. {
  3772. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  3773. }
  3774. if (QueueLen < 1)
  3775. {
  3776. QueueLen = 1;
  3777. }
  3778. Queue.Init(QueueLen, RemoteHandle, OperationProgress->TransferedSize,
  3779. OperationProgress);
  3780. bool Eof = false;
  3781. bool PrevIncomplete = false;
  3782. int GapFillCount = 0;
  3783. int GapCount = 0;
  3784. unsigned long Missing = 0;
  3785. unsigned long DataLen = 0;
  3786. unsigned long BlockSize;
  3787. while (!Eof)
  3788. {
  3789. if (Missing > 0)
  3790. {
  3791. Queue.InitFillGapRequest(OperationProgress->TransferedSize, Missing,
  3792. &DataPacket);
  3793. GapFillCount++;
  3794. SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
  3795. SSH_FXP_DATA, asEOF);
  3796. }
  3797. else
  3798. {
  3799. Queue.ReceivePacket(&DataPacket, BlockSize);
  3800. }
  3801. if (DataPacket.Type == SSH_FXP_STATUS)
  3802. {
  3803. // must be SSH_FX_EOF, any other status packet would raise exception
  3804. Eof = true;
  3805. // close file right away, before waiting for pending responses
  3806. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  3807. true, true, NULL);
  3808. RemoteHandle = ""; // do not close file again in __finally block
  3809. }
  3810. if (!Eof)
  3811. {
  3812. if ((Missing == 0) && PrevIncomplete)
  3813. {
  3814. // This can happen only if last request returned less bytes
  3815. // than expected, but exacly number of bytes missing to last
  3816. // known file size, but actually EOF was not reached.
  3817. // Can happen only when filesize has changed since directory
  3818. // listing and server returns less bytes than requested and
  3819. // file has some special file size.
  3820. FTerminal->LogEvent(FORMAT(
  3821. "Received incomplete data packet before end of file, "
  3822. "offset: %s, size: %d, requested: %d",
  3823. (IntToStr(OperationProgress->TransferedSize), int(DataLen),
  3824. int(BlockSize))));
  3825. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  3826. }
  3827. // Buffer for one block of data
  3828. TFileBuffer BlockBuf;
  3829. DataLen = DataPacket.GetCardinal();
  3830. PrevIncomplete = false;
  3831. if (Missing > 0)
  3832. {
  3833. assert(DataLen <= Missing);
  3834. Missing -= DataLen;
  3835. }
  3836. else if (DataLen < BlockSize)
  3837. {
  3838. if (OperationProgress->TransferedSize + DataLen !=
  3839. OperationProgress->TransferSize)
  3840. {
  3841. // with native text transfer mode (SFTP>=4), do not bother about
  3842. // getting less than requested, read offset is ignored anyway
  3843. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  3844. {
  3845. GapCount++;
  3846. Missing = BlockSize - DataLen;
  3847. }
  3848. }
  3849. else
  3850. {
  3851. PrevIncomplete = true;
  3852. }
  3853. }
  3854. assert(DataLen <= BlockSize);
  3855. BlockBuf.Insert(0, DataPacket.GetNextData(DataLen), DataLen);
  3856. OperationProgress->AddTransfered(DataLen);
  3857. if (OperationProgress->AsciiTransfer)
  3858. {
  3859. assert(!ResumeTransfer && !ResumeAllowed);
  3860. unsigned int PrevBlockSize = BlockBuf.Size;
  3861. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0);
  3862. OperationProgress->SetLocalSize(
  3863. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  3864. }
  3865. FILE_OPERATION_LOOP (FMTLOAD(WRITE_ERROR, (LocalFileName)),
  3866. try
  3867. {
  3868. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  3869. }
  3870. catch(...)
  3871. {
  3872. RaiseLastOSError();
  3873. }
  3874. );
  3875. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  3876. }
  3877. if (OperationProgress->Cancel == csCancel)
  3878. {
  3879. Abort();
  3880. }
  3881. };
  3882. if (GapCount > 0)
  3883. {
  3884. FTerminal->LogEvent(FORMAT(
  3885. "%d requests to fill %d data gaps were issued.",
  3886. (GapFillCount, GapCount)));
  3887. }
  3888. }
  3889. if (CopyParam->PreserveTime)
  3890. {
  3891. FILETIME AcTime = DateTimeToFileTime(File->LastAccess,
  3892. FTerminal->SessionData->ConsiderDST);
  3893. FILETIME WrTime = DateTimeToFileTime(File->Modification,
  3894. FTerminal->SessionData->ConsiderDST);
  3895. SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
  3896. }
  3897. CloseHandle(LocalHandle);
  3898. LocalHandle = NULL;
  3899. if (ResumeAllowed)
  3900. {
  3901. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  3902. (ExtractFileName(DestPartinalFullName), DestFileName)),
  3903. if (FileExists(DestFullName))
  3904. {
  3905. if (!Sysutils::DeleteFile(DestFullName)) EXCEPTION;
  3906. }
  3907. if (!Sysutils::RenameFile(DestPartinalFullName, DestFullName))
  3908. {
  3909. EXCEPTION;
  3910. }
  3911. );
  3912. }
  3913. DeleteLocalFile = false;
  3914. if (Attrs == -1)
  3915. {
  3916. Attrs = faArchive;
  3917. }
  3918. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  3919. if ((NewAttrs & Attrs) != NewAttrs)
  3920. {
  3921. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  3922. FileSetAttr(DestFullName, Attrs | NewAttrs);
  3923. );
  3924. }
  3925. }
  3926. __finally
  3927. {
  3928. if (LocalHandle) CloseHandle(LocalHandle);
  3929. if (FileStream) delete FileStream;
  3930. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocalyUsed == 0) &&
  3931. (OverwriteMode == omOverwrite))
  3932. {
  3933. Sysutils::DeleteFile(LocalFileName);
  3934. }
  3935. // if the transfer was finished, the file is closed already
  3936. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  3937. {
  3938. // do not wait for response
  3939. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  3940. true, true, NULL);
  3941. }
  3942. }
  3943. }
  3944. if (Params & cpDelete)
  3945. {
  3946. // If file is directory, do not delete it recursively, because it should be
  3947. // empty already. If not, it should not be deleted (some files were
  3948. // skipped or some new files were copied to it, while we were downloading)
  3949. bool Recursive = false;
  3950. FTerminal->DeleteFile(FileName, File, &Recursive);
  3951. }
  3952. }
  3953. //---------------------------------------------------------------------------
  3954. void __fastcall TSFTPFileSystem::SFTPSinkFile(AnsiString FileName,
  3955. const TRemoteFile * File, void * Param)
  3956. {
  3957. TSinkFileParams * Params = (TSinkFileParams *)Param;
  3958. assert(Params->OperationProgress);
  3959. try
  3960. {
  3961. SFTPSink(FileName, File, Params->TargetDir, Params->CopyParam,
  3962. Params->Params, Params->OperationProgress, Params->Flags);
  3963. }
  3964. catch(EScpSkipFile & E)
  3965. {
  3966. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  3967. Params->Skipped = true;
  3968. SUSPEND_OPERATION (
  3969. if (!FTerminal->HandleException(&E)) throw;
  3970. );
  3971. if (OperationProgress->Cancel)
  3972. {
  3973. Abort();
  3974. }
  3975. }
  3976. }