Terminal.cpp 294 KB

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