Terminal.cpp 189 KB

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