Terminal.cpp 275 KB

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