Terminal.cpp 245 KB

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