Terminal.cpp 251 KB

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