Terminal.cpp 260 KB

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