SessionData.cpp 183 KB

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