SftpFileSystem.cpp 167 KB

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