Terminal.cpp 241 KB

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