Terminal.cpp 213 KB

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