SftpFileSystem.cpp 158 KB

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