1
0

SftpFileSystem.cpp 186 KB

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