Terminal.cpp 205 KB

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