SftpFileSystem.cpp 173 KB

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