SftpFileSystem.cpp 182 KB

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