Terminal.cpp 248 KB

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