SftpFileSystem.cpp 179 KB

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