SftpFileSystem.cpp 182 KB

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