Terminal.cpp 294 KB

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