Terminal.cpp 188 KB

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