SftpFileSystem.cpp 190 KB

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