Terminal.cpp 214 KB

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