Terminal.cpp 249 KB

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