SftpFileSystem.cpp 185 KB

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