SftpFileSystem.cpp 178 KB

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