SftpFileSystem.cpp 183 KB

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