Terminal.cpp 254 KB

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