SftpFileSystem.cpp 185 KB

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