Terminal.cpp 273 KB

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