SftpFileSystem.cpp 182 KB

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