SessionData.cpp 164 KB

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