Terminal.cpp 260 KB

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