SftpFileSystem.cpp 181 KB

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