SftpFileSystem.cpp 183 KB

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