Terminal.cpp 230 KB

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