Terminal.cpp 192 KB

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