SftpFileSystem.cpp 163 KB

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