Terminal.cpp 272 KB

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