Terminal.cpp 246 KB

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