SftpFileSystem.cpp 191 KB

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