SftpFileSystem.cpp 152 KB

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