SftpFileSystem.cpp 184 KB

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