Terminal.cpp 214 KB

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