SftpFileSystem.cpp 179 KB

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