Terminal.cpp 240 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790
  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. ChangeDirectory(SessionData->RemoteDirectory);
  3044. }
  3045. }
  3046. __finally
  3047. {
  3048. DoEndTransaction(true);
  3049. }
  3050. LogEvent(L"Startup conversation with host finished.");
  3051. }
  3052. //---------------------------------------------------------------------------
  3053. void __fastcall TTerminal::ReadCurrentDirectory()
  3054. {
  3055. DebugAssert(FFileSystem);
  3056. try
  3057. {
  3058. // reset flag is case we are called externally (like from console dialog)
  3059. FReadCurrentDirectoryPending = false;
  3060. LogEvent(L"Getting current directory name.");
  3061. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  3062. FFileSystem->ReadCurrentDirectory();
  3063. ReactOnCommand(fsCurrentDirectory);
  3064. if (SessionData->CacheDirectoryChanges)
  3065. {
  3066. DebugAssert(FDirectoryChangesCache != NULL);
  3067. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  3068. {
  3069. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  3070. FLastDirectoryChange, CurrentDirectory);
  3071. }
  3072. // not to broke the cache, if the next directory change would not
  3073. // be initialized by ChangeDirectory(), which sets it
  3074. // (HomeDirectory() particularly)
  3075. FLastDirectoryChange = L"";
  3076. }
  3077. if (OldDirectory.IsEmpty())
  3078. {
  3079. FLockDirectory = (SessionData->LockInHome ?
  3080. FFileSystem->CurrentDirectory : UnicodeString(L""));
  3081. }
  3082. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  3083. }
  3084. catch (Exception &E)
  3085. {
  3086. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  3087. }
  3088. }
  3089. //---------------------------------------------------------------------------
  3090. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  3091. {
  3092. bool LoadedFromCache = false;
  3093. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  3094. {
  3095. if (ReloadOnly && !ForceCache)
  3096. {
  3097. LogEvent(L"Cached directory not reloaded.");
  3098. }
  3099. else
  3100. {
  3101. DoStartReadDirectory();
  3102. try
  3103. {
  3104. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  3105. }
  3106. __finally
  3107. {
  3108. DoReadDirectory(ReloadOnly);
  3109. }
  3110. if (LoadedFromCache)
  3111. {
  3112. LogEvent(L"Directory content loaded from cache.");
  3113. }
  3114. else
  3115. {
  3116. LogEvent(L"Cached Directory content has been removed.");
  3117. }
  3118. }
  3119. }
  3120. if (!LoadedFromCache)
  3121. {
  3122. DoStartReadDirectory();
  3123. FReadingCurrentDirectory = true;
  3124. bool Cancel = false; // dummy
  3125. DoReadDirectoryProgress(0, 0, Cancel);
  3126. try
  3127. {
  3128. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  3129. try
  3130. {
  3131. Files->Directory = CurrentDirectory;
  3132. CustomReadDirectory(Files);
  3133. }
  3134. __finally
  3135. {
  3136. DoReadDirectoryProgress(-1, 0, Cancel);
  3137. FReadingCurrentDirectory = false;
  3138. TRemoteDirectory * OldFiles = FFiles;
  3139. FFiles = Files;
  3140. try
  3141. {
  3142. DoReadDirectory(ReloadOnly);
  3143. }
  3144. __finally
  3145. {
  3146. // delete only after loading new files to dir view,
  3147. // not to destroy the file objects that the view holds
  3148. // (can be issue in multi threaded environment, such as when the
  3149. // terminal is reconnecting in the terminal thread)
  3150. delete OldFiles;
  3151. }
  3152. if (Active)
  3153. {
  3154. if (SessionData->CacheDirectories)
  3155. {
  3156. DirectoryLoaded(FFiles);
  3157. }
  3158. }
  3159. }
  3160. }
  3161. catch (Exception &E)
  3162. {
  3163. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  3164. }
  3165. }
  3166. }
  3167. //---------------------------------------------------------------------------
  3168. UnicodeString __fastcall TTerminal::GetRemoteFileInfo(TRemoteFile * File)
  3169. {
  3170. return
  3171. FORMAT(L"%s;%s;%d;%s;%d;%s;%s;%s;%d",
  3172. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification), int(File->ModificationFmt),
  3173. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  3174. File->Attr));
  3175. }
  3176. //---------------------------------------------------------------------------
  3177. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  3178. {
  3179. // optimization
  3180. if (Log->Logging)
  3181. {
  3182. LogEvent(GetRemoteFileInfo(File));
  3183. }
  3184. }
  3185. //---------------------------------------------------------------------------
  3186. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  3187. {
  3188. UnicodeString Result;
  3189. // optimization
  3190. if (Log->Logging)
  3191. {
  3192. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  3193. }
  3194. return Result;
  3195. }
  3196. //---------------------------------------------------------------------------
  3197. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  3198. {
  3199. // optimization
  3200. if (Log->Logging)
  3201. {
  3202. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size))));
  3203. }
  3204. }
  3205. //---------------------------------------------------------------------------
  3206. void __fastcall TTerminal::LogFileDone(TFileOperationProgressType * OperationProgress, const UnicodeString & DestFileName)
  3207. {
  3208. if (FDestFileName.IsEmpty())
  3209. {
  3210. FDestFileName = DestFileName;
  3211. }
  3212. else
  3213. {
  3214. FMultipleDestinationFiles = true;
  3215. }
  3216. // optimization
  3217. if (Log->Logging)
  3218. {
  3219. LogEvent(FORMAT("Transfer done: '%s' => '%s' [%s]", (OperationProgress->FullFileName, DestFileName, IntToStr(OperationProgress->TransferredSize))));
  3220. }
  3221. }
  3222. //---------------------------------------------------------------------------
  3223. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  3224. {
  3225. DebugAssert(FileList);
  3226. DebugAssert(FFileSystem);
  3227. // To match FTP upload/download, we also limit directory listing.
  3228. // For simiplicity, we limit it unconditionally, for all protocols for any kind of errors.
  3229. bool FileTransferAny = false;
  3230. TRobustOperationLoop RobustLoop(this, OperationProgress, &FileTransferAny);
  3231. do
  3232. {
  3233. try
  3234. {
  3235. FFileSystem->ReadDirectory(FileList);
  3236. }
  3237. catch (Exception & E)
  3238. {
  3239. // Do not retry for initial listing of directory,
  3240. // we instead retry whole connection attempt,
  3241. // what would be done anyway (but Open is not ready for recursion).
  3242. if ((FOpening > 0) ||
  3243. !RobustLoop.TryReopen(E))
  3244. {
  3245. throw;
  3246. }
  3247. }
  3248. }
  3249. while (RobustLoop.Retry());
  3250. if (Log->Logging)
  3251. {
  3252. for (int Index = 0; Index < FileList->Count; Index++)
  3253. {
  3254. LogRemoteFile(FileList->Files[Index]);
  3255. }
  3256. }
  3257. ReactOnCommand(fsListDirectory);
  3258. }
  3259. //---------------------------------------------------------------------------
  3260. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  3261. {
  3262. TRemoteFileList * FileList;
  3263. TRetryOperationLoop RetryLoop(this);
  3264. do
  3265. {
  3266. FileList = NULL;
  3267. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  3268. try
  3269. {
  3270. FileList = DoReadDirectoryListing(Directory, false);
  3271. if (FileList != NULL)
  3272. {
  3273. int Index = 0;
  3274. while (Index < FileList->Count)
  3275. {
  3276. TRemoteFile * File = FileList->Files[Index];
  3277. TFileMasks::TParams Params;
  3278. Params.Size = File->Size;
  3279. Params.Modification = File->Modification;
  3280. // Have to use UnicodeString(), instead of L"", as with that
  3281. // overload with (UnicodeString, bool, bool, TParams*) wins
  3282. if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  3283. {
  3284. FileList->Delete(Index);
  3285. }
  3286. else
  3287. {
  3288. Index++;
  3289. }
  3290. }
  3291. Action.FileList(FileList);
  3292. }
  3293. }
  3294. catch(Exception & E)
  3295. {
  3296. RetryLoop.Error(E, Action);
  3297. }
  3298. }
  3299. while (RetryLoop.Retry());
  3300. return FileList;
  3301. }
  3302. //---------------------------------------------------------------------------
  3303. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  3304. {
  3305. TRemoteFile * File;
  3306. TRetryOperationLoop RetryLoop(this);
  3307. do
  3308. {
  3309. File = NULL;
  3310. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  3311. try
  3312. {
  3313. // reset caches
  3314. AnnounceFileListOperation();
  3315. ReadFile(Path, File);
  3316. Action.File(File);
  3317. }
  3318. catch(Exception & E)
  3319. {
  3320. RetryLoop.Error(E, Action);
  3321. }
  3322. }
  3323. while (RetryLoop.Retry());
  3324. return File;
  3325. }
  3326. //---------------------------------------------------------------------------
  3327. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  3328. {
  3329. TRemoteFileList * FileList = NULL;
  3330. TRetryOperationLoop RetryLoop(this);
  3331. do
  3332. {
  3333. try
  3334. {
  3335. FileList = DoReadDirectoryListing(Directory, UseCache);
  3336. }
  3337. catch(Exception & E)
  3338. {
  3339. RetryLoop.Error(E);
  3340. }
  3341. }
  3342. while (RetryLoop.Retry());
  3343. return FileList;
  3344. }
  3345. //---------------------------------------------------------------------------
  3346. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  3347. {
  3348. TRemoteFileList * FileList = new TRemoteFileList();
  3349. try
  3350. {
  3351. bool Cache = UseCache && SessionData->CacheDirectories;
  3352. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  3353. if (LoadedFromCache)
  3354. {
  3355. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  3356. }
  3357. if (!LoadedFromCache)
  3358. {
  3359. FileList->Directory = Directory;
  3360. ExceptionOnFail = true;
  3361. try
  3362. {
  3363. ReadDirectory(FileList);
  3364. }
  3365. __finally
  3366. {
  3367. ExceptionOnFail = false;
  3368. }
  3369. if (Cache)
  3370. {
  3371. AddCachedFileList(FileList);
  3372. }
  3373. }
  3374. }
  3375. catch(...)
  3376. {
  3377. delete FileList;
  3378. throw;
  3379. }
  3380. return FileList;
  3381. }
  3382. //---------------------------------------------------------------------------
  3383. bool __fastcall TTerminal::DeleteContentsIfDirectory(
  3384. const UnicodeString & FileName, const TRemoteFile * File, int Params, TRmSessionAction & Action)
  3385. {
  3386. bool Dir = (File != NULL) && File->IsDirectory && CanRecurseToDirectory(File);
  3387. if (Dir && FLAGCLEAR(Params, dfNoRecursive))
  3388. {
  3389. try
  3390. {
  3391. ProcessDirectory(FileName, DeleteFile, &Params);
  3392. }
  3393. catch(...)
  3394. {
  3395. Action.Cancel();
  3396. throw;
  3397. }
  3398. }
  3399. return Dir;
  3400. }
  3401. //---------------------------------------------------------------------------
  3402. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  3403. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  3404. {
  3405. TRemoteFileList * FileList = NULL;
  3406. if (IgnoreErrors)
  3407. {
  3408. ExceptionOnFail = true;
  3409. try
  3410. {
  3411. try
  3412. {
  3413. FileList = CustomReadDirectoryListing(DirName, UseCache);
  3414. }
  3415. catch(...)
  3416. {
  3417. if (!Active)
  3418. {
  3419. throw;
  3420. }
  3421. }
  3422. }
  3423. __finally
  3424. {
  3425. ExceptionOnFail = false;
  3426. }
  3427. }
  3428. else
  3429. {
  3430. FileList = CustomReadDirectoryListing(DirName, UseCache);
  3431. }
  3432. // skip if directory listing fails and user selects "skip"
  3433. if (FileList)
  3434. {
  3435. try
  3436. {
  3437. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  3438. TRemoteFile * File;
  3439. for (int Index = 0; Index < FileList->Count; Index++)
  3440. {
  3441. File = FileList->Files[Index];
  3442. if (!File->IsParentDirectory && !File->IsThisDirectory)
  3443. {
  3444. CallBackFunc(Directory + File->FileName, File, Param);
  3445. // We should catch ESkipFile here as we do in ProcessFiles.
  3446. // Now we have to handle ESkipFile in every callback implementation.
  3447. }
  3448. }
  3449. }
  3450. __finally
  3451. {
  3452. delete FileList;
  3453. }
  3454. }
  3455. }
  3456. //---------------------------------------------------------------------------
  3457. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  3458. {
  3459. try
  3460. {
  3461. CustomReadDirectory(FileList);
  3462. }
  3463. catch (Exception &E)
  3464. {
  3465. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  3466. }
  3467. }
  3468. //---------------------------------------------------------------------------
  3469. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  3470. TRemoteFile *& File)
  3471. {
  3472. DebugAssert(FFileSystem);
  3473. try
  3474. {
  3475. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  3476. FFileSystem->ReadSymlink(SymlinkFile, File);
  3477. ReactOnCommand(fsReadSymlink);
  3478. }
  3479. catch (Exception &E)
  3480. {
  3481. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  3482. }
  3483. }
  3484. //---------------------------------------------------------------------------
  3485. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  3486. TRemoteFile *& File)
  3487. {
  3488. DebugAssert(FFileSystem);
  3489. File = NULL;
  3490. try
  3491. {
  3492. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  3493. FFileSystem->ReadFile(FileName, File);
  3494. ReactOnCommand(fsListFile);
  3495. LogRemoteFile(File);
  3496. }
  3497. catch (Exception &E)
  3498. {
  3499. if (File) delete File;
  3500. File = NULL;
  3501. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3502. }
  3503. }
  3504. //---------------------------------------------------------------------------
  3505. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  3506. {
  3507. bool Result;
  3508. TRemoteFile * File = NULL;
  3509. try
  3510. {
  3511. ExceptionOnFail = true;
  3512. try
  3513. {
  3514. ReadFile(UnixExcludeTrailingBackslash(FileName), File);
  3515. }
  3516. __finally
  3517. {
  3518. ExceptionOnFail = false;
  3519. }
  3520. if (AFile != NULL)
  3521. {
  3522. *AFile = File;
  3523. }
  3524. else
  3525. {
  3526. delete File;
  3527. }
  3528. Result = true;
  3529. }
  3530. catch(...)
  3531. {
  3532. if (Active)
  3533. {
  3534. Result = false;
  3535. }
  3536. else
  3537. {
  3538. throw;
  3539. }
  3540. }
  3541. return Result;
  3542. }
  3543. //---------------------------------------------------------------------------
  3544. void __fastcall TTerminal::AnnounceFileListOperation()
  3545. {
  3546. FFileSystem->AnnounceFileListOperation();
  3547. }
  3548. //---------------------------------------------------------------------------
  3549. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  3550. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  3551. TOperationSide Side, bool Ex)
  3552. {
  3553. DebugAssert(FileList);
  3554. bool Result = false;
  3555. TOnceDoneOperation OnceDoneOperation = odoIdle;
  3556. try
  3557. {
  3558. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  3559. Progress.Start(Operation, Side, FileList->Count);
  3560. FOperationProgress = &Progress;
  3561. try
  3562. {
  3563. if (Side == osRemote)
  3564. {
  3565. DebugAssert(FFileSystem != NULL);
  3566. BeginTransaction();
  3567. }
  3568. try
  3569. {
  3570. int Index = 0;
  3571. UnicodeString FileName;
  3572. bool Success;
  3573. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  3574. {
  3575. FileName = FileList->Strings[Index];
  3576. try
  3577. {
  3578. try
  3579. {
  3580. Success = false;
  3581. if (!Ex)
  3582. {
  3583. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  3584. }
  3585. else
  3586. {
  3587. // not used anymore
  3588. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  3589. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  3590. }
  3591. Success = true;
  3592. }
  3593. __finally
  3594. {
  3595. Progress.Finish(FileName, Success, OnceDoneOperation);
  3596. }
  3597. }
  3598. catch(ESkipFile & E)
  3599. {
  3600. TSuspendFileOperationProgress Suspend(OperationProgress);
  3601. if (!HandleException(&E))
  3602. {
  3603. throw;
  3604. }
  3605. }
  3606. Index++;
  3607. }
  3608. }
  3609. __finally
  3610. {
  3611. if (Side == osRemote)
  3612. {
  3613. EndTransaction();
  3614. }
  3615. }
  3616. if (Progress.Cancel == csContinue)
  3617. {
  3618. Result = true;
  3619. }
  3620. }
  3621. __finally
  3622. {
  3623. FOperationProgress = NULL;
  3624. Progress.Stop();
  3625. }
  3626. }
  3627. catch (...)
  3628. {
  3629. OnceDoneOperation = odoIdle;
  3630. // this was missing here. was it by purpose?
  3631. // without it any error message is lost
  3632. throw;
  3633. }
  3634. if (OnceDoneOperation != odoIdle)
  3635. {
  3636. CloseOnCompletion(OnceDoneOperation);
  3637. }
  3638. return Result;
  3639. }
  3640. //---------------------------------------------------------------------------
  3641. // not used anymore
  3642. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  3643. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  3644. {
  3645. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  3646. Param, Side, true);
  3647. }
  3648. //---------------------------------------------------------------------------
  3649. TStrings * __fastcall TTerminal::GetFixedPaths()
  3650. {
  3651. DebugAssert(FFileSystem != NULL);
  3652. return FFileSystem->GetFixedPaths();
  3653. }
  3654. //---------------------------------------------------------------------------
  3655. bool __fastcall TTerminal::GetResolvingSymlinks()
  3656. {
  3657. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  3658. }
  3659. //---------------------------------------------------------------------------
  3660. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  3661. {
  3662. TUsableCopyParamAttrs Result;
  3663. Result.General =
  3664. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  3665. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  3666. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  3667. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  3668. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  3669. // the following three are never supported for download,
  3670. // so when they are not suppored for upload too,
  3671. // set them in General flags, so that they do not get enabled on
  3672. // Synchronize dialog.
  3673. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  3674. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  3675. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM) |
  3676. FLAGMASK(!IsCapable[fcPreservingTimestampDirs], cpaNoPreserveTimeDirs) |
  3677. FLAGMASK(!IsCapable[fcResumeSupport], cpaNoResumeSupport);
  3678. Result.Download = Result.General | cpaNoClearArchive |
  3679. cpaNoIgnorePermErrors |
  3680. // May be already set in General flags, but it's unconditional here
  3681. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM;
  3682. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  3683. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  3684. return Result;
  3685. }
  3686. //---------------------------------------------------------------------------
  3687. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  3688. {
  3689. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  3690. if (Result)
  3691. {
  3692. UnicodeString Path = UnixExtractFilePath(FileName);
  3693. if (Path.IsEmpty())
  3694. {
  3695. Path = CurrentDirectory;
  3696. }
  3697. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  3698. }
  3699. return Result;
  3700. }
  3701. //---------------------------------------------------------------------------
  3702. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  3703. const TRemoteFile * File)
  3704. {
  3705. if (FileName.IsEmpty())
  3706. {
  3707. DebugAssert(File != NULL);
  3708. FileName = File->FileName;
  3709. }
  3710. if (!IsRecycledFile(FileName))
  3711. {
  3712. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  3713. (FileName, SessionData->RecycleBinPath)));
  3714. TMoveFileParams Params;
  3715. Params.Target = SessionData->RecycleBinPath;
  3716. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  3717. MoveFile(FileName, File, &Params);
  3718. }
  3719. }
  3720. //---------------------------------------------------------------------------
  3721. bool __fastcall TTerminal::TryStartOperationWithFile(
  3722. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3723. {
  3724. bool Result = true;
  3725. if ((OperationProgress != NULL) &&
  3726. ((OperationProgress->Operation == Operation1) ||
  3727. ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
  3728. {
  3729. if (OperationProgress->Cancel != csContinue)
  3730. {
  3731. Result = false;
  3732. }
  3733. else
  3734. {
  3735. OperationProgress->SetFile(FileName);
  3736. }
  3737. }
  3738. return Result;
  3739. }
  3740. //---------------------------------------------------------------------------
  3741. void __fastcall TTerminal::StartOperationWithFile(
  3742. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3743. {
  3744. if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
  3745. {
  3746. Abort();
  3747. }
  3748. }
  3749. //---------------------------------------------------------------------------
  3750. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  3751. const TRemoteFile * File, void * AParams)
  3752. {
  3753. if (FileName.IsEmpty() && File)
  3754. {
  3755. FileName = File->FileName;
  3756. }
  3757. StartOperationWithFile(FileName, foDelete);
  3758. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  3759. bool Recycle =
  3760. FLAGCLEAR(Params, dfForceDelete) &&
  3761. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  3762. !SessionData->RecycleBinPath.IsEmpty();
  3763. if (Recycle && !IsRecycledFile(FileName))
  3764. {
  3765. RecycleFile(FileName, File);
  3766. }
  3767. else
  3768. {
  3769. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  3770. FileModified(File, FileName, true);
  3771. DoDeleteFile(FileName, File, Params);
  3772. ReactOnCommand(fsDeleteFile);
  3773. }
  3774. }
  3775. //---------------------------------------------------------------------------
  3776. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  3777. const TRemoteFile * File, int Params)
  3778. {
  3779. TRetryOperationLoop RetryLoop(this);
  3780. do
  3781. {
  3782. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3783. try
  3784. {
  3785. DebugAssert(FFileSystem);
  3786. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  3787. FFileSystem->DeleteFile(FileName, File, Params, Action);
  3788. }
  3789. catch(Exception & E)
  3790. {
  3791. RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  3792. }
  3793. }
  3794. while (RetryLoop.Retry());
  3795. }
  3796. //---------------------------------------------------------------------------
  3797. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  3798. {
  3799. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3800. FUseBusyCursor = false;
  3801. // TODO: avoid resolving symlinks while reading subdirectories.
  3802. // Resolving does not work anyway for relative symlinks in subdirectories
  3803. // (at least for SFTP).
  3804. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  3805. }
  3806. //---------------------------------------------------------------------------
  3807. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  3808. const TRemoteFile * /*File*/, void * Params)
  3809. {
  3810. StartOperationWithFile(FileName, foDelete);
  3811. if (OnDeleteLocalFile == NULL)
  3812. {
  3813. RecursiveDeleteFileChecked(FileName, false);
  3814. }
  3815. else
  3816. {
  3817. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  3818. }
  3819. }
  3820. //---------------------------------------------------------------------------
  3821. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  3822. {
  3823. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  3824. }
  3825. //---------------------------------------------------------------------------
  3826. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  3827. const TRemoteFile * File, void * AParams)
  3828. {
  3829. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3830. if (FileName.IsEmpty() && File)
  3831. {
  3832. FileName = File->FileName;
  3833. }
  3834. StartOperationWithFile(FileName, foCustomCommand);
  3835. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3836. (Params->Command, Params->Params, FileName)));
  3837. FileModified(File, FileName);
  3838. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3839. Params->OutputEvent);
  3840. ReactOnCommand(fsAnyCommand);
  3841. }
  3842. //---------------------------------------------------------------------------
  3843. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  3844. const TRemoteFile * File, UnicodeString Command, int Params,
  3845. TCaptureOutputEvent OutputEvent)
  3846. {
  3847. TRetryOperationLoop RetryLoop(this);
  3848. do
  3849. {
  3850. try
  3851. {
  3852. if (IsCapable[fcAnyCommand])
  3853. {
  3854. DebugAssert(FFileSystem);
  3855. DebugAssert(fcShellAnyCommand);
  3856. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  3857. }
  3858. else
  3859. {
  3860. DebugAssert(CommandSessionOpened);
  3861. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  3862. LogEvent(L"Executing custom command on command session.");
  3863. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  3864. {
  3865. FCommandSession->CurrentDirectory = CurrentDirectory;
  3866. // We are likely in transaction, so ReadCurrentDirectory won't get called
  3867. // until transaction ends. But we need to know CurrentDirectory to
  3868. // expand !/ pattern.
  3869. // Doing this only, when current directory of the main and secondary shell differs,
  3870. // what would be the case before the first file in transaction.
  3871. // Otherwise we would be reading pwd before every time as the
  3872. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  3873. if (FCommandSession->FReadCurrentDirectoryPending)
  3874. {
  3875. FCommandSession->ReadCurrentDirectory();
  3876. }
  3877. }
  3878. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  3879. Params, OutputEvent);
  3880. }
  3881. }
  3882. catch(Exception & E)
  3883. {
  3884. RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
  3885. }
  3886. }
  3887. while (RetryLoop.Retry());
  3888. }
  3889. //---------------------------------------------------------------------------
  3890. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  3891. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  3892. {
  3893. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  3894. {
  3895. TCustomCommandParams AParams;
  3896. AParams.Command = Command;
  3897. AParams.Params = Params;
  3898. AParams.OutputEvent = OutputEvent;
  3899. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  3900. }
  3901. else
  3902. {
  3903. UnicodeString FileList;
  3904. for (int i = 0; i < Files->Count; i++)
  3905. {
  3906. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  3907. bool Dir = File->IsDirectory && CanRecurseToDirectory(File);
  3908. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  3909. {
  3910. if (!FileList.IsEmpty())
  3911. {
  3912. FileList += L" ";
  3913. }
  3914. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  3915. }
  3916. }
  3917. TCustomCommandData Data(this);
  3918. UnicodeString Cmd =
  3919. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  3920. Complete(Command, true);
  3921. if (!DoOnCustomCommand(Cmd))
  3922. {
  3923. DoAnyCommand(Cmd, OutputEvent, NULL);
  3924. }
  3925. }
  3926. }
  3927. //---------------------------------------------------------------------------
  3928. bool __fastcall TTerminal::DoOnCustomCommand(const UnicodeString & Command)
  3929. {
  3930. bool Result = false;
  3931. if (FOnCustomCommand != NULL)
  3932. {
  3933. FOnCustomCommand(this, Command, Result);
  3934. }
  3935. return Result;
  3936. }
  3937. //---------------------------------------------------------------------------
  3938. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  3939. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  3940. {
  3941. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  3942. DebugAssert(RProperties && !RProperties->Valid.Empty());
  3943. if (FileName.IsEmpty() && File)
  3944. {
  3945. FileName = File->FileName;
  3946. }
  3947. StartOperationWithFile(FileName, foSetProperties);
  3948. if (Log->Logging)
  3949. {
  3950. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  3951. (FileName, BooleanToEngStr(RProperties->Recursive))));
  3952. if (RProperties->Valid.Contains(vpRights))
  3953. {
  3954. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  3955. }
  3956. if (RProperties->Valid.Contains(vpGroup))
  3957. {
  3958. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  3959. }
  3960. if (RProperties->Valid.Contains(vpOwner))
  3961. {
  3962. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  3963. }
  3964. if (RProperties->Valid.Contains(vpModification))
  3965. {
  3966. LogEvent(FORMAT(L" - modification: \"%s\"",
  3967. (FormatDateTime(L"dddddd tt",
  3968. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  3969. }
  3970. if (RProperties->Valid.Contains(vpLastAccess))
  3971. {
  3972. LogEvent(FORMAT(L" - last access: \"%s\"",
  3973. (FormatDateTime(L"dddddd tt",
  3974. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  3975. }
  3976. }
  3977. FileModified(File, FileName);
  3978. DoChangeFileProperties(FileName, File, RProperties);
  3979. ReactOnCommand(fsChangeProperties);
  3980. }
  3981. //---------------------------------------------------------------------------
  3982. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  3983. const TRemoteFile * File, const TRemoteProperties * Properties)
  3984. {
  3985. TRetryOperationLoop RetryLoop(this);
  3986. do
  3987. {
  3988. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3989. try
  3990. {
  3991. DebugAssert(FFileSystem);
  3992. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  3993. }
  3994. catch(Exception & E)
  3995. {
  3996. RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
  3997. }
  3998. }
  3999. while (RetryLoop.Retry());
  4000. }
  4001. //---------------------------------------------------------------------------
  4002. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  4003. const TRemoteProperties * Properties)
  4004. {
  4005. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4006. FUseBusyCursor = false;
  4007. AnnounceFileListOperation();
  4008. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  4009. }
  4010. //---------------------------------------------------------------------------
  4011. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  4012. {
  4013. // see comment in TSFTPFileSystem::IsCapable
  4014. bool Result =
  4015. IsCapable[fcLoadingAdditionalProperties] &&
  4016. FFileSystem->LoadFilesProperties(FileList);
  4017. if (Result && SessionData->CacheDirectories &&
  4018. (FileList->Count > 0) &&
  4019. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  4020. {
  4021. AddCachedFileList(FFiles);
  4022. }
  4023. return Result;
  4024. }
  4025. //---------------------------------------------------------------------------
  4026. void __fastcall TTerminal::DoCalculateFileSize(UnicodeString FileName,
  4027. const TRemoteFile * File, void * Param)
  4028. {
  4029. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  4030. if (AParams->Stats->FoundFiles != NULL)
  4031. {
  4032. UnicodeString DirPath = UnixExtractFilePath(UnixExcludeTrailingBackslash(File->FullFileName));
  4033. if ((DirPath != AParams->LastDirPath) ||
  4034. (AParams->Files == NULL))
  4035. {
  4036. AParams->Files = new TCollectedFileList();
  4037. AParams->LastDirPath = DirPath;
  4038. AParams->Stats->FoundFiles->AddObject(AParams->LastDirPath, AParams->Files);
  4039. }
  4040. }
  4041. CalculateFileSize(FileName, File, Param);
  4042. }
  4043. //---------------------------------------------------------------------------
  4044. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  4045. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  4046. {
  4047. DebugAssert(Param);
  4048. DebugAssert(File);
  4049. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  4050. if (FileName.IsEmpty())
  4051. {
  4052. FileName = File->FileName;
  4053. }
  4054. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  4055. {
  4056. AParams->Result = false;
  4057. // Combined with csIgnoreErrors, this will not abort completelly, but we get called again
  4058. // with next sibling of our parent directory (and we get again to this branch, throwing again)
  4059. Abort();
  4060. }
  4061. bool AllowTransfer = (AParams->CopyParam == NULL);
  4062. if (!AllowTransfer)
  4063. {
  4064. TFileMasks::TParams MaskParams;
  4065. MaskParams.Size = File->Size;
  4066. MaskParams.Modification = File->Modification;
  4067. UnicodeString BaseFileName =
  4068. GetBaseFileName(UnixExcludeTrailingBackslash(File->FullFileName));
  4069. AllowTransfer = AParams->CopyParam->AllowTransfer(
  4070. BaseFileName, osRemote, File->IsDirectory, MaskParams);
  4071. }
  4072. if (AllowTransfer)
  4073. {
  4074. int CollectionIndex = -1;
  4075. if (AParams->Files != NULL)
  4076. {
  4077. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  4078. CollectionIndex = AParams->Files->Add(FullFileName, File->Duplicate(), File->IsDirectory);
  4079. }
  4080. if (File->IsDirectory)
  4081. {
  4082. if (CanRecurseToDirectory(File))
  4083. {
  4084. if (!AParams->AllowDirs)
  4085. {
  4086. AParams->Result = false;
  4087. }
  4088. else
  4089. {
  4090. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  4091. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  4092. if (!DoCalculateDirectorySize(File->FullFileName, File, AParams))
  4093. {
  4094. if (CollectionIndex >= 0)
  4095. {
  4096. AParams->Files->DidNotRecurse(CollectionIndex);
  4097. }
  4098. }
  4099. }
  4100. }
  4101. AParams->Stats->Directories++;
  4102. }
  4103. else
  4104. {
  4105. AParams->Size += File->Size;
  4106. AParams->Stats->Files++;
  4107. }
  4108. if (File->IsSymLink)
  4109. {
  4110. AParams->Stats->SymLinks++;
  4111. }
  4112. }
  4113. }
  4114. //---------------------------------------------------------------------------
  4115. bool __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  4116. const TRemoteFile * /*File*/, TCalculateSizeParams * Params)
  4117. {
  4118. bool Result = false;
  4119. TRetryOperationLoop RetryLoop(this);
  4120. do
  4121. {
  4122. try
  4123. {
  4124. ProcessDirectory(FileName, CalculateFileSize, Params);
  4125. Result = true;
  4126. }
  4127. catch(Exception & E)
  4128. {
  4129. // We can probably replace the csIgnoreErrors with IgnoreErrors argument of the ProcessDirectory
  4130. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  4131. {
  4132. RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
  4133. }
  4134. }
  4135. }
  4136. while (RetryLoop.Retry());
  4137. return Result;
  4138. }
  4139. //---------------------------------------------------------------------------
  4140. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  4141. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  4142. bool AllowDirs, TCalculateSizeStats & Stats)
  4143. {
  4144. // With FTP protocol, we may use DSIZ command from
  4145. // draft-peterson-streamlined-ftp-command-extensions-10
  4146. // Implemented by Serv-U FTP.
  4147. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4148. FUseBusyCursor = false;
  4149. TCalculateSizeParams Param;
  4150. Param.Size = 0;
  4151. Param.Params = Params;
  4152. Param.CopyParam = CopyParam;
  4153. Param.Stats = &Stats;
  4154. Param.AllowDirs = AllowDirs;
  4155. Param.Result = true;
  4156. Param.Files = NULL;
  4157. ProcessFiles(FileList, foCalculateSize, DoCalculateFileSize, &Param);
  4158. Size = Param.Size;
  4159. return Param.Result;
  4160. }
  4161. //---------------------------------------------------------------------------
  4162. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  4163. TStrings * FileList, TStrings * Checksums,
  4164. TCalculatedChecksumEvent OnCalculatedChecksum)
  4165. {
  4166. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  4167. }
  4168. //---------------------------------------------------------------------------
  4169. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  4170. const UnicodeString NewName, bool CheckExistence)
  4171. {
  4172. DebugAssert(File && File->Directory == FFiles);
  4173. bool Proceed = true;
  4174. // if filename doesn't contain path, we check for existence of file
  4175. if ((File->FileName != NewName) && CheckExistence &&
  4176. Configuration->ConfirmOverwriting &&
  4177. UnixSamePath(CurrentDirectory, FFiles->Directory))
  4178. {
  4179. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  4180. if (DuplicateFile)
  4181. {
  4182. UnicodeString QuestionFmt;
  4183. if (DuplicateFile->IsDirectory)
  4184. {
  4185. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  4186. }
  4187. else
  4188. {
  4189. QuestionFmt = LoadStr(FILE_OVERWRITE);
  4190. }
  4191. TQueryParams Params(qpNeverAskAgainCheck);
  4192. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  4193. unsigned int Result = QueryUser(Question, NULL,
  4194. qaYes | qaNo, &Params);
  4195. if (Result == qaNeverAskAgain)
  4196. {
  4197. Proceed = true;
  4198. Configuration->ConfirmOverwriting = false;
  4199. }
  4200. else
  4201. {
  4202. Proceed = (Result == qaYes);
  4203. }
  4204. }
  4205. }
  4206. if (Proceed)
  4207. {
  4208. FileModified(File, File->FileName);
  4209. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (File->FileName, NewName)));
  4210. DoRenameFile(File->FileName, File, NewName, false);
  4211. ReactOnCommand(fsRenameFile);
  4212. }
  4213. }
  4214. //---------------------------------------------------------------------------
  4215. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName, const TRemoteFile * File,
  4216. const UnicodeString NewName, bool Move)
  4217. {
  4218. TRetryOperationLoop RetryLoop(this);
  4219. do
  4220. {
  4221. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  4222. try
  4223. {
  4224. DebugAssert(FFileSystem);
  4225. FFileSystem->RenameFile(FileName, File, NewName);
  4226. }
  4227. catch(Exception & E)
  4228. {
  4229. UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
  4230. RetryLoop.Error(E, Action, Message);
  4231. }
  4232. }
  4233. while (RetryLoop.Retry());
  4234. }
  4235. //---------------------------------------------------------------------------
  4236. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  4237. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4238. {
  4239. StartOperationWithFile(FileName, foRemoteMove, foDelete);
  4240. DebugAssert(Param != NULL);
  4241. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  4242. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  4243. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  4244. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  4245. FileModified(File, FileName);
  4246. DoRenameFile(FileName, File, NewName, true);
  4247. ReactOnCommand(fsMoveFile);
  4248. }
  4249. //---------------------------------------------------------------------------
  4250. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  4251. const UnicodeString FileMask)
  4252. {
  4253. TMoveFileParams Params;
  4254. Params.Target = Target;
  4255. Params.FileMask = FileMask;
  4256. DirectoryModified(Target, true);
  4257. bool Result;
  4258. BeginTransaction();
  4259. try
  4260. {
  4261. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  4262. }
  4263. __finally
  4264. {
  4265. if (Active)
  4266. {
  4267. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  4268. bool PossiblyMoved = false;
  4269. // check if we was moving current directory.
  4270. // this is just optimization to avoid checking existence of current
  4271. // directory after each move operation.
  4272. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  4273. {
  4274. const TRemoteFile * File =
  4275. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  4276. // File can be NULL, and filename may not be full path,
  4277. // but currently this is the only way we can move (at least in GUI)
  4278. // current directory
  4279. if ((File != NULL) &&
  4280. File->IsDirectory &&
  4281. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  4282. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  4283. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  4284. {
  4285. PossiblyMoved = true;
  4286. }
  4287. }
  4288. if (PossiblyMoved && !FileExists(CurrentDirectory))
  4289. {
  4290. UnicodeString NearestExisting = CurrentDirectory;
  4291. do
  4292. {
  4293. NearestExisting = UnixExtractFileDir(NearestExisting);
  4294. }
  4295. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  4296. ChangeDirectory(NearestExisting);
  4297. }
  4298. }
  4299. EndTransaction();
  4300. }
  4301. return Result;
  4302. }
  4303. //---------------------------------------------------------------------------
  4304. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName, const TRemoteFile * File,
  4305. const UnicodeString NewName)
  4306. {
  4307. TRetryOperationLoop RetryLoop(this);
  4308. do
  4309. {
  4310. TCpSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  4311. try
  4312. {
  4313. DebugAssert(FFileSystem);
  4314. if (IsCapable[fcRemoteCopy])
  4315. {
  4316. FFileSystem->CopyFile(FileName, File, NewName);
  4317. }
  4318. else
  4319. {
  4320. DebugAssert(CommandSessionOpened);
  4321. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  4322. LogEvent(L"Copying file on command session.");
  4323. FCommandSession->CurrentDirectory = CurrentDirectory;
  4324. FCommandSession->FFileSystem->CopyFile(FileName, File, NewName);
  4325. }
  4326. }
  4327. catch(Exception & E)
  4328. {
  4329. RetryLoop.Error(E, Action, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
  4330. }
  4331. }
  4332. while (RetryLoop.Retry());
  4333. }
  4334. //---------------------------------------------------------------------------
  4335. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  4336. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4337. {
  4338. StartOperationWithFile(FileName, foRemoteCopy);
  4339. DebugAssert(Param != NULL);
  4340. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  4341. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  4342. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  4343. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  4344. DoCopyFile(FileName, File, NewName);
  4345. ReactOnCommand(fsCopyFile);
  4346. }
  4347. //---------------------------------------------------------------------------
  4348. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  4349. const UnicodeString FileMask)
  4350. {
  4351. TMoveFileParams Params;
  4352. Params.Target = Target;
  4353. Params.FileMask = FileMask;
  4354. DirectoryModified(Target, true);
  4355. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  4356. }
  4357. //---------------------------------------------------------------------------
  4358. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  4359. const TRemoteProperties * Properties)
  4360. {
  4361. DebugAssert(FFileSystem);
  4362. EnsureNonExistence(DirName);
  4363. FileModified(NULL, DirName);
  4364. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  4365. DoCreateDirectory(DirName);
  4366. if ((Properties != NULL) && !Properties->Valid.Empty())
  4367. {
  4368. DoChangeFileProperties(DirName, NULL, Properties);
  4369. }
  4370. ReactOnCommand(fsCreateDirectory);
  4371. }
  4372. //---------------------------------------------------------------------------
  4373. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  4374. {
  4375. TRetryOperationLoop RetryLoop(this);
  4376. do
  4377. {
  4378. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  4379. try
  4380. {
  4381. DebugAssert(FFileSystem);
  4382. FFileSystem->CreateDirectory(DirName);
  4383. }
  4384. catch(Exception & E)
  4385. {
  4386. RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
  4387. }
  4388. }
  4389. while (RetryLoop.Retry());
  4390. }
  4391. //---------------------------------------------------------------------------
  4392. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  4393. const UnicodeString PointTo, bool Symbolic)
  4394. {
  4395. DebugAssert(FFileSystem);
  4396. EnsureNonExistence(FileName);
  4397. if (SessionData->CacheDirectories)
  4398. {
  4399. DirectoryModified(CurrentDirectory, false);
  4400. }
  4401. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  4402. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  4403. DoCreateLink(FileName, PointTo, Symbolic);
  4404. ReactOnCommand(fsCreateDirectory);
  4405. }
  4406. //---------------------------------------------------------------------------
  4407. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  4408. const UnicodeString PointTo, bool Symbolic)
  4409. {
  4410. TRetryOperationLoop RetryLoop(this);
  4411. do
  4412. {
  4413. try
  4414. {
  4415. DebugAssert(FFileSystem);
  4416. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  4417. }
  4418. catch(Exception & E)
  4419. {
  4420. RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
  4421. }
  4422. }
  4423. while (RetryLoop.Retry());
  4424. }
  4425. //---------------------------------------------------------------------------
  4426. void __fastcall TTerminal::HomeDirectory()
  4427. {
  4428. DebugAssert(FFileSystem);
  4429. try
  4430. {
  4431. LogEvent(L"Changing directory to home directory.");
  4432. FFileSystem->HomeDirectory();
  4433. ReactOnCommand(fsHomeDirectory);
  4434. }
  4435. catch (Exception &E)
  4436. {
  4437. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  4438. }
  4439. }
  4440. //---------------------------------------------------------------------------
  4441. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  4442. {
  4443. DebugAssert(FFileSystem);
  4444. try
  4445. {
  4446. UnicodeString CachedDirectory;
  4447. DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  4448. // never use directory change cache during startup, this ensures, we never
  4449. // end-up initially in non-existing directory
  4450. if ((Status == ssOpened) &&
  4451. SessionData->CacheDirectoryChanges &&
  4452. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  4453. Directory, CachedDirectory))
  4454. {
  4455. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  4456. (Directory, CachedDirectory)));
  4457. FFileSystem->CachedChangeDirectory(CachedDirectory);
  4458. }
  4459. else
  4460. {
  4461. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  4462. FFileSystem->ChangeDirectory(Directory);
  4463. }
  4464. FLastDirectoryChange = Directory;
  4465. ReactOnCommand(fsChangeDirectory);
  4466. }
  4467. catch (Exception &E)
  4468. {
  4469. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  4470. }
  4471. }
  4472. //---------------------------------------------------------------------------
  4473. void __fastcall TTerminal::LookupUsersGroups()
  4474. {
  4475. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  4476. IsCapable[fcUserGroupListing])
  4477. {
  4478. DebugAssert(FFileSystem);
  4479. try
  4480. {
  4481. FUsersGroupsLookedup = true;
  4482. LogEvent(L"Looking up groups and users.");
  4483. FFileSystem->LookupUsersGroups();
  4484. ReactOnCommand(fsLookupUsersGroups);
  4485. if (Log->Logging)
  4486. {
  4487. FGroups.Log(this, L"groups");
  4488. FMembership.Log(this, L"membership");
  4489. FUsers.Log(this, L"users");
  4490. }
  4491. }
  4492. catch (Exception &E)
  4493. {
  4494. if (!Active || (SessionData->LookupUserGroups == asOn))
  4495. {
  4496. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  4497. }
  4498. }
  4499. }
  4500. }
  4501. //---------------------------------------------------------------------------
  4502. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  4503. {
  4504. return !Command.Trim().IsEmpty();
  4505. }
  4506. //---------------------------------------------------------------------------
  4507. bool __fastcall TTerminal::GetCommandSessionOpened()
  4508. {
  4509. // consider secondary terminal open in "ready" state only
  4510. // so we never do keepalives on it until it is completely initialized
  4511. return (FCommandSession != NULL) &&
  4512. (FCommandSession->Status == ssOpened);
  4513. }
  4514. //---------------------------------------------------------------------------
  4515. TTerminal * __fastcall TTerminal::CreateSecondarySession(const UnicodeString & Name, TSessionData * SessionData)
  4516. {
  4517. std::unique_ptr<TTerminal> Result(new TSecondaryTerminal(this, SessionData, Configuration, Name));
  4518. Result->AutoReadDirectory = false;
  4519. Result->FExceptionOnFail = FExceptionOnFail;
  4520. Result->OnQueryUser = OnQueryUser;
  4521. Result->OnPromptUser = OnPromptUser;
  4522. Result->OnShowExtendedException = OnShowExtendedException;
  4523. Result->OnProgress = OnProgress;
  4524. Result->OnFinished = OnFinished;
  4525. Result->OnInformation = OnInformation;
  4526. Result->OnCustomCommand = OnCustomCommand;
  4527. // do not copy OnDisplayBanner to avoid it being displayed
  4528. return Result.release();
  4529. }
  4530. //---------------------------------------------------------------------------
  4531. void __fastcall TTerminal::FillSessionDataForCode(TSessionData * Data)
  4532. {
  4533. const TSessionInfo & SessionInfo = GetSessionInfo();
  4534. if (!SessionInfo.HostKeyFingerprintSHA256.IsEmpty())
  4535. {
  4536. Data->HostKey = SessionInfo.HostKeyFingerprintSHA256;
  4537. }
  4538. else if (!SessionInfo.CertificateFingerprint.IsEmpty())
  4539. {
  4540. Data->HostKey = SessionInfo.CertificateFingerprint;
  4541. }
  4542. }
  4543. //---------------------------------------------------------------------------
  4544. TTerminal * __fastcall TTerminal::GetCommandSession()
  4545. {
  4546. if ((FCommandSession != NULL) && !FCommandSession->Active)
  4547. {
  4548. SAFE_DESTROY(FCommandSession);
  4549. }
  4550. if (FCommandSession == NULL)
  4551. {
  4552. // transaction cannot be started yet to allow proper matching transaction
  4553. // levels between main and command session
  4554. DebugAssert(FInTransaction == 0);
  4555. std::unique_ptr<TSessionData> CommandSessionData(SessionData->Clone());
  4556. CommandSessionData->RemoteDirectory = CurrentDirectory;
  4557. CommandSessionData->FSProtocol = fsSCPonly;
  4558. CommandSessionData->ClearAliases = false;
  4559. CommandSessionData->UnsetNationalVars = false;
  4560. CommandSessionData->LookupUserGroups = asOff;
  4561. FCommandSession = CreateSecondarySession(L"Shell", CommandSessionData.get());
  4562. FCommandSession->AutoReadDirectory = false;
  4563. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  4564. FCommandSession->OnQueryUser = OnQueryUser;
  4565. FCommandSession->OnPromptUser = OnPromptUser;
  4566. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  4567. FCommandSession->OnProgress = OnProgress;
  4568. FCommandSession->OnFinished = OnFinished;
  4569. FCommandSession->OnInformation = OnInformation;
  4570. FCommandSession->OnCustomCommand = OnCustomCommand;
  4571. // do not copy OnDisplayBanner to avoid it being displayed
  4572. }
  4573. return FCommandSession;
  4574. }
  4575. //---------------------------------------------------------------------------
  4576. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  4577. TCaptureOutputEvent OutputEvent)
  4578. {
  4579. #pragma warn -inl
  4580. class TOutputProxy
  4581. {
  4582. public:
  4583. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  4584. FAction(Action),
  4585. FOutputEvent(OutputEvent)
  4586. {
  4587. }
  4588. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  4589. {
  4590. switch (OutputType)
  4591. {
  4592. case cotOutput:
  4593. FAction.AddOutput(Str, false);
  4594. break;
  4595. case cotError:
  4596. FAction.AddOutput(Str, true);
  4597. break;
  4598. case cotExitCode:
  4599. FAction.ExitCode(StrToInt(Str));
  4600. break;
  4601. }
  4602. if (FOutputEvent != NULL)
  4603. {
  4604. FOutputEvent(Str, OutputType);
  4605. }
  4606. }
  4607. private:
  4608. TCallSessionAction & FAction;
  4609. TCaptureOutputEvent FOutputEvent;
  4610. };
  4611. #pragma warn .inl
  4612. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  4613. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  4614. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  4615. }
  4616. //---------------------------------------------------------------------------
  4617. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  4618. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  4619. {
  4620. DebugAssert(FFileSystem);
  4621. try
  4622. {
  4623. DirectoryModified(CurrentDirectory, false);
  4624. if (IsCapable[fcAnyCommand])
  4625. {
  4626. LogEvent(L"Executing user defined command.");
  4627. FFileSystem->AnyCommand(Command, OutputEvent);
  4628. }
  4629. else
  4630. {
  4631. DebugAssert(CommandSessionOpened);
  4632. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  4633. LogEvent(L"Executing user defined command on command session.");
  4634. FCommandSession->CurrentDirectory = CurrentDirectory;
  4635. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  4636. FCommandSession->FFileSystem->ReadCurrentDirectory();
  4637. // synchronize pwd (by purpose we lose transaction optimization here)
  4638. ChangeDirectory(FCommandSession->CurrentDirectory);
  4639. }
  4640. ReactOnCommand(fsAnyCommand);
  4641. }
  4642. catch (Exception &E)
  4643. {
  4644. if (Action != NULL)
  4645. {
  4646. RollbackAction(*Action, NULL, &E);
  4647. }
  4648. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  4649. else HandleExtendedException(&E);
  4650. }
  4651. }
  4652. //---------------------------------------------------------------------------
  4653. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  4654. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4655. bool NoConfirmation)
  4656. {
  4657. bool Result = true;
  4658. bool Done;
  4659. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  4660. do
  4661. {
  4662. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  4663. NULL, CREATE_ALWAYS, CreateAttr, 0);
  4664. Done = (*AHandle != INVALID_HANDLE_VALUE);
  4665. if (!Done)
  4666. {
  4667. // save the error, otherwise it gets overwritten by call to FileExists
  4668. int LastError = GetLastError();
  4669. int FileAttr;
  4670. if (::FileExists(ApiPath(FileName)) &&
  4671. (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  4672. {
  4673. if (FLAGSET(FileAttr, faReadOnly))
  4674. {
  4675. OperationProgress->LockUserSelections();
  4676. try
  4677. {
  4678. if (OperationProgress->BatchOverwrite == boNone)
  4679. {
  4680. Result = false;
  4681. }
  4682. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  4683. {
  4684. unsigned int Answer;
  4685. {
  4686. TSuspendFileOperationProgress Suspend(OperationProgress);
  4687. Answer = QueryUser(
  4688. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  4689. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  4690. }
  4691. switch (Answer) {
  4692. case qaYesToAll: OperationProgress->SetBatchOverwrite(boAll); break;
  4693. case qaCancel: OperationProgress->SetCancel(csCancel); // continue on next case
  4694. case qaNoToAll: OperationProgress->SetBatchOverwrite(boNone);
  4695. case qaNo: Result = false; break;
  4696. }
  4697. }
  4698. }
  4699. __finally
  4700. {
  4701. OperationProgress->UnlockUserSelections();
  4702. }
  4703. }
  4704. else
  4705. {
  4706. DebugAssert(FLAGSET(FileAttr, faHidden));
  4707. Result = true;
  4708. }
  4709. if (Result)
  4710. {
  4711. CreateAttr |=
  4712. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  4713. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  4714. FILE_OPERATION_LOOP_BEGIN
  4715. {
  4716. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  4717. {
  4718. RaiseLastOSError();
  4719. }
  4720. }
  4721. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  4722. }
  4723. else
  4724. {
  4725. Done = true;
  4726. }
  4727. }
  4728. else
  4729. {
  4730. RaiseLastOSError(LastError);
  4731. }
  4732. }
  4733. }
  4734. while (!Done);
  4735. return Result;
  4736. }
  4737. //---------------------------------------------------------------------------
  4738. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  4739. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4740. bool NoConfirmation)
  4741. {
  4742. DebugAssert(AHandle);
  4743. bool Result = true;
  4744. FILE_OPERATION_LOOP_BEGIN
  4745. {
  4746. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  4747. }
  4748. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  4749. return Result;
  4750. }
  4751. //---------------------------------------------------------------------------
  4752. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  4753. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  4754. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  4755. bool TryWriteReadOnly)
  4756. {
  4757. int Attrs = 0;
  4758. HANDLE Handle = 0;
  4759. FILE_OPERATION_LOOP_BEGIN
  4760. {
  4761. UnicodeString FileNameApi = ApiPath(FileName);
  4762. Attrs = FileGetAttrFix(FileNameApi);
  4763. if (Attrs < 0)
  4764. {
  4765. RaiseLastOSError();
  4766. }
  4767. }
  4768. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4769. if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
  4770. {
  4771. bool NoHandle = false;
  4772. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  4773. ((Attrs & faReadOnly) != 0))
  4774. {
  4775. Access = GENERIC_READ;
  4776. NoHandle = true;
  4777. }
  4778. FILE_OPERATION_LOOP_BEGIN
  4779. {
  4780. DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
  4781. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  4782. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  4783. NULL, OPEN_EXISTING, Flags, 0);
  4784. if (Handle == INVALID_HANDLE_VALUE)
  4785. {
  4786. Handle = 0;
  4787. RaiseLastOSError();
  4788. }
  4789. }
  4790. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  4791. try
  4792. {
  4793. if (AATime || AMTime || ACTime)
  4794. {
  4795. FILETIME ATime;
  4796. FILETIME MTime;
  4797. FILETIME CTime;
  4798. // Get last file access and modification time
  4799. FILE_OPERATION_LOOP_BEGIN
  4800. {
  4801. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  4802. }
  4803. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4804. if (ACTime)
  4805. {
  4806. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  4807. }
  4808. if (AATime)
  4809. {
  4810. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  4811. }
  4812. if (AMTime)
  4813. {
  4814. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  4815. }
  4816. }
  4817. if (ASize)
  4818. {
  4819. // Get file size
  4820. FILE_OPERATION_LOOP_BEGIN
  4821. {
  4822. unsigned long LSize;
  4823. unsigned long HSize;
  4824. LSize = GetFileSize(Handle, &HSize);
  4825. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  4826. *ASize = (__int64(HSize) << 32) + LSize;
  4827. }
  4828. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4829. }
  4830. if ((AHandle == NULL) || NoHandle)
  4831. {
  4832. CloseHandle(Handle);
  4833. Handle = NULL;
  4834. }
  4835. }
  4836. catch(...)
  4837. {
  4838. CloseHandle(Handle);
  4839. throw;
  4840. }
  4841. }
  4842. if (AAttrs) *AAttrs = Attrs;
  4843. if (AHandle) *AHandle = Handle;
  4844. }
  4845. //---------------------------------------------------------------------------
  4846. void __fastcall TTerminal::OpenLocalFile(
  4847. const UnicodeString & FileName, unsigned int Access, TLocalFileHandle & Handle, bool TryWriteReadOnly)
  4848. {
  4849. Handle.FileName = FileName;
  4850. OpenLocalFile(
  4851. FileName, Access, &Handle.Attrs, &Handle.Handle, NULL, &Handle.MTime, &Handle.ATime, &Handle.Size,
  4852. TryWriteReadOnly);
  4853. Handle.Modification = UnixToDateTime(Handle.MTime, SessionData->DSTMode);
  4854. Handle.Directory = FLAGSET(Handle.Attrs, faDirectory);
  4855. }
  4856. //---------------------------------------------------------------------------
  4857. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  4858. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  4859. {
  4860. bool Result = true;
  4861. // optimization
  4862. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  4863. {
  4864. WIN32_FIND_DATA FindData;
  4865. HANDLE Handle;
  4866. FILE_OPERATION_LOOP_BEGIN
  4867. {
  4868. Handle = FindFirstFile(ApiPath(ExcludeTrailingBackslash(FileName)).c_str(), &FindData);
  4869. if (Handle == INVALID_HANDLE_VALUE)
  4870. {
  4871. RaiseLastOSError();
  4872. }
  4873. }
  4874. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4875. ::FindClose(Handle);
  4876. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  4877. TFileMasks::TParams Params;
  4878. // SearchRec.Size in C++B2010 is __int64,
  4879. // so we should be able to use it instead of FindData.nFileSize*
  4880. Params.Size =
  4881. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  4882. FindData.nFileSizeLow;
  4883. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  4884. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4885. if (!CopyParam->AllowTransfer(BaseFileName, osLocal, Directory, Params))
  4886. {
  4887. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  4888. Result = false;
  4889. }
  4890. else if (CopyParam->SkipTransfer(FileName, Directory))
  4891. {
  4892. OperationProgress->AddSkippedFileSize(Params.Size);
  4893. Result = false;
  4894. }
  4895. if (Result)
  4896. {
  4897. LogFileDetails(FileName, Params.Modification, Params.Size);
  4898. }
  4899. }
  4900. return Result;
  4901. }
  4902. //---------------------------------------------------------------------------
  4903. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  4904. const TSearchRec Rec, void * Param)
  4905. {
  4906. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  4907. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  4908. if (Directory && Params.Recursive)
  4909. {
  4910. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  4911. }
  4912. if (!Directory || Params.IncludeDirs)
  4913. {
  4914. Params.FileList->Add(FileName);
  4915. if (Params.FileTimes != NULL)
  4916. {
  4917. Params.FileTimes->push_back(const_cast<TSearchRec &>(Rec).TimeStamp);
  4918. }
  4919. }
  4920. }
  4921. //---------------------------------------------------------------------------
  4922. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  4923. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  4924. {
  4925. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  4926. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  4927. {
  4928. AParams->Result = false;
  4929. }
  4930. else
  4931. {
  4932. try
  4933. {
  4934. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  4935. bool AllowTransfer = (AParams->CopyParam == NULL);
  4936. // SearchRec.Size in C++B2010 is __int64,
  4937. // so we should be able to use it instead of FindData.nFileSize*
  4938. __int64 Size =
  4939. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  4940. Rec.FindData.nFileSizeLow;
  4941. if (!AllowTransfer)
  4942. {
  4943. TFileMasks::TParams MaskParams;
  4944. MaskParams.Size = Size;
  4945. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  4946. UnicodeString BaseFileName = GetBaseFileName(FileName);
  4947. AllowTransfer = AParams->CopyParam->AllowTransfer(BaseFileName, osLocal, Dir, MaskParams);
  4948. }
  4949. if (AllowTransfer)
  4950. {
  4951. int CollectionIndex = -1;
  4952. if (AParams->Files != NULL)
  4953. {
  4954. UnicodeString FullFileName = ::ExpandFileName(FileName);
  4955. CollectionIndex = AParams->Files->Add(FullFileName, NULL, Dir);
  4956. }
  4957. if (!Dir)
  4958. {
  4959. AParams->Size += Size;
  4960. }
  4961. else
  4962. {
  4963. try
  4964. {
  4965. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  4966. }
  4967. catch (...)
  4968. {
  4969. if (CollectionIndex >= 0)
  4970. {
  4971. AParams->Files->DidNotRecurse(CollectionIndex);
  4972. }
  4973. }
  4974. }
  4975. }
  4976. }
  4977. catch (...)
  4978. {
  4979. // ignore
  4980. }
  4981. }
  4982. }
  4983. //---------------------------------------------------------------------------
  4984. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  4985. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs, TStrings * Files)
  4986. {
  4987. bool Result = false;
  4988. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4989. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4990. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  4991. try
  4992. {
  4993. TCalculateSizeParams Params;
  4994. Params.Size = 0;
  4995. Params.Params = 0;
  4996. Params.CopyParam = CopyParam;
  4997. Params.Files = NULL;
  4998. Params.Result = true;
  4999. DebugAssert(!FOperationProgress);
  5000. FOperationProgress = &OperationProgress;
  5001. UnicodeString LastDirPath;
  5002. for (int Index = 0; Params.Result && (Index < FileList->Count); Index++)
  5003. {
  5004. UnicodeString FileName = FileList->Strings[Index];
  5005. TSearchRec Rec;
  5006. if (FileSearchRec(FileName, Rec))
  5007. {
  5008. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  5009. if (Dir && !AllowDirs)
  5010. {
  5011. Params.Result = false;
  5012. }
  5013. else
  5014. {
  5015. if (Files != NULL)
  5016. {
  5017. UnicodeString FullFileName = ::ExpandFileName(FileName);
  5018. UnicodeString DirPath = ExtractFilePath(FullFileName);
  5019. if (DirPath != LastDirPath)
  5020. {
  5021. Params.Files = new TCollectedFileList();
  5022. LastDirPath = DirPath;
  5023. Files->AddObject(LastDirPath, Params.Files);
  5024. }
  5025. }
  5026. CalculateLocalFileSize(FileName, Rec, &Params);
  5027. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  5028. }
  5029. }
  5030. }
  5031. Size = Params.Size;
  5032. Result = Params.Result;
  5033. }
  5034. __finally
  5035. {
  5036. FOperationProgress = NULL;
  5037. OperationProgress.Stop();
  5038. }
  5039. if (OnceDoneOperation != odoIdle)
  5040. {
  5041. CloseOnCompletion(OnceDoneOperation);
  5042. }
  5043. return Result;
  5044. }
  5045. //---------------------------------------------------------------------------
  5046. struct TSynchronizeFileData
  5047. {
  5048. bool Modified;
  5049. bool New;
  5050. bool IsDirectory;
  5051. TSynchronizeChecklist::TItem::TFileInfo Info;
  5052. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  5053. TRemoteFile * MatchingRemoteFileFile;
  5054. int MatchingRemoteFileImageIndex;
  5055. FILETIME LocalLastWriteTime;
  5056. };
  5057. //---------------------------------------------------------------------------
  5058. const int sfFirstLevel = 0x01;
  5059. struct TSynchronizeData
  5060. {
  5061. UnicodeString LocalDirectory;
  5062. UnicodeString RemoteDirectory;
  5063. TTerminal::TSynchronizeMode Mode;
  5064. int Params;
  5065. TSynchronizeDirectory OnSynchronizeDirectory;
  5066. TSynchronizeOptions * Options;
  5067. int Flags;
  5068. TStringList * LocalFileList;
  5069. const TCopyParamType * CopyParam;
  5070. TSynchronizeChecklist * Checklist;
  5071. };
  5072. //---------------------------------------------------------------------------
  5073. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  5074. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5075. const TCopyParamType * CopyParam, int Params,
  5076. TSynchronizeDirectory OnSynchronizeDirectory,
  5077. TSynchronizeOptions * Options)
  5078. {
  5079. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  5080. FUseBusyCursor = false;
  5081. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  5082. try
  5083. {
  5084. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  5085. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  5086. Checklist);
  5087. Checklist->Sort();
  5088. }
  5089. catch(...)
  5090. {
  5091. delete Checklist;
  5092. throw;
  5093. }
  5094. return Checklist;
  5095. }
  5096. //---------------------------------------------------------------------------
  5097. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  5098. {
  5099. if (FLAGSET(Params, Param))
  5100. {
  5101. AddToList(ParamsStr, Name, ", ");
  5102. }
  5103. Params &= ~Param;
  5104. }
  5105. //---------------------------------------------------------------------------
  5106. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  5107. {
  5108. UnicodeString ModeStr;
  5109. switch (Mode)
  5110. {
  5111. case smRemote:
  5112. ModeStr = L"Remote";
  5113. break;
  5114. case smLocal:
  5115. ModeStr = L"Local";
  5116. break;
  5117. case smBoth:
  5118. ModeStr = L"Both";
  5119. break;
  5120. default:
  5121. ModeStr = L"Unknown";
  5122. break;
  5123. }
  5124. return ModeStr;
  5125. }
  5126. //---------------------------------------------------------------------------
  5127. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  5128. {
  5129. UnicodeString ParamsStr;
  5130. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  5131. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  5132. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  5133. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  5134. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  5135. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  5136. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  5137. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  5138. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  5139. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  5140. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  5141. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  5142. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  5143. if (Params > 0)
  5144. {
  5145. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  5146. }
  5147. return ParamsStr;
  5148. }
  5149. //---------------------------------------------------------------------------
  5150. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  5151. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5152. const TCopyParamType * CopyParam, int Params,
  5153. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  5154. int Flags, TSynchronizeChecklist * Checklist)
  5155. {
  5156. TSynchronizeData Data;
  5157. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  5158. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  5159. Data.Mode = Mode;
  5160. Data.Params = Params;
  5161. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  5162. Data.LocalFileList = NULL;
  5163. Data.CopyParam = CopyParam;
  5164. Data.Options = Options;
  5165. Data.Flags = Flags;
  5166. Data.Checklist = Checklist;
  5167. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  5168. "mode = %s, params = 0x%x (%s), file mask = '%s'", (LocalDirectory, RemoteDirectory,
  5169. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params), CopyParam->IncludeFileMask.Masks)));
  5170. if (FLAGCLEAR(Params, spDelayProgress))
  5171. {
  5172. DoSynchronizeProgress(Data, true);
  5173. }
  5174. try
  5175. {
  5176. bool Found;
  5177. TSearchRecChecked SearchRec;
  5178. Data.LocalFileList = CreateSortedStringList();
  5179. FILE_OPERATION_LOOP_BEGIN
  5180. {
  5181. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  5182. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  5183. }
  5184. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  5185. if (Found)
  5186. {
  5187. try
  5188. {
  5189. UnicodeString FileName;
  5190. while (Found)
  5191. {
  5192. FileName = SearchRec.Name;
  5193. // add dirs for recursive mode or when we are interested in newly
  5194. // added subdirs
  5195. // SearchRec.Size in C++B2010 is __int64,
  5196. // so we should be able to use it instead of FindData.nFileSize*
  5197. __int64 Size =
  5198. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  5199. SearchRec.FindData.nFileSizeLow;
  5200. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  5201. TFileMasks::TParams MaskParams;
  5202. MaskParams.Size = Size;
  5203. MaskParams.Modification = Modification;
  5204. UnicodeString RemoteFileName =
  5205. ChangeFileName(CopyParam, FileName, osLocal, false);
  5206. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  5207. UnicodeString BaseFileName = GetBaseFileName(FullLocalFileName);
  5208. if ((FileName != L".") && (FileName != L"..") &&
  5209. CopyParam->AllowTransfer(BaseFileName, osLocal,
  5210. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  5211. !FFileSystem->TemporaryTransferFile(FileName) &&
  5212. (FLAGCLEAR(Flags, sfFirstLevel) ||
  5213. (Options == NULL) ||
  5214. Options->MatchesFilter(FileName) ||
  5215. Options->MatchesFilter(RemoteFileName)))
  5216. {
  5217. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  5218. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  5219. FileData->Info.FileName = FileName;
  5220. FileData->Info.Directory = Data.LocalDirectory;
  5221. FileData->Info.Modification = Modification;
  5222. FileData->Info.ModificationFmt = mfFull;
  5223. FileData->Info.Size = Size;
  5224. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  5225. FileData->New = true;
  5226. FileData->Modified = false;
  5227. Data.LocalFileList->AddObject(FileName,
  5228. reinterpret_cast<TObject*>(FileData));
  5229. LogEvent(FORMAT(L"Local file %s included to synchronization",
  5230. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  5231. }
  5232. else
  5233. {
  5234. LogEvent(FORMAT(L"Local file %s excluded from synchronization",
  5235. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  5236. }
  5237. FILE_OPERATION_LOOP_BEGIN
  5238. {
  5239. Found = (FindNextChecked(SearchRec) == 0);
  5240. }
  5241. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  5242. }
  5243. }
  5244. __finally
  5245. {
  5246. FindClose(SearchRec);
  5247. }
  5248. // can we expect that ProcessDirectory would take so little time
  5249. // that we can postpone showing progress window until anything actually happens?
  5250. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  5251. FDirectoryCache->HasFileList(RemoteDirectory);
  5252. if (!Cached && FLAGSET(Params, spDelayProgress))
  5253. {
  5254. DoSynchronizeProgress(Data, true);
  5255. }
  5256. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  5257. FLAGSET(Params, spUseCache));
  5258. TSynchronizeFileData * FileData;
  5259. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  5260. {
  5261. FileData = reinterpret_cast<TSynchronizeFileData *>
  5262. (Data.LocalFileList->Objects[Index]);
  5263. // add local file either if we are going to upload it
  5264. // (i.e. if it is updated or we want to upload even new files)
  5265. // or if we are going to delete it (i.e. all "new"=obsolete files)
  5266. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  5267. bool New = (FileData->New &&
  5268. ((Mode == smLocal) ||
  5269. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  5270. if (New)
  5271. {
  5272. LogEvent(FORMAT(L"Local file %s is new",
  5273. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  5274. FileData->Info.Modification, FileData->Info.Size))));
  5275. }
  5276. if (Modified || New)
  5277. {
  5278. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  5279. try
  5280. {
  5281. ChecklistItem->IsDirectory = FileData->IsDirectory;
  5282. ChecklistItem->Local = FileData->Info;
  5283. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  5284. if (Modified)
  5285. {
  5286. DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  5287. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  5288. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  5289. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  5290. }
  5291. else
  5292. {
  5293. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  5294. }
  5295. if ((Mode == smBoth) || (Mode == smRemote))
  5296. {
  5297. ChecklistItem->Action =
  5298. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  5299. ChecklistItem->Checked =
  5300. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  5301. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  5302. FLAGSET(Params, spSubDirs));
  5303. }
  5304. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  5305. {
  5306. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  5307. ChecklistItem->Checked =
  5308. FLAGSET(Params, spDelete) &&
  5309. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  5310. FLAGSET(Params, spSubDirs));
  5311. }
  5312. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  5313. {
  5314. Data.Checklist->Add(ChecklistItem);
  5315. ChecklistItem = NULL;
  5316. }
  5317. }
  5318. __finally
  5319. {
  5320. delete ChecklistItem;
  5321. }
  5322. }
  5323. else
  5324. {
  5325. if (FileData->Modified)
  5326. {
  5327. delete FileData->MatchingRemoteFileFile;
  5328. }
  5329. }
  5330. }
  5331. }
  5332. }
  5333. __finally
  5334. {
  5335. if (Data.LocalFileList != NULL)
  5336. {
  5337. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  5338. {
  5339. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  5340. (Data.LocalFileList->Objects[Index]);
  5341. delete FileData;
  5342. }
  5343. delete Data.LocalFileList;
  5344. }
  5345. }
  5346. }
  5347. //---------------------------------------------------------------------------
  5348. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  5349. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  5350. {
  5351. try
  5352. {
  5353. DoSynchronizeCollectFile(FileName, File, Param);
  5354. }
  5355. catch(ESkipFile & E)
  5356. {
  5357. TSuspendFileOperationProgress Suspend(OperationProgress);
  5358. if (!HandleException(&E))
  5359. {
  5360. throw;
  5361. }
  5362. }
  5363. }
  5364. //---------------------------------------------------------------------------
  5365. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  5366. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  5367. {
  5368. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  5369. TFileMasks::TParams MaskParams;
  5370. MaskParams.Size = File->Size;
  5371. MaskParams.Modification = File->Modification;
  5372. UnicodeString LocalFileName =
  5373. ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
  5374. UnicodeString FullRemoteFileName =
  5375. UnixExcludeTrailingBackslash(File->FullFileName);
  5376. UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
  5377. if (Data->CopyParam->AllowTransfer(
  5378. BaseFileName, osRemote,
  5379. File->IsDirectory, MaskParams) &&
  5380. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  5381. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  5382. (Data->Options == NULL) ||
  5383. Data->Options->MatchesFilter(File->FileName) ||
  5384. Data->Options->MatchesFilter(LocalFileName)))
  5385. {
  5386. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  5387. try
  5388. {
  5389. ChecklistItem->IsDirectory = File->IsDirectory;
  5390. ChecklistItem->ImageIndex = File->IconIndex;
  5391. ChecklistItem->Remote.FileName = File->FileName;
  5392. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  5393. ChecklistItem->Remote.Modification = File->Modification;
  5394. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  5395. ChecklistItem->Remote.Size = File->Size;
  5396. bool Modified = false;
  5397. bool New = false;
  5398. if (File->IsDirectory && !CanRecurseToDirectory(File))
  5399. {
  5400. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
  5401. }
  5402. else
  5403. {
  5404. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  5405. New = (LocalIndex < 0);
  5406. if (!New)
  5407. {
  5408. TSynchronizeFileData * LocalData =
  5409. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  5410. LocalData->New = false;
  5411. if (File->IsDirectory != LocalData->IsDirectory)
  5412. {
  5413. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  5414. (File->FileName)));
  5415. }
  5416. else if (!File->IsDirectory)
  5417. {
  5418. ChecklistItem->Local = LocalData->Info;
  5419. ChecklistItem->Local.Modification =
  5420. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  5421. bool LocalModified = false;
  5422. // for spTimestamp+spBySize require that the file sizes are the same
  5423. // before comparing file time
  5424. int TimeCompare;
  5425. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  5426. (FLAGCLEAR(Data->Params, spTimestamp) ||
  5427. FLAGCLEAR(Data->Params, spBySize) ||
  5428. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  5429. {
  5430. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  5431. ChecklistItem->Remote.Modification);
  5432. }
  5433. else
  5434. {
  5435. TimeCompare = 0;
  5436. }
  5437. if (TimeCompare < 0)
  5438. {
  5439. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  5440. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  5441. {
  5442. Modified = true;
  5443. }
  5444. else
  5445. {
  5446. LocalModified = true;
  5447. }
  5448. }
  5449. else if (TimeCompare > 0)
  5450. {
  5451. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  5452. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  5453. {
  5454. LocalModified = true;
  5455. }
  5456. else
  5457. {
  5458. Modified = true;
  5459. }
  5460. }
  5461. else if (FLAGSET(Data->Params, spBySize) &&
  5462. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  5463. FLAGCLEAR(Data->Params, spTimestamp))
  5464. {
  5465. Modified = true;
  5466. LocalModified = true;
  5467. }
  5468. if (LocalModified)
  5469. {
  5470. LocalData->Modified = true;
  5471. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  5472. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  5473. // we need this for custom commands over checklist only,
  5474. // not for sync itself
  5475. LocalData->MatchingRemoteFileFile = File->Duplicate();
  5476. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  5477. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  5478. LocalData->Info.Modification, LocalData->Info.Size),
  5479. FormatFileDetailsForLog(FullRemoteFileName,
  5480. File->Modification, File->Size))));
  5481. }
  5482. if (Modified)
  5483. {
  5484. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  5485. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size),
  5486. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  5487. LocalData->Info.Modification, LocalData->Info.Size))));
  5488. }
  5489. }
  5490. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  5491. {
  5492. DoSynchronizeCollectDirectory(
  5493. Data->LocalDirectory + LocalData->Info.FileName,
  5494. Data->RemoteDirectory + File->FileName,
  5495. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  5496. Data->Options, (Data->Flags & ~sfFirstLevel),
  5497. Data->Checklist);
  5498. }
  5499. }
  5500. else
  5501. {
  5502. ChecklistItem->Local.Directory = Data->LocalDirectory;
  5503. LogEvent(FORMAT(L"Remote file %s is new",
  5504. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  5505. }
  5506. }
  5507. if (New || Modified)
  5508. {
  5509. DebugAssert(!New || !Modified);
  5510. // download the file if it changed or is new and we want to have it locally
  5511. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  5512. {
  5513. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  5514. {
  5515. ChecklistItem->Action =
  5516. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  5517. ChecklistItem->Checked =
  5518. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  5519. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  5520. FLAGSET(Data->Params, spSubDirs));
  5521. }
  5522. }
  5523. else if ((Data->Mode == smRemote) && New)
  5524. {
  5525. if (FLAGCLEAR(Data->Params, spTimestamp))
  5526. {
  5527. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  5528. ChecklistItem->Checked =
  5529. FLAGSET(Data->Params, spDelete) &&
  5530. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  5531. FLAGSET(Data->Params, spSubDirs));
  5532. }
  5533. }
  5534. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  5535. {
  5536. ChecklistItem->RemoteFile = File->Duplicate();
  5537. Data->Checklist->Add(ChecklistItem);
  5538. ChecklistItem = NULL;
  5539. }
  5540. }
  5541. }
  5542. __finally
  5543. {
  5544. delete ChecklistItem;
  5545. }
  5546. }
  5547. else
  5548. {
  5549. LogEvent(FORMAT(L"Remote file %s excluded from synchronization",
  5550. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  5551. }
  5552. }
  5553. //---------------------------------------------------------------------------
  5554. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  5555. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  5556. const TCopyParamType * CopyParam, int Params,
  5557. TSynchronizeDirectory OnSynchronizeDirectory)
  5558. {
  5559. TSynchronizeData Data;
  5560. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  5561. int CopyParams =
  5562. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  5563. TCopyParamType SyncCopyParam = *CopyParam;
  5564. // when synchronizing by time, we force preserving time,
  5565. // otherwise it does not make any sense
  5566. if (FLAGCLEAR(Params, spNotByTime))
  5567. {
  5568. SyncCopyParam.PreserveTime = true;
  5569. }
  5570. TStringList * DownloadList = new TStringList();
  5571. TStringList * DeleteRemoteList = new TStringList();
  5572. TStringList * UploadList = new TStringList();
  5573. TStringList * DeleteLocalList = new TStringList();
  5574. BeginTransaction();
  5575. try
  5576. {
  5577. int IIndex = 0;
  5578. while (IIndex < Checklist->Count)
  5579. {
  5580. const TSynchronizeChecklist::TItem * ChecklistItem;
  5581. DownloadList->Clear();
  5582. DeleteRemoteList->Clear();
  5583. UploadList->Clear();
  5584. DeleteLocalList->Clear();
  5585. ChecklistItem = Checklist->Item[IIndex];
  5586. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  5587. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  5588. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  5589. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  5590. int(Params), SynchronizeParamsStr(Params))));
  5591. int Count = 0;
  5592. while ((IIndex < Checklist->Count) &&
  5593. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  5594. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  5595. {
  5596. ChecklistItem = Checklist->Item[IIndex];
  5597. if (ChecklistItem->Checked)
  5598. {
  5599. Count++;
  5600. if (FLAGSET(Params, spTimestamp))
  5601. {
  5602. switch (ChecklistItem->Action)
  5603. {
  5604. case TSynchronizeChecklist::saDownloadUpdate:
  5605. DownloadList->AddObject(
  5606. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  5607. ChecklistItem->Remote.FileName,
  5608. (TObject *)(ChecklistItem));
  5609. break;
  5610. case TSynchronizeChecklist::saUploadUpdate:
  5611. UploadList->AddObject(
  5612. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  5613. ChecklistItem->Local.FileName,
  5614. (TObject *)(ChecklistItem));
  5615. break;
  5616. default:
  5617. DebugFail();
  5618. break;
  5619. }
  5620. }
  5621. else
  5622. {
  5623. switch (ChecklistItem->Action)
  5624. {
  5625. case TSynchronizeChecklist::saDownloadNew:
  5626. case TSynchronizeChecklist::saDownloadUpdate:
  5627. DownloadList->AddObject(
  5628. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  5629. ChecklistItem->Remote.FileName,
  5630. ChecklistItem->RemoteFile);
  5631. break;
  5632. case TSynchronizeChecklist::saDeleteRemote:
  5633. DeleteRemoteList->AddObject(
  5634. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  5635. ChecklistItem->Remote.FileName,
  5636. ChecklistItem->RemoteFile);
  5637. break;
  5638. case TSynchronizeChecklist::saUploadNew:
  5639. case TSynchronizeChecklist::saUploadUpdate:
  5640. UploadList->Add(
  5641. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  5642. ChecklistItem->Local.FileName);
  5643. break;
  5644. case TSynchronizeChecklist::saDeleteLocal:
  5645. DeleteLocalList->Add(
  5646. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  5647. ChecklistItem->Local.FileName);
  5648. break;
  5649. default:
  5650. DebugFail();
  5651. break;
  5652. }
  5653. }
  5654. }
  5655. IIndex++;
  5656. }
  5657. // prevent showing/updating of progress dialog if there's nothing to do
  5658. if (Count > 0)
  5659. {
  5660. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  5661. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  5662. DoSynchronizeProgress(Data, false);
  5663. if (FLAGSET(Params, spTimestamp))
  5664. {
  5665. if (DownloadList->Count > 0)
  5666. {
  5667. ProcessFiles(DownloadList, foSetProperties,
  5668. SynchronizeLocalTimestamp, NULL, osLocal);
  5669. }
  5670. if (UploadList->Count > 0)
  5671. {
  5672. ProcessFiles(UploadList, foSetProperties,
  5673. SynchronizeRemoteTimestamp);
  5674. }
  5675. }
  5676. else
  5677. {
  5678. if ((DownloadList->Count > 0) &&
  5679. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams, NULL))
  5680. {
  5681. Abort();
  5682. }
  5683. if ((DeleteRemoteList->Count > 0) &&
  5684. !DeleteFiles(DeleteRemoteList))
  5685. {
  5686. Abort();
  5687. }
  5688. if ((UploadList->Count > 0) &&
  5689. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams, NULL))
  5690. {
  5691. Abort();
  5692. }
  5693. if ((DeleteLocalList->Count > 0) &&
  5694. !DeleteLocalFiles(DeleteLocalList))
  5695. {
  5696. Abort();
  5697. }
  5698. }
  5699. }
  5700. }
  5701. }
  5702. __finally
  5703. {
  5704. delete DownloadList;
  5705. delete DeleteRemoteList;
  5706. delete UploadList;
  5707. delete DeleteLocalList;
  5708. EndTransaction();
  5709. }
  5710. }
  5711. //---------------------------------------------------------------------------
  5712. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  5713. bool Collect)
  5714. {
  5715. if (Data.OnSynchronizeDirectory != NULL)
  5716. {
  5717. bool Continue = true;
  5718. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  5719. Continue, Collect);
  5720. if (!Continue)
  5721. {
  5722. Abort();
  5723. }
  5724. }
  5725. }
  5726. //---------------------------------------------------------------------------
  5727. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  5728. const TRemoteFile * File, void * /*Param*/)
  5729. {
  5730. const TSynchronizeChecklist::TItem * ChecklistItem =
  5731. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5732. UnicodeString LocalFile =
  5733. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  5734. ChecklistItem->Local.FileName;
  5735. FILE_OPERATION_LOOP_BEGIN
  5736. {
  5737. HANDLE Handle;
  5738. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  5739. NULL, NULL, NULL, NULL);
  5740. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  5741. SessionData->DSTMode);
  5742. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  5743. int Error = GetLastError();
  5744. CloseHandle(Handle);
  5745. if (!Result)
  5746. {
  5747. RaiseLastOSError(Error);
  5748. }
  5749. }
  5750. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  5751. }
  5752. //---------------------------------------------------------------------------
  5753. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  5754. const TRemoteFile * File, void * /*Param*/)
  5755. {
  5756. const TSynchronizeChecklist::TItem * ChecklistItem =
  5757. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  5758. TRemoteProperties Properties;
  5759. Properties.Valid << vpModification;
  5760. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  5761. SessionData->DSTMode);
  5762. ChangeFileProperties(
  5763. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  5764. NULL, &Properties);
  5765. }
  5766. //---------------------------------------------------------------------------
  5767. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  5768. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  5769. {
  5770. // see DoFilesFind
  5771. FOnFindingFile = NULL;
  5772. DebugAssert(Param);
  5773. DebugAssert(File);
  5774. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  5775. if (!AParams->Cancel)
  5776. {
  5777. if (FileName.IsEmpty())
  5778. {
  5779. FileName = File->FileName;
  5780. }
  5781. TFileMasks::TParams MaskParams;
  5782. MaskParams.Size = File->Size;
  5783. MaskParams.Modification = File->Modification;
  5784. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5785. bool ImplicitMatch;
  5786. // Do not use recursive include match
  5787. if (AParams->FileMask.Matches(FullFileName, false,
  5788. File->IsDirectory, &MaskParams, false, ImplicitMatch))
  5789. {
  5790. if (!ImplicitMatch)
  5791. {
  5792. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  5793. }
  5794. if (File->IsDirectory)
  5795. {
  5796. UnicodeString RealDirectory;
  5797. if (!File->IsSymLink || File->LinkTo.IsEmpty())
  5798. {
  5799. RealDirectory = UnixIncludeTrailingBackslash(AParams->RealDirectory) + File->FileName;
  5800. }
  5801. else
  5802. {
  5803. RealDirectory = ::AbsolutePath(AParams->RealDirectory, File->LinkTo);
  5804. }
  5805. if (!AParams->LoopDetector.IsUnvisitedDirectory(RealDirectory))
  5806. {
  5807. LogEvent(FORMAT(L"Already searched \"%s\" directory (real path \"%s\"), link loop detected", (FullFileName, RealDirectory)));
  5808. }
  5809. else
  5810. {
  5811. DoFilesFind(FullFileName, *AParams, RealDirectory);
  5812. }
  5813. }
  5814. }
  5815. }
  5816. }
  5817. //---------------------------------------------------------------------------
  5818. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params, UnicodeString RealDirectory)
  5819. {
  5820. LogEvent(FORMAT(L"Searching directory \"%s\" (real path \"%s\")", (Directory, RealDirectory)));
  5821. Params.OnFindingFile(this, Directory, Params.Cancel);
  5822. if (!Params.Cancel)
  5823. {
  5824. DebugAssert(FOnFindingFile == NULL);
  5825. // ideally we should set the handler only around actually reading
  5826. // of the directory listing, so we at least reset the handler in
  5827. // FileFind
  5828. FOnFindingFile = Params.OnFindingFile;
  5829. UnicodeString PrevRealDirectory = Params.RealDirectory;
  5830. try
  5831. {
  5832. Params.RealDirectory = RealDirectory;
  5833. ProcessDirectory(Directory, FileFind, &Params, false, true);
  5834. }
  5835. __finally
  5836. {
  5837. Params.RealDirectory = PrevRealDirectory;
  5838. FOnFindingFile = NULL;
  5839. }
  5840. }
  5841. }
  5842. //---------------------------------------------------------------------------
  5843. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  5844. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  5845. {
  5846. TFilesFindParams Params;
  5847. Params.FileMask = FileMask;
  5848. Params.OnFileFound = OnFileFound;
  5849. Params.OnFindingFile = OnFindingFile;
  5850. Params.Cancel = false;
  5851. Params.LoopDetector.RecordVisitedDirectory(Directory);
  5852. DoFilesFind(Directory, Params, Directory);
  5853. }
  5854. //---------------------------------------------------------------------------
  5855. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  5856. TSpaceAvailable & ASpaceAvailable)
  5857. {
  5858. DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
  5859. try
  5860. {
  5861. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  5862. }
  5863. catch (Exception &E)
  5864. {
  5865. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  5866. }
  5867. }
  5868. //---------------------------------------------------------------------------
  5869. void __fastcall TTerminal::LockFile(const UnicodeString FileName,
  5870. const TRemoteFile * File, void * /*Param*/)
  5871. {
  5872. StartOperationWithFile(FileName, foLock);
  5873. LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
  5874. FileModified(File, FileName, true);
  5875. DoLockFile(FileName, File);
  5876. ReactOnCommand(fsLock);
  5877. }
  5878. //---------------------------------------------------------------------------
  5879. void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5880. {
  5881. TRetryOperationLoop RetryLoop(this);
  5882. do
  5883. {
  5884. try
  5885. {
  5886. FFileSystem->LockFile(FileName, File);
  5887. }
  5888. catch(Exception & E)
  5889. {
  5890. RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
  5891. }
  5892. }
  5893. while (RetryLoop.Retry());
  5894. }
  5895. //---------------------------------------------------------------------------
  5896. void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
  5897. const TRemoteFile * File, void * /*Param*/)
  5898. {
  5899. StartOperationWithFile(FileName, foUnlock);
  5900. LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
  5901. FileModified(File, FileName, true);
  5902. DoUnlockFile(FileName, File);
  5903. ReactOnCommand(fsLock);
  5904. }
  5905. //---------------------------------------------------------------------------
  5906. void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  5907. {
  5908. TRetryOperationLoop RetryLoop(this);
  5909. do
  5910. {
  5911. try
  5912. {
  5913. FFileSystem->UnlockFile(FileName, File);
  5914. }
  5915. catch(Exception & E)
  5916. {
  5917. RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
  5918. }
  5919. }
  5920. while (RetryLoop.Retry());
  5921. }
  5922. //---------------------------------------------------------------------------
  5923. void __fastcall TTerminal::LockFiles(TStrings * FileList)
  5924. {
  5925. BeginTransaction();
  5926. try
  5927. {
  5928. ProcessFiles(FileList, foLock, LockFile, NULL);
  5929. }
  5930. __finally
  5931. {
  5932. EndTransaction();
  5933. }
  5934. }
  5935. //---------------------------------------------------------------------------
  5936. void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
  5937. {
  5938. BeginTransaction();
  5939. try
  5940. {
  5941. ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
  5942. }
  5943. __finally
  5944. {
  5945. EndTransaction();
  5946. }
  5947. }
  5948. //---------------------------------------------------------------------------
  5949. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  5950. {
  5951. return FFileSystem->GetSessionInfo();
  5952. }
  5953. //---------------------------------------------------------------------------
  5954. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  5955. {
  5956. return FFileSystem->GetFileSystemInfo(Retrieve);
  5957. }
  5958. //---------------------------------------------------------------------
  5959. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  5960. {
  5961. FFileSystem->GetSupportedChecksumAlgs(Algs);
  5962. }
  5963. //---------------------------------------------------------------------
  5964. UnicodeString __fastcall TTerminal::GetPassword()
  5965. {
  5966. UnicodeString Result;
  5967. // FRememberedPassword is empty also when stored password was used
  5968. if (FRememberedPassword.IsEmpty())
  5969. {
  5970. Result = SessionData->Password;
  5971. }
  5972. else
  5973. {
  5974. Result = RememberedPassword;
  5975. }
  5976. return Result;
  5977. }
  5978. //---------------------------------------------------------------------
  5979. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  5980. {
  5981. return DecryptPassword(FRememberedPassword);
  5982. }
  5983. //---------------------------------------------------------------------
  5984. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  5985. {
  5986. return DecryptPassword(FRememberedTunnelPassword);
  5987. }
  5988. //---------------------------------------------------------------------
  5989. bool __fastcall TTerminal::GetStoredCredentialsTried()
  5990. {
  5991. bool Result;
  5992. if (FFileSystem != NULL)
  5993. {
  5994. Result = FFileSystem->GetStoredCredentialsTried();
  5995. }
  5996. else if (FSecureShell != NULL)
  5997. {
  5998. Result = FSecureShell->GetStoredCredentialsTried();
  5999. }
  6000. else
  6001. {
  6002. DebugAssert(FTunnelOpening);
  6003. Result = false;
  6004. }
  6005. return Result;
  6006. }
  6007. //---------------------------------------------------------------------------
  6008. int __fastcall TTerminal::CopyToParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
  6009. {
  6010. UnicodeString FileName;
  6011. TObject * Object;
  6012. UnicodeString TargetDir;
  6013. bool Dir;
  6014. bool Recursed;
  6015. int Result = ParallelOperation->GetNext(this, FileName, Object, TargetDir, Dir, Recursed);
  6016. if (Result > 0)
  6017. {
  6018. std::unique_ptr<TStrings> FilesToCopy(new TStringList());
  6019. FilesToCopy->AddObject(FileName, Object);
  6020. if (ParallelOperation->Side == osLocal)
  6021. {
  6022. TargetDir = TranslateLockedPath(TargetDir, false);
  6023. }
  6024. // OnceDoneOperation is not supported
  6025. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6026. int Params = ParallelOperation->Params;
  6027. // If we failed to recurse the directory when enumerating, recurse now (typically only to show the recursion error)
  6028. if (Dir && Recursed)
  6029. {
  6030. Params = Params | cpNoRecurse;
  6031. }
  6032. int Prev = OperationProgress->FilesFinishedSuccessfully;
  6033. try
  6034. {
  6035. FOperationProgress = OperationProgress;
  6036. if (ParallelOperation->Side == osLocal)
  6037. {
  6038. FFileSystem->CopyToRemote(
  6039. FilesToCopy.get(), TargetDir, ParallelOperation->CopyParam, Params, OperationProgress, OnceDoneOperation);
  6040. }
  6041. else if (DebugAlwaysTrue(ParallelOperation->Side == osRemote))
  6042. {
  6043. FFileSystem->CopyToLocal(
  6044. FilesToCopy.get(), TargetDir, ParallelOperation->CopyParam, Params, OperationProgress, OnceDoneOperation);
  6045. }
  6046. }
  6047. __finally
  6048. {
  6049. bool Success = (Prev < OperationProgress->FilesFinishedSuccessfully);
  6050. ParallelOperation->Done(FileName, Dir, Success);
  6051. FOperationProgress = NULL;
  6052. }
  6053. }
  6054. return Result;
  6055. }
  6056. //---------------------------------------------------------------------------
  6057. bool __fastcall TTerminal::CanParallel(
  6058. const TCopyParamType * CopyParam, int Params, TParallelOperation * ParallelOperation)
  6059. {
  6060. return
  6061. (ParallelOperation != NULL) &&
  6062. FFileSystem->IsCapable(fsParallelTransfers) &&
  6063. // parallel transfer is not implemented for operations needed to be done on a folder
  6064. // after all its files are processed
  6065. FLAGCLEAR(Params, cpDelete) &&
  6066. (!CopyParam->PreserveTime || !CopyParam->PreserveTimeDirs);
  6067. }
  6068. //---------------------------------------------------------------------------
  6069. void __fastcall TTerminal::CopyParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
  6070. {
  6071. try
  6072. {
  6073. bool Continue = true;
  6074. do
  6075. {
  6076. int GotNext = CopyToParallel(ParallelOperation, OperationProgress);
  6077. if (GotNext < 0)
  6078. {
  6079. Continue = false;
  6080. }
  6081. else if (GotNext == 0)
  6082. {
  6083. Sleep(100);
  6084. }
  6085. }
  6086. while (Continue && !OperationProgress->Cancel);
  6087. }
  6088. __finally
  6089. {
  6090. OperationProgress->SetDone();
  6091. ParallelOperation->WaitFor();
  6092. }
  6093. }
  6094. //---------------------------------------------------------------------------
  6095. void __fastcall TTerminal::LogParallelTransfer(TParallelOperation * ParallelOperation)
  6096. {
  6097. LogEvent(
  6098. FORMAT("Adding a parallel transfer to the transfer started on the connection \"%s\"",
  6099. (ParallelOperation->MainName)));
  6100. }
  6101. //---------------------------------------------------------------------------
  6102. void __fastcall TTerminal::LogTotalTransferDetails(
  6103. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  6104. TFileOperationProgressType * OperationProgress, bool Parallel, TStrings * Files)
  6105. {
  6106. if (Log->Logging)
  6107. {
  6108. UnicodeString TargetSide = ((OperationProgress->Side == osLocal) ? L"remote" : L"local");
  6109. UnicodeString S =
  6110. FORMAT(
  6111. L"Copying %d files/directories to %s directory \"%s\"",
  6112. (OperationProgress->Count, TargetSide, TargetDir));
  6113. if (Parallel && DebugAlwaysTrue(Files != NULL))
  6114. {
  6115. int Count = 0;
  6116. for (int Index = 0; Index < Files->Count; Index++)
  6117. {
  6118. TCollectedFileList * FileList = dynamic_cast<TCollectedFileList *>(Files->Objects[Index]);
  6119. Count += FileList->Count();
  6120. }
  6121. S += FORMAT(L" - in parallel, with %d total files", (Count));
  6122. }
  6123. if (OperationProgress->TotalSizeSet)
  6124. {
  6125. S += FORMAT(L" - total size: %s", (FormatSize(OperationProgress->TotalSize)));
  6126. }
  6127. LogEvent(S);
  6128. LogEvent(CopyParam->LogStr);
  6129. }
  6130. }
  6131. //---------------------------------------------------------------------------
  6132. void __fastcall TTerminal::LogTotalTransferDone(TFileOperationProgressType * OperationProgress)
  6133. {
  6134. LogEvent(L"Copying finished: " + OperationProgress->GetLogStr(true));
  6135. }
  6136. //---------------------------------------------------------------------------
  6137. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  6138. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params, TParallelOperation * ParallelOperation)
  6139. {
  6140. DebugAssert(FFileSystem);
  6141. DebugAssert(FilesToCopy);
  6142. bool Result = false;
  6143. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6144. try
  6145. {
  6146. __int64 Size;
  6147. std::unique_ptr<TStringList> Files;
  6148. if (CanParallel(CopyParam, Params, ParallelOperation) &&
  6149. !CopyParam->ClearArchive)
  6150. {
  6151. Files.reset(new TStringList());
  6152. Files->OwnsObjects = true;
  6153. }
  6154. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  6155. bool CalculatedSize =
  6156. CalculateLocalFilesSize(
  6157. FilesToCopy, Size,
  6158. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  6159. CopyParam->CalculateSize, Files.get());
  6160. FLastProgressLogged = GetTickCount();
  6161. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  6162. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  6163. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  6164. FOperationProgress = &OperationProgress;
  6165. bool CollectingUsage = false;
  6166. try
  6167. {
  6168. if (CalculatedSize)
  6169. {
  6170. if (Configuration->Usage->Collect)
  6171. {
  6172. int CounterSize = TUsage::CalculateCounterSize(Size);
  6173. Configuration->Usage->Inc(L"Uploads");
  6174. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  6175. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  6176. CollectingUsage = true;
  6177. }
  6178. OperationProgress.SetTotalSize(Size);
  6179. }
  6180. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  6181. BeginTransaction();
  6182. try
  6183. {
  6184. bool Parallel = CalculatedSize && (Files.get() != NULL);
  6185. LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
  6186. if (Parallel)
  6187. {
  6188. // OnceDoneOperation is not supported
  6189. ParallelOperation->Init(Files.release(), UnlockedTargetDir, CopyParam, Params, &OperationProgress, Log->Name);
  6190. CopyParallel(ParallelOperation, &OperationProgress);
  6191. }
  6192. else
  6193. {
  6194. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  6195. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  6196. }
  6197. LogTotalTransferDone(&OperationProgress);
  6198. }
  6199. __finally
  6200. {
  6201. if (Active)
  6202. {
  6203. ReactOnCommand(fsCopyToRemote);
  6204. }
  6205. EndTransaction();
  6206. }
  6207. if (OperationProgress.Cancel == csContinue)
  6208. {
  6209. Result = true;
  6210. }
  6211. }
  6212. __finally
  6213. {
  6214. if (CollectingUsage)
  6215. {
  6216. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  6217. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  6218. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  6219. }
  6220. OperationProgress.Stop();
  6221. FOperationProgress = NULL;
  6222. }
  6223. }
  6224. catch (Exception &E)
  6225. {
  6226. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  6227. OnceDoneOperation = odoIdle;
  6228. }
  6229. if (OnceDoneOperation != odoIdle)
  6230. {
  6231. CloseOnCompletion(OnceDoneOperation);
  6232. }
  6233. return Result;
  6234. }
  6235. //---------------------------------------------------------------------------
  6236. void __fastcall TTerminal::DoCopyToRemote(
  6237. TStrings * FilesToCopy, const UnicodeString & ATargetDir, const TCopyParamType * CopyParam, int Params,
  6238. TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
  6239. {
  6240. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  6241. FFileSystem->TransferOnDirectory(ATargetDir, CopyParam, Params);
  6242. UnicodeString TargetDir = AbsolutePath(ATargetDir, false);
  6243. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  6244. int Index = 0;
  6245. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  6246. {
  6247. bool Success = false;
  6248. UnicodeString FileName = FilesToCopy->Strings[Index];
  6249. try
  6250. {
  6251. try
  6252. {
  6253. if (SessionData->CacheDirectories)
  6254. {
  6255. DirectoryModified(TargetDir, false);
  6256. if (DirectoryExists(ApiPath(FileName)))
  6257. {
  6258. UnicodeString FileNameOnly = ExtractFileName(FileName);
  6259. DirectoryModified(FullTargetDir + FileNameOnly, true);
  6260. }
  6261. }
  6262. SourceRobust(FileName, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
  6263. Success = true;
  6264. }
  6265. catch (ESkipFile & E)
  6266. {
  6267. TSuspendFileOperationProgress Suspend(OperationProgress);
  6268. if (!HandleException(&E))
  6269. {
  6270. throw;
  6271. }
  6272. }
  6273. }
  6274. __finally
  6275. {
  6276. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  6277. }
  6278. Index++;
  6279. }
  6280. }
  6281. //---------------------------------------------------------------------------
  6282. void __fastcall TTerminal::SourceRobust(
  6283. const UnicodeString & FileName, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6284. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  6285. {
  6286. TUploadSessionAction Action(ActionLog);
  6287. bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
  6288. TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny);
  6289. do
  6290. {
  6291. bool ChildError = false;
  6292. try
  6293. {
  6294. Source(FileName, TargetDir, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
  6295. }
  6296. catch (Exception & E)
  6297. {
  6298. if (!RobustLoop.TryReopen(E))
  6299. {
  6300. if (!ChildError)
  6301. {
  6302. RollbackAction(Action, OperationProgress, &E);
  6303. }
  6304. throw;
  6305. }
  6306. }
  6307. if (RobustLoop.ShouldRetry())
  6308. {
  6309. OperationProgress->RollbackTransfer();
  6310. Action.Restart();
  6311. // prevent overwrite and resume confirmations (should not be set for directories!)
  6312. Params |= cpNoConfirmation;
  6313. // enable resume even if we are uploading into new directory
  6314. Flags &= ~tfNewDirectory;
  6315. Flags |= tfAutoResume;
  6316. }
  6317. }
  6318. while (RobustLoop.Retry());
  6319. }
  6320. //---------------------------------------------------------------------------
  6321. void __fastcall TTerminal::CreateTargetDirectory(
  6322. const UnicodeString & DirectoryPath, int Attrs, const TCopyParamType * CopyParam)
  6323. {
  6324. TRemoteProperties Properties;
  6325. if (CopyParam->PreserveRights)
  6326. {
  6327. Properties.Valid = TValidProperties() << vpRights;
  6328. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  6329. }
  6330. CreateDirectory(DirectoryPath, &Properties);
  6331. }
  6332. //---------------------------------------------------------------------------
  6333. void __fastcall TTerminal::DirectorySource(
  6334. const UnicodeString & DirectoryName, const UnicodeString & TargetDir, const UnicodeString & DestDirectoryName,
  6335. int Attrs, const TCopyParamType * CopyParam, int Params,
  6336. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  6337. {
  6338. FFileSystem->TransferOnDirectory(TargetDir, CopyParam, Params);
  6339. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  6340. OperationProgress->SetFile(DirectoryName);
  6341. bool PostCreateDir = FLAGCLEAR(Flags, tfPreCreateDir);
  6342. // WebDAV and SFTP
  6343. if (!PostCreateDir)
  6344. {
  6345. // This is originally a code for WebDAV, SFTP used a slightly different logic,
  6346. // but functionally it should be very similar.
  6347. if (!FileExists(DestFullName))
  6348. {
  6349. CreateTargetDirectory(DestFullName, Attrs, CopyParam);
  6350. Flags |= tfNewDirectory;
  6351. }
  6352. }
  6353. if (FLAGCLEAR(Params, cpNoRecurse))
  6354. {
  6355. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  6356. TSearchRecChecked SearchRec;
  6357. bool FindOK;
  6358. FILE_OPERATION_LOOP_BEGIN
  6359. {
  6360. FindOK =
  6361. (FindFirstChecked(DirectoryName + L"*.*", FindAttrs, SearchRec) == 0);
  6362. }
  6363. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  6364. try
  6365. {
  6366. while (FindOK && !OperationProgress->Cancel)
  6367. {
  6368. UnicodeString FileName = DirectoryName + SearchRec.Name;
  6369. try
  6370. {
  6371. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  6372. {
  6373. SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress, (Flags & ~(tfFirstLevel | tfAutoResume)));
  6374. // FTP: if any file got uploaded (i.e. there were any file in the directory and at least one was not skipped),
  6375. // do not try to create the directory, as it should be already created by FZAPI during upload
  6376. PostCreateDir = false;
  6377. }
  6378. }
  6379. catch (ESkipFile &E)
  6380. {
  6381. // If ESkipFile occurs, just log it and continue with next file
  6382. TSuspendFileOperationProgress Suspend(OperationProgress);
  6383. // here a message to user was displayed, which was not appropriate
  6384. // when user refused to overwrite the file in subdirectory.
  6385. // hopefully it won't be missing in other situations.
  6386. if (!HandleException(&E))
  6387. {
  6388. throw;
  6389. }
  6390. }
  6391. FILE_OPERATION_LOOP_BEGIN
  6392. {
  6393. FindOK = (FindNextChecked(SearchRec) == 0);
  6394. }
  6395. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (DirectoryName)));
  6396. }
  6397. }
  6398. __finally
  6399. {
  6400. FindClose(SearchRec);
  6401. }
  6402. // FTP
  6403. if (PostCreateDir)
  6404. {
  6405. TRemoteFile * File = NULL;
  6406. // ignore non-fatal error when the directory already exists
  6407. bool DoCreate =
  6408. !FileExists(DestFullName, &File) ||
  6409. !File->IsDirectory; // just try to create and make it fail
  6410. delete File;
  6411. if (DoCreate)
  6412. {
  6413. CreateTargetDirectory(DestFullName, Attrs, CopyParam);
  6414. }
  6415. }
  6416. // TODO : Delete also read-only directories.
  6417. // TODO : Show error message on failure.
  6418. if (!OperationProgress->Cancel)
  6419. {
  6420. if (IsCapable[fcPreservingTimestampDirs] && CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  6421. {
  6422. TRemoteProperties Properties;
  6423. Properties.Valid << vpModification;
  6424. OpenLocalFile(
  6425. ExcludeTrailingBackslash(DirectoryName), GENERIC_READ, NULL, NULL, NULL,
  6426. &Properties.Modification, &Properties.LastAccess, NULL);
  6427. ChangeFileProperties(DestFullName, NULL, &Properties);
  6428. }
  6429. if (FLAGSET(Params, cpDelete))
  6430. {
  6431. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  6432. RemoveDir(ApiPath(DirectoryName));
  6433. }
  6434. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  6435. {
  6436. FILE_OPERATION_LOOP_BEGIN
  6437. {
  6438. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  6439. }
  6440. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  6441. }
  6442. }
  6443. }
  6444. }
  6445. //---------------------------------------------------------------------------
  6446. void __fastcall TTerminal::SelectTransferMode(
  6447. const UnicodeString & BaseFileName, TOperationSide Side, const TCopyParamType * CopyParam,
  6448. const TFileMasks::TParams & MaskParams)
  6449. {
  6450. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(BaseFileName, Side, MaskParams));
  6451. UnicodeString ModeName = (OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary");
  6452. LogEvent(FORMAT(L"%s transfer mode selected.", (ModeName)));
  6453. }
  6454. //---------------------------------------------------------------------------
  6455. void __fastcall TTerminal::SelectSourceTransferMode(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam)
  6456. {
  6457. // Will we use ASCII or BINARY file transfer?
  6458. TFileMasks::TParams MaskParams;
  6459. MaskParams.Size = Handle.Size;
  6460. MaskParams.Modification = Handle.Modification;
  6461. UnicodeString BaseFileName = GetBaseFileName(Handle.FileName);
  6462. SelectTransferMode(BaseFileName, osLocal, CopyParam, MaskParams);
  6463. }
  6464. //---------------------------------------------------------------------------
  6465. void __fastcall TTerminal::UpdateSource(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam, int Params)
  6466. {
  6467. // TODO: Delete also read-only files.
  6468. if (FLAGSET(Params, cpDelete))
  6469. {
  6470. if (!Handle.Directory)
  6471. {
  6472. FILE_OPERATION_LOOP_BEGIN
  6473. {
  6474. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(Handle.FileName)));
  6475. }
  6476. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (Handle.FileName)));
  6477. }
  6478. }
  6479. else if (CopyParam->ClearArchive && FLAGSET(Handle.Attrs, faArchive))
  6480. {
  6481. FILE_OPERATION_LOOP_BEGIN
  6482. {
  6483. THROWOSIFFALSE(FileSetAttr(ApiPath(Handle.FileName), (Handle.Attrs & ~faArchive)) == 0);
  6484. }
  6485. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (Handle.FileName)));
  6486. }
  6487. }
  6488. //---------------------------------------------------------------------------
  6489. void __fastcall TTerminal::Source(
  6490. const UnicodeString & FileName, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6491. TFileOperationProgressType * OperationProgress, unsigned int Flags, TUploadSessionAction & Action, bool & ChildError)
  6492. {
  6493. Action.FileName(ExpandUNCFileName(FileName));
  6494. OperationProgress->SetFile(FileName, false);
  6495. if (!AllowLocalFileTransfer(FileName, CopyParam, OperationProgress))
  6496. {
  6497. throw ESkipFile();
  6498. }
  6499. TLocalFileHandle Handle;
  6500. OpenLocalFile(FileName, GENERIC_READ, Handle);
  6501. OperationProgress->SetFileInProgress();
  6502. UnicodeString DestFileName =
  6503. ChangeFileName(CopyParam, ExtractFileName(FileName), osLocal, FLAGSET(Flags, tfFirstLevel));
  6504. if (Handle.Directory)
  6505. {
  6506. Action.Cancel();
  6507. DirectorySource(
  6508. IncludeTrailingBackslash(FileName), TargetDir, DestFileName, Handle.Attrs,
  6509. CopyParam, Params, OperationProgress, Flags);
  6510. }
  6511. else
  6512. {
  6513. LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  6514. OperationProgress->SetLocalSize(Handle.Size);
  6515. // Suppose same data size to transfer as to read
  6516. // (not true with ASCII transfer)
  6517. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  6518. if (IsCapable[fcTextMode])
  6519. {
  6520. SelectSourceTransferMode(Handle, CopyParam);
  6521. }
  6522. FFileSystem->Source(
  6523. Handle, TargetDir, DestFileName, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
  6524. LogFileDone(OperationProgress, AbsolutePath(TargetDir + DestFileName, true));
  6525. }
  6526. Handle.Release();
  6527. UpdateSource(Handle, CopyParam, Params);
  6528. }
  6529. //---------------------------------------------------------------------------
  6530. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  6531. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  6532. TParallelOperation * ParallelOperation)
  6533. {
  6534. DebugAssert(FFileSystem);
  6535. // see scp.c: sink(), tolocal()
  6536. bool Result = false;
  6537. DebugAssert(FilesToCopy != NULL);
  6538. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6539. FDestFileName = L"";
  6540. FMultipleDestinationFiles = false;
  6541. BeginTransaction();
  6542. try
  6543. {
  6544. __int64 TotalSize;
  6545. bool TotalSizeKnown = false;
  6546. FLastProgressLogged = GetTickCount();
  6547. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  6548. std::unique_ptr<TStringList> Files;
  6549. if (CanParallel(CopyParam, Params, ParallelOperation))
  6550. {
  6551. Files.reset(new TStringList());
  6552. Files->OwnsObjects = true;
  6553. }
  6554. ExceptionOnFail = true;
  6555. try
  6556. {
  6557. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  6558. TCalculateSizeStats Stats;
  6559. Stats.FoundFiles = Files.get();
  6560. if (CalculateFilesSize(
  6561. FilesToCopy, TotalSize, csIgnoreErrors,
  6562. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  6563. CopyParam->CalculateSize, Stats))
  6564. {
  6565. TotalSizeKnown = true;
  6566. }
  6567. }
  6568. __finally
  6569. {
  6570. ExceptionOnFail = false;
  6571. }
  6572. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  6573. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  6574. FOperationProgress = &OperationProgress;
  6575. bool CollectingUsage = false;
  6576. try
  6577. {
  6578. if (TotalSizeKnown)
  6579. {
  6580. if (Configuration->Usage->Collect)
  6581. {
  6582. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  6583. Configuration->Usage->Inc(L"Downloads");
  6584. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  6585. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  6586. CollectingUsage = true;
  6587. }
  6588. OperationProgress.SetTotalSize(TotalSize);
  6589. }
  6590. try
  6591. {
  6592. try
  6593. {
  6594. bool Parallel = TotalSizeKnown && (Files.get() != NULL);
  6595. LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
  6596. if (Parallel)
  6597. {
  6598. // OnceDoneOperation is not supported
  6599. ParallelOperation->Init(Files.release(), TargetDir, CopyParam, Params, &OperationProgress, Log->Name);
  6600. CopyParallel(ParallelOperation, &OperationProgress);
  6601. }
  6602. else
  6603. {
  6604. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  6605. &OperationProgress, OnceDoneOperation);
  6606. }
  6607. LogTotalTransferDone(&OperationProgress);
  6608. }
  6609. __finally
  6610. {
  6611. if (Active)
  6612. {
  6613. ReactOnCommand(fsCopyToLocal);
  6614. }
  6615. }
  6616. }
  6617. catch (Exception &E)
  6618. {
  6619. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  6620. OnceDoneOperation = odoIdle;
  6621. }
  6622. if (OperationProgress.Cancel == csContinue)
  6623. {
  6624. Result = true;
  6625. }
  6626. }
  6627. __finally
  6628. {
  6629. if (CollectingUsage)
  6630. {
  6631. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  6632. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  6633. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  6634. }
  6635. FOperationProgress = NULL;
  6636. OperationProgress.Stop();
  6637. }
  6638. }
  6639. __finally
  6640. {
  6641. // If session is still active (no fatal error) we reload directory
  6642. // by calling EndTransaction
  6643. EndTransaction();
  6644. }
  6645. if (OnceDoneOperation != odoIdle)
  6646. {
  6647. UnicodeString DestFileName;
  6648. if (!FMultipleDestinationFiles)
  6649. {
  6650. DestFileName = FDestFileName;
  6651. }
  6652. CloseOnCompletion(OnceDoneOperation, UnicodeString(), TargetDir, DestFileName);
  6653. }
  6654. return Result;
  6655. }
  6656. //---------------------------------------------------------------------------
  6657. void __fastcall TTerminal::DoCopyToLocal(
  6658. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6659. TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
  6660. {
  6661. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  6662. UnicodeString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  6663. int Index = 0;
  6664. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  6665. {
  6666. bool Success = false;
  6667. UnicodeString FileName = FilesToCopy->Strings[Index];
  6668. try
  6669. {
  6670. try
  6671. {
  6672. UnicodeString AbsoluteFileName = AbsolutePath(FileName, true);
  6673. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  6674. SinkRobust(AbsoluteFileName, File, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
  6675. Success = true;
  6676. }
  6677. catch (ESkipFile & E)
  6678. {
  6679. TSuspendFileOperationProgress Suspend(OperationProgress);
  6680. if (!HandleException(&E))
  6681. {
  6682. throw;
  6683. }
  6684. }
  6685. }
  6686. __finally
  6687. {
  6688. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  6689. }
  6690. Index++;
  6691. }
  6692. }
  6693. //---------------------------------------------------------------------------
  6694. void __fastcall TTerminal::SinkRobust(
  6695. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
  6696. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  6697. {
  6698. TDownloadSessionAction Action(ActionLog);
  6699. bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
  6700. TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny);
  6701. bool Sunk = false;
  6702. do
  6703. {
  6704. try
  6705. {
  6706. // If connection is lost while deleting the file, so not retry download on the next round.
  6707. // The file may not exist anymore and the download attempt might overwrite the (only) local copy.
  6708. if (!Sunk)
  6709. {
  6710. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress, Flags, Action);
  6711. Sunk = true;
  6712. }
  6713. if (FLAGSET(Params, cpDelete))
  6714. {
  6715. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  6716. // If file is directory, do not delete it recursively, because it should be
  6717. // empty already. If not, it should not be deleted (some files were
  6718. // skipped or some new files were copied to it, while we were downloading)
  6719. int Params = dfNoRecursive;
  6720. DeleteFile(FileName, File, &Params);
  6721. }
  6722. }
  6723. catch (Exception & E)
  6724. {
  6725. if (!RobustLoop.TryReopen(E))
  6726. {
  6727. if (!Sunk)
  6728. {
  6729. RollbackAction(Action, OperationProgress, &E);
  6730. }
  6731. throw;
  6732. }
  6733. }
  6734. if (RobustLoop.ShouldRetry())
  6735. {
  6736. OperationProgress->RollbackTransfer();
  6737. Action.Restart();
  6738. DebugAssert(File != NULL);
  6739. if (!File->IsDirectory)
  6740. {
  6741. // prevent overwrite and resume confirmations
  6742. Params |= cpNoConfirmation;
  6743. Flags |= tfAutoResume;
  6744. }
  6745. }
  6746. }
  6747. while (RobustLoop.Retry());
  6748. }
  6749. //---------------------------------------------------------------------------
  6750. struct TSinkFileParams
  6751. {
  6752. UnicodeString TargetDir;
  6753. const TCopyParamType * CopyParam;
  6754. int Params;
  6755. TFileOperationProgressType * OperationProgress;
  6756. bool Skipped;
  6757. unsigned int Flags;
  6758. };
  6759. //---------------------------------------------------------------------------
  6760. void __fastcall TTerminal::Sink(
  6761. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
  6762. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags,
  6763. TDownloadSessionAction & Action)
  6764. {
  6765. Action.FileName(FileName);
  6766. TFileMasks::TParams MaskParams;
  6767. DebugAssert(File);
  6768. MaskParams.Size = File->Size;
  6769. MaskParams.Modification = File->Modification;
  6770. UnicodeString BaseFileName = GetBaseFileName(FileName);
  6771. if (!CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams))
  6772. {
  6773. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  6774. throw ESkipFile();
  6775. }
  6776. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  6777. {
  6778. OperationProgress->AddSkippedFileSize(File->Size);
  6779. throw ESkipFile();
  6780. }
  6781. LogFileDetails(FileName, File->Modification, File->Size);
  6782. OperationProgress->SetFile(FileName);
  6783. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  6784. UnicodeString DestFileName = ChangeFileName(CopyParam, OnlyFileName, osRemote, FLAGSET(Flags, tfFirstLevel));
  6785. UnicodeString DestFullName = TargetDir + DestFileName;
  6786. if (File->IsDirectory)
  6787. {
  6788. Action.Cancel();
  6789. if (CanRecurseToDirectory(File))
  6790. {
  6791. FILE_OPERATION_LOOP_BEGIN
  6792. {
  6793. int Attrs = FileGetAttrFix(ApiPath(DestFullName));
  6794. if (FLAGCLEAR(Attrs, faDirectory))
  6795. {
  6796. EXCEPTION;
  6797. }
  6798. }
  6799. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  6800. FILE_OPERATION_LOOP_BEGIN
  6801. {
  6802. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  6803. }
  6804. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  6805. if (FLAGCLEAR(Params, cpNoRecurse))
  6806. {
  6807. TSinkFileParams SinkFileParams;
  6808. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  6809. SinkFileParams.CopyParam = CopyParam;
  6810. SinkFileParams.Params = Params;
  6811. SinkFileParams.OperationProgress = OperationProgress;
  6812. SinkFileParams.Skipped = false;
  6813. SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
  6814. ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  6815. FFileSystem->DirectorySunk(DestFullName, File, CopyParam);
  6816. // Do not delete directory if some of its files were skip.
  6817. // Throw "skip file" for the directory to avoid attempt to deletion
  6818. // of any parent directory
  6819. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  6820. {
  6821. throw ESkipFile();
  6822. }
  6823. }
  6824. }
  6825. else
  6826. {
  6827. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (FileName)));
  6828. }
  6829. }
  6830. else
  6831. {
  6832. LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  6833. // Will we use ASCII of BINARY file transfer?
  6834. SelectTransferMode(BaseFileName, osRemote, CopyParam, MaskParams);
  6835. // Suppose same data size to transfer as to write
  6836. // (not true with ASCII transfer)
  6837. OperationProgress->SetTransferSize(File->Size);
  6838. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  6839. int Attrs;
  6840. FILE_OPERATION_LOOP_BEGIN
  6841. {
  6842. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  6843. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
  6844. {
  6845. EXCEPTION;
  6846. }
  6847. }
  6848. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  6849. FFileSystem->Sink(
  6850. FileName, File, TargetDir, DestFileName, Attrs, CopyParam, Params, OperationProgress, Flags, Action);
  6851. LogFileDone(OperationProgress, ExpandUNCFileName(DestFullName));
  6852. }
  6853. }
  6854. //---------------------------------------------------------------------------
  6855. void __fastcall TTerminal::UpdateTargetAttrs(
  6856. const UnicodeString & DestFullName, const TRemoteFile * File, const TCopyParamType * CopyParam, int Attrs)
  6857. {
  6858. if (Attrs == -1)
  6859. {
  6860. Attrs = faArchive;
  6861. }
  6862. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  6863. if ((NewAttrs & Attrs) != NewAttrs)
  6864. {
  6865. FILE_OPERATION_LOOP_BEGIN
  6866. {
  6867. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  6868. }
  6869. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  6870. }
  6871. }
  6872. //---------------------------------------------------------------------------
  6873. void __fastcall TTerminal::UpdateTargetTime(HANDLE Handle, TDateTime Modification, TDSTMode DSTMode)
  6874. {
  6875. LogEvent(FORMAT(L"Preserving timestamp [%s]", (StandardTimestamp(Modification))));
  6876. FILETIME WrTime = DateTimeToFileTime(Modification, DSTMode);
  6877. if (!SetFileTime(Handle, NULL, NULL, &WrTime))
  6878. {
  6879. int Error = GetLastError();
  6880. LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s", (SysErrorMessageForError(Error))));
  6881. }
  6882. }
  6883. //---------------------------------------------------------------------------
  6884. void __fastcall TTerminal::SinkFile(UnicodeString FileName, const TRemoteFile * File, void * Param)
  6885. {
  6886. TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
  6887. DebugAssert(Params->OperationProgress != NULL);
  6888. try
  6889. {
  6890. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  6891. Params->Params, Params->OperationProgress, Params->Flags);
  6892. }
  6893. catch (ESkipFile & E)
  6894. {
  6895. Params->Skipped = true;
  6896. {
  6897. TSuspendFileOperationProgress Suspend(Params->OperationProgress);
  6898. if (!HandleException(&E))
  6899. {
  6900. throw;
  6901. }
  6902. }
  6903. if (Params->OperationProgress->Cancel)
  6904. {
  6905. Abort();
  6906. }
  6907. }
  6908. }
  6909. //---------------------------------------------------------------------------
  6910. void __fastcall TTerminal::ReflectSettings()
  6911. {
  6912. DebugAssert(FLog != NULL);
  6913. FLog->ReflectSettings();
  6914. DebugAssert(FActionLog != NULL);
  6915. FActionLog->ReflectSettings();
  6916. // also FTunnelLog ?
  6917. }
  6918. //---------------------------------------------------------------------------
  6919. void __fastcall TTerminal::CollectUsage()
  6920. {
  6921. switch (SessionData->FSProtocol)
  6922. {
  6923. case fsSCPonly:
  6924. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  6925. break;
  6926. case fsSFTP:
  6927. case fsSFTPonly:
  6928. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  6929. break;
  6930. case fsFTP:
  6931. if (SessionData->Ftps == ftpsNone)
  6932. {
  6933. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  6934. }
  6935. else
  6936. {
  6937. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  6938. }
  6939. break;
  6940. case fsWebDAV:
  6941. if (SessionData->Ftps == ftpsNone)
  6942. {
  6943. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  6944. }
  6945. else
  6946. {
  6947. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  6948. }
  6949. break;
  6950. case fsS3:
  6951. Configuration->Usage->Inc(L"OpenedSessionsS3");
  6952. break;
  6953. }
  6954. if (Configuration->Logging && Configuration->LogToFile)
  6955. {
  6956. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  6957. }
  6958. if (Configuration->LogActions)
  6959. {
  6960. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  6961. }
  6962. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  6963. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  6964. {
  6965. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  6966. }
  6967. if (SessionData->ProxyMethod != ::pmNone)
  6968. {
  6969. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  6970. }
  6971. if (SessionData->FtpProxyLogonType > 0)
  6972. {
  6973. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  6974. }
  6975. FCollectFileSystemUsage = true;
  6976. }
  6977. //---------------------------------------------------------------------------
  6978. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  6979. {
  6980. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  6981. }
  6982. //---------------------------------------------------------------------------
  6983. bool __fastcall TTerminal::VerifyCertificate(
  6984. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  6985. const UnicodeString & Fingerprint,
  6986. const UnicodeString & CertificateSubject, int Failures)
  6987. {
  6988. bool Result = false;
  6989. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  6990. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  6991. Storage->AccessMode = smRead;
  6992. if (Storage->OpenSubKey(CertificateStorageKey, false))
  6993. {
  6994. if (Storage->ValueExists(SiteKey))
  6995. {
  6996. UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
  6997. if (CertificateData == CachedCertificateData)
  6998. {
  6999. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  7000. Result = true;
  7001. }
  7002. }
  7003. else if (Storage->ValueExists(Fingerprint))
  7004. {
  7005. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  7006. Result = true;
  7007. }
  7008. }
  7009. if (!Result)
  7010. {
  7011. UnicodeString Buf = SessionData->HostKey;
  7012. while (!Result && !Buf.IsEmpty())
  7013. {
  7014. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  7015. if (ExpectedKey == L"*")
  7016. {
  7017. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  7018. Information(Message, true);
  7019. Log->Add(llException, Message);
  7020. Result = true;
  7021. }
  7022. else if (ExpectedKey == Fingerprint)
  7023. {
  7024. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  7025. Result = true;
  7026. }
  7027. }
  7028. }
  7029. return Result;
  7030. }
  7031. //---------------------------------------------------------------------------
  7032. bool __fastcall TTerminal::ConfirmCertificate(
  7033. TSessionInfo & SessionInfo, int Failures, const UnicodeString & CertificateStorageKey, bool CanRemember)
  7034. {
  7035. TClipboardHandler ClipboardHandler;
  7036. ClipboardHandler.Text = SessionInfo.CertificateFingerprint;
  7037. TQueryButtonAlias Aliases[1];
  7038. Aliases[0].Button = qaRetry;
  7039. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  7040. Aliases[0].ActionAlias = LoadStr(COPY_CERTIFICATE_ACTION);
  7041. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  7042. TQueryParams Params(qpWaitInBatch);
  7043. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  7044. Params.NoBatchAnswers = qaYes | qaRetry;
  7045. Params.Aliases = Aliases;
  7046. Params.AliasesCount = LENOF(Aliases);
  7047. unsigned int Answer =
  7048. QueryUser(
  7049. FMTLOAD(VERIFY_CERT_PROMPT3, (SessionInfo.Certificate)),
  7050. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  7051. bool Result;
  7052. switch (Answer)
  7053. {
  7054. case qaYes:
  7055. CacheCertificate(
  7056. CertificateStorageKey, SessionData->SiteKey, SessionInfo.CertificateFingerprint, Failures);
  7057. Result = true;
  7058. break;
  7059. case qaNo:
  7060. Result = true;
  7061. break;
  7062. case qaCancel:
  7063. Configuration->Usage->Inc(L"HostNotVerified");
  7064. Result = false;
  7065. break;
  7066. default:
  7067. DebugFail();
  7068. Result = false;
  7069. break;
  7070. }
  7071. // Cache only if the certificate was accepted manually
  7072. if (Result && CanRemember)
  7073. {
  7074. Configuration->RememberLastFingerprint(
  7075. SessionData->SiteKey, TlsFingerprintType, SessionInfo.CertificateFingerprint);
  7076. }
  7077. return Result;
  7078. }
  7079. //---------------------------------------------------------------------------
  7080. void __fastcall TTerminal::CacheCertificate(const UnicodeString & CertificateStorageKey,
  7081. const UnicodeString & SiteKey, const UnicodeString & Fingerprint, int Failures)
  7082. {
  7083. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  7084. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  7085. Storage->AccessMode = smReadWrite;
  7086. if (Storage->OpenSubKey(CertificateStorageKey, true))
  7087. {
  7088. Storage->WriteString(SiteKey, CertificateData);
  7089. }
  7090. }
  7091. //---------------------------------------------------------------------------
  7092. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  7093. {
  7094. // see SSL_get_version() in OpenSSL ssl_lib.c
  7095. if (TlsVersionStr == L"TLSv1.2")
  7096. {
  7097. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  7098. }
  7099. else if (TlsVersionStr == L"TLSv1.1")
  7100. {
  7101. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  7102. }
  7103. else if (TlsVersionStr == L"TLSv1")
  7104. {
  7105. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  7106. }
  7107. else if (TlsVersionStr == L"SSLv3")
  7108. {
  7109. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  7110. }
  7111. else if (TlsVersionStr == L"SSLv2")
  7112. {
  7113. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  7114. }
  7115. else
  7116. {
  7117. DebugFail();
  7118. }
  7119. }
  7120. //---------------------------------------------------------------------------
  7121. bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
  7122. {
  7123. bool Result = !SessionData->TlsCertificateFile.IsEmpty();
  7124. if (Result)
  7125. {
  7126. UnicodeString Passphrase = SessionData->Passphrase;
  7127. // Inspired by neon's ne_ssl_clicert_read
  7128. bool Retry;
  7129. do
  7130. {
  7131. Retry = false;
  7132. bool WrongPassphrase = false;
  7133. ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
  7134. if (WrongPassphrase)
  7135. {
  7136. if (Passphrase.IsEmpty())
  7137. {
  7138. LogEvent(L"Certificate is encrypted, need passphrase");
  7139. Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
  7140. }
  7141. else
  7142. {
  7143. Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
  7144. }
  7145. Passphrase = L"";
  7146. if (PromptUser(
  7147. SessionData, pkPassphrase,
  7148. LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
  7149. LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
  7150. {
  7151. Retry = true;
  7152. }
  7153. else
  7154. {
  7155. Result = false;
  7156. }
  7157. }
  7158. }
  7159. while (Retry);
  7160. }
  7161. return Result;
  7162. }
  7163. //---------------------------------------------------------------------------
  7164. UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
  7165. {
  7166. if (FSessionData->TrimVMSVersions)
  7167. {
  7168. int P = FileName.LastDelimiter(L";");
  7169. if (P > 0)
  7170. {
  7171. FileName.SetLength(P - 1);
  7172. }
  7173. }
  7174. return FileName;
  7175. }
  7176. //---------------------------------------------------------------------------
  7177. UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
  7178. UnicodeString FileName, TOperationSide Side, bool FirstLevel)
  7179. {
  7180. FileName = GetBaseFileName(FileName);
  7181. FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
  7182. return FileName;
  7183. }
  7184. //---------------------------------------------------------------------------
  7185. bool __fastcall TTerminal::CanRecurseToDirectory(const TRemoteFile * File)
  7186. {
  7187. return !File->IsSymLink || FSessionData->FollowDirectorySymlinks;
  7188. }
  7189. //---------------------------------------------------------------------------
  7190. bool __fastcall TTerminal::IsThisOrChild(TTerminal * Terminal)
  7191. {
  7192. return
  7193. (this == Terminal) ||
  7194. ((FCommandSession != NULL) && (FCommandSession == Terminal));
  7195. }
  7196. //---------------------------------------------------------------------------
  7197. //---------------------------------------------------------------------------
  7198. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  7199. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  7200. TTerminal(ASessionData, Configuration),
  7201. FMainTerminal(MainTerminal)
  7202. {
  7203. Log->SetParent(FMainTerminal->Log, Name);
  7204. ActionLog->Enabled = false;
  7205. SessionData->NonPersistant();
  7206. DebugAssert(FMainTerminal != NULL);
  7207. if (!FMainTerminal->UserName.IsEmpty())
  7208. {
  7209. SessionData->UserName = FMainTerminal->UserName;
  7210. }
  7211. }
  7212. //---------------------------------------------------------------------------
  7213. void __fastcall TSecondaryTerminal::UpdateFromMain()
  7214. {
  7215. if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
  7216. {
  7217. FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
  7218. }
  7219. }
  7220. //---------------------------------------------------------------------------
  7221. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  7222. {
  7223. FMainTerminal->DirectoryLoaded(FileList);
  7224. DebugAssert(FileList != NULL);
  7225. }
  7226. //---------------------------------------------------------------------------
  7227. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  7228. bool SubDirs)
  7229. {
  7230. // clear cache of main terminal
  7231. FMainTerminal->DirectoryModified(Path, SubDirs);
  7232. }
  7233. //---------------------------------------------------------------------------
  7234. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  7235. {
  7236. return FMainTerminal;
  7237. }
  7238. //---------------------------------------------------------------------------
  7239. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  7240. TObjectList()
  7241. {
  7242. DebugAssert(AConfiguration);
  7243. FConfiguration = AConfiguration;
  7244. }
  7245. //---------------------------------------------------------------------------
  7246. __fastcall TTerminalList::~TTerminalList()
  7247. {
  7248. DebugAssert(Count == 0);
  7249. }
  7250. //---------------------------------------------------------------------------
  7251. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  7252. {
  7253. return new TTerminal(Data, FConfiguration);
  7254. }
  7255. //---------------------------------------------------------------------------
  7256. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  7257. {
  7258. TTerminal * Terminal = CreateTerminal(Data);
  7259. Add(Terminal);
  7260. return Terminal;
  7261. }
  7262. //---------------------------------------------------------------------------
  7263. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  7264. {
  7265. DebugAssert(IndexOf(Terminal) >= 0);
  7266. Remove(Terminal);
  7267. }
  7268. //---------------------------------------------------------------------------
  7269. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  7270. {
  7271. TTerminal * T = Terminal;
  7272. Terminal = NULL;
  7273. FreeTerminal(T);
  7274. }
  7275. //---------------------------------------------------------------------------
  7276. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  7277. {
  7278. return dynamic_cast<TTerminal *>(Items[Index]);
  7279. }
  7280. //---------------------------------------------------------------------------
  7281. void __fastcall TTerminalList::RecryptPasswords()
  7282. {
  7283. for (int Index = 0; Index < Count; Index++)
  7284. {
  7285. Terminals[Index]->RecryptPasswords();
  7286. }
  7287. }
  7288. //---------------------------------------------------------------------------
  7289. //---------------------------------------------------------------------------
  7290. TLocalFileHandle::TLocalFileHandle()
  7291. {
  7292. Handle = 0;
  7293. Attrs = 0;
  7294. MTime = 0;
  7295. ATime = 0;
  7296. Size = 0;
  7297. Directory = false;
  7298. }
  7299. //---------------------------------------------------------------------------
  7300. TLocalFileHandle::~TLocalFileHandle()
  7301. {
  7302. Release();
  7303. }
  7304. //---------------------------------------------------------------------------
  7305. void TLocalFileHandle::Release()
  7306. {
  7307. if (Handle != 0)
  7308. {
  7309. Close();
  7310. }
  7311. }
  7312. //---------------------------------------------------------------------------
  7313. void TLocalFileHandle::Dismiss()
  7314. {
  7315. if (DebugAlwaysTrue(Handle != 0))
  7316. {
  7317. Handle = 0;
  7318. }
  7319. }
  7320. //---------------------------------------------------------------------------
  7321. void TLocalFileHandle::Close()
  7322. {
  7323. if (DebugAlwaysTrue(Handle != 0))
  7324. {
  7325. CloseHandle(Handle);
  7326. Dismiss();
  7327. }
  7328. }