SftpFileSystem.cpp 192 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SftpFileSystem.h"
  5. #include "PuttyTools.h"
  6. #include "Common.h"
  7. #include "Exceptions.h"
  8. #include "Interface.h"
  9. #include "Terminal.h"
  10. #include "TextsCore.h"
  11. #include "HelpCore.h"
  12. #include "SecureShell.h"
  13. #include <WideStrUtils.hpp>
  14. #include <limits>
  15. #include <memory>
  16. //---------------------------------------------------------------------------
  17. #pragma package(smart_init)
  18. //---------------------------------------------------------------------------
  19. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  20. //---------------------------------------------------------------------------
  21. #define SSH_FX_OK 0
  22. #define SSH_FX_EOF 1
  23. #define SSH_FX_NO_SUCH_FILE 2
  24. #define SSH_FX_PERMISSION_DENIED 3
  25. #define SSH_FX_FAILURE 4
  26. #define SSH_FX_OP_UNSUPPORTED 8
  27. #define SSH_FXP_INIT 1
  28. #define SSH_FXP_VERSION 2
  29. #define SSH_FXP_OPEN 3
  30. #define SSH_FXP_CLOSE 4
  31. #define SSH_FXP_READ 5
  32. #define SSH_FXP_WRITE 6
  33. #define SSH_FXP_LSTAT 7
  34. #define SSH_FXP_FSTAT 8
  35. #define SSH_FXP_SETSTAT 9
  36. #define SSH_FXP_FSETSTAT 10
  37. #define SSH_FXP_OPENDIR 11
  38. #define SSH_FXP_READDIR 12
  39. #define SSH_FXP_REMOVE 13
  40. #define SSH_FXP_MKDIR 14
  41. #define SSH_FXP_RMDIR 15
  42. #define SSH_FXP_REALPATH 16
  43. #define SSH_FXP_STAT 17
  44. #define SSH_FXP_RENAME 18
  45. #define SSH_FXP_READLINK 19
  46. #define SSH_FXP_SYMLINK 20
  47. #define SSH_FXP_LINK 21
  48. #define SSH_FXP_STATUS 101
  49. #define SSH_FXP_HANDLE 102
  50. #define SSH_FXP_DATA 103
  51. #define SSH_FXP_NAME 104
  52. #define SSH_FXP_ATTRS 105
  53. #define SSH_FXP_EXTENDED 200
  54. #define SSH_FXP_EXTENDED_REPLY 201
  55. #define SSH_FXP_ATTRS 105
  56. #define SSH_FILEXFER_ATTR_SIZE 0x00000001
  57. #define SSH_FILEXFER_ATTR_UIDGID 0x00000002
  58. #define SSH_FILEXFER_ATTR_PERMISSIONS 0x00000004
  59. #define SSH_FILEXFER_ATTR_ACMODTIME 0x00000008
  60. #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
  61. #define SSH_FILEXFER_ATTR_ACCESSTIME 0x00000008
  62. #define SSH_FILEXFER_ATTR_CREATETIME 0x00000010
  63. #define SSH_FILEXFER_ATTR_MODIFYTIME 0x00000020
  64. #define SSH_FILEXFER_ATTR_ACL 0x00000040
  65. #define SSH_FILEXFER_ATTR_OWNERGROUP 0x00000080
  66. #define SSH_FILEXFER_ATTR_SUBSECOND_TIMES 0x00000100
  67. #define SSH_FILEXFER_ATTR_BITS 0x00000200
  68. #define SSH_FILEXFER_ATTR_ALLOCATION_SIZE 0x00000400
  69. #define SSH_FILEXFER_ATTR_TEXT_HINT 0x00000800
  70. #define SSH_FILEXFER_ATTR_MIME_TYPE 0x00001000
  71. #define SSH_FILEXFER_ATTR_LINK_COUNT 0x00002000
  72. #define SSH_FILEXFER_ATTR_UNTRANSLATED_NAME 0x00004000
  73. #define SSH_FILEXFER_ATTR_CTIME 0x00008000
  74. #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
  75. #define SSH_FILEXFER_ATTR_COMMON \
  76. (SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_OWNERGROUP | \
  77. SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACCESSTIME | \
  78. SSH_FILEXFER_ATTR_MODIFYTIME)
  79. #define SSH_FILEXFER_TYPE_REGULAR 1
  80. #define SSH_FILEXFER_TYPE_DIRECTORY 2
  81. #define SSH_FILEXFER_TYPE_SYMLINK 3
  82. #define SSH_FILEXFER_TYPE_SPECIAL 4
  83. #define SSH_FILEXFER_TYPE_UNKNOWN 5
  84. #define SSH_FXF_READ 0x00000001
  85. #define SSH_FXF_WRITE 0x00000002
  86. #define SSH_FXF_APPEND 0x00000004
  87. #define SSH_FXF_CREAT 0x00000008
  88. #define SSH_FXF_TRUNC 0x00000010
  89. #define SSH_FXF_EXCL 0x00000020
  90. #define SSH_FXF_TEXT 0x00000040
  91. #define SSH_FXF_ACCESS_DISPOSITION 0x00000007
  92. #define SSH_FXF_CREATE_NEW 0x00000000
  93. #define SSH_FXF_CREATE_TRUNCATE 0x00000001
  94. #define SSH_FXF_OPEN_EXISTING 0x00000002
  95. #define SSH_FXF_OPEN_OR_CREATE 0x00000003
  96. #define SSH_FXF_TRUNCATE_EXISTING 0x00000004
  97. #define SSH_FXF_ACCESS_APPEND_DATA 0x00000008
  98. #define SSH_FXF_ACCESS_APPEND_DATA_ATOMIC 0x00000010
  99. #define SSH_FXF_ACCESS_TEXT_MODE 0x00000020
  100. #define ACE4_READ_DATA 0x00000001
  101. #define ACE4_LIST_DIRECTORY 0x00000001
  102. #define ACE4_WRITE_DATA 0x00000002
  103. #define ACE4_ADD_FILE 0x00000002
  104. #define ACE4_APPEND_DATA 0x00000004
  105. #define ACE4_ADD_SUBDIRECTORY 0x00000004
  106. #define ACE4_READ_NAMED_ATTRS 0x00000008
  107. #define ACE4_WRITE_NAMED_ATTRS 0x00000010
  108. #define ACE4_EXECUTE 0x00000020
  109. #define ACE4_DELETE_CHILD 0x00000040
  110. #define ACE4_READ_ATTRIBUTES 0x00000080
  111. #define ACE4_WRITE_ATTRIBUTES 0x00000100
  112. #define ACE4_DELETE 0x00010000
  113. #define ACE4_READ_ACL 0x00020000
  114. #define ACE4_WRITE_ACL 0x00040000
  115. #define ACE4_WRITE_OWNER 0x00080000
  116. #define ACE4_SYNCHRONIZE 0x00100000
  117. #define SSH_FILEXFER_ATTR_FLAGS_HIDDEN 0x00000004
  118. #define SSH_FXP_REALPATH_NO_CHECK 0x00000001
  119. #define SSH_FXP_REALPATH_STAT_IF 0x00000002
  120. #define SSH_FXP_REALPATH_STAT_ALWAYS 0x00000003
  121. #define SFTP_MAX_PACKET_LEN 1024000
  122. //---------------------------------------------------------------------------
  123. #define SFTP_EXT_OWNER_GROUP "owner-group-query@generic-extensions"
  124. #define SFTP_EXT_OWNER_GROUP_REPLY "owner-group-query-reply@generic-extensions"
  125. #define SFTP_EXT_NEWLINE "newline"
  126. #define SFTP_EXT_SUPPORTED "supported"
  127. #define SFTP_EXT_SUPPORTED2 "supported2"
  128. #define SFTP_EXT_FSROOTS "[email protected]"
  129. #define SFTP_EXT_VENDOR_ID "vendor-id"
  130. #define SFTP_EXT_VERSIONS "versions"
  131. #define SFTP_EXT_SPACE_AVAILABLE "space-available"
  132. #define SFTP_EXT_CHECK_FILE "check-file"
  133. #define SFTP_EXT_CHECK_FILE_NAME "check-file-name"
  134. #define SFTP_EXT_STATVFS "[email protected]"
  135. #define SFTP_EXT_STATVFS_VALUE_V2 L"2"
  136. #define SFTP_EXT_STATVFS_ST_RDONLY 0x1
  137. #define SFTP_EXT_STATVFS_ST_NOSUID 0x2
  138. #define SFTP_EXT_HARDLINK "[email protected]"
  139. #define SFTP_EXT_HARDLINK_VALUE_V1 L"1"
  140. #define SFTP_EXT_COPY_FILE "copy-file"
  141. //---------------------------------------------------------------------------
  142. #define OGQ_LIST_OWNERS 0x01
  143. #define OGQ_LIST_GROUPS 0x02
  144. //---------------------------------------------------------------------------
  145. const int SFTPMinVersion = 0;
  146. const int SFTPMaxVersion = 6;
  147. const unsigned int SFTPNoMessageNumber = static_cast<unsigned int>(-1);
  148. const int asNo = 0;
  149. const int asOK = 1 << SSH_FX_OK;
  150. const int asEOF = 1 << SSH_FX_EOF;
  151. const int asPermDenied = 1 << SSH_FX_PERMISSION_DENIED;
  152. const int asOpUnsupported = 1 << SSH_FX_OP_UNSUPPORTED;
  153. const int asNoSuchFile = 1 << SSH_FX_NO_SUCH_FILE;
  154. const int asAll = 0xFFFF;
  155. const int tfFirstLevel = 0x01;
  156. const int tfNewDirectory = 0x02;
  157. //---------------------------------------------------------------------------
  158. #define GET_32BIT(cp) \
  159. (((unsigned long)(unsigned char)(cp)[0] << 24) | \
  160. ((unsigned long)(unsigned char)(cp)[1] << 16) | \
  161. ((unsigned long)(unsigned char)(cp)[2] << 8) | \
  162. ((unsigned long)(unsigned char)(cp)[3]))
  163. #define PUT_32BIT(cp, value) { \
  164. (cp)[0] = (unsigned char)((value) >> 24); \
  165. (cp)[1] = (unsigned char)((value) >> 16); \
  166. (cp)[2] = (unsigned char)((value) >> 8); \
  167. (cp)[3] = (unsigned char)(value); }
  168. //---------------------------------------------------------------------------
  169. #define SFTP_PACKET_ALLOC_DELTA 256
  170. //---------------------------------------------------------------------------
  171. #pragma warn -inl
  172. //---------------------------------------------------------------------------
  173. struct TSFTPSupport
  174. {
  175. TSFTPSupport() :
  176. AttribExtensions(new TStringList()),
  177. Extensions(new TStringList())
  178. {
  179. Reset();
  180. }
  181. ~TSFTPSupport()
  182. {
  183. delete AttribExtensions;
  184. delete Extensions;
  185. }
  186. void Reset()
  187. {
  188. AttributeMask = 0;
  189. AttributeBits = 0;
  190. OpenFlags = 0;
  191. AccessMask = 0;
  192. MaxReadSize = 0;
  193. OpenBlockVector = 0;
  194. BlockVector = 0;
  195. AttribExtensions->Clear();
  196. Extensions->Clear();
  197. Loaded = false;
  198. }
  199. unsigned int AttributeMask;
  200. unsigned int AttributeBits;
  201. unsigned int OpenFlags;
  202. unsigned int AccessMask;
  203. unsigned int MaxReadSize;
  204. unsigned int OpenBlockVector;
  205. unsigned int BlockVector;
  206. TStrings * AttribExtensions;
  207. TStrings * Extensions;
  208. bool Loaded;
  209. };
  210. //---------------------------------------------------------------------------
  211. class TSFTPPacket
  212. {
  213. public:
  214. TSFTPPacket()
  215. {
  216. Init();
  217. }
  218. TSFTPPacket(const TSFTPPacket & Source)
  219. {
  220. Init();
  221. *this = Source;
  222. }
  223. TSFTPPacket(unsigned char AType)
  224. {
  225. Init();
  226. ChangeType(AType);
  227. }
  228. TSFTPPacket(const unsigned char * Source, unsigned int Len)
  229. {
  230. Init();
  231. FLength = Len;
  232. Capacity = FLength;
  233. memcpy(Data, Source, Len);
  234. }
  235. TSFTPPacket(const RawByteString & Source)
  236. {
  237. Init();
  238. FLength = Source.Length();
  239. Capacity = FLength;
  240. memcpy(Data, Source.c_str(), Source.Length());
  241. }
  242. ~TSFTPPacket()
  243. {
  244. if (FData != NULL)
  245. {
  246. delete[] (FData - FSendPrefixLen);
  247. }
  248. if (FReservedBy) FReservedBy->UnreserveResponse(this);
  249. }
  250. void ChangeType(unsigned char AType)
  251. {
  252. FPosition = 0;
  253. FLength = 0;
  254. Capacity = 0;
  255. FType = AType;
  256. AddByte(FType);
  257. if ((FType != 1) && (FType != SSH_FXP_INIT))
  258. {
  259. AssignNumber();
  260. AddCardinal(FMessageNumber);
  261. }
  262. }
  263. void Reuse()
  264. {
  265. AssignNumber();
  266. DebugAssert(Length >= 5);
  267. // duplicated in AddCardinal()
  268. unsigned char Buf[4];
  269. PUT_32BIT(Buf, FMessageNumber);
  270. memcpy(FData + 1, Buf, sizeof(Buf));
  271. }
  272. void AddByte(unsigned char Value)
  273. {
  274. Add(&Value, sizeof(Value));
  275. }
  276. void AddBool(bool Value)
  277. {
  278. AddByte(Value ? 1 : 0);
  279. }
  280. void AddCardinal(unsigned long Value)
  281. {
  282. // duplicated in Reuse()
  283. unsigned char Buf[4];
  284. PUT_32BIT(Buf, Value);
  285. Add(&Buf, sizeof(Buf));
  286. }
  287. void AddInt64(__int64 Value)
  288. {
  289. AddCardinal((unsigned long)(Value >> 32));
  290. AddCardinal((unsigned long)(Value & 0xFFFFFFFF));
  291. }
  292. void AddData(const void * Data, int ALength)
  293. {
  294. AddCardinal(ALength);
  295. Add(Data, ALength);
  296. }
  297. void AddString(const RawByteString & Value)
  298. {
  299. AddCardinal(Value.Length());
  300. Add(Value.c_str(), Value.Length());
  301. }
  302. inline void AddUtfString(const UTF8String & Value)
  303. {
  304. AddString(Value);
  305. }
  306. inline void AddUtfString(const UnicodeString & Value)
  307. {
  308. AddUtfString(UTF8String(Value));
  309. }
  310. inline void AddString(const UnicodeString Value, TAutoSwitch Utf)
  311. {
  312. // asAuto: Using UTF until we receive non-UTF string from the server
  313. if ((Utf == asOn) || (Utf == asAuto))
  314. {
  315. AddUtfString(Value);
  316. }
  317. else
  318. {
  319. AddString(RawByteString(AnsiString(Value)));
  320. }
  321. }
  322. // now purposeless alias to AddString
  323. inline void AddPathString(const UnicodeString & Value, TAutoSwitch Utf)
  324. {
  325. AddString(Value, Utf);
  326. }
  327. unsigned int AllocationSizeAttribute(int Version)
  328. {
  329. return (Version >= 6) ? SSH_FILEXFER_ATTR_ALLOCATION_SIZE : SSH_FILEXFER_ATTR_SIZE;
  330. }
  331. void AddProperties(unsigned short * Rights, TRemoteToken * Owner,
  332. TRemoteToken * Group, __int64 * MTime, __int64 * ATime,
  333. __int64 * Size, bool IsDirectory, int Version, TAutoSwitch Utf)
  334. {
  335. int Flags = 0;
  336. if (Size != NULL)
  337. {
  338. Flags |= AllocationSizeAttribute(Version);
  339. }
  340. // both or neither
  341. DebugAssert((Owner != NULL) == (Group != NULL));
  342. if ((Owner != NULL) && (Group != NULL))
  343. {
  344. if (Version < 4)
  345. {
  346. DebugAssert(Owner->IDValid && Group->IDValid);
  347. Flags |= SSH_FILEXFER_ATTR_UIDGID;
  348. }
  349. else
  350. {
  351. DebugAssert(Owner->NameValid && Group->NameValid);
  352. Flags |= SSH_FILEXFER_ATTR_OWNERGROUP;
  353. }
  354. }
  355. if (Rights != NULL)
  356. {
  357. Flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
  358. }
  359. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  360. {
  361. Flags |= SSH_FILEXFER_ATTR_ACMODTIME;
  362. }
  363. if ((Version >= 4) && (ATime != NULL))
  364. {
  365. Flags |= SSH_FILEXFER_ATTR_ACCESSTIME;
  366. }
  367. if ((Version >= 4) && (MTime != NULL))
  368. {
  369. Flags |= SSH_FILEXFER_ATTR_MODIFYTIME;
  370. }
  371. AddCardinal(Flags);
  372. if (Version >= 4)
  373. {
  374. AddByte(static_cast<unsigned char>(IsDirectory ?
  375. SSH_FILEXFER_TYPE_DIRECTORY : SSH_FILEXFER_TYPE_REGULAR));
  376. }
  377. if (Size != NULL)
  378. {
  379. // this is SSH_FILEXFER_ATTR_SIZE for version <= 5, but
  380. // SSH_FILEXFER_ATTR_ALLOCATION_SIZE for version >= 6
  381. AddInt64(*Size);
  382. }
  383. if ((Owner != NULL) && (Group != NULL))
  384. {
  385. if (Version < 4)
  386. {
  387. DebugAssert(Owner->IDValid && Group->IDValid);
  388. AddCardinal(Owner->ID);
  389. AddCardinal(Group->ID);
  390. }
  391. else
  392. {
  393. DebugAssert(Owner->NameValid && Group->NameValid);
  394. AddString(Owner->Name, Utf);
  395. AddString(Group->Name, Utf);
  396. }
  397. }
  398. if (Rights != NULL)
  399. {
  400. AddCardinal(*Rights);
  401. }
  402. if ((Version < 4) && ((MTime != NULL) || (ATime != NULL)))
  403. {
  404. // any way to reflect sbSignedTS here?
  405. // (note that casting __int64 > 2^31 < 2^32 to unsigned long is wrapped,
  406. // thus we never can set time after 2038, even if the server supports it)
  407. AddCardinal(static_cast<unsigned long>(ATime != NULL ? *ATime : *MTime));
  408. AddCardinal(static_cast<unsigned long>(MTime != NULL ? *MTime : *ATime));
  409. }
  410. if ((Version >= 4) && (ATime != NULL))
  411. {
  412. AddInt64(*ATime);
  413. }
  414. if ((Version >= 4) && (MTime != NULL))
  415. {
  416. AddInt64(*MTime);
  417. }
  418. }
  419. void AddProperties(const TRemoteProperties * Properties,
  420. unsigned short BaseRights, bool IsDirectory, int Version, TAutoSwitch Utf,
  421. TChmodSessionAction * Action)
  422. {
  423. enum TValid { valNone = 0, valRights = 0x01, valOwner = 0x02, valGroup = 0x04,
  424. valMTime = 0x08, valATime = 0x10 } Valid = valNone;
  425. unsigned short RightsNum = 0;
  426. TRemoteToken Owner;
  427. TRemoteToken Group;
  428. __int64 MTime;
  429. __int64 ATime;
  430. if (Properties != NULL)
  431. {
  432. if (Properties->Valid.Contains(vpGroup))
  433. {
  434. Valid = (TValid)(Valid | valGroup);
  435. Group = Properties->Group;
  436. }
  437. if (Properties->Valid.Contains(vpOwner))
  438. {
  439. Valid = (TValid)(Valid | valOwner);
  440. Owner = Properties->Owner;
  441. }
  442. if (Properties->Valid.Contains(vpRights))
  443. {
  444. Valid = (TValid)(Valid | valRights);
  445. TRights Rights = BaseRights;
  446. Rights |= Properties->Rights.NumberSet;
  447. Rights &= (unsigned short)~Properties->Rights.NumberUnset;
  448. if (IsDirectory && Properties->AddXToDirectories)
  449. {
  450. Rights.AddExecute();
  451. }
  452. RightsNum = Rights;
  453. if (Action != NULL)
  454. {
  455. Action->Rights(Rights);
  456. }
  457. }
  458. if (Properties->Valid.Contains(vpLastAccess))
  459. {
  460. Valid = (TValid)(Valid | valATime);
  461. ATime = Properties->LastAccess;
  462. }
  463. if (Properties->Valid.Contains(vpModification))
  464. {
  465. Valid = (TValid)(Valid | valMTime);
  466. MTime = Properties->Modification;
  467. }
  468. }
  469. AddProperties(
  470. Valid & valRights ? &RightsNum : NULL,
  471. Valid & valOwner ? &Owner : NULL,
  472. Valid & valGroup ? &Group : NULL,
  473. Valid & valMTime ? &MTime : NULL,
  474. Valid & valATime ? &ATime : NULL,
  475. NULL, IsDirectory, Version, Utf);
  476. }
  477. unsigned char GetByte()
  478. {
  479. Need(sizeof(unsigned char));
  480. unsigned char Result = FData[FPosition];
  481. DataConsumed(sizeof(unsigned char));
  482. return Result;
  483. }
  484. bool GetBool()
  485. {
  486. return (GetByte() != 0);
  487. }
  488. bool CanGetBool()
  489. {
  490. return (RemainingLength >= sizeof(unsigned char));
  491. }
  492. unsigned long GetCardinal()
  493. {
  494. unsigned long Result = PeekCardinal();
  495. DataConsumed(sizeof(Result));
  496. return Result;
  497. }
  498. bool CanGetCardinal()
  499. {
  500. return (RemainingLength >= sizeof(unsigned long));
  501. }
  502. unsigned long GetSmallCardinal()
  503. {
  504. unsigned long Result;
  505. Need(2);
  506. Result = (FData[FPosition] << 8) + FData[FPosition + 1];
  507. DataConsumed(2);
  508. return Result;
  509. }
  510. bool CanGetSmallCardinal()
  511. {
  512. return (RemainingLength >= 2);
  513. }
  514. __int64 GetInt64()
  515. {
  516. __int64 Hi = GetCardinal();
  517. __int64 Lo = GetCardinal();
  518. return (Hi << 32) + Lo;
  519. }
  520. RawByteString GetRawByteString()
  521. {
  522. RawByteString Result;
  523. unsigned long Len = GetCardinal();
  524. Need(Len);
  525. // cannot happen anyway as Need() would raise exception
  526. DebugAssert(Len < SFTP_MAX_PACKET_LEN);
  527. Result.SetLength(Len);
  528. memcpy(Result.c_str(), FData + FPosition, Len);
  529. DataConsumed(Len);
  530. return Result;
  531. }
  532. bool CanGetString(unsigned int & Size)
  533. {
  534. bool Result = CanGetCardinal();
  535. if (Result)
  536. {
  537. unsigned long Len = PeekCardinal();
  538. Size = (sizeof(Len) + Len);
  539. Result = (Size <= RemainingLength);
  540. }
  541. return Result;
  542. }
  543. // For reading strings that are character strings (not byte strings as
  544. // as file handles), and SFTP spec does not say explicitly that they
  545. // are in UTF. For most of them it actually does not matter as
  546. // the content should be pure ASCII (e.g. extension names, etc.)
  547. inline UnicodeString GetAnsiString()
  548. {
  549. return AnsiToString(GetRawByteString());
  550. }
  551. inline RawByteString GetFileHandle()
  552. {
  553. return GetRawByteString();
  554. }
  555. inline UnicodeString GetString(TAutoSwitch & Utf)
  556. {
  557. if (Utf != asOff)
  558. {
  559. return GetUtfString(Utf);
  560. }
  561. else
  562. {
  563. return GetAnsiString();
  564. }
  565. }
  566. // now purposeless alias to GetString(bool)
  567. inline UnicodeString GetPathString(TAutoSwitch & Utf)
  568. {
  569. return GetString(Utf);
  570. }
  571. void GetFile(TRemoteFile * File, int Version, TDSTMode DSTMode, TAutoSwitch & Utf, bool SignedTS, bool Complete)
  572. {
  573. DebugAssert(File);
  574. unsigned int Flags;
  575. UnicodeString ListingStr;
  576. unsigned long Permissions = 0;
  577. bool ParsingFailed = false;
  578. if (Type != SSH_FXP_ATTRS)
  579. {
  580. File->FileName = GetPathString(Utf);
  581. if (Version < 4)
  582. {
  583. ListingStr = GetString(Utf);
  584. }
  585. }
  586. Flags = GetCardinal();
  587. if (Version >= 4)
  588. {
  589. unsigned char FXType = GetByte();
  590. // -:regular, D:directory, L:symlink, S:special, U:unknown
  591. // O:socket, C:char device, B:block device, F:fifo
  592. // SSH-2.0-cryptlib returns file type 0 in response to SSH_FXP_LSTAT,
  593. // handle this undefined value as "unknown"
  594. static wchar_t * Types = L"U-DLSUOCBF";
  595. if (FXType > (unsigned char)wcslen(Types))
  596. {
  597. throw Exception(FMTLOAD(SFTP_UNKNOWN_FILE_TYPE, (int(FXType))));
  598. }
  599. File->Type = Types[FXType];
  600. }
  601. if (Flags & SSH_FILEXFER_ATTR_SIZE)
  602. {
  603. File->Size = GetInt64();
  604. }
  605. // SFTP-6 only
  606. if (Flags & SSH_FILEXFER_ATTR_ALLOCATION_SIZE)
  607. {
  608. GetInt64(); // skip
  609. }
  610. // SSH-2.0-3.2.0 F-SECURE SSH - Process Software MultiNet
  611. // sets SSH_FILEXFER_ATTR_UIDGID for v4, but does not include the UID/GUID
  612. if ((Flags & SSH_FILEXFER_ATTR_UIDGID) && (Version < 4))
  613. {
  614. File->Owner.ID = GetCardinal();
  615. File->Group.ID = GetCardinal();
  616. }
  617. if (Flags & SSH_FILEXFER_ATTR_OWNERGROUP)
  618. {
  619. DebugAssert(Version >= 4);
  620. File->Owner.Name = GetString(Utf);
  621. File->Group.Name = GetString(Utf);
  622. }
  623. if (Flags & SSH_FILEXFER_ATTR_PERMISSIONS)
  624. {
  625. Permissions = GetCardinal();
  626. }
  627. if (Version < 4)
  628. {
  629. if (Flags & SSH_FILEXFER_ATTR_ACMODTIME)
  630. {
  631. File->LastAccess = UnixToDateTime(
  632. SignedTS ?
  633. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  634. static_cast<__int64>(GetCardinal()),
  635. DSTMode);
  636. File->Modification = UnixToDateTime(
  637. SignedTS ?
  638. static_cast<__int64>(static_cast<signed long>(GetCardinal())) :
  639. static_cast<__int64>(GetCardinal()),
  640. DSTMode);
  641. }
  642. }
  643. else
  644. {
  645. if (Flags & SSH_FILEXFER_ATTR_ACCESSTIME)
  646. {
  647. File->LastAccess = UnixToDateTime(GetInt64(), DSTMode);
  648. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  649. {
  650. GetCardinal(); // skip access time subseconds
  651. }
  652. }
  653. if (Flags & SSH_FILEXFER_ATTR_CREATETIME)
  654. {
  655. GetInt64(); // skip create time
  656. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  657. {
  658. GetCardinal(); // skip create time subseconds
  659. }
  660. }
  661. if (Flags & SSH_FILEXFER_ATTR_MODIFYTIME)
  662. {
  663. File->Modification = UnixToDateTime(GetInt64(), DSTMode);
  664. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  665. {
  666. GetCardinal(); // skip modification time subseconds
  667. }
  668. }
  669. // SFTP-6
  670. if (Flags & SSH_FILEXFER_ATTR_CTIME)
  671. {
  672. GetInt64(); // skip attribute modification time
  673. if (Flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES)
  674. {
  675. GetCardinal(); // skip attribute modification time subseconds
  676. }
  677. }
  678. }
  679. if (Flags & SSH_FILEXFER_ATTR_ACL)
  680. {
  681. GetRawByteString();
  682. }
  683. if (Flags & SSH_FILEXFER_ATTR_BITS)
  684. {
  685. // while SSH_FILEXFER_ATTR_BITS is defined for SFTP5 only, vandyke 2.3.3 sets it
  686. // for SFTP4 as well
  687. unsigned long Bits = GetCardinal();
  688. if (Version >= 6)
  689. {
  690. unsigned long BitsValid = GetCardinal();
  691. Bits = Bits & BitsValid;
  692. }
  693. if (FLAGSET(Bits, SSH_FILEXFER_ATTR_FLAGS_HIDDEN))
  694. {
  695. File->IsHidden = true;
  696. }
  697. }
  698. // skip some SFTP-6 only fields
  699. if (Flags & SSH_FILEXFER_ATTR_TEXT_HINT)
  700. {
  701. GetByte();
  702. }
  703. if (Flags & SSH_FILEXFER_ATTR_MIME_TYPE)
  704. {
  705. GetAnsiString();
  706. }
  707. if (Flags & SSH_FILEXFER_ATTR_LINK_COUNT)
  708. {
  709. GetCardinal();
  710. }
  711. if (Flags & SSH_FILEXFER_ATTR_UNTRANSLATED_NAME)
  712. {
  713. GetPathString(Utf);
  714. }
  715. if ((Version < 4) && (Type != SSH_FXP_ATTRS))
  716. {
  717. try
  718. {
  719. // update permissions and user/group name
  720. // modification time and filename is ignored
  721. File->ListingStr = ListingStr;
  722. }
  723. catch(...)
  724. {
  725. // ignore any error while parsing listing line,
  726. // SFTP specification do not recommend to parse it
  727. ParsingFailed = true;
  728. }
  729. }
  730. if (Type == SSH_FXP_ATTRS || Version >= 4 || ParsingFailed)
  731. {
  732. wchar_t Type = FILETYPE_DEFAULT;
  733. if (FLAGSET(Flags, SSH_FILEXFER_ATTR_PERMISSIONS))
  734. {
  735. File->Rights->Number = (unsigned short)(Permissions & TRights::rfAllSpecials);
  736. if (FLAGSET(Permissions, TRights::rfDirectory))
  737. {
  738. Type = FILETYPE_DIRECTORY;
  739. }
  740. }
  741. if (Version < 4)
  742. {
  743. File->Type = Type;
  744. }
  745. }
  746. if (Flags & SSH_FILEXFER_ATTR_EXTENDED)
  747. {
  748. unsigned int ExtendedCount = GetCardinal();
  749. for (unsigned int Index = 0; Index < ExtendedCount; Index++)
  750. {
  751. GetRawByteString(); // skip extended_type
  752. GetRawByteString(); // skip extended_data
  753. }
  754. }
  755. if (Complete)
  756. {
  757. File->Complete();
  758. }
  759. }
  760. unsigned char * GetNextData(unsigned int Size = 0)
  761. {
  762. if (Size > 0)
  763. {
  764. Need(Size);
  765. }
  766. return FPosition < FLength ? FData + FPosition : NULL;
  767. }
  768. void DataConsumed(unsigned int Size)
  769. {
  770. FPosition += Size;
  771. }
  772. void DataUpdated(int ALength)
  773. {
  774. FPosition = 0;
  775. FLength = ALength;
  776. FType = GetByte();
  777. if (FType != SSH_FXP_VERSION)
  778. {
  779. FMessageNumber = GetCardinal();
  780. }
  781. else
  782. {
  783. FMessageNumber = SFTPNoMessageNumber;
  784. }
  785. }
  786. void LoadFromFile(const UnicodeString FileName)
  787. {
  788. TStringList * DumpLines = new TStringList();
  789. RawByteString Dump;
  790. try
  791. {
  792. DumpLines->LoadFromFile(FileName);
  793. Dump = RawByteString(AnsiString(DumpLines->Text));
  794. }
  795. __finally
  796. {
  797. delete DumpLines;
  798. }
  799. Capacity = 20480;
  800. unsigned char Byte[3];
  801. memset(Byte, '\0', sizeof(Byte));
  802. int Index = 1;
  803. unsigned int Length = 0;
  804. while (Index < Dump.Length())
  805. {
  806. char C = Dump[Index];
  807. if (IsHex(C))
  808. {
  809. if (Byte[0] == '\0')
  810. {
  811. Byte[0] = C;
  812. }
  813. else
  814. {
  815. Byte[1] = C;
  816. DebugAssert(Length < Capacity);
  817. Data[Length] = HexToByte(UnicodeString(reinterpret_cast<char *>(Byte)));
  818. Length++;
  819. memset(Byte, '\0', sizeof(Byte));
  820. }
  821. }
  822. Index++;
  823. }
  824. DataUpdated(Length);
  825. }
  826. UnicodeString __fastcall Dump() const
  827. {
  828. UnicodeString Result;
  829. for (unsigned int Index = 0; Index < Length; Index++)
  830. {
  831. Result += ByteToHex(Data[Index]) + L",";
  832. if (((Index + 1) % 25) == 0)
  833. {
  834. Result += L"\n";
  835. }
  836. }
  837. return Result;
  838. }
  839. TSFTPPacket & operator = (const TSFTPPacket & Source)
  840. {
  841. Capacity = 0;
  842. Add(Source.Data, Source.Length);
  843. DataUpdated(Source.Length);
  844. FPosition = Source.FPosition;
  845. return *this;
  846. }
  847. __property unsigned int Length = { read = FLength };
  848. __property unsigned int RemainingLength = { read = GetRemainingLength };
  849. __property unsigned char * Data = { read = FData };
  850. __property unsigned char * SendData = { read = GetSendData };
  851. __property unsigned int SendLength = { read = GetSendLength };
  852. __property unsigned int Capacity = { read = FCapacity, write = SetCapacity };
  853. __property unsigned char Type = { read = FType };
  854. __property unsigned char RequestType = { read = GetRequestType };
  855. __property unsigned int MessageNumber = { read = FMessageNumber, write = FMessageNumber };
  856. __property TSFTPFileSystem * ReservedBy = { read = FReservedBy, write = FReservedBy };
  857. __property UnicodeString TypeName = { read = GetTypeName };
  858. private:
  859. unsigned char * FData;
  860. unsigned int FLength;
  861. unsigned int FCapacity;
  862. unsigned int FPosition;
  863. unsigned char FType;
  864. unsigned int FMessageNumber;
  865. TSFTPFileSystem * FReservedBy;
  866. static int FMessageCounter;
  867. static const FSendPrefixLen = 4;
  868. void Init()
  869. {
  870. FData = NULL;
  871. FCapacity = 0;
  872. FLength = 0;
  873. FPosition = 0;
  874. FMessageNumber = SFTPNoMessageNumber;
  875. FType = -1;
  876. FReservedBy = NULL;
  877. }
  878. void AssignNumber()
  879. {
  880. // this is not strictly thread-safe, but as it is accessed from multiple
  881. // threads only for multiple connection, it is not problem if two threads get
  882. // the same number
  883. FMessageNumber = (FMessageCounter << 8) + FType;
  884. FMessageCounter++;
  885. }
  886. unsigned char GetRequestType()
  887. {
  888. if (FMessageNumber != SFTPNoMessageNumber)
  889. {
  890. return (unsigned char)(FMessageNumber & 0xFF);
  891. }
  892. else
  893. {
  894. DebugAssert(Type == SSH_FXP_VERSION);
  895. return SSH_FXP_INIT;
  896. }
  897. }
  898. inline void Add(const void * AData, int ALength)
  899. {
  900. if (Length + ALength > Capacity)
  901. {
  902. Capacity = Length + ALength + SFTP_PACKET_ALLOC_DELTA;
  903. }
  904. memcpy(FData + Length, AData, ALength);
  905. FLength += ALength;
  906. }
  907. void SetCapacity(unsigned int ACapacity)
  908. {
  909. if (ACapacity != Capacity)
  910. {
  911. FCapacity = ACapacity;
  912. if (FCapacity > 0)
  913. {
  914. unsigned char * NData = (new unsigned char[FCapacity + FSendPrefixLen]) + FSendPrefixLen;
  915. if (FData)
  916. {
  917. memcpy(NData - FSendPrefixLen, FData - FSendPrefixLen,
  918. (FLength < FCapacity ? FLength : FCapacity) + FSendPrefixLen);
  919. delete[] (FData - FSendPrefixLen);
  920. }
  921. FData = NData;
  922. }
  923. else
  924. {
  925. if (FData) delete[] (FData - FSendPrefixLen);
  926. FData = NULL;
  927. }
  928. if (FLength > FCapacity) FLength = FCapacity;
  929. }
  930. }
  931. UnicodeString GetTypeName() const
  932. {
  933. #define TYPE_CASE(TYPE) case TYPE: return TEXT(#TYPE)
  934. switch (Type) {
  935. TYPE_CASE(SSH_FXP_INIT);
  936. TYPE_CASE(SSH_FXP_VERSION);
  937. TYPE_CASE(SSH_FXP_OPEN);
  938. TYPE_CASE(SSH_FXP_CLOSE);
  939. TYPE_CASE(SSH_FXP_READ);
  940. TYPE_CASE(SSH_FXP_WRITE);
  941. TYPE_CASE(SSH_FXP_LSTAT);
  942. TYPE_CASE(SSH_FXP_FSTAT);
  943. TYPE_CASE(SSH_FXP_SETSTAT);
  944. TYPE_CASE(SSH_FXP_FSETSTAT);
  945. TYPE_CASE(SSH_FXP_OPENDIR);
  946. TYPE_CASE(SSH_FXP_READDIR);
  947. TYPE_CASE(SSH_FXP_REMOVE);
  948. TYPE_CASE(SSH_FXP_MKDIR);
  949. TYPE_CASE(SSH_FXP_RMDIR);
  950. TYPE_CASE(SSH_FXP_REALPATH);
  951. TYPE_CASE(SSH_FXP_STAT);
  952. TYPE_CASE(SSH_FXP_RENAME);
  953. TYPE_CASE(SSH_FXP_READLINK);
  954. TYPE_CASE(SSH_FXP_SYMLINK);
  955. TYPE_CASE(SSH_FXP_LINK);
  956. TYPE_CASE(SSH_FXP_STATUS);
  957. TYPE_CASE(SSH_FXP_HANDLE);
  958. TYPE_CASE(SSH_FXP_DATA);
  959. TYPE_CASE(SSH_FXP_NAME);
  960. TYPE_CASE(SSH_FXP_ATTRS);
  961. TYPE_CASE(SSH_FXP_EXTENDED);
  962. TYPE_CASE(SSH_FXP_EXTENDED_REPLY);
  963. default:
  964. return FORMAT(L"Unknown message (%d)", (int(Type)));
  965. }
  966. }
  967. unsigned char * GetSendData() const
  968. {
  969. unsigned char * Result = FData - FSendPrefixLen;
  970. // this is not strictly const-object operation
  971. PUT_32BIT(Result, Length);
  972. return Result;
  973. }
  974. unsigned int GetSendLength() const
  975. {
  976. return FSendPrefixLen + Length;
  977. }
  978. unsigned int GetRemainingLength() const
  979. {
  980. return Length - FPosition;
  981. }
  982. inline void Need(unsigned int Size)
  983. {
  984. if (Size > RemainingLength)
  985. {
  986. throw Exception(FMTLOAD(SFTP_PACKET_ERROR, (int(FPosition), int(Size), int(FLength))));
  987. }
  988. }
  989. unsigned long PeekCardinal()
  990. {
  991. unsigned long Result;
  992. Need(sizeof(Result));
  993. Result = GET_32BIT(FData + FPosition);
  994. return Result;
  995. }
  996. inline UnicodeString GetUtfString(TAutoSwitch & Utf)
  997. {
  998. DebugAssert(Utf != asOff);
  999. UnicodeString Result;
  1000. RawByteString S = GetRawByteString();
  1001. if (Utf == asAuto)
  1002. {
  1003. TEncodeType EncodeType = DetectUTF8Encoding(S);
  1004. if (EncodeType == etANSI)
  1005. {
  1006. Utf = asOff;
  1007. Result = AnsiToString(S);
  1008. }
  1009. }
  1010. if (Utf != asOff)
  1011. {
  1012. Result = UTF8ToString(S);
  1013. }
  1014. return Result;
  1015. }
  1016. };
  1017. //---------------------------------------------------------------------------
  1018. int TSFTPPacket::FMessageCounter = 0;
  1019. //---------------------------------------------------------------------------
  1020. class TSFTPQueue
  1021. {
  1022. public:
  1023. __fastcall TSFTPQueue(TSFTPFileSystem * AFileSystem)
  1024. {
  1025. FFileSystem = AFileSystem;
  1026. DebugAssert(FFileSystem);
  1027. FRequests = new TList();
  1028. FResponses = new TList();
  1029. }
  1030. virtual __fastcall ~TSFTPQueue()
  1031. {
  1032. TSFTPQueuePacket * Request;
  1033. TSFTPPacket * Response;
  1034. DebugAssert(FResponses->Count == FRequests->Count);
  1035. for (int Index = 0; Index < FRequests->Count; Index++)
  1036. {
  1037. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[Index]);
  1038. DebugAssert(Request);
  1039. delete Request;
  1040. Response = static_cast<TSFTPPacket*>(FResponses->Items[Index]);
  1041. DebugAssert(Response);
  1042. delete Response;
  1043. }
  1044. delete FRequests;
  1045. delete FResponses;
  1046. }
  1047. bool __fastcall Init()
  1048. {
  1049. return SendRequests();
  1050. }
  1051. virtual void __fastcall Dispose(int ExpectedType, int AllowStatus)
  1052. {
  1053. DebugAssert(FFileSystem->FTerminal->Active);
  1054. while (FRequests->Count)
  1055. {
  1056. DebugAssert(FResponses->Count);
  1057. std::unique_ptr<TSFTPQueuePacket> Request(DebugNotNull(static_cast<TSFTPQueuePacket*>(FRequests->Items[0])));
  1058. std::unique_ptr<TSFTPPacket> Response(DebugNotNull(static_cast<TSFTPPacket*>(FResponses->Items[0])));
  1059. // Particularly when ExpectedType >= 0, the ReceiveResponse may throw, and we have to remove the packets from queue
  1060. FRequests->Delete(0);
  1061. FResponses->Delete(0);
  1062. try
  1063. {
  1064. ReceiveResponse(Request.get(), Response.get(), ExpectedType, AllowStatus);
  1065. }
  1066. catch(Exception & E)
  1067. {
  1068. if (ExpectedType < 0)
  1069. {
  1070. if (FFileSystem->FTerminal->Active)
  1071. {
  1072. FFileSystem->FTerminal->LogEvent(L"Error while disposing the SFTP queue.");
  1073. FFileSystem->FTerminal->Log->AddException(&E);
  1074. }
  1075. else
  1076. {
  1077. FFileSystem->FTerminal->LogEvent(L"Fatal error while disposing the SFTP queue.");
  1078. throw;
  1079. }
  1080. }
  1081. else
  1082. {
  1083. throw;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. void __fastcall DisposeSafe(int ExpectedType = -1, int AllowStatus = -1)
  1089. {
  1090. if (FFileSystem->FTerminal->Active)
  1091. {
  1092. Dispose(ExpectedType, AllowStatus);
  1093. }
  1094. }
  1095. bool __fastcall ReceivePacket(TSFTPPacket * Packet,
  1096. int ExpectedType = -1, int AllowStatus = -1, void ** Token = NULL, bool TryOnly = false)
  1097. {
  1098. DebugAssert(FRequests->Count);
  1099. bool Result;
  1100. TSFTPQueuePacket * Request = NULL;
  1101. TSFTPPacket * Response = NULL;
  1102. try
  1103. {
  1104. Request = static_cast<TSFTPQueuePacket*>(FRequests->Items[0]);
  1105. FRequests->Delete(0);
  1106. DebugAssert(Request);
  1107. if (Token != NULL)
  1108. {
  1109. *Token = Request->Token;
  1110. }
  1111. Response = static_cast<TSFTPPacket*>(FResponses->Items[0]);
  1112. FResponses->Delete(0);
  1113. DebugAssert(Response);
  1114. ReceiveResponse(Request, Response, ExpectedType, AllowStatus, TryOnly);
  1115. if ((Response->Capacity == 0) && DebugAlwaysTrue(TryOnly))
  1116. {
  1117. FRequests->Insert(0, Request);
  1118. Request = NULL;
  1119. FResponses->Insert(0, Response);
  1120. Response = NULL;
  1121. Result = true;
  1122. }
  1123. else
  1124. {
  1125. if (Packet)
  1126. {
  1127. *Packet = *Response;
  1128. }
  1129. Result = !End(Response);
  1130. if (Result)
  1131. {
  1132. SendRequests();
  1133. }
  1134. }
  1135. }
  1136. __finally
  1137. {
  1138. delete Request;
  1139. delete Response;
  1140. }
  1141. return Result;
  1142. }
  1143. bool __fastcall Next(int ExpectedType = -1, int AllowStatus = -1)
  1144. {
  1145. return ReceivePacket(NULL, ExpectedType, AllowStatus);
  1146. }
  1147. protected:
  1148. TList * FRequests;
  1149. TList * FResponses;
  1150. TSFTPFileSystem * FFileSystem;
  1151. class TSFTPQueuePacket : public TSFTPPacket
  1152. {
  1153. public:
  1154. TSFTPQueuePacket() :
  1155. TSFTPPacket()
  1156. {
  1157. Token = NULL;
  1158. }
  1159. void * Token;
  1160. };
  1161. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request) = 0;
  1162. virtual bool __fastcall End(TSFTPPacket * Response) = 0;
  1163. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1164. {
  1165. FFileSystem->SendPacket(Packet);
  1166. }
  1167. virtual void __fastcall ReceiveResponse(
  1168. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1169. int AllowStatus, bool TryOnly = false)
  1170. {
  1171. FFileSystem->ReceiveResponse(Packet, Response, ExpectedType, AllowStatus, TryOnly);
  1172. }
  1173. // sends as many requests as allowed by implementation
  1174. virtual bool SendRequests() = 0;
  1175. virtual bool __fastcall SendRequest()
  1176. {
  1177. TSFTPQueuePacket * Request = NULL;
  1178. try
  1179. {
  1180. Request = new TSFTPQueuePacket();
  1181. if (!InitRequest(Request))
  1182. {
  1183. delete Request;
  1184. Request = NULL;
  1185. }
  1186. }
  1187. catch(...)
  1188. {
  1189. delete Request;
  1190. throw;
  1191. }
  1192. if (Request != NULL)
  1193. {
  1194. TSFTPPacket * Response = new TSFTPPacket();
  1195. FRequests->Add(Request);
  1196. FResponses->Add(Response);
  1197. // make sure the response is reserved before actually ending the message
  1198. // as we may receive response asynchronously before SendPacket finishes
  1199. FFileSystem->ReserveResponse(Request, Response);
  1200. SendPacket(Request);
  1201. }
  1202. return (Request != NULL);
  1203. }
  1204. };
  1205. //---------------------------------------------------------------------------
  1206. class TSFTPFixedLenQueue : public TSFTPQueue
  1207. {
  1208. public:
  1209. __fastcall TSFTPFixedLenQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  1210. {
  1211. FMissedRequests = 0;
  1212. }
  1213. virtual __fastcall ~TSFTPFixedLenQueue(){}
  1214. bool Init(int QueueLen)
  1215. {
  1216. FMissedRequests = QueueLen - 1;
  1217. return TSFTPQueue::Init();
  1218. }
  1219. protected:
  1220. int FMissedRequests;
  1221. // sends as many requests as allowed by implementation
  1222. virtual bool SendRequests()
  1223. {
  1224. bool Result = false;
  1225. FMissedRequests++;
  1226. while ((FMissedRequests > 0) && SendRequest())
  1227. {
  1228. Result = true;
  1229. FMissedRequests--;
  1230. }
  1231. return Result;
  1232. }
  1233. };
  1234. //---------------------------------------------------------------------------
  1235. class TSFTPAsynchronousQueue : public TSFTPQueue
  1236. {
  1237. public:
  1238. __fastcall TSFTPAsynchronousQueue(TSFTPFileSystem * AFileSystem) : TSFTPQueue(AFileSystem)
  1239. {
  1240. FFileSystem->FSecureShell->RegisterReceiveHandler(ReceiveHandler);
  1241. FReceiveHandlerRegistered = true;
  1242. }
  1243. virtual __fastcall ~TSFTPAsynchronousQueue()
  1244. {
  1245. UnregisterReceiveHandler();
  1246. }
  1247. virtual void __fastcall Dispose(int ExpectedType, int AllowStatus)
  1248. {
  1249. // we do not want to receive asynchronous notifications anymore,
  1250. // while waiting synchronously for pending responses
  1251. UnregisterReceiveHandler();
  1252. TSFTPQueue::Dispose(ExpectedType, AllowStatus);
  1253. }
  1254. bool __fastcall Continue()
  1255. {
  1256. return SendRequest();
  1257. }
  1258. protected:
  1259. // event handler for incoming data
  1260. void __fastcall ReceiveHandler(TObject * /*Sender*/)
  1261. {
  1262. while (// optimization only as we call ReceivePacket with TryOnly anyway
  1263. FFileSystem->PeekPacket() &&
  1264. ReceivePacketAsynchronously())
  1265. {
  1266. // loop
  1267. }
  1268. }
  1269. virtual bool __fastcall ReceivePacketAsynchronously() = 0;
  1270. // sends as many requests as allowed by implementation
  1271. virtual bool SendRequests()
  1272. {
  1273. // noop
  1274. return true;
  1275. }
  1276. void __fastcall UnregisterReceiveHandler()
  1277. {
  1278. if (FReceiveHandlerRegistered)
  1279. {
  1280. FReceiveHandlerRegistered = false;
  1281. FFileSystem->FSecureShell->UnregisterReceiveHandler(ReceiveHandler);
  1282. }
  1283. }
  1284. private:
  1285. bool FReceiveHandlerRegistered;
  1286. };
  1287. //---------------------------------------------------------------------------
  1288. class TSFTPDownloadQueue : public TSFTPFixedLenQueue
  1289. {
  1290. public:
  1291. TSFTPDownloadQueue(TSFTPFileSystem * AFileSystem) :
  1292. TSFTPFixedLenQueue(AFileSystem)
  1293. {
  1294. }
  1295. virtual __fastcall ~TSFTPDownloadQueue(){}
  1296. bool __fastcall Init(int QueueLen, const RawByteString & AHandle,__int64 ATransferred,
  1297. TFileOperationProgressType * AOperationProgress)
  1298. {
  1299. FHandle = AHandle;
  1300. FTransferred = ATransferred;
  1301. OperationProgress = AOperationProgress;
  1302. return TSFTPFixedLenQueue::Init(QueueLen);
  1303. }
  1304. void __fastcall InitFillGapRequest(__int64 Offset, unsigned long Missing,
  1305. TSFTPPacket * Packet)
  1306. {
  1307. InitRequest(Packet, Offset, Missing);
  1308. }
  1309. bool __fastcall ReceivePacket(TSFTPPacket * Packet, unsigned long & BlockSize)
  1310. {
  1311. void * Token;
  1312. bool Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_DATA, asEOF, &Token);
  1313. BlockSize = reinterpret_cast<unsigned long>(Token);
  1314. return Result;
  1315. }
  1316. protected:
  1317. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1318. {
  1319. unsigned int BlockSize = FFileSystem->DownloadBlockSize(OperationProgress);
  1320. InitRequest(Request, FTransferred, BlockSize);
  1321. Request->Token = reinterpret_cast<void*>(BlockSize);
  1322. FTransferred += BlockSize;
  1323. return true;
  1324. }
  1325. void __fastcall InitRequest(TSFTPPacket * Request, __int64 Offset,
  1326. unsigned long Size)
  1327. {
  1328. Request->ChangeType(SSH_FXP_READ);
  1329. Request->AddString(FHandle);
  1330. Request->AddInt64(Offset);
  1331. Request->AddCardinal(Size);
  1332. }
  1333. virtual bool __fastcall End(TSFTPPacket * Response)
  1334. {
  1335. return (Response->Type != SSH_FXP_DATA);
  1336. }
  1337. private:
  1338. TFileOperationProgressType * OperationProgress;
  1339. __int64 FTransferred;
  1340. RawByteString FHandle;
  1341. };
  1342. //---------------------------------------------------------------------------
  1343. class TSFTPUploadQueue : public TSFTPAsynchronousQueue
  1344. {
  1345. public:
  1346. TSFTPUploadQueue(TSFTPFileSystem * AFileSystem) :
  1347. TSFTPAsynchronousQueue(AFileSystem)
  1348. {
  1349. FStream = NULL;
  1350. OperationProgress = NULL;
  1351. FLastBlockSize = 0;
  1352. FEnd = false;
  1353. FConvertToken = false;
  1354. }
  1355. virtual __fastcall ~TSFTPUploadQueue()
  1356. {
  1357. delete FStream;
  1358. }
  1359. bool __fastcall Init(const UnicodeString AFileName,
  1360. HANDLE AFile, TFileOperationProgressType * AOperationProgress,
  1361. const RawByteString AHandle, __int64 ATransferred,
  1362. int ConvertParams)
  1363. {
  1364. FFileName = AFileName;
  1365. FStream = new TSafeHandleStream((THandle)AFile);
  1366. OperationProgress = AOperationProgress;
  1367. FHandle = AHandle;
  1368. FTransferred = ATransferred;
  1369. FConvertParams = ConvertParams;
  1370. return TSFTPAsynchronousQueue::Init();
  1371. }
  1372. void __fastcall DisposeSafeWithErrorHandling()
  1373. {
  1374. DisposeSafe(SSH_FXP_STATUS);
  1375. }
  1376. protected:
  1377. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1378. {
  1379. TTerminal * FTerminal = FFileSystem->FTerminal;
  1380. // Buffer for one block of data
  1381. TFileBuffer BlockBuf;
  1382. unsigned long BlockSize = GetBlockSize();
  1383. bool Result = (BlockSize > 0);
  1384. if (Result)
  1385. {
  1386. FILE_OPERATION_LOOP_BEGIN
  1387. {
  1388. BlockBuf.LoadStream(FStream, BlockSize, false);
  1389. }
  1390. FILE_OPERATION_LOOP_END(FMTLOAD(READ_ERROR, (FFileName)));
  1391. FEnd = (BlockBuf.Size == 0);
  1392. Result = !FEnd;
  1393. if (Result)
  1394. {
  1395. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  1396. // We do ASCII transfer: convert EOL of current block
  1397. if (OperationProgress->AsciiTransfer)
  1398. {
  1399. __int64 PrevBufSize = BlockBuf.Size;
  1400. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1401. FFileSystem->GetEOL(), FConvertParams, FConvertToken);
  1402. // update transfer size with difference arised from EOL conversion
  1403. OperationProgress->ChangeTransferSize(OperationProgress->TransferSize -
  1404. PrevBufSize + BlockBuf.Size);
  1405. }
  1406. if (FFileSystem->FTerminal->Configuration->ActualLogProtocol >= 1)
  1407. {
  1408. FFileSystem->FTerminal->LogEvent(FORMAT(L"Write request offset: %d, len: %d",
  1409. (int(FTransferred), int(BlockBuf.Size))));
  1410. }
  1411. Request->ChangeType(SSH_FXP_WRITE);
  1412. Request->AddString(FHandle);
  1413. Request->AddInt64(FTransferred);
  1414. Request->AddData(BlockBuf.Data, BlockBuf.Size);
  1415. FLastBlockSize = BlockBuf.Size;
  1416. FTransferred += BlockBuf.Size;
  1417. }
  1418. }
  1419. return Result;
  1420. }
  1421. virtual void __fastcall SendPacket(TSFTPQueuePacket * Packet)
  1422. {
  1423. TSFTPAsynchronousQueue::SendPacket(Packet);
  1424. OperationProgress->AddTransferred(FLastBlockSize);
  1425. }
  1426. virtual void __fastcall ReceiveResponse(
  1427. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  1428. int AllowStatus, bool TryOnly)
  1429. {
  1430. TSFTPAsynchronousQueue::ReceiveResponse(Packet, Response, ExpectedType, AllowStatus, TryOnly);
  1431. if (Response->Capacity > 0)
  1432. {
  1433. // particularly when uploading a file that completelly fits into send buffer
  1434. // over slow line, we may end up seemingly completing the transfer immediatelly
  1435. // but hanging the application for a long time waiting for responses
  1436. // (common is that the progress window would not even manage to draw itself,
  1437. // showing that upload finished, before the application "hangs")
  1438. FFileSystem->Progress(OperationProgress);
  1439. }
  1440. else
  1441. {
  1442. DebugAssert(TryOnly);
  1443. }
  1444. }
  1445. virtual bool __fastcall ReceivePacketAsynchronously()
  1446. {
  1447. // do not read response to close request
  1448. bool Result = (FRequests->Count > 0);
  1449. if (Result)
  1450. {
  1451. // Try only: We cannot read from the socket here as we are already called
  1452. // from TSecureShell::HandleNetworkEvents as it would cause a recursion
  1453. // that would potentially make PuTTY code process the SSH packets in wrong order.
  1454. ReceivePacket(NULL, SSH_FXP_STATUS, -1, NULL, true);
  1455. }
  1456. return Result;
  1457. }
  1458. inline int __fastcall GetBlockSize()
  1459. {
  1460. return FFileSystem->UploadBlockSize(FHandle, OperationProgress);
  1461. }
  1462. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1463. {
  1464. return FEnd;
  1465. }
  1466. private:
  1467. TStream * FStream;
  1468. TFileOperationProgressType * OperationProgress;
  1469. UnicodeString FFileName;
  1470. unsigned long FLastBlockSize;
  1471. bool FEnd;
  1472. __int64 FTransferred;
  1473. RawByteString FHandle;
  1474. bool FConvertToken;
  1475. int FConvertParams;
  1476. };
  1477. //---------------------------------------------------------------------------
  1478. class TSFTPLoadFilesPropertiesQueue : public TSFTPFixedLenQueue
  1479. {
  1480. public:
  1481. TSFTPLoadFilesPropertiesQueue(TSFTPFileSystem * AFileSystem) :
  1482. TSFTPFixedLenQueue(AFileSystem)
  1483. {
  1484. FIndex = 0;
  1485. }
  1486. virtual __fastcall ~TSFTPLoadFilesPropertiesQueue(){}
  1487. bool __fastcall Init(int QueueLen, TStrings * FileList)
  1488. {
  1489. FFileList = FileList;
  1490. return TSFTPFixedLenQueue::Init(QueueLen);
  1491. }
  1492. bool __fastcall ReceivePacket(TSFTPPacket * Packet, TRemoteFile *& File)
  1493. {
  1494. void * Token;
  1495. bool Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_ATTRS, asAll, &Token);
  1496. File = static_cast<TRemoteFile *>(Token);
  1497. return Result;
  1498. }
  1499. protected:
  1500. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1501. {
  1502. bool Result = false;
  1503. while (!Result && (FIndex < FFileList->Count))
  1504. {
  1505. TRemoteFile * File = static_cast<TRemoteFile *>(FFileList->Objects[FIndex]);
  1506. FIndex++;
  1507. bool MissingRights =
  1508. (FFileSystem->FSupport->Loaded &&
  1509. FLAGSET(FFileSystem->FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS) &&
  1510. File->Rights->Unknown);
  1511. bool MissingOwnerGroup =
  1512. (FFileSystem->FSecureShell->SshImplementation == sshiBitvise) ||
  1513. (FFileSystem->FSupport->Loaded &&
  1514. FLAGSET(FFileSystem->FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP) &&
  1515. !File->Owner.IsSet || !File->Group.IsSet);
  1516. Result = (MissingRights || MissingOwnerGroup);
  1517. if (Result)
  1518. {
  1519. Request->ChangeType(SSH_FXP_LSTAT);
  1520. Request->AddPathString(FFileSystem->LocalCanonify(File->FileName),
  1521. FFileSystem->FUtfStrings);
  1522. if (FFileSystem->FVersion >= 4)
  1523. {
  1524. Request->AddCardinal(
  1525. FLAGMASK(MissingRights, SSH_FILEXFER_ATTR_PERMISSIONS) |
  1526. FLAGMASK(MissingOwnerGroup, SSH_FILEXFER_ATTR_OWNERGROUP));
  1527. }
  1528. Request->Token = File;
  1529. }
  1530. }
  1531. return Result;
  1532. }
  1533. virtual bool __fastcall SendRequest()
  1534. {
  1535. bool Result =
  1536. (FIndex < FFileList->Count) &&
  1537. TSFTPFixedLenQueue::SendRequest();
  1538. return Result;
  1539. }
  1540. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1541. {
  1542. return (FRequests->Count == 0);
  1543. }
  1544. private:
  1545. TStrings * FFileList;
  1546. int FIndex;
  1547. };
  1548. //---------------------------------------------------------------------------
  1549. class TSFTPCalculateFilesChecksumQueue : public TSFTPFixedLenQueue
  1550. {
  1551. public:
  1552. TSFTPCalculateFilesChecksumQueue(TSFTPFileSystem * AFileSystem) :
  1553. TSFTPFixedLenQueue(AFileSystem)
  1554. {
  1555. FIndex = 0;
  1556. }
  1557. virtual __fastcall ~TSFTPCalculateFilesChecksumQueue(){}
  1558. bool __fastcall Init(int QueueLen, const UnicodeString & Alg, TStrings * FileList)
  1559. {
  1560. FAlg = Alg;
  1561. FFileList = FileList;
  1562. return TSFTPFixedLenQueue::Init(QueueLen);
  1563. }
  1564. bool __fastcall ReceivePacket(TSFTPPacket * Packet, TRemoteFile *& File)
  1565. {
  1566. void * Token;
  1567. bool Result;
  1568. try
  1569. {
  1570. Result = TSFTPFixedLenQueue::ReceivePacket(Packet, SSH_FXP_EXTENDED_REPLY, asNo, &Token);
  1571. }
  1572. __finally
  1573. {
  1574. File = static_cast<TRemoteFile *>(Token);
  1575. }
  1576. return Result;
  1577. }
  1578. protected:
  1579. virtual bool __fastcall InitRequest(TSFTPQueuePacket * Request)
  1580. {
  1581. bool Result = false;
  1582. while (!Result && (FIndex < FFileList->Count))
  1583. {
  1584. TRemoteFile * File = static_cast<TRemoteFile *>(FFileList->Objects[FIndex]);
  1585. DebugAssert(File != NULL);
  1586. FIndex++;
  1587. Result = !File->IsDirectory;
  1588. if (Result)
  1589. {
  1590. DebugAssert(!File->IsParentDirectory && !File->IsThisDirectory);
  1591. Request->ChangeType(SSH_FXP_EXTENDED);
  1592. Request->AddString(SFTP_EXT_CHECK_FILE_NAME);
  1593. Request->AddPathString(FFileSystem->LocalCanonify(File->FullFileName),
  1594. FFileSystem->FUtfStrings);
  1595. Request->AddString(FAlg);
  1596. Request->AddInt64(0); // offset
  1597. Request->AddInt64(0); // length (0 = till end)
  1598. Request->AddCardinal(0); // block size (0 = no blocks or "one block")
  1599. Request->Token = File;
  1600. }
  1601. }
  1602. return Result;
  1603. }
  1604. virtual bool __fastcall SendRequest()
  1605. {
  1606. bool Result =
  1607. (FIndex < FFileList->Count) &&
  1608. TSFTPFixedLenQueue::SendRequest();
  1609. return Result;
  1610. }
  1611. virtual bool __fastcall End(TSFTPPacket * /*Response*/)
  1612. {
  1613. return (FRequests->Count == 0);
  1614. }
  1615. private:
  1616. UnicodeString FAlg;
  1617. TStrings * FFileList;
  1618. int FIndex;
  1619. };
  1620. //---------------------------------------------------------------------------
  1621. #pragma warn .inl
  1622. //---------------------------------------------------------------------------
  1623. class TSFTPBusy
  1624. {
  1625. public:
  1626. __fastcall TSFTPBusy(TSFTPFileSystem * FileSystem)
  1627. {
  1628. FFileSystem = FileSystem;
  1629. DebugAssert(FFileSystem != NULL);
  1630. FFileSystem->BusyStart();
  1631. }
  1632. __fastcall ~TSFTPBusy()
  1633. {
  1634. FFileSystem->BusyEnd();
  1635. }
  1636. private:
  1637. TSFTPFileSystem * FFileSystem;
  1638. };
  1639. //===========================================================================
  1640. struct TOpenRemoteFileParams
  1641. {
  1642. int LocalFileAttrs;
  1643. UnicodeString FileName;
  1644. UnicodeString RemoteFileName;
  1645. TFileOperationProgressType * OperationProgress;
  1646. const TCopyParamType * CopyParam;
  1647. int Params;
  1648. bool Resume;
  1649. bool Resuming;
  1650. TSFTPOverwriteMode OverwriteMode;
  1651. __int64 DestFileSize; // output
  1652. RawByteString RemoteFileHandle; // output
  1653. TOverwriteFileParams * FileParams;
  1654. bool Confirmed;
  1655. };
  1656. //---------------------------------------------------------------------------
  1657. struct TSinkFileParams
  1658. {
  1659. UnicodeString TargetDir;
  1660. const TCopyParamType * CopyParam;
  1661. int Params;
  1662. TFileOperationProgressType * OperationProgress;
  1663. bool Skipped;
  1664. unsigned int Flags;
  1665. };
  1666. //===========================================================================
  1667. __fastcall TSFTPFileSystem::TSFTPFileSystem(TTerminal * ATerminal,
  1668. TSecureShell * SecureShell):
  1669. TCustomFileSystem(ATerminal)
  1670. {
  1671. FSecureShell = SecureShell;
  1672. FPacketReservations = new TList();
  1673. FPacketNumbers = VarArrayCreate(OPENARRAY(int, (0, 1)), varLongWord);
  1674. FPreviousLoggedPacket = 0;
  1675. FNotLoggedPackets = 0;
  1676. FBusy = 0;
  1677. FAvoidBusy = false;
  1678. FUtfStrings = asOff;
  1679. FUtfDisablingAnnounced = true;
  1680. FSignedTS = false;
  1681. FSupport = new TSFTPSupport();
  1682. FExtensions = new TStringList();
  1683. FFixedPaths = NULL;
  1684. FFileSystemInfoValid = false;
  1685. FChecksumAlgs.reset(new TStringList());
  1686. FChecksumSftpAlgs.reset(new TStringList());
  1687. // List as defined by draft-ietf-secsh-filexfer-extensions-00
  1688. // MD5 moved to the back
  1689. RegisterChecksumAlg(Sha1ChecksumAlg, L"sha1");
  1690. RegisterChecksumAlg(Sha224ChecksumAlg, L"sha224");
  1691. RegisterChecksumAlg(Sha256ChecksumAlg, L"sha256");
  1692. RegisterChecksumAlg(Sha384ChecksumAlg, L"sha384");
  1693. RegisterChecksumAlg(Sha512ChecksumAlg, L"sha512");
  1694. RegisterChecksumAlg(Md5ChecksumAlg, L"md5");
  1695. RegisterChecksumAlg(Crc32ChecksumAlg, L"crc32");
  1696. }
  1697. //---------------------------------------------------------------------------
  1698. __fastcall TSFTPFileSystem::~TSFTPFileSystem()
  1699. {
  1700. delete FSupport;
  1701. ResetConnection();
  1702. delete FPacketReservations;
  1703. delete FExtensions;
  1704. delete FFixedPaths;
  1705. delete FSecureShell;
  1706. }
  1707. //---------------------------------------------------------------------------
  1708. void __fastcall TSFTPFileSystem::Open()
  1709. {
  1710. // this is used for reconnects only
  1711. FSecureShell->Open();
  1712. }
  1713. //---------------------------------------------------------------------------
  1714. void __fastcall TSFTPFileSystem::Close()
  1715. {
  1716. FSecureShell->Close();
  1717. }
  1718. //---------------------------------------------------------------------------
  1719. bool __fastcall TSFTPFileSystem::GetActive()
  1720. {
  1721. return FSecureShell->Active;
  1722. }
  1723. //---------------------------------------------------------------------------
  1724. void __fastcall TSFTPFileSystem::CollectUsage()
  1725. {
  1726. FSecureShell->CollectUsage();
  1727. UnicodeString VersionCounter;
  1728. switch (FVersion)
  1729. {
  1730. case 0:
  1731. VersionCounter = L"OpenedSessionsSFTP0";
  1732. break;
  1733. case 1:
  1734. VersionCounter = L"OpenedSessionsSFTP1";
  1735. break;
  1736. case 2:
  1737. VersionCounter = L"OpenedSessionsSFTP2";
  1738. break;
  1739. case 3:
  1740. VersionCounter = L"OpenedSessionsSFTP3";
  1741. break;
  1742. case 4:
  1743. VersionCounter = L"OpenedSessionsSFTP4";
  1744. break;
  1745. case 5:
  1746. VersionCounter = L"OpenedSessionsSFTP5";
  1747. break;
  1748. case 6:
  1749. VersionCounter = L"OpenedSessionsSFTP6";
  1750. break;
  1751. default:
  1752. DebugFail();
  1753. }
  1754. FTerminal->Configuration->Usage->Inc(VersionCounter);
  1755. }
  1756. //---------------------------------------------------------------------------
  1757. const TSessionInfo & __fastcall TSFTPFileSystem::GetSessionInfo()
  1758. {
  1759. return FSecureShell->GetSessionInfo();
  1760. }
  1761. //---------------------------------------------------------------------------
  1762. const TFileSystemInfo & __fastcall TSFTPFileSystem::GetFileSystemInfo(bool /*Retrieve*/)
  1763. {
  1764. if (!FFileSystemInfoValid)
  1765. {
  1766. FFileSystemInfo.AdditionalInfo = L"";
  1767. if (!IsCapable(fcRename))
  1768. {
  1769. FFileSystemInfo.AdditionalInfo += LoadStr(FS_RENAME_NOT_SUPPORTED) + L"\r\n\r\n";
  1770. }
  1771. if (FExtensions->Count > 0)
  1772. {
  1773. UnicodeString Name;
  1774. UnicodeString Value;
  1775. UnicodeString Line;
  1776. FFileSystemInfo.AdditionalInfo += LoadStr(SFTP_EXTENSION_INFO) + L"\r\n";
  1777. for (int Index = 0; Index < FExtensions->Count; Index++)
  1778. {
  1779. UnicodeString Name = FExtensions->Names[Index];
  1780. UnicodeString Value = FExtensions->Values[Name];
  1781. UnicodeString Line;
  1782. if (Value.IsEmpty())
  1783. {
  1784. Line = Name;
  1785. }
  1786. else
  1787. {
  1788. Line = FORMAT(L"%s=%s", (Name, Value));
  1789. }
  1790. FFileSystemInfo.AdditionalInfo += FORMAT(L" %s\r\n", (Line));
  1791. }
  1792. }
  1793. else
  1794. {
  1795. FFileSystemInfo.AdditionalInfo += LoadStr(SFTP_NO_EXTENSION_INFO) + L"\r\n";
  1796. }
  1797. FFileSystemInfo.ProtocolBaseName = L"SFTP";
  1798. FFileSystemInfo.ProtocolName = FMTLOAD(SFTP_PROTOCOL_NAME2, (FVersion));
  1799. FTerminal->SaveCapabilities(FFileSystemInfo);
  1800. FFileSystemInfoValid = true;
  1801. }
  1802. return FFileSystemInfo;
  1803. }
  1804. //---------------------------------------------------------------------------
  1805. bool __fastcall TSFTPFileSystem::TemporaryTransferFile(const UnicodeString & FileName)
  1806. {
  1807. return SameText(UnixExtractFileExt(FileName), PARTIAL_EXT);
  1808. }
  1809. //---------------------------------------------------------------------------
  1810. bool __fastcall TSFTPFileSystem::GetStoredCredentialsTried()
  1811. {
  1812. return FSecureShell->GetStoredCredentialsTried();
  1813. }
  1814. //---------------------------------------------------------------------------
  1815. UnicodeString __fastcall TSFTPFileSystem::GetUserName()
  1816. {
  1817. return FSecureShell->UserName;
  1818. }
  1819. //---------------------------------------------------------------------------
  1820. void __fastcall TSFTPFileSystem::Idle()
  1821. {
  1822. // Keep session alive
  1823. if ((FTerminal->SessionData->PingType != ptOff) &&
  1824. (Now() - FSecureShell->LastDataSent > FTerminal->SessionData->PingIntervalDT))
  1825. {
  1826. if ((FTerminal->SessionData->PingType == ptDummyCommand) &&
  1827. FSecureShell->Ready)
  1828. {
  1829. FTerminal->LogEvent(L"Sending dummy command to keep session alive.");
  1830. TSFTPPacket Packet(SSH_FXP_REALPATH);
  1831. Packet.AddPathString(L"/", FUtfStrings);
  1832. SendPacketAndReceiveResponse(&Packet, &Packet);
  1833. }
  1834. else
  1835. {
  1836. FSecureShell->KeepAlive();
  1837. }
  1838. }
  1839. FSecureShell->Idle();
  1840. }
  1841. //---------------------------------------------------------------------------
  1842. void __fastcall TSFTPFileSystem::ResetConnection()
  1843. {
  1844. // there must be no valid packet reservation at the end
  1845. for (int i = 0; i < FPacketReservations->Count; i++)
  1846. {
  1847. DebugAssert(FPacketReservations->Items[i] == NULL);
  1848. delete (TSFTPPacket *)FPacketReservations->Items[i];
  1849. }
  1850. FPacketReservations->Clear();
  1851. FPacketNumbers.Clear();
  1852. }
  1853. //---------------------------------------------------------------------------
  1854. bool __fastcall TSFTPFileSystem::IsCapable(int Capability) const
  1855. {
  1856. DebugAssert(FTerminal);
  1857. switch (Capability) {
  1858. case fcAnyCommand:
  1859. case fcShellAnyCommand:
  1860. return false;
  1861. case fcNewerOnlyUpload:
  1862. case fcTimestampChanging:
  1863. case fcIgnorePermErrors:
  1864. case fcPreservingTimestampUpload:
  1865. case fcSecondaryShell:
  1866. case fcRemoveCtrlZUpload:
  1867. case fcRemoveBOMUpload:
  1868. case fcMoveToQueue:
  1869. case fcPreservingTimestampDirs:
  1870. case fcResumeSupport:
  1871. case fsSkipTransfer:
  1872. case fsParallelTransfers:
  1873. return true;
  1874. case fcRename:
  1875. case fcRemoteMove:
  1876. return (FVersion >= 2);
  1877. case fcSymbolicLink:
  1878. case fcResolveSymlink:
  1879. return (FVersion >= 3);
  1880. case fcModeChanging:
  1881. case fcModeChangingUpload:
  1882. return !FSupport->Loaded ||
  1883. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS);
  1884. case fcGroupOwnerChangingByID:
  1885. return (FVersion <= 3);
  1886. case fcOwnerChanging:
  1887. case fcGroupChanging:
  1888. return
  1889. (FVersion <= 3) ||
  1890. ((FVersion >= 4) &&
  1891. (!FSupport->Loaded ||
  1892. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP)));
  1893. case fcNativeTextMode:
  1894. return (FVersion >= 4);
  1895. case fcTextMode:
  1896. return (FVersion >= 4) ||
  1897. strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0;
  1898. case fcUserGroupListing:
  1899. return SupportsExtension(SFTP_EXT_OWNER_GROUP);
  1900. case fcLoadingAdditionalProperties:
  1901. // We allow loading properties only, if "supported" extension is supported and
  1902. // the server supports "permissions" and/or "owner/group" attributes
  1903. // (no other attributes are loaded).
  1904. // This is here only because of VShell
  1905. // (it supports owner/group, but does not include them into response to
  1906. // SSH_FXP_READDIR)
  1907. // and Bitwise (the same as VShell, but it does not even bother to provide "supported" extension until 6.21)
  1908. // No other use is known.
  1909. return
  1910. (FSupport->Loaded &&
  1911. ((FSupport->AttributeMask &
  1912. (SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_OWNERGROUP)) != 0)) ||
  1913. (FSecureShell->SshImplementation == sshiBitvise);
  1914. case fcCheckingSpaceAvailable:
  1915. return
  1916. // extension announced in extension list of by
  1917. // SFTP_EXT_SUPPORTED/SFTP_EXT_SUPPORTED2 extension
  1918. // (SFTP version 5 and newer only)
  1919. SupportsExtension(SFTP_EXT_SPACE_AVAILABLE) ||
  1920. // extension announced by proprietary SFTP_EXT_STATVFS extension
  1921. FSupportsStatVfsV2 ||
  1922. // Bitwise (until 6.21) fails to report it's supported extensions.
  1923. (FSecureShell->SshImplementation == sshiBitvise);
  1924. case fcCalculatingChecksum:
  1925. return
  1926. // Specification says that "check-file" should be announced,
  1927. // yet Vandyke VShell (as of 4.0.3) announce "check-file-name"
  1928. // https://forums.vandyke.com/showthread.php?t=11597
  1929. SupportsExtension(SFTP_EXT_CHECK_FILE) ||
  1930. SupportsExtension(SFTP_EXT_CHECK_FILE_NAME) ||
  1931. // see above
  1932. (FSecureShell->SshImplementation == sshiBitvise);
  1933. case fcRemoteCopy:
  1934. return
  1935. SupportsExtension(SFTP_EXT_COPY_FILE) ||
  1936. // see above
  1937. (FSecureShell->SshImplementation == sshiBitvise);
  1938. case fcHardLink:
  1939. return
  1940. (FVersion >= 6) ||
  1941. FSupportsHardlink;
  1942. case fcLocking:
  1943. return false;
  1944. case fcChangePassword:
  1945. return FSecureShell->CanChangePassword();
  1946. default:
  1947. DebugFail();
  1948. return false;
  1949. }
  1950. }
  1951. //---------------------------------------------------------------------------
  1952. bool __fastcall TSFTPFileSystem::SupportsExtension(const UnicodeString & Extension) const
  1953. {
  1954. return FSupport->Loaded && (FSupport->Extensions->IndexOf(Extension) >= 0);
  1955. }
  1956. //---------------------------------------------------------------------------
  1957. inline void __fastcall TSFTPFileSystem::BusyStart()
  1958. {
  1959. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1960. {
  1961. FBusyToken = ::BusyStart();
  1962. }
  1963. FBusy++;
  1964. DebugAssert(FBusy < 10);
  1965. }
  1966. //---------------------------------------------------------------------------
  1967. inline void __fastcall TSFTPFileSystem::BusyEnd()
  1968. {
  1969. DebugAssert(FBusy > 0);
  1970. FBusy--;
  1971. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1972. {
  1973. ::BusyEnd(FBusyToken);
  1974. FBusyToken = NULL;
  1975. }
  1976. }
  1977. //---------------------------------------------------------------------------
  1978. unsigned long __fastcall TSFTPFileSystem::TransferBlockSize(unsigned long Overhead,
  1979. TFileOperationProgressType * OperationProgress, unsigned long MaxPacketSize)
  1980. {
  1981. const unsigned long MinPacketSize = 32768;
  1982. // size + message number + type
  1983. const unsigned long SFTPPacketOverhead = 4 + 4 + 1;
  1984. unsigned long AMaxPacketSize = FSecureShell->MaxPacketSize();
  1985. bool MaxPacketSizeValid = (AMaxPacketSize > 0);
  1986. unsigned long Result = OperationProgress->CPS();
  1987. if ((MaxPacketSize > 0) &&
  1988. ((MaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1989. {
  1990. AMaxPacketSize = MaxPacketSize;
  1991. MaxPacketSizeValid = true;
  1992. }
  1993. if ((FMaxPacketSize > 0) &&
  1994. ((FMaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1995. {
  1996. AMaxPacketSize = FMaxPacketSize;
  1997. MaxPacketSizeValid = true;
  1998. }
  1999. if (Result == 0)
  2000. {
  2001. Result = OperationProgress->StaticBlockSize();
  2002. }
  2003. if (Result < MinPacketSize)
  2004. {
  2005. Result = MinPacketSize;
  2006. }
  2007. if (MaxPacketSizeValid)
  2008. {
  2009. Overhead += SFTPPacketOverhead;
  2010. if (AMaxPacketSize < Overhead)
  2011. {
  2012. // do not send another request
  2013. // (generally should happen only if upload buffer is full)
  2014. Result = 0;
  2015. }
  2016. else
  2017. {
  2018. AMaxPacketSize -= Overhead;
  2019. if (Result > AMaxPacketSize)
  2020. {
  2021. Result = AMaxPacketSize;
  2022. }
  2023. }
  2024. }
  2025. Result = OperationProgress->AdjustToCPSLimit(Result);
  2026. return Result;
  2027. }
  2028. //---------------------------------------------------------------------------
  2029. unsigned long __fastcall TSFTPFileSystem::UploadBlockSize(const RawByteString & Handle,
  2030. TFileOperationProgressType * OperationProgress)
  2031. {
  2032. // handle length + offset + data size
  2033. const unsigned long UploadPacketOverhead =
  2034. sizeof(unsigned long) + sizeof(__int64) + sizeof(unsigned long);
  2035. return TransferBlockSize(UploadPacketOverhead + Handle.Length(), OperationProgress);
  2036. }
  2037. //---------------------------------------------------------------------------
  2038. unsigned long __fastcall TSFTPFileSystem::DownloadBlockSize(
  2039. TFileOperationProgressType * OperationProgress)
  2040. {
  2041. unsigned long Result = TransferBlockSize(sizeof(unsigned long), OperationProgress);
  2042. if (FSupport->Loaded && (FSupport->MaxReadSize > 0) &&
  2043. (Result > FSupport->MaxReadSize))
  2044. {
  2045. Result = FSupport->MaxReadSize;
  2046. }
  2047. return Result;
  2048. }
  2049. //---------------------------------------------------------------------------
  2050. void __fastcall TSFTPFileSystem::Progress(TFileOperationProgressType * OperationProgress)
  2051. {
  2052. FTerminal->Progress(OperationProgress);
  2053. }
  2054. //---------------------------------------------------------------------------
  2055. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  2056. {
  2057. // putting here for a lack of better place
  2058. if (!FUtfDisablingAnnounced && (FUtfStrings == asOff))
  2059. {
  2060. FTerminal->LogEvent(L"Strings received in non-UTF-8 encoding in a previous packet, will not use UTF-8 anymore");
  2061. FUtfDisablingAnnounced = true;
  2062. }
  2063. BusyStart();
  2064. try
  2065. {
  2066. if (FTerminal->Log->Logging)
  2067. {
  2068. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  2069. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  2070. (Packet->Type != FPreviousLoggedPacket) ||
  2071. (FTerminal->Configuration->ActualLogProtocol >= 1))
  2072. {
  2073. if (FNotLoggedPackets)
  2074. {
  2075. FTerminal->LogEvent(FORMAT(L"%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  2076. (FNotLoggedPackets)));
  2077. FNotLoggedPackets = 0;
  2078. }
  2079. FTerminal->Log->Add(llInput, FORMAT(L"Type: %s, Size: %d, Number: %d",
  2080. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  2081. if (FTerminal->Configuration->ActualLogProtocol >= 2)
  2082. {
  2083. FTerminal->Log->Add(llInput, Packet->Dump());
  2084. }
  2085. FPreviousLoggedPacket = Packet->Type;
  2086. }
  2087. else
  2088. {
  2089. FNotLoggedPackets++;
  2090. }
  2091. }
  2092. FSecureShell->Send(Packet->SendData, Packet->SendLength);
  2093. }
  2094. __finally
  2095. {
  2096. BusyEnd();
  2097. }
  2098. }
  2099. //---------------------------------------------------------------------------
  2100. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
  2101. int AllowStatus)
  2102. {
  2103. unsigned long Code = Packet->GetCardinal();
  2104. static int Messages[] = {
  2105. SFTP_STATUS_OK,
  2106. SFTP_STATUS_EOF,
  2107. SFTP_STATUS_NO_SUCH_FILE,
  2108. SFTP_STATUS_PERMISSION_DENIED,
  2109. SFTP_STATUS_FAILURE,
  2110. SFTP_STATUS_BAD_MESSAGE,
  2111. SFTP_STATUS_NO_CONNECTION,
  2112. SFTP_STATUS_CONNECTION_LOST,
  2113. SFTP_STATUS_OP_UNSUPPORTED,
  2114. SFTP_STATUS_INVALID_HANDLE,
  2115. SFTP_STATUS_NO_SUCH_PATH,
  2116. SFTP_STATUS_FILE_ALREADY_EXISTS,
  2117. SFTP_STATUS_WRITE_PROTECT,
  2118. SFTP_STATUS_NO_MEDIA,
  2119. SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
  2120. SFTP_STATUS_QUOTA_EXCEEDED,
  2121. SFTP_STATUS_UNKNOWN_PRINCIPAL,
  2122. SFTP_STATUS_LOCK_CONFLICT,
  2123. SFTP_STATUS_DIR_NOT_EMPTY,
  2124. SFTP_STATUS_NOT_A_DIRECTORY,
  2125. SFTP_STATUS_INVALID_FILENAME,
  2126. SFTP_STATUS_LINK_LOOP,
  2127. SFTP_STATUS_CANNOT_DELETE,
  2128. SFTP_STATUS_INVALID_PARAMETER,
  2129. SFTP_STATUS_FILE_IS_A_DIRECTORY,
  2130. SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT,
  2131. SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED,
  2132. SFTP_STATUS_DELETE_PENDING,
  2133. SFTP_STATUS_FILE_CORRUPT,
  2134. SFTP_STATUS_OWNER_INVALID,
  2135. SFTP_STATUS_GROUP_INVALID,
  2136. SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK
  2137. };
  2138. int Message;
  2139. if ((AllowStatus & (0x01 << Code)) == 0)
  2140. {
  2141. if (Code >= LENOF(Messages))
  2142. {
  2143. Message = SFTP_STATUS_UNKNOWN;
  2144. }
  2145. else
  2146. {
  2147. Message = Messages[Code];
  2148. }
  2149. UnicodeString MessageStr = LoadStr(Message);
  2150. UnicodeString ServerMessage;
  2151. UnicodeString LanguageTag;
  2152. if ((FVersion >= 3) ||
  2153. // if version is not decided yet (i.e. this is status response
  2154. // to the init request), go on, only if there are any more data
  2155. ((FVersion < 0) && (Packet->RemainingLength > 0)))
  2156. {
  2157. // message is in UTF only since SFTP specification 01 (specification 00
  2158. // is also version 3)
  2159. // (in other words, always use UTF unless server is known to be buggy)
  2160. ServerMessage = Packet->GetString(FUtfStrings);
  2161. // SSH-2.0-Maverick_SSHD and SSH-2.0-CIGNA SFTP Server Ready! omit the language tag
  2162. // and I believe I've seen one more server doing the same.
  2163. if (Packet->RemainingLength > 0)
  2164. {
  2165. LanguageTag = Packet->GetAnsiString();
  2166. if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPAL))
  2167. {
  2168. UnicodeString Principals;
  2169. while (Packet->GetNextData() != NULL)
  2170. {
  2171. if (!Principals.IsEmpty())
  2172. {
  2173. Principals += L", ";
  2174. }
  2175. Principals += Packet->GetAnsiString();
  2176. }
  2177. MessageStr = FORMAT(MessageStr, (Principals));
  2178. }
  2179. }
  2180. }
  2181. else
  2182. {
  2183. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  2184. }
  2185. if (FTerminal->Log->Logging)
  2186. {
  2187. FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d, Message: %d, Server: %s, Language: %s ",
  2188. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  2189. }
  2190. if (!LanguageTag.IsEmpty())
  2191. {
  2192. LanguageTag = FORMAT(L" (%s)", (LanguageTag));
  2193. }
  2194. UnicodeString HelpKeyword;
  2195. switch (Code)
  2196. {
  2197. case SSH_FX_FAILURE:
  2198. HelpKeyword = HELP_SFTP_STATUS_FAILURE;
  2199. break;
  2200. case SSH_FX_PERMISSION_DENIED:
  2201. HelpKeyword = HELP_SFTP_STATUS_PERMISSION_DENIED;
  2202. break;
  2203. }
  2204. UnicodeString Error = FMTLOAD(SFTP_ERROR_FORMAT3, (MessageStr,
  2205. int(Code), LanguageTag, ServerMessage));
  2206. if (Code == SSH_FX_FAILURE)
  2207. {
  2208. FTerminal->Configuration->Usage->Inc(L"SftpFailureErrors");
  2209. Error += L"\n\n" + LoadStr(SFTP_STATUS_4);
  2210. }
  2211. FTerminal->TerminalError(NULL, Error, HelpKeyword);
  2212. return 0;
  2213. }
  2214. else
  2215. {
  2216. if (!FNotLoggedPackets || Code)
  2217. {
  2218. FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d", ((int)Code)));
  2219. }
  2220. return Code;
  2221. }
  2222. }
  2223. //---------------------------------------------------------------------------
  2224. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  2225. {
  2226. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  2227. {
  2228. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  2229. }
  2230. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  2231. if (Packet)
  2232. {
  2233. DebugAssert(Packet->ReservedBy == this);
  2234. Packet->ReservedBy = NULL;
  2235. }
  2236. FPacketReservations->Delete(Reservation);
  2237. }
  2238. //---------------------------------------------------------------------------
  2239. inline int __fastcall TSFTPFileSystem::PacketLength(unsigned char * LenBuf, int ExpectedType)
  2240. {
  2241. int Length = GET_32BIT(LenBuf);
  2242. if (Length > SFTP_MAX_PACKET_LEN)
  2243. {
  2244. UnicodeString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  2245. int(Length), SFTP_MAX_PACKET_LEN));
  2246. if (ExpectedType == SSH_FXP_VERSION)
  2247. {
  2248. RawByteString LenString(reinterpret_cast<char *>(LenBuf), 4);
  2249. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  2250. (Message, DisplayableStr(LenString)));
  2251. }
  2252. FTerminal->FatalError(NULL, Message, HELP_SFTP_PACKET_TOO_BIG);
  2253. }
  2254. return Length;
  2255. }
  2256. //---------------------------------------------------------------------------
  2257. bool __fastcall TSFTPFileSystem::PeekPacket()
  2258. {
  2259. bool Result;
  2260. unsigned char * Buf;
  2261. Result = FSecureShell->Peek(Buf, 4);
  2262. if (Result)
  2263. {
  2264. int Length = PacketLength(Buf, -1);
  2265. Result = FSecureShell->Peek(Buf, 4 + Length);
  2266. }
  2267. return Result;
  2268. }
  2269. //---------------------------------------------------------------------------
  2270. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  2271. int ExpectedType, int AllowStatus, bool TryOnly)
  2272. {
  2273. TSFTPBusy Busy(this);
  2274. int Result = SSH_FX_OK;
  2275. int Reservation = FPacketReservations->IndexOf(Packet);
  2276. if (Reservation < 0 || Packet->Capacity == 0)
  2277. {
  2278. bool IsReserved;
  2279. do
  2280. {
  2281. IsReserved = false;
  2282. DebugAssert(Packet);
  2283. if (TryOnly && !PeekPacket())
  2284. {
  2285. // Reset packet in case it was filled by previous out-of-order
  2286. // reserved packet
  2287. *Packet = TSFTPPacket();
  2288. }
  2289. else
  2290. {
  2291. unsigned char LenBuf[4];
  2292. FSecureShell->Receive(LenBuf, sizeof(LenBuf));
  2293. int Length = PacketLength(LenBuf, ExpectedType);
  2294. Packet->Capacity = Length;
  2295. FSecureShell->Receive(Packet->Data, Length);
  2296. Packet->DataUpdated(Length);
  2297. if (FTerminal->Log->Logging)
  2298. {
  2299. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  2300. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  2301. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA) ||
  2302. (FTerminal->Configuration->ActualLogProtocol >= 1))
  2303. {
  2304. if (FNotLoggedPackets)
  2305. {
  2306. FTerminal->LogEvent(FORMAT(L"%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  2307. (FNotLoggedPackets)));
  2308. FNotLoggedPackets = 0;
  2309. }
  2310. FTerminal->Log->Add(llOutput, FORMAT(L"Type: %s, Size: %d, Number: %d",
  2311. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  2312. if (FTerminal->Configuration->ActualLogProtocol >= 2)
  2313. {
  2314. FTerminal->Log->Add(llOutput, Packet->Dump());
  2315. }
  2316. }
  2317. else
  2318. {
  2319. FNotLoggedPackets++;
  2320. }
  2321. }
  2322. if (Reservation < 0 ||
  2323. Packet->MessageNumber != (unsigned int)FPacketNumbers.GetElement(Reservation))
  2324. {
  2325. TSFTPPacket * ReservedPacket;
  2326. unsigned int MessageNumber;
  2327. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  2328. {
  2329. MessageNumber = (unsigned int)FPacketNumbers.GetElement(Index);
  2330. if (MessageNumber == Packet->MessageNumber)
  2331. {
  2332. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  2333. IsReserved = true;
  2334. if (ReservedPacket)
  2335. {
  2336. FTerminal->LogEvent(L"Storing reserved response");
  2337. *ReservedPacket = *Packet;
  2338. }
  2339. else
  2340. {
  2341. FTerminal->LogEvent(L"Discarding reserved response");
  2342. RemoveReservation(Index);
  2343. if ((Reservation >= 0) && (Reservation > Index))
  2344. {
  2345. Reservation--;
  2346. DebugAssert(Reservation == FPacketReservations->IndexOf(Packet));
  2347. }
  2348. }
  2349. break;
  2350. }
  2351. }
  2352. }
  2353. }
  2354. }
  2355. while (IsReserved);
  2356. }
  2357. if ((Packet->Capacity == 0) && DebugAlwaysTrue(TryOnly))
  2358. {
  2359. // noop
  2360. }
  2361. else
  2362. {
  2363. // before we removed the reservation after check for packet type,
  2364. // but if it raises exception, removal is unnecessarily
  2365. // postponed until the packet is removed
  2366. // (and it have not worked anyway until recent fix to UnreserveResponse)
  2367. if (Reservation >= 0)
  2368. {
  2369. DebugAssert(Packet->MessageNumber == (unsigned int)FPacketNumbers.GetElement(Reservation));
  2370. RemoveReservation(Reservation);
  2371. }
  2372. if (ExpectedType >= 0)
  2373. {
  2374. if (Packet->Type == SSH_FXP_STATUS)
  2375. {
  2376. if (AllowStatus < 0)
  2377. {
  2378. AllowStatus = (ExpectedType == SSH_FXP_STATUS ? asOK : asNo);
  2379. }
  2380. Result = GotStatusPacket(Packet, AllowStatus);
  2381. }
  2382. else if (ExpectedType != Packet->Type)
  2383. {
  2384. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  2385. }
  2386. }
  2387. }
  2388. return Result;
  2389. }
  2390. //---------------------------------------------------------------------------
  2391. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  2392. TSFTPPacket * Response)
  2393. {
  2394. if (Response != NULL)
  2395. {
  2396. DebugAssert(FPacketReservations->IndexOf(Response) < 0);
  2397. // mark response as not received yet
  2398. Response->Capacity = 0;
  2399. Response->ReservedBy = this;
  2400. }
  2401. FPacketReservations->Add(Response);
  2402. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  2403. {
  2404. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  2405. }
  2406. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  2407. }
  2408. //---------------------------------------------------------------------------
  2409. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  2410. {
  2411. int Reservation = FPacketReservations->IndexOf(Response);
  2412. if (Response->Capacity != 0)
  2413. {
  2414. // added check for already received packet
  2415. // (it happens when the reserved response is received out of order,
  2416. // unexpectedly soon, and then receivepacket() on the packet
  2417. // is not actually called, due to exception)
  2418. RemoveReservation(Reservation);
  2419. }
  2420. else
  2421. {
  2422. if (Reservation >= 0)
  2423. {
  2424. // we probably do not remove the item at all, because
  2425. // we must remember that the response was expected, so we skip it
  2426. // in receivepacket()
  2427. FPacketReservations->Items[Reservation] = NULL;
  2428. }
  2429. }
  2430. }
  2431. //---------------------------------------------------------------------------
  2432. int __fastcall TSFTPFileSystem::ReceiveResponse(
  2433. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2434. int AllowStatus, bool TryOnly)
  2435. {
  2436. int Result;
  2437. unsigned int MessageNumber = Packet->MessageNumber;
  2438. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  2439. try
  2440. {
  2441. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus, TryOnly);
  2442. if (MessageNumber != AResponse->MessageNumber)
  2443. {
  2444. FTerminal->FatalError(NULL, FMTLOAD(SFTP_MESSAGE_NUMBER,
  2445. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  2446. }
  2447. }
  2448. __finally
  2449. {
  2450. if (!Response)
  2451. {
  2452. delete AResponse;
  2453. }
  2454. }
  2455. return Result;
  2456. }
  2457. //---------------------------------------------------------------------------
  2458. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  2459. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2460. int AllowStatus)
  2461. {
  2462. int Result;
  2463. TSFTPBusy Busy(this);
  2464. SendPacket(Packet);
  2465. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  2466. return Result;
  2467. }
  2468. //---------------------------------------------------------------------------
  2469. UnicodeString __fastcall TSFTPFileSystem::RealPath(const UnicodeString Path)
  2470. {
  2471. try
  2472. {
  2473. FTerminal->LogEvent(FORMAT(L"Getting real path for '%s'",
  2474. (Path)));
  2475. TSFTPPacket Packet(SSH_FXP_REALPATH);
  2476. Packet.AddPathString(Path, FUtfStrings);
  2477. // In SFTP-6 new optional field control-byte is added that defaults to
  2478. // SSH_FXP_REALPATH_NO_CHECK=0x01, meaning it won't fail, if the path does not exist.
  2479. // That differs from SFTP-5 recommendation that
  2480. // "The server SHOULD fail the request if the path is not present on the server."
  2481. // Earlier versions had no recommendation, though canonical SFTP-3 implementation
  2482. // in OpenSSH fails.
  2483. // While we really do not care much, we anyway set the flag to ~ & 0x01 to make the request fail.
  2484. // First for consistency.
  2485. // Second to workaround a bug in ProFTPD/mod_sftp version 1.3.5rc1 through 1.3.5-stable
  2486. // that sends a completelly malformed response for non-existing paths,
  2487. // when SSH_FXP_REALPATH_NO_CHECK (even implicitly) is used.
  2488. // See http://bugs.proftpd.org/show_bug.cgi?id=4160
  2489. // Note that earlier drafts of SFTP-6 (filexfer-07 and -08) had optional compose-path field
  2490. // before control-byte field. If we ever use this against a server conforming to those drafts,
  2491. // if may cause trouble.
  2492. if (FVersion >= 6)
  2493. {
  2494. if (FSecureShell->SshImplementation != sshiProFTPD)
  2495. {
  2496. Packet.AddByte(SSH_FXP_REALPATH_STAT_ALWAYS);
  2497. }
  2498. else
  2499. {
  2500. // Cannot use SSH_FXP_REALPATH_STAT_ALWAYS as ProFTPD does wrong bitwise test
  2501. // so it incorrectly evaluates SSH_FXP_REALPATH_STAT_ALWAYS (0x03) as
  2502. // SSH_FXP_REALPATH_NO_CHECK (0x01). The only value conforming to the
  2503. // specification, yet working with ProFTPD is SSH_FXP_REALPATH_STAT_IF (0x02).
  2504. Packet.AddByte(SSH_FXP_REALPATH_STAT_IF);
  2505. }
  2506. }
  2507. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  2508. if (Packet.GetCardinal() != 1)
  2509. {
  2510. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2511. }
  2512. UnicodeString RealDir = UnixExcludeTrailingBackslash(Packet.GetPathString(FUtfStrings));
  2513. // ignore rest of SSH_FXP_NAME packet
  2514. FTerminal->LogEvent(FORMAT(L"Real path is '%s'", (RealDir)));
  2515. return RealDir;
  2516. }
  2517. catch(Exception & E)
  2518. {
  2519. if (FTerminal->Active)
  2520. {
  2521. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  2522. }
  2523. else
  2524. {
  2525. throw;
  2526. }
  2527. }
  2528. }
  2529. //---------------------------------------------------------------------------
  2530. UnicodeString __fastcall TSFTPFileSystem::RealPath(const UnicodeString Path,
  2531. const UnicodeString BaseDir)
  2532. {
  2533. UnicodeString APath;
  2534. if (UnixIsAbsolutePath(Path))
  2535. {
  2536. APath = Path;
  2537. }
  2538. else
  2539. {
  2540. if (!Path.IsEmpty())
  2541. {
  2542. // this condition/block was outside (before) current block
  2543. // but it did not work when Path was empty
  2544. if (!BaseDir.IsEmpty())
  2545. {
  2546. APath = UnixIncludeTrailingBackslash(BaseDir);
  2547. }
  2548. APath = APath + Path;
  2549. }
  2550. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(L".");
  2551. }
  2552. return RealPath(APath);
  2553. }
  2554. //---------------------------------------------------------------------------
  2555. UnicodeString __fastcall TSFTPFileSystem::LocalCanonify(const UnicodeString & Path)
  2556. {
  2557. // TODO: improve (handle .. etc.)
  2558. if (UnixIsAbsolutePath(Path) ||
  2559. (!FCurrentDirectory.IsEmpty() && UnixSamePath(FCurrentDirectory, Path)))
  2560. {
  2561. return Path;
  2562. }
  2563. else
  2564. {
  2565. return ::AbsolutePath(FCurrentDirectory, Path);
  2566. }
  2567. }
  2568. //---------------------------------------------------------------------------
  2569. UnicodeString __fastcall TSFTPFileSystem::Canonify(UnicodeString Path)
  2570. {
  2571. // inspired by canonify() from PSFTP.C
  2572. UnicodeString Result;
  2573. FTerminal->LogEvent(FORMAT(L"Canonifying: \"%s\"", (Path)));
  2574. Path = LocalCanonify(Path);
  2575. bool TryParent = false;
  2576. try
  2577. {
  2578. Result = RealPath(Path);
  2579. }
  2580. catch(...)
  2581. {
  2582. if (FTerminal->Active)
  2583. {
  2584. TryParent = true;
  2585. }
  2586. else
  2587. {
  2588. throw;
  2589. }
  2590. }
  2591. if (TryParent)
  2592. {
  2593. UnicodeString APath = UnixExcludeTrailingBackslash(Path);
  2594. UnicodeString Name = UnixExtractFileName(APath);
  2595. if (Name == L"." || Name == L"..")
  2596. {
  2597. Result = Path;
  2598. }
  2599. else
  2600. {
  2601. UnicodeString FPath = UnixExtractFilePath(APath);
  2602. try
  2603. {
  2604. Result = RealPath(FPath);
  2605. Result = UnixIncludeTrailingBackslash(Result) + Name;
  2606. }
  2607. catch(...)
  2608. {
  2609. if (FTerminal->Active)
  2610. {
  2611. Result = Path;
  2612. }
  2613. else
  2614. {
  2615. throw;
  2616. }
  2617. }
  2618. }
  2619. }
  2620. FTerminal->LogEvent(FORMAT(L"Canonified: \"%s\"", (Result)));
  2621. return Result;
  2622. }
  2623. //---------------------------------------------------------------------------
  2624. UnicodeString __fastcall TSFTPFileSystem::AbsolutePath(UnicodeString Path, bool Local)
  2625. {
  2626. if (Local)
  2627. {
  2628. return LocalCanonify(Path);
  2629. }
  2630. else
  2631. {
  2632. return RealPath(Path, CurrentDirectory);
  2633. }
  2634. }
  2635. //---------------------------------------------------------------------------
  2636. UnicodeString __fastcall TSFTPFileSystem::GetHomeDirectory()
  2637. {
  2638. if (FHomeDirectory.IsEmpty())
  2639. {
  2640. FHomeDirectory = RealPath(L".");
  2641. }
  2642. return FHomeDirectory;
  2643. }
  2644. //---------------------------------------------------------------------------
  2645. void __fastcall TSFTPFileSystem::LoadFile(TRemoteFile * File, TSFTPPacket * Packet,
  2646. bool Complete)
  2647. {
  2648. Packet->GetFile(File, FVersion, FTerminal->SessionData->DSTMode,
  2649. FUtfStrings, FSignedTS, Complete);
  2650. }
  2651. //---------------------------------------------------------------------------
  2652. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  2653. TRemoteFile * ALinkedByFile, const UnicodeString FileName,
  2654. TRemoteFileList * TempFileList, bool Complete)
  2655. {
  2656. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  2657. try
  2658. {
  2659. File->Terminal = FTerminal;
  2660. if (!FileName.IsEmpty())
  2661. {
  2662. File->FileName = FileName;
  2663. }
  2664. // to get full path for symlink completion
  2665. File->Directory = TempFileList;
  2666. LoadFile(File, Packet, Complete);
  2667. File->Directory = NULL;
  2668. }
  2669. catch(...)
  2670. {
  2671. delete File;
  2672. throw;
  2673. }
  2674. return File;
  2675. }
  2676. //---------------------------------------------------------------------------
  2677. UnicodeString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  2678. {
  2679. return FCurrentDirectory;
  2680. }
  2681. //---------------------------------------------------------------------------
  2682. void __fastcall TSFTPFileSystem::DoStartup()
  2683. {
  2684. // do not know yet
  2685. FVersion = -1;
  2686. FFileSystemInfoValid = false;
  2687. TSFTPPacket Packet(SSH_FXP_INIT);
  2688. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  2689. if (MaxVersion > SFTPMaxVersion)
  2690. {
  2691. MaxVersion = SFTPMaxVersion;
  2692. }
  2693. Packet.AddCardinal(MaxVersion);
  2694. try
  2695. {
  2696. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  2697. }
  2698. catch(Exception &E)
  2699. {
  2700. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR), HELP_SFTP_INITIALIZE_ERROR);
  2701. }
  2702. FVersion = Packet.GetCardinal();
  2703. FTerminal->LogEvent(FORMAT(L"SFTP version %d negotiated.", (FVersion)));
  2704. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  2705. {
  2706. FTerminal->FatalError(NULL, FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  2707. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  2708. }
  2709. FExtensions->Clear();
  2710. FEOL = "\r\n";
  2711. FSupport->Loaded = false;
  2712. FSupportsStatVfsV2 = false;
  2713. FSupportsHardlink = false;
  2714. SAFE_DESTROY(FFixedPaths);
  2715. if (FVersion >= 3)
  2716. {
  2717. while (Packet.GetNextData() != NULL)
  2718. {
  2719. UnicodeString ExtensionName = Packet.GetAnsiString();
  2720. RawByteString ExtensionData = Packet.GetRawByteString();
  2721. UnicodeString ExtensionDisplayData = DisplayableStr(ExtensionData);
  2722. if (ExtensionName == SFTP_EXT_NEWLINE)
  2723. {
  2724. FEOL = AnsiString(ExtensionData);
  2725. FTerminal->LogEvent(FORMAT(L"Server requests EOL sequence %s.",
  2726. (ExtensionDisplayData)));
  2727. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2728. {
  2729. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2730. }
  2731. }
  2732. // do not allow "supported" to override "supported2" if both are received
  2733. else if (((ExtensionName == SFTP_EXT_SUPPORTED) && !FSupport->Loaded) ||
  2734. (ExtensionName == SFTP_EXT_SUPPORTED2))
  2735. {
  2736. FSupport->Reset();
  2737. TSFTPPacket SupportedStruct(ExtensionData);
  2738. FSupport->Loaded = true;
  2739. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2740. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2741. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2742. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2743. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2744. if (ExtensionName == SFTP_EXT_SUPPORTED)
  2745. {
  2746. while (SupportedStruct.GetNextData() != NULL)
  2747. {
  2748. FSupport->Extensions->Add(SupportedStruct.GetAnsiString());
  2749. }
  2750. }
  2751. else
  2752. {
  2753. // note that supported-open-block-vector, supported-block-vector,
  2754. // attrib-extension-count and attrib-extension-names fields
  2755. // were added only in rev 08, while "supported2" was defined in rev 07
  2756. FSupport->OpenBlockVector = SupportedStruct.GetSmallCardinal();
  2757. FSupport->BlockVector = SupportedStruct.GetSmallCardinal();
  2758. unsigned int ExtensionCount;
  2759. ExtensionCount = SupportedStruct.GetCardinal();
  2760. for (unsigned int i = 0; i < ExtensionCount; i++)
  2761. {
  2762. FSupport->AttribExtensions->Add(SupportedStruct.GetAnsiString());
  2763. }
  2764. ExtensionCount = SupportedStruct.GetCardinal();
  2765. for (unsigned int i = 0; i < ExtensionCount; i++)
  2766. {
  2767. FSupport->Extensions->Add(SupportedStruct.GetAnsiString());
  2768. }
  2769. }
  2770. if (FTerminal->Log->Logging)
  2771. {
  2772. FTerminal->LogEvent(FORMAT(
  2773. L"Server support information (%s):\n"
  2774. " Attribute mask: %x, Attribute bits: %x, Open flags: %x\n"
  2775. " Access mask: %x, Open block vector: %x, Block vector: %x, Max read size: %d\n",
  2776. (ExtensionName,
  2777. int(FSupport->AttributeMask),
  2778. int(FSupport->AttributeBits),
  2779. int(FSupport->OpenFlags),
  2780. int(FSupport->AccessMask),
  2781. int(FSupport->OpenBlockVector),
  2782. int(FSupport->BlockVector),
  2783. int(FSupport->MaxReadSize))));
  2784. FTerminal->LogEvent(FORMAT(L" Attribute extensions (%d)\n", (FSupport->AttribExtensions->Count)));
  2785. for (int Index = 0; Index < FSupport->AttribExtensions->Count; Index++)
  2786. {
  2787. FTerminal->LogEvent(
  2788. FORMAT(L" %s", (FSupport->AttribExtensions->Strings[Index])));
  2789. }
  2790. FTerminal->LogEvent(FORMAT(L" Extensions (%d)\n", (FSupport->Extensions->Count)));
  2791. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2792. {
  2793. FTerminal->LogEvent(
  2794. FORMAT(L" %s", (FSupport->Extensions->Strings[Index])));
  2795. }
  2796. }
  2797. }
  2798. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2799. {
  2800. TSFTPPacket VendorIdStruct(ExtensionData);
  2801. UnicodeString VendorName(VendorIdStruct.GetAnsiString());
  2802. UnicodeString ProductName(VendorIdStruct.GetAnsiString());
  2803. UnicodeString ProductVersion(VendorIdStruct.GetAnsiString());
  2804. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2805. FTerminal->LogEvent(FORMAT(L"Server software: %s %s (%d) by %s",
  2806. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2807. }
  2808. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2809. {
  2810. FTerminal->LogEvent(L"File system roots:\n");
  2811. DebugAssert(FFixedPaths == NULL);
  2812. FFixedPaths = new TStringList();
  2813. try
  2814. {
  2815. TSFTPPacket RootsPacket(ExtensionData);
  2816. while (RootsPacket.GetNextData() != NULL)
  2817. {
  2818. unsigned long Dummy = RootsPacket.GetCardinal();
  2819. if (Dummy != 1)
  2820. {
  2821. break;
  2822. }
  2823. else
  2824. {
  2825. unsigned char Drive = RootsPacket.GetByte();
  2826. unsigned char MaybeType = RootsPacket.GetByte();
  2827. FTerminal->LogEvent(FORMAT(L" %s: (type %d)", (static_cast<char>(Drive), (int)MaybeType)));
  2828. FFixedPaths->Add(FORMAT(L"%s:", (static_cast<char>(Drive))));
  2829. }
  2830. }
  2831. }
  2832. catch(Exception & E)
  2833. {
  2834. FFixedPaths->Clear();
  2835. FTerminal->LogEvent(FORMAT(L"Failed to decode %s extension",
  2836. (SFTP_EXT_FSROOTS)));
  2837. FTerminal->HandleException(&E);
  2838. }
  2839. }
  2840. else if (ExtensionName == SFTP_EXT_VERSIONS)
  2841. {
  2842. // first try legacy decoding according to incorrect encoding
  2843. // (structure-like) as of VShell (bug no longer present as of 4.0.3).
  2844. TSFTPPacket VersionsPacket(ExtensionData);
  2845. unsigned int StringSize;
  2846. if (VersionsPacket.CanGetString(StringSize) &&
  2847. (StringSize == VersionsPacket.RemainingLength))
  2848. {
  2849. UnicodeString Versions = VersionsPacket.GetAnsiString();
  2850. FTerminal->LogEvent(FORMAT(L"SFTP versions supported by the server (VShell format): %s",
  2851. (Versions)));
  2852. }
  2853. else
  2854. {
  2855. // if that fails, fallback to proper decoding
  2856. FTerminal->LogEvent(FORMAT(L"SFTP versions supported by the server: %s",
  2857. (AnsiToString(ExtensionData))));
  2858. }
  2859. }
  2860. else if (ExtensionName == SFTP_EXT_STATVFS)
  2861. {
  2862. UnicodeString StatVfsVersion = AnsiToString(ExtensionData);
  2863. if (StatVfsVersion == SFTP_EXT_STATVFS_VALUE_V2)
  2864. {
  2865. FSupportsStatVfsV2 = true;
  2866. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2867. }
  2868. else
  2869. {
  2870. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2871. }
  2872. }
  2873. else if (ExtensionName == SFTP_EXT_HARDLINK)
  2874. {
  2875. UnicodeString HardlinkVersion = AnsiToString(ExtensionData);
  2876. if (HardlinkVersion == SFTP_EXT_HARDLINK_VALUE_V1)
  2877. {
  2878. FSupportsHardlink = true;
  2879. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2880. }
  2881. else
  2882. {
  2883. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2884. }
  2885. }
  2886. else
  2887. {
  2888. FTerminal->LogEvent(FORMAT(L"Unknown server extension %s=%s",
  2889. (ExtensionName, ExtensionDisplayData)));
  2890. }
  2891. FExtensions->Values[ExtensionName] = ExtensionDisplayData;
  2892. }
  2893. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  2894. {
  2895. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  2896. Packet.AddString(SFTP_EXT_VENDOR_ID);
  2897. Packet.AddString(FTerminal->Configuration->CompanyName);
  2898. Packet.AddString(FTerminal->Configuration->ProductName);
  2899. Packet.AddString(FTerminal->Configuration->ProductVersion);
  2900. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  2901. SendPacket(&Packet);
  2902. // we are not interested in the response, do not wait for it
  2903. ReceiveResponse(&Packet, &Packet);
  2904. //ReserveResponse(&Packet, NULL);
  2905. }
  2906. }
  2907. if (FVersion < 4)
  2908. {
  2909. // currently enable the bug for all servers (really known on OpenSSH)
  2910. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  2911. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  2912. if (FSignedTS)
  2913. {
  2914. FTerminal->LogEvent(L"We believe the server has signed timestamps bug");
  2915. }
  2916. }
  2917. else
  2918. {
  2919. FSignedTS = false;
  2920. }
  2921. switch (FTerminal->SessionData->NotUtf)
  2922. {
  2923. case asOff:
  2924. FUtfStrings = asOn;
  2925. FTerminal->LogEvent(L"We will use UTF-8 strings as configured");
  2926. break;
  2927. default:
  2928. DebugFail();
  2929. case asAuto:
  2930. // Nb, Foxit server does not exist anymore
  2931. if (GetSessionInfo().SshImplementation.Pos(L"Foxit-WAC-Server") == 1)
  2932. {
  2933. FUtfStrings = asOff;
  2934. FTerminal->LogEvent(L"We will not use UTF-8 strings as the server is known not to use them");
  2935. }
  2936. else
  2937. {
  2938. if (FVersion >= 4)
  2939. {
  2940. FTerminal->LogEvent(L"We will use UTF-8 strings as it is mandatory with SFTP version 4 and newer");
  2941. FUtfStrings = asOn;
  2942. }
  2943. else
  2944. {
  2945. FTerminal->LogEvent(L"We will use UTF-8 strings until server sends an invalid UTF-8 string as with SFTP version 3 and older UTF-8 strings are not mandatory");
  2946. FUtfStrings = asAuto;
  2947. FUtfDisablingAnnounced = false;
  2948. }
  2949. }
  2950. break;
  2951. case asOn:
  2952. FTerminal->LogEvent(L"We will not use UTF-8 strings as configured");
  2953. FUtfStrings = asOff;
  2954. break;
  2955. }
  2956. FMaxPacketSize = FTerminal->SessionData->SFTPMaxPacketSize;
  2957. if (FMaxPacketSize == 0)
  2958. {
  2959. if ((FSecureShell->SshImplementation == sshiOpenSSH) && (FVersion == 3) && !FSupport->Loaded)
  2960. {
  2961. FMaxPacketSize = 4 + (256 * 1024); // len + 256kB payload
  2962. FTerminal->LogEvent(FORMAT(L"Limiting packet size to OpenSSH sftp-server limit of %d bytes",
  2963. (int(FMaxPacketSize))));
  2964. }
  2965. // full string is "1.77 sshlib: Momentum SSH Server",
  2966. // possibly it is sshlib-related
  2967. else if (GetSessionInfo().SshImplementation.Pos(L"Momentum SSH Server") != 0)
  2968. {
  2969. FMaxPacketSize = 4 + (32 * 1024);
  2970. FTerminal->LogEvent(FORMAT(L"Limiting packet size to Momentum sftp-server limit of %d bytes",
  2971. (int(FMaxPacketSize))));
  2972. }
  2973. }
  2974. }
  2975. //---------------------------------------------------------------------------
  2976. char * __fastcall TSFTPFileSystem::GetEOL() const
  2977. {
  2978. if (FVersion >= 4)
  2979. {
  2980. DebugAssert(!FEOL.IsEmpty());
  2981. return FEOL.c_str();
  2982. }
  2983. else
  2984. {
  2985. return EOLToStr(FTerminal->SessionData->EOLType);
  2986. }
  2987. }
  2988. //---------------------------------------------------------------------------
  2989. void __fastcall TSFTPFileSystem::LookupUsersGroups()
  2990. {
  2991. DebugAssert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
  2992. TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
  2993. TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
  2994. TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
  2995. TRemoteTokenList * Lists[] = { &FTerminal->FUsers, &FTerminal->FGroups };
  2996. wchar_t ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
  2997. for (size_t Index = 0; Index < LENOF(Packets); Index++)
  2998. {
  2999. TSFTPPacket * Packet = Packets[Index];
  3000. Packet->AddString(SFTP_EXT_OWNER_GROUP);
  3001. Packet->AddByte(ListTypes[Index]);
  3002. SendPacket(Packet);
  3003. ReserveResponse(Packet, Packet);
  3004. }
  3005. for (size_t Index = 0; Index < LENOF(Packets); Index++)
  3006. {
  3007. TSFTPPacket * Packet = Packets[Index];
  3008. ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
  3009. if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
  3010. (Packet->GetAnsiString() != SFTP_EXT_OWNER_GROUP_REPLY))
  3011. {
  3012. FTerminal->LogEvent(FORMAT(L"Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
  3013. }
  3014. else
  3015. {
  3016. TRemoteTokenList & List = *Lists[Index];
  3017. unsigned long Count = Packet->GetCardinal();
  3018. List.Clear();
  3019. for (unsigned long Item = 0; Item < Count; Item++)
  3020. {
  3021. TRemoteToken Token(Packet->GetString(FUtfStrings));
  3022. List.Add(Token);
  3023. if (&List == &FTerminal->FGroups)
  3024. {
  3025. FTerminal->FMembership.Add(Token);
  3026. }
  3027. }
  3028. }
  3029. }
  3030. }
  3031. //---------------------------------------------------------------------------
  3032. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  3033. {
  3034. if (!FDirectoryToChangeTo.IsEmpty())
  3035. {
  3036. FCurrentDirectory = FDirectoryToChangeTo;
  3037. FDirectoryToChangeTo = L"";
  3038. }
  3039. else if (FCurrentDirectory.IsEmpty())
  3040. {
  3041. // this happens only after startup when default remote directory is not specified
  3042. FCurrentDirectory = GetHomeDirectory();
  3043. }
  3044. }
  3045. //---------------------------------------------------------------------------
  3046. void __fastcall TSFTPFileSystem::HomeDirectory()
  3047. {
  3048. ChangeDirectory(GetHomeDirectory());
  3049. }
  3050. //---------------------------------------------------------------------------
  3051. void __fastcall TSFTPFileSystem::TryOpenDirectory(const UnicodeString Directory)
  3052. {
  3053. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  3054. TRemoteFile * File;
  3055. CustomReadFile(Directory, File, SSH_FXP_LSTAT, NULL, asOpUnsupported);
  3056. if (File == NULL)
  3057. {
  3058. // File can be NULL only when server does not support SSH_FXP_LSTAT.
  3059. // Fallback to legacy solution, which in turn does not allow entering
  3060. // traverse-only (chmod 110) directories.
  3061. // This is workaround for http://www.ftpshell.com/
  3062. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  3063. Packet.AddPathString(UnixExcludeTrailingBackslash(Directory), FUtfStrings);
  3064. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3065. RawByteString Handle = Packet.GetFileHandle();
  3066. Packet.ChangeType(SSH_FXP_CLOSE);
  3067. Packet.AddString(Handle);
  3068. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  3069. }
  3070. else
  3071. {
  3072. delete File;
  3073. }
  3074. }
  3075. //---------------------------------------------------------------------------
  3076. void __fastcall TSFTPFileSystem::AnnounceFileListOperation()
  3077. {
  3078. }
  3079. //---------------------------------------------------------------------------
  3080. void __fastcall TSFTPFileSystem::ChangeDirectory(const UnicodeString Directory)
  3081. {
  3082. UnicodeString Path, Current;
  3083. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  3084. Path = RealPath(Directory, Current);
  3085. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  3086. // for invalid paths on some systems, like CygWin)
  3087. TryOpenDirectory(Path);
  3088. // if open dir did not fail, directory exists -> success.
  3089. FDirectoryToChangeTo = Path;
  3090. }
  3091. //---------------------------------------------------------------------------
  3092. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  3093. {
  3094. FDirectoryToChangeTo = UnixExcludeTrailingBackslash(Directory);
  3095. }
  3096. //---------------------------------------------------------------------------
  3097. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  3098. {
  3099. DebugAssert(FileList && !FileList->Directory.IsEmpty());
  3100. UnicodeString Directory;
  3101. Directory = UnixExcludeTrailingBackslash(LocalCanonify(FileList->Directory));
  3102. FTerminal->LogEvent(FORMAT(L"Listing directory \"%s\".", (Directory)));
  3103. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  3104. // old data (e.g. parent directory) when reading fails
  3105. FileList->Reset();
  3106. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  3107. RawByteString Handle;
  3108. try
  3109. {
  3110. Packet.AddPathString(Directory, FUtfStrings);
  3111. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3112. Handle = Packet.GetFileHandle();
  3113. }
  3114. catch(...)
  3115. {
  3116. if (FTerminal->Active)
  3117. {
  3118. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  3119. }
  3120. throw;
  3121. }
  3122. TSFTPPacket Response;
  3123. try
  3124. {
  3125. bool isEOF = false;
  3126. int Total = 0;
  3127. bool HasParentDirectory = false;
  3128. TRemoteFile * File;
  3129. Packet.ChangeType(SSH_FXP_READDIR);
  3130. Packet.AddString(Handle);
  3131. SendPacket(&Packet);
  3132. do
  3133. {
  3134. ReceiveResponse(&Packet, &Response);
  3135. if (Response.Type == SSH_FXP_NAME)
  3136. {
  3137. TSFTPPacket ListingPacket = Response;
  3138. Packet.ChangeType(SSH_FXP_READDIR);
  3139. Packet.AddString(Handle);
  3140. SendPacket(&Packet);
  3141. ReserveResponse(&Packet, &Response);
  3142. unsigned int Count = ListingPacket.GetCardinal();
  3143. int ResolvedLinks = 0;
  3144. for (unsigned long Index = 0; !isEOF && (Index < Count); Index++)
  3145. {
  3146. File = LoadFile(&ListingPacket, NULL, L"", FileList);
  3147. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3148. {
  3149. FTerminal->LogEvent(FORMAT(L"Read file '%s' from listing", (File->FileName)));
  3150. }
  3151. if (File->LinkedFile != NULL)
  3152. {
  3153. ResolvedLinks++;
  3154. }
  3155. if (File->IsParentDirectory)
  3156. {
  3157. HasParentDirectory = true;
  3158. }
  3159. FileList->AddFile(File);
  3160. Total++;
  3161. if (Total % 10 == 0)
  3162. {
  3163. FTerminal->DoReadDirectoryProgress(Total, ResolvedLinks, isEOF);
  3164. if (isEOF)
  3165. {
  3166. FTerminal->DoReadDirectoryProgress(-2, 0, isEOF);
  3167. }
  3168. }
  3169. }
  3170. if ((FVersion >= 6) &&
  3171. // As of 7.0.9 the Cerberus SFTP server always sets the end-of-list to true.
  3172. // Fixed in 7.0.10.
  3173. (FSecureShell->SshImplementation != sshiCerberus) &&
  3174. ListingPacket.CanGetBool())
  3175. {
  3176. isEOF = ListingPacket.GetBool();
  3177. }
  3178. if (Count == 0)
  3179. {
  3180. FTerminal->LogEvent(L"Empty directory listing packet. Aborting directory reading.");
  3181. isEOF = true;
  3182. }
  3183. }
  3184. else if (Response.Type == SSH_FXP_STATUS)
  3185. {
  3186. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  3187. }
  3188. else
  3189. {
  3190. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  3191. }
  3192. }
  3193. while (!isEOF);
  3194. if (Total == 0)
  3195. {
  3196. bool Failure = false;
  3197. // no point reading parent of root directory,
  3198. // moreover CompleteFTP terminates session upon attempt to do so
  3199. if (IsUnixRootPath(FileList->Directory))
  3200. {
  3201. File = NULL;
  3202. }
  3203. else
  3204. {
  3205. // Empty file list -> probably "permission denied", we
  3206. // at least get link to parent directory ("..")
  3207. try
  3208. {
  3209. FTerminal->ExceptionOnFail = true;
  3210. try
  3211. {
  3212. File = NULL;
  3213. FTerminal->ReadFile(
  3214. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  3215. }
  3216. __finally
  3217. {
  3218. FTerminal->ExceptionOnFail = false;
  3219. }
  3220. }
  3221. catch(Exception &E)
  3222. {
  3223. if (E.InheritsFrom(__classid(EFatal)))
  3224. {
  3225. throw;
  3226. }
  3227. else
  3228. {
  3229. File = NULL;
  3230. Failure = true;
  3231. }
  3232. }
  3233. }
  3234. // on some systems even getting ".." fails, we create dummy ".." instead
  3235. if (File == NULL)
  3236. {
  3237. File = new TRemoteParentDirectory(FTerminal);
  3238. }
  3239. DebugAssert(File && File->IsParentDirectory);
  3240. FileList->AddFile(File);
  3241. if (Failure)
  3242. {
  3243. throw ExtException(
  3244. NULL, FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)),
  3245. HELP_EMPTY_DIRECTORY);
  3246. }
  3247. }
  3248. else
  3249. {
  3250. if (!HasParentDirectory)
  3251. {
  3252. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  3253. }
  3254. }
  3255. }
  3256. __finally
  3257. {
  3258. if (FTerminal->Active)
  3259. {
  3260. Packet.ChangeType(SSH_FXP_CLOSE);
  3261. Packet.AddString(Handle);
  3262. SendPacket(&Packet);
  3263. // we are not interested in the response, do not wait for it
  3264. ReserveResponse(&Packet, NULL);
  3265. }
  3266. }
  3267. }
  3268. //---------------------------------------------------------------------------
  3269. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  3270. TRemoteFile *& File)
  3271. {
  3272. DebugAssert(SymlinkFile && SymlinkFile->IsSymLink);
  3273. DebugAssert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  3274. // need to use full filename when resolving links within subdirectory
  3275. // (i.e. for download)
  3276. UnicodeString FileName = LocalCanonify(
  3277. SymlinkFile->Directory != NULL ? SymlinkFile->FullFileName : SymlinkFile->FileName);
  3278. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  3279. ReadLinkPacket.AddPathString(FileName, FUtfStrings);
  3280. SendPacket(&ReadLinkPacket);
  3281. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  3282. // send second request before reading response to first one
  3283. // (performance benefit)
  3284. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  3285. AttrsPacket.AddPathString(FileName, FUtfStrings);
  3286. if (FVersion >= 4)
  3287. {
  3288. AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
  3289. }
  3290. SendPacket(&AttrsPacket);
  3291. ReserveResponse(&AttrsPacket, &AttrsPacket);
  3292. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  3293. if (ReadLinkPacket.GetCardinal() != 1)
  3294. {
  3295. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  3296. }
  3297. SymlinkFile->LinkTo = ReadLinkPacket.GetPathString(FUtfStrings);
  3298. FTerminal->LogEvent(FORMAT(L"Link resolved to \"%s\".", (SymlinkFile->LinkTo)));
  3299. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  3300. // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
  3301. File = LoadFile(&AttrsPacket, SymlinkFile,
  3302. UnixExtractFileName(SymlinkFile->LinkTo));
  3303. }
  3304. //---------------------------------------------------------------------------
  3305. void __fastcall TSFTPFileSystem::ReadFile(const UnicodeString FileName,
  3306. TRemoteFile *& File)
  3307. {
  3308. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  3309. }
  3310. //---------------------------------------------------------------------------
  3311. bool __fastcall TSFTPFileSystem::RemoteFileExists(const UnicodeString FullPath,
  3312. TRemoteFile ** File)
  3313. {
  3314. bool Result;
  3315. try
  3316. {
  3317. TRemoteFile * AFile;
  3318. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, asNoSuchFile);
  3319. Result = (AFile != NULL);
  3320. if (Result)
  3321. {
  3322. if (File)
  3323. {
  3324. *File = AFile;
  3325. }
  3326. else
  3327. {
  3328. delete AFile;
  3329. }
  3330. }
  3331. }
  3332. catch(...)
  3333. {
  3334. if (!FTerminal->Active)
  3335. {
  3336. throw;
  3337. }
  3338. Result = false;
  3339. }
  3340. return Result;
  3341. }
  3342. //---------------------------------------------------------------------------
  3343. void __fastcall TSFTPFileSystem::SendCustomReadFile(TSFTPPacket * Packet,
  3344. TSFTPPacket * Response, unsigned long Flags)
  3345. {
  3346. if (FVersion >= 4)
  3347. {
  3348. Packet->AddCardinal(Flags);
  3349. }
  3350. SendPacket(Packet);
  3351. ReserveResponse(Packet, Response);
  3352. }
  3353. //---------------------------------------------------------------------------
  3354. void __fastcall TSFTPFileSystem::CustomReadFile(const UnicodeString FileName,
  3355. TRemoteFile *& File, unsigned char Type, TRemoteFile * ALinkedByFile,
  3356. int AllowStatus)
  3357. {
  3358. unsigned long Flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  3359. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  3360. SSH_FILEXFER_ATTR_OWNERGROUP;
  3361. TSFTPPacket Packet(Type);
  3362. Packet.AddPathString(LocalCanonify(FileName), FUtfStrings);
  3363. SendCustomReadFile(&Packet, &Packet, Flags);
  3364. ReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS, AllowStatus);
  3365. if (Packet.Type == SSH_FXP_ATTRS)
  3366. {
  3367. File = LoadFile(&Packet, ALinkedByFile, UnixExtractFileName(FileName));
  3368. }
  3369. else
  3370. {
  3371. DebugAssert(AllowStatus > 0);
  3372. File = NULL;
  3373. }
  3374. }
  3375. //---------------------------------------------------------------------------
  3376. void __fastcall TSFTPFileSystem::DoDeleteFile(const UnicodeString FileName, unsigned char Type)
  3377. {
  3378. TSFTPPacket Packet(Type);
  3379. UnicodeString RealFileName = LocalCanonify(FileName);
  3380. Packet.AddPathString(RealFileName, FUtfStrings);
  3381. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3382. }
  3383. //---------------------------------------------------------------------------
  3384. void __fastcall TSFTPFileSystem::DeleteFile(const UnicodeString FileName,
  3385. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  3386. {
  3387. unsigned char Type;
  3388. if (File && File->IsDirectory && FTerminal->CanRecurseToDirectory(File))
  3389. {
  3390. if (FLAGCLEAR(Params, dfNoRecursive))
  3391. {
  3392. try
  3393. {
  3394. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Params);
  3395. }
  3396. catch(...)
  3397. {
  3398. Action.Cancel();
  3399. throw;
  3400. }
  3401. }
  3402. Type = SSH_FXP_RMDIR;
  3403. }
  3404. else
  3405. {
  3406. Type = SSH_FXP_REMOVE;
  3407. }
  3408. DoDeleteFile(FileName, Type);
  3409. }
  3410. //---------------------------------------------------------------------------
  3411. void __fastcall TSFTPFileSystem::RenameFile(const UnicodeString FileName,
  3412. const UnicodeString NewName)
  3413. {
  3414. TSFTPPacket Packet(SSH_FXP_RENAME);
  3415. UnicodeString RealName = LocalCanonify(FileName);
  3416. Packet.AddPathString(RealName, FUtfStrings);
  3417. UnicodeString TargetName;
  3418. if (UnixExtractFilePath(NewName).IsEmpty())
  3419. {
  3420. // rename case (TTerminal::RenameFile)
  3421. TargetName = UnixExtractFilePath(RealName) + NewName;
  3422. }
  3423. else
  3424. {
  3425. TargetName = LocalCanonify(NewName);
  3426. }
  3427. Packet.AddPathString(TargetName, FUtfStrings);
  3428. if (FVersion >= 5)
  3429. {
  3430. Packet.AddCardinal(0);
  3431. }
  3432. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3433. }
  3434. //---------------------------------------------------------------------------
  3435. void __fastcall TSFTPFileSystem::CopyFile(const UnicodeString FileName,
  3436. const UnicodeString NewName)
  3437. {
  3438. // Implemented by ProFTPD/mod_sftp and Bitvise WinSSHD (without announcing it)
  3439. DebugAssert(SupportsExtension(SFTP_EXT_COPY_FILE) || (FSecureShell->SshImplementation == sshiBitvise));
  3440. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3441. Packet.AddString(SFTP_EXT_COPY_FILE);
  3442. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  3443. Packet.AddPathString(Canonify(NewName), FUtfStrings);
  3444. Packet.AddBool(false);
  3445. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3446. }
  3447. //---------------------------------------------------------------------------
  3448. void __fastcall TSFTPFileSystem::CreateDirectory(const UnicodeString DirName)
  3449. {
  3450. TSFTPPacket Packet(SSH_FXP_MKDIR);
  3451. UnicodeString CanonifiedName = Canonify(DirName);
  3452. Packet.AddPathString(CanonifiedName, FUtfStrings);
  3453. Packet.AddProperties(NULL, 0, true, FVersion, FUtfStrings, NULL);
  3454. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3455. }
  3456. //---------------------------------------------------------------------------
  3457. void __fastcall TSFTPFileSystem::CreateLink(const UnicodeString FileName,
  3458. const UnicodeString PointTo, bool Symbolic)
  3459. {
  3460. // Cerberus server does not even respond to LINK or SYMLINK,
  3461. // Although its log says:
  3462. // Unrecognized SFTP client command: (20)
  3463. // Unknown SFTP packet - Sending Unsupported OP response
  3464. DebugAssert(FVersion >= 3); // links are supported with SFTP version 3 and later
  3465. bool UseLink = (FVersion >= 6);
  3466. bool UseHardlink = !Symbolic && !UseLink && FSupportsHardlink;
  3467. TSFTPPacket Packet(UseHardlink ? SSH_FXP_EXTENDED : (UseLink ? SSH_FXP_LINK : SSH_FXP_SYMLINK));
  3468. if (UseHardlink)
  3469. {
  3470. Packet.AddString(SFTP_EXT_HARDLINK);
  3471. }
  3472. bool Buggy;
  3473. // OpenSSH hardlink extension always uses the "wrong" order
  3474. // as it's defined as such to mimic OpenSSH symlink bug
  3475. if (UseHardlink)
  3476. {
  3477. Buggy = true; //sic
  3478. }
  3479. else
  3480. {
  3481. if (FTerminal->SessionData->SFTPBug[sbSymlink] == asOn)
  3482. {
  3483. Buggy = true;
  3484. FTerminal->LogEvent(L"Forcing workaround for SFTP link bug");
  3485. }
  3486. else if (FTerminal->SessionData->SFTPBug[sbSymlink] == asOff)
  3487. {
  3488. Buggy = false;
  3489. }
  3490. else
  3491. {
  3492. if (UseLink)
  3493. {
  3494. if (FSecureShell->SshImplementation == sshiProFTPD)
  3495. {
  3496. // ProFTPD/mod_sftp followed OpenSSH symlink bug even for link implementation.
  3497. // This will be fixed with the next release with
  3498. // SSH version string bumbed to "mod_sftp/1.0.0"
  3499. // http://bugs.proftpd.org/show_bug.cgi?id=4080
  3500. UnicodeString ProFTPDVerStr = GetSessionInfo().SshImplementation;
  3501. CutToChar(ProFTPDVerStr, L'/', false);
  3502. int ProFTPDMajorVer = StrToIntDef(CutToChar(ProFTPDVerStr, L'.', false), 0);
  3503. Buggy = (ProFTPDMajorVer == 0);
  3504. if (Buggy)
  3505. {
  3506. FTerminal->LogEvent(L"We believe the server has SFTP link bug");
  3507. }
  3508. }
  3509. else
  3510. {
  3511. Buggy = false;
  3512. }
  3513. }
  3514. else
  3515. {
  3516. // ProFTPD/mod_sftp deliberately follows OpenSSH bug.
  3517. // Though we should get here with ProFTPD only when user forced
  3518. // SFTP version < 6 or when connecting to an ancient version of ProFTPD.
  3519. Buggy =
  3520. (FSecureShell->SshImplementation == sshiOpenSSH) ||
  3521. (FSecureShell->SshImplementation == sshiProFTPD);
  3522. if (Buggy)
  3523. {
  3524. FTerminal->LogEvent(L"We believe the server has SFTP symlink bug");
  3525. }
  3526. }
  3527. }
  3528. }
  3529. UnicodeString FinalPointTo = PointTo;
  3530. UnicodeString FinalFileName = Canonify(FileName);
  3531. if (!Symbolic)
  3532. {
  3533. FinalPointTo = Canonify(PointTo);
  3534. }
  3535. if (!Buggy)
  3536. {
  3537. Packet.AddPathString(FinalFileName, FUtfStrings);
  3538. Packet.AddPathString(FinalPointTo, FUtfStrings);
  3539. }
  3540. else
  3541. {
  3542. Packet.AddPathString(FinalPointTo, FUtfStrings);
  3543. Packet.AddPathString(FinalFileName, FUtfStrings);
  3544. }
  3545. if (UseLink)
  3546. {
  3547. Packet.AddBool(Symbolic);
  3548. }
  3549. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3550. }
  3551. //---------------------------------------------------------------------------
  3552. void __fastcall TSFTPFileSystem::ChangeFileProperties(const UnicodeString FileName,
  3553. const TRemoteFile * /*File*/, const TRemoteProperties * AProperties,
  3554. TChmodSessionAction & Action)
  3555. {
  3556. DebugAssert(AProperties != NULL);
  3557. TRemoteFile * File;
  3558. UnicodeString RealFileName = LocalCanonify(FileName);
  3559. ReadFile(RealFileName, File);
  3560. try
  3561. {
  3562. DebugAssert(File);
  3563. if (File->IsDirectory && FTerminal->CanRecurseToDirectory(File) && AProperties->Recursive)
  3564. {
  3565. try
  3566. {
  3567. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  3568. (void*)AProperties);
  3569. }
  3570. catch(...)
  3571. {
  3572. Action.Cancel();
  3573. throw;
  3574. }
  3575. }
  3576. // SFTP can change owner and group at the same time only, not individually.
  3577. // Fortunately we know current owner/group, so if only one is present,
  3578. // we can supplement the other.
  3579. TRemoteProperties Properties(*AProperties);
  3580. if (Properties.Valid.Contains(vpGroup) &&
  3581. !Properties.Valid.Contains(vpOwner))
  3582. {
  3583. Properties.Owner = File->Owner;
  3584. Properties.Valid << vpOwner;
  3585. }
  3586. else if (Properties.Valid.Contains(vpOwner) &&
  3587. !Properties.Valid.Contains(vpGroup))
  3588. {
  3589. Properties.Group = File->Group;
  3590. Properties.Valid << vpGroup;
  3591. }
  3592. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  3593. Packet.AddPathString(RealFileName, FUtfStrings);
  3594. Packet.AddProperties(&Properties, *File->Rights, File->IsDirectory, FVersion, FUtfStrings, &Action);
  3595. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3596. }
  3597. __finally
  3598. {
  3599. delete File;
  3600. }
  3601. }
  3602. //---------------------------------------------------------------------------
  3603. bool __fastcall TSFTPFileSystem::LoadFilesProperties(TStrings * FileList)
  3604. {
  3605. bool Result = false;
  3606. // without knowledge of server's capabilities, this all make no sense
  3607. if (FSupport->Loaded || (FSecureShell->SshImplementation == sshiBitvise))
  3608. {
  3609. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  3610. Progress.Start(foGetProperties, osRemote, FileList->Count);
  3611. FTerminal->FOperationProgress = &Progress;
  3612. static int LoadFilesPropertiesQueueLen = 5;
  3613. TSFTPLoadFilesPropertiesQueue Queue(this);
  3614. try
  3615. {
  3616. if (Queue.Init(LoadFilesPropertiesQueueLen, FileList))
  3617. {
  3618. TRemoteFile * File;
  3619. TSFTPPacket Packet;
  3620. bool Next;
  3621. do
  3622. {
  3623. Next = Queue.ReceivePacket(&Packet, File);
  3624. DebugAssert((Packet.Type == SSH_FXP_ATTRS) || (Packet.Type == SSH_FXP_STATUS));
  3625. if (Packet.Type == SSH_FXP_ATTRS)
  3626. {
  3627. DebugAssert(File != NULL);
  3628. Progress.SetFile(File->FileName);
  3629. LoadFile(File, &Packet);
  3630. Result = true;
  3631. TOnceDoneOperation OnceDoneOperation;
  3632. Progress.Finish(File->FileName, true, OnceDoneOperation);
  3633. }
  3634. if (Progress.Cancel != csContinue)
  3635. {
  3636. Next = false;
  3637. }
  3638. }
  3639. while (Next);
  3640. }
  3641. }
  3642. __finally
  3643. {
  3644. Queue.DisposeSafe();
  3645. FTerminal->FOperationProgress = NULL;
  3646. Progress.Stop();
  3647. }
  3648. // queue is discarded here
  3649. }
  3650. return Result;
  3651. }
  3652. //---------------------------------------------------------------------------
  3653. void __fastcall TSFTPFileSystem::DoCalculateFilesChecksum(
  3654. const UnicodeString & Alg, const UnicodeString & SftpAlg,
  3655. TStrings * FileList, TStrings * Checksums,
  3656. TCalculatedChecksumEvent OnCalculatedChecksum,
  3657. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  3658. {
  3659. TOnceDoneOperation OnceDoneOperation; // not used
  3660. // recurse into subdirectories only if we have callback function
  3661. if (OnCalculatedChecksum != NULL)
  3662. {
  3663. for (int Index = 0; Index < FileList->Count; Index++)
  3664. {
  3665. TRemoteFile * File = (TRemoteFile *)FileList->Objects[Index];
  3666. DebugAssert(File != NULL);
  3667. if (File->IsDirectory && FTerminal->CanRecurseToDirectory(File) &&
  3668. !File->IsParentDirectory && !File->IsThisDirectory)
  3669. {
  3670. OperationProgress->SetFile(File->FileName);
  3671. TRemoteFileList * SubFiles =
  3672. FTerminal->CustomReadDirectoryListing(File->FullFileName, false);
  3673. if (SubFiles != NULL)
  3674. {
  3675. TStrings * SubFileList = new TStringList();
  3676. bool Success = false;
  3677. try
  3678. {
  3679. OperationProgress->SetFile(File->FileName);
  3680. for (int Index = 0; Index < SubFiles->Count; Index++)
  3681. {
  3682. TRemoteFile * SubFile = SubFiles->Files[Index];
  3683. SubFileList->AddObject(SubFile->FullFileName, SubFile);
  3684. }
  3685. // do not collect checksums for files in subdirectories,
  3686. // only send back checksums via callback
  3687. DoCalculateFilesChecksum(Alg, SftpAlg, SubFileList, NULL,
  3688. OnCalculatedChecksum, OperationProgress, false);
  3689. Success = true;
  3690. }
  3691. __finally
  3692. {
  3693. delete SubFiles;
  3694. delete SubFileList;
  3695. if (FirstLevel)
  3696. {
  3697. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  3698. }
  3699. }
  3700. }
  3701. }
  3702. }
  3703. }
  3704. static int CalculateFilesChecksumQueueLen = 5;
  3705. TSFTPCalculateFilesChecksumQueue Queue(this);
  3706. try
  3707. {
  3708. if (Queue.Init(CalculateFilesChecksumQueueLen, SftpAlg, FileList))
  3709. {
  3710. TSFTPPacket Packet;
  3711. bool Next;
  3712. do
  3713. {
  3714. bool Success = false;
  3715. UnicodeString Checksum;
  3716. TRemoteFile * File = NULL;
  3717. try
  3718. {
  3719. TChecksumSessionAction Action(FTerminal->ActionLog);
  3720. try
  3721. {
  3722. Next = Queue.ReceivePacket(&Packet, File);
  3723. DebugAssert(Packet.Type == SSH_FXP_EXTENDED_REPLY);
  3724. OperationProgress->SetFile(File->FileName);
  3725. Action.FileName(FTerminal->AbsolutePath(File->FullFileName, true));
  3726. // skip alg
  3727. Packet.GetAnsiString();
  3728. Checksum = BytesToHex(reinterpret_cast<const unsigned char*>(Packet.GetNextData(Packet.RemainingLength)), Packet.RemainingLength, false);
  3729. if (OnCalculatedChecksum != NULL)
  3730. {
  3731. OnCalculatedChecksum(File->FileName, Alg, Checksum);
  3732. }
  3733. Action.Checksum(Alg, Checksum);
  3734. Success = true;
  3735. }
  3736. catch (Exception & E)
  3737. {
  3738. FTerminal->RollbackAction(Action, OperationProgress, &E);
  3739. // Error formatting expanded from inline to avoid strange exceptions
  3740. UnicodeString Error =
  3741. FMTLOAD(CHECKSUM_ERROR,
  3742. (File != NULL ? File->FullFileName : UnicodeString(L"")));
  3743. FTerminal->CommandError(&E, Error);
  3744. // TODO: retries? resume?
  3745. Next = false;
  3746. }
  3747. if (Checksums != NULL)
  3748. {
  3749. Checksums->Add(Checksum);
  3750. }
  3751. }
  3752. __finally
  3753. {
  3754. if (FirstLevel)
  3755. {
  3756. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  3757. }
  3758. }
  3759. if (OperationProgress->Cancel != csContinue)
  3760. {
  3761. Next = false;
  3762. }
  3763. }
  3764. while (Next);
  3765. }
  3766. }
  3767. __finally
  3768. {
  3769. Queue.DisposeSafe();
  3770. }
  3771. // queue is discarded here
  3772. }
  3773. //---------------------------------------------------------------------------
  3774. void __fastcall TSFTPFileSystem::CalculateFilesChecksum(const UnicodeString & Alg,
  3775. TStrings * FileList, TStrings * Checksums,
  3776. TCalculatedChecksumEvent OnCalculatedChecksum)
  3777. {
  3778. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  3779. Progress.Start(foCalculateChecksum, osRemote, FileList->Count);
  3780. UnicodeString NormalizedAlg = FindIdent(Alg, FChecksumAlgs.get());
  3781. UnicodeString SftpAlg;
  3782. int Index = FChecksumAlgs->IndexOf(NormalizedAlg);
  3783. if (Index >= 0)
  3784. {
  3785. SftpAlg = FChecksumSftpAlgs->Strings[Index];
  3786. }
  3787. else
  3788. {
  3789. // try user-specified alg
  3790. SftpAlg = NormalizedAlg;
  3791. }
  3792. FTerminal->FOperationProgress = &Progress;
  3793. try
  3794. {
  3795. DoCalculateFilesChecksum(NormalizedAlg, SftpAlg, FileList, Checksums, OnCalculatedChecksum,
  3796. &Progress, true);
  3797. }
  3798. __finally
  3799. {
  3800. FTerminal->FOperationProgress = NULL;
  3801. Progress.Stop();
  3802. }
  3803. }
  3804. //---------------------------------------------------------------------------
  3805. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const UnicodeString /*FileName*/,
  3806. const TRemoteFile * /*File*/, UnicodeString /*Command*/, int /*Params*/,
  3807. TCaptureOutputEvent /*OutputEvent*/)
  3808. {
  3809. DebugFail();
  3810. }
  3811. //---------------------------------------------------------------------------
  3812. void __fastcall TSFTPFileSystem::AnyCommand(const UnicodeString /*Command*/,
  3813. TCaptureOutputEvent /*OutputEvent*/)
  3814. {
  3815. DebugFail();
  3816. }
  3817. //---------------------------------------------------------------------------
  3818. TStrings * __fastcall TSFTPFileSystem::GetFixedPaths()
  3819. {
  3820. return FFixedPaths;
  3821. }
  3822. //---------------------------------------------------------------------------
  3823. void __fastcall TSFTPFileSystem::SpaceAvailable(const UnicodeString Path,
  3824. TSpaceAvailable & ASpaceAvailable)
  3825. {
  3826. if (SupportsExtension(SFTP_EXT_SPACE_AVAILABLE) ||
  3827. // See comment in IsCapable
  3828. (FSecureShell->SshImplementation == sshiBitvise))
  3829. {
  3830. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3831. Packet.AddString(SFTP_EXT_SPACE_AVAILABLE);
  3832. Packet.AddPathString(LocalCanonify(Path), FUtfStrings);
  3833. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3834. ASpaceAvailable.BytesOnDevice = Packet.GetInt64();
  3835. ASpaceAvailable.UnusedBytesOnDevice = Packet.GetInt64();
  3836. ASpaceAvailable.BytesAvailableToUser = Packet.GetInt64();
  3837. ASpaceAvailable.UnusedBytesAvailableToUser = Packet.GetInt64();
  3838. // bytes-per-allocation-unit was added later to the protocol
  3839. // (revision 07, while the extension was defined already in rev 06),
  3840. // be tolerant
  3841. if (Packet.CanGetCardinal())
  3842. {
  3843. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetCardinal();
  3844. }
  3845. else if (Packet.CanGetSmallCardinal())
  3846. {
  3847. // See http://bugs.proftpd.org/show_bug.cgi?id=4079
  3848. FTerminal->LogEvent(L"Assuming ProFTPD/mod_sftp bug of 2-byte bytes-per-allocation-unit field");
  3849. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetSmallCardinal();
  3850. }
  3851. else
  3852. {
  3853. FTerminal->LogEvent(L"Missing bytes-per-allocation-unit field");
  3854. }
  3855. }
  3856. else if (DebugAlwaysTrue(FSupportsStatVfsV2))
  3857. {
  3858. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL
  3859. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3860. Packet.AddString(SFTP_EXT_STATVFS);
  3861. Packet.AddPathString(LocalCanonify(Path), FUtfStrings);
  3862. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3863. __int64 BlockSize = Packet.GetInt64(); // file system block size
  3864. __int64 FundamentalBlockSize = Packet.GetInt64(); // fundamental fs block size
  3865. __int64 Blocks = Packet.GetInt64(); // number of blocks (unit f_frsize)
  3866. __int64 FreeBlocks = Packet.GetInt64(); // free blocks in file system
  3867. __int64 AvailableBlocks = Packet.GetInt64(); // free blocks for non-root
  3868. __int64 FileINodes = Packet.GetInt64(); // total file inodes
  3869. __int64 FreeFileINodes = Packet.GetInt64(); // free file inodes
  3870. __int64 AvailableFileINodes = Packet.GetInt64(); // free file inodes for to non-root
  3871. __int64 SID = Packet.GetInt64(); // file system id
  3872. __int64 Flags = Packet.GetInt64(); // bit mask of f_flag values
  3873. __int64 NameMax = Packet.GetInt64(); // maximum filename length
  3874. FTerminal->LogEvent(FORMAT(L"Block size: %s", (IntToStr(BlockSize))));
  3875. FTerminal->LogEvent(FORMAT(L"Fundamental block size: %s", (IntToStr(FundamentalBlockSize))));
  3876. FTerminal->LogEvent(FORMAT(L"Total blocks: %s", (IntToStr(Blocks))));
  3877. FTerminal->LogEvent(FORMAT(L"Free blocks: %s", (IntToStr(FreeBlocks))));
  3878. FTerminal->LogEvent(FORMAT(L"Free blocks for non-root: %s", (IntToStr(AvailableBlocks))));
  3879. FTerminal->LogEvent(FORMAT(L"Total file inodes: %s", (IntToStr(FileINodes))));
  3880. FTerminal->LogEvent(FORMAT(L"Free file inodes: %s", (IntToStr(FreeFileINodes))));
  3881. FTerminal->LogEvent(FORMAT(L"Free file inodes for non-root: %s", (IntToStr(AvailableFileINodes))));
  3882. FTerminal->LogEvent(FORMAT(L"File system ID: %s", (BytesToHex(reinterpret_cast<const unsigned char *>(&SID), sizeof(SID)))));
  3883. UnicodeString FlagStr;
  3884. if (FLAGSET(Flags, SFTP_EXT_STATVFS_ST_RDONLY))
  3885. {
  3886. AddToList(FlagStr, L"read-only", L",");
  3887. Flags -= SFTP_EXT_STATVFS_ST_RDONLY;
  3888. }
  3889. if (FLAGSET(Flags, SFTP_EXT_STATVFS_ST_NOSUID))
  3890. {
  3891. AddToList(FlagStr, L"no-setuid", L",");
  3892. Flags -= SFTP_EXT_STATVFS_ST_NOSUID;
  3893. }
  3894. if (Flags != 0)
  3895. {
  3896. AddToList(FlagStr, UnicodeString(L"0x") + IntToHex(Flags, 2), L",");
  3897. }
  3898. if (FlagStr.IsEmpty())
  3899. {
  3900. FlagStr = L"none";
  3901. }
  3902. FTerminal->LogEvent(FORMAT(L"Flags: %s", (FlagStr)));
  3903. FTerminal->LogEvent(FORMAT(L"Max name length: %s", (IntToStr(NameMax))));
  3904. ASpaceAvailable.BytesOnDevice = BlockSize * Blocks;
  3905. ASpaceAvailable.UnusedBytesOnDevice = BlockSize * FreeBlocks;
  3906. ASpaceAvailable.BytesAvailableToUser = 0;
  3907. ASpaceAvailable.UnusedBytesAvailableToUser = BlockSize * AvailableBlocks;
  3908. ASpaceAvailable.BytesPerAllocationUnit =
  3909. (BlockSize > std::numeric_limits<unsigned long>::max()) ? 0 : static_cast<unsigned long>(BlockSize);
  3910. }
  3911. }
  3912. //---------------------------------------------------------------------------
  3913. // transfer protocol
  3914. //---------------------------------------------------------------------------
  3915. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  3916. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  3917. int Params, TFileOperationProgressType * OperationProgress,
  3918. TOnceDoneOperation & OnceDoneOperation)
  3919. {
  3920. DebugAssert(FilesToCopy && OperationProgress);
  3921. UnicodeString FileName, FileNameOnly;
  3922. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  3923. int Index = 0;
  3924. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  3925. {
  3926. bool Success = false;
  3927. FileName = FilesToCopy->Strings[Index];
  3928. FileNameOnly = ExtractFileName(FileName);
  3929. DebugAssert(!FAvoidBusy);
  3930. FAvoidBusy = true;
  3931. try
  3932. {
  3933. try
  3934. {
  3935. if (FTerminal->SessionData->CacheDirectories)
  3936. {
  3937. FTerminal->DirectoryModified(TargetDir, false);
  3938. if (DirectoryExists(ApiPath(FileName)))
  3939. {
  3940. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  3941. FileNameOnly, true);
  3942. }
  3943. }
  3944. SFTPSourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  3945. tfFirstLevel);
  3946. Success = true;
  3947. }
  3948. catch(EScpSkipFile & E)
  3949. {
  3950. TSuspendFileOperationProgress Suspend(OperationProgress);
  3951. if (!FTerminal->HandleException(&E))
  3952. {
  3953. throw;
  3954. }
  3955. }
  3956. }
  3957. __finally
  3958. {
  3959. FAvoidBusy = false;
  3960. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  3961. }
  3962. Index++;
  3963. }
  3964. }
  3965. //---------------------------------------------------------------------------
  3966. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(
  3967. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  3968. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  3969. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  3970. {
  3971. bool CanAppend = (FVersion < 4) || !OperationProgress->AsciiTransfer;
  3972. unsigned int Answer;
  3973. {
  3974. TSuspendFileOperationProgress Suspend(OperationProgress);
  3975. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  3976. // possibly we can allow alternate resume at least in some cases
  3977. if (CanAppend)
  3978. {
  3979. Answers |= qaRetry;
  3980. }
  3981. TQueryButtonAlias Aliases[5];
  3982. Aliases[0].Button = qaRetry;
  3983. Aliases[0].Alias = LoadStr(APPEND_BUTTON);
  3984. Aliases[0].GroupWith = qaNo;
  3985. Aliases[0].GrouppedShiftState = TShiftState() << ssAlt;
  3986. Aliases[1].Button = qaAll;
  3987. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  3988. Aliases[1].GroupWith = qaYes;
  3989. Aliases[1].GrouppedShiftState = TShiftState() << ssCtrl;
  3990. Aliases[2].Button = qaIgnore;
  3991. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  3992. Aliases[2].GroupWith = qaNo;
  3993. Aliases[2].GrouppedShiftState = TShiftState() << ssCtrl;
  3994. Aliases[3].Button = qaYesToAll;
  3995. Aliases[3].GroupWith = qaYes;
  3996. Aliases[3].GrouppedShiftState = TShiftState() << ssShift;
  3997. Aliases[4].Button = qaNoToAll;
  3998. Aliases[4].GroupWith = qaNo;
  3999. Aliases[4].GrouppedShiftState = TShiftState() << ssShift;
  4000. TQueryParams QueryParams(qpNeverAskAgainCheck);
  4001. QueryParams.NoBatchAnswers = qaIgnore | qaRetry | qaAll;
  4002. QueryParams.Aliases = Aliases;
  4003. QueryParams.AliasesCount = LENOF(Aliases);
  4004. Answer = FTerminal->ConfirmFileOverwrite(
  4005. SourceFullFileName, TargetFileName, FileParams,
  4006. Answers, &QueryParams,
  4007. OperationProgress->Side == osLocal ? osRemote : osLocal,
  4008. CopyParam, Params, OperationProgress);
  4009. }
  4010. if (CanAppend &&
  4011. ((Answer == qaRetry) || (Answer == qaSkip)))
  4012. {
  4013. OperationProgress->LockUserSelections();
  4014. try
  4015. {
  4016. // duplicated in TTerminal::ConfirmFileOverwrite
  4017. bool CanAlternateResume =
  4018. (FileParams->DestSize < FileParams->SourceSize) && !OperationProgress->AsciiTransfer;
  4019. TBatchOverwrite BatchOverwrite =
  4020. FTerminal->EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  4021. // when mode is forced by batch, never query user
  4022. if (BatchOverwrite == boAppend)
  4023. {
  4024. OverwriteMode = omAppend;
  4025. }
  4026. else if (CanAlternateResume &&
  4027. ((BatchOverwrite == boResume) || (BatchOverwrite == boAlternateResume)))
  4028. {
  4029. OverwriteMode = omResume;
  4030. }
  4031. // no other option, but append
  4032. else if (!CanAlternateResume)
  4033. {
  4034. OverwriteMode = omAppend;
  4035. }
  4036. else
  4037. {
  4038. TQueryParams Params(0, HELP_APPEND_OR_RESUME);
  4039. {
  4040. TSuspendFileOperationProgress Suspend(OperationProgress);
  4041. Answer = FTerminal->QueryUser(FORMAT(LoadStr(APPEND_OR_RESUME2), (SourceFullFileName)),
  4042. NULL, qaYes | qaNo | qaNoToAll | qaCancel, &Params);
  4043. }
  4044. switch (Answer)
  4045. {
  4046. case qaYes:
  4047. OverwriteMode = omAppend;
  4048. break;
  4049. case qaNo:
  4050. OverwriteMode = omResume;
  4051. break;
  4052. case qaNoToAll:
  4053. OverwriteMode = omResume;
  4054. OperationProgress->SetBatchOverwrite(boAlternateResume);
  4055. break;
  4056. default: DebugFail(); //fallthru
  4057. case qaCancel:
  4058. OperationProgress->SetCancelAtLeast(csCancel);
  4059. Abort();
  4060. break;
  4061. }
  4062. }
  4063. }
  4064. __finally
  4065. {
  4066. OperationProgress->UnlockUserSelections();
  4067. }
  4068. }
  4069. else if (Answer == qaIgnore)
  4070. {
  4071. if (FTerminal->PromptUser(FTerminal->SessionData, pkFileName, LoadStr(RENAME_TITLE), L"",
  4072. LoadStr(RENAME_PROMPT2), true, 0, TargetFileName))
  4073. {
  4074. OverwriteMode = omOverwrite;
  4075. }
  4076. else
  4077. {
  4078. OperationProgress->SetCancelAtLeast(csCancel);
  4079. Abort();
  4080. }
  4081. }
  4082. else
  4083. {
  4084. OverwriteMode = omOverwrite;
  4085. switch (Answer)
  4086. {
  4087. case qaCancel:
  4088. OperationProgress->SetCancelAtLeast(csCancel);
  4089. Abort();
  4090. break;
  4091. case qaNo:
  4092. THROW_SKIP_FILE_NULL;
  4093. }
  4094. }
  4095. }
  4096. //---------------------------------------------------------------------------
  4097. bool TSFTPFileSystem::SFTPConfirmResume(const UnicodeString DestFileName,
  4098. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  4099. {
  4100. bool ResumeTransfer;
  4101. DebugAssert(OperationProgress);
  4102. if (PartialBiggerThanSource)
  4103. {
  4104. unsigned int Answer;
  4105. {
  4106. TSuspendFileOperationProgress Suspend(OperationProgress);
  4107. TQueryParams Params(qpAllowContinueOnError, HELP_PARTIAL_BIGGER_THAN_SOURCE);
  4108. Answer = FTerminal->QueryUser(
  4109. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
  4110. qaOK | qaAbort, &Params, qtWarning);
  4111. }
  4112. if (Answer == qaAbort)
  4113. {
  4114. OperationProgress->SetCancelAtLeast(csCancel);
  4115. Abort();
  4116. }
  4117. ResumeTransfer = false;
  4118. }
  4119. else if (FTerminal->Configuration->ConfirmResume)
  4120. {
  4121. unsigned int Answer;
  4122. {
  4123. TSuspendFileOperationProgress Suspend(OperationProgress);
  4124. TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck,
  4125. HELP_RESUME_TRANSFER);
  4126. // "abort" replaced with "cancel" to unify with "append/resume" query
  4127. Answer = FTerminal->QueryUser(
  4128. FMTLOAD(RESUME_TRANSFER2, (DestFileName)), NULL, qaYes | qaNo | qaCancel,
  4129. &Params);
  4130. }
  4131. switch (Answer) {
  4132. case qaNeverAskAgain:
  4133. FTerminal->Configuration->ConfirmResume = false;
  4134. case qaYes:
  4135. ResumeTransfer = true;
  4136. break;
  4137. case qaNo:
  4138. ResumeTransfer = false;
  4139. break;
  4140. case qaCancel:
  4141. OperationProgress->SetCancelAtLeast(csCancel);
  4142. Abort();
  4143. break;
  4144. }
  4145. }
  4146. else
  4147. {
  4148. ResumeTransfer = true;
  4149. }
  4150. return ResumeTransfer;
  4151. }
  4152. //---------------------------------------------------------------------------
  4153. void __fastcall TSFTPFileSystem::SFTPSourceRobust(const UnicodeString FileName,
  4154. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  4155. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4156. {
  4157. // the same in TFTPFileSystem
  4158. TUploadSessionAction Action(FTerminal->ActionLog);
  4159. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  4160. do
  4161. {
  4162. bool ChildError = false;
  4163. try
  4164. {
  4165. SFTPSource(FileName, TargetDir, CopyParam, Params, OperationProgress,
  4166. Flags, Action, ChildError);
  4167. }
  4168. catch(Exception & E)
  4169. {
  4170. if (!RobustLoop.TryReopen(E))
  4171. {
  4172. if (!ChildError)
  4173. {
  4174. FTerminal->RollbackAction(Action, OperationProgress, &E);
  4175. }
  4176. throw;
  4177. }
  4178. }
  4179. if (RobustLoop.ShouldRetry())
  4180. {
  4181. OperationProgress->RollbackTransfer();
  4182. Action.Restart();
  4183. // prevent overwrite and resume confirmations
  4184. // (should not be set for directories!)
  4185. Params |= cpNoConfirmation;
  4186. // enable resume even if we are uploading into new directory
  4187. Flags &= ~tfNewDirectory;
  4188. }
  4189. }
  4190. while (RobustLoop.Retry());
  4191. }
  4192. //---------------------------------------------------------------------------
  4193. void __fastcall TSFTPFileSystem::SFTPSource(const UnicodeString FileName,
  4194. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  4195. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  4196. TUploadSessionAction & Action, bool & ChildError)
  4197. {
  4198. Action.FileName(ExpandUNCFileName(FileName));
  4199. OperationProgress->SetFile(FileName, false);
  4200. if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
  4201. {
  4202. THROW_SKIP_FILE_NULL;
  4203. }
  4204. TOpenRemoteFileParams OpenParams;
  4205. OpenParams.OverwriteMode = omOverwrite;
  4206. HANDLE File;
  4207. __int64 MTime;
  4208. __int64 Size;
  4209. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
  4210. &File, NULL, &MTime, NULL, &Size);
  4211. bool Dir = FLAGSET(OpenParams.LocalFileAttrs, faDirectory);
  4212. try
  4213. {
  4214. OperationProgress->SetFileInProgress();
  4215. if (Dir)
  4216. {
  4217. Action.Cancel();
  4218. SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  4219. OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
  4220. }
  4221. else
  4222. {
  4223. // File is regular file (not directory)
  4224. DebugAssert(File);
  4225. UnicodeString DestFileName =
  4226. FTerminal->ChangeFileName(
  4227. CopyParam, ExtractFileName(FileName), osLocal,
  4228. FLAGSET(Flags, tfFirstLevel));
  4229. UnicodeString DestFullName = LocalCanonify(TargetDir + DestFileName);
  4230. UnicodeString DestPartialFullName;
  4231. bool ResumeAllowed;
  4232. bool ResumeTransfer = false;
  4233. bool DestFileExists = false;
  4234. TRights DestRights;
  4235. __int64 ResumeOffset;
  4236. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  4237. OperationProgress->SetLocalSize(Size);
  4238. // Suppose same data size to transfer as to read
  4239. // (not true with ASCII transfer)
  4240. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  4241. TDateTime Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  4242. // Will we use ASCII of BINARY file transfer?
  4243. TFileMasks::TParams MaskParams;
  4244. MaskParams.Size = Size;
  4245. MaskParams.Modification = Modification;
  4246. UnicodeString BaseFileName = FTerminal->GetBaseFileName(FileName);
  4247. OperationProgress->SetAsciiTransfer(
  4248. CopyParam->UseAsciiTransfer(BaseFileName, osLocal, MaskParams));
  4249. FTerminal->LogEvent(
  4250. UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
  4251. L" transfer mode selected.");
  4252. // should we check for interrupted transfer?
  4253. ResumeAllowed = !OperationProgress->AsciiTransfer &&
  4254. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  4255. IsCapable(fcRename);
  4256. TOverwriteFileParams FileParams;
  4257. FileParams.SourceSize = OperationProgress->LocalSize;
  4258. FileParams.SourceTimestamp = Modification;
  4259. if (ResumeAllowed)
  4260. {
  4261. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4262. if (FLAGCLEAR(Flags, tfNewDirectory))
  4263. {
  4264. FTerminal->LogEvent(L"Checking existence of file.");
  4265. TRemoteFile * File = NULL;
  4266. DestFileExists = RemoteFileExists(DestFullName, &File);
  4267. OperationProgress->Progress();
  4268. if (DestFileExists)
  4269. {
  4270. FTerminal->LogEvent(FORMAT(L"File exists: %s", (FTerminal->GetRemoteFileInfo(File))));
  4271. OpenParams.DestFileSize = File->Size;
  4272. FileParams.DestSize = OpenParams.DestFileSize;
  4273. FileParams.DestTimestamp = File->Modification;
  4274. DestRights = *File->Rights;
  4275. // If destination file is symlink, never do resumable transfer,
  4276. // as it would delete the symlink.
  4277. if (File->IsSymLink)
  4278. {
  4279. ResumeAllowed = false;
  4280. FTerminal->LogEvent(L"Existing file is symbolic link, not doing resumable transfer.");
  4281. }
  4282. // Also bit of heuristics to detect symlink on SFTP-3 and older
  4283. // (which does not indicate symlink in SSH_FXP_ATTRS).
  4284. // if file has all permissions and is small, then it is likely symlink.
  4285. // also it is not likely that such a small file (if it is not symlink)
  4286. // gets overwritten by large file (that would trigger resumable transfer).
  4287. else if ((FVersion < 4) &&
  4288. ((*File->Rights & TRights::rfAll) == TRights::rfAll) &&
  4289. (File->Size < 100))
  4290. {
  4291. ResumeAllowed = false;
  4292. FTerminal->LogEvent(L"Existing file looks like a symbolic link, not doing resumable transfer.");
  4293. }
  4294. // Also never do resumable transfer for file owned by other user
  4295. // as deleting and recreating the file would change ownership.
  4296. // This won't for work for SFTP-3 (OpenSSH) as it does not provide
  4297. // owner name (only UID) and we know only logged in user name (not UID)
  4298. else if (!File->Owner.Name.IsEmpty() && !SameUserName(File->Owner.Name, FTerminal->UserName))
  4299. {
  4300. ResumeAllowed = false;
  4301. FTerminal->LogEvent(
  4302. FORMAT(L"Existing file is owned by another user [%s], not doing resumable transfer.", (File->Owner.Name)));
  4303. }
  4304. delete File;
  4305. File = NULL;
  4306. }
  4307. if (ResumeAllowed)
  4308. {
  4309. FTerminal->LogEvent(L"Checking existence of partially transferred file.");
  4310. if (RemoteFileExists(DestPartialFullName, &File))
  4311. {
  4312. ResumeOffset = File->Size;
  4313. delete File;
  4314. File = NULL;
  4315. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->LocalSize);
  4316. if (FLAGCLEAR(Params, cpNoConfirmation) &&
  4317. FLAGCLEAR(Params, cpResume) &&
  4318. !CopyParam->ResumeTransfer(FileName))
  4319. {
  4320. ResumeTransfer = SFTPConfirmResume(DestFileName,
  4321. PartialBiggerThanSource, OperationProgress);
  4322. }
  4323. else
  4324. {
  4325. ResumeTransfer = !PartialBiggerThanSource;
  4326. }
  4327. if (!ResumeTransfer)
  4328. {
  4329. DoDeleteFile(DestPartialFullName, SSH_FXP_REMOVE);
  4330. OperationProgress->Progress();
  4331. }
  4332. else
  4333. {
  4334. FTerminal->LogEvent(L"Resuming file transfer.");
  4335. }
  4336. }
  4337. else
  4338. {
  4339. // partial upload file does not exists, check for full file
  4340. if (DestFileExists)
  4341. {
  4342. UnicodeString PrevDestFileName = DestFileName;
  4343. SFTPConfirmOverwrite(FileName, DestFileName,
  4344. CopyParam, Params, OperationProgress, OpenParams.OverwriteMode, &FileParams);
  4345. if (PrevDestFileName != DestFileName)
  4346. {
  4347. // update paths in case user changes the file name
  4348. DestFullName = LocalCanonify(TargetDir + DestFileName);
  4349. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4350. FTerminal->LogEvent(L"Checking existence of new file.");
  4351. DestFileExists = RemoteFileExists(DestFullName, NULL);
  4352. }
  4353. }
  4354. }
  4355. }
  4356. }
  4357. }
  4358. // will the transfer be resumable?
  4359. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  4360. UnicodeString RemoteFileName = DoResume ? DestPartialFullName : DestFullName;
  4361. OpenParams.FileName = FileName;
  4362. OpenParams.RemoteFileName = RemoteFileName;
  4363. OpenParams.Resume = DoResume;
  4364. OpenParams.Resuming = ResumeTransfer;
  4365. OpenParams.OperationProgress = OperationProgress;
  4366. OpenParams.CopyParam = CopyParam;
  4367. OpenParams.Params = Params;
  4368. OpenParams.FileParams = &FileParams;
  4369. OpenParams.Confirmed = false;
  4370. FTerminal->LogEvent(L"Opening remote file.");
  4371. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
  4372. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  4373. &OpenParams);
  4374. OperationProgress->Progress();
  4375. if (OpenParams.RemoteFileName != RemoteFileName)
  4376. {
  4377. DebugAssert(!DoResume);
  4378. DebugAssert(UnixExtractFilePath(OpenParams.RemoteFileName) == UnixExtractFilePath(RemoteFileName));
  4379. DestFullName = OpenParams.RemoteFileName;
  4380. UnicodeString NewFileName = UnixExtractFileName(DestFullName);
  4381. DebugAssert(DestFileName != NewFileName);
  4382. DestFileName = NewFileName;
  4383. }
  4384. Action.Destination(DestFullName);
  4385. bool TransferFinished = false;
  4386. __int64 DestWriteOffset = 0;
  4387. TSFTPPacket CloseRequest;
  4388. bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
  4389. bool SetProperties = (CopyParam->PreserveTime || SetRights);
  4390. TSFTPPacket PropertiesRequest(SSH_FXP_SETSTAT);
  4391. TSFTPPacket PropertiesResponse;
  4392. TRights Rights;
  4393. if (SetProperties)
  4394. {
  4395. PropertiesRequest.AddPathString(DestFullName, FUtfStrings);
  4396. if (CopyParam->PreserveRights)
  4397. {
  4398. Rights = CopyParam->RemoteFileRights(OpenParams.LocalFileAttrs);
  4399. }
  4400. else if (DoResume && DestFileExists)
  4401. {
  4402. Rights = DestRights;
  4403. }
  4404. else
  4405. {
  4406. DebugAssert(!SetRights);
  4407. }
  4408. unsigned short RightsNumber = Rights.NumberSet;
  4409. PropertiesRequest.AddProperties(
  4410. SetRights ? &RightsNumber : NULL, NULL, NULL,
  4411. CopyParam->PreserveTime ? &MTime : NULL,
  4412. NULL, NULL, false, FVersion, FUtfStrings);
  4413. }
  4414. try
  4415. {
  4416. if (OpenParams.OverwriteMode == omAppend)
  4417. {
  4418. FTerminal->LogEvent(L"Appending file.");
  4419. DestWriteOffset = OpenParams.DestFileSize;
  4420. }
  4421. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  4422. {
  4423. if (OpenParams.OverwriteMode == omResume)
  4424. {
  4425. FTerminal->LogEvent(L"Resuming file transfer (append style).");
  4426. ResumeOffset = OpenParams.DestFileSize;
  4427. }
  4428. FileSeek((THandle)File, ResumeOffset, 0);
  4429. OperationProgress->AddResumed(ResumeOffset);
  4430. }
  4431. TSFTPUploadQueue Queue(this);
  4432. try
  4433. {
  4434. int ConvertParams =
  4435. FLAGMASK(CopyParam->RemoveCtrlZ, cpRemoveCtrlZ) |
  4436. FLAGMASK(CopyParam->RemoveBOM, cpRemoveBOM);
  4437. Queue.Init(FileName, File, OperationProgress,
  4438. OpenParams.RemoteFileHandle,
  4439. DestWriteOffset + OperationProgress->TransferredSize,
  4440. ConvertParams);
  4441. while (Queue.Continue())
  4442. {
  4443. if (OperationProgress->Cancel)
  4444. {
  4445. if (OperationProgress->ClearCancelFile())
  4446. {
  4447. THROW_SKIP_FILE_NULL;
  4448. }
  4449. else
  4450. {
  4451. Abort();
  4452. }
  4453. }
  4454. }
  4455. // send close request before waiting for pending read responses
  4456. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4457. OperationProgress, false, true, &CloseRequest);
  4458. OpenParams.RemoteFileHandle = L"";
  4459. // when resuming is disabled, we can send "set properties"
  4460. // request before waiting for pending read/close responses
  4461. if (SetProperties && !DoResume)
  4462. {
  4463. SendPacket(&PropertiesRequest);
  4464. ReserveResponse(&PropertiesRequest, &PropertiesResponse);
  4465. }
  4466. // No error so far, processes pending responses and throw on first error
  4467. Queue.DisposeSafeWithErrorHandling();
  4468. }
  4469. __finally
  4470. {
  4471. // Either queue is empty now (noop call then),
  4472. // or some error occured (in that case, process remaining responses, ignoring other errors)
  4473. Queue.DisposeSafe();
  4474. }
  4475. TransferFinished = true;
  4476. // queue is discarded here
  4477. }
  4478. __finally
  4479. {
  4480. if (FTerminal->Active)
  4481. {
  4482. // if file transfer was finished, the close request was already sent
  4483. if (!OpenParams.RemoteFileHandle.IsEmpty())
  4484. {
  4485. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4486. OperationProgress, TransferFinished, true, &CloseRequest);
  4487. }
  4488. // wait for the response
  4489. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4490. OperationProgress, TransferFinished, false, &CloseRequest);
  4491. // delete file if transfer was not completed, resuming was not allowed and
  4492. // we were not appending (incl. alternate resume),
  4493. // shortly after plain transfer completes (eq. !ResumeAllowed)
  4494. if (!TransferFinished && !DoResume && (OpenParams.OverwriteMode == omOverwrite))
  4495. {
  4496. DoDeleteFile(OpenParams.RemoteFileName, SSH_FXP_REMOVE);
  4497. }
  4498. }
  4499. }
  4500. OperationProgress->Progress();
  4501. if (DoResume)
  4502. {
  4503. if (DestFileExists)
  4504. {
  4505. FILE_OPERATION_LOOP_BEGIN
  4506. {
  4507. if (FTerminal->SessionData->OverwrittenToRecycleBin &&
  4508. !FTerminal->SessionData->RecycleBinPath.IsEmpty())
  4509. {
  4510. FTerminal->RecycleFile(DestFullName, NULL);
  4511. }
  4512. else
  4513. {
  4514. DoDeleteFile(DestFullName, SSH_FXP_REMOVE);
  4515. }
  4516. }
  4517. FILE_OPERATION_LOOP_END(
  4518. FMTLOAD(DELETE_ON_RESUME_ERROR,
  4519. (UnixExtractFileName(DestFullName), DestFullName)));
  4520. }
  4521. // originally this was before CLOSE (last __finally statement),
  4522. // on VShell it failed
  4523. FILE_OPERATION_LOOP_BEGIN
  4524. {
  4525. RenameFile(OpenParams.RemoteFileName, DestFileName);
  4526. }
  4527. FILE_OPERATION_LOOP_END_CUSTOM(
  4528. FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  4529. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  4530. true, HELP_RENAME_AFTER_RESUME_ERROR);
  4531. }
  4532. if (SetProperties)
  4533. {
  4534. std::unique_ptr<TTouchSessionAction> TouchAction;
  4535. if (CopyParam->PreserveTime)
  4536. {
  4537. TDateTime MDateTime = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  4538. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  4539. (StandardTimestamp(MDateTime))));
  4540. TouchAction.reset(new TTouchSessionAction(FTerminal->ActionLog, DestFullName,
  4541. MDateTime));
  4542. }
  4543. std::unique_ptr<TChmodSessionAction> ChmodAction;
  4544. // do record chmod only if it was explicitly requested,
  4545. // not when it was implicitly performed to apply timestamp
  4546. // of overwritten file to new file
  4547. if (CopyParam->PreserveRights)
  4548. {
  4549. ChmodAction.reset(new TChmodSessionAction(FTerminal->ActionLog, DestFullName, Rights));
  4550. }
  4551. try
  4552. {
  4553. // when resuming is enabled, the set properties request was not sent yet
  4554. if (DoResume)
  4555. {
  4556. SendPacket(&PropertiesRequest);
  4557. }
  4558. bool Resend = false;
  4559. FILE_OPERATION_LOOP_BEGIN
  4560. {
  4561. try
  4562. {
  4563. TSFTPPacket DummyResponse;
  4564. TSFTPPacket * Response = &PropertiesResponse;
  4565. if (Resend)
  4566. {
  4567. PropertiesRequest.Reuse();
  4568. SendPacket(&PropertiesRequest);
  4569. // ReceiveResponse currently cannot receive twice into same packet,
  4570. // so DummyResponse is temporary workaround
  4571. Response = &DummyResponse;
  4572. }
  4573. Resend = true;
  4574. ReceiveResponse(&PropertiesRequest, Response, SSH_FXP_STATUS,
  4575. asOK | FLAGMASK(CopyParam->IgnorePermErrors, asPermDenied));
  4576. }
  4577. catch (...)
  4578. {
  4579. if (FTerminal->Active &&
  4580. (!CopyParam->PreserveRights && !CopyParam->PreserveTime))
  4581. {
  4582. DebugAssert(DoResume);
  4583. FTerminal->LogEvent(L"Ignoring error preserving permissions of overwritten file");
  4584. }
  4585. else
  4586. {
  4587. throw;
  4588. }
  4589. }
  4590. }
  4591. FILE_OPERATION_LOOP_END_CUSTOM(
  4592. FMTLOAD(PRESERVE_TIME_PERM_ERROR3, (DestFileName)),
  4593. true, HELP_PRESERVE_TIME_PERM_ERROR);
  4594. }
  4595. catch(Exception & E)
  4596. {
  4597. if (TouchAction.get() != NULL)
  4598. {
  4599. TouchAction->Rollback(&E);
  4600. }
  4601. if (ChmodAction.get() != NULL)
  4602. {
  4603. ChmodAction->Rollback(&E);
  4604. }
  4605. ChildError = true;
  4606. throw;
  4607. }
  4608. }
  4609. FTerminal->LogFileDone(OperationProgress, DestFullName);
  4610. }
  4611. }
  4612. __finally
  4613. {
  4614. if (File != NULL)
  4615. {
  4616. CloseHandle(File);
  4617. }
  4618. }
  4619. /* TODO : Delete also read-only files. */
  4620. if (FLAGSET(Params, cpDelete))
  4621. {
  4622. if (!Dir)
  4623. {
  4624. FILE_OPERATION_LOOP_BEGIN
  4625. {
  4626. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(FileName)));
  4627. }
  4628. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  4629. }
  4630. }
  4631. else if (CopyParam->ClearArchive && FLAGSET(OpenParams.LocalFileAttrs, faArchive))
  4632. {
  4633. FILE_OPERATION_LOOP_BEGIN
  4634. {
  4635. THROWOSIFFALSE(FileSetAttr(ApiPath(FileName), OpenParams.LocalFileAttrs & ~faArchive) == 0);
  4636. }
  4637. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  4638. }
  4639. }
  4640. //---------------------------------------------------------------------------
  4641. RawByteString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
  4642. const UnicodeString & FileName, unsigned int OpenType, __int64 Size)
  4643. {
  4644. TSFTPPacket Packet(SSH_FXP_OPEN);
  4645. Packet.AddPathString(FileName, FUtfStrings);
  4646. if (FVersion < 5)
  4647. {
  4648. Packet.AddCardinal(OpenType);
  4649. }
  4650. else
  4651. {
  4652. unsigned long Access =
  4653. FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
  4654. FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
  4655. unsigned long Flags;
  4656. if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
  4657. {
  4658. Flags = SSH_FXF_CREATE_NEW;
  4659. }
  4660. else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
  4661. {
  4662. Flags = SSH_FXF_CREATE_TRUNCATE;
  4663. }
  4664. else if (FLAGSET(OpenType, SSH_FXF_CREAT))
  4665. {
  4666. Flags = SSH_FXF_OPEN_OR_CREATE;
  4667. }
  4668. else
  4669. {
  4670. Flags = SSH_FXF_OPEN_EXISTING;
  4671. }
  4672. Flags |=
  4673. FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
  4674. FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
  4675. Packet.AddCardinal(Access);
  4676. Packet.AddCardinal(Flags);
  4677. }
  4678. bool SendSize =
  4679. (Size >= 0) &&
  4680. FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC) &&
  4681. // Particuarly VanDyke VShell (4.0.3) does not support SSH_FILEXFER_ATTR_ALLOCATION_SIZE
  4682. // (it fails open request when the attribute is included).
  4683. // It's SFTP-6 attribute, so support structure should be available.
  4684. // It's actually not with VShell. But VShell supports the SSH_FILEXFER_ATTR_ALLOCATION_SIZE.
  4685. // All servers should support SSH_FILEXFER_ATTR_SIZE (SFTP < 6)
  4686. (!FSupport->Loaded || FLAGSET(FSupport->AttributeMask, Packet.AllocationSizeAttribute(FVersion)));
  4687. Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
  4688. SendSize ? &Size : NULL, false, FVersion, FUtfStrings);
  4689. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  4690. return Packet.GetFileHandle();
  4691. }
  4692. //---------------------------------------------------------------------------
  4693. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  4694. {
  4695. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  4696. DebugAssert(OpenParams);
  4697. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  4698. int OpenType;
  4699. bool Success = false;
  4700. bool ConfirmOverwriting;
  4701. do
  4702. {
  4703. try
  4704. {
  4705. ConfirmOverwriting =
  4706. !OpenParams->Confirmed && !OpenParams->Resume &&
  4707. FTerminal->CheckRemoteFile(OpenParams->FileName, OpenParams->CopyParam, OpenParams->Params, OperationProgress);
  4708. OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
  4709. // when we want to preserve overwritten files, we need to find out that
  4710. // they exist first... even if overwrite confirmation is disabled.
  4711. // but not when we already know we are not going to overwrite (but e.g. to append)
  4712. if ((ConfirmOverwriting || FTerminal->SessionData->OverwrittenToRecycleBin) &&
  4713. (OpenParams->OverwriteMode == omOverwrite))
  4714. {
  4715. OpenType |= SSH_FXF_EXCL;
  4716. }
  4717. if (!OpenParams->Resuming && (OpenParams->OverwriteMode == omOverwrite))
  4718. {
  4719. OpenType |= SSH_FXF_TRUNC;
  4720. }
  4721. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  4722. {
  4723. OpenType |= SSH_FXF_TEXT;
  4724. }
  4725. OpenParams->RemoteFileHandle = SFTPOpenRemoteFile(
  4726. OpenParams->RemoteFileName, OpenType, OperationProgress->LocalSize);
  4727. Success = true;
  4728. }
  4729. catch(Exception & E)
  4730. {
  4731. if (!OpenParams->Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  4732. {
  4733. FTerminal->LogEvent(FORMAT(L"Cannot create new file \"%s\", checking if it exists already", (OpenParams->RemoteFileName)));
  4734. bool ThrowOriginal = false;
  4735. // When exclusive opening of file fails, try to detect if file exists.
  4736. // When file does not exist, failure was probably caused by 'permission denied'
  4737. // or similar error. In this case throw original exception.
  4738. try
  4739. {
  4740. OperationProgress->Progress();
  4741. TRemoteFile * File;
  4742. UnicodeString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  4743. ReadFile(RealFileName, File);
  4744. DebugAssert(File);
  4745. OpenParams->DestFileSize = File->Size;
  4746. if (OpenParams->FileParams != NULL)
  4747. {
  4748. OpenParams->FileParams->DestTimestamp = File->Modification;
  4749. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  4750. }
  4751. // file exists (otherwise exception was thrown)
  4752. SAFE_DESTROY(File);
  4753. }
  4754. catch(...)
  4755. {
  4756. if (!FTerminal->Active)
  4757. {
  4758. throw;
  4759. }
  4760. else
  4761. {
  4762. ThrowOriginal = true;
  4763. }
  4764. }
  4765. if (ThrowOriginal)
  4766. {
  4767. throw;
  4768. }
  4769. // we may get here even if confirmation is disabled,
  4770. // when we have preserving of overwritten files enabled
  4771. if (ConfirmOverwriting)
  4772. {
  4773. OperationProgress->Progress();
  4774. // confirmation duplicated in SFTPSource for resumable file transfers.
  4775. UnicodeString RemoteFileNameOnly = UnixExtractFileName(OpenParams->RemoteFileName);
  4776. SFTPConfirmOverwrite(OpenParams->FileName, RemoteFileNameOnly,
  4777. OpenParams->CopyParam, OpenParams->Params, OperationProgress, OpenParams->OverwriteMode, OpenParams->FileParams);
  4778. if (RemoteFileNameOnly != UnixExtractFileName(OpenParams->RemoteFileName))
  4779. {
  4780. OpenParams->RemoteFileName =
  4781. UnixExtractFilePath(OpenParams->RemoteFileName) + RemoteFileNameOnly;
  4782. }
  4783. OpenParams->Confirmed = true;
  4784. }
  4785. else
  4786. {
  4787. DebugAssert(FTerminal->SessionData->OverwrittenToRecycleBin);
  4788. }
  4789. if ((OpenParams->OverwriteMode == omOverwrite) &&
  4790. FTerminal->SessionData->OverwrittenToRecycleBin &&
  4791. !FTerminal->SessionData->RecycleBinPath.IsEmpty())
  4792. {
  4793. OperationProgress->Progress();
  4794. FTerminal->RecycleFile(OpenParams->RemoteFileName, NULL);
  4795. }
  4796. }
  4797. else if (FTerminal->Active)
  4798. {
  4799. // if file overwriting was confirmed, it means that the file already exists,
  4800. // if not, check now
  4801. if (!OpenParams->Confirmed)
  4802. {
  4803. bool ThrowOriginal = false;
  4804. // When file does not exist, failure was probably caused by 'permission denied'
  4805. // or similar error. In this case throw original exception.
  4806. try
  4807. {
  4808. TRemoteFile * File;
  4809. UnicodeString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  4810. ReadFile(RealFileName, File);
  4811. SAFE_DESTROY(File);
  4812. }
  4813. catch(...)
  4814. {
  4815. if (!FTerminal->Active)
  4816. {
  4817. throw;
  4818. }
  4819. else
  4820. {
  4821. ThrowOriginal = true;
  4822. }
  4823. }
  4824. if (ThrowOriginal)
  4825. {
  4826. throw;
  4827. }
  4828. }
  4829. // now we know that the file exists
  4830. if (FTerminal->FileOperationLoopQuery(E, OperationProgress,
  4831. FMTLOAD(SFTP_OVERWRITE_FILE_ERROR2, (OpenParams->RemoteFileName)),
  4832. true, LoadStr(SFTP_OVERWRITE_DELETE_BUTTON)))
  4833. {
  4834. OperationProgress->Progress();
  4835. int Params = dfNoRecursive;
  4836. FTerminal->DeleteFile(OpenParams->RemoteFileName, NULL, &Params);
  4837. }
  4838. }
  4839. else
  4840. {
  4841. throw;
  4842. }
  4843. }
  4844. }
  4845. while (!Success);
  4846. return 0;
  4847. }
  4848. //---------------------------------------------------------------------------
  4849. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const RawByteString Handle,
  4850. const UnicodeString FileName, TFileOperationProgressType * OperationProgress,
  4851. bool TransferFinished, bool Request, TSFTPPacket * Packet)
  4852. {
  4853. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  4854. FILE_OPERATION_LOOP_BEGIN
  4855. {
  4856. try
  4857. {
  4858. TSFTPPacket CloseRequest;
  4859. TSFTPPacket * P = (Packet == NULL ? &CloseRequest : Packet);
  4860. if (Request)
  4861. {
  4862. P->ChangeType(SSH_FXP_CLOSE);
  4863. P->AddString(Handle);
  4864. SendPacket(P);
  4865. ReserveResponse(P, Packet);
  4866. }
  4867. else
  4868. {
  4869. DebugAssert(Packet != NULL);
  4870. ReceiveResponse(P, Packet, SSH_FXP_STATUS);
  4871. }
  4872. }
  4873. catch(...)
  4874. {
  4875. if (!FTerminal->Active || TransferFinished)
  4876. {
  4877. throw;
  4878. }
  4879. }
  4880. }
  4881. FILE_OPERATION_LOOP_END(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)));
  4882. }
  4883. //---------------------------------------------------------------------------
  4884. void __fastcall TSFTPFileSystem::SFTPDirectorySource(const UnicodeString DirectoryName,
  4885. const UnicodeString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  4886. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4887. {
  4888. UnicodeString DestDirectoryName =
  4889. FTerminal->ChangeFileName(
  4890. CopyParam, ExtractFileName(ExcludeTrailingBackslash(DirectoryName)),
  4891. osLocal, FLAGSET(Flags, tfFirstLevel));
  4892. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  4893. OperationProgress->SetFile(DirectoryName);
  4894. bool CreateDir = false;
  4895. try
  4896. {
  4897. TryOpenDirectory(DestFullName);
  4898. }
  4899. catch(...)
  4900. {
  4901. if (FTerminal->Active)
  4902. {
  4903. // opening directory failed, it probably does not exists, try to
  4904. // create it
  4905. CreateDir = true;
  4906. }
  4907. else
  4908. {
  4909. throw;
  4910. }
  4911. }
  4912. if (CreateDir)
  4913. {
  4914. TRemoteProperties Properties;
  4915. if (CopyParam->PreserveRights)
  4916. {
  4917. Properties.Valid = TValidProperties() << vpRights;
  4918. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  4919. }
  4920. FTerminal->CreateDirectory(DestFullName, &Properties);
  4921. Flags |= tfNewDirectory;
  4922. }
  4923. if (FLAGCLEAR(Params, cpNoRecurse))
  4924. {
  4925. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4926. TSearchRecChecked SearchRec;
  4927. bool FindOK;
  4928. FILE_OPERATION_LOOP_BEGIN
  4929. {
  4930. FindOK =
  4931. (FindFirstChecked(DirectoryName + L"*.*", FindAttrs, SearchRec) == 0);
  4932. }
  4933. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  4934. try
  4935. {
  4936. while (FindOK && !OperationProgress->Cancel)
  4937. {
  4938. UnicodeString FileName = DirectoryName + SearchRec.Name;
  4939. try
  4940. {
  4941. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  4942. {
  4943. SFTPSourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  4944. Flags & ~tfFirstLevel);
  4945. }
  4946. }
  4947. catch (EScpSkipFile &E)
  4948. {
  4949. // If ESkipFile occurs, just log it and continue with next file
  4950. TSuspendFileOperationProgress Suspend(OperationProgress);
  4951. // here a message to user was displayed, which was not appropriate
  4952. // when user refused to overwrite the file in subdirectory.
  4953. // hopefully it won't be missing in other situations.
  4954. if (!FTerminal->HandleException(&E))
  4955. {
  4956. throw;
  4957. }
  4958. }
  4959. FILE_OPERATION_LOOP_BEGIN
  4960. {
  4961. FindOK = (FindNextChecked(SearchRec) == 0);
  4962. }
  4963. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  4964. };
  4965. }
  4966. __finally
  4967. {
  4968. FindClose(SearchRec);
  4969. }
  4970. /* TODO : Delete also read-only directories. */
  4971. /* TODO : Show error message on failure. */
  4972. if (!OperationProgress->Cancel)
  4973. {
  4974. if (CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  4975. {
  4976. TRemoteProperties Properties;
  4977. Properties.Valid << vpModification;
  4978. FTerminal->OpenLocalFile(
  4979. ExcludeTrailingBackslash(DirectoryName), GENERIC_READ, NULL, NULL, NULL,
  4980. &Properties.Modification, &Properties.LastAccess, NULL);
  4981. FTerminal->ChangeFileProperties(DestFullName, NULL, &Properties);
  4982. }
  4983. if (FLAGSET(Params, cpDelete))
  4984. {
  4985. RemoveDir(ApiPath(DirectoryName));
  4986. }
  4987. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  4988. {
  4989. FILE_OPERATION_LOOP_BEGIN
  4990. {
  4991. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  4992. }
  4993. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  4994. }
  4995. }
  4996. }
  4997. }
  4998. //---------------------------------------------------------------------------
  4999. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  5000. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  5001. int Params, TFileOperationProgressType * OperationProgress,
  5002. TOnceDoneOperation & OnceDoneOperation)
  5003. {
  5004. DebugAssert(FilesToCopy && OperationProgress);
  5005. UnicodeString FileName;
  5006. UnicodeString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  5007. const TRemoteFile * File;
  5008. bool Success;
  5009. int Index = 0;
  5010. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  5011. {
  5012. Success = false;
  5013. FileName = FilesToCopy->Strings[Index];
  5014. File = (TRemoteFile *)FilesToCopy->Objects[Index];
  5015. DebugAssert(!FAvoidBusy);
  5016. FAvoidBusy = true;
  5017. try
  5018. {
  5019. try
  5020. {
  5021. SFTPSinkRobust(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
  5022. Params, OperationProgress, tfFirstLevel);
  5023. Success = true;
  5024. }
  5025. catch(EScpSkipFile & E)
  5026. {
  5027. TSuspendFileOperationProgress Suspend(OperationProgress);
  5028. if (!FTerminal->HandleException(&E))
  5029. {
  5030. throw;
  5031. }
  5032. }
  5033. catch(...)
  5034. {
  5035. // TODO: remove the block?
  5036. throw;
  5037. }
  5038. }
  5039. __finally
  5040. {
  5041. FAvoidBusy = false;
  5042. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  5043. }
  5044. Index++;
  5045. }
  5046. }
  5047. //---------------------------------------------------------------------------
  5048. void __fastcall TSFTPFileSystem::SFTPSinkRobust(const UnicodeString FileName,
  5049. const TRemoteFile * File, const UnicodeString TargetDir,
  5050. const TCopyParamType * CopyParam, int Params,
  5051. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  5052. {
  5053. // the same in TFTPFileSystem
  5054. TDownloadSessionAction Action(FTerminal->ActionLog);
  5055. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  5056. do
  5057. {
  5058. bool ChildError = false;
  5059. try
  5060. {
  5061. SFTPSink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  5062. Flags, Action, ChildError);
  5063. }
  5064. catch(Exception & E)
  5065. {
  5066. if (!RobustLoop.TryReopen(E))
  5067. {
  5068. if (!ChildError)
  5069. {
  5070. FTerminal->RollbackAction(Action, OperationProgress, &E);
  5071. }
  5072. throw;
  5073. }
  5074. }
  5075. if (RobustLoop.ShouldRetry())
  5076. {
  5077. OperationProgress->RollbackTransfer();
  5078. Action.Restart();
  5079. DebugAssert(File != NULL);
  5080. if (!File->IsDirectory)
  5081. {
  5082. // prevent overwrite and resume confirmations
  5083. Params |= cpNoConfirmation;
  5084. }
  5085. }
  5086. }
  5087. while (RobustLoop.Retry());
  5088. }
  5089. //---------------------------------------------------------------------------
  5090. void __fastcall TSFTPFileSystem::SFTPSink(const UnicodeString FileName,
  5091. const TRemoteFile * File, const UnicodeString TargetDir,
  5092. const TCopyParamType * CopyParam, int Params,
  5093. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  5094. TDownloadSessionAction & Action, bool & ChildError)
  5095. {
  5096. Action.FileName(FileName);
  5097. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  5098. TFileMasks::TParams MaskParams;
  5099. DebugAssert(File);
  5100. MaskParams.Size = File->Size;
  5101. MaskParams.Modification = File->Modification;
  5102. UnicodeString BaseFileName = FTerminal->GetBaseFileName(FileName);
  5103. if (!CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams))
  5104. {
  5105. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  5106. THROW_SKIP_FILE_NULL;
  5107. }
  5108. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  5109. {
  5110. OperationProgress->AddSkippedFileSize(File->Size);
  5111. THROW_SKIP_FILE_NULL;
  5112. }
  5113. FTerminal->LogFileDetails(FileName, File->Modification, File->Size);
  5114. OperationProgress->SetFile(FileName);
  5115. UnicodeString DestFileName =
  5116. FTerminal->ChangeFileName(
  5117. CopyParam, OnlyFileName, osRemote, FLAGSET(Flags, tfFirstLevel));
  5118. UnicodeString DestFullName = TargetDir + DestFileName;
  5119. if (File->IsDirectory)
  5120. {
  5121. Action.Cancel();
  5122. if (FTerminal->CanRecurseToDirectory(File))
  5123. {
  5124. FILE_OPERATION_LOOP_BEGIN
  5125. {
  5126. int Attrs = FileGetAttrFix(ApiPath(DestFullName));
  5127. if ((Attrs & faDirectory) == 0) EXCEPTION;
  5128. }
  5129. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  5130. FILE_OPERATION_LOOP_BEGIN
  5131. {
  5132. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  5133. }
  5134. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  5135. if (FLAGCLEAR(Params, cpNoRecurse))
  5136. {
  5137. TSinkFileParams SinkFileParams;
  5138. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  5139. SinkFileParams.CopyParam = CopyParam;
  5140. SinkFileParams.Params = Params;
  5141. SinkFileParams.OperationProgress = OperationProgress;
  5142. SinkFileParams.Skipped = false;
  5143. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  5144. FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
  5145. if (CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  5146. {
  5147. FTerminal->LogEvent(FORMAT(L"Preserving directory timestamp [%s]",
  5148. (StandardTimestamp(File->Modification))));
  5149. int SetFileTimeError = ERROR_SUCCESS;
  5150. // FILE_FLAG_BACKUP_SEMANTICS is needed to "open" directory
  5151. HANDLE LocalHandle = CreateFile(ApiPath(DestFullName).c_str(), GENERIC_WRITE,
  5152. FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  5153. if (LocalHandle == INVALID_HANDLE_VALUE)
  5154. {
  5155. SetFileTimeError = GetLastError();
  5156. }
  5157. else
  5158. {
  5159. FILETIME AcTime = DateTimeToFileTime(File->LastAccess, FTerminal->SessionData->DSTMode);
  5160. FILETIME WrTime = DateTimeToFileTime(File->Modification, FTerminal->SessionData->DSTMode);
  5161. if (!SetFileTime(LocalHandle, NULL, &AcTime, &WrTime))
  5162. {
  5163. SetFileTimeError = GetLastError();
  5164. }
  5165. CloseHandle(LocalHandle);
  5166. }
  5167. if (SetFileTimeError != ERROR_SUCCESS)
  5168. {
  5169. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  5170. (SysErrorMessageForError(SetFileTimeError))));
  5171. }
  5172. }
  5173. // Do not delete directory if some of its files were skip.
  5174. // Throw "skip file" for the directory to avoid attempt to deletion
  5175. // of any parent directory
  5176. if ((Params & cpDelete) && SinkFileParams.Skipped)
  5177. {
  5178. THROW_SKIP_FILE_NULL;
  5179. }
  5180. }
  5181. }
  5182. else
  5183. {
  5184. FTerminal->LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (FileName)));
  5185. }
  5186. }
  5187. else
  5188. {
  5189. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  5190. UnicodeString DestPartialFullName;
  5191. bool ResumeAllowed;
  5192. bool ResumeTransfer = false;
  5193. __int64 ResumeOffset;
  5194. // Will we use ASCII of BINARY file transfer?
  5195. OperationProgress->SetAsciiTransfer(
  5196. CopyParam->UseAsciiTransfer(BaseFileName, osRemote, MaskParams));
  5197. FTerminal->LogEvent(UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
  5198. " transfer mode selected.");
  5199. // Suppose same data size to transfer as to write
  5200. // (not true with ASCII transfer)
  5201. OperationProgress->SetTransferSize(File->Size);
  5202. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  5203. // resume has no sense for temporary downloads
  5204. ResumeAllowed = ((Params & cpTemporary) == 0) &&
  5205. !OperationProgress->AsciiTransfer &&
  5206. CopyParam->AllowResume(OperationProgress->TransferSize);
  5207. int Attrs;
  5208. FILE_OPERATION_LOOP_BEGIN
  5209. {
  5210. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  5211. if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
  5212. }
  5213. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  5214. HANDLE LocalHandle = NULL;
  5215. TStream * FileStream = NULL;
  5216. bool DeleteLocalFile = false;
  5217. RawByteString RemoteHandle;
  5218. UnicodeString LocalFileName = DestFullName;
  5219. TSFTPOverwriteMode OverwriteMode = omOverwrite;
  5220. UnicodeString ExpandedDestFullName;
  5221. try
  5222. {
  5223. if (ResumeAllowed)
  5224. {
  5225. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  5226. LocalFileName = DestPartialFullName;
  5227. FTerminal->LogEvent(L"Checking existence of partially transferred file.");
  5228. if (FileExists(ApiPath(DestPartialFullName)))
  5229. {
  5230. FTerminal->LogEvent(L"Partially transferred file exists.");
  5231. FTerminal->OpenLocalFile(DestPartialFullName, GENERIC_WRITE,
  5232. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  5233. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->TransferSize);
  5234. if (FLAGCLEAR(Params, cpNoConfirmation))
  5235. {
  5236. ResumeTransfer = SFTPConfirmResume(DestFileName,
  5237. PartialBiggerThanSource, OperationProgress);
  5238. }
  5239. else
  5240. {
  5241. ResumeTransfer = !PartialBiggerThanSource;
  5242. if (!ResumeTransfer)
  5243. {
  5244. FTerminal->LogEvent(L"Partially transferred file is bigger that original file.");
  5245. }
  5246. }
  5247. if (!ResumeTransfer)
  5248. {
  5249. CloseHandle(LocalHandle);
  5250. LocalHandle = NULL;
  5251. FILE_OPERATION_LOOP_BEGIN
  5252. {
  5253. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestPartialFullName)));
  5254. }
  5255. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestPartialFullName)));
  5256. }
  5257. else
  5258. {
  5259. FTerminal->LogEvent(L"Resuming file transfer.");
  5260. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  5261. OperationProgress->AddResumed(ResumeOffset);
  5262. }
  5263. }
  5264. OperationProgress->Progress();
  5265. }
  5266. // first open source file, not to loose the destination file,
  5267. // if we cannot open the source one in the first place
  5268. FTerminal->LogEvent(L"Opening remote file.");
  5269. FILE_OPERATION_LOOP_BEGIN
  5270. {
  5271. int OpenType = SSH_FXF_READ;
  5272. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  5273. {
  5274. OpenType |= SSH_FXF_TEXT;
  5275. }
  5276. RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
  5277. OperationProgress->Progress();
  5278. }
  5279. FILE_OPERATION_LOOP_END(FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)));
  5280. TDateTime Modification;
  5281. FILETIME AcTime;
  5282. FILETIME WrTime;
  5283. TSFTPPacket RemoteFilePacket(SSH_FXP_FSTAT);
  5284. RemoteFilePacket.AddString(RemoteHandle);
  5285. SendCustomReadFile(&RemoteFilePacket, &RemoteFilePacket,
  5286. SSH_FILEXFER_ATTR_MODIFYTIME);
  5287. ReceiveResponse(&RemoteFilePacket, &RemoteFilePacket);
  5288. OperationProgress->Progress();
  5289. const TRemoteFile * AFile = NULL;
  5290. try
  5291. {
  5292. // ignore errors
  5293. if (RemoteFilePacket.Type == SSH_FXP_ATTRS)
  5294. {
  5295. // load file, avoid completion (resolving symlinks) as we do not need that
  5296. AFile = LoadFile(&RemoteFilePacket, NULL, UnixExtractFileName(FileName),
  5297. NULL, false);
  5298. }
  5299. Modification =
  5300. (AFile != NULL) && (AFile->Modification != TDateTime()) ? AFile->Modification : File->Modification;
  5301. TDateTime LastAccess =
  5302. (AFile != NULL) && (AFile->LastAccess != TDateTime()) ? AFile->LastAccess : File->LastAccess;
  5303. AcTime = DateTimeToFileTime(LastAccess, FTerminal->SessionData->DSTMode);
  5304. WrTime = DateTimeToFileTime(Modification, FTerminal->SessionData->DSTMode);
  5305. }
  5306. __finally
  5307. {
  5308. delete AFile;
  5309. }
  5310. if ((Attrs >= 0) && !ResumeTransfer)
  5311. {
  5312. __int64 DestFileSize;
  5313. __int64 MTime;
  5314. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  5315. NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  5316. FTerminal->LogEvent(L"Confirming overwriting of file.");
  5317. TOverwriteFileParams FileParams;
  5318. FileParams.SourceSize = OperationProgress->TransferSize;
  5319. FileParams.SourceTimestamp = Modification;
  5320. FileParams.DestTimestamp = UnixToDateTime(MTime,
  5321. FTerminal->SessionData->DSTMode);
  5322. FileParams.DestSize = DestFileSize;
  5323. UnicodeString PrevDestFileName = DestFileName;
  5324. SFTPConfirmOverwrite(FileName, DestFileName, CopyParam, Params, OperationProgress, OverwriteMode, &FileParams);
  5325. if (PrevDestFileName != DestFileName)
  5326. {
  5327. DestFullName = TargetDir + DestFileName;
  5328. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  5329. if (ResumeAllowed)
  5330. {
  5331. if (FileExists(ApiPath(DestPartialFullName)))
  5332. {
  5333. FILE_OPERATION_LOOP_BEGIN
  5334. {
  5335. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestPartialFullName)));
  5336. }
  5337. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestPartialFullName)));
  5338. }
  5339. LocalFileName = DestPartialFullName;
  5340. }
  5341. else
  5342. {
  5343. LocalFileName = DestFullName;
  5344. }
  5345. }
  5346. if (OverwriteMode == omOverwrite)
  5347. {
  5348. // is NULL when overwriting read-only file
  5349. if (LocalHandle)
  5350. {
  5351. CloseHandle(LocalHandle);
  5352. LocalHandle = NULL;
  5353. }
  5354. }
  5355. else
  5356. {
  5357. // is NULL when overwriting read-only file, so following will
  5358. // probably fail anyway
  5359. if (LocalHandle == NULL)
  5360. {
  5361. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  5362. NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  5363. }
  5364. ResumeAllowed = false;
  5365. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  5366. if (OverwriteMode == omAppend)
  5367. {
  5368. FTerminal->LogEvent(L"Appending to file.");
  5369. }
  5370. else
  5371. {
  5372. FTerminal->LogEvent(L"Resuming file transfer (append style).");
  5373. DebugAssert(OverwriteMode == omResume);
  5374. OperationProgress->AddResumed(DestFileSize);
  5375. }
  5376. }
  5377. }
  5378. ExpandedDestFullName = ExpandUNCFileName(DestFullName);
  5379. Action.Destination(ExpandedDestFullName);
  5380. // if not already opened (resume, append...), create new empty file
  5381. if (!LocalHandle)
  5382. {
  5383. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress,
  5384. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  5385. {
  5386. THROW_SKIP_FILE_NULL;
  5387. }
  5388. }
  5389. DebugAssert(LocalHandle);
  5390. DeleteLocalFile = true;
  5391. FileStream = new TSafeHandleStream((THandle)LocalHandle);
  5392. // at end of this block queue is discarded
  5393. {
  5394. TSFTPDownloadQueue Queue(this);
  5395. try
  5396. {
  5397. TSFTPPacket DataPacket;
  5398. int QueueLen = int(File->Size / DownloadBlockSize(OperationProgress)) + 1;
  5399. if ((QueueLen > FTerminal->SessionData->SFTPDownloadQueue) ||
  5400. (QueueLen < 0))
  5401. {
  5402. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  5403. }
  5404. if (QueueLen < 1)
  5405. {
  5406. QueueLen = 1;
  5407. }
  5408. Queue.Init(QueueLen, RemoteHandle, OperationProgress->TransferredSize,
  5409. OperationProgress);
  5410. bool Eof = false;
  5411. bool PrevIncomplete = false;
  5412. int GapFillCount = 0;
  5413. int GapCount = 0;
  5414. unsigned long Missing = 0;
  5415. unsigned long DataLen = 0;
  5416. unsigned long BlockSize;
  5417. bool ConvertToken = false;
  5418. while (!Eof)
  5419. {
  5420. if (Missing > 0)
  5421. {
  5422. Queue.InitFillGapRequest(OperationProgress->TransferredSize, Missing,
  5423. &DataPacket);
  5424. GapFillCount++;
  5425. SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
  5426. SSH_FXP_DATA, asEOF);
  5427. }
  5428. else
  5429. {
  5430. Queue.ReceivePacket(&DataPacket, BlockSize);
  5431. }
  5432. if (DataPacket.Type == SSH_FXP_STATUS)
  5433. {
  5434. // must be SSH_FX_EOF, any other status packet would raise exception
  5435. Eof = true;
  5436. // close file right away, before waiting for pending responses
  5437. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  5438. true, true, NULL);
  5439. RemoteHandle = L""; // do not close file again in __finally block
  5440. }
  5441. if (!Eof)
  5442. {
  5443. if ((Missing == 0) && PrevIncomplete)
  5444. {
  5445. // This can happen only if last request returned less bytes
  5446. // than expected, but exactly number of bytes missing to last
  5447. // known file size, but actually EOF was not reached.
  5448. // Can happen only when filesize has changed since directory
  5449. // listing and server returns less bytes than requested and
  5450. // file has some special file size.
  5451. FTerminal->LogEvent(FORMAT(
  5452. L"Received incomplete data packet before end of file, "
  5453. "offset: %s, size: %d, requested: %d",
  5454. (IntToStr(OperationProgress->TransferredSize), int(DataLen),
  5455. int(BlockSize))));
  5456. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  5457. }
  5458. // Buffer for one block of data
  5459. TFileBuffer BlockBuf;
  5460. DataLen = DataPacket.GetCardinal();
  5461. PrevIncomplete = false;
  5462. if (Missing > 0)
  5463. {
  5464. DebugAssert(DataLen <= Missing);
  5465. Missing -= DataLen;
  5466. }
  5467. else if (DataLen < BlockSize)
  5468. {
  5469. if (OperationProgress->TransferredSize + DataLen !=
  5470. OperationProgress->TransferSize)
  5471. {
  5472. // with native text transfer mode (SFTP>=4), do not bother about
  5473. // getting less than requested, read offset is ignored anyway
  5474. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  5475. {
  5476. GapCount++;
  5477. Missing = BlockSize - DataLen;
  5478. }
  5479. }
  5480. else
  5481. {
  5482. PrevIncomplete = true;
  5483. }
  5484. }
  5485. DebugAssert(DataLen <= BlockSize);
  5486. BlockBuf.Insert(0, reinterpret_cast<const char *>(DataPacket.GetNextData(DataLen)), DataLen);
  5487. DataPacket.DataConsumed(DataLen);
  5488. OperationProgress->AddTransferred(DataLen);
  5489. if ((FVersion >= 6) && DataPacket.CanGetBool() && (Missing == 0))
  5490. {
  5491. Eof = DataPacket.GetBool();
  5492. }
  5493. if (OperationProgress->AsciiTransfer)
  5494. {
  5495. DebugAssert(!ResumeTransfer && !ResumeAllowed);
  5496. unsigned int PrevBlockSize = BlockBuf.Size;
  5497. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0, ConvertToken);
  5498. OperationProgress->SetLocalSize(
  5499. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  5500. }
  5501. FILE_OPERATION_LOOP_BEGIN
  5502. {
  5503. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  5504. }
  5505. FILE_OPERATION_LOOP_END(FMTLOAD(WRITE_ERROR, (LocalFileName)));
  5506. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  5507. }
  5508. if (OperationProgress->Cancel != csContinue)
  5509. {
  5510. if (OperationProgress->ClearCancelFile())
  5511. {
  5512. THROW_SKIP_FILE_NULL;
  5513. }
  5514. else
  5515. {
  5516. Abort();
  5517. }
  5518. }
  5519. };
  5520. if (GapCount > 0)
  5521. {
  5522. FTerminal->LogEvent(FORMAT(
  5523. L"%d requests to fill %d data gaps were issued.",
  5524. (GapFillCount, GapCount)));
  5525. }
  5526. }
  5527. __finally
  5528. {
  5529. Queue.DisposeSafe();
  5530. }
  5531. // queue is discarded here
  5532. }
  5533. if (CopyParam->PreserveTime)
  5534. {
  5535. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  5536. (StandardTimestamp(Modification))));
  5537. SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
  5538. }
  5539. CloseHandle(LocalHandle);
  5540. LocalHandle = NULL;
  5541. if (ResumeAllowed)
  5542. {
  5543. FILE_OPERATION_LOOP_BEGIN
  5544. {
  5545. if (FileExists(ApiPath(DestFullName)))
  5546. {
  5547. DeleteFileChecked(DestFullName);
  5548. }
  5549. THROWOSIFFALSE(Sysutils::RenameFile(DestPartialFullName, DestFullName));
  5550. }
  5551. FILE_OPERATION_LOOP_END(
  5552. FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  5553. (ExtractFileName(DestPartialFullName), DestFileName)));
  5554. }
  5555. DeleteLocalFile = false;
  5556. if (Attrs == -1)
  5557. {
  5558. Attrs = faArchive;
  5559. }
  5560. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  5561. if ((NewAttrs & Attrs) != NewAttrs)
  5562. {
  5563. FILE_OPERATION_LOOP_BEGIN
  5564. {
  5565. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  5566. }
  5567. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  5568. }
  5569. }
  5570. __finally
  5571. {
  5572. if (LocalHandle) CloseHandle(LocalHandle);
  5573. if (FileStream) delete FileStream;
  5574. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocallyUsed == 0) &&
  5575. (OverwriteMode == omOverwrite))
  5576. {
  5577. FILE_OPERATION_LOOP_BEGIN
  5578. {
  5579. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(LocalFileName)));
  5580. }
  5581. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (LocalFileName)));
  5582. }
  5583. // if the transfer was finished, the file is closed already
  5584. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  5585. {
  5586. // do not wait for response
  5587. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  5588. true, true, NULL);
  5589. }
  5590. }
  5591. FTerminal->LogFileDone(OperationProgress, ExpandedDestFullName);
  5592. }
  5593. if (Params & cpDelete)
  5594. {
  5595. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  5596. ChildError = true;
  5597. // If file is directory, do not delete it recursively, because it should be
  5598. // empty already. If not, it should not be deleted (some files were
  5599. // skipped or some new files were copied to it, while we were downloading)
  5600. int Params = dfNoRecursive;
  5601. FTerminal->DeleteFile(FileName, File, &Params);
  5602. ChildError = false;
  5603. }
  5604. }
  5605. //---------------------------------------------------------------------------
  5606. void __fastcall TSFTPFileSystem::SFTPSinkFile(UnicodeString FileName,
  5607. const TRemoteFile * File, void * Param)
  5608. {
  5609. TSinkFileParams * Params = (TSinkFileParams *)Param;
  5610. DebugAssert(Params->OperationProgress);
  5611. try
  5612. {
  5613. SFTPSinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  5614. Params->Params, Params->OperationProgress, Params->Flags);
  5615. }
  5616. catch(EScpSkipFile & E)
  5617. {
  5618. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  5619. Params->Skipped = true;
  5620. {
  5621. TSuspendFileOperationProgress Suspend(OperationProgress);
  5622. if (!FTerminal->HandleException(&E))
  5623. {
  5624. throw;
  5625. }
  5626. }
  5627. if (OperationProgress->Cancel)
  5628. {
  5629. Abort();
  5630. }
  5631. }
  5632. }
  5633. //---------------------------------------------------------------------------
  5634. void __fastcall TSFTPFileSystem::RegisterChecksumAlg(const UnicodeString & Alg, const UnicodeString & SftpAlg)
  5635. {
  5636. FChecksumAlgs->Add(Alg);
  5637. FChecksumSftpAlgs->Add(SftpAlg);
  5638. }
  5639. //---------------------------------------------------------------------------
  5640. void __fastcall TSFTPFileSystem::GetSupportedChecksumAlgs(TStrings * Algs)
  5641. {
  5642. Algs->AddStrings(FChecksumAlgs.get());
  5643. }
  5644. //---------------------------------------------------------------------------
  5645. void __fastcall TSFTPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  5646. {
  5647. DebugFail();
  5648. }
  5649. //---------------------------------------------------------------------------
  5650. void __fastcall TSFTPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  5651. {
  5652. DebugFail();
  5653. }
  5654. //---------------------------------------------------------------------------
  5655. void __fastcall TSFTPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
  5656. {
  5657. // noop
  5658. }