Terminal.cpp 294 KB

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