SftpFileSystem.cpp 157 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288
  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)), varLongWord);
  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 int)FPacketNumbers.GetElement(Reservation))
  2010. {
  2011. TSFTPPacket * ReservedPacket;
  2012. unsigned int MessageNumber;
  2013. for (int Index = 0; Index < FPacketReservations->Count; Index++)
  2014. {
  2015. MessageNumber = (unsigned int)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 int)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)
  2129. {
  2130. delete AResponse;
  2131. }
  2132. }
  2133. return Result;
  2134. }
  2135. //---------------------------------------------------------------------------
  2136. int __fastcall TSFTPFileSystem::SendPacketAndReceiveResponse(
  2137. const TSFTPPacket * Packet, TSFTPPacket * Response, int ExpectedType,
  2138. int AllowStatus)
  2139. {
  2140. int Result;
  2141. TSFTPBusy Busy(this);
  2142. SendPacket(Packet);
  2143. Result = ReceiveResponse(Packet, Response, ExpectedType, AllowStatus);
  2144. return Result;
  2145. }
  2146. //---------------------------------------------------------------------------
  2147. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path)
  2148. {
  2149. try
  2150. {
  2151. FTerminal->LogEvent(FORMAT("Getting real path for '%s'",
  2152. (Path)));
  2153. TSFTPPacket Packet(SSH_FXP_REALPATH);
  2154. Packet.AddPathString(Path, FUtfStrings);
  2155. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_NAME);
  2156. if (Packet.GetCardinal() != 1)
  2157. {
  2158. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2159. }
  2160. AnsiString RealDir = UnixExcludeTrailingBackslash(Packet.GetPathString(FUtfStrings));
  2161. // ignore rest of SSH_FXP_NAME packet
  2162. FTerminal->LogEvent(FORMAT("Real path is '%s'", (RealDir)));
  2163. return RealDir;
  2164. }
  2165. catch(Exception & E)
  2166. {
  2167. if (FTerminal->Active)
  2168. {
  2169. throw ExtException(&E, FMTLOAD(SFTP_REALPATH_ERROR, (Path)));
  2170. }
  2171. else
  2172. {
  2173. throw;
  2174. }
  2175. }
  2176. }
  2177. //---------------------------------------------------------------------------
  2178. AnsiString __fastcall TSFTPFileSystem::RealPath(const AnsiString Path,
  2179. const AnsiString BaseDir)
  2180. {
  2181. AnsiString APath;
  2182. if (TTerminal::IsAbsolutePath(Path))
  2183. {
  2184. APath = Path;
  2185. }
  2186. else
  2187. {
  2188. if (!Path.IsEmpty())
  2189. {
  2190. // this condition/block was outside (before) current block
  2191. // but it dod not work when Path was empty
  2192. if (!BaseDir.IsEmpty())
  2193. {
  2194. APath = UnixIncludeTrailingBackslash(BaseDir);
  2195. }
  2196. APath = APath + Path;
  2197. }
  2198. if (APath.IsEmpty()) APath = UnixIncludeTrailingBackslash(".");
  2199. }
  2200. return RealPath(APath);
  2201. }
  2202. //---------------------------------------------------------------------------
  2203. AnsiString __fastcall TSFTPFileSystem::LocalCanonify(const AnsiString & Path)
  2204. {
  2205. // TODO: improve (handle .. etc.)
  2206. if (TTerminal::IsAbsolutePath(Path) ||
  2207. (!FCurrentDirectory.IsEmpty() && UnixComparePaths(FCurrentDirectory, Path)))
  2208. {
  2209. return Path;
  2210. }
  2211. else
  2212. {
  2213. return ::AbsolutePath(FCurrentDirectory, Path);
  2214. }
  2215. }
  2216. //---------------------------------------------------------------------------
  2217. AnsiString __fastcall TSFTPFileSystem::Canonify(AnsiString Path)
  2218. {
  2219. // inspired by canonify() from PSFTP.C
  2220. AnsiString Result;
  2221. FTerminal->LogEvent(FORMAT("Canonifying: \"%s\"", (Path)));
  2222. Path = LocalCanonify(Path);
  2223. bool TryParent = false;
  2224. try
  2225. {
  2226. Result = RealPath(Path);
  2227. }
  2228. catch(...)
  2229. {
  2230. if (FTerminal->Active)
  2231. {
  2232. TryParent = true;
  2233. }
  2234. else
  2235. {
  2236. throw;
  2237. }
  2238. }
  2239. if (TryParent)
  2240. {
  2241. AnsiString APath = UnixExcludeTrailingBackslash(Path);
  2242. AnsiString Name = UnixExtractFileName(APath);
  2243. if (Name == "." || Name == "..")
  2244. {
  2245. Result = Path;
  2246. }
  2247. else
  2248. {
  2249. AnsiString FPath = UnixExtractFilePath(APath);
  2250. try
  2251. {
  2252. Result = RealPath(FPath);
  2253. Result = UnixIncludeTrailingBackslash(Result) + Name;
  2254. }
  2255. catch(...)
  2256. {
  2257. if (FTerminal->Active)
  2258. {
  2259. Result = Path;
  2260. }
  2261. else
  2262. {
  2263. throw;
  2264. }
  2265. }
  2266. }
  2267. }
  2268. FTerminal->LogEvent(FORMAT("Canonified: \"%s\"", (Result)));
  2269. return Result;
  2270. }
  2271. //---------------------------------------------------------------------------
  2272. AnsiString __fastcall TSFTPFileSystem::AbsolutePath(AnsiString Path, bool Local)
  2273. {
  2274. if (Local)
  2275. {
  2276. return LocalCanonify(Path);
  2277. }
  2278. else
  2279. {
  2280. return RealPath(Path, CurrentDirectory);
  2281. }
  2282. }
  2283. //---------------------------------------------------------------------------
  2284. AnsiString __fastcall TSFTPFileSystem::GetHomeDirectory()
  2285. {
  2286. if (FHomeDirectory.IsEmpty())
  2287. {
  2288. FHomeDirectory = RealPath(".");
  2289. }
  2290. return FHomeDirectory;
  2291. }
  2292. //---------------------------------------------------------------------------
  2293. void __fastcall TSFTPFileSystem::LoadFile(TRemoteFile * File, TSFTPPacket * Packet,
  2294. bool Complete)
  2295. {
  2296. Packet->GetFile(File, FVersion, FTerminal->SessionData->DSTMode,
  2297. FUtfStrings, FSignedTS, Complete);
  2298. }
  2299. //---------------------------------------------------------------------------
  2300. TRemoteFile * __fastcall TSFTPFileSystem::LoadFile(TSFTPPacket * Packet,
  2301. TRemoteFile * ALinkedByFile, const AnsiString FileName,
  2302. TRemoteFileList * TempFileList, bool Complete)
  2303. {
  2304. TRemoteFile * File = new TRemoteFile(ALinkedByFile);
  2305. try
  2306. {
  2307. File->Terminal = FTerminal;
  2308. if (!FileName.IsEmpty())
  2309. {
  2310. File->FileName = FileName;
  2311. }
  2312. // to get full path for symlink completion
  2313. File->Directory = TempFileList;
  2314. LoadFile(File, Packet, Complete);
  2315. File->Directory = NULL;
  2316. }
  2317. catch(...)
  2318. {
  2319. delete File;
  2320. throw;
  2321. }
  2322. return File;
  2323. }
  2324. //---------------------------------------------------------------------------
  2325. AnsiString __fastcall TSFTPFileSystem::GetCurrentDirectory()
  2326. {
  2327. return FCurrentDirectory;
  2328. }
  2329. //---------------------------------------------------------------------------
  2330. void __fastcall TSFTPFileSystem::DoStartup()
  2331. {
  2332. FFileSystemInfoValid = false;
  2333. TSFTPPacket Packet(SSH_FXP_INIT);
  2334. int MaxVersion = FTerminal->SessionData->SFTPMaxVersion;
  2335. if (MaxVersion > SFTPMaxVersion)
  2336. {
  2337. MaxVersion = SFTPMaxVersion;
  2338. }
  2339. Packet.AddCardinal(MaxVersion);
  2340. try
  2341. {
  2342. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_VERSION);
  2343. }
  2344. catch(Exception &E)
  2345. {
  2346. FTerminal->FatalError(&E, LoadStr(SFTP_INITIALIZE_ERROR));
  2347. }
  2348. FVersion = Packet.GetCardinal();
  2349. FTerminal->LogEvent(FORMAT("SFTP version %d negotiated.", (FVersion)));
  2350. if (FVersion < SFTPMinVersion || FVersion > SFTPMaxVersion)
  2351. {
  2352. FTerminal->FatalError(NULL, FMTLOAD(SFTP_VERSION_NOT_SUPPORTED,
  2353. (FVersion, SFTPMinVersion, SFTPMaxVersion)));
  2354. }
  2355. FExtensions->Clear();
  2356. FEOL = "\r\n";
  2357. FSupport->Loaded = false;
  2358. SAFE_DESTROY(FFixedPaths);
  2359. if (FVersion >= 3)
  2360. {
  2361. while (Packet.GetNextData() != NULL)
  2362. {
  2363. AnsiString ExtensionName = Packet.GetString();
  2364. AnsiString ExtensionData = Packet.GetString();
  2365. AnsiString ExtensionDisplayData = DisplayableStr(ExtensionData);
  2366. if (ExtensionName == SFTP_EXT_NEWLINE)
  2367. {
  2368. FEOL = ExtensionData;
  2369. FTerminal->LogEvent(FORMAT("Server requests EOL sequence %s.",
  2370. (ExtensionDisplayData)));
  2371. if (FEOL.Length() < 1 || FEOL.Length() > 2)
  2372. {
  2373. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_EOL, (ExtensionDisplayData)));
  2374. }
  2375. }
  2376. // do not allow "supported" to override "supported2" if both are received
  2377. else if (((ExtensionName == SFTP_EXT_SUPPORTED) && !FSupport->Loaded) ||
  2378. (ExtensionName == SFTP_EXT_SUPPORTED2))
  2379. {
  2380. FSupport->Reset();
  2381. TSFTPPacket SupportedStruct(ExtensionData);
  2382. FSupport->Loaded = true;
  2383. FSupport->AttributeMask = SupportedStruct.GetCardinal();
  2384. FSupport->AttributeBits = SupportedStruct.GetCardinal();
  2385. FSupport->OpenFlags = SupportedStruct.GetCardinal();
  2386. FSupport->AccessMask = SupportedStruct.GetCardinal();
  2387. FSupport->MaxReadSize = SupportedStruct.GetCardinal();
  2388. if (ExtensionName == SFTP_EXT_SUPPORTED)
  2389. {
  2390. while (SupportedStruct.GetNextData() != NULL)
  2391. {
  2392. FSupport->Extensions->Add(SupportedStruct.GetString());
  2393. }
  2394. }
  2395. else
  2396. {
  2397. FSupport->OpenBlockMasks = SupportedStruct.GetSmallCardinal();
  2398. FSupport->BlockMasks = SupportedStruct.GetSmallCardinal();
  2399. unsigned int ExtensionCount;
  2400. ExtensionCount = SupportedStruct.GetCardinal();
  2401. for (unsigned int i = 0; i < ExtensionCount; i++)
  2402. {
  2403. FSupport->AttribExtensions->Add(SupportedStruct.GetString());
  2404. }
  2405. ExtensionCount = SupportedStruct.GetCardinal();
  2406. for (unsigned int i = 0; i < ExtensionCount; i++)
  2407. {
  2408. FSupport->Extensions->Add(SupportedStruct.GetString());
  2409. }
  2410. }
  2411. if (FTerminal->Log->Logging)
  2412. {
  2413. FTerminal->LogEvent(FORMAT(
  2414. "Server support information:\n"
  2415. " Attribute mask: %x, Attribute bits: %x, Open flags: %x\n"
  2416. " Access mask: %x, Open block masks: %x, Block masks: %x, Max read size: %d\n",
  2417. (int(FSupport->AttributeMask),
  2418. int(FSupport->AttributeBits),
  2419. int(FSupport->OpenFlags),
  2420. int(FSupport->AccessMask),
  2421. int(FSupport->OpenBlockMasks),
  2422. int(FSupport->BlockMasks),
  2423. int(FSupport->MaxReadSize))));
  2424. FTerminal->LogEvent(FORMAT( " Attribute extensions (%d)\n", (FSupport->AttribExtensions->Count)));
  2425. for (int Index = 0; Index < FSupport->AttribExtensions->Count; Index++)
  2426. {
  2427. FTerminal->LogEvent(
  2428. FORMAT(" %s", (FSupport->AttribExtensions->Strings[Index])));
  2429. }
  2430. FTerminal->LogEvent(FORMAT( " Extensions (%d)\n", (FSupport->Extensions->Count)));
  2431. for (int Index = 0; Index < FSupport->Extensions->Count; Index++)
  2432. {
  2433. FTerminal->LogEvent(
  2434. FORMAT(" %s", (FSupport->Extensions->Strings[Index])));
  2435. }
  2436. }
  2437. }
  2438. else if (ExtensionName == SFTP_EXT_VENDOR_ID)
  2439. {
  2440. TSFTPPacket VendorIdStruct(ExtensionData);
  2441. AnsiString VendorName(VendorIdStruct.GetString());
  2442. AnsiString ProductName(VendorIdStruct.GetString());
  2443. AnsiString ProductVersion(VendorIdStruct.GetString());
  2444. __int64 ProductBuildNumber = VendorIdStruct.GetInt64();
  2445. FTerminal->LogEvent(FORMAT("Server software: %s %s (%d) by %s",
  2446. (ProductName, ProductVersion, int(ProductBuildNumber), VendorName)));
  2447. }
  2448. else if (ExtensionName == SFTP_EXT_FSROOTS)
  2449. {
  2450. FTerminal->LogEvent("File system roots:\n");
  2451. assert(FFixedPaths == NULL);
  2452. FFixedPaths = new TStringList();
  2453. try
  2454. {
  2455. TSFTPPacket RootsPacket(ExtensionData);
  2456. while (RootsPacket.GetNextData() != NULL)
  2457. {
  2458. unsigned long Dummy = RootsPacket.GetCardinal();
  2459. if (Dummy != 1)
  2460. {
  2461. break;
  2462. }
  2463. else
  2464. {
  2465. char Drive = RootsPacket.GetByte();
  2466. char MaybeType = RootsPacket.GetByte();
  2467. FTerminal->LogEvent(FORMAT(" %s: (type %d)", (Drive, (int)MaybeType)));
  2468. FFixedPaths->Add(FORMAT("%s:", (Drive)));
  2469. }
  2470. }
  2471. }
  2472. catch(Exception & E)
  2473. {
  2474. FFixedPaths->Clear();
  2475. FTerminal->LogEvent(FORMAT("Failed to decode %s extension",
  2476. (SFTP_EXT_FSROOTS)));
  2477. FTerminal->HandleException(&E);
  2478. }
  2479. }
  2480. else if (ExtensionName == SFTP_EXT_VERSIONS)
  2481. {
  2482. try
  2483. {
  2484. // first try legacy decoding according to incorrect encoding
  2485. // (structure-like) as of VShell.
  2486. TSFTPPacket VersionsPacket(ExtensionData);
  2487. AnsiString Versions = VersionsPacket.GetString();
  2488. if (VersionsPacket.GetNextData() != NULL)
  2489. {
  2490. Abort();
  2491. }
  2492. FTerminal->LogEvent(FORMAT("SFTP versions supported by the server (VShell format): %s",
  2493. (Versions)));
  2494. }
  2495. catch(...)
  2496. {
  2497. // if that fails, fallback to proper decoding
  2498. FTerminal->LogEvent(FORMAT("SFTP versions supported by the server: %s",
  2499. (ExtensionData)));
  2500. }
  2501. }
  2502. else
  2503. {
  2504. FTerminal->LogEvent(FORMAT("Unknown server extension %s=%s",
  2505. (ExtensionName, ExtensionDisplayData)));
  2506. }
  2507. FExtensions->Values[ExtensionName] = ExtensionData;
  2508. }
  2509. if (SupportsExtension(SFTP_EXT_VENDOR_ID))
  2510. {
  2511. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  2512. Packet.AddString(SFTP_EXT_VENDOR_ID);
  2513. Packet.AddString(FTerminal->Configuration->CompanyName);
  2514. Packet.AddString(FTerminal->Configuration->ProductName);
  2515. Packet.AddString(FTerminal->Configuration->ProductVersion);
  2516. Packet.AddInt64(LOWORD(FTerminal->Configuration->FixedApplicationInfo->dwFileVersionLS));
  2517. SendPacket(&Packet);
  2518. // we are not interested in the response, do not wait for it
  2519. ReserveResponse(&Packet, NULL);
  2520. }
  2521. }
  2522. if (FVersion < 4)
  2523. {
  2524. // currently enable the bug for all servers (really known on OpenSSH)
  2525. FSignedTS = (FTerminal->SessionData->SFTPBug[sbSignedTS] == asOn) ||
  2526. (FTerminal->SessionData->SFTPBug[sbSignedTS] == asAuto);
  2527. if (FSignedTS)
  2528. {
  2529. FTerminal->LogEvent("We believe the server has signed timestamps bug");
  2530. }
  2531. }
  2532. else
  2533. {
  2534. FSignedTS = false;
  2535. }
  2536. // use UTF when forced or ...
  2537. // when "auto" and version is at least 4 and the server is not know not to use UTF
  2538. FUtfNever = (GetSessionInfo().SshImplementation.Pos("Foxit-WAC-Server") == 1) ||
  2539. (FTerminal->SessionData->NotUtf == asOn);
  2540. FUtfStrings =
  2541. (FTerminal->SessionData->NotUtf == asOff) ||
  2542. ((FTerminal->SessionData->NotUtf == asAuto) &&
  2543. (FVersion >= 4) && !FUtfNever);
  2544. if (FUtfStrings)
  2545. {
  2546. FTerminal->LogEvent("We will use UTF-8 strings when appropriate");
  2547. }
  2548. else if (FUtfNever)
  2549. {
  2550. FTerminal->LogEvent("We will never use UTF-8 strings");
  2551. }
  2552. else
  2553. {
  2554. FTerminal->LogEvent("We will use UTF-8 strings for status messages only");
  2555. }
  2556. FOpenSSH =
  2557. // Sun SSH is based on OpenSSH (suffers the same bugs)
  2558. (GetSessionInfo().SshImplementation.Pos("OpenSSH") == 1) ||
  2559. (GetSessionInfo().SshImplementation.Pos("Sun_SSH") == 1);
  2560. FMaxPacketSize = FTerminal->SessionData->SFTPMaxPacketSize;
  2561. if (FMaxPacketSize == 0)
  2562. {
  2563. if (FOpenSSH && (FVersion == 3) && !FSupport->Loaded)
  2564. {
  2565. FMaxPacketSize = 4 + (256 * 1024); // len + 256kB payload
  2566. FTerminal->LogEvent(FORMAT("Limiting packet size to OpenSSH sftp-server limit of %d bytes",
  2567. (int(FMaxPacketSize))));
  2568. }
  2569. // full string is "1.77 sshlib: Momentum SSH Server",
  2570. // possibly it is sshlib-related
  2571. else if (GetSessionInfo().SshImplementation.Pos("Momentum SSH Server") != 0)
  2572. {
  2573. FMaxPacketSize = 4 + (32 * 1024);
  2574. FTerminal->LogEvent(FORMAT("Limiting packet size to Momentum sftp-server limit of %d bytes",
  2575. (int(FMaxPacketSize))));
  2576. }
  2577. }
  2578. }
  2579. //---------------------------------------------------------------------------
  2580. char * __fastcall TSFTPFileSystem::GetEOL() const
  2581. {
  2582. if (FVersion >= 4)
  2583. {
  2584. assert(!FEOL.IsEmpty());
  2585. return FEOL.c_str();
  2586. }
  2587. else
  2588. {
  2589. return EOLToStr(FTerminal->SessionData->EOLType);
  2590. }
  2591. }
  2592. //---------------------------------------------------------------------------
  2593. void __fastcall TSFTPFileSystem::LookupUsersGroups()
  2594. {
  2595. assert(SupportsExtension(SFTP_EXT_OWNER_GROUP));
  2596. TSFTPPacket PacketOwners(SSH_FXP_EXTENDED);
  2597. TSFTPPacket PacketGroups(SSH_FXP_EXTENDED);
  2598. TSFTPPacket * Packets[] = { &PacketOwners, &PacketGroups };
  2599. TRemoteTokenList * Lists[] = { &FTerminal->FUsers, &FTerminal->FGroups };
  2600. char ListTypes[] = { OGQ_LIST_OWNERS, OGQ_LIST_GROUPS };
  2601. for (int Index = 0; Index < LENOF(Packets); Index++)
  2602. {
  2603. TSFTPPacket * Packet = Packets[Index];
  2604. Packet->AddString(SFTP_EXT_OWNER_GROUP);
  2605. Packet->AddByte(ListTypes[Index]);
  2606. SendPacket(Packet);
  2607. ReserveResponse(Packet, Packet);
  2608. }
  2609. for (int Index = 0; Index < LENOF(Packets); Index++)
  2610. {
  2611. TSFTPPacket * Packet = Packets[Index];
  2612. ReceiveResponse(Packet, Packet, SSH_FXP_EXTENDED_REPLY, asOpUnsupported);
  2613. if ((Packet->Type != SSH_FXP_EXTENDED_REPLY) ||
  2614. (Packet->GetString() != SFTP_EXT_OWNER_GROUP_REPLY))
  2615. {
  2616. FTerminal->LogEvent(FORMAT("Invalid response to %s", (SFTP_EXT_OWNER_GROUP)));
  2617. }
  2618. else
  2619. {
  2620. TRemoteTokenList & List = *Lists[Index];
  2621. unsigned long Count = Packet->GetCardinal();
  2622. List.Clear();
  2623. for (unsigned long Item = 0; Item < Count; Item++)
  2624. {
  2625. TRemoteToken Token(Packet->GetString(!FUtfNever));
  2626. List.Add(Token);
  2627. if (&List == &FTerminal->FGroups)
  2628. {
  2629. FTerminal->FMembership.Add(Token);
  2630. }
  2631. }
  2632. }
  2633. }
  2634. }
  2635. //---------------------------------------------------------------------------
  2636. void __fastcall TSFTPFileSystem::ReadCurrentDirectory()
  2637. {
  2638. if (!FDirectoryToChangeTo.IsEmpty())
  2639. {
  2640. FCurrentDirectory = FDirectoryToChangeTo;
  2641. FDirectoryToChangeTo = "";
  2642. }
  2643. else if (FCurrentDirectory.IsEmpty())
  2644. {
  2645. // this happens only after startup when default remote directory is not specified
  2646. FCurrentDirectory = GetHomeDirectory();
  2647. }
  2648. }
  2649. //---------------------------------------------------------------------------
  2650. void __fastcall TSFTPFileSystem::HomeDirectory()
  2651. {
  2652. ChangeDirectory(GetHomeDirectory());
  2653. }
  2654. //---------------------------------------------------------------------------
  2655. void __fastcall TSFTPFileSystem::TryOpenDirectory(const AnsiString Directory)
  2656. {
  2657. FTerminal->LogEvent(FORMAT("Trying to open directory \"%s\".", (Directory)));
  2658. TRemoteFile * File;
  2659. CustomReadFile(Directory, File, SSH_FXP_LSTAT, NULL, asOpUnsupported);
  2660. if (File == NULL)
  2661. {
  2662. // File can be NULL only when server does not support SSH_FXP_LSTAT.
  2663. // Fallback to legacy solution, which in turn does not allow entering
  2664. // traverse-only (chmod 110) directories.
  2665. // This is workaround for http://www.ftpshell.com/
  2666. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2667. Packet.AddPathString(UnixExcludeTrailingBackslash(Directory), FUtfStrings);
  2668. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2669. AnsiString Handle = Packet.GetString();
  2670. Packet.ChangeType(SSH_FXP_CLOSE);
  2671. Packet.AddString(Handle);
  2672. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS, asAll);
  2673. }
  2674. else
  2675. {
  2676. delete File;
  2677. }
  2678. }
  2679. //---------------------------------------------------------------------------
  2680. void __fastcall TSFTPFileSystem::AnnounceFileListOperation()
  2681. {
  2682. }
  2683. //---------------------------------------------------------------------------
  2684. void __fastcall TSFTPFileSystem::ChangeDirectory(const AnsiString Directory)
  2685. {
  2686. AnsiString Path, Current;
  2687. Current = !FDirectoryToChangeTo.IsEmpty() ? FDirectoryToChangeTo : FCurrentDirectory;
  2688. Path = RealPath(Directory, Current);
  2689. // to verify existence of directory try to open it (SSH_FXP_REALPATH succeeds
  2690. // for invalid paths on some systems, like CygWin)
  2691. TryOpenDirectory(Path);
  2692. // if open dir did not fail, directory exists -> success.
  2693. FDirectoryToChangeTo = Path;
  2694. }
  2695. //---------------------------------------------------------------------------
  2696. void __fastcall TSFTPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  2697. {
  2698. FDirectoryToChangeTo = UnixExcludeTrailingBackslash(Directory);
  2699. }
  2700. //---------------------------------------------------------------------------
  2701. void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  2702. {
  2703. assert(FileList && !FileList->Directory.IsEmpty());
  2704. AnsiString Directory;
  2705. Directory = UnixExcludeTrailingBackslash(LocalCanonify(FileList->Directory));
  2706. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".", (Directory)));
  2707. // moved before SSH_FXP_OPENDIR, so directory listing does not retain
  2708. // old data (e.g. parent directory) when reading fails
  2709. FileList->Clear();
  2710. TSFTPPacket Packet(SSH_FXP_OPENDIR);
  2711. AnsiString Handle;
  2712. try
  2713. {
  2714. Packet.AddPathString(Directory, FUtfStrings);
  2715. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  2716. Handle = Packet.GetString();
  2717. }
  2718. catch(...)
  2719. {
  2720. if (FTerminal->Active)
  2721. {
  2722. FileList->AddFile(new TRemoteParentDirectory(FTerminal));
  2723. }
  2724. throw;
  2725. }
  2726. TSFTPPacket Response;
  2727. try
  2728. {
  2729. bool isEOF = false;
  2730. int Total = 0;
  2731. TRemoteFile * File;
  2732. Packet.ChangeType(SSH_FXP_READDIR);
  2733. Packet.AddString(Handle);
  2734. SendPacket(&Packet);
  2735. do
  2736. {
  2737. ReceiveResponse(&Packet, &Response);
  2738. if (Response.Type == SSH_FXP_NAME)
  2739. {
  2740. TSFTPPacket ListingPacket = Response;
  2741. Packet.ChangeType(SSH_FXP_READDIR);
  2742. Packet.AddString(Handle);
  2743. SendPacket(&Packet);
  2744. ReserveResponse(&Packet, &Response);
  2745. unsigned int Count = ListingPacket.GetCardinal();
  2746. for (unsigned long Index = 0; !isEOF && (Index < Count); Index++)
  2747. {
  2748. File = LoadFile(&ListingPacket, NULL, "", FileList);
  2749. if (FTerminal->Configuration->ActualLogProtocol >= 1)
  2750. {
  2751. FTerminal->LogEvent(FORMAT("Read file '%s' from listing", (File->FileName)));
  2752. }
  2753. FileList->AddFile(File);
  2754. Total++;
  2755. if (Total % 10 == 0)
  2756. {
  2757. FTerminal->DoReadDirectoryProgress(Total, isEOF);
  2758. if (isEOF)
  2759. {
  2760. FTerminal->DoReadDirectoryProgress(-2, isEOF);
  2761. }
  2762. }
  2763. }
  2764. if (Count == 0)
  2765. {
  2766. FTerminal->LogEvent("Empty directory listing packet. Aborting directory reading.");
  2767. isEOF = true;
  2768. }
  2769. }
  2770. else if (Response.Type == SSH_FXP_STATUS)
  2771. {
  2772. isEOF = (GotStatusPacket(&Response, asEOF) == SSH_FX_EOF);
  2773. }
  2774. else
  2775. {
  2776. FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type)));
  2777. }
  2778. }
  2779. while (!isEOF);
  2780. if (Total == 0)
  2781. {
  2782. // Empty file list -> probably "permision denied", we
  2783. // at least get link to parent directory ("..")
  2784. try
  2785. {
  2786. FTerminal->ExceptionOnFail = true;
  2787. try
  2788. {
  2789. File = NULL;
  2790. FTerminal->ReadFile(
  2791. UnixIncludeTrailingBackslash(FileList->Directory) + PARENTDIRECTORY, File);
  2792. }
  2793. __finally
  2794. {
  2795. FTerminal->ExceptionOnFail = false;
  2796. }
  2797. }
  2798. catch(Exception &E)
  2799. {
  2800. if (E.InheritsFrom(__classid(EFatal))) throw;
  2801. else File = NULL;
  2802. }
  2803. // on some systems even getting ".." fails, we create dummy ".." instead
  2804. bool Failure = (File == NULL);
  2805. if (Failure)
  2806. {
  2807. File = new TRemoteParentDirectory(FTerminal);
  2808. }
  2809. assert(File && File->IsParentDirectory);
  2810. FileList->AddFile(File);
  2811. if (Failure)
  2812. {
  2813. throw Exception(FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)));
  2814. }
  2815. }
  2816. }
  2817. __finally
  2818. {
  2819. if (FTerminal->Active)
  2820. {
  2821. Packet.ChangeType(SSH_FXP_CLOSE);
  2822. Packet.AddString(Handle);
  2823. SendPacket(&Packet);
  2824. // we are not interested in the response, do not wait for it
  2825. ReserveResponse(&Packet, NULL);
  2826. }
  2827. }
  2828. }
  2829. //---------------------------------------------------------------------------
  2830. void __fastcall TSFTPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  2831. TRemoteFile *& File)
  2832. {
  2833. assert(SymlinkFile && SymlinkFile->IsSymLink);
  2834. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  2835. // need to use full filename when resolving links within subdirectory
  2836. // (i.e. for download)
  2837. AnsiString FileName = LocalCanonify(
  2838. SymlinkFile->Directory != NULL ? SymlinkFile->FullFileName : SymlinkFile->FileName);
  2839. TSFTPPacket ReadLinkPacket(SSH_FXP_READLINK);
  2840. ReadLinkPacket.AddPathString(FileName, FUtfStrings);
  2841. SendPacket(&ReadLinkPacket);
  2842. ReserveResponse(&ReadLinkPacket, &ReadLinkPacket);
  2843. // send second request before reading response to first one
  2844. // (performance benefit)
  2845. TSFTPPacket AttrsPacket(SSH_FXP_STAT);
  2846. AttrsPacket.AddPathString(FileName, FUtfStrings);
  2847. if (FVersion >= 4)
  2848. {
  2849. AttrsPacket.AddCardinal(SSH_FILEXFER_ATTR_COMMON);
  2850. }
  2851. SendPacket(&AttrsPacket);
  2852. ReserveResponse(&AttrsPacket, &AttrsPacket);
  2853. ReceiveResponse(&ReadLinkPacket, &ReadLinkPacket, SSH_FXP_NAME);
  2854. if (ReadLinkPacket.GetCardinal() != 1)
  2855. {
  2856. FTerminal->FatalError(NULL, LoadStr(SFTP_NON_ONE_FXP_NAME_PACKET));
  2857. }
  2858. SymlinkFile->LinkTo = ReadLinkPacket.GetPathString(FUtfStrings);
  2859. ReceiveResponse(&AttrsPacket, &AttrsPacket, SSH_FXP_ATTRS);
  2860. // SymlinkFile->FileName was used instead SymlinkFile->LinkTo before, why?
  2861. File = LoadFile(&AttrsPacket, SymlinkFile,
  2862. UnixExtractFileName(SymlinkFile->LinkTo));
  2863. }
  2864. //---------------------------------------------------------------------------
  2865. void __fastcall TSFTPFileSystem::ReadFile(const AnsiString FileName,
  2866. TRemoteFile *& File)
  2867. {
  2868. CustomReadFile(FileName, File, SSH_FXP_LSTAT);
  2869. }
  2870. //---------------------------------------------------------------------------
  2871. bool __fastcall TSFTPFileSystem::RemoteFileExists(const AnsiString FullPath,
  2872. TRemoteFile ** File)
  2873. {
  2874. bool Result;
  2875. try
  2876. {
  2877. TRemoteFile * AFile;
  2878. CustomReadFile(FullPath, AFile, SSH_FXP_LSTAT, NULL, asNoSuchFile);
  2879. Result = (AFile != NULL);
  2880. if (Result)
  2881. {
  2882. if (File)
  2883. {
  2884. *File = AFile;
  2885. }
  2886. else
  2887. {
  2888. delete AFile;
  2889. }
  2890. }
  2891. }
  2892. catch(...)
  2893. {
  2894. if (!FTerminal->Active)
  2895. {
  2896. throw;
  2897. }
  2898. Result = false;
  2899. }
  2900. return Result;
  2901. }
  2902. //---------------------------------------------------------------------------
  2903. void __fastcall TSFTPFileSystem::SendCustomReadFile(TSFTPPacket * Packet,
  2904. TSFTPPacket * Response, const AnsiString FileName, unsigned long Flags)
  2905. {
  2906. if ((Packet->Type == SSH_FXP_STAT) || (Packet->Type == SSH_FXP_LSTAT))
  2907. {
  2908. Packet->AddPathString(LocalCanonify(FileName), FUtfStrings);
  2909. }
  2910. else
  2911. {
  2912. assert(Packet->Type == SSH_FXP_FSTAT);
  2913. // actualy handle, not filename
  2914. Packet->AddString(FileName);
  2915. }
  2916. if (FVersion >= 4)
  2917. {
  2918. Packet->AddCardinal(Flags);
  2919. }
  2920. SendPacket(Packet);
  2921. ReserveResponse(Packet, Response);
  2922. }
  2923. //---------------------------------------------------------------------------
  2924. void __fastcall TSFTPFileSystem::CustomReadFile(const AnsiString FileName,
  2925. TRemoteFile *& File, char Type, TRemoteFile * ALinkedByFile,
  2926. int AllowStatus)
  2927. {
  2928. unsigned long Flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS |
  2929. SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
  2930. SSH_FILEXFER_ATTR_OWNERGROUP;
  2931. TSFTPPacket Packet(Type);
  2932. SendCustomReadFile(&Packet, &Packet, FileName, Flags);
  2933. ReceiveResponse(&Packet, &Packet, SSH_FXP_ATTRS, AllowStatus);
  2934. if (Packet.Type == SSH_FXP_ATTRS)
  2935. {
  2936. File = LoadFile(&Packet, ALinkedByFile, UnixExtractFileName(FileName));
  2937. }
  2938. else
  2939. {
  2940. assert(AllowStatus > 0);
  2941. File = NULL;
  2942. }
  2943. }
  2944. //---------------------------------------------------------------------------
  2945. void __fastcall TSFTPFileSystem::DoDeleteFile(const AnsiString FileName, char Type)
  2946. {
  2947. TSFTPPacket Packet(Type);
  2948. AnsiString RealFileName = LocalCanonify(FileName);
  2949. Packet.AddPathString(RealFileName, FUtfStrings);
  2950. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  2951. }
  2952. //---------------------------------------------------------------------------
  2953. void __fastcall TSFTPFileSystem::DeleteFile(const AnsiString FileName,
  2954. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  2955. {
  2956. char Type;
  2957. if (File && File->IsDirectory && !File->IsSymLink)
  2958. {
  2959. if (FLAGCLEAR(Params, dfNoRecursive))
  2960. {
  2961. try
  2962. {
  2963. FTerminal->ProcessDirectory(FileName, FTerminal->DeleteFile, &Params);
  2964. }
  2965. catch(...)
  2966. {
  2967. Action.Cancel();
  2968. throw;
  2969. }
  2970. }
  2971. Type = SSH_FXP_RMDIR;
  2972. }
  2973. else
  2974. {
  2975. Type = SSH_FXP_REMOVE;
  2976. }
  2977. DoDeleteFile(FileName, Type);
  2978. }
  2979. //---------------------------------------------------------------------------
  2980. void __fastcall TSFTPFileSystem::RenameFile(const AnsiString FileName,
  2981. const AnsiString NewName)
  2982. {
  2983. TSFTPPacket Packet(SSH_FXP_RENAME);
  2984. AnsiString RealName = LocalCanonify(FileName);
  2985. Packet.AddPathString(RealName, FUtfStrings);
  2986. AnsiString TargetName;
  2987. if (UnixExtractFilePath(NewName).IsEmpty())
  2988. {
  2989. // rename case (TTerminal::RenameFile)
  2990. TargetName = UnixExtractFilePath(RealName) + NewName;
  2991. }
  2992. else
  2993. {
  2994. TargetName = LocalCanonify(NewName);
  2995. }
  2996. Packet.AddPathString(TargetName, FUtfStrings);
  2997. if (FVersion >= 5)
  2998. {
  2999. Packet.AddCardinal(0);
  3000. }
  3001. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3002. }
  3003. //---------------------------------------------------------------------------
  3004. void __fastcall TSFTPFileSystem::CopyFile(const AnsiString /*FileName*/,
  3005. const AnsiString /*NewName*/)
  3006. {
  3007. assert(false);
  3008. }
  3009. //---------------------------------------------------------------------------
  3010. void __fastcall TSFTPFileSystem::CreateDirectory(const AnsiString DirName)
  3011. {
  3012. TSFTPPacket Packet(SSH_FXP_MKDIR);
  3013. AnsiString CanonifiedName = Canonify(DirName);
  3014. Packet.AddPathString(CanonifiedName, FUtfStrings);
  3015. Packet.AddProperties(NULL, 0, true, FVersion, FUtfStrings, NULL);
  3016. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3017. }
  3018. //---------------------------------------------------------------------------
  3019. void __fastcall TSFTPFileSystem::CreateLink(const AnsiString FileName,
  3020. const AnsiString PointTo, bool Symbolic)
  3021. {
  3022. USEDPARAM(Symbolic);
  3023. assert(Symbolic); // only symlinks are supported by SFTP
  3024. assert(FVersion >= 3); // symlinks are supported with SFTP version 3 and later
  3025. TSFTPPacket Packet(SSH_FXP_SYMLINK);
  3026. bool Buggy = (FTerminal->SessionData->SFTPBug[sbSymlink] == asOn) ||
  3027. ((FTerminal->SessionData->SFTPBug[sbSymlink] == asAuto) && FOpenSSH);
  3028. if (!Buggy)
  3029. {
  3030. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  3031. Packet.AddPathString(PointTo, FUtfStrings);
  3032. }
  3033. else
  3034. {
  3035. FTerminal->LogEvent("We believe the server has SFTP symlink bug");
  3036. Packet.AddPathString(PointTo, FUtfStrings);
  3037. Packet.AddPathString(Canonify(FileName), FUtfStrings);
  3038. }
  3039. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3040. }
  3041. //---------------------------------------------------------------------------
  3042. void __fastcall TSFTPFileSystem::ChangeFileProperties(const AnsiString FileName,
  3043. const TRemoteFile * /*File*/, const TRemoteProperties * AProperties,
  3044. TChmodSessionAction & Action)
  3045. {
  3046. assert(AProperties != NULL);
  3047. TRemoteFile * File;
  3048. AnsiString RealFileName = LocalCanonify(FileName);
  3049. ReadFile(RealFileName, File);
  3050. try
  3051. {
  3052. assert(File);
  3053. if (File->IsDirectory && !File->IsSymLink && AProperties->Recursive)
  3054. {
  3055. try
  3056. {
  3057. FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties,
  3058. (void*)AProperties);
  3059. }
  3060. catch(...)
  3061. {
  3062. Action.Cancel();
  3063. throw;
  3064. }
  3065. }
  3066. // SFTP can change owner and group at the same time only, not individually.
  3067. // Fortunatelly we know current owner/group, so if only one is present,
  3068. // we can supplement the other.
  3069. TRemoteProperties Properties(*AProperties);
  3070. if (Properties.Valid.Contains(vpGroup) &&
  3071. !Properties.Valid.Contains(vpOwner))
  3072. {
  3073. Properties.Owner = File->Owner;
  3074. Properties.Valid << vpOwner;
  3075. }
  3076. else if (Properties.Valid.Contains(vpOwner) &&
  3077. !Properties.Valid.Contains(vpGroup))
  3078. {
  3079. Properties.Group = File->Group;
  3080. Properties.Valid << vpGroup;
  3081. }
  3082. TSFTPPacket Packet(SSH_FXP_SETSTAT);
  3083. Packet.AddPathString(RealFileName, FUtfStrings);
  3084. Packet.AddProperties(&Properties, *File->Rights, File->IsDirectory, FVersion, FUtfStrings, &Action);
  3085. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_STATUS);
  3086. }
  3087. __finally
  3088. {
  3089. delete File;
  3090. }
  3091. }
  3092. //---------------------------------------------------------------------------
  3093. bool __fastcall TSFTPFileSystem::LoadFilesProperties(TStrings * FileList)
  3094. {
  3095. bool Result = false;
  3096. // without knowledge of server's capabilities, this all make no sense
  3097. if (FSupport->Loaded)
  3098. {
  3099. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  3100. Progress.Start(foGetProperties, osRemote, FileList->Count);
  3101. FTerminal->FOperationProgress = &Progress;
  3102. static int LoadFilesPropertiesQueueLen = 5;
  3103. TSFTPLoadFilesPropertiesQueue Queue(this);
  3104. try
  3105. {
  3106. if (Queue.Init(LoadFilesPropertiesQueueLen, FileList))
  3107. {
  3108. TRemoteFile * File;
  3109. TSFTPPacket Packet;
  3110. bool Next;
  3111. do
  3112. {
  3113. Next = Queue.ReceivePacket(&Packet, File);
  3114. assert((Packet.Type == SSH_FXP_ATTRS) || (Packet.Type == SSH_FXP_STATUS));
  3115. if (Packet.Type == SSH_FXP_ATTRS)
  3116. {
  3117. Progress.SetFile(File->FileName);
  3118. assert(File != NULL);
  3119. LoadFile(File, &Packet);
  3120. Result = true;
  3121. TOnceDoneOperation OnceDoneOperation;
  3122. Progress.Finish(File->FileName, true, OnceDoneOperation);
  3123. }
  3124. if (Progress.Cancel != csContinue)
  3125. {
  3126. Next = false;
  3127. }
  3128. }
  3129. while (Next);
  3130. }
  3131. }
  3132. __finally
  3133. {
  3134. Queue.DisposeSafe();
  3135. FTerminal->FOperationProgress = NULL;
  3136. Progress.Stop();
  3137. }
  3138. // queue is discarded here
  3139. }
  3140. return Result;
  3141. }
  3142. //---------------------------------------------------------------------------
  3143. void __fastcall TSFTPFileSystem::DoCalculateFilesChecksum(const AnsiString & Alg,
  3144. TStrings * FileList, TStrings * Checksums,
  3145. TCalculatedChecksumEvent OnCalculatedChecksum,
  3146. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  3147. {
  3148. TOnceDoneOperation OnceDoneOperation; // not used
  3149. // recurse into subdirectories only if we have callback function
  3150. if (OnCalculatedChecksum != NULL)
  3151. {
  3152. for (int Index = 0; Index < FileList->Count; Index++)
  3153. {
  3154. TRemoteFile * File = (TRemoteFile *)FileList->Objects[Index];
  3155. assert(File != NULL);
  3156. if (File->IsDirectory && !File->IsSymLink &&
  3157. !File->IsParentDirectory && !File->IsThisDirectory)
  3158. {
  3159. OperationProgress->SetFile(File->FileName);
  3160. TRemoteFileList * SubFiles =
  3161. FTerminal->CustomReadDirectoryListing(File->FullFileName, false);
  3162. if (SubFiles != NULL)
  3163. {
  3164. TStrings * SubFileList = new TStringList();
  3165. bool Success = false;
  3166. try
  3167. {
  3168. OperationProgress->SetFile(File->FileName);
  3169. for (int Index = 0; Index < SubFiles->Count; Index++)
  3170. {
  3171. TRemoteFile * SubFile = SubFiles->Files[Index];
  3172. SubFileList->AddObject(SubFile->FullFileName, SubFile);
  3173. }
  3174. // do not collect checksums for files in subdirectories,
  3175. // only send back checksums via callback
  3176. DoCalculateFilesChecksum(Alg, SubFileList, NULL,
  3177. OnCalculatedChecksum, OperationProgress, false);
  3178. Success = true;
  3179. }
  3180. __finally
  3181. {
  3182. delete SubFiles;
  3183. delete SubFileList;
  3184. if (FirstLevel)
  3185. {
  3186. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  3187. }
  3188. }
  3189. }
  3190. }
  3191. }
  3192. }
  3193. static int CalculateFilesChecksumQueueLen = 5;
  3194. TSFTPCalculateFilesChecksumQueue Queue(this);
  3195. try
  3196. {
  3197. if (Queue.Init(CalculateFilesChecksumQueueLen, Alg, FileList))
  3198. {
  3199. TSFTPPacket Packet;
  3200. bool Next;
  3201. do
  3202. {
  3203. bool Success = false;
  3204. AnsiString Alg;
  3205. AnsiString Checksum;
  3206. TRemoteFile * File = NULL;
  3207. try
  3208. {
  3209. try
  3210. {
  3211. Next = Queue.ReceivePacket(&Packet, File);
  3212. assert(Packet.Type == SSH_FXP_EXTENDED_REPLY);
  3213. OperationProgress->SetFile(File->FileName);
  3214. Alg = Packet.GetString();
  3215. Checksum = StrToHex(AnsiString(Packet.GetNextData(Packet.RemainingLength), Packet.RemainingLength));
  3216. OnCalculatedChecksum(File->FileName, Alg, Checksum);
  3217. Success = true;
  3218. }
  3219. catch (Exception & E)
  3220. {
  3221. FTerminal->CommandError(&E, FMTLOAD(CHECKSUM_ERROR,
  3222. (File != NULL ? File->FullFileName : AnsiString(""))));
  3223. // TODO: retries? resume?
  3224. Next = false;
  3225. }
  3226. if (Checksums != NULL)
  3227. {
  3228. Checksums->Add("");
  3229. }
  3230. }
  3231. __finally
  3232. {
  3233. if (FirstLevel)
  3234. {
  3235. OperationProgress->Finish(File->FileName, Success, OnceDoneOperation);
  3236. }
  3237. }
  3238. if (OperationProgress->Cancel != csContinue)
  3239. {
  3240. Next = false;
  3241. }
  3242. }
  3243. while (Next);
  3244. }
  3245. }
  3246. __finally
  3247. {
  3248. Queue.DisposeSafe();
  3249. }
  3250. // queue is discarded here
  3251. }
  3252. //---------------------------------------------------------------------------
  3253. void __fastcall TSFTPFileSystem::CalculateFilesChecksum(const AnsiString & Alg,
  3254. TStrings * FileList, TStrings * Checksums,
  3255. TCalculatedChecksumEvent OnCalculatedChecksum)
  3256. {
  3257. TFileOperationProgressType Progress(&FTerminal->DoProgress, &FTerminal->DoFinished);
  3258. Progress.Start(foCalculateChecksum, osRemote, FileList->Count);
  3259. FTerminal->FOperationProgress = &Progress;
  3260. try
  3261. {
  3262. DoCalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum,
  3263. &Progress, true);
  3264. }
  3265. __finally
  3266. {
  3267. FTerminal->FOperationProgress = NULL;
  3268. Progress.Stop();
  3269. }
  3270. }
  3271. //---------------------------------------------------------------------------
  3272. void __fastcall TSFTPFileSystem::CustomCommandOnFile(const AnsiString /*FileName*/,
  3273. const TRemoteFile * /*File*/, AnsiString /*Command*/, int /*Params*/,
  3274. TCaptureOutputEvent /*OutputEvent*/)
  3275. {
  3276. assert(false);
  3277. }
  3278. //---------------------------------------------------------------------------
  3279. void __fastcall TSFTPFileSystem::AnyCommand(const AnsiString /*Command*/,
  3280. TCaptureOutputEvent /*OutputEvent*/)
  3281. {
  3282. assert(false);
  3283. }
  3284. //---------------------------------------------------------------------------
  3285. AnsiString __fastcall TSFTPFileSystem::FileUrl(const AnsiString FileName)
  3286. {
  3287. return FTerminal->FileUrl("sftp", FileName);
  3288. }
  3289. //---------------------------------------------------------------------------
  3290. TStrings * __fastcall TSFTPFileSystem::GetFixedPaths()
  3291. {
  3292. return FFixedPaths;
  3293. }
  3294. //---------------------------------------------------------------------------
  3295. void __fastcall TSFTPFileSystem::SpaceAvailable(const AnsiString Path,
  3296. TSpaceAvailable & ASpaceAvailable)
  3297. {
  3298. TSFTPPacket Packet(SSH_FXP_EXTENDED);
  3299. Packet.AddString(SFTP_EXT_SPACE_AVAILABLE);
  3300. Packet.AddPathString(LocalCanonify(Path), FUtfStrings);
  3301. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_EXTENDED_REPLY);
  3302. ASpaceAvailable.BytesOnDevice = Packet.GetInt64();
  3303. ASpaceAvailable.UnusedBytesOnDevice = Packet.GetInt64();
  3304. ASpaceAvailable.BytesAvailableToUser = Packet.GetInt64();
  3305. ASpaceAvailable.UnusedBytesAvailableToUser = Packet.GetInt64();
  3306. ASpaceAvailable.BytesPerAllocationUnit = Packet.GetCardinal();
  3307. }
  3308. //---------------------------------------------------------------------------
  3309. // transfer protocol
  3310. //---------------------------------------------------------------------------
  3311. void __fastcall TSFTPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  3312. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  3313. int Params, TFileOperationProgressType * OperationProgress,
  3314. TOnceDoneOperation & OnceDoneOperation)
  3315. {
  3316. assert(FilesToCopy && OperationProgress);
  3317. AnsiString FileName, FileNameOnly;
  3318. AnsiString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  3319. int Index = 0;
  3320. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  3321. {
  3322. bool Success = false;
  3323. FileName = FilesToCopy->Strings[Index];
  3324. FileNameOnly = ExtractFileName(FileName);
  3325. assert(!FAvoidBusy);
  3326. FAvoidBusy = true;
  3327. try
  3328. {
  3329. try
  3330. {
  3331. if (FTerminal->SessionData->CacheDirectories)
  3332. {
  3333. FTerminal->DirectoryModified(TargetDir, false);
  3334. if (DirectoryExists(FileName))
  3335. {
  3336. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  3337. FileNameOnly, true);
  3338. }
  3339. }
  3340. SFTPSourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress,
  3341. tfFirstLevel);
  3342. Success = true;
  3343. }
  3344. catch(EScpSkipFile & E)
  3345. {
  3346. SUSPEND_OPERATION (
  3347. if (!FTerminal->HandleException(&E))
  3348. {
  3349. throw;
  3350. };
  3351. );
  3352. }
  3353. }
  3354. __finally
  3355. {
  3356. FAvoidBusy = false;
  3357. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  3358. }
  3359. Index++;
  3360. }
  3361. }
  3362. //---------------------------------------------------------------------------
  3363. void __fastcall TSFTPFileSystem::SFTPConfirmOverwrite(AnsiString & FileName,
  3364. int Params, TFileOperationProgressType * OperationProgress,
  3365. TSFTPOverwriteMode & OverwriteMode, const TOverwriteFileParams * FileParams)
  3366. {
  3367. bool CanAppend = (FVersion < 4) || !OperationProgress->AsciiTransfer;
  3368. int Answer;
  3369. SUSPEND_OPERATION
  3370. (
  3371. int Answers = qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll | qaIgnore;
  3372. // possibly we can allow alternate resume at least in some cases
  3373. if (CanAppend)
  3374. {
  3375. Answers |= qaRetry;
  3376. }
  3377. TQueryButtonAlias Aliases[3];
  3378. Aliases[0].Button = qaRetry;
  3379. Aliases[0].Alias = LoadStr(APPEND_BUTTON);
  3380. Aliases[1].Button = qaAll;
  3381. Aliases[1].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  3382. Aliases[2].Button = qaIgnore;
  3383. Aliases[2].Alias = LoadStr(RENAME_BUTTON);
  3384. TQueryParams QueryParams(qpNeverAskAgainCheck);
  3385. QueryParams.NoBatchAnswers = qaIgnore | qaRetry | qaAll;
  3386. QueryParams.Aliases = Aliases;
  3387. QueryParams.AliasesCount = LENOF(Aliases);
  3388. Answer = FTerminal->ConfirmFileOverwrite(FileName, FileParams,
  3389. Answers, &QueryParams,
  3390. OperationProgress->Side == osLocal ? osRemote : osLocal,
  3391. Params, OperationProgress);
  3392. );
  3393. if (CanAppend &&
  3394. ((Answer == qaRetry) || (Answer == qaSkip)))
  3395. {
  3396. // duplicated in TTerminal::ConfirmFileOverwrite
  3397. bool CanAlternateResume =
  3398. (FileParams->DestSize < FileParams->SourceSize) && !OperationProgress->AsciiTransfer;
  3399. TBatchOverwrite BatchOverwrite =
  3400. FTerminal->EffectiveBatchOverwrite(Params, OperationProgress, true);
  3401. // when mode is forced by batch, never query user
  3402. if (BatchOverwrite == boAppend)
  3403. {
  3404. OverwriteMode = omAppend;
  3405. }
  3406. else if (CanAlternateResume &&
  3407. ((BatchOverwrite == boResume) || (BatchOverwrite == boAlternateResume)))
  3408. {
  3409. OverwriteMode = omResume;
  3410. }
  3411. // no other option, but append
  3412. else if (!CanAlternateResume)
  3413. {
  3414. OverwriteMode = omAppend;
  3415. }
  3416. else
  3417. {
  3418. TQueryParams Params(0, HELP_APPEND_OR_RESUME);
  3419. SUSPEND_OPERATION
  3420. (
  3421. Answer = FTerminal->QueryUser(FORMAT(LoadStr(APPEND_OR_RESUME), (FileName)),
  3422. NULL, qaYes | qaNo | qaNoToAll | qaCancel, &Params);
  3423. );
  3424. switch (Answer)
  3425. {
  3426. case qaYes:
  3427. OverwriteMode = omAppend;
  3428. break;
  3429. case qaNo:
  3430. OverwriteMode = omResume;
  3431. break;
  3432. case qaNoToAll:
  3433. OverwriteMode = omResume;
  3434. OperationProgress->BatchOverwrite = boAlternateResume;
  3435. break;
  3436. default: assert(false); //fallthru
  3437. case qaCancel:
  3438. if (!OperationProgress->Cancel)
  3439. {
  3440. OperationProgress->Cancel = csCancel;
  3441. }
  3442. Abort();
  3443. break;
  3444. }
  3445. }
  3446. }
  3447. else if (Answer == qaIgnore)
  3448. {
  3449. if (FTerminal->PromptUser(FTerminal->SessionData, pkPrompt, LoadStr(RENAME_TITLE), "",
  3450. LoadStr(RENAME_PROMPT2), true, 0, FileName))
  3451. {
  3452. OverwriteMode = omOverwrite;
  3453. }
  3454. else
  3455. {
  3456. if (!OperationProgress->Cancel)
  3457. {
  3458. OperationProgress->Cancel = csCancel;
  3459. }
  3460. Abort();
  3461. }
  3462. }
  3463. else
  3464. {
  3465. OverwriteMode = omOverwrite;
  3466. switch (Answer)
  3467. {
  3468. case qaCancel:
  3469. if (!OperationProgress->Cancel)
  3470. {
  3471. OperationProgress->Cancel = csCancel;
  3472. }
  3473. Abort();
  3474. break;
  3475. case qaNo:
  3476. THROW_SKIP_FILE_NULL;
  3477. }
  3478. }
  3479. }
  3480. //---------------------------------------------------------------------------
  3481. bool TSFTPFileSystem::SFTPConfirmResume(const AnsiString DestFileName,
  3482. bool PartialBiggerThanSource, TFileOperationProgressType * OperationProgress)
  3483. {
  3484. bool ResumeTransfer;
  3485. assert(OperationProgress);
  3486. if (PartialBiggerThanSource)
  3487. {
  3488. int Answer;
  3489. SUSPEND_OPERATION
  3490. (
  3491. TQueryParams Params(qpAllowContinueOnError, HELP_PARTIAL_BIGGER_THAN_SOURCE);
  3492. Answer = FTerminal->QueryUser(
  3493. FMTLOAD(PARTIAL_BIGGER_THAN_SOURCE, (DestFileName)), NULL,
  3494. qaOK | qaAbort, &Params, qtWarning);
  3495. )
  3496. if (Answer == qaAbort)
  3497. {
  3498. if (!OperationProgress->Cancel)
  3499. {
  3500. OperationProgress->Cancel = csCancel;
  3501. }
  3502. Abort();
  3503. }
  3504. ResumeTransfer = false;
  3505. }
  3506. else if (FTerminal->Configuration->ConfirmResume)
  3507. {
  3508. int Answer;
  3509. SUSPEND_OPERATION
  3510. (
  3511. TQueryParams Params(qpAllowContinueOnError | qpNeverAskAgainCheck,
  3512. HELP_RESUME_TRANSFER);
  3513. // "abort" replaced with "cancel" to unify with "append/resume" query
  3514. Answer = FTerminal->QueryUser(
  3515. FMTLOAD(RESUME_TRANSFER, (DestFileName)), NULL, qaYes | qaNo | qaCancel,
  3516. &Params);
  3517. );
  3518. switch (Answer) {
  3519. case qaNeverAskAgain:
  3520. FTerminal->Configuration->ConfirmResume = false;
  3521. case qaYes:
  3522. ResumeTransfer = true;
  3523. break;
  3524. case qaNo:
  3525. ResumeTransfer = false;
  3526. break;
  3527. case qaCancel:
  3528. if (!OperationProgress->Cancel)
  3529. {
  3530. OperationProgress->Cancel = csCancel;
  3531. }
  3532. Abort();
  3533. break;
  3534. }
  3535. }
  3536. else
  3537. {
  3538. ResumeTransfer = true;
  3539. }
  3540. return ResumeTransfer;
  3541. }
  3542. //---------------------------------------------------------------------------
  3543. void __fastcall TSFTPFileSystem::SFTPSourceRobust(const AnsiString FileName,
  3544. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  3545. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  3546. {
  3547. // the same in TFTPFileSystem
  3548. bool Retry;
  3549. TUploadSessionAction Action(FTerminal->Log);
  3550. do
  3551. {
  3552. Retry = false;
  3553. bool ChildError = false;
  3554. try
  3555. {
  3556. SFTPSource(FileName, TargetDir, CopyParam, Params, OperationProgress,
  3557. Flags, Action, ChildError);
  3558. }
  3559. catch(Exception & E)
  3560. {
  3561. Retry = true;
  3562. if (FTerminal->Active ||
  3563. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  3564. {
  3565. if (!ChildError)
  3566. {
  3567. FTerminal->RollbackAction(Action, OperationProgress, &E);
  3568. }
  3569. throw;
  3570. }
  3571. }
  3572. if (Retry)
  3573. {
  3574. OperationProgress->RollbackTransfer();
  3575. Action.Restart();
  3576. // prevent overwrite and resume confirmations
  3577. // (should not be set for directories!)
  3578. Params |= cpNoConfirmation;
  3579. // enable resume even if we are uploading into new directory
  3580. Flags &= ~tfNewDirectory;
  3581. }
  3582. }
  3583. while (Retry);
  3584. }
  3585. //---------------------------------------------------------------------------
  3586. void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
  3587. const AnsiString TargetDir, const TCopyParamType * CopyParam, int Params,
  3588. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  3589. TUploadSessionAction & Action, bool & ChildError)
  3590. {
  3591. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  3592. Action.FileName(ExpandUNCFileName(FileName));
  3593. OperationProgress->SetFile(FileName, false);
  3594. if (FLAGCLEAR(Params, cpDelete) &&
  3595. !FTerminal->AllowLocalFileTransfer(FileName, CopyParam))
  3596. {
  3597. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  3598. THROW_SKIP_FILE_NULL;
  3599. }
  3600. TOpenRemoteFileParams OpenParams;
  3601. OpenParams.OverwriteMode = omOverwrite;
  3602. HANDLE File;
  3603. __int64 MTime, ATime;
  3604. __int64 Size;
  3605. FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
  3606. &File, NULL, &MTime, &ATime, &Size);
  3607. bool Dir = FLAGSET(OpenParams.LocalFileAttrs, faDirectory);
  3608. try
  3609. {
  3610. OperationProgress->SetFileInProgress();
  3611. if (Dir)
  3612. {
  3613. SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
  3614. OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
  3615. Action.Cancel();
  3616. }
  3617. else
  3618. {
  3619. // File is regular file (not directory)
  3620. assert(File);
  3621. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName),
  3622. osLocal, FLAGSET(Flags, tfFirstLevel));
  3623. AnsiString DestFullName = LocalCanonify(TargetDir + DestFileName);
  3624. AnsiString DestPartinalFullName;
  3625. bool ResumeAllowed;
  3626. bool ResumeTransfer = false;
  3627. bool DestFileExists = false;
  3628. TRights DestRights;
  3629. __int64 ResumeOffset;
  3630. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  3631. OperationProgress->SetLocalSize(Size);
  3632. // Suppose same data size to transfer as to read
  3633. // (not true with ASCII transfer)
  3634. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  3635. OperationProgress->TransferingFile = false;
  3636. // Will we use ASCII of BINARY file tranfer?
  3637. TFileMasks::TParams MaskParams;
  3638. MaskParams.Size = Size;
  3639. OperationProgress->SetAsciiTransfer(
  3640. CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
  3641. FTerminal->LogEvent(
  3642. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  3643. " transfer mode selected.");
  3644. // should we check for interrupted transfer?
  3645. ResumeAllowed = !OperationProgress->AsciiTransfer &&
  3646. CopyParam->AllowResume(OperationProgress->LocalSize) &&
  3647. IsCapable(fcRename);
  3648. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  3649. TOverwriteFileParams FileParams;
  3650. FileParams.SourceSize = OperationProgress->LocalSize;
  3651. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  3652. FTerminal->SessionData->DSTMode);
  3653. if (ResumeAllowed)
  3654. {
  3655. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3656. if (FLAGCLEAR(Flags, tfNewDirectory))
  3657. {
  3658. FTerminal->LogEvent("Checking existence of file.");
  3659. TRemoteFile * File = NULL;
  3660. DestFileExists = RemoteFileExists(DestFullName, &File);
  3661. if (DestFileExists)
  3662. {
  3663. OpenParams.DestFileSize = File->Size;
  3664. FileParams.DestSize = OpenParams.DestFileSize;
  3665. FileParams.DestTimestamp = File->Modification;
  3666. DestRights = *File->Rights;
  3667. // if destination file is symlink, never do resumable transfer,
  3668. // as it would delete the symlink.
  3669. // also bit of heuristics to detect symlink on SFTP-3 and older
  3670. // (which does not indicate symlink in SSH_FXP_ATTRS).
  3671. // if file has all permissions and is small, then it is likely symlink.
  3672. // also it is not likely that such a small file (if it is not symlink)
  3673. // gets overwritten by large file (that would trigger resumable transfer).
  3674. if (File->IsSymLink ||
  3675. ((FVersion < 4) &&
  3676. ((*File->Rights & TRights::rfAll) == TRights::rfAll) &&
  3677. (File->Size < 100)))
  3678. {
  3679. ResumeAllowed = false;
  3680. OperationProgress->SetResumeStatus(rsDisabled);
  3681. }
  3682. delete File;
  3683. File = NULL;
  3684. }
  3685. if (ResumeAllowed)
  3686. {
  3687. FTerminal->LogEvent("Checking existence of partially transfered file.");
  3688. if (RemoteFileExists(DestPartinalFullName, &File))
  3689. {
  3690. ResumeOffset = File->Size;
  3691. delete File;
  3692. File = NULL;
  3693. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->LocalSize);
  3694. if (FLAGCLEAR(Params, cpNoConfirmation) &&
  3695. FLAGCLEAR(Params, cpResume))
  3696. {
  3697. ResumeTransfer = SFTPConfirmResume(DestFileName,
  3698. PartialBiggerThanSource, OperationProgress);
  3699. }
  3700. else
  3701. {
  3702. ResumeTransfer = !PartialBiggerThanSource;
  3703. }
  3704. if (!ResumeTransfer)
  3705. {
  3706. DoDeleteFile(DestPartinalFullName, SSH_FXP_REMOVE);
  3707. }
  3708. else
  3709. {
  3710. FTerminal->LogEvent("Resuming file transfer.");
  3711. }
  3712. }
  3713. else
  3714. {
  3715. // partial upload file does not exists, check for full file
  3716. if (DestFileExists)
  3717. {
  3718. AnsiString PrevDestFileName = DestFileName;
  3719. SFTPConfirmOverwrite(DestFileName,
  3720. Params, OperationProgress, OpenParams.OverwriteMode, &FileParams);
  3721. if (PrevDestFileName != DestFileName)
  3722. {
  3723. // update paths in case user changes the file name
  3724. DestFullName = LocalCanonify(TargetDir + DestFileName);
  3725. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  3726. FTerminal->LogEvent("Checking existence of new file.");
  3727. DestFileExists = RemoteFileExists(DestFullName, NULL);
  3728. }
  3729. }
  3730. }
  3731. }
  3732. }
  3733. }
  3734. // will the transfer be resumable?
  3735. bool DoResume = (ResumeAllowed && (OpenParams.OverwriteMode == omOverwrite));
  3736. AnsiString RemoteFileName = DoResume ? DestPartinalFullName : DestFullName;
  3737. OpenParams.RemoteFileName = RemoteFileName;
  3738. OpenParams.Resume = DoResume;
  3739. OpenParams.Resuming = ResumeTransfer;
  3740. OpenParams.OperationProgress = OperationProgress;
  3741. OpenParams.CopyParam = CopyParam;
  3742. OpenParams.Params = Params;
  3743. OpenParams.FileParams = &FileParams;
  3744. OpenParams.Confirmed = false;
  3745. FTerminal->LogEvent("Opening remote file.");
  3746. FTerminal->FileOperationLoop(SFTPOpenRemote, OperationProgress, true,
  3747. FMTLOAD(SFTP_CREATE_FILE_ERROR, (OpenParams.RemoteFileName)),
  3748. &OpenParams);
  3749. if (OpenParams.RemoteFileName != RemoteFileName)
  3750. {
  3751. assert(!DoResume);
  3752. assert(UnixExtractFilePath(OpenParams.RemoteFileName) == UnixExtractFilePath(RemoteFileName));
  3753. DestFullName = OpenParams.RemoteFileName;
  3754. AnsiString NewFileName = UnixExtractFileName(DestFullName);
  3755. assert(DestFileName != NewFileName);
  3756. DestFileName = NewFileName;
  3757. }
  3758. Action.Destination(DestFullName);
  3759. bool TransferFinished = false;
  3760. __int64 DestWriteOffset = 0;
  3761. TSFTPPacket CloseRequest;
  3762. bool SetRights = ((DoResume && DestFileExists) || CopyParam->PreserveRights);
  3763. bool SetProperties = (CopyParam->PreserveTime || SetRights);
  3764. TSFTPPacket PropertiesRequest(SSH_FXP_SETSTAT);
  3765. TSFTPPacket PropertiesResponse;
  3766. TRights Rights;
  3767. if (SetProperties)
  3768. {
  3769. PropertiesRequest.AddPathString(DestFullName, FUtfStrings);
  3770. if (CopyParam->PreserveRights)
  3771. {
  3772. Rights = CopyParam->RemoteFileRights(OpenParams.LocalFileAttrs);
  3773. }
  3774. else if (DoResume && DestFileExists)
  3775. {
  3776. Rights = DestRights;
  3777. }
  3778. else
  3779. {
  3780. assert(!SetRights);
  3781. }
  3782. unsigned short RightsNumber = Rights.NumberSet;
  3783. PropertiesRequest.AddProperties(
  3784. SetRights ? &RightsNumber : NULL, NULL, NULL,
  3785. CopyParam->PreserveTime ? &MTime : NULL,
  3786. CopyParam->PreserveTime ? &ATime : NULL,
  3787. NULL, false, FVersion, FUtfStrings);
  3788. }
  3789. try
  3790. {
  3791. if (OpenParams.OverwriteMode == omAppend)
  3792. {
  3793. FTerminal->LogEvent("Appending file.");
  3794. DestWriteOffset = OpenParams.DestFileSize;
  3795. }
  3796. else if (ResumeTransfer || (OpenParams.OverwriteMode == omResume))
  3797. {
  3798. if (OpenParams.OverwriteMode == omResume)
  3799. {
  3800. FTerminal->LogEvent("Resuming file transfer (append style).");
  3801. ResumeOffset = OpenParams.DestFileSize;
  3802. }
  3803. FileSeek((THandle)File, ResumeOffset, 0);
  3804. OperationProgress->AddResumed(ResumeOffset);
  3805. }
  3806. TSFTPUploadQueue Queue(this);
  3807. try
  3808. {
  3809. Queue.Init(FileName, File, OperationProgress,
  3810. OpenParams.RemoteFileHandle,
  3811. DestWriteOffset + OperationProgress->TransferedSize);
  3812. while (Queue.Continue())
  3813. {
  3814. if (OperationProgress->Cancel)
  3815. {
  3816. Abort();
  3817. }
  3818. }
  3819. // send close request before waiting for pending read responses
  3820. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3821. OperationProgress, false, true, &CloseRequest);
  3822. OpenParams.RemoteFileHandle = "";
  3823. // when resuming is disabled, we can send "set properties"
  3824. // request before waiting for pending read/close responses
  3825. if (SetProperties && !DoResume)
  3826. {
  3827. SendPacket(&PropertiesRequest);
  3828. ReserveResponse(&PropertiesRequest, &PropertiesResponse);
  3829. }
  3830. }
  3831. __finally
  3832. {
  3833. Queue.DisposeSafe();
  3834. }
  3835. TransferFinished = true;
  3836. // queue is discarded here
  3837. }
  3838. __finally
  3839. {
  3840. if (FTerminal->Active)
  3841. {
  3842. // if file transfer was finished, the close request was already sent
  3843. if (!OpenParams.RemoteFileHandle.IsEmpty())
  3844. {
  3845. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3846. OperationProgress, TransferFinished, true, &CloseRequest);
  3847. }
  3848. // wait for the response
  3849. SFTPCloseRemote(OpenParams.RemoteFileHandle, DestFileName,
  3850. OperationProgress, TransferFinished, false, &CloseRequest);
  3851. // delete file if transfer was not completed, resuming was not allowed and
  3852. // we were not appending (incl. alternate resume),
  3853. // shortly after plain transfer completes (eq. !ResumeAllowed)
  3854. if (!TransferFinished && !DoResume && (OpenParams.OverwriteMode == omOverwrite))
  3855. {
  3856. DoDeleteFile(OpenParams.RemoteFileName, SSH_FXP_REMOVE);
  3857. }
  3858. }
  3859. }
  3860. if (DoResume)
  3861. {
  3862. if (DestFileExists)
  3863. {
  3864. FILE_OPERATION_LOOP(FMTLOAD(DELETE_ON_RESUME_ERROR,
  3865. (UnixExtractFileName(DestFullName), DestFullName)),
  3866. if (FTerminal->SessionData->OverwrittenToRecycleBin)
  3867. {
  3868. FTerminal->RecycleFile(DestFullName, NULL);
  3869. }
  3870. else
  3871. {
  3872. DoDeleteFile(DestFullName, SSH_FXP_REMOVE);
  3873. }
  3874. );
  3875. }
  3876. // originally this was before CLOSE (last __finally statement),
  3877. // on VShell it failed
  3878. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  3879. (UnixExtractFileName(OpenParams.RemoteFileName), DestFileName)),
  3880. RenameFile(OpenParams.RemoteFileName, DestFileName);
  3881. );
  3882. }
  3883. if (SetProperties)
  3884. {
  3885. std::auto_ptr<TTouchSessionAction> TouchAction;
  3886. if (CopyParam->PreserveTime)
  3887. {
  3888. TouchAction.reset(new TTouchSessionAction(FTerminal->Log, DestFullName,
  3889. UnixToDateTime(MTime, FTerminal->SessionData->DSTMode)));
  3890. }
  3891. std::auto_ptr<TChmodSessionAction> ChmodAction;
  3892. // do record chmod only if it was explicitly requested,
  3893. // not when it was implicitly performed to apply timestamp
  3894. // of overwritten file to new file
  3895. if (CopyParam->PreserveRights)
  3896. {
  3897. ChmodAction.reset(new TChmodSessionAction(FTerminal->Log, DestFullName, Rights));
  3898. }
  3899. try
  3900. {
  3901. // when resuming is enabled, the set properties request was not sent yet
  3902. if (DoResume)
  3903. {
  3904. SendPacket(&PropertiesRequest);
  3905. }
  3906. bool Resend = false;
  3907. FILE_OPERATION_LOOP(FMTLOAD(PRESERVE_TIME_PERM_ERROR, (DestFileName)),
  3908. TSFTPPacket DummyResponse;
  3909. TSFTPPacket * Response = &PropertiesResponse;
  3910. if (Resend)
  3911. {
  3912. PropertiesRequest.Reuse();
  3913. SendPacket(&PropertiesRequest);
  3914. // ReceiveResponse currently cannot receive twice into same packet,
  3915. // so DummyResponse is temporary workaround
  3916. Response = &DummyResponse;
  3917. }
  3918. Resend = true;
  3919. ReceiveResponse(&PropertiesRequest, Response, SSH_FXP_STATUS,
  3920. asOK | FLAGMASK(CopyParam->IgnorePermErrors, asPermDenied));
  3921. );
  3922. }
  3923. catch(Exception & E)
  3924. {
  3925. if (TouchAction.get() != NULL)
  3926. {
  3927. TouchAction->Rollback(&E);
  3928. }
  3929. if (ChmodAction.get() != NULL)
  3930. {
  3931. ChmodAction->Rollback(&E);
  3932. }
  3933. ChildError = true;
  3934. throw;
  3935. }
  3936. }
  3937. }
  3938. }
  3939. __finally
  3940. {
  3941. if (File != NULL)
  3942. {
  3943. CloseHandle(File);
  3944. }
  3945. }
  3946. /* TODO : Delete also read-only files. */
  3947. if (FLAGSET(Params, cpDelete))
  3948. {
  3949. if (!Dir)
  3950. {
  3951. FILE_OPERATION_LOOP (FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)),
  3952. THROWOSIFFALSE(Sysutils::DeleteFile(FileName));
  3953. )
  3954. }
  3955. }
  3956. else if (CopyParam->ClearArchive && FLAGSET(OpenParams.LocalFileAttrs, faArchive))
  3957. {
  3958. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  3959. THROWOSIFFALSE(FileSetAttr(FileName, OpenParams.LocalFileAttrs & ~faArchive) == 0);
  3960. )
  3961. }
  3962. }
  3963. //---------------------------------------------------------------------------
  3964. AnsiString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile(
  3965. const AnsiString & FileName, unsigned int OpenType, __int64 Size)
  3966. {
  3967. TSFTPPacket Packet(SSH_FXP_OPEN);
  3968. Packet.AddPathString(FileName, FUtfStrings);
  3969. if (FVersion < 5)
  3970. {
  3971. Packet.AddCardinal(OpenType);
  3972. }
  3973. else
  3974. {
  3975. unsigned long Access =
  3976. FLAGMASK(FLAGSET(OpenType, SSH_FXF_READ), ACE4_READ_DATA) |
  3977. FLAGMASK(FLAGSET(OpenType, SSH_FXF_WRITE), ACE4_WRITE_DATA | ACE4_APPEND_DATA);
  3978. unsigned long Flags;
  3979. if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_EXCL))
  3980. {
  3981. Flags = SSH_FXF_CREATE_NEW;
  3982. }
  3983. else if (FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC))
  3984. {
  3985. Flags = SSH_FXF_CREATE_TRUNCATE;
  3986. }
  3987. else if (FLAGSET(OpenType, SSH_FXF_CREAT))
  3988. {
  3989. Flags = SSH_FXF_OPEN_OR_CREATE;
  3990. }
  3991. else
  3992. {
  3993. Flags = SSH_FXF_OPEN_EXISTING;
  3994. }
  3995. Flags |=
  3996. FLAGMASK(FLAGSET(OpenType, SSH_FXF_APPEND), SSH_FXF_ACCESS_APPEND_DATA) |
  3997. FLAGMASK(FLAGSET(OpenType, SSH_FXF_TEXT), SSH_FXF_ACCESS_TEXT_MODE);
  3998. Packet.AddCardinal(Access);
  3999. Packet.AddCardinal(Flags);
  4000. }
  4001. bool SendSize =
  4002. (Size >= 0) &&
  4003. FLAGSET(OpenType, SSH_FXF_CREAT | SSH_FXF_TRUNC);
  4004. Packet.AddProperties(NULL, NULL, NULL, NULL, NULL,
  4005. SendSize ? &Size : NULL, false, FVersion, FUtfStrings);
  4006. SendPacketAndReceiveResponse(&Packet, &Packet, SSH_FXP_HANDLE);
  4007. return Packet.GetString();
  4008. }
  4009. //---------------------------------------------------------------------------
  4010. int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/)
  4011. {
  4012. TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams;
  4013. assert(OpenParams);
  4014. TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress;
  4015. int OpenType;
  4016. bool Success = false;
  4017. bool ConfirmOverwriting;
  4018. do
  4019. {
  4020. try
  4021. {
  4022. ConfirmOverwriting =
  4023. !OpenParams->Confirmed && !OpenParams->Resume &&
  4024. FTerminal->CheckRemoteFile(OpenParams->Params, OperationProgress);
  4025. OpenType = SSH_FXF_WRITE | SSH_FXF_CREAT;
  4026. // when we want to preserve overwritten files, we need to find out that
  4027. // they exist first... even if overwrite confirmation is disabled.
  4028. // but not when we already know we are not going to overwrite (but e.g. to append)
  4029. if ((ConfirmOverwriting || FTerminal->SessionData->OverwrittenToRecycleBin) &&
  4030. (OpenParams->OverwriteMode == omOverwrite))
  4031. {
  4032. OpenType |= SSH_FXF_EXCL;
  4033. }
  4034. if (!OpenParams->Resuming && (OpenParams->OverwriteMode == omOverwrite))
  4035. {
  4036. OpenType |= SSH_FXF_TRUNC;
  4037. }
  4038. if ((FVersion >= 4) && OpenParams->OperationProgress->AsciiTransfer)
  4039. {
  4040. OpenType |= SSH_FXF_TEXT;
  4041. }
  4042. OpenParams->RemoteFileHandle = SFTPOpenRemoteFile(
  4043. OpenParams->RemoteFileName, OpenType, OperationProgress->LocalSize);
  4044. Success = true;
  4045. }
  4046. catch(Exception & E)
  4047. {
  4048. if (!OpenParams->Confirmed && (OpenType & SSH_FXF_EXCL) && FTerminal->Active)
  4049. {
  4050. bool ThrowOriginal = false;
  4051. // When exclusive opening of file fails, try to detect if file exists.
  4052. // When file does not exist, failure was probably caused by 'permission denied'
  4053. // or similar error. In this case throw original exception.
  4054. try
  4055. {
  4056. TRemoteFile * File;
  4057. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  4058. ReadFile(RealFileName, File);
  4059. OpenParams->DestFileSize = File->Size;
  4060. if (OpenParams->FileParams != NULL)
  4061. {
  4062. OpenParams->FileParams->DestTimestamp = File->Modification;
  4063. OpenParams->FileParams->DestSize = OpenParams->DestFileSize;
  4064. }
  4065. // file exists (otherwise exception was thrown)
  4066. assert(File);
  4067. SAFE_DESTROY(File);
  4068. }
  4069. catch(...)
  4070. {
  4071. if (!FTerminal->Active)
  4072. {
  4073. throw;
  4074. }
  4075. else
  4076. {
  4077. ThrowOriginal = true;
  4078. }
  4079. }
  4080. if (ThrowOriginal)
  4081. {
  4082. throw;
  4083. }
  4084. // we may get here even if confirmation is disabled,
  4085. // when we have preserving of overwritten files enabled
  4086. if (ConfirmOverwriting)
  4087. {
  4088. // confirmation duplicated in SFTPSource for resumable file transfers.
  4089. AnsiString RemoteFileNameOnly = UnixExtractFileName(OpenParams->RemoteFileName);
  4090. SFTPConfirmOverwrite(RemoteFileNameOnly,
  4091. OpenParams->Params, OperationProgress, OpenParams->OverwriteMode, OpenParams->FileParams);
  4092. if (RemoteFileNameOnly != UnixExtractFileName(OpenParams->RemoteFileName))
  4093. {
  4094. OpenParams->RemoteFileName =
  4095. UnixExtractFilePath(OpenParams->RemoteFileName) + RemoteFileNameOnly;
  4096. }
  4097. OpenParams->Confirmed = true;
  4098. }
  4099. else
  4100. {
  4101. assert(FTerminal->SessionData->OverwrittenToRecycleBin);
  4102. }
  4103. if ((OpenParams->OverwriteMode == omOverwrite) &&
  4104. FTerminal->SessionData->OverwrittenToRecycleBin)
  4105. {
  4106. FTerminal->RecycleFile(OpenParams->RemoteFileName, NULL);
  4107. }
  4108. }
  4109. else if (FTerminal->Active)
  4110. {
  4111. // if file overwritting was confirmed, it means that the file already exists,
  4112. // if not, check now
  4113. if (!OpenParams->Confirmed)
  4114. {
  4115. bool ThrowOriginal = false;
  4116. // When file does not exist, failure was probably caused by 'permission denied'
  4117. // or similar error. In this case throw original exception.
  4118. try
  4119. {
  4120. TRemoteFile * File;
  4121. AnsiString RealFileName = LocalCanonify(OpenParams->RemoteFileName);
  4122. ReadFile(RealFileName, File);
  4123. SAFE_DESTROY(File);
  4124. }
  4125. catch(...)
  4126. {
  4127. if (!FTerminal->Active)
  4128. {
  4129. throw;
  4130. }
  4131. else
  4132. {
  4133. ThrowOriginal = true;
  4134. }
  4135. }
  4136. if (ThrowOriginal)
  4137. {
  4138. throw;
  4139. }
  4140. }
  4141. // now we know that the file exists
  4142. if (FTerminal->FileOperationLoopQuery(E, OperationProgress,
  4143. FMTLOAD(SFTP_OVERWRITE_FILE_ERROR, (OpenParams->RemoteFileName)),
  4144. true, LoadStr(SFTP_OVERWRITE_DELETE_BUTTON)))
  4145. {
  4146. int Params = dfNoRecursive;
  4147. FTerminal->DeleteFile(OpenParams->RemoteFileName, NULL, &Params);
  4148. }
  4149. }
  4150. else
  4151. {
  4152. throw;
  4153. }
  4154. }
  4155. }
  4156. while (!Success);
  4157. return 0;
  4158. }
  4159. //---------------------------------------------------------------------------
  4160. void __fastcall TSFTPFileSystem::SFTPCloseRemote(const AnsiString Handle,
  4161. const AnsiString FileName, TFileOperationProgressType * OperationProgress,
  4162. bool TransferFinished, bool Request, TSFTPPacket * Packet)
  4163. {
  4164. // Moving this out of SFTPSource() fixed external exception 0xC0000029 error
  4165. FILE_OPERATION_LOOP(FMTLOAD(SFTP_CLOSE_FILE_ERROR, (FileName)),
  4166. try
  4167. {
  4168. TSFTPPacket CloseRequest;
  4169. TSFTPPacket * P = (Packet == NULL ? &CloseRequest : Packet);
  4170. if (Request)
  4171. {
  4172. P->ChangeType(SSH_FXP_CLOSE);
  4173. P->AddString(Handle);
  4174. SendPacket(P);
  4175. ReserveResponse(P, Packet);
  4176. }
  4177. else
  4178. {
  4179. assert(Packet != NULL);
  4180. ReceiveResponse(P, Packet, SSH_FXP_STATUS);
  4181. }
  4182. }
  4183. catch(...)
  4184. {
  4185. if (!FTerminal->Active || TransferFinished)
  4186. {
  4187. throw;
  4188. }
  4189. }
  4190. );
  4191. }
  4192. //---------------------------------------------------------------------------
  4193. void __fastcall TSFTPFileSystem::SFTPDirectorySource(const AnsiString DirectoryName,
  4194. const AnsiString TargetDir, int Attrs, const TCopyParamType * CopyParam,
  4195. int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4196. {
  4197. AnsiString DestDirectoryName = CopyParam->ChangeFileName(
  4198. ExtractFileName(ExcludeTrailingBackslash(DirectoryName)), osLocal,
  4199. FLAGSET(Flags, tfFirstLevel));
  4200. AnsiString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  4201. OperationProgress->SetFile(DirectoryName);
  4202. bool CreateDir = false;
  4203. try
  4204. {
  4205. TryOpenDirectory(DestFullName);
  4206. }
  4207. catch(...)
  4208. {
  4209. if (FTerminal->Active)
  4210. {
  4211. // opening directory failed, it probably does not exists, try to
  4212. // create it
  4213. CreateDir = true;
  4214. }
  4215. else
  4216. {
  4217. throw;
  4218. }
  4219. }
  4220. if (CreateDir)
  4221. {
  4222. TRemoteProperties Properties;
  4223. if (CopyParam->PreserveRights)
  4224. {
  4225. Properties.Valid = TValidProperties() << vpRights;
  4226. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  4227. }
  4228. FTerminal->CreateDirectory(DestFullName, &Properties);
  4229. Flags |= tfNewDirectory;
  4230. }
  4231. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4232. TSearchRec SearchRec;
  4233. bool FindOK;
  4234. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  4235. FindOK = (bool)(FindFirst(DirectoryName + "*.*",
  4236. FindAttrs, SearchRec) == 0);
  4237. );
  4238. try
  4239. {
  4240. while (FindOK && !OperationProgress->Cancel)
  4241. {
  4242. AnsiString FileName = DirectoryName + SearchRec.Name;
  4243. try
  4244. {
  4245. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  4246. {
  4247. SFTPSourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
  4248. Flags & ~tfFirstLevel);
  4249. }
  4250. }
  4251. catch (EScpSkipFile &E)
  4252. {
  4253. // If ESkipFile occurs, just log it and continue with next file
  4254. SUSPEND_OPERATION (
  4255. // here a message to user was displayed, which was not appropriate
  4256. // when user refused to overwrite the file in subdirectory.
  4257. // hopefuly it won't be missing in other situations.
  4258. if (!FTerminal->HandleException(&E)) throw;
  4259. );
  4260. }
  4261. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  4262. FindOK = (FindNext(SearchRec) == 0);
  4263. );
  4264. };
  4265. }
  4266. __finally
  4267. {
  4268. FindClose(SearchRec);
  4269. }
  4270. /* TODO : Delete also read-only directories. */
  4271. /* TODO : Show error message on failure. */
  4272. if (!OperationProgress->Cancel)
  4273. {
  4274. if (FLAGSET(Params, cpDelete))
  4275. {
  4276. RemoveDir(DirectoryName);
  4277. }
  4278. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  4279. {
  4280. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  4281. THROWOSIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  4282. )
  4283. }
  4284. }
  4285. }
  4286. //---------------------------------------------------------------------------
  4287. void __fastcall TSFTPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  4288. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  4289. int Params, TFileOperationProgressType * OperationProgress,
  4290. TOnceDoneOperation & OnceDoneOperation)
  4291. {
  4292. assert(FilesToCopy && OperationProgress);
  4293. AnsiString FileName;
  4294. AnsiString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  4295. const TRemoteFile * File;
  4296. bool Success;
  4297. int Index = 0;
  4298. while (Index < FilesToCopy->Count && !OperationProgress->Cancel)
  4299. {
  4300. Success = false;
  4301. FileName = FilesToCopy->Strings[Index];
  4302. File = (TRemoteFile *)FilesToCopy->Objects[Index];
  4303. assert(!FAvoidBusy);
  4304. FAvoidBusy = true;
  4305. try
  4306. {
  4307. try
  4308. {
  4309. SFTPSinkRobust(LocalCanonify(FileName), File, FullTargetDir, CopyParam,
  4310. Params, OperationProgress, tfFirstLevel);
  4311. Success = true;
  4312. }
  4313. catch(EScpSkipFile & E)
  4314. {
  4315. SUSPEND_OPERATION (
  4316. if (!FTerminal->HandleException(&E)) throw;
  4317. );
  4318. }
  4319. catch(...)
  4320. {
  4321. // TODO: remove the block?
  4322. throw;
  4323. }
  4324. }
  4325. __finally
  4326. {
  4327. FAvoidBusy = false;
  4328. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  4329. }
  4330. Index++;
  4331. }
  4332. }
  4333. //---------------------------------------------------------------------------
  4334. void __fastcall TSFTPFileSystem::SFTPSinkRobust(const AnsiString FileName,
  4335. const TRemoteFile * File, const AnsiString TargetDir,
  4336. const TCopyParamType * CopyParam, int Params,
  4337. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  4338. {
  4339. // the same in TFTPFileSystem
  4340. bool Retry;
  4341. TDownloadSessionAction Action(FTerminal->Log);
  4342. do
  4343. {
  4344. Retry = false;
  4345. bool ChildError = false;
  4346. try
  4347. {
  4348. SFTPSink(FileName, File, TargetDir, CopyParam, Params, OperationProgress,
  4349. Flags, Action, ChildError);
  4350. }
  4351. catch(Exception & E)
  4352. {
  4353. Retry = true;
  4354. if (FTerminal->Active ||
  4355. !FTerminal->QueryReopen(&E, ropNoReadDirectory, OperationProgress))
  4356. {
  4357. if (!ChildError)
  4358. {
  4359. FTerminal->RollbackAction(Action, OperationProgress, &E);
  4360. }
  4361. throw;
  4362. }
  4363. }
  4364. if (Retry)
  4365. {
  4366. OperationProgress->RollbackTransfer();
  4367. Action.Restart();
  4368. assert(File != NULL);
  4369. if (!File->IsDirectory)
  4370. {
  4371. // prevent overwrite and resume confirmations
  4372. Params |= cpNoConfirmation;
  4373. }
  4374. }
  4375. }
  4376. while (Retry);
  4377. }
  4378. //---------------------------------------------------------------------------
  4379. void __fastcall TSFTPFileSystem::SFTPSink(const AnsiString FileName,
  4380. const TRemoteFile * File, const AnsiString TargetDir,
  4381. const TCopyParamType * CopyParam, int Params,
  4382. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  4383. TDownloadSessionAction & Action, bool & ChildError)
  4384. {
  4385. Action.FileName(FileName);
  4386. AnsiString OnlyFileName = UnixExtractFileName(FileName);
  4387. TFileMasks::TParams MaskParams;
  4388. MaskParams.Size = File->Size;
  4389. if (FLAGCLEAR(Params, cpDelete) &&
  4390. !CopyParam->AllowTransfer(FileName, osRemote, File->IsDirectory, MaskParams))
  4391. {
  4392. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  4393. THROW_SKIP_FILE_NULL;
  4394. }
  4395. assert(File);
  4396. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  4397. OperationProgress->SetFile(OnlyFileName);
  4398. AnsiString DestFileName = CopyParam->ChangeFileName(OnlyFileName,
  4399. osRemote, FLAGSET(Flags, tfFirstLevel));
  4400. AnsiString DestFullName = TargetDir + DestFileName;
  4401. if (File->IsDirectory)
  4402. {
  4403. Action.Cancel();
  4404. if (!File->IsSymLink)
  4405. {
  4406. FILE_OPERATION_LOOP (FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)),
  4407. int Attrs = FileGetAttr(DestFullName);
  4408. if ((Attrs & faDirectory) == 0) EXCEPTION;
  4409. );
  4410. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFullName)),
  4411. if (!ForceDirectories(DestFullName)) RaiseLastOSError();
  4412. );
  4413. TSinkFileParams SinkFileParams;
  4414. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  4415. SinkFileParams.CopyParam = CopyParam;
  4416. SinkFileParams.Params = Params;
  4417. SinkFileParams.OperationProgress = OperationProgress;
  4418. SinkFileParams.Skipped = false;
  4419. SinkFileParams.Flags = Flags & ~tfFirstLevel;
  4420. FTerminal->ProcessDirectory(FileName, SFTPSinkFile, &SinkFileParams);
  4421. // Do not delete directory if some of its files were skip.
  4422. // Throw "skip file" for the directory to avoid attempt to deletion
  4423. // of any parent directory
  4424. if ((Params & cpDelete) && SinkFileParams.Skipped)
  4425. {
  4426. THROW_SKIP_FILE_NULL;
  4427. }
  4428. }
  4429. else
  4430. {
  4431. // file is symlink to directory, currently do nothing, but it should be
  4432. // reported to user
  4433. }
  4434. }
  4435. else
  4436. {
  4437. FTerminal->LogEvent(FORMAT("Copying \"%s\" to local directory started.", (FileName)));
  4438. AnsiString DestPartinalFullName;
  4439. bool ResumeAllowed;
  4440. bool ResumeTransfer = false;
  4441. __int64 ResumeOffset;
  4442. // Will we use ASCII of BINARY file tranfer?
  4443. OperationProgress->SetAsciiTransfer(
  4444. CopyParam->UseAsciiTransfer(FileName, osRemote, MaskParams));
  4445. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  4446. " transfer mode selected.");
  4447. // Suppose same data size to transfer as to write
  4448. // (not true with ASCII transfer)
  4449. OperationProgress->SetTransferSize(File->Size);
  4450. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  4451. // resume has no sense for temporary downloads
  4452. ResumeAllowed = ((Params & cpTemporary) == 0) &&
  4453. !OperationProgress->AsciiTransfer &&
  4454. CopyParam->AllowResume(OperationProgress->TransferSize);
  4455. OperationProgress->SetResumeStatus(ResumeAllowed ? rsEnabled : rsDisabled);
  4456. int Attrs;
  4457. FILE_OPERATION_LOOP (FMTLOAD(NOT_FILE_ERROR, (DestFullName)),
  4458. Attrs = FileGetAttr(DestFullName);
  4459. if ((Attrs >= 0) && (Attrs & faDirectory)) EXCEPTION;
  4460. );
  4461. OperationProgress->TransferingFile = false; // not set with SFTP protocol
  4462. HANDLE LocalHandle = NULL;
  4463. TStream * FileStream = NULL;
  4464. bool DeleteLocalFile = false;
  4465. AnsiString RemoteHandle;
  4466. AnsiString LocalFileName = DestFullName;
  4467. TSFTPOverwriteMode OverwriteMode = omOverwrite;
  4468. try
  4469. {
  4470. if (ResumeAllowed)
  4471. {
  4472. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4473. LocalFileName = DestPartinalFullName;
  4474. FTerminal->LogEvent("Checking existence of partially transfered file.");
  4475. if (FileExists(DestPartinalFullName))
  4476. {
  4477. FTerminal->OpenLocalFile(DestPartinalFullName, GENERIC_WRITE,
  4478. NULL, &LocalHandle, NULL, NULL, NULL, &ResumeOffset);
  4479. bool PartialBiggerThanSource = (ResumeOffset > OperationProgress->TransferSize);
  4480. if (FLAGCLEAR(Params, cpNoConfirmation))
  4481. {
  4482. ResumeTransfer = SFTPConfirmResume(DestFileName,
  4483. PartialBiggerThanSource, OperationProgress);
  4484. }
  4485. else
  4486. {
  4487. ResumeTransfer = !PartialBiggerThanSource;
  4488. }
  4489. if (!ResumeTransfer)
  4490. {
  4491. CloseHandle(LocalHandle);
  4492. LocalHandle = NULL;
  4493. FILE_OPERATION_LOOP (FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestPartinalFullName)),
  4494. THROWOSIFFALSE(Sysutils::DeleteFile(DestPartinalFullName));
  4495. )
  4496. }
  4497. else
  4498. {
  4499. FTerminal->LogEvent("Resuming file transfer.");
  4500. FileSeek((THandle)LocalHandle, ResumeOffset, 0);
  4501. OperationProgress->AddResumed(ResumeOffset);
  4502. }
  4503. }
  4504. }
  4505. if ((Attrs >= 0) && !ResumeTransfer)
  4506. {
  4507. __int64 DestFileSize;
  4508. __int64 MTime;
  4509. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  4510. NULL, &LocalHandle, NULL, &MTime, NULL, &DestFileSize, false);
  4511. FTerminal->LogEvent("Confirming overwriting of file.");
  4512. TOverwriteFileParams FileParams;
  4513. FileParams.SourceSize = OperationProgress->TransferSize;
  4514. FileParams.SourceTimestamp = File->Modification;
  4515. FileParams.DestTimestamp = UnixToDateTime(MTime,
  4516. FTerminal->SessionData->DSTMode);
  4517. FileParams.DestSize = DestFileSize;
  4518. AnsiString PrevDestFileName = DestFileName;
  4519. SFTPConfirmOverwrite(DestFileName, Params, OperationProgress, OverwriteMode, &FileParams);
  4520. if (PrevDestFileName != DestFileName)
  4521. {
  4522. DestFullName = TargetDir + DestFileName;
  4523. DestPartinalFullName = DestFullName + FTerminal->Configuration->PartialExt;
  4524. if (ResumeAllowed)
  4525. {
  4526. if (FileExists(DestPartinalFullName))
  4527. {
  4528. FILE_OPERATION_LOOP (FMTLOAD(DELETE_LOCAL_FILE_ERROR, (DestPartinalFullName)),
  4529. THROWOSIFFALSE(Sysutils::DeleteFile(DestPartinalFullName));
  4530. )
  4531. }
  4532. LocalFileName = DestPartinalFullName;
  4533. }
  4534. else
  4535. {
  4536. LocalFileName = DestFullName;
  4537. }
  4538. }
  4539. if (OverwriteMode == omOverwrite)
  4540. {
  4541. // is NULL when overwritting read-only file
  4542. if (LocalHandle)
  4543. {
  4544. CloseHandle(LocalHandle);
  4545. LocalHandle = NULL;
  4546. }
  4547. }
  4548. else
  4549. {
  4550. // is NULL when overwritting read-only file, so following will
  4551. // probably fail anyway
  4552. if (LocalHandle == NULL)
  4553. {
  4554. FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE,
  4555. NULL, &LocalHandle, NULL, NULL, NULL, NULL);
  4556. }
  4557. ResumeAllowed = false;
  4558. FileSeek((THandle)LocalHandle, DestFileSize, 0);
  4559. if (OverwriteMode == omAppend)
  4560. {
  4561. FTerminal->LogEvent("Appending to file.");
  4562. }
  4563. else
  4564. {
  4565. FTerminal->LogEvent("Resuming file transfer (append style).");
  4566. assert(OverwriteMode == omResume);
  4567. OperationProgress->AddResumed(DestFileSize);
  4568. }
  4569. }
  4570. }
  4571. // if not already opened (resume, append...), create new empty file
  4572. if (!LocalHandle)
  4573. {
  4574. if (!FTerminal->CreateLocalFile(LocalFileName, OperationProgress,
  4575. &LocalHandle, FLAGSET(Params, cpNoConfirmation)))
  4576. {
  4577. THROW_SKIP_FILE_NULL;
  4578. }
  4579. }
  4580. assert(LocalHandle);
  4581. Action.Destination(ExpandUNCFileName(DestFullName));
  4582. DeleteLocalFile = true;
  4583. FTerminal->LogEvent("Opening remote file.");
  4584. FILE_OPERATION_LOOP (FMTLOAD(SFTP_OPEN_FILE_ERROR, (FileName)),
  4585. int OpenType = SSH_FXF_READ;
  4586. if ((FVersion >= 4) && OperationProgress->AsciiTransfer)
  4587. {
  4588. OpenType |= SSH_FXF_TEXT;
  4589. }
  4590. RemoteHandle = SFTPOpenRemoteFile(FileName, OpenType);
  4591. );
  4592. TSFTPPacket RemoteFilePacket(SSH_FXP_FSTAT);
  4593. if (CopyParam->PreserveTime)
  4594. {
  4595. SendCustomReadFile(&RemoteFilePacket, &RemoteFilePacket, RemoteHandle,
  4596. SSH_FILEXFER_ATTR_MODIFYTIME);
  4597. }
  4598. FileStream = new TSafeHandleStream((THandle)LocalHandle);
  4599. // at end of this block queue is discarded
  4600. {
  4601. TSFTPDownloadQueue Queue(this);
  4602. try
  4603. {
  4604. TSFTPPacket DataPacket;
  4605. int QueueLen = int(File->Size / DownloadBlockSize(OperationProgress)) + 1;
  4606. if ((QueueLen > FTerminal->SessionData->SFTPDownloadQueue) ||
  4607. (QueueLen < 0))
  4608. {
  4609. QueueLen = FTerminal->SessionData->SFTPDownloadQueue;
  4610. }
  4611. if (QueueLen < 1)
  4612. {
  4613. QueueLen = 1;
  4614. }
  4615. Queue.Init(QueueLen, RemoteHandle, OperationProgress->TransferedSize,
  4616. OperationProgress);
  4617. bool Eof = false;
  4618. bool PrevIncomplete = false;
  4619. int GapFillCount = 0;
  4620. int GapCount = 0;
  4621. unsigned long Missing = 0;
  4622. unsigned long DataLen = 0;
  4623. unsigned long BlockSize;
  4624. while (!Eof)
  4625. {
  4626. if (Missing > 0)
  4627. {
  4628. Queue.InitFillGapRequest(OperationProgress->TransferedSize, Missing,
  4629. &DataPacket);
  4630. GapFillCount++;
  4631. SendPacketAndReceiveResponse(&DataPacket, &DataPacket,
  4632. SSH_FXP_DATA, asEOF);
  4633. }
  4634. else
  4635. {
  4636. Queue.ReceivePacket(&DataPacket, BlockSize);
  4637. }
  4638. if (DataPacket.Type == SSH_FXP_STATUS)
  4639. {
  4640. // must be SSH_FX_EOF, any other status packet would raise exception
  4641. Eof = true;
  4642. // close file right away, before waiting for pending responses
  4643. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  4644. true, true, NULL);
  4645. RemoteHandle = ""; // do not close file again in __finally block
  4646. }
  4647. if (!Eof)
  4648. {
  4649. if ((Missing == 0) && PrevIncomplete)
  4650. {
  4651. // This can happen only if last request returned less bytes
  4652. // than expected, but exacly number of bytes missing to last
  4653. // known file size, but actually EOF was not reached.
  4654. // Can happen only when filesize has changed since directory
  4655. // listing and server returns less bytes than requested and
  4656. // file has some special file size.
  4657. FTerminal->LogEvent(FORMAT(
  4658. "Received incomplete data packet before end of file, "
  4659. "offset: %s, size: %d, requested: %d",
  4660. (IntToStr(OperationProgress->TransferedSize), int(DataLen),
  4661. int(BlockSize))));
  4662. FTerminal->TerminalError(NULL, LoadStr(SFTP_INCOMPLETE_BEFORE_EOF));
  4663. }
  4664. // Buffer for one block of data
  4665. TFileBuffer BlockBuf;
  4666. DataLen = DataPacket.GetCardinal();
  4667. PrevIncomplete = false;
  4668. if (Missing > 0)
  4669. {
  4670. assert(DataLen <= Missing);
  4671. Missing -= DataLen;
  4672. }
  4673. else if (DataLen < BlockSize)
  4674. {
  4675. if (OperationProgress->TransferedSize + DataLen !=
  4676. OperationProgress->TransferSize)
  4677. {
  4678. // with native text transfer mode (SFTP>=4), do not bother about
  4679. // getting less than requested, read offset is ignored anyway
  4680. if ((FVersion < 4) || !OperationProgress->AsciiTransfer)
  4681. {
  4682. GapCount++;
  4683. Missing = BlockSize - DataLen;
  4684. }
  4685. }
  4686. else
  4687. {
  4688. PrevIncomplete = true;
  4689. }
  4690. }
  4691. assert(DataLen <= BlockSize);
  4692. BlockBuf.Insert(0, DataPacket.GetNextData(DataLen), DataLen);
  4693. OperationProgress->AddTransfered(DataLen);
  4694. if (OperationProgress->AsciiTransfer)
  4695. {
  4696. assert(!ResumeTransfer && !ResumeAllowed);
  4697. unsigned int PrevBlockSize = BlockBuf.Size;
  4698. BlockBuf.Convert(GetEOL(), FTerminal->Configuration->LocalEOLType, 0);
  4699. OperationProgress->SetLocalSize(
  4700. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  4701. }
  4702. FILE_OPERATION_LOOP (FMTLOAD(WRITE_ERROR, (LocalFileName)),
  4703. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  4704. );
  4705. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  4706. }
  4707. if (OperationProgress->Cancel == csCancel)
  4708. {
  4709. Abort();
  4710. }
  4711. };
  4712. if (GapCount > 0)
  4713. {
  4714. FTerminal->LogEvent(FORMAT(
  4715. "%d requests to fill %d data gaps were issued.",
  4716. (GapFillCount, GapCount)));
  4717. }
  4718. }
  4719. __finally
  4720. {
  4721. Queue.DisposeSafe();
  4722. }
  4723. // queue is discarded here
  4724. }
  4725. if (CopyParam->PreserveTime)
  4726. {
  4727. ReceiveResponse(&RemoteFilePacket, &RemoteFilePacket);
  4728. const TRemoteFile * AFile = File;
  4729. try
  4730. {
  4731. // ignore errors
  4732. if (RemoteFilePacket.Type == SSH_FXP_ATTRS)
  4733. {
  4734. // load file, avoid completion (resolving symlinks) as we do not need that
  4735. AFile = LoadFile(&RemoteFilePacket, NULL, UnixExtractFileName(FileName),
  4736. NULL, false);
  4737. }
  4738. FILETIME AcTime = DateTimeToFileTime(AFile->LastAccess,
  4739. FTerminal->SessionData->DSTMode);
  4740. FILETIME WrTime = DateTimeToFileTime(AFile->Modification,
  4741. FTerminal->SessionData->DSTMode);
  4742. SetFileTime(LocalHandle, NULL, &AcTime, &WrTime);
  4743. }
  4744. __finally
  4745. {
  4746. if (AFile != File)
  4747. {
  4748. delete AFile;
  4749. }
  4750. }
  4751. }
  4752. CloseHandle(LocalHandle);
  4753. LocalHandle = NULL;
  4754. if (ResumeAllowed)
  4755. {
  4756. FILE_OPERATION_LOOP(FMTLOAD(RENAME_AFTER_RESUME_ERROR,
  4757. (ExtractFileName(DestPartinalFullName), DestFileName)),
  4758. if (FileExists(DestFullName))
  4759. {
  4760. THROWOSIFFALSE(Sysutils::DeleteFile(DestFullName));
  4761. }
  4762. if (!Sysutils::RenameFile(DestPartinalFullName, DestFullName))
  4763. {
  4764. RaiseLastOSError();
  4765. }
  4766. );
  4767. }
  4768. DeleteLocalFile = false;
  4769. if (Attrs == -1)
  4770. {
  4771. Attrs = faArchive;
  4772. }
  4773. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  4774. if ((NewAttrs & Attrs) != NewAttrs)
  4775. {
  4776. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFullName)),
  4777. THROWOSIFFALSE(FileSetAttr(DestFullName, Attrs | NewAttrs) == 0);
  4778. );
  4779. }
  4780. }
  4781. __finally
  4782. {
  4783. if (LocalHandle) CloseHandle(LocalHandle);
  4784. if (FileStream) delete FileStream;
  4785. if (DeleteLocalFile && (!ResumeAllowed || OperationProgress->LocalyUsed == 0) &&
  4786. (OverwriteMode == omOverwrite))
  4787. {
  4788. FILE_OPERATION_LOOP (FMTLOAD(DELETE_LOCAL_FILE_ERROR, (LocalFileName)),
  4789. THROWOSIFFALSE(Sysutils::DeleteFile(LocalFileName));
  4790. )
  4791. }
  4792. // if the transfer was finished, the file is closed already
  4793. if (FTerminal->Active && !RemoteHandle.IsEmpty())
  4794. {
  4795. // do not wait for response
  4796. SFTPCloseRemote(RemoteHandle, DestFileName, OperationProgress,
  4797. true, true, NULL);
  4798. }
  4799. }
  4800. }
  4801. if (Params & cpDelete)
  4802. {
  4803. ChildError = true;
  4804. // If file is directory, do not delete it recursively, because it should be
  4805. // empty already. If not, it should not be deleted (some files were
  4806. // skipped or some new files were copied to it, while we were downloading)
  4807. int Params = dfNoRecursive;
  4808. FTerminal->DeleteFile(FileName, File, &Params);
  4809. ChildError = false;
  4810. }
  4811. }
  4812. //---------------------------------------------------------------------------
  4813. void __fastcall TSFTPFileSystem::SFTPSinkFile(AnsiString FileName,
  4814. const TRemoteFile * File, void * Param)
  4815. {
  4816. TSinkFileParams * Params = (TSinkFileParams *)Param;
  4817. assert(Params->OperationProgress);
  4818. try
  4819. {
  4820. SFTPSinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  4821. Params->Params, Params->OperationProgress, Params->Flags);
  4822. }
  4823. catch(EScpSkipFile & E)
  4824. {
  4825. TFileOperationProgressType * OperationProgress = Params->OperationProgress;
  4826. Params->Skipped = true;
  4827. SUSPEND_OPERATION (
  4828. if (!FTerminal->HandleException(&E)) throw;
  4829. );
  4830. if (OperationProgress->Cancel)
  4831. {
  4832. Abort();
  4833. }
  4834. }
  4835. }