SftpFileSystem.cpp 175 KB

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