SftpFileSystem.cpp 162 KB

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