Terminal.cpp 190 KB

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