Terminal.cpp 173 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include "Common.h"
  8. #include "PuttyTools.h"
  9. #include "FileBuffer.h"
  10. #include "Interface.h"
  11. #include "RemoteFiles.h"
  12. #include "SecureShell.h"
  13. #include "ScpFileSystem.h"
  14. #include "SftpFileSystem.h"
  15. #ifndef NO_FILEZILLA
  16. #include "FtpFileSystem.h"
  17. #endif
  18. #include "WebDAVFileSystem.h"
  19. #include "TextsCore.h"
  20. #include "HelpCore.h"
  21. #include "CoreMain.h"
  22. #include "Queue.h"
  23. #ifndef AUTO_WINSOCK
  24. #include <winsock2.h>
  25. #endif
  26. //---------------------------------------------------------------------------
  27. #pragma package(smart_init)
  28. //---------------------------------------------------------------------------
  29. #define COMMAND_ERROR_ARI(MESSAGE, REPEAT) \
  30. { \
  31. unsigned int Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  32. switch (Result) { \
  33. case qaRetry: { REPEAT; } break; \
  34. case qaAbort: Abort(); \
  35. } \
  36. }
  37. //---------------------------------------------------------------------------
  38. // Note that the action may already be canceled when RollbackAction is called
  39. #define COMMAND_ERROR_ARI_ACTION(MESSAGE, REPEAT, ACTION) \
  40. { \
  41. unsigned int Result; \
  42. try \
  43. { \
  44. Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  45. } \
  46. catch(Exception & E2) \
  47. { \
  48. RollbackAction(ACTION, NULL, &E2); \
  49. throw; \
  50. } \
  51. switch (Result) { \
  52. case qaRetry: ACTION.Cancel(); { REPEAT; } break; \
  53. case qaAbort: RollbackAction(ACTION, NULL, &E); Abort(); \
  54. case qaSkip: ACTION.Cancel(); break; \
  55. default: FAIL; \
  56. } \
  57. }
  58. #define FILE_OPERATION_LOOP_TERMINAL this
  59. //---------------------------------------------------------------------------
  60. //---------------------------------------------------------------------------
  61. class TLoopDetector
  62. {
  63. public:
  64. __fastcall TLoopDetector();
  65. void __fastcall RecordVisitedDirectory(const UnicodeString & Directory);
  66. bool __fastcall IsUnvisitedDirectory(const TRemoteFile * File);
  67. private:
  68. std::unique_ptr<TStringList> FVisitedDirectories;
  69. };
  70. //---------------------------------------------------------------------------
  71. __fastcall TLoopDetector::TLoopDetector()
  72. {
  73. FVisitedDirectories.reset(new TStringList());
  74. FVisitedDirectories->Sorted = true;
  75. }
  76. //---------------------------------------------------------------------------
  77. void __fastcall TLoopDetector::RecordVisitedDirectory(const UnicodeString & Directory)
  78. {
  79. FVisitedDirectories->Add(ExcludeTrailingBackslash(Directory));
  80. }
  81. //---------------------------------------------------------------------------
  82. bool __fastcall TLoopDetector::IsUnvisitedDirectory(const TRemoteFile * File)
  83. {
  84. assert(File->IsDirectory);
  85. UnicodeString Directory = UnixExcludeTrailingBackslash(File->FullFileName);
  86. bool Result = (FVisitedDirectories->IndexOf(Directory) < 0);
  87. if (Result)
  88. {
  89. if (File->IsSymLink)
  90. {
  91. UnicodeString BaseDirectory = UnixExtractFileDir(Directory);
  92. UnicodeString SymlinkDirectory =
  93. UnixExcludeTrailingBackslash(AbsolutePath(BaseDirectory, File->LinkTo));
  94. Result = (FVisitedDirectories->IndexOf(SymlinkDirectory) < 0);
  95. }
  96. }
  97. if (Result)
  98. {
  99. RecordVisitedDirectory(Directory);
  100. }
  101. return Result;
  102. }
  103. //---------------------------------------------------------------------------
  104. //---------------------------------------------------------------------------
  105. struct TMoveFileParams
  106. {
  107. UnicodeString Target;
  108. UnicodeString FileMask;
  109. };
  110. //---------------------------------------------------------------------------
  111. struct TFilesFindParams
  112. {
  113. TFileMasks FileMask;
  114. TFileFoundEvent OnFileFound;
  115. TFindingFileEvent OnFindingFile;
  116. bool Cancel;
  117. TLoopDetector LoopDetector;
  118. };
  119. //---------------------------------------------------------------------------
  120. TCalculateSizeStats::TCalculateSizeStats()
  121. {
  122. memset(this, 0, sizeof(*this));
  123. }
  124. //---------------------------------------------------------------------------
  125. TSynchronizeOptions::TSynchronizeOptions()
  126. {
  127. memset(this, 0, sizeof(*this));
  128. }
  129. //---------------------------------------------------------------------------
  130. TSynchronizeOptions::~TSynchronizeOptions()
  131. {
  132. delete Filter;
  133. }
  134. //---------------------------------------------------------------------------
  135. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  136. {
  137. int FoundIndex;
  138. bool Result;
  139. if (Filter == NULL)
  140. {
  141. Result = true;
  142. }
  143. else
  144. {
  145. Result = Filter->Find(FileName, FoundIndex);
  146. }
  147. return Result;
  148. }
  149. //---------------------------------------------------------------------------
  150. TSpaceAvailable::TSpaceAvailable()
  151. {
  152. memset(this, 0, sizeof(*this));
  153. }
  154. //---------------------------------------------------------------------------
  155. TOverwriteFileParams::TOverwriteFileParams()
  156. {
  157. SourceSize = 0;
  158. DestSize = 0;
  159. SourcePrecision = mfFull;
  160. DestPrecision = mfFull;
  161. }
  162. //---------------------------------------------------------------------------
  163. //---------------------------------------------------------------------------
  164. TSynchronizeChecklist::TItem::TItem() :
  165. Action(saNone), IsDirectory(false), RemoteFile(NULL), Checked(true), ImageIndex(-1)
  166. {
  167. Local.ModificationFmt = mfFull;
  168. Local.Modification = 0;
  169. Local.Size = 0;
  170. Remote.ModificationFmt = mfFull;
  171. Remote.Modification = 0;
  172. Remote.Size = 0;
  173. }
  174. //---------------------------------------------------------------------------
  175. TSynchronizeChecklist::TItem::~TItem()
  176. {
  177. delete RemoteFile;
  178. }
  179. //---------------------------------------------------------------------------
  180. const UnicodeString& TSynchronizeChecklist::TItem::GetFileName() const
  181. {
  182. if (!Remote.FileName.IsEmpty())
  183. {
  184. return Remote.FileName;
  185. }
  186. else
  187. {
  188. assert(!Local.FileName.IsEmpty());
  189. return Local.FileName;
  190. }
  191. }
  192. //---------------------------------------------------------------------------
  193. //---------------------------------------------------------------------------
  194. TSynchronizeChecklist::TSynchronizeChecklist() :
  195. FList(new TList())
  196. {
  197. }
  198. //---------------------------------------------------------------------------
  199. TSynchronizeChecklist::~TSynchronizeChecklist()
  200. {
  201. for (int Index = 0; Index < FList->Count; Index++)
  202. {
  203. delete static_cast<TItem *>(FList->Items[Index]);
  204. }
  205. delete FList;
  206. }
  207. //---------------------------------------------------------------------------
  208. void TSynchronizeChecklist::Add(TItem * Item)
  209. {
  210. FList->Add(Item);
  211. }
  212. //---------------------------------------------------------------------------
  213. int __fastcall TSynchronizeChecklist::Compare(void * AItem1, void * AItem2)
  214. {
  215. TItem * Item1 = static_cast<TItem *>(AItem1);
  216. TItem * Item2 = static_cast<TItem *>(AItem2);
  217. int Result;
  218. if (!Item1->Local.Directory.IsEmpty())
  219. {
  220. Result = AnsiCompareText(Item1->Local.Directory, Item2->Local.Directory);
  221. }
  222. else
  223. {
  224. assert(!Item1->Remote.Directory.IsEmpty());
  225. Result = AnsiCompareText(Item1->Remote.Directory, Item2->Remote.Directory);
  226. }
  227. if (Result == 0)
  228. {
  229. Result = AnsiCompareText(Item1->GetFileName(), Item2->GetFileName());
  230. }
  231. return Result;
  232. }
  233. //---------------------------------------------------------------------------
  234. void TSynchronizeChecklist::Sort()
  235. {
  236. FList->Sort(Compare);
  237. }
  238. //---------------------------------------------------------------------------
  239. int TSynchronizeChecklist::GetCount() const
  240. {
  241. return FList->Count;
  242. }
  243. //---------------------------------------------------------------------------
  244. const TSynchronizeChecklist::TItem * TSynchronizeChecklist::GetItem(int Index) const
  245. {
  246. return static_cast<TItem *>(FList->Items[Index]);
  247. }
  248. //---------------------------------------------------------------------------
  249. //---------------------------------------------------------------------------
  250. class TTunnelThread : public TSimpleThread
  251. {
  252. public:
  253. __fastcall TTunnelThread(TSecureShell * SecureShell);
  254. virtual __fastcall ~TTunnelThread();
  255. virtual void __fastcall Terminate();
  256. protected:
  257. virtual void __fastcall Execute();
  258. private:
  259. TSecureShell * FSecureShell;
  260. bool FTerminated;
  261. };
  262. //---------------------------------------------------------------------------
  263. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  264. FSecureShell(SecureShell),
  265. FTerminated(false)
  266. {
  267. Start();
  268. }
  269. //---------------------------------------------------------------------------
  270. __fastcall TTunnelThread::~TTunnelThread()
  271. {
  272. // close before the class's virtual functions (Terminate particularly) are lost
  273. Close();
  274. }
  275. //---------------------------------------------------------------------------
  276. void __fastcall TTunnelThread::Terminate()
  277. {
  278. FTerminated = true;
  279. }
  280. //---------------------------------------------------------------------------
  281. void __fastcall TTunnelThread::Execute()
  282. {
  283. try
  284. {
  285. while (!FTerminated)
  286. {
  287. FSecureShell->Idle(250);
  288. }
  289. }
  290. catch(...)
  291. {
  292. if (FSecureShell->Active)
  293. {
  294. FSecureShell->Close();
  295. }
  296. // do not pass exception out of thread's proc
  297. }
  298. }
  299. //---------------------------------------------------------------------------
  300. //---------------------------------------------------------------------------
  301. class TTunnelUI : public TSessionUI
  302. {
  303. public:
  304. __fastcall TTunnelUI(TTerminal * Terminal);
  305. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  306. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  307. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  308. TQueryType QueryType);
  309. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  310. Exception * E, unsigned int Answers, const TQueryParams * Params,
  311. TQueryType QueryType);
  312. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  313. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  314. TStrings * Results);
  315. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  316. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
  317. virtual void __fastcall HandleExtendedException(Exception * E);
  318. virtual void __fastcall Closed();
  319. private:
  320. TTerminal * FTerminal;
  321. unsigned int FTerminalThread;
  322. };
  323. //---------------------------------------------------------------------------
  324. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  325. {
  326. FTerminal = Terminal;
  327. FTerminalThread = GetCurrentThreadId();
  328. }
  329. //---------------------------------------------------------------------------
  330. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  331. {
  332. if (GetCurrentThreadId() == FTerminalThread)
  333. {
  334. FTerminal->Information(Str, Status);
  335. }
  336. }
  337. //---------------------------------------------------------------------------
  338. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  339. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  340. TQueryType QueryType)
  341. {
  342. unsigned int Result;
  343. if (GetCurrentThreadId() == FTerminalThread)
  344. {
  345. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  346. }
  347. else
  348. {
  349. Result = AbortAnswer(Answers);
  350. }
  351. return Result;
  352. }
  353. //---------------------------------------------------------------------------
  354. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  355. Exception * E, unsigned int Answers, const TQueryParams * Params,
  356. TQueryType QueryType)
  357. {
  358. unsigned int Result;
  359. if (GetCurrentThreadId() == FTerminalThread)
  360. {
  361. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  362. }
  363. else
  364. {
  365. Result = AbortAnswer(Answers);
  366. }
  367. return Result;
  368. }
  369. //---------------------------------------------------------------------------
  370. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  371. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  372. {
  373. bool Result;
  374. if (GetCurrentThreadId() == FTerminalThread)
  375. {
  376. if (IsAuthenticationPrompt(Kind))
  377. {
  378. Instructions = LoadStr(TUNNEL_INSTRUCTION) +
  379. (Instructions.IsEmpty() ? L"" : L"\n") +
  380. Instructions;
  381. }
  382. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  383. }
  384. else
  385. {
  386. Result = false;
  387. }
  388. return Result;
  389. }
  390. //---------------------------------------------------------------------------
  391. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  392. {
  393. if (GetCurrentThreadId() == FTerminalThread)
  394. {
  395. FTerminal->DisplayBanner(Banner);
  396. }
  397. }
  398. //---------------------------------------------------------------------------
  399. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  400. {
  401. throw ESshFatal(E, Msg, HelpKeyword);
  402. }
  403. //---------------------------------------------------------------------------
  404. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  405. {
  406. if (GetCurrentThreadId() == FTerminalThread)
  407. {
  408. FTerminal->HandleExtendedException(E);
  409. }
  410. }
  411. //---------------------------------------------------------------------------
  412. void __fastcall TTunnelUI::Closed()
  413. {
  414. // noop
  415. }
  416. //---------------------------------------------------------------------------
  417. //---------------------------------------------------------------------------
  418. class TCallbackGuard
  419. {
  420. public:
  421. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  422. inline __fastcall ~TCallbackGuard();
  423. void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
  424. inline void __fastcall Verify();
  425. void __fastcall Dismiss();
  426. private:
  427. ExtException * FFatalError;
  428. TTerminal * FTerminal;
  429. bool FGuarding;
  430. };
  431. //---------------------------------------------------------------------------
  432. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  433. FTerminal(Terminal),
  434. FFatalError(NULL),
  435. FGuarding(FTerminal->FCallbackGuard == NULL)
  436. {
  437. if (FGuarding)
  438. {
  439. FTerminal->FCallbackGuard = this;
  440. }
  441. }
  442. //---------------------------------------------------------------------------
  443. __fastcall TCallbackGuard::~TCallbackGuard()
  444. {
  445. if (FGuarding)
  446. {
  447. assert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  448. FTerminal->FCallbackGuard = NULL;
  449. }
  450. delete FFatalError;
  451. }
  452. //---------------------------------------------------------------------------
  453. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
  454. {
  455. assert(FGuarding);
  456. // make sure we do not bother about getting back the silent abort exception
  457. // we issued ourselves. this may happen when there is an exception handler
  458. // that converts any exception to fatal one (such as in TTerminal::Open).
  459. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  460. {
  461. delete FFatalError;
  462. FFatalError = new ExtException(E, Msg, HelpKeyword);
  463. }
  464. // silently abort what we are doing.
  465. // non-silent exception would be caught probably by default application
  466. // exception handler, which may not do an appropriate action
  467. // (particularly it will not resume broken transfer).
  468. throw ECallbackGuardAbort();
  469. }
  470. //---------------------------------------------------------------------------
  471. void __fastcall TCallbackGuard::Dismiss()
  472. {
  473. assert(FFatalError == NULL);
  474. FGuarding = false;
  475. }
  476. //---------------------------------------------------------------------------
  477. void __fastcall TCallbackGuard::Verify()
  478. {
  479. if (FGuarding)
  480. {
  481. FGuarding = false;
  482. assert(FTerminal->FCallbackGuard == this);
  483. FTerminal->FCallbackGuard = NULL;
  484. if (FFatalError != NULL)
  485. {
  486. throw ESshFatal(FFatalError, L"");
  487. }
  488. }
  489. }
  490. //---------------------------------------------------------------------------
  491. //---------------------------------------------------------------------------
  492. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  493. TConfiguration * Configuration)
  494. {
  495. FConfiguration = Configuration;
  496. FSessionData = new TSessionData(L"");
  497. FSessionData->Assign(SessionData);
  498. FLog = new TSessionLog(this, FSessionData, Configuration);
  499. FActionLog = new TActionLog(this, FSessionData, Configuration);
  500. FFiles = new TRemoteDirectory(this);
  501. FExceptionOnFail = 0;
  502. FInTransaction = 0;
  503. FReadCurrentDirectoryPending = false;
  504. FReadDirectoryPending = false;
  505. FUsersGroupsLookedup = False;
  506. FTunnelLocalPortNumber = 0;
  507. FFileSystem = NULL;
  508. FSecureShell = NULL;
  509. FOnProgress = NULL;
  510. FOnFinished = NULL;
  511. FOnDeleteLocalFile = NULL;
  512. FOnReadDirectoryProgress = NULL;
  513. FOnQueryUser = NULL;
  514. FOnPromptUser = NULL;
  515. FOnDisplayBanner = NULL;
  516. FOnShowExtendedException = NULL;
  517. FOnInformation = NULL;
  518. FOnClose = NULL;
  519. FOnFindingFile = NULL;
  520. FUseBusyCursor = True;
  521. FLockDirectory = L"";
  522. FDirectoryCache = new TRemoteDirectoryCache();
  523. FDirectoryChangesCache = NULL;
  524. FFSProtocol = cfsUnknown;
  525. FCommandSession = NULL;
  526. FAutoReadDirectory = true;
  527. FReadingCurrentDirectory = false;
  528. FStatus = ssClosed;
  529. FTunnelThread = NULL;
  530. FTunnel = NULL;
  531. FTunnelData = NULL;
  532. FTunnelLog = NULL;
  533. FTunnelUI = NULL;
  534. FTunnelOpening = false;
  535. FCallbackGuard = NULL;
  536. }
  537. //---------------------------------------------------------------------------
  538. __fastcall TTerminal::~TTerminal()
  539. {
  540. if (Active)
  541. {
  542. Close();
  543. }
  544. if (FCallbackGuard != NULL)
  545. {
  546. // see TTerminal::HandleExtendedException
  547. FCallbackGuard->Dismiss();
  548. }
  549. assert(FTunnel == NULL);
  550. SAFE_DESTROY(FCommandSession);
  551. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  552. (FDirectoryChangesCache != NULL))
  553. {
  554. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  555. FDirectoryChangesCache);
  556. }
  557. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  558. SAFE_DESTROY_EX(TSessionLog, FLog);
  559. SAFE_DESTROY_EX(TActionLog, FActionLog);
  560. delete FFiles;
  561. delete FDirectoryCache;
  562. delete FDirectoryChangesCache;
  563. SAFE_DESTROY(FSessionData);
  564. }
  565. //---------------------------------------------------------------------------
  566. void __fastcall TTerminal::Idle()
  567. {
  568. // once we disconnect, do nothing, until reconnect handler
  569. // "receives the information"
  570. if (Active)
  571. {
  572. if (Configuration->ActualLogProtocol >= 1)
  573. {
  574. LogEvent(L"Session upkeep");
  575. }
  576. assert(FFileSystem != NULL);
  577. FFileSystem->Idle();
  578. if (CommandSessionOpened)
  579. {
  580. try
  581. {
  582. FCommandSession->Idle();
  583. }
  584. catch(Exception & E)
  585. {
  586. // If the secondary session is dropped, ignore the error and let
  587. // it be reconnected when needed.
  588. // BTW, non-fatal error can hardly happen here, that's why
  589. // it is displayed, because it can be useful to know.
  590. if (FCommandSession->Active)
  591. {
  592. FCommandSession->HandleExtendedException(&E);
  593. }
  594. }
  595. }
  596. }
  597. }
  598. //---------------------------------------------------------------------
  599. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  600. {
  601. return Configuration->EncryptPassword(Password, SessionData->SessionName);
  602. }
  603. //---------------------------------------------------------------------
  604. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  605. {
  606. UnicodeString Result;
  607. try
  608. {
  609. Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
  610. }
  611. catch(EAbort &)
  612. {
  613. // silently ignore aborted prompts for master password and return empty password
  614. }
  615. return Result;
  616. }
  617. //---------------------------------------------------------------------------
  618. void __fastcall TTerminal::RecryptPasswords()
  619. {
  620. FSessionData->RecryptPasswords();
  621. FRememberedPassword = EncryptPassword(DecryptPassword(FRememberedPassword));
  622. FRememberedTunnelPassword = EncryptPassword(DecryptPassword(FRememberedTunnelPassword));
  623. }
  624. //---------------------------------------------------------------------------
  625. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  626. const UnicodeString BasePath)
  627. {
  628. // replace this by AbsolutePath()
  629. Path = UnixExcludeTrailingBackslash(Path);
  630. if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
  631. {
  632. // TODO: Handle more complicated cases like "../../xxx"
  633. if (Path == L"..")
  634. {
  635. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  636. UnixExcludeTrailingBackslash(BasePath)));
  637. }
  638. else
  639. {
  640. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  641. }
  642. }
  643. return Path;
  644. }
  645. //---------------------------------------------------------------------------
  646. bool __fastcall TTerminal::GetActive()
  647. {
  648. return (FFileSystem != NULL) && FFileSystem->GetActive();
  649. }
  650. //---------------------------------------------------------------------------
  651. void __fastcall TTerminal::Close()
  652. {
  653. FFileSystem->Close();
  654. if (CommandSessionOpened)
  655. {
  656. FCommandSession->Close();
  657. }
  658. }
  659. //---------------------------------------------------------------------------
  660. void __fastcall TTerminal::ResetConnection()
  661. {
  662. // used to be called from Reopen(), why?
  663. FTunnelError = L"";
  664. FRememberedPasswordTried = false;
  665. FRememberedTunnelPasswordTried = false;
  666. if (FDirectoryChangesCache != NULL)
  667. {
  668. delete FDirectoryChangesCache;
  669. FDirectoryChangesCache = NULL;
  670. }
  671. FFiles->Directory = L"";
  672. // note that we cannot clear contained files
  673. // as they can still be referenced in the GUI atm
  674. }
  675. //---------------------------------------------------------------------------
  676. void __fastcall TTerminal::Open()
  677. {
  678. ReflectSettings();
  679. try
  680. {
  681. DoInformation(L"", true, 1);
  682. try
  683. {
  684. try
  685. {
  686. ResetConnection();
  687. FStatus = ssOpening;
  688. try
  689. {
  690. if (FFileSystem == NULL)
  691. {
  692. Log->AddSystemInfo();
  693. DoInitializeLog();
  694. Log->AddStartupInfo();
  695. }
  696. assert(FTunnel == NULL);
  697. if (FSessionData->Tunnel)
  698. {
  699. DoInformation(LoadStr(OPEN_TUNNEL), true);
  700. LogEvent(L"Opening tunnel.");
  701. OpenTunnel();
  702. Log->AddSeparator();
  703. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  704. DoInformation(LoadStr(USING_TUNNEL), false);
  705. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  706. (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
  707. }
  708. else
  709. {
  710. assert(FTunnelLocalPortNumber == 0);
  711. }
  712. if (FFileSystem == NULL)
  713. {
  714. if (SessionData->FSProtocol == fsFTP)
  715. {
  716. #ifdef NO_FILEZILLA
  717. LogEvent(L"FTP protocol is not supported by this build.");
  718. FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
  719. #else
  720. FFSProtocol = cfsFTP;
  721. FFileSystem = new TFTPFileSystem(this);
  722. FFileSystem->Open();
  723. Log->AddSeparator();
  724. LogEvent(L"Using FTP protocol.");
  725. #endif
  726. }
  727. else if (SessionData->FSProtocol == fsWebDAV)
  728. {
  729. FFSProtocol = cfsWebDAV;
  730. FFileSystem = new TWebDAVFileSystem(this);
  731. FFileSystem->Open();
  732. Log->AddSeparator();
  733. LogEvent(L"Using WebDAV protocol.");
  734. }
  735. else
  736. {
  737. assert(FSecureShell == NULL);
  738. try
  739. {
  740. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  741. try
  742. {
  743. // there will be only one channel in this session
  744. FSecureShell->Simple = true;
  745. FSecureShell->Open();
  746. }
  747. catch(Exception & E)
  748. {
  749. assert(!FSecureShell->Active);
  750. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  751. {
  752. // the only case where we expect this to happen
  753. assert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
  754. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  755. }
  756. else
  757. {
  758. throw;
  759. }
  760. }
  761. Log->AddSeparator();
  762. if ((SessionData->FSProtocol == fsSCPonly) ||
  763. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  764. {
  765. FFSProtocol = cfsSCP;
  766. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  767. FSecureShell = NULL; // ownership passed
  768. LogEvent(L"Using SCP protocol.");
  769. }
  770. else
  771. {
  772. FFSProtocol = cfsSFTP;
  773. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  774. FSecureShell = NULL; // ownership passed
  775. LogEvent(L"Using SFTP protocol.");
  776. }
  777. }
  778. __finally
  779. {
  780. delete FSecureShell;
  781. FSecureShell = NULL;
  782. }
  783. }
  784. }
  785. else
  786. {
  787. FFileSystem->Open();
  788. }
  789. }
  790. __finally
  791. {
  792. if (FSessionData->Tunnel)
  793. {
  794. FSessionData->RollbackTunnel();
  795. }
  796. }
  797. if (SessionData->CacheDirectoryChanges)
  798. {
  799. assert(FDirectoryChangesCache == NULL);
  800. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  801. Configuration->CacheDirectoryChangesMaxSize);
  802. if (SessionData->PreserveDirectoryChanges)
  803. {
  804. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  805. FDirectoryChangesCache);
  806. }
  807. }
  808. DoStartup();
  809. if (FCollectFileSystemUsage)
  810. {
  811. FFileSystem->CollectUsage();
  812. FCollectFileSystemUsage = false;
  813. }
  814. DoInformation(LoadStr(STATUS_READY), true);
  815. FStatus = ssOpened;
  816. }
  817. catch(...)
  818. {
  819. // rollback
  820. if (FDirectoryChangesCache != NULL)
  821. {
  822. delete FDirectoryChangesCache;
  823. FDirectoryChangesCache = NULL;
  824. }
  825. throw;
  826. }
  827. }
  828. __finally
  829. {
  830. DoInformation(L"", true, 0);
  831. }
  832. }
  833. catch(EFatal &)
  834. {
  835. throw;
  836. }
  837. catch(Exception & E)
  838. {
  839. // any exception while opening session is fatal
  840. FatalError(&E, L"");
  841. }
  842. }
  843. //---------------------------------------------------------------------------
  844. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  845. {
  846. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  847. bool Result = (Socket != INVALID_SOCKET);
  848. if (Result)
  849. {
  850. SOCKADDR_IN Address;
  851. memset(&Address, 0, sizeof(Address));
  852. Address.sin_family = AF_INET;
  853. Address.sin_port = htons(static_cast<short>(PortNumber));
  854. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  855. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  856. closesocket(Socket);
  857. }
  858. return Result;
  859. }
  860. //---------------------------------------------------------------------------
  861. void __fastcall TTerminal::OpenTunnel()
  862. {
  863. assert(FTunnelData == NULL);
  864. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  865. if (FTunnelLocalPortNumber == 0)
  866. {
  867. FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
  868. while (!IsListenerFree(FTunnelLocalPortNumber))
  869. {
  870. FTunnelLocalPortNumber++;
  871. if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
  872. {
  873. FTunnelLocalPortNumber = 0;
  874. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  875. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  876. }
  877. }
  878. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  879. }
  880. try
  881. {
  882. FTunnelData = new TSessionData(L"");
  883. FTunnelData->Assign(StoredSessions->DefaultSettings);
  884. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  885. FTunnelData->Tunnel = false;
  886. FTunnelData->HostName = FSessionData->TunnelHostName;
  887. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  888. FTunnelData->UserName = FSessionData->TunnelUserName;
  889. FTunnelData->Password = FSessionData->TunnelPassword;
  890. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  891. FTunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  892. (FTunnelLocalPortNumber, FSessionData->HostNameExpanded, FSessionData->PortNumber));
  893. FTunnelData->HostKey = FSessionData->TunnelHostKey;
  894. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  895. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  896. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  897. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  898. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  899. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  900. FTunnelData->ProxyLocalCommand = FSessionData->ProxyLocalCommand;
  901. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  902. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  903. FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
  904. FTunnelLog->Parent = FLog;
  905. FTunnelLog->Name = L"Tunnel";
  906. FTunnelLog->ReflectSettings();
  907. FTunnelUI = new TTunnelUI(this);
  908. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  909. FTunnelOpening = true;
  910. try
  911. {
  912. FTunnel->Open();
  913. }
  914. __finally
  915. {
  916. FTunnelOpening = false;
  917. }
  918. FTunnelThread = new TTunnelThread(FTunnel);
  919. }
  920. catch(...)
  921. {
  922. CloseTunnel();
  923. throw;
  924. }
  925. }
  926. //---------------------------------------------------------------------------
  927. void __fastcall TTerminal::CloseTunnel()
  928. {
  929. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  930. FTunnelError = FTunnel->LastTunnelError;
  931. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  932. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  933. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  934. SAFE_DESTROY(FTunnelData);
  935. FTunnelLocalPortNumber = 0;
  936. }
  937. //---------------------------------------------------------------------------
  938. void __fastcall TTerminal::Closed()
  939. {
  940. if (FTunnel != NULL)
  941. {
  942. CloseTunnel();
  943. }
  944. if (OnClose)
  945. {
  946. TCallbackGuard Guard(this);
  947. OnClose(this);
  948. Guard.Verify();
  949. }
  950. FStatus = ssClosed;
  951. }
  952. //---------------------------------------------------------------------------
  953. void __fastcall TTerminal::Reopen(int Params)
  954. {
  955. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  956. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  957. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  958. bool PrevReadDirectoryPending = FReadDirectoryPending;
  959. assert(!FSuspendTransaction);
  960. bool PrevAutoReadDirectory = FAutoReadDirectory;
  961. // here used to be a check for FExceptionOnFail being 0
  962. // but it can happen, e.g. when we are downloading file to execute it.
  963. // however I'm not sure why we mind having excaption-on-fail enabled here
  964. int PrevExceptionOnFail = FExceptionOnFail;
  965. try
  966. {
  967. FReadCurrentDirectoryPending = false;
  968. FReadDirectoryPending = false;
  969. FSuspendTransaction = true;
  970. FExceptionOnFail = 0;
  971. // typically, we avoid reading directory, when there is operation ongoing,
  972. // for file list which may reference files from current directory
  973. if (FLAGSET(Params, ropNoReadDirectory))
  974. {
  975. AutoReadDirectory = false;
  976. }
  977. // only peek, we may not be connected at all atm,
  978. // so make sure we do not try retrieving current directory from the server
  979. // (particularly with FTP)
  980. AnsiString ACurrentDirectory = PeekCurrentDirectory();
  981. if (!ACurrentDirectory.IsEmpty())
  982. {
  983. SessionData->RemoteDirectory = ACurrentDirectory;
  984. }
  985. if (SessionData->FSProtocol == fsSFTP)
  986. {
  987. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  988. }
  989. if (Active)
  990. {
  991. Close();
  992. }
  993. Open();
  994. }
  995. __finally
  996. {
  997. SessionData->RemoteDirectory = PrevRemoteDirectory;
  998. SessionData->FSProtocol = OrigFSProtocol;
  999. FAutoReadDirectory = PrevAutoReadDirectory;
  1000. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  1001. FReadDirectoryPending = PrevReadDirectoryPending;
  1002. FSuspendTransaction = false;
  1003. FExceptionOnFail = PrevExceptionOnFail;
  1004. }
  1005. }
  1006. //---------------------------------------------------------------------------
  1007. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1008. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  1009. {
  1010. bool AResult;
  1011. TStrings * Prompts = new TStringList;
  1012. TStrings * Results = new TStringList;
  1013. try
  1014. {
  1015. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  1016. Results->AddObject(Result, (TObject *)MaxLen);
  1017. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1018. Result = Results->Strings[0];
  1019. }
  1020. __finally
  1021. {
  1022. delete Prompts;
  1023. delete Results;
  1024. }
  1025. return AResult;
  1026. }
  1027. //---------------------------------------------------------------------------
  1028. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1029. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1030. {
  1031. // If PromptUser is overridden in descendant class, the overridden version
  1032. // is not called when accessed via TSessionIU interface.
  1033. // So this is workaround.
  1034. // Actually no longer needed as we do not uverride DoPromptUser
  1035. // anymore in TSecondaryTerminal.
  1036. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1037. }
  1038. //---------------------------------------------------------------------------
  1039. TTerminal * __fastcall TTerminal::GetPasswordSource()
  1040. {
  1041. return this;
  1042. }
  1043. //---------------------------------------------------------------------------
  1044. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  1045. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1046. {
  1047. bool AResult = false;
  1048. bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
  1049. if (PasswordOrPassphrasePrompt)
  1050. {
  1051. bool & PasswordTried =
  1052. FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
  1053. if (!PasswordTried)
  1054. {
  1055. // let's expect that the main session is already authenticated and its password
  1056. // is not written after, so no locking is necessary
  1057. // (no longer true, once the main session can be reconnected)
  1058. UnicodeString APassword;
  1059. if (FTunnelOpening)
  1060. {
  1061. APassword = GetPasswordSource()->RememberedTunnelPassword;
  1062. }
  1063. else
  1064. {
  1065. APassword = GetPasswordSource()->RememberedPassword;
  1066. }
  1067. Results->Strings[0] = APassword;
  1068. if (!Results->Strings[0].IsEmpty())
  1069. {
  1070. LogEvent(L"Using remembered password.");
  1071. AResult = true;
  1072. }
  1073. PasswordTried = true;
  1074. }
  1075. }
  1076. if (!AResult)
  1077. {
  1078. if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
  1079. {
  1080. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1081. }
  1082. if (OnPromptUser != NULL)
  1083. {
  1084. TCallbackGuard Guard(this);
  1085. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1086. Guard.Verify();
  1087. }
  1088. if (AResult && PasswordOrPassphrasePrompt &&
  1089. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1090. {
  1091. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1092. if (FTunnelOpening)
  1093. {
  1094. GetPasswordSource()->FRememberedTunnelPassword = EncryptedPassword;
  1095. }
  1096. else
  1097. {
  1098. GetPasswordSource()->FRememberedPassword = EncryptedPassword;
  1099. }
  1100. }
  1101. }
  1102. return AResult;
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1106. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1107. TQueryType QueryType)
  1108. {
  1109. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1110. unsigned int Answer = AbortAnswer(Answers);
  1111. if (FOnQueryUser)
  1112. {
  1113. TCallbackGuard Guard(this);
  1114. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1115. Guard.Verify();
  1116. }
  1117. return Answer;
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1121. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1122. TQueryType QueryType)
  1123. {
  1124. unsigned int Result;
  1125. UnicodeString ExMessage;
  1126. if (ALWAYS_TRUE(ExceptionMessage(E, ExMessage) || !Query.IsEmpty()))
  1127. {
  1128. TStrings * MoreMessages = new TStringList();
  1129. try
  1130. {
  1131. if (!ExMessage.IsEmpty() && !Query.IsEmpty())
  1132. {
  1133. MoreMessages->Add(UnformatMessage(ExMessage));
  1134. }
  1135. ExtException * EE = dynamic_cast<ExtException*>(E);
  1136. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1137. {
  1138. MoreMessages->AddStrings(EE->MoreMessages);
  1139. }
  1140. // We know MoreMessages not to be NULL here,
  1141. // AppendExceptionStackTraceAndForget should never return true
  1142. // (indicating it had to create the string list)
  1143. ALWAYS_FALSE(AppendExceptionStackTraceAndForget(MoreMessages));
  1144. TQueryParams HelpKeywordOverrideParams;
  1145. if (Params != NULL)
  1146. {
  1147. HelpKeywordOverrideParams.Assign(*Params);
  1148. }
  1149. HelpKeywordOverrideParams.HelpKeyword =
  1150. MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
  1151. Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
  1152. MoreMessages->Count ? MoreMessages : NULL,
  1153. Answers, &HelpKeywordOverrideParams, QueryType);
  1154. }
  1155. __finally
  1156. {
  1157. delete MoreMessages;
  1158. }
  1159. }
  1160. return Result;
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1164. {
  1165. if (OnDisplayBanner != NULL)
  1166. {
  1167. if (Configuration->ForceBanners ||
  1168. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  1169. {
  1170. bool NeverShowAgain = false;
  1171. int Options =
  1172. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1173. TCallbackGuard Guard(this);
  1174. OnDisplayBanner(this, SessionData->SessionName, Banner,
  1175. NeverShowAgain, Options);
  1176. Guard.Verify();
  1177. if (!Configuration->ForceBanners && NeverShowAgain)
  1178. {
  1179. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1180. }
  1181. }
  1182. }
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  1186. {
  1187. Log->AddException(E);
  1188. if (OnShowExtendedException != NULL)
  1189. {
  1190. TCallbackGuard Guard(this);
  1191. // the event handler may destroy 'this' ...
  1192. OnShowExtendedException(this, E, NULL);
  1193. // .. hence guard is dismissed from destructor, to make following call no-op
  1194. Guard.Verify();
  1195. }
  1196. }
  1197. //---------------------------------------------------------------------------
  1198. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  1199. {
  1200. Log->AddException(E);
  1201. if (OnShowExtendedException != NULL)
  1202. {
  1203. OnShowExtendedException(this, E, NULL);
  1204. }
  1205. }
  1206. //---------------------------------------------------------------------------
  1207. void __fastcall TTerminal::DoInformation(const UnicodeString & Str, bool Status,
  1208. int Phase)
  1209. {
  1210. if (OnInformation)
  1211. {
  1212. TCallbackGuard Guard(this);
  1213. OnInformation(this, Str, Status, Phase);
  1214. Guard.Verify();
  1215. }
  1216. }
  1217. //---------------------------------------------------------------------------
  1218. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  1219. {
  1220. DoInformation(Str, Status);
  1221. }
  1222. //---------------------------------------------------------------------------
  1223. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
  1224. {
  1225. if (OnProgress != NULL)
  1226. {
  1227. TCallbackGuard Guard(this);
  1228. OnProgress(ProgressData);
  1229. Guard.Verify();
  1230. }
  1231. }
  1232. //---------------------------------------------------------------------------
  1233. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  1234. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  1235. {
  1236. if (OnFinished != NULL)
  1237. {
  1238. TCallbackGuard Guard(this);
  1239. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  1240. Guard.Verify();
  1241. }
  1242. }
  1243. //---------------------------------------------------------------------------
  1244. void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
  1245. {
  1246. for (int Index = 0; Index < fcCount; Index++)
  1247. {
  1248. FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
  1249. }
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  1253. {
  1254. assert(FFileSystem);
  1255. return FFileSystem->IsCapable(Capability);
  1256. }
  1257. //---------------------------------------------------------------------------
  1258. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  1259. {
  1260. return FFileSystem->AbsolutePath(Path, Local);
  1261. }
  1262. //---------------------------------------------------------------------------
  1263. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  1264. {
  1265. bool ChangesDirectory = false;
  1266. bool ModifiesFiles = false;
  1267. switch ((TFSCommand)Cmd) {
  1268. case fsChangeDirectory:
  1269. case fsHomeDirectory:
  1270. ChangesDirectory = true;
  1271. break;
  1272. case fsCopyToRemote:
  1273. case fsDeleteFile:
  1274. case fsRenameFile:
  1275. case fsMoveFile:
  1276. case fsCopyFile:
  1277. case fsCreateDirectory:
  1278. case fsChangeMode:
  1279. case fsChangeGroup:
  1280. case fsChangeOwner:
  1281. case fsChangeProperties:
  1282. ModifiesFiles = true;
  1283. break;
  1284. case fsAnyCommand:
  1285. ChangesDirectory = true;
  1286. ModifiesFiles = true;
  1287. break;
  1288. }
  1289. if (ChangesDirectory)
  1290. {
  1291. if (!InTransaction())
  1292. {
  1293. ReadCurrentDirectory();
  1294. if (AutoReadDirectory)
  1295. {
  1296. ReadDirectory(false);
  1297. }
  1298. }
  1299. else
  1300. {
  1301. FReadCurrentDirectoryPending = true;
  1302. if (AutoReadDirectory)
  1303. {
  1304. FReadDirectoryPending = true;
  1305. }
  1306. }
  1307. }
  1308. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  1309. {
  1310. if (!InTransaction())
  1311. {
  1312. ReadDirectory(true);
  1313. }
  1314. else
  1315. {
  1316. FReadDirectoryPending = true;
  1317. }
  1318. }
  1319. }
  1320. //---------------------------------------------------------------------------
  1321. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  1322. {
  1323. TerminalError(NULL, Msg);
  1324. }
  1325. //---------------------------------------------------------------------------
  1326. void __fastcall TTerminal::TerminalError(
  1327. Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  1328. {
  1329. throw ETerminal(E, Msg, HelpKeyword);
  1330. }
  1331. //---------------------------------------------------------------------------
  1332. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  1333. {
  1334. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  1335. assert(Fatal != NULL);
  1336. bool Result;
  1337. if ((Fatal != NULL) && Fatal->ReopenQueried)
  1338. {
  1339. Result = false;
  1340. }
  1341. else
  1342. {
  1343. LogEvent(L"Connection was lost, asking what to do.");
  1344. TQueryParams Params(qpAllowContinueOnError);
  1345. Params.Timeout = Configuration->SessionReopenAuto;
  1346. Params.TimeoutAnswer = qaRetry;
  1347. TQueryButtonAlias Aliases[1];
  1348. Aliases[0].Button = qaRetry;
  1349. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  1350. Params.Aliases = Aliases;
  1351. Params.AliasesCount = LENOF(Aliases);
  1352. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  1353. if (Fatal != NULL)
  1354. {
  1355. Fatal->ReopenQueried = true;
  1356. }
  1357. }
  1358. return Result;
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  1362. TFileOperationProgressType * OperationProgress)
  1363. {
  1364. TSuspendFileOperationProgress Suspend(OperationProgress);
  1365. bool Result = DoQueryReopen(E);
  1366. if (Result)
  1367. {
  1368. TDateTime Start = Now();
  1369. do
  1370. {
  1371. try
  1372. {
  1373. Reopen(Params);
  1374. }
  1375. catch(Exception & E)
  1376. {
  1377. if (!Active)
  1378. {
  1379. Result =
  1380. ((Configuration->SessionReopenTimeout == 0) ||
  1381. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout)) &&
  1382. DoQueryReopen(&E);
  1383. }
  1384. else
  1385. {
  1386. throw;
  1387. }
  1388. }
  1389. }
  1390. while (!Active && Result);
  1391. }
  1392. return Result;
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  1396. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  1397. bool AllowSkip, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
  1398. {
  1399. bool Result = false;
  1400. Log->AddException(&E);
  1401. unsigned int Answer;
  1402. bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
  1403. if (SkipToAllPossible && OperationProgress->SkipToAll)
  1404. {
  1405. Answer = qaSkip;
  1406. }
  1407. else
  1408. {
  1409. int Answers = qaRetry | qaAbort |
  1410. FLAGMASK(AllowSkip, qaSkip) |
  1411. FLAGMASK(SkipToAllPossible, qaAll) |
  1412. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  1413. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  1414. Params.HelpKeyword = HelpKeyword;
  1415. TQueryButtonAlias Aliases[2];
  1416. int AliasCount = 0;
  1417. if (FLAGSET(Answers, qaAll))
  1418. {
  1419. Aliases[AliasCount].Button = qaAll;
  1420. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  1421. AliasCount++;
  1422. }
  1423. if (FLAGSET(Answers, qaYes))
  1424. {
  1425. Aliases[AliasCount].Button = qaYes;
  1426. Aliases[AliasCount].Alias = SpecialRetry;
  1427. AliasCount++;
  1428. }
  1429. if (AliasCount > 0)
  1430. {
  1431. Params.Aliases = Aliases;
  1432. Params.AliasesCount = AliasCount;
  1433. }
  1434. {
  1435. TSuspendFileOperationProgress Suspend(OperationProgress);
  1436. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  1437. }
  1438. if (Answer == qaAll)
  1439. {
  1440. assert(OperationProgress != NULL);
  1441. OperationProgress->SkipToAll = true;
  1442. Answer = qaSkip;
  1443. }
  1444. if (Answer == qaYes)
  1445. {
  1446. Result = true;
  1447. Answer = qaRetry;
  1448. }
  1449. }
  1450. if (Answer != qaRetry)
  1451. {
  1452. if ((Answer == qaAbort) && (OperationProgress != NULL))
  1453. {
  1454. OperationProgress->Cancel = csCancel;
  1455. }
  1456. if (AllowSkip)
  1457. {
  1458. THROW_SKIP_FILE(&E, Message);
  1459. }
  1460. else
  1461. {
  1462. // this can happen only during file transfer with SCP
  1463. throw ExtException(&E, Message);
  1464. }
  1465. }
  1466. return Result;
  1467. }
  1468. //---------------------------------------------------------------------------
  1469. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  1470. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  1471. const UnicodeString Message, void * Param1, void * Param2)
  1472. {
  1473. assert(CallBackFunc);
  1474. int Result;
  1475. FILE_OPERATION_LOOP_BEGIN
  1476. {
  1477. Result = CallBackFunc(Param1, Param2);
  1478. }
  1479. FILE_OPERATION_LOOP_END_EX(Message, AllowSkip);
  1480. return Result;
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. UnicodeString __fastcall TTerminal::TranslateLockedPath(UnicodeString Path, bool Lock)
  1484. {
  1485. if (SessionData->LockInHome && !Path.IsEmpty() && (Path[1] == L'/'))
  1486. {
  1487. if (Lock)
  1488. {
  1489. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  1490. {
  1491. Path.Delete(1, FLockDirectory.Length());
  1492. if (Path.IsEmpty()) Path = L"/";
  1493. }
  1494. }
  1495. else
  1496. {
  1497. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  1498. }
  1499. }
  1500. return Path;
  1501. }
  1502. //---------------------------------------------------------------------------
  1503. void __fastcall TTerminal::ClearCaches()
  1504. {
  1505. FDirectoryCache->Clear();
  1506. if (FDirectoryChangesCache != NULL)
  1507. {
  1508. FDirectoryChangesCache->Clear();
  1509. }
  1510. if (FCommandSession != NULL)
  1511. {
  1512. FCommandSession->ClearCaches();
  1513. }
  1514. }
  1515. //---------------------------------------------------------------------------
  1516. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  1517. bool SubDirs)
  1518. {
  1519. FDirectoryCache->ClearFileList(Path, SubDirs);
  1520. }
  1521. //---------------------------------------------------------------------------
  1522. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  1523. {
  1524. FDirectoryCache->AddFileList(FileList);
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. bool __fastcall TTerminal::DirectoryFileList(const UnicodeString Path,
  1528. TRemoteFileList *& FileList, bool CanLoad)
  1529. {
  1530. bool Result = false;
  1531. if (UnixSamePath(FFiles->Directory, Path))
  1532. {
  1533. Result = (FileList == NULL) || (FileList->Timestamp < FFiles->Timestamp);
  1534. if (Result)
  1535. {
  1536. if (FileList == NULL)
  1537. {
  1538. FileList = new TRemoteFileList();
  1539. }
  1540. FFiles->DuplicateTo(FileList);
  1541. }
  1542. }
  1543. else
  1544. {
  1545. if (((FileList == NULL) && FDirectoryCache->HasFileList(Path)) ||
  1546. ((FileList != NULL) && FDirectoryCache->HasNewerFileList(Path, FileList->Timestamp)))
  1547. {
  1548. bool Created = (FileList == NULL);
  1549. if (Created)
  1550. {
  1551. FileList = new TRemoteFileList();
  1552. }
  1553. Result = FDirectoryCache->GetFileList(Path, FileList);
  1554. if (!Result && Created)
  1555. {
  1556. SAFE_DESTROY(FileList);
  1557. }
  1558. }
  1559. // do not attempt to load file list if there is cached version,
  1560. // only absence of cached version indicates that we consider
  1561. // the directory content obsolete
  1562. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  1563. {
  1564. bool Created = (FileList == NULL);
  1565. if (Created)
  1566. {
  1567. FileList = new TRemoteFileList();
  1568. }
  1569. FileList->Directory = Path;
  1570. try
  1571. {
  1572. ReadDirectory(FileList);
  1573. Result = true;
  1574. }
  1575. catch(...)
  1576. {
  1577. if (Created)
  1578. {
  1579. SAFE_DESTROY(FileList);
  1580. }
  1581. throw;
  1582. }
  1583. }
  1584. }
  1585. return Result;
  1586. }
  1587. //---------------------------------------------------------------------------
  1588. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  1589. {
  1590. assert(FFileSystem);
  1591. value = TranslateLockedPath(value, false);
  1592. if (value != FFileSystem->CurrentDirectory)
  1593. {
  1594. ChangeDirectory(value);
  1595. }
  1596. }
  1597. //---------------------------------------------------------------------------
  1598. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  1599. {
  1600. if (FFileSystem != NULL)
  1601. {
  1602. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  1603. // to FCurrentDirectory, splitting the assignment to two statemets
  1604. // to locate the crash more closely
  1605. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  1606. FCurrentDirectory = CurrentDirectory;
  1607. if (FCurrentDirectory.IsEmpty())
  1608. {
  1609. ReadCurrentDirectory();
  1610. }
  1611. }
  1612. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1613. return Result;
  1614. }
  1615. //---------------------------------------------------------------------------
  1616. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  1617. {
  1618. if (FFileSystem)
  1619. {
  1620. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1621. }
  1622. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1623. return Result;
  1624. }
  1625. //---------------------------------------------------------------------------
  1626. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  1627. {
  1628. assert(FFileSystem);
  1629. LookupUsersGroups();
  1630. return &FGroups;
  1631. }
  1632. //---------------------------------------------------------------------------
  1633. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  1634. {
  1635. assert(FFileSystem);
  1636. LookupUsersGroups();
  1637. return &FUsers;
  1638. }
  1639. //---------------------------------------------------------------------------
  1640. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  1641. {
  1642. assert(FFileSystem);
  1643. LookupUsersGroups();
  1644. return &FMembership;
  1645. }
  1646. //---------------------------------------------------------------------------
  1647. UnicodeString __fastcall TTerminal::GetUserName() const
  1648. {
  1649. // in future might also be implemented to detect username similar to GetUserGroups
  1650. assert(FFileSystem != NULL);
  1651. UnicodeString Result = FFileSystem->GetUserName();
  1652. // Is empty also when stored username was used
  1653. if (Result.IsEmpty())
  1654. {
  1655. Result = SessionData->UserNameExpanded;
  1656. }
  1657. return Result;
  1658. }
  1659. //---------------------------------------------------------------------------
  1660. bool __fastcall TTerminal::GetAreCachesEmpty() const
  1661. {
  1662. return FDirectoryCache->IsEmpty &&
  1663. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  1664. }
  1665. //---------------------------------------------------------------------------
  1666. void __fastcall TTerminal::DoInitializeLog()
  1667. {
  1668. if (FOnInitializeLog)
  1669. {
  1670. TCallbackGuard Guard(this);
  1671. FOnInitializeLog(this);
  1672. Guard.Verify();
  1673. }
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. void __fastcall TTerminal::DoChangeDirectory()
  1677. {
  1678. if (FOnChangeDirectory)
  1679. {
  1680. TCallbackGuard Guard(this);
  1681. FOnChangeDirectory(this);
  1682. Guard.Verify();
  1683. }
  1684. }
  1685. //---------------------------------------------------------------------------
  1686. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  1687. {
  1688. if (FOnReadDirectory)
  1689. {
  1690. TCallbackGuard Guard(this);
  1691. FOnReadDirectory(this, ReloadOnly);
  1692. Guard.Verify();
  1693. }
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. void __fastcall TTerminal::DoStartReadDirectory()
  1697. {
  1698. if (FOnStartReadDirectory)
  1699. {
  1700. TCallbackGuard Guard(this);
  1701. FOnStartReadDirectory(this);
  1702. Guard.Verify();
  1703. }
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
  1707. {
  1708. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  1709. {
  1710. TCallbackGuard Guard(this);
  1711. FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
  1712. Guard.Verify();
  1713. }
  1714. if (FOnFindingFile != NULL)
  1715. {
  1716. TCallbackGuard Guard(this);
  1717. FOnFindingFile(this, L"", Cancel);
  1718. Guard.Verify();
  1719. }
  1720. }
  1721. //---------------------------------------------------------------------------
  1722. bool __fastcall TTerminal::InTransaction()
  1723. {
  1724. return (FInTransaction > 0) && !FSuspendTransaction;
  1725. }
  1726. //---------------------------------------------------------------------------
  1727. void __fastcall TTerminal::BeginTransaction()
  1728. {
  1729. if (FInTransaction == 0)
  1730. {
  1731. FReadCurrentDirectoryPending = false;
  1732. FReadDirectoryPending = false;
  1733. }
  1734. FInTransaction++;
  1735. if (FCommandSession != NULL)
  1736. {
  1737. FCommandSession->BeginTransaction();
  1738. }
  1739. }
  1740. //---------------------------------------------------------------------------
  1741. void __fastcall TTerminal::EndTransaction()
  1742. {
  1743. DoEndTransaction(false);
  1744. }
  1745. //---------------------------------------------------------------------------
  1746. void __fastcall TTerminal::DoEndTransaction(bool Inform)
  1747. {
  1748. if (FInTransaction == 0)
  1749. TerminalError(L"Can't end transaction, not in transaction");
  1750. assert(FInTransaction > 0);
  1751. FInTransaction--;
  1752. // it connection was closed due to fatal error during transaction, do nothing
  1753. if (Active)
  1754. {
  1755. if (FInTransaction == 0)
  1756. {
  1757. try
  1758. {
  1759. if (FReadCurrentDirectoryPending)
  1760. {
  1761. ReadCurrentDirectory();
  1762. }
  1763. if (FReadDirectoryPending)
  1764. {
  1765. if (Inform)
  1766. {
  1767. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
  1768. }
  1769. ReadDirectory(!FReadCurrentDirectoryPending);
  1770. }
  1771. }
  1772. __finally
  1773. {
  1774. FReadCurrentDirectoryPending = false;
  1775. FReadDirectoryPending = false;
  1776. }
  1777. }
  1778. }
  1779. if (FCommandSession != NULL)
  1780. {
  1781. FCommandSession->EndTransaction();
  1782. }
  1783. }
  1784. //---------------------------------------------------------------------------
  1785. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  1786. {
  1787. if (value)
  1788. {
  1789. FExceptionOnFail++;
  1790. }
  1791. else
  1792. {
  1793. if (FExceptionOnFail == 0)
  1794. throw Exception(L"ExceptionOnFail is already zero.");
  1795. FExceptionOnFail--;
  1796. }
  1797. if (FCommandSession != NULL)
  1798. {
  1799. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  1800. }
  1801. }
  1802. //---------------------------------------------------------------------------
  1803. bool __fastcall TTerminal::GetExceptionOnFail() const
  1804. {
  1805. return (bool)(FExceptionOnFail > 0);
  1806. }
  1807. //---------------------------------------------------------------------------
  1808. void __fastcall TTerminal::FatalAbort()
  1809. {
  1810. FatalError(NULL, "");
  1811. }
  1812. //---------------------------------------------------------------------------
  1813. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  1814. {
  1815. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  1816. if (Active || SecureShellActive)
  1817. {
  1818. // We log this instead of exception handler, because Close() would
  1819. // probably cause exception handler to loose pointer to TShellLog()
  1820. LogEvent(L"Attempt to close connection due to fatal exception:");
  1821. Log->Add(llException, Msg);
  1822. Log->AddException(E);
  1823. if (Active)
  1824. {
  1825. Close();
  1826. }
  1827. // this may happen if failure of authentication of SSH, owned by terminal yet
  1828. // (because the protocol was not decided yet), is detected by us (not by putty).
  1829. // e.g. not verified host key
  1830. if (SecureShellActive)
  1831. {
  1832. FSecureShell->Close();
  1833. }
  1834. }
  1835. if (FCallbackGuard != NULL)
  1836. {
  1837. FCallbackGuard->FatalError(E, Msg, HelpKeyword);
  1838. }
  1839. else
  1840. {
  1841. throw ESshFatal(E, Msg, HelpKeyword);
  1842. }
  1843. }
  1844. //---------------------------------------------------------------------------
  1845. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  1846. {
  1847. CommandError(E, Msg, 0);
  1848. }
  1849. //---------------------------------------------------------------------------
  1850. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  1851. unsigned int Answers, const UnicodeString HelpKeyword)
  1852. {
  1853. // may not be, particularly when TTerminal::Reopen is being called
  1854. // from within OnShowExtendedException handler
  1855. assert(FCallbackGuard == NULL);
  1856. unsigned int Result = 0;
  1857. if (E && E->InheritsFrom(__classid(EFatal)))
  1858. {
  1859. FatalError(E, Msg, HelpKeyword);
  1860. }
  1861. else if (E && E->InheritsFrom(__classid(EAbort)))
  1862. {
  1863. // resent EAbort exception
  1864. Abort();
  1865. }
  1866. else if (ExceptionOnFail)
  1867. {
  1868. throw ECommand(E, Msg, HelpKeyword);
  1869. }
  1870. else if (!Answers)
  1871. {
  1872. ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
  1873. try
  1874. {
  1875. HandleExtendedException(ECmd);
  1876. }
  1877. __finally
  1878. {
  1879. delete ECmd;
  1880. }
  1881. }
  1882. else
  1883. {
  1884. // small hack to enable "skip to all" for COMMAND_ERROR_ARI
  1885. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  1886. if (CanSkip && OperationProgress->SkipToAll)
  1887. {
  1888. Result = qaSkip;
  1889. }
  1890. else
  1891. {
  1892. TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
  1893. TQueryButtonAlias Aliases[1];
  1894. if (CanSkip)
  1895. {
  1896. Aliases[0].Button = qaAll;
  1897. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  1898. Params.Aliases = Aliases;
  1899. Params.AliasesCount = LENOF(Aliases);
  1900. Answers |= qaAll;
  1901. }
  1902. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  1903. if (Result == qaAll)
  1904. {
  1905. assert(OperationProgress != NULL);
  1906. OperationProgress->SkipToAll = true;
  1907. Result = qaSkip;
  1908. }
  1909. }
  1910. }
  1911. return Result;
  1912. }
  1913. //---------------------------------------------------------------------------
  1914. bool __fastcall TTerminal::HandleException(Exception * E)
  1915. {
  1916. if (ExceptionOnFail)
  1917. {
  1918. return false;
  1919. }
  1920. else
  1921. {
  1922. Log->AddException(E);
  1923. return true;
  1924. }
  1925. }
  1926. //---------------------------------------------------------------------------
  1927. void __fastcall TTerminal::CloseOnCompletion(TOnceDoneOperation Operation, const UnicodeString Message)
  1928. {
  1929. Configuration->Usage->Inc(L"ClosesOnCompletion");
  1930. LogEvent(L"Closing session after completed operation (as requested by user)");
  1931. Close();
  1932. throw ESshTerminate(NULL,
  1933. Message.IsEmpty() ? UnicodeString(LoadStr(CLOSED_ON_COMPLETION)) : Message,
  1934. Operation);
  1935. }
  1936. //---------------------------------------------------------------------------
  1937. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  1938. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  1939. {
  1940. TBatchOverwrite Result;
  1941. if (Special &&
  1942. (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(FileName)))
  1943. {
  1944. Result = boResume;
  1945. }
  1946. else if (FLAGSET(Params, cpAppend))
  1947. {
  1948. Result = boAppend;
  1949. }
  1950. else if (CopyParam->NewerOnly &&
  1951. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  1952. (OperationProgress->Side != osLocal)))
  1953. {
  1954. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  1955. Result = boOlder;
  1956. }
  1957. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  1958. {
  1959. // no way to change batch overwrite mode when overwrite confirmations are off
  1960. assert(OperationProgress->BatchOverwrite == boNo);
  1961. Result = boAll;
  1962. }
  1963. else
  1964. {
  1965. Result = OperationProgress->BatchOverwrite;
  1966. if (!Special &&
  1967. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  1968. {
  1969. Result = boNo;
  1970. }
  1971. }
  1972. return Result;
  1973. }
  1974. //---------------------------------------------------------------------------
  1975. bool __fastcall TTerminal::CheckRemoteFile(
  1976. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  1977. {
  1978. return (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
  1979. }
  1980. //---------------------------------------------------------------------------
  1981. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(const UnicodeString FileName,
  1982. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  1983. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  1984. UnicodeString Message)
  1985. {
  1986. unsigned int Result;
  1987. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  1988. bool CanAlternateResume =
  1989. (FileParams != NULL) &&
  1990. (FileParams->DestSize < FileParams->SourceSize) &&
  1991. !OperationProgress->AsciiTransfer;
  1992. TBatchOverwrite BatchOverwrite = EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true);
  1993. bool Applicable = true;
  1994. switch (BatchOverwrite)
  1995. {
  1996. case boOlder:
  1997. Applicable = (FileParams != NULL);
  1998. break;
  1999. case boAlternateResume:
  2000. Applicable = CanAlternateResume;
  2001. break;
  2002. case boResume:
  2003. Applicable = CanAlternateResume;
  2004. break;
  2005. }
  2006. if (!Applicable)
  2007. {
  2008. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, false);
  2009. assert(BatchOverwrite != ABatchOverwrite);
  2010. BatchOverwrite = ABatchOverwrite;
  2011. }
  2012. if (BatchOverwrite == boNo)
  2013. {
  2014. if (Message.IsEmpty())
  2015. {
  2016. // Side refers to destination side here
  2017. UnicodeString FileNameOnly = (Side == osRemote) ? ExtractFileName(FileName) : UnixExtractFileName(FileName);
  2018. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  2019. REMOTE_FILE_OVERWRITE2), (FileNameOnly, FileNameOnly));
  2020. }
  2021. if (FileParams != NULL)
  2022. {
  2023. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  2024. FormatSize(FileParams->SourceSize),
  2025. UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision),
  2026. FormatSize(FileParams->DestSize),
  2027. UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision)));
  2028. }
  2029. if (ALWAYS_TRUE(QueryParams->HelpKeyword.IsEmpty()))
  2030. {
  2031. QueryParams->HelpKeyword = HELP_OVERWRITE;
  2032. }
  2033. Result = QueryUser(Message, NULL, Answers, QueryParams);
  2034. switch (Result)
  2035. {
  2036. case qaNeverAskAgain:
  2037. Configuration->ConfirmOverwriting = false;
  2038. Result = qaYes;
  2039. break;
  2040. case qaYesToAll:
  2041. BatchOverwrite = boAll;
  2042. break;
  2043. case qaAll:
  2044. BatchOverwrite = boOlder;
  2045. break;
  2046. case qaNoToAll:
  2047. BatchOverwrite = boNone;
  2048. break;
  2049. }
  2050. // we user has not selected another batch overwrite mode,
  2051. // keep the current one. note that we may get here even
  2052. // when batch overwrite was selected already, but it could not be applied
  2053. // to current transfer (see condition above)
  2054. if (BatchOverwrite != boNo)
  2055. {
  2056. OperationProgress->BatchOverwrite = BatchOverwrite;
  2057. }
  2058. }
  2059. if (BatchOverwrite != boNo)
  2060. {
  2061. switch (BatchOverwrite)
  2062. {
  2063. case boAll:
  2064. Result = qaYes;
  2065. break;
  2066. case boNone:
  2067. Result = qaNo;
  2068. break;
  2069. case boOlder:
  2070. if (FileParams == NULL)
  2071. {
  2072. Result = qaNo;
  2073. }
  2074. else
  2075. {
  2076. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  2077. TDateTime ReducedSourceTimestamp =
  2078. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  2079. TDateTime ReducedDestTimestamp =
  2080. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  2081. Result =
  2082. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  2083. qaYes : qaNo;
  2084. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  2085. (StandardTimestamp(ReducedSourceTimestamp),
  2086. StandardTimestamp(ReducedDestTimestamp),
  2087. ((Result == qaYes) ? L"" : L" not"))));
  2088. }
  2089. break;
  2090. case boAlternateResume:
  2091. assert(CanAlternateResume);
  2092. Result = qaSkip; // ugh
  2093. break;
  2094. case boAppend:
  2095. Result = qaRetry;
  2096. break;
  2097. case boResume:
  2098. Result = qaRetry;
  2099. break;
  2100. }
  2101. }
  2102. return Result;
  2103. }
  2104. //---------------------------------------------------------------------------
  2105. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  2106. const UnicodeString FileName, bool ClearDirectoryChange)
  2107. {
  2108. UnicodeString ParentDirectory;
  2109. UnicodeString Directory;
  2110. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  2111. {
  2112. if ((File != NULL) && (File->Directory != NULL))
  2113. {
  2114. if (File->IsDirectory)
  2115. {
  2116. Directory = File->Directory->FullDirectory + File->FileName;
  2117. }
  2118. ParentDirectory = File->Directory->Directory;
  2119. }
  2120. else if (!FileName.IsEmpty())
  2121. {
  2122. ParentDirectory = UnixExtractFilePath(FileName);
  2123. if (ParentDirectory.IsEmpty())
  2124. {
  2125. ParentDirectory = CurrentDirectory;
  2126. }
  2127. // this case for scripting
  2128. if ((File != NULL) && File->IsDirectory)
  2129. {
  2130. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  2131. UnixExtractFileName(File->FileName);
  2132. }
  2133. }
  2134. }
  2135. if (SessionData->CacheDirectories)
  2136. {
  2137. if (!Directory.IsEmpty())
  2138. {
  2139. DirectoryModified(Directory, true);
  2140. }
  2141. if (!ParentDirectory.IsEmpty())
  2142. {
  2143. DirectoryModified(ParentDirectory, false);
  2144. }
  2145. }
  2146. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  2147. {
  2148. if (!Directory.IsEmpty())
  2149. {
  2150. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  2151. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  2152. }
  2153. }
  2154. }
  2155. //---------------------------------------------------------------------------
  2156. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  2157. {
  2158. if (Path.IsEmpty())
  2159. {
  2160. ClearCachedFileList(CurrentDirectory, SubDirs);
  2161. }
  2162. else
  2163. {
  2164. ClearCachedFileList(Path, SubDirs);
  2165. }
  2166. }
  2167. //---------------------------------------------------------------------------
  2168. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  2169. {
  2170. AddCachedFileList(FileList);
  2171. }
  2172. //---------------------------------------------------------------------------
  2173. void __fastcall TTerminal::ReloadDirectory()
  2174. {
  2175. if (SessionData->CacheDirectories)
  2176. {
  2177. DirectoryModified(CurrentDirectory, false);
  2178. }
  2179. if (SessionData->CacheDirectoryChanges)
  2180. {
  2181. assert(FDirectoryChangesCache != NULL);
  2182. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  2183. }
  2184. ReadCurrentDirectory();
  2185. FReadCurrentDirectoryPending = false;
  2186. ReadDirectory(true);
  2187. FReadDirectoryPending = false;
  2188. }
  2189. //---------------------------------------------------------------------------
  2190. void __fastcall TTerminal::RefreshDirectory()
  2191. {
  2192. if (!SessionData->CacheDirectories)
  2193. {
  2194. LogEvent(L"Not refreshing directory, caching is off.");
  2195. }
  2196. else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  2197. {
  2198. // Second parameter was added to allow (rather force) using the cache.
  2199. // Before, the directory was reloaded always, it seems useless,
  2200. // has it any reason?
  2201. ReadDirectory(true, true);
  2202. FReadDirectoryPending = false;
  2203. }
  2204. }
  2205. //---------------------------------------------------------------------------
  2206. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  2207. {
  2208. // if filename doesn't contain path, we check for existence of file
  2209. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  2210. UnixSamePath(CurrentDirectory, FFiles->Directory))
  2211. {
  2212. TRemoteFile *File = FFiles->FindFile(FileName);
  2213. if (File)
  2214. {
  2215. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  2216. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  2217. }
  2218. }
  2219. }
  2220. //---------------------------------------------------------------------------
  2221. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  2222. {
  2223. if (Log->Logging)
  2224. {
  2225. Log->Add(llMessage, Str);
  2226. }
  2227. }
  2228. //---------------------------------------------------------------------------
  2229. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  2230. TFileOperationProgressType * OperationProgress, Exception * E)
  2231. {
  2232. // EScpSkipFile without "cancel" is file skip,
  2233. // and we do not want to record skipped actions.
  2234. // But EScpSkipFile with "cancel" is abort and we want to record that.
  2235. // Note that TSCPFileSystem modifies the logic of RollbackAction little bit.
  2236. if ((dynamic_cast<EScpSkipFile *>(E) != NULL) &&
  2237. ((OperationProgress == NULL) ||
  2238. (OperationProgress->Cancel == csContinue)))
  2239. {
  2240. Action.Cancel();
  2241. }
  2242. else
  2243. {
  2244. Action.Rollback(E);
  2245. }
  2246. }
  2247. //---------------------------------------------------------------------------
  2248. void __fastcall TTerminal::DoStartup()
  2249. {
  2250. LogEvent(L"Doing startup conversation with host.");
  2251. BeginTransaction();
  2252. try
  2253. {
  2254. DoInformation(LoadStr(STATUS_STARTUP), true);
  2255. // Make sure that directory would be loaded at last
  2256. FReadCurrentDirectoryPending = true;
  2257. FReadDirectoryPending = AutoReadDirectory;
  2258. FFileSystem->DoStartup();
  2259. LookupUsersGroups();
  2260. if (!SessionData->RemoteDirectory.IsEmpty())
  2261. {
  2262. ChangeDirectory(SessionData->RemoteDirectory);
  2263. }
  2264. }
  2265. __finally
  2266. {
  2267. DoEndTransaction(true);
  2268. }
  2269. LogEvent(L"Startup conversation with host finished.");
  2270. }
  2271. //---------------------------------------------------------------------------
  2272. void __fastcall TTerminal::ReadCurrentDirectory()
  2273. {
  2274. assert(FFileSystem);
  2275. try
  2276. {
  2277. // reset flag is case we are called externally (like from console dialog)
  2278. FReadCurrentDirectoryPending = false;
  2279. LogEvent(L"Getting current directory name.");
  2280. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  2281. FFileSystem->ReadCurrentDirectory();
  2282. ReactOnCommand(fsCurrentDirectory);
  2283. if (SessionData->CacheDirectoryChanges)
  2284. {
  2285. assert(FDirectoryChangesCache != NULL);
  2286. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  2287. {
  2288. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  2289. FLastDirectoryChange, CurrentDirectory);
  2290. }
  2291. // not to broke the cache, if the next directory change would not
  2292. // be initialized by ChangeDirectory(), which sets it
  2293. // (HomeDirectory() particularly)
  2294. FLastDirectoryChange = L"";
  2295. }
  2296. if (OldDirectory.IsEmpty())
  2297. {
  2298. FLockDirectory = (SessionData->LockInHome ?
  2299. FFileSystem->CurrentDirectory : UnicodeString(L""));
  2300. }
  2301. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  2302. }
  2303. catch (Exception &E)
  2304. {
  2305. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  2306. }
  2307. }
  2308. //---------------------------------------------------------------------------
  2309. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  2310. {
  2311. bool LoadedFromCache = false;
  2312. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  2313. {
  2314. if (ReloadOnly && !ForceCache)
  2315. {
  2316. LogEvent(L"Cached directory not reloaded.");
  2317. }
  2318. else
  2319. {
  2320. DoStartReadDirectory();
  2321. try
  2322. {
  2323. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  2324. }
  2325. __finally
  2326. {
  2327. DoReadDirectory(ReloadOnly);
  2328. }
  2329. if (LoadedFromCache)
  2330. {
  2331. LogEvent(L"Directory content loaded from cache.");
  2332. }
  2333. else
  2334. {
  2335. LogEvent(L"Cached Directory content has been removed.");
  2336. }
  2337. }
  2338. }
  2339. if (!LoadedFromCache)
  2340. {
  2341. DoStartReadDirectory();
  2342. FReadingCurrentDirectory = true;
  2343. bool Cancel = false; // dummy
  2344. DoReadDirectoryProgress(0, 0, Cancel);
  2345. try
  2346. {
  2347. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  2348. try
  2349. {
  2350. Files->Directory = CurrentDirectory;
  2351. CustomReadDirectory(Files);
  2352. }
  2353. __finally
  2354. {
  2355. DoReadDirectoryProgress(-1, 0, Cancel);
  2356. FReadingCurrentDirectory = false;
  2357. TRemoteDirectory * OldFiles = FFiles;
  2358. FFiles = Files;
  2359. try
  2360. {
  2361. DoReadDirectory(ReloadOnly);
  2362. }
  2363. __finally
  2364. {
  2365. // delete only after loading new files to dir view,
  2366. // not to destroy the file objects that the view holds
  2367. // (can be issue in multi threaded environment, such as when the
  2368. // terminal is reconnecting in the terminal thread)
  2369. delete OldFiles;
  2370. }
  2371. if (Active)
  2372. {
  2373. if (SessionData->CacheDirectories)
  2374. {
  2375. DirectoryLoaded(FFiles);
  2376. }
  2377. }
  2378. }
  2379. }
  2380. catch (Exception &E)
  2381. {
  2382. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  2383. }
  2384. }
  2385. }
  2386. //---------------------------------------------------------------------------
  2387. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  2388. {
  2389. // optimization
  2390. if (Log->Logging)
  2391. {
  2392. LogEvent(FORMAT(L"%s;%s;%d;%s;%s;%s;%s;%d",
  2393. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification),
  2394. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  2395. File->Attr)));
  2396. }
  2397. }
  2398. //---------------------------------------------------------------------------
  2399. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2400. {
  2401. UnicodeString Result;
  2402. // optimization
  2403. if (Log->Logging)
  2404. {
  2405. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  2406. }
  2407. return Result;
  2408. }
  2409. //---------------------------------------------------------------------------
  2410. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2411. {
  2412. // optimization
  2413. if (Log->Logging)
  2414. {
  2415. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size))));
  2416. }
  2417. }
  2418. //---------------------------------------------------------------------------
  2419. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  2420. {
  2421. assert(FileList);
  2422. assert(FFileSystem);
  2423. FFileSystem->ReadDirectory(FileList);
  2424. if (Log->Logging)
  2425. {
  2426. for (int Index = 0; Index < FileList->Count; Index++)
  2427. {
  2428. LogRemoteFile(FileList->Files[Index]);
  2429. }
  2430. }
  2431. ReactOnCommand(fsListDirectory);
  2432. }
  2433. //---------------------------------------------------------------------------
  2434. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  2435. {
  2436. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  2437. TRemoteFileList * FileList = NULL;
  2438. try
  2439. {
  2440. FileList = DoReadDirectoryListing(Directory, false);
  2441. if (FileList != NULL)
  2442. {
  2443. int Index = 0;
  2444. while (Index < FileList->Count)
  2445. {
  2446. TRemoteFile * File = FileList->Files[Index];
  2447. TFileMasks::TParams Params;
  2448. Params.Size = File->Size;
  2449. Params.Modification = File->Modification;
  2450. // Have to use UnicodeString(), instead of L"", as with that
  2451. // overload with (UnicodeString, bool, bool, TParams*) wins
  2452. if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  2453. {
  2454. FileList->Delete(Index);
  2455. }
  2456. else
  2457. {
  2458. Index++;
  2459. }
  2460. }
  2461. Action.FileList(FileList);
  2462. }
  2463. }
  2464. catch(Exception & E)
  2465. {
  2466. COMMAND_ERROR_ARI_ACTION
  2467. (
  2468. L"",
  2469. FileList = ReadDirectoryListing(Directory, Mask),
  2470. Action
  2471. );
  2472. }
  2473. return FileList;
  2474. }
  2475. //---------------------------------------------------------------------------
  2476. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  2477. {
  2478. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  2479. TRemoteFile * File = NULL;
  2480. try
  2481. {
  2482. // reset caches
  2483. AnnounceFileListOperation();
  2484. ReadFile(Path, File);
  2485. Action.File(File);
  2486. }
  2487. catch(Exception & E)
  2488. {
  2489. COMMAND_ERROR_ARI_ACTION
  2490. (
  2491. L"",
  2492. File = ReadFileListing(Path),
  2493. Action
  2494. );
  2495. }
  2496. return File;
  2497. }
  2498. //---------------------------------------------------------------------------
  2499. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2500. {
  2501. TRemoteFileList * FileList = NULL;
  2502. try
  2503. {
  2504. FileList = DoReadDirectoryListing(Directory, UseCache);
  2505. }
  2506. catch(Exception & E)
  2507. {
  2508. COMMAND_ERROR_ARI
  2509. (
  2510. L"",
  2511. FileList = CustomReadDirectoryListing(Directory, UseCache);
  2512. );
  2513. }
  2514. return FileList;
  2515. }
  2516. //---------------------------------------------------------------------------
  2517. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2518. {
  2519. TRemoteFileList * FileList = new TRemoteFileList();
  2520. try
  2521. {
  2522. bool Cache = UseCache && SessionData->CacheDirectories;
  2523. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  2524. if (LoadedFromCache)
  2525. {
  2526. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  2527. }
  2528. if (!LoadedFromCache)
  2529. {
  2530. FileList->Directory = Directory;
  2531. ExceptionOnFail = true;
  2532. try
  2533. {
  2534. ReadDirectory(FileList);
  2535. }
  2536. __finally
  2537. {
  2538. ExceptionOnFail = false;
  2539. }
  2540. if (Cache)
  2541. {
  2542. AddCachedFileList(FileList);
  2543. }
  2544. }
  2545. }
  2546. catch(...)
  2547. {
  2548. delete FileList;
  2549. throw;
  2550. }
  2551. return FileList;
  2552. }
  2553. //---------------------------------------------------------------------------
  2554. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  2555. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  2556. {
  2557. TRemoteFileList * FileList = NULL;
  2558. if (IgnoreErrors)
  2559. {
  2560. ExceptionOnFail = true;
  2561. try
  2562. {
  2563. try
  2564. {
  2565. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2566. }
  2567. catch(...)
  2568. {
  2569. if (!Active)
  2570. {
  2571. throw;
  2572. }
  2573. }
  2574. }
  2575. __finally
  2576. {
  2577. ExceptionOnFail = false;
  2578. }
  2579. }
  2580. else
  2581. {
  2582. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2583. }
  2584. // skip if directory listing fails and user selects "skip"
  2585. if (FileList)
  2586. {
  2587. try
  2588. {
  2589. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  2590. TRemoteFile * File;
  2591. for (int Index = 0; Index < FileList->Count; Index++)
  2592. {
  2593. File = FileList->Files[Index];
  2594. if (!File->IsParentDirectory && !File->IsThisDirectory)
  2595. {
  2596. CallBackFunc(Directory + File->FileName, File, Param);
  2597. // We should catch EScpSkipFile here as we do in ProcessFiles.
  2598. // Now we have to handle EScpSkipFile in every callback implementation.
  2599. }
  2600. }
  2601. }
  2602. __finally
  2603. {
  2604. delete FileList;
  2605. }
  2606. }
  2607. }
  2608. //---------------------------------------------------------------------------
  2609. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  2610. {
  2611. try
  2612. {
  2613. CustomReadDirectory(FileList);
  2614. }
  2615. catch (Exception &E)
  2616. {
  2617. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  2618. }
  2619. }
  2620. //---------------------------------------------------------------------------
  2621. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  2622. TRemoteFile *& File)
  2623. {
  2624. assert(FFileSystem);
  2625. try
  2626. {
  2627. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  2628. FFileSystem->ReadSymlink(SymlinkFile, File);
  2629. ReactOnCommand(fsReadSymlink);
  2630. }
  2631. catch (Exception &E)
  2632. {
  2633. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  2634. }
  2635. }
  2636. //---------------------------------------------------------------------------
  2637. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  2638. TRemoteFile *& File)
  2639. {
  2640. assert(FFileSystem);
  2641. File = NULL;
  2642. try
  2643. {
  2644. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  2645. FFileSystem->ReadFile(FileName, File);
  2646. ReactOnCommand(fsListFile);
  2647. LogRemoteFile(File);
  2648. }
  2649. catch (Exception &E)
  2650. {
  2651. if (File) delete File;
  2652. File = NULL;
  2653. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  2654. }
  2655. }
  2656. //---------------------------------------------------------------------------
  2657. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  2658. {
  2659. bool Result;
  2660. TRemoteFile * File = NULL;
  2661. try
  2662. {
  2663. ExceptionOnFail = true;
  2664. try
  2665. {
  2666. ReadFile(FileName, File);
  2667. }
  2668. __finally
  2669. {
  2670. ExceptionOnFail = false;
  2671. }
  2672. if (AFile != NULL)
  2673. {
  2674. *AFile = File;
  2675. }
  2676. else
  2677. {
  2678. delete File;
  2679. }
  2680. Result = true;
  2681. }
  2682. catch(...)
  2683. {
  2684. if (Active)
  2685. {
  2686. Result = false;
  2687. }
  2688. else
  2689. {
  2690. throw;
  2691. }
  2692. }
  2693. return Result;
  2694. }
  2695. //---------------------------------------------------------------------------
  2696. void __fastcall TTerminal::AnnounceFileListOperation()
  2697. {
  2698. FFileSystem->AnnounceFileListOperation();
  2699. }
  2700. //---------------------------------------------------------------------------
  2701. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  2702. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  2703. TOperationSide Side, bool Ex)
  2704. {
  2705. assert(FFileSystem);
  2706. assert(FileList);
  2707. bool Result = false;
  2708. TOnceDoneOperation OnceDoneOperation = odoIdle;
  2709. try
  2710. {
  2711. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  2712. Progress.Start(Operation, Side, FileList->Count);
  2713. FOperationProgress = &Progress;
  2714. try
  2715. {
  2716. if (Side == osRemote)
  2717. {
  2718. BeginTransaction();
  2719. }
  2720. try
  2721. {
  2722. int Index = 0;
  2723. UnicodeString FileName;
  2724. bool Success;
  2725. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  2726. {
  2727. FileName = FileList->Strings[Index];
  2728. try
  2729. {
  2730. try
  2731. {
  2732. Success = false;
  2733. if (!Ex)
  2734. {
  2735. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  2736. }
  2737. else
  2738. {
  2739. // not used anymore
  2740. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  2741. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  2742. }
  2743. Success = true;
  2744. }
  2745. __finally
  2746. {
  2747. Progress.Finish(FileName, Success, OnceDoneOperation);
  2748. }
  2749. }
  2750. catch(EScpSkipFile & E)
  2751. {
  2752. TSuspendFileOperationProgress Suspend(OperationProgress);
  2753. if (!HandleException(&E))
  2754. {
  2755. throw;
  2756. }
  2757. }
  2758. Index++;
  2759. }
  2760. }
  2761. __finally
  2762. {
  2763. if (Side == osRemote)
  2764. {
  2765. EndTransaction();
  2766. }
  2767. }
  2768. if (Progress.Cancel == csContinue)
  2769. {
  2770. Result = true;
  2771. }
  2772. }
  2773. __finally
  2774. {
  2775. FOperationProgress = NULL;
  2776. Progress.Stop();
  2777. }
  2778. }
  2779. catch (...)
  2780. {
  2781. OnceDoneOperation = odoIdle;
  2782. // this was missing here. was it by purpose?
  2783. // without it any error message is lost
  2784. throw;
  2785. }
  2786. if (OnceDoneOperation != odoIdle)
  2787. {
  2788. CloseOnCompletion(OnceDoneOperation);
  2789. }
  2790. return Result;
  2791. }
  2792. //---------------------------------------------------------------------------
  2793. // not used anymore
  2794. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  2795. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  2796. {
  2797. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  2798. Param, Side, true);
  2799. }
  2800. //---------------------------------------------------------------------------
  2801. TStrings * __fastcall TTerminal::GetFixedPaths()
  2802. {
  2803. assert(FFileSystem != NULL);
  2804. return FFileSystem->GetFixedPaths();
  2805. }
  2806. //---------------------------------------------------------------------------
  2807. bool __fastcall TTerminal::GetResolvingSymlinks()
  2808. {
  2809. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  2810. }
  2811. //---------------------------------------------------------------------------
  2812. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  2813. {
  2814. TUsableCopyParamAttrs Result;
  2815. Result.General =
  2816. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  2817. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  2818. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  2819. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  2820. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  2821. // the following three are never supported for download,
  2822. // so when they are not suppored for upload too,
  2823. // set them in General flags, so that they do not get enabled on
  2824. // Synchronize dialog.
  2825. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  2826. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  2827. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM);
  2828. Result.Download = Result.General | cpaNoClearArchive |
  2829. cpaNoIgnorePermErrors |
  2830. // May be already set in General flags, but it's unconditional here
  2831. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM;
  2832. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  2833. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  2834. return Result;
  2835. }
  2836. //---------------------------------------------------------------------------
  2837. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  2838. {
  2839. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  2840. if (Result)
  2841. {
  2842. UnicodeString Path = UnixExtractFilePath(FileName);
  2843. if (Path.IsEmpty())
  2844. {
  2845. Path = CurrentDirectory;
  2846. }
  2847. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  2848. }
  2849. return Result;
  2850. }
  2851. //---------------------------------------------------------------------------
  2852. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  2853. const TRemoteFile * File)
  2854. {
  2855. if (FileName.IsEmpty())
  2856. {
  2857. assert(File != NULL);
  2858. FileName = File->FileName;
  2859. }
  2860. if (!IsRecycledFile(FileName))
  2861. {
  2862. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  2863. (FileName, SessionData->RecycleBinPath)));
  2864. TMoveFileParams Params;
  2865. Params.Target = SessionData->RecycleBinPath;
  2866. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  2867. MoveFile(FileName, File, &Params);
  2868. }
  2869. }
  2870. //---------------------------------------------------------------------------
  2871. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  2872. const TRemoteFile * File, void * AParams)
  2873. {
  2874. if (FileName.IsEmpty() && File)
  2875. {
  2876. FileName = File->FileName;
  2877. }
  2878. if (OperationProgress && OperationProgress->Operation == foDelete)
  2879. {
  2880. if (OperationProgress->Cancel != csContinue) Abort();
  2881. OperationProgress->SetFile(FileName);
  2882. }
  2883. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  2884. bool Recycle =
  2885. FLAGCLEAR(Params, dfForceDelete) &&
  2886. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  2887. !SessionData->RecycleBinPath.IsEmpty();
  2888. if (Recycle && !IsRecycledFile(FileName))
  2889. {
  2890. RecycleFile(FileName, File);
  2891. }
  2892. else
  2893. {
  2894. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  2895. if (File) FileModified(File, FileName, true);
  2896. DoDeleteFile(FileName, File, Params);
  2897. ReactOnCommand(fsDeleteFile);
  2898. }
  2899. }
  2900. //---------------------------------------------------------------------------
  2901. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  2902. const TRemoteFile * File, int Params)
  2903. {
  2904. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  2905. try
  2906. {
  2907. assert(FFileSystem);
  2908. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  2909. FFileSystem->DeleteFile(FileName, File, Params, Action);
  2910. }
  2911. catch(Exception & E)
  2912. {
  2913. COMMAND_ERROR_ARI_ACTION
  2914. (
  2915. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  2916. DoDeleteFile(FileName, File, Params),
  2917. Action
  2918. );
  2919. }
  2920. }
  2921. //---------------------------------------------------------------------------
  2922. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  2923. {
  2924. // TODO: avoid resolving symlinks while reading subdirectories.
  2925. // Resolving does not work anyway for relative symlinks in subdirectories
  2926. // (at least for SFTP).
  2927. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  2928. }
  2929. //---------------------------------------------------------------------------
  2930. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  2931. const TRemoteFile * /*File*/, void * Params)
  2932. {
  2933. if ((OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  2934. {
  2935. OperationProgress->SetFile(FileName);
  2936. }
  2937. if (OnDeleteLocalFile == NULL)
  2938. {
  2939. if (!RecursiveDeleteFile(FileName, false))
  2940. {
  2941. throw Exception(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  2942. }
  2943. }
  2944. else
  2945. {
  2946. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  2947. }
  2948. }
  2949. //---------------------------------------------------------------------------
  2950. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  2951. {
  2952. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  2953. }
  2954. //---------------------------------------------------------------------------
  2955. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  2956. const TRemoteFile * File, void * AParams)
  2957. {
  2958. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  2959. if (FileName.IsEmpty() && File)
  2960. {
  2961. FileName = File->FileName;
  2962. }
  2963. if (OperationProgress && OperationProgress->Operation == foCustomCommand)
  2964. {
  2965. if (OperationProgress->Cancel != csContinue) Abort();
  2966. OperationProgress->SetFile(FileName);
  2967. }
  2968. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  2969. (Params->Command, Params->Params, FileName)));
  2970. if (File) FileModified(File, FileName);
  2971. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  2972. Params->OutputEvent);
  2973. ReactOnCommand(fsAnyCommand);
  2974. }
  2975. //---------------------------------------------------------------------------
  2976. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  2977. const TRemoteFile * File, UnicodeString Command, int Params,
  2978. TCaptureOutputEvent OutputEvent)
  2979. {
  2980. try
  2981. {
  2982. if (IsCapable[fcAnyCommand])
  2983. {
  2984. assert(FFileSystem);
  2985. assert(fcShellAnyCommand);
  2986. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  2987. }
  2988. else
  2989. {
  2990. assert(CommandSessionOpened);
  2991. assert(FCommandSession->FSProtocol == cfsSCP);
  2992. LogEvent(L"Executing custom command on command session.");
  2993. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  2994. {
  2995. FCommandSession->CurrentDirectory = CurrentDirectory;
  2996. // We are likely in transaction, so ReadCurrentDirectory won't get called
  2997. // until transaction ends. But we need to know CurrentDirectory to
  2998. // expand !/ pattern.
  2999. // Doing this only, when current directory of the main and secondary shell differs,
  3000. // what would be the case before the first file in transaction.
  3001. // Otherwise we would be reading pwd before every time as the
  3002. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  3003. if (FCommandSession->FReadCurrentDirectoryPending)
  3004. {
  3005. FCommandSession->ReadCurrentDirectory();
  3006. }
  3007. }
  3008. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  3009. Params, OutputEvent);
  3010. }
  3011. }
  3012. catch(Exception & E)
  3013. {
  3014. COMMAND_ERROR_ARI
  3015. (
  3016. FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
  3017. DoCustomCommandOnFile(FileName, File, Command, Params, OutputEvent)
  3018. );
  3019. }
  3020. }
  3021. //---------------------------------------------------------------------------
  3022. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  3023. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  3024. {
  3025. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  3026. {
  3027. TCustomCommandParams AParams;
  3028. AParams.Command = Command;
  3029. AParams.Params = Params;
  3030. AParams.OutputEvent = OutputEvent;
  3031. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  3032. }
  3033. else
  3034. {
  3035. UnicodeString FileList;
  3036. for (int i = 0; i < Files->Count; i++)
  3037. {
  3038. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  3039. bool Dir = File->IsDirectory && !File->IsSymLink;
  3040. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  3041. {
  3042. if (!FileList.IsEmpty())
  3043. {
  3044. FileList += L" ";
  3045. }
  3046. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  3047. }
  3048. }
  3049. TCustomCommandData Data(this);
  3050. UnicodeString Cmd =
  3051. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  3052. Complete(Command, true);
  3053. DoAnyCommand(Cmd, OutputEvent, NULL);
  3054. }
  3055. }
  3056. //---------------------------------------------------------------------------
  3057. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  3058. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  3059. {
  3060. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  3061. assert(RProperties && !RProperties->Valid.Empty());
  3062. if (FileName.IsEmpty() && File)
  3063. {
  3064. FileName = File->FileName;
  3065. }
  3066. if (OperationProgress && OperationProgress->Operation == foSetProperties)
  3067. {
  3068. if (OperationProgress->Cancel != csContinue) Abort();
  3069. OperationProgress->SetFile(FileName);
  3070. }
  3071. if (Log->Logging)
  3072. {
  3073. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  3074. (FileName, BooleanToEngStr(RProperties->Recursive))));
  3075. if (RProperties->Valid.Contains(vpRights))
  3076. {
  3077. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  3078. }
  3079. if (RProperties->Valid.Contains(vpGroup))
  3080. {
  3081. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  3082. }
  3083. if (RProperties->Valid.Contains(vpOwner))
  3084. {
  3085. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  3086. }
  3087. if (RProperties->Valid.Contains(vpModification))
  3088. {
  3089. LogEvent(FORMAT(L" - modification: \"%s\"",
  3090. (FormatDateTime(L"dddddd tt",
  3091. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  3092. }
  3093. if (RProperties->Valid.Contains(vpLastAccess))
  3094. {
  3095. LogEvent(FORMAT(L" - last access: \"%s\"",
  3096. (FormatDateTime(L"dddddd tt",
  3097. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  3098. }
  3099. }
  3100. FileModified(File, FileName);
  3101. DoChangeFileProperties(FileName, File, RProperties);
  3102. ReactOnCommand(fsChangeProperties);
  3103. }
  3104. //---------------------------------------------------------------------------
  3105. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  3106. const TRemoteFile * File, const TRemoteProperties * Properties)
  3107. {
  3108. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3109. try
  3110. {
  3111. assert(FFileSystem);
  3112. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  3113. }
  3114. catch(Exception & E)
  3115. {
  3116. COMMAND_ERROR_ARI_ACTION
  3117. (
  3118. FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
  3119. DoChangeFileProperties(FileName, File, Properties),
  3120. Action
  3121. );
  3122. }
  3123. }
  3124. //---------------------------------------------------------------------------
  3125. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  3126. const TRemoteProperties * Properties)
  3127. {
  3128. AnnounceFileListOperation();
  3129. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  3130. }
  3131. //---------------------------------------------------------------------------
  3132. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  3133. {
  3134. bool Result =
  3135. IsCapable[fcLoadingAdditionalProperties] &&
  3136. FFileSystem->LoadFilesProperties(FileList);
  3137. if (Result && SessionData->CacheDirectories &&
  3138. (FileList->Count > 0) &&
  3139. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  3140. {
  3141. AddCachedFileList(FFiles);
  3142. }
  3143. return Result;
  3144. }
  3145. //---------------------------------------------------------------------------
  3146. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  3147. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  3148. {
  3149. assert(Param);
  3150. assert(File);
  3151. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  3152. if (FileName.IsEmpty())
  3153. {
  3154. FileName = File->FileName;
  3155. }
  3156. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  3157. {
  3158. if (OperationProgress->Cancel != csContinue) Abort();
  3159. OperationProgress->SetFile(FileName);
  3160. }
  3161. bool AllowTransfer = (AParams->CopyParam == NULL);
  3162. if (!AllowTransfer)
  3163. {
  3164. TFileMasks::TParams MaskParams;
  3165. MaskParams.Size = File->Size;
  3166. MaskParams.Modification = File->Modification;
  3167. AllowTransfer = AParams->CopyParam->AllowTransfer(
  3168. UnixExcludeTrailingBackslash(File->FullFileName), osRemote, File->IsDirectory,
  3169. MaskParams);
  3170. }
  3171. if (AllowTransfer)
  3172. {
  3173. if (File->IsDirectory)
  3174. {
  3175. if (!File->IsSymLink)
  3176. {
  3177. if (!AParams->AllowDirs)
  3178. {
  3179. AParams->Result = false;
  3180. }
  3181. else
  3182. {
  3183. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  3184. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  3185. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  3186. }
  3187. }
  3188. else
  3189. {
  3190. AParams->Size += File->Size;
  3191. }
  3192. if (AParams->Stats != NULL)
  3193. {
  3194. AParams->Stats->Directories++;
  3195. }
  3196. }
  3197. else
  3198. {
  3199. AParams->Size += File->Size;
  3200. if (AParams->Stats != NULL)
  3201. {
  3202. AParams->Stats->Files++;
  3203. }
  3204. }
  3205. if ((AParams->Stats != NULL) && File->IsSymLink)
  3206. {
  3207. AParams->Stats->SymLinks++;
  3208. }
  3209. }
  3210. }
  3211. //---------------------------------------------------------------------------
  3212. void __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  3213. const TRemoteFile * File, TCalculateSizeParams * Params)
  3214. {
  3215. try
  3216. {
  3217. ProcessDirectory(FileName, CalculateFileSize, Params);
  3218. }
  3219. catch(Exception & E)
  3220. {
  3221. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  3222. {
  3223. COMMAND_ERROR_ARI
  3224. (
  3225. FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)),
  3226. DoCalculateDirectorySize(FileName, File, Params)
  3227. );
  3228. }
  3229. }
  3230. }
  3231. //---------------------------------------------------------------------------
  3232. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  3233. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  3234. bool AllowDirs, TCalculateSizeStats * Stats)
  3235. {
  3236. TCalculateSizeParams Param;
  3237. Param.Size = 0;
  3238. Param.Params = Params;
  3239. Param.CopyParam = CopyParam;
  3240. Param.Stats = Stats;
  3241. Param.AllowDirs = AllowDirs;
  3242. Param.Result = true;
  3243. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  3244. Size = Param.Size;
  3245. return Param.Result;
  3246. }
  3247. //---------------------------------------------------------------------------
  3248. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  3249. TStrings * FileList, TStrings * Checksums,
  3250. TCalculatedChecksumEvent OnCalculatedChecksum)
  3251. {
  3252. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  3253. }
  3254. //---------------------------------------------------------------------------
  3255. void __fastcall TTerminal::RenameFile(const UnicodeString FileName,
  3256. const UnicodeString NewName)
  3257. {
  3258. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  3259. DoRenameFile(FileName, NewName, false);
  3260. ReactOnCommand(fsRenameFile);
  3261. }
  3262. //---------------------------------------------------------------------------
  3263. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  3264. const UnicodeString NewName, bool CheckExistence)
  3265. {
  3266. assert(File && File->Directory == FFiles);
  3267. bool Proceed = true;
  3268. // if filename doesn't contain path, we check for existence of file
  3269. if ((File->FileName != NewName) && CheckExistence &&
  3270. Configuration->ConfirmOverwriting &&
  3271. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3272. {
  3273. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  3274. if (DuplicateFile)
  3275. {
  3276. UnicodeString QuestionFmt;
  3277. if (DuplicateFile->IsDirectory)
  3278. {
  3279. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  3280. }
  3281. else
  3282. {
  3283. QuestionFmt = LoadStr(FILE_OVERWRITE);
  3284. }
  3285. TQueryParams Params(qpNeverAskAgainCheck);
  3286. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  3287. unsigned int Result = QueryUser(Question, NULL,
  3288. qaYes | qaNo, &Params);
  3289. if (Result == qaNeverAskAgain)
  3290. {
  3291. Proceed = true;
  3292. Configuration->ConfirmOverwriting = false;
  3293. }
  3294. else
  3295. {
  3296. Proceed = (Result == qaYes);
  3297. }
  3298. }
  3299. }
  3300. if (Proceed)
  3301. {
  3302. FileModified(File, File->FileName);
  3303. RenameFile(File->FileName, NewName);
  3304. }
  3305. }
  3306. //---------------------------------------------------------------------------
  3307. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName,
  3308. const UnicodeString NewName, bool Move)
  3309. {
  3310. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  3311. try
  3312. {
  3313. assert(FFileSystem);
  3314. FFileSystem->RenameFile(FileName, NewName);
  3315. }
  3316. catch(Exception & E)
  3317. {
  3318. COMMAND_ERROR_ARI_ACTION
  3319. (
  3320. FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName)),
  3321. DoRenameFile(FileName, NewName, Move),
  3322. Action
  3323. );
  3324. }
  3325. }
  3326. //---------------------------------------------------------------------------
  3327. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  3328. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  3329. {
  3330. if (OperationProgress &&
  3331. ((OperationProgress->Operation == foRemoteMove) ||
  3332. (OperationProgress->Operation == foDelete)))
  3333. {
  3334. if (OperationProgress->Cancel != csContinue) Abort();
  3335. OperationProgress->SetFile(FileName);
  3336. }
  3337. assert(Param != NULL);
  3338. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3339. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3340. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3341. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  3342. FileModified(File, FileName);
  3343. DoRenameFile(FileName, NewName, true);
  3344. ReactOnCommand(fsMoveFile);
  3345. }
  3346. //---------------------------------------------------------------------------
  3347. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  3348. const UnicodeString FileMask)
  3349. {
  3350. TMoveFileParams Params;
  3351. Params.Target = Target;
  3352. Params.FileMask = FileMask;
  3353. DirectoryModified(Target, true);
  3354. bool Result;
  3355. BeginTransaction();
  3356. try
  3357. {
  3358. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  3359. }
  3360. __finally
  3361. {
  3362. if (Active)
  3363. {
  3364. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  3365. bool PossiblyMoved = false;
  3366. // check if we was moving current directory.
  3367. // this is just optimization to avoid checking existence of current
  3368. // directory after each move operation.
  3369. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  3370. {
  3371. const TRemoteFile * File =
  3372. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  3373. // File can be NULL, and filename may not be full path,
  3374. // but currently this is the only way we can move (at least in GUI)
  3375. // current directory
  3376. if ((File != NULL) &&
  3377. File->IsDirectory &&
  3378. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  3379. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  3380. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  3381. {
  3382. PossiblyMoved = true;
  3383. }
  3384. }
  3385. if (PossiblyMoved && !FileExists(CurrentDirectory))
  3386. {
  3387. UnicodeString NearestExisting = CurrentDirectory;
  3388. do
  3389. {
  3390. NearestExisting = UnixExtractFileDir(NearestExisting);
  3391. }
  3392. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  3393. ChangeDirectory(NearestExisting);
  3394. }
  3395. }
  3396. EndTransaction();
  3397. }
  3398. return Result;
  3399. }
  3400. //---------------------------------------------------------------------------
  3401. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName,
  3402. const UnicodeString NewName)
  3403. {
  3404. try
  3405. {
  3406. assert(FFileSystem);
  3407. if (IsCapable[fcRemoteCopy])
  3408. {
  3409. FFileSystem->CopyFile(FileName, NewName);
  3410. }
  3411. else
  3412. {
  3413. assert(CommandSessionOpened);
  3414. assert(FCommandSession->FSProtocol == cfsSCP);
  3415. LogEvent(L"Copying file on command session.");
  3416. FCommandSession->CurrentDirectory = CurrentDirectory;
  3417. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  3418. }
  3419. }
  3420. catch(Exception & E)
  3421. {
  3422. COMMAND_ERROR_ARI
  3423. (
  3424. FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)),
  3425. DoCopyFile(FileName, NewName)
  3426. );
  3427. }
  3428. }
  3429. //---------------------------------------------------------------------------
  3430. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  3431. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  3432. {
  3433. if (OperationProgress && (OperationProgress->Operation == foRemoteCopy))
  3434. {
  3435. if (OperationProgress->Cancel != csContinue) Abort();
  3436. OperationProgress->SetFile(FileName);
  3437. }
  3438. assert(Param != NULL);
  3439. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3440. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3441. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3442. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  3443. DoCopyFile(FileName, NewName);
  3444. ReactOnCommand(fsCopyFile);
  3445. }
  3446. //---------------------------------------------------------------------------
  3447. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  3448. const UnicodeString FileMask)
  3449. {
  3450. TMoveFileParams Params;
  3451. Params.Target = Target;
  3452. Params.FileMask = FileMask;
  3453. DirectoryModified(Target, true);
  3454. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  3455. }
  3456. //---------------------------------------------------------------------------
  3457. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  3458. const TRemoteProperties * Properties)
  3459. {
  3460. assert(FFileSystem);
  3461. EnsureNonExistence(DirName);
  3462. FileModified(NULL, DirName);
  3463. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  3464. DoCreateDirectory(DirName);
  3465. if ((Properties != NULL) && !Properties->Valid.Empty())
  3466. {
  3467. DoChangeFileProperties(DirName, NULL, Properties);
  3468. }
  3469. ReactOnCommand(fsCreateDirectory);
  3470. }
  3471. //---------------------------------------------------------------------------
  3472. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  3473. {
  3474. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  3475. try
  3476. {
  3477. assert(FFileSystem);
  3478. FFileSystem->CreateDirectory(DirName);
  3479. }
  3480. catch(Exception & E)
  3481. {
  3482. COMMAND_ERROR_ARI_ACTION
  3483. (
  3484. FMTLOAD(CREATE_DIR_ERROR, (DirName)),
  3485. DoCreateDirectory(DirName),
  3486. Action
  3487. );
  3488. }
  3489. }
  3490. //---------------------------------------------------------------------------
  3491. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  3492. const UnicodeString PointTo, bool Symbolic)
  3493. {
  3494. assert(FFileSystem);
  3495. EnsureNonExistence(FileName);
  3496. if (SessionData->CacheDirectories)
  3497. {
  3498. DirectoryModified(CurrentDirectory, false);
  3499. }
  3500. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  3501. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  3502. DoCreateLink(FileName, PointTo, Symbolic);
  3503. ReactOnCommand(fsCreateDirectory);
  3504. }
  3505. //---------------------------------------------------------------------------
  3506. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  3507. const UnicodeString PointTo, bool Symbolic)
  3508. {
  3509. try
  3510. {
  3511. assert(FFileSystem);
  3512. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  3513. }
  3514. catch(Exception & E)
  3515. {
  3516. COMMAND_ERROR_ARI
  3517. (
  3518. FMTLOAD(CREATE_LINK_ERROR, (FileName)),
  3519. DoCreateLink(FileName, PointTo, Symbolic);
  3520. );
  3521. }
  3522. }
  3523. //---------------------------------------------------------------------------
  3524. void __fastcall TTerminal::HomeDirectory()
  3525. {
  3526. assert(FFileSystem);
  3527. try
  3528. {
  3529. LogEvent(L"Changing directory to home directory.");
  3530. FFileSystem->HomeDirectory();
  3531. ReactOnCommand(fsHomeDirectory);
  3532. }
  3533. catch (Exception &E)
  3534. {
  3535. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  3536. }
  3537. }
  3538. //---------------------------------------------------------------------------
  3539. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  3540. {
  3541. assert(FFileSystem);
  3542. try
  3543. {
  3544. UnicodeString CachedDirectory;
  3545. assert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  3546. // never use directory change cache during startup, this ensures, we never
  3547. // end-up initially in non-existing directory
  3548. if ((Status == ssOpened) &&
  3549. SessionData->CacheDirectoryChanges &&
  3550. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  3551. Directory, CachedDirectory))
  3552. {
  3553. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  3554. (Directory, CachedDirectory)));
  3555. FFileSystem->CachedChangeDirectory(CachedDirectory);
  3556. }
  3557. else
  3558. {
  3559. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  3560. FFileSystem->ChangeDirectory(Directory);
  3561. }
  3562. FLastDirectoryChange = Directory;
  3563. ReactOnCommand(fsChangeDirectory);
  3564. }
  3565. catch (Exception &E)
  3566. {
  3567. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  3568. }
  3569. }
  3570. //---------------------------------------------------------------------------
  3571. void __fastcall TTerminal::LookupUsersGroups()
  3572. {
  3573. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  3574. IsCapable[fcUserGroupListing])
  3575. {
  3576. assert(FFileSystem);
  3577. try
  3578. {
  3579. FUsersGroupsLookedup = true;
  3580. LogEvent(L"Looking up groups and users.");
  3581. FFileSystem->LookupUsersGroups();
  3582. ReactOnCommand(fsLookupUsersGroups);
  3583. if (Log->Logging)
  3584. {
  3585. FGroups.Log(this, L"groups");
  3586. FMembership.Log(this, L"membership");
  3587. FUsers.Log(this, L"users");
  3588. }
  3589. }
  3590. catch (Exception &E)
  3591. {
  3592. if (!Active || (SessionData->LookupUserGroups == asOn))
  3593. {
  3594. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  3595. }
  3596. }
  3597. }
  3598. }
  3599. //---------------------------------------------------------------------------
  3600. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  3601. {
  3602. return !Command.Trim().IsEmpty();
  3603. }
  3604. //---------------------------------------------------------------------------
  3605. bool __fastcall TTerminal::GetCommandSessionOpened()
  3606. {
  3607. // consider secondary terminal open in "ready" state only
  3608. // so we never do keepalives on it until it is completely initialized
  3609. return (FCommandSession != NULL) &&
  3610. (FCommandSession->Status == ssOpened);
  3611. }
  3612. //---------------------------------------------------------------------------
  3613. TTerminal * __fastcall TTerminal::GetCommandSession()
  3614. {
  3615. if ((FCommandSession != NULL) && !FCommandSession->Active)
  3616. {
  3617. SAFE_DESTROY(FCommandSession);
  3618. }
  3619. if (FCommandSession == NULL)
  3620. {
  3621. // transaction cannot be started yet to allow proper matching transaction
  3622. // levels between main and command session
  3623. assert(FInTransaction == 0);
  3624. try
  3625. {
  3626. FCommandSession = new TSecondaryTerminal(this, SessionData,
  3627. Configuration, L"Shell");
  3628. FCommandSession->AutoReadDirectory = false;
  3629. TSessionData * CommandSessionData = FCommandSession->FSessionData;
  3630. CommandSessionData->RemoteDirectory = CurrentDirectory;
  3631. CommandSessionData->FSProtocol = fsSCPonly;
  3632. CommandSessionData->ClearAliases = false;
  3633. CommandSessionData->UnsetNationalVars = false;
  3634. CommandSessionData->LookupUserGroups = asOff;
  3635. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  3636. FCommandSession->OnQueryUser = OnQueryUser;
  3637. FCommandSession->OnPromptUser = OnPromptUser;
  3638. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  3639. FCommandSession->OnProgress = OnProgress;
  3640. FCommandSession->OnFinished = OnFinished;
  3641. FCommandSession->OnInformation = OnInformation;
  3642. // do not copy OnDisplayBanner to avoid it being displayed
  3643. }
  3644. catch(...)
  3645. {
  3646. SAFE_DESTROY(FCommandSession);
  3647. throw;
  3648. }
  3649. }
  3650. return FCommandSession;
  3651. }
  3652. //---------------------------------------------------------------------------
  3653. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  3654. TCaptureOutputEvent OutputEvent)
  3655. {
  3656. class TOutputProxy
  3657. {
  3658. public:
  3659. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  3660. FAction(Action),
  3661. FOutputEvent(OutputEvent)
  3662. {
  3663. }
  3664. void __fastcall Output(const UnicodeString & Str, bool StdError)
  3665. {
  3666. FAction.AddOutput(Str, StdError);
  3667. if (FOutputEvent != NULL)
  3668. {
  3669. FOutputEvent(Str, StdError);
  3670. }
  3671. }
  3672. private:
  3673. TCallSessionAction & FAction;
  3674. TCaptureOutputEvent FOutputEvent;
  3675. };
  3676. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  3677. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  3678. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  3679. }
  3680. //---------------------------------------------------------------------------
  3681. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  3682. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  3683. {
  3684. assert(FFileSystem);
  3685. try
  3686. {
  3687. DirectoryModified(CurrentDirectory, false);
  3688. if (IsCapable[fcAnyCommand])
  3689. {
  3690. LogEvent(L"Executing user defined command.");
  3691. FFileSystem->AnyCommand(Command, OutputEvent);
  3692. }
  3693. else
  3694. {
  3695. assert(CommandSessionOpened);
  3696. assert(FCommandSession->FSProtocol == cfsSCP);
  3697. LogEvent(L"Executing user defined command on command session.");
  3698. FCommandSession->CurrentDirectory = CurrentDirectory;
  3699. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  3700. FCommandSession->FFileSystem->ReadCurrentDirectory();
  3701. // synchronize pwd (by purpose we lose transaction optimization here)
  3702. ChangeDirectory(FCommandSession->CurrentDirectory);
  3703. }
  3704. ReactOnCommand(fsAnyCommand);
  3705. }
  3706. catch (Exception &E)
  3707. {
  3708. if (Action != NULL)
  3709. {
  3710. RollbackAction(*Action, NULL, &E);
  3711. }
  3712. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  3713. else HandleExtendedException(&E);
  3714. }
  3715. }
  3716. //---------------------------------------------------------------------------
  3717. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  3718. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3719. bool NoConfirmation)
  3720. {
  3721. bool Result = true;
  3722. bool Done;
  3723. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  3724. do
  3725. {
  3726. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  3727. NULL, CREATE_ALWAYS, CreateAttr, 0);
  3728. Done = (*AHandle != INVALID_HANDLE_VALUE);
  3729. if (!Done)
  3730. {
  3731. // save the error, otherwise it gets overwritten by call to FileExists
  3732. int LastError = GetLastError();
  3733. int FileAttr;
  3734. if (::FileExists(ApiPath(FileName)) &&
  3735. (((FileAttr = FileGetAttr(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  3736. {
  3737. if (FLAGSET(FileAttr, faReadOnly))
  3738. {
  3739. if (OperationProgress->BatchOverwrite == boNone)
  3740. {
  3741. Result = false;
  3742. }
  3743. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  3744. {
  3745. unsigned int Answer;
  3746. {
  3747. TSuspendFileOperationProgress Suspend(OperationProgress);
  3748. Answer = QueryUser(
  3749. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  3750. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  3751. }
  3752. switch (Answer) {
  3753. case qaYesToAll: OperationProgress->BatchOverwrite = boAll; break;
  3754. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  3755. case qaNoToAll: OperationProgress->BatchOverwrite = boNone;
  3756. case qaNo: Result = false; break;
  3757. }
  3758. }
  3759. }
  3760. else
  3761. {
  3762. assert(FLAGSET(FileAttr, faHidden));
  3763. Result = true;
  3764. }
  3765. if (Result)
  3766. {
  3767. CreateAttr |=
  3768. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  3769. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  3770. FILE_OPERATION_LOOP_BEGIN
  3771. {
  3772. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  3773. {
  3774. RaiseLastOSError();
  3775. }
  3776. }
  3777. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  3778. }
  3779. else
  3780. {
  3781. Done = true;
  3782. }
  3783. }
  3784. else
  3785. {
  3786. RaiseLastOSError(LastError);
  3787. }
  3788. }
  3789. }
  3790. while (!Done);
  3791. return Result;
  3792. }
  3793. //---------------------------------------------------------------------------
  3794. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  3795. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3796. bool NoConfirmation)
  3797. {
  3798. assert(AHandle);
  3799. bool Result = true;
  3800. FILE_OPERATION_LOOP_BEGIN
  3801. {
  3802. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  3803. }
  3804. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  3805. return Result;
  3806. }
  3807. //---------------------------------------------------------------------------
  3808. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  3809. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  3810. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  3811. bool TryWriteReadOnly)
  3812. {
  3813. int Attrs = 0;
  3814. HANDLE Handle = 0;
  3815. FILE_OPERATION_LOOP_BEGIN
  3816. {
  3817. Attrs = FileGetAttr(ApiPath(FileName));
  3818. if (Attrs < 0) RaiseLastOSError();
  3819. }
  3820. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  3821. if ((Attrs & faDirectory) == 0)
  3822. {
  3823. bool NoHandle = false;
  3824. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  3825. ((Attrs & faReadOnly) != 0))
  3826. {
  3827. Access = GENERIC_READ;
  3828. NoHandle = true;
  3829. }
  3830. FILE_OPERATION_LOOP_BEGIN
  3831. {
  3832. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  3833. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  3834. NULL, OPEN_EXISTING, 0, 0);
  3835. if (Handle == INVALID_HANDLE_VALUE)
  3836. {
  3837. Handle = 0;
  3838. RaiseLastOSError();
  3839. }
  3840. }
  3841. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  3842. try
  3843. {
  3844. if (AATime || AMTime || ACTime)
  3845. {
  3846. FILETIME ATime;
  3847. FILETIME MTime;
  3848. FILETIME CTime;
  3849. // Get last file access and modification time
  3850. FILE_OPERATION_LOOP_BEGIN
  3851. {
  3852. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  3853. }
  3854. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3855. if (ACTime)
  3856. {
  3857. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  3858. }
  3859. if (AATime)
  3860. {
  3861. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  3862. }
  3863. if (AMTime)
  3864. {
  3865. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  3866. }
  3867. }
  3868. if (ASize)
  3869. {
  3870. // Get file size
  3871. FILE_OPERATION_LOOP_BEGIN
  3872. {
  3873. unsigned long LSize;
  3874. unsigned long HSize;
  3875. LSize = GetFileSize(Handle, &HSize);
  3876. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  3877. *ASize = (__int64(HSize) << 32) + LSize;
  3878. }
  3879. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3880. }
  3881. if ((AHandle == NULL) || NoHandle)
  3882. {
  3883. CloseHandle(Handle);
  3884. Handle = NULL;
  3885. }
  3886. }
  3887. catch(...)
  3888. {
  3889. CloseHandle(Handle);
  3890. throw;
  3891. }
  3892. }
  3893. if (AAttrs) *AAttrs = Attrs;
  3894. if (AHandle) *AHandle = Handle;
  3895. }
  3896. //---------------------------------------------------------------------------
  3897. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  3898. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  3899. {
  3900. bool Result = true;
  3901. // optimization
  3902. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  3903. {
  3904. WIN32_FIND_DATA FindData;
  3905. HANDLE Handle;
  3906. FILE_OPERATION_LOOP_BEGIN
  3907. {
  3908. Handle = FindFirstFile(ApiPath(ExcludeTrailingBackslash(FileName)).c_str(), &FindData);
  3909. if (Handle == INVALID_HANDLE_VALUE)
  3910. {
  3911. RaiseLastOSError();
  3912. }
  3913. }
  3914. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  3915. ::FindClose(Handle);
  3916. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  3917. TFileMasks::TParams Params;
  3918. // SearchRec.Size in C++B2010 is __int64,
  3919. // so we should be able to use it instead of FindData.nFileSize*
  3920. Params.Size =
  3921. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  3922. FindData.nFileSizeLow;
  3923. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  3924. if (!CopyParam->AllowTransfer(FileName, osLocal, Directory, Params))
  3925. {
  3926. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  3927. Result = false;
  3928. }
  3929. else if (CopyParam->SkipTransfer(FileName, Directory))
  3930. {
  3931. OperationProgress->AddSkippedFileSize(Params.Size);
  3932. Result = false;
  3933. }
  3934. if (Result)
  3935. {
  3936. LogFileDetails(FileName, Params.Modification, Params.Size);
  3937. }
  3938. }
  3939. return Result;
  3940. }
  3941. //---------------------------------------------------------------------------
  3942. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  3943. const TSearchRec Rec, void * Param)
  3944. {
  3945. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  3946. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  3947. if (Directory && Params.Recursive)
  3948. {
  3949. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  3950. }
  3951. if (!Directory || Params.IncludeDirs)
  3952. {
  3953. Params.FileList->Add(FileName);
  3954. }
  3955. }
  3956. //---------------------------------------------------------------------------
  3957. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  3958. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  3959. {
  3960. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  3961. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  3962. bool AllowTransfer = (AParams->CopyParam == NULL);
  3963. // SearchRec.Size in C++B2010 is __int64,
  3964. // so we should be able to use it instead of FindData.nFileSize*
  3965. __int64 Size =
  3966. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  3967. Rec.FindData.nFileSizeLow;
  3968. if (!AllowTransfer)
  3969. {
  3970. TFileMasks::TParams MaskParams;
  3971. MaskParams.Size = Size;
  3972. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  3973. AllowTransfer = AParams->CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams);
  3974. }
  3975. if (AllowTransfer)
  3976. {
  3977. if (!Dir)
  3978. {
  3979. AParams->Size += Size;
  3980. }
  3981. else
  3982. {
  3983. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  3984. }
  3985. }
  3986. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  3987. {
  3988. if (OperationProgress->Cancel != csContinue) Abort();
  3989. OperationProgress->SetFile(FileName);
  3990. }
  3991. }
  3992. //---------------------------------------------------------------------------
  3993. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  3994. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs)
  3995. {
  3996. bool Result = true;
  3997. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  3998. TOnceDoneOperation OnceDoneOperation = odoIdle;
  3999. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  4000. try
  4001. {
  4002. TCalculateSizeParams Params;
  4003. Params.Size = 0;
  4004. Params.Params = 0;
  4005. Params.CopyParam = CopyParam;
  4006. assert(!FOperationProgress);
  4007. FOperationProgress = &OperationProgress;
  4008. for (int Index = 0; Result && (Index < FileList->Count); Index++)
  4009. {
  4010. UnicodeString FileName = FileList->Strings[Index];
  4011. TSearchRec Rec;
  4012. if (FileSearchRec(FileName, Rec))
  4013. {
  4014. if (FLAGSET(Rec.Attr, faDirectory) && !AllowDirs)
  4015. {
  4016. Result = false;
  4017. }
  4018. else
  4019. {
  4020. CalculateLocalFileSize(FileName, Rec, &Params);
  4021. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  4022. }
  4023. }
  4024. }
  4025. Size = Params.Size;
  4026. }
  4027. __finally
  4028. {
  4029. FOperationProgress = NULL;
  4030. OperationProgress.Stop();
  4031. }
  4032. if (OnceDoneOperation != odoIdle)
  4033. {
  4034. CloseOnCompletion(OnceDoneOperation);
  4035. }
  4036. return Result;
  4037. }
  4038. //---------------------------------------------------------------------------
  4039. struct TSynchronizeFileData
  4040. {
  4041. bool Modified;
  4042. bool New;
  4043. bool IsDirectory;
  4044. TSynchronizeChecklist::TItem::TFileInfo Info;
  4045. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  4046. TRemoteFile * MatchingRemoteFileFile;
  4047. int MatchingRemoteFileImageIndex;
  4048. FILETIME LocalLastWriteTime;
  4049. };
  4050. //---------------------------------------------------------------------------
  4051. const int sfFirstLevel = 0x01;
  4052. struct TSynchronizeData
  4053. {
  4054. UnicodeString LocalDirectory;
  4055. UnicodeString RemoteDirectory;
  4056. TTerminal::TSynchronizeMode Mode;
  4057. int Params;
  4058. TSynchronizeDirectory OnSynchronizeDirectory;
  4059. TSynchronizeOptions * Options;
  4060. int Flags;
  4061. TStringList * LocalFileList;
  4062. const TCopyParamType * CopyParam;
  4063. TSynchronizeChecklist * Checklist;
  4064. };
  4065. //---------------------------------------------------------------------------
  4066. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  4067. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4068. const TCopyParamType * CopyParam, int Params,
  4069. TSynchronizeDirectory OnSynchronizeDirectory,
  4070. TSynchronizeOptions * Options)
  4071. {
  4072. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  4073. try
  4074. {
  4075. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  4076. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  4077. Checklist);
  4078. Checklist->Sort();
  4079. }
  4080. catch(...)
  4081. {
  4082. delete Checklist;
  4083. throw;
  4084. }
  4085. return Checklist;
  4086. }
  4087. //---------------------------------------------------------------------------
  4088. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  4089. {
  4090. if (FLAGSET(Params, Param))
  4091. {
  4092. AddToList(ParamsStr, Name, ", ");
  4093. }
  4094. Params &= ~Param;
  4095. }
  4096. //---------------------------------------------------------------------------
  4097. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  4098. {
  4099. UnicodeString ModeStr;
  4100. switch (Mode)
  4101. {
  4102. case smRemote:
  4103. ModeStr = L"Remote";
  4104. break;
  4105. case smLocal:
  4106. ModeStr = L"Local";
  4107. break;
  4108. case smBoth:
  4109. ModeStr = L"Both";
  4110. break;
  4111. default:
  4112. ModeStr = L"Unknown";
  4113. break;
  4114. }
  4115. return ModeStr;
  4116. }
  4117. //---------------------------------------------------------------------------
  4118. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  4119. {
  4120. UnicodeString ParamsStr;
  4121. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  4122. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  4123. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  4124. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  4125. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  4126. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  4127. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  4128. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  4129. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  4130. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  4131. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  4132. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  4133. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  4134. if (Params > 0)
  4135. {
  4136. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  4137. }
  4138. return ParamsStr;
  4139. }
  4140. //---------------------------------------------------------------------------
  4141. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  4142. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4143. const TCopyParamType * CopyParam, int Params,
  4144. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  4145. int Flags, TSynchronizeChecklist * Checklist)
  4146. {
  4147. TSynchronizeData Data;
  4148. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  4149. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  4150. Data.Mode = Mode;
  4151. Data.Params = Params;
  4152. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4153. Data.LocalFileList = NULL;
  4154. Data.CopyParam = CopyParam;
  4155. Data.Options = Options;
  4156. Data.Flags = Flags;
  4157. Data.Checklist = Checklist;
  4158. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  4159. "mode = %s, params = 0x%x (%s)", (LocalDirectory, RemoteDirectory,
  4160. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params))));
  4161. if (FLAGCLEAR(Params, spDelayProgress))
  4162. {
  4163. DoSynchronizeProgress(Data, true);
  4164. }
  4165. try
  4166. {
  4167. bool Found;
  4168. TSearchRecChecked SearchRec;
  4169. Data.LocalFileList = new TStringList();
  4170. Data.LocalFileList->Sorted = true;
  4171. Data.LocalFileList->CaseSensitive = false;
  4172. FILE_OPERATION_LOOP_BEGIN
  4173. {
  4174. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4175. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  4176. }
  4177. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4178. if (Found)
  4179. {
  4180. try
  4181. {
  4182. UnicodeString FileName;
  4183. while (Found)
  4184. {
  4185. FileName = SearchRec.Name;
  4186. // add dirs for recursive mode or when we are interested in newly
  4187. // added subdirs
  4188. // SearchRec.Size in C++B2010 is __int64,
  4189. // so we should be able to use it instead of FindData.nFileSize*
  4190. __int64 Size =
  4191. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  4192. SearchRec.FindData.nFileSizeLow;
  4193. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  4194. TFileMasks::TParams MaskParams;
  4195. MaskParams.Size = Size;
  4196. MaskParams.Modification = Modification;
  4197. UnicodeString RemoteFileName =
  4198. CopyParam->ChangeFileName(FileName, osLocal, false);
  4199. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  4200. if ((FileName != L".") && (FileName != L"..") &&
  4201. CopyParam->AllowTransfer(FullLocalFileName, osLocal,
  4202. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  4203. !FFileSystem->TemporaryTransferFile(FileName) &&
  4204. (FLAGCLEAR(Flags, sfFirstLevel) ||
  4205. (Options == NULL) ||
  4206. Options->MatchesFilter(FileName) ||
  4207. Options->MatchesFilter(RemoteFileName)))
  4208. {
  4209. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  4210. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  4211. FileData->Info.FileName = FileName;
  4212. FileData->Info.Directory = Data.LocalDirectory;
  4213. FileData->Info.Modification = Modification;
  4214. FileData->Info.ModificationFmt = mfFull;
  4215. FileData->Info.Size = Size;
  4216. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  4217. FileData->New = true;
  4218. FileData->Modified = false;
  4219. Data.LocalFileList->AddObject(FileName,
  4220. reinterpret_cast<TObject*>(FileData));
  4221. LogEvent(FORMAT(L"Local file %s included to synchronization",
  4222. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4223. }
  4224. else
  4225. {
  4226. LogEvent(FORMAT(L"Local file %s excluded from synchronization",
  4227. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4228. }
  4229. FILE_OPERATION_LOOP_BEGIN
  4230. {
  4231. Found = (FindNextChecked(SearchRec) == 0);
  4232. }
  4233. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4234. }
  4235. }
  4236. __finally
  4237. {
  4238. FindClose(SearchRec);
  4239. }
  4240. // can we expect that ProcessDirectory would take so little time
  4241. // that we can postpone showing progress window until anything actually happens?
  4242. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  4243. FDirectoryCache->HasFileList(RemoteDirectory);
  4244. if (!Cached && FLAGSET(Params, spDelayProgress))
  4245. {
  4246. DoSynchronizeProgress(Data, true);
  4247. }
  4248. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  4249. FLAGSET(Params, spUseCache));
  4250. TSynchronizeFileData * FileData;
  4251. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4252. {
  4253. FileData = reinterpret_cast<TSynchronizeFileData *>
  4254. (Data.LocalFileList->Objects[Index]);
  4255. // add local file either if we are going to upload it
  4256. // (i.e. if it is updated or we want to upload even new files)
  4257. // or if we are going to delete it (i.e. all "new"=obsolete files)
  4258. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  4259. bool New = (FileData->New &&
  4260. ((Mode == smLocal) ||
  4261. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  4262. if (New)
  4263. {
  4264. LogEvent(FORMAT(L"Local file %s is new",
  4265. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  4266. FileData->Info.Modification, FileData->Info.Size))));
  4267. }
  4268. if (Modified || New)
  4269. {
  4270. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4271. try
  4272. {
  4273. ChecklistItem->IsDirectory = FileData->IsDirectory;
  4274. ChecklistItem->Local = FileData->Info;
  4275. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  4276. if (Modified)
  4277. {
  4278. assert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  4279. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  4280. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  4281. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  4282. }
  4283. else
  4284. {
  4285. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  4286. }
  4287. if ((Mode == smBoth) || (Mode == smRemote))
  4288. {
  4289. ChecklistItem->Action =
  4290. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  4291. ChecklistItem->Checked =
  4292. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  4293. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4294. FLAGSET(Params, spSubDirs));
  4295. }
  4296. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  4297. {
  4298. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  4299. ChecklistItem->Checked =
  4300. FLAGSET(Params, spDelete) &&
  4301. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4302. FLAGSET(Params, spSubDirs));
  4303. }
  4304. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4305. {
  4306. Data.Checklist->Add(ChecklistItem);
  4307. ChecklistItem = NULL;
  4308. }
  4309. }
  4310. __finally
  4311. {
  4312. delete ChecklistItem;
  4313. }
  4314. }
  4315. else
  4316. {
  4317. if (FileData->Modified)
  4318. {
  4319. delete FileData->MatchingRemoteFileFile;
  4320. }
  4321. }
  4322. }
  4323. }
  4324. }
  4325. __finally
  4326. {
  4327. if (Data.LocalFileList != NULL)
  4328. {
  4329. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4330. {
  4331. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  4332. (Data.LocalFileList->Objects[Index]);
  4333. delete FileData;
  4334. }
  4335. delete Data.LocalFileList;
  4336. }
  4337. }
  4338. }
  4339. //---------------------------------------------------------------------------
  4340. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  4341. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4342. {
  4343. try
  4344. {
  4345. DoSynchronizeCollectFile(FileName, File, Param);
  4346. }
  4347. catch(EScpSkipFile & E)
  4348. {
  4349. TSuspendFileOperationProgress Suspend(OperationProgress);
  4350. if (!HandleException(&E))
  4351. {
  4352. throw;
  4353. }
  4354. }
  4355. }
  4356. //---------------------------------------------------------------------------
  4357. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  4358. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4359. {
  4360. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  4361. TFileMasks::TParams MaskParams;
  4362. MaskParams.Size = File->Size;
  4363. MaskParams.Modification = File->Modification;
  4364. UnicodeString LocalFileName =
  4365. Data->CopyParam->ChangeFileName(File->FileName, osRemote, false);
  4366. UnicodeString FullRemoteFileName =
  4367. UnixExcludeTrailingBackslash(File->FullFileName);
  4368. if (Data->CopyParam->AllowTransfer(
  4369. FullRemoteFileName, osRemote,
  4370. File->IsDirectory, MaskParams) &&
  4371. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  4372. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  4373. (Data->Options == NULL) ||
  4374. Data->Options->MatchesFilter(File->FileName) ||
  4375. Data->Options->MatchesFilter(LocalFileName)))
  4376. {
  4377. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4378. try
  4379. {
  4380. ChecklistItem->IsDirectory = File->IsDirectory;
  4381. ChecklistItem->ImageIndex = File->IconIndex;
  4382. ChecklistItem->Remote.FileName = File->FileName;
  4383. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  4384. ChecklistItem->Remote.Modification = File->Modification;
  4385. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  4386. ChecklistItem->Remote.Size = File->Size;
  4387. bool Modified = false;
  4388. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  4389. bool New = (LocalIndex < 0);
  4390. if (!New)
  4391. {
  4392. TSynchronizeFileData * LocalData =
  4393. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  4394. LocalData->New = false;
  4395. if (File->IsDirectory != LocalData->IsDirectory)
  4396. {
  4397. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  4398. (File->FileName)));
  4399. }
  4400. else if (!File->IsDirectory)
  4401. {
  4402. ChecklistItem->Local = LocalData->Info;
  4403. ChecklistItem->Local.Modification =
  4404. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  4405. bool LocalModified = false;
  4406. // for spTimestamp+spBySize require that the file sizes are the same
  4407. // before comparing file time
  4408. int TimeCompare;
  4409. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  4410. (FLAGCLEAR(Data->Params, spTimestamp) ||
  4411. FLAGCLEAR(Data->Params, spBySize) ||
  4412. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  4413. {
  4414. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  4415. ChecklistItem->Remote.Modification);
  4416. }
  4417. else
  4418. {
  4419. TimeCompare = 0;
  4420. }
  4421. if (TimeCompare < 0)
  4422. {
  4423. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4424. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  4425. {
  4426. Modified = true;
  4427. }
  4428. else
  4429. {
  4430. LocalModified = true;
  4431. }
  4432. }
  4433. else if (TimeCompare > 0)
  4434. {
  4435. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4436. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  4437. {
  4438. LocalModified = true;
  4439. }
  4440. else
  4441. {
  4442. Modified = true;
  4443. }
  4444. }
  4445. else if (FLAGSET(Data->Params, spBySize) &&
  4446. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  4447. FLAGCLEAR(Data->Params, spTimestamp))
  4448. {
  4449. Modified = true;
  4450. LocalModified = true;
  4451. }
  4452. if (LocalModified)
  4453. {
  4454. LocalData->Modified = true;
  4455. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  4456. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  4457. // we need this for custom commands over checklist only,
  4458. // not for sync itself
  4459. LocalData->MatchingRemoteFileFile = File->Duplicate();
  4460. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  4461. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4462. LocalData->Info.Modification, LocalData->Info.Size),
  4463. FormatFileDetailsForLog(FullRemoteFileName,
  4464. File->Modification, File->Size))));
  4465. }
  4466. if (Modified)
  4467. {
  4468. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  4469. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size),
  4470. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4471. LocalData->Info.Modification, LocalData->Info.Size))));
  4472. }
  4473. }
  4474. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  4475. {
  4476. DoSynchronizeCollectDirectory(
  4477. Data->LocalDirectory + LocalData->Info.FileName,
  4478. Data->RemoteDirectory + File->FileName,
  4479. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  4480. Data->Options, (Data->Flags & ~sfFirstLevel),
  4481. Data->Checklist);
  4482. }
  4483. }
  4484. else
  4485. {
  4486. ChecklistItem->Local.Directory = Data->LocalDirectory;
  4487. LogEvent(FORMAT(L"Remote file %s is new",
  4488. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4489. }
  4490. if (New || Modified)
  4491. {
  4492. assert(!New || !Modified);
  4493. // download the file if it changed or is new and we want to have it locally
  4494. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  4495. {
  4496. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  4497. {
  4498. ChecklistItem->Action =
  4499. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  4500. ChecklistItem->Checked =
  4501. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  4502. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4503. FLAGSET(Data->Params, spSubDirs));
  4504. }
  4505. }
  4506. else if ((Data->Mode == smRemote) && New)
  4507. {
  4508. if (FLAGCLEAR(Data->Params, spTimestamp))
  4509. {
  4510. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  4511. ChecklistItem->Checked =
  4512. FLAGSET(Data->Params, spDelete) &&
  4513. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4514. FLAGSET(Data->Params, spSubDirs));
  4515. }
  4516. }
  4517. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4518. {
  4519. ChecklistItem->RemoteFile = File->Duplicate();
  4520. Data->Checklist->Add(ChecklistItem);
  4521. ChecklistItem = NULL;
  4522. }
  4523. }
  4524. }
  4525. __finally
  4526. {
  4527. delete ChecklistItem;
  4528. }
  4529. }
  4530. else
  4531. {
  4532. LogEvent(FORMAT(L"Remote file %s excluded from synchronization",
  4533. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4534. }
  4535. }
  4536. //---------------------------------------------------------------------------
  4537. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  4538. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  4539. const TCopyParamType * CopyParam, int Params,
  4540. TSynchronizeDirectory OnSynchronizeDirectory)
  4541. {
  4542. TSynchronizeData Data;
  4543. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4544. int CopyParams =
  4545. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  4546. TCopyParamType SyncCopyParam = *CopyParam;
  4547. // when synchronizing by time, we force preserving time,
  4548. // otherwise it does not make any sense
  4549. if (FLAGCLEAR(Params, spNotByTime))
  4550. {
  4551. SyncCopyParam.PreserveTime = true;
  4552. }
  4553. TStringList * DownloadList = new TStringList();
  4554. TStringList * DeleteRemoteList = new TStringList();
  4555. TStringList * UploadList = new TStringList();
  4556. TStringList * DeleteLocalList = new TStringList();
  4557. BeginTransaction();
  4558. try
  4559. {
  4560. int IIndex = 0;
  4561. while (IIndex < Checklist->Count)
  4562. {
  4563. const TSynchronizeChecklist::TItem * ChecklistItem;
  4564. DownloadList->Clear();
  4565. DeleteRemoteList->Clear();
  4566. UploadList->Clear();
  4567. DeleteLocalList->Clear();
  4568. ChecklistItem = Checklist->Item[IIndex];
  4569. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  4570. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  4571. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  4572. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  4573. int(Params), SynchronizeParamsStr(Params))));
  4574. int Count = 0;
  4575. while ((IIndex < Checklist->Count) &&
  4576. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  4577. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  4578. {
  4579. ChecklistItem = Checklist->Item[IIndex];
  4580. if (ChecklistItem->Checked)
  4581. {
  4582. Count++;
  4583. if (FLAGSET(Params, spTimestamp))
  4584. {
  4585. switch (ChecklistItem->Action)
  4586. {
  4587. case TSynchronizeChecklist::saDownloadUpdate:
  4588. DownloadList->AddObject(
  4589. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4590. ChecklistItem->Remote.FileName,
  4591. (TObject *)(ChecklistItem));
  4592. break;
  4593. case TSynchronizeChecklist::saUploadUpdate:
  4594. UploadList->AddObject(
  4595. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4596. ChecklistItem->Local.FileName,
  4597. (TObject *)(ChecklistItem));
  4598. break;
  4599. default:
  4600. FAIL;
  4601. break;
  4602. }
  4603. }
  4604. else
  4605. {
  4606. switch (ChecklistItem->Action)
  4607. {
  4608. case TSynchronizeChecklist::saDownloadNew:
  4609. case TSynchronizeChecklist::saDownloadUpdate:
  4610. DownloadList->AddObject(
  4611. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4612. ChecklistItem->Remote.FileName,
  4613. ChecklistItem->RemoteFile);
  4614. break;
  4615. case TSynchronizeChecklist::saDeleteRemote:
  4616. DeleteRemoteList->AddObject(
  4617. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4618. ChecklistItem->Remote.FileName,
  4619. ChecklistItem->RemoteFile);
  4620. break;
  4621. case TSynchronizeChecklist::saUploadNew:
  4622. case TSynchronizeChecklist::saUploadUpdate:
  4623. UploadList->Add(
  4624. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4625. ChecklistItem->Local.FileName);
  4626. break;
  4627. case TSynchronizeChecklist::saDeleteLocal:
  4628. DeleteLocalList->Add(
  4629. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4630. ChecklistItem->Local.FileName);
  4631. break;
  4632. default:
  4633. FAIL;
  4634. break;
  4635. }
  4636. }
  4637. }
  4638. IIndex++;
  4639. }
  4640. // prevent showing/updating of progress dialog if there's nothing to do
  4641. if (Count > 0)
  4642. {
  4643. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  4644. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  4645. DoSynchronizeProgress(Data, false);
  4646. if (FLAGSET(Params, spTimestamp))
  4647. {
  4648. if (DownloadList->Count > 0)
  4649. {
  4650. ProcessFiles(DownloadList, foSetProperties,
  4651. SynchronizeLocalTimestamp, NULL, osLocal);
  4652. }
  4653. if (UploadList->Count > 0)
  4654. {
  4655. ProcessFiles(UploadList, foSetProperties,
  4656. SynchronizeRemoteTimestamp);
  4657. }
  4658. }
  4659. else
  4660. {
  4661. if ((DownloadList->Count > 0) &&
  4662. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  4663. {
  4664. Abort();
  4665. }
  4666. if ((DeleteRemoteList->Count > 0) &&
  4667. !DeleteFiles(DeleteRemoteList))
  4668. {
  4669. Abort();
  4670. }
  4671. if ((UploadList->Count > 0) &&
  4672. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  4673. {
  4674. Abort();
  4675. }
  4676. if ((DeleteLocalList->Count > 0) &&
  4677. !DeleteLocalFiles(DeleteLocalList))
  4678. {
  4679. Abort();
  4680. }
  4681. }
  4682. }
  4683. }
  4684. }
  4685. __finally
  4686. {
  4687. delete DownloadList;
  4688. delete DeleteRemoteList;
  4689. delete UploadList;
  4690. delete DeleteLocalList;
  4691. EndTransaction();
  4692. }
  4693. }
  4694. //---------------------------------------------------------------------------
  4695. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  4696. bool Collect)
  4697. {
  4698. if (Data.OnSynchronizeDirectory != NULL)
  4699. {
  4700. bool Continue = true;
  4701. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  4702. Continue, Collect);
  4703. if (!Continue)
  4704. {
  4705. Abort();
  4706. }
  4707. }
  4708. }
  4709. //---------------------------------------------------------------------------
  4710. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  4711. const TRemoteFile * File, void * /*Param*/)
  4712. {
  4713. const TSynchronizeChecklist::TItem * ChecklistItem =
  4714. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4715. UnicodeString LocalFile =
  4716. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4717. ChecklistItem->Local.FileName;
  4718. FILE_OPERATION_LOOP_BEGIN
  4719. {
  4720. HANDLE Handle;
  4721. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  4722. NULL, NULL, NULL, NULL);
  4723. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  4724. SessionData->DSTMode);
  4725. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  4726. int Error = GetLastError();
  4727. CloseHandle(Handle);
  4728. if (!Result)
  4729. {
  4730. RaiseLastOSError(Error);
  4731. }
  4732. }
  4733. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  4734. }
  4735. //---------------------------------------------------------------------------
  4736. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  4737. const TRemoteFile * File, void * /*Param*/)
  4738. {
  4739. const TSynchronizeChecklist::TItem * ChecklistItem =
  4740. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4741. TRemoteProperties Properties;
  4742. Properties.Valid << vpModification;
  4743. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  4744. SessionData->DSTMode);
  4745. ChangeFileProperties(
  4746. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  4747. NULL, &Properties);
  4748. }
  4749. //---------------------------------------------------------------------------
  4750. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  4751. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  4752. {
  4753. // see DoFilesFind
  4754. FOnFindingFile = NULL;
  4755. assert(Param);
  4756. assert(File);
  4757. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  4758. if (!AParams->Cancel)
  4759. {
  4760. if (FileName.IsEmpty())
  4761. {
  4762. FileName = File->FileName;
  4763. }
  4764. TFileMasks::TParams MaskParams;
  4765. MaskParams.Size = File->Size;
  4766. MaskParams.Modification = File->Modification;
  4767. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  4768. bool ImplicitMatch;
  4769. if (AParams->FileMask.Matches(FullFileName, false,
  4770. File->IsDirectory, &MaskParams, ImplicitMatch))
  4771. {
  4772. if (!ImplicitMatch)
  4773. {
  4774. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  4775. }
  4776. if (File->IsDirectory)
  4777. {
  4778. if (!AParams->LoopDetector.IsUnvisitedDirectory(File))
  4779. {
  4780. LogEvent(FORMAT(L"Already searched \"%s\" directory, link loop detected", (FullFileName)));
  4781. }
  4782. else
  4783. {
  4784. DoFilesFind(FullFileName, *AParams);
  4785. }
  4786. }
  4787. }
  4788. }
  4789. }
  4790. //---------------------------------------------------------------------------
  4791. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params)
  4792. {
  4793. Params.OnFindingFile(this, Directory, Params.Cancel);
  4794. if (!Params.Cancel)
  4795. {
  4796. assert(FOnFindingFile == NULL);
  4797. // ideally we should set the handler only around actually reading
  4798. // of the directory listing, so we at least reset the handler in
  4799. // FileFind
  4800. FOnFindingFile = Params.OnFindingFile;
  4801. try
  4802. {
  4803. ProcessDirectory(Directory, FileFind, &Params, false, true);
  4804. }
  4805. __finally
  4806. {
  4807. FOnFindingFile = NULL;
  4808. }
  4809. }
  4810. }
  4811. //---------------------------------------------------------------------------
  4812. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  4813. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  4814. {
  4815. TFilesFindParams Params;
  4816. Params.FileMask = FileMask;
  4817. Params.OnFileFound = OnFileFound;
  4818. Params.OnFindingFile = OnFindingFile;
  4819. Params.Cancel = false;
  4820. Params.LoopDetector.RecordVisitedDirectory(Directory);
  4821. DoFilesFind(Directory, Params);
  4822. }
  4823. //---------------------------------------------------------------------------
  4824. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  4825. TSpaceAvailable & ASpaceAvailable)
  4826. {
  4827. assert(IsCapable[fcCheckingSpaceAvailable]);
  4828. try
  4829. {
  4830. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  4831. }
  4832. catch (Exception &E)
  4833. {
  4834. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  4835. }
  4836. }
  4837. //---------------------------------------------------------------------------
  4838. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  4839. {
  4840. return FFileSystem->GetSessionInfo();
  4841. }
  4842. //---------------------------------------------------------------------------
  4843. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  4844. {
  4845. return FFileSystem->GetFileSystemInfo(Retrieve);
  4846. }
  4847. //---------------------------------------------------------------------
  4848. UnicodeString __fastcall TTerminal::GetPassword()
  4849. {
  4850. UnicodeString Result;
  4851. // FRememberedPassword is empty also when stored password was used
  4852. if (FRememberedPassword.IsEmpty())
  4853. {
  4854. Result = SessionData->Password;
  4855. }
  4856. else
  4857. {
  4858. Result = RememberedPassword;
  4859. }
  4860. return Result;
  4861. }
  4862. //---------------------------------------------------------------------
  4863. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  4864. {
  4865. return DecryptPassword(FRememberedPassword);
  4866. }
  4867. //---------------------------------------------------------------------
  4868. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  4869. {
  4870. return DecryptPassword(FRememberedTunnelPassword);
  4871. }
  4872. //---------------------------------------------------------------------
  4873. bool __fastcall TTerminal::GetStoredCredentialsTried()
  4874. {
  4875. bool Result;
  4876. if (FFileSystem != NULL)
  4877. {
  4878. Result = FFileSystem->GetStoredCredentialsTried();
  4879. }
  4880. else if (FSecureShell != NULL)
  4881. {
  4882. Result = FSecureShell->GetStoredCredentialsTried();
  4883. }
  4884. else
  4885. {
  4886. assert(FTunnelOpening);
  4887. Result = false;
  4888. }
  4889. return Result;
  4890. }
  4891. //---------------------------------------------------------------------------
  4892. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  4893. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  4894. {
  4895. assert(FFileSystem);
  4896. assert(FilesToCopy);
  4897. bool Result = false;
  4898. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4899. try
  4900. {
  4901. __int64 Size;
  4902. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  4903. bool CalculatedSize =
  4904. CalculateLocalFilesSize(
  4905. FilesToCopy, Size,
  4906. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  4907. CopyParam->CalculateSize);
  4908. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4909. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  4910. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  4911. FOperationProgress = &OperationProgress;
  4912. bool CollectingUsage = false;
  4913. try
  4914. {
  4915. if (CalculatedSize)
  4916. {
  4917. if (Configuration->Usage->Collect)
  4918. {
  4919. int CounterSize = TUsage::CalculateCounterSize(Size);
  4920. Configuration->Usage->Inc(L"Uploads");
  4921. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  4922. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  4923. CollectingUsage = true;
  4924. }
  4925. OperationProgress.SetTotalSize(Size);
  4926. }
  4927. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  4928. BeginTransaction();
  4929. try
  4930. {
  4931. if (Log->Logging)
  4932. {
  4933. LogEvent(FORMAT(L"Copying %d files/directories to remote directory "
  4934. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  4935. LogEvent(CopyParam->LogStr);
  4936. }
  4937. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  4938. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  4939. }
  4940. __finally
  4941. {
  4942. if (Active)
  4943. {
  4944. ReactOnCommand(fsCopyToRemote);
  4945. }
  4946. EndTransaction();
  4947. }
  4948. if (OperationProgress.Cancel == csContinue)
  4949. {
  4950. Result = true;
  4951. }
  4952. }
  4953. __finally
  4954. {
  4955. if (CollectingUsage)
  4956. {
  4957. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  4958. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  4959. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  4960. }
  4961. OperationProgress.Stop();
  4962. FOperationProgress = NULL;
  4963. }
  4964. }
  4965. catch (Exception &E)
  4966. {
  4967. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  4968. OnceDoneOperation = odoIdle;
  4969. }
  4970. if (OnceDoneOperation != odoIdle)
  4971. {
  4972. CloseOnCompletion(OnceDoneOperation);
  4973. }
  4974. return Result;
  4975. }
  4976. //---------------------------------------------------------------------------
  4977. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  4978. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  4979. {
  4980. assert(FFileSystem);
  4981. // see scp.c: sink(), tolocal()
  4982. bool Result = false;
  4983. bool OwnsFileList = (FilesToCopy == NULL);
  4984. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4985. try
  4986. {
  4987. if (OwnsFileList)
  4988. {
  4989. FilesToCopy = new TStringList();
  4990. FilesToCopy->Assign(Files->SelectedFiles);
  4991. }
  4992. BeginTransaction();
  4993. try
  4994. {
  4995. __int64 TotalSize;
  4996. bool TotalSizeKnown = false;
  4997. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4998. ExceptionOnFail = true;
  4999. try
  5000. {
  5001. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5002. if (CalculateFilesSize(
  5003. FilesToCopy, TotalSize, csIgnoreErrors,
  5004. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5005. CopyParam->CalculateSize, NULL))
  5006. {
  5007. TotalSizeKnown = true;
  5008. }
  5009. }
  5010. __finally
  5011. {
  5012. ExceptionOnFail = false;
  5013. }
  5014. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  5015. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5016. FOperationProgress = &OperationProgress;
  5017. bool CollectingUsage = false;
  5018. try
  5019. {
  5020. if (TotalSizeKnown)
  5021. {
  5022. if (Configuration->Usage->Collect)
  5023. {
  5024. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  5025. Configuration->Usage->Inc(L"Downloads");
  5026. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  5027. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  5028. CollectingUsage = true;
  5029. }
  5030. OperationProgress.SetTotalSize(TotalSize);
  5031. }
  5032. try
  5033. {
  5034. try
  5035. {
  5036. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  5037. &OperationProgress, OnceDoneOperation);
  5038. }
  5039. __finally
  5040. {
  5041. if (Active)
  5042. {
  5043. ReactOnCommand(fsCopyToLocal);
  5044. }
  5045. }
  5046. }
  5047. catch (Exception &E)
  5048. {
  5049. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  5050. OnceDoneOperation = odoIdle;
  5051. }
  5052. if (OperationProgress.Cancel == csContinue)
  5053. {
  5054. Result = true;
  5055. }
  5056. }
  5057. __finally
  5058. {
  5059. if (CollectingUsage)
  5060. {
  5061. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5062. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  5063. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  5064. }
  5065. FOperationProgress = NULL;
  5066. OperationProgress.Stop();
  5067. }
  5068. }
  5069. __finally
  5070. {
  5071. // If session is still active (no fatal error) we reload directory
  5072. // by calling EndTransaction
  5073. EndTransaction();
  5074. }
  5075. }
  5076. __finally
  5077. {
  5078. if (OwnsFileList) delete FilesToCopy;
  5079. }
  5080. if (OnceDoneOperation != odoIdle)
  5081. {
  5082. CloseOnCompletion(OnceDoneOperation);
  5083. }
  5084. return Result;
  5085. }
  5086. //---------------------------------------------------------------------------
  5087. void __fastcall TTerminal::ReflectSettings()
  5088. {
  5089. assert(FLog != NULL);
  5090. FLog->ReflectSettings();
  5091. assert(FActionLog != NULL);
  5092. FActionLog->ReflectSettings();
  5093. // also FTunnelLog ?
  5094. }
  5095. //---------------------------------------------------------------------------
  5096. void __fastcall TTerminal::CollectUsage()
  5097. {
  5098. switch (SessionData->FSProtocol)
  5099. {
  5100. case fsSCPonly:
  5101. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  5102. break;
  5103. case fsSFTP:
  5104. case fsSFTPonly:
  5105. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  5106. break;
  5107. case fsFTP:
  5108. if (SessionData->Ftps == ftpsNone)
  5109. {
  5110. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  5111. }
  5112. else
  5113. {
  5114. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  5115. }
  5116. break;
  5117. case fsWebDAV:
  5118. if (SessionData->Ftps == ftpsNone)
  5119. {
  5120. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  5121. }
  5122. else
  5123. {
  5124. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  5125. }
  5126. break;
  5127. }
  5128. if (Configuration->Logging && Configuration->LogToFile)
  5129. {
  5130. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  5131. }
  5132. if (Configuration->LogActions)
  5133. {
  5134. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  5135. }
  5136. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5137. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  5138. {
  5139. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  5140. }
  5141. if (SessionData->ProxyMethod != ::pmNone)
  5142. {
  5143. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  5144. }
  5145. if (SessionData->FtpProxyLogonType > 0)
  5146. {
  5147. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  5148. }
  5149. FCollectFileSystemUsage = true;
  5150. }
  5151. //---------------------------------------------------------------------------
  5152. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  5153. {
  5154. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  5155. }
  5156. //---------------------------------------------------------------------------
  5157. bool __fastcall TTerminal::VerifyCertificate(
  5158. const UnicodeString & CertificateStorageKey, const UnicodeString & Fingerprint,
  5159. const UnicodeString & CertificateSubject, int Failures)
  5160. {
  5161. bool Result = false;
  5162. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5163. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(false));
  5164. Storage->AccessMode = smRead;
  5165. if (Storage->OpenSubKey(CertificateStorageKey, false))
  5166. {
  5167. if (Storage->ValueExists(SessionData->SiteKey))
  5168. {
  5169. UnicodeString CachedCertificateData = Storage->ReadString(SessionData->SiteKey, L"");
  5170. if (CertificateData == CachedCertificateData)
  5171. {
  5172. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  5173. Result = true;
  5174. }
  5175. }
  5176. else if (Storage->ValueExists(Fingerprint))
  5177. {
  5178. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  5179. Result = true;
  5180. }
  5181. }
  5182. if (!Result)
  5183. {
  5184. UnicodeString Buf = SessionData->HostKey;
  5185. while (!Result && !Buf.IsEmpty())
  5186. {
  5187. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  5188. if (ExpectedKey == L"*")
  5189. {
  5190. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  5191. Information(Message, true);
  5192. Log->Add(llException, Message);
  5193. Result = true;
  5194. }
  5195. else if (ExpectedKey == Fingerprint)
  5196. {
  5197. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  5198. Result = true;
  5199. }
  5200. }
  5201. }
  5202. return Result;
  5203. }
  5204. //---------------------------------------------------------------------------
  5205. void __fastcall TTerminal::CacheCertificate(const UnicodeString & CertificateStorageKey,
  5206. const UnicodeString & Fingerprint, int Failures)
  5207. {
  5208. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5209. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(false));
  5210. Storage->AccessMode = smReadWrite;
  5211. if (Storage->OpenSubKey(CertificateStorageKey, true))
  5212. {
  5213. Storage->WriteString(SessionData->SiteKey, CertificateData);
  5214. }
  5215. }
  5216. //---------------------------------------------------------------------------
  5217. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  5218. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  5219. TTerminal(ASessionData, Configuration),
  5220. FMainTerminal(MainTerminal)
  5221. {
  5222. Log->Parent = FMainTerminal->Log;
  5223. Log->Name = Name;
  5224. ActionLog->Enabled = false;
  5225. SessionData->NonPersistant();
  5226. assert(FMainTerminal != NULL);
  5227. if (!FMainTerminal->UserName.IsEmpty())
  5228. {
  5229. SessionData->UserName = FMainTerminal->UserName;
  5230. }
  5231. }
  5232. //---------------------------------------------------------------------------
  5233. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  5234. {
  5235. FMainTerminal->DirectoryLoaded(FileList);
  5236. assert(FileList != NULL);
  5237. }
  5238. //---------------------------------------------------------------------------
  5239. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  5240. bool SubDirs)
  5241. {
  5242. // clear cache of main terminal
  5243. FMainTerminal->DirectoryModified(Path, SubDirs);
  5244. }
  5245. //---------------------------------------------------------------------------
  5246. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  5247. {
  5248. return FMainTerminal;
  5249. }
  5250. //---------------------------------------------------------------------------
  5251. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  5252. TObjectList()
  5253. {
  5254. assert(AConfiguration);
  5255. FConfiguration = AConfiguration;
  5256. }
  5257. //---------------------------------------------------------------------------
  5258. __fastcall TTerminalList::~TTerminalList()
  5259. {
  5260. assert(Count == 0);
  5261. }
  5262. //---------------------------------------------------------------------------
  5263. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  5264. {
  5265. return new TTerminal(Data, FConfiguration);
  5266. }
  5267. //---------------------------------------------------------------------------
  5268. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  5269. {
  5270. TTerminal * Terminal = CreateTerminal(Data);
  5271. Add(Terminal);
  5272. return Terminal;
  5273. }
  5274. //---------------------------------------------------------------------------
  5275. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  5276. {
  5277. assert(IndexOf(Terminal) >= 0);
  5278. Remove(Terminal);
  5279. }
  5280. //---------------------------------------------------------------------------
  5281. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  5282. {
  5283. TTerminal * T = Terminal;
  5284. Terminal = NULL;
  5285. FreeTerminal(T);
  5286. }
  5287. //---------------------------------------------------------------------------
  5288. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  5289. {
  5290. return dynamic_cast<TTerminal *>(Items[Index]);
  5291. }
  5292. //---------------------------------------------------------------------------
  5293. void __fastcall TTerminalList::Idle()
  5294. {
  5295. TTerminal * Terminal;
  5296. for (int i = 0; i < Count; i++)
  5297. {
  5298. Terminal = Terminals[i];
  5299. if (Terminal->Status == ssOpened)
  5300. {
  5301. Terminal->Idle();
  5302. }
  5303. }
  5304. }
  5305. //---------------------------------------------------------------------------
  5306. void __fastcall TTerminalList::RecryptPasswords()
  5307. {
  5308. for (int Index = 0; Index < Count; Index++)
  5309. {
  5310. Terminals[Index]->RecryptPasswords();
  5311. }
  5312. }