SftpFileSystem.cpp 191 KB

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