SftpFileSystem.cpp 186 KB

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