SftpFileSystem.cpp 189 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140
  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) && ALWAYS_TRUE(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. FAIL;
  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 AnsiSameText(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. return true;
  1873. case fcRename:
  1874. case fcRemoteMove:
  1875. return (FVersion >= 2);
  1876. case fcSymbolicLink:
  1877. case fcResolveSymlink:
  1878. return (FVersion >= 3);
  1879. case fcModeChanging:
  1880. case fcModeChangingUpload:
  1881. return !FSupport->Loaded ||
  1882. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_PERMISSIONS);
  1883. case fcGroupOwnerChangingByID:
  1884. return (FVersion <= 3);
  1885. case fcOwnerChanging:
  1886. case fcGroupChanging:
  1887. return
  1888. (FVersion <= 3) ||
  1889. ((FVersion >= 4) &&
  1890. (!FSupport->Loaded ||
  1891. FLAGSET(FSupport->AttributeMask, SSH_FILEXFER_ATTR_OWNERGROUP)));
  1892. case fcNativeTextMode:
  1893. return (FVersion >= 4);
  1894. case fcTextMode:
  1895. return (FVersion >= 4) ||
  1896. strcmp(GetEOL(), EOLToStr(FTerminal->Configuration->LocalEOLType)) != 0;
  1897. case fcUserGroupListing:
  1898. return SupportsExtension(SFTP_EXT_OWNER_GROUP);
  1899. case fcLoadingAdditionalProperties:
  1900. // We allow loading properties only, if "supported" extension is supported and
  1901. // the server supports "permissions" and/or "owner/group" attributes
  1902. // (no other attributes are loaded).
  1903. // This is here only because of VShell
  1904. // (it supports owner/group, but does not include them into response to
  1905. // SSH_FXP_READDIR)
  1906. // and Bitwise (the same as VShell, but it does not even bother to provide "supported" extension until 6.21)
  1907. // No other use is known.
  1908. return
  1909. (FSupport->Loaded &&
  1910. ((FSupport->AttributeMask &
  1911. (SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_OWNERGROUP)) != 0)) ||
  1912. (FSecureShell->SshImplementation == sshiBitvise);
  1913. case fcCheckingSpaceAvailable:
  1914. return
  1915. // extension announced in extension list of by
  1916. // SFTP_EXT_SUPPORTED/SFTP_EXT_SUPPORTED2 extension
  1917. // (SFTP version 5 and newer only)
  1918. SupportsExtension(SFTP_EXT_SPACE_AVAILABLE) ||
  1919. // extension announced by proprietary SFTP_EXT_STATVFS extension
  1920. FSupportsStatVfsV2 ||
  1921. // Bitwise (until 6.21) fails to report it's supported extensions.
  1922. (FSecureShell->SshImplementation == sshiBitvise);
  1923. case fcCalculatingChecksum:
  1924. return
  1925. // Specification says that "check-file" should be announced,
  1926. // yet Vandyke VShell (as of 4.0.3) announce "check-file-name"
  1927. // https://forums.vandyke.com/showthread.php?t=11597
  1928. SupportsExtension(SFTP_EXT_CHECK_FILE) ||
  1929. SupportsExtension(SFTP_EXT_CHECK_FILE_NAME) ||
  1930. // see above
  1931. (FSecureShell->SshImplementation == sshiBitvise);
  1932. case fcRemoteCopy:
  1933. return
  1934. SupportsExtension(SFTP_EXT_COPY_FILE) ||
  1935. // see above
  1936. (FSecureShell->SshImplementation == sshiBitvise);
  1937. case fcHardLink:
  1938. return
  1939. (FVersion >= 6) ||
  1940. FSupportsHardlink;
  1941. case fcLocking:
  1942. return false;
  1943. default:
  1944. FAIL;
  1945. return false;
  1946. }
  1947. }
  1948. //---------------------------------------------------------------------------
  1949. bool __fastcall TSFTPFileSystem::SupportsExtension(const UnicodeString & Extension) const
  1950. {
  1951. return FSupport->Loaded && (FSupport->Extensions->IndexOf(Extension) >= 0);
  1952. }
  1953. //---------------------------------------------------------------------------
  1954. inline void __fastcall TSFTPFileSystem::BusyStart()
  1955. {
  1956. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1957. {
  1958. FBusyToken = ::BusyStart();
  1959. }
  1960. FBusy++;
  1961. DebugAssert(FBusy < 10);
  1962. }
  1963. //---------------------------------------------------------------------------
  1964. inline void __fastcall TSFTPFileSystem::BusyEnd()
  1965. {
  1966. DebugAssert(FBusy > 0);
  1967. FBusy--;
  1968. if (FBusy == 0 && FTerminal->UseBusyCursor && !FAvoidBusy)
  1969. {
  1970. ::BusyEnd(FBusyToken);
  1971. FBusyToken = NULL;
  1972. }
  1973. }
  1974. //---------------------------------------------------------------------------
  1975. unsigned long __fastcall TSFTPFileSystem::TransferBlockSize(unsigned long Overhead,
  1976. TFileOperationProgressType * OperationProgress, unsigned long MaxPacketSize)
  1977. {
  1978. const unsigned long MinPacketSize = 32768;
  1979. // size + message number + type
  1980. const unsigned long SFTPPacketOverhead = 4 + 4 + 1;
  1981. unsigned long AMaxPacketSize = FSecureShell->MaxPacketSize();
  1982. bool MaxPacketSizeValid = (AMaxPacketSize > 0);
  1983. unsigned long Result = OperationProgress->CPS();
  1984. if ((MaxPacketSize > 0) &&
  1985. ((MaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1986. {
  1987. AMaxPacketSize = MaxPacketSize;
  1988. MaxPacketSizeValid = true;
  1989. }
  1990. if ((FMaxPacketSize > 0) &&
  1991. ((FMaxPacketSize < AMaxPacketSize) || !MaxPacketSizeValid))
  1992. {
  1993. AMaxPacketSize = FMaxPacketSize;
  1994. MaxPacketSizeValid = true;
  1995. }
  1996. if (Result == 0)
  1997. {
  1998. Result = OperationProgress->StaticBlockSize();
  1999. }
  2000. if (Result < MinPacketSize)
  2001. {
  2002. Result = MinPacketSize;
  2003. }
  2004. if (MaxPacketSizeValid)
  2005. {
  2006. Overhead += SFTPPacketOverhead;
  2007. if (AMaxPacketSize < Overhead)
  2008. {
  2009. // do not send another request
  2010. // (generally should happen only if upload buffer is full)
  2011. Result = 0;
  2012. }
  2013. else
  2014. {
  2015. AMaxPacketSize -= Overhead;
  2016. if (Result > AMaxPacketSize)
  2017. {
  2018. Result = AMaxPacketSize;
  2019. }
  2020. }
  2021. }
  2022. Result = OperationProgress->AdjustToCPSLimit(Result);
  2023. return Result;
  2024. }
  2025. //---------------------------------------------------------------------------
  2026. unsigned long __fastcall TSFTPFileSystem::UploadBlockSize(const RawByteString & Handle,
  2027. TFileOperationProgressType * OperationProgress)
  2028. {
  2029. // handle length + offset + data size
  2030. const unsigned long UploadPacketOverhead =
  2031. sizeof(unsigned long) + sizeof(__int64) + sizeof(unsigned long);
  2032. return TransferBlockSize(UploadPacketOverhead + Handle.Length(), OperationProgress);
  2033. }
  2034. //---------------------------------------------------------------------------
  2035. unsigned long __fastcall TSFTPFileSystem::DownloadBlockSize(
  2036. TFileOperationProgressType * OperationProgress)
  2037. {
  2038. unsigned long Result = TransferBlockSize(sizeof(unsigned long), OperationProgress);
  2039. if (FSupport->Loaded && (FSupport->MaxReadSize > 0) &&
  2040. (Result > FSupport->MaxReadSize))
  2041. {
  2042. Result = FSupport->MaxReadSize;
  2043. }
  2044. return Result;
  2045. }
  2046. //---------------------------------------------------------------------------
  2047. void __fastcall TSFTPFileSystem::Progress(TFileOperationProgressType * OperationProgress)
  2048. {
  2049. FTerminal->Progress(OperationProgress);
  2050. }
  2051. //---------------------------------------------------------------------------
  2052. void __fastcall TSFTPFileSystem::SendPacket(const TSFTPPacket * Packet)
  2053. {
  2054. // putting here for a lack of better place
  2055. if (!FUtfDisablingAnnounced && (FUtfStrings == asOff))
  2056. {
  2057. FTerminal->LogEvent(L"Strings received in non-UTF-8 encoding in a previous packet, will not use UTF-8 anymore");
  2058. FUtfDisablingAnnounced = true;
  2059. }
  2060. BusyStart();
  2061. try
  2062. {
  2063. if (FTerminal->Log->Logging)
  2064. {
  2065. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  2066. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  2067. (Packet->Type != FPreviousLoggedPacket) ||
  2068. (FTerminal->Configuration->ActualLogProtocol >= 1))
  2069. {
  2070. if (FNotLoggedPackets)
  2071. {
  2072. FTerminal->LogEvent(FORMAT(L"%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  2073. (FNotLoggedPackets)));
  2074. FNotLoggedPackets = 0;
  2075. }
  2076. FTerminal->Log->Add(llInput, FORMAT(L"Type: %s, Size: %d, Number: %d",
  2077. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  2078. if (FTerminal->Configuration->ActualLogProtocol >= 2)
  2079. {
  2080. FTerminal->Log->Add(llInput, Packet->Dump());
  2081. }
  2082. FPreviousLoggedPacket = Packet->Type;
  2083. }
  2084. else
  2085. {
  2086. FNotLoggedPackets++;
  2087. }
  2088. }
  2089. FSecureShell->Send(Packet->SendData, Packet->SendLength);
  2090. }
  2091. __finally
  2092. {
  2093. BusyEnd();
  2094. }
  2095. }
  2096. //---------------------------------------------------------------------------
  2097. unsigned long __fastcall TSFTPFileSystem::GotStatusPacket(TSFTPPacket * Packet,
  2098. int AllowStatus)
  2099. {
  2100. unsigned long Code = Packet->GetCardinal();
  2101. static int Messages[] = {
  2102. SFTP_STATUS_OK,
  2103. SFTP_STATUS_EOF,
  2104. SFTP_STATUS_NO_SUCH_FILE,
  2105. SFTP_STATUS_PERMISSION_DENIED,
  2106. SFTP_STATUS_FAILURE,
  2107. SFTP_STATUS_BAD_MESSAGE,
  2108. SFTP_STATUS_NO_CONNECTION,
  2109. SFTP_STATUS_CONNECTION_LOST,
  2110. SFTP_STATUS_OP_UNSUPPORTED,
  2111. SFTP_STATUS_INVALID_HANDLE,
  2112. SFTP_STATUS_NO_SUCH_PATH,
  2113. SFTP_STATUS_FILE_ALREADY_EXISTS,
  2114. SFTP_STATUS_WRITE_PROTECT,
  2115. SFTP_STATUS_NO_MEDIA,
  2116. SFTP_STATUS_NO_SPACE_ON_FILESYSTEM,
  2117. SFTP_STATUS_QUOTA_EXCEEDED,
  2118. SFTP_STATUS_UNKNOWN_PRINCIPAL,
  2119. SFTP_STATUS_LOCK_CONFLICT,
  2120. SFTP_STATUS_DIR_NOT_EMPTY,
  2121. SFTP_STATUS_NOT_A_DIRECTORY,
  2122. SFTP_STATUS_INVALID_FILENAME,
  2123. SFTP_STATUS_LINK_LOOP,
  2124. SFTP_STATUS_CANNOT_DELETE,
  2125. SFTP_STATUS_INVALID_PARAMETER,
  2126. SFTP_STATUS_FILE_IS_A_DIRECTORY,
  2127. SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT,
  2128. SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED,
  2129. SFTP_STATUS_DELETE_PENDING,
  2130. SFTP_STATUS_FILE_CORRUPT,
  2131. SFTP_STATUS_OWNER_INVALID,
  2132. SFTP_STATUS_GROUP_INVALID,
  2133. SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK
  2134. };
  2135. int Message;
  2136. if ((AllowStatus & (0x01 << Code)) == 0)
  2137. {
  2138. if (Code >= LENOF(Messages))
  2139. {
  2140. Message = SFTP_STATUS_UNKNOWN;
  2141. }
  2142. else
  2143. {
  2144. Message = Messages[Code];
  2145. }
  2146. UnicodeString MessageStr = LoadStr(Message);
  2147. UnicodeString ServerMessage;
  2148. UnicodeString LanguageTag;
  2149. if ((FVersion >= 3) ||
  2150. // if version is not decided yet (i.e. this is status response
  2151. // to the init request), go on, only if there are any more data
  2152. ((FVersion < 0) && (Packet->RemainingLength > 0)))
  2153. {
  2154. // message is in UTF only since SFTP specification 01 (specification 00
  2155. // is also version 3)
  2156. // (in other words, always use UTF unless server is known to be buggy)
  2157. ServerMessage = Packet->GetString(FUtfStrings);
  2158. // SSH-2.0-Maverick_SSHD and SSH-2.0-CIGNA SFTP Server Ready! omit the language tag
  2159. // and I believe I've seen one more server doing the same.
  2160. if (Packet->RemainingLength > 0)
  2161. {
  2162. LanguageTag = Packet->GetAnsiString();
  2163. if ((FVersion >= 5) && (Message == SFTP_STATUS_UNKNOWN_PRINCIPAL))
  2164. {
  2165. UnicodeString Principals;
  2166. while (Packet->GetNextData() != NULL)
  2167. {
  2168. if (!Principals.IsEmpty())
  2169. {
  2170. Principals += L", ";
  2171. }
  2172. Principals += Packet->GetAnsiString();
  2173. }
  2174. MessageStr = FORMAT(MessageStr, (Principals));
  2175. }
  2176. }
  2177. }
  2178. else
  2179. {
  2180. ServerMessage = LoadStr(SFTP_SERVER_MESSAGE_UNSUPPORTED);
  2181. }
  2182. if (FTerminal->Log->Logging)
  2183. {
  2184. FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d, Message: %d, Server: %s, Language: %s ",
  2185. (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag)));
  2186. }
  2187. if (!LanguageTag.IsEmpty())
  2188. {
  2189. LanguageTag = FORMAT(L" (%s)", (LanguageTag));
  2190. }
  2191. UnicodeString HelpKeyword;
  2192. switch (Code)
  2193. {
  2194. case SSH_FX_FAILURE:
  2195. HelpKeyword = HELP_SFTP_STATUS_FAILURE;
  2196. break;
  2197. case SSH_FX_PERMISSION_DENIED:
  2198. HelpKeyword = HELP_SFTP_STATUS_PERMISSION_DENIED;
  2199. break;
  2200. }
  2201. UnicodeString Error = FMTLOAD(SFTP_ERROR_FORMAT3, (MessageStr,
  2202. int(Code), LanguageTag, ServerMessage));
  2203. if (Code == SSH_FX_FAILURE)
  2204. {
  2205. FTerminal->Configuration->Usage->Inc(L"SftpFailureErrors");
  2206. Error += L"\n\n" + LoadStr(SFTP_STATUS_4);
  2207. }
  2208. FTerminal->TerminalError(NULL, Error, HelpKeyword);
  2209. return 0;
  2210. }
  2211. else
  2212. {
  2213. if (!FNotLoggedPackets || Code)
  2214. {
  2215. FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d", ((int)Code)));
  2216. }
  2217. return Code;
  2218. }
  2219. }
  2220. //---------------------------------------------------------------------------
  2221. void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation)
  2222. {
  2223. for (int Index = Reservation+1; Index < FPacketReservations->Count; Index++)
  2224. {
  2225. FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1);
  2226. }
  2227. TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation];
  2228. if (Packet)
  2229. {
  2230. DebugAssert(Packet->ReservedBy == this);
  2231. Packet->ReservedBy = NULL;
  2232. }
  2233. FPacketReservations->Delete(Reservation);
  2234. }
  2235. //---------------------------------------------------------------------------
  2236. inline int __fastcall TSFTPFileSystem::PacketLength(unsigned char * LenBuf, int ExpectedType)
  2237. {
  2238. int Length = GET_32BIT(LenBuf);
  2239. if (Length > SFTP_MAX_PACKET_LEN)
  2240. {
  2241. UnicodeString Message = FMTLOAD(SFTP_PACKET_TOO_BIG, (
  2242. int(Length), SFTP_MAX_PACKET_LEN));
  2243. if (ExpectedType == SSH_FXP_VERSION)
  2244. {
  2245. RawByteString LenString(reinterpret_cast<char *>(LenBuf), 4);
  2246. Message = FMTLOAD(SFTP_PACKET_TOO_BIG_INIT_EXPLAIN,
  2247. (Message, DisplayableStr(LenString)));
  2248. }
  2249. FTerminal->FatalError(NULL, Message, HELP_SFTP_PACKET_TOO_BIG);
  2250. }
  2251. return Length;
  2252. }
  2253. //---------------------------------------------------------------------------
  2254. bool __fastcall TSFTPFileSystem::PeekPacket()
  2255. {
  2256. bool Result;
  2257. unsigned char * Buf;
  2258. Result = FSecureShell->Peek(Buf, 4);
  2259. if (Result)
  2260. {
  2261. int Length = PacketLength(Buf, -1);
  2262. Result = FSecureShell->Peek(Buf, 4 + Length);
  2263. }
  2264. return Result;
  2265. }
  2266. //---------------------------------------------------------------------------
  2267. int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet,
  2268. int ExpectedType, int AllowStatus, bool TryOnly)
  2269. {
  2270. TSFTPBusy Busy(this);
  2271. int Result = SSH_FX_OK;
  2272. int Reservation = FPacketReservations->IndexOf(Packet);
  2273. if (Reservation < 0 || Packet->Capacity == 0)
  2274. {
  2275. bool IsReserved;
  2276. do
  2277. {
  2278. IsReserved = false;
  2279. DebugAssert(Packet);
  2280. if (TryOnly && !PeekPacket())
  2281. {
  2282. // Reset packet in case it was filled by previous out-of-order
  2283. // reserved packet
  2284. *Packet = TSFTPPacket();
  2285. }
  2286. else
  2287. {
  2288. unsigned char LenBuf[4];
  2289. FSecureShell->Receive(LenBuf, sizeof(LenBuf));
  2290. int Length = PacketLength(LenBuf, ExpectedType);
  2291. Packet->Capacity = Length;
  2292. FSecureShell->Receive(Packet->Data, Length);
  2293. Packet->DataUpdated(Length);
  2294. if (FTerminal->Log->Logging)
  2295. {
  2296. if ((FPreviousLoggedPacket != SSH_FXP_READ &&
  2297. FPreviousLoggedPacket != SSH_FXP_WRITE) ||
  2298. (Packet->Type != SSH_FXP_STATUS && Packet->Type != SSH_FXP_DATA) ||
  2299. (FTerminal->Configuration->ActualLogProtocol >= 1))
  2300. {
  2301. if (FNotLoggedPackets)
  2302. {
  2303. FTerminal->LogEvent(FORMAT(L"%d skipped SSH_FXP_WRITE, SSH_FXP_READ, SSH_FXP_DATA and SSH_FXP_STATUS packets.",
  2304. (FNotLoggedPackets)));
  2305. FNotLoggedPackets = 0;
  2306. }
  2307. FTerminal->Log->Add(llOutput, FORMAT(L"Type: %s, Size: %d, Number: %d",
  2308. (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber)));
  2309. if (FTerminal->Configuration->ActualLogProtocol >= 2)
  2310. {
  2311. FTerminal->Log->Add(llOutput, Packet->Dump());
  2312. }
  2313. }
  2314. else
  2315. {
  2316. FNotLoggedPackets++;
  2317. }
  2318. }
  2319. if (Reservation < 0 ||
  2320. Packet->MessageNumber != (unsigned int)FPacketNumbers.GetElement(Reservation))
  2321. {
  2322. TSFTPPacket * ReservedPacket;
  2323. unsigned int MessageNumber;
  2324. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  2325. {
  2326. MessageNumber = (unsigned int)FPacketNumbers.GetElement(Index);
  2327. if (MessageNumber == Packet->MessageNumber)
  2328. {
  2329. ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index];
  2330. IsReserved = true;
  2331. if (ReservedPacket)
  2332. {
  2333. FTerminal->LogEvent(L"Storing reserved response");
  2334. *ReservedPacket = *Packet;
  2335. }
  2336. else
  2337. {
  2338. FTerminal->LogEvent(L"Discarding reserved response");
  2339. RemoveReservation(Index);
  2340. if ((Reservation >= 0) && (Reservation > Index))
  2341. {
  2342. Reservation--;
  2343. DebugAssert(Reservation == FPacketReservations->IndexOf(Packet));
  2344. }
  2345. }
  2346. break;
  2347. }
  2348. }
  2349. }
  2350. }
  2351. }
  2352. while (IsReserved);
  2353. }
  2354. if ((Packet->Capacity == 0) && ALWAYS_TRUE(TryOnly))
  2355. {
  2356. // noop
  2357. }
  2358. else
  2359. {
  2360. // before we removed the reservation after check for packet type,
  2361. // but if it raises exception, removal is unnecessarily
  2362. // postponed until the packet is removed
  2363. // (and it have not worked anyway until recent fix to UnreserveResponse)
  2364. if (Reservation >= 0)
  2365. {
  2366. DebugAssert(Packet->MessageNumber == (unsigned int)FPacketNumbers.GetElement(Reservation));
  2367. RemoveReservation(Reservation);
  2368. }
  2369. if (ExpectedType >= 0)
  2370. {
  2371. if (Packet->Type == SSH_FXP_STATUS)
  2372. {
  2373. if (AllowStatus < 0)
  2374. {
  2375. AllowStatus = (ExpectedType == SSH_FXP_STATUS ? asOK : asNo);
  2376. }
  2377. Result = GotStatusPacket(Packet, AllowStatus);
  2378. }
  2379. else if (ExpectedType != Packet->Type)
  2380. {
  2381. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type)));
  2382. }
  2383. }
  2384. }
  2385. return Result;
  2386. }
  2387. //---------------------------------------------------------------------------
  2388. void __fastcall TSFTPFileSystem::ReserveResponse(const TSFTPPacket * Packet,
  2389. TSFTPPacket * Response)
  2390. {
  2391. if (Response != NULL)
  2392. {
  2393. DebugAssert(FPacketReservations->IndexOf(Response) < 0);
  2394. // mark response as not received yet
  2395. Response->Capacity = 0;
  2396. Response->ReservedBy = this;
  2397. }
  2398. FPacketReservations->Add(Response);
  2399. if (FPacketReservations->Count >= FPacketNumbers.ArrayHighBound())
  2400. {
  2401. FPacketNumbers.ArrayRedim(FPacketReservations->Count + 10);
  2402. }
  2403. FPacketNumbers.PutElement(Packet->MessageNumber, FPacketReservations->Count - 1);
  2404. }
  2405. //---------------------------------------------------------------------------
  2406. void __fastcall TSFTPFileSystem::UnreserveResponse(TSFTPPacket * Response)
  2407. {
  2408. int Reservation = FPacketReservations->IndexOf(Response);
  2409. if (Response->Capacity != 0)
  2410. {
  2411. // added check for already received packet
  2412. // (it happens when the reserved response is received out of order,
  2413. // unexpectedly soon, and then receivepacket() on the packet
  2414. // is not actually called, due to exception)
  2415. RemoveReservation(Reservation);
  2416. }
  2417. else
  2418. {
  2419. if (Reservation >= 0)
  2420. {
  2421. // we probably do not remove the item at all, because
  2422. // we must remember that the response was expected, so we skip it
  2423. // in receivepacket()
  2424. FPacketReservations->Items[Reservation] = NULL;
  2425. }
  2426. }
  2427. }
  2428. //---------------------------------------------------------------------------
  2429. int __fastcall TSFTPFileSystem::ReceiveResponse(
  2430. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2431. int AllowStatus, bool TryOnly)
  2432. {
  2433. int Result;
  2434. unsigned int MessageNumber = Packet->MessageNumber;
  2435. TSFTPPacket * AResponse = (Response ? Response : new TSFTPPacket());
  2436. try
  2437. {
  2438. Result = ReceivePacket(AResponse, ExpectedType, AllowStatus, TryOnly);
  2439. if (MessageNumber != AResponse->MessageNumber)
  2440. {
  2441. FTerminal->FatalError(NULL, FMTLOAD(SFTP_MESSAGE_NUMBER,
  2442. ((int)AResponse->MessageNumber, (int)MessageNumber)));
  2443. }
  2444. }
  2445. __finally
  2446. {
  2447. if (!Response)
  2448. {
  2449. delete AResponse;
  2450. }
  2451. }
  2452. return Result;
  2453. }
  2454. //---------------------------------------------------------------------------
  2455. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  2456. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2457. int AllowStatus)
  2458. {
  2459. int Result;
  2460. TSFTPBusy Busy(this);
  2461. SendPacket(Packet);
  2462. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  2463. return Result;
  2464. }
  2465. //---------------------------------------------------------------------------
  2466. UnicodeString __fastcall TSFTPFileSystem::RealPath(const UnicodeString Path)
  2467. {
  2468. try
  2469. {
  2470. FTerminal->LogEvent(FORMAT(L"Getting real path for '%s'",
  2471. (Path)));
  2472. TSFTPPacket Packet(SSH_FXP_REALPATH);
  2473. Packet.AddPathString(Path, FUtfStrings);
  2474. // In SFTP-6 new optional field control-byte is added that defaults to
  2475. // SSH_FXP_REALPATH_NO_CHECK=0x01, meaning it won't fail, if the path does not exist.
  2476. // That differs from SFTP-5 recommendation that
  2477. // "The server SHOULD fail the request if the path is not present on the server."
  2478. // Earlier versions had no recommendation, though canonical SFTP-3 implementation
  2479. // in OpenSSH fails.
  2480. // While we really do not care much, we anyway set the flag to ~ & 0x01 to make the request fail.
  2481. // First for consistency.
  2482. // Second to workaround a bug in ProFTPD/mod_sftp version 1.3.5rc1 through 1.3.5-stable
  2483. // that sends a completelly malformed response for non-existing paths,
  2484. // when SSH_FXP_REALPATH_NO_CHECK (even implicitly) is used.
  2485. // See http://bugs.proftpd.org/show_bug.cgi?id=4160
  2486. // Note that earlier drafts of SFTP-6 (filexfer-07 and -08) had optional compose-path field
  2487. // before control-byte field. If we ever use this against a server conforming to those drafts,
  2488. // if may cause trouble.
  2489. if (FVersion >= 6)
  2490. {
  2491. if (FSecureShell->SshImplementation != sshiProFTPD)
  2492. {
  2493. Packet.AddByte(SSH_FXP_REALPATH_STAT_ALWAYS);
  2494. }
  2495. else
  2496. {
  2497. // Cannot use SSH_FXP_REALPATH_STAT_ALWAYS as ProFTPD does wrong bitwise test
  2498. // so it incorrectly evaluates SSH_FXP_REALPATH_STAT_ALWAYS (0x03) as
  2499. // SSH_FXP_REALPATH_NO_CHECK (0x01). The only value conforming to the
  2500. // specification, yet working with ProFTPD is SSH_FXP_REALPATH_STAT_IF (0x02).
  2501. Packet.AddByte(SSH_FXP_REALPATH_STAT_IF);
  2502. }
  2503. }
  2504. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  2505. if (Packet.GetCardinal() != 1)
  2506. {
  2507. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2508. }
  2509. UnicodeString RealDir = UnixExcludeTrailingBackslash(Packet.GetPathString(FUtfStrings));
  2510. // ignore rest of SSH_FXP_NAME packet
  2511. FTerminal->LogEvent(FORMAT(L"Real path is '%s'", (RealDir)));
  2512. return RealDir;
  2513. }
  2514. catch(Exception & E)
  2515. {
  2516. if (FTerminal->Active)
  2517. {
  2518. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  2519. }
  2520. else
  2521. {
  2522. throw;
  2523. }
  2524. }
  2525. }
  2526. //---------------------------------------------------------------------------
  2527. UnicodeString __fastcall TSFTPFileSystem::RealPath(const UnicodeString Path,
  2528. const UnicodeString BaseDir)
  2529. {
  2530. UnicodeString APath;
  2531. if (UnixIsAbsolutePath(Path))
  2532. {
  2533. APath = Path;
  2534. }
  2535. else
  2536. {
  2537. if (!Path.IsEmpty())
  2538. {
  2539. // this condition/block was outside (before) current block
  2540. // but it did not work when Path was empty
  2541. if (!BaseDir.IsEmpty())
  2542. {
  2543. APath = UnixIncludeTrailingBackslash(BaseDir);
  2544. }
  2545. APath = APath + Path;
  2546. }
  2547. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(L".");
  2548. }
  2549. return RealPath(APath);
  2550. }
  2551. //---------------------------------------------------------------------------
  2552. UnicodeString __fastcall TSFTPFileSystem::LocalCanonify(const UnicodeString & Path)
  2553. {
  2554. // TODO: improve (handle .. etc.)
  2555. if (UnixIsAbsolutePath(Path) ||
  2556. (!FCurrentDirectory.IsEmpty() && UnixSamePath(FCurrentDirectory, Path)))
  2557. {
  2558. return Path;
  2559. }
  2560. else
  2561. {
  2562. return ::AbsolutePath(FCurrentDirectory, Path);
  2563. }
  2564. }
  2565. //---------------------------------------------------------------------------
  2566. UnicodeString __fastcall TSFTPFileSystem::Canonify(UnicodeString Path)
  2567. {
  2568. // inspired by canonify() from PSFTP.C
  2569. UnicodeString Result;
  2570. FTerminal->LogEvent(FORMAT(L"Canonifying: \"%s\"", (Path)));
  2571. Path = LocalCanonify(Path);
  2572. bool TryParent = false;
  2573. try
  2574. {
  2575. Result = RealPath(Path);
  2576. }
  2577. catch(...)
  2578. {
  2579. if (FTerminal->Active)
  2580. {
  2581. TryParent = true;
  2582. }
  2583. else
  2584. {
  2585. throw;
  2586. }
  2587. }
  2588. if (TryParent)
  2589. {
  2590. UnicodeString APath = UnixExcludeTrailingBackslash(Path);
  2591. UnicodeString Name = UnixExtractFileName(APath);
  2592. if (Name == L"." || Name == L"..")
  2593. {
  2594. Result = Path;
  2595. }
  2596. else
  2597. {
  2598. UnicodeString FPath = UnixExtractFilePath(APath);
  2599. try
  2600. {
  2601. Result = RealPath(FPath);
  2602. Result = UnixIncludeTrailingBackslash(Result) + Name;
  2603. }
  2604. catch(...)
  2605. {
  2606. if (FTerminal->Active)
  2607. {
  2608. Result = Path;
  2609. }
  2610. else
  2611. {
  2612. throw;
  2613. }
  2614. }
  2615. }
  2616. }
  2617. FTerminal->LogEvent(FORMAT(L"Canonified: \"%s\"", (Result)));
  2618. return Result;
  2619. }
  2620. //---------------------------------------------------------------------------
  2621. UnicodeString __fastcall TSFTPFileSystem::AbsolutePath(UnicodeString Path, bool Local)
  2622. {
  2623. if (Local)
  2624. {
  2625. return LocalCanonify(Path);
  2626. }
  2627. else
  2628. {
  2629. return RealPath(Path, CurrentDirectory);
  2630. }
  2631. }
  2632. //---------------------------------------------------------------------------
  2633. UnicodeString __fastcall TSFTPFileSystem::GetHomeDirectory()
  2634. {
  2635. if (FHomeDirectory.IsEmpty())
  2636. {
  2637. FHomeDirectory = RealPath(L".");
  2638. }
  2639. return FHomeDirectory;
  2640. }
  2641. //---------------------------------------------------------------------------
  2642. void __fastcall TSFTPFileSystem::LoadFile(TRemoteFile * File, TSFTPPacket * Packet,
  2643. bool Complete)
  2644. {
  2645. Packet->GetFile(File, FVersion, FTerminal->SessionData->DSTMode,
  2646. FUtfStrings, FSignedTS, Complete);
  2647. }
  2648. //---------------------------------------------------------------------------
  2649. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  2650. TRemoteFile * ALinkedByFile, const UnicodeString FileName,
  2651. TRemoteFileList * TempFileList, bool Complete)
  2652. {
  2653. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  2654. try
  2655. {
  2656. File->Terminal = FTerminal;
  2657. if (!FileName.IsEmpty())
  2658. {
  2659. File->FileName = FileName;
  2660. }
  2661. // to get full path for symlink completion
  2662. File->Directory = TempFileList;
  2663. LoadFile(File, Packet, Complete);
  2664. File->Directory = NULL;
  2665. }
  2666. catch(...)
  2667. {
  2668. delete File;
  2669. throw;
  2670. }
  2671. return File;
  2672. }
  2673. //---------------------------------------------------------------------------
  2674. UnicodeString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  2675. {
  2676. return FCurrentDirectory;
  2677. }
  2678. //---------------------------------------------------------------------------
  2679. void __fastcall TSFTPFileSystem::DoStartup()
  2680. {
  2681. // do not know yet
  2682. FVersion = -1;
  2683. FFileSystemInfoValid = false;
  2684. TSFTPPacket Packet(SSH_FXP_INIT);
  2685. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  2686. if (MaxVersion > SFTPMaxVersion)
  2687. {
  2688. MaxVersion = SFTPMaxVersion;
  2689. }
  2690. Packet.AddCardinal(MaxVersion);
  2691. try
  2692. {
  2693. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  2694. }
  2695. catch(Exception &E)
  2696. {
  2697. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR), HELP_SFTP_INITIALIZE_ERROR);
  2698. }
  2699. FVersion = Packet.GetCardinal();
  2700. FTerminal->LogEvent(FORMAT(L"SFTP version %d negotiated.", (FVersion)));
  2701. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  2702. {
  2703. FTerminal->FatalError(NULL, FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  2704. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  2705. }
  2706. FExtensions->Clear();
  2707. FEOL = "\r\n";
  2708. FSupport->Loaded = false;
  2709. FSupportsStatVfsV2 = false;
  2710. FSupportsHardlink = false;
  2711. SAFE_DESTROY(FFixedPaths);
  2712. if (FVersion >= 3)
  2713. {
  2714. while (Packet.GetNextData() != NULL)
  2715. {
  2716. UnicodeString ExtensionName = Packet.GetAnsiString();
  2717. RawByteString ExtensionData = Packet.GetRawByteString();
  2718. UnicodeString ExtensionDisplayData = DisplayableStr(ExtensionData);
  2719. if (ExtensionName == SFTP_EXT_NEWLINE)
  2720. {
  2721. FEOL = AnsiString(ExtensionData);
  2722. FTerminal->LogEvent(FORMAT(L"Server requests EOL sequence %s.",
  2723. (ExtensionDisplayData)));
  2724. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2725. {
  2726. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2727. }
  2728. }
  2729. // do not allow "supported" to override "supported2" if both are received
  2730. else if (((ExtensionName == SFTP_EXT_SUPPORTED) && !FSupport->Loaded) ||
  2731. (ExtensionName == SFTP_EXT_SUPPORTED2))
  2732. {
  2733. FSupport->Reset();
  2734. TSFTPPacket SupportedStruct(ExtensionData);
  2735. FSupport->Loaded = true;
  2736. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2737. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2738. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2739. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2740. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2741. if (ExtensionName == SFTP_EXT_SUPPORTED)
  2742. {
  2743. while (SupportedStruct.GetNextData() != NULL)
  2744. {
  2745. FSupport->Extensions->Add(SupportedStruct.GetAnsiString());
  2746. }
  2747. }
  2748. else
  2749. {
  2750. // note that supported-open-block-vector, supported-block-vector,
  2751. // attrib-extension-count and attrib-extension-names fields
  2752. // were added only in rev 08, while "supported2" was defined in rev 07
  2753. FSupport->OpenBlockVector = SupportedStruct.GetSmallCardinal();
  2754. FSupport->BlockVector = SupportedStruct.GetSmallCardinal();
  2755. unsigned int ExtensionCount;
  2756. ExtensionCount = SupportedStruct.GetCardinal();
  2757. for (unsigned int i = 0; i < ExtensionCount; i++)
  2758. {
  2759. FSupport->AttribExtensions->Add(SupportedStruct.GetAnsiString());
  2760. }
  2761. ExtensionCount = SupportedStruct.GetCardinal();
  2762. for (unsigned int i = 0; i < ExtensionCount; i++)
  2763. {
  2764. FSupport->Extensions->Add(SupportedStruct.GetAnsiString());
  2765. }
  2766. }
  2767. if (FTerminal->Log->Logging)
  2768. {
  2769. FTerminal->LogEvent(FORMAT(
  2770. L"Server support information (%s):\n"
  2771. " Attribute mask: %x, Attribute bits: %x, Open flags: %x\n"
  2772. " Access mask: %x, Open block vector: %x, Block vector: %x, Max read size: %d\n",
  2773. (ExtensionName,
  2774. int(FSupport->AttributeMask),
  2775. int(FSupport->AttributeBits),
  2776. int(FSupport->OpenFlags),
  2777. int(FSupport->AccessMask),
  2778. int(FSupport->OpenBlockVector),
  2779. int(FSupport->BlockVector),
  2780. int(FSupport->MaxReadSize))));
  2781. FTerminal->LogEvent(FORMAT(L" Attribute extensions (%d)\n", (FSupport->AttribExtensions->Count)));
  2782. for (int Index = 0; Index < FSupport->AttribExtensions->Count; Index++)
  2783. {
  2784. FTerminal->LogEvent(
  2785. FORMAT(L" %s", (FSupport->AttribExtensions->Strings[Index])));
  2786. }
  2787. FTerminal->LogEvent(FORMAT(L" Extensions (%d)\n", (FSupport->Extensions->Count)));
  2788. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2789. {
  2790. FTerminal->LogEvent(
  2791. FORMAT(L" %s", (FSupport->Extensions->Strings[Index])));
  2792. }
  2793. }
  2794. }
  2795. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2796. {
  2797. TSFTPPacket VendorIdStruct(ExtensionData);
  2798. UnicodeString VendorName(VendorIdStruct.GetAnsiString());
  2799. UnicodeString ProductName(VendorIdStruct.GetAnsiString());
  2800. UnicodeString ProductVersion(VendorIdStruct.GetAnsiString());
  2801. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2802. FTerminal->LogEvent(FORMAT(L"Server software: %s %s (%d) by %s",
  2803. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2804. }
  2805. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2806. {
  2807. FTerminal->LogEvent(L"File system roots:\n");
  2808. DebugAssert(FFixedPaths == NULL);
  2809. FFixedPaths = new TStringList();
  2810. try
  2811. {
  2812. TSFTPPacket RootsPacket(ExtensionData);
  2813. while (RootsPacket.GetNextData() != NULL)
  2814. {
  2815. unsigned long Dummy = RootsPacket.GetCardinal();
  2816. if (Dummy != 1)
  2817. {
  2818. break;
  2819. }
  2820. else
  2821. {
  2822. unsigned char Drive = RootsPacket.GetByte();
  2823. unsigned char MaybeType = RootsPacket.GetByte();
  2824. FTerminal->LogEvent(FORMAT(L" %s: (type %d)", (static_cast<char>(Drive), (int)MaybeType)));
  2825. FFixedPaths->Add(FORMAT(L"%s:", (static_cast<char>(Drive))));
  2826. }
  2827. }
  2828. }
  2829. catch(Exception & E)
  2830. {
  2831. FFixedPaths->Clear();
  2832. FTerminal->LogEvent(FORMAT(L"Failed to decode %s extension",
  2833. (SFTP_EXT_FSROOTS)));
  2834. FTerminal->HandleException(&E);
  2835. }
  2836. }
  2837. else if (ExtensionName == SFTP_EXT_VERSIONS)
  2838. {
  2839. // first try legacy decoding according to incorrect encoding
  2840. // (structure-like) as of VShell (bug no longer present as of 4.0.3).
  2841. TSFTPPacket VersionsPacket(ExtensionData);
  2842. unsigned int StringSize;
  2843. if (VersionsPacket.CanGetString(StringSize) &&
  2844. (StringSize == VersionsPacket.RemainingLength))
  2845. {
  2846. UnicodeString Versions = VersionsPacket.GetAnsiString();
  2847. FTerminal->LogEvent(FORMAT(L"SFTP versions supported by the server (VShell format): %s",
  2848. (Versions)));
  2849. }
  2850. else
  2851. {
  2852. // if that fails, fallback to proper decoding
  2853. FTerminal->LogEvent(FORMAT(L"SFTP versions supported by the server: %s",
  2854. (AnsiToString(ExtensionData))));
  2855. }
  2856. }
  2857. else if (ExtensionName == SFTP_EXT_STATVFS)
  2858. {
  2859. UnicodeString StatVfsVersion = AnsiToString(ExtensionData);
  2860. if (StatVfsVersion == SFTP_EXT_STATVFS_VALUE_V2)
  2861. {
  2862. FSupportsStatVfsV2 = true;
  2863. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2864. }
  2865. else
  2866. {
  2867. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2868. }
  2869. }
  2870. else if (ExtensionName == SFTP_EXT_HARDLINK)
  2871. {
  2872. UnicodeString HardlinkVersion = AnsiToString(ExtensionData);
  2873. if (HardlinkVersion == SFTP_EXT_HARDLINK_VALUE_V1)
  2874. {
  2875. FSupportsHardlink = true;
  2876. FTerminal->LogEvent(FORMAT(L"Supports %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2877. }
  2878. else
  2879. {
  2880. FTerminal->LogEvent(FORMAT(L"Unsupported %s extension version %s", (ExtensionName, ExtensionDisplayData)));
  2881. }
  2882. }
  2883. else
  2884. {
  2885. FTerminal->LogEvent(FORMAT(L"Unknown server extension %s=%s",
  2886. (ExtensionName, ExtensionDisplayData)));
  2887. }
  2888. FExtensions->Values[ExtensionName] = ExtensionDisplayData;
  2889. }
  2890. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  2891. {
  2892. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  2893. Packet.AddString(SFTP_EXT_VENDOR_ID);
  2894. Packet.AddString(FTerminal->Configuration->CompanyName);
  2895. Packet.AddString(FTerminal->Configuration->ProductName);
  2896. Packet.AddString(FTerminal->Configuration->ProductVersion);
  2897. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  2898. SendPacket(&Packet);
  2899. // we are not interested in the response, do not wait for it
  2900. ReceiveResponse(&Packet, &Packet);
  2901. //ReserveResponse(&Packet, NULL);
  2902. }
  2903. }
  2904. if (FVersion < 4)
  2905. {
  2906. // currently enable the bug for all servers (really known on OpenSSH)
  2907. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  2908. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  2909. if (FSignedTS)
  2910. {
  2911. FTerminal->LogEvent(L"We believe the server has signed timestamps bug");
  2912. }
  2913. }
  2914. else
  2915. {
  2916. FSignedTS = false;
  2917. }
  2918. switch (FTerminal->SessionData->NotUtf)
  2919. {
  2920. case asOff:
  2921. FUtfStrings = asOn;
  2922. FTerminal->LogEvent(L"We will use UTF-8 strings as configured");
  2923. break;
  2924. default:
  2925. FAIL;
  2926. case asAuto:
  2927. // Nb, Foxit server does not exist anymore
  2928. if (GetSessionInfo().SshImplementation.Pos(L"Foxit-WAC-Server") == 1)
  2929. {
  2930. FUtfStrings = asOff;
  2931. FTerminal->LogEvent(L"We will not use UTF-8 strings as the server is known not to use them");
  2932. }
  2933. else
  2934. {
  2935. if (FVersion >= 4)
  2936. {
  2937. FTerminal->LogEvent(L"We will use UTF-8 strings as it is mandatory with SFTP version 4 and newer");
  2938. FUtfStrings = asOn;
  2939. }
  2940. else
  2941. {
  2942. 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");
  2943. FUtfStrings = asAuto;
  2944. FUtfDisablingAnnounced = false;
  2945. }
  2946. }
  2947. break;
  2948. case asOn:
  2949. FTerminal->LogEvent(L"We will not use UTF-8 strings as configured");
  2950. FUtfStrings = asOff;
  2951. break;
  2952. }
  2953. FMaxPacketSize = FTerminal->SessionData->SFTPMaxPacketSize;
  2954. if (FMaxPacketSize == 0)
  2955. {
  2956. if ((FSecureShell->SshImplementation == sshiOpenSSH) && (FVersion == 3) && !FSupport->Loaded)
  2957. {
  2958. FMaxPacketSize = 4 + (256 * 1024); // len + 256kB payload
  2959. FTerminal->LogEvent(FORMAT(L"Limiting packet size to OpenSSH sftp-server limit of %d bytes",
  2960. (int(FMaxPacketSize))));
  2961. }
  2962. // full string is "1.77 sshlib: Momentum SSH Server",
  2963. // possibly it is sshlib-related
  2964. else if (GetSessionInfo().SshImplementation.Pos(L"Momentum SSH Server") != 0)
  2965. {
  2966. FMaxPacketSize = 4 + (32 * 1024);
  2967. FTerminal->LogEvent(FORMAT(L"Limiting packet size to Momentum sftp-server limit of %d bytes",
  2968. (int(FMaxPacketSize))));
  2969. }
  2970. }
  2971. }
  2972. //---------------------------------------------------------------------------
  2973. char * __fastcall TSFTPFileSystem::GetEOL() const
  2974. {
  2975. if (FVersion >= 4)
  2976. {
  2977. DebugAssert(!FEOL.IsEmpty());
  2978. return FEOL.c_str();
  2979. }
  2980. else
  2981. {
  2982. return EOLToStr(FTerminal->SessionData->EOLType);
  2983. }
  2984. }
  2985. //---------------------------------------------------------------------------
  2986. void __fastcall TSFTPFileSystem::LookupUsersGroups()
  2987. {
  2988. DebugAssert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
  2989. TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
  2990. TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
  2991. TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
  2992. TRemoteTokenList * Lists[] = { &FTerminal->FUsers, &FTerminal->FGroups };
  2993. wchar_t ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
  2994. for (size_t Index = 0; Index < LENOF(Packets); Index++)
  2995. {
  2996. TSFTPPacket * Packet = Packets[Index];
  2997. Packet->AddString(SFTP_EXT_OWNER_GROUP);
  2998. Packet->AddByte(ListTypes[Index]);
  2999. SendPacket(Packet);
  3000. ReserveResponse(Packet, Packet);
  3001. }
  3002. for (size_t Index = 0; Index < LENOF(Packets); Index++)
  3003. {
  3004. TSFTPPacket * Packet = Packets[Index];
  3005. ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
  3006. if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
  3007. (Packet->GetAnsiString() != SFTP_EXT_OWNER_GROUP_REPLY))
  3008. {
  3009. FTerminal->LogEvent(FORMAT(L"Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
  3010. }
  3011. else
  3012. {
  3013. TRemoteTokenList & List = *Lists[Index];
  3014. unsigned long Count = Packet->GetCardinal();
  3015. List.Clear();
  3016. for (unsigned long Item = 0; Item < Count; Item++)
  3017. {
  3018. TRemoteToken Token(Packet->GetString(FUtfStrings));
  3019. List.Add(Token);
  3020. if (&List == &FTerminal->FGroups)
  3021. {
  3022. FTerminal->FMembership.Add(Token);
  3023. }
  3024. }
  3025. }
  3026. }
  3027. }
  3028. //---------------------------------------------------------------------------
  3029. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  3030. {
  3031. if (!FDirectoryToChangeTo.IsEmpty())
  3032. {
  3033. FCurrentDirectory = FDirectoryToChangeTo;
  3034. FDirectoryToChangeTo = L"";
  3035. }
  3036. else if (FCurrentDirectory.IsEmpty())
  3037. {
  3038. // this happens only after startup when default remote directory is not specified
  3039. FCurrentDirectory = GetHomeDirectory();
  3040. }
  3041. }
  3042. //---------------------------------------------------------------------------
  3043. void __fastcall TSFTPFileSystem::HomeDirectory()
  3044. {
  3045. ChangeDirectory(GetHomeDirectory());
  3046. }
  3047. //---------------------------------------------------------------------------
  3048. void __fastcall TSFTPFileSystem::TryOpenDirectory(const UnicodeString Directory)
  3049. {
  3050. FTerminal->LogEvent(FORMAT(L"Trying to open directory \"%s\".", (Directory)));
  3051. TRemoteFile * File;
  3052. CustomReadFile(Directory, File, SSH_FXP_LSTAT, NULL, asOpUnsupported);
  3053. if (File == NULL)
  3054. {
  3055. // File can be NULL only when server does not support SSH_FXP_LSTAT.
  3056. // Fallback to legacy solution, which in turn does not allow entering
  3057. // traverse-only (chmod 110) directories.
  3058. // This is workaround for http://www.ftpshell.com/
  3059. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  3060. Packet.AddPathString(UnixExcludeTrailingBackslash(Directory), FUtfStrings);
  3061. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3062. RawByteString Handle = Packet.GetFileHandle();
  3063. Packet.ChangeType(SSH_FXP_CLOSE);
  3064. Packet.AddString(Handle);
  3065. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  3066. }
  3067. else
  3068. {
  3069. delete File;
  3070. }
  3071. }
  3072. //---------------------------------------------------------------------------
  3073. void __fastcall TSFTPFileSystem::AnnounceFileListOperation()
  3074. {
  3075. }
  3076. //---------------------------------------------------------------------------
  3077. void __fastcall TSFTPFileSystem::ChangeDirectory(const UnicodeString Directory)
  3078. {
  3079. UnicodeString Path, Current;
  3080. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  3081. Path = RealPath(Directory, Current);
  3082. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  3083. // for invalid paths on some systems, like CygWin)
  3084. TryOpenDirectory(Path);
  3085. // if open dir did not fail, directory exists -> success.
  3086. FDirectoryToChangeTo = Path;
  3087. }
  3088. //---------------------------------------------------------------------------
  3089. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  3090. {
  3091. FDirectoryToChangeTo = UnixExcludeTrailingBackslash(Directory);
  3092. }
  3093. //---------------------------------------------------------------------------
  3094. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  3095. {
  3096. DebugAssert(FileList && !FileList->Directory.IsEmpty());
  3097. UnicodeString Directory;
  3098. Directory = UnixExcludeTrailingBackslash(LocalCanonify(FileList->Directory));
  3099. FTerminal->LogEvent(FORMAT(L"Listing directory \"%s\".", (Directory)));
  3100. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  3101. // old data (e.g. parent directory) when reading fails
  3102. FileList->Reset();
  3103. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  3104. RawByteString Handle;
  3105. try
  3106. {
  3107. Packet.AddPathString(Directory, FUtfStrings);
  3108. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  3109. Handle = Packet.GetFileHandle();
  3110. }
  3111. catch(...)
  3112. {
  3113. if (FTerminal->Active)
  3114. {
  3115. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  3116. }
  3117. throw;
  3118. }
  3119. TSFTPPacket Response;
  3120. try
  3121. {
  3122. bool isEOF = false;
  3123. int Total = 0;
  3124. bool HasParentDirectory = false;
  3125. TRemoteFile * File;
  3126. Packet.ChangeType(SSH_FXP_READDIR);
  3127. Packet.AddString(Handle);
  3128. SendPacket(&Packet);
  3129. do
  3130. {
  3131. ReceiveResponse(&Packet, &Response);
  3132. if (Response.Type == SSH_FXP_NAME)
  3133. {
  3134. TSFTPPacket ListingPacket = Response;
  3135. Packet.ChangeType(SSH_FXP_READDIR);
  3136. Packet.AddString(Handle);
  3137. SendPacket(&Packet);
  3138. ReserveResponse(&Packet, &Response);
  3139. unsigned int Count = ListingPacket.GetCardinal();
  3140. int ResolvedLinks = 0;
  3141. for (unsigned long Index = 0; !isEOF && (Index < Count); Index++)
  3142. {
  3143. File = LoadFile(&ListingPacket, NULL, L"", FileList);
  3144. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  3145. {
  3146. FTerminal->LogEvent(FORMAT(L"Read file '%s' from listing", (File->FileName)));
  3147. }
  3148. if (File->LinkedFile != NULL)
  3149. {
  3150. ResolvedLinks++;
  3151. }
  3152. if (File->IsParentDirectory)
  3153. {
  3154. HasParentDirectory = true;
  3155. }
  3156. FileList->AddFile(File);
  3157. Total++;
  3158. if (Total % 10 == 0)
  3159. {
  3160. FTerminal->DoReadDirectoryProgress(Total, ResolvedLinks, isEOF);
  3161. if (isEOF)
  3162. {
  3163. FTerminal->DoReadDirectoryProgress(-2, 0, isEOF);
  3164. }
  3165. }
  3166. }
  3167. if ((FVersion >= 6) &&
  3168. // As of 7.0.9 the Cerberus SFTP server always sets the end-of-list to true.
  3169. (FSecureShell->SshImplementation != sshiCerberus) &&
  3170. ListingPacket.CanGetBool())
  3171. {
  3172. isEOF = ListingPacket.GetBool();
  3173. }
  3174. if (Count == 0)
  3175. {
  3176. FTerminal->LogEvent(L"Empty directory listing packet. Aborting directory reading.");
  3177. isEOF = true;
  3178. }
  3179. }
  3180. else if (Response.Type == SSH_FXP_STATUS)
  3181. {
  3182. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  3183. }
  3184. else
  3185. {
  3186. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  3187. }
  3188. }
  3189. while (!isEOF);
  3190. if (Total == 0)
  3191. {
  3192. bool Failure = false;
  3193. // no point reading parent of root directory,
  3194. // moreover CompleteFTP terminates session upon attempt to do so
  3195. if (IsUnixRootPath(FileList->Directory))
  3196. {
  3197. File = NULL;
  3198. }
  3199. else
  3200. {
  3201. // Empty file list -> probably "permission denied", we
  3202. // at least get link to parent directory ("..")
  3203. try
  3204. {
  3205. FTerminal->ExceptionOnFail = true;
  3206. try
  3207. {
  3208. File = NULL;
  3209. FTerminal->ReadFile(
  3210. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  3211. }
  3212. __finally
  3213. {
  3214. FTerminal->ExceptionOnFail = false;
  3215. }
  3216. }
  3217. catch(Exception &E)
  3218. {
  3219. if (E.InheritsFrom(__classid(EFatal)))
  3220. {
  3221. throw;
  3222. }
  3223. else
  3224. {
  3225. File = NULL;
  3226. Failure = true;
  3227. }
  3228. }
  3229. }
  3230. // on some systems even getting ".." fails, we create dummy ".." instead
  3231. if (File == NULL)
  3232. {
  3233. File = new TRemoteParentDirectory(FTerminal);
  3234. }
  3235. DebugAssert(File && File->IsParentDirectory);
  3236. FileList->AddFile(File);
  3237. if (Failure)
  3238. {
  3239. throw ExtException(
  3240. NULL, FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)),
  3241. HELP_EMPTY_DIRECTORY);
  3242. }
  3243. }
  3244. else
  3245. {
  3246. if (!HasParentDirectory)
  3247. {
  3248. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  3249. }
  3250. }
  3251. }
  3252. __finally
  3253. {
  3254. if (FTerminal->Active)
  3255. {
  3256. Packet.ChangeType(SSH_FXP_CLOSE);
  3257. Packet.AddString(Handle);
  3258. SendPacket(&Packet);
  3259. // we are not interested in the response, do not wait for it
  3260. ReserveResponse(&Packet, NULL);
  3261. }
  3262. }
  3263. }
  3264. //---------------------------------------------------------------------------
  3265. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  3266. TRemoteFile *& File)
  3267. {
  3268. DebugAssert(SymlinkFile && SymlinkFile->IsSymLink);
  3269. DebugAssert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  3270. // need to use full filename when resolving links within subdirectory
  3271. // (i.e. for download)
  3272. UnicodeString FileName = LocalCanonify(
  3273. SymlinkFile->Directory != NULL ? SymlinkFile->FullFileName : SymlinkFile->FileName);
  3274. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  3275. ReadLinkPacket.AddPathString(FileName, FUtfStrings);
  3276. SendPacket(&ReadLinkPacket);
  3277. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  3278. // send second request before reading response to first one
  3279. // (performance benefit)
  3280. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  3281. AttrsPacket.AddPathString(FileName, FUtfStrings);
  3282. if (FVersion >= 4)
  3283. {
  3284. AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
  3285. }
  3286. SendPacket(&AttrsPacket);
  3287. ReserveResponse(&AttrsPacket, &AttrsPacket);
  3288. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  3289. if (ReadLinkPacket.GetCardinal() != 1)
  3290. {
  3291. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  3292. }
  3293. SymlinkFile->LinkTo = ReadLinkPacket.GetPathString(FUtfStrings);
  3294. FTerminal->LogEvent(FORMAT(L"Link resolved to \"%s\".", (SymlinkFile->LinkTo)));
  3295. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  3296. // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
  3297. File = LoadFile(&AttrsPacket, SymlinkFile,
  3298. UnixExtractFileName(SymlinkFile->LinkTo));
  3299. }
  3300. //---------------------------------------------------------------------------
  3301. void __fastcall TSFTPFileSystem::ReadFile(const UnicodeString FileName,
  3302. TRemoteFile *& File)
  3303. {
  3304. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  3305. }
  3306. //---------------------------------------------------------------------------
  3307. bool __fastcall TSFTPFileSystem::RemoteFileExists(const UnicodeString FullPath,
  3308. TRemoteFile ** File)
  3309. {
  3310. bool Result;
  3311. try
  3312. {
  3313. TRemoteFile * AFile;
  3314. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, asNoSuchFile);
  3315. Result = (AFile != NULL);
  3316. if (Result)
  3317. {
  3318. if (File)
  3319. {
  3320. *File = AFile;
  3321. }
  3322. else
  3323. {
  3324. delete AFile;
  3325. }
  3326. }
  3327. }
  3328. catch(...)
  3329. {
  3330. if (!FTerminal->Active)
  3331. {
  3332. throw;
  3333. }
  3334. Result = false;
  3335. }
  3336. return Result;
  3337. }
  3338. //---------------------------------------------------------------------------
  3339. void __fastcall TSFTPFileSystem::SendCustomReadFile(TSFTPPacket * Packet,
  3340. TSFTPPacket * Response, unsigned long Flags)
  3341. {
  3342. if (FVersion >= 4)
  3343. {
  3344. Packet->AddCardinal(Flags);
  3345. }
  3346. SendPacket(Packet);
  3347. ReserveResponse(Packet, Response);
  3348. }
  3349. //---------------------------------------------------------------------------
  3350. void __fastcall TSFTPFileSystem::CustomReadFile(const UnicodeString FileName,
  3351. TRemoteFile *& File, unsigned char Type, TRemoteFile * ALinkedByFile,
  3352. int AllowStatus)
  3353. {
  3354. unsigned long Flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  3355. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  3356. SSH_FILEXFER_ATTR_OWNERGROUP;
  3357. TSFTPPacket Packet(Type);
  3358. Packet.AddPathString(LocalCanonify(FileName), FUtfStrings);
  3359. SendCustomReadFile(&Packet, &Packet, Flags);
  3360. ReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS, AllowStatus);
  3361. if (Packet.Type == SSH_FXP_ATTRS)
  3362. {
  3363. File = LoadFile(&Packet, ALinkedByFile, UnixExtractFileName(FileName));
  3364. }
  3365. else
  3366. {
  3367. DebugAssert(AllowStatus > 0);
  3368. File = NULL;
  3369. }
  3370. }
  3371. //---------------------------------------------------------------------------
  3372. void __fastcall TSFTPFileSystem::DoDeleteFile(const UnicodeString FileName, unsigned char Type)
  3373. {
  3374. TSFTPPacket Packet(Type);
  3375. UnicodeString RealFileName = LocalCanonify(FileName);
  3376. Packet.AddPathString(RealFileName, FUtfStrings);
  3377. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3378. }
  3379. //---------------------------------------------------------------------------
  3380. void __fastcall TSFTPFileSystem::DeleteFile(const UnicodeString FileName,
  3381. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  3382. {
  3383. unsigned char Type;
  3384. if (File && File->IsDirectory && !File->IsSymLink)
  3385. {
  3386. if (FLAGCLEAR(Params, dfNoRecursive))
  3387. {
  3388. try
  3389. {
  3390. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Params);
  3391. }
  3392. catch(...)
  3393. {
  3394. Action.Cancel();
  3395. throw;
  3396. }
  3397. }
  3398. Type = SSH_FXP_RMDIR;
  3399. }
  3400. else
  3401. {
  3402. Type = SSH_FXP_REMOVE;
  3403. }
  3404. DoDeleteFile(FileName, Type);
  3405. }
  3406. //---------------------------------------------------------------------------
  3407. void __fastcall TSFTPFileSystem::RenameFile(const UnicodeString FileName,
  3408. const UnicodeString NewName)
  3409. {
  3410. TSFTPPacket Packet(SSH_FXP_RENAME);
  3411. UnicodeString RealName = LocalCanonify(FileName);
  3412. Packet.AddPathString(RealName, FUtfStrings);
  3413. UnicodeString TargetName;
  3414. if (UnixExtractFilePath(NewName).IsEmpty())
  3415. {
  3416. // rename case (TTerminal::RenameFile)
  3417. TargetName = UnixExtractFilePath(RealName) + NewName;
  3418. }
  3419. else
  3420. {
  3421. TargetName = LocalCanonify(NewName);
  3422. }
  3423. Packet.AddPathString(TargetName, FUtfStrings);
  3424. if (FVersion >= 5)
  3425. {
  3426. Packet.AddCardinal(0);
  3427. }
  3428. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3429. }
  3430. //---------------------------------------------------------------------------
  3431. void __fastcall TSFTPFileSystem::CopyFile(const UnicodeString FileName,
  3432. const UnicodeString NewName)
  3433. {
  3434. // Implemented by ProFTPD/mod_sftp and Bitvise WinSSHD (without announcing it)
  3435. DebugAssert(SupportsExtension(SFTP_EXT_COPY_FILE) || (FSecureShell->SshImplementation == sshiBitvise));
  3436. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3437. Packet.AddString(SFTP_EXT_COPY_FILE);
  3438. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  3439. Packet.AddPathString(Canonify(NewName), FUtfStrings);
  3440. Packet.AddBool(false);
  3441. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3442. }
  3443. //---------------------------------------------------------------------------
  3444. void __fastcall TSFTPFileSystem::CreateDirectory(const UnicodeString DirName)
  3445. {
  3446. TSFTPPacket Packet(SSH_FXP_MKDIR);
  3447. UnicodeString CanonifiedName = Canonify(DirName);
  3448. Packet.AddPathString(CanonifiedName, FUtfStrings);
  3449. Packet.AddProperties(NULL, 0, true, FVersion, FUtfStrings, NULL);
  3450. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3451. }
  3452. //---------------------------------------------------------------------------
  3453. void __fastcall TSFTPFileSystem::CreateLink(const UnicodeString FileName,
  3454. const UnicodeString PointTo, bool Symbolic)
  3455. {
  3456. // Cerberus server does not even response to LINK or SYMLINK,
  3457. // Although its log says:
  3458. // Unrecognized SFTP client command: (20)
  3459. // Unknown SFTP packet - Sending Unsupported OP response
  3460. DebugAssert(FVersion >= 3); // links are supported with SFTP version 3 and later
  3461. bool UseLink = (FVersion >= 6);
  3462. bool UseHardlink = !Symbolic && !UseLink && FSupportsHardlink;
  3463. TSFTPPacket Packet(UseHardlink ? SSH_FXP_EXTENDED : (UseLink ? SSH_FXP_LINK : SSH_FXP_SYMLINK));
  3464. if (UseHardlink)
  3465. {
  3466. Packet.AddString(SFTP_EXT_HARDLINK);
  3467. }
  3468. bool Buggy;
  3469. // OpenSSH hardlink extension always uses the "wrong" order
  3470. // as it's defined as such to mimic OpenSSH symlink bug
  3471. if (UseHardlink)
  3472. {
  3473. Buggy = true; //sic
  3474. }
  3475. else
  3476. {
  3477. if (FTerminal->SessionData->SFTPBug[sbSymlink] == asOn)
  3478. {
  3479. Buggy = true;
  3480. FTerminal->LogEvent(L"Forcing workaround for SFTP link bug");
  3481. }
  3482. else if (FTerminal->SessionData->SFTPBug[sbSymlink] == asOff)
  3483. {
  3484. Buggy = false;
  3485. }
  3486. else
  3487. {
  3488. if (UseLink)
  3489. {
  3490. if (FSecureShell->SshImplementation == sshiProFTPD)
  3491. {
  3492. // ProFTPD/mod_sftp followed OpenSSH symlink bug even for link implementation.
  3493. // This will be fixed with the next release with
  3494. // SSH version string bumbed to "mod_sftp/1.0.0"
  3495. // http://bugs.proftpd.org/show_bug.cgi?id=4080
  3496. UnicodeString ProFTPDVerStr = GetSessionInfo().SshImplementation;
  3497. CutToChar(ProFTPDVerStr, L'/', false);
  3498. int ProFTPDMajorVer = StrToIntDef(CutToChar(ProFTPDVerStr, L'.', false), 0);
  3499. Buggy = (ProFTPDMajorVer == 0);
  3500. if (Buggy)
  3501. {
  3502. FTerminal->LogEvent(L"We believe the server has SFTP link bug");
  3503. }
  3504. }
  3505. else
  3506. {
  3507. Buggy = false;
  3508. }
  3509. }
  3510. else
  3511. {
  3512. // ProFTPD/mod_sftp deliberately follows OpenSSH bug.
  3513. // Though we should get here with ProFTPD only when user forced
  3514. // SFTP version < 6 or when connecting to an ancient version of ProFTPD.
  3515. Buggy =
  3516. (FSecureShell->SshImplementation == sshiOpenSSH) ||
  3517. (FSecureShell->SshImplementation == sshiProFTPD);
  3518. if (Buggy)
  3519. {
  3520. FTerminal->LogEvent(L"We believe the server has SFTP symlink bug");
  3521. }
  3522. }
  3523. }
  3524. }
  3525. UnicodeString FinalPointTo = PointTo;
  3526. UnicodeString FinalFileName = Canonify(FileName);
  3527. if (!Symbolic)
  3528. {
  3529. FinalPointTo = Canonify(PointTo);
  3530. }
  3531. if (!Buggy)
  3532. {
  3533. Packet.AddPathString(FinalFileName, FUtfStrings);
  3534. Packet.AddPathString(FinalPointTo, FUtfStrings);
  3535. }
  3536. else
  3537. {
  3538. Packet.AddPathString(FinalPointTo, FUtfStrings);
  3539. Packet.AddPathString(FinalFileName, FUtfStrings);
  3540. }
  3541. if (UseLink)
  3542. {
  3543. Packet.AddBool(Symbolic);
  3544. }
  3545. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3546. }
  3547. //---------------------------------------------------------------------------
  3548. void __fastcall TSFTPFileSystem::ChangeFileProperties(const UnicodeString FileName,
  3549. const TRemoteFile * /*File*/, const TRemoteProperties * AProperties,
  3550. TChmodSessionAction & Action)
  3551. {
  3552. DebugAssert(AProperties != NULL);
  3553. TRemoteFile * File;
  3554. UnicodeString RealFileName = LocalCanonify(FileName);
  3555. ReadFile(RealFileName, File);
  3556. try
  3557. {
  3558. DebugAssert(File);
  3559. if (File->IsDirectory && !File->IsSymLink && AProperties->Recursive)
  3560. {
  3561. try
  3562. {
  3563. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  3564. (void*)AProperties);
  3565. }
  3566. catch(...)
  3567. {
  3568. Action.Cancel();
  3569. throw;
  3570. }
  3571. }
  3572. // SFTP can change owner and group at the same time only, not individually.
  3573. // Fortunately we know current owner/group, so if only one is present,
  3574. // we can supplement the other.
  3575. TRemoteProperties Properties(*AProperties);
  3576. if (Properties.Valid.Contains(vpGroup) &&
  3577. !Properties.Valid.Contains(vpOwner))
  3578. {
  3579. Properties.Owner = File->Owner;
  3580. Properties.Valid << vpOwner;
  3581. }
  3582. else if (Properties.Valid.Contains(vpOwner) &&
  3583. !Properties.Valid.Contains(vpGroup))
  3584. {
  3585. Properties.Group = File->Group;
  3586. Properties.Valid << vpGroup;
  3587. }
  3588. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  3589. Packet.AddPathString(RealFileName, FUtfStrings);
  3590. Packet.AddProperties(&Properties, *File->Rights, File->IsDirectory, FVersion, FUtfStrings, &Action);
  3591. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3592. }
  3593. __finally
  3594. {
  3595. delete File;
  3596. }
  3597. }
  3598. //---------------------------------------------------------------------------
  3599. bool __fastcall TSFTPFileSystem::LoadFilesProperties(TStrings * FileList)
  3600. {
  3601. bool Result = false;
  3602. // without knowledge of server's capabilities, this all make no sense
  3603. if (FSupport->Loaded || (FSecureShell->SshImplementation == sshiBitvise))
  3604. {
  3605. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  3606. Progress.Start(foGetProperties, osRemote, FileList->Count);
  3607. FTerminal->FOperationProgress = &Progress;
  3608. static int LoadFilesPropertiesQueueLen = 5;
  3609. TSFTPLoadFilesPropertiesQueue Queue(this);
  3610. try
  3611. {
  3612. if (Queue.Init(LoadFilesPropertiesQueueLen, FileList))
  3613. {
  3614. TRemoteFile * File;
  3615. TSFTPPacket Packet;
  3616. bool Next;
  3617. do
  3618. {
  3619. Next = Queue.ReceivePacket(&Packet, File);
  3620. DebugAssert((Packet.Type == SSH_FXP_ATTRS) || (Packet.Type == SSH_FXP_STATUS));
  3621. if (Packet.Type == SSH_FXP_ATTRS)
  3622. {
  3623. DebugAssert(File != NULL);
  3624. Progress.SetFile(File->FileName);
  3625. LoadFile(File, &Packet);
  3626. Result = true;
  3627. TOnceDoneOperation OnceDoneOperation;
  3628. Progress.Finish(File->FileName, true, OnceDoneOperation);
  3629. }
  3630. if (Progress.Cancel != csContinue)
  3631. {
  3632. Next = false;
  3633. }
  3634. }
  3635. while (Next);
  3636. }
  3637. }
  3638. __finally
  3639. {
  3640. Queue.DisposeSafe();
  3641. FTerminal->FOperationProgress = NULL;
  3642. Progress.Stop();
  3643. }
  3644. // queue is discarded here
  3645. }
  3646. return Result;
  3647. }
  3648. //---------------------------------------------------------------------------
  3649. void __fastcall TSFTPFileSystem::DoCalculateFilesChecksum(
  3650. const UnicodeString & Alg, const UnicodeString & SftpAlg,
  3651. TStrings * FileList, TStrings * Checksums,
  3652. TCalculatedChecksumEvent OnCalculatedChecksum,
  3653. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  3654. {
  3655. TOnceDoneOperation OnceDoneOperation; // not used
  3656. // recurse into subdirectories only if we have callback function
  3657. if (OnCalculatedChecksum != NULL)
  3658. {
  3659. for (int Index = 0; Index < FileList->Count; Index++)
  3660. {
  3661. TRemoteFile * File = (TRemoteFile *)FileList->Objects[Index];
  3662. DebugAssert(File != NULL);
  3663. if (File->IsDirectory && !File->IsSymLink &&
  3664. !File->IsParentDirectory && !File->IsThisDirectory)
  3665. {
  3666. OperationProgress->SetFile(File->FileName);
  3667. TRemoteFileList * SubFiles =
  3668. FTerminal->CustomReadDirectoryListing(File->FullFileName, false);
  3669. if (SubFiles != NULL)
  3670. {
  3671. TStrings * SubFileList = new TStringList();
  3672. bool Success = false;
  3673. try
  3674. {
  3675. OperationProgress->SetFile(File->FileName);
  3676. for (int Index = 0; Index < SubFiles->Count; Index++)
  3677. {
  3678. TRemoteFile * SubFile = SubFiles->Files[Index];
  3679. SubFileList->AddObject(SubFile->FullFileName, SubFile);
  3680. }
  3681. // do not collect checksums for files in subdirectories,
  3682. // only send back checksums via callback
  3683. DoCalculateFilesChecksum(Alg, SftpAlg, SubFileList, NULL,
  3684. OnCalculatedChecksum, OperationProgress, false);
  3685. Success = true;
  3686. }
  3687. __finally
  3688. {
  3689. delete SubFiles;
  3690. delete SubFileList;
  3691. if (FirstLevel)
  3692. {
  3693. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  3694. }
  3695. }
  3696. }
  3697. }
  3698. }
  3699. }
  3700. static int CalculateFilesChecksumQueueLen = 5;
  3701. TSFTPCalculateFilesChecksumQueue Queue(this);
  3702. try
  3703. {
  3704. if (Queue.Init(CalculateFilesChecksumQueueLen, SftpAlg, FileList))
  3705. {
  3706. TSFTPPacket Packet;
  3707. bool Next;
  3708. do
  3709. {
  3710. bool Success = false;
  3711. UnicodeString Checksum;
  3712. TRemoteFile * File = NULL;
  3713. try
  3714. {
  3715. TChecksumSessionAction Action(FTerminal->ActionLog);
  3716. try
  3717. {
  3718. Next = Queue.ReceivePacket(&Packet, File);
  3719. DebugAssert(Packet.Type == SSH_FXP_EXTENDED_REPLY);
  3720. OperationProgress->SetFile(File->FileName);
  3721. Action.FileName(FTerminal->AbsolutePath(File->FullFileName, true));
  3722. // skip alg
  3723. Packet.GetAnsiString();
  3724. Checksum = BytesToHex(reinterpret_cast<const unsigned char*>(Packet.GetNextData(Packet.RemainingLength)), Packet.RemainingLength, false);
  3725. if (OnCalculatedChecksum != NULL)
  3726. {
  3727. OnCalculatedChecksum(File->FileName, Alg, Checksum);
  3728. }
  3729. Action.Checksum(Alg, Checksum);
  3730. Success = true;
  3731. }
  3732. catch (Exception & E)
  3733. {
  3734. FTerminal->RollbackAction(Action, OperationProgress, &E);
  3735. // Error formatting expanded from inline to avoid strange exceptions
  3736. UnicodeString Error =
  3737. FMTLOAD(CHECKSUM_ERROR,
  3738. (File != NULL ? File->FullFileName : UnicodeString(L"")));
  3739. FTerminal->CommandError(&E, Error);
  3740. // TODO: retries? resume?
  3741. Next = false;
  3742. }
  3743. if (Checksums != NULL)
  3744. {
  3745. Checksums->Add(Checksum);
  3746. }
  3747. }
  3748. __finally
  3749. {
  3750. if (FirstLevel)
  3751. {
  3752. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  3753. }
  3754. }
  3755. if (OperationProgress->Cancel != csContinue)
  3756. {
  3757. Next = false;
  3758. }
  3759. }
  3760. while (Next);
  3761. }
  3762. }
  3763. __finally
  3764. {
  3765. Queue.DisposeSafe();
  3766. }
  3767. // queue is discarded here
  3768. }
  3769. //---------------------------------------------------------------------------
  3770. void __fastcall TSFTPFileSystem::CalculateFilesChecksum(const UnicodeString & Alg,
  3771. TStrings * FileList, TStrings * Checksums,
  3772. TCalculatedChecksumEvent OnCalculatedChecksum)
  3773. {
  3774. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  3775. Progress.Start(foCalculateChecksum, osRemote, FileList->Count);
  3776. UnicodeString NormalizedAlg = FindIdent(Alg, FChecksumAlgs.get());
  3777. UnicodeString SftpAlg;
  3778. int Index = FChecksumAlgs->IndexOf(NormalizedAlg);
  3779. if (Index >= 0)
  3780. {
  3781. SftpAlg = FChecksumSftpAlgs->Strings[Index];
  3782. }
  3783. else
  3784. {
  3785. // try user-specified alg
  3786. SftpAlg = NormalizedAlg;
  3787. }
  3788. FTerminal->FOperationProgress = &Progress;
  3789. try
  3790. {
  3791. DoCalculateFilesChecksum(NormalizedAlg, SftpAlg, FileList, Checksums, OnCalculatedChecksum,
  3792. &Progress, true);
  3793. }
  3794. __finally
  3795. {
  3796. FTerminal->FOperationProgress = NULL;
  3797. Progress.Stop();
  3798. }
  3799. }
  3800. //---------------------------------------------------------------------------
  3801. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const UnicodeString /*FileName*/,
  3802. const TRemoteFile * /*File*/, UnicodeString /*Command*/, int /*Params*/,
  3803. TCaptureOutputEvent /*OutputEvent*/)
  3804. {
  3805. FAIL;
  3806. }
  3807. //---------------------------------------------------------------------------
  3808. void __fastcall TSFTPFileSystem::AnyCommand(const UnicodeString /*Command*/,
  3809. TCaptureOutputEvent /*OutputEvent*/)
  3810. {
  3811. FAIL;
  3812. }
  3813. //---------------------------------------------------------------------------
  3814. TStrings * __fastcall TSFTPFileSystem::GetFixedPaths()
  3815. {
  3816. return FFixedPaths;
  3817. }
  3818. //---------------------------------------------------------------------------
  3819. void __fastcall TSFTPFileSystem::SpaceAvailable(const UnicodeString Path,
  3820. TSpaceAvailable & ASpaceAvailable)
  3821. {
  3822. if (SupportsExtension(SFTP_EXT_SPACE_AVAILABLE) ||
  3823. // See comment in IsCapable
  3824. (FSecureShell->SshImplementation == sshiBitvise))
  3825. {
  3826. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3827. Packet.AddString(SFTP_EXT_SPACE_AVAILABLE);
  3828. Packet.AddPathString(LocalCanonify(Path), FUtfStrings);
  3829. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3830. ASpaceAvailable.BytesOnDevice = Packet.GetInt64();
  3831. ASpaceAvailable.UnusedBytesOnDevice = Packet.GetInt64();
  3832. ASpaceAvailable.BytesAvailableToUser = Packet.GetInt64();
  3833. ASpaceAvailable.UnusedBytesAvailableToUser = Packet.GetInt64();
  3834. // bytes-per-allocation-unit was added later to the protocol
  3835. // (revision 07, while the extension was defined already in rev 06),
  3836. // be tolerant
  3837. if (Packet.CanGetCardinal())
  3838. {
  3839. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetCardinal();
  3840. }
  3841. else if (Packet.CanGetSmallCardinal())
  3842. {
  3843. // See http://bugs.proftpd.org/show_bug.cgi?id=4079
  3844. FTerminal->LogEvent(L"Assuming ProFTPD/mod_sftp bug of 2-byte bytes-per-allocation-unit field");
  3845. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetSmallCardinal();
  3846. }
  3847. else
  3848. {
  3849. FTerminal->LogEvent(L"Missing bytes-per-allocation-unit field");
  3850. }
  3851. }
  3852. else if (ALWAYS_TRUE(FSupportsStatVfsV2))
  3853. {
  3854. // http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL?rev=HEAD;content-type=text/plain
  3855. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3856. Packet.AddString(SFTP_EXT_STATVFS);
  3857. Packet.AddPathString(LocalCanonify(Path), FUtfStrings);
  3858. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3859. __int64 BlockSize = Packet.GetInt64(); // file system block size
  3860. __int64 FundamentalBlockSize = Packet.GetInt64(); // fundamental fs block size
  3861. __int64 Blocks = Packet.GetInt64(); // number of blocks (unit f_frsize)
  3862. __int64 FreeBlocks = Packet.GetInt64(); // free blocks in file system
  3863. __int64 AvailableBlocks = Packet.GetInt64(); // free blocks for non-root
  3864. __int64 FileINodes = Packet.GetInt64(); // total file inodes
  3865. __int64 FreeFileINodes = Packet.GetInt64(); // free file inodes
  3866. __int64 AvailableFileINodes = Packet.GetInt64(); // free file inodes for to non-root
  3867. __int64 SID = Packet.GetInt64(); // file system id
  3868. __int64 Flags = Packet.GetInt64(); // bit mask of f_flag values
  3869. __int64 NameMax = Packet.GetInt64(); // maximum filename length
  3870. FTerminal->LogEvent(FORMAT(L"Block size: %s", (IntToStr(BlockSize))));
  3871. FTerminal->LogEvent(FORMAT(L"Fundamental block size: %s", (IntToStr(FundamentalBlockSize))));
  3872. FTerminal->LogEvent(FORMAT(L"Total blocks: %s", (IntToStr(Blocks))));
  3873. FTerminal->LogEvent(FORMAT(L"Free blocks: %s", (IntToStr(FreeBlocks))));
  3874. FTerminal->LogEvent(FORMAT(L"Free blocks for non-root: %s", (IntToStr(AvailableBlocks))));
  3875. FTerminal->LogEvent(FORMAT(L"Total file inodes: %s", (IntToStr(FileINodes))));
  3876. FTerminal->LogEvent(FORMAT(L"Free file inodes: %s", (IntToStr(FreeFileINodes))));
  3877. FTerminal->LogEvent(FORMAT(L"Free file inodes for non-root: %s", (IntToStr(AvailableFileINodes))));
  3878. FTerminal->LogEvent(FORMAT(L"File system ID: %s", (BytesToHex(reinterpret_cast<const unsigned char *>(&SID), sizeof(SID)))));
  3879. UnicodeString FlagStr;
  3880. if (FLAGSET(Flags, SFTP_EXT_STATVFS_ST_RDONLY))
  3881. {
  3882. AddToList(FlagStr, L"read-only", L",");
  3883. Flags -= SFTP_EXT_STATVFS_ST_RDONLY;
  3884. }
  3885. if (FLAGSET(Flags, SFTP_EXT_STATVFS_ST_NOSUID))
  3886. {
  3887. AddToList(FlagStr, L"no-setuid", L",");
  3888. Flags -= SFTP_EXT_STATVFS_ST_NOSUID;
  3889. }
  3890. if (Flags != 0)
  3891. {
  3892. AddToList(FlagStr, UnicodeString(L"0x") + IntToHex(Flags, 2), L",");
  3893. }
  3894. if (FlagStr.IsEmpty())
  3895. {
  3896. FlagStr = L"none";
  3897. }
  3898. FTerminal->LogEvent(FORMAT(L"Flags: %s", (FlagStr)));
  3899. FTerminal->LogEvent(FORMAT(L"Max name length: %s", (IntToStr(NameMax))));
  3900. ASpaceAvailable.BytesOnDevice = BlockSize * Blocks;
  3901. ASpaceAvailable.UnusedBytesOnDevice = BlockSize * FreeBlocks;
  3902. ASpaceAvailable.BytesAvailableToUser = 0;
  3903. ASpaceAvailable.UnusedBytesAvailableToUser = BlockSize * AvailableBlocks;
  3904. ASpaceAvailable.BytesPerAllocationUnit =
  3905. (BlockSize > std::numeric_limits<unsigned long>::max()) ? 0 : static_cast<unsigned long>(BlockSize);
  3906. }
  3907. }
  3908. //---------------------------------------------------------------------------
  3909. // transfer protocol
  3910. //---------------------------------------------------------------------------
  3911. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  3912. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  3913. int Params, TFileOperationProgressType * OperationProgress,
  3914. TOnceDoneOperation & OnceDoneOperation)
  3915. {
  3916. DebugAssert(FilesToCopy && OperationProgress);
  3917. UnicodeString FileName, FileNameOnly;
  3918. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  3919. int Index = 0;
  3920. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  3921. {
  3922. bool Success = false;
  3923. FileName = FilesToCopy->Strings[Index];
  3924. FileNameOnly = ExtractFileName(FileName);
  3925. DebugAssert(!FAvoidBusy);
  3926. FAvoidBusy = true;
  3927. try
  3928. {
  3929. try
  3930. {
  3931. if (FTerminal->SessionData->CacheDirectories)
  3932. {
  3933. FTerminal->DirectoryModified(TargetDir, false);
  3934. if (DirectoryExists(ApiPath(FileName)))
  3935. {
  3936. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  3937. FileNameOnly, true);
  3938. }
  3939. }
  3940. SFTPSourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  3941. tfFirstLevel);
  3942. Success = true;
  3943. }
  3944. catch(EScpSkipFile & E)
  3945. {
  3946. TSuspendFileOperationProgress Suspend(OperationProgress);
  3947. if (!FTerminal->HandleException(&E))
  3948. {
  3949. throw;
  3950. }
  3951. }
  3952. }
  3953. __finally
  3954. {
  3955. FAvoidBusy = false;
  3956. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  3957. }
  3958. Index++;
  3959. }
  3960. }
  3961. //---------------------------------------------------------------------------
  3962. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(
  3963. const UnicodeString & SourceFullFileName, UnicodeString & TargetFileName,
  3964. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  3965. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  3966. {
  3967. bool CanAppend = (FVersion < 4) || !OperationProgress->AsciiTransfer;
  3968. unsigned int Answer;
  3969. {
  3970. TSuspendFileOperationProgress Suspend(OperationProgress);
  3971. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  3972. // possibly we can allow alternate resume at least in some cases
  3973. if (CanAppend)
  3974. {
  3975. Answers |= qaRetry;
  3976. }
  3977. TQueryButtonAlias Aliases[5];
  3978. Aliases[0].Button = qaRetry;
  3979. Aliases[0].Alias = LoadStr(APPEND_BUTTON);
  3980. Aliases[0].GroupWith = qaNo;
  3981. Aliases[0].GrouppedShiftState = TShiftState() << ssAlt;
  3982. Aliases[1].Button = qaAll;
  3983. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  3984. Aliases[1].GroupWith = qaYes;
  3985. Aliases[1].GrouppedShiftState = TShiftState() << ssCtrl;
  3986. Aliases[2].Button = qaIgnore;
  3987. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  3988. Aliases[2].GroupWith = qaNo;
  3989. Aliases[2].GrouppedShiftState = TShiftState() << ssCtrl;
  3990. Aliases[3].Button = qaYesToAll;
  3991. Aliases[3].GroupWith = qaYes;
  3992. Aliases[3].GrouppedShiftState = TShiftState() << ssShift;
  3993. Aliases[4].Button = qaNoToAll;
  3994. Aliases[4].GroupWith = qaNo;
  3995. Aliases[4].GrouppedShiftState = TShiftState() << ssShift;
  3996. TQueryParams QueryParams(qpNeverAskAgainCheck);
  3997. QueryParams.NoBatchAnswers = qaIgnore | qaRetry | qaAll;
  3998. QueryParams.Aliases = Aliases;
  3999. QueryParams.AliasesCount = LENOF(Aliases);
  4000. Answer = FTerminal->ConfirmFileOverwrite(
  4001. SourceFullFileName, TargetFileName, FileParams,
  4002. Answers, &QueryParams,
  4003. OperationProgress->Side == osLocal ? osRemote : osLocal,
  4004. CopyParam, Params, OperationProgress);
  4005. }
  4006. if (CanAppend &&
  4007. ((Answer == qaRetry) || (Answer == qaSkip)))
  4008. {
  4009. // duplicated in TTerminal::ConfirmFileOverwrite
  4010. bool CanAlternateResume =
  4011. (FileParams->DestSize < FileParams->SourceSize) && !OperationProgress->AsciiTransfer;
  4012. TBatchOverwrite BatchOverwrite =
  4013. FTerminal->EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  4014. // when mode is forced by batch, never query user
  4015. if (BatchOverwrite == boAppend)
  4016. {
  4017. OverwriteMode = omAppend;
  4018. }
  4019. else if (CanAlternateResume &&
  4020. ((BatchOverwrite == boResume) || (BatchOverwrite == boAlternateResume)))
  4021. {
  4022. OverwriteMode = omResume;
  4023. }
  4024. // no other option, but append
  4025. else if (!CanAlternateResume)
  4026. {
  4027. OverwriteMode = omAppend;
  4028. }
  4029. else
  4030. {
  4031. TQueryParams Params(0, HELP_APPEND_OR_RESUME);
  4032. {
  4033. TSuspendFileOperationProgress Suspend(OperationProgress);
  4034. Answer = FTerminal->QueryUser(FORMAT(LoadStr(APPEND_OR_RESUME2), (SourceFullFileName)),
  4035. NULL, qaYes | qaNo | qaNoToAll | qaCancel, &Params);
  4036. }
  4037. switch (Answer)
  4038. {
  4039. case qaYes:
  4040. OverwriteMode = omAppend;
  4041. break;
  4042. case qaNo:
  4043. OverwriteMode = omResume;
  4044. break;
  4045. case qaNoToAll:
  4046. OverwriteMode = omResume;
  4047. OperationProgress->BatchOverwrite = boAlternateResume;
  4048. break;
  4049. default: FAIL; //fallthru
  4050. case qaCancel:
  4051. if (!OperationProgress->Cancel)
  4052. {
  4053. OperationProgress->Cancel = csCancel;
  4054. }
  4055. Abort();
  4056. break;
  4057. }
  4058. }
  4059. }
  4060. else if (Answer == qaIgnore)
  4061. {
  4062. if (FTerminal->PromptUser(FTerminal->SessionData, pkFileName, LoadStr(RENAME_TITLE), L"",
  4063. LoadStr(RENAME_PROMPT2), true, 0, TargetFileName))
  4064. {
  4065. OverwriteMode = omOverwrite;
  4066. }
  4067. else
  4068. {
  4069. if (!OperationProgress->Cancel)
  4070. {
  4071. OperationProgress->Cancel = csCancel;
  4072. }
  4073. Abort();
  4074. }
  4075. }
  4076. else
  4077. {
  4078. OverwriteMode = omOverwrite;
  4079. switch (Answer)
  4080. {
  4081. case qaCancel:
  4082. if (!OperationProgress->Cancel)
  4083. {
  4084. OperationProgress->Cancel = csCancel;
  4085. }
  4086. Abort();
  4087. break;
  4088. case qaNo:
  4089. THROW_SKIP_FILE_NULL;
  4090. }
  4091. }
  4092. }
  4093. //---------------------------------------------------------------------------
  4094. bool TSFTPFileSystem::SFTPConfirmResume(const UnicodeString DestFileName,
  4095. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  4096. {
  4097. bool ResumeTransfer;
  4098. DebugAssert(OperationProgress);
  4099. if (PartialBiggerThanSource)
  4100. {
  4101. unsigned int Answer;
  4102. {
  4103. TSuspendFileOperationProgress Suspend(OperationProgress);
  4104. TQueryParams Params(qpAllowContinueOnError, HELP_PARTIAL_BIGGER_THAN_SOURCE);
  4105. Answer = FTerminal->QueryUser(
  4106. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
  4107. qaOK | qaAbort, &Params, qtWarning);
  4108. }
  4109. if (Answer == qaAbort)
  4110. {
  4111. if (!OperationProgress->Cancel)
  4112. {
  4113. OperationProgress->Cancel = csCancel;
  4114. }
  4115. Abort();
  4116. }
  4117. ResumeTransfer = false;
  4118. }
  4119. else if (FTerminal->Configuration->ConfirmResume)
  4120. {
  4121. unsigned int Answer;
  4122. {
  4123. TSuspendFileOperationProgress Suspend(OperationProgress);
  4124. TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck,
  4125. HELP_RESUME_TRANSFER);
  4126. // "abort" replaced with "cancel" to unify with "append/resume" query
  4127. Answer = FTerminal->QueryUser(
  4128. FMTLOAD(RESUME_TRANSFER2, (DestFileName)), NULL, qaYes | qaNo | qaCancel,
  4129. &Params);
  4130. }
  4131. switch (Answer) {
  4132. case qaNeverAskAgain:
  4133. FTerminal->Configuration->ConfirmResume = false;
  4134. case qaYes:
  4135. ResumeTransfer = true;
  4136. break;
  4137. case qaNo:
  4138. ResumeTransfer = false;
  4139. break;
  4140. case qaCancel:
  4141. if (!OperationProgress->Cancel)
  4142. {
  4143. OperationProgress->Cancel = csCancel;
  4144. }
  4145. Abort();
  4146. break;
  4147. }
  4148. }
  4149. else
  4150. {
  4151. ResumeTransfer = true;
  4152. }
  4153. return ResumeTransfer;
  4154. }
  4155. //---------------------------------------------------------------------------
  4156. void __fastcall TSFTPFileSystem::SFTPSourceRobust(const UnicodeString FileName,
  4157. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  4158. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4159. {
  4160. // the same in TFTPFileSystem
  4161. TUploadSessionAction Action(FTerminal->ActionLog);
  4162. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  4163. do
  4164. {
  4165. bool ChildError = false;
  4166. try
  4167. {
  4168. SFTPSource(FileName, TargetDir, CopyParam, Params, OperationProgress,
  4169. Flags, Action, ChildError);
  4170. }
  4171. catch(Exception & E)
  4172. {
  4173. if (!RobustLoop.TryReopen(E))
  4174. {
  4175. if (!ChildError)
  4176. {
  4177. FTerminal->RollbackAction(Action, OperationProgress, &E);
  4178. }
  4179. throw;
  4180. }
  4181. }
  4182. if (RobustLoop.ShouldRetry())
  4183. {
  4184. OperationProgress->RollbackTransfer();
  4185. Action.Restart();
  4186. // prevent overwrite and resume confirmations
  4187. // (should not be set for directories!)
  4188. Params |= cpNoConfirmation;
  4189. // enable resume even if we are uploading into new directory
  4190. Flags &= ~tfNewDirectory;
  4191. }
  4192. }
  4193. while (RobustLoop.Retry());
  4194. }
  4195. //---------------------------------------------------------------------------
  4196. void __fastcall TSFTPFileSystem::SFTPSource(const UnicodeString FileName,
  4197. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  4198. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  4199. TUploadSessionAction & Action, bool & ChildError)
  4200. {
  4201. Action.FileName(ExpandUNCFileName(FileName));
  4202. OperationProgress->SetFile(FileName, false);
  4203. if (!FTerminal->AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
  4204. {
  4205. THROW_SKIP_FILE_NULL;
  4206. }
  4207. TOpenRemoteFileParams OpenParams;
  4208. OpenParams.OverwriteMode = omOverwrite;
  4209. HANDLE File;
  4210. __int64 MTime, ATime;
  4211. __int64 Size;
  4212. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
  4213. &File, NULL, &MTime, &ATime, &Size);
  4214. bool Dir = FLAGSET(OpenParams.LocalFileAttrs, faDirectory);
  4215. try
  4216. {
  4217. OperationProgress->SetFileInProgress();
  4218. if (Dir)
  4219. {
  4220. Action.Cancel();
  4221. SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  4222. OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
  4223. }
  4224. else
  4225. {
  4226. // File is regular file (not directory)
  4227. DebugAssert(File);
  4228. UnicodeString DestFileName =
  4229. FTerminal->ChangeFileName(
  4230. CopyParam, ExtractFileName(FileName), osLocal,
  4231. FLAGSET(Flags, tfFirstLevel));
  4232. UnicodeString DestFullName = LocalCanonify(TargetDir + DestFileName);
  4233. UnicodeString DestPartialFullName;
  4234. bool ResumeAllowed;
  4235. bool ResumeTransfer = false;
  4236. bool DestFileExists = false;
  4237. TRights DestRights;
  4238. __int64 ResumeOffset;
  4239. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  4240. OperationProgress->SetLocalSize(Size);
  4241. // Suppose same data size to transfer as to read
  4242. // (not true with ASCII transfer)
  4243. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  4244. OperationProgress->TransferingFile = false;
  4245. TDateTime Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  4246. // Will we use ASCII of BINARY file transfer?
  4247. TFileMasks::TParams MaskParams;
  4248. MaskParams.Size = Size;
  4249. MaskParams.Modification = Modification;
  4250. UnicodeString BaseFileName = FTerminal->GetBaseFileName(FileName);
  4251. OperationProgress->SetAsciiTransfer(
  4252. CopyParam->UseAsciiTransfer(BaseFileName, osLocal, MaskParams));
  4253. FTerminal->LogEvent(
  4254. UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
  4255. L" transfer mode selected.");
  4256. // should we check for interrupted transfer?
  4257. ResumeAllowed = !OperationProgress->AsciiTransfer &&
  4258. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  4259. IsCapable(fcRename);
  4260. TOverwriteFileParams FileParams;
  4261. FileParams.SourceSize = OperationProgress->LocalSize;
  4262. FileParams.SourceTimestamp = Modification;
  4263. if (ResumeAllowed)
  4264. {
  4265. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4266. if (FLAGCLEAR(Flags, tfNewDirectory))
  4267. {
  4268. FTerminal->LogEvent(L"Checking existence of file.");
  4269. TRemoteFile * File = NULL;
  4270. DestFileExists = RemoteFileExists(DestFullName, &File);
  4271. OperationProgress->Progress();
  4272. if (DestFileExists)
  4273. {
  4274. OpenParams.DestFileSize = File->Size;
  4275. FileParams.DestSize = OpenParams.DestFileSize;
  4276. FileParams.DestTimestamp = File->Modification;
  4277. DestRights = *File->Rights;
  4278. // - If destination file is symlink, never do resumable transfer,
  4279. // as it would delete the symlink.
  4280. // - Also bit of heuristics to detect symlink on SFTP-3 and older
  4281. // (which does not indicate symlink in SSH_FXP_ATTRS).
  4282. // if file has all permissions and is small, then it is likely symlink.
  4283. // also it is not likely that such a small file (if it is not symlink)
  4284. // gets overwritten by large file (that would trigger resumable transfer).
  4285. // - Also never do resumable transfer for file owned by other user
  4286. // as deleting and recreating the file would change ownership.
  4287. // This won't for work for SFTP-3 (OpenSSH) as it does not provide
  4288. // owner name (only UID) and we know only logged in user name (not UID)
  4289. if (File->IsSymLink ||
  4290. ((FVersion < 4) &&
  4291. ((*File->Rights & TRights::rfAll) == TRights::rfAll) &&
  4292. (File->Size < 100)) ||
  4293. (!File->Owner.Name.IsEmpty() && !SameUserName(File->Owner.Name, FTerminal->UserName)))
  4294. {
  4295. ResumeAllowed = false;
  4296. }
  4297. delete File;
  4298. File = NULL;
  4299. }
  4300. if (ResumeAllowed)
  4301. {
  4302. FTerminal->LogEvent(L"Checking existence of partially transfered file.");
  4303. if (RemoteFileExists(DestPartialFullName, &File))
  4304. {
  4305. ResumeOffset = File->Size;
  4306. delete File;
  4307. File = NULL;
  4308. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->LocalSize);
  4309. if (FLAGCLEAR(Params, cpNoConfirmation) &&
  4310. FLAGCLEAR(Params, cpResume) &&
  4311. !CopyParam->ResumeTransfer(FileName))
  4312. {
  4313. ResumeTransfer = SFTPConfirmResume(DestFileName,
  4314. PartialBiggerThanSource, OperationProgress);
  4315. }
  4316. else
  4317. {
  4318. ResumeTransfer = !PartialBiggerThanSource;
  4319. }
  4320. if (!ResumeTransfer)
  4321. {
  4322. DoDeleteFile(DestPartialFullName, SSH_FXP_REMOVE);
  4323. OperationProgress->Progress();
  4324. }
  4325. else
  4326. {
  4327. FTerminal->LogEvent(L"Resuming file transfer.");
  4328. }
  4329. }
  4330. else
  4331. {
  4332. // partial upload file does not exists, check for full file
  4333. if (DestFileExists)
  4334. {
  4335. UnicodeString PrevDestFileName = DestFileName;
  4336. SFTPConfirmOverwrite(FileName, DestFileName,
  4337. CopyParam, Params, OperationProgress, OpenParams.OverwriteMode, &FileParams);
  4338. if (PrevDestFileName != DestFileName)
  4339. {
  4340. // update paths in case user changes the file name
  4341. DestFullName = LocalCanonify(TargetDir + DestFileName);
  4342. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4343. FTerminal->LogEvent(L"Checking existence of new file.");
  4344. DestFileExists = RemoteFileExists(DestFullName, NULL);
  4345. }
  4346. }
  4347. }
  4348. }
  4349. }
  4350. }
  4351. // will the transfer be resumable?
  4352. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  4353. UnicodeString RemoteFileName = DoResume ? DestPartialFullName : DestFullName;
  4354. OpenParams.FileName = FileName;
  4355. OpenParams.RemoteFileName = RemoteFileName;
  4356. OpenParams.Resume = DoResume;
  4357. OpenParams.Resuming = ResumeTransfer;
  4358. OpenParams.OperationProgress = OperationProgress;
  4359. OpenParams.CopyParam = CopyParam;
  4360. OpenParams.Params = Params;
  4361. OpenParams.FileParams = &FileParams;
  4362. OpenParams.Confirmed = false;
  4363. FTerminal->LogEvent(L"Opening remote file.");
  4364. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
  4365. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  4366. &OpenParams);
  4367. OperationProgress->Progress();
  4368. if (OpenParams.RemoteFileName != RemoteFileName)
  4369. {
  4370. DebugAssert(!DoResume);
  4371. DebugAssert(UnixExtractFilePath(OpenParams.RemoteFileName) == UnixExtractFilePath(RemoteFileName));
  4372. DestFullName = OpenParams.RemoteFileName;
  4373. UnicodeString NewFileName = UnixExtractFileName(DestFullName);
  4374. DebugAssert(DestFileName != NewFileName);
  4375. DestFileName = NewFileName;
  4376. }
  4377. Action.Destination(DestFullName);
  4378. bool TransferFinished = false;
  4379. __int64 DestWriteOffset = 0;
  4380. TSFTPPacket CloseRequest;
  4381. bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
  4382. bool SetProperties = (CopyParam->PreserveTime || SetRights);
  4383. TSFTPPacket PropertiesRequest(SSH_FXP_SETSTAT);
  4384. TSFTPPacket PropertiesResponse;
  4385. TRights Rights;
  4386. if (SetProperties)
  4387. {
  4388. PropertiesRequest.AddPathString(DestFullName, FUtfStrings);
  4389. if (CopyParam->PreserveRights)
  4390. {
  4391. Rights = CopyParam->RemoteFileRights(OpenParams.LocalFileAttrs);
  4392. }
  4393. else if (DoResume && DestFileExists)
  4394. {
  4395. Rights = DestRights;
  4396. }
  4397. else
  4398. {
  4399. DebugAssert(!SetRights);
  4400. }
  4401. unsigned short RightsNumber = Rights.NumberSet;
  4402. PropertiesRequest.AddProperties(
  4403. SetRights ? &RightsNumber : NULL, NULL, NULL,
  4404. CopyParam->PreserveTime ? &MTime : NULL,
  4405. CopyParam->PreserveTime ? &ATime : NULL,
  4406. NULL, false, FVersion, FUtfStrings);
  4407. }
  4408. try
  4409. {
  4410. if (OpenParams.OverwriteMode == omAppend)
  4411. {
  4412. FTerminal->LogEvent(L"Appending file.");
  4413. DestWriteOffset = OpenParams.DestFileSize;
  4414. }
  4415. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  4416. {
  4417. if (OpenParams.OverwriteMode == omResume)
  4418. {
  4419. FTerminal->LogEvent(L"Resuming file transfer (append style).");
  4420. ResumeOffset = OpenParams.DestFileSize;
  4421. }
  4422. FileSeek((THandle)File, ResumeOffset, 0);
  4423. OperationProgress->AddResumed(ResumeOffset);
  4424. }
  4425. TSFTPUploadQueue Queue(this);
  4426. try
  4427. {
  4428. int ConvertParams =
  4429. FLAGMASK(CopyParam->RemoveCtrlZ, cpRemoveCtrlZ) |
  4430. FLAGMASK(CopyParam->RemoveBOM, cpRemoveBOM);
  4431. Queue.Init(FileName, File, OperationProgress,
  4432. OpenParams.RemoteFileHandle,
  4433. DestWriteOffset + OperationProgress->TransferedSize,
  4434. ConvertParams);
  4435. while (Queue.Continue())
  4436. {
  4437. if (OperationProgress->Cancel)
  4438. {
  4439. Abort();
  4440. }
  4441. }
  4442. // send close request before waiting for pending read responses
  4443. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4444. OperationProgress, false, true, &CloseRequest);
  4445. OpenParams.RemoteFileHandle = L"";
  4446. // when resuming is disabled, we can send "set properties"
  4447. // request before waiting for pending read/close responses
  4448. if (SetProperties && !DoResume)
  4449. {
  4450. SendPacket(&PropertiesRequest);
  4451. ReserveResponse(&PropertiesRequest, &PropertiesResponse);
  4452. }
  4453. }
  4454. __finally
  4455. {
  4456. Queue.DisposeSafe();
  4457. }
  4458. TransferFinished = true;
  4459. // queue is discarded here
  4460. }
  4461. __finally
  4462. {
  4463. if (FTerminal->Active)
  4464. {
  4465. // if file transfer was finished, the close request was already sent
  4466. if (!OpenParams.RemoteFileHandle.IsEmpty())
  4467. {
  4468. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4469. OperationProgress, TransferFinished, true, &CloseRequest);
  4470. }
  4471. // wait for the response
  4472. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  4473. OperationProgress, TransferFinished, false, &CloseRequest);
  4474. // delete file if transfer was not completed, resuming was not allowed and
  4475. // we were not appending (incl. alternate resume),
  4476. // shortly after plain transfer completes (eq. !ResumeAllowed)
  4477. if (!TransferFinished && !DoResume && (OpenParams.OverwriteMode == omOverwrite))
  4478. {
  4479. DoDeleteFile(OpenParams.RemoteFileName, SSH_FXP_REMOVE);
  4480. }
  4481. }
  4482. }
  4483. OperationProgress->Progress();
  4484. if (DoResume)
  4485. {
  4486. if (DestFileExists)
  4487. {
  4488. FILE_OPERATION_LOOP_BEGIN
  4489. {
  4490. if (FTerminal->SessionData->OverwrittenToRecycleBin &&
  4491. !FTerminal->SessionData->RecycleBinPath.IsEmpty())
  4492. {
  4493. FTerminal->RecycleFile(DestFullName, NULL);
  4494. }
  4495. else
  4496. {
  4497. DoDeleteFile(DestFullName, SSH_FXP_REMOVE);
  4498. }
  4499. }
  4500. FILE_OPERATION_LOOP_END(
  4501. FMTLOAD(DELETE_ON_RESUME_ERROR,
  4502. (UnixExtractFileName(DestFullName), DestFullName)));
  4503. }
  4504. // originally this was before CLOSE (last __finally statement),
  4505. // on VShell it failed
  4506. FILE_OPERATION_LOOP_BEGIN
  4507. {
  4508. RenameFile(OpenParams.RemoteFileName, DestFileName);
  4509. }
  4510. FILE_OPERATION_LOOP_END_CUSTOM(
  4511. FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  4512. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  4513. true, HELP_RENAME_AFTER_RESUME_ERROR);
  4514. }
  4515. if (SetProperties)
  4516. {
  4517. std::unique_ptr<TTouchSessionAction> TouchAction;
  4518. if (CopyParam->PreserveTime)
  4519. {
  4520. TDateTime MDateTime = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  4521. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  4522. (StandardTimestamp(MDateTime))));
  4523. TouchAction.reset(new TTouchSessionAction(FTerminal->ActionLog, DestFullName,
  4524. MDateTime));
  4525. }
  4526. std::unique_ptr<TChmodSessionAction> ChmodAction;
  4527. // do record chmod only if it was explicitly requested,
  4528. // not when it was implicitly performed to apply timestamp
  4529. // of overwritten file to new file
  4530. if (CopyParam->PreserveRights)
  4531. {
  4532. ChmodAction.reset(new TChmodSessionAction(FTerminal->ActionLog, DestFullName, Rights));
  4533. }
  4534. try
  4535. {
  4536. // when resuming is enabled, the set properties request was not sent yet
  4537. if (DoResume)
  4538. {
  4539. SendPacket(&PropertiesRequest);
  4540. }
  4541. bool Resend = false;
  4542. FILE_OPERATION_LOOP_BEGIN
  4543. {
  4544. try
  4545. {
  4546. TSFTPPacket DummyResponse;
  4547. TSFTPPacket * Response = &PropertiesResponse;
  4548. if (Resend)
  4549. {
  4550. PropertiesRequest.Reuse();
  4551. SendPacket(&PropertiesRequest);
  4552. // ReceiveResponse currently cannot receive twice into same packet,
  4553. // so DummyResponse is temporary workaround
  4554. Response = &DummyResponse;
  4555. }
  4556. Resend = true;
  4557. ReceiveResponse(&PropertiesRequest, Response, SSH_FXP_STATUS,
  4558. asOK | FLAGMASK(CopyParam->IgnorePermErrors, asPermDenied));
  4559. }
  4560. catch (...)
  4561. {
  4562. if (FTerminal->Active &&
  4563. (!CopyParam->PreserveRights && !CopyParam->PreserveTime))
  4564. {
  4565. DebugAssert(DoResume);
  4566. FTerminal->LogEvent(L"Ignoring error preserving permissions of overwritten file");
  4567. }
  4568. else
  4569. {
  4570. throw;
  4571. }
  4572. }
  4573. }
  4574. FILE_OPERATION_LOOP_END_CUSTOM(
  4575. FMTLOAD(PRESERVE_TIME_PERM_ERROR3, (DestFileName)),
  4576. true, HELP_PRESERVE_TIME_PERM_ERROR);
  4577. }
  4578. catch(Exception & E)
  4579. {
  4580. if (TouchAction.get() != NULL)
  4581. {
  4582. TouchAction->Rollback(&E);
  4583. }
  4584. if (ChmodAction.get() != NULL)
  4585. {
  4586. ChmodAction->Rollback(&E);
  4587. }
  4588. ChildError = true;
  4589. throw;
  4590. }
  4591. }
  4592. FTerminal->LogFileDone(OperationProgress);
  4593. }
  4594. }
  4595. __finally
  4596. {
  4597. if (File != NULL)
  4598. {
  4599. CloseHandle(File);
  4600. }
  4601. }
  4602. /* TODO : Delete also read-only files. */
  4603. if (FLAGSET(Params, cpDelete))
  4604. {
  4605. if (!Dir)
  4606. {
  4607. FILE_OPERATION_LOOP_BEGIN
  4608. {
  4609. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(FileName)));
  4610. }
  4611. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  4612. }
  4613. }
  4614. else if (CopyParam->ClearArchive && FLAGSET(OpenParams.LocalFileAttrs, faArchive))
  4615. {
  4616. FILE_OPERATION_LOOP_BEGIN
  4617. {
  4618. THROWOSIFFALSE(FileSetAttr(ApiPath(FileName), OpenParams.LocalFileAttrs & ~faArchive) == 0);
  4619. }
  4620. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  4621. }
  4622. }
  4623. //---------------------------------------------------------------------------
  4624. RawByteString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
  4625. const UnicodeString & FileName, unsigned int OpenType, __int64 Size)
  4626. {
  4627. TSFTPPacket Packet(SSH_FXP_OPEN);
  4628. Packet.AddPathString(FileName, FUtfStrings);
  4629. if (FVersion < 5)
  4630. {
  4631. Packet.AddCardinal(OpenType);
  4632. }
  4633. else
  4634. {
  4635. unsigned long Access =
  4636. FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
  4637. FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
  4638. unsigned long Flags;
  4639. if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
  4640. {
  4641. Flags = SSH_FXF_CREATE_NEW;
  4642. }
  4643. else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
  4644. {
  4645. Flags = SSH_FXF_CREATE_TRUNCATE;
  4646. }
  4647. else if (FLAGSET(OpenType, SSH_FXF_CREAT))
  4648. {
  4649. Flags = SSH_FXF_OPEN_OR_CREATE;
  4650. }
  4651. else
  4652. {
  4653. Flags = SSH_FXF_OPEN_EXISTING;
  4654. }
  4655. Flags |=
  4656. FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
  4657. FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
  4658. Packet.AddCardinal(Access);
  4659. Packet.AddCardinal(Flags);
  4660. }
  4661. bool SendSize =
  4662. (Size >= 0) &&
  4663. FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC) &&
  4664. // Particuarly VanDyke VShell (4.0.3) does not support SSH_FILEXFER_ATTR_ALLOCATION_SIZE
  4665. // (it fails open request when the attribute is included).
  4666. // It's SFTP-6 attribute, so support structure should be available.
  4667. // It's actually not with VShell. But VShell supports the SSH_FILEXFER_ATTR_ALLOCATION_SIZE.
  4668. // All servers should support SSH_FILEXFER_ATTR_SIZE (SFTP < 6)
  4669. (!FSupport->Loaded || FLAGSET(FSupport->AttributeMask, Packet.AllocationSizeAttribute(FVersion)));
  4670. Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
  4671. SendSize ? &Size : NULL, false, FVersion, FUtfStrings);
  4672. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  4673. return Packet.GetFileHandle();
  4674. }
  4675. //---------------------------------------------------------------------------
  4676. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  4677. {
  4678. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  4679. DebugAssert(OpenParams);
  4680. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  4681. int OpenType;
  4682. bool Success = false;
  4683. bool ConfirmOverwriting;
  4684. do
  4685. {
  4686. try
  4687. {
  4688. ConfirmOverwriting =
  4689. !OpenParams->Confirmed && !OpenParams->Resume &&
  4690. FTerminal->CheckRemoteFile(OpenParams->FileName, OpenParams->CopyParam, OpenParams->Params, OperationProgress);
  4691. OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
  4692. // when we want to preserve overwritten files, we need to find out that
  4693. // they exist first... even if overwrite confirmation is disabled.
  4694. // but not when we already know we are not going to overwrite (but e.g. to append)
  4695. if ((ConfirmOverwriting || FTerminal->SessionData->OverwrittenToRecycleBin) &&
  4696. (OpenParams->OverwriteMode == omOverwrite))
  4697. {
  4698. OpenType |= SSH_FXF_EXCL;
  4699. }
  4700. if (!OpenParams->Resuming && (OpenParams->OverwriteMode == omOverwrite))
  4701. {
  4702. OpenType |= SSH_FXF_TRUNC;
  4703. }
  4704. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  4705. {
  4706. OpenType |= SSH_FXF_TEXT;
  4707. }
  4708. OpenParams->RemoteFileHandle = SFTPOpenRemoteFile(
  4709. OpenParams->RemoteFileName, OpenType, OperationProgress->LocalSize);
  4710. Success = true;
  4711. }
  4712. catch(Exception & E)
  4713. {
  4714. if (!OpenParams->Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  4715. {
  4716. FTerminal->LogEvent(FORMAT(L"Cannot create new file \"%s\", checking if it exists already", (OpenParams->RemoteFileName)));
  4717. bool ThrowOriginal = false;
  4718. // When exclusive opening of file fails, try to detect if file exists.
  4719. // When file does not exist, failure was probably caused by 'permission denied'
  4720. // or similar error. In this case throw original exception.
  4721. try
  4722. {
  4723. OperationProgress->Progress();
  4724. TRemoteFile * File;
  4725. UnicodeString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  4726. ReadFile(RealFileName, File);
  4727. DebugAssert(File);
  4728. OpenParams->DestFileSize = File->Size;
  4729. if (OpenParams->FileParams != NULL)
  4730. {
  4731. OpenParams->FileParams->DestTimestamp = File->Modification;
  4732. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  4733. }
  4734. // file exists (otherwise exception was thrown)
  4735. SAFE_DESTROY(File);
  4736. }
  4737. catch(...)
  4738. {
  4739. if (!FTerminal->Active)
  4740. {
  4741. throw;
  4742. }
  4743. else
  4744. {
  4745. ThrowOriginal = true;
  4746. }
  4747. }
  4748. if (ThrowOriginal)
  4749. {
  4750. throw;
  4751. }
  4752. // we may get here even if confirmation is disabled,
  4753. // when we have preserving of overwritten files enabled
  4754. if (ConfirmOverwriting)
  4755. {
  4756. OperationProgress->Progress();
  4757. // confirmation duplicated in SFTPSource for resumable file transfers.
  4758. UnicodeString RemoteFileNameOnly = UnixExtractFileName(OpenParams->RemoteFileName);
  4759. SFTPConfirmOverwrite(OpenParams->FileName, RemoteFileNameOnly,
  4760. OpenParams->CopyParam, OpenParams->Params, OperationProgress, OpenParams->OverwriteMode, OpenParams->FileParams);
  4761. if (RemoteFileNameOnly != UnixExtractFileName(OpenParams->RemoteFileName))
  4762. {
  4763. OpenParams->RemoteFileName =
  4764. UnixExtractFilePath(OpenParams->RemoteFileName) + RemoteFileNameOnly;
  4765. }
  4766. OpenParams->Confirmed = true;
  4767. }
  4768. else
  4769. {
  4770. DebugAssert(FTerminal->SessionData->OverwrittenToRecycleBin);
  4771. }
  4772. if ((OpenParams->OverwriteMode == omOverwrite) &&
  4773. FTerminal->SessionData->OverwrittenToRecycleBin &&
  4774. !FTerminal->SessionData->RecycleBinPath.IsEmpty())
  4775. {
  4776. OperationProgress->Progress();
  4777. FTerminal->RecycleFile(OpenParams->RemoteFileName, NULL);
  4778. }
  4779. }
  4780. else if (FTerminal->Active)
  4781. {
  4782. // if file overwriting was confirmed, it means that the file already exists,
  4783. // if not, check now
  4784. if (!OpenParams->Confirmed)
  4785. {
  4786. bool ThrowOriginal = false;
  4787. // When file does not exist, failure was probably caused by 'permission denied'
  4788. // or similar error. In this case throw original exception.
  4789. try
  4790. {
  4791. TRemoteFile * File;
  4792. UnicodeString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  4793. ReadFile(RealFileName, File);
  4794. SAFE_DESTROY(File);
  4795. }
  4796. catch(...)
  4797. {
  4798. if (!FTerminal->Active)
  4799. {
  4800. throw;
  4801. }
  4802. else
  4803. {
  4804. ThrowOriginal = true;
  4805. }
  4806. }
  4807. if (ThrowOriginal)
  4808. {
  4809. throw;
  4810. }
  4811. }
  4812. // now we know that the file exists
  4813. if (FTerminal->FileOperationLoopQuery(E, OperationProgress,
  4814. FMTLOAD(SFTP_OVERWRITE_FILE_ERROR2, (OpenParams->RemoteFileName)),
  4815. true, LoadStr(SFTP_OVERWRITE_DELETE_BUTTON)))
  4816. {
  4817. OperationProgress->Progress();
  4818. int Params = dfNoRecursive;
  4819. FTerminal->DeleteFile(OpenParams->RemoteFileName, NULL, &Params);
  4820. }
  4821. }
  4822. else
  4823. {
  4824. throw;
  4825. }
  4826. }
  4827. }
  4828. while (!Success);
  4829. return 0;
  4830. }
  4831. //---------------------------------------------------------------------------
  4832. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const RawByteString Handle,
  4833. const UnicodeString FileName, TFileOperationProgressType * OperationProgress,
  4834. bool TransferFinished, bool Request, TSFTPPacket * Packet)
  4835. {
  4836. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  4837. FILE_OPERATION_LOOP_BEGIN
  4838. {
  4839. try
  4840. {
  4841. TSFTPPacket CloseRequest;
  4842. TSFTPPacket * P = (Packet == NULL ? &CloseRequest : Packet);
  4843. if (Request)
  4844. {
  4845. P->ChangeType(SSH_FXP_CLOSE);
  4846. P->AddString(Handle);
  4847. SendPacket(P);
  4848. ReserveResponse(P, Packet);
  4849. }
  4850. else
  4851. {
  4852. DebugAssert(Packet != NULL);
  4853. ReceiveResponse(P, Packet, SSH_FXP_STATUS);
  4854. }
  4855. }
  4856. catch(...)
  4857. {
  4858. if (!FTerminal->Active || TransferFinished)
  4859. {
  4860. throw;
  4861. }
  4862. }
  4863. }
  4864. FILE_OPERATION_LOOP_END(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)));
  4865. }
  4866. //---------------------------------------------------------------------------
  4867. void __fastcall TSFTPFileSystem::SFTPDirectorySource(const UnicodeString DirectoryName,
  4868. const UnicodeString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  4869. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4870. {
  4871. UnicodeString DestDirectoryName =
  4872. FTerminal->ChangeFileName(
  4873. CopyParam, ExtractFileName(ExcludeTrailingBackslash(DirectoryName)),
  4874. osLocal, FLAGSET(Flags, tfFirstLevel));
  4875. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  4876. OperationProgress->SetFile(DirectoryName);
  4877. bool CreateDir = false;
  4878. try
  4879. {
  4880. TryOpenDirectory(DestFullName);
  4881. }
  4882. catch(...)
  4883. {
  4884. if (FTerminal->Active)
  4885. {
  4886. // opening directory failed, it probably does not exists, try to
  4887. // create it
  4888. CreateDir = true;
  4889. }
  4890. else
  4891. {
  4892. throw;
  4893. }
  4894. }
  4895. if (CreateDir)
  4896. {
  4897. TRemoteProperties Properties;
  4898. if (CopyParam->PreserveRights)
  4899. {
  4900. Properties.Valid = TValidProperties() << vpRights;
  4901. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  4902. }
  4903. FTerminal->CreateDirectory(DestFullName, &Properties);
  4904. Flags |= tfNewDirectory;
  4905. }
  4906. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4907. TSearchRecChecked SearchRec;
  4908. bool FindOK;
  4909. FILE_OPERATION_LOOP_BEGIN
  4910. {
  4911. FindOK =
  4912. (FindFirstChecked(DirectoryName + L"*.*", FindAttrs, SearchRec) == 0);
  4913. }
  4914. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  4915. try
  4916. {
  4917. while (FindOK && !OperationProgress->Cancel)
  4918. {
  4919. UnicodeString FileName = DirectoryName + SearchRec.Name;
  4920. try
  4921. {
  4922. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  4923. {
  4924. SFTPSourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  4925. Flags & ~tfFirstLevel);
  4926. }
  4927. }
  4928. catch (EScpSkipFile &E)
  4929. {
  4930. // If ESkipFile occurs, just log it and continue with next file
  4931. TSuspendFileOperationProgress Suspend(OperationProgress);
  4932. // here a message to user was displayed, which was not appropriate
  4933. // when user refused to overwrite the file in subdirectory.
  4934. // hopefully it won't be missing in other situations.
  4935. if (!FTerminal->HandleException(&E))
  4936. {
  4937. throw;
  4938. }
  4939. }
  4940. FILE_OPERATION_LOOP_BEGIN
  4941. {
  4942. FindOK = (FindNextChecked(SearchRec) == 0);
  4943. }
  4944. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  4945. };
  4946. }
  4947. __finally
  4948. {
  4949. FindClose(SearchRec);
  4950. }
  4951. /* TODO : Delete also read-only directories. */
  4952. /* TODO : Show error message on failure. */
  4953. if (!OperationProgress->Cancel)
  4954. {
  4955. if (CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  4956. {
  4957. TRemoteProperties Properties;
  4958. Properties.Valid << vpModification;
  4959. FTerminal->OpenLocalFile(
  4960. ExcludeTrailingBackslash(DirectoryName), GENERIC_READ, NULL, NULL, NULL,
  4961. &Properties.Modification, &Properties.LastAccess, NULL);
  4962. FTerminal->ChangeFileProperties(DestFullName, NULL, &Properties);
  4963. }
  4964. if (FLAGSET(Params, cpDelete))
  4965. {
  4966. RemoveDir(ApiPath(DirectoryName));
  4967. }
  4968. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  4969. {
  4970. FILE_OPERATION_LOOP_BEGIN
  4971. {
  4972. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  4973. }
  4974. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  4975. }
  4976. }
  4977. }
  4978. //---------------------------------------------------------------------------
  4979. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  4980. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  4981. int Params, TFileOperationProgressType * OperationProgress,
  4982. TOnceDoneOperation & OnceDoneOperation)
  4983. {
  4984. DebugAssert(FilesToCopy && OperationProgress);
  4985. UnicodeString FileName;
  4986. UnicodeString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  4987. const TRemoteFile * File;
  4988. bool Success;
  4989. int Index = 0;
  4990. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  4991. {
  4992. Success = false;
  4993. FileName = FilesToCopy->Strings[Index];
  4994. File = (TRemoteFile *)FilesToCopy->Objects[Index];
  4995. DebugAssert(!FAvoidBusy);
  4996. FAvoidBusy = true;
  4997. try
  4998. {
  4999. try
  5000. {
  5001. SFTPSinkRobust(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
  5002. Params, OperationProgress, tfFirstLevel);
  5003. Success = true;
  5004. }
  5005. catch(EScpSkipFile & E)
  5006. {
  5007. TSuspendFileOperationProgress Suspend(OperationProgress);
  5008. if (!FTerminal->HandleException(&E))
  5009. {
  5010. throw;
  5011. }
  5012. }
  5013. catch(...)
  5014. {
  5015. // TODO: remove the block?
  5016. throw;
  5017. }
  5018. }
  5019. __finally
  5020. {
  5021. FAvoidBusy = false;
  5022. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  5023. }
  5024. Index++;
  5025. }
  5026. }
  5027. //---------------------------------------------------------------------------
  5028. void __fastcall TSFTPFileSystem::SFTPSinkRobust(const UnicodeString FileName,
  5029. const TRemoteFile * File, const UnicodeString TargetDir,
  5030. const TCopyParamType * CopyParam, int Params,
  5031. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  5032. {
  5033. // the same in TFTPFileSystem
  5034. TDownloadSessionAction Action(FTerminal->ActionLog);
  5035. TRobustOperationLoop RobustLoop(FTerminal, OperationProgress);
  5036. do
  5037. {
  5038. bool ChildError = false;
  5039. try
  5040. {
  5041. SFTPSink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  5042. Flags, Action, ChildError);
  5043. }
  5044. catch(Exception & E)
  5045. {
  5046. if (!RobustLoop.TryReopen(E))
  5047. {
  5048. if (!ChildError)
  5049. {
  5050. FTerminal->RollbackAction(Action, OperationProgress, &E);
  5051. }
  5052. throw;
  5053. }
  5054. }
  5055. if (RobustLoop.ShouldRetry())
  5056. {
  5057. OperationProgress->RollbackTransfer();
  5058. Action.Restart();
  5059. DebugAssert(File != NULL);
  5060. if (!File->IsDirectory)
  5061. {
  5062. // prevent overwrite and resume confirmations
  5063. Params |= cpNoConfirmation;
  5064. }
  5065. }
  5066. }
  5067. while (RobustLoop.Retry());
  5068. }
  5069. //---------------------------------------------------------------------------
  5070. void __fastcall TSFTPFileSystem::SFTPSink(const UnicodeString FileName,
  5071. const TRemoteFile * File, const UnicodeString TargetDir,
  5072. const TCopyParamType * CopyParam, int Params,
  5073. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  5074. TDownloadSessionAction & Action, bool & ChildError)
  5075. {
  5076. Action.FileName(FileName);
  5077. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  5078. TFileMasks::TParams MaskParams;
  5079. DebugAssert(File);
  5080. MaskParams.Size = File->Size;
  5081. MaskParams.Modification = File->Modification;
  5082. UnicodeString BaseFileName = FTerminal->GetBaseFileName(FileName);
  5083. if (!CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams))
  5084. {
  5085. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  5086. THROW_SKIP_FILE_NULL;
  5087. }
  5088. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  5089. {
  5090. OperationProgress->AddSkippedFileSize(File->Size);
  5091. THROW_SKIP_FILE_NULL;
  5092. }
  5093. FTerminal->LogFileDetails(FileName, File->Modification, File->Size);
  5094. OperationProgress->SetFile(FileName);
  5095. UnicodeString DestFileName =
  5096. FTerminal->ChangeFileName(
  5097. CopyParam, OnlyFileName, osRemote, FLAGSET(Flags, tfFirstLevel));
  5098. UnicodeString DestFullName = TargetDir + DestFileName;
  5099. if (File->IsDirectory)
  5100. {
  5101. Action.Cancel();
  5102. if (!File->IsSymLink)
  5103. {
  5104. FILE_OPERATION_LOOP_BEGIN
  5105. {
  5106. int Attrs = FileGetAttr(ApiPath(DestFullName));
  5107. if ((Attrs & faDirectory) == 0) EXCEPTION;
  5108. }
  5109. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  5110. FILE_OPERATION_LOOP_BEGIN
  5111. {
  5112. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  5113. }
  5114. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  5115. TSinkFileParams SinkFileParams;
  5116. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  5117. SinkFileParams.CopyParam = CopyParam;
  5118. SinkFileParams.Params = Params;
  5119. SinkFileParams.OperationProgress = OperationProgress;
  5120. SinkFileParams.Skipped = false;
  5121. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  5122. FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
  5123. if (CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  5124. {
  5125. FTerminal->LogEvent(FORMAT(L"Preserving directory timestamp [%s]",
  5126. (StandardTimestamp(File->Modification))));
  5127. int SetFileTimeError = ERROR_SUCCESS;
  5128. // FILE_FLAG_BACKUP_SEMANTICS is needed to "open" directory
  5129. HANDLE LocalHandle = CreateFile(ApiPath(DestFullName).c_str(), GENERIC_WRITE,
  5130. FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
  5131. if (LocalHandle == INVALID_HANDLE_VALUE)
  5132. {
  5133. SetFileTimeError = GetLastError();
  5134. }
  5135. else
  5136. {
  5137. FILETIME AcTime = DateTimeToFileTime(File->LastAccess, FTerminal->SessionData->DSTMode);
  5138. FILETIME WrTime = DateTimeToFileTime(File->Modification, FTerminal->SessionData->DSTMode);
  5139. if (!SetFileTime(LocalHandle, NULL, &AcTime, &WrTime))
  5140. {
  5141. SetFileTimeError = GetLastError();
  5142. }
  5143. CloseHandle(LocalHandle);
  5144. }
  5145. if (SetFileTimeError != ERROR_SUCCESS)
  5146. {
  5147. FTerminal->LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s",
  5148. (SysErrorMessageForError(SetFileTimeError))));
  5149. }
  5150. }
  5151. // Do not delete directory if some of its files were skip.
  5152. // Throw "skip file" for the directory to avoid attempt to deletion
  5153. // of any parent directory
  5154. if ((Params & cpDelete) && SinkFileParams.Skipped)
  5155. {
  5156. THROW_SKIP_FILE_NULL;
  5157. }
  5158. }
  5159. else
  5160. {
  5161. FTerminal->LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (FileName)));
  5162. }
  5163. }
  5164. else
  5165. {
  5166. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  5167. UnicodeString DestPartialFullName;
  5168. bool ResumeAllowed;
  5169. bool ResumeTransfer = false;
  5170. __int64 ResumeOffset;
  5171. // Will we use ASCII of BINARY file transfer?
  5172. OperationProgress->SetAsciiTransfer(
  5173. CopyParam->UseAsciiTransfer(BaseFileName, osRemote, MaskParams));
  5174. FTerminal->LogEvent(UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
  5175. " transfer mode selected.");
  5176. // Suppose same data size to transfer as to write
  5177. // (not true with ASCII transfer)
  5178. OperationProgress->SetTransferSize(File->Size);
  5179. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  5180. // resume has no sense for temporary downloads
  5181. ResumeAllowed = ((Params & cpTemporary) == 0) &&
  5182. !OperationProgress->AsciiTransfer &&
  5183. CopyParam->AllowResume(OperationProgress->TransferSize);
  5184. int Attrs;
  5185. FILE_OPERATION_LOOP_BEGIN
  5186. {
  5187. Attrs = FileGetAttr(ApiPath(DestFullName));
  5188. if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
  5189. }
  5190. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  5191. OperationProgress->TransferingFile = false; // not set with SFTP protocol
  5192. HANDLE LocalHandle = NULL;
  5193. TStream * FileStream = NULL;
  5194. bool DeleteLocalFile = false;
  5195. RawByteString RemoteHandle;
  5196. UnicodeString LocalFileName = DestFullName;
  5197. TSFTPOverwriteMode OverwriteMode = omOverwrite;
  5198. try
  5199. {
  5200. if (ResumeAllowed)
  5201. {
  5202. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  5203. LocalFileName = DestPartialFullName;
  5204. FTerminal->LogEvent(L"Checking existence of partially transfered file.");
  5205. if (FileExists(ApiPath(DestPartialFullName)))
  5206. {
  5207. FTerminal->LogEvent(L"Partially transfered file exists.");
  5208. FTerminal->OpenLocalFile(DestPartialFullName, GENERIC_WRITE,
  5209. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  5210. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->TransferSize);
  5211. if (FLAGCLEAR(Params, cpNoConfirmation))
  5212. {
  5213. ResumeTransfer = SFTPConfirmResume(DestFileName,
  5214. PartialBiggerThanSource, OperationProgress);
  5215. }
  5216. else
  5217. {
  5218. ResumeTransfer = !PartialBiggerThanSource;
  5219. if (!ResumeTransfer)
  5220. {
  5221. FTerminal->LogEvent(L"Partially transfered file is bigger that original file.");
  5222. }
  5223. }
  5224. if (!ResumeTransfer)
  5225. {
  5226. CloseHandle(LocalHandle);
  5227. LocalHandle = NULL;
  5228. FILE_OPERATION_LOOP_BEGIN
  5229. {
  5230. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestPartialFullName)));
  5231. }
  5232. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestPartialFullName)));
  5233. }
  5234. else
  5235. {
  5236. FTerminal->LogEvent(L"Resuming file transfer.");
  5237. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  5238. OperationProgress->AddResumed(ResumeOffset);
  5239. }
  5240. }
  5241. OperationProgress->Progress();
  5242. }
  5243. // first open source file, not to loose the destination file,
  5244. // if we cannot open the source one in the first place
  5245. FTerminal->LogEvent(L"Opening remote file.");
  5246. FILE_OPERATION_LOOP_BEGIN
  5247. {
  5248. int OpenType = SSH_FXF_READ;
  5249. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  5250. {
  5251. OpenType |= SSH_FXF_TEXT;
  5252. }
  5253. RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
  5254. OperationProgress->Progress();
  5255. }
  5256. FILE_OPERATION_LOOP_END(FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)));
  5257. TDateTime Modification;
  5258. FILETIME AcTime;
  5259. FILETIME WrTime;
  5260. TSFTPPacket RemoteFilePacket(SSH_FXP_FSTAT);
  5261. RemoteFilePacket.AddString(RemoteHandle);
  5262. SendCustomReadFile(&RemoteFilePacket, &RemoteFilePacket,
  5263. SSH_FILEXFER_ATTR_MODIFYTIME);
  5264. ReceiveResponse(&RemoteFilePacket, &RemoteFilePacket);
  5265. OperationProgress->Progress();
  5266. const TRemoteFile * AFile = File;
  5267. try
  5268. {
  5269. // ignore errors
  5270. if (RemoteFilePacket.Type == SSH_FXP_ATTRS)
  5271. {
  5272. // load file, avoid completion (resolving symlinks) as we do not need that
  5273. AFile = LoadFile(&RemoteFilePacket, NULL, UnixExtractFileName(FileName),
  5274. NULL, false);
  5275. }
  5276. Modification = AFile->Modification;
  5277. AcTime = DateTimeToFileTime(AFile->LastAccess,
  5278. FTerminal->SessionData->DSTMode);
  5279. WrTime = DateTimeToFileTime(Modification,
  5280. FTerminal->SessionData->DSTMode);
  5281. }
  5282. __finally
  5283. {
  5284. if (AFile != File)
  5285. {
  5286. delete AFile;
  5287. }
  5288. }
  5289. if ((Attrs >= 0) && !ResumeTransfer)
  5290. {
  5291. __int64 DestFileSize;
  5292. __int64 MTime;
  5293. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  5294. NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  5295. FTerminal->LogEvent(L"Confirming overwriting of file.");
  5296. TOverwriteFileParams FileParams;
  5297. FileParams.SourceSize = OperationProgress->TransferSize;
  5298. FileParams.SourceTimestamp = Modification;
  5299. FileParams.DestTimestamp = UnixToDateTime(MTime,
  5300. FTerminal->SessionData->DSTMode);
  5301. FileParams.DestSize = DestFileSize;
  5302. UnicodeString PrevDestFileName = DestFileName;
  5303. SFTPConfirmOverwrite(FileName, DestFileName, CopyParam, Params, OperationProgress, OverwriteMode, &FileParams);
  5304. if (PrevDestFileName != DestFileName)
  5305. {
  5306. DestFullName = TargetDir + DestFileName;
  5307. DestPartialFullName = DestFullName + FTerminal->Configuration->PartialExt;
  5308. if (ResumeAllowed)
  5309. {
  5310. if (FileExists(ApiPath(DestPartialFullName)))
  5311. {
  5312. FILE_OPERATION_LOOP_BEGIN
  5313. {
  5314. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(DestPartialFullName)));
  5315. }
  5316. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestPartialFullName)));
  5317. }
  5318. LocalFileName = DestPartialFullName;
  5319. }
  5320. else
  5321. {
  5322. LocalFileName = DestFullName;
  5323. }
  5324. }
  5325. if (OverwriteMode == omOverwrite)
  5326. {
  5327. // is NULL when overwriting read-only file
  5328. if (LocalHandle)
  5329. {
  5330. CloseHandle(LocalHandle);
  5331. LocalHandle = NULL;
  5332. }
  5333. }
  5334. else
  5335. {
  5336. // is NULL when overwriting read-only file, so following will
  5337. // probably fail anyway
  5338. if (LocalHandle == NULL)
  5339. {
  5340. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  5341. NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  5342. }
  5343. ResumeAllowed = false;
  5344. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  5345. if (OverwriteMode == omAppend)
  5346. {
  5347. FTerminal->LogEvent(L"Appending to file.");
  5348. }
  5349. else
  5350. {
  5351. FTerminal->LogEvent(L"Resuming file transfer (append style).");
  5352. DebugAssert(OverwriteMode == omResume);
  5353. OperationProgress->AddResumed(DestFileSize);
  5354. }
  5355. }
  5356. }
  5357. Action.Destination(ExpandUNCFileName(DestFullName));
  5358. // if not already opened (resume, append...), create new empty file
  5359. if (!LocalHandle)
  5360. {
  5361. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress,
  5362. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  5363. {
  5364. THROW_SKIP_FILE_NULL;
  5365. }
  5366. }
  5367. DebugAssert(LocalHandle);
  5368. DeleteLocalFile = true;
  5369. FileStream = new TSafeHandleStream((THandle)LocalHandle);
  5370. // at end of this block queue is discarded
  5371. {
  5372. TSFTPDownloadQueue Queue(this);
  5373. try
  5374. {
  5375. TSFTPPacket DataPacket;
  5376. int QueueLen = int(File->Size / DownloadBlockSize(OperationProgress)) + 1;
  5377. if ((QueueLen > FTerminal->SessionData->SFTPDownloadQueue) ||
  5378. (QueueLen < 0))
  5379. {
  5380. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  5381. }
  5382. if (QueueLen < 1)
  5383. {
  5384. QueueLen = 1;
  5385. }
  5386. Queue.Init(QueueLen, RemoteHandle, OperationProgress->TransferedSize,
  5387. OperationProgress);
  5388. bool Eof = false;
  5389. bool PrevIncomplete = false;
  5390. int GapFillCount = 0;
  5391. int GapCount = 0;
  5392. unsigned long Missing = 0;
  5393. unsigned long DataLen = 0;
  5394. unsigned long BlockSize;
  5395. bool ConvertToken = false;
  5396. while (!Eof)
  5397. {
  5398. if (Missing > 0)
  5399. {
  5400. Queue.InitFillGapRequest(OperationProgress->TransferedSize, Missing,
  5401. &DataPacket);
  5402. GapFillCount++;
  5403. SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
  5404. SSH_FXP_DATA, asEOF);
  5405. }
  5406. else
  5407. {
  5408. Queue.ReceivePacket(&DataPacket, BlockSize);
  5409. }
  5410. if (DataPacket.Type == SSH_FXP_STATUS)
  5411. {
  5412. // must be SSH_FX_EOF, any other status packet would raise exception
  5413. Eof = true;
  5414. // close file right away, before waiting for pending responses
  5415. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  5416. true, true, NULL);
  5417. RemoteHandle = L""; // do not close file again in __finally block
  5418. }
  5419. if (!Eof)
  5420. {
  5421. if ((Missing == 0) && PrevIncomplete)
  5422. {
  5423. // This can happen only if last request returned less bytes
  5424. // than expected, but exactly number of bytes missing to last
  5425. // known file size, but actually EOF was not reached.
  5426. // Can happen only when filesize has changed since directory
  5427. // listing and server returns less bytes than requested and
  5428. // file has some special file size.
  5429. FTerminal->LogEvent(FORMAT(
  5430. L"Received incomplete data packet before end of file, "
  5431. "offset: %s, size: %d, requested: %d",
  5432. (IntToStr(OperationProgress->TransferedSize), int(DataLen),
  5433. int(BlockSize))));
  5434. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  5435. }
  5436. // Buffer for one block of data
  5437. TFileBuffer BlockBuf;
  5438. DataLen = DataPacket.GetCardinal();
  5439. PrevIncomplete = false;
  5440. if (Missing > 0)
  5441. {
  5442. DebugAssert(DataLen <= Missing);
  5443. Missing -= DataLen;
  5444. }
  5445. else if (DataLen < BlockSize)
  5446. {
  5447. if (OperationProgress->TransferedSize + DataLen !=
  5448. OperationProgress->TransferSize)
  5449. {
  5450. // with native text transfer mode (SFTP>=4), do not bother about
  5451. // getting less than requested, read offset is ignored anyway
  5452. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  5453. {
  5454. GapCount++;
  5455. Missing = BlockSize - DataLen;
  5456. }
  5457. }
  5458. else
  5459. {
  5460. PrevIncomplete = true;
  5461. }
  5462. }
  5463. DebugAssert(DataLen <= BlockSize);
  5464. BlockBuf.Insert(0, reinterpret_cast<const char *>(DataPacket.GetNextData(DataLen)), DataLen);
  5465. DataPacket.DataConsumed(DataLen);
  5466. OperationProgress->AddTransfered(DataLen);
  5467. if ((FVersion >= 6) && DataPacket.CanGetBool() && (Missing == 0))
  5468. {
  5469. Eof = DataPacket.GetBool();
  5470. }
  5471. if (OperationProgress->AsciiTransfer)
  5472. {
  5473. DebugAssert(!ResumeTransfer && !ResumeAllowed);
  5474. unsigned int PrevBlockSize = BlockBuf.Size;
  5475. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0, ConvertToken);
  5476. OperationProgress->SetLocalSize(
  5477. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  5478. }
  5479. FILE_OPERATION_LOOP_BEGIN
  5480. {
  5481. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  5482. }
  5483. FILE_OPERATION_LOOP_END(FMTLOAD(WRITE_ERROR, (LocalFileName)));
  5484. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  5485. }
  5486. if (OperationProgress->Cancel == csCancel)
  5487. {
  5488. Abort();
  5489. }
  5490. };
  5491. if (GapCount > 0)
  5492. {
  5493. FTerminal->LogEvent(FORMAT(
  5494. L"%d requests to fill %d data gaps were issued.",
  5495. (GapFillCount, GapCount)));
  5496. }
  5497. }
  5498. __finally
  5499. {
  5500. Queue.DisposeSafe();
  5501. }
  5502. // queue is discarded here
  5503. }
  5504. if (CopyParam->PreserveTime)
  5505. {
  5506. FTerminal->LogEvent(FORMAT(L"Preserving timestamp [%s]",
  5507. (StandardTimestamp(Modification))));
  5508. SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
  5509. }
  5510. CloseHandle(LocalHandle);
  5511. LocalHandle = NULL;
  5512. if (ResumeAllowed)
  5513. {
  5514. FILE_OPERATION_LOOP_BEGIN
  5515. {
  5516. if (FileExists(ApiPath(DestFullName)))
  5517. {
  5518. DeleteFileChecked(DestFullName);
  5519. }
  5520. THROWOSIFFALSE(Sysutils::RenameFile(DestPartialFullName, DestFullName));
  5521. }
  5522. FILE_OPERATION_LOOP_END(
  5523. FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  5524. (ExtractFileName(DestPartialFullName), DestFileName)));
  5525. }
  5526. DeleteLocalFile = false;
  5527. if (Attrs == -1)
  5528. {
  5529. Attrs = faArchive;
  5530. }
  5531. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  5532. if ((NewAttrs & Attrs) != NewAttrs)
  5533. {
  5534. FILE_OPERATION_LOOP_BEGIN
  5535. {
  5536. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  5537. }
  5538. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  5539. }
  5540. }
  5541. __finally
  5542. {
  5543. if (LocalHandle) CloseHandle(LocalHandle);
  5544. if (FileStream) delete FileStream;
  5545. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocallyUsed == 0) &&
  5546. (OverwriteMode == omOverwrite))
  5547. {
  5548. FILE_OPERATION_LOOP_BEGIN
  5549. {
  5550. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(LocalFileName)));
  5551. }
  5552. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (LocalFileName)));
  5553. }
  5554. // if the transfer was finished, the file is closed already
  5555. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  5556. {
  5557. // do not wait for response
  5558. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  5559. true, true, NULL);
  5560. }
  5561. }
  5562. FTerminal->LogFileDone(OperationProgress);
  5563. }
  5564. if (Params & cpDelete)
  5565. {
  5566. ChildError = true;
  5567. // If file is directory, do not delete it recursively, because it should be
  5568. // empty already. If not, it should not be deleted (some files were
  5569. // skipped or some new files were copied to it, while we were downloading)
  5570. int Params = dfNoRecursive;
  5571. FTerminal->DeleteFile(FileName, File, &Params);
  5572. ChildError = false;
  5573. }
  5574. }
  5575. //---------------------------------------------------------------------------
  5576. void __fastcall TSFTPFileSystem::SFTPSinkFile(UnicodeString FileName,
  5577. const TRemoteFile * File, void * Param)
  5578. {
  5579. TSinkFileParams * Params = (TSinkFileParams *)Param;
  5580. DebugAssert(Params->OperationProgress);
  5581. try
  5582. {
  5583. SFTPSinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  5584. Params->Params, Params->OperationProgress, Params->Flags);
  5585. }
  5586. catch(EScpSkipFile & E)
  5587. {
  5588. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  5589. Params->Skipped = true;
  5590. {
  5591. TSuspendFileOperationProgress Suspend(OperationProgress);
  5592. if (!FTerminal->HandleException(&E))
  5593. {
  5594. throw;
  5595. }
  5596. }
  5597. if (OperationProgress->Cancel)
  5598. {
  5599. Abort();
  5600. }
  5601. }
  5602. }
  5603. //---------------------------------------------------------------------------
  5604. void __fastcall TSFTPFileSystem::RegisterChecksumAlg(const UnicodeString & Alg, const UnicodeString & SftpAlg)
  5605. {
  5606. FChecksumAlgs->Add(Alg);
  5607. FChecksumSftpAlgs->Add(SftpAlg);
  5608. }
  5609. //---------------------------------------------------------------------------
  5610. void __fastcall TSFTPFileSystem::GetSupportedChecksumAlgs(TStrings * Algs)
  5611. {
  5612. Algs->AddStrings(FChecksumAlgs.get());
  5613. }
  5614. //---------------------------------------------------------------------------
  5615. void __fastcall TSFTPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  5616. {
  5617. FAIL;
  5618. }
  5619. //---------------------------------------------------------------------------
  5620. void __fastcall TSFTPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  5621. {
  5622. FAIL;
  5623. }
  5624. //---------------------------------------------------------------------------
  5625. void __fastcall TSFTPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
  5626. {
  5627. // noop
  5628. }