Terminal.cpp 294 KB

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