SessionData.cpp 186 KB

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