SftpFileSystem.cpp 182 KB

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