SftpFileSystem.cpp 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083
  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 | cpRemoveBOM);
  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. Result = OperationProgress->AdjustToCPSLimit(Result);
  1710. return Result;
  1711. }
  1712. //---------------------------------------------------------------------------
  1713. unsigned long __fastcall TSFTPFileSystem::UploadBlockSize(const AnsiString & Handle,
  1714. TFileOperationProgressType * OperationProgress)
  1715. {
  1716. // handle length + offset + data size
  1717. const unsigned long UploadPacketOverhead =
  1718. sizeof(unsigned long) + sizeof(__int64) + sizeof(unsigned long);
  1719. return TransferBlockSize(UploadPacketOverhead + Handle.Length(), OperationProgress);
  1720. }
  1721. //---------------------------------------------------------------------------
  1722. unsigned long __fastcall TSFTPFileSystem::DownloadBlockSize(
  1723. TFileOperationProgressType * OperationProgress)
  1724. {
  1725. unsigned long Result = TransferBlockSize(sizeof(unsigned long), OperationProgress);
  1726. if (FSupport->Loaded && (FSupport->MaxReadSize > 0) &&
  1727. (Result > FSupport->MaxReadSize))
  1728. {
  1729. Result = FSupport->MaxReadSize;
  1730. }
  1731. return Result;
  1732. }
  1733. //---------------------------------------------------------------------------
  1734. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  1735. {
  1736. BusyStart();
  1737. try
  1738. {
  1739. if (FTerminal->Log->Logging)
  1740. {
  1741. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1742. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1743. (Packet->Type != FPreviousLoggedPacket) ||
  1744. (FTerminal->Configuration->LogProtocol >= 1))
  1745. {
  1746. if (FNotLoggedPackets)
  1747. {
  1748. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1749. (FNotLoggedPackets)));
  1750. FNotLoggedPackets = 0;
  1751. }
  1752. FTerminal->Log->Add(llInput, FORMAT("Type: %s, Size: %d, Number: %d",
  1753. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1754. if (FTerminal->Configuration->LogProtocol >= 2)
  1755. {
  1756. FTerminal->Log->Add(llInput, Packet->Dump());
  1757. }
  1758. FPreviousLoggedPacket = Packet->Type;
  1759. }
  1760. else
  1761. {
  1762. FNotLoggedPackets++;
  1763. }
  1764. }
  1765. FSecureShell->Send(Packet->SendData, Packet->SendLength);
  1766. }
  1767. __finally
  1768. {
  1769. BusyEnd();
  1770. }
  1771. }
  1772. //---------------------------------------------------------------------------
  1773. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
  1774. int AllowStatus)
  1775. {
  1776. unsigned long Code = Packet->GetCardinal();
  1777. static int Messages[] = {
  1778. SFTP_STATUS_OK,
  1779. SFTP_STATUS_EOF,
  1780. SFTP_STATUS_NO_SUCH_FILE,
  1781. SFTP_STATUS_PERMISSION_DENIED,
  1782. SFTP_STATUS_FAILURE,
  1783. SFTP_STATUS_BAD_MESSAGE,
  1784. SFTP_STATUS_NO_CONNECTION,
  1785. SFTP_STATUS_CONNECTION_LOST,
  1786. SFTP_STATUS_OP_UNSUPPORTED,
  1787. SFTP_STATUS_INVALID_HANDLE,
  1788. SFTP_STATUS_NO_SUCH_PATH,
  1789. SFTP_STATUS_FILE_ALREADY_EXISTS,
  1790. SFTP_STATUS_WRITE_PROTECT,
  1791. SFTP_STATUS_NO_MEDIA,
  1792. SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
  1793. SFTP_STATUS_QUOTA_EXCEEDED,
  1794. SFTP_STATUS_UNKNOWN_PRINCIPAL,
  1795. SFTP_STATUS_LOCK_CONFLICT,
  1796. SFTP_STATUS_DIR_NOT_EMPTY,
  1797. SFTP_STATUS_NOT_A_DIRECTORY,
  1798. SFTP_STATUS_INVALID_FILENAME,
  1799. SFTP_STATUS_LINK_LOOP,
  1800. SFTP_STATUS_CANNOT_DELETE,
  1801. SFTP_STATUS_INVALID_PARAMETER,
  1802. SFTP_STATUS_FILE_IS_A_DIRECTORY,
  1803. SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT,
  1804. SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED,
  1805. SFTP_STATUS_DELETE_PENDING,
  1806. SFTP_STATUS_FILE_CORRUPT
  1807. };
  1808. int Message;
  1809. if ((AllowStatus & (0x01 << Code)) == 0)
  1810. {
  1811. if (Code >= LENOF(Messages))
  1812. {
  1813. Message = SFTP_STATUS_UNKNOWN;
  1814. }
  1815. else
  1816. {
  1817. Message = Messages[Code];
  1818. }
  1819. AnsiString MessageStr = LoadStr(Message);
  1820. AnsiString ServerMessage;
  1821. AnsiString LanguageTag;
  1822. if (FVersion >= 3)
  1823. {
  1824. // message is in UTF only since SFTP specification 01 (specification 00
  1825. // is also version 3)
  1826. // (in other words, always use UTF unless server is know to be buggy)
  1827. ServerMessage = Packet->GetString(!FUtfNever);
  1828. LanguageTag = Packet->GetString();
  1829. if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPAL))
  1830. {
  1831. AnsiString Principals;
  1832. while (Packet->GetNextData() != NULL)
  1833. {
  1834. if (!Principals.IsEmpty())
  1835. {
  1836. Principals += ", ";
  1837. }
  1838. Principals += Packet->GetString();
  1839. }
  1840. MessageStr = FORMAT(MessageStr, (Principals));
  1841. }
  1842. }
  1843. else
  1844. {
  1845. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  1846. }
  1847. if (FTerminal->Log->Logging)
  1848. {
  1849. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d, Message: %d, Server: %s, Language: %s ",
  1850. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  1851. }
  1852. if (!LanguageTag.IsEmpty())
  1853. {
  1854. LanguageTag = FORMAT(" (%s)", (LanguageTag));
  1855. }
  1856. AnsiString Error = FMTLOAD(SFTP_ERROR_FORMAT2, (MessageStr,
  1857. int(Code), LanguageTag, ServerMessage, int(Packet->RequestType)));
  1858. FTerminal->TerminalError(NULL, Error);
  1859. return 0;
  1860. }
  1861. else
  1862. {
  1863. if (!FNotLoggedPackets || Code)
  1864. {
  1865. FTerminal->Log->Add(llOutput, FORMAT("Status/error code: %d", ((int)Code)));
  1866. }
  1867. return Code;
  1868. }
  1869. }
  1870. //---------------------------------------------------------------------------
  1871. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  1872. {
  1873. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  1874. {
  1875. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  1876. }
  1877. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  1878. if (Packet)
  1879. {
  1880. assert(Packet->ReservedBy == this);
  1881. Packet->ReservedBy = NULL;
  1882. }
  1883. FPacketReservations->Delete(Reservation);
  1884. }
  1885. //---------------------------------------------------------------------------
  1886. inline int __fastcall TSFTPFileSystem::PacketLength(char * LenBuf, int ExpectedType)
  1887. {
  1888. int Length = GET_32BIT(LenBuf);
  1889. if (Length > SFTP_MAX_PACKET_LEN)
  1890. {
  1891. AnsiString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  1892. int(Length), SFTP_MAX_PACKET_LEN));
  1893. if (ExpectedType == SSH_FXP_VERSION)
  1894. {
  1895. AnsiString LenString(LenBuf, 4);
  1896. if (!IsDisplayableStr(LenString))
  1897. {
  1898. LenString = "0x" + StrToHex(LenString);
  1899. }
  1900. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  1901. (Message, LenString));
  1902. }
  1903. FTerminal->FatalError(NULL, Message);
  1904. }
  1905. return Length;
  1906. }
  1907. //---------------------------------------------------------------------------
  1908. bool __fastcall TSFTPFileSystem::PeekPacket()
  1909. {
  1910. bool Result;
  1911. char * Buf;
  1912. Result = FSecureShell->Peek(Buf, 4);
  1913. if (Result)
  1914. {
  1915. int Length = PacketLength(Buf, -1);
  1916. Result = FSecureShell->Peek(Buf, 4 + Length);
  1917. }
  1918. return Result;
  1919. }
  1920. //---------------------------------------------------------------------------
  1921. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  1922. int ExpectedType, int AllowStatus)
  1923. {
  1924. TSFTPBusy Busy(this);
  1925. int Result = SSH_FX_OK;
  1926. int Reservation = FPacketReservations->IndexOf(Packet);
  1927. if (Reservation < 0 || Packet->Capacity == 0)
  1928. {
  1929. bool IsReserved;
  1930. do
  1931. {
  1932. IsReserved = false;
  1933. assert(Packet);
  1934. char LenBuf[4];
  1935. FSecureShell->Receive(LenBuf, sizeof(LenBuf));
  1936. int Length = PacketLength(LenBuf, ExpectedType);
  1937. Packet->Capacity = Length;
  1938. FSecureShell->Receive(Packet->Data, Length);
  1939. Packet->DataUpdated(Length);
  1940. if (FTerminal->Log->Logging)
  1941. {
  1942. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  1943. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  1944. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA) ||
  1945. (FTerminal->Configuration->LogProtocol >= 1))
  1946. {
  1947. if (FNotLoggedPackets)
  1948. {
  1949. FTerminal->LogEvent(FORMAT("%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  1950. (FNotLoggedPackets)));
  1951. FNotLoggedPackets = 0;
  1952. }
  1953. FTerminal->Log->Add(llOutput, FORMAT("Type: %s, Size: %d, Number: %d",
  1954. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  1955. if (FTerminal->Configuration->LogProtocol >= 2)
  1956. {
  1957. FTerminal->Log->Add(llOutput, Packet->Dump());
  1958. }
  1959. }
  1960. else
  1961. {
  1962. FNotLoggedPackets++;
  1963. }
  1964. }
  1965. if (Reservation < 0 ||
  1966. Packet->MessageNumber != (unsigned long)FPacketNumbers.GetElement(Reservation))
  1967. {
  1968. TSFTPPacket * ReservedPacket;
  1969. unsigned long MessageNumber;
  1970. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  1971. {
  1972. MessageNumber = FPacketNumbers.GetElement(Index);
  1973. if (MessageNumber == Packet->MessageNumber)
  1974. {
  1975. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  1976. IsReserved = true;
  1977. if (ReservedPacket)
  1978. {
  1979. FTerminal->LogEvent("Storing reserved response");
  1980. *ReservedPacket = *Packet;
  1981. }
  1982. else
  1983. {
  1984. FTerminal->LogEvent("Discarding reserved response");
  1985. RemoveReservation(Index);
  1986. if ((Reservation >= 0) && (Reservation > Index))
  1987. {
  1988. Reservation--;
  1989. assert(Reservation == FPacketReservations->IndexOf(Packet));
  1990. }
  1991. }
  1992. break;
  1993. }
  1994. }
  1995. }
  1996. }
  1997. while (IsReserved);
  1998. }
  1999. // before we removed the reservation after check for packet type,
  2000. // but if it raises exception, removal is unnecessarily
  2001. // postponed until the packet is removed
  2002. // (and it have not worked anyway until recent fix to UnreserveResponse)
  2003. if (Reservation >= 0)
  2004. {
  2005. assert(Packet->MessageNumber == (unsigned long)FPacketNumbers.GetElement(Reservation));
  2006. RemoveReservation(Reservation);
  2007. }
  2008. if (ExpectedType >= 0)
  2009. {
  2010. if (Packet->Type == SSH_FXP_STATUS)
  2011. {
  2012. if (AllowStatus < 0)
  2013. {
  2014. AllowStatus = (ExpectedType == SSH_FXP_STATUS ? asOK : asNo);
  2015. }
  2016. Result = GotStatusPacket(Packet, AllowStatus);
  2017. }
  2018. else if (ExpectedType != Packet->Type)
  2019. {
  2020. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  2021. }
  2022. }
  2023. return Result;
  2024. }
  2025. //---------------------------------------------------------------------------
  2026. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  2027. TSFTPPacket * Response)
  2028. {
  2029. if (Response != NULL)
  2030. {
  2031. assert(FPacketReservations->IndexOf(Response) < 0);
  2032. // mark response as not received yet
  2033. Response->Capacity = 0;
  2034. Response->ReservedBy = this;
  2035. }
  2036. FPacketReservations->Add(Response);
  2037. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  2038. {
  2039. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  2040. }
  2041. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  2042. }
  2043. //---------------------------------------------------------------------------
  2044. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  2045. {
  2046. int Reservation = FPacketReservations->IndexOf(Response);
  2047. if (Response->Capacity != 0)
  2048. {
  2049. // added check for already received packet
  2050. // (it happens when the reserved response is received out of order,
  2051. // unexpectedly soon, and then receivepacket() on the packet
  2052. // is not actually called, due to exception)
  2053. RemoveReservation(Reservation);
  2054. }
  2055. else
  2056. {
  2057. if (Reservation >= 0)
  2058. {
  2059. // we probably do not remove the item at all, because
  2060. // we must remember that the respose was expected, so we skip it
  2061. // in receivepacket()
  2062. FPacketReservations->Items[Reservation] = NULL;
  2063. }
  2064. }
  2065. }
  2066. //---------------------------------------------------------------------------
  2067. int __fastcall TSFTPFileSystem::ReceiveResponse(
  2068. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2069. int AllowStatus)
  2070. {
  2071. int Result;
  2072. unsigned int MessageNumber = Packet->MessageNumber;
  2073. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  2074. try
  2075. {
  2076. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus);
  2077. if (MessageNumber != AResponse->MessageNumber)
  2078. {
  2079. FTerminal->FatalError(NULL, FMTLOAD(SFTP_MESSAGE_NUMBER,
  2080. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  2081. }
  2082. }
  2083. __finally
  2084. {
  2085. if (!Response) delete AResponse;
  2086. }
  2087. return Result;
  2088. }
  2089. //---------------------------------------------------------------------------
  2090. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  2091. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2092. int AllowStatus)
  2093. {
  2094. int Result;
  2095. TSFTPBusy Busy(this);
  2096. SendPacket(Packet);
  2097. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  2098. return Result;
  2099. }
  2100. //---------------------------------------------------------------------------
  2101. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path)
  2102. {
  2103. try
  2104. {
  2105. FTerminal->LogEvent(FORMAT("Getting real path for '%s'",
  2106. (Path)));
  2107. TSFTPPacket Packet(SSH_FXP_REALPATH);
  2108. Packet.AddPathString(Path, FUtfStrings);
  2109. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  2110. if (Packet.GetCardinal() != 1)
  2111. {
  2112. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2113. }
  2114. AnsiString RealDir = Packet.GetPathString(FUtfStrings);
  2115. // ignore rest of SSH_FXP_NAME packet
  2116. FTerminal->LogEvent(FORMAT("Real path is '%s'", (RealDir)));
  2117. return RealDir;
  2118. }
  2119. catch(Exception & E)
  2120. {
  2121. if (FTerminal->Active)
  2122. {
  2123. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  2124. }
  2125. else
  2126. {
  2127. throw;
  2128. }
  2129. }
  2130. }
  2131. //---------------------------------------------------------------------------
  2132. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path,
  2133. const AnsiString BaseDir)
  2134. {
  2135. AnsiString APath;
  2136. if (TTerminal::IsAbsolutePath(Path))
  2137. {
  2138. APath = Path;
  2139. }
  2140. else
  2141. {
  2142. if (!Path.IsEmpty())
  2143. {
  2144. // this condition/block was outside (before) current block
  2145. // but it dod not work when Path was empty
  2146. if (!BaseDir.IsEmpty())
  2147. {
  2148. APath = UnixIncludeTrailingBackslash(BaseDir);
  2149. }
  2150. APath = APath + Path;
  2151. }
  2152. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(".");
  2153. }
  2154. return RealPath(APath);
  2155. }
  2156. //---------------------------------------------------------------------------
  2157. AnsiString __fastcall TSFTPFileSystem::LocalCanonify(const AnsiString & Path)
  2158. {
  2159. // TODO: improve (handle .. etc.)
  2160. if (TTerminal::IsAbsolutePath(Path) ||
  2161. (!FCurrentDirectory.IsEmpty() && UnixComparePaths(FCurrentDirectory, Path)))
  2162. {
  2163. return Path;
  2164. }
  2165. else
  2166. {
  2167. return ::AbsolutePath(FCurrentDirectory, Path);
  2168. }
  2169. }
  2170. //---------------------------------------------------------------------------
  2171. AnsiString __fastcall TSFTPFileSystem::Canonify(AnsiString Path)
  2172. {
  2173. // inspired by canonify() from PSFTP.C
  2174. AnsiString Result;
  2175. FTerminal->LogEvent(FORMAT("Canonifying: \"%s\"", (Path)));
  2176. Path = LocalCanonify(Path);
  2177. bool TryParent = false;
  2178. try
  2179. {
  2180. Result = RealPath(Path);
  2181. }
  2182. catch(...)
  2183. {
  2184. if (FTerminal->Active)
  2185. {
  2186. TryParent = true;
  2187. }
  2188. else
  2189. {
  2190. throw;
  2191. }
  2192. }
  2193. if (TryParent)
  2194. {
  2195. AnsiString APath = UnixExcludeTrailingBackslash(Path);
  2196. AnsiString Name = UnixExtractFileName(APath);
  2197. if (Name == "." || Name == "..")
  2198. {
  2199. Result = Path;
  2200. }
  2201. else
  2202. {
  2203. AnsiString FPath = UnixExtractFilePath(APath);
  2204. try
  2205. {
  2206. Result = RealPath(FPath);
  2207. Result = UnixIncludeTrailingBackslash(Result) + Name;
  2208. }
  2209. catch(...)
  2210. {
  2211. if (FTerminal->Active)
  2212. {
  2213. Result = Path;
  2214. }
  2215. else
  2216. {
  2217. throw;
  2218. }
  2219. }
  2220. }
  2221. }
  2222. FTerminal->LogEvent(FORMAT("Canonified: \"%s\"", (Result)));
  2223. return Result;
  2224. }
  2225. //---------------------------------------------------------------------------
  2226. AnsiString __fastcall TSFTPFileSystem::AbsolutePath(AnsiString Path)
  2227. {
  2228. return RealPath(Path, CurrentDirectory);
  2229. }
  2230. //---------------------------------------------------------------------------
  2231. AnsiString __fastcall TSFTPFileSystem::GetHomeDirectory()
  2232. {
  2233. if (FHomeDirectory.IsEmpty())
  2234. {
  2235. FHomeDirectory = RealPath(".");
  2236. }
  2237. return FHomeDirectory;
  2238. }
  2239. //---------------------------------------------------------------------------
  2240. void __fastcall TSFTPFileSystem::LoadFile(TRemoteFile * File, TSFTPPacket * Packet,
  2241. bool Complete)
  2242. {
  2243. Packet->GetFile(File, FVersion, FTerminal->SessionData->DSTMode,
  2244. FUtfStrings, FSignedTS, Complete);
  2245. }
  2246. //---------------------------------------------------------------------------
  2247. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  2248. TRemoteFile * ALinkedByFile, const AnsiString FileName,
  2249. TRemoteFileList * TempFileList, bool Complete)
  2250. {
  2251. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  2252. try
  2253. {
  2254. File->Terminal = FTerminal;
  2255. if (!FileName.IsEmpty())
  2256. {
  2257. File->FileName = FileName;
  2258. }
  2259. // to get full path for symlink completion
  2260. File->Directory = TempFileList;
  2261. LoadFile(File, Packet, Complete);
  2262. File->Directory = NULL;
  2263. }
  2264. catch(...)
  2265. {
  2266. delete File;
  2267. throw;
  2268. }
  2269. return File;
  2270. }
  2271. //---------------------------------------------------------------------------
  2272. AnsiString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  2273. {
  2274. return FCurrentDirectory;
  2275. }
  2276. //---------------------------------------------------------------------------
  2277. void __fastcall TSFTPFileSystem::DoStartup()
  2278. {
  2279. FFileSystemInfoValid = false;
  2280. TSFTPPacket Packet(SSH_FXP_INIT);
  2281. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  2282. if (MaxVersion > SFTPMaxVersion)
  2283. {
  2284. MaxVersion = SFTPMaxVersion;
  2285. }
  2286. Packet.AddCardinal(MaxVersion);
  2287. try
  2288. {
  2289. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  2290. }
  2291. catch(Exception &E)
  2292. {
  2293. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR));
  2294. }
  2295. FVersion = Packet.GetCardinal();
  2296. FTerminal->LogEvent(FORMAT("SFTP version %d negotiated.", (FVersion)));
  2297. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  2298. {
  2299. FTerminal->FatalError(NULL, FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  2300. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  2301. }
  2302. FExtensions->Clear();
  2303. FEOL = "\r\n";
  2304. FSupport->Loaded = false;
  2305. SAFE_DESTROY(FFixedPaths);
  2306. if (FVersion >= 3)
  2307. {
  2308. AnsiString ExtensionName;
  2309. AnsiString ExtensionData;
  2310. AnsiString ExtensionDisplayData;
  2311. while (Packet.GetNextData() != NULL)
  2312. {
  2313. ExtensionName = Packet.GetString();
  2314. ExtensionData = Packet.GetString();
  2315. if (IsDisplayableStr(ExtensionData))
  2316. {
  2317. ExtensionDisplayData = ExtensionData;
  2318. }
  2319. else
  2320. {
  2321. ExtensionDisplayData = "0x" + StrToHex(ExtensionData);
  2322. }
  2323. if (ExtensionName == SFTP_EXT_NEWLINE)
  2324. {
  2325. FEOL = ExtensionData;
  2326. FTerminal->LogEvent(FORMAT("Server requests EOL sequence %s.",
  2327. (ExtensionDisplayData)));
  2328. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2329. {
  2330. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2331. }
  2332. }
  2333. // do not allow "supported" to override "supported2" if both are received
  2334. else if (((ExtensionName == SFTP_EXT_SUPPORTED) && !FSupport->Loaded) ||
  2335. (ExtensionName == SFTP_EXT_SUPPORTED2))
  2336. {
  2337. FSupport->Reset();
  2338. TSFTPPacket SupportedStruct(ExtensionData);
  2339. FSupport->Loaded = true;
  2340. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2341. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2342. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2343. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2344. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2345. if (ExtensionName == SFTP_EXT_SUPPORTED)
  2346. {
  2347. while (SupportedStruct.GetNextData() != NULL)
  2348. {
  2349. FSupport->Extensions->Add(SupportedStruct.GetString());
  2350. }
  2351. }
  2352. else
  2353. {
  2354. FSupport->OpenBlockMasks = SupportedStruct.GetSmallCardinal();
  2355. FSupport->BlockMasks = SupportedStruct.GetSmallCardinal();
  2356. unsigned int ExtensionCount;
  2357. ExtensionCount = SupportedStruct.GetCardinal();
  2358. for (unsigned int i = 0; i < ExtensionCount; i++)
  2359. {
  2360. FSupport->AttribExtensions->Add(SupportedStruct.GetString());
  2361. }
  2362. ExtensionCount = SupportedStruct.GetCardinal();
  2363. for (unsigned int i = 0; i < ExtensionCount; i++)
  2364. {
  2365. FSupport->Extensions->Add(SupportedStruct.GetString());
  2366. }
  2367. }
  2368. if (FTerminal->Log->Logging)
  2369. {
  2370. FTerminal->LogEvent(FORMAT(
  2371. "Server support information:\n"
  2372. " Attribute mask: %x, Attribute bits: %x, Open flags: %x\n"
  2373. " Access mask: %x, Open block masks: %x, Block masks: %x, Max read size: %d\n",
  2374. (int(FSupport->AttributeMask),
  2375. int(FSupport->AttributeBits),
  2376. int(FSupport->OpenFlags),
  2377. int(FSupport->AccessMask),
  2378. int(FSupport->OpenBlockMasks),
  2379. int(FSupport->BlockMasks),
  2380. int(FSupport->MaxReadSize))));
  2381. FTerminal->LogEvent(FORMAT( " Attribute extensions (%d)\n", (FSupport->AttribExtensions->Count)));
  2382. for (int Index = 0; Index < FSupport->AttribExtensions->Count; Index++)
  2383. {
  2384. FTerminal->LogEvent(
  2385. FORMAT(" %s", (FSupport->AttribExtensions->Strings[Index])));
  2386. }
  2387. FTerminal->LogEvent(FORMAT( " Extensions (%d)\n", (FSupport->Extensions->Count)));
  2388. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2389. {
  2390. FTerminal->LogEvent(
  2391. FORMAT(" %s", (FSupport->Extensions->Strings[Index])));
  2392. }
  2393. }
  2394. }
  2395. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2396. {
  2397. TSFTPPacket VendorIdStruct(ExtensionData);
  2398. AnsiString VendorName(VendorIdStruct.GetString());
  2399. AnsiString ProductName(VendorIdStruct.GetString());
  2400. AnsiString ProductVersion(VendorIdStruct.GetString());
  2401. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2402. FTerminal->LogEvent(FORMAT("Server software: %s %s (%d) by %s",
  2403. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2404. }
  2405. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2406. {
  2407. FTerminal->LogEvent("File system roots:\n");
  2408. assert(FFixedPaths == NULL);
  2409. FFixedPaths = new TStringList();
  2410. try
  2411. {
  2412. TSFTPPacket RootsPacket(ExtensionData);
  2413. while (RootsPacket.GetNextData() != NULL)
  2414. {
  2415. unsigned long Dummy = RootsPacket.GetCardinal();
  2416. if (Dummy != 1)
  2417. {
  2418. break;
  2419. }
  2420. else
  2421. {
  2422. char Drive = RootsPacket.GetByte();
  2423. char MaybeType = RootsPacket.GetByte();
  2424. FTerminal->LogEvent(FORMAT(" %s: (type %d)", (Drive, (int)MaybeType)));
  2425. FFixedPaths->Add(FORMAT("%s:", (Drive)));
  2426. }
  2427. }
  2428. }
  2429. catch(Exception & E)
  2430. {
  2431. FFixedPaths->Clear();
  2432. FTerminal->LogEvent(FORMAT("Failed to decode %s extension",
  2433. (SFTP_EXT_FSROOTS)));
  2434. FTerminal->HandleException(&E);
  2435. }
  2436. }
  2437. else if (ExtensionName == SFTP_EXT_VERSIONS)
  2438. {
  2439. try
  2440. {
  2441. // first try legacy decoding according to incorrect encoding
  2442. // (structure-like) as of VShell.
  2443. TSFTPPacket VersionsPacket(ExtensionData);
  2444. AnsiString Versions = VersionsPacket.GetString();
  2445. if (VersionsPacket.GetNextData() != NULL)
  2446. {
  2447. Abort();
  2448. }
  2449. FTerminal->LogEvent(FORMAT("SFTP versions supported by the server (VShell format): %s",
  2450. (Versions)));
  2451. }
  2452. catch(...)
  2453. {
  2454. // if that fails, fallback to proper decoding
  2455. FTerminal->LogEvent(FORMAT("SFTP versions supported by the server: %s",
  2456. (ExtensionData)));
  2457. }
  2458. }
  2459. else
  2460. {
  2461. FTerminal->LogEvent(FORMAT("Unknown server extension %s=%s",
  2462. (ExtensionName, ExtensionDisplayData)));
  2463. }
  2464. FExtensions->Values[ExtensionName] = ExtensionData;
  2465. }
  2466. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  2467. {
  2468. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  2469. Packet.AddString(SFTP_EXT_VENDOR_ID);
  2470. Packet.AddString(FTerminal->Configuration->CompanyName);
  2471. Packet.AddString(FTerminal->Configuration->ProductName);
  2472. Packet.AddString(FTerminal->Configuration->ProductVersion);
  2473. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  2474. SendPacket(&Packet);
  2475. // we are not interested in the response, do not wait for it
  2476. ReserveResponse(&Packet, NULL);
  2477. }
  2478. }
  2479. if (FVersion < 4)
  2480. {
  2481. // currently enable the bug for all servers (really known on OpenSSH)
  2482. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  2483. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  2484. if (FSignedTS)
  2485. {
  2486. FTerminal->LogEvent("We believe the server has signed timestamps bug");
  2487. }
  2488. }
  2489. else
  2490. {
  2491. FSignedTS = false;
  2492. }
  2493. // use UTF when forced or ...
  2494. // when "auto" and version is at least 4 and the server is not know not to use UTF
  2495. FUtfNever = (GetSessionInfo().SshImplementation.Pos("Foxit-WAC-Server") == 1) ||
  2496. (FTerminal->SessionData->Utf == asOn);
  2497. FUtfStrings =
  2498. (FTerminal->SessionData->Utf == asOff) ||
  2499. ((FTerminal->SessionData->Utf == asAuto) &&
  2500. (FVersion >= 4) && !FUtfNever);
  2501. if (FUtfStrings)
  2502. {
  2503. FTerminal->LogEvent("We will use UTF-8 strings when appropriate");
  2504. }
  2505. else if (FUtfNever)
  2506. {
  2507. FTerminal->LogEvent("We will never use UTF-8 strings");
  2508. }
  2509. else
  2510. {
  2511. FTerminal->LogEvent("We will use UTF-8 strings for status messages only");
  2512. }
  2513. FMaxPacketSize = FTerminal->SessionData->SFTPMaxPacketSize;
  2514. if (FMaxPacketSize == 0)
  2515. {
  2516. if ((GetSessionInfo().SshImplementation.Pos("OpenSSH") == 1) &&
  2517. (FVersion == 3) && !FSupport->Loaded)
  2518. {
  2519. FMaxPacketSize = 4 + (256 * 1024); // len + 256kB payload
  2520. FTerminal->LogEvent(FORMAT("Limiting packet size to OpenSSH sftp-server limit of %d bytes",
  2521. (int(FMaxPacketSize))));
  2522. }
  2523. }
  2524. }
  2525. //---------------------------------------------------------------------------
  2526. char * __fastcall TSFTPFileSystem::GetEOL() const
  2527. {
  2528. if (FVersion >= 4)
  2529. {
  2530. assert(!FEOL.IsEmpty());
  2531. return FEOL.c_str();
  2532. }
  2533. else
  2534. {
  2535. return EOLToStr(FTerminal->SessionData->EOLType);
  2536. }
  2537. }
  2538. //---------------------------------------------------------------------------
  2539. void __fastcall TSFTPFileSystem::LookupUsersGroups()
  2540. {
  2541. assert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
  2542. TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
  2543. TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
  2544. TSFTPPacket * Packet;
  2545. TUsersGroupsList * List;
  2546. TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
  2547. TUsersGroupsList * Lists[] = { FTerminal->FUsers, FTerminal->FGroups };
  2548. char ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
  2549. for (int Index = 0; Index < LENOF(Packets); Index++)
  2550. {
  2551. Packet = Packets[Index];
  2552. Packet->AddString(SFTP_EXT_OWNER_GROUP);
  2553. Packet->AddByte(ListTypes[Index]);
  2554. SendPacket(Packet);
  2555. ReserveResponse(Packet, Packet);
  2556. }
  2557. for (int Index = 0; Index < LENOF(Packets); Index++)
  2558. {
  2559. Packet = Packets[Index];
  2560. ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
  2561. if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
  2562. (Packet->GetString() != SFTP_EXT_OWNER_GROUP_REPLY))
  2563. {
  2564. FTerminal->LogEvent(FORMAT("Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
  2565. }
  2566. else
  2567. {
  2568. List = Lists[Index];
  2569. unsigned long Count = Packet->GetCardinal();
  2570. List->BeginUpdate();
  2571. try
  2572. {
  2573. List->Clear();
  2574. for (unsigned long Item = 0; Item < Count; Item++)
  2575. {
  2576. List->Add(Packet->GetString(!FUtfNever));
  2577. }
  2578. }
  2579. __finally
  2580. {
  2581. List->EndUpdate();
  2582. }
  2583. }
  2584. }
  2585. }
  2586. //---------------------------------------------------------------------------
  2587. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  2588. {
  2589. if (!FDirectoryToChangeTo.IsEmpty())
  2590. {
  2591. FCurrentDirectory = FDirectoryToChangeTo;
  2592. FDirectoryToChangeTo = "";
  2593. }
  2594. else if (FCurrentDirectory.IsEmpty())
  2595. {
  2596. // this happens only after startup when default remote directory is not specified
  2597. FCurrentDirectory = GetHomeDirectory();
  2598. }
  2599. }
  2600. //---------------------------------------------------------------------------
  2601. void __fastcall TSFTPFileSystem::HomeDirectory()
  2602. {
  2603. ChangeDirectory(GetHomeDirectory());
  2604. }
  2605. //---------------------------------------------------------------------------
  2606. void __fastcall TSFTPFileSystem::TryOpenDirectory(const AnsiString Directory)
  2607. {
  2608. FTerminal->LogEvent(FORMAT("Trying to open directory \"%s\".", (Directory)));
  2609. TRemoteFile * File;
  2610. CustomReadFile(Directory, File, SSH_FXP_LSTAT, NULL, asOpUnsupported);
  2611. if (File == NULL)
  2612. {
  2613. // File can be NULL only when server does not support SSH_FXP_LSTAT.
  2614. // Fallback to legacy solution, which in turn does not allow entering
  2615. // traverse-only (chmod 110) directories.
  2616. // This is workaround for http://www.ftpshell.com/
  2617. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2618. Packet.AddPathString(UnixExcludeTrailingBackslash(Directory), FUtfStrings);
  2619. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2620. AnsiString Handle = Packet.GetString();
  2621. Packet.ChangeType(SSH_FXP_CLOSE);
  2622. Packet.AddString(Handle);
  2623. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  2624. }
  2625. else
  2626. {
  2627. delete File;
  2628. }
  2629. }
  2630. //---------------------------------------------------------------------------
  2631. void __fastcall TSFTPFileSystem::AnnounceFileListOperation()
  2632. {
  2633. }
  2634. //---------------------------------------------------------------------------
  2635. void __fastcall TSFTPFileSystem::ChangeDirectory(const AnsiString Directory)
  2636. {
  2637. AnsiString Path, Current;
  2638. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  2639. Path = RealPath(Directory, Current);
  2640. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  2641. // for invalid paths on some systems, like CygWin)
  2642. TryOpenDirectory(Path);
  2643. // if open dir did not fail, directory exists -> success.
  2644. FDirectoryToChangeTo = Path;
  2645. }
  2646. //---------------------------------------------------------------------------
  2647. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  2648. {
  2649. FDirectoryToChangeTo = Directory;
  2650. }
  2651. //---------------------------------------------------------------------------
  2652. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  2653. {
  2654. assert(FileList && !FileList->Directory.IsEmpty());
  2655. AnsiString Directory;
  2656. Directory = UnixExcludeTrailingBackslash(LocalCanonify(FileList->Directory));
  2657. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".", (Directory)));
  2658. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  2659. // old data (e.g. parent directory) when reading fails
  2660. FileList->Clear();
  2661. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2662. AnsiString Handle;
  2663. try
  2664. {
  2665. Packet.AddPathString(Directory, FUtfStrings);
  2666. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2667. Handle = Packet.GetString();
  2668. }
  2669. catch(...)
  2670. {
  2671. if (FTerminal->Active)
  2672. {
  2673. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  2674. }
  2675. throw;
  2676. }
  2677. TSFTPPacket Response;
  2678. try
  2679. {
  2680. bool isEOF = false;
  2681. int Total = 0;
  2682. TRemoteFile * File;
  2683. Packet.ChangeType(SSH_FXP_READDIR);
  2684. Packet.AddString(Handle);
  2685. SendPacket(&Packet);
  2686. do
  2687. {
  2688. ReceiveResponse(&Packet, &Response);
  2689. if (Response.Type == SSH_FXP_NAME)
  2690. {
  2691. TSFTPPacket ListingPacket = Response;
  2692. Packet.ChangeType(SSH_FXP_READDIR);
  2693. Packet.AddString(Handle);
  2694. SendPacket(&Packet);
  2695. ReserveResponse(&Packet, &Response);
  2696. unsigned int Count = ListingPacket.GetCardinal();
  2697. for (unsigned long Index = 0; !isEOF && (Index < Count); Index++)
  2698. {
  2699. File = LoadFile(&ListingPacket, NULL, "", FileList);
  2700. // security fix
  2701. // (LastDelimiter works for MBCS)
  2702. if (((File->FileName.Length() > 2) && IsDots(File->FileName)) ||
  2703. (File->FileName.LastDelimiter("/\\") > 0))
  2704. {
  2705. FTerminal->LogEvent(FORMAT("Ignored suspicious file '%s'", (File->FileName)));
  2706. delete File;
  2707. }
  2708. else
  2709. {
  2710. if (FTerminal->Configuration->LogProtocol >= 1)
  2711. {
  2712. FTerminal->LogEvent(FORMAT("Read file '%s' from listing", (File->FileName)));
  2713. }
  2714. FileList->AddFile(File);
  2715. Total++;
  2716. }
  2717. if (Total % 10 == 0)
  2718. {
  2719. FTerminal->DoReadDirectoryProgress(Total, isEOF);
  2720. if (isEOF)
  2721. {
  2722. FTerminal->DoReadDirectoryProgress(-2, isEOF);
  2723. }
  2724. }
  2725. }
  2726. if (Count == 0)
  2727. {
  2728. FTerminal->LogEvent("Empty directory listing packet. Aborting directory reading.");
  2729. isEOF = true;
  2730. }
  2731. }
  2732. else if (Response.Type == SSH_FXP_STATUS)
  2733. {
  2734. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  2735. }
  2736. else
  2737. {
  2738. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  2739. }
  2740. }
  2741. while (!isEOF);
  2742. if (Total == 0)
  2743. {
  2744. // Empty file list -> probably "permision denied", we
  2745. // at least get link to parent directory ("..")
  2746. try
  2747. {
  2748. FTerminal->ExceptionOnFail = true;
  2749. try
  2750. {
  2751. File = NULL;
  2752. FTerminal->ReadFile(
  2753. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  2754. }
  2755. __finally
  2756. {
  2757. FTerminal->ExceptionOnFail = false;
  2758. }
  2759. }
  2760. catch(Exception &E)
  2761. {
  2762. if (E.InheritsFrom(__classid(EFatal))) throw;
  2763. else File = NULL;
  2764. }
  2765. // on some systems even getting ".." fails, we create dummy ".." instead
  2766. bool Failure = (File == NULL);
  2767. if (Failure)
  2768. {
  2769. File = new TRemoteParentDirectory(FTerminal);
  2770. }
  2771. assert(File && File->IsParentDirectory);
  2772. FileList->AddFile(File);
  2773. if (Failure)
  2774. {
  2775. throw Exception(FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)));
  2776. }
  2777. }
  2778. }
  2779. __finally
  2780. {
  2781. if (FTerminal->Active)
  2782. {
  2783. Packet.ChangeType(SSH_FXP_CLOSE);
  2784. Packet.AddString(Handle);
  2785. SendPacket(&Packet);
  2786. // we are not interested in the response, do not wait for it
  2787. ReserveResponse(&Packet, NULL);
  2788. }
  2789. }
  2790. }
  2791. //---------------------------------------------------------------------------
  2792. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  2793. TRemoteFile *& File)
  2794. {
  2795. assert(SymlinkFile && SymlinkFile->IsSymLink);
  2796. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2797. // need to use full filename when resolving links within subdirectory
  2798. // (i.e. for download)
  2799. AnsiString FileName = LocalCanonify(
  2800. SymlinkFile->Directory != NULL ? SymlinkFile->FullFileName : SymlinkFile->FileName);
  2801. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  2802. ReadLinkPacket.AddPathString(FileName, FUtfStrings);
  2803. SendPacket(&ReadLinkPacket);
  2804. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  2805. // send second request before reading response to first one
  2806. // (performance benefit)
  2807. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  2808. AttrsPacket.AddPathString(FileName, FUtfStrings);
  2809. if (FVersion >= 4)
  2810. {
  2811. AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
  2812. }
  2813. SendPacket(&AttrsPacket);
  2814. ReserveResponse(&AttrsPacket, &AttrsPacket);
  2815. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  2816. if (ReadLinkPacket.GetCardinal() != 1)
  2817. {
  2818. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2819. }
  2820. SymlinkFile->LinkTo = ReadLinkPacket.GetPathString(FUtfStrings);
  2821. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  2822. // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
  2823. File = LoadFile(&AttrsPacket, SymlinkFile,
  2824. UnixExtractFileName(SymlinkFile->LinkTo));
  2825. }
  2826. //---------------------------------------------------------------------------
  2827. void __fastcall TSFTPFileSystem::ReadFile(const AnsiString FileName,
  2828. TRemoteFile *& File)
  2829. {
  2830. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  2831. }
  2832. //---------------------------------------------------------------------------
  2833. bool __fastcall TSFTPFileSystem::RemoteFileExists(const AnsiString FullPath,
  2834. TRemoteFile ** File)
  2835. {
  2836. bool Result;
  2837. try
  2838. {
  2839. TRemoteFile * AFile;
  2840. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, asNoSuchFile);
  2841. Result = (AFile != NULL);
  2842. if (Result)
  2843. {
  2844. if (File)
  2845. {
  2846. *File = AFile;
  2847. }
  2848. else
  2849. {
  2850. delete AFile;
  2851. }
  2852. }
  2853. }
  2854. catch(...)
  2855. {
  2856. if (!FTerminal->Active)
  2857. {
  2858. throw;
  2859. }
  2860. Result = false;
  2861. }
  2862. return Result;
  2863. }
  2864. //---------------------------------------------------------------------------
  2865. void __fastcall TSFTPFileSystem::SendCustomReadFile(TSFTPPacket * Packet,
  2866. TSFTPPacket * Response, const AnsiString FileName, unsigned long Flags)
  2867. {
  2868. if ((Packet->Type == SSH_FXP_STAT) || (Packet->Type == SSH_FXP_LSTAT))
  2869. {
  2870. Packet->AddPathString(LocalCanonify(FileName), FUtfStrings);
  2871. }
  2872. else
  2873. {
  2874. assert(Packet->Type == SSH_FXP_FSTAT);
  2875. // actualy handle, not filename
  2876. Packet->AddString(FileName);
  2877. }
  2878. if (FVersion >= 4)
  2879. {
  2880. Packet->AddCardinal(Flags);
  2881. }
  2882. SendPacket(Packet);
  2883. ReserveResponse(Packet, Response);
  2884. }
  2885. //---------------------------------------------------------------------------
  2886. void __fastcall TSFTPFileSystem::CustomReadFile(const AnsiString FileName,
  2887. TRemoteFile *& File, char Type, TRemoteFile * ALinkedByFile,
  2888. int AllowStatus)
  2889. {
  2890. unsigned long Flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  2891. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  2892. SSH_FILEXFER_ATTR_OWNERGROUP;
  2893. TSFTPPacket Packet(Type);
  2894. SendCustomReadFile(&Packet, &Packet, FileName, Flags);
  2895. ReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS, AllowStatus);
  2896. if (Packet.Type == SSH_FXP_ATTRS)
  2897. {
  2898. File = LoadFile(&Packet, ALinkedByFile, UnixExtractFileName(FileName));
  2899. }
  2900. else
  2901. {
  2902. assert(AllowStatus > 0);
  2903. File = NULL;
  2904. }
  2905. }
  2906. //---------------------------------------------------------------------------
  2907. void __fastcall TSFTPFileSystem::DeleteFile(const AnsiString FileName,
  2908. const TRemoteFile * File, int Params)
  2909. {
  2910. char Type;
  2911. AnsiString RealFileName = LocalCanonify(FileName);
  2912. if (File && File->IsDirectory && !File->IsSymLink)
  2913. {
  2914. if (FLAGCLEAR(Params, dfNoRecursive))
  2915. {
  2916. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Params);
  2917. }
  2918. Type = SSH_FXP_RMDIR;
  2919. }
  2920. else
  2921. {
  2922. Type = SSH_FXP_REMOVE;
  2923. }
  2924. TSFTPPacket Packet(Type);
  2925. Packet.AddPathString(RealFileName, FUtfStrings);
  2926. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2927. }
  2928. //---------------------------------------------------------------------------
  2929. void __fastcall TSFTPFileSystem::RenameFile(const AnsiString FileName,
  2930. const AnsiString NewName)
  2931. {
  2932. TSFTPPacket Packet(SSH_FXP_RENAME);
  2933. AnsiString RealName = LocalCanonify(FileName);
  2934. Packet.AddPathString(RealName, FUtfStrings);
  2935. AnsiString TargetName;
  2936. if (UnixExtractFilePath(NewName).IsEmpty())
  2937. {
  2938. // rename case (TTerminal::RenameFile)
  2939. TargetName = UnixExtractFilePath(RealName) + NewName;
  2940. }
  2941. else
  2942. {
  2943. TargetName = LocalCanonify(NewName);
  2944. }
  2945. Packet.AddPathString(TargetName, FUtfStrings);
  2946. if (FVersion >= 5)
  2947. {
  2948. Packet.AddCardinal(0);
  2949. }
  2950. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2951. }
  2952. //---------------------------------------------------------------------------
  2953. void __fastcall TSFTPFileSystem::CopyFile(const AnsiString /*FileName*/,
  2954. const AnsiString /*NewName*/)
  2955. {
  2956. assert(false);
  2957. }
  2958. //---------------------------------------------------------------------------
  2959. void __fastcall TSFTPFileSystem::CreateDirectory(const AnsiString DirName,
  2960. const TRemoteProperties * Properties)
  2961. {
  2962. TSFTPPacket Packet(SSH_FXP_MKDIR);
  2963. AnsiString CanonifiedName = Canonify(DirName);
  2964. Packet.AddPathString(CanonifiedName, FUtfStrings);
  2965. Packet.AddProperties(NULL, 0, true, FVersion, FUtfStrings);
  2966. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2967. // explicitly set permissions after directory creation,
  2968. // permissions specified in SSH_FXP_MKDIR are ignored at least by OpenSSH
  2969. try
  2970. {
  2971. Packet.ChangeType(SSH_FXP_SETSTAT);
  2972. Packet.AddPathString(CanonifiedName, FUtfStrings);
  2973. Packet.AddProperties(Properties, 0, true, FVersion, FUtfStrings);
  2974. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2975. }
  2976. catch(Exception & E)
  2977. {
  2978. if (FTerminal->Active)
  2979. {
  2980. throw ECommand(&E, FMTLOAD(CHANGE_PROPERTIES_ERROR, (DirName)));
  2981. }
  2982. else
  2983. {
  2984. throw;
  2985. }
  2986. }
  2987. }
  2988. //---------------------------------------------------------------------------
  2989. void __fastcall TSFTPFileSystem::CreateLink(const AnsiString FileName,
  2990. const AnsiString PointTo, bool Symbolic)
  2991. {
  2992. USEDPARAM(Symbolic);
  2993. assert(Symbolic); // only symlinks are supported by SFTP
  2994. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2995. TSFTPPacket Packet(SSH_FXP_SYMLINK);
  2996. bool Buggy = (FTerminal->SessionData->SFTPBug[sbSymlink] == asOn) ||
  2997. ((FTerminal->SessionData->SFTPBug[sbSymlink] == asAuto) &&
  2998. (GetSessionInfo().SshImplementation.Pos("OpenSSH") == 1));
  2999. if (!Buggy)
  3000. {
  3001. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  3002. Packet.AddPathString(PointTo, FUtfStrings);
  3003. }
  3004. else
  3005. {
  3006. FTerminal->LogEvent("We believe the server has SFTP symlink bug");
  3007. Packet.AddPathString(PointTo, FUtfStrings);
  3008. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  3009. }
  3010. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3011. }
  3012. //---------------------------------------------------------------------------
  3013. void __fastcall TSFTPFileSystem::ChangeFileProperties(const AnsiString FileName,
  3014. const TRemoteFile * /*File*/, const TRemoteProperties * Properties)
  3015. {
  3016. assert(Properties);
  3017. TRemoteFile * File;
  3018. AnsiString RealFileName = LocalCanonify(FileName);
  3019. ReadFile(RealFileName, File);
  3020. try
  3021. {
  3022. assert(File);
  3023. if (File->IsDirectory && !File->IsSymLink && Properties->Recursive)
  3024. {
  3025. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  3026. (void*)Properties);
  3027. }
  3028. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  3029. Packet.AddPathString(RealFileName, FUtfStrings);
  3030. Packet.AddProperties(Properties, *File->Rights, File->IsDirectory, FVersion, FUtfStrings);
  3031. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3032. }
  3033. __finally
  3034. {
  3035. delete File;
  3036. }
  3037. }
  3038. //---------------------------------------------------------------------------
  3039. bool __fastcall TSFTPFileSystem::LoadFilesProperties(TStrings * FileList)
  3040. {
  3041. bool Result = false;
  3042. // without knowledge of server's capabilities, this all make no sense
  3043. if (FSupport->Loaded)
  3044. {
  3045. TFileOperationProgressType Progress(FTerminal->FOnProgress, FTerminal->FOnFinished);
  3046. Progress.Start(foGetProperties, osRemote, FileList->Count);
  3047. FTerminal->FOperationProgress = &Progress;
  3048. try
  3049. {
  3050. static int LoadFilesPropertiesQueueLen = 5;
  3051. // at end of this block queue is disposed
  3052. TSFTPLoadFilesPropertiesQueue Queue(this);
  3053. if (Queue.Init(LoadFilesPropertiesQueueLen, FileList))
  3054. {
  3055. TRemoteFile * File;
  3056. TSFTPPacket Packet;
  3057. bool Next;
  3058. do
  3059. {
  3060. Next = Queue.ReceivePacket(&Packet, File);
  3061. assert((Packet.Type == SSH_FXP_ATTRS) || (Packet.Type == SSH_FXP_STATUS));
  3062. if (Packet.Type == SSH_FXP_ATTRS)
  3063. {
  3064. Progress.SetFile(File->FileName);
  3065. assert(File != NULL);
  3066. LoadFile(File, &Packet);
  3067. Result = true;
  3068. bool DisconnectWhenComplete;
  3069. Progress.Finish(File->FileName, true, DisconnectWhenComplete);
  3070. }
  3071. if (Progress.Cancel != csContinue)
  3072. {
  3073. Next = false;
  3074. }
  3075. }
  3076. while (Next);
  3077. }
  3078. }
  3079. __finally
  3080. {
  3081. FTerminal->FOperationProgress = NULL;
  3082. Progress.Stop();
  3083. }
  3084. }
  3085. return Result;
  3086. }
  3087. //---------------------------------------------------------------------------
  3088. void __fastcall TSFTPFileSystem::DoCalculateFilesChecksum(const AnsiString & Alg,
  3089. TStrings * FileList, TStrings * Checksums,
  3090. TCalculatedChecksumEvent OnCalculatedChecksum,
  3091. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  3092. {
  3093. bool DisconnectWhenComplete; // not used
  3094. // recurse into subdirectories only if we have callback function
  3095. if (OnCalculatedChecksum != NULL)
  3096. {
  3097. for (int Index = 0; Index < FileList->Count; Index++)
  3098. {
  3099. TRemoteFile * File = (TRemoteFile *)FileList->Objects[Index];
  3100. assert(File != NULL);
  3101. if (File->IsDirectory && !File->IsSymLink &&
  3102. !File->IsParentDirectory && !File->IsThisDirectory)
  3103. {
  3104. OperationProgress->SetFile(File->FileName);
  3105. TRemoteFileList * SubFiles =
  3106. FTerminal->ReadDirectoryListing(File->FullFileName, false);
  3107. if (SubFiles != NULL)
  3108. {
  3109. TStrings * SubFileList = new TStringList();
  3110. bool Success = false;
  3111. try
  3112. {
  3113. OperationProgress->SetFile(File->FileName);
  3114. for (int Index = 0; Index < SubFiles->Count; Index++)
  3115. {
  3116. TRemoteFile * SubFile = SubFiles->Files[Index];
  3117. SubFileList->AddObject(SubFile->FullFileName, SubFile);
  3118. }
  3119. // do not collect checksums for files in subdirectories,
  3120. // only send back checksums via callback
  3121. DoCalculateFilesChecksum(Alg, SubFileList, NULL,
  3122. OnCalculatedChecksum, OperationProgress, false);
  3123. Success = true;
  3124. }
  3125. __finally
  3126. {
  3127. delete SubFiles;
  3128. delete SubFileList;
  3129. if (FirstLevel)
  3130. {
  3131. OperationProgress->Finish(File->FileName, Success, DisconnectWhenComplete);
  3132. }
  3133. }
  3134. }
  3135. }
  3136. }
  3137. }
  3138. static int CalculateFilesChecksumQueueLen = 5;
  3139. // at end of this block queue is disposed
  3140. TSFTPCalculateFilesChecksumQueue Queue(this);
  3141. if (Queue.Init(CalculateFilesChecksumQueueLen, Alg, FileList))
  3142. {
  3143. TSFTPPacket Packet;
  3144. bool Next;
  3145. do
  3146. {
  3147. bool Success = false;
  3148. AnsiString Alg;
  3149. AnsiString Checksum;
  3150. TRemoteFile * File = NULL;
  3151. try
  3152. {
  3153. try
  3154. {
  3155. Next = Queue.ReceivePacket(&Packet, File);
  3156. assert(Packet.Type == SSH_FXP_EXTENDED_REPLY);
  3157. OperationProgress->SetFile(File->FileName);
  3158. Alg = Packet.GetString();
  3159. Checksum = StrToHex(AnsiString(Packet.GetNextData(Packet.RemainingLength), Packet.RemainingLength));
  3160. OnCalculatedChecksum(File->FileName, Alg, Checksum);
  3161. Success = true;
  3162. }
  3163. catch (Exception & E)
  3164. {
  3165. FTerminal->CommandError(&E, FMTLOAD(CHECKSUM_ERROR,
  3166. (File != NULL ? File->FullFileName : AnsiString(""))));
  3167. // TODO: retries? resume?
  3168. Next = false;
  3169. }
  3170. if (Checksums != NULL)
  3171. {
  3172. Checksums->Add("");
  3173. }
  3174. }
  3175. __finally
  3176. {
  3177. if (FirstLevel)
  3178. {
  3179. OperationProgress->Finish(File->FileName, Success, DisconnectWhenComplete);
  3180. }
  3181. }
  3182. if (OperationProgress->Cancel != csContinue)
  3183. {
  3184. Next = false;
  3185. }
  3186. }
  3187. while (Next);
  3188. }
  3189. }
  3190. //---------------------------------------------------------------------------
  3191. void __fastcall TSFTPFileSystem::CalculateFilesChecksum(const AnsiString & Alg,
  3192. TStrings * FileList, TStrings * Checksums,
  3193. TCalculatedChecksumEvent OnCalculatedChecksum)
  3194. {
  3195. TFileOperationProgressType Progress(FTerminal->FOnProgress, FTerminal->FOnFinished);
  3196. Progress.Start(foCalculateChecksum, osRemote, FileList->Count);
  3197. FTerminal->FOperationProgress = &Progress;
  3198. try
  3199. {
  3200. DoCalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum,
  3201. &Progress, true);
  3202. }
  3203. __finally
  3204. {
  3205. FTerminal->FOperationProgress = NULL;
  3206. Progress.Stop();
  3207. }
  3208. }
  3209. //---------------------------------------------------------------------------
  3210. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  3211. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/,
  3212. TCaptureOutputEvent /*OutputEvent*/)
  3213. {
  3214. assert(false);
  3215. }
  3216. //---------------------------------------------------------------------------
  3217. void __fastcall TSFTPFileSystem::AnyCommand(const AnsiString /*Command*/,
  3218. TCaptureOutputEvent /*OutputEvent*/)
  3219. {
  3220. assert(false);
  3221. }
  3222. //---------------------------------------------------------------------------
  3223. AnsiString __fastcall TSFTPFileSystem::FileUrl(const AnsiString FileName)
  3224. {
  3225. return FTerminal->FileUrl("sftp", FileName);
  3226. }
  3227. //---------------------------------------------------------------------------
  3228. TStrings * __fastcall TSFTPFileSystem::GetFixedPaths()
  3229. {
  3230. return FFixedPaths;
  3231. }
  3232. //---------------------------------------------------------------------------
  3233. void __fastcall TSFTPFileSystem::SpaceAvailable(const AnsiString Path,
  3234. TSpaceAvailable & ASpaceAvailable)
  3235. {
  3236. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3237. Packet.AddString(SFTP_EXT_SPACE_AVAILABLE);
  3238. Packet.AddPathString(LocalCanonify(Path), FUtfStrings);
  3239. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3240. ASpaceAvailable.BytesOnDevice = Packet.GetInt64();
  3241. ASpaceAvailable.UnusedBytesOnDevice = Packet.GetInt64();
  3242. ASpaceAvailable.BytesAvailableToUser = Packet.GetInt64();
  3243. ASpaceAvailable.UnusedBytesAvailableToUser = Packet.GetInt64();
  3244. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetCardinal();
  3245. }
  3246. //---------------------------------------------------------------------------
  3247. // transfer protocol
  3248. //---------------------------------------------------------------------------
  3249. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  3250. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  3251. int Params, TFileOperationProgressType * OperationProgress,
  3252. bool & DisconnectWhenComplete)
  3253. {
  3254. assert(FilesToCopy && OperationProgress);
  3255. AnsiString FileName, FileNameOnly;
  3256. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  3257. int Index = 0;
  3258. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  3259. {
  3260. bool Success = false;
  3261. FileName = FilesToCopy->Strings[Index];
  3262. FileNameOnly = ExtractFileName(FileName);
  3263. assert(!FAvoidBusy);
  3264. FAvoidBusy = true;
  3265. try
  3266. {
  3267. try
  3268. {
  3269. if (FTerminal->SessionData->CacheDirectories)
  3270. {
  3271. FTerminal->DirectoryModified(TargetDir, false);
  3272. if (DirectoryExists(FileName))
  3273. {
  3274. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  3275. FileNameOnly, true);
  3276. }
  3277. }
  3278. SFTPSourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  3279. tfFirstLevel);
  3280. Success = true;
  3281. }
  3282. catch(EScpSkipFile & E)
  3283. {
  3284. SUSPEND_OPERATION (
  3285. if (!FTerminal->HandleException(&E))
  3286. {
  3287. throw;
  3288. };
  3289. );
  3290. }
  3291. }
  3292. __finally
  3293. {
  3294. FAvoidBusy = false;
  3295. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  3296. }
  3297. Index++;
  3298. }
  3299. }
  3300. //---------------------------------------------------------------------------
  3301. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(AnsiString & FileName,
  3302. TFileOperationProgressType * OperationProgress,
  3303. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  3304. {
  3305. bool TargetBiggerThanSource = (FileParams->DestSize > FileParams->SourceSize);
  3306. bool CanAlternateResume = !TargetBiggerThanSource && !OperationProgress->AsciiTransfer;
  3307. if (OperationProgress->NoToAll)
  3308. {
  3309. THROW_SKIP_FILE_NULL;
  3310. }
  3311. else if (CanAlternateResume && OperationProgress->AlternateResumeAlways)
  3312. {
  3313. OverwriteMode = omResume;
  3314. }
  3315. else
  3316. {
  3317. int Answer;
  3318. SUSPEND_OPERATION
  3319. (
  3320. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  3321. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  3322. {
  3323. Answers |= qaRetry;
  3324. }
  3325. TQueryButtonAlias Aliases[3];
  3326. Aliases[0].Button = qaRetry;
  3327. Aliases[0].Alias = LoadStr(APPEND_BUTTON);
  3328. Aliases[1].Button = qaAll;
  3329. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  3330. Aliases[2].Button = qaIgnore;
  3331. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  3332. TQueryParams Params(qpNeverAskAgainCheck);
  3333. Params.Aliases = Aliases;
  3334. Params.AliasesCount = LENOF(Aliases);
  3335. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  3336. Answers, &Params,
  3337. OperationProgress->Side == osLocal ? osRemote : osLocal,
  3338. OperationProgress);
  3339. );
  3340. if (Answer == qaRetry)
  3341. {
  3342. if (!CanAlternateResume)
  3343. {
  3344. OverwriteMode = omAppend;
  3345. }
  3346. else
  3347. {
  3348. TQueryParams Params(0, HELP_APPEND_OR_RESUME);
  3349. SUSPEND_OPERATION
  3350. (
  3351. Answer = FTerminal->QueryUser(FORMAT(LoadStr(APPEND_OR_RESUME), (FileName)),
  3352. NULL, qaYes | qaNo | qaNoToAll | qaCancel, &Params);
  3353. );
  3354. switch (Answer)
  3355. {
  3356. case qaYes:
  3357. OverwriteMode = omAppend;
  3358. break;
  3359. case qaNo:
  3360. OverwriteMode = omResume;
  3361. break;
  3362. case qaNoToAll:
  3363. OverwriteMode = omResume;
  3364. OperationProgress->AlternateResumeAlways = true;
  3365. break;
  3366. default: assert(false); //fallthru
  3367. case qaCancel:
  3368. if (!OperationProgress->Cancel)
  3369. {
  3370. OperationProgress->Cancel = csCancel;
  3371. }
  3372. Abort();
  3373. break;
  3374. }
  3375. }
  3376. }
  3377. else if (Answer == qaIgnore)
  3378. {
  3379. if (FTerminal->PromptUser(FTerminal->SessionData, pkPrompt, LoadStr(RENAME_TITLE), "",
  3380. LoadStr(RENAME_PROMPT2), true, 0, FileName))
  3381. {
  3382. OverwriteMode = omOverwrite;
  3383. }
  3384. else
  3385. {
  3386. if (!OperationProgress->Cancel)
  3387. {
  3388. OperationProgress->Cancel = csCancel;
  3389. }
  3390. Abort();
  3391. }
  3392. }
  3393. else
  3394. {
  3395. OverwriteMode = omOverwrite;
  3396. switch (Answer)
  3397. {
  3398. case qaCancel:
  3399. if (!OperationProgress->Cancel)
  3400. {
  3401. OperationProgress->Cancel = csCancel;
  3402. }
  3403. Abort();
  3404. break;
  3405. case qaNo:
  3406. THROW_SKIP_FILE_NULL;
  3407. }
  3408. }
  3409. }
  3410. }
  3411. //---------------------------------------------------------------------------
  3412. bool TSFTPFileSystem::SFTPConfirmResume(const AnsiString DestFileName,
  3413. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  3414. {
  3415. bool ResumeTransfer;
  3416. assert(OperationProgress);
  3417. if (PartialBiggerThanSource)
  3418. {
  3419. int Answer;
  3420. SUSPEND_OPERATION
  3421. (
  3422. TQueryParams Params(qpAllowContinueOnError, HELP_PARTIAL_BIGGER_THAN_SOURCE);
  3423. Answer = FTerminal->QueryUser(
  3424. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
  3425. qaOK | qaAbort, &Params, qtWarning);
  3426. )
  3427. if (Answer == qaAbort)
  3428. {
  3429. if (!OperationProgress->Cancel)
  3430. {
  3431. OperationProgress->Cancel = csCancel;
  3432. }
  3433. Abort();
  3434. }
  3435. ResumeTransfer = false;
  3436. }
  3437. else if (FTerminal->Configuration->ConfirmResume)
  3438. {
  3439. int Answer;
  3440. SUSPEND_OPERATION
  3441. (
  3442. TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck,
  3443. HELP_RESUME_TRANSFER);
  3444. // "abort" replaced with "cancel" to unify with "append/resume" query
  3445. Answer = FTerminal->QueryUser(
  3446. FMTLOAD(RESUME_TRANSFER, (DestFileName)), NULL, qaYes | qaNo | qaCancel,
  3447. &Params);
  3448. );
  3449. switch (Answer) {
  3450. case qaNeverAskAgain:
  3451. FTerminal->Configuration->ConfirmResume = false;
  3452. case qaYes:
  3453. ResumeTransfer = true;
  3454. break;
  3455. case qaNo:
  3456. ResumeTransfer = false;
  3457. break;
  3458. case qaCancel:
  3459. if (!OperationProgress->Cancel)
  3460. {
  3461. OperationProgress->Cancel = csCancel;
  3462. }
  3463. Abort();
  3464. break;
  3465. }
  3466. }
  3467. else
  3468. {
  3469. ResumeTransfer = true;
  3470. }
  3471. return ResumeTransfer;
  3472. }
  3473. //---------------------------------------------------------------------------
  3474. void __fastcall TSFTPFileSystem::SFTPSourceRobust(const AnsiString FileName,
  3475. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  3476. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3477. {
  3478. // the same in TFTPFileSystem
  3479. bool Retry;
  3480. do
  3481. {
  3482. Retry = false;
  3483. try
  3484. {
  3485. SFTPSource(FileName, TargetDir, CopyParam, Params, OperationProgress, Flags);
  3486. }
  3487. catch(Exception & E)
  3488. {
  3489. Retry = true;
  3490. if (FTerminal->Active ||
  3491. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  3492. {
  3493. throw;
  3494. }
  3495. }
  3496. if (Retry)
  3497. {
  3498. OperationProgress->RollbackTransfer();
  3499. // prevent overwrite and resume confirmations
  3500. // (should not be set for directories!)
  3501. Params |= cpNoConfirmation;
  3502. // enable resume even if we are uploading into new directory
  3503. Flags &= ~tfNewDirectory;
  3504. }
  3505. }
  3506. while (Retry);
  3507. }
  3508. //---------------------------------------------------------------------------
  3509. void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
  3510. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  3511. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3512. {
  3513. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  3514. OperationProgress->SetFile(FileName);
  3515. TOpenRemoteFileParams OpenParams;
  3516. OpenParams.OverwriteMode = omOverwrite;
  3517. HANDLE File;
  3518. __int64 MTime, ATime;
  3519. __int64 Size;
  3520. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
  3521. &File, NULL, &MTime, &ATime, &Size);
  3522. try
  3523. {
  3524. bool Dir = FLAGSET(OpenParams.LocalFileAttrs, faDirectory);
  3525. TFileMasks::TParams MaskParams;
  3526. MaskParams.Size = Size;
  3527. if (FLAGCLEAR(Params, cpDelete) &&
  3528. !CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams))
  3529. {
  3530. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  3531. THROW_SKIP_FILE_NULL;
  3532. }
  3533. if (Dir)
  3534. {
  3535. SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  3536. OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
  3537. }
  3538. else
  3539. {
  3540. // File is regular file (not directory)
  3541. assert(File);
  3542. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  3543. osLocal, FLAGSET(Flags, tfFirstLevel));
  3544. AnsiString DestFullName = LocalCanonify(TargetDir + DestFileName);
  3545. AnsiString DestPartinalFullName;
  3546. bool ResumeAllowed;
  3547. bool ResumeTransfer = false;
  3548. bool DestFileExists = false;
  3549. TRights DestRights;
  3550. __int64 ResumeOffset;
  3551. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  3552. OperationProgress->SetLocalSize(Size);
  3553. // Suppose same data size to transfer as to read
  3554. // (not true with ASCII transfer)
  3555. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  3556. OperationProgress->TransferingFile = false;
  3557. // Will we use ASCII of BINARY file tranfer?
  3558. OperationProgress->SetAsciiTransfer(
  3559. CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
  3560. FTerminal->LogEvent(
  3561. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  3562. " transfer mode selected.");
  3563. // should we check for interrupted transfer?
  3564. ResumeAllowed = !OperationProgress->AsciiTransfer &&
  3565. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  3566. IsCapable(fcRename);
  3567. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  3568. TOverwriteFileParams FileParams;
  3569. FileParams.SourceSize = OperationProgress->LocalSize;
  3570. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  3571. FTerminal->SessionData->DSTMode);
  3572. if (ResumeAllowed)
  3573. {
  3574. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3575. if (FLAGCLEAR(Flags, tfNewDirectory))
  3576. {
  3577. FTerminal->LogEvent("Checking existence of file.");
  3578. TRemoteFile * File = NULL;
  3579. DestFileExists = RemoteFileExists(DestFullName, &File);
  3580. if (DestFileExists)
  3581. {
  3582. OpenParams.DestFileSize = File->Size;
  3583. FileParams.DestSize = OpenParams.DestFileSize;
  3584. FileParams.DestTimestamp = File->Modification;
  3585. DestRights = *File->Rights;
  3586. // if destination file is symlink, never do resumable transfer,
  3587. // as it would delete the symlink.
  3588. // also bit of heuristics to detect symlink on SFTP-3 and older
  3589. // (which does not indicate symlink in SSH_FXP_ATTRS).
  3590. // if file has all permissions and is small, then it is likely symlink.
  3591. // also it is not likely that such a small file (if it is not symlink)
  3592. // gets overwritten by large file (that would trigger resumable transfer).
  3593. if (File->IsSymLink ||
  3594. ((FVersion < 4) &&
  3595. ((*File->Rights & TRights::rfAll) == TRights::rfAll) &&
  3596. (File->Size < 100)))
  3597. {
  3598. ResumeAllowed = false;
  3599. OperationProgress->SetResumeStatus(rsDisabled);
  3600. }
  3601. delete File;
  3602. File = NULL;
  3603. }
  3604. if (ResumeAllowed)
  3605. {
  3606. FTerminal->LogEvent("Checking existence of partially transfered file.");
  3607. if (RemoteFileExists(DestPartinalFullName, &File))
  3608. {
  3609. ResumeOffset = File->Size;
  3610. delete File;
  3611. File = NULL;
  3612. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->LocalSize);
  3613. if (FLAGCLEAR(Params, cpNoConfirmation))
  3614. {
  3615. ResumeTransfer = SFTPConfirmResume(DestFileName,
  3616. PartialBiggerThanSource, OperationProgress);
  3617. }
  3618. else
  3619. {
  3620. ResumeTransfer = !PartialBiggerThanSource;
  3621. }
  3622. if (!ResumeTransfer)
  3623. {
  3624. DeleteFile(DestPartinalFullName);
  3625. }
  3626. else
  3627. {
  3628. FTerminal->LogEvent("Resuming file transfer.");
  3629. }
  3630. }
  3631. else
  3632. {
  3633. // partial upload file does not exists, check for full file
  3634. if (DestFileExists &&
  3635. (FLAGSET(Params, cpNewerOnly) ||
  3636. (FTerminal->Configuration->ConfirmOverwriting &&
  3637. !OperationProgress->YesToAll && FLAGCLEAR(Params, cpNoConfirmation))))
  3638. {
  3639. AnsiString PrevDestFileName = DestFileName;
  3640. SFTPConfirmOverwrite(DestFileName,
  3641. OperationProgress, OpenParams.OverwriteMode, &FileParams);
  3642. if (PrevDestFileName != DestFileName)
  3643. {
  3644. // update paths in case user changes the file name
  3645. DestFullName = LocalCanonify(TargetDir + DestFileName);
  3646. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3647. FTerminal->LogEvent("Checking existence of new file.");
  3648. DestFileExists = RemoteFileExists(DestFullName, NULL);
  3649. }
  3650. }
  3651. }
  3652. }
  3653. }
  3654. }
  3655. // will the transfer be resumable?
  3656. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  3657. OpenParams.RemoteFileName = DoResume ? DestPartinalFullName : DestFullName;
  3658. OpenParams.Resume = DoResume;
  3659. OpenParams.OperationProgress = OperationProgress;
  3660. OpenParams.CopyParam = CopyParam;
  3661. OpenParams.Params = Params;
  3662. OpenParams.FileParams = &FileParams;
  3663. OpenParams.Confirmed = false;
  3664. FTerminal->LogEvent("Opening remote file.");
  3665. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
  3666. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  3667. &OpenParams);
  3668. bool TransferFinished = false;
  3669. __int64 DestWriteOffset = 0;
  3670. TSFTPPacket CloseRequest;
  3671. bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
  3672. bool SetProperties = (CopyParam->PreserveTime || SetRights);
  3673. TSFTPPacket PropertiesRequest(SSH_FXP_SETSTAT);
  3674. TSFTPPacket PropertiesResponse;
  3675. if (SetProperties)
  3676. {
  3677. PropertiesRequest.AddPathString(DestFullName, FUtfStrings);
  3678. unsigned short Rights = 0;
  3679. if (CopyParam->PreserveRights)
  3680. {
  3681. Rights = CopyParam->RemoteFileRights(OpenParams.LocalFileAttrs);
  3682. }
  3683. else if (DoResume && DestFileExists)
  3684. {
  3685. Rights = DestRights.NumberSet;
  3686. }
  3687. PropertiesRequest.AddProperties(
  3688. SetRights ? &Rights : NULL, NULL, NULL,
  3689. CopyParam->PreserveTime ? &MTime : NULL,
  3690. CopyParam->PreserveTime ? &ATime : NULL,
  3691. NULL, false, FVersion, FUtfStrings);
  3692. }
  3693. try
  3694. {
  3695. if (OpenParams.OverwriteMode == omAppend)
  3696. {
  3697. FTerminal->LogEvent("Appending file.");
  3698. DestWriteOffset = OpenParams.DestFileSize;
  3699. }
  3700. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  3701. {
  3702. if (OpenParams.OverwriteMode == omResume)
  3703. {
  3704. FTerminal->LogEvent("Resuming file transfer (append style).");
  3705. ResumeOffset = OpenParams.DestFileSize;
  3706. }
  3707. FileSeek((THandle)File, ResumeOffset, 0);
  3708. OperationProgress->AddResumed(ResumeOffset);
  3709. }
  3710. // at end of this block queue is disposed
  3711. {
  3712. TSFTPUploadQueue Queue(this);
  3713. Queue.Init(FileName, File, OperationProgress,
  3714. OpenParams.RemoteFileHandle,
  3715. DestWriteOffset + OperationProgress->TransferedSize);
  3716. while (Queue.Continue())
  3717. {
  3718. if (OperationProgress->Cancel)
  3719. {
  3720. Abort();
  3721. }
  3722. }
  3723. // send close request before waiting for pending read responses
  3724. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3725. OperationProgress, false, true, &CloseRequest);
  3726. OpenParams.RemoteFileHandle = "";
  3727. // when resuming is disabled, we can send "set properties"
  3728. // request before waiting for pending read/close responses
  3729. if (SetProperties && !DoResume)
  3730. {
  3731. SendPacket(&PropertiesRequest);
  3732. ReserveResponse(&PropertiesRequest, &PropertiesResponse);
  3733. }
  3734. }
  3735. TransferFinished = true;
  3736. }
  3737. __finally
  3738. {
  3739. if (FTerminal->Active)
  3740. {
  3741. // if file transfer was finished, the close request was already sent
  3742. if (!OpenParams.RemoteFileHandle.IsEmpty())
  3743. {
  3744. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3745. OperationProgress, TransferFinished, true, &CloseRequest);
  3746. }
  3747. // wait for the response
  3748. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3749. OperationProgress, TransferFinished, false, &CloseRequest);
  3750. // delete file if transfer was not completed, resuming was not allowed and
  3751. // we were not appending (incl. alternate resume),
  3752. // shortly after plain transfer completes (eq. !ResumeAllowed)
  3753. if (!TransferFinished && !DoResume && (OpenParams.OverwriteMode == omOverwrite))
  3754. {
  3755. DeleteFile(OpenParams.RemoteFileName);
  3756. }
  3757. }
  3758. }
  3759. if (DoResume)
  3760. {
  3761. if (DestFileExists)
  3762. {
  3763. FILE_OPERATION_LOOP(FMTLOAD(DELETE_ON_RESUME_ERROR,
  3764. (UnixExtractFileName(DestFullName), DestFullName)),
  3765. DeleteFile(DestFullName);
  3766. );
  3767. }
  3768. // originally this was before CLOSE (last __finally statement),
  3769. // on VShell it failed
  3770. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  3771. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  3772. RenameFile(OpenParams.RemoteFileName, DestFileName);
  3773. );
  3774. }
  3775. if (SetProperties)
  3776. {
  3777. // when resuming is enabled, the set properties request was not sent yet
  3778. if (DoResume)
  3779. {
  3780. SendPacket(&PropertiesRequest);
  3781. }
  3782. bool Resend = false;
  3783. FILE_OPERATION_LOOP(FMTLOAD(PRESERVE_TIME_PERM_ERROR, (DestFileName)),
  3784. TSFTPPacket DummyResponse;
  3785. TSFTPPacket * Response = &PropertiesResponse;
  3786. if (Resend)
  3787. {
  3788. PropertiesRequest.Reuse();
  3789. SendPacket(&PropertiesRequest);
  3790. // ReceiveResponse currently cannot receive twice into same packet,
  3791. // so DummyResponse is temporary workaround
  3792. Response = &DummyResponse;
  3793. }
  3794. Resend = true;
  3795. ReceiveResponse(&PropertiesRequest, Response, SSH_FXP_STATUS,
  3796. asOK | FLAGMASK(CopyParam->IgnorePermErrors, asPermDenied));
  3797. );
  3798. }
  3799. }
  3800. }
  3801. __finally
  3802. {
  3803. if (File != NULL)
  3804. {
  3805. CloseHandle(File);
  3806. }
  3807. }
  3808. /* TODO : Delete also read-only files. */
  3809. /* TODO : Show error message on failure. */
  3810. if (FLAGSET(Params, cpDelete))
  3811. {
  3812. Sysutils::DeleteFile(FileName);
  3813. }
  3814. else if (CopyParam->ClearArchive && FLAGSET(OpenParams.LocalFileAttrs, faArchive))
  3815. {
  3816. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  3817. THROWIFFALSE(FileSetAttr(FileName, OpenParams.LocalFileAttrs & ~faArchive) == 0);
  3818. )
  3819. }
  3820. }
  3821. //---------------------------------------------------------------------------
  3822. AnsiString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
  3823. const AnsiString & FileName, unsigned int OpenType, __int64 Size)
  3824. {
  3825. TSFTPPacket Packet(SSH_FXP_OPEN);
  3826. Packet.AddPathString(FileName, FUtfStrings);
  3827. if (FVersion < 5)
  3828. {
  3829. Packet.AddCardinal(OpenType);
  3830. }
  3831. else
  3832. {
  3833. unsigned long Access =
  3834. FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
  3835. FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
  3836. unsigned long Flags;
  3837. if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
  3838. {
  3839. Flags = SSH_FXF_CREATE_NEW;
  3840. }
  3841. else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
  3842. {
  3843. Flags = SSH_FXF_CREATE_TRUNCATE;
  3844. }
  3845. else if (FLAGSET(OpenType, SSH_FXF_CREAT))
  3846. {
  3847. Flags = SSH_FXF_OPEN_OR_CREATE;
  3848. }
  3849. else
  3850. {
  3851. Flags = SSH_FXF_OPEN_EXISTING;
  3852. }
  3853. Flags |=
  3854. FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
  3855. FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
  3856. Packet.AddCardinal(Access);
  3857. Packet.AddCardinal(Flags);
  3858. }
  3859. Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
  3860. Size >= 0 ? &Size : NULL, false, FVersion, FUtfStrings);
  3861. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3862. return Packet.GetString();
  3863. }
  3864. //---------------------------------------------------------------------------
  3865. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  3866. {
  3867. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  3868. assert(OpenParams);
  3869. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  3870. int OpenType;
  3871. bool Success = false;
  3872. do
  3873. {
  3874. try
  3875. {
  3876. OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
  3877. if (FTerminal->Configuration->ConfirmOverwriting &&
  3878. !OpenParams->Confirmed && !OperationProgress->YesToAll && !OpenParams->Resume &&
  3879. !(OpenParams->Params & cpNoConfirmation) &&
  3880. (OpenParams->OverwriteMode == omOverwrite))
  3881. {
  3882. OpenType |= SSH_FXF_EXCL;
  3883. }
  3884. if (!OpenParams->Resume && (OpenParams->OverwriteMode == omOverwrite))
  3885. {
  3886. OpenType |= SSH_FXF_TRUNC;
  3887. }
  3888. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  3889. {
  3890. OpenType |= SSH_FXF_TEXT;
  3891. }
  3892. OpenParams->RemoteFileHandle = SFTPOpenRemoteFile(
  3893. OpenParams->RemoteFileName, OpenType, OperationProgress->LocalSize);
  3894. Success = true;
  3895. }
  3896. catch(Exception & E)
  3897. {
  3898. if (!OpenParams->Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  3899. {
  3900. bool ThrowOriginal = false;
  3901. // When exclusive opening of file fails, try to detect if file exists.
  3902. // When file does not exist, failure was probably caused by 'permission denied'
  3903. // or similar error. In this case throw original exception.
  3904. try
  3905. {
  3906. TRemoteFile * File;
  3907. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  3908. ReadFile(RealFileName, File);
  3909. OpenParams->DestFileSize = File->Size;
  3910. if (OpenParams->FileParams != NULL)
  3911. {
  3912. OpenParams->FileParams->DestTimestamp = File->Modification;
  3913. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  3914. }
  3915. // file exists (otherwise exception was thrown)
  3916. assert(File);
  3917. SAFE_DESTROY(File);
  3918. }
  3919. catch(...)
  3920. {
  3921. if (!FTerminal->Active)
  3922. {
  3923. throw;
  3924. }
  3925. else
  3926. {
  3927. ThrowOriginal = true;
  3928. }
  3929. }
  3930. if (ThrowOriginal)
  3931. {
  3932. throw;
  3933. }
  3934. // confirmation duplicated in SFTPSource for resumable file transfers.
  3935. AnsiString RemoteFileNameOnly = UnixExtractFileName(OpenParams->RemoteFileName);
  3936. SFTPConfirmOverwrite(RemoteFileNameOnly,
  3937. OperationProgress, OpenParams->OverwriteMode, OpenParams->FileParams);
  3938. if (RemoteFileNameOnly != UnixExtractFileName(OpenParams->RemoteFileName))
  3939. {
  3940. OpenParams->RemoteFileName =
  3941. UnixExtractFilePath(OpenParams->RemoteFileName) + RemoteFileNameOnly;
  3942. }
  3943. OpenParams->Confirmed = true;
  3944. if (FTerminal->SessionData->OverwrittenToRecycleBin)
  3945. {
  3946. FTerminal->RecycleFile(OpenParams->RemoteFileName, NULL);
  3947. }
  3948. }
  3949. else if (FTerminal->Active)
  3950. {
  3951. // if file overwritting was confirmed, it means that the file already exists,
  3952. // if not, check now
  3953. if (!OpenParams->Confirmed)
  3954. {
  3955. bool ThrowOriginal = false;
  3956. // When file does not exist, failure was probably caused by 'permission denied'
  3957. // or similar error. In this case throw original exception.
  3958. try
  3959. {
  3960. TRemoteFile * File;
  3961. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  3962. ReadFile(RealFileName, File);
  3963. SAFE_DESTROY(File);
  3964. }
  3965. catch(...)
  3966. {
  3967. if (!FTerminal->Active)
  3968. {
  3969. throw;
  3970. }
  3971. else
  3972. {
  3973. ThrowOriginal = true;
  3974. }
  3975. }
  3976. if (ThrowOriginal)
  3977. {
  3978. throw;
  3979. }
  3980. }
  3981. // now we know that the file exists
  3982. if (FTerminal->FileOperationLoopQuery(E, OperationProgress,
  3983. FMTLOAD(SFTP_OVERWRITE_FILE_ERROR, (OpenParams->RemoteFileName)),
  3984. true, LoadStr(SFTP_OVERWRITE_DELETE_BUTTON)))
  3985. {
  3986. int Params = dfNoRecursive;
  3987. FTerminal->DeleteFile(OpenParams->RemoteFileName, NULL, &Params);
  3988. }
  3989. }
  3990. else
  3991. {
  3992. throw;
  3993. }
  3994. }
  3995. }
  3996. while (!Success);
  3997. return 0;
  3998. }
  3999. //---------------------------------------------------------------------------
  4000. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const AnsiString Handle,
  4001. const AnsiString FileName, TFileOperationProgressType * OperationProgress,
  4002. bool TransferFinished, bool Request, TSFTPPacket * Packet)
  4003. {
  4004. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  4005. FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)),
  4006. try
  4007. {
  4008. TSFTPPacket CloseRequest;
  4009. TSFTPPacket * P = (Packet == NULL ? &CloseRequest : Packet);
  4010. if (Request)
  4011. {
  4012. P->ChangeType(SSH_FXP_CLOSE);
  4013. P->AddString(Handle);
  4014. SendPacket(P);
  4015. ReserveResponse(P, Packet);
  4016. }
  4017. else
  4018. {
  4019. assert(Packet != NULL);
  4020. ReceiveResponse(P, Packet, SSH_FXP_STATUS);
  4021. }
  4022. }
  4023. catch(...)
  4024. {
  4025. if (!FTerminal->Active || TransferFinished)
  4026. {
  4027. throw;
  4028. }
  4029. }
  4030. );
  4031. }
  4032. //---------------------------------------------------------------------------
  4033. void __fastcall TSFTPFileSystem::SFTPDirectorySource(const AnsiString DirectoryName,
  4034. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  4035. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4036. {
  4037. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  4038. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  4039. FLAGSET(Flags, tfFirstLevel));
  4040. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  4041. OperationProgress->SetFile(DirectoryName);
  4042. bool CreateDir = false;
  4043. try
  4044. {
  4045. TryOpenDirectory(DestFullName);
  4046. }
  4047. catch(...)
  4048. {
  4049. if (FTerminal->Active)
  4050. {
  4051. // opening directory failed, it probably does not exists, try to
  4052. // create it
  4053. CreateDir = true;
  4054. }
  4055. else
  4056. {
  4057. throw;
  4058. }
  4059. }
  4060. if (CreateDir)
  4061. {
  4062. TRemoteProperties Properties;
  4063. if (CopyParam->PreserveRights)
  4064. {
  4065. Properties.Valid = TValidProperties() << vpRights;
  4066. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  4067. }
  4068. FTerminal->CreateDirectory(DestFullName, &Properties);
  4069. Flags |= tfNewDirectory;
  4070. }
  4071. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4072. TSearchRec SearchRec;
  4073. bool FindOK;
  4074. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  4075. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  4076. FindAttrs, SearchRec) == 0);
  4077. );
  4078. while (FindOK && !OperationProgress->Cancel)
  4079. {
  4080. AnsiString FileName = DirectoryName + SearchRec.Name;
  4081. try
  4082. {
  4083. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  4084. {
  4085. SFTPSourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  4086. Flags & ~tfFirstLevel);
  4087. }
  4088. }
  4089. catch (EScpSkipFile &E)
  4090. {
  4091. // If ESkipFile occurs, just log it and continue with next file
  4092. SUSPEND_OPERATION (
  4093. // here a message to user was displayed, which was not appropriate
  4094. // when user refused to overwrite the file in subdirectory.
  4095. // hopefuly it won't be missing in other situations.
  4096. if (!FTerminal->HandleException(&E)) throw;
  4097. );
  4098. }
  4099. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  4100. FindOK = (FindNext(SearchRec) == 0);
  4101. );
  4102. };
  4103. FindClose(SearchRec);
  4104. /* TODO : Delete also read-only directories. */
  4105. /* TODO : Show error message on failure. */
  4106. if (!OperationProgress->Cancel)
  4107. {
  4108. if (FLAGSET(Params, cpDelete))
  4109. {
  4110. RemoveDir(DirectoryName);
  4111. }
  4112. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  4113. {
  4114. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  4115. THROWIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  4116. )
  4117. }
  4118. }
  4119. }
  4120. //---------------------------------------------------------------------------
  4121. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  4122. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  4123. int Params, TFileOperationProgressType * OperationProgress,
  4124. bool & DisconnectWhenComplete)
  4125. {
  4126. assert(FilesToCopy && OperationProgress);
  4127. AnsiString FileName;
  4128. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  4129. const TRemoteFile * File;
  4130. bool Success;
  4131. int Index = 0;
  4132. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  4133. {
  4134. Success = false;
  4135. FileName = FilesToCopy->Strings[Index];
  4136. File = (TRemoteFile *)FilesToCopy->Objects[Index];
  4137. assert(!FAvoidBusy);
  4138. FAvoidBusy = true;
  4139. try
  4140. {
  4141. try
  4142. {
  4143. SFTPSinkRobust(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
  4144. Params, OperationProgress, tfFirstLevel);
  4145. Success = true;
  4146. }
  4147. catch(EScpSkipFile & E)
  4148. {
  4149. SUSPEND_OPERATION (
  4150. if (!FTerminal->HandleException(&E)) throw;
  4151. );
  4152. }
  4153. catch(...)
  4154. {
  4155. // TODO: remove the block?
  4156. throw;
  4157. }
  4158. }
  4159. __finally
  4160. {
  4161. FAvoidBusy = false;
  4162. OperationProgress->Finish(FileName, Success, DisconnectWhenComplete);
  4163. }
  4164. Index++;
  4165. }
  4166. }
  4167. //---------------------------------------------------------------------------
  4168. void __fastcall TSFTPFileSystem::SFTPSinkRobust(const AnsiString FileName,
  4169. const TRemoteFile * File, const AnsiString TargetDir,
  4170. const TCopyParamType * CopyParam, int Params,
  4171. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4172. {
  4173. // the same in TFTPFileSystem
  4174. bool Retry;
  4175. do
  4176. {
  4177. Retry = false;
  4178. try
  4179. {
  4180. SFTPSink(FileName, File, TargetDir, CopyParam, Params, OperationProgress, Flags);
  4181. }
  4182. catch(Exception & E)
  4183. {
  4184. Retry = true;
  4185. if (FTerminal->Active ||
  4186. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  4187. {
  4188. throw;
  4189. }
  4190. }
  4191. if (Retry)
  4192. {
  4193. OperationProgress->RollbackTransfer();
  4194. assert(File != NULL);
  4195. if (!File->IsDirectory)
  4196. {
  4197. // prevent overwrite and resume confirmations
  4198. Params |= cpNoConfirmation;
  4199. }
  4200. }
  4201. }
  4202. while (Retry);
  4203. }
  4204. //---------------------------------------------------------------------------
  4205. void __fastcall TSFTPFileSystem::SFTPSink(const AnsiString FileName,
  4206. const TRemoteFile * File, const AnsiString TargetDir,
  4207. const TCopyParamType * CopyParam, int Params,
  4208. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4209. {
  4210. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  4211. TFileMasks::TParams MaskParams;
  4212. MaskParams.Size = File->Size;
  4213. if (FLAGCLEAR(Params, cpDelete) &&
  4214. !CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  4215. {
  4216. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  4217. THROW_SKIP_FILE_NULL;
  4218. }
  4219. assert(File);
  4220. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  4221. OperationProgress->SetFile(OnlyFileName);
  4222. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  4223. osRemote, FLAGSET(Flags, tfFirstLevel));
  4224. AnsiString DestFullName = TargetDir + DestFileName;
  4225. if (File->IsDirectory)
  4226. {
  4227. if (!File->IsSymLink)
  4228. {
  4229. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  4230. int Attrs = FileGetAttr(DestFullName);
  4231. if ((Attrs & faDirectory) == 0) EXCEPTION;
  4232. );
  4233. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  4234. if (!ForceDirectories(DestFullName)) EXCEPTION;
  4235. );
  4236. TSinkFileParams SinkFileParams;
  4237. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  4238. SinkFileParams.CopyParam = CopyParam;
  4239. SinkFileParams.Params = Params;
  4240. SinkFileParams.OperationProgress = OperationProgress;
  4241. SinkFileParams.Skipped = false;
  4242. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  4243. FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
  4244. // Do not delete directory if some of its files were skip.
  4245. // Throw "skip file" for the directory to avoid attempt to deletion
  4246. // of any parent directory
  4247. if ((Params & cpDelete) && SinkFileParams.Skipped)
  4248. {
  4249. THROW_SKIP_FILE_NULL;
  4250. }
  4251. }
  4252. else
  4253. {
  4254. // file is symlink to directory, currently do nothing, but it should be
  4255. // reported to user
  4256. }
  4257. }
  4258. else
  4259. {
  4260. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  4261. AnsiString DestPartinalFullName;
  4262. bool ResumeAllowed;
  4263. bool ResumeTransfer = false;
  4264. __int64 ResumeOffset;
  4265. // Will we use ASCII of BINARY file tranfer?
  4266. OperationProgress->SetAsciiTransfer(
  4267. CopyParam->UseAsciiTransfer(FileName, osRemote, MaskParams));
  4268. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  4269. " transfer mode selected.");
  4270. // Suppose same data size to transfer as to write
  4271. // (not true with ASCII transfer)
  4272. OperationProgress->SetTransferSize(File->Size);
  4273. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  4274. // resume has no sense for temporary downloads
  4275. ResumeAllowed = ((Params & cpTemporary) == 0) &&
  4276. !OperationProgress->AsciiTransfer &&
  4277. CopyParam->AllowResume(OperationProgress->TransferSize);
  4278. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  4279. int Attrs;
  4280. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  4281. Attrs = FileGetAttr(DestFullName);
  4282. if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
  4283. );
  4284. OperationProgress->TransferingFile = false; // not set with SFTP protocol
  4285. HANDLE LocalHandle = NULL;
  4286. TStream * FileStream = NULL;
  4287. bool DeleteLocalFile = false;
  4288. AnsiString RemoteHandle;
  4289. AnsiString LocalFileName = DestFullName;
  4290. TSFTPOverwriteMode OverwriteMode = omOverwrite;
  4291. try
  4292. {
  4293. if (ResumeAllowed)
  4294. {
  4295. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4296. LocalFileName = DestPartinalFullName;
  4297. FTerminal->LogEvent("Checking existence of partially transfered file.");
  4298. if (FileExists(DestPartinalFullName))
  4299. {
  4300. FTerminal->OpenLocalFile(DestPartinalFullName, GENERIC_WRITE,
  4301. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  4302. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->TransferSize);
  4303. if (FLAGCLEAR(Params, cpNoConfirmation))
  4304. {
  4305. ResumeTransfer = SFTPConfirmResume(DestFileName,
  4306. PartialBiggerThanSource, OperationProgress);
  4307. }
  4308. else
  4309. {
  4310. ResumeTransfer = !PartialBiggerThanSource;
  4311. }
  4312. if (!ResumeTransfer)
  4313. {
  4314. CloseHandle(LocalHandle);
  4315. LocalHandle = NULL;
  4316. Sysutils::DeleteFile(DestPartinalFullName);
  4317. }
  4318. else
  4319. {
  4320. FTerminal->LogEvent("Resuming file transfer.");
  4321. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  4322. OperationProgress->AddResumed(ResumeOffset);
  4323. }
  4324. }
  4325. }
  4326. if ((Attrs >= 0) && !ResumeTransfer &&
  4327. (FLAGSET(Params, cpNewerOnly) ||
  4328. (FTerminal->Configuration->ConfirmOverwriting &&
  4329. !OperationProgress->YesToAll &&
  4330. FLAGCLEAR(Params, cpNoConfirmation))))
  4331. {
  4332. __int64 DestFileSize;
  4333. __int64 MTime;
  4334. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  4335. NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  4336. FTerminal->LogEvent("Checking existence of file.");
  4337. TOverwriteFileParams FileParams;
  4338. FileParams.SourceSize = OperationProgress->TransferSize;
  4339. FileParams.SourceTimestamp = File->Modification;
  4340. FileParams.DestTimestamp = UnixToDateTime(MTime,
  4341. FTerminal->SessionData->DSTMode);
  4342. FileParams.DestSize = DestFileSize;
  4343. AnsiString PrevDestFileName = DestFileName;
  4344. SFTPConfirmOverwrite(DestFileName, OperationProgress, OverwriteMode, &FileParams);
  4345. if (PrevDestFileName != DestFileName)
  4346. {
  4347. DestFullName = TargetDir + DestFileName;
  4348. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4349. if (ResumeAllowed)
  4350. {
  4351. if (FileExists(DestPartinalFullName))
  4352. {
  4353. Sysutils::DeleteFile(DestPartinalFullName);
  4354. }
  4355. LocalFileName = DestPartinalFullName;
  4356. }
  4357. else
  4358. {
  4359. LocalFileName = DestFullName;
  4360. }
  4361. }
  4362. if (OverwriteMode == omOverwrite)
  4363. {
  4364. // is NULL when overwritting read-only file
  4365. if (LocalHandle)
  4366. {
  4367. CloseHandle(LocalHandle);
  4368. LocalHandle = NULL;
  4369. }
  4370. }
  4371. else
  4372. {
  4373. // is NULL when overwritting read-only file, so following will
  4374. // probably fail anyway
  4375. if (LocalHandle == NULL)
  4376. {
  4377. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  4378. NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  4379. }
  4380. ResumeAllowed = false;
  4381. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  4382. if (OverwriteMode == omAppend)
  4383. {
  4384. FTerminal->LogEvent("Appending to file.");
  4385. }
  4386. else
  4387. {
  4388. FTerminal->LogEvent("Resuming file transfer (append style).");
  4389. assert(OverwriteMode == omResume);
  4390. OperationProgress->AddResumed(DestFileSize);
  4391. }
  4392. }
  4393. }
  4394. // if not already opened (resume, append...), create new empty file
  4395. if (!LocalHandle)
  4396. {
  4397. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress,
  4398. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  4399. {
  4400. THROW_SKIP_FILE_NULL;
  4401. }
  4402. }
  4403. assert(LocalHandle);
  4404. DeleteLocalFile = true;
  4405. FTerminal->LogEvent("Opening remote file.");
  4406. FILE_OPERATION_LOOP (FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)),
  4407. int OpenType = SSH_FXF_READ;
  4408. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  4409. {
  4410. OpenType |= SSH_FXF_TEXT;
  4411. }
  4412. RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
  4413. );
  4414. TSFTPPacket RemoteFilePacket(SSH_FXP_FSTAT);
  4415. if (CopyParam->PreserveTime)
  4416. {
  4417. SendCustomReadFile(&RemoteFilePacket, &RemoteFilePacket, RemoteHandle,
  4418. SSH_FILEXFER_ATTR_MODIFYTIME);
  4419. }
  4420. FileStream = new TSafeHandleStream((THandle)LocalHandle);
  4421. // at end of this block queue is disposed
  4422. {
  4423. TSFTPDownloadQueue Queue(this);
  4424. TSFTPPacket DataPacket;
  4425. int QueueLen = int(File->Size / DownloadBlockSize(OperationProgress)) + 1;
  4426. if ((QueueLen > FTerminal->SessionData->SFTPDownloadQueue) ||
  4427. (QueueLen < 0))
  4428. {
  4429. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  4430. }
  4431. if (QueueLen < 1)
  4432. {
  4433. QueueLen = 1;
  4434. }
  4435. Queue.Init(QueueLen, RemoteHandle, OperationProgress->TransferedSize,
  4436. OperationProgress);
  4437. bool Eof = false;
  4438. bool PrevIncomplete = false;
  4439. int GapFillCount = 0;
  4440. int GapCount = 0;
  4441. unsigned long Missing = 0;
  4442. unsigned long DataLen = 0;
  4443. unsigned long BlockSize;
  4444. while (!Eof)
  4445. {
  4446. if (Missing > 0)
  4447. {
  4448. Queue.InitFillGapRequest(OperationProgress->TransferedSize, Missing,
  4449. &DataPacket);
  4450. GapFillCount++;
  4451. SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
  4452. SSH_FXP_DATA, asEOF);
  4453. }
  4454. else
  4455. {
  4456. Queue.ReceivePacket(&DataPacket, BlockSize);
  4457. }
  4458. if (DataPacket.Type == SSH_FXP_STATUS)
  4459. {
  4460. // must be SSH_FX_EOF, any other status packet would raise exception
  4461. Eof = true;
  4462. // close file right away, before waiting for pending responses
  4463. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  4464. true, true, NULL);
  4465. RemoteHandle = ""; // do not close file again in __finally block
  4466. }
  4467. if (!Eof)
  4468. {
  4469. if ((Missing == 0) && PrevIncomplete)
  4470. {
  4471. // This can happen only if last request returned less bytes
  4472. // than expected, but exacly number of bytes missing to last
  4473. // known file size, but actually EOF was not reached.
  4474. // Can happen only when filesize has changed since directory
  4475. // listing and server returns less bytes than requested and
  4476. // file has some special file size.
  4477. FTerminal->LogEvent(FORMAT(
  4478. "Received incomplete data packet before end of file, "
  4479. "offset: %s, size: %d, requested: %d",
  4480. (IntToStr(OperationProgress->TransferedSize), int(DataLen),
  4481. int(BlockSize))));
  4482. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  4483. }
  4484. // Buffer for one block of data
  4485. TFileBuffer BlockBuf;
  4486. DataLen = DataPacket.GetCardinal();
  4487. PrevIncomplete = false;
  4488. if (Missing > 0)
  4489. {
  4490. assert(DataLen <= Missing);
  4491. Missing -= DataLen;
  4492. }
  4493. else if (DataLen < BlockSize)
  4494. {
  4495. if (OperationProgress->TransferedSize + DataLen !=
  4496. OperationProgress->TransferSize)
  4497. {
  4498. // with native text transfer mode (SFTP>=4), do not bother about
  4499. // getting less than requested, read offset is ignored anyway
  4500. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  4501. {
  4502. GapCount++;
  4503. Missing = BlockSize - DataLen;
  4504. }
  4505. }
  4506. else
  4507. {
  4508. PrevIncomplete = true;
  4509. }
  4510. }
  4511. assert(DataLen <= BlockSize);
  4512. BlockBuf.Insert(0, DataPacket.GetNextData(DataLen), DataLen);
  4513. OperationProgress->AddTransfered(DataLen);
  4514. if (OperationProgress->AsciiTransfer)
  4515. {
  4516. assert(!ResumeTransfer && !ResumeAllowed);
  4517. unsigned int PrevBlockSize = BlockBuf.Size;
  4518. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0);
  4519. OperationProgress->SetLocalSize(
  4520. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  4521. }
  4522. FILE_OPERATION_LOOP (FMTLOAD(WRITE_ERROR, (LocalFileName)),
  4523. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  4524. );
  4525. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  4526. }
  4527. if (OperationProgress->Cancel == csCancel)
  4528. {
  4529. Abort();
  4530. }
  4531. };
  4532. if (GapCount > 0)
  4533. {
  4534. FTerminal->LogEvent(FORMAT(
  4535. "%d requests to fill %d data gaps were issued.",
  4536. (GapFillCount, GapCount)));
  4537. }
  4538. }
  4539. if (CopyParam->PreserveTime)
  4540. {
  4541. ReceiveResponse(&RemoteFilePacket, &RemoteFilePacket);
  4542. const TRemoteFile * AFile = File;
  4543. try
  4544. {
  4545. // ignore errors
  4546. if (RemoteFilePacket.Type == SSH_FXP_ATTRS)
  4547. {
  4548. // load file, avoid completion (resolving symlinks) as we do not need that
  4549. AFile = LoadFile(&RemoteFilePacket, NULL, UnixExtractFileName(FileName),
  4550. NULL, false);
  4551. }
  4552. FILETIME AcTime = DateTimeToFileTime(AFile->LastAccess,
  4553. FTerminal->SessionData->DSTMode);
  4554. FILETIME WrTime = DateTimeToFileTime(AFile->Modification,
  4555. FTerminal->SessionData->DSTMode);
  4556. SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
  4557. }
  4558. __finally
  4559. {
  4560. if (AFile != File)
  4561. {
  4562. delete AFile;
  4563. }
  4564. }
  4565. }
  4566. CloseHandle(LocalHandle);
  4567. LocalHandle = NULL;
  4568. if (ResumeAllowed)
  4569. {
  4570. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  4571. (ExtractFileName(DestPartinalFullName), DestFileName)),
  4572. if (FileExists(DestFullName))
  4573. {
  4574. if (!Sysutils::DeleteFile(DestFullName)) EXCEPTION;
  4575. }
  4576. if (!Sysutils::RenameFile(DestPartinalFullName, DestFullName))
  4577. {
  4578. EXCEPTION;
  4579. }
  4580. );
  4581. }
  4582. DeleteLocalFile = false;
  4583. if (Attrs == -1)
  4584. {
  4585. Attrs = faArchive;
  4586. }
  4587. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  4588. if ((NewAttrs & Attrs) != NewAttrs)
  4589. {
  4590. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  4591. THROWIFFALSE(FileSetAttr(DestFullName, Attrs | NewAttrs) == 0);
  4592. );
  4593. }
  4594. }
  4595. __finally
  4596. {
  4597. if (LocalHandle) CloseHandle(LocalHandle);
  4598. if (FileStream) delete FileStream;
  4599. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocalyUsed == 0) &&
  4600. (OverwriteMode == omOverwrite))
  4601. {
  4602. Sysutils::DeleteFile(LocalFileName);
  4603. }
  4604. // if the transfer was finished, the file is closed already
  4605. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  4606. {
  4607. // do not wait for response
  4608. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  4609. true, true, NULL);
  4610. }
  4611. }
  4612. }
  4613. if (Params & cpDelete)
  4614. {
  4615. // If file is directory, do not delete it recursively, because it should be
  4616. // empty already. If not, it should not be deleted (some files were
  4617. // skipped or some new files were copied to it, while we were downloading)
  4618. int Params = dfNoRecursive;
  4619. FTerminal->DeleteFile(FileName, File, &Params);
  4620. }
  4621. }
  4622. //---------------------------------------------------------------------------
  4623. void __fastcall TSFTPFileSystem::SFTPSinkFile(AnsiString FileName,
  4624. const TRemoteFile * File, void * Param)
  4625. {
  4626. TSinkFileParams * Params = (TSinkFileParams *)Param;
  4627. assert(Params->OperationProgress);
  4628. try
  4629. {
  4630. SFTPSinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  4631. Params->Params, Params->OperationProgress, Params->Flags);
  4632. }
  4633. catch(EScpSkipFile & E)
  4634. {
  4635. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  4636. Params->Skipped = true;
  4637. SUSPEND_OPERATION (
  4638. if (!FTerminal->HandleException(&E)) throw;
  4639. );
  4640. if (OperationProgress->Cancel)
  4641. {
  4642. Abort();
  4643. }
  4644. }
  4645. }