Terminal.cpp 191 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include "Common.h"
  8. #include "PuttyTools.h"
  9. #include "FileBuffer.h"
  10. #include "Interface.h"
  11. #include "RemoteFiles.h"
  12. #include "SecureShell.h"
  13. #include "ScpFileSystem.h"
  14. #include "SftpFileSystem.h"
  15. #ifndef NO_FILEZILLA
  16. #include "FtpFileSystem.h"
  17. #endif
  18. #include "WebDAVFileSystem.h"
  19. #include "TextsCore.h"
  20. #include "HelpCore.h"
  21. #include "CoreMain.h"
  22. #include "Queue.h"
  23. #include <openssl/pkcs12.h>
  24. #include <openssl/err.h>
  25. #ifndef AUTO_WINSOCK
  26. #include <winsock2.h>
  27. #endif
  28. //---------------------------------------------------------------------------
  29. #pragma package(smart_init)
  30. //---------------------------------------------------------------------------
  31. #define FILE_OPERATION_LOOP_TERMINAL this
  32. //---------------------------------------------------------------------------
  33. //---------------------------------------------------------------------------
  34. class TLoopDetector
  35. {
  36. public:
  37. __fastcall TLoopDetector();
  38. void __fastcall RecordVisitedDirectory(const UnicodeString & Directory);
  39. bool __fastcall IsUnvisitedDirectory(const UnicodeString & Directory);
  40. private:
  41. std::unique_ptr<TStringList> FVisitedDirectories;
  42. };
  43. //---------------------------------------------------------------------------
  44. __fastcall TLoopDetector::TLoopDetector()
  45. {
  46. FVisitedDirectories.reset(CreateSortedStringList());
  47. }
  48. //---------------------------------------------------------------------------
  49. void __fastcall TLoopDetector::RecordVisitedDirectory(const UnicodeString & Directory)
  50. {
  51. UnicodeString VisitedDirectory = ExcludeTrailingBackslash(Directory);
  52. FVisitedDirectories->Add(VisitedDirectory);
  53. }
  54. //---------------------------------------------------------------------------
  55. bool __fastcall TLoopDetector::IsUnvisitedDirectory(const UnicodeString & Directory)
  56. {
  57. bool Result = (FVisitedDirectories->IndexOf(Directory) < 0);
  58. if (Result)
  59. {
  60. RecordVisitedDirectory(Directory);
  61. }
  62. return Result;
  63. }
  64. //---------------------------------------------------------------------------
  65. //---------------------------------------------------------------------------
  66. struct TMoveFileParams
  67. {
  68. UnicodeString Target;
  69. UnicodeString FileMask;
  70. };
  71. //---------------------------------------------------------------------------
  72. struct TFilesFindParams
  73. {
  74. TFileMasks FileMask;
  75. TFileFoundEvent OnFileFound;
  76. TFindingFileEvent OnFindingFile;
  77. bool Cancel;
  78. TLoopDetector LoopDetector;
  79. UnicodeString RealDirectory;
  80. };
  81. //---------------------------------------------------------------------------
  82. TCalculateSizeStats::TCalculateSizeStats()
  83. {
  84. memset(this, 0, sizeof(*this));
  85. }
  86. //---------------------------------------------------------------------------
  87. TSynchronizeOptions::TSynchronizeOptions()
  88. {
  89. memset(this, 0, sizeof(*this));
  90. }
  91. //---------------------------------------------------------------------------
  92. TSynchronizeOptions::~TSynchronizeOptions()
  93. {
  94. delete Filter;
  95. }
  96. //---------------------------------------------------------------------------
  97. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  98. {
  99. int FoundIndex;
  100. bool Result;
  101. if (Filter == NULL)
  102. {
  103. Result = true;
  104. }
  105. else
  106. {
  107. Result = Filter->Find(FileName, FoundIndex);
  108. }
  109. return Result;
  110. }
  111. //---------------------------------------------------------------------------
  112. TSpaceAvailable::TSpaceAvailable()
  113. {
  114. memset(this, 0, sizeof(*this));
  115. }
  116. //---------------------------------------------------------------------------
  117. TOverwriteFileParams::TOverwriteFileParams()
  118. {
  119. SourceSize = 0;
  120. DestSize = 0;
  121. SourcePrecision = mfFull;
  122. DestPrecision = mfFull;
  123. }
  124. //---------------------------------------------------------------------------
  125. //---------------------------------------------------------------------------
  126. TSynchronizeChecklist::TItem::TItem() :
  127. Action(saNone), IsDirectory(false), RemoteFile(NULL), Checked(true), ImageIndex(-1)
  128. {
  129. Local.ModificationFmt = mfFull;
  130. Local.Modification = 0;
  131. Local.Size = 0;
  132. Remote.ModificationFmt = mfFull;
  133. Remote.Modification = 0;
  134. Remote.Size = 0;
  135. }
  136. //---------------------------------------------------------------------------
  137. TSynchronizeChecklist::TItem::~TItem()
  138. {
  139. delete RemoteFile;
  140. }
  141. //---------------------------------------------------------------------------
  142. const UnicodeString& TSynchronizeChecklist::TItem::GetFileName() const
  143. {
  144. if (!Remote.FileName.IsEmpty())
  145. {
  146. return Remote.FileName;
  147. }
  148. else
  149. {
  150. DebugAssert(!Local.FileName.IsEmpty());
  151. return Local.FileName;
  152. }
  153. }
  154. //---------------------------------------------------------------------------
  155. //---------------------------------------------------------------------------
  156. TSynchronizeChecklist::TSynchronizeChecklist() :
  157. FList(new TList())
  158. {
  159. }
  160. //---------------------------------------------------------------------------
  161. TSynchronizeChecklist::~TSynchronizeChecklist()
  162. {
  163. for (int Index = 0; Index < FList->Count; Index++)
  164. {
  165. delete static_cast<TItem *>(FList->Items[Index]);
  166. }
  167. delete FList;
  168. }
  169. //---------------------------------------------------------------------------
  170. void TSynchronizeChecklist::Add(TItem * Item)
  171. {
  172. FList->Add(Item);
  173. }
  174. //---------------------------------------------------------------------------
  175. int __fastcall TSynchronizeChecklist::Compare(void * AItem1, void * AItem2)
  176. {
  177. TItem * Item1 = static_cast<TItem *>(AItem1);
  178. TItem * Item2 = static_cast<TItem *>(AItem2);
  179. int Result;
  180. if (!Item1->Local.Directory.IsEmpty())
  181. {
  182. Result = AnsiCompareText(Item1->Local.Directory, Item2->Local.Directory);
  183. }
  184. else
  185. {
  186. DebugAssert(!Item1->Remote.Directory.IsEmpty());
  187. Result = AnsiCompareText(Item1->Remote.Directory, Item2->Remote.Directory);
  188. }
  189. if (Result == 0)
  190. {
  191. Result = AnsiCompareText(Item1->GetFileName(), Item2->GetFileName());
  192. }
  193. return Result;
  194. }
  195. //---------------------------------------------------------------------------
  196. void TSynchronizeChecklist::Sort()
  197. {
  198. FList->Sort(Compare);
  199. }
  200. //---------------------------------------------------------------------------
  201. int TSynchronizeChecklist::GetCount() const
  202. {
  203. return FList->Count;
  204. }
  205. //---------------------------------------------------------------------------
  206. const TSynchronizeChecklist::TItem * TSynchronizeChecklist::GetItem(int Index) const
  207. {
  208. return static_cast<TItem *>(FList->Items[Index]);
  209. }
  210. //---------------------------------------------------------------------------
  211. void __fastcall TSynchronizeChecklist::Update(const TItem * Item, bool Check, TAction Action)
  212. {
  213. // TSynchronizeChecklist owns non-const items so it can manipulate them freely,
  214. // const_cast here is just an optimization
  215. TItem * MutableItem = const_cast<TItem *>(Item);
  216. DebugAssert(FList->IndexOf(MutableItem) >= 0);
  217. MutableItem->Checked = Check;
  218. MutableItem->Action = Action;
  219. }
  220. //---------------------------------------------------------------------------
  221. TSynchronizeChecklist::TAction __fastcall TSynchronizeChecklist::Reverse(TSynchronizeChecklist::TAction Action)
  222. {
  223. switch (Action)
  224. {
  225. case saUploadNew:
  226. return saDeleteLocal;
  227. case saDownloadNew:
  228. return saDeleteRemote;
  229. case saUploadUpdate:
  230. return saDownloadUpdate;
  231. case saDownloadUpdate:
  232. return saUploadUpdate;
  233. case saDeleteRemote:
  234. return saDownloadNew;
  235. case saDeleteLocal:
  236. return saUploadNew;
  237. default:
  238. case saNone:
  239. DebugFail();
  240. return saNone;
  241. }
  242. }
  243. //---------------------------------------------------------------------------
  244. //---------------------------------------------------------------------------
  245. class TTunnelThread : public TSimpleThread
  246. {
  247. public:
  248. __fastcall TTunnelThread(TSecureShell * SecureShell);
  249. virtual __fastcall ~TTunnelThread();
  250. virtual void __fastcall Terminate();
  251. protected:
  252. virtual void __fastcall Execute();
  253. private:
  254. TSecureShell * FSecureShell;
  255. bool FTerminated;
  256. };
  257. //---------------------------------------------------------------------------
  258. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  259. FSecureShell(SecureShell),
  260. FTerminated(false)
  261. {
  262. Start();
  263. }
  264. //---------------------------------------------------------------------------
  265. __fastcall TTunnelThread::~TTunnelThread()
  266. {
  267. // close before the class's virtual functions (Terminate particularly) are lost
  268. Close();
  269. }
  270. //---------------------------------------------------------------------------
  271. void __fastcall TTunnelThread::Terminate()
  272. {
  273. FTerminated = true;
  274. }
  275. //---------------------------------------------------------------------------
  276. void __fastcall TTunnelThread::Execute()
  277. {
  278. try
  279. {
  280. while (!FTerminated)
  281. {
  282. FSecureShell->Idle(250);
  283. }
  284. }
  285. catch(...)
  286. {
  287. if (FSecureShell->Active)
  288. {
  289. FSecureShell->Close();
  290. }
  291. // do not pass exception out of thread's proc
  292. }
  293. }
  294. //---------------------------------------------------------------------------
  295. //---------------------------------------------------------------------------
  296. class TTunnelUI : public TSessionUI
  297. {
  298. public:
  299. __fastcall TTunnelUI(TTerminal * Terminal);
  300. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  301. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  302. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  303. TQueryType QueryType);
  304. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  305. Exception * E, unsigned int Answers, const TQueryParams * Params,
  306. TQueryType QueryType);
  307. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  308. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  309. TStrings * Results);
  310. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  311. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
  312. virtual void __fastcall HandleExtendedException(Exception * E);
  313. virtual void __fastcall Closed();
  314. virtual void __fastcall ProcessGUI();
  315. private:
  316. TTerminal * FTerminal;
  317. unsigned int FTerminalThread;
  318. };
  319. //---------------------------------------------------------------------------
  320. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  321. {
  322. FTerminal = Terminal;
  323. FTerminalThread = GetCurrentThreadId();
  324. }
  325. //---------------------------------------------------------------------------
  326. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  327. {
  328. if (GetCurrentThreadId() == FTerminalThread)
  329. {
  330. FTerminal->Information(Str, Status);
  331. }
  332. }
  333. //---------------------------------------------------------------------------
  334. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  335. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  336. TQueryType QueryType)
  337. {
  338. unsigned int Result;
  339. if (GetCurrentThreadId() == FTerminalThread)
  340. {
  341. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  342. }
  343. else
  344. {
  345. Result = AbortAnswer(Answers);
  346. }
  347. return Result;
  348. }
  349. //---------------------------------------------------------------------------
  350. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  351. Exception * E, unsigned int Answers, const TQueryParams * Params,
  352. TQueryType QueryType)
  353. {
  354. unsigned int Result;
  355. if (GetCurrentThreadId() == FTerminalThread)
  356. {
  357. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  358. }
  359. else
  360. {
  361. Result = AbortAnswer(Answers);
  362. }
  363. return Result;
  364. }
  365. //---------------------------------------------------------------------------
  366. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  367. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  368. {
  369. bool Result;
  370. if (GetCurrentThreadId() == FTerminalThread)
  371. {
  372. if (IsAuthenticationPrompt(Kind))
  373. {
  374. Instructions = LoadStr(TUNNEL_INSTRUCTION) +
  375. (Instructions.IsEmpty() ? L"" : L"\n") +
  376. Instructions;
  377. }
  378. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  379. }
  380. else
  381. {
  382. Result = false;
  383. }
  384. return Result;
  385. }
  386. //---------------------------------------------------------------------------
  387. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  388. {
  389. if (GetCurrentThreadId() == FTerminalThread)
  390. {
  391. FTerminal->DisplayBanner(Banner);
  392. }
  393. }
  394. //---------------------------------------------------------------------------
  395. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  396. {
  397. throw ESshFatal(E, Msg, HelpKeyword);
  398. }
  399. //---------------------------------------------------------------------------
  400. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  401. {
  402. if (GetCurrentThreadId() == FTerminalThread)
  403. {
  404. FTerminal->HandleExtendedException(E);
  405. }
  406. }
  407. //---------------------------------------------------------------------------
  408. void __fastcall TTunnelUI::Closed()
  409. {
  410. // noop
  411. }
  412. //---------------------------------------------------------------------------
  413. void __fastcall TTunnelUI::ProcessGUI()
  414. {
  415. // noop
  416. }
  417. //---------------------------------------------------------------------------
  418. //---------------------------------------------------------------------------
  419. class TCallbackGuard
  420. {
  421. public:
  422. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  423. inline __fastcall ~TCallbackGuard();
  424. void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
  425. inline void __fastcall Verify();
  426. void __fastcall Dismiss();
  427. private:
  428. ExtException * FFatalError;
  429. TTerminal * FTerminal;
  430. bool FGuarding;
  431. };
  432. //---------------------------------------------------------------------------
  433. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  434. FTerminal(Terminal),
  435. FFatalError(NULL),
  436. FGuarding(FTerminal->FCallbackGuard == NULL)
  437. {
  438. if (FGuarding)
  439. {
  440. FTerminal->FCallbackGuard = this;
  441. }
  442. }
  443. //---------------------------------------------------------------------------
  444. __fastcall TCallbackGuard::~TCallbackGuard()
  445. {
  446. if (FGuarding)
  447. {
  448. DebugAssert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  449. FTerminal->FCallbackGuard = NULL;
  450. }
  451. delete FFatalError;
  452. }
  453. //---------------------------------------------------------------------------
  454. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
  455. {
  456. DebugAssert(FGuarding);
  457. // make sure we do not bother about getting back the silent abort exception
  458. // we issued ourselves. this may happen when there is an exception handler
  459. // that converts any exception to fatal one (such as in TTerminal::Open).
  460. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  461. {
  462. delete FFatalError;
  463. FFatalError = new ExtException(E, Msg, HelpKeyword);
  464. }
  465. // silently abort what we are doing.
  466. // non-silent exception would be caught probably by default application
  467. // exception handler, which may not do an appropriate action
  468. // (particularly it will not resume broken transfer).
  469. throw ECallbackGuardAbort();
  470. }
  471. //---------------------------------------------------------------------------
  472. void __fastcall TCallbackGuard::Dismiss()
  473. {
  474. DebugAssert(FFatalError == NULL);
  475. FGuarding = false;
  476. }
  477. //---------------------------------------------------------------------------
  478. void __fastcall TCallbackGuard::Verify()
  479. {
  480. if (FGuarding)
  481. {
  482. FGuarding = false;
  483. DebugAssert(FTerminal->FCallbackGuard == this);
  484. FTerminal->FCallbackGuard = NULL;
  485. if (FFatalError != NULL)
  486. {
  487. throw ESshFatal(FFatalError, L"");
  488. }
  489. }
  490. }
  491. //---------------------------------------------------------------------------
  492. //---------------------------------------------------------------------------
  493. TRobustOperationLoop::TRobustOperationLoop(TTerminal * Terminal, TFileOperationProgressType * OperationProgress) :
  494. FTerminal(Terminal),
  495. FOperationProgress(OperationProgress),
  496. FRetry(false)
  497. {
  498. }
  499. //---------------------------------------------------------------------------
  500. bool TRobustOperationLoop::TryReopen(Exception & E)
  501. {
  502. FRetry =
  503. !FTerminal->Active &&
  504. FTerminal->QueryReopen(&E, ropNoReadDirectory, FOperationProgress);
  505. return FRetry;
  506. }
  507. //---------------------------------------------------------------------------
  508. bool TRobustOperationLoop::ShouldRetry()
  509. {
  510. return FRetry;
  511. }
  512. //---------------------------------------------------------------------------
  513. bool TRobustOperationLoop::Retry()
  514. {
  515. bool Result = FRetry;
  516. FRetry = false;
  517. return Result;
  518. }
  519. //---------------------------------------------------------------------------
  520. class TRetryOperationLoop
  521. {
  522. public:
  523. TRetryOperationLoop(TTerminal * Terminal);
  524. void Error(Exception & E);
  525. void Error(Exception & E, TSessionAction & Action);
  526. void Error(Exception & E, const UnicodeString & Message);
  527. void Error(Exception & E, TSessionAction & Action, const UnicodeString & Message);
  528. bool Retry();
  529. private:
  530. TTerminal * FTerminal;
  531. bool FRetry;
  532. void DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message);
  533. };
  534. //---------------------------------------------------------------------------
  535. TRetryOperationLoop::TRetryOperationLoop(TTerminal * Terminal)
  536. {
  537. FTerminal = Terminal;
  538. FRetry = false;
  539. }
  540. //---------------------------------------------------------------------------
  541. void TRetryOperationLoop::DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message)
  542. {
  543. // Note that the action may already be canceled when RollbackAction is called
  544. unsigned int Result;
  545. try
  546. {
  547. Result = FTerminal->CommandError(&E, Message, qaRetry | qaSkip | qaAbort);
  548. }
  549. catch (Exception & E2)
  550. {
  551. if (Action != NULL)
  552. {
  553. FTerminal->RollbackAction(*Action, NULL, &E2);
  554. }
  555. throw;
  556. }
  557. switch (Result)
  558. {
  559. case qaRetry:
  560. FRetry = true;
  561. if (Action != NULL)
  562. {
  563. Action->Cancel();
  564. }
  565. break;
  566. case qaAbort:
  567. if (Action != NULL)
  568. {
  569. FTerminal->RollbackAction(*Action, NULL, &E);
  570. }
  571. Abort();
  572. break;
  573. case qaSkip:
  574. if (Action != NULL)
  575. {
  576. Action->Cancel();
  577. }
  578. break;
  579. default:
  580. DebugFail();
  581. break;
  582. }
  583. }
  584. //---------------------------------------------------------------------------
  585. void TRetryOperationLoop::Error(Exception & E)
  586. {
  587. DoError(E, NULL, UnicodeString());
  588. }
  589. //---------------------------------------------------------------------------
  590. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action)
  591. {
  592. DoError(E, &Action, UnicodeString());
  593. }
  594. //---------------------------------------------------------------------------
  595. void TRetryOperationLoop::Error(Exception & E, const UnicodeString & Message)
  596. {
  597. DoError(E, NULL, Message);
  598. }
  599. //---------------------------------------------------------------------------
  600. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action, const UnicodeString & Message)
  601. {
  602. DoError(E, &Action, Message);
  603. }
  604. //---------------------------------------------------------------------------
  605. bool TRetryOperationLoop::Retry()
  606. {
  607. bool Result = FRetry;
  608. FRetry = false;
  609. return Result;
  610. }
  611. //---------------------------------------------------------------------------
  612. //---------------------------------------------------------------------------
  613. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  614. TConfiguration * Configuration)
  615. {
  616. FConfiguration = Configuration;
  617. FSessionData = new TSessionData(L"");
  618. FSessionData->Assign(SessionData);
  619. FLog = new TSessionLog(this, FSessionData, Configuration);
  620. FActionLog = new TActionLog(this, FSessionData, Configuration);
  621. FFiles = new TRemoteDirectory(this);
  622. FExceptionOnFail = 0;
  623. FInTransaction = 0;
  624. FReadCurrentDirectoryPending = false;
  625. FReadDirectoryPending = false;
  626. FUsersGroupsLookedup = False;
  627. FTunnelLocalPortNumber = 0;
  628. FFileSystem = NULL;
  629. FSecureShell = NULL;
  630. FOnProgress = NULL;
  631. FOnFinished = NULL;
  632. FOnDeleteLocalFile = NULL;
  633. FOnReadDirectoryProgress = NULL;
  634. FOnQueryUser = NULL;
  635. FOnPromptUser = NULL;
  636. FOnDisplayBanner = NULL;
  637. FOnShowExtendedException = NULL;
  638. FOnInformation = NULL;
  639. FOnClose = NULL;
  640. FOnFindingFile = NULL;
  641. FUseBusyCursor = True;
  642. FLockDirectory = L"";
  643. FDirectoryCache = new TRemoteDirectoryCache();
  644. FDirectoryChangesCache = NULL;
  645. FFSProtocol = cfsUnknown;
  646. FCommandSession = NULL;
  647. FAutoReadDirectory = true;
  648. FReadingCurrentDirectory = false;
  649. FStatus = ssClosed;
  650. FOpening = 0;
  651. FTunnelThread = NULL;
  652. FTunnel = NULL;
  653. FTunnelData = NULL;
  654. FTunnelLog = NULL;
  655. FTunnelUI = NULL;
  656. FTunnelOpening = false;
  657. FCallbackGuard = NULL;
  658. FNesting = 0;
  659. }
  660. //---------------------------------------------------------------------------
  661. __fastcall TTerminal::~TTerminal()
  662. {
  663. if (Active)
  664. {
  665. Close();
  666. }
  667. if (FCallbackGuard != NULL)
  668. {
  669. // see TTerminal::HandleExtendedException
  670. FCallbackGuard->Dismiss();
  671. }
  672. DebugAssert(FTunnel == NULL);
  673. SAFE_DESTROY(FCommandSession);
  674. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  675. (FDirectoryChangesCache != NULL))
  676. {
  677. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  678. FDirectoryChangesCache);
  679. }
  680. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  681. SAFE_DESTROY_EX(TSessionLog, FLog);
  682. SAFE_DESTROY_EX(TActionLog, FActionLog);
  683. delete FFiles;
  684. delete FDirectoryCache;
  685. delete FDirectoryChangesCache;
  686. SAFE_DESTROY(FSessionData);
  687. }
  688. //---------------------------------------------------------------------------
  689. void __fastcall TTerminal::Idle()
  690. {
  691. // Once we disconnect, do nothing, until reconnect handler
  692. // "receives the information".
  693. // Never go idle when called from within ::ProcessGUI() call
  694. // as we may recurse for good, timeouting eventually.
  695. if (Active && (FNesting == 0))
  696. {
  697. TAutoNestingCounter NestingCounter(FNesting);
  698. if (Configuration->ActualLogProtocol >= 1)
  699. {
  700. LogEvent(L"Session upkeep");
  701. }
  702. DebugAssert(FFileSystem != NULL);
  703. FFileSystem->Idle();
  704. if (CommandSessionOpened)
  705. {
  706. try
  707. {
  708. FCommandSession->Idle();
  709. }
  710. catch(Exception & E)
  711. {
  712. // If the secondary session is dropped, ignore the error and let
  713. // it be reconnected when needed.
  714. // BTW, non-fatal error can hardly happen here, that's why
  715. // it is displayed, because it can be useful to know.
  716. if (FCommandSession->Active)
  717. {
  718. FCommandSession->HandleExtendedException(&E);
  719. }
  720. }
  721. }
  722. }
  723. }
  724. //---------------------------------------------------------------------
  725. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  726. {
  727. return Configuration->EncryptPassword(Password, SessionData->SessionName);
  728. }
  729. //---------------------------------------------------------------------
  730. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  731. {
  732. UnicodeString Result;
  733. try
  734. {
  735. Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
  736. }
  737. catch(EAbort &)
  738. {
  739. // silently ignore aborted prompts for master password and return empty password
  740. }
  741. return Result;
  742. }
  743. //---------------------------------------------------------------------------
  744. void __fastcall TTerminal::RecryptPasswords()
  745. {
  746. FSessionData->RecryptPasswords();
  747. FRememberedPassword = EncryptPassword(DecryptPassword(FRememberedPassword));
  748. FRememberedTunnelPassword = EncryptPassword(DecryptPassword(FRememberedTunnelPassword));
  749. }
  750. //---------------------------------------------------------------------------
  751. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  752. const UnicodeString BasePath)
  753. {
  754. // replace this by AbsolutePath()
  755. Path = UnixExcludeTrailingBackslash(Path);
  756. if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
  757. {
  758. // TODO: Handle more complicated cases like "../../xxx"
  759. if (Path == L"..")
  760. {
  761. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  762. UnixExcludeTrailingBackslash(BasePath)));
  763. }
  764. else
  765. {
  766. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  767. }
  768. }
  769. return Path;
  770. }
  771. //---------------------------------------------------------------------------
  772. bool __fastcall TTerminal::GetActive()
  773. {
  774. return (FFileSystem != NULL) && FFileSystem->GetActive();
  775. }
  776. //---------------------------------------------------------------------------
  777. void __fastcall TTerminal::Close()
  778. {
  779. FFileSystem->Close();
  780. // Cannot rely on CommandSessionOpened here as Status is set to ssClosed
  781. // only after the OnClose is called
  782. if ((FCommandSession != NULL) && FCommandSession->Active)
  783. {
  784. // prevent recursion
  785. FCommandSession->OnClose = NULL;
  786. FCommandSession->Close();
  787. }
  788. }
  789. //---------------------------------------------------------------------------
  790. void __fastcall TTerminal::ResetConnection()
  791. {
  792. // used to be called from Reopen(), why?
  793. FTunnelError = L"";
  794. FRememberedPasswordTried = false;
  795. // Particularly to prevent reusing a wrong client certificate passphrase
  796. // from a previous login attempt
  797. FRememberedPassword = UnicodeString();
  798. FRememberedTunnelPasswordTried = false;
  799. FRememberedTunnelPassword = UnicodeString();
  800. if (FDirectoryChangesCache != NULL)
  801. {
  802. delete FDirectoryChangesCache;
  803. FDirectoryChangesCache = NULL;
  804. }
  805. FFiles->Directory = L"";
  806. // note that we cannot clear contained files
  807. // as they can still be referenced in the GUI atm
  808. }
  809. //---------------------------------------------------------------------------
  810. UnicodeString __fastcall TTerminal::FingerprintScan()
  811. {
  812. SessionData->FingerprintScan = true;
  813. try
  814. {
  815. Open();
  816. // we should never get here
  817. Abort();
  818. }
  819. catch (...)
  820. {
  821. if (!FFingerprintScanned.IsEmpty())
  822. {
  823. return FFingerprintScanned;
  824. }
  825. throw;
  826. }
  827. DebugFail();
  828. return UnicodeString();
  829. }
  830. //---------------------------------------------------------------------------
  831. void __fastcall TTerminal::Open()
  832. {
  833. TAutoNestingCounter OpeningCounter(FOpening);
  834. ReflectSettings();
  835. try
  836. {
  837. DoInformation(L"", true, 1);
  838. try
  839. {
  840. try
  841. {
  842. ResetConnection();
  843. FStatus = ssOpening;
  844. try
  845. {
  846. if (FFileSystem == NULL)
  847. {
  848. Log->AddSystemInfo();
  849. DoInitializeLog();
  850. Log->AddStartupInfo();
  851. }
  852. DebugAssert(FTunnel == NULL);
  853. if (FSessionData->Tunnel)
  854. {
  855. DoInformation(LoadStr(OPEN_TUNNEL), true);
  856. LogEvent(L"Opening tunnel.");
  857. OpenTunnel();
  858. Log->AddSeparator();
  859. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  860. DoInformation(LoadStr(USING_TUNNEL), false);
  861. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  862. (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
  863. }
  864. else
  865. {
  866. DebugAssert(FTunnelLocalPortNumber == 0);
  867. }
  868. if (FFileSystem == NULL)
  869. {
  870. if (SessionData->FSProtocol == fsFTP)
  871. {
  872. #ifdef NO_FILEZILLA
  873. LogEvent(L"FTP protocol is not supported by this build.");
  874. FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
  875. #else
  876. FFSProtocol = cfsFTP;
  877. FFileSystem = new TFTPFileSystem(this);
  878. FFileSystem->Open();
  879. Log->AddSeparator();
  880. LogEvent(L"Using FTP protocol.");
  881. #endif
  882. }
  883. else if (SessionData->FSProtocol == fsWebDAV)
  884. {
  885. FFSProtocol = cfsWebDAV;
  886. FFileSystem = new TWebDAVFileSystem(this);
  887. FFileSystem->Open();
  888. Log->AddSeparator();
  889. LogEvent(L"Using WebDAV protocol.");
  890. }
  891. else
  892. {
  893. DebugAssert(FSecureShell == NULL);
  894. try
  895. {
  896. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  897. try
  898. {
  899. // there will be only one channel in this session
  900. FSecureShell->Simple = true;
  901. FSecureShell->Open();
  902. }
  903. catch(Exception & E)
  904. {
  905. DebugAssert(!FSecureShell->Active);
  906. if (SessionData->FingerprintScan)
  907. {
  908. FFingerprintScanned = FSecureShell->GetHostKeyFingerprint();
  909. }
  910. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  911. {
  912. // the only case where we expect this to happen
  913. DebugAssert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
  914. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  915. }
  916. else
  917. {
  918. throw;
  919. }
  920. }
  921. Log->AddSeparator();
  922. if ((SessionData->FSProtocol == fsSCPonly) ||
  923. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  924. {
  925. FFSProtocol = cfsSCP;
  926. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  927. FSecureShell = NULL; // ownership passed
  928. LogEvent(L"Using SCP protocol.");
  929. }
  930. else
  931. {
  932. FFSProtocol = cfsSFTP;
  933. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  934. FSecureShell = NULL; // ownership passed
  935. LogEvent(L"Using SFTP protocol.");
  936. }
  937. }
  938. __finally
  939. {
  940. delete FSecureShell;
  941. FSecureShell = NULL;
  942. }
  943. }
  944. }
  945. else
  946. {
  947. FFileSystem->Open();
  948. }
  949. }
  950. __finally
  951. {
  952. if (FSessionData->Tunnel)
  953. {
  954. FSessionData->RollbackTunnel();
  955. }
  956. }
  957. if (SessionData->CacheDirectoryChanges)
  958. {
  959. DebugAssert(FDirectoryChangesCache == NULL);
  960. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  961. Configuration->CacheDirectoryChangesMaxSize);
  962. if (SessionData->PreserveDirectoryChanges)
  963. {
  964. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  965. FDirectoryChangesCache);
  966. }
  967. }
  968. DoStartup();
  969. if (FCollectFileSystemUsage)
  970. {
  971. FFileSystem->CollectUsage();
  972. FCollectFileSystemUsage = false;
  973. }
  974. DoInformation(LoadStr(STATUS_READY), true);
  975. FStatus = ssOpened;
  976. }
  977. catch(...)
  978. {
  979. // rollback
  980. if (FDirectoryChangesCache != NULL)
  981. {
  982. delete FDirectoryChangesCache;
  983. FDirectoryChangesCache = NULL;
  984. }
  985. if (SessionData->FingerprintScan && (FFileSystem != NULL) &&
  986. DebugAlwaysTrue(SessionData->Ftps != ftpsNone))
  987. {
  988. FFingerprintScanned = FFileSystem->GetSessionInfo().CertificateFingerprint;
  989. }
  990. throw;
  991. }
  992. }
  993. __finally
  994. {
  995. DoInformation(L"", true, 0);
  996. }
  997. }
  998. catch(EFatal &)
  999. {
  1000. throw;
  1001. }
  1002. catch(Exception & E)
  1003. {
  1004. // any exception while opening session is fatal
  1005. FatalError(&E, L"");
  1006. }
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  1010. {
  1011. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  1012. bool Result = (Socket != INVALID_SOCKET);
  1013. if (Result)
  1014. {
  1015. SOCKADDR_IN Address;
  1016. memset(&Address, 0, sizeof(Address));
  1017. Address.sin_family = AF_INET;
  1018. Address.sin_port = htons(static_cast<short>(PortNumber));
  1019. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1020. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  1021. closesocket(Socket);
  1022. }
  1023. return Result;
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. void __fastcall TTerminal::OpenTunnel()
  1027. {
  1028. DebugAssert(FTunnelData == NULL);
  1029. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  1030. if (FTunnelLocalPortNumber == 0)
  1031. {
  1032. FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
  1033. while (!IsListenerFree(FTunnelLocalPortNumber))
  1034. {
  1035. FTunnelLocalPortNumber++;
  1036. if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
  1037. {
  1038. FTunnelLocalPortNumber = 0;
  1039. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  1040. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  1041. }
  1042. }
  1043. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  1044. }
  1045. try
  1046. {
  1047. FTunnelData = new TSessionData(L"");
  1048. FTunnelData->Assign(StoredSessions->DefaultSettings);
  1049. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  1050. FTunnelData->Tunnel = false;
  1051. FTunnelData->HostName = FSessionData->TunnelHostName;
  1052. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  1053. FTunnelData->UserName = FSessionData->TunnelUserName;
  1054. FTunnelData->Password = FSessionData->TunnelPassword;
  1055. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  1056. FTunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  1057. (FTunnelLocalPortNumber, FSessionData->HostNameExpanded, FSessionData->PortNumber));
  1058. FTunnelData->HostKey = FSessionData->TunnelHostKey;
  1059. // inherit proxy options on the main session
  1060. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  1061. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  1062. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  1063. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  1064. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  1065. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  1066. FTunnelData->ProxyLocalCommand = FSessionData->ProxyLocalCommand;
  1067. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  1068. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  1069. // inherit most SSH options of the main session (except for private key and bugs)
  1070. FTunnelData->Compression = FSessionData->Compression;
  1071. FTunnelData->SshProt = FSessionData->SshProt;
  1072. FTunnelData->CipherList = FSessionData->CipherList;
  1073. FTunnelData->Ssh2DES = FSessionData->Ssh2DES;
  1074. FTunnelData->KexList = FSessionData->KexList;
  1075. FTunnelData->RekeyData = FSessionData->RekeyData;
  1076. FTunnelData->RekeyTime = FSessionData->RekeyTime;
  1077. FTunnelData->SshNoUserAuth = FSessionData->SshNoUserAuth;
  1078. FTunnelData->AuthGSSAPI = FSessionData->AuthGSSAPI;
  1079. FTunnelData->GSSAPIFwdTGT = FSessionData->GSSAPIFwdTGT;
  1080. FTunnelData->TryAgent = FSessionData->TryAgent;
  1081. FTunnelData->AgentFwd = FSessionData->AgentFwd;
  1082. FTunnelData->AuthTIS = FSessionData->AuthTIS;
  1083. FTunnelData->AuthKI = FSessionData->AuthKI;
  1084. FTunnelData->AuthKIPassword = FSessionData->AuthKIPassword;
  1085. FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
  1086. FTunnelLog->Parent = FLog;
  1087. FTunnelLog->Name = L"Tunnel";
  1088. FTunnelLog->ReflectSettings();
  1089. FTunnelUI = new TTunnelUI(this);
  1090. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  1091. FTunnelOpening = true;
  1092. try
  1093. {
  1094. FTunnel->Open();
  1095. }
  1096. __finally
  1097. {
  1098. FTunnelOpening = false;
  1099. }
  1100. FTunnelThread = new TTunnelThread(FTunnel);
  1101. }
  1102. catch(...)
  1103. {
  1104. CloseTunnel();
  1105. throw;
  1106. }
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall TTerminal::CloseTunnel()
  1110. {
  1111. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  1112. FTunnelError = FTunnel->LastTunnelError;
  1113. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  1114. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  1115. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  1116. SAFE_DESTROY(FTunnelData);
  1117. FTunnelLocalPortNumber = 0;
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. void __fastcall TTerminal::Closed()
  1121. {
  1122. if (FTunnel != NULL)
  1123. {
  1124. CloseTunnel();
  1125. }
  1126. if (OnClose)
  1127. {
  1128. TCallbackGuard Guard(this);
  1129. OnClose(this);
  1130. Guard.Verify();
  1131. }
  1132. FStatus = ssClosed;
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TTerminal::ProcessGUI()
  1136. {
  1137. // Do not process GUI here, as we are called directly from a GUI loop and may
  1138. // recurse for good.
  1139. // Alternatively we may check for (FOperationProgress == NULL)
  1140. if (FNesting == 0)
  1141. {
  1142. TAutoNestingCounter NestingCounter(FNesting);
  1143. ::ProcessGUI();
  1144. }
  1145. }
  1146. //---------------------------------------------------------------------------
  1147. void __fastcall TTerminal::Progress(TFileOperationProgressType * OperationProgress)
  1148. {
  1149. if (FNesting == 0)
  1150. {
  1151. TAutoNestingCounter NestingCounter(FNesting);
  1152. OperationProgress->Progress();
  1153. }
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall TTerminal::Reopen(int Params)
  1157. {
  1158. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  1159. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  1160. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  1161. bool PrevReadDirectoryPending = FReadDirectoryPending;
  1162. DebugAssert(!FSuspendTransaction);
  1163. bool PrevAutoReadDirectory = FAutoReadDirectory;
  1164. // here used to be a check for FExceptionOnFail being 0
  1165. // but it can happen, e.g. when we are downloading file to execute it.
  1166. // however I'm not sure why we mind having excaption-on-fail enabled here
  1167. int PrevExceptionOnFail = FExceptionOnFail;
  1168. try
  1169. {
  1170. FReadCurrentDirectoryPending = false;
  1171. FReadDirectoryPending = false;
  1172. FSuspendTransaction = true;
  1173. FExceptionOnFail = 0;
  1174. // typically, we avoid reading directory, when there is operation ongoing,
  1175. // for file list which may reference files from current directory
  1176. if (FLAGSET(Params, ropNoReadDirectory))
  1177. {
  1178. AutoReadDirectory = false;
  1179. }
  1180. // only peek, we may not be connected at all atm,
  1181. // so make sure we do not try retrieving current directory from the server
  1182. // (particularly with FTP)
  1183. UnicodeString ACurrentDirectory = PeekCurrentDirectory();
  1184. if (!ACurrentDirectory.IsEmpty())
  1185. {
  1186. SessionData->RemoteDirectory = ACurrentDirectory;
  1187. }
  1188. if (SessionData->FSProtocol == fsSFTP)
  1189. {
  1190. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  1191. }
  1192. // Could be active before, if fatal error occured in the secondary terminal.
  1193. // But now, since we handle the secondary terminal's OnClose,
  1194. // by closing outselves, it should not happen anymore.
  1195. if (DebugAlwaysFalse(Active))
  1196. {
  1197. Close();
  1198. }
  1199. Open();
  1200. }
  1201. __finally
  1202. {
  1203. SessionData->RemoteDirectory = PrevRemoteDirectory;
  1204. SessionData->FSProtocol = OrigFSProtocol;
  1205. FAutoReadDirectory = PrevAutoReadDirectory;
  1206. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  1207. FReadDirectoryPending = PrevReadDirectoryPending;
  1208. FSuspendTransaction = false;
  1209. FExceptionOnFail = PrevExceptionOnFail;
  1210. }
  1211. }
  1212. //---------------------------------------------------------------------------
  1213. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1214. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  1215. {
  1216. bool AResult;
  1217. TStrings * Prompts = new TStringList;
  1218. TStrings * Results = new TStringList;
  1219. try
  1220. {
  1221. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  1222. Results->AddObject(Result, (TObject *)MaxLen);
  1223. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1224. Result = Results->Strings[0];
  1225. }
  1226. __finally
  1227. {
  1228. delete Prompts;
  1229. delete Results;
  1230. }
  1231. return AResult;
  1232. }
  1233. //---------------------------------------------------------------------------
  1234. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1235. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1236. {
  1237. // If PromptUser is overridden in descendant class, the overridden version
  1238. // is not called when accessed via TSessionIU interface.
  1239. // So this is workaround.
  1240. // Actually no longer needed as we do not uverride DoPromptUser
  1241. // anymore in TSecondaryTerminal.
  1242. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1243. }
  1244. //---------------------------------------------------------------------------
  1245. TTerminal * __fastcall TTerminal::GetPasswordSource()
  1246. {
  1247. return this;
  1248. }
  1249. //---------------------------------------------------------------------------
  1250. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  1251. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1252. {
  1253. bool AResult = false;
  1254. bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
  1255. if (PasswordOrPassphrasePrompt)
  1256. {
  1257. bool & PasswordTried =
  1258. FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
  1259. if (!PasswordTried)
  1260. {
  1261. // let's expect that the main session is already authenticated and its password
  1262. // is not written after, so no locking is necessary
  1263. // (no longer true, once the main session can be reconnected)
  1264. UnicodeString APassword;
  1265. if (FTunnelOpening)
  1266. {
  1267. APassword = GetPasswordSource()->RememberedTunnelPassword;
  1268. }
  1269. else
  1270. {
  1271. APassword = GetPasswordSource()->RememberedPassword;
  1272. }
  1273. Results->Strings[0] = APassword;
  1274. if (!Results->Strings[0].IsEmpty())
  1275. {
  1276. LogEvent(L"Using remembered password.");
  1277. AResult = true;
  1278. }
  1279. PasswordTried = true;
  1280. }
  1281. }
  1282. if (!AResult)
  1283. {
  1284. if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
  1285. {
  1286. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1287. }
  1288. if (OnPromptUser != NULL)
  1289. {
  1290. TCallbackGuard Guard(this);
  1291. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1292. Guard.Verify();
  1293. }
  1294. if (AResult && PasswordOrPassphrasePrompt &&
  1295. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1296. {
  1297. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1298. if (FTunnelOpening)
  1299. {
  1300. GetPasswordSource()->FRememberedTunnelPassword = EncryptedPassword;
  1301. }
  1302. else
  1303. {
  1304. GetPasswordSource()->FRememberedPassword = EncryptedPassword;
  1305. }
  1306. }
  1307. }
  1308. return AResult;
  1309. }
  1310. //---------------------------------------------------------------------------
  1311. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1312. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1313. TQueryType QueryType)
  1314. {
  1315. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1316. unsigned int Answer = AbortAnswer(Answers);
  1317. if (FOnQueryUser)
  1318. {
  1319. TCallbackGuard Guard(this);
  1320. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1321. Guard.Verify();
  1322. }
  1323. return Answer;
  1324. }
  1325. //---------------------------------------------------------------------------
  1326. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1327. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1328. TQueryType QueryType)
  1329. {
  1330. unsigned int Result;
  1331. UnicodeString ExMessage;
  1332. if (DebugAlwaysTrue(ExceptionMessage(E, ExMessage) || !Query.IsEmpty()))
  1333. {
  1334. TStrings * MoreMessages = new TStringList();
  1335. try
  1336. {
  1337. if (!ExMessage.IsEmpty() && !Query.IsEmpty())
  1338. {
  1339. MoreMessages->Add(UnformatMessage(ExMessage));
  1340. }
  1341. ExtException * EE = dynamic_cast<ExtException*>(E);
  1342. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1343. {
  1344. MoreMessages->AddStrings(EE->MoreMessages);
  1345. }
  1346. // We know MoreMessages not to be NULL here,
  1347. // AppendExceptionStackTraceAndForget should never return true
  1348. // (indicating it had to create the string list)
  1349. DebugAlwaysFalse(AppendExceptionStackTraceAndForget(MoreMessages));
  1350. TQueryParams HelpKeywordOverrideParams;
  1351. if (Params != NULL)
  1352. {
  1353. HelpKeywordOverrideParams.Assign(*Params);
  1354. }
  1355. HelpKeywordOverrideParams.HelpKeyword =
  1356. MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
  1357. Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
  1358. MoreMessages->Count ? MoreMessages : NULL,
  1359. Answers, &HelpKeywordOverrideParams, QueryType);
  1360. }
  1361. __finally
  1362. {
  1363. delete MoreMessages;
  1364. }
  1365. }
  1366. return Result;
  1367. }
  1368. //---------------------------------------------------------------------------
  1369. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1370. {
  1371. if (OnDisplayBanner != NULL)
  1372. {
  1373. if (Configuration->ForceBanners ||
  1374. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  1375. {
  1376. bool NeverShowAgain = false;
  1377. int Options =
  1378. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1379. TCallbackGuard Guard(this);
  1380. OnDisplayBanner(this, SessionData->SessionName, Banner,
  1381. NeverShowAgain, Options);
  1382. Guard.Verify();
  1383. if (!Configuration->ForceBanners && NeverShowAgain)
  1384. {
  1385. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1386. }
  1387. }
  1388. }
  1389. }
  1390. //---------------------------------------------------------------------------
  1391. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  1392. {
  1393. Log->AddException(E);
  1394. if (OnShowExtendedException != NULL)
  1395. {
  1396. TCallbackGuard Guard(this);
  1397. // the event handler may destroy 'this' ...
  1398. OnShowExtendedException(this, E, NULL);
  1399. // .. hence guard is dismissed from destructor, to make following call no-op
  1400. Guard.Verify();
  1401. }
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  1405. {
  1406. Log->AddException(E);
  1407. if (OnShowExtendedException != NULL)
  1408. {
  1409. OnShowExtendedException(this, E, NULL);
  1410. }
  1411. }
  1412. //---------------------------------------------------------------------------
  1413. void __fastcall TTerminal::DoInformation(const UnicodeString & Str, bool Status,
  1414. int Phase)
  1415. {
  1416. if (OnInformation)
  1417. {
  1418. TCallbackGuard Guard(this);
  1419. OnInformation(this, Str, Status, Phase);
  1420. Guard.Verify();
  1421. }
  1422. }
  1423. //---------------------------------------------------------------------------
  1424. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  1425. {
  1426. DoInformation(Str, Status);
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
  1430. {
  1431. if (OnProgress != NULL)
  1432. {
  1433. TCallbackGuard Guard(this);
  1434. OnProgress(ProgressData);
  1435. Guard.Verify();
  1436. }
  1437. }
  1438. //---------------------------------------------------------------------------
  1439. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  1440. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  1441. {
  1442. if (OnFinished != NULL)
  1443. {
  1444. TCallbackGuard Guard(this);
  1445. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  1446. Guard.Verify();
  1447. }
  1448. }
  1449. //---------------------------------------------------------------------------
  1450. void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
  1451. {
  1452. for (int Index = 0; Index < fcCount; Index++)
  1453. {
  1454. FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
  1455. }
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  1459. {
  1460. DebugAssert(FFileSystem);
  1461. return FFileSystem->IsCapable(Capability);
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  1465. {
  1466. return FFileSystem->AbsolutePath(Path, Local);
  1467. }
  1468. //---------------------------------------------------------------------------
  1469. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  1470. {
  1471. bool ChangesDirectory = false;
  1472. bool ModifiesFiles = false;
  1473. switch ((TFSCommand)Cmd) {
  1474. case fsChangeDirectory:
  1475. case fsHomeDirectory:
  1476. ChangesDirectory = true;
  1477. break;
  1478. case fsCopyToRemote:
  1479. case fsDeleteFile:
  1480. case fsRenameFile:
  1481. case fsMoveFile:
  1482. case fsCopyFile:
  1483. case fsCreateDirectory:
  1484. case fsChangeMode:
  1485. case fsChangeGroup:
  1486. case fsChangeOwner:
  1487. case fsChangeProperties:
  1488. case fsLock:
  1489. ModifiesFiles = true;
  1490. break;
  1491. case fsAnyCommand:
  1492. ChangesDirectory = true;
  1493. ModifiesFiles = true;
  1494. break;
  1495. }
  1496. if (ChangesDirectory)
  1497. {
  1498. if (!InTransaction())
  1499. {
  1500. ReadCurrentDirectory();
  1501. if (AutoReadDirectory)
  1502. {
  1503. ReadDirectory(false);
  1504. }
  1505. }
  1506. else
  1507. {
  1508. FReadCurrentDirectoryPending = true;
  1509. if (AutoReadDirectory)
  1510. {
  1511. FReadDirectoryPending = true;
  1512. }
  1513. }
  1514. }
  1515. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  1516. {
  1517. if (!InTransaction())
  1518. {
  1519. ReadDirectory(true);
  1520. }
  1521. else
  1522. {
  1523. FReadDirectoryPending = true;
  1524. }
  1525. }
  1526. }
  1527. //---------------------------------------------------------------------------
  1528. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  1529. {
  1530. TerminalError(NULL, Msg);
  1531. }
  1532. //---------------------------------------------------------------------------
  1533. void __fastcall TTerminal::TerminalError(
  1534. Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  1535. {
  1536. throw ETerminal(E, Msg, HelpKeyword);
  1537. }
  1538. //---------------------------------------------------------------------------
  1539. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  1540. {
  1541. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  1542. DebugAssert(Fatal != NULL);
  1543. bool Result;
  1544. if ((Fatal != NULL) && Fatal->ReopenQueried)
  1545. {
  1546. Result = false;
  1547. }
  1548. else
  1549. {
  1550. LogEvent(L"Connection was lost, asking what to do.");
  1551. TQueryParams Params(qpAllowContinueOnError);
  1552. Params.Timeout = Configuration->SessionReopenAuto;
  1553. Params.TimeoutAnswer = qaRetry;
  1554. TQueryButtonAlias Aliases[1];
  1555. Aliases[0].Button = qaRetry;
  1556. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  1557. Params.Aliases = Aliases;
  1558. Params.AliasesCount = LENOF(Aliases);
  1559. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  1560. if (Fatal != NULL)
  1561. {
  1562. Fatal->ReopenQueried = true;
  1563. }
  1564. }
  1565. return Result;
  1566. }
  1567. //---------------------------------------------------------------------------
  1568. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  1569. TFileOperationProgressType * OperationProgress)
  1570. {
  1571. TSuspendFileOperationProgress Suspend(OperationProgress);
  1572. bool Result = DoQueryReopen(E);
  1573. if (Result)
  1574. {
  1575. TDateTime Start = Now();
  1576. do
  1577. {
  1578. try
  1579. {
  1580. Reopen(Params);
  1581. }
  1582. catch(Exception & E)
  1583. {
  1584. if (!Active)
  1585. {
  1586. Result =
  1587. ((Configuration->SessionReopenTimeout == 0) ||
  1588. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout)) &&
  1589. DoQueryReopen(&E);
  1590. }
  1591. else
  1592. {
  1593. throw;
  1594. }
  1595. }
  1596. }
  1597. while (!Active && Result);
  1598. }
  1599. return Result;
  1600. }
  1601. //---------------------------------------------------------------------------
  1602. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  1603. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  1604. bool AllowSkip, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
  1605. {
  1606. bool Result = false;
  1607. Log->AddException(&E);
  1608. unsigned int Answer;
  1609. bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
  1610. if (SkipToAllPossible && OperationProgress->SkipToAll)
  1611. {
  1612. Answer = qaSkip;
  1613. }
  1614. else
  1615. {
  1616. int Answers = qaRetry | qaAbort |
  1617. FLAGMASK(AllowSkip, qaSkip) |
  1618. FLAGMASK(SkipToAllPossible, qaAll) |
  1619. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  1620. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  1621. Params.HelpKeyword = HelpKeyword;
  1622. TQueryButtonAlias Aliases[2];
  1623. int AliasCount = 0;
  1624. if (FLAGSET(Answers, qaAll))
  1625. {
  1626. Aliases[AliasCount].Button = qaAll;
  1627. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  1628. AliasCount++;
  1629. }
  1630. if (FLAGSET(Answers, qaYes))
  1631. {
  1632. Aliases[AliasCount].Button = qaYes;
  1633. Aliases[AliasCount].Alias = SpecialRetry;
  1634. AliasCount++;
  1635. }
  1636. if (AliasCount > 0)
  1637. {
  1638. Params.Aliases = Aliases;
  1639. Params.AliasesCount = AliasCount;
  1640. }
  1641. {
  1642. TSuspendFileOperationProgress Suspend(OperationProgress);
  1643. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  1644. }
  1645. if (Answer == qaAll)
  1646. {
  1647. DebugAssert(OperationProgress != NULL);
  1648. OperationProgress->SkipToAll = true;
  1649. Answer = qaSkip;
  1650. }
  1651. if (Answer == qaYes)
  1652. {
  1653. Result = true;
  1654. Answer = qaRetry;
  1655. }
  1656. }
  1657. if (Answer != qaRetry)
  1658. {
  1659. if ((Answer == qaAbort) && (OperationProgress != NULL))
  1660. {
  1661. OperationProgress->Cancel = csCancel;
  1662. }
  1663. if (AllowSkip)
  1664. {
  1665. THROW_SKIP_FILE(&E, Message);
  1666. }
  1667. else
  1668. {
  1669. // this can happen only during file transfer with SCP
  1670. throw ExtException(&E, Message);
  1671. }
  1672. }
  1673. return Result;
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  1677. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  1678. const UnicodeString Message, void * Param1, void * Param2)
  1679. {
  1680. DebugAssert(CallBackFunc);
  1681. int Result;
  1682. FILE_OPERATION_LOOP_BEGIN
  1683. {
  1684. Result = CallBackFunc(Param1, Param2);
  1685. }
  1686. FILE_OPERATION_LOOP_END_EX(Message, AllowSkip);
  1687. return Result;
  1688. }
  1689. //---------------------------------------------------------------------------
  1690. UnicodeString __fastcall TTerminal::TranslateLockedPath(UnicodeString Path, bool Lock)
  1691. {
  1692. if (SessionData->LockInHome && !Path.IsEmpty() && (Path[1] == L'/'))
  1693. {
  1694. if (Lock)
  1695. {
  1696. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  1697. {
  1698. Path.Delete(1, FLockDirectory.Length());
  1699. if (Path.IsEmpty()) Path = L"/";
  1700. }
  1701. }
  1702. else
  1703. {
  1704. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  1705. }
  1706. }
  1707. return Path;
  1708. }
  1709. //---------------------------------------------------------------------------
  1710. void __fastcall TTerminal::ClearCaches()
  1711. {
  1712. FDirectoryCache->Clear();
  1713. if (FDirectoryChangesCache != NULL)
  1714. {
  1715. FDirectoryChangesCache->Clear();
  1716. }
  1717. if (FCommandSession != NULL)
  1718. {
  1719. FCommandSession->ClearCaches();
  1720. }
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  1724. bool SubDirs)
  1725. {
  1726. FDirectoryCache->ClearFileList(Path, SubDirs);
  1727. }
  1728. //---------------------------------------------------------------------------
  1729. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  1730. {
  1731. FDirectoryCache->AddFileList(FileList);
  1732. }
  1733. //---------------------------------------------------------------------------
  1734. bool __fastcall TTerminal::DirectoryFileList(const UnicodeString Path,
  1735. TRemoteFileList *& FileList, bool CanLoad)
  1736. {
  1737. bool Result = false;
  1738. if (UnixSamePath(FFiles->Directory, Path))
  1739. {
  1740. Result = (FileList == NULL) || (FileList->Timestamp < FFiles->Timestamp);
  1741. if (Result)
  1742. {
  1743. if (FileList == NULL)
  1744. {
  1745. FileList = new TRemoteFileList();
  1746. }
  1747. FFiles->DuplicateTo(FileList);
  1748. }
  1749. }
  1750. else
  1751. {
  1752. if (((FileList == NULL) && FDirectoryCache->HasFileList(Path)) ||
  1753. ((FileList != NULL) && FDirectoryCache->HasNewerFileList(Path, FileList->Timestamp)))
  1754. {
  1755. bool Created = (FileList == NULL);
  1756. if (Created)
  1757. {
  1758. FileList = new TRemoteFileList();
  1759. }
  1760. Result = FDirectoryCache->GetFileList(Path, FileList);
  1761. if (!Result && Created)
  1762. {
  1763. SAFE_DESTROY(FileList);
  1764. }
  1765. }
  1766. // do not attempt to load file list if there is cached version,
  1767. // only absence of cached version indicates that we consider
  1768. // the directory content obsolete
  1769. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  1770. {
  1771. bool Created = (FileList == NULL);
  1772. if (Created)
  1773. {
  1774. FileList = new TRemoteFileList();
  1775. }
  1776. FileList->Directory = Path;
  1777. try
  1778. {
  1779. ReadDirectory(FileList);
  1780. Result = true;
  1781. }
  1782. catch(...)
  1783. {
  1784. if (Created)
  1785. {
  1786. SAFE_DESTROY(FileList);
  1787. }
  1788. throw;
  1789. }
  1790. }
  1791. }
  1792. return Result;
  1793. }
  1794. //---------------------------------------------------------------------------
  1795. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  1796. {
  1797. DebugAssert(FFileSystem);
  1798. value = TranslateLockedPath(value, false);
  1799. if (value != FFileSystem->CurrentDirectory)
  1800. {
  1801. ChangeDirectory(value);
  1802. }
  1803. }
  1804. //---------------------------------------------------------------------------
  1805. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  1806. {
  1807. if (FFileSystem != NULL)
  1808. {
  1809. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  1810. // to FCurrentDirectory, splitting the assignment to two statemets
  1811. // to locate the crash more closely
  1812. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  1813. FCurrentDirectory = CurrentDirectory;
  1814. if (FCurrentDirectory.IsEmpty())
  1815. {
  1816. ReadCurrentDirectory();
  1817. }
  1818. }
  1819. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1820. return Result;
  1821. }
  1822. //---------------------------------------------------------------------------
  1823. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  1824. {
  1825. if (FFileSystem)
  1826. {
  1827. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1828. }
  1829. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1830. return Result;
  1831. }
  1832. //---------------------------------------------------------------------------
  1833. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  1834. {
  1835. DebugAssert(FFileSystem);
  1836. LookupUsersGroups();
  1837. return &FGroups;
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  1841. {
  1842. DebugAssert(FFileSystem);
  1843. LookupUsersGroups();
  1844. return &FUsers;
  1845. }
  1846. //---------------------------------------------------------------------------
  1847. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  1848. {
  1849. DebugAssert(FFileSystem);
  1850. LookupUsersGroups();
  1851. return &FMembership;
  1852. }
  1853. //---------------------------------------------------------------------------
  1854. UnicodeString __fastcall TTerminal::GetUserName() const
  1855. {
  1856. // in future might also be implemented to detect username similar to GetUserGroups
  1857. DebugAssert(FFileSystem != NULL);
  1858. UnicodeString Result = FFileSystem->GetUserName();
  1859. // Is empty also when stored username was used
  1860. if (Result.IsEmpty())
  1861. {
  1862. Result = SessionData->UserNameExpanded;
  1863. }
  1864. return Result;
  1865. }
  1866. //---------------------------------------------------------------------------
  1867. bool __fastcall TTerminal::GetAreCachesEmpty() const
  1868. {
  1869. return FDirectoryCache->IsEmpty &&
  1870. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  1871. }
  1872. //---------------------------------------------------------------------------
  1873. void __fastcall TTerminal::DoInitializeLog()
  1874. {
  1875. if (FOnInitializeLog)
  1876. {
  1877. TCallbackGuard Guard(this);
  1878. FOnInitializeLog(this);
  1879. Guard.Verify();
  1880. }
  1881. }
  1882. //---------------------------------------------------------------------------
  1883. void __fastcall TTerminal::DoChangeDirectory()
  1884. {
  1885. if (FOnChangeDirectory)
  1886. {
  1887. TCallbackGuard Guard(this);
  1888. FOnChangeDirectory(this);
  1889. Guard.Verify();
  1890. }
  1891. }
  1892. //---------------------------------------------------------------------------
  1893. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  1894. {
  1895. if (FOnReadDirectory)
  1896. {
  1897. TCallbackGuard Guard(this);
  1898. FOnReadDirectory(this, ReloadOnly);
  1899. Guard.Verify();
  1900. }
  1901. }
  1902. //---------------------------------------------------------------------------
  1903. void __fastcall TTerminal::DoStartReadDirectory()
  1904. {
  1905. if (FOnStartReadDirectory)
  1906. {
  1907. TCallbackGuard Guard(this);
  1908. FOnStartReadDirectory(this);
  1909. Guard.Verify();
  1910. }
  1911. }
  1912. //---------------------------------------------------------------------------
  1913. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
  1914. {
  1915. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  1916. {
  1917. TCallbackGuard Guard(this);
  1918. FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
  1919. Guard.Verify();
  1920. }
  1921. if (FOnFindingFile != NULL)
  1922. {
  1923. TCallbackGuard Guard(this);
  1924. FOnFindingFile(this, L"", Cancel);
  1925. Guard.Verify();
  1926. }
  1927. }
  1928. //---------------------------------------------------------------------------
  1929. bool __fastcall TTerminal::InTransaction()
  1930. {
  1931. return (FInTransaction > 0) && !FSuspendTransaction;
  1932. }
  1933. //---------------------------------------------------------------------------
  1934. void __fastcall TTerminal::BeginTransaction()
  1935. {
  1936. if (FInTransaction == 0)
  1937. {
  1938. FReadCurrentDirectoryPending = false;
  1939. FReadDirectoryPending = false;
  1940. }
  1941. FInTransaction++;
  1942. if (FCommandSession != NULL)
  1943. {
  1944. FCommandSession->BeginTransaction();
  1945. }
  1946. }
  1947. //---------------------------------------------------------------------------
  1948. void __fastcall TTerminal::EndTransaction()
  1949. {
  1950. DoEndTransaction(false);
  1951. }
  1952. //---------------------------------------------------------------------------
  1953. void __fastcall TTerminal::DoEndTransaction(bool Inform)
  1954. {
  1955. if (FInTransaction == 0)
  1956. TerminalError(L"Can't end transaction, not in transaction");
  1957. DebugAssert(FInTransaction > 0);
  1958. FInTransaction--;
  1959. // it connection was closed due to fatal error during transaction, do nothing
  1960. if (Active)
  1961. {
  1962. if (FInTransaction == 0)
  1963. {
  1964. try
  1965. {
  1966. if (FReadCurrentDirectoryPending)
  1967. {
  1968. ReadCurrentDirectory();
  1969. }
  1970. if (FReadDirectoryPending)
  1971. {
  1972. if (Inform)
  1973. {
  1974. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
  1975. }
  1976. ReadDirectory(!FReadCurrentDirectoryPending);
  1977. }
  1978. }
  1979. __finally
  1980. {
  1981. FReadCurrentDirectoryPending = false;
  1982. FReadDirectoryPending = false;
  1983. }
  1984. }
  1985. }
  1986. if (FCommandSession != NULL)
  1987. {
  1988. FCommandSession->EndTransaction();
  1989. }
  1990. }
  1991. //---------------------------------------------------------------------------
  1992. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  1993. {
  1994. if (value)
  1995. {
  1996. FExceptionOnFail++;
  1997. }
  1998. else
  1999. {
  2000. if (FExceptionOnFail == 0)
  2001. throw Exception(L"ExceptionOnFail is already zero.");
  2002. FExceptionOnFail--;
  2003. }
  2004. if (FCommandSession != NULL)
  2005. {
  2006. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  2007. }
  2008. }
  2009. //---------------------------------------------------------------------------
  2010. bool __fastcall TTerminal::GetExceptionOnFail() const
  2011. {
  2012. return (bool)(FExceptionOnFail > 0);
  2013. }
  2014. //---------------------------------------------------------------------------
  2015. void __fastcall TTerminal::FatalAbort()
  2016. {
  2017. FatalError(NULL, "");
  2018. }
  2019. //---------------------------------------------------------------------------
  2020. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  2021. {
  2022. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  2023. if (Active || SecureShellActive)
  2024. {
  2025. // We log this instead of exception handler, because Close() would
  2026. // probably cause exception handler to loose pointer to TShellLog()
  2027. LogEvent(L"Attempt to close connection due to fatal exception:");
  2028. Log->Add(llException, Msg);
  2029. Log->AddException(E);
  2030. if (Active)
  2031. {
  2032. Close();
  2033. }
  2034. // this may happen if failure of authentication of SSH, owned by terminal yet
  2035. // (because the protocol was not decided yet), is detected by us (not by putty).
  2036. // e.g. not verified host key
  2037. if (SecureShellActive)
  2038. {
  2039. FSecureShell->Close();
  2040. }
  2041. }
  2042. if (FCallbackGuard != NULL)
  2043. {
  2044. FCallbackGuard->FatalError(E, Msg, HelpKeyword);
  2045. }
  2046. else
  2047. {
  2048. throw ESshFatal(E, Msg, HelpKeyword);
  2049. }
  2050. }
  2051. //---------------------------------------------------------------------------
  2052. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  2053. {
  2054. CommandError(E, Msg, 0);
  2055. }
  2056. //---------------------------------------------------------------------------
  2057. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  2058. unsigned int Answers, const UnicodeString HelpKeyword)
  2059. {
  2060. // may not be, particularly when TTerminal::Reopen is being called
  2061. // from within OnShowExtendedException handler
  2062. DebugAssert(FCallbackGuard == NULL);
  2063. unsigned int Result = 0;
  2064. if (E && E->InheritsFrom(__classid(EFatal)))
  2065. {
  2066. FatalError(E, Msg, HelpKeyword);
  2067. }
  2068. else if (E && E->InheritsFrom(__classid(EAbort)))
  2069. {
  2070. // resent EAbort exception
  2071. Abort();
  2072. }
  2073. else if (ExceptionOnFail)
  2074. {
  2075. throw ECommand(E, Msg, HelpKeyword);
  2076. }
  2077. else if (!Answers)
  2078. {
  2079. ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
  2080. try
  2081. {
  2082. HandleExtendedException(ECmd);
  2083. }
  2084. __finally
  2085. {
  2086. delete ECmd;
  2087. }
  2088. }
  2089. else
  2090. {
  2091. // small hack to enable "skip to all" for TRetryOperationLoop
  2092. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  2093. if (CanSkip && OperationProgress->SkipToAll)
  2094. {
  2095. Result = qaSkip;
  2096. }
  2097. else
  2098. {
  2099. TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
  2100. TQueryButtonAlias Aliases[1];
  2101. if (CanSkip)
  2102. {
  2103. Aliases[0].Button = qaAll;
  2104. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  2105. Params.Aliases = Aliases;
  2106. Params.AliasesCount = LENOF(Aliases);
  2107. Answers |= qaAll;
  2108. }
  2109. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  2110. if (Result == qaAll)
  2111. {
  2112. DebugAssert(OperationProgress != NULL);
  2113. OperationProgress->SkipToAll = true;
  2114. Result = qaSkip;
  2115. }
  2116. }
  2117. }
  2118. return Result;
  2119. }
  2120. //---------------------------------------------------------------------------
  2121. bool __fastcall TTerminal::HandleException(Exception * E)
  2122. {
  2123. if (ExceptionOnFail)
  2124. {
  2125. return false;
  2126. }
  2127. else
  2128. {
  2129. Log->AddException(E);
  2130. return true;
  2131. }
  2132. }
  2133. //---------------------------------------------------------------------------
  2134. void __fastcall TTerminal::CloseOnCompletion(TOnceDoneOperation Operation, const UnicodeString Message)
  2135. {
  2136. Configuration->Usage->Inc(L"ClosesOnCompletion");
  2137. LogEvent(L"Closing session after completed operation (as requested by user)");
  2138. Close();
  2139. throw ESshTerminate(NULL,
  2140. Message.IsEmpty() ? UnicodeString(LoadStr(CLOSED_ON_COMPLETION)) : Message,
  2141. Operation);
  2142. }
  2143. //---------------------------------------------------------------------------
  2144. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  2145. const UnicodeString & SourceFullFileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  2146. {
  2147. TBatchOverwrite Result;
  2148. if (Special &&
  2149. (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(SourceFullFileName)))
  2150. {
  2151. Result = boResume;
  2152. }
  2153. else if (FLAGSET(Params, cpAppend))
  2154. {
  2155. Result = boAppend;
  2156. }
  2157. else if (CopyParam->NewerOnly &&
  2158. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  2159. (OperationProgress->Side != osLocal)))
  2160. {
  2161. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  2162. Result = boOlder;
  2163. }
  2164. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  2165. {
  2166. // no way to change batch overwrite mode when overwrite confirmations are off
  2167. DebugAssert(OperationProgress->BatchOverwrite == boNo);
  2168. Result = boAll;
  2169. }
  2170. else
  2171. {
  2172. Result = OperationProgress->BatchOverwrite;
  2173. if (!Special &&
  2174. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  2175. {
  2176. Result = boNo;
  2177. }
  2178. }
  2179. return Result;
  2180. }
  2181. //---------------------------------------------------------------------------
  2182. bool __fastcall TTerminal::CheckRemoteFile(
  2183. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  2184. {
  2185. return (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
  2186. }
  2187. //---------------------------------------------------------------------------
  2188. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(
  2189. const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName,
  2190. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  2191. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  2192. UnicodeString Message)
  2193. {
  2194. unsigned int Result;
  2195. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  2196. bool CanAlternateResume =
  2197. (FileParams != NULL) &&
  2198. (FileParams->DestSize < FileParams->SourceSize) &&
  2199. !OperationProgress->AsciiTransfer;
  2200. TBatchOverwrite BatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  2201. bool Applicable = true;
  2202. switch (BatchOverwrite)
  2203. {
  2204. case boOlder:
  2205. Applicable = (FileParams != NULL);
  2206. break;
  2207. case boAlternateResume:
  2208. Applicable = CanAlternateResume;
  2209. break;
  2210. case boResume:
  2211. Applicable = CanAlternateResume;
  2212. break;
  2213. }
  2214. if (!Applicable)
  2215. {
  2216. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, false);
  2217. DebugAssert(BatchOverwrite != ABatchOverwrite);
  2218. BatchOverwrite = ABatchOverwrite;
  2219. }
  2220. if (BatchOverwrite == boNo)
  2221. {
  2222. if (Message.IsEmpty())
  2223. {
  2224. // Side refers to destination side here
  2225. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  2226. REMOTE_FILE_OVERWRITE2), (TargetFileName, TargetFileName));
  2227. }
  2228. if (FileParams != NULL)
  2229. {
  2230. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  2231. FormatSize(FileParams->SourceSize),
  2232. UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision),
  2233. FormatSize(FileParams->DestSize),
  2234. UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision)));
  2235. }
  2236. if (DebugAlwaysTrue(QueryParams->HelpKeyword.IsEmpty()))
  2237. {
  2238. QueryParams->HelpKeyword = HELP_OVERWRITE;
  2239. }
  2240. Result = QueryUser(Message, NULL, Answers, QueryParams);
  2241. switch (Result)
  2242. {
  2243. case qaNeverAskAgain:
  2244. Configuration->ConfirmOverwriting = false;
  2245. Result = qaYes;
  2246. break;
  2247. case qaYesToAll:
  2248. BatchOverwrite = boAll;
  2249. break;
  2250. case qaAll:
  2251. BatchOverwrite = boOlder;
  2252. break;
  2253. case qaNoToAll:
  2254. BatchOverwrite = boNone;
  2255. break;
  2256. }
  2257. // we user has not selected another batch overwrite mode,
  2258. // keep the current one. note that we may get here even
  2259. // when batch overwrite was selected already, but it could not be applied
  2260. // to current transfer (see condition above)
  2261. if (BatchOverwrite != boNo)
  2262. {
  2263. OperationProgress->BatchOverwrite = BatchOverwrite;
  2264. }
  2265. }
  2266. if (BatchOverwrite != boNo)
  2267. {
  2268. switch (BatchOverwrite)
  2269. {
  2270. case boAll:
  2271. Result = qaYes;
  2272. break;
  2273. case boNone:
  2274. Result = qaNo;
  2275. break;
  2276. case boOlder:
  2277. if (FileParams == NULL)
  2278. {
  2279. Result = qaNo;
  2280. }
  2281. else
  2282. {
  2283. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  2284. TDateTime ReducedSourceTimestamp =
  2285. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  2286. TDateTime ReducedDestTimestamp =
  2287. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  2288. Result =
  2289. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  2290. qaYes : qaNo;
  2291. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  2292. (StandardTimestamp(ReducedSourceTimestamp),
  2293. StandardTimestamp(ReducedDestTimestamp),
  2294. ((Result == qaYes) ? L"" : L" not"))));
  2295. }
  2296. break;
  2297. case boAlternateResume:
  2298. DebugAssert(CanAlternateResume);
  2299. Result = qaSkip; // ugh
  2300. break;
  2301. case boAppend:
  2302. Result = qaRetry;
  2303. break;
  2304. case boResume:
  2305. Result = qaRetry;
  2306. break;
  2307. }
  2308. }
  2309. return Result;
  2310. }
  2311. //---------------------------------------------------------------------------
  2312. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  2313. const UnicodeString FileName, bool ClearDirectoryChange)
  2314. {
  2315. UnicodeString ParentDirectory;
  2316. UnicodeString Directory;
  2317. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  2318. {
  2319. if ((File != NULL) && (File->Directory != NULL))
  2320. {
  2321. if (File->IsDirectory)
  2322. {
  2323. Directory = File->Directory->FullDirectory + File->FileName;
  2324. }
  2325. ParentDirectory = File->Directory->Directory;
  2326. }
  2327. else if (!FileName.IsEmpty())
  2328. {
  2329. ParentDirectory = UnixExtractFilePath(FileName);
  2330. if (ParentDirectory.IsEmpty())
  2331. {
  2332. ParentDirectory = CurrentDirectory;
  2333. }
  2334. // this case for scripting
  2335. if ((File != NULL) && File->IsDirectory)
  2336. {
  2337. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  2338. UnixExtractFileName(File->FileName);
  2339. }
  2340. }
  2341. }
  2342. if (SessionData->CacheDirectories)
  2343. {
  2344. if (!Directory.IsEmpty())
  2345. {
  2346. DirectoryModified(Directory, true);
  2347. }
  2348. if (!ParentDirectory.IsEmpty())
  2349. {
  2350. DirectoryModified(ParentDirectory, false);
  2351. }
  2352. }
  2353. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  2354. {
  2355. if (!Directory.IsEmpty())
  2356. {
  2357. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  2358. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  2359. }
  2360. }
  2361. }
  2362. //---------------------------------------------------------------------------
  2363. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  2364. {
  2365. if (Path.IsEmpty())
  2366. {
  2367. ClearCachedFileList(CurrentDirectory, SubDirs);
  2368. }
  2369. else
  2370. {
  2371. ClearCachedFileList(Path, SubDirs);
  2372. }
  2373. }
  2374. //---------------------------------------------------------------------------
  2375. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  2376. {
  2377. AddCachedFileList(FileList);
  2378. }
  2379. //---------------------------------------------------------------------------
  2380. void __fastcall TTerminal::ReloadDirectory()
  2381. {
  2382. if (SessionData->CacheDirectories)
  2383. {
  2384. DirectoryModified(CurrentDirectory, false);
  2385. }
  2386. if (SessionData->CacheDirectoryChanges)
  2387. {
  2388. DebugAssert(FDirectoryChangesCache != NULL);
  2389. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  2390. }
  2391. ReadCurrentDirectory();
  2392. FReadCurrentDirectoryPending = false;
  2393. ReadDirectory(true);
  2394. FReadDirectoryPending = false;
  2395. }
  2396. //---------------------------------------------------------------------------
  2397. void __fastcall TTerminal::RefreshDirectory()
  2398. {
  2399. if (!SessionData->CacheDirectories)
  2400. {
  2401. LogEvent(L"Not refreshing directory, caching is off.");
  2402. }
  2403. else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  2404. {
  2405. // Second parameter was added to allow (rather force) using the cache.
  2406. // Before, the directory was reloaded always, it seems useless,
  2407. // has it any reason?
  2408. ReadDirectory(true, true);
  2409. FReadDirectoryPending = false;
  2410. }
  2411. }
  2412. //---------------------------------------------------------------------------
  2413. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  2414. {
  2415. // if filename doesn't contain path, we check for existence of file
  2416. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  2417. UnixSamePath(CurrentDirectory, FFiles->Directory))
  2418. {
  2419. TRemoteFile *File = FFiles->FindFile(FileName);
  2420. if (File)
  2421. {
  2422. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  2423. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  2424. }
  2425. }
  2426. }
  2427. //---------------------------------------------------------------------------
  2428. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  2429. {
  2430. if (Log->Logging)
  2431. {
  2432. Log->Add(llMessage, Str);
  2433. }
  2434. }
  2435. //---------------------------------------------------------------------------
  2436. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  2437. TFileOperationProgressType * OperationProgress, Exception * E)
  2438. {
  2439. // EScpSkipFile without "cancel" is file skip,
  2440. // and we do not want to record skipped actions.
  2441. // But EScpSkipFile with "cancel" is abort and we want to record that.
  2442. // Note that TSCPFileSystem modifies the logic of RollbackAction little bit.
  2443. if ((dynamic_cast<EScpSkipFile *>(E) != NULL) &&
  2444. ((OperationProgress == NULL) ||
  2445. (OperationProgress->Cancel == csContinue)))
  2446. {
  2447. Action.Cancel();
  2448. }
  2449. else
  2450. {
  2451. Action.Rollback(E);
  2452. }
  2453. }
  2454. //---------------------------------------------------------------------------
  2455. void __fastcall TTerminal::DoStartup()
  2456. {
  2457. LogEvent(L"Doing startup conversation with host.");
  2458. BeginTransaction();
  2459. try
  2460. {
  2461. DoInformation(LoadStr(STATUS_STARTUP), true);
  2462. // Make sure that directory would be loaded at last
  2463. FReadCurrentDirectoryPending = true;
  2464. FReadDirectoryPending = AutoReadDirectory;
  2465. FFileSystem->DoStartup();
  2466. LookupUsersGroups();
  2467. if (!SessionData->RemoteDirectory.IsEmpty())
  2468. {
  2469. ChangeDirectory(SessionData->RemoteDirectory);
  2470. }
  2471. }
  2472. __finally
  2473. {
  2474. DoEndTransaction(true);
  2475. }
  2476. LogEvent(L"Startup conversation with host finished.");
  2477. }
  2478. //---------------------------------------------------------------------------
  2479. void __fastcall TTerminal::ReadCurrentDirectory()
  2480. {
  2481. DebugAssert(FFileSystem);
  2482. try
  2483. {
  2484. // reset flag is case we are called externally (like from console dialog)
  2485. FReadCurrentDirectoryPending = false;
  2486. LogEvent(L"Getting current directory name.");
  2487. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  2488. FFileSystem->ReadCurrentDirectory();
  2489. ReactOnCommand(fsCurrentDirectory);
  2490. if (SessionData->CacheDirectoryChanges)
  2491. {
  2492. DebugAssert(FDirectoryChangesCache != NULL);
  2493. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  2494. {
  2495. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  2496. FLastDirectoryChange, CurrentDirectory);
  2497. }
  2498. // not to broke the cache, if the next directory change would not
  2499. // be initialized by ChangeDirectory(), which sets it
  2500. // (HomeDirectory() particularly)
  2501. FLastDirectoryChange = L"";
  2502. }
  2503. if (OldDirectory.IsEmpty())
  2504. {
  2505. FLockDirectory = (SessionData->LockInHome ?
  2506. FFileSystem->CurrentDirectory : UnicodeString(L""));
  2507. }
  2508. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  2509. }
  2510. catch (Exception &E)
  2511. {
  2512. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  2513. }
  2514. }
  2515. //---------------------------------------------------------------------------
  2516. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  2517. {
  2518. bool LoadedFromCache = false;
  2519. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  2520. {
  2521. if (ReloadOnly && !ForceCache)
  2522. {
  2523. LogEvent(L"Cached directory not reloaded.");
  2524. }
  2525. else
  2526. {
  2527. DoStartReadDirectory();
  2528. try
  2529. {
  2530. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  2531. }
  2532. __finally
  2533. {
  2534. DoReadDirectory(ReloadOnly);
  2535. }
  2536. if (LoadedFromCache)
  2537. {
  2538. LogEvent(L"Directory content loaded from cache.");
  2539. }
  2540. else
  2541. {
  2542. LogEvent(L"Cached Directory content has been removed.");
  2543. }
  2544. }
  2545. }
  2546. if (!LoadedFromCache)
  2547. {
  2548. DoStartReadDirectory();
  2549. FReadingCurrentDirectory = true;
  2550. bool Cancel = false; // dummy
  2551. DoReadDirectoryProgress(0, 0, Cancel);
  2552. try
  2553. {
  2554. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  2555. try
  2556. {
  2557. Files->Directory = CurrentDirectory;
  2558. CustomReadDirectory(Files);
  2559. }
  2560. __finally
  2561. {
  2562. DoReadDirectoryProgress(-1, 0, Cancel);
  2563. FReadingCurrentDirectory = false;
  2564. TRemoteDirectory * OldFiles = FFiles;
  2565. FFiles = Files;
  2566. try
  2567. {
  2568. DoReadDirectory(ReloadOnly);
  2569. }
  2570. __finally
  2571. {
  2572. // delete only after loading new files to dir view,
  2573. // not to destroy the file objects that the view holds
  2574. // (can be issue in multi threaded environment, such as when the
  2575. // terminal is reconnecting in the terminal thread)
  2576. delete OldFiles;
  2577. }
  2578. if (Active)
  2579. {
  2580. if (SessionData->CacheDirectories)
  2581. {
  2582. DirectoryLoaded(FFiles);
  2583. }
  2584. }
  2585. }
  2586. }
  2587. catch (Exception &E)
  2588. {
  2589. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  2590. }
  2591. }
  2592. }
  2593. //---------------------------------------------------------------------------
  2594. UnicodeString __fastcall TTerminal::GetRemoteFileInfo(TRemoteFile * File)
  2595. {
  2596. return
  2597. FORMAT(L"%s;%s;%d;%s;%d;%s;%s;%s;%d",
  2598. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification), int(File->ModificationFmt),
  2599. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  2600. File->Attr));
  2601. }
  2602. //---------------------------------------------------------------------------
  2603. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  2604. {
  2605. // optimization
  2606. if (Log->Logging)
  2607. {
  2608. LogEvent(GetRemoteFileInfo(File));
  2609. }
  2610. }
  2611. //---------------------------------------------------------------------------
  2612. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2613. {
  2614. UnicodeString Result;
  2615. // optimization
  2616. if (Log->Logging)
  2617. {
  2618. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  2619. }
  2620. return Result;
  2621. }
  2622. //---------------------------------------------------------------------------
  2623. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2624. {
  2625. // optimization
  2626. if (Log->Logging)
  2627. {
  2628. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size))));
  2629. }
  2630. }
  2631. //---------------------------------------------------------------------------
  2632. void __fastcall TTerminal::LogFileDone(TFileOperationProgressType * OperationProgress)
  2633. {
  2634. // optimization
  2635. if (Log->Logging)
  2636. {
  2637. LogEvent(FORMAT("Transfer done: '%s' [%s]", (OperationProgress->FullFileName, IntToStr(OperationProgress->TransferedSize))));
  2638. }
  2639. }
  2640. //---------------------------------------------------------------------------
  2641. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  2642. {
  2643. DebugAssert(FileList);
  2644. DebugAssert(FFileSystem);
  2645. TRobustOperationLoop RobustLoop(this, OperationProgress);
  2646. do
  2647. {
  2648. try
  2649. {
  2650. FFileSystem->ReadDirectory(FileList);
  2651. }
  2652. catch (Exception & E)
  2653. {
  2654. // Do not retry for initial listing of directory,
  2655. // we instead retry whole connection attempt,
  2656. // what would be done anyway (but Open is not ready for recursion).
  2657. if ((FOpening > 0) ||
  2658. !RobustLoop.TryReopen(E))
  2659. {
  2660. throw;
  2661. }
  2662. }
  2663. }
  2664. while (RobustLoop.Retry());
  2665. if (Log->Logging)
  2666. {
  2667. for (int Index = 0; Index < FileList->Count; Index++)
  2668. {
  2669. LogRemoteFile(FileList->Files[Index]);
  2670. }
  2671. }
  2672. ReactOnCommand(fsListDirectory);
  2673. }
  2674. //---------------------------------------------------------------------------
  2675. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  2676. {
  2677. TRemoteFileList * FileList;
  2678. TRetryOperationLoop RetryLoop(this);
  2679. do
  2680. {
  2681. FileList = NULL;
  2682. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  2683. try
  2684. {
  2685. FileList = DoReadDirectoryListing(Directory, false);
  2686. if (FileList != NULL)
  2687. {
  2688. int Index = 0;
  2689. while (Index < FileList->Count)
  2690. {
  2691. TRemoteFile * File = FileList->Files[Index];
  2692. TFileMasks::TParams Params;
  2693. Params.Size = File->Size;
  2694. Params.Modification = File->Modification;
  2695. // Have to use UnicodeString(), instead of L"", as with that
  2696. // overload with (UnicodeString, bool, bool, TParams*) wins
  2697. if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  2698. {
  2699. FileList->Delete(Index);
  2700. }
  2701. else
  2702. {
  2703. Index++;
  2704. }
  2705. }
  2706. Action.FileList(FileList);
  2707. }
  2708. }
  2709. catch(Exception & E)
  2710. {
  2711. RetryLoop.Error(E, Action);
  2712. }
  2713. }
  2714. while (RetryLoop.Retry());
  2715. return FileList;
  2716. }
  2717. //---------------------------------------------------------------------------
  2718. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  2719. {
  2720. TRemoteFile * File;
  2721. TRetryOperationLoop RetryLoop(this);
  2722. do
  2723. {
  2724. File = NULL;
  2725. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  2726. try
  2727. {
  2728. // reset caches
  2729. AnnounceFileListOperation();
  2730. ReadFile(Path, File);
  2731. Action.File(File);
  2732. }
  2733. catch(Exception & E)
  2734. {
  2735. RetryLoop.Error(E, Action);
  2736. }
  2737. }
  2738. while (RetryLoop.Retry());
  2739. return File;
  2740. }
  2741. //---------------------------------------------------------------------------
  2742. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2743. {
  2744. TRemoteFileList * FileList = NULL;
  2745. TRetryOperationLoop RetryLoop(this);
  2746. do
  2747. {
  2748. try
  2749. {
  2750. FileList = DoReadDirectoryListing(Directory, UseCache);
  2751. }
  2752. catch(Exception & E)
  2753. {
  2754. RetryLoop.Error(E);
  2755. }
  2756. }
  2757. while (RetryLoop.Retry());
  2758. return FileList;
  2759. }
  2760. //---------------------------------------------------------------------------
  2761. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2762. {
  2763. TRemoteFileList * FileList = new TRemoteFileList();
  2764. try
  2765. {
  2766. bool Cache = UseCache && SessionData->CacheDirectories;
  2767. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  2768. if (LoadedFromCache)
  2769. {
  2770. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  2771. }
  2772. if (!LoadedFromCache)
  2773. {
  2774. FileList->Directory = Directory;
  2775. ExceptionOnFail = true;
  2776. try
  2777. {
  2778. ReadDirectory(FileList);
  2779. }
  2780. __finally
  2781. {
  2782. ExceptionOnFail = false;
  2783. }
  2784. if (Cache)
  2785. {
  2786. AddCachedFileList(FileList);
  2787. }
  2788. }
  2789. }
  2790. catch(...)
  2791. {
  2792. delete FileList;
  2793. throw;
  2794. }
  2795. return FileList;
  2796. }
  2797. //---------------------------------------------------------------------------
  2798. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  2799. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  2800. {
  2801. TRemoteFileList * FileList = NULL;
  2802. if (IgnoreErrors)
  2803. {
  2804. ExceptionOnFail = true;
  2805. try
  2806. {
  2807. try
  2808. {
  2809. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2810. }
  2811. catch(...)
  2812. {
  2813. if (!Active)
  2814. {
  2815. throw;
  2816. }
  2817. }
  2818. }
  2819. __finally
  2820. {
  2821. ExceptionOnFail = false;
  2822. }
  2823. }
  2824. else
  2825. {
  2826. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2827. }
  2828. // skip if directory listing fails and user selects "skip"
  2829. if (FileList)
  2830. {
  2831. try
  2832. {
  2833. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  2834. TRemoteFile * File;
  2835. for (int Index = 0; Index < FileList->Count; Index++)
  2836. {
  2837. File = FileList->Files[Index];
  2838. if (!File->IsParentDirectory && !File->IsThisDirectory)
  2839. {
  2840. CallBackFunc(Directory + File->FileName, File, Param);
  2841. // We should catch EScpSkipFile here as we do in ProcessFiles.
  2842. // Now we have to handle EScpSkipFile in every callback implementation.
  2843. }
  2844. }
  2845. }
  2846. __finally
  2847. {
  2848. delete FileList;
  2849. }
  2850. }
  2851. }
  2852. //---------------------------------------------------------------------------
  2853. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  2854. {
  2855. try
  2856. {
  2857. CustomReadDirectory(FileList);
  2858. }
  2859. catch (Exception &E)
  2860. {
  2861. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  2862. }
  2863. }
  2864. //---------------------------------------------------------------------------
  2865. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  2866. TRemoteFile *& File)
  2867. {
  2868. DebugAssert(FFileSystem);
  2869. try
  2870. {
  2871. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  2872. FFileSystem->ReadSymlink(SymlinkFile, File);
  2873. ReactOnCommand(fsReadSymlink);
  2874. }
  2875. catch (Exception &E)
  2876. {
  2877. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  2878. }
  2879. }
  2880. //---------------------------------------------------------------------------
  2881. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  2882. TRemoteFile *& File)
  2883. {
  2884. DebugAssert(FFileSystem);
  2885. File = NULL;
  2886. try
  2887. {
  2888. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  2889. FFileSystem->ReadFile(FileName, File);
  2890. ReactOnCommand(fsListFile);
  2891. LogRemoteFile(File);
  2892. }
  2893. catch (Exception &E)
  2894. {
  2895. if (File) delete File;
  2896. File = NULL;
  2897. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  2898. }
  2899. }
  2900. //---------------------------------------------------------------------------
  2901. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  2902. {
  2903. bool Result;
  2904. TRemoteFile * File = NULL;
  2905. try
  2906. {
  2907. ExceptionOnFail = true;
  2908. try
  2909. {
  2910. ReadFile(UnixExcludeTrailingBackslash(FileName), File);
  2911. }
  2912. __finally
  2913. {
  2914. ExceptionOnFail = false;
  2915. }
  2916. if (AFile != NULL)
  2917. {
  2918. *AFile = File;
  2919. }
  2920. else
  2921. {
  2922. delete File;
  2923. }
  2924. Result = true;
  2925. }
  2926. catch(...)
  2927. {
  2928. if (Active)
  2929. {
  2930. Result = false;
  2931. }
  2932. else
  2933. {
  2934. throw;
  2935. }
  2936. }
  2937. return Result;
  2938. }
  2939. //---------------------------------------------------------------------------
  2940. void __fastcall TTerminal::AnnounceFileListOperation()
  2941. {
  2942. FFileSystem->AnnounceFileListOperation();
  2943. }
  2944. //---------------------------------------------------------------------------
  2945. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  2946. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  2947. TOperationSide Side, bool Ex)
  2948. {
  2949. DebugAssert(FFileSystem);
  2950. DebugAssert(FileList);
  2951. bool Result = false;
  2952. TOnceDoneOperation OnceDoneOperation = odoIdle;
  2953. try
  2954. {
  2955. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  2956. Progress.Start(Operation, Side, FileList->Count);
  2957. FOperationProgress = &Progress;
  2958. try
  2959. {
  2960. if (Side == osRemote)
  2961. {
  2962. BeginTransaction();
  2963. }
  2964. try
  2965. {
  2966. int Index = 0;
  2967. UnicodeString FileName;
  2968. bool Success;
  2969. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  2970. {
  2971. FileName = FileList->Strings[Index];
  2972. try
  2973. {
  2974. try
  2975. {
  2976. Success = false;
  2977. if (!Ex)
  2978. {
  2979. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  2980. }
  2981. else
  2982. {
  2983. // not used anymore
  2984. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  2985. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  2986. }
  2987. Success = true;
  2988. }
  2989. __finally
  2990. {
  2991. Progress.Finish(FileName, Success, OnceDoneOperation);
  2992. }
  2993. }
  2994. catch(EScpSkipFile & E)
  2995. {
  2996. TSuspendFileOperationProgress Suspend(OperationProgress);
  2997. if (!HandleException(&E))
  2998. {
  2999. throw;
  3000. }
  3001. }
  3002. Index++;
  3003. }
  3004. }
  3005. __finally
  3006. {
  3007. if (Side == osRemote)
  3008. {
  3009. EndTransaction();
  3010. }
  3011. }
  3012. if (Progress.Cancel == csContinue)
  3013. {
  3014. Result = true;
  3015. }
  3016. }
  3017. __finally
  3018. {
  3019. FOperationProgress = NULL;
  3020. Progress.Stop();
  3021. }
  3022. }
  3023. catch (...)
  3024. {
  3025. OnceDoneOperation = odoIdle;
  3026. // this was missing here. was it by purpose?
  3027. // without it any error message is lost
  3028. throw;
  3029. }
  3030. if (OnceDoneOperation != odoIdle)
  3031. {
  3032. CloseOnCompletion(OnceDoneOperation);
  3033. }
  3034. return Result;
  3035. }
  3036. //---------------------------------------------------------------------------
  3037. // not used anymore
  3038. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  3039. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  3040. {
  3041. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  3042. Param, Side, true);
  3043. }
  3044. //---------------------------------------------------------------------------
  3045. TStrings * __fastcall TTerminal::GetFixedPaths()
  3046. {
  3047. DebugAssert(FFileSystem != NULL);
  3048. return FFileSystem->GetFixedPaths();
  3049. }
  3050. //---------------------------------------------------------------------------
  3051. bool __fastcall TTerminal::GetResolvingSymlinks()
  3052. {
  3053. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  3054. }
  3055. //---------------------------------------------------------------------------
  3056. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  3057. {
  3058. TUsableCopyParamAttrs Result;
  3059. Result.General =
  3060. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  3061. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  3062. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  3063. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  3064. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  3065. // the following three are never supported for download,
  3066. // so when they are not suppored for upload too,
  3067. // set them in General flags, so that they do not get enabled on
  3068. // Synchronize dialog.
  3069. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  3070. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  3071. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM) |
  3072. FLAGMASK(!IsCapable[fcPreservingTimestampDirs], cpaNoPreserveTimeDirs) |
  3073. FLAGMASK(!IsCapable[fcResumeSupport], cpaNoResumeSupport);
  3074. Result.Download = Result.General | cpaNoClearArchive |
  3075. cpaNoIgnorePermErrors |
  3076. // May be already set in General flags, but it's unconditional here
  3077. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM;
  3078. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  3079. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  3080. return Result;
  3081. }
  3082. //---------------------------------------------------------------------------
  3083. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  3084. {
  3085. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  3086. if (Result)
  3087. {
  3088. UnicodeString Path = UnixExtractFilePath(FileName);
  3089. if (Path.IsEmpty())
  3090. {
  3091. Path = CurrentDirectory;
  3092. }
  3093. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  3094. }
  3095. return Result;
  3096. }
  3097. //---------------------------------------------------------------------------
  3098. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  3099. const TRemoteFile * File)
  3100. {
  3101. if (FileName.IsEmpty())
  3102. {
  3103. DebugAssert(File != NULL);
  3104. FileName = File->FileName;
  3105. }
  3106. if (!IsRecycledFile(FileName))
  3107. {
  3108. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  3109. (FileName, SessionData->RecycleBinPath)));
  3110. TMoveFileParams Params;
  3111. Params.Target = SessionData->RecycleBinPath;
  3112. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  3113. MoveFile(FileName, File, &Params);
  3114. }
  3115. }
  3116. //---------------------------------------------------------------------------
  3117. bool __fastcall TTerminal::TryStartOperationWithFile(
  3118. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3119. {
  3120. bool Result = true;
  3121. if ((OperationProgress != NULL) &&
  3122. ((OperationProgress->Operation == Operation1) ||
  3123. ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
  3124. {
  3125. if (OperationProgress->Cancel != csContinue)
  3126. {
  3127. Result = false;
  3128. }
  3129. else
  3130. {
  3131. OperationProgress->SetFile(FileName);
  3132. }
  3133. }
  3134. return Result;
  3135. }
  3136. //---------------------------------------------------------------------------
  3137. void __fastcall TTerminal::StartOperationWithFile(
  3138. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3139. {
  3140. if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
  3141. {
  3142. Abort();
  3143. }
  3144. }
  3145. //---------------------------------------------------------------------------
  3146. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  3147. const TRemoteFile * File, void * AParams)
  3148. {
  3149. if (FileName.IsEmpty() && File)
  3150. {
  3151. FileName = File->FileName;
  3152. }
  3153. StartOperationWithFile(FileName, foDelete);
  3154. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  3155. bool Recycle =
  3156. FLAGCLEAR(Params, dfForceDelete) &&
  3157. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  3158. !SessionData->RecycleBinPath.IsEmpty();
  3159. if (Recycle && !IsRecycledFile(FileName))
  3160. {
  3161. RecycleFile(FileName, File);
  3162. }
  3163. else
  3164. {
  3165. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  3166. FileModified(File, FileName, true);
  3167. DoDeleteFile(FileName, File, Params);
  3168. ReactOnCommand(fsDeleteFile);
  3169. }
  3170. }
  3171. //---------------------------------------------------------------------------
  3172. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  3173. const TRemoteFile * File, int Params)
  3174. {
  3175. TRetryOperationLoop RetryLoop(this);
  3176. do
  3177. {
  3178. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3179. try
  3180. {
  3181. DebugAssert(FFileSystem);
  3182. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  3183. FFileSystem->DeleteFile(FileName, File, Params, Action);
  3184. }
  3185. catch(Exception & E)
  3186. {
  3187. RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  3188. }
  3189. }
  3190. while (RetryLoop.Retry());
  3191. }
  3192. //---------------------------------------------------------------------------
  3193. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  3194. {
  3195. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3196. FUseBusyCursor = false;
  3197. // TODO: avoid resolving symlinks while reading subdirectories.
  3198. // Resolving does not work anyway for relative symlinks in subdirectories
  3199. // (at least for SFTP).
  3200. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  3201. }
  3202. //---------------------------------------------------------------------------
  3203. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  3204. const TRemoteFile * /*File*/, void * Params)
  3205. {
  3206. StartOperationWithFile(FileName, foDelete);
  3207. if (OnDeleteLocalFile == NULL)
  3208. {
  3209. RecursiveDeleteFileChecked(FileName, false);
  3210. }
  3211. else
  3212. {
  3213. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  3214. }
  3215. }
  3216. //---------------------------------------------------------------------------
  3217. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  3218. {
  3219. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  3220. }
  3221. //---------------------------------------------------------------------------
  3222. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  3223. const TRemoteFile * File, void * AParams)
  3224. {
  3225. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3226. if (FileName.IsEmpty() && File)
  3227. {
  3228. FileName = File->FileName;
  3229. }
  3230. StartOperationWithFile(FileName, foCustomCommand);
  3231. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3232. (Params->Command, Params->Params, FileName)));
  3233. FileModified(File, FileName);
  3234. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3235. Params->OutputEvent);
  3236. ReactOnCommand(fsAnyCommand);
  3237. }
  3238. //---------------------------------------------------------------------------
  3239. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  3240. const TRemoteFile * File, UnicodeString Command, int Params,
  3241. TCaptureOutputEvent OutputEvent)
  3242. {
  3243. TRetryOperationLoop RetryLoop(this);
  3244. do
  3245. {
  3246. try
  3247. {
  3248. if (IsCapable[fcAnyCommand])
  3249. {
  3250. DebugAssert(FFileSystem);
  3251. DebugAssert(fcShellAnyCommand);
  3252. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  3253. }
  3254. else
  3255. {
  3256. DebugAssert(CommandSessionOpened);
  3257. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3258. LogEvent(L"Executing custom command on command session.");
  3259. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  3260. {
  3261. FCommandSession->CurrentDirectory = CurrentDirectory;
  3262. // We are likely in transaction, so ReadCurrentDirectory won't get called
  3263. // until transaction ends. But we need to know CurrentDirectory to
  3264. // expand !/ pattern.
  3265. // Doing this only, when current directory of the main and secondary shell differs,
  3266. // what would be the case before the first file in transaction.
  3267. // Otherwise we would be reading pwd before every time as the
  3268. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  3269. if (FCommandSession->FReadCurrentDirectoryPending)
  3270. {
  3271. FCommandSession->ReadCurrentDirectory();
  3272. }
  3273. }
  3274. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  3275. Params, OutputEvent);
  3276. }
  3277. }
  3278. catch(Exception & E)
  3279. {
  3280. RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
  3281. }
  3282. }
  3283. while (RetryLoop.Retry());
  3284. }
  3285. //---------------------------------------------------------------------------
  3286. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  3287. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  3288. {
  3289. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  3290. {
  3291. TCustomCommandParams AParams;
  3292. AParams.Command = Command;
  3293. AParams.Params = Params;
  3294. AParams.OutputEvent = OutputEvent;
  3295. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  3296. }
  3297. else
  3298. {
  3299. UnicodeString FileList;
  3300. for (int i = 0; i < Files->Count; i++)
  3301. {
  3302. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  3303. bool Dir = File->IsDirectory && CanRecurseToDirectory(File);
  3304. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  3305. {
  3306. if (!FileList.IsEmpty())
  3307. {
  3308. FileList += L" ";
  3309. }
  3310. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  3311. }
  3312. }
  3313. TCustomCommandData Data(this);
  3314. UnicodeString Cmd =
  3315. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  3316. Complete(Command, true);
  3317. DoAnyCommand(Cmd, OutputEvent, NULL);
  3318. }
  3319. }
  3320. //---------------------------------------------------------------------------
  3321. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  3322. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  3323. {
  3324. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  3325. DebugAssert(RProperties && !RProperties->Valid.Empty());
  3326. if (FileName.IsEmpty() && File)
  3327. {
  3328. FileName = File->FileName;
  3329. }
  3330. StartOperationWithFile(FileName, foSetProperties);
  3331. if (Log->Logging)
  3332. {
  3333. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  3334. (FileName, BooleanToEngStr(RProperties->Recursive))));
  3335. if (RProperties->Valid.Contains(vpRights))
  3336. {
  3337. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  3338. }
  3339. if (RProperties->Valid.Contains(vpGroup))
  3340. {
  3341. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  3342. }
  3343. if (RProperties->Valid.Contains(vpOwner))
  3344. {
  3345. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  3346. }
  3347. if (RProperties->Valid.Contains(vpModification))
  3348. {
  3349. LogEvent(FORMAT(L" - modification: \"%s\"",
  3350. (FormatDateTime(L"dddddd tt",
  3351. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  3352. }
  3353. if (RProperties->Valid.Contains(vpLastAccess))
  3354. {
  3355. LogEvent(FORMAT(L" - last access: \"%s\"",
  3356. (FormatDateTime(L"dddddd tt",
  3357. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  3358. }
  3359. }
  3360. FileModified(File, FileName);
  3361. DoChangeFileProperties(FileName, File, RProperties);
  3362. ReactOnCommand(fsChangeProperties);
  3363. }
  3364. //---------------------------------------------------------------------------
  3365. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  3366. const TRemoteFile * File, const TRemoteProperties * Properties)
  3367. {
  3368. TRetryOperationLoop RetryLoop(this);
  3369. do
  3370. {
  3371. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3372. try
  3373. {
  3374. DebugAssert(FFileSystem);
  3375. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  3376. }
  3377. catch(Exception & E)
  3378. {
  3379. RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
  3380. }
  3381. }
  3382. while (RetryLoop.Retry());
  3383. }
  3384. //---------------------------------------------------------------------------
  3385. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  3386. const TRemoteProperties * Properties)
  3387. {
  3388. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3389. FUseBusyCursor = false;
  3390. AnnounceFileListOperation();
  3391. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  3392. }
  3393. //---------------------------------------------------------------------------
  3394. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  3395. {
  3396. // see comment in TSFTPFileSystem::IsCapable
  3397. bool Result =
  3398. IsCapable[fcLoadingAdditionalProperties] &&
  3399. FFileSystem->LoadFilesProperties(FileList);
  3400. if (Result && SessionData->CacheDirectories &&
  3401. (FileList->Count > 0) &&
  3402. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  3403. {
  3404. AddCachedFileList(FFiles);
  3405. }
  3406. return Result;
  3407. }
  3408. //---------------------------------------------------------------------------
  3409. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  3410. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  3411. {
  3412. DebugAssert(Param);
  3413. DebugAssert(File);
  3414. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  3415. if (FileName.IsEmpty())
  3416. {
  3417. FileName = File->FileName;
  3418. }
  3419. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  3420. {
  3421. AParams->Result = false;
  3422. Abort();
  3423. }
  3424. bool AllowTransfer = (AParams->CopyParam == NULL);
  3425. if (!AllowTransfer)
  3426. {
  3427. TFileMasks::TParams MaskParams;
  3428. MaskParams.Size = File->Size;
  3429. MaskParams.Modification = File->Modification;
  3430. UnicodeString BaseFileName =
  3431. GetBaseFileName(UnixExcludeTrailingBackslash(File->FullFileName));
  3432. AllowTransfer = AParams->CopyParam->AllowTransfer(
  3433. BaseFileName, osRemote, File->IsDirectory, MaskParams);
  3434. }
  3435. if (AllowTransfer)
  3436. {
  3437. if (File->IsDirectory)
  3438. {
  3439. if (CanRecurseToDirectory(File))
  3440. {
  3441. if (!AParams->AllowDirs)
  3442. {
  3443. AParams->Result = false;
  3444. }
  3445. else
  3446. {
  3447. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  3448. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  3449. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  3450. }
  3451. }
  3452. if (AParams->Stats != NULL)
  3453. {
  3454. AParams->Stats->Directories++;
  3455. }
  3456. }
  3457. else
  3458. {
  3459. AParams->Size += File->Size;
  3460. if (AParams->Stats != NULL)
  3461. {
  3462. AParams->Stats->Files++;
  3463. }
  3464. }
  3465. if ((AParams->Stats != NULL) && File->IsSymLink)
  3466. {
  3467. AParams->Stats->SymLinks++;
  3468. }
  3469. }
  3470. }
  3471. //---------------------------------------------------------------------------
  3472. void __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  3473. const TRemoteFile * /*File*/, TCalculateSizeParams * Params)
  3474. {
  3475. TRetryOperationLoop RetryLoop(this);
  3476. do
  3477. {
  3478. try
  3479. {
  3480. ProcessDirectory(FileName, CalculateFileSize, Params);
  3481. }
  3482. catch(Exception & E)
  3483. {
  3484. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  3485. {
  3486. RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
  3487. }
  3488. }
  3489. }
  3490. while (RetryLoop.Retry());
  3491. }
  3492. //---------------------------------------------------------------------------
  3493. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  3494. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  3495. bool AllowDirs, TCalculateSizeStats * Stats)
  3496. {
  3497. // With FTP protocol, we may use DSIZ command from
  3498. // draft-peterson-streamlined-ftp-command-extensions-10
  3499. // Implemented by Serv-U FTP.
  3500. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3501. FUseBusyCursor = false;
  3502. TCalculateSizeParams Param;
  3503. Param.Size = 0;
  3504. Param.Params = Params;
  3505. Param.CopyParam = CopyParam;
  3506. Param.Stats = Stats;
  3507. Param.AllowDirs = AllowDirs;
  3508. Param.Result = true;
  3509. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  3510. Size = Param.Size;
  3511. return Param.Result;
  3512. }
  3513. //---------------------------------------------------------------------------
  3514. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  3515. TStrings * FileList, TStrings * Checksums,
  3516. TCalculatedChecksumEvent OnCalculatedChecksum)
  3517. {
  3518. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  3519. }
  3520. //---------------------------------------------------------------------------
  3521. void __fastcall TTerminal::RenameFile(const UnicodeString FileName,
  3522. const UnicodeString NewName)
  3523. {
  3524. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  3525. DoRenameFile(FileName, NewName, false);
  3526. ReactOnCommand(fsRenameFile);
  3527. }
  3528. //---------------------------------------------------------------------------
  3529. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  3530. const UnicodeString NewName, bool CheckExistence)
  3531. {
  3532. DebugAssert(File && File->Directory == FFiles);
  3533. bool Proceed = true;
  3534. // if filename doesn't contain path, we check for existence of file
  3535. if ((File->FileName != NewName) && CheckExistence &&
  3536. Configuration->ConfirmOverwriting &&
  3537. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3538. {
  3539. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  3540. if (DuplicateFile)
  3541. {
  3542. UnicodeString QuestionFmt;
  3543. if (DuplicateFile->IsDirectory)
  3544. {
  3545. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  3546. }
  3547. else
  3548. {
  3549. QuestionFmt = LoadStr(FILE_OVERWRITE);
  3550. }
  3551. TQueryParams Params(qpNeverAskAgainCheck);
  3552. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  3553. unsigned int Result = QueryUser(Question, NULL,
  3554. qaYes | qaNo, &Params);
  3555. if (Result == qaNeverAskAgain)
  3556. {
  3557. Proceed = true;
  3558. Configuration->ConfirmOverwriting = false;
  3559. }
  3560. else
  3561. {
  3562. Proceed = (Result == qaYes);
  3563. }
  3564. }
  3565. }
  3566. if (Proceed)
  3567. {
  3568. FileModified(File, File->FileName);
  3569. RenameFile(File->FileName, NewName);
  3570. }
  3571. }
  3572. //---------------------------------------------------------------------------
  3573. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName,
  3574. const UnicodeString NewName, bool Move)
  3575. {
  3576. TRetryOperationLoop RetryLoop(this);
  3577. do
  3578. {
  3579. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  3580. try
  3581. {
  3582. DebugAssert(FFileSystem);
  3583. FFileSystem->RenameFile(FileName, NewName);
  3584. }
  3585. catch(Exception & E)
  3586. {
  3587. UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
  3588. RetryLoop.Error(E, Action, Message);
  3589. }
  3590. }
  3591. while (RetryLoop.Retry());
  3592. }
  3593. //---------------------------------------------------------------------------
  3594. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  3595. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  3596. {
  3597. StartOperationWithFile(FileName, foRemoteMove, foDelete);
  3598. DebugAssert(Param != NULL);
  3599. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3600. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3601. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3602. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  3603. FileModified(File, FileName);
  3604. DoRenameFile(FileName, NewName, true);
  3605. ReactOnCommand(fsMoveFile);
  3606. }
  3607. //---------------------------------------------------------------------------
  3608. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  3609. const UnicodeString FileMask)
  3610. {
  3611. TMoveFileParams Params;
  3612. Params.Target = Target;
  3613. Params.FileMask = FileMask;
  3614. DirectoryModified(Target, true);
  3615. bool Result;
  3616. BeginTransaction();
  3617. try
  3618. {
  3619. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  3620. }
  3621. __finally
  3622. {
  3623. if (Active)
  3624. {
  3625. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  3626. bool PossiblyMoved = false;
  3627. // check if we was moving current directory.
  3628. // this is just optimization to avoid checking existence of current
  3629. // directory after each move operation.
  3630. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  3631. {
  3632. const TRemoteFile * File =
  3633. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  3634. // File can be NULL, and filename may not be full path,
  3635. // but currently this is the only way we can move (at least in GUI)
  3636. // current directory
  3637. if ((File != NULL) &&
  3638. File->IsDirectory &&
  3639. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  3640. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  3641. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  3642. {
  3643. PossiblyMoved = true;
  3644. }
  3645. }
  3646. if (PossiblyMoved && !FileExists(CurrentDirectory))
  3647. {
  3648. UnicodeString NearestExisting = CurrentDirectory;
  3649. do
  3650. {
  3651. NearestExisting = UnixExtractFileDir(NearestExisting);
  3652. }
  3653. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  3654. ChangeDirectory(NearestExisting);
  3655. }
  3656. }
  3657. EndTransaction();
  3658. }
  3659. return Result;
  3660. }
  3661. //---------------------------------------------------------------------------
  3662. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName,
  3663. const UnicodeString NewName)
  3664. {
  3665. TRetryOperationLoop RetryLoop(this);
  3666. do
  3667. {
  3668. try
  3669. {
  3670. DebugAssert(FFileSystem);
  3671. if (IsCapable[fcRemoteCopy])
  3672. {
  3673. FFileSystem->CopyFile(FileName, NewName);
  3674. }
  3675. else
  3676. {
  3677. DebugAssert(CommandSessionOpened);
  3678. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3679. LogEvent(L"Copying file on command session.");
  3680. FCommandSession->CurrentDirectory = CurrentDirectory;
  3681. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  3682. }
  3683. }
  3684. catch(Exception & E)
  3685. {
  3686. RetryLoop.Error(E, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
  3687. }
  3688. }
  3689. while (RetryLoop.Retry());
  3690. }
  3691. //---------------------------------------------------------------------------
  3692. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  3693. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  3694. {
  3695. StartOperationWithFile(FileName, foRemoteCopy);
  3696. DebugAssert(Param != NULL);
  3697. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3698. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3699. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3700. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  3701. DoCopyFile(FileName, NewName);
  3702. ReactOnCommand(fsCopyFile);
  3703. }
  3704. //---------------------------------------------------------------------------
  3705. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  3706. const UnicodeString FileMask)
  3707. {
  3708. TMoveFileParams Params;
  3709. Params.Target = Target;
  3710. Params.FileMask = FileMask;
  3711. DirectoryModified(Target, true);
  3712. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  3713. }
  3714. //---------------------------------------------------------------------------
  3715. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  3716. const TRemoteProperties * Properties)
  3717. {
  3718. DebugAssert(FFileSystem);
  3719. EnsureNonExistence(DirName);
  3720. FileModified(NULL, DirName);
  3721. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  3722. DoCreateDirectory(DirName);
  3723. if ((Properties != NULL) && !Properties->Valid.Empty())
  3724. {
  3725. DoChangeFileProperties(DirName, NULL, Properties);
  3726. }
  3727. ReactOnCommand(fsCreateDirectory);
  3728. }
  3729. //---------------------------------------------------------------------------
  3730. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  3731. {
  3732. TRetryOperationLoop RetryLoop(this);
  3733. do
  3734. {
  3735. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  3736. try
  3737. {
  3738. DebugAssert(FFileSystem);
  3739. FFileSystem->CreateDirectory(DirName);
  3740. }
  3741. catch(Exception & E)
  3742. {
  3743. RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
  3744. }
  3745. }
  3746. while (RetryLoop.Retry());
  3747. }
  3748. //---------------------------------------------------------------------------
  3749. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  3750. const UnicodeString PointTo, bool Symbolic)
  3751. {
  3752. DebugAssert(FFileSystem);
  3753. EnsureNonExistence(FileName);
  3754. if (SessionData->CacheDirectories)
  3755. {
  3756. DirectoryModified(CurrentDirectory, false);
  3757. }
  3758. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  3759. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  3760. DoCreateLink(FileName, PointTo, Symbolic);
  3761. ReactOnCommand(fsCreateDirectory);
  3762. }
  3763. //---------------------------------------------------------------------------
  3764. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  3765. const UnicodeString PointTo, bool Symbolic)
  3766. {
  3767. TRetryOperationLoop RetryLoop(this);
  3768. do
  3769. {
  3770. try
  3771. {
  3772. DebugAssert(FFileSystem);
  3773. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  3774. }
  3775. catch(Exception & E)
  3776. {
  3777. RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
  3778. }
  3779. }
  3780. while (RetryLoop.Retry());
  3781. }
  3782. //---------------------------------------------------------------------------
  3783. void __fastcall TTerminal::HomeDirectory()
  3784. {
  3785. DebugAssert(FFileSystem);
  3786. try
  3787. {
  3788. LogEvent(L"Changing directory to home directory.");
  3789. FFileSystem->HomeDirectory();
  3790. ReactOnCommand(fsHomeDirectory);
  3791. }
  3792. catch (Exception &E)
  3793. {
  3794. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  3795. }
  3796. }
  3797. //---------------------------------------------------------------------------
  3798. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  3799. {
  3800. DebugAssert(FFileSystem);
  3801. try
  3802. {
  3803. UnicodeString CachedDirectory;
  3804. DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  3805. // never use directory change cache during startup, this ensures, we never
  3806. // end-up initially in non-existing directory
  3807. if ((Status == ssOpened) &&
  3808. SessionData->CacheDirectoryChanges &&
  3809. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  3810. Directory, CachedDirectory))
  3811. {
  3812. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  3813. (Directory, CachedDirectory)));
  3814. FFileSystem->CachedChangeDirectory(CachedDirectory);
  3815. }
  3816. else
  3817. {
  3818. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  3819. FFileSystem->ChangeDirectory(Directory);
  3820. }
  3821. FLastDirectoryChange = Directory;
  3822. ReactOnCommand(fsChangeDirectory);
  3823. }
  3824. catch (Exception &E)
  3825. {
  3826. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  3827. }
  3828. }
  3829. //---------------------------------------------------------------------------
  3830. void __fastcall TTerminal::LookupUsersGroups()
  3831. {
  3832. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  3833. IsCapable[fcUserGroupListing])
  3834. {
  3835. DebugAssert(FFileSystem);
  3836. try
  3837. {
  3838. FUsersGroupsLookedup = true;
  3839. LogEvent(L"Looking up groups and users.");
  3840. FFileSystem->LookupUsersGroups();
  3841. ReactOnCommand(fsLookupUsersGroups);
  3842. if (Log->Logging)
  3843. {
  3844. FGroups.Log(this, L"groups");
  3845. FMembership.Log(this, L"membership");
  3846. FUsers.Log(this, L"users");
  3847. }
  3848. }
  3849. catch (Exception &E)
  3850. {
  3851. if (!Active || (SessionData->LookupUserGroups == asOn))
  3852. {
  3853. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  3854. }
  3855. }
  3856. }
  3857. }
  3858. //---------------------------------------------------------------------------
  3859. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  3860. {
  3861. return !Command.Trim().IsEmpty();
  3862. }
  3863. //---------------------------------------------------------------------------
  3864. bool __fastcall TTerminal::GetCommandSessionOpened()
  3865. {
  3866. // consider secondary terminal open in "ready" state only
  3867. // so we never do keepalives on it until it is completely initialized
  3868. return (FCommandSession != NULL) &&
  3869. (FCommandSession->Status == ssOpened);
  3870. }
  3871. //---------------------------------------------------------------------------
  3872. TTerminal * __fastcall TTerminal::GetCommandSession()
  3873. {
  3874. if ((FCommandSession != NULL) && !FCommandSession->Active)
  3875. {
  3876. SAFE_DESTROY(FCommandSession);
  3877. }
  3878. if (FCommandSession == NULL)
  3879. {
  3880. // transaction cannot be started yet to allow proper matching transaction
  3881. // levels between main and command session
  3882. DebugAssert(FInTransaction == 0);
  3883. try
  3884. {
  3885. FCommandSession = new TSecondaryTerminal(this, SessionData,
  3886. Configuration, L"Shell");
  3887. FCommandSession->AutoReadDirectory = false;
  3888. TSessionData * CommandSessionData = FCommandSession->FSessionData;
  3889. CommandSessionData->RemoteDirectory = CurrentDirectory;
  3890. CommandSessionData->FSProtocol = fsSCPonly;
  3891. CommandSessionData->ClearAliases = false;
  3892. CommandSessionData->UnsetNationalVars = false;
  3893. CommandSessionData->LookupUserGroups = asOff;
  3894. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  3895. FCommandSession->OnQueryUser = OnQueryUser;
  3896. FCommandSession->OnPromptUser = OnPromptUser;
  3897. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  3898. FCommandSession->OnProgress = OnProgress;
  3899. FCommandSession->OnFinished = OnFinished;
  3900. FCommandSession->OnInformation = OnInformation;
  3901. FCommandSession->OnClose = CommandSessionClose;
  3902. // do not copy OnDisplayBanner to avoid it being displayed
  3903. }
  3904. catch(...)
  3905. {
  3906. SAFE_DESTROY(FCommandSession);
  3907. throw;
  3908. }
  3909. }
  3910. return FCommandSession;
  3911. }
  3912. //---------------------------------------------------------------------------
  3913. void __fastcall TTerminal::CommandSessionClose(TObject * /*Sender*/)
  3914. {
  3915. // Keep the states in sync.
  3916. // This is particularly to invoke ours OnClose,
  3917. // So that it is triggered before Reopen is called
  3918. Close();
  3919. }
  3920. //---------------------------------------------------------------------------
  3921. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  3922. TCaptureOutputEvent OutputEvent)
  3923. {
  3924. #pragma warn -inl
  3925. class TOutputProxy
  3926. {
  3927. public:
  3928. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  3929. FAction(Action),
  3930. FOutputEvent(OutputEvent)
  3931. {
  3932. }
  3933. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  3934. {
  3935. switch (OutputType)
  3936. {
  3937. case cotOutput:
  3938. FAction.AddOutput(Str, false);
  3939. break;
  3940. case cotError:
  3941. FAction.AddOutput(Str, true);
  3942. break;
  3943. case cotExitCode:
  3944. FAction.ExitCode(StrToInt(Str));
  3945. break;
  3946. }
  3947. if (FOutputEvent != NULL)
  3948. {
  3949. FOutputEvent(Str, OutputType);
  3950. }
  3951. }
  3952. private:
  3953. TCallSessionAction & FAction;
  3954. TCaptureOutputEvent FOutputEvent;
  3955. };
  3956. #pragma warn .inl
  3957. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  3958. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  3959. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  3960. }
  3961. //---------------------------------------------------------------------------
  3962. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  3963. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  3964. {
  3965. DebugAssert(FFileSystem);
  3966. try
  3967. {
  3968. DirectoryModified(CurrentDirectory, false);
  3969. if (IsCapable[fcAnyCommand])
  3970. {
  3971. LogEvent(L"Executing user defined command.");
  3972. FFileSystem->AnyCommand(Command, OutputEvent);
  3973. }
  3974. else
  3975. {
  3976. DebugAssert(CommandSessionOpened);
  3977. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3978. LogEvent(L"Executing user defined command on command session.");
  3979. FCommandSession->CurrentDirectory = CurrentDirectory;
  3980. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  3981. FCommandSession->FFileSystem->ReadCurrentDirectory();
  3982. // synchronize pwd (by purpose we lose transaction optimization here)
  3983. ChangeDirectory(FCommandSession->CurrentDirectory);
  3984. }
  3985. ReactOnCommand(fsAnyCommand);
  3986. }
  3987. catch (Exception &E)
  3988. {
  3989. if (Action != NULL)
  3990. {
  3991. RollbackAction(*Action, NULL, &E);
  3992. }
  3993. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  3994. else HandleExtendedException(&E);
  3995. }
  3996. }
  3997. //---------------------------------------------------------------------------
  3998. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  3999. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4000. bool NoConfirmation)
  4001. {
  4002. bool Result = true;
  4003. bool Done;
  4004. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  4005. do
  4006. {
  4007. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  4008. NULL, CREATE_ALWAYS, CreateAttr, 0);
  4009. Done = (*AHandle != INVALID_HANDLE_VALUE);
  4010. if (!Done)
  4011. {
  4012. // save the error, otherwise it gets overwritten by call to FileExists
  4013. int LastError = GetLastError();
  4014. int FileAttr;
  4015. if (::FileExists(ApiPath(FileName)) &&
  4016. (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  4017. {
  4018. if (FLAGSET(FileAttr, faReadOnly))
  4019. {
  4020. if (OperationProgress->BatchOverwrite == boNone)
  4021. {
  4022. Result = false;
  4023. }
  4024. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  4025. {
  4026. unsigned int Answer;
  4027. {
  4028. TSuspendFileOperationProgress Suspend(OperationProgress);
  4029. Answer = QueryUser(
  4030. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  4031. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  4032. }
  4033. switch (Answer) {
  4034. case qaYesToAll: OperationProgress->BatchOverwrite = boAll; break;
  4035. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  4036. case qaNoToAll: OperationProgress->BatchOverwrite = boNone;
  4037. case qaNo: Result = false; break;
  4038. }
  4039. }
  4040. }
  4041. else
  4042. {
  4043. DebugAssert(FLAGSET(FileAttr, faHidden));
  4044. Result = true;
  4045. }
  4046. if (Result)
  4047. {
  4048. CreateAttr |=
  4049. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  4050. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  4051. FILE_OPERATION_LOOP_BEGIN
  4052. {
  4053. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  4054. {
  4055. RaiseLastOSError();
  4056. }
  4057. }
  4058. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  4059. }
  4060. else
  4061. {
  4062. Done = true;
  4063. }
  4064. }
  4065. else
  4066. {
  4067. RaiseLastOSError(LastError);
  4068. }
  4069. }
  4070. }
  4071. while (!Done);
  4072. return Result;
  4073. }
  4074. //---------------------------------------------------------------------------
  4075. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  4076. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4077. bool NoConfirmation)
  4078. {
  4079. DebugAssert(AHandle);
  4080. bool Result = true;
  4081. FILE_OPERATION_LOOP_BEGIN
  4082. {
  4083. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  4084. }
  4085. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  4086. return Result;
  4087. }
  4088. //---------------------------------------------------------------------------
  4089. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  4090. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  4091. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  4092. bool TryWriteReadOnly)
  4093. {
  4094. int Attrs = 0;
  4095. HANDLE Handle = 0;
  4096. FILE_OPERATION_LOOP_BEGIN
  4097. {
  4098. UnicodeString FileNameApi = ApiPath(FileName);
  4099. Attrs = FileGetAttrFix(FileNameApi);
  4100. if (Attrs < 0)
  4101. {
  4102. RaiseLastOSError();
  4103. }
  4104. }
  4105. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4106. if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
  4107. {
  4108. bool NoHandle = false;
  4109. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  4110. ((Attrs & faReadOnly) != 0))
  4111. {
  4112. Access = GENERIC_READ;
  4113. NoHandle = true;
  4114. }
  4115. FILE_OPERATION_LOOP_BEGIN
  4116. {
  4117. DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
  4118. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  4119. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  4120. NULL, OPEN_EXISTING, Flags, 0);
  4121. if (Handle == INVALID_HANDLE_VALUE)
  4122. {
  4123. Handle = 0;
  4124. RaiseLastOSError();
  4125. }
  4126. }
  4127. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  4128. try
  4129. {
  4130. if (AATime || AMTime || ACTime)
  4131. {
  4132. FILETIME ATime;
  4133. FILETIME MTime;
  4134. FILETIME CTime;
  4135. // Get last file access and modification time
  4136. FILE_OPERATION_LOOP_BEGIN
  4137. {
  4138. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  4139. }
  4140. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4141. if (ACTime)
  4142. {
  4143. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  4144. }
  4145. if (AATime)
  4146. {
  4147. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  4148. }
  4149. if (AMTime)
  4150. {
  4151. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  4152. }
  4153. }
  4154. if (ASize)
  4155. {
  4156. // Get file size
  4157. FILE_OPERATION_LOOP_BEGIN
  4158. {
  4159. unsigned long LSize;
  4160. unsigned long HSize;
  4161. LSize = GetFileSize(Handle, &HSize);
  4162. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  4163. *ASize = (__int64(HSize) << 32) + LSize;
  4164. }
  4165. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4166. }
  4167. if ((AHandle == NULL) || NoHandle)
  4168. {
  4169. CloseHandle(Handle);
  4170. Handle = NULL;
  4171. }
  4172. }
  4173. catch(...)
  4174. {
  4175. CloseHandle(Handle);
  4176. throw;
  4177. }
  4178. }
  4179. if (AAttrs) *AAttrs = Attrs;
  4180. if (AHandle) *AHandle = Handle;
  4181. }
  4182. //---------------------------------------------------------------------------
  4183. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  4184. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  4185. {
  4186. bool Result = true;
  4187. // optimization
  4188. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  4189. {
  4190. WIN32_FIND_DATA FindData;
  4191. HANDLE Handle;
  4192. FILE_OPERATION_LOOP_BEGIN
  4193. {
  4194. Handle = FindFirstFile(ApiPath(ExcludeTrailingBackslash(FileName)).c_str(), &FindData);
  4195. if (Handle == INVALID_HANDLE_VALUE)
  4196. {
  4197. RaiseLastOSError();
  4198. }
  4199. }
  4200. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4201. ::FindClose(Handle);
  4202. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  4203. TFileMasks::TParams Params;
  4204. // SearchRec.Size in C++B2010 is __int64,
  4205. // so we should be able to use it instead of FindData.nFileSize*
  4206. Params.Size =
  4207. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  4208. FindData.nFileSizeLow;
  4209. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  4210. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4211. if (!CopyParam->AllowTransfer(BaseFileName, osLocal, Directory, Params))
  4212. {
  4213. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  4214. Result = false;
  4215. }
  4216. else if (CopyParam->SkipTransfer(FileName, Directory))
  4217. {
  4218. OperationProgress->AddSkippedFileSize(Params.Size);
  4219. Result = false;
  4220. }
  4221. if (Result)
  4222. {
  4223. LogFileDetails(FileName, Params.Modification, Params.Size);
  4224. }
  4225. }
  4226. return Result;
  4227. }
  4228. //---------------------------------------------------------------------------
  4229. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  4230. const TSearchRec Rec, void * Param)
  4231. {
  4232. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  4233. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  4234. if (Directory && Params.Recursive)
  4235. {
  4236. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  4237. }
  4238. if (!Directory || Params.IncludeDirs)
  4239. {
  4240. Params.FileList->Add(FileName);
  4241. if (Params.FileTimes != NULL)
  4242. {
  4243. Params.FileTimes->push_back(const_cast<TSearchRec &>(Rec).TimeStamp);
  4244. }
  4245. }
  4246. }
  4247. //---------------------------------------------------------------------------
  4248. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  4249. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  4250. {
  4251. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  4252. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  4253. bool AllowTransfer = (AParams->CopyParam == NULL);
  4254. // SearchRec.Size in C++B2010 is __int64,
  4255. // so we should be able to use it instead of FindData.nFileSize*
  4256. __int64 Size =
  4257. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  4258. Rec.FindData.nFileSizeLow;
  4259. if (!AllowTransfer)
  4260. {
  4261. TFileMasks::TParams MaskParams;
  4262. MaskParams.Size = Size;
  4263. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  4264. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4265. AllowTransfer = AParams->CopyParam->AllowTransfer(BaseFileName, osLocal, Dir, MaskParams);
  4266. }
  4267. if (AllowTransfer)
  4268. {
  4269. if (!Dir)
  4270. {
  4271. AParams->Size += Size;
  4272. }
  4273. else
  4274. {
  4275. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  4276. }
  4277. }
  4278. StartOperationWithFile(FileName, foCalculateSize);
  4279. }
  4280. //---------------------------------------------------------------------------
  4281. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  4282. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs)
  4283. {
  4284. bool Result = true;
  4285. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4286. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4287. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  4288. try
  4289. {
  4290. TCalculateSizeParams Params;
  4291. Params.Size = 0;
  4292. Params.Params = 0;
  4293. Params.CopyParam = CopyParam;
  4294. DebugAssert(!FOperationProgress);
  4295. FOperationProgress = &OperationProgress;
  4296. for (int Index = 0; Result && (Index < FileList->Count); Index++)
  4297. {
  4298. UnicodeString FileName = FileList->Strings[Index];
  4299. TSearchRec Rec;
  4300. if (FileSearchRec(FileName, Rec))
  4301. {
  4302. if (FLAGSET(Rec.Attr, faDirectory) && !AllowDirs)
  4303. {
  4304. Result = false;
  4305. }
  4306. else
  4307. {
  4308. CalculateLocalFileSize(FileName, Rec, &Params);
  4309. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  4310. }
  4311. }
  4312. }
  4313. Size = Params.Size;
  4314. }
  4315. __finally
  4316. {
  4317. FOperationProgress = NULL;
  4318. OperationProgress.Stop();
  4319. }
  4320. if (OnceDoneOperation != odoIdle)
  4321. {
  4322. CloseOnCompletion(OnceDoneOperation);
  4323. }
  4324. return Result;
  4325. }
  4326. //---------------------------------------------------------------------------
  4327. struct TSynchronizeFileData
  4328. {
  4329. bool Modified;
  4330. bool New;
  4331. bool IsDirectory;
  4332. TSynchronizeChecklist::TItem::TFileInfo Info;
  4333. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  4334. TRemoteFile * MatchingRemoteFileFile;
  4335. int MatchingRemoteFileImageIndex;
  4336. FILETIME LocalLastWriteTime;
  4337. };
  4338. //---------------------------------------------------------------------------
  4339. const int sfFirstLevel = 0x01;
  4340. struct TSynchronizeData
  4341. {
  4342. UnicodeString LocalDirectory;
  4343. UnicodeString RemoteDirectory;
  4344. TTerminal::TSynchronizeMode Mode;
  4345. int Params;
  4346. TSynchronizeDirectory OnSynchronizeDirectory;
  4347. TSynchronizeOptions * Options;
  4348. int Flags;
  4349. TStringList * LocalFileList;
  4350. const TCopyParamType * CopyParam;
  4351. TSynchronizeChecklist * Checklist;
  4352. };
  4353. //---------------------------------------------------------------------------
  4354. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  4355. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4356. const TCopyParamType * CopyParam, int Params,
  4357. TSynchronizeDirectory OnSynchronizeDirectory,
  4358. TSynchronizeOptions * Options)
  4359. {
  4360. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4361. FUseBusyCursor = false;
  4362. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  4363. try
  4364. {
  4365. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  4366. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  4367. Checklist);
  4368. Checklist->Sort();
  4369. }
  4370. catch(...)
  4371. {
  4372. delete Checklist;
  4373. throw;
  4374. }
  4375. return Checklist;
  4376. }
  4377. //---------------------------------------------------------------------------
  4378. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  4379. {
  4380. if (FLAGSET(Params, Param))
  4381. {
  4382. AddToList(ParamsStr, Name, ", ");
  4383. }
  4384. Params &= ~Param;
  4385. }
  4386. //---------------------------------------------------------------------------
  4387. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  4388. {
  4389. UnicodeString ModeStr;
  4390. switch (Mode)
  4391. {
  4392. case smRemote:
  4393. ModeStr = L"Remote";
  4394. break;
  4395. case smLocal:
  4396. ModeStr = L"Local";
  4397. break;
  4398. case smBoth:
  4399. ModeStr = L"Both";
  4400. break;
  4401. default:
  4402. ModeStr = L"Unknown";
  4403. break;
  4404. }
  4405. return ModeStr;
  4406. }
  4407. //---------------------------------------------------------------------------
  4408. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  4409. {
  4410. UnicodeString ParamsStr;
  4411. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  4412. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  4413. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  4414. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  4415. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  4416. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  4417. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  4418. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  4419. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  4420. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  4421. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  4422. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  4423. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  4424. if (Params > 0)
  4425. {
  4426. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  4427. }
  4428. return ParamsStr;
  4429. }
  4430. //---------------------------------------------------------------------------
  4431. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  4432. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4433. const TCopyParamType * CopyParam, int Params,
  4434. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  4435. int Flags, TSynchronizeChecklist * Checklist)
  4436. {
  4437. TSynchronizeData Data;
  4438. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  4439. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  4440. Data.Mode = Mode;
  4441. Data.Params = Params;
  4442. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4443. Data.LocalFileList = NULL;
  4444. Data.CopyParam = CopyParam;
  4445. Data.Options = Options;
  4446. Data.Flags = Flags;
  4447. Data.Checklist = Checklist;
  4448. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  4449. "mode = %s, params = 0x%x (%s)", (LocalDirectory, RemoteDirectory,
  4450. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params))));
  4451. if (FLAGCLEAR(Params, spDelayProgress))
  4452. {
  4453. DoSynchronizeProgress(Data, true);
  4454. }
  4455. try
  4456. {
  4457. bool Found;
  4458. TSearchRecChecked SearchRec;
  4459. Data.LocalFileList = CreateSortedStringList();
  4460. FILE_OPERATION_LOOP_BEGIN
  4461. {
  4462. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4463. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  4464. }
  4465. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4466. if (Found)
  4467. {
  4468. try
  4469. {
  4470. UnicodeString FileName;
  4471. while (Found)
  4472. {
  4473. FileName = SearchRec.Name;
  4474. // add dirs for recursive mode or when we are interested in newly
  4475. // added subdirs
  4476. // SearchRec.Size in C++B2010 is __int64,
  4477. // so we should be able to use it instead of FindData.nFileSize*
  4478. __int64 Size =
  4479. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  4480. SearchRec.FindData.nFileSizeLow;
  4481. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  4482. TFileMasks::TParams MaskParams;
  4483. MaskParams.Size = Size;
  4484. MaskParams.Modification = Modification;
  4485. UnicodeString RemoteFileName =
  4486. ChangeFileName(CopyParam, FileName, osLocal, false);
  4487. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  4488. UnicodeString BaseFileName = GetBaseFileName(FullLocalFileName);
  4489. if ((FileName != L".") && (FileName != L"..") &&
  4490. CopyParam->AllowTransfer(BaseFileName, osLocal,
  4491. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  4492. !FFileSystem->TemporaryTransferFile(FileName) &&
  4493. (FLAGCLEAR(Flags, sfFirstLevel) ||
  4494. (Options == NULL) ||
  4495. Options->MatchesFilter(FileName) ||
  4496. Options->MatchesFilter(RemoteFileName)))
  4497. {
  4498. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  4499. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  4500. FileData->Info.FileName = FileName;
  4501. FileData->Info.Directory = Data.LocalDirectory;
  4502. FileData->Info.Modification = Modification;
  4503. FileData->Info.ModificationFmt = mfFull;
  4504. FileData->Info.Size = Size;
  4505. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  4506. FileData->New = true;
  4507. FileData->Modified = false;
  4508. Data.LocalFileList->AddObject(FileName,
  4509. reinterpret_cast<TObject*>(FileData));
  4510. LogEvent(FORMAT(L"Local file %s included to synchronization",
  4511. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4512. }
  4513. else
  4514. {
  4515. LogEvent(FORMAT(L"Local file %s excluded from synchronization",
  4516. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4517. }
  4518. FILE_OPERATION_LOOP_BEGIN
  4519. {
  4520. Found = (FindNextChecked(SearchRec) == 0);
  4521. }
  4522. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4523. }
  4524. }
  4525. __finally
  4526. {
  4527. FindClose(SearchRec);
  4528. }
  4529. // can we expect that ProcessDirectory would take so little time
  4530. // that we can postpone showing progress window until anything actually happens?
  4531. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  4532. FDirectoryCache->HasFileList(RemoteDirectory);
  4533. if (!Cached && FLAGSET(Params, spDelayProgress))
  4534. {
  4535. DoSynchronizeProgress(Data, true);
  4536. }
  4537. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  4538. FLAGSET(Params, spUseCache));
  4539. TSynchronizeFileData * FileData;
  4540. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4541. {
  4542. FileData = reinterpret_cast<TSynchronizeFileData *>
  4543. (Data.LocalFileList->Objects[Index]);
  4544. // add local file either if we are going to upload it
  4545. // (i.e. if it is updated or we want to upload even new files)
  4546. // or if we are going to delete it (i.e. all "new"=obsolete files)
  4547. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  4548. bool New = (FileData->New &&
  4549. ((Mode == smLocal) ||
  4550. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  4551. if (New)
  4552. {
  4553. LogEvent(FORMAT(L"Local file %s is new",
  4554. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  4555. FileData->Info.Modification, FileData->Info.Size))));
  4556. }
  4557. if (Modified || New)
  4558. {
  4559. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4560. try
  4561. {
  4562. ChecklistItem->IsDirectory = FileData->IsDirectory;
  4563. ChecklistItem->Local = FileData->Info;
  4564. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  4565. if (Modified)
  4566. {
  4567. DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  4568. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  4569. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  4570. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  4571. }
  4572. else
  4573. {
  4574. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  4575. }
  4576. if ((Mode == smBoth) || (Mode == smRemote))
  4577. {
  4578. ChecklistItem->Action =
  4579. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  4580. ChecklistItem->Checked =
  4581. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  4582. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4583. FLAGSET(Params, spSubDirs));
  4584. }
  4585. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  4586. {
  4587. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  4588. ChecklistItem->Checked =
  4589. FLAGSET(Params, spDelete) &&
  4590. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4591. FLAGSET(Params, spSubDirs));
  4592. }
  4593. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4594. {
  4595. Data.Checklist->Add(ChecklistItem);
  4596. ChecklistItem = NULL;
  4597. }
  4598. }
  4599. __finally
  4600. {
  4601. delete ChecklistItem;
  4602. }
  4603. }
  4604. else
  4605. {
  4606. if (FileData->Modified)
  4607. {
  4608. delete FileData->MatchingRemoteFileFile;
  4609. }
  4610. }
  4611. }
  4612. }
  4613. }
  4614. __finally
  4615. {
  4616. if (Data.LocalFileList != NULL)
  4617. {
  4618. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4619. {
  4620. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  4621. (Data.LocalFileList->Objects[Index]);
  4622. delete FileData;
  4623. }
  4624. delete Data.LocalFileList;
  4625. }
  4626. }
  4627. }
  4628. //---------------------------------------------------------------------------
  4629. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  4630. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4631. {
  4632. try
  4633. {
  4634. DoSynchronizeCollectFile(FileName, File, Param);
  4635. }
  4636. catch(EScpSkipFile & E)
  4637. {
  4638. TSuspendFileOperationProgress Suspend(OperationProgress);
  4639. if (!HandleException(&E))
  4640. {
  4641. throw;
  4642. }
  4643. }
  4644. }
  4645. //---------------------------------------------------------------------------
  4646. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  4647. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4648. {
  4649. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  4650. TFileMasks::TParams MaskParams;
  4651. MaskParams.Size = File->Size;
  4652. MaskParams.Modification = File->Modification;
  4653. UnicodeString LocalFileName =
  4654. ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
  4655. UnicodeString FullRemoteFileName =
  4656. UnixExcludeTrailingBackslash(File->FullFileName);
  4657. UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
  4658. if (Data->CopyParam->AllowTransfer(
  4659. BaseFileName, osRemote,
  4660. File->IsDirectory, MaskParams) &&
  4661. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  4662. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  4663. (Data->Options == NULL) ||
  4664. Data->Options->MatchesFilter(File->FileName) ||
  4665. Data->Options->MatchesFilter(LocalFileName)))
  4666. {
  4667. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4668. try
  4669. {
  4670. ChecklistItem->IsDirectory = File->IsDirectory;
  4671. ChecklistItem->ImageIndex = File->IconIndex;
  4672. ChecklistItem->Remote.FileName = File->FileName;
  4673. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  4674. ChecklistItem->Remote.Modification = File->Modification;
  4675. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  4676. ChecklistItem->Remote.Size = File->Size;
  4677. bool Modified = false;
  4678. bool New = false;
  4679. if (File->IsDirectory && !CanRecurseToDirectory(File))
  4680. {
  4681. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
  4682. }
  4683. else
  4684. {
  4685. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  4686. New = (LocalIndex < 0);
  4687. if (!New)
  4688. {
  4689. TSynchronizeFileData * LocalData =
  4690. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  4691. LocalData->New = false;
  4692. if (File->IsDirectory != LocalData->IsDirectory)
  4693. {
  4694. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  4695. (File->FileName)));
  4696. }
  4697. else if (!File->IsDirectory)
  4698. {
  4699. ChecklistItem->Local = LocalData->Info;
  4700. ChecklistItem->Local.Modification =
  4701. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  4702. bool LocalModified = false;
  4703. // for spTimestamp+spBySize require that the file sizes are the same
  4704. // before comparing file time
  4705. int TimeCompare;
  4706. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  4707. (FLAGCLEAR(Data->Params, spTimestamp) ||
  4708. FLAGCLEAR(Data->Params, spBySize) ||
  4709. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  4710. {
  4711. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  4712. ChecklistItem->Remote.Modification);
  4713. }
  4714. else
  4715. {
  4716. TimeCompare = 0;
  4717. }
  4718. if (TimeCompare < 0)
  4719. {
  4720. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4721. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  4722. {
  4723. Modified = true;
  4724. }
  4725. else
  4726. {
  4727. LocalModified = true;
  4728. }
  4729. }
  4730. else if (TimeCompare > 0)
  4731. {
  4732. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4733. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  4734. {
  4735. LocalModified = true;
  4736. }
  4737. else
  4738. {
  4739. Modified = true;
  4740. }
  4741. }
  4742. else if (FLAGSET(Data->Params, spBySize) &&
  4743. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  4744. FLAGCLEAR(Data->Params, spTimestamp))
  4745. {
  4746. Modified = true;
  4747. LocalModified = true;
  4748. }
  4749. if (LocalModified)
  4750. {
  4751. LocalData->Modified = true;
  4752. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  4753. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  4754. // we need this for custom commands over checklist only,
  4755. // not for sync itself
  4756. LocalData->MatchingRemoteFileFile = File->Duplicate();
  4757. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  4758. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4759. LocalData->Info.Modification, LocalData->Info.Size),
  4760. FormatFileDetailsForLog(FullRemoteFileName,
  4761. File->Modification, File->Size))));
  4762. }
  4763. if (Modified)
  4764. {
  4765. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  4766. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size),
  4767. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4768. LocalData->Info.Modification, LocalData->Info.Size))));
  4769. }
  4770. }
  4771. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  4772. {
  4773. DoSynchronizeCollectDirectory(
  4774. Data->LocalDirectory + LocalData->Info.FileName,
  4775. Data->RemoteDirectory + File->FileName,
  4776. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  4777. Data->Options, (Data->Flags & ~sfFirstLevel),
  4778. Data->Checklist);
  4779. }
  4780. }
  4781. else
  4782. {
  4783. ChecklistItem->Local.Directory = Data->LocalDirectory;
  4784. LogEvent(FORMAT(L"Remote file %s is new",
  4785. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4786. }
  4787. }
  4788. if (New || Modified)
  4789. {
  4790. DebugAssert(!New || !Modified);
  4791. // download the file if it changed or is new and we want to have it locally
  4792. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  4793. {
  4794. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  4795. {
  4796. ChecklistItem->Action =
  4797. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  4798. ChecklistItem->Checked =
  4799. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  4800. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4801. FLAGSET(Data->Params, spSubDirs));
  4802. }
  4803. }
  4804. else if ((Data->Mode == smRemote) && New)
  4805. {
  4806. if (FLAGCLEAR(Data->Params, spTimestamp))
  4807. {
  4808. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  4809. ChecklistItem->Checked =
  4810. FLAGSET(Data->Params, spDelete) &&
  4811. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4812. FLAGSET(Data->Params, spSubDirs));
  4813. }
  4814. }
  4815. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4816. {
  4817. ChecklistItem->RemoteFile = File->Duplicate();
  4818. Data->Checklist->Add(ChecklistItem);
  4819. ChecklistItem = NULL;
  4820. }
  4821. }
  4822. }
  4823. __finally
  4824. {
  4825. delete ChecklistItem;
  4826. }
  4827. }
  4828. else
  4829. {
  4830. LogEvent(FORMAT(L"Remote file %s excluded from synchronization",
  4831. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4832. }
  4833. }
  4834. //---------------------------------------------------------------------------
  4835. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  4836. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  4837. const TCopyParamType * CopyParam, int Params,
  4838. TSynchronizeDirectory OnSynchronizeDirectory)
  4839. {
  4840. TSynchronizeData Data;
  4841. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4842. int CopyParams =
  4843. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  4844. TCopyParamType SyncCopyParam = *CopyParam;
  4845. // when synchronizing by time, we force preserving time,
  4846. // otherwise it does not make any sense
  4847. if (FLAGCLEAR(Params, spNotByTime))
  4848. {
  4849. SyncCopyParam.PreserveTime = true;
  4850. }
  4851. TStringList * DownloadList = new TStringList();
  4852. TStringList * DeleteRemoteList = new TStringList();
  4853. TStringList * UploadList = new TStringList();
  4854. TStringList * DeleteLocalList = new TStringList();
  4855. BeginTransaction();
  4856. try
  4857. {
  4858. int IIndex = 0;
  4859. while (IIndex < Checklist->Count)
  4860. {
  4861. const TSynchronizeChecklist::TItem * ChecklistItem;
  4862. DownloadList->Clear();
  4863. DeleteRemoteList->Clear();
  4864. UploadList->Clear();
  4865. DeleteLocalList->Clear();
  4866. ChecklistItem = Checklist->Item[IIndex];
  4867. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  4868. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  4869. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  4870. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  4871. int(Params), SynchronizeParamsStr(Params))));
  4872. int Count = 0;
  4873. while ((IIndex < Checklist->Count) &&
  4874. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  4875. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  4876. {
  4877. ChecklistItem = Checklist->Item[IIndex];
  4878. if (ChecklistItem->Checked)
  4879. {
  4880. Count++;
  4881. if (FLAGSET(Params, spTimestamp))
  4882. {
  4883. switch (ChecklistItem->Action)
  4884. {
  4885. case TSynchronizeChecklist::saDownloadUpdate:
  4886. DownloadList->AddObject(
  4887. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4888. ChecklistItem->Remote.FileName,
  4889. (TObject *)(ChecklistItem));
  4890. break;
  4891. case TSynchronizeChecklist::saUploadUpdate:
  4892. UploadList->AddObject(
  4893. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4894. ChecklistItem->Local.FileName,
  4895. (TObject *)(ChecklistItem));
  4896. break;
  4897. default:
  4898. DebugFail();
  4899. break;
  4900. }
  4901. }
  4902. else
  4903. {
  4904. switch (ChecklistItem->Action)
  4905. {
  4906. case TSynchronizeChecklist::saDownloadNew:
  4907. case TSynchronizeChecklist::saDownloadUpdate:
  4908. DownloadList->AddObject(
  4909. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4910. ChecklistItem->Remote.FileName,
  4911. ChecklistItem->RemoteFile);
  4912. break;
  4913. case TSynchronizeChecklist::saDeleteRemote:
  4914. DeleteRemoteList->AddObject(
  4915. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4916. ChecklistItem->Remote.FileName,
  4917. ChecklistItem->RemoteFile);
  4918. break;
  4919. case TSynchronizeChecklist::saUploadNew:
  4920. case TSynchronizeChecklist::saUploadUpdate:
  4921. UploadList->Add(
  4922. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4923. ChecklistItem->Local.FileName);
  4924. break;
  4925. case TSynchronizeChecklist::saDeleteLocal:
  4926. DeleteLocalList->Add(
  4927. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4928. ChecklistItem->Local.FileName);
  4929. break;
  4930. default:
  4931. DebugFail();
  4932. break;
  4933. }
  4934. }
  4935. }
  4936. IIndex++;
  4937. }
  4938. // prevent showing/updating of progress dialog if there's nothing to do
  4939. if (Count > 0)
  4940. {
  4941. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  4942. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  4943. DoSynchronizeProgress(Data, false);
  4944. if (FLAGSET(Params, spTimestamp))
  4945. {
  4946. if (DownloadList->Count > 0)
  4947. {
  4948. ProcessFiles(DownloadList, foSetProperties,
  4949. SynchronizeLocalTimestamp, NULL, osLocal);
  4950. }
  4951. if (UploadList->Count > 0)
  4952. {
  4953. ProcessFiles(UploadList, foSetProperties,
  4954. SynchronizeRemoteTimestamp);
  4955. }
  4956. }
  4957. else
  4958. {
  4959. if ((DownloadList->Count > 0) &&
  4960. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  4961. {
  4962. Abort();
  4963. }
  4964. if ((DeleteRemoteList->Count > 0) &&
  4965. !DeleteFiles(DeleteRemoteList))
  4966. {
  4967. Abort();
  4968. }
  4969. if ((UploadList->Count > 0) &&
  4970. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  4971. {
  4972. Abort();
  4973. }
  4974. if ((DeleteLocalList->Count > 0) &&
  4975. !DeleteLocalFiles(DeleteLocalList))
  4976. {
  4977. Abort();
  4978. }
  4979. }
  4980. }
  4981. }
  4982. }
  4983. __finally
  4984. {
  4985. delete DownloadList;
  4986. delete DeleteRemoteList;
  4987. delete UploadList;
  4988. delete DeleteLocalList;
  4989. EndTransaction();
  4990. }
  4991. }
  4992. //---------------------------------------------------------------------------
  4993. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  4994. bool Collect)
  4995. {
  4996. if (Data.OnSynchronizeDirectory != NULL)
  4997. {
  4998. bool Continue = true;
  4999. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  5000. Continue, Collect);
  5001. if (!Continue)
  5002. {
  5003. Abort();
  5004. }
  5005. }
  5006. }
  5007. //---------------------------------------------------------------------------
  5008. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  5009. const TRemoteFile * File, void * /*Param*/)
  5010. {
  5011. const TSynchronizeChecklist::TItem * ChecklistItem =
  5012. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5013. UnicodeString LocalFile =
  5014. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  5015. ChecklistItem->Local.FileName;
  5016. FILE_OPERATION_LOOP_BEGIN
  5017. {
  5018. HANDLE Handle;
  5019. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  5020. NULL, NULL, NULL, NULL);
  5021. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  5022. SessionData->DSTMode);
  5023. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  5024. int Error = GetLastError();
  5025. CloseHandle(Handle);
  5026. if (!Result)
  5027. {
  5028. RaiseLastOSError(Error);
  5029. }
  5030. }
  5031. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  5032. }
  5033. //---------------------------------------------------------------------------
  5034. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  5035. const TRemoteFile * File, void * /*Param*/)
  5036. {
  5037. const TSynchronizeChecklist::TItem * ChecklistItem =
  5038. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5039. TRemoteProperties Properties;
  5040. Properties.Valid << vpModification;
  5041. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  5042. SessionData->DSTMode);
  5043. ChangeFileProperties(
  5044. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  5045. NULL, &Properties);
  5046. }
  5047. //---------------------------------------------------------------------------
  5048. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  5049. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  5050. {
  5051. // see DoFilesFind
  5052. FOnFindingFile = NULL;
  5053. DebugAssert(Param);
  5054. DebugAssert(File);
  5055. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  5056. if (!AParams->Cancel)
  5057. {
  5058. if (FileName.IsEmpty())
  5059. {
  5060. FileName = File->FileName;
  5061. }
  5062. TFileMasks::TParams MaskParams;
  5063. MaskParams.Size = File->Size;
  5064. MaskParams.Modification = File->Modification;
  5065. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5066. bool ImplicitMatch;
  5067. // Do not use recursive include match
  5068. if (AParams->FileMask.Matches(FullFileName, false,
  5069. File->IsDirectory, &MaskParams, false, ImplicitMatch))
  5070. {
  5071. if (!ImplicitMatch)
  5072. {
  5073. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  5074. }
  5075. if (File->IsDirectory)
  5076. {
  5077. UnicodeString RealDirectory;
  5078. if (!File->IsSymLink || File->LinkTo.IsEmpty())
  5079. {
  5080. RealDirectory = UnixIncludeTrailingBackslash(AParams->RealDirectory) + File->FileName;
  5081. }
  5082. else
  5083. {
  5084. RealDirectory = ::AbsolutePath(AParams->RealDirectory, File->LinkTo);
  5085. }
  5086. if (!AParams->LoopDetector.IsUnvisitedDirectory(RealDirectory))
  5087. {
  5088. LogEvent(FORMAT(L"Already searched \"%s\" directory (real path \"%s\"), link loop detected", (FullFileName, RealDirectory)));
  5089. }
  5090. else
  5091. {
  5092. DoFilesFind(FullFileName, *AParams, RealDirectory);
  5093. }
  5094. }
  5095. }
  5096. }
  5097. }
  5098. //---------------------------------------------------------------------------
  5099. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params, UnicodeString RealDirectory)
  5100. {
  5101. LogEvent(FORMAT(L"Searching directory \"%s\" (real path \"%s\")", (Directory, RealDirectory)));
  5102. Params.OnFindingFile(this, Directory, Params.Cancel);
  5103. if (!Params.Cancel)
  5104. {
  5105. DebugAssert(FOnFindingFile == NULL);
  5106. // ideally we should set the handler only around actually reading
  5107. // of the directory listing, so we at least reset the handler in
  5108. // FileFind
  5109. FOnFindingFile = Params.OnFindingFile;
  5110. UnicodeString PrevRealDirectory = Params.RealDirectory;
  5111. try
  5112. {
  5113. Params.RealDirectory = RealDirectory;
  5114. ProcessDirectory(Directory, FileFind, &Params, false, true);
  5115. }
  5116. __finally
  5117. {
  5118. Params.RealDirectory = PrevRealDirectory;
  5119. FOnFindingFile = NULL;
  5120. }
  5121. }
  5122. }
  5123. //---------------------------------------------------------------------------
  5124. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  5125. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  5126. {
  5127. TFilesFindParams Params;
  5128. Params.FileMask = FileMask;
  5129. Params.OnFileFound = OnFileFound;
  5130. Params.OnFindingFile = OnFindingFile;
  5131. Params.Cancel = false;
  5132. Params.LoopDetector.RecordVisitedDirectory(Directory);
  5133. DoFilesFind(Directory, Params, Directory);
  5134. }
  5135. //---------------------------------------------------------------------------
  5136. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  5137. TSpaceAvailable & ASpaceAvailable)
  5138. {
  5139. DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
  5140. try
  5141. {
  5142. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  5143. }
  5144. catch (Exception &E)
  5145. {
  5146. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  5147. }
  5148. }
  5149. //---------------------------------------------------------------------------
  5150. void __fastcall TTerminal::LockFile(const UnicodeString FileName,
  5151. const TRemoteFile * File, void * /*Param*/)
  5152. {
  5153. StartOperationWithFile(FileName, foLock);
  5154. LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
  5155. FileModified(File, FileName, true);
  5156. DoLockFile(FileName, File);
  5157. ReactOnCommand(fsLock);
  5158. }
  5159. //---------------------------------------------------------------------------
  5160. void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5161. {
  5162. TRetryOperationLoop RetryLoop(this);
  5163. do
  5164. {
  5165. try
  5166. {
  5167. FFileSystem->LockFile(FileName, File);
  5168. }
  5169. catch(Exception & E)
  5170. {
  5171. RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
  5172. }
  5173. }
  5174. while (RetryLoop.Retry());
  5175. }
  5176. //---------------------------------------------------------------------------
  5177. void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
  5178. const TRemoteFile * File, void * /*Param*/)
  5179. {
  5180. StartOperationWithFile(FileName, foUnlock);
  5181. LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
  5182. FileModified(File, FileName, true);
  5183. DoUnlockFile(FileName, File);
  5184. ReactOnCommand(fsLock);
  5185. }
  5186. //---------------------------------------------------------------------------
  5187. void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5188. {
  5189. TRetryOperationLoop RetryLoop(this);
  5190. do
  5191. {
  5192. try
  5193. {
  5194. FFileSystem->UnlockFile(FileName, File);
  5195. }
  5196. catch(Exception & E)
  5197. {
  5198. RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
  5199. }
  5200. }
  5201. while (RetryLoop.Retry());
  5202. }
  5203. //---------------------------------------------------------------------------
  5204. void __fastcall TTerminal::LockFiles(TStrings * FileList)
  5205. {
  5206. BeginTransaction();
  5207. try
  5208. {
  5209. ProcessFiles(FileList, foLock, LockFile, NULL);
  5210. }
  5211. __finally
  5212. {
  5213. EndTransaction();
  5214. }
  5215. }
  5216. //---------------------------------------------------------------------------
  5217. void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
  5218. {
  5219. BeginTransaction();
  5220. try
  5221. {
  5222. ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
  5223. }
  5224. __finally
  5225. {
  5226. EndTransaction();
  5227. }
  5228. }
  5229. //---------------------------------------------------------------------------
  5230. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  5231. {
  5232. return FFileSystem->GetSessionInfo();
  5233. }
  5234. //---------------------------------------------------------------------------
  5235. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  5236. {
  5237. return FFileSystem->GetFileSystemInfo(Retrieve);
  5238. }
  5239. //---------------------------------------------------------------------
  5240. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  5241. {
  5242. FFileSystem->GetSupportedChecksumAlgs(Algs);
  5243. }
  5244. //---------------------------------------------------------------------
  5245. UnicodeString __fastcall TTerminal::GetPassword()
  5246. {
  5247. UnicodeString Result;
  5248. // FRememberedPassword is empty also when stored password was used
  5249. if (FRememberedPassword.IsEmpty())
  5250. {
  5251. Result = SessionData->Password;
  5252. }
  5253. else
  5254. {
  5255. Result = RememberedPassword;
  5256. }
  5257. return Result;
  5258. }
  5259. //---------------------------------------------------------------------
  5260. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  5261. {
  5262. return DecryptPassword(FRememberedPassword);
  5263. }
  5264. //---------------------------------------------------------------------
  5265. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  5266. {
  5267. return DecryptPassword(FRememberedTunnelPassword);
  5268. }
  5269. //---------------------------------------------------------------------
  5270. bool __fastcall TTerminal::GetStoredCredentialsTried()
  5271. {
  5272. bool Result;
  5273. if (FFileSystem != NULL)
  5274. {
  5275. Result = FFileSystem->GetStoredCredentialsTried();
  5276. }
  5277. else if (FSecureShell != NULL)
  5278. {
  5279. Result = FSecureShell->GetStoredCredentialsTried();
  5280. }
  5281. else
  5282. {
  5283. DebugAssert(FTunnelOpening);
  5284. Result = false;
  5285. }
  5286. return Result;
  5287. }
  5288. //---------------------------------------------------------------------------
  5289. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  5290. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5291. {
  5292. DebugAssert(FFileSystem);
  5293. DebugAssert(FilesToCopy);
  5294. bool Result = false;
  5295. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5296. try
  5297. {
  5298. __int64 Size;
  5299. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5300. bool CalculatedSize =
  5301. CalculateLocalFilesSize(
  5302. FilesToCopy, Size,
  5303. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5304. CopyParam->CalculateSize);
  5305. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5306. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  5307. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5308. FOperationProgress = &OperationProgress;
  5309. bool CollectingUsage = false;
  5310. try
  5311. {
  5312. if (CalculatedSize)
  5313. {
  5314. if (Configuration->Usage->Collect)
  5315. {
  5316. int CounterSize = TUsage::CalculateCounterSize(Size);
  5317. Configuration->Usage->Inc(L"Uploads");
  5318. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  5319. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  5320. CollectingUsage = true;
  5321. }
  5322. OperationProgress.SetTotalSize(Size);
  5323. }
  5324. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  5325. BeginTransaction();
  5326. try
  5327. {
  5328. if (Log->Logging)
  5329. {
  5330. LogEvent(FORMAT(L"Copying %d files/directories to remote directory "
  5331. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5332. LogEvent(CopyParam->LogStr);
  5333. }
  5334. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  5335. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  5336. }
  5337. __finally
  5338. {
  5339. if (Active)
  5340. {
  5341. ReactOnCommand(fsCopyToRemote);
  5342. }
  5343. EndTransaction();
  5344. }
  5345. if (OperationProgress.Cancel == csContinue)
  5346. {
  5347. Result = true;
  5348. }
  5349. }
  5350. __finally
  5351. {
  5352. if (CollectingUsage)
  5353. {
  5354. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5355. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  5356. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  5357. }
  5358. OperationProgress.Stop();
  5359. FOperationProgress = NULL;
  5360. }
  5361. }
  5362. catch (Exception &E)
  5363. {
  5364. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  5365. OnceDoneOperation = odoIdle;
  5366. }
  5367. if (OnceDoneOperation != odoIdle)
  5368. {
  5369. CloseOnCompletion(OnceDoneOperation);
  5370. }
  5371. return Result;
  5372. }
  5373. //---------------------------------------------------------------------------
  5374. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  5375. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5376. {
  5377. DebugAssert(FFileSystem);
  5378. // see scp.c: sink(), tolocal()
  5379. bool Result = false;
  5380. bool OwnsFileList = (FilesToCopy == NULL);
  5381. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5382. try
  5383. {
  5384. if (OwnsFileList)
  5385. {
  5386. FilesToCopy = new TStringList();
  5387. FilesToCopy->Assign(Files->SelectedFiles);
  5388. }
  5389. BeginTransaction();
  5390. try
  5391. {
  5392. __int64 TotalSize;
  5393. bool TotalSizeKnown = false;
  5394. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5395. ExceptionOnFail = true;
  5396. try
  5397. {
  5398. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5399. if (CalculateFilesSize(
  5400. FilesToCopy, TotalSize, csIgnoreErrors,
  5401. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5402. CopyParam->CalculateSize, NULL))
  5403. {
  5404. TotalSizeKnown = true;
  5405. }
  5406. }
  5407. __finally
  5408. {
  5409. ExceptionOnFail = false;
  5410. }
  5411. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  5412. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5413. FOperationProgress = &OperationProgress;
  5414. bool CollectingUsage = false;
  5415. try
  5416. {
  5417. if (TotalSizeKnown)
  5418. {
  5419. if (Configuration->Usage->Collect)
  5420. {
  5421. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  5422. Configuration->Usage->Inc(L"Downloads");
  5423. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  5424. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  5425. CollectingUsage = true;
  5426. }
  5427. OperationProgress.SetTotalSize(TotalSize);
  5428. }
  5429. try
  5430. {
  5431. try
  5432. {
  5433. if (Log->Logging)
  5434. {
  5435. LogEvent(FORMAT(L"Copying %d files/directories to local directory "
  5436. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5437. LogEvent(CopyParam->LogStr);
  5438. }
  5439. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  5440. &OperationProgress, OnceDoneOperation);
  5441. }
  5442. __finally
  5443. {
  5444. if (Active)
  5445. {
  5446. ReactOnCommand(fsCopyToLocal);
  5447. }
  5448. }
  5449. }
  5450. catch (Exception &E)
  5451. {
  5452. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  5453. OnceDoneOperation = odoIdle;
  5454. }
  5455. if (OperationProgress.Cancel == csContinue)
  5456. {
  5457. Result = true;
  5458. }
  5459. }
  5460. __finally
  5461. {
  5462. if (CollectingUsage)
  5463. {
  5464. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5465. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  5466. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  5467. }
  5468. FOperationProgress = NULL;
  5469. OperationProgress.Stop();
  5470. }
  5471. }
  5472. __finally
  5473. {
  5474. // If session is still active (no fatal error) we reload directory
  5475. // by calling EndTransaction
  5476. EndTransaction();
  5477. }
  5478. }
  5479. __finally
  5480. {
  5481. if (OwnsFileList) delete FilesToCopy;
  5482. }
  5483. if (OnceDoneOperation != odoIdle)
  5484. {
  5485. CloseOnCompletion(OnceDoneOperation);
  5486. }
  5487. return Result;
  5488. }
  5489. //---------------------------------------------------------------------------
  5490. void __fastcall TTerminal::ReflectSettings()
  5491. {
  5492. DebugAssert(FLog != NULL);
  5493. FLog->ReflectSettings();
  5494. DebugAssert(FActionLog != NULL);
  5495. FActionLog->ReflectSettings();
  5496. // also FTunnelLog ?
  5497. }
  5498. //---------------------------------------------------------------------------
  5499. void __fastcall TTerminal::CollectUsage()
  5500. {
  5501. switch (SessionData->FSProtocol)
  5502. {
  5503. case fsSCPonly:
  5504. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  5505. break;
  5506. case fsSFTP:
  5507. case fsSFTPonly:
  5508. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  5509. break;
  5510. case fsFTP:
  5511. if (SessionData->Ftps == ftpsNone)
  5512. {
  5513. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  5514. }
  5515. else
  5516. {
  5517. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  5518. }
  5519. break;
  5520. case fsWebDAV:
  5521. if (SessionData->Ftps == ftpsNone)
  5522. {
  5523. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  5524. }
  5525. else
  5526. {
  5527. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  5528. }
  5529. break;
  5530. }
  5531. if (Configuration->Logging && Configuration->LogToFile)
  5532. {
  5533. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  5534. }
  5535. if (Configuration->LogActions)
  5536. {
  5537. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  5538. }
  5539. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5540. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  5541. {
  5542. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  5543. }
  5544. if (SessionData->ProxyMethod != ::pmNone)
  5545. {
  5546. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  5547. }
  5548. if (SessionData->FtpProxyLogonType > 0)
  5549. {
  5550. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  5551. }
  5552. FCollectFileSystemUsage = true;
  5553. }
  5554. //---------------------------------------------------------------------------
  5555. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  5556. {
  5557. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  5558. }
  5559. //---------------------------------------------------------------------------
  5560. bool __fastcall TTerminal::VerifyCertificate(
  5561. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  5562. const UnicodeString & Fingerprint,
  5563. const UnicodeString & CertificateSubject, int Failures)
  5564. {
  5565. bool Result = false;
  5566. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5567. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5568. Storage->AccessMode = smRead;
  5569. if (Storage->OpenSubKey(CertificateStorageKey, false))
  5570. {
  5571. if (Storage->ValueExists(SiteKey))
  5572. {
  5573. UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
  5574. if (CertificateData == CachedCertificateData)
  5575. {
  5576. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  5577. Result = true;
  5578. }
  5579. }
  5580. else if (Storage->ValueExists(Fingerprint))
  5581. {
  5582. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  5583. Result = true;
  5584. }
  5585. }
  5586. if (!Result)
  5587. {
  5588. UnicodeString Buf = SessionData->HostKey;
  5589. while (!Result && !Buf.IsEmpty())
  5590. {
  5591. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  5592. if (ExpectedKey == L"*")
  5593. {
  5594. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  5595. Information(Message, true);
  5596. Log->Add(llException, Message);
  5597. Result = true;
  5598. }
  5599. else if (ExpectedKey == Fingerprint)
  5600. {
  5601. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  5602. Result = true;
  5603. }
  5604. }
  5605. }
  5606. return Result;
  5607. }
  5608. //---------------------------------------------------------------------------
  5609. void __fastcall TTerminal::CacheCertificate(const UnicodeString & CertificateStorageKey,
  5610. const UnicodeString & SiteKey, const UnicodeString & Fingerprint, int Failures)
  5611. {
  5612. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5613. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5614. Storage->AccessMode = smReadWrite;
  5615. if (Storage->OpenSubKey(CertificateStorageKey, true))
  5616. {
  5617. Storage->WriteString(SiteKey, CertificateData);
  5618. }
  5619. }
  5620. //---------------------------------------------------------------------------
  5621. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  5622. {
  5623. // see SSL_get_version() in OpenSSL ssl_lib.c
  5624. if (TlsVersionStr == L"TLSv1.2")
  5625. {
  5626. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  5627. }
  5628. else if (TlsVersionStr == L"TLSv1.1")
  5629. {
  5630. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  5631. }
  5632. else if (TlsVersionStr == L"TLSv1")
  5633. {
  5634. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  5635. }
  5636. else if (TlsVersionStr == L"SSLv3")
  5637. {
  5638. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  5639. }
  5640. else if (TlsVersionStr == L"SSLv2")
  5641. {
  5642. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  5643. }
  5644. else
  5645. {
  5646. DebugFail();
  5647. }
  5648. }
  5649. //---------------------------------------------------------------------------
  5650. bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
  5651. {
  5652. bool Result = !SessionData->TlsCertificateFile.IsEmpty();
  5653. if (Result)
  5654. {
  5655. UnicodeString Passphrase = SessionData->Passphrase;
  5656. // Inspired by neon's ne_ssl_clicert_read
  5657. bool Retry;
  5658. do
  5659. {
  5660. Retry = false;
  5661. bool WrongPassphrase = false;
  5662. ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
  5663. if (WrongPassphrase)
  5664. {
  5665. if (Passphrase.IsEmpty())
  5666. {
  5667. LogEvent(L"Certificate is encrypted, need passphrase");
  5668. Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
  5669. }
  5670. else
  5671. {
  5672. Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
  5673. }
  5674. Passphrase = L"";
  5675. if (PromptUser(
  5676. SessionData, pkPassphrase,
  5677. LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
  5678. LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
  5679. {
  5680. Retry = true;
  5681. }
  5682. else
  5683. {
  5684. Result = false;
  5685. }
  5686. }
  5687. }
  5688. while (Retry);
  5689. }
  5690. return Result;
  5691. }
  5692. //---------------------------------------------------------------------------
  5693. UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
  5694. {
  5695. if (FSessionData->TrimVMSVersions)
  5696. {
  5697. int P = FileName.LastDelimiter(L";");
  5698. if (P > 0)
  5699. {
  5700. FileName.SetLength(P - 1);
  5701. }
  5702. }
  5703. return FileName;
  5704. }
  5705. //---------------------------------------------------------------------------
  5706. UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
  5707. UnicodeString FileName, TOperationSide Side, bool FirstLevel)
  5708. {
  5709. FileName = GetBaseFileName(FileName);
  5710. FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
  5711. return FileName;
  5712. }
  5713. //---------------------------------------------------------------------------
  5714. bool __fastcall TTerminal::CanRecurseToDirectory(const TRemoteFile * File)
  5715. {
  5716. return !File->IsSymLink || FSessionData->FollowDirectorySymlinks;
  5717. }
  5718. //---------------------------------------------------------------------------
  5719. bool __fastcall TTerminal::IsThisOrChild(TTerminal * Terminal)
  5720. {
  5721. return
  5722. (this == Terminal) ||
  5723. ((FCommandSession != NULL) && (FCommandSession == Terminal));
  5724. }
  5725. //---------------------------------------------------------------------------
  5726. //---------------------------------------------------------------------------
  5727. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  5728. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  5729. TTerminal(ASessionData, Configuration),
  5730. FMainTerminal(MainTerminal)
  5731. {
  5732. Log->Parent = FMainTerminal->Log;
  5733. Log->Name = Name;
  5734. ActionLog->Enabled = false;
  5735. SessionData->NonPersistant();
  5736. DebugAssert(FMainTerminal != NULL);
  5737. if (!FMainTerminal->UserName.IsEmpty())
  5738. {
  5739. SessionData->UserName = FMainTerminal->UserName;
  5740. }
  5741. }
  5742. //---------------------------------------------------------------------------
  5743. void __fastcall TSecondaryTerminal::UpdateFromMain()
  5744. {
  5745. if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
  5746. {
  5747. FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
  5748. }
  5749. }
  5750. //---------------------------------------------------------------------------
  5751. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  5752. {
  5753. FMainTerminal->DirectoryLoaded(FileList);
  5754. DebugAssert(FileList != NULL);
  5755. }
  5756. //---------------------------------------------------------------------------
  5757. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  5758. bool SubDirs)
  5759. {
  5760. // clear cache of main terminal
  5761. FMainTerminal->DirectoryModified(Path, SubDirs);
  5762. }
  5763. //---------------------------------------------------------------------------
  5764. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  5765. {
  5766. return FMainTerminal;
  5767. }
  5768. //---------------------------------------------------------------------------
  5769. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  5770. TObjectList()
  5771. {
  5772. DebugAssert(AConfiguration);
  5773. FConfiguration = AConfiguration;
  5774. }
  5775. //---------------------------------------------------------------------------
  5776. __fastcall TTerminalList::~TTerminalList()
  5777. {
  5778. DebugAssert(Count == 0);
  5779. }
  5780. //---------------------------------------------------------------------------
  5781. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  5782. {
  5783. return new TTerminal(Data, FConfiguration);
  5784. }
  5785. //---------------------------------------------------------------------------
  5786. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  5787. {
  5788. TTerminal * Terminal = CreateTerminal(Data);
  5789. Add(Terminal);
  5790. return Terminal;
  5791. }
  5792. //---------------------------------------------------------------------------
  5793. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  5794. {
  5795. DebugAssert(IndexOf(Terminal) >= 0);
  5796. Remove(Terminal);
  5797. }
  5798. //---------------------------------------------------------------------------
  5799. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  5800. {
  5801. TTerminal * T = Terminal;
  5802. Terminal = NULL;
  5803. FreeTerminal(T);
  5804. }
  5805. //---------------------------------------------------------------------------
  5806. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  5807. {
  5808. return dynamic_cast<TTerminal *>(Items[Index]);
  5809. }
  5810. //---------------------------------------------------------------------------
  5811. void __fastcall TTerminalList::Idle()
  5812. {
  5813. TTerminal * Terminal;
  5814. for (int i = 0; i < Count; i++)
  5815. {
  5816. Terminal = Terminals[i];
  5817. if (Terminal->Status == ssOpened)
  5818. {
  5819. Terminal->Idle();
  5820. }
  5821. }
  5822. }
  5823. //---------------------------------------------------------------------------
  5824. void __fastcall TTerminalList::RecryptPasswords()
  5825. {
  5826. for (int Index = 0; Index < Count; Index++)
  5827. {
  5828. Terminals[Index]->RecryptPasswords();
  5829. }
  5830. }