SftpFileSystem.cpp 157 KB

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