Terminal.cpp 294 KB

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