SftpFileSystem.cpp 190 KB

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