SftpFileSystem.cpp 151 KB

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