Terminal.cpp 250 KB

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