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