1
0

Terminal.cpp 207 KB

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