1
0

SessionData.cpp 160 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SessionData.h"
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "FileBuffer.h"
  8. #include "CoreMain.h"
  9. #include "TextsCore.h"
  10. #include "PuttyIntf.h"
  11. #include "RemoteFiles.h"
  12. #include "SFTPFileSystem.h"
  13. #include "S3FileSystem.h"
  14. #include <Soap.EncdDecd.hpp>
  15. #include <StrUtils.hpp>
  16. #include <XMLDoc.hpp>
  17. #include <StrUtils.hpp>
  18. #include <algorithm>
  19. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. const wchar_t * PingTypeNames = L"Off;Null;Dummy";
  23. const wchar_t * ProxyMethodNames = L"None;SOCKS4;SOCKS5;HTTP;Telnet;Cmd";
  24. const wchar_t * DefaultName = L"Default Settings";
  25. const UnicodeString CipherNames[CIPHER_COUNT] = {L"WARN", L"3des", L"blowfish", L"aes", L"des", L"arcfour", L"chacha20"};
  26. const UnicodeString KexNames[KEX_COUNT] = {L"WARN", L"dh-group1-sha1", L"dh-group14-sha1", L"dh-gex-sha1", L"rsa", L"ecdh"};
  27. const UnicodeString HostKeyNames[HOSTKEY_COUNT] = {L"WARN", L"rsa", L"dsa", L"ecdsa", L"ed25519"};
  28. const UnicodeString GssLibNames[GSSLIB_COUNT] = {L"gssapi32", L"sspi", L"custom"};
  29. const wchar_t SshProtList[][10] = {L"1", L"1>2", L"2>1", L"2"};
  30. const TCipher DefaultCipherList[CIPHER_COUNT] =
  31. { cipAES, cipChaCha20, cipBlowfish, cip3DES, cipWarn, cipArcfour, cipDES };
  32. const TKex DefaultKexList[KEX_COUNT] =
  33. { kexECDH, kexDHGEx, kexDHGroup14, kexRSA, kexWarn, kexDHGroup1 };
  34. const THostKey DefaultHostKeyList[HOSTKEY_COUNT] =
  35. { hkED25519, hkECDSA, hkRSA, hkDSA, hkWarn };
  36. const TGssLib DefaultGssLibList[GSSLIB_COUNT] =
  37. { gssGssApi32, gssSspi, gssCustom };
  38. const wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16] = { L"SCP", L"SFTP (SCP)", L"SFTP", L"", L"", L"FTP", L"WebDAV", L"S3" };
  39. const int SshPortNumber = 22;
  40. const int FtpPortNumber = 21;
  41. const int FtpsImplicitPortNumber = 990;
  42. const int HTTPPortNumber = 80;
  43. const int HTTPSPortNumber = 443;
  44. const int TelnetPortNumber = 23;
  45. const int DefaultSendBuf = 262144;
  46. const int ProxyPortNumber = 80;
  47. const UnicodeString AnonymousUserName(L"anonymous");
  48. const UnicodeString AnonymousPassword(L"[email protected]");
  49. const UnicodeString PuttySshProtocol(L"ssh");
  50. const UnicodeString PuttyTelnetProtocol(L"telnet");
  51. const UnicodeString SftpProtocol(L"sftp");
  52. const UnicodeString ScpProtocol(L"scp");
  53. const UnicodeString FtpProtocol(L"ftp");
  54. const UnicodeString FtpsProtocol(L"ftps");
  55. const UnicodeString FtpesProtocol(L"ftpes");
  56. const UnicodeString WebDAVProtocol(L"dav");
  57. const UnicodeString WebDAVSProtocol(L"davs");
  58. const UnicodeString S3Protocol(L"s3");
  59. const UnicodeString SshProtocol(L"ssh");
  60. const UnicodeString WinSCPProtocolPrefix(L"winscp-");
  61. const wchar_t UrlParamSeparator = L';';
  62. const wchar_t UrlParamValueSeparator = L'=';
  63. const UnicodeString UrlHostKeyParamName(L"fingerprint");
  64. const UnicodeString UrlSaveParamName(L"save");
  65. const UnicodeString PassphraseOption(L"passphrase");
  66. const UnicodeString RawSettingsOption(L"rawsettings");
  67. const UnicodeString S3HostName(S3LibDefaultHostName());
  68. //---------------------------------------------------------------------
  69. TDateTime __fastcall SecToDateTime(int Sec)
  70. {
  71. return TDateTime(double(Sec) / SecsPerDay);
  72. }
  73. //--- TSessionData ----------------------------------------------------
  74. __fastcall TSessionData::TSessionData(UnicodeString aName):
  75. TNamedObject(aName)
  76. {
  77. Default();
  78. FModified = true;
  79. }
  80. //---------------------------------------------------------------------
  81. _fastcall TSessionData::~TSessionData()
  82. {
  83. }
  84. //---------------------------------------------------------------------
  85. int __fastcall TSessionData::Compare(TNamedObject * Other)
  86. {
  87. int Result;
  88. // To avoid using CompareLogicalText on hex names of sessions in workspace.
  89. // The session 000A would be sorted before 0001.
  90. if (IsWorkspace && DebugNotNull(dynamic_cast<TSessionData *>(Other))->IsWorkspace)
  91. {
  92. Result = CompareText(Name, Other->Name);
  93. }
  94. else
  95. {
  96. Result = TNamedObject::Compare(Other);
  97. }
  98. return Result;
  99. }
  100. //---------------------------------------------------------------------
  101. TSessionData * __fastcall TSessionData::Clone()
  102. {
  103. std::unique_ptr<TSessionData> Data(new TSessionData(L""));
  104. Data->Assign(this);
  105. return Data.release();
  106. }
  107. //---------------------------------------------------------------------
  108. void __fastcall TSessionData::Default()
  109. {
  110. HostName = L"";
  111. PortNumber = SshPortNumber;
  112. UserName = L"";
  113. Password = L"";
  114. NewPassword = L"";
  115. ChangePassword = false;
  116. PingInterval = 30;
  117. PingType = ptOff;
  118. Timeout = 15;
  119. TryAgent = true;
  120. AgentFwd = false;
  121. AuthTIS = false;
  122. AuthKI = true;
  123. AuthKIPassword = true;
  124. AuthGSSAPI = true;
  125. GSSAPIFwdTGT = false;
  126. LogicalHostName = L"";
  127. ChangeUsername = false;
  128. Compression = false;
  129. SshProt = ssh2only;
  130. Ssh2DES = false;
  131. SshNoUserAuth = false;
  132. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  133. {
  134. Cipher[Index] = DefaultCipherList[Index];
  135. }
  136. for (int Index = 0; Index < KEX_COUNT; Index++)
  137. {
  138. Kex[Index] = DefaultKexList[Index];
  139. }
  140. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  141. {
  142. HostKeys[Index] = DefaultHostKeyList[Index];
  143. }
  144. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  145. {
  146. GssLib[Index] = DefaultGssLibList[Index];
  147. }
  148. GssLibCustom = L"";
  149. PublicKeyFile = L"";
  150. Passphrase = L"";
  151. FPuttyProtocol = L"";
  152. TcpNoDelay = false;
  153. SendBuf = DefaultSendBuf;
  154. SshSimple = true;
  155. HostKey = L"";
  156. FingerprintScan = false;
  157. FOverrideCachedHostKey = true;
  158. Note = L"";
  159. WinTitle = L"";
  160. InternalEditorEncoding = -1;
  161. ProxyMethod = ::pmNone;
  162. ProxyHost = L"proxy";
  163. ProxyPort = ProxyPortNumber;
  164. ProxyUsername = L"";
  165. ProxyPassword = L"";
  166. ProxyTelnetCommand = L"connect %host %port\\n";
  167. ProxyLocalCommand = L"";
  168. ProxyDNS = asAuto;
  169. ProxyLocalhost = false;
  170. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++)
  171. {
  172. Bug[(TSshBug)Index] = asAuto;
  173. }
  174. Special = false;
  175. FSProtocol = fsSFTP;
  176. AddressFamily = afAuto;
  177. RekeyData = L"1G";
  178. RekeyTime = MinsPerHour;
  179. // FS common
  180. LocalDirectory = L"";
  181. RemoteDirectory = L"";
  182. SynchronizeBrowsing = false;
  183. UpdateDirectories = true;
  184. CacheDirectories = true;
  185. CacheDirectoryChanges = true;
  186. PreserveDirectoryChanges = true;
  187. LockInHome = false;
  188. ResolveSymlinks = true;
  189. FollowDirectorySymlinks = false;
  190. DSTMode = dstmUnix;
  191. DeleteToRecycleBin = false;
  192. OverwrittenToRecycleBin = false;
  193. RecycleBinPath = L"";
  194. Color = 0;
  195. PostLoginCommands = L"";
  196. // SCP
  197. ReturnVar = L"";
  198. LookupUserGroups = asAuto;
  199. EOLType = eolLF;
  200. TrimVMSVersions = false;
  201. Shell = L""; //default shell
  202. ReturnVar = L"";
  203. ClearAliases = true;
  204. UnsetNationalVars = true;
  205. ListingCommand = L"ls -la";
  206. IgnoreLsWarnings = true;
  207. Scp1Compatibility = false;
  208. TimeDifference = 0;
  209. TimeDifferenceAuto = true;
  210. SCPLsFullTime = asAuto;
  211. NotUtf = asAuto;
  212. S3DefaultRegion = S3LibDefaultRegion();
  213. // SFTP
  214. SftpServer = L"";
  215. SFTPDownloadQueue = 32;
  216. SFTPUploadQueue = 32;
  217. SFTPListingQueue = 2;
  218. SFTPMaxVersion = ::SFTPMaxVersion;
  219. SFTPMaxPacketSize = 0;
  220. for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++)
  221. {
  222. SFTPBug[(TSftpBug)Index] = asAuto;
  223. }
  224. Tunnel = false;
  225. TunnelHostName = L"";
  226. TunnelPortNumber = SshPortNumber;
  227. TunnelUserName = L"";
  228. TunnelPassword = L"";
  229. TunnelPublicKeyFile = L"";
  230. TunnelLocalPortNumber = 0;
  231. TunnelPortFwd = L"";
  232. TunnelHostKey = L"";
  233. // FTP
  234. FtpPasvMode = true;
  235. FtpForcePasvIp = asAuto;
  236. FtpUseMlsd = asAuto;
  237. FtpAccount = L"";
  238. FtpPingInterval = 30;
  239. FtpPingType = ptDummyCommand;
  240. FtpTransferActiveImmediately = asAuto;
  241. Ftps = ftpsNone;
  242. MinTlsVersion = tls10;
  243. MaxTlsVersion = tls12;
  244. FtpListAll = asAuto;
  245. FtpHost = asAuto;
  246. FtpDeleteFromCwd = asAuto;
  247. SslSessionReuse = true;
  248. TlsCertificateFile = L"";
  249. FtpProxyLogonType = 0; // none
  250. CustomParam1 = L"";
  251. CustomParam2 = L"";
  252. IsWorkspace = false;
  253. Link = L"";
  254. Selected = false;
  255. FModified = false;
  256. FSource = ::ssNone;
  257. FSaveOnly = false;
  258. // add also to TSessionLog::AddStartupInfo()
  259. }
  260. //---------------------------------------------------------------------
  261. void __fastcall TSessionData::NonPersistant()
  262. {
  263. UpdateDirectories = false;
  264. PreserveDirectoryChanges = false;
  265. }
  266. //---------------------------------------------------------------------
  267. #define BASE_PROPERTIES \
  268. PROPERTY(HostName); \
  269. PROPERTY(PortNumber); \
  270. PROPERTY(UserName); \
  271. PROPERTY(Password); \
  272. PROPERTY(PublicKeyFile); \
  273. PROPERTY(Passphrase); \
  274. PROPERTY(FSProtocol); \
  275. PROPERTY(Ftps); \
  276. PROPERTY(LocalDirectory); \
  277. PROPERTY(RemoteDirectory); \
  278. PROPERTY(Color); \
  279. PROPERTY(SynchronizeBrowsing); \
  280. PROPERTY(Note);
  281. //---------------------------------------------------------------------
  282. #define ADVANCED_PROPERTIES \
  283. PROPERTY(NewPassword); \
  284. PROPERTY(ChangePassword); \
  285. PROPERTY(PingInterval); \
  286. PROPERTY(PingType); \
  287. PROPERTY(Timeout); \
  288. PROPERTY(TryAgent); \
  289. PROPERTY(AgentFwd); \
  290. PROPERTY(AuthTIS); \
  291. PROPERTY(LogicalHostName); \
  292. PROPERTY(ChangeUsername); \
  293. PROPERTY(Compression); \
  294. PROPERTY(SshProt); \
  295. PROPERTY(Ssh2DES); \
  296. PROPERTY(SshNoUserAuth); \
  297. PROPERTY(CipherList); \
  298. PROPERTY(KexList); \
  299. PROPERTY(HostKeyList); \
  300. PROPERTY(GssLibList); \
  301. PROPERTY(GssLibCustom); \
  302. PROPERTY(AddressFamily); \
  303. PROPERTY(RekeyData); \
  304. PROPERTY(RekeyTime); \
  305. PROPERTY(HostKey); \
  306. PROPERTY(FingerprintScan); \
  307. PROPERTY(InternalEditorEncoding); \
  308. \
  309. PROPERTY(UpdateDirectories); \
  310. PROPERTY(CacheDirectories); \
  311. PROPERTY(CacheDirectoryChanges); \
  312. PROPERTY(PreserveDirectoryChanges); \
  313. \
  314. PROPERTY(ResolveSymlinks); \
  315. PROPERTY(FollowDirectorySymlinks); \
  316. PROPERTY(DSTMode); \
  317. PROPERTY(LockInHome); \
  318. PROPERTY(Special); \
  319. PROPERTY(Selected); \
  320. PROPERTY(ReturnVar); \
  321. PROPERTY(LookupUserGroups); \
  322. PROPERTY(EOLType); \
  323. PROPERTY(TrimVMSVersions); \
  324. PROPERTY(Shell); \
  325. PROPERTY(ClearAliases); \
  326. PROPERTY(Scp1Compatibility); \
  327. PROPERTY(UnsetNationalVars); \
  328. PROPERTY(ListingCommand); \
  329. PROPERTY(IgnoreLsWarnings); \
  330. PROPERTY(SCPLsFullTime); \
  331. \
  332. PROPERTY(TimeDifference); \
  333. PROPERTY(TimeDifferenceAuto); \
  334. PROPERTY(TcpNoDelay); \
  335. PROPERTY(SendBuf); \
  336. PROPERTY(SshSimple); \
  337. PROPERTY(AuthKI); \
  338. PROPERTY(AuthKIPassword); \
  339. PROPERTY(AuthGSSAPI); \
  340. PROPERTY(GSSAPIFwdTGT); \
  341. PROPERTY(DeleteToRecycleBin); \
  342. PROPERTY(OverwrittenToRecycleBin); \
  343. PROPERTY(RecycleBinPath); \
  344. PROPERTY(NotUtf); \
  345. PROPERTY(PostLoginCommands); \
  346. \
  347. PROPERTY(S3DefaultRegion); \
  348. \
  349. PROPERTY(ProxyMethod); \
  350. PROPERTY(ProxyHost); \
  351. PROPERTY(ProxyPort); \
  352. PROPERTY(ProxyUsername); \
  353. PROPERTY(ProxyPassword); \
  354. PROPERTY(ProxyTelnetCommand); \
  355. PROPERTY(ProxyLocalCommand); \
  356. PROPERTY(ProxyDNS); \
  357. PROPERTY(ProxyLocalhost); \
  358. \
  359. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++) \
  360. { \
  361. PROPERTY(Bug[(TSshBug)Index]); \
  362. } \
  363. \
  364. PROPERTY(SftpServer); \
  365. PROPERTY(SFTPDownloadQueue); \
  366. PROPERTY(SFTPUploadQueue); \
  367. PROPERTY(SFTPListingQueue); \
  368. PROPERTY(SFTPMaxVersion); \
  369. PROPERTY(SFTPMaxPacketSize); \
  370. \
  371. for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++) \
  372. { \
  373. PROPERTY(SFTPBug[(TSftpBug)Index]); \
  374. } \
  375. \
  376. PROPERTY(Tunnel); \
  377. PROPERTY(TunnelHostName); \
  378. PROPERTY(TunnelPortNumber); \
  379. PROPERTY(TunnelUserName); \
  380. PROPERTY(TunnelPassword); \
  381. PROPERTY(TunnelPublicKeyFile); \
  382. PROPERTY(TunnelLocalPortNumber); \
  383. PROPERTY(TunnelPortFwd); \
  384. PROPERTY(TunnelHostKey); \
  385. \
  386. PROPERTY(FtpPasvMode); \
  387. PROPERTY(FtpForcePasvIp); \
  388. PROPERTY(FtpUseMlsd); \
  389. PROPERTY(FtpAccount); \
  390. PROPERTY(FtpPingInterval); \
  391. PROPERTY(FtpPingType); \
  392. PROPERTY(FtpTransferActiveImmediately); \
  393. PROPERTY(FtpListAll); \
  394. PROPERTY(FtpHost); \
  395. PROPERTY(FtpDeleteFromCwd); \
  396. PROPERTY(SslSessionReuse); \
  397. PROPERTY(TlsCertificateFile); \
  398. \
  399. PROPERTY(FtpProxyLogonType); \
  400. \
  401. PROPERTY(MinTlsVersion); \
  402. PROPERTY(MaxTlsVersion); \
  403. \
  404. PROPERTY(WinTitle); \
  405. PROPERTY(CustomParam1); \
  406. PROPERTY(CustomParam2);
  407. #define META_PROPERTIES \
  408. PROPERTY(IsWorkspace); \
  409. PROPERTY(Link);
  410. //---------------------------------------------------------------------
  411. void __fastcall TSessionData::Assign(TPersistent * Source)
  412. {
  413. if (Source && Source->InheritsFrom(__classid(TSessionData)))
  414. {
  415. TSessionData * SourceData = (TSessionData *)Source;
  416. CopyData(SourceData);
  417. FSource = SourceData->FSource;
  418. }
  419. else
  420. {
  421. TNamedObject::Assign(Source);
  422. }
  423. }
  424. //---------------------------------------------------------------------
  425. void __fastcall TSessionData::CopyData(TSessionData * SourceData)
  426. {
  427. #define PROPERTY(P) P = SourceData->P
  428. PROPERTY(Name);
  429. BASE_PROPERTIES;
  430. ADVANCED_PROPERTIES;
  431. META_PROPERTIES;
  432. #undef PROPERTY
  433. FOverrideCachedHostKey = SourceData->FOverrideCachedHostKey;
  434. FModified = SourceData->Modified;
  435. FSaveOnly = SourceData->FSaveOnly;
  436. }
  437. //---------------------------------------------------------------------
  438. void __fastcall TSessionData::CopyDirectoriesStateData(TSessionData * SourceData)
  439. {
  440. RemoteDirectory = SourceData->RemoteDirectory;
  441. LocalDirectory = SourceData->LocalDirectory;
  442. SynchronizeBrowsing = SourceData->SynchronizeBrowsing;
  443. }
  444. //---------------------------------------------------------------------
  445. bool __fastcall TSessionData::HasStateData()
  446. {
  447. return
  448. !RemoteDirectory.IsEmpty() ||
  449. !LocalDirectory.IsEmpty() ||
  450. (Color != 0);
  451. }
  452. //---------------------------------------------------------------------
  453. void __fastcall TSessionData::CopyStateData(TSessionData * SourceData)
  454. {
  455. // Keep in sync with TCustomScpExplorerForm::UpdateSessionData.
  456. CopyDirectoriesStateData(SourceData);
  457. Color = SourceData->Color;
  458. }
  459. //---------------------------------------------------------------------
  460. void __fastcall TSessionData::CopyNonCoreData(TSessionData * SourceData)
  461. {
  462. CopyStateData(SourceData);
  463. UpdateDirectories = SourceData->UpdateDirectories;
  464. Note = SourceData->Note;
  465. }
  466. //---------------------------------------------------------------------
  467. bool __fastcall TSessionData::IsSame(const TSessionData * Default, bool AdvancedOnly, TStrings * DifferentProperties)
  468. {
  469. bool Result = true;
  470. #define PROPERTY(P) \
  471. if (P != Default->P) \
  472. { \
  473. if (DifferentProperties != NULL) \
  474. { \
  475. DifferentProperties->Add(#P); \
  476. } \
  477. Result = false; \
  478. }
  479. if (!AdvancedOnly)
  480. {
  481. BASE_PROPERTIES;
  482. META_PROPERTIES;
  483. }
  484. ADVANCED_PROPERTIES;
  485. #undef PROPERTY
  486. return Result;
  487. }
  488. //---------------------------------------------------------------------
  489. bool __fastcall TSessionData::IsSame(const TSessionData * Default, bool AdvancedOnly)
  490. {
  491. return IsSame(Default, AdvancedOnly, NULL);
  492. }
  493. //---------------------------------------------------------------------
  494. static TFSProtocol NormalizeFSProtocol(TFSProtocol FSProtocol)
  495. {
  496. if ((FSProtocol == fsSCPonly) || (FSProtocol == fsSFTPonly))
  497. {
  498. FSProtocol = fsSFTP;
  499. }
  500. return FSProtocol;
  501. }
  502. //---------------------------------------------------------------------
  503. bool __fastcall TSessionData::IsSameSite(const TSessionData * Other)
  504. {
  505. return
  506. // Particularly when handling /refresh,
  507. // fsSFTPonly sites when compared against sftp:// URLs (fsSFTP) have to match.
  508. // But similarly also falled back SCP sites.
  509. (NormalizeFSProtocol(FSProtocol) == NormalizeFSProtocol(Other->FSProtocol)) &&
  510. (HostName == Other->HostName) &&
  511. (PortNumber == Other->PortNumber) &&
  512. (UserName == Other->UserName);
  513. }
  514. //---------------------------------------------------------------------
  515. bool __fastcall TSessionData::IsInFolderOrWorkspace(UnicodeString AFolder)
  516. {
  517. return StartsText(UnixIncludeTrailingBackslash(AFolder), Name);
  518. }
  519. //---------------------------------------------------------------------
  520. void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyImport, bool & RewritePassword)
  521. {
  522. // Make sure we only ever use methods supported by TOptionsStorage
  523. // (implemented by TOptionsIniFile)
  524. PortNumber = Storage->ReadInteger(L"PortNumber", PortNumber);
  525. UserName = Storage->ReadString(L"UserName", UserName);
  526. // must be loaded after UserName, because HostName may be in format user@host
  527. HostName = Storage->ReadString(L"HostName", HostName);
  528. if (!Configuration->DisablePasswordStoring)
  529. {
  530. if (Storage->ValueExists(L"PasswordPlain"))
  531. {
  532. Password = Storage->ReadString(L"PasswordPlain", Password);
  533. RewritePassword = true;
  534. }
  535. else
  536. {
  537. FPassword = Storage->ReadStringAsBinaryData(L"Password", FPassword);
  538. }
  539. }
  540. HostKey = Storage->ReadString(L"SshHostKey", HostKey); // probably never used
  541. Note = Storage->ReadString(L"Note", Note);
  542. // Putty uses PingIntervalSecs
  543. int PingIntervalSecs = Storage->ReadInteger(L"PingIntervalSecs", -1);
  544. if (PingIntervalSecs < 0)
  545. {
  546. PingIntervalSecs = Storage->ReadInteger(L"PingIntervalSec", PingInterval%SecsPerMin);
  547. }
  548. PingInterval =
  549. Storage->ReadInteger(L"PingInterval", PingInterval/SecsPerMin)*SecsPerMin +
  550. PingIntervalSecs;
  551. if (PingInterval == 0)
  552. {
  553. PingInterval = 30;
  554. }
  555. PingType = static_cast<TPingType>(Storage->ReadInteger(L"PingType", PingType));
  556. Timeout = Storage->ReadInteger(L"Timeout", Timeout);
  557. TryAgent = Storage->ReadBool(L"TryAgent", TryAgent);
  558. AgentFwd = Storage->ReadBool(L"AgentFwd", AgentFwd);
  559. AuthTIS = Storage->ReadBool(L"AuthTIS", AuthTIS);
  560. AuthKI = Storage->ReadBool(L"AuthKI", AuthKI);
  561. AuthKIPassword = Storage->ReadBool(L"AuthKIPassword", AuthKIPassword);
  562. // Continue to use setting keys of previous kerberos implementation (vaclav tomec),
  563. // but fallback to keys of other implementations (official putty and vintela quest putty),
  564. // to allow imports from all putty versions.
  565. // Both vaclav tomec and official putty use AuthGSSAPI
  566. AuthGSSAPI = Storage->ReadBool(L"AuthGSSAPI", Storage->ReadBool(L"AuthSSPI", AuthGSSAPI));
  567. GSSAPIFwdTGT = Storage->ReadBool(L"GSSAPIFwdTGT", Storage->ReadBool(L"GssapiFwd", Storage->ReadBool(L"SSPIFwdTGT", GSSAPIFwdTGT)));
  568. // KerbPrincipal was used by Quest PuTTY
  569. // GSSAPIServerRealm was used by Vaclav Tomec
  570. LogicalHostName = Storage->ReadString(L"LogicalHostName", Storage->ReadString(L"GSSAPIServerRealm", Storage->ReadString(L"KerbPrincipal", LogicalHostName)));
  571. ChangeUsername = Storage->ReadBool(L"ChangeUsername", ChangeUsername);
  572. Compression = Storage->ReadBool(L"Compression", Compression);
  573. TSshProt ASshProt = (TSshProt)Storage->ReadInteger(L"SshProt", SshProt);
  574. // Old sessions may contain the values correponding to the fallbacks we used to allow; migrate them
  575. if (ASshProt == ssh2deprecated)
  576. {
  577. ASshProt = ssh2only;
  578. }
  579. else if (ASshProt == ssh1deprecated)
  580. {
  581. ASshProt = ssh1only;
  582. }
  583. SshProt = ASshProt;
  584. Ssh2DES = Storage->ReadBool(L"Ssh2DES", Ssh2DES);
  585. SshNoUserAuth = Storage->ReadBool(L"SshNoUserAuth", SshNoUserAuth);
  586. CipherList = Storage->ReadString(L"Cipher", CipherList);
  587. KexList = Storage->ReadString(L"KEX", KexList);
  588. HostKeyList = Storage->ReadString(L"HostKey", HostKeyList);
  589. GssLibList = Storage->ReadString(L"GSSLibs", GssLibList);
  590. GssLibCustom = Storage->ReadString(L"GSSCustom", GssLibCustom);
  591. PublicKeyFile = Storage->ReadString(L"PublicKeyFile", PublicKeyFile);
  592. AddressFamily = static_cast<TAddressFamily>
  593. (Storage->ReadInteger(L"AddressFamily", AddressFamily));
  594. RekeyData = Storage->ReadString(L"RekeyBytes", RekeyData);
  595. RekeyTime = Storage->ReadInteger(L"RekeyTime", RekeyTime);
  596. FSProtocol = (TFSProtocol)Storage->ReadInteger(L"FSProtocol", FSProtocol);
  597. LocalDirectory = Storage->ReadString(L"LocalDirectory", LocalDirectory);
  598. RemoteDirectory = Storage->ReadString(L"RemoteDirectory", RemoteDirectory);
  599. SynchronizeBrowsing = Storage->ReadBool(L"SynchronizeBrowsing", SynchronizeBrowsing);
  600. UpdateDirectories = Storage->ReadBool(L"UpdateDirectories", UpdateDirectories);
  601. CacheDirectories = Storage->ReadBool(L"CacheDirectories", CacheDirectories);
  602. CacheDirectoryChanges = Storage->ReadBool(L"CacheDirectoryChanges", CacheDirectoryChanges);
  603. PreserveDirectoryChanges = Storage->ReadBool(L"PreserveDirectoryChanges", PreserveDirectoryChanges);
  604. ResolveSymlinks = Storage->ReadBool(L"ResolveSymlinks", ResolveSymlinks);
  605. FollowDirectorySymlinks = Storage->ReadBool(L"FollowDirectorySymlinks", FollowDirectorySymlinks);
  606. DSTMode = (TDSTMode)Storage->ReadInteger(L"ConsiderDST", DSTMode);
  607. LockInHome = Storage->ReadBool(L"LockInHome", LockInHome);
  608. Special = Storage->ReadBool(L"Special", Special);
  609. Shell = Storage->ReadString(L"Shell", Shell);
  610. ClearAliases = Storage->ReadBool(L"ClearAliases", ClearAliases);
  611. UnsetNationalVars = Storage->ReadBool(L"UnsetNationalVars", UnsetNationalVars);
  612. ListingCommand = Storage->ReadString(L"ListingCommand",
  613. Storage->ReadBool(L"AliasGroupList", false) ? UnicodeString(L"ls -gla") : ListingCommand);
  614. IgnoreLsWarnings = Storage->ReadBool(L"IgnoreLsWarnings", IgnoreLsWarnings);
  615. SCPLsFullTime = TAutoSwitch(Storage->ReadInteger(L"SCPLsFullTime", SCPLsFullTime));
  616. Scp1Compatibility = Storage->ReadBool(L"Scp1Compatibility", Scp1Compatibility);
  617. TimeDifference = Storage->ReadFloat(L"TimeDifference", TimeDifference);
  618. TimeDifferenceAuto = Storage->ReadBool(L"TimeDifferenceAuto", (TimeDifference == TDateTime()));
  619. DeleteToRecycleBin = Storage->ReadBool(L"DeleteToRecycleBin", DeleteToRecycleBin);
  620. OverwrittenToRecycleBin = Storage->ReadBool(L"OverwrittenToRecycleBin", OverwrittenToRecycleBin);
  621. RecycleBinPath = Storage->ReadString(L"RecycleBinPath", RecycleBinPath);
  622. PostLoginCommands = Storage->ReadString(L"PostLoginCommands", PostLoginCommands);
  623. ReturnVar = Storage->ReadString(L"ReturnVar", ReturnVar);
  624. LookupUserGroups = TAutoSwitch(Storage->ReadInteger(L"LookupUserGroups2", LookupUserGroups));
  625. EOLType = (TEOLType)Storage->ReadInteger(L"EOLType", EOLType);
  626. TrimVMSVersions = Storage->ReadBool(L"TrimVMSVersions", TrimVMSVersions);
  627. NotUtf = TAutoSwitch(Storage->ReadInteger(L"Utf", Storage->ReadInteger(L"SFTPUtfBug", NotUtf)));
  628. InternalEditorEncoding = Storage->ReadInteger(L"InternalEditorEncoding", InternalEditorEncoding);
  629. S3DefaultRegion = Storage->ReadString(L"S3DefaultRegion", S3DefaultRegion);
  630. // PuTTY defaults to TcpNoDelay, but the psftp/pscp ignores this preference, and always set this to off (what is our default too)
  631. if (!PuttyImport)
  632. {
  633. TcpNoDelay = Storage->ReadBool(L"TcpNoDelay", TcpNoDelay);
  634. }
  635. SendBuf = Storage->ReadInteger(L"SendBuf", Storage->ReadInteger("SshSendBuf", SendBuf));
  636. SshSimple = Storage->ReadBool(L"SshSimple", SshSimple);
  637. ProxyMethod = (TProxyMethod)Storage->ReadInteger(L"ProxyMethod", ProxyMethod);
  638. ProxyHost = Storage->ReadString(L"ProxyHost", ProxyHost);
  639. ProxyPort = Storage->ReadInteger(L"ProxyPort", ProxyPort);
  640. ProxyUsername = Storage->ReadString(L"ProxyUsername", ProxyUsername);
  641. if (Storage->ValueExists(L"ProxyPassword"))
  642. {
  643. // encrypt unencrypted password
  644. ProxyPassword = Storage->ReadString(L"ProxyPassword", L"");
  645. }
  646. else
  647. {
  648. // load encrypted password
  649. FProxyPassword = Storage->ReadStringAsBinaryData(L"ProxyPasswordEnc", FProxyPassword);
  650. }
  651. if (ProxyMethod == pmCmd)
  652. {
  653. ProxyLocalCommand = Storage->ReadStringRaw(L"ProxyTelnetCommand", ProxyLocalCommand);
  654. }
  655. else
  656. {
  657. ProxyTelnetCommand = Storage->ReadStringRaw(L"ProxyTelnetCommand", ProxyTelnetCommand);
  658. }
  659. ProxyDNS = TAutoSwitch((Storage->ReadInteger(L"ProxyDNS", (ProxyDNS + 2) % 3) + 1) % 3);
  660. ProxyLocalhost = Storage->ReadBool(L"ProxyLocalhost", ProxyLocalhost);
  661. #define READ_BUG(BUG) \
  662. Bug[sb##BUG] = TAutoSwitch(2 - Storage->ReadInteger(L"Bug"#BUG, \
  663. 2 - Bug[sb##BUG]));
  664. READ_BUG(Ignore1);
  665. READ_BUG(PlainPW1);
  666. READ_BUG(RSA1);
  667. READ_BUG(HMAC2);
  668. READ_BUG(DeriveKey2);
  669. READ_BUG(RSAPad2);
  670. READ_BUG(PKSessID2);
  671. READ_BUG(Rekey2);
  672. READ_BUG(MaxPkt2);
  673. READ_BUG(Ignore2);
  674. READ_BUG(OldGex2);
  675. READ_BUG(WinAdj);
  676. READ_BUG(ChanReq);
  677. #undef READ_BUG
  678. if ((Bug[sbHMAC2] == asAuto) &&
  679. Storage->ReadBool(L"BuggyMAC", false))
  680. {
  681. Bug[sbHMAC2] = asOn;
  682. }
  683. SftpServer = Storage->ReadString(L"SftpServer", SftpServer);
  684. #define READ_SFTP_BUG(BUG) \
  685. SFTPBug[sb##BUG] = TAutoSwitch(Storage->ReadInteger(L"SFTP" #BUG "Bug", SFTPBug[sb##BUG]));
  686. READ_SFTP_BUG(Symlink);
  687. READ_SFTP_BUG(SignedTS);
  688. #undef READ_SFTP_BUG
  689. SFTPMaxVersion = Storage->ReadInteger(L"SFTPMaxVersion", SFTPMaxVersion);
  690. SFTPMaxPacketSize = Storage->ReadInteger(L"SFTPMaxPacketSize", SFTPMaxPacketSize);
  691. SFTPDownloadQueue = Storage->ReadInteger(L"SFTPDownloadQueue", SFTPDownloadQueue);
  692. SFTPUploadQueue = Storage->ReadInteger(L"SFTPUploadQueue", SFTPUploadQueue);
  693. SFTPListingQueue = Storage->ReadInteger(L"SFTPListingQueue", SFTPListingQueue);
  694. Color = Storage->ReadInteger(L"Color", Color);
  695. PuttyProtocol = Storage->ReadString(L"Protocol", PuttyProtocol);
  696. Tunnel = Storage->ReadBool(L"Tunnel", Tunnel);
  697. TunnelPortNumber = Storage->ReadInteger(L"TunnelPortNumber", TunnelPortNumber);
  698. TunnelUserName = Storage->ReadString(L"TunnelUserName", TunnelUserName);
  699. // must be loaded after TunnelUserName,
  700. // because TunnelHostName may be in format user@host
  701. TunnelHostName = Storage->ReadString(L"TunnelHostName", TunnelHostName);
  702. if (!Configuration->DisablePasswordStoring)
  703. {
  704. if (Storage->ValueExists(L"TunnelPasswordPlain"))
  705. {
  706. TunnelPassword = Storage->ReadString(L"TunnelPasswordPlain", TunnelPassword);
  707. RewritePassword = true;
  708. }
  709. else
  710. {
  711. FTunnelPassword = Storage->ReadStringAsBinaryData(L"TunnelPassword", FTunnelPassword);
  712. }
  713. }
  714. TunnelPublicKeyFile = Storage->ReadString(L"TunnelPublicKeyFile", TunnelPublicKeyFile);
  715. TunnelLocalPortNumber = Storage->ReadInteger(L"TunnelLocalPortNumber", TunnelLocalPortNumber);
  716. TunnelHostKey = Storage->ReadString(L"TunnelHostKey", TunnelHostKey);
  717. // Ftp prefix
  718. FtpPasvMode = Storage->ReadBool(L"FtpPasvMode", FtpPasvMode);
  719. FtpForcePasvIp = TAutoSwitch(Storage->ReadInteger(L"FtpForcePasvIp2", FtpForcePasvIp));
  720. FtpUseMlsd = TAutoSwitch(Storage->ReadInteger(L"FtpUseMlsd", FtpUseMlsd));
  721. FtpAccount = Storage->ReadString(L"FtpAccount", FtpAccount);
  722. FtpPingInterval = Storage->ReadInteger(L"FtpPingInterval", FtpPingInterval);
  723. FtpPingType = static_cast<TPingType>(Storage->ReadInteger(L"FtpPingType", FtpPingType));
  724. FtpTransferActiveImmediately = static_cast<TAutoSwitch>(Storage->ReadInteger(L"FtpTransferActiveImmediately2", FtpTransferActiveImmediately));
  725. Ftps = static_cast<TFtps>(Storage->ReadInteger(L"Ftps", Ftps));
  726. FtpListAll = TAutoSwitch(Storage->ReadInteger(L"FtpListAll", FtpListAll));
  727. FtpHost = TAutoSwitch(Storage->ReadInteger(L"FtpHost", FtpHost));
  728. FtpDeleteFromCwd = TAutoSwitch(Storage->ReadInteger(L"FtpDeleteFromCwd", FtpDeleteFromCwd));
  729. SslSessionReuse = Storage->ReadBool(L"SslSessionReuse", SslSessionReuse);
  730. TlsCertificateFile = Storage->ReadString(L"TlsCertificateFile", TlsCertificateFile);
  731. FtpProxyLogonType = Storage->ReadInteger(L"FtpProxyLogonType", FtpProxyLogonType);
  732. MinTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L"MinTlsVersion", MinTlsVersion));
  733. MaxTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L"MaxTlsVersion", MaxTlsVersion));
  734. IsWorkspace = Storage->ReadBool(L"IsWorkspace", IsWorkspace);
  735. Link = Storage->ReadString(L"Link", Link);
  736. CustomParam1 = Storage->ReadString(L"CustomParam1", CustomParam1);
  737. CustomParam2 = Storage->ReadString(L"CustomParam2", CustomParam2);
  738. #ifdef TEST
  739. #define KEX_TEST(VALUE, EXPECTED) KexList = VALUE; DebugAssert(KexList == EXPECTED);
  740. #define KEX_DEFAULT L"ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1"
  741. // Empty source should result in default list
  742. KEX_TEST(L"", KEX_DEFAULT);
  743. // Default of pre 5.8.1
  744. KEX_TEST(L"dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN", L"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN");
  745. // Missing first two priority algos, and last non-priority algo
  746. KEX_TEST(L"dh-group14-sha1,dh-group1-sha1,WARN", L"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN");
  747. // Missing first two priority algos, last non-priority algo and WARN
  748. KEX_TEST(L"dh-group14-sha1,dh-group1-sha1", L"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN");
  749. // Old algos, with all but the first below WARN
  750. KEX_TEST(L"dh-gex-sha1,WARN,dh-group14-sha1,dh-group1-sha1,rsa", L"ecdh,dh-gex-sha1,WARN,dh-group14-sha1,dh-group1-sha1,rsa");
  751. // Unknown algo at front
  752. KEX_TEST(L"unknown,ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1", KEX_DEFAULT);
  753. // Unknown algo at back
  754. KEX_TEST(L"ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1,unknown", KEX_DEFAULT);
  755. // Unknown algo in the middle
  756. KEX_TEST(L"ecdh,dh-gex-sha1,dh-group14-sha1,unknown,rsa,WARN,dh-group1-sha1", KEX_DEFAULT);
  757. #undef KEX_DEFAULT
  758. #undef KEX_TEST
  759. #define CIPHER_TEST(VALUE, EXPECTED) CipherList = VALUE; DebugAssert(CipherList == EXPECTED);
  760. #define CIPHER_DEFAULT L"aes,chacha20,blowfish,3des,WARN,arcfour,des"
  761. // Empty source should result in default list
  762. CIPHER_TEST(L"", CIPHER_DEFAULT);
  763. // Default of pre 5.8.1
  764. CIPHER_TEST(L"aes,blowfish,3des,WARN,arcfour,des", L"aes,blowfish,3des,chacha20,WARN,arcfour,des");
  765. // Missing priority algo
  766. CIPHER_TEST(L"chacha20,blowfish,3des,WARN,arcfour,des", CIPHER_DEFAULT);
  767. // Missing non-priority algo
  768. CIPHER_TEST(L"aes,chacha20,3des,WARN,arcfour,des", L"aes,chacha20,3des,blowfish,WARN,arcfour,des");
  769. // Missing last warn algo
  770. CIPHER_TEST(L"aes,blowfish,chacha20,3des,WARN,arcfour", L"aes,blowfish,chacha20,3des,WARN,arcfour,des");
  771. // Missing first warn algo
  772. CIPHER_TEST(L"aes,blowfish,chacha20,3des,WARN,des", L"aes,blowfish,chacha20,3des,WARN,des,arcfour");
  773. #undef CIPHER_DEFAULT
  774. #undef CIPHER_TEST
  775. #define HOSTKEY_TEST(VALUE, EXPECTED) HostKeyList = VALUE; DebugAssert(HostKeyList == EXPECTED);
  776. #define HOSTKEY_DEFAULT L"ed25519,ecdsa,rsa,dsa,WARN"
  777. // Empty source should result in default list
  778. HOSTKEY_TEST(L"", HOSTKEY_DEFAULT);
  779. // Missing priority algo
  780. HOSTKEY_TEST(L"ecdsa,rsa,dsa,WARN", HOSTKEY_DEFAULT);
  781. // Missing non-priority algo
  782. HOSTKEY_TEST(L"ed25519,ecdsa,dsa,WARN", L"ed25519,ecdsa,dsa,rsa,WARN");
  783. #undef HOSTKEY_DEFAULT
  784. #undef HOSTKEY_TEST
  785. #endif
  786. }
  787. //---------------------------------------------------------------------
  788. void __fastcall TSessionData::Load(THierarchicalStorage * Storage, bool PuttyImport)
  789. {
  790. bool RewritePassword = false;
  791. if (Storage->OpenSubKey(InternalStorageKey, False))
  792. {
  793. // In case we are re-loading, reset passwords, to avoid pointless
  794. // re-cryption, while loading username/hostname. And moreover, when
  795. // the password is wrongly encrypted (using a different master password),
  796. // this breaks sites reload and consequently an overal operation,
  797. // such as opening Sites menu
  798. ClearSessionPasswords();
  799. FProxyPassword = L"";
  800. DoLoad(Storage, PuttyImport, RewritePassword);
  801. Storage->CloseSubKey();
  802. }
  803. if (RewritePassword)
  804. {
  805. TStorageAccessMode AccessMode = Storage->AccessMode;
  806. Storage->AccessMode = smReadWrite;
  807. try
  808. {
  809. if (Storage->OpenSubKey(InternalStorageKey, true))
  810. {
  811. Storage->DeleteValue(L"PasswordPlain");
  812. if (!Password.IsEmpty())
  813. {
  814. Storage->WriteBinaryDataAsString(L"Password", FPassword);
  815. }
  816. Storage->DeleteValue(L"TunnelPasswordPlain");
  817. if (!TunnelPassword.IsEmpty())
  818. {
  819. Storage->WriteBinaryDataAsString(L"TunnelPassword", FTunnelPassword);
  820. }
  821. Storage->CloseSubKey();
  822. }
  823. }
  824. catch(...)
  825. {
  826. // ignore errors (like read-only INI file)
  827. }
  828. Storage->AccessMode = AccessMode;
  829. }
  830. FModified = false;
  831. FSource = ssStored;
  832. }
  833. //---------------------------------------------------------------------
  834. void __fastcall TSessionData::DoSave(THierarchicalStorage * Storage,
  835. bool PuttyExport, const TSessionData * Default, bool DoNotEncryptPasswords)
  836. {
  837. #define WRITE_DATA_EX(TYPE, NAME, PROPERTY, CONV) \
  838. if ((Default != NULL) && (CONV(Default->PROPERTY) == CONV(PROPERTY))) \
  839. { \
  840. Storage->DeleteValue(NAME); \
  841. } \
  842. else \
  843. { \
  844. Storage->Write ## TYPE(NAME, CONV(PROPERTY)); \
  845. }
  846. #define WRITE_DATA_CONV(TYPE, NAME, PROPERTY) WRITE_DATA_EX(TYPE, NAME, PROPERTY, WRITE_DATA_CONV_FUNC)
  847. #define WRITE_DATA(TYPE, PROPERTY) WRITE_DATA_EX(TYPE, TEXT(#PROPERTY), PROPERTY, )
  848. WRITE_DATA(String, HostName);
  849. WRITE_DATA(Integer, PortNumber);
  850. WRITE_DATA_EX(Integer, L"PingInterval", PingInterval / SecsPerMin, );
  851. WRITE_DATA_EX(Integer, L"PingIntervalSecs", PingInterval % SecsPerMin, );
  852. Storage->DeleteValue(L"PingIntervalSec"); // obsolete
  853. WRITE_DATA(Integer, PingType);
  854. WRITE_DATA(Integer, Timeout);
  855. WRITE_DATA(Bool, TryAgent);
  856. WRITE_DATA(Bool, AgentFwd);
  857. WRITE_DATA(Bool, AuthTIS);
  858. WRITE_DATA(Bool, AuthKI);
  859. WRITE_DATA(Bool, AuthKIPassword);
  860. WRITE_DATA(String, Note);
  861. WRITE_DATA(Bool, AuthGSSAPI);
  862. WRITE_DATA(Bool, GSSAPIFwdTGT);
  863. Storage->DeleteValue(L"TryGSSKEX");
  864. Storage->DeleteValue(L"UserNameFromEnvironment");
  865. Storage->DeleteValue("GSSAPIServerChoosesUserName");
  866. Storage->DeleteValue(L"GSSAPITrustDNS");
  867. WRITE_DATA(String, LogicalHostName);
  868. if (PuttyExport)
  869. {
  870. // duplicate kerberos setting with keys of the vintela quest putty
  871. WRITE_DATA_EX(Bool, L"AuthSSPI", AuthGSSAPI, );
  872. WRITE_DATA_EX(Bool, L"SSPIFwdTGT", GSSAPIFwdTGT, );
  873. WRITE_DATA_EX(String, L"KerbPrincipal", LogicalHostName, );
  874. // duplicate kerberos setting with keys of the official putty
  875. WRITE_DATA_EX(Bool, L"GssapiFwd", GSSAPIFwdTGT, );
  876. }
  877. WRITE_DATA(Bool, ChangeUsername);
  878. WRITE_DATA(Bool, Compression);
  879. WRITE_DATA(Integer, SshProt);
  880. WRITE_DATA(Bool, Ssh2DES);
  881. WRITE_DATA(Bool, SshNoUserAuth);
  882. WRITE_DATA_EX(String, L"Cipher", CipherList, );
  883. WRITE_DATA_EX(String, L"KEX", KexList, );
  884. WRITE_DATA_EX(String, L"HostKey", HostKeyList, );
  885. WRITE_DATA_EX(String, L"GSSLibs", GssLibList, );
  886. WRITE_DATA_EX(String, L"GSSCustom", GssLibCustom, );
  887. WRITE_DATA(Integer, AddressFamily);
  888. WRITE_DATA_EX(String, L"RekeyBytes", RekeyData, );
  889. WRITE_DATA(Integer, RekeyTime);
  890. WRITE_DATA(Bool, TcpNoDelay);
  891. if (PuttyExport)
  892. {
  893. WRITE_DATA(StringRaw, UserName);
  894. // PuTTY is started in its binary directory to allow relative paths when opening PuTTY's own stored session.
  895. // To allow relative paths in our sessions, we have to expand them for PuTTY.
  896. WRITE_DATA_EX(StringRaw, L"PublicKeyFile", PublicKeyFile, ExpandFileName);
  897. }
  898. else
  899. {
  900. WRITE_DATA(String, UserName);
  901. WRITE_DATA(String, PublicKeyFile);
  902. WRITE_DATA(Integer, FSProtocol);
  903. WRITE_DATA(String, LocalDirectory);
  904. WRITE_DATA(String, RemoteDirectory);
  905. WRITE_DATA(Bool, SynchronizeBrowsing);
  906. WRITE_DATA(Bool, UpdateDirectories);
  907. WRITE_DATA(Bool, CacheDirectories);
  908. WRITE_DATA(Bool, CacheDirectoryChanges);
  909. WRITE_DATA(Bool, PreserveDirectoryChanges);
  910. WRITE_DATA(Bool, ResolveSymlinks);
  911. WRITE_DATA(Bool, FollowDirectorySymlinks);
  912. WRITE_DATA_EX(Integer, L"ConsiderDST", DSTMode, );
  913. WRITE_DATA(Bool, LockInHome);
  914. // Special is never stored (if it would, login dialog must be modified not to
  915. // duplicate Special parameter when Special session is loaded and then stored
  916. // under different name)
  917. // WRITE_DATA(Bool, Special);
  918. WRITE_DATA(String, Shell);
  919. WRITE_DATA(Bool, ClearAliases);
  920. WRITE_DATA(Bool, UnsetNationalVars);
  921. WRITE_DATA(String, ListingCommand);
  922. WRITE_DATA(Bool, IgnoreLsWarnings);
  923. WRITE_DATA(Integer, SCPLsFullTime);
  924. WRITE_DATA(Bool, Scp1Compatibility);
  925. // TimeDifferenceAuto is valid for FTP protocol only.
  926. // For other protocols it's typically true (default value),
  927. // but ignored so TimeDifference is still taken into account (SCP only actually)
  928. if (TimeDifferenceAuto && (FSProtocol == fsFTP))
  929. {
  930. // Have to delete it as TimeDifferenceAuto is not saved when enabled,
  931. // but the default is derived from value of TimeDifference.
  932. Storage->DeleteValue(L"TimeDifference");
  933. }
  934. else
  935. {
  936. WRITE_DATA(Float, TimeDifference);
  937. }
  938. WRITE_DATA(Bool, TimeDifferenceAuto);
  939. WRITE_DATA(Bool, DeleteToRecycleBin);
  940. WRITE_DATA(Bool, OverwrittenToRecycleBin);
  941. WRITE_DATA(String, RecycleBinPath);
  942. WRITE_DATA(String, PostLoginCommands);
  943. WRITE_DATA(String, ReturnVar);
  944. WRITE_DATA_EX(Integer, L"LookupUserGroups2", LookupUserGroups, );
  945. WRITE_DATA(Integer, EOLType);
  946. WRITE_DATA(Bool, TrimVMSVersions);
  947. Storage->DeleteValue(L"SFTPUtfBug");
  948. WRITE_DATA_EX(Integer, L"Utf", NotUtf, );
  949. WRITE_DATA(Integer, InternalEditorEncoding);
  950. WRITE_DATA(String, S3DefaultRegion);
  951. WRITE_DATA(Integer, SendBuf);
  952. WRITE_DATA(Bool, SshSimple);
  953. }
  954. WRITE_DATA(Integer, ProxyMethod);
  955. WRITE_DATA(String, ProxyHost);
  956. WRITE_DATA(Integer, ProxyPort);
  957. WRITE_DATA(String, ProxyUsername);
  958. if (ProxyMethod == pmCmd)
  959. {
  960. WRITE_DATA_EX(StringRaw, L"ProxyTelnetCommand", ProxyLocalCommand, );
  961. }
  962. else
  963. {
  964. WRITE_DATA(StringRaw, ProxyTelnetCommand);
  965. }
  966. #define WRITE_DATA_CONV_FUNC(X) (((X) + 2) % 3)
  967. WRITE_DATA_CONV(Integer, L"ProxyDNS", ProxyDNS);
  968. #undef WRITE_DATA_CONV_FUNC
  969. WRITE_DATA(Bool, ProxyLocalhost);
  970. #define WRITE_DATA_CONV_FUNC(X) (2 - (X))
  971. #define WRITE_BUG(BUG) WRITE_DATA_CONV(Integer, L"Bug" #BUG, Bug[sb##BUG]);
  972. WRITE_BUG(Ignore1);
  973. WRITE_BUG(PlainPW1);
  974. WRITE_BUG(RSA1);
  975. WRITE_BUG(HMAC2);
  976. WRITE_BUG(DeriveKey2);
  977. WRITE_BUG(RSAPad2);
  978. WRITE_BUG(PKSessID2);
  979. WRITE_BUG(Rekey2);
  980. WRITE_BUG(MaxPkt2);
  981. WRITE_BUG(Ignore2);
  982. WRITE_BUG(OldGex2);
  983. WRITE_BUG(WinAdj);
  984. WRITE_BUG(ChanReq);
  985. #undef WRITE_BUG
  986. #undef WRITE_DATA_CONV_FUNC
  987. Storage->DeleteValue(L"BuggyMAC");
  988. Storage->DeleteValue(L"AliasGroupList");
  989. if (PuttyExport)
  990. {
  991. WRITE_DATA_EX(String, L"Protocol", GetNormalizedPuttyProtocol(), );
  992. WRITE_DATA_EX(String, L"WinTitle", WinTitle, );
  993. }
  994. if (!PuttyExport)
  995. {
  996. WRITE_DATA(String, SftpServer);
  997. #define WRITE_SFTP_BUG(BUG) WRITE_DATA_EX(Integer, L"SFTP" #BUG "Bug", SFTPBug[sb##BUG], );
  998. WRITE_SFTP_BUG(Symlink);
  999. WRITE_SFTP_BUG(SignedTS);
  1000. #undef WRITE_SFTP_BUG
  1001. WRITE_DATA(Integer, SFTPMaxVersion);
  1002. WRITE_DATA(Integer, SFTPMaxPacketSize);
  1003. WRITE_DATA(Integer, SFTPDownloadQueue);
  1004. WRITE_DATA(Integer, SFTPUploadQueue);
  1005. WRITE_DATA(Integer, SFTPListingQueue);
  1006. WRITE_DATA(Integer, Color);
  1007. WRITE_DATA(Bool, Tunnel);
  1008. WRITE_DATA(String, TunnelHostName);
  1009. WRITE_DATA(Integer, TunnelPortNumber);
  1010. WRITE_DATA(String, TunnelUserName);
  1011. WRITE_DATA(String, TunnelPublicKeyFile);
  1012. WRITE_DATA(Integer, TunnelLocalPortNumber);
  1013. WRITE_DATA(Bool, FtpPasvMode);
  1014. WRITE_DATA_EX(Integer, L"FtpForcePasvIp2", FtpForcePasvIp, );
  1015. WRITE_DATA(Integer, FtpUseMlsd);
  1016. WRITE_DATA(String, FtpAccount);
  1017. WRITE_DATA(Integer, FtpPingInterval);
  1018. WRITE_DATA(Integer, FtpPingType);
  1019. WRITE_DATA_EX(Integer, L"FtpTransferActiveImmediately2", FtpTransferActiveImmediately, );
  1020. WRITE_DATA(Integer, Ftps);
  1021. WRITE_DATA(Integer, FtpListAll);
  1022. WRITE_DATA(Integer, FtpHost);
  1023. WRITE_DATA(Integer, FtpDeleteFromCwd);
  1024. WRITE_DATA(Bool, SslSessionReuse);
  1025. WRITE_DATA(String, TlsCertificateFile);
  1026. WRITE_DATA(Integer, FtpProxyLogonType);
  1027. WRITE_DATA(Integer, MinTlsVersion);
  1028. WRITE_DATA(Integer, MaxTlsVersion);
  1029. WRITE_DATA(Bool, IsWorkspace);
  1030. WRITE_DATA(String, Link);
  1031. WRITE_DATA(String, CustomParam1);
  1032. WRITE_DATA(String, CustomParam2);
  1033. }
  1034. SavePasswords(Storage, PuttyExport, DoNotEncryptPasswords);
  1035. }
  1036. //---------------------------------------------------------------------
  1037. TStrings * __fastcall TSessionData::SaveToOptions(const TSessionData * Default)
  1038. {
  1039. std::unique_ptr<TStringList> Options(new TStringList());
  1040. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  1041. DoSave(OptionsStorage.get(), false, Default, true);
  1042. return Options.release();
  1043. }
  1044. //---------------------------------------------------------------------
  1045. void __fastcall TSessionData::Save(THierarchicalStorage * Storage,
  1046. bool PuttyExport, const TSessionData * Default)
  1047. {
  1048. if (Storage->OpenSubKey(InternalStorageKey, true))
  1049. {
  1050. DoSave(Storage, PuttyExport, Default, false);
  1051. Storage->CloseSubKey();
  1052. }
  1053. }
  1054. //---------------------------------------------------------------------
  1055. UnicodeString __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)
  1056. {
  1057. _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);
  1058. UnicodeString Result;
  1059. if (TheNode != NULL)
  1060. {
  1061. Result = TheNode->Text.Trim();
  1062. }
  1063. if (Result.IsEmpty())
  1064. {
  1065. Result = Default;
  1066. }
  1067. return Result;
  1068. }
  1069. //---------------------------------------------------------------------
  1070. int __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)
  1071. {
  1072. _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);
  1073. int Result;
  1074. if (TheNode != NULL)
  1075. {
  1076. Result = StrToIntDef(TheNode->Text.Trim(), Default);
  1077. }
  1078. else
  1079. {
  1080. Result = Default;
  1081. }
  1082. return Result;
  1083. }
  1084. //---------------------------------------------------------------------
  1085. _di_IXMLNode __fastcall TSessionData::FindSettingsNode(_di_IXMLNode Node, const UnicodeString & Name)
  1086. {
  1087. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  1088. {
  1089. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  1090. if (ChildNode->NodeName == L"Setting")
  1091. {
  1092. OleVariant SettingName = ChildNode->GetAttribute(L"name");
  1093. if (SettingName == Name)
  1094. {
  1095. return ChildNode;
  1096. }
  1097. }
  1098. }
  1099. return NULL;
  1100. }
  1101. //---------------------------------------------------------------------
  1102. UnicodeString __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)
  1103. {
  1104. _di_IXMLNode TheNode = FindSettingsNode(Node, Name);
  1105. UnicodeString Result;
  1106. if (TheNode != NULL)
  1107. {
  1108. Result = TheNode->Text.Trim();
  1109. }
  1110. if (Result.IsEmpty())
  1111. {
  1112. Result = Default;
  1113. }
  1114. return Result;
  1115. }
  1116. //---------------------------------------------------------------------
  1117. int __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)
  1118. {
  1119. _di_IXMLNode TheNode = FindSettingsNode(Node, Name);
  1120. int Result;
  1121. if (TheNode != NULL)
  1122. {
  1123. Result = StrToIntDef(TheNode->Text.Trim(), Default);
  1124. }
  1125. else
  1126. {
  1127. Result = Default;
  1128. }
  1129. return Result;
  1130. }
  1131. //---------------------------------------------------------------------
  1132. void __fastcall TSessionData::ImportFromFilezilla(
  1133. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  1134. {
  1135. Name = UnixIncludeTrailingBackslash(Path) + MakeValidName(ReadXmlNode(Node, L"Name", Name));
  1136. HostName = ReadXmlNode(Node, L"Host", HostName);
  1137. PortNumber = ReadXmlNode(Node, L"Port", PortNumber);
  1138. int AProtocol = ReadXmlNode(Node, L"Protocol", 0);
  1139. // ServerProtocol enum
  1140. switch (AProtocol)
  1141. {
  1142. case 0: // FTP
  1143. default: // UNKNOWN, HTTP, HTTPS, INSECURE_FTP
  1144. FSProtocol = fsFTP;
  1145. break;
  1146. case 1: // SFTP
  1147. FSProtocol = fsSFTP;
  1148. break;
  1149. case 3: // FTPS
  1150. FSProtocol = fsFTP;
  1151. Ftps = ftpsImplicit;
  1152. break;
  1153. case 4: // FTPES
  1154. FSProtocol = fsFTP;
  1155. Ftps = ftpsExplicitTls;
  1156. break;
  1157. }
  1158. // LogonType enum
  1159. int LogonType = ReadXmlNode(Node, L"Logontype", 0);
  1160. if (LogonType == 0) // ANONYMOUS
  1161. {
  1162. UserName = AnonymousUserName;
  1163. Password = AnonymousPassword;
  1164. }
  1165. else
  1166. {
  1167. UserName = ReadXmlNode(Node, L"User", UserName);
  1168. FtpAccount = ReadXmlNode(Node, L"Account", FtpAccount);
  1169. _di_IXMLNode PassNode = Node->ChildNodes->FindNode(L"Pass");
  1170. if (PassNode != NULL)
  1171. {
  1172. UnicodeString APassword = PassNode->Text.Trim();
  1173. OleVariant EncodingValue = PassNode->GetAttribute(L"encoding");
  1174. if (!EncodingValue.IsNull())
  1175. {
  1176. UnicodeString EncodingValueStr = EncodingValue;
  1177. if (SameText(EncodingValueStr, L"base64"))
  1178. {
  1179. TBytes Bytes = DecodeBase64(APassword);
  1180. APassword = TEncoding::UTF8->GetString(Bytes);
  1181. }
  1182. }
  1183. Password = APassword;
  1184. }
  1185. }
  1186. int DefaultTimeDifference = TimeToSeconds(TimeDifference);
  1187. TimeDifference =
  1188. (double(ReadXmlNode(Node, L"TimezoneOffset", DefaultTimeDifference) / SecsPerDay));
  1189. TimeDifferenceAuto = (TimeDifference == TDateTime());
  1190. UnicodeString PasvMode = ReadXmlNode(Node, L"PasvMode", L"");
  1191. if (SameText(PasvMode, L"MODE_PASSIVE"))
  1192. {
  1193. FtpPasvMode = true;
  1194. }
  1195. else if (SameText(PasvMode, L"MODE_ACTIVE"))
  1196. {
  1197. FtpPasvMode = false;
  1198. }
  1199. UnicodeString EncodingType = ReadXmlNode(Node, L"EncodingType", L"");
  1200. if (SameText(EncodingType, L"Auto"))
  1201. {
  1202. NotUtf = asAuto;
  1203. }
  1204. else if (SameText(EncodingType, L"UTF-8"))
  1205. {
  1206. NotUtf = asOff;
  1207. }
  1208. // todo PostLoginCommands
  1209. Note = ReadXmlNode(Node, L"Comments", Note);
  1210. LocalDirectory = ReadXmlNode(Node, L"LocalDir", LocalDirectory);
  1211. UnicodeString RemoteDir = ReadXmlNode(Node, L"RemoteDir", L"");
  1212. if (!RemoteDir.IsEmpty())
  1213. {
  1214. CutToChar(RemoteDir, L' ', false); // type
  1215. int PrefixSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0); // prefix size
  1216. if (PrefixSize > 0)
  1217. {
  1218. RemoteDir.Delete(1, PrefixSize);
  1219. }
  1220. RemoteDirectory = L"/";
  1221. while (!RemoteDir.IsEmpty())
  1222. {
  1223. int SegmentSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0);
  1224. UnicodeString Segment = RemoteDir.SubString(1, SegmentSize);
  1225. RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory) + Segment;
  1226. RemoteDir.Delete(1, SegmentSize + 1);
  1227. }
  1228. }
  1229. SynchronizeBrowsing = (ReadXmlNode(Node, L"SyncBrowsing", SynchronizeBrowsing ? 1 : 0) != 0);
  1230. if (SettingsNode != NULL)
  1231. {
  1232. if (UsesSsh)
  1233. {
  1234. UnicodeString KeyFiles = ReadSettingsNode(SettingsNode, L"SFTP keyfiles", UnicodeString());
  1235. UnicodeString KeyFile = CutToChar(KeyFiles, L'\n', true).Trim();
  1236. KeyFiles = KeyFiles.Trim();
  1237. // If there are more keys, ignore them, as we do not know which one to use
  1238. if (!KeyFile.IsEmpty() && KeyFiles.IsEmpty())
  1239. {
  1240. PublicKeyFile = KeyFile;
  1241. }
  1242. }
  1243. bool BypassProxy = (ReadXmlNode(Node, L"BypassProxy", 0) != 0);
  1244. if (!BypassProxy)
  1245. {
  1246. int FtpProxyType = ReadSettingsNode(SettingsNode, L"FTP Proxy type", -1);
  1247. if (FtpProxyType > 0)
  1248. {
  1249. switch (FtpProxyType)
  1250. {
  1251. case 1:
  1252. FtpProxyLogonType = 2;
  1253. break;
  1254. case 2:
  1255. FtpProxyLogonType = 1;
  1256. break;
  1257. case 3:
  1258. FtpProxyLogonType = 3;
  1259. break;
  1260. case 4:
  1261. // custom
  1262. // TODO: map known sequences to our enumeration
  1263. FtpProxyLogonType = 0;
  1264. break;
  1265. default:
  1266. DebugFail();
  1267. FtpProxyLogonType = 0;
  1268. break;
  1269. }
  1270. ProxyHost = ReadSettingsNode(SettingsNode, L"FTP Proxy host", ProxyHost);
  1271. ProxyUsername = ReadSettingsNode(SettingsNode, L"FTP Proxy user", ProxyUsername);
  1272. ProxyPassword = ReadSettingsNode(SettingsNode, L"FTP Proxy password", ProxyPassword);
  1273. // ProxyPort is not used with FtpProxyLogonType
  1274. }
  1275. else
  1276. {
  1277. int ProxyType = ReadSettingsNode(SettingsNode, L"Proxy type", -1);
  1278. if (ProxyType >= 0)
  1279. {
  1280. switch (ProxyType)
  1281. {
  1282. case 0:
  1283. ProxyMethod = ::pmNone;
  1284. break;
  1285. case 1:
  1286. ProxyMethod = pmHTTP;
  1287. break;
  1288. case 2:
  1289. ProxyMethod = pmSocks5;
  1290. break;
  1291. case 3:
  1292. ProxyMethod = pmSocks4;
  1293. break;
  1294. default:
  1295. DebugFail();
  1296. ProxyMethod = ::pmNone;
  1297. break;
  1298. }
  1299. ProxyHost = ReadSettingsNode(SettingsNode, L"Proxy host", ProxyHost);
  1300. ProxyPort = ReadSettingsNode(SettingsNode, L"Proxy port", ProxyPort);
  1301. ProxyUsername = ReadSettingsNode(SettingsNode, L"Proxy user", ProxyUsername);
  1302. ProxyPassword = ReadSettingsNode(SettingsNode, L"Proxy password", ProxyPassword);
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. //---------------------------------------------------------------------
  1309. void __fastcall TSessionData::SavePasswords(THierarchicalStorage * Storage, bool PuttyExport, bool DoNotEncryptPasswords)
  1310. {
  1311. if (!Configuration->DisablePasswordStoring && !PuttyExport && !FPassword.IsEmpty())
  1312. {
  1313. // DoNotEncryptPasswords is set when called from GenerateOpenCommandArgs only
  1314. // and it never saves session password
  1315. DebugAssert(!DoNotEncryptPasswords);
  1316. Storage->WriteBinaryDataAsString(L"Password", StronglyRecryptPassword(FPassword, UserName+HostName));
  1317. }
  1318. else
  1319. {
  1320. Storage->DeleteValue(L"Password");
  1321. }
  1322. Storage->DeleteValue(L"PasswordPlain");
  1323. if (PuttyExport)
  1324. {
  1325. // save password unencrypted
  1326. Storage->WriteString(L"ProxyPassword", ProxyPassword);
  1327. }
  1328. else
  1329. {
  1330. if (DoNotEncryptPasswords)
  1331. {
  1332. if (!FProxyPassword.IsEmpty())
  1333. {
  1334. Storage->WriteString(L"ProxyPassword", ProxyPassword);
  1335. }
  1336. else
  1337. {
  1338. Storage->DeleteValue(L"ProxyPassword");
  1339. }
  1340. Storage->DeleteValue(L"ProxyPasswordEnc");
  1341. }
  1342. else
  1343. {
  1344. // save password encrypted
  1345. if (!FProxyPassword.IsEmpty())
  1346. {
  1347. Storage->WriteBinaryDataAsString(L"ProxyPasswordEnc", StronglyRecryptPassword(FProxyPassword, ProxyUsername+ProxyHost));
  1348. }
  1349. else
  1350. {
  1351. Storage->DeleteValue(L"ProxyPasswordEnc");
  1352. }
  1353. Storage->DeleteValue(L"ProxyPassword");
  1354. }
  1355. if (DoNotEncryptPasswords)
  1356. {
  1357. if (!FTunnelPassword.IsEmpty())
  1358. {
  1359. Storage->WriteString(L"TunnelPasswordPlain", TunnelPassword);
  1360. }
  1361. else
  1362. {
  1363. Storage->DeleteValue(L"TunnelPasswordPlain");
  1364. }
  1365. }
  1366. else
  1367. {
  1368. if (!Configuration->DisablePasswordStoring && !FTunnelPassword.IsEmpty())
  1369. {
  1370. Storage->WriteBinaryDataAsString(L"TunnelPassword", StronglyRecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName));
  1371. }
  1372. else
  1373. {
  1374. Storage->DeleteValue(L"TunnelPassword");
  1375. }
  1376. }
  1377. }
  1378. }
  1379. //---------------------------------------------------------------------
  1380. void __fastcall TSessionData::RecryptPasswords()
  1381. {
  1382. Password = Password;
  1383. NewPassword = NewPassword;
  1384. ProxyPassword = ProxyPassword;
  1385. TunnelPassword = TunnelPassword;
  1386. Passphrase = Passphrase;
  1387. }
  1388. //---------------------------------------------------------------------
  1389. bool __fastcall TSessionData::HasPassword()
  1390. {
  1391. return !FPassword.IsEmpty();
  1392. }
  1393. //---------------------------------------------------------------------
  1394. bool __fastcall TSessionData::HasAnySessionPassword()
  1395. {
  1396. return HasPassword() || !FTunnelPassword.IsEmpty();
  1397. }
  1398. //---------------------------------------------------------------------
  1399. bool __fastcall TSessionData::HasAnyPassword()
  1400. {
  1401. return
  1402. HasAnySessionPassword() ||
  1403. !FProxyPassword.IsEmpty() ||
  1404. // will probably be never used
  1405. FNewPassword.IsEmpty();
  1406. }
  1407. //---------------------------------------------------------------------
  1408. void __fastcall TSessionData::ClearSessionPasswords()
  1409. {
  1410. FPassword = L"";
  1411. FNewPassword = L"";
  1412. FTunnelPassword = L"";
  1413. }
  1414. //---------------------------------------------------------------------
  1415. void __fastcall TSessionData::Modify()
  1416. {
  1417. FModified = true;
  1418. if (FSource == ssStored)
  1419. {
  1420. FSource = ssStoredModified;
  1421. }
  1422. }
  1423. //---------------------------------------------------------------------
  1424. UnicodeString __fastcall TSessionData::GetSource()
  1425. {
  1426. switch (FSource)
  1427. {
  1428. case ::ssNone:
  1429. return L"Ad-Hoc site";
  1430. case ssStored:
  1431. return L"Site";
  1432. case ssStoredModified:
  1433. return L"Modified site";
  1434. default:
  1435. DebugFail();
  1436. return L"";
  1437. }
  1438. }
  1439. //---------------------------------------------------------------------
  1440. void __fastcall TSessionData::SaveRecryptedPasswords(THierarchicalStorage * Storage)
  1441. {
  1442. if (Storage->OpenSubKey(InternalStorageKey, true))
  1443. {
  1444. try
  1445. {
  1446. RecryptPasswords();
  1447. SavePasswords(Storage, false, false);
  1448. }
  1449. __finally
  1450. {
  1451. Storage->CloseSubKey();
  1452. }
  1453. }
  1454. }
  1455. //---------------------------------------------------------------------
  1456. void __fastcall TSessionData::Remove()
  1457. {
  1458. bool SessionList = true;
  1459. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  1460. try
  1461. {
  1462. Storage->Explicit = true;
  1463. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, false))
  1464. {
  1465. Storage->RecursiveDeleteSubKey(InternalStorageKey);
  1466. }
  1467. }
  1468. __finally
  1469. {
  1470. delete Storage;
  1471. }
  1472. }
  1473. //---------------------------------------------------------------------
  1474. void __fastcall TSessionData::CacheHostKeyIfNotCached()
  1475. {
  1476. UnicodeString KeyType = KeyTypeFromFingerprint(HostKey);
  1477. // Should allow importing to INI file as ImportHostKeys
  1478. UnicodeString TargetKey = Configuration->RegistryStorageKey + L"\\" + Configuration->SshHostKeysSubKey;
  1479. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(TargetKey));
  1480. Storage->AccessMode = smReadWrite;
  1481. if (Storage->OpenRootKey(true))
  1482. {
  1483. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"%s@%d:%s", (KeyType, PortNumber, HostName)));
  1484. if (!Storage->ValueExists(HostKeyName))
  1485. {
  1486. // fingerprint is MD5 of host key, so it cannot be translated back to host key,
  1487. // so we store fingerprint and TSecureShell::VerifyHostKey was
  1488. // modified to accept also fingerprint
  1489. Storage->WriteString(HostKeyName, HostKey);
  1490. }
  1491. }
  1492. }
  1493. //---------------------------------------------------------------------
  1494. inline void __fastcall MoveStr(UnicodeString & Source, UnicodeString * Dest, int Count)
  1495. {
  1496. if (Dest != NULL)
  1497. {
  1498. (*Dest) += Source.SubString(1, Count);
  1499. }
  1500. Source.Delete(1, Count);
  1501. }
  1502. //---------------------------------------------------------------------
  1503. bool __fastcall TSessionData::DoIsProtocolUrl(
  1504. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1505. {
  1506. bool Result = SameText(Url.SubString(1, Protocol.Length() + 1), Protocol + L":");
  1507. if (Result)
  1508. {
  1509. ProtocolLen = Protocol.Length() + 1;
  1510. }
  1511. return Result;
  1512. }
  1513. //---------------------------------------------------------------------
  1514. bool __fastcall TSessionData::IsProtocolUrl(
  1515. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1516. {
  1517. return
  1518. DoIsProtocolUrl(Url, Protocol, ProtocolLen) ||
  1519. DoIsProtocolUrl(Url, WinSCPProtocolPrefix + Protocol, ProtocolLen);
  1520. }
  1521. //---------------------------------------------------------------------
  1522. bool __fastcall TSessionData::IsSensitiveOption(const UnicodeString & Option)
  1523. {
  1524. return
  1525. SameText(Option, PassphraseOption) ||
  1526. SameText(Option, NEWPASSWORD_SWITCH);
  1527. }
  1528. //---------------------------------------------------------------------
  1529. bool __fastcall TSessionData::IsOptionWithParameters(const UnicodeString & Option)
  1530. {
  1531. return SameText(Option, RawSettingsOption);
  1532. }
  1533. //---------------------------------------------------------------------
  1534. bool __fastcall TSessionData::MaskPasswordInOptionParameter(const UnicodeString & Option, UnicodeString & Param)
  1535. {
  1536. bool Result = false;
  1537. if (SameText(Option, RawSettingsOption))
  1538. {
  1539. int P = Param.Pos(L"=");
  1540. if (P > 0)
  1541. {
  1542. // TStrings.IndexOfName does not trim
  1543. UnicodeString Key = Param.SubString(1, P - 1);
  1544. if (SameText(Key, L"ProxyPassword") ||
  1545. SameText(Key, L"ProxyPasswordEnc") ||
  1546. SameText(Key, L"TunnelPassword") ||
  1547. SameText(Key, L"TunnelPasswordPlain"))
  1548. {
  1549. Param = Key + L"=" + PasswordMask;
  1550. Result = true;
  1551. }
  1552. }
  1553. }
  1554. return Result;
  1555. }
  1556. //---------------------------------------------------------------------
  1557. void __fastcall TSessionData::MaskPasswords()
  1558. {
  1559. if (!Password.IsEmpty())
  1560. {
  1561. Password = PasswordMask;
  1562. }
  1563. if (!NewPassword.IsEmpty())
  1564. {
  1565. NewPassword = PasswordMask;
  1566. }
  1567. if (!ProxyPassword.IsEmpty())
  1568. {
  1569. ProxyPassword = PasswordMask;
  1570. }
  1571. if (!TunnelPassword.IsEmpty())
  1572. {
  1573. TunnelPassword = PasswordMask;
  1574. }
  1575. if (!Passphrase.IsEmpty())
  1576. {
  1577. Passphrase = PasswordMask;
  1578. }
  1579. }
  1580. //---------------------------------------------------------------------
  1581. bool __fastcall TSessionData::ParseUrl(UnicodeString Url, TOptions * Options,
  1582. TStoredSessionList * StoredSessions, bool & DefaultsOnly, UnicodeString * FileName,
  1583. bool * AProtocolDefined, UnicodeString * MaskedUrl)
  1584. {
  1585. bool ProtocolDefined = false;
  1586. bool PortNumberDefined = false;
  1587. TFSProtocol AFSProtocol;
  1588. int APortNumber;
  1589. TFtps AFtps = ftpsNone;
  1590. int ProtocolLen = 0;
  1591. if (IsProtocolUrl(Url, ScpProtocol, ProtocolLen))
  1592. {
  1593. AFSProtocol = fsSCPonly;
  1594. APortNumber = SshPortNumber;
  1595. MoveStr(Url, MaskedUrl, ProtocolLen);
  1596. ProtocolDefined = true;
  1597. }
  1598. else if (IsProtocolUrl(Url, SftpProtocol, ProtocolLen))
  1599. {
  1600. AFSProtocol = fsSFTPonly;
  1601. APortNumber = SshPortNumber;
  1602. MoveStr(Url, MaskedUrl, ProtocolLen);
  1603. ProtocolDefined = true;
  1604. }
  1605. else if (IsProtocolUrl(Url, FtpProtocol, ProtocolLen))
  1606. {
  1607. AFSProtocol = fsFTP;
  1608. Ftps = ftpsNone;
  1609. APortNumber = FtpPortNumber;
  1610. MoveStr(Url, MaskedUrl, ProtocolLen);
  1611. ProtocolDefined = true;
  1612. }
  1613. else if (IsProtocolUrl(Url, FtpsProtocol, ProtocolLen))
  1614. {
  1615. AFSProtocol = fsFTP;
  1616. AFtps = ftpsImplicit;
  1617. APortNumber = FtpsImplicitPortNumber;
  1618. MoveStr(Url, MaskedUrl, ProtocolLen);
  1619. ProtocolDefined = true;
  1620. }
  1621. else if (IsProtocolUrl(Url, FtpesProtocol, ProtocolLen))
  1622. {
  1623. AFSProtocol = fsFTP;
  1624. AFtps = ftpsExplicitTls;
  1625. APortNumber = FtpPortNumber;
  1626. MoveStr(Url, MaskedUrl, ProtocolLen);
  1627. ProtocolDefined = true;
  1628. }
  1629. else if (IsProtocolUrl(Url, WebDAVProtocol, ProtocolLen) ||
  1630. IsProtocolUrl(Url, HttpProtocol, ProtocolLen))
  1631. {
  1632. AFSProtocol = fsWebDAV;
  1633. AFtps = ftpsNone;
  1634. APortNumber = HTTPPortNumber;
  1635. MoveStr(Url, MaskedUrl, ProtocolLen);
  1636. ProtocolDefined = true;
  1637. }
  1638. else if (IsProtocolUrl(Url, WebDAVSProtocol, ProtocolLen) ||
  1639. IsProtocolUrl(Url, HttpsProtocol, ProtocolLen))
  1640. {
  1641. AFSProtocol = fsWebDAV;
  1642. AFtps = ftpsImplicit;
  1643. APortNumber = HTTPSPortNumber;
  1644. MoveStr(Url, MaskedUrl, ProtocolLen);
  1645. ProtocolDefined = true;
  1646. }
  1647. else if (IsProtocolUrl(Url, S3Protocol, ProtocolLen))
  1648. {
  1649. AFSProtocol = fsS3;
  1650. AFtps = ftpsImplicit;
  1651. APortNumber = HTTPSPortNumber;
  1652. MoveStr(Url, MaskedUrl, ProtocolLen);
  1653. ProtocolDefined = true;
  1654. }
  1655. else if (IsProtocolUrl(Url, SshProtocol, ProtocolLen))
  1656. {
  1657. // For most uses, handling ssh:// the same way as sftp://
  1658. // The only place where a difference is made is GetLoginData() in WinMain.cpp
  1659. AFSProtocol = fsSFTPonly;
  1660. PuttyProtocol = PuttySshProtocol;
  1661. APortNumber = SshPortNumber;
  1662. MoveStr(Url, MaskedUrl, ProtocolLen);
  1663. ProtocolDefined = true;
  1664. }
  1665. if (ProtocolDefined && (Url.SubString(1, 2) == L"//"))
  1666. {
  1667. MoveStr(Url, MaskedUrl, 2);
  1668. }
  1669. if (AProtocolDefined != NULL)
  1670. {
  1671. *AProtocolDefined = ProtocolDefined;
  1672. }
  1673. if (!Url.IsEmpty())
  1674. {
  1675. UnicodeString DecodedUrl = DecodeUrlChars(Url);
  1676. // lookup stored session even if protocol was defined
  1677. // (this allows setting for example default username for host
  1678. // by creating stored session named by host)
  1679. TSessionData * Data = NULL;
  1680. // When using to paste URL on Login dialog, we do not want to lookup the stored sites
  1681. if (StoredSessions != NULL)
  1682. {
  1683. // this can be optimized as the list is sorted
  1684. for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++)
  1685. {
  1686. TSessionData * AData = (TSessionData *)StoredSessions->Items[Index];
  1687. if (!AData->IsWorkspace)
  1688. {
  1689. bool Match = false;
  1690. // Comparison optimizations as this is called many times
  1691. // e.g. when updating jumplist
  1692. if ((AData->Name.Length() == DecodedUrl.Length()) &&
  1693. SameText(AData->Name, DecodedUrl))
  1694. {
  1695. Match = true;
  1696. }
  1697. else if ((AData->Name.Length() < DecodedUrl.Length()) &&
  1698. (DecodedUrl[AData->Name.Length() + 1] == L'/') &&
  1699. // StrLIComp is an equivalent of SameText
  1700. (StrLIComp(AData->Name.c_str(), DecodedUrl.c_str(), AData->Name.Length()) == 0))
  1701. {
  1702. Match = true;
  1703. }
  1704. if (Match)
  1705. {
  1706. Data = AData;
  1707. break;
  1708. }
  1709. }
  1710. }
  1711. }
  1712. UnicodeString ARemoteDirectory;
  1713. if (Data != NULL)
  1714. {
  1715. Assign(Data);
  1716. int P = 1;
  1717. while (!AnsiSameText(DecodeUrlChars(Url.SubString(1, P)), Data->Name))
  1718. {
  1719. P++;
  1720. DebugAssert(P <= Url.Length());
  1721. }
  1722. ARemoteDirectory = Url.SubString(P + 1, Url.Length() - P);
  1723. if (Data->Hidden)
  1724. {
  1725. Data->Remove();
  1726. StoredSessions->Remove(Data);
  1727. // only modified, implicit
  1728. StoredSessions->Save(false, false);
  1729. }
  1730. if (MaskedUrl != NULL)
  1731. {
  1732. (*MaskedUrl) += Url;
  1733. }
  1734. }
  1735. else
  1736. {
  1737. // This happens when pasting URL on Login dialog
  1738. if (StoredSessions != NULL)
  1739. {
  1740. CopyData(StoredSessions->DefaultSettings);
  1741. }
  1742. Name = L"";
  1743. int PSlash = Url.Pos(L"/");
  1744. if (PSlash == 0)
  1745. {
  1746. PSlash = Url.Length() + 1;
  1747. }
  1748. UnicodeString ConnectInfo = Url.SubString(1, PSlash - 1);
  1749. int P = ConnectInfo.LastDelimiter(L"@");
  1750. UnicodeString UserInfo;
  1751. UnicodeString HostInfo;
  1752. if (P > 0)
  1753. {
  1754. UserInfo = ConnectInfo.SubString(1, P - 1);
  1755. HostInfo = ConnectInfo.SubString(P + 1, ConnectInfo.Length() - P);
  1756. }
  1757. else
  1758. {
  1759. HostInfo = ConnectInfo;
  1760. }
  1761. UnicodeString OrigHostInfo = HostInfo;
  1762. if ((HostInfo.Length() >= 2) && (HostInfo[1] == L'[') && ((P = HostInfo.Pos(L"]")) > 0))
  1763. {
  1764. HostName = HostInfo.SubString(2, P - 2);
  1765. HostInfo.Delete(1, P);
  1766. if (!HostInfo.IsEmpty() && (HostInfo[1] == L':'))
  1767. {
  1768. HostInfo.Delete(1, 1);
  1769. }
  1770. }
  1771. else
  1772. {
  1773. HostName = DecodeUrlChars(CutToChar(HostInfo, L':', true));
  1774. }
  1775. // expanded from ?: operator, as it caused strange "access violation" errors
  1776. if (!HostInfo.IsEmpty())
  1777. {
  1778. PortNumber = StrToIntDef(DecodeUrlChars(HostInfo), -1);
  1779. PortNumberDefined = true;
  1780. }
  1781. else if (ProtocolDefined)
  1782. {
  1783. PortNumber = APortNumber;
  1784. }
  1785. if (ProtocolDefined)
  1786. {
  1787. Ftps = AFtps;
  1788. }
  1789. UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);
  1790. UnicodeString ConnectionParams = UserInfo;
  1791. UserInfo = UserInfoWithoutConnectionParams;
  1792. while (!ConnectionParams.IsEmpty())
  1793. {
  1794. UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);
  1795. UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);
  1796. if (SameText(ConnectionParamName, UrlHostKeyParamName))
  1797. {
  1798. HostKey = DecodeUrlChars(ConnectionParam);
  1799. FOverrideCachedHostKey = false;
  1800. }
  1801. }
  1802. UnicodeString RawUserName = CutToChar(UserInfo, L':', false);
  1803. UserName = DecodeUrlChars(RawUserName);
  1804. Password = DecodeUrlChars(UserInfo);
  1805. UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);
  1806. ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);
  1807. UnicodeString SessionParams = RemoteDirectoryWithSessionParams;
  1808. // We should handle session params in "stored session" branch too.
  1809. // And particularly if there's a "save" param, we should actually not try to match the
  1810. // URL against site names
  1811. while (!SessionParams.IsEmpty())
  1812. {
  1813. UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);
  1814. UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);
  1815. if (SameText(SessionParamName, UrlSaveParamName))
  1816. {
  1817. FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);
  1818. }
  1819. }
  1820. if (MaskedUrl != NULL)
  1821. {
  1822. (*MaskedUrl) += RawUserName;
  1823. if (!UserInfo.IsEmpty())
  1824. {
  1825. (*MaskedUrl) += L":" + PasswordMask;
  1826. }
  1827. if (!RawUserName.IsEmpty() || !UserInfo.IsEmpty())
  1828. {
  1829. (*MaskedUrl) += L"@";
  1830. }
  1831. (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;
  1832. }
  1833. }
  1834. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L"/"))
  1835. {
  1836. if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&
  1837. (FileName != NULL))
  1838. {
  1839. *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));
  1840. ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);
  1841. }
  1842. RemoteDirectory = DecodeUrlChars(ARemoteDirectory);
  1843. }
  1844. DefaultsOnly = false;
  1845. }
  1846. else
  1847. {
  1848. // This happens when pasting URL on Login dialog
  1849. if (StoredSessions != NULL)
  1850. {
  1851. CopyData(StoredSessions->DefaultSettings);
  1852. }
  1853. DefaultsOnly = true;
  1854. }
  1855. if (ProtocolDefined)
  1856. {
  1857. FSProtocol = AFSProtocol;
  1858. }
  1859. if (Options != NULL)
  1860. {
  1861. // we deliberately do keep defaultonly to false, in presence of any option,
  1862. // as the option should not make session "connectable"
  1863. UnicodeString Value;
  1864. if (Options->FindSwitch(SESSIONNAME_SWICH, Value))
  1865. {
  1866. Name = Value;
  1867. }
  1868. if (Options->FindSwitch(NEWPASSWORD_SWITCH, Value))
  1869. {
  1870. ChangePassword = true;
  1871. NewPassword = Value;
  1872. }
  1873. if (Options->FindSwitch(L"privatekey", Value))
  1874. {
  1875. PublicKeyFile = Value;
  1876. }
  1877. if (Options->FindSwitch(L"clientcert", Value))
  1878. {
  1879. TlsCertificateFile = Value;
  1880. }
  1881. if (Options->FindSwitch(PassphraseOption, Value))
  1882. {
  1883. Passphrase = Value;
  1884. }
  1885. if (Options->FindSwitch(L"timeout", Value))
  1886. {
  1887. Timeout = StrToInt(Value);
  1888. }
  1889. if (Options->FindSwitch(L"hostkey", Value) ||
  1890. Options->FindSwitch(L"certificate", Value))
  1891. {
  1892. HostKey = Value;
  1893. FOverrideCachedHostKey = true;
  1894. }
  1895. FtpPasvMode = Options->SwitchValue(L"passive", FtpPasvMode);
  1896. if (Options->FindSwitch(L"implicit"))
  1897. {
  1898. bool Enabled = Options->SwitchValue(L"implicit", true);
  1899. Ftps = Enabled ? ftpsImplicit : ftpsNone;
  1900. if (!PortNumberDefined && Enabled)
  1901. {
  1902. PortNumber = FtpsImplicitPortNumber;
  1903. }
  1904. }
  1905. // BACKWARD COMPATIBILITY with 5.5.x
  1906. if (Options->FindSwitch(L"explicitssl"))
  1907. {
  1908. bool Enabled = Options->SwitchValue(L"explicitssl", true);
  1909. Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;
  1910. if (!PortNumberDefined && Enabled)
  1911. {
  1912. PortNumber = FtpPortNumber;
  1913. }
  1914. }
  1915. if (Options->FindSwitch(L"explicit") ||
  1916. // BACKWARD COMPATIBILITY with 5.5.x
  1917. Options->FindSwitch(L"explicittls"))
  1918. {
  1919. UnicodeString SwitchName =
  1920. Options->FindSwitch(L"explicit") ? L"explicit" : L"explicittls";
  1921. bool Enabled = Options->SwitchValue(SwitchName, true);
  1922. Ftps = Enabled ? ftpsExplicitTls : ftpsNone;
  1923. if (!PortNumberDefined && Enabled)
  1924. {
  1925. PortNumber = FtpPortNumber;
  1926. }
  1927. }
  1928. if (Options->FindSwitch(RawSettingsOption))
  1929. {
  1930. TStrings * RawSettings = NULL;
  1931. TOptionsStorage * OptionsStorage = NULL;
  1932. try
  1933. {
  1934. RawSettings = new TStringList();
  1935. if (Options->FindSwitch(RawSettingsOption, RawSettings))
  1936. {
  1937. OptionsStorage = new TOptionsStorage(RawSettings, false);
  1938. ApplyRawSettings(OptionsStorage);
  1939. }
  1940. }
  1941. __finally
  1942. {
  1943. delete RawSettings;
  1944. delete OptionsStorage;
  1945. }
  1946. }
  1947. }
  1948. return true;
  1949. }
  1950. //---------------------------------------------------------------------
  1951. void __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage)
  1952. {
  1953. bool Dummy;
  1954. DoLoad(Storage, false, Dummy);
  1955. }
  1956. //---------------------------------------------------------------------
  1957. void __fastcall TSessionData::ConfigureTunnel(int APortNumber)
  1958. {
  1959. FOrigHostName = HostName;
  1960. FOrigPortNumber = PortNumber;
  1961. FOrigProxyMethod = ProxyMethod;
  1962. HostName = L"127.0.0.1";
  1963. PortNumber = APortNumber;
  1964. // proxy settings is used for tunnel
  1965. ProxyMethod = ::pmNone;
  1966. FLogicalHostName = FOrigHostName;
  1967. }
  1968. //---------------------------------------------------------------------
  1969. void __fastcall TSessionData::RollbackTunnel()
  1970. {
  1971. HostName = FOrigHostName;
  1972. PortNumber = FOrigPortNumber;
  1973. ProxyMethod = FOrigProxyMethod;
  1974. FLogicalHostName = L"";
  1975. }
  1976. //---------------------------------------------------------------------
  1977. void __fastcall TSessionData::ExpandEnvironmentVariables()
  1978. {
  1979. HostName = HostNameExpanded;
  1980. UserName = UserNameExpanded;
  1981. PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);
  1982. }
  1983. //---------------------------------------------------------------------
  1984. void __fastcall TSessionData::ValidatePath(const UnicodeString Path)
  1985. {
  1986. // noop
  1987. }
  1988. //---------------------------------------------------------------------
  1989. void __fastcall TSessionData::ValidateName(const UnicodeString Name)
  1990. {
  1991. // keep consistent with MakeValidName
  1992. if (Name.LastDelimiter(L"/") > 0)
  1993. {
  1994. throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L"/")));
  1995. }
  1996. }
  1997. //---------------------------------------------------------------------
  1998. UnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)
  1999. {
  2000. // keep consistent with ValidateName
  2001. return ReplaceStr(Name, L"/", L"\\");
  2002. }
  2003. //---------------------------------------------------------------------
  2004. RawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)
  2005. {
  2006. return Configuration->EncryptPassword(Password, Key);
  2007. }
  2008. //---------------------------------------------------------------------
  2009. RawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)
  2010. {
  2011. return Configuration->StronglyRecryptPassword(Password, Key);
  2012. }
  2013. //---------------------------------------------------------------------
  2014. UnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)
  2015. {
  2016. UnicodeString Result;
  2017. try
  2018. {
  2019. Result = Configuration->DecryptPassword(Password, Key);
  2020. }
  2021. catch(EAbort &)
  2022. {
  2023. // silently ignore aborted prompts for master password and return empty password
  2024. }
  2025. return Result;
  2026. }
  2027. //---------------------------------------------------------------------
  2028. bool __fastcall TSessionData::GetCanLogin()
  2029. {
  2030. return !FHostName.IsEmpty();
  2031. }
  2032. //---------------------------------------------------------------------------
  2033. UnicodeString __fastcall TSessionData::GetSessionKey()
  2034. {
  2035. UnicodeString Result = FORMAT(L"%s@%s", (UserName, HostName));
  2036. if (PortNumber != DefaultPort(FSProtocol, Ftps))
  2037. {
  2038. Result += FORMAT(L":%d", (PortNumber));
  2039. }
  2040. return Result;
  2041. }
  2042. //---------------------------------------------------------------------
  2043. UnicodeString __fastcall TSessionData::GetInternalStorageKey()
  2044. {
  2045. // This is probably useless remnant of previous use of this method from OpenSessionInPutty
  2046. // that needs the method to return something even for ad-hoc sessions
  2047. if (Name.IsEmpty())
  2048. {
  2049. return SessionKey;
  2050. }
  2051. else
  2052. {
  2053. return Name;
  2054. }
  2055. }
  2056. //---------------------------------------------------------------------
  2057. UnicodeString __fastcall TSessionData::GetStorageKey()
  2058. {
  2059. return SessionName;
  2060. }
  2061. //---------------------------------------------------------------------
  2062. UnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)
  2063. {
  2064. return FORMAT(L"%s:%d", (HostName, PortNumber));
  2065. }
  2066. //---------------------------------------------------------------------
  2067. UnicodeString __fastcall TSessionData::GetSiteKey()
  2068. {
  2069. return FormatSiteKey(HostNameExpanded, PortNumber);
  2070. }
  2071. //---------------------------------------------------------------------
  2072. void __fastcall TSessionData::SetHostName(UnicodeString value)
  2073. {
  2074. if (FHostName != value)
  2075. {
  2076. // HostName is key for password encryption
  2077. UnicodeString XPassword = Password;
  2078. UnicodeString XNewPassword = Password;
  2079. // This is now hardly used as hostname is parsed directly on login dialog.
  2080. // But can be used when importing sites from PuTTY, as it allows same format too.
  2081. int P = value.LastDelimiter(L"@");
  2082. if (P > 0)
  2083. {
  2084. UserName = value.SubString(1, P - 1);
  2085. value = value.SubString(P + 1, value.Length() - P);
  2086. }
  2087. FHostName = value;
  2088. Modify();
  2089. Password = XPassword;
  2090. NewPassword = XNewPassword;
  2091. Shred(XPassword);
  2092. Shred(XNewPassword);
  2093. }
  2094. }
  2095. //---------------------------------------------------------------------
  2096. UnicodeString __fastcall TSessionData::GetHostNameExpanded()
  2097. {
  2098. return ::ExpandEnvironmentVariables(HostName);
  2099. }
  2100. //---------------------------------------------------------------------
  2101. void __fastcall TSessionData::SetPortNumber(int value)
  2102. {
  2103. SET_SESSION_PROPERTY(PortNumber);
  2104. }
  2105. //---------------------------------------------------------------------------
  2106. void __fastcall TSessionData::SetShell(UnicodeString value)
  2107. {
  2108. SET_SESSION_PROPERTY(Shell);
  2109. }
  2110. //---------------------------------------------------------------------------
  2111. void __fastcall TSessionData::SetSftpServer(UnicodeString value)
  2112. {
  2113. SET_SESSION_PROPERTY(SftpServer);
  2114. }
  2115. //---------------------------------------------------------------------------
  2116. void __fastcall TSessionData::SetClearAliases(bool value)
  2117. {
  2118. SET_SESSION_PROPERTY(ClearAliases);
  2119. }
  2120. //---------------------------------------------------------------------------
  2121. void __fastcall TSessionData::SetListingCommand(UnicodeString value)
  2122. {
  2123. SET_SESSION_PROPERTY(ListingCommand);
  2124. }
  2125. //---------------------------------------------------------------------------
  2126. void __fastcall TSessionData::SetIgnoreLsWarnings(bool value)
  2127. {
  2128. SET_SESSION_PROPERTY(IgnoreLsWarnings);
  2129. }
  2130. //---------------------------------------------------------------------------
  2131. void __fastcall TSessionData::SetUnsetNationalVars(bool value)
  2132. {
  2133. SET_SESSION_PROPERTY(UnsetNationalVars);
  2134. }
  2135. //---------------------------------------------------------------------
  2136. void __fastcall TSessionData::SetUserName(UnicodeString value)
  2137. {
  2138. // Avoid password recryption (what may popup master password prompt)
  2139. if (FUserName != value)
  2140. {
  2141. // UserName is key for password encryption
  2142. UnicodeString XPassword = Password;
  2143. UnicodeString XNewPassword = NewPassword;
  2144. SET_SESSION_PROPERTY(UserName);
  2145. Password = XPassword;
  2146. NewPassword = XNewPassword;
  2147. Shred(XPassword);
  2148. Shred(XNewPassword);
  2149. }
  2150. }
  2151. //---------------------------------------------------------------------
  2152. UnicodeString __fastcall TSessionData::GetUserNameExpanded()
  2153. {
  2154. return ::ExpandEnvironmentVariables(UserName);
  2155. }
  2156. //---------------------------------------------------------------------
  2157. void __fastcall TSessionData::SetPassword(UnicodeString avalue)
  2158. {
  2159. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  2160. SET_SESSION_PROPERTY(Password);
  2161. }
  2162. //---------------------------------------------------------------------
  2163. UnicodeString __fastcall TSessionData::GetPassword() const
  2164. {
  2165. return DecryptPassword(FPassword, UserName+HostName);
  2166. }
  2167. //---------------------------------------------------------------------
  2168. void __fastcall TSessionData::SetNewPassword(UnicodeString avalue)
  2169. {
  2170. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  2171. SET_SESSION_PROPERTY(NewPassword);
  2172. }
  2173. //---------------------------------------------------------------------
  2174. UnicodeString __fastcall TSessionData::GetNewPassword() const
  2175. {
  2176. return DecryptPassword(FNewPassword, UserName+HostName);
  2177. }
  2178. //---------------------------------------------------------------------
  2179. void __fastcall TSessionData::SetChangePassword(bool value)
  2180. {
  2181. SET_SESSION_PROPERTY(ChangePassword);
  2182. }
  2183. //---------------------------------------------------------------------
  2184. void __fastcall TSessionData::SetPingInterval(int value)
  2185. {
  2186. SET_SESSION_PROPERTY(PingInterval);
  2187. }
  2188. //---------------------------------------------------------------------
  2189. void __fastcall TSessionData::SetTryAgent(bool value)
  2190. {
  2191. SET_SESSION_PROPERTY(TryAgent);
  2192. }
  2193. //---------------------------------------------------------------------
  2194. void __fastcall TSessionData::SetAgentFwd(bool value)
  2195. {
  2196. SET_SESSION_PROPERTY(AgentFwd);
  2197. }
  2198. //---------------------------------------------------------------------
  2199. void __fastcall TSessionData::SetAuthTIS(bool value)
  2200. {
  2201. SET_SESSION_PROPERTY(AuthTIS);
  2202. }
  2203. //---------------------------------------------------------------------
  2204. void __fastcall TSessionData::SetAuthKI(bool value)
  2205. {
  2206. SET_SESSION_PROPERTY(AuthKI);
  2207. }
  2208. //---------------------------------------------------------------------
  2209. void __fastcall TSessionData::SetAuthKIPassword(bool value)
  2210. {
  2211. SET_SESSION_PROPERTY(AuthKIPassword);
  2212. }
  2213. //---------------------------------------------------------------------
  2214. void __fastcall TSessionData::SetAuthGSSAPI(bool value)
  2215. {
  2216. SET_SESSION_PROPERTY(AuthGSSAPI);
  2217. }
  2218. //---------------------------------------------------------------------
  2219. void __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)
  2220. {
  2221. SET_SESSION_PROPERTY(GSSAPIFwdTGT);
  2222. }
  2223. //---------------------------------------------------------------------
  2224. void __fastcall TSessionData::SetChangeUsername(bool value)
  2225. {
  2226. SET_SESSION_PROPERTY(ChangeUsername);
  2227. }
  2228. //---------------------------------------------------------------------
  2229. void __fastcall TSessionData::SetCompression(bool value)
  2230. {
  2231. SET_SESSION_PROPERTY(Compression);
  2232. }
  2233. //---------------------------------------------------------------------
  2234. void __fastcall TSessionData::SetSshProt(TSshProt value)
  2235. {
  2236. SET_SESSION_PROPERTY(SshProt);
  2237. }
  2238. //---------------------------------------------------------------------
  2239. void __fastcall TSessionData::SetSsh2DES(bool value)
  2240. {
  2241. SET_SESSION_PROPERTY(Ssh2DES);
  2242. }
  2243. //---------------------------------------------------------------------
  2244. void __fastcall TSessionData::SetSshNoUserAuth(bool value)
  2245. {
  2246. SET_SESSION_PROPERTY(SshNoUserAuth);
  2247. }
  2248. //---------------------------------------------------------------------
  2249. UnicodeString __fastcall TSessionData::GetSshProtStr()
  2250. {
  2251. return SshProtList[FSshProt];
  2252. }
  2253. //---------------------------------------------------------------------
  2254. bool __fastcall TSessionData::GetUsesSsh()
  2255. {
  2256. return IsSshProtocol(FSProtocol);
  2257. }
  2258. //---------------------------------------------------------------------
  2259. void __fastcall TSessionData::SetCipher(int Index, TCipher value)
  2260. {
  2261. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2262. SET_SESSION_PROPERTY(Ciphers[Index]);
  2263. }
  2264. //---------------------------------------------------------------------
  2265. TCipher __fastcall TSessionData::GetCipher(int Index) const
  2266. {
  2267. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2268. return FCiphers[Index];
  2269. }
  2270. //---------------------------------------------------------------------
  2271. template<class AlgoT>
  2272. void __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,
  2273. int Count, AlgoT WarnAlgo, UnicodeString value)
  2274. {
  2275. std::vector<bool> Used(Count); // initialized to false
  2276. std::vector<AlgoT> NewList(Count);
  2277. bool HasWarnAlgo = (WarnAlgo >= AlgoT());
  2278. const AlgoT * WarnPtr;
  2279. int WarnDefaultIndex;
  2280. if (!HasWarnAlgo)
  2281. {
  2282. WarnPtr = NULL;
  2283. WarnDefaultIndex = -1;
  2284. }
  2285. else
  2286. {
  2287. WarnPtr = std::find(DefaultList, DefaultList + Count, WarnAlgo);
  2288. DebugAssert(WarnPtr != NULL);
  2289. WarnDefaultIndex = (WarnPtr - DefaultList);
  2290. }
  2291. int Index = 0;
  2292. while (!value.IsEmpty())
  2293. {
  2294. UnicodeString AlgoStr = CutToChar(value, L',', true);
  2295. for (int Algo = 0; Algo < Count; Algo++)
  2296. {
  2297. if (!AlgoStr.CompareIC(Names[Algo]) &&
  2298. !Used[Algo] && DebugAlwaysTrue(Index < Count))
  2299. {
  2300. NewList[Index] = (AlgoT)Algo;
  2301. Used[Algo] = true;
  2302. Index++;
  2303. break;
  2304. }
  2305. }
  2306. }
  2307. if (HasWarnAlgo && !Used[WarnAlgo] && DebugAlwaysTrue(Index < Count))
  2308. {
  2309. NewList[Index] = WarnAlgo;
  2310. Used[WarnAlgo] = true;
  2311. Index++;
  2312. }
  2313. int WarnIndex = -1;
  2314. if (HasWarnAlgo)
  2315. {
  2316. WarnIndex = std::find(NewList.begin(), NewList.end(), WarnAlgo) - NewList.begin();
  2317. }
  2318. bool Priority = true;
  2319. for (int DefaultIndex = 0; (DefaultIndex < Count); DefaultIndex++)
  2320. {
  2321. AlgoT DefaultAlgo = DefaultList[DefaultIndex];
  2322. if (!Used[DefaultAlgo] && DebugAlwaysTrue(Index < Count))
  2323. {
  2324. int TargetIndex;
  2325. // Unused algs that are prioritized in the default list,
  2326. // should be merged before the existing custom list
  2327. if (Priority)
  2328. {
  2329. TargetIndex = DefaultIndex;
  2330. }
  2331. else
  2332. {
  2333. if (HasWarnAlgo && (DefaultIndex < WarnDefaultIndex))
  2334. {
  2335. TargetIndex = WarnIndex;
  2336. }
  2337. else
  2338. {
  2339. TargetIndex = Index;
  2340. }
  2341. }
  2342. NewList.insert(NewList.begin() + TargetIndex, DefaultAlgo);
  2343. DebugAssert(NewList.back() == AlgoT());
  2344. NewList.pop_back();
  2345. if (HasWarnAlgo && (TargetIndex <= WarnIndex))
  2346. {
  2347. WarnIndex++;
  2348. }
  2349. Index++;
  2350. }
  2351. else
  2352. {
  2353. Priority = false;
  2354. }
  2355. }
  2356. if (!std::equal(NewList.begin(), NewList.end(), List))
  2357. {
  2358. std::copy(NewList.begin(), NewList.end(), List);
  2359. Modify();
  2360. }
  2361. }
  2362. //---------------------------------------------------------------------
  2363. void __fastcall TSessionData::SetCipherList(UnicodeString value)
  2364. {
  2365. SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, cipWarn, value);
  2366. }
  2367. //---------------------------------------------------------------------
  2368. UnicodeString __fastcall TSessionData::GetCipherList() const
  2369. {
  2370. UnicodeString Result;
  2371. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  2372. {
  2373. Result += UnicodeString(Index ? L"," : L"") + CipherNames[Cipher[Index]];
  2374. }
  2375. return Result;
  2376. }
  2377. //---------------------------------------------------------------------
  2378. void __fastcall TSessionData::SetKex(int Index, TKex value)
  2379. {
  2380. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2381. SET_SESSION_PROPERTY(Kex[Index]);
  2382. }
  2383. //---------------------------------------------------------------------
  2384. TKex __fastcall TSessionData::GetKex(int Index) const
  2385. {
  2386. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2387. return FKex[Index];
  2388. }
  2389. //---------------------------------------------------------------------
  2390. void __fastcall TSessionData::SetKexList(UnicodeString value)
  2391. {
  2392. SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, kexWarn, value);
  2393. }
  2394. //---------------------------------------------------------------------
  2395. UnicodeString __fastcall TSessionData::GetKexList() const
  2396. {
  2397. UnicodeString Result;
  2398. for (int Index = 0; Index < KEX_COUNT; Index++)
  2399. {
  2400. Result += UnicodeString(Index ? L"," : L"") + KexNames[Kex[Index]];
  2401. }
  2402. return Result;
  2403. }
  2404. //---------------------------------------------------------------------
  2405. void __fastcall TSessionData::SetHostKeys(int Index, THostKey value)
  2406. {
  2407. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  2408. SET_SESSION_PROPERTY(HostKeys[Index]);
  2409. }
  2410. //---------------------------------------------------------------------
  2411. THostKey __fastcall TSessionData::GetHostKeys(int Index) const
  2412. {
  2413. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  2414. return FHostKeys[Index];
  2415. }
  2416. //---------------------------------------------------------------------
  2417. void __fastcall TSessionData::SetHostKeyList(UnicodeString value)
  2418. {
  2419. SetAlgoList(FHostKeys, DefaultHostKeyList, HostKeyNames, HOSTKEY_COUNT, hkWarn, value);
  2420. }
  2421. //---------------------------------------------------------------------
  2422. UnicodeString __fastcall TSessionData::GetHostKeyList() const
  2423. {
  2424. UnicodeString Result;
  2425. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  2426. {
  2427. Result += UnicodeString(Index ? L"," : L"") + HostKeyNames[HostKeys[Index]];
  2428. }
  2429. return Result;
  2430. }
  2431. //---------------------------------------------------------------------
  2432. void __fastcall TSessionData::SetGssLib(int Index, TGssLib value)
  2433. {
  2434. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  2435. SET_SESSION_PROPERTY(GssLib[Index]);
  2436. }
  2437. //---------------------------------------------------------------------
  2438. TGssLib __fastcall TSessionData::GetGssLib(int Index) const
  2439. {
  2440. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  2441. return FGssLib[Index];
  2442. }
  2443. //---------------------------------------------------------------------
  2444. void __fastcall TSessionData::SetGssLibList(UnicodeString value)
  2445. {
  2446. SetAlgoList(FGssLib, DefaultGssLibList, GssLibNames, GSSLIB_COUNT, TGssLib(-1), value);
  2447. }
  2448. //---------------------------------------------------------------------
  2449. UnicodeString __fastcall TSessionData::GetGssLibList() const
  2450. {
  2451. UnicodeString Result;
  2452. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  2453. {
  2454. Result += UnicodeString(Index ? L"," : L"") + GssLibNames[GssLib[Index]];
  2455. }
  2456. return Result;
  2457. }
  2458. //---------------------------------------------------------------------
  2459. void __fastcall TSessionData::SetGssLibCustom(UnicodeString value)
  2460. {
  2461. SET_SESSION_PROPERTY(GssLibCustom);
  2462. }
  2463. //---------------------------------------------------------------------
  2464. void __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)
  2465. {
  2466. if (FPublicKeyFile != value)
  2467. {
  2468. // PublicKeyFile is key for Passphrase encryption
  2469. UnicodeString XPassphrase = Passphrase;
  2470. // StripPathQuotes should not be needed as we do not feed quotes anymore
  2471. FPublicKeyFile = StripPathQuotes(value);
  2472. Modify();
  2473. Passphrase = XPassphrase;
  2474. Shred(XPassphrase);
  2475. }
  2476. }
  2477. //---------------------------------------------------------------------
  2478. void __fastcall TSessionData::SetPassphrase(UnicodeString avalue)
  2479. {
  2480. RawByteString value = EncryptPassword(avalue, PublicKeyFile);
  2481. SET_SESSION_PROPERTY(Passphrase);
  2482. }
  2483. //---------------------------------------------------------------------
  2484. UnicodeString __fastcall TSessionData::GetPassphrase() const
  2485. {
  2486. return DecryptPassword(FPassphrase, PublicKeyFile);
  2487. }
  2488. //---------------------------------------------------------------------
  2489. void __fastcall TSessionData::SetReturnVar(UnicodeString value)
  2490. {
  2491. SET_SESSION_PROPERTY(ReturnVar);
  2492. }
  2493. //---------------------------------------------------------------------------
  2494. void __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)
  2495. {
  2496. SET_SESSION_PROPERTY(LookupUserGroups);
  2497. }
  2498. //---------------------------------------------------------------------------
  2499. void __fastcall TSessionData::SetEOLType(TEOLType value)
  2500. {
  2501. SET_SESSION_PROPERTY(EOLType);
  2502. }
  2503. //---------------------------------------------------------------------------
  2504. void __fastcall TSessionData::SetTrimVMSVersions(bool value)
  2505. {
  2506. SET_SESSION_PROPERTY(TrimVMSVersions);
  2507. }
  2508. //---------------------------------------------------------------------------
  2509. TDateTime __fastcall TSessionData::GetTimeoutDT()
  2510. {
  2511. return SecToDateTime(Timeout);
  2512. }
  2513. //---------------------------------------------------------------------------
  2514. void __fastcall TSessionData::SetTimeout(int value)
  2515. {
  2516. SET_SESSION_PROPERTY(Timeout);
  2517. }
  2518. //---------------------------------------------------------------------------
  2519. void __fastcall TSessionData::SetFSProtocol(TFSProtocol value)
  2520. {
  2521. SET_SESSION_PROPERTY(FSProtocol);
  2522. }
  2523. //---------------------------------------------------------------------
  2524. UnicodeString __fastcall TSessionData::GetFSProtocolStr()
  2525. {
  2526. DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);
  2527. return FSProtocolNames[FSProtocol];
  2528. }
  2529. //---------------------------------------------------------------------------
  2530. void __fastcall TSessionData::SetDetectReturnVar(bool value)
  2531. {
  2532. if (value != DetectReturnVar)
  2533. {
  2534. ReturnVar = value ? L"" : L"$?";
  2535. }
  2536. }
  2537. //---------------------------------------------------------------------------
  2538. bool __fastcall TSessionData::GetDetectReturnVar()
  2539. {
  2540. return ReturnVar.IsEmpty();
  2541. }
  2542. //---------------------------------------------------------------------------
  2543. void __fastcall TSessionData::SetDefaultShell(bool value)
  2544. {
  2545. if (value != DefaultShell)
  2546. {
  2547. Shell = value ? L"" : L"/bin/bash";
  2548. }
  2549. }
  2550. //---------------------------------------------------------------------------
  2551. bool __fastcall TSessionData::GetDefaultShell()
  2552. {
  2553. return Shell.IsEmpty();
  2554. }
  2555. //---------------------------------------------------------------------------
  2556. void __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)
  2557. {
  2558. SET_SESSION_PROPERTY(PuttyProtocol);
  2559. }
  2560. //---------------------------------------------------------------------
  2561. UnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const
  2562. {
  2563. return DefaultStr(PuttyProtocol, PuttySshProtocol);
  2564. }
  2565. //---------------------------------------------------------------------
  2566. void __fastcall TSessionData::SetPingIntervalDT(TDateTime value)
  2567. {
  2568. unsigned short hour, min, sec, msec;
  2569. value.DecodeTime(&hour, &min, &sec, &msec);
  2570. PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;
  2571. }
  2572. //---------------------------------------------------------------------------
  2573. TDateTime __fastcall TSessionData::GetPingIntervalDT()
  2574. {
  2575. return SecToDateTime(PingInterval);
  2576. }
  2577. //---------------------------------------------------------------------------
  2578. void __fastcall TSessionData::SetPingType(TPingType value)
  2579. {
  2580. SET_SESSION_PROPERTY(PingType);
  2581. }
  2582. //---------------------------------------------------------------------------
  2583. void __fastcall TSessionData::SetAddressFamily(TAddressFamily value)
  2584. {
  2585. SET_SESSION_PROPERTY(AddressFamily);
  2586. }
  2587. //---------------------------------------------------------------------------
  2588. void __fastcall TSessionData::SetRekeyData(UnicodeString value)
  2589. {
  2590. SET_SESSION_PROPERTY(RekeyData);
  2591. }
  2592. //---------------------------------------------------------------------------
  2593. void __fastcall TSessionData::SetRekeyTime(unsigned int value)
  2594. {
  2595. SET_SESSION_PROPERTY(RekeyTime);
  2596. }
  2597. //---------------------------------------------------------------------
  2598. UnicodeString __fastcall TSessionData::GetDefaultSessionName()
  2599. {
  2600. if (!HostName.IsEmpty() && !UserName.IsEmpty())
  2601. {
  2602. // If we ever choose to include port number,
  2603. // we have to escape IPv6 literals in HostName
  2604. return FORMAT(L"%s@%s", (UserName, HostName));
  2605. }
  2606. else if (!HostName.IsEmpty())
  2607. {
  2608. return HostName;
  2609. }
  2610. else
  2611. {
  2612. return L"session";
  2613. }
  2614. }
  2615. //---------------------------------------------------------------------
  2616. UnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()
  2617. {
  2618. UnicodeString Result = Name;
  2619. if (Hidden)
  2620. {
  2621. Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());
  2622. }
  2623. return Result;
  2624. }
  2625. //---------------------------------------------------------------------
  2626. bool __fastcall TSessionData::HasSessionName()
  2627. {
  2628. return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName) && !IsWorkspace);
  2629. }
  2630. //---------------------------------------------------------------------
  2631. UnicodeString __fastcall TSessionData::GetSessionName()
  2632. {
  2633. UnicodeString Result;
  2634. if (HasSessionName())
  2635. {
  2636. Result = GetNameWithoutHiddenPrefix();
  2637. }
  2638. else
  2639. {
  2640. Result = DefaultSessionName;
  2641. }
  2642. return Result;
  2643. }
  2644. //---------------------------------------------------------------------
  2645. bool __fastcall TSessionData::IsSecure()
  2646. {
  2647. bool Result;
  2648. switch (FSProtocol)
  2649. {
  2650. case fsSCPonly:
  2651. case fsSFTP:
  2652. case fsSFTPonly:
  2653. Result = true;
  2654. break;
  2655. case fsFTP:
  2656. case fsWebDAV:
  2657. case fsS3:
  2658. Result = (Ftps != ftpsNone);
  2659. break;
  2660. default:
  2661. DebugFail();
  2662. break;
  2663. }
  2664. return Result;
  2665. }
  2666. //---------------------------------------------------------------------
  2667. UnicodeString __fastcall TSessionData::GetProtocolUrl()
  2668. {
  2669. UnicodeString Url;
  2670. switch (FSProtocol)
  2671. {
  2672. case fsSCPonly:
  2673. Url = ScpProtocol;
  2674. break;
  2675. default:
  2676. DebugFail();
  2677. // fallback
  2678. case fsSFTP:
  2679. case fsSFTPonly:
  2680. Url = SftpProtocol;
  2681. break;
  2682. case fsFTP:
  2683. if (Ftps == ftpsImplicit)
  2684. {
  2685. Url = FtpsProtocol;
  2686. }
  2687. else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))
  2688. {
  2689. Url = FtpesProtocol;
  2690. }
  2691. else
  2692. {
  2693. Url = FtpProtocol;
  2694. }
  2695. break;
  2696. case fsWebDAV:
  2697. if (Ftps == ftpsImplicit)
  2698. {
  2699. Url = WebDAVSProtocol;
  2700. }
  2701. else
  2702. {
  2703. Url = WebDAVProtocol;
  2704. }
  2705. break;
  2706. case fsS3:
  2707. Url = S3Protocol;
  2708. break;
  2709. }
  2710. Url += ProtocolSeparator;
  2711. return Url;
  2712. }
  2713. //---------------------------------------------------------------------
  2714. bool __fastcall IsIPv6Literal(const UnicodeString & HostName)
  2715. {
  2716. bool Result = (HostName.Pos(L":") > 0);
  2717. if (Result)
  2718. {
  2719. for (int Index = 1; Result && (Index <= HostName.Length()); Index++)
  2720. {
  2721. wchar_t C = HostName[Index];
  2722. Result = IsHex(C) || (C == L':');
  2723. }
  2724. }
  2725. return Result;
  2726. }
  2727. //---------------------------------------------------------------------
  2728. UnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP)
  2729. {
  2730. return L"[" + IP + L"]";
  2731. }
  2732. //---------------------------------------------------------------------
  2733. UnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)
  2734. {
  2735. UnicodeString Url;
  2736. if (FLAGSET(Flags, sufSpecific))
  2737. {
  2738. Url += WinSCPProtocolPrefix;
  2739. }
  2740. Url += GetProtocolUrl();
  2741. if (FLAGSET(Flags, sufUserName) && !UserNameExpanded.IsEmpty())
  2742. {
  2743. Url += EncodeUrlString(UserNameExpanded);
  2744. if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())
  2745. {
  2746. Url += L":" + EncodeUrlString(Password);
  2747. }
  2748. if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())
  2749. {
  2750. // Many SHA-256 fingeprints end with an equal sign and we do not really need it to be encoded, so avoid that.
  2751. // Also colons in TLS/SSL fingerprint do not really need encoding.
  2752. UnicodeString S = EncodeUrlString(NormalizeFingerprint(HostKey), L"=:");
  2753. Url +=
  2754. UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +
  2755. UnicodeString(UrlParamValueSeparator) + S;
  2756. }
  2757. Url += L"@";
  2758. }
  2759. DebugAssert(!HostNameExpanded.IsEmpty());
  2760. if (IsIPv6Literal(HostNameExpanded))
  2761. {
  2762. Url += EscapeIPv6Literal(HostNameExpanded);
  2763. }
  2764. else
  2765. {
  2766. Url += EncodeUrlString(HostNameExpanded);
  2767. }
  2768. if (PortNumber != DefaultPort(FSProtocol, Ftps))
  2769. {
  2770. Url += L":" + IntToStr(PortNumber);
  2771. }
  2772. Url += L"/";
  2773. return Url;
  2774. }
  2775. //---------------------------------------------------------------------
  2776. UnicodeString ScriptCommandOpenLink(TraceInitStr(ScriptCommandLink(L"open")));
  2777. //---------------------------------------------------------------------
  2778. void __fastcall TSessionData::AddSwitch(
  2779. UnicodeString & Result, const UnicodeString & Name, bool Rtf)
  2780. {
  2781. Result += RtfSwitch(Name, ScriptCommandOpenLink, Rtf);
  2782. }
  2783. //---------------------------------------------------------------------
  2784. void __fastcall TSessionData::AddSwitch(
  2785. UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf)
  2786. {
  2787. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  2788. }
  2789. //---------------------------------------------------------------------
  2790. void __fastcall TSessionData::AddSwitch(
  2791. UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf)
  2792. {
  2793. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  2794. }
  2795. //---------------------------------------------------------------------
  2796. void __fastcall TSessionData::LookupLastFingerprint()
  2797. {
  2798. UnicodeString FingerprintType;
  2799. if (IsSshProtocol(FSProtocol))
  2800. {
  2801. FingerprintType = SshFingerprintType;
  2802. }
  2803. else if (Ftps != ftpsNone)
  2804. {
  2805. FingerprintType = TlsFingerprintType;
  2806. }
  2807. if (!FingerprintType.IsEmpty())
  2808. {
  2809. HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);
  2810. }
  2811. }
  2812. //---------------------------------------------------------------------
  2813. UnicodeString __fastcall TSessionData::GenerateOpenCommandArgs(bool Rtf)
  2814. {
  2815. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  2816. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  2817. SessionData->Assign(this);
  2818. UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);
  2819. // Before we reset the FSProtocol
  2820. bool AUsesSsh = SessionData->UsesSsh;
  2821. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  2822. if (SessionData->FSProtocol != fsSFTPonly)
  2823. {
  2824. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  2825. }
  2826. SessionData->HostName = FactoryDefaults->HostName;
  2827. SessionData->PortNumber = FactoryDefaults->PortNumber;
  2828. SessionData->UserName = FactoryDefaults->UserName;
  2829. SessionData->Password = FactoryDefaults->Password;
  2830. SessionData->CopyNonCoreData(FactoryDefaults.get());
  2831. SessionData->Ftps = FactoryDefaults->Ftps;
  2832. if (SessionData->HostKey != FactoryDefaults->HostKey)
  2833. {
  2834. UnicodeString SwitchName = AUsesSsh ? L"hostkey" : L"certificate";
  2835. AddSwitch(Result, SwitchName, SessionData->HostKey, Rtf);
  2836. SessionData->HostKey = FactoryDefaults->HostKey;
  2837. }
  2838. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  2839. {
  2840. AddSwitch(Result, L"privatekey", SessionData->PublicKeyFile, Rtf);
  2841. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  2842. }
  2843. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  2844. {
  2845. AddSwitch(Result, L"clientcert", SessionData->TlsCertificateFile, Rtf);
  2846. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  2847. }
  2848. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  2849. {
  2850. AddSwitch(Result, PassphraseOption, SessionData->Passphrase, Rtf);
  2851. SessionData->Passphrase = FactoryDefaults->Passphrase;
  2852. }
  2853. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  2854. {
  2855. AddSwitch(Result, L"passive", SessionData->FtpPasvMode ? 1 : 0, Rtf);
  2856. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  2857. }
  2858. if (SessionData->Timeout != FactoryDefaults->Timeout)
  2859. {
  2860. AddSwitch(Result, L"timeout", SessionData->Timeout, Rtf);
  2861. SessionData->Timeout = FactoryDefaults->Timeout;
  2862. }
  2863. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get()));
  2864. if (RawSettings->Count > 0)
  2865. {
  2866. AddSwitch(Result, RawSettingsOption, Rtf);
  2867. for (int Index = 0; Index < RawSettings->Count; Index++)
  2868. {
  2869. UnicodeString Name = RawSettings->Names[Index];
  2870. UnicodeString Value = RawSettings->ValueFromIndex[Index];
  2871. // Do not quote if it is all-numeric
  2872. if (IntToStr(StrToIntDef(Value, -1)) != Value)
  2873. {
  2874. Value = FORMAT(L"\"%s\"", (EscapeParam(Value)));
  2875. }
  2876. Result += FORMAT(L" %s=%s", (Name, Value));
  2877. }
  2878. }
  2879. return Result;
  2880. }
  2881. //---------------------------------------------------------------------
  2882. UnicodeString SessionOptionsClassName(L"SessionOptions");
  2883. //---------------------------------------------------------------------
  2884. void __fastcall TSessionData::AddAssemblyProperty(
  2885. UnicodeString & Result, TAssemblyLanguage Language,
  2886. const UnicodeString & Name, const UnicodeString & Type,
  2887. const UnicodeString & Member)
  2888. {
  2889. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Type, Member, false);
  2890. }
  2891. //---------------------------------------------------------------------
  2892. void __fastcall TSessionData::AddAssemblyProperty(
  2893. UnicodeString & Result, TAssemblyLanguage Language,
  2894. const UnicodeString & Name, const UnicodeString & Value)
  2895. {
  2896. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  2897. }
  2898. //---------------------------------------------------------------------
  2899. void __fastcall TSessionData::AddAssemblyProperty(
  2900. UnicodeString & Result, TAssemblyLanguage Language,
  2901. const UnicodeString & Name, int Value)
  2902. {
  2903. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  2904. }
  2905. //---------------------------------------------------------------------
  2906. void __fastcall TSessionData::AddAssemblyProperty(
  2907. UnicodeString & Result, TAssemblyLanguage Language,
  2908. const UnicodeString & Name, bool Value)
  2909. {
  2910. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  2911. }
  2912. //---------------------------------------------------------------------
  2913. void __fastcall TSessionData::GenerateAssemblyCode(
  2914. TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent)
  2915. {
  2916. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  2917. std::unique_ptr<TSessionData> SessionData(Clone());
  2918. switch (Language)
  2919. {
  2920. case alCSharp:
  2921. case alVBNET:
  2922. // noop
  2923. break;
  2924. case alPowerShell:
  2925. Head +=
  2926. AssemblyCommentLine(Language, LoadStr(CODE_PS_ADD_TYPE)) +
  2927. RtfKeyword(L"Add-Type") + RtfText(" -Path ") + AssemblyString(Language, "WinSCPnet.dll") + RtfPara +
  2928. RtfPara;
  2929. break;
  2930. default:
  2931. DebugFail();
  2932. break;
  2933. }
  2934. Head +=
  2935. AssemblyCommentLine(Language, LoadStr(CODE_SESSION_OPTIONS)) +
  2936. AssemblyNewClassInstanceStart(Language, SessionOptionsClassName, false);
  2937. UnicodeString ProtocolMember;
  2938. switch (SessionData->FSProtocol)
  2939. {
  2940. case fsSCPonly:
  2941. ProtocolMember = "Scp";
  2942. break;
  2943. default:
  2944. DebugFail();
  2945. // fallback
  2946. case fsSFTP:
  2947. case fsSFTPonly:
  2948. ProtocolMember = "Sftp";
  2949. break;
  2950. case fsFTP:
  2951. ProtocolMember = "Ftp";
  2952. break;
  2953. case fsWebDAV:
  2954. ProtocolMember = "Webdav";
  2955. break;
  2956. case fsS3:
  2957. ProtocolMember = "S3";
  2958. break;
  2959. }
  2960. // Before we reset the FSProtocol
  2961. bool AUsesSsh = SessionData->UsesSsh;
  2962. // Protocol is set unconditionally, we want even the default SFTP
  2963. AddAssemblyProperty(Head, Language, L"Protocol", L"Protocol", ProtocolMember);
  2964. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  2965. if (SessionData->FSProtocol != fsSFTPonly)
  2966. {
  2967. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  2968. }
  2969. if (SessionData->HostName != FactoryDefaults->HostName)
  2970. {
  2971. AddAssemblyProperty(Head, Language, L"HostName", HostName);
  2972. SessionData->HostName = FactoryDefaults->HostName;
  2973. }
  2974. if (SessionData->PortNumber != FactoryDefaults->PortNumber)
  2975. {
  2976. AddAssemblyProperty(Head, Language, L"PortNumber", PortNumber);
  2977. SessionData->PortNumber = FactoryDefaults->PortNumber;
  2978. }
  2979. if (SessionData->UserName != FactoryDefaults->UserName)
  2980. {
  2981. AddAssemblyProperty(Head, Language, L"UserName", UserName);
  2982. SessionData->UserName = FactoryDefaults->UserName;
  2983. }
  2984. if (SessionData->Password != FactoryDefaults->Password)
  2985. {
  2986. AddAssemblyProperty(Head, Language, L"Password", Password);
  2987. SessionData->Password = FactoryDefaults->Password;
  2988. }
  2989. SessionData->CopyNonCoreData(FactoryDefaults.get());
  2990. if (SessionData->Ftps != FactoryDefaults->Ftps)
  2991. {
  2992. // SessionData->FSProtocol is reset already
  2993. switch (FSProtocol)
  2994. {
  2995. case fsFTP:
  2996. {
  2997. UnicodeString FtpSecureMember;
  2998. switch (SessionData->Ftps)
  2999. {
  3000. case ftpsNone:
  3001. // noop
  3002. break;
  3003. case ftpsImplicit:
  3004. FtpSecureMember = L"Implicit";
  3005. break;
  3006. case ftpsExplicitTls:
  3007. case ftpsExplicitSsl:
  3008. FtpSecureMember = L"Explicit";
  3009. break;
  3010. default:
  3011. DebugFail();
  3012. break;
  3013. }
  3014. AddAssemblyProperty(Head, Language, L"FtpSecure", L"FtpSecure", FtpSecureMember);
  3015. }
  3016. break;
  3017. case fsWebDAV:
  3018. AddAssemblyProperty(Head, Language, L"WebdavSecure", (SessionData->Ftps != ftpsNone));
  3019. break;
  3020. case fsS3:
  3021. // implicit
  3022. break;
  3023. default:
  3024. DebugFail();
  3025. break;
  3026. }
  3027. SessionData->Ftps = FactoryDefaults->Ftps;
  3028. }
  3029. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3030. {
  3031. UnicodeString PropertyName = AUsesSsh ? L"SshHostKeyFingerprint" : L"TlsHostCertificateFingerprint";
  3032. AddAssemblyProperty(Head, Language, PropertyName, SessionData->HostKey);
  3033. SessionData->HostKey = FactoryDefaults->HostKey;
  3034. }
  3035. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3036. {
  3037. AddAssemblyProperty(Head, Language, L"SshPrivateKeyPath", SessionData->PublicKeyFile);
  3038. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3039. }
  3040. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3041. {
  3042. AddAssemblyProperty(Head, Language, L"TlsClientCertificatePath", SessionData->TlsCertificateFile);
  3043. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3044. }
  3045. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3046. {
  3047. AddAssemblyProperty(Head, Language, L"PrivateKeyPassphrase", SessionData->Passphrase);
  3048. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3049. }
  3050. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3051. {
  3052. AddAssemblyProperty(Head, Language, L"FtpMode", L"FtpMode", (SessionData->FtpPasvMode ? L"Passive" : L"Active"));
  3053. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3054. }
  3055. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3056. {
  3057. AddAssemblyProperty(Head, Language, L"TimeoutInMilliseconds", SessionData->Timeout * 1000);
  3058. SessionData->Timeout = FactoryDefaults->Timeout;
  3059. }
  3060. switch (Language)
  3061. {
  3062. case alCSharp:
  3063. case alPowerShell:
  3064. Head += AssemblyNewClassInstanceEnd(Language, false);
  3065. break;
  3066. case alVBNET:
  3067. // noop
  3068. // Ending With only after AddRawSettings
  3069. break;
  3070. }
  3071. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get()));
  3072. UnicodeString SessionOptionsVariableName = AssemblyVariableName(Language, SessionOptionsClassName);
  3073. if (RawSettings->Count > 0)
  3074. {
  3075. Head += RtfPara;
  3076. for (int Index = 0; Index < RawSettings->Count; Index++)
  3077. {
  3078. UnicodeString Name = RawSettings->Names[Index];
  3079. UnicodeString Value = RawSettings->ValueFromIndex[Index];
  3080. UnicodeString AddRawSettingsMethod =
  3081. RtfLibraryMethod(SessionOptionsClassName, L"AddRawSettings", false) +
  3082. FORMAT(L"(%s, %s)", (AssemblyString(Language, Name), AssemblyString(Language, Value)));
  3083. switch (Language)
  3084. {
  3085. case alCSharp:
  3086. Head += RtfText(SessionOptionsVariableName + L".") + AddRawSettingsMethod + RtfText(L";") + RtfPara;
  3087. break;
  3088. case alVBNET:
  3089. Head += RtfText(L" .") + AddRawSettingsMethod + RtfPara;
  3090. break;
  3091. case alPowerShell:
  3092. Head += RtfText(SessionOptionsVariableName + L".") + AddRawSettingsMethod + RtfPara;
  3093. break;
  3094. }
  3095. }
  3096. }
  3097. UnicodeString Indentation = L" ";
  3098. UnicodeString SessionVariableName = AssemblyVariableName(Language, SessionClassName);
  3099. UnicodeString RtfSessionClass = RtfLibraryClass(SessionClassName);
  3100. UnicodeString RtfSessionOpenMethod = RtfLibraryMethod(SessionClassName, L"Open", false);
  3101. UnicodeString NewSessionInstance = AssemblyNewClassInstance(Language, SessionClassName, false);
  3102. UnicodeString OpenCall =
  3103. Indentation + AssemblyCommentLine(Language, LoadStr(CODE_CONNECT)) +
  3104. Indentation + RtfText(SessionVariableName + L".") + RtfSessionOpenMethod + RtfText(L"(" + SessionOptionsVariableName + L")") +
  3105. AssemblyStatementSeparator(Language) + RtfPara;
  3106. switch (Language)
  3107. {
  3108. case alCSharp:
  3109. Head +=
  3110. RtfPara +
  3111. RtfKeyword(L"using") + RtfText(" (") + NewSessionInstance + RtfText(L"())") + RtfPara +
  3112. RtfText(L"{") + RtfPara +
  3113. OpenCall;
  3114. Tail =
  3115. RtfText(L"}") + RtfPara;
  3116. break;
  3117. case alVBNET:
  3118. Head +=
  3119. AssemblyNewClassInstanceEnd(Language, false) +
  3120. RtfPara +
  3121. RtfKeyword(L"Using") + RtfText(L" ") + NewSessionInstance + RtfPara +
  3122. OpenCall;
  3123. Tail =
  3124. RtfKeyword(L"End Using");
  3125. break;
  3126. case alPowerShell:
  3127. Head +=
  3128. RtfPara +
  3129. NewSessionInstance + RtfPara +
  3130. RtfPara +
  3131. RtfKeyword(L"try") + RtfPara +
  3132. RtfText(L"{") + RtfPara +
  3133. OpenCall;
  3134. Tail =
  3135. RtfText(L"}") + RtfPara +
  3136. RtfKeyword(L"finally") + RtfPara +
  3137. RtfText(L"{") + RtfPara +
  3138. RtfText(Indentation + SessionVariableName + L".") +
  3139. RtfLibraryMethod(SessionClassName, L"Dispose", false) + RtfText(L"()") + RtfPara +
  3140. RtfText(L"}") + RtfPara;
  3141. break;
  3142. }
  3143. Head += RtfPara;
  3144. Indent = 4; // the same for all languages so far
  3145. }
  3146. //---------------------------------------------------------------------
  3147. void __fastcall TSessionData::SetTimeDifference(TDateTime value)
  3148. {
  3149. SET_SESSION_PROPERTY(TimeDifference);
  3150. }
  3151. //---------------------------------------------------------------------
  3152. void __fastcall TSessionData::SetTimeDifferenceAuto(bool value)
  3153. {
  3154. SET_SESSION_PROPERTY(TimeDifferenceAuto);
  3155. }
  3156. //---------------------------------------------------------------------
  3157. void __fastcall TSessionData::SetLocalDirectory(UnicodeString value)
  3158. {
  3159. SET_SESSION_PROPERTY(LocalDirectory);
  3160. }
  3161. //---------------------------------------------------------------------
  3162. void __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)
  3163. {
  3164. SET_SESSION_PROPERTY(RemoteDirectory);
  3165. }
  3166. //---------------------------------------------------------------------
  3167. void __fastcall TSessionData::SetSynchronizeBrowsing(bool value)
  3168. {
  3169. SET_SESSION_PROPERTY(SynchronizeBrowsing);
  3170. }
  3171. //---------------------------------------------------------------------
  3172. void __fastcall TSessionData::SetUpdateDirectories(bool value)
  3173. {
  3174. SET_SESSION_PROPERTY(UpdateDirectories);
  3175. }
  3176. //---------------------------------------------------------------------
  3177. void __fastcall TSessionData::SetCacheDirectories(bool value)
  3178. {
  3179. SET_SESSION_PROPERTY(CacheDirectories);
  3180. }
  3181. //---------------------------------------------------------------------
  3182. void __fastcall TSessionData::SetCacheDirectoryChanges(bool value)
  3183. {
  3184. SET_SESSION_PROPERTY(CacheDirectoryChanges);
  3185. }
  3186. //---------------------------------------------------------------------
  3187. void __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)
  3188. {
  3189. SET_SESSION_PROPERTY(PreserveDirectoryChanges);
  3190. }
  3191. //---------------------------------------------------------------------
  3192. void __fastcall TSessionData::SetResolveSymlinks(bool value)
  3193. {
  3194. SET_SESSION_PROPERTY(ResolveSymlinks);
  3195. }
  3196. //---------------------------------------------------------------------
  3197. void __fastcall TSessionData::SetFollowDirectorySymlinks(bool value)
  3198. {
  3199. SET_SESSION_PROPERTY(FollowDirectorySymlinks);
  3200. }
  3201. //---------------------------------------------------------------------------
  3202. void __fastcall TSessionData::SetDSTMode(TDSTMode value)
  3203. {
  3204. SET_SESSION_PROPERTY(DSTMode);
  3205. }
  3206. //---------------------------------------------------------------------------
  3207. void __fastcall TSessionData::SetDeleteToRecycleBin(bool value)
  3208. {
  3209. SET_SESSION_PROPERTY(DeleteToRecycleBin);
  3210. }
  3211. //---------------------------------------------------------------------------
  3212. void __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)
  3213. {
  3214. SET_SESSION_PROPERTY(OverwrittenToRecycleBin);
  3215. }
  3216. //---------------------------------------------------------------------------
  3217. void __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)
  3218. {
  3219. SET_SESSION_PROPERTY(RecycleBinPath);
  3220. }
  3221. //---------------------------------------------------------------------------
  3222. void __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)
  3223. {
  3224. SET_SESSION_PROPERTY(PostLoginCommands);
  3225. }
  3226. //---------------------------------------------------------------------
  3227. void __fastcall TSessionData::SetLockInHome(bool value)
  3228. {
  3229. SET_SESSION_PROPERTY(LockInHome);
  3230. }
  3231. //---------------------------------------------------------------------
  3232. void __fastcall TSessionData::SetSpecial(bool value)
  3233. {
  3234. SET_SESSION_PROPERTY(Special);
  3235. }
  3236. //---------------------------------------------------------------------------
  3237. void __fastcall TSessionData::SetScp1Compatibility(bool value)
  3238. {
  3239. SET_SESSION_PROPERTY(Scp1Compatibility);
  3240. }
  3241. //---------------------------------------------------------------------
  3242. void __fastcall TSessionData::SetTcpNoDelay(bool value)
  3243. {
  3244. SET_SESSION_PROPERTY(TcpNoDelay);
  3245. }
  3246. //---------------------------------------------------------------------
  3247. void __fastcall TSessionData::SetSendBuf(int value)
  3248. {
  3249. SET_SESSION_PROPERTY(SendBuf);
  3250. }
  3251. //---------------------------------------------------------------------
  3252. void __fastcall TSessionData::SetSshSimple(bool value)
  3253. {
  3254. SET_SESSION_PROPERTY(SshSimple);
  3255. }
  3256. //---------------------------------------------------------------------
  3257. void __fastcall TSessionData::SetProxyMethod(TProxyMethod value)
  3258. {
  3259. SET_SESSION_PROPERTY(ProxyMethod);
  3260. }
  3261. //---------------------------------------------------------------------
  3262. void __fastcall TSessionData::SetProxyHost(UnicodeString value)
  3263. {
  3264. SET_SESSION_PROPERTY(ProxyHost);
  3265. }
  3266. //---------------------------------------------------------------------
  3267. void __fastcall TSessionData::SetProxyPort(int value)
  3268. {
  3269. SET_SESSION_PROPERTY(ProxyPort);
  3270. }
  3271. //---------------------------------------------------------------------
  3272. void __fastcall TSessionData::SetProxyUsername(UnicodeString value)
  3273. {
  3274. SET_SESSION_PROPERTY(ProxyUsername);
  3275. }
  3276. //---------------------------------------------------------------------
  3277. void __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)
  3278. {
  3279. RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);
  3280. SET_SESSION_PROPERTY(ProxyPassword);
  3281. }
  3282. //---------------------------------------------------------------------
  3283. UnicodeString __fastcall TSessionData::GetProxyPassword() const
  3284. {
  3285. return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);
  3286. }
  3287. //---------------------------------------------------------------------
  3288. void __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)
  3289. {
  3290. SET_SESSION_PROPERTY(ProxyTelnetCommand);
  3291. }
  3292. //---------------------------------------------------------------------
  3293. void __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)
  3294. {
  3295. SET_SESSION_PROPERTY(ProxyLocalCommand);
  3296. }
  3297. //---------------------------------------------------------------------
  3298. void __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)
  3299. {
  3300. SET_SESSION_PROPERTY(ProxyDNS);
  3301. }
  3302. //---------------------------------------------------------------------
  3303. void __fastcall TSessionData::SetProxyLocalhost(bool value)
  3304. {
  3305. SET_SESSION_PROPERTY(ProxyLocalhost);
  3306. }
  3307. //---------------------------------------------------------------------
  3308. void __fastcall TSessionData::SetFtpProxyLogonType(int value)
  3309. {
  3310. SET_SESSION_PROPERTY(FtpProxyLogonType);
  3311. }
  3312. //---------------------------------------------------------------------
  3313. void __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)
  3314. {
  3315. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  3316. SET_SESSION_PROPERTY(Bugs[Bug]);
  3317. }
  3318. //---------------------------------------------------------------------
  3319. TAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const
  3320. {
  3321. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  3322. return FBugs[Bug];
  3323. }
  3324. //---------------------------------------------------------------------
  3325. void __fastcall TSessionData::SetCustomParam1(UnicodeString value)
  3326. {
  3327. SET_SESSION_PROPERTY(CustomParam1);
  3328. }
  3329. //---------------------------------------------------------------------
  3330. void __fastcall TSessionData::SetCustomParam2(UnicodeString value)
  3331. {
  3332. SET_SESSION_PROPERTY(CustomParam2);
  3333. }
  3334. //---------------------------------------------------------------------
  3335. void __fastcall TSessionData::SetSFTPDownloadQueue(int value)
  3336. {
  3337. SET_SESSION_PROPERTY(SFTPDownloadQueue);
  3338. }
  3339. //---------------------------------------------------------------------
  3340. void __fastcall TSessionData::SetSFTPUploadQueue(int value)
  3341. {
  3342. SET_SESSION_PROPERTY(SFTPUploadQueue);
  3343. }
  3344. //---------------------------------------------------------------------
  3345. void __fastcall TSessionData::SetSFTPListingQueue(int value)
  3346. {
  3347. SET_SESSION_PROPERTY(SFTPListingQueue);
  3348. }
  3349. //---------------------------------------------------------------------
  3350. void __fastcall TSessionData::SetSFTPMaxVersion(int value)
  3351. {
  3352. SET_SESSION_PROPERTY(SFTPMaxVersion);
  3353. }
  3354. //---------------------------------------------------------------------
  3355. void __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)
  3356. {
  3357. SET_SESSION_PROPERTY(SFTPMaxPacketSize);
  3358. }
  3359. //---------------------------------------------------------------------
  3360. void __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)
  3361. {
  3362. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  3363. SET_SESSION_PROPERTY(SFTPBugs[Bug]);
  3364. }
  3365. //---------------------------------------------------------------------
  3366. TAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const
  3367. {
  3368. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  3369. return FSFTPBugs[Bug];
  3370. }
  3371. //---------------------------------------------------------------------
  3372. void __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)
  3373. {
  3374. SET_SESSION_PROPERTY(SCPLsFullTime);
  3375. }
  3376. //---------------------------------------------------------------------------
  3377. void __fastcall TSessionData::SetColor(int value)
  3378. {
  3379. SET_SESSION_PROPERTY(Color);
  3380. }
  3381. //---------------------------------------------------------------------------
  3382. void __fastcall TSessionData::SetTunnel(bool value)
  3383. {
  3384. SET_SESSION_PROPERTY(Tunnel);
  3385. }
  3386. //---------------------------------------------------------------------
  3387. void __fastcall TSessionData::SetTunnelHostName(UnicodeString value)
  3388. {
  3389. if (FTunnelHostName != value)
  3390. {
  3391. // HostName is key for password encryption
  3392. UnicodeString XTunnelPassword = TunnelPassword;
  3393. int P = value.LastDelimiter(L"@");
  3394. if (P > 0)
  3395. {
  3396. TunnelUserName = value.SubString(1, P - 1);
  3397. value = value.SubString(P + 1, value.Length() - P);
  3398. }
  3399. FTunnelHostName = value;
  3400. Modify();
  3401. TunnelPassword = XTunnelPassword;
  3402. Shred(XTunnelPassword);
  3403. }
  3404. }
  3405. //---------------------------------------------------------------------
  3406. void __fastcall TSessionData::SetTunnelPortNumber(int value)
  3407. {
  3408. SET_SESSION_PROPERTY(TunnelPortNumber);
  3409. }
  3410. //---------------------------------------------------------------------
  3411. void __fastcall TSessionData::SetTunnelUserName(UnicodeString value)
  3412. {
  3413. // Avoid password recryption (what may popup master password prompt)
  3414. if (FTunnelUserName != value)
  3415. {
  3416. // TunnelUserName is key for password encryption
  3417. UnicodeString XTunnelPassword = TunnelPassword;
  3418. SET_SESSION_PROPERTY(TunnelUserName);
  3419. TunnelPassword = XTunnelPassword;
  3420. Shred(XTunnelPassword);
  3421. }
  3422. }
  3423. //---------------------------------------------------------------------
  3424. void __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)
  3425. {
  3426. RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);
  3427. SET_SESSION_PROPERTY(TunnelPassword);
  3428. }
  3429. //---------------------------------------------------------------------
  3430. UnicodeString __fastcall TSessionData::GetTunnelPassword() const
  3431. {
  3432. return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);
  3433. }
  3434. //---------------------------------------------------------------------
  3435. void __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)
  3436. {
  3437. if (FTunnelPublicKeyFile != value)
  3438. {
  3439. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3440. FTunnelPublicKeyFile = StripPathQuotes(value);
  3441. Modify();
  3442. }
  3443. }
  3444. //---------------------------------------------------------------------
  3445. void __fastcall TSessionData::SetTunnelLocalPortNumber(int value)
  3446. {
  3447. SET_SESSION_PROPERTY(TunnelLocalPortNumber);
  3448. }
  3449. //---------------------------------------------------------------------
  3450. bool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()
  3451. {
  3452. return (FTunnelLocalPortNumber <= 0);
  3453. }
  3454. //---------------------------------------------------------------------
  3455. void __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)
  3456. {
  3457. SET_SESSION_PROPERTY(TunnelPortFwd);
  3458. }
  3459. //---------------------------------------------------------------------
  3460. void __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)
  3461. {
  3462. SET_SESSION_PROPERTY(TunnelHostKey);
  3463. }
  3464. //---------------------------------------------------------------------
  3465. void __fastcall TSessionData::SetFtpPasvMode(bool value)
  3466. {
  3467. SET_SESSION_PROPERTY(FtpPasvMode);
  3468. }
  3469. //---------------------------------------------------------------------
  3470. void __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)
  3471. {
  3472. SET_SESSION_PROPERTY(FtpForcePasvIp);
  3473. }
  3474. //---------------------------------------------------------------------
  3475. void __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)
  3476. {
  3477. SET_SESSION_PROPERTY(FtpUseMlsd);
  3478. }
  3479. //---------------------------------------------------------------------
  3480. void __fastcall TSessionData::SetFtpAccount(UnicodeString value)
  3481. {
  3482. SET_SESSION_PROPERTY(FtpAccount);
  3483. }
  3484. //---------------------------------------------------------------------
  3485. void __fastcall TSessionData::SetFtpPingInterval(int value)
  3486. {
  3487. SET_SESSION_PROPERTY(FtpPingInterval);
  3488. }
  3489. //---------------------------------------------------------------------------
  3490. TDateTime __fastcall TSessionData::GetFtpPingIntervalDT()
  3491. {
  3492. return SecToDateTime(FtpPingInterval);
  3493. }
  3494. //---------------------------------------------------------------------------
  3495. void __fastcall TSessionData::SetFtpPingType(TPingType value)
  3496. {
  3497. SET_SESSION_PROPERTY(FtpPingType);
  3498. }
  3499. //---------------------------------------------------------------------------
  3500. void __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)
  3501. {
  3502. SET_SESSION_PROPERTY(FtpTransferActiveImmediately);
  3503. }
  3504. //---------------------------------------------------------------------------
  3505. void __fastcall TSessionData::SetFtps(TFtps value)
  3506. {
  3507. SET_SESSION_PROPERTY(Ftps);
  3508. }
  3509. //---------------------------------------------------------------------------
  3510. void __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)
  3511. {
  3512. SET_SESSION_PROPERTY(MinTlsVersion);
  3513. }
  3514. //---------------------------------------------------------------------------
  3515. void __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)
  3516. {
  3517. SET_SESSION_PROPERTY(MaxTlsVersion);
  3518. }
  3519. //---------------------------------------------------------------------------
  3520. void __fastcall TSessionData::SetLogicalHostName(UnicodeString value)
  3521. {
  3522. SET_SESSION_PROPERTY(LogicalHostName);
  3523. }
  3524. //---------------------------------------------------------------------
  3525. void __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)
  3526. {
  3527. SET_SESSION_PROPERTY(FtpListAll);
  3528. }
  3529. //---------------------------------------------------------------------
  3530. void __fastcall TSessionData::SetFtpHost(TAutoSwitch value)
  3531. {
  3532. SET_SESSION_PROPERTY(FtpHost);
  3533. }
  3534. //---------------------------------------------------------------------
  3535. void __fastcall TSessionData::SetFtpDeleteFromCwd(TAutoSwitch value)
  3536. {
  3537. SET_SESSION_PROPERTY(FtpDeleteFromCwd);
  3538. }
  3539. //---------------------------------------------------------------------
  3540. void __fastcall TSessionData::SetSslSessionReuse(bool value)
  3541. {
  3542. SET_SESSION_PROPERTY(SslSessionReuse);
  3543. }
  3544. //---------------------------------------------------------------------
  3545. void __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)
  3546. {
  3547. SET_SESSION_PROPERTY(TlsCertificateFile);
  3548. }
  3549. //---------------------------------------------------------------------
  3550. void __fastcall TSessionData::SetNotUtf(TAutoSwitch value)
  3551. {
  3552. SET_SESSION_PROPERTY(NotUtf);
  3553. }
  3554. //---------------------------------------------------------------------
  3555. void __fastcall TSessionData::SetInternalEditorEncoding(int value)
  3556. {
  3557. SET_SESSION_PROPERTY(InternalEditorEncoding);
  3558. }
  3559. //---------------------------------------------------------------------
  3560. void __fastcall TSessionData::SetS3DefaultRegion(UnicodeString value)
  3561. {
  3562. SET_SESSION_PROPERTY(S3DefaultRegion);
  3563. }
  3564. //---------------------------------------------------------------------
  3565. void __fastcall TSessionData::SetIsWorkspace(bool value)
  3566. {
  3567. SET_SESSION_PROPERTY(IsWorkspace);
  3568. }
  3569. //---------------------------------------------------------------------
  3570. void __fastcall TSessionData::SetLink(UnicodeString value)
  3571. {
  3572. SET_SESSION_PROPERTY(Link);
  3573. }
  3574. //---------------------------------------------------------------------
  3575. void __fastcall TSessionData::SetHostKey(UnicodeString value)
  3576. {
  3577. SET_SESSION_PROPERTY(HostKey);
  3578. }
  3579. //---------------------------------------------------------------------
  3580. void __fastcall TSessionData::SetNote(UnicodeString value)
  3581. {
  3582. SET_SESSION_PROPERTY(Note);
  3583. }
  3584. //---------------------------------------------------------------------
  3585. void __fastcall TSessionData::SetWinTitle(UnicodeString value)
  3586. {
  3587. SET_SESSION_PROPERTY(WinTitle);
  3588. }
  3589. //---------------------------------------------------------------------
  3590. UnicodeString __fastcall TSessionData::GetInfoTip()
  3591. {
  3592. if (UsesSsh)
  3593. {
  3594. return FMTLOAD(SESSION_INFO_TIP2,
  3595. (HostName, UserName,
  3596. (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),
  3597. FSProtocolStr));
  3598. }
  3599. else
  3600. {
  3601. return FMTLOAD(SESSION_INFO_TIP_NO_SSH,
  3602. (HostName, UserName, FSProtocolStr));
  3603. }
  3604. }
  3605. //---------------------------------------------------------------------
  3606. UnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)
  3607. {
  3608. UnicodeString Result = Name;
  3609. int P = Result.LastDelimiter(L"/");
  3610. if (P > 0)
  3611. {
  3612. Result.Delete(1, P);
  3613. }
  3614. return Result;
  3615. }
  3616. //---------------------------------------------------------------------
  3617. UnicodeString __fastcall TSessionData::GetLocalName()
  3618. {
  3619. UnicodeString Result;
  3620. if (HasSessionName())
  3621. {
  3622. Result = ExtractLocalName(Name);
  3623. }
  3624. else
  3625. {
  3626. Result = DefaultSessionName;
  3627. }
  3628. return Result;
  3629. }
  3630. //---------------------------------------------------------------------
  3631. UnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)
  3632. {
  3633. UnicodeString Result;
  3634. int P = Name.LastDelimiter(L"/");
  3635. if (P > 0)
  3636. {
  3637. Result = Name.SubString(1, P - 1);
  3638. }
  3639. return Result;
  3640. }
  3641. //---------------------------------------------------------------------
  3642. UnicodeString __fastcall TSessionData::GetFolderName()
  3643. {
  3644. UnicodeString Result;
  3645. if (HasSessionName() || IsWorkspace)
  3646. {
  3647. Result = ExtractFolderName(Name);
  3648. }
  3649. return Result;
  3650. }
  3651. //---------------------------------------------------------------------
  3652. UnicodeString __fastcall TSessionData::ComposePath(
  3653. const UnicodeString & Path, const UnicodeString & Name)
  3654. {
  3655. return UnixIncludeTrailingBackslash(Path) + Name;
  3656. }
  3657. //---------------------------------------------------------------------
  3658. void __fastcall TSessionData::DisableAuthentationsExceptPassword()
  3659. {
  3660. SshNoUserAuth = false;
  3661. AuthTIS = false;
  3662. AuthKI = false;
  3663. AuthKIPassword = false;
  3664. AuthGSSAPI = false;
  3665. PublicKeyFile = L"";
  3666. TlsCertificateFile = L"";
  3667. Passphrase = L"";
  3668. TryAgent = false;
  3669. }
  3670. //=== TStoredSessionList ----------------------------------------------
  3671. __fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):
  3672. TNamedObjectList(), FReadOnly(aReadOnly)
  3673. {
  3674. DebugAssert(Configuration);
  3675. FDefaultSettings = new TSessionData(DefaultName);
  3676. }
  3677. //---------------------------------------------------------------------
  3678. __fastcall TStoredSessionList::~TStoredSessionList()
  3679. {
  3680. DebugAssert(Configuration);
  3681. delete FDefaultSettings;
  3682. }
  3683. //---------------------------------------------------------------------
  3684. void __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,
  3685. bool AsModified, bool UseDefaults, bool PuttyImport)
  3686. {
  3687. TStringList *SubKeys = new TStringList();
  3688. TList * Loaded = new TList;
  3689. try
  3690. {
  3691. DebugAssert(AutoSort);
  3692. AutoSort = false;
  3693. bool WasEmpty = (Count == 0);
  3694. Storage->GetSubKeyNames(SubKeys);
  3695. for (int Index = 0; Index < SubKeys->Count; Index++)
  3696. {
  3697. UnicodeString SessionName = SubKeys->Strings[Index];
  3698. bool ValidName = true;
  3699. try
  3700. {
  3701. TSessionData::ValidatePath(SessionName);
  3702. }
  3703. catch(...)
  3704. {
  3705. ValidName = false;
  3706. }
  3707. if (ValidName)
  3708. {
  3709. TSessionData * SessionData;
  3710. if (SessionName == FDefaultSettings->Name)
  3711. {
  3712. SessionData = FDefaultSettings;
  3713. }
  3714. else
  3715. {
  3716. // if the list was empty before loading, do not waste time trying to
  3717. // find existing sites to overwrite (we rely on underlying storage
  3718. // to secure uniqueness of the key names)
  3719. if (WasEmpty)
  3720. {
  3721. SessionData = NULL;
  3722. }
  3723. else
  3724. {
  3725. SessionData = (TSessionData*)FindByName(SessionName);
  3726. }
  3727. }
  3728. if ((SessionData != FDefaultSettings) || !UseDefaults)
  3729. {
  3730. if (SessionData == NULL)
  3731. {
  3732. SessionData = new TSessionData(L"");
  3733. if (UseDefaults)
  3734. {
  3735. SessionData->CopyData(DefaultSettings);
  3736. }
  3737. SessionData->Name = SessionName;
  3738. Add(SessionData);
  3739. }
  3740. Loaded->Add(SessionData);
  3741. SessionData->Load(Storage, PuttyImport);
  3742. if (AsModified)
  3743. {
  3744. SessionData->Modified = true;
  3745. }
  3746. }
  3747. }
  3748. }
  3749. if (!AsModified)
  3750. {
  3751. for (int Index = 0; Index < TObjectList::Count; Index++)
  3752. {
  3753. if (Loaded->IndexOf(Items[Index]) < 0)
  3754. {
  3755. Delete(Index);
  3756. Index--;
  3757. }
  3758. }
  3759. }
  3760. }
  3761. __finally
  3762. {
  3763. AutoSort = true;
  3764. AlphaSort();
  3765. delete SubKeys;
  3766. delete Loaded;
  3767. }
  3768. }
  3769. //---------------------------------------------------------------------
  3770. void __fastcall TStoredSessionList::Load()
  3771. {
  3772. bool SessionList = true;
  3773. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  3774. try
  3775. {
  3776. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))
  3777. Load(Storage);
  3778. }
  3779. __finally
  3780. {
  3781. delete Storage;
  3782. }
  3783. }
  3784. //---------------------------------------------------------------------
  3785. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  3786. TSessionData * Data, bool All, bool RecryptPasswordOnly,
  3787. TSessionData * FactoryDefaults)
  3788. {
  3789. if (All || Data->Modified)
  3790. {
  3791. if (RecryptPasswordOnly)
  3792. {
  3793. Data->SaveRecryptedPasswords(Storage);
  3794. }
  3795. else
  3796. {
  3797. Data->Save(Storage, false, FactoryDefaults);
  3798. }
  3799. }
  3800. }
  3801. //---------------------------------------------------------------------
  3802. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  3803. bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  3804. {
  3805. TSessionData * FactoryDefaults = new TSessionData(L"");
  3806. try
  3807. {
  3808. DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);
  3809. for (int Index = 0; Index < CountIncludingHidden; Index++)
  3810. {
  3811. TSessionData * SessionData = (TSessionData *)Items[Index];
  3812. try
  3813. {
  3814. DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);
  3815. }
  3816. catch (Exception & E)
  3817. {
  3818. UnicodeString Message;
  3819. if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&
  3820. ExceptionMessage(&E, Message))
  3821. {
  3822. RecryptPasswordErrors->Add(FORMAT("%s: %s", (SessionData->SessionName, Message)));
  3823. }
  3824. else
  3825. {
  3826. throw;
  3827. }
  3828. }
  3829. }
  3830. }
  3831. __finally
  3832. {
  3833. delete FactoryDefaults;
  3834. }
  3835. }
  3836. //---------------------------------------------------------------------
  3837. void __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)
  3838. {
  3839. DoSave(Storage, All, false, NULL);
  3840. }
  3841. //---------------------------------------------------------------------
  3842. void __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,
  3843. bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  3844. {
  3845. bool SessionList = true;
  3846. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  3847. try
  3848. {
  3849. Storage->AccessMode = smReadWrite;
  3850. Storage->Explicit = Explicit;
  3851. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  3852. {
  3853. DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);
  3854. }
  3855. }
  3856. __finally
  3857. {
  3858. delete Storage;
  3859. }
  3860. Saved();
  3861. }
  3862. //---------------------------------------------------------------------
  3863. void __fastcall TStoredSessionList::Save(bool All, bool Explicit)
  3864. {
  3865. DoSave(All, Explicit, false, NULL);
  3866. }
  3867. //---------------------------------------------------------------------
  3868. void __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)
  3869. {
  3870. DoSave(true, true, true, RecryptPasswordErrors);
  3871. }
  3872. //---------------------------------------------------------------------
  3873. void __fastcall TStoredSessionList::Saved()
  3874. {
  3875. FDefaultSettings->Modified = false;
  3876. for (int Index = 0; Index < CountIncludingHidden; Index++)
  3877. {
  3878. ((TSessionData *)Items[Index])->Modified = false;
  3879. }
  3880. }
  3881. //---------------------------------------------------------------------
  3882. void __fastcall TStoredSessionList::ImportLevelFromFilezilla(
  3883. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  3884. {
  3885. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  3886. {
  3887. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  3888. if (ChildNode->NodeName == L"Server")
  3889. {
  3890. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3891. SessionData->CopyData(DefaultSettings);
  3892. SessionData->ImportFromFilezilla(ChildNode, Path, SettingsNode);
  3893. Add(SessionData.release());
  3894. }
  3895. else if (ChildNode->NodeName == L"Folder")
  3896. {
  3897. UnicodeString Name;
  3898. for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)
  3899. {
  3900. _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);
  3901. if (PossibleTextMode->NodeType == ntText)
  3902. {
  3903. UnicodeString NodeValue = PossibleTextMode->NodeValue;
  3904. AddToList(Name, NodeValue.Trim(), L" ");
  3905. }
  3906. }
  3907. Name = TSessionData::MakeValidName(Name).Trim();
  3908. ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name), SettingsNode);
  3909. }
  3910. }
  3911. }
  3912. //---------------------------------------------------------------------
  3913. void __fastcall TStoredSessionList::ImportFromFilezilla(
  3914. const UnicodeString FileName, const UnicodeString ConfigurationFileName)
  3915. {
  3916. // not sure if the document must exists if we want to use its node
  3917. _di_IXMLDocument ConfigurationDocument;
  3918. _di_IXMLNode SettingsNode;
  3919. if (FileExists(ApiPath(ConfigurationFileName)))
  3920. {
  3921. ConfigurationDocument = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  3922. ConfigurationDocument->LoadFromFile(ConfigurationFileName);
  3923. _di_IXMLNode FileZilla3Node = ConfigurationDocument->ChildNodes->FindNode(L"FileZilla3");
  3924. if (FileZilla3Node != NULL)
  3925. {
  3926. SettingsNode = FileZilla3Node->ChildNodes->FindNode(L"Settings");
  3927. }
  3928. }
  3929. const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  3930. Document->LoadFromFile(FileName);
  3931. _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L"FileZilla3");
  3932. if (FileZilla3Node != NULL)
  3933. {
  3934. _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L"Servers");
  3935. if (ServersNode != NULL)
  3936. {
  3937. ImportLevelFromFilezilla(ServersNode, L"", SettingsNode);
  3938. }
  3939. }
  3940. }
  3941. //---------------------------------------------------------------------
  3942. void __fastcall TStoredSessionList::ImportFromKnownHosts(TStrings * Lines)
  3943. {
  3944. bool SessionList = false;
  3945. std::unique_ptr<THierarchicalStorage> HostKeyStorage(Configuration->CreateScpStorage(SessionList));
  3946. std::unique_ptr<TStrings> KeyList(new TStringList());
  3947. if (OpenHostKeysSubKey(HostKeyStorage.get(), false))
  3948. {
  3949. HostKeyStorage->GetValueNames(KeyList.get());
  3950. }
  3951. HostKeyStorage.reset(NULL);
  3952. UnicodeString FirstError;
  3953. for (int Index = 0; Index < Lines->Count; Index++)
  3954. {
  3955. try
  3956. {
  3957. UnicodeString Line = Lines->Strings[Index];
  3958. Line = Trim(Line);
  3959. if (!Line.IsEmpty() && (Line[1] != L';'))
  3960. {
  3961. int P = Pos(L' ', Line);
  3962. if (P > 0)
  3963. {
  3964. UnicodeString HostNameStr = Line.SubString(1, P - 1);
  3965. Line = Line.SubString(P + 1, Line.Length() - P);
  3966. P = Pos(L',', HostNameStr);
  3967. if (P > 0)
  3968. {
  3969. HostNameStr.SetLength(P - 1);
  3970. }
  3971. P = Pos(L':', HostNameStr);
  3972. int PortNumber = -1;
  3973. if (P > 0)
  3974. {
  3975. UnicodeString PortNumberStr = HostNameStr.SubString(P + 1, HostNameStr.Length() - P);
  3976. PortNumber = StrToInt(PortNumberStr);
  3977. HostNameStr.SetLength(P - 1);
  3978. }
  3979. if ((HostNameStr.Length() >= 2) &&
  3980. (HostNameStr[1] == L'[') && (HostNameStr[HostNameStr.Length()] == L']'))
  3981. {
  3982. HostNameStr = HostNameStr.SubString(2, HostNameStr.Length() - 2);
  3983. }
  3984. UnicodeString NameStr = HostNameStr;
  3985. if (PortNumber >= 0)
  3986. {
  3987. NameStr = FORMAT(L"%s:%d", (NameStr, PortNumber));
  3988. }
  3989. std::unique_ptr<TSessionData> SessionDataOwner;
  3990. TSessionData * SessionData = dynamic_cast<TSessionData *>(FindByName(NameStr));
  3991. if (SessionData == NULL)
  3992. {
  3993. SessionData = new TSessionData(L"");
  3994. SessionDataOwner.reset(SessionData);
  3995. SessionData->CopyData(DefaultSettings);
  3996. SessionData->Name = NameStr;
  3997. SessionData->HostName = HostNameStr;
  3998. if (PortNumber >= 0)
  3999. {
  4000. SessionData->PortNumber = PortNumber;
  4001. }
  4002. }
  4003. const struct ssh_signkey * Algorithm;
  4004. UnicodeString Key = ParseOpenSshPubLine(Line, Algorithm);
  4005. UnicodeString KeyKey =
  4006. FORMAT(L"%s@%d:%s", (Algorithm->keytype, SessionData->PortNumber, HostNameStr));
  4007. UnicodeString HostKey =
  4008. FORMAT(L"%s:%s=%s", (Algorithm->name, KeyKey, Key));
  4009. UnicodeString HostKeyList = SessionData->HostKey;
  4010. AddToList(HostKeyList, HostKey, L";");
  4011. SessionData->HostKey = HostKeyList;
  4012. // If there's at least one unknown key type for this host, select it
  4013. if (KeyList->IndexOf(KeyKey) < 0)
  4014. {
  4015. SessionData->Selected = true;
  4016. }
  4017. if (SessionDataOwner.get() != NULL)
  4018. {
  4019. Add(SessionDataOwner.release());
  4020. }
  4021. }
  4022. }
  4023. }
  4024. catch (Exception & E)
  4025. {
  4026. if (FirstError.IsEmpty())
  4027. {
  4028. FirstError = E.Message;
  4029. }
  4030. }
  4031. }
  4032. if (Count == 0)
  4033. {
  4034. UnicodeString Message = LoadStr(KNOWN_HOSTS_NO_SITES);
  4035. if (!FirstError.IsEmpty())
  4036. {
  4037. Message = FORMAT(L"%s\n(%s)", (Message, FirstError));
  4038. }
  4039. throw Exception(Message);
  4040. }
  4041. }
  4042. //---------------------------------------------------------------------
  4043. void __fastcall TStoredSessionList::Export(const UnicodeString FileName)
  4044. {
  4045. THierarchicalStorage * Storage = TIniFileStorage::CreateFromPath(FileName);
  4046. try
  4047. {
  4048. Storage->AccessMode = smReadWrite;
  4049. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4050. {
  4051. Save(Storage, true);
  4052. }
  4053. }
  4054. __finally
  4055. {
  4056. delete Storage;
  4057. }
  4058. }
  4059. //---------------------------------------------------------------------
  4060. void __fastcall TStoredSessionList::SelectAll(bool Select)
  4061. {
  4062. for (int Index = 0; Index < Count; Index++)
  4063. Sessions[Index]->Selected = Select;
  4064. }
  4065. //---------------------------------------------------------------------
  4066. void __fastcall TStoredSessionList::Import(TStoredSessionList * From,
  4067. bool OnlySelected, TList * Imported)
  4068. {
  4069. for (int Index = 0; Index < From->Count; Index++)
  4070. {
  4071. if (!OnlySelected || From->Sessions[Index]->Selected)
  4072. {
  4073. TSessionData *Session = new TSessionData(L"");
  4074. Session->Assign(From->Sessions[Index]);
  4075. Session->Modified = true;
  4076. Session->MakeUniqueIn(this);
  4077. Add(Session);
  4078. if (Imported != NULL)
  4079. {
  4080. Imported->Add(Session);
  4081. }
  4082. }
  4083. }
  4084. // only modified, explicit
  4085. Save(false, true);
  4086. }
  4087. //---------------------------------------------------------------------
  4088. void __fastcall TStoredSessionList::SelectSessionsToImport
  4089. (TStoredSessionList * Dest, bool SSHOnly)
  4090. {
  4091. for (int Index = 0; Index < Count; Index++)
  4092. {
  4093. Sessions[Index]->Selected =
  4094. (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&
  4095. !Dest->FindByName(Sessions[Index]->Name);
  4096. }
  4097. }
  4098. //---------------------------------------------------------------------
  4099. void __fastcall TStoredSessionList::Cleanup()
  4100. {
  4101. try
  4102. {
  4103. if (Configuration->Storage == stRegistry) Clear();
  4104. TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);
  4105. try
  4106. {
  4107. Storage->AccessMode = smReadWrite;
  4108. if (Storage->OpenRootKey(False))
  4109. Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);
  4110. }
  4111. __finally
  4112. {
  4113. delete Storage;
  4114. }
  4115. }
  4116. catch (Exception &E)
  4117. {
  4118. throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));
  4119. }
  4120. }
  4121. //---------------------------------------------------------------------------
  4122. void __fastcall TStoredSessionList::UpdateStaticUsage()
  4123. {
  4124. int SCP = 0;
  4125. int SFTP = 0;
  4126. int FTP = 0;
  4127. int FTPS = 0;
  4128. int WebDAV = 0;
  4129. int WebDAVS = 0;
  4130. int S3 = 0;
  4131. int Password = 0;
  4132. int Advanced = 0;
  4133. int Color = 0;
  4134. int Note = 0;
  4135. int Tunnel = 0;
  4136. bool Folders = false;
  4137. bool Workspaces = false;
  4138. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4139. std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());
  4140. for (int Index = 0; Index < Count; Index++)
  4141. {
  4142. TSessionData * Data = Sessions[Index];
  4143. if (Data->IsWorkspace)
  4144. {
  4145. Workspaces = true;
  4146. }
  4147. else
  4148. {
  4149. switch (Data->FSProtocol)
  4150. {
  4151. case fsSCPonly:
  4152. SCP++;
  4153. break;
  4154. case fsSFTP:
  4155. case fsSFTPonly:
  4156. SFTP++;
  4157. break;
  4158. case fsFTP:
  4159. if (Data->Ftps == ftpsNone)
  4160. {
  4161. FTP++;
  4162. }
  4163. else
  4164. {
  4165. FTPS++;
  4166. }
  4167. break;
  4168. case fsWebDAV:
  4169. if (Data->Ftps == ftpsNone)
  4170. {
  4171. WebDAV++;
  4172. }
  4173. else
  4174. {
  4175. WebDAVS++;
  4176. }
  4177. break;
  4178. case fsS3:
  4179. S3++;
  4180. break;
  4181. }
  4182. if (Data->HasAnySessionPassword())
  4183. {
  4184. Password++;
  4185. }
  4186. if (Data->Color != 0)
  4187. {
  4188. Color++;
  4189. }
  4190. if (!Data->Note.IsEmpty())
  4191. {
  4192. Note++;
  4193. }
  4194. // this effectively does not take passwords (proxy + tunnel) into account,
  4195. // when master password is set, as master password handler in not set up yet
  4196. if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get()))
  4197. {
  4198. Advanced++;
  4199. }
  4200. if (Data->Tunnel)
  4201. {
  4202. Tunnel++;
  4203. }
  4204. if (!Data->FolderName.IsEmpty())
  4205. {
  4206. Folders = true;
  4207. }
  4208. }
  4209. }
  4210. Configuration->Usage->Set(L"StoredSessionsCountSCP", SCP);
  4211. Configuration->Usage->Set(L"StoredSessionsCountSFTP", SFTP);
  4212. Configuration->Usage->Set(L"StoredSessionsCountFTP", FTP);
  4213. Configuration->Usage->Set(L"StoredSessionsCountFTPS", FTPS);
  4214. Configuration->Usage->Set(L"StoredSessionsCountWebDAV", WebDAV);
  4215. Configuration->Usage->Set(L"StoredSessionsCountWebDAVS", WebDAVS);
  4216. Configuration->Usage->Set(L"StoredSessionsCountS3", S3);
  4217. Configuration->Usage->Set(L"StoredSessionsCountPassword", Password);
  4218. Configuration->Usage->Set(L"StoredSessionsCountColor", Color);
  4219. Configuration->Usage->Set(L"StoredSessionsCountNote", Note);
  4220. Configuration->Usage->Set(L"StoredSessionsCountAdvanced", Advanced);
  4221. DifferentAdvancedProperties->Delimiter = L',';
  4222. Configuration->Usage->Set(L"StoredSessionsAdvancedSettings", DifferentAdvancedProperties->DelimitedText);
  4223. Configuration->Usage->Set(L"StoredSessionsCountTunnel", Tunnel);
  4224. // actually default might be true, see below for when the default is actually used
  4225. bool CustomDefaultStoredSession = false;
  4226. try
  4227. {
  4228. // this can throw, when the default session settings have password set
  4229. // (and no other basic property, like hostname/username),
  4230. // and master password is enabled as we are called before master password
  4231. // handler is set
  4232. CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);
  4233. }
  4234. catch (...)
  4235. {
  4236. }
  4237. Configuration->Usage->Set(L"UsingDefaultStoredSession", CustomDefaultStoredSession);
  4238. Configuration->Usage->Set(L"UsingStoredSessionsFolders", Folders);
  4239. Configuration->Usage->Set(L"UsingWorkspaces", Workspaces);
  4240. }
  4241. //---------------------------------------------------------------------------
  4242. TSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)
  4243. {
  4244. TSessionData * Result;
  4245. if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)
  4246. {
  4247. Result = NULL;
  4248. }
  4249. else
  4250. {
  4251. Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));
  4252. }
  4253. return Result;
  4254. }
  4255. //---------------------------------------------------------------------------
  4256. int __fastcall TStoredSessionList::IndexOf(TSessionData * Data)
  4257. {
  4258. for (int Index = 0; Index < Count; Index++)
  4259. if (Data == Sessions[Index]) return Index;
  4260. return -1;
  4261. }
  4262. //---------------------------------------------------------------------------
  4263. TSessionData * __fastcall TStoredSessionList::NewSession(
  4264. UnicodeString SessionName, TSessionData * Session)
  4265. {
  4266. TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);
  4267. if (!DuplicateSession)
  4268. {
  4269. DuplicateSession = new TSessionData(L"");
  4270. DuplicateSession->Assign(Session);
  4271. DuplicateSession->Name = SessionName;
  4272. // make sure, that new stored session is saved to registry
  4273. DuplicateSession->Modified = true;
  4274. Add(DuplicateSession);
  4275. }
  4276. else
  4277. {
  4278. DuplicateSession->Assign(Session);
  4279. DuplicateSession->Name = SessionName;
  4280. DuplicateSession->Modified = true;
  4281. }
  4282. // list was saved here before to default storage, but it would not allow
  4283. // to work with special lists (export/import) not using default storage
  4284. return DuplicateSession;
  4285. }
  4286. //---------------------------------------------------------------------------
  4287. void __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)
  4288. {
  4289. DebugAssert(FDefaultSettings);
  4290. if (FDefaultSettings != value)
  4291. {
  4292. FDefaultSettings->Assign(value);
  4293. // make sure default settings are saved
  4294. FDefaultSettings->Modified = true;
  4295. FDefaultSettings->Name = DefaultName;
  4296. if (!FReadOnly)
  4297. {
  4298. // only modified, explicit
  4299. Save(false, true);
  4300. }
  4301. }
  4302. }
  4303. //---------------------------------------------------------------------------
  4304. bool __fastcall TStoredSessionList::OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate)
  4305. {
  4306. return
  4307. Storage->OpenRootKey(CanCreate) &&
  4308. Storage->OpenSubKey(Configuration->SshHostKeysSubKey, CanCreate);
  4309. }
  4310. //---------------------------------------------------------------------------
  4311. THierarchicalStorage * __fastcall TStoredSessionList::CreateHostKeysStorageForWritting()
  4312. {
  4313. bool SessionList = false;
  4314. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  4315. Storage->Explicit = true;
  4316. Storage->AccessMode = smReadWrite;
  4317. if (!OpenHostKeysSubKey(Storage.get(), true))
  4318. {
  4319. Storage.reset(NULL);
  4320. }
  4321. return Storage.release();
  4322. }
  4323. //---------------------------------------------------------------------------
  4324. void __fastcall TStoredSessionList::ImportHostKeys(
  4325. const UnicodeString SourceKey, TStoredSessionList * Sessions,
  4326. bool OnlySelected)
  4327. {
  4328. TRegistryStorage * SourceStorage = NULL;
  4329. THierarchicalStorage * TargetStorage = NULL;
  4330. TStringList * KeyList = NULL;
  4331. try
  4332. {
  4333. TargetStorage = CreateHostKeysStorageForWritting();
  4334. SourceStorage = new TRegistryStorage(SourceKey);
  4335. KeyList = new TStringList();
  4336. if ((TargetStorage != NULL) &&
  4337. SourceStorage->OpenRootKey(false))
  4338. {
  4339. SourceStorage->GetValueNames(KeyList);
  4340. TSessionData * Session;
  4341. UnicodeString HostKeyName;
  4342. DebugAssert(Sessions != NULL);
  4343. for (int Index = 0; Index < Sessions->Count; Index++)
  4344. {
  4345. Session = Sessions->Sessions[Index];
  4346. if (!OnlySelected || Session->Selected)
  4347. {
  4348. HostKeyName = PuttyMungeStr(FORMAT(L"@%d:%s", (Session->PortNumber, Session->HostNameExpanded)));
  4349. UnicodeString KeyName;
  4350. for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)
  4351. {
  4352. KeyName = KeyList->Strings[KeyIndex];
  4353. int P = KeyName.Pos(HostKeyName);
  4354. if ((P > 0) && (P == KeyName.Length() - HostKeyName.Length() + 1))
  4355. {
  4356. TargetStorage->WriteStringRaw(KeyName,
  4357. SourceStorage->ReadStringRaw(KeyName, L""));
  4358. }
  4359. }
  4360. }
  4361. }
  4362. }
  4363. }
  4364. __finally
  4365. {
  4366. delete SourceStorage;
  4367. delete TargetStorage;
  4368. delete KeyList;
  4369. }
  4370. }
  4371. //---------------------------------------------------------------------------
  4372. void __fastcall TStoredSessionList::ImportSelectedKnownHosts(TStoredSessionList * Sessions)
  4373. {
  4374. std::unique_ptr<THierarchicalStorage> Storage(CreateHostKeysStorageForWritting());
  4375. if (Storage.get() != NULL)
  4376. {
  4377. for (int Index = 0; Index < Sessions->Count; Index++)
  4378. {
  4379. TSessionData * Session = Sessions->Sessions[Index];
  4380. if (Session->Selected)
  4381. {
  4382. UnicodeString Algs;
  4383. UnicodeString HostKeys = Session->HostKey;
  4384. while (!HostKeys.IsEmpty())
  4385. {
  4386. UnicodeString HostKey = CutToChar(HostKeys, L';', true);
  4387. // skip alg
  4388. CutToChar(HostKey, L':', true);
  4389. UnicodeString Key = CutToChar(HostKey, L'=', true);
  4390. Storage->WriteStringRaw(Key, HostKey);
  4391. }
  4392. }
  4393. }
  4394. }
  4395. }
  4396. //---------------------------------------------------------------------------
  4397. bool __fastcall TStoredSessionList::IsFolderOrWorkspace(
  4398. const UnicodeString & Name, bool Workspace)
  4399. {
  4400. bool Result = false;
  4401. TSessionData * FirstData = NULL;
  4402. if (!Name.IsEmpty())
  4403. {
  4404. for (int Index = 0; !Result && (Index < Count); Index++)
  4405. {
  4406. Result = Sessions[Index]->IsInFolderOrWorkspace(Name);
  4407. if (Result)
  4408. {
  4409. FirstData = Sessions[Index];
  4410. }
  4411. }
  4412. }
  4413. return
  4414. Result &&
  4415. DebugAlwaysTrue(FirstData != NULL) &&
  4416. (FirstData->IsWorkspace == Workspace);
  4417. }
  4418. //---------------------------------------------------------------------------
  4419. bool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)
  4420. {
  4421. return IsFolderOrWorkspace(Name, false);
  4422. }
  4423. //---------------------------------------------------------------------------
  4424. bool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)
  4425. {
  4426. return IsFolderOrWorkspace(Name, true);
  4427. }
  4428. //---------------------------------------------------------------------------
  4429. TSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(
  4430. TSessionData * Data, const UnicodeString & Name)
  4431. {
  4432. if (Data->IsInFolderOrWorkspace(Name))
  4433. {
  4434. Data = ResolveWorkspaceData(Data);
  4435. if ((Data != NULL) && Data->CanLogin &&
  4436. DebugAlwaysTrue(Data->Link.IsEmpty()))
  4437. {
  4438. return Data;
  4439. }
  4440. }
  4441. return NULL;
  4442. }
  4443. //---------------------------------------------------------------------------
  4444. void __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)
  4445. {
  4446. for (int Index = 0; (Index < Count); Index++)
  4447. {
  4448. TSessionData * RawData = Sessions[Index];
  4449. TSessionData * Data =
  4450. CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);
  4451. if (Data != NULL)
  4452. {
  4453. TSessionData * Data2 = new TSessionData(L"");
  4454. Data2->Assign(Data);
  4455. if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&
  4456. // BACKWARD COMPATIBILITY
  4457. // When loading pre-5.6.4 workspace, that does not have state saved,
  4458. // do not overwrite the site "state" defaults
  4459. // with (empty) workspace state
  4460. RawData->HasStateData())
  4461. {
  4462. Data2->CopyStateData(RawData);
  4463. }
  4464. List->Add(Data2);
  4465. }
  4466. }
  4467. }
  4468. //---------------------------------------------------------------------------
  4469. TStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(
  4470. const UnicodeString & Name)
  4471. {
  4472. std::unique_ptr<TStringList> Result(new TStringList());
  4473. for (int Index = 0; (Index < Count); Index++)
  4474. {
  4475. TSessionData * Data =
  4476. CheckIsInFolderOrWorkspaceAndResolve(Sessions[Index], Name);
  4477. if (Data != NULL)
  4478. {
  4479. Result->Add(Data->SessionName);
  4480. }
  4481. }
  4482. return Result.release();
  4483. }
  4484. //---------------------------------------------------------------------------
  4485. TStrings * __fastcall TStoredSessionList::GetWorkspaces()
  4486. {
  4487. std::unique_ptr<TStringList> Result(CreateSortedStringList());
  4488. for (int Index = 0; (Index < Count); Index++)
  4489. {
  4490. TSessionData * Data = Sessions[Index];
  4491. if (Data->IsWorkspace)
  4492. {
  4493. Result->Add(Data->FolderName);
  4494. }
  4495. }
  4496. return Result.release();
  4497. }
  4498. //---------------------------------------------------------------------------
  4499. void __fastcall TStoredSessionList::NewWorkspace(
  4500. UnicodeString Name, TList * DataList)
  4501. {
  4502. for (int Index = 0; (Index < Count); Index++)
  4503. {
  4504. TSessionData * Data = Sessions[Index];
  4505. if (Data->IsInFolderOrWorkspace(Name))
  4506. {
  4507. Data->Remove();
  4508. Remove(Data);
  4509. Index--;
  4510. }
  4511. }
  4512. for (int Index = 0; (Index < DataList->Count); Index++)
  4513. {
  4514. TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);
  4515. TSessionData * Data2 = new TSessionData(L"");
  4516. Data2->Assign(Data);
  4517. Data2->Name = TSessionData::ComposePath(Name, Data->Name);
  4518. // make sure, that new stored session is saved to registry
  4519. Data2->Modified = true;
  4520. Add(Data2);
  4521. }
  4522. }
  4523. //---------------------------------------------------------------------------
  4524. bool __fastcall TStoredSessionList::HasAnyWorkspace()
  4525. {
  4526. bool Result = false;
  4527. for (int Index = 0; !Result && (Index < Count); Index++)
  4528. {
  4529. TSessionData * Data = Sessions[Index];
  4530. Result = Data->IsWorkspace;
  4531. }
  4532. return Result;
  4533. }
  4534. //---------------------------------------------------------------------------
  4535. TSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,
  4536. TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,
  4537. bool * AProtocolDefined, UnicodeString * MaskedUrl)
  4538. {
  4539. TSessionData * Data = new TSessionData(L"");
  4540. try
  4541. {
  4542. Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl);
  4543. }
  4544. catch(...)
  4545. {
  4546. delete Data;
  4547. throw;
  4548. }
  4549. return Data;
  4550. }
  4551. //---------------------------------------------------------------------
  4552. bool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)
  4553. {
  4554. bool DefaultsOnly;
  4555. bool ProtocolDefined = false;
  4556. std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));
  4557. bool Result = ProtocolDefined;
  4558. return Result;
  4559. }
  4560. //---------------------------------------------------------------------
  4561. TSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)
  4562. {
  4563. if (!Data->Link.IsEmpty())
  4564. {
  4565. Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));
  4566. if (Data != NULL)
  4567. {
  4568. Data = ResolveWorkspaceData(Data);
  4569. }
  4570. }
  4571. return Data;
  4572. }
  4573. //---------------------------------------------------------------------
  4574. TSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data)
  4575. {
  4576. std::unique_ptr<TSessionData> Result(new TSessionData(L""));
  4577. TSessionData * SameData = StoredSessions->FindSame(Data);
  4578. if (SameData != NULL)
  4579. {
  4580. Result->CopyStateData(Data);
  4581. Result->Link = Data->Name;
  4582. }
  4583. else
  4584. {
  4585. Result->Assign(Data);
  4586. }
  4587. Result->IsWorkspace = true;
  4588. return Result.release();
  4589. }
  4590. //---------------------------------------------------------------------
  4591. bool __fastcall TStoredSessionList::CanLogin(TSessionData * Data)
  4592. {
  4593. Data = ResolveWorkspaceData(Data);
  4594. return (Data != NULL) && Data->CanLogin;
  4595. }
  4596. //---------------------------------------------------------------------
  4597. UnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData)
  4598. {
  4599. // StripPathQuotes should not be needed as we do not feed quotes anymore
  4600. UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));
  4601. for (int Index = 1; Index < ANewFileName.Length(); Index++)
  4602. {
  4603. if (ANewFileName[Index] == L'!')
  4604. {
  4605. UnicodeString Replacement;
  4606. // keep consistent with TFileCustomCommand::PatternReplacement
  4607. switch (tolower(ANewFileName[Index + 1]))
  4608. {
  4609. case L'y':
  4610. Replacement = FormatDateTime(L"yyyy", Started);
  4611. break;
  4612. case L'm':
  4613. Replacement = FormatDateTime(L"mm", Started);
  4614. break;
  4615. case L'd':
  4616. Replacement = FormatDateTime(L"dd", Started);
  4617. break;
  4618. case L't':
  4619. Replacement = FormatDateTime(L"hhnnss", Started);
  4620. break;
  4621. case 'p':
  4622. Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));
  4623. break;
  4624. case L'@':
  4625. if (SessionData != NULL)
  4626. {
  4627. Replacement = MakeValidFileName(SessionData->HostNameExpanded);
  4628. }
  4629. else
  4630. {
  4631. Replacement = L"nohost";
  4632. }
  4633. break;
  4634. case L's':
  4635. if (SessionData != NULL)
  4636. {
  4637. Replacement = MakeValidFileName(SessionData->SessionName);
  4638. }
  4639. else
  4640. {
  4641. Replacement = L"nosession";
  4642. }
  4643. break;
  4644. case L'!':
  4645. Replacement = L"!";
  4646. break;
  4647. default:
  4648. Replacement = UnicodeString(L"!") + ANewFileName[Index + 1];
  4649. break;
  4650. }
  4651. ANewFileName.Delete(Index, 2);
  4652. ANewFileName.Insert(Replacement, Index);
  4653. Index += Replacement.Length() - 1;
  4654. }
  4655. }
  4656. return ANewFileName;
  4657. }
  4658. //---------------------------------------------------------------------
  4659. bool __fastcall IsSshProtocol(TFSProtocol FSProtocol)
  4660. {
  4661. return
  4662. (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||
  4663. (FSProtocol == fsSCPonly);
  4664. }
  4665. //---------------------------------------------------------------------------
  4666. int __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)
  4667. {
  4668. int Result;
  4669. switch (FSProtocol)
  4670. {
  4671. case fsFTP:
  4672. if (Ftps == ftpsImplicit)
  4673. {
  4674. Result = FtpsImplicitPortNumber;
  4675. }
  4676. else
  4677. {
  4678. Result = FtpPortNumber;
  4679. }
  4680. break;
  4681. case fsWebDAV:
  4682. case fsS3:
  4683. if (Ftps == ftpsNone)
  4684. {
  4685. Result = HTTPPortNumber;
  4686. }
  4687. else
  4688. {
  4689. Result = HTTPSPortNumber;
  4690. }
  4691. break;
  4692. default:
  4693. if (IsSshProtocol(FSProtocol))
  4694. {
  4695. Result = SshPortNumber;
  4696. }
  4697. else
  4698. {
  4699. DebugFail();
  4700. Result = -1;
  4701. }
  4702. break;
  4703. }
  4704. return Result;
  4705. }
  4706. //---------------------------------------------------------------------