SftpFileSystem.cpp 183 KB

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