SftpFileSystem.cpp 182 KB

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