SftpFileSystem.cpp 150 KB

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