SessionData.cpp 186 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693
  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. if (IsProtocolUrl(Url, ScpProtocol, ProtocolLen))
  1918. {
  1919. AFSProtocol = fsSCPonly;
  1920. DefaultProtocolPortNumber = SshPortNumber;
  1921. MoveStr(Url, MaskedUrl, ProtocolLen);
  1922. ProtocolDefined = true;
  1923. }
  1924. else if (IsProtocolUrl(Url, SftpProtocol, ProtocolLen))
  1925. {
  1926. AFSProtocol = fsSFTPonly;
  1927. DefaultProtocolPortNumber = SshPortNumber;
  1928. MoveStr(Url, MaskedUrl, ProtocolLen);
  1929. ProtocolDefined = true;
  1930. }
  1931. else if (IsProtocolUrl(Url, FtpProtocol, ProtocolLen))
  1932. {
  1933. AFSProtocol = fsFTP;
  1934. Ftps = ftpsNone;
  1935. DefaultProtocolPortNumber = FtpPortNumber;
  1936. MoveStr(Url, MaskedUrl, ProtocolLen);
  1937. ProtocolDefined = true;
  1938. }
  1939. else if (IsProtocolUrl(Url, FtpsProtocol, ProtocolLen))
  1940. {
  1941. AFSProtocol = fsFTP;
  1942. AFtps = ftpsImplicit;
  1943. DefaultProtocolPortNumber = FtpsImplicitPortNumber;
  1944. MoveStr(Url, MaskedUrl, ProtocolLen);
  1945. ProtocolDefined = true;
  1946. }
  1947. else if (IsProtocolUrl(Url, FtpesProtocol, ProtocolLen))
  1948. {
  1949. AFSProtocol = fsFTP;
  1950. AFtps = ftpsExplicitTls;
  1951. DefaultProtocolPortNumber = FtpPortNumber;
  1952. MoveStr(Url, MaskedUrl, ProtocolLen);
  1953. ProtocolDefined = true;
  1954. }
  1955. else if (IsProtocolUrl(Url, WebDAVProtocol, ProtocolLen) ||
  1956. IsProtocolUrl(Url, HttpProtocol, ProtocolLen))
  1957. {
  1958. AFSProtocol = fsWebDAV;
  1959. AFtps = ftpsNone;
  1960. DefaultProtocolPortNumber = HTTPPortNumber;
  1961. MoveStr(Url, MaskedUrl, ProtocolLen);
  1962. ProtocolDefined = true;
  1963. }
  1964. else if (IsProtocolUrl(Url, WebDAVSProtocol, ProtocolLen) ||
  1965. IsProtocolUrl(Url, HttpsProtocol, ProtocolLen))
  1966. {
  1967. AFSProtocol = fsWebDAV;
  1968. AFtps = ftpsImplicit;
  1969. DefaultProtocolPortNumber = HTTPSPortNumber;
  1970. MoveStr(Url, MaskedUrl, ProtocolLen);
  1971. ProtocolDefined = true;
  1972. }
  1973. else if (IsProtocolUrl(Url, S3Protocol, ProtocolLen))
  1974. {
  1975. AFSProtocol = fsS3;
  1976. AFtps = ftpsImplicit;
  1977. DefaultProtocolPortNumber = HTTPSPortNumber;
  1978. MoveStr(Url, MaskedUrl, ProtocolLen);
  1979. ProtocolDefined = true;
  1980. }
  1981. else if (IsProtocolUrl(Url, SshProtocol, ProtocolLen))
  1982. {
  1983. // For most uses, handling ssh:// the same way as sftp://
  1984. // The only place where a difference is made is GetLoginData() in WinMain.cpp
  1985. AFSProtocol = fsSFTPonly;
  1986. PuttyProtocol = PuttySshProtocol;
  1987. DefaultProtocolPortNumber = SshPortNumber;
  1988. MoveStr(Url, MaskedUrl, ProtocolLen);
  1989. ProtocolDefined = true;
  1990. }
  1991. if (ProtocolDefined && (Url.SubString(1, 2) == L"//"))
  1992. {
  1993. MoveStr(Url, MaskedUrl, 2);
  1994. }
  1995. if (AProtocolDefined != NULL)
  1996. {
  1997. *AProtocolDefined = ProtocolDefined;
  1998. }
  1999. bool Unsafe = FLAGSET(Flags, pufUnsafe);
  2000. if (!Url.IsEmpty())
  2001. {
  2002. UnicodeString DecodedUrl = DecodeUrlChars(Url);
  2003. // lookup stored session even if protocol was defined
  2004. // (this allows setting for example default username for host
  2005. // by creating stored session named by host)
  2006. TSessionData * Data = NULL;
  2007. // When using to paste URL on Login dialog, we do not want to lookup the stored sites
  2008. if ((StoredSessions != NULL) &&
  2009. (!ProtocolDefined || FLAGSET(Flags, pufAllowStoredSiteWithProtocol)))
  2010. {
  2011. // this can be optimized as the list is sorted
  2012. for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++)
  2013. {
  2014. TSessionData * AData = (TSessionData *)StoredSessions->Items[Index];
  2015. if (!AData->IsWorkspace)
  2016. {
  2017. bool Match = false;
  2018. // Comparison optimizations as this is called many times
  2019. // e.g. when updating jumplist
  2020. if ((AData->Name.Length() == DecodedUrl.Length()) &&
  2021. SameText(AData->Name, DecodedUrl))
  2022. {
  2023. Match = true;
  2024. }
  2025. else if ((AData->Name.Length() < DecodedUrl.Length()) &&
  2026. (DecodedUrl[AData->Name.Length() + 1] == L'/') &&
  2027. // StrLIComp is an equivalent of SameText
  2028. (StrLIComp(AData->Name.c_str(), DecodedUrl.c_str(), AData->Name.Length()) == 0))
  2029. {
  2030. Match = true;
  2031. }
  2032. if (Match)
  2033. {
  2034. Data = AData;
  2035. break;
  2036. }
  2037. }
  2038. }
  2039. }
  2040. UnicodeString ARemoteDirectory;
  2041. if (Data != NULL)
  2042. {
  2043. Assign(Data);
  2044. int P = 1;
  2045. while (!AnsiSameText(DecodeUrlChars(Url.SubString(1, P)), Data->Name))
  2046. {
  2047. P++;
  2048. DebugAssert(P <= Url.Length());
  2049. }
  2050. ARemoteDirectory = Url.SubString(P + 1, Url.Length() - P);
  2051. if (Data->Hidden)
  2052. {
  2053. Data->Remove();
  2054. StoredSessions->Remove(Data);
  2055. // only modified, implicit
  2056. StoredSessions->Save(false, false);
  2057. }
  2058. if (MaskedUrl != NULL)
  2059. {
  2060. (*MaskedUrl) += Url;
  2061. }
  2062. }
  2063. else
  2064. {
  2065. // This happens when pasting URL on Login dialog
  2066. if (StoredSessions != NULL)
  2067. {
  2068. CopyData(StoredSessions->DefaultSettings);
  2069. }
  2070. Name = L"";
  2071. int PSlash = Url.Pos(L"/");
  2072. if (PSlash == 0)
  2073. {
  2074. PSlash = Url.Length() + 1;
  2075. }
  2076. UnicodeString ConnectInfo = Url.SubString(1, PSlash - 1);
  2077. int P = ConnectInfo.LastDelimiter(L"@");
  2078. UnicodeString UserInfo;
  2079. UnicodeString HostInfo;
  2080. if (P > 0)
  2081. {
  2082. UserInfo = ConnectInfo.SubString(1, P - 1);
  2083. HostInfo = ConnectInfo.SubString(P + 1, ConnectInfo.Length() - P);
  2084. }
  2085. else
  2086. {
  2087. HostInfo = ConnectInfo;
  2088. }
  2089. UnicodeString OrigHostInfo = HostInfo;
  2090. if ((HostInfo.Length() >= 2) && (HostInfo[1] == L'[') && ((P = HostInfo.Pos(L"]")) > 0))
  2091. {
  2092. HostName = HostInfo.SubString(2, P - 2);
  2093. HostInfo.Delete(1, P);
  2094. if (!HostInfo.IsEmpty() && (HostInfo[1] == L':'))
  2095. {
  2096. HostInfo.Delete(1, 1);
  2097. }
  2098. }
  2099. else
  2100. {
  2101. HostName = DecodeUrlChars(CutToChar(HostInfo, L':', true));
  2102. }
  2103. // expanded from ?: operator, as it caused strange "access violation" errors
  2104. if (!HostInfo.IsEmpty())
  2105. {
  2106. int APortNumber = StrToIntDef(DecodeUrlChars(HostInfo), -1);
  2107. if ((APortNumber > 0) && (APortNumber <= 65535))
  2108. {
  2109. PortNumber = APortNumber;
  2110. PortNumberDefined = true;
  2111. }
  2112. }
  2113. else if (ProtocolDefined)
  2114. {
  2115. if ((AFSProtocol == fsWebDAV) &&
  2116. (IsDomainOrSubdomain(HostName, S3LibDefaultHostName()) ||
  2117. IsDomainOrSubdomain(HostName, L"digitaloceanspaces.com") ||
  2118. IsDomainOrSubdomain(HostName, L"storage.googleapis.com")))
  2119. {
  2120. AFSProtocol = fsS3;
  2121. }
  2122. PortNumber = DefaultProtocolPortNumber;
  2123. }
  2124. if (ProtocolDefined)
  2125. {
  2126. Ftps = AFtps;
  2127. }
  2128. UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);
  2129. UnicodeString ConnectionParams = UserInfo;
  2130. UserInfo = UserInfoWithoutConnectionParams;
  2131. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2132. while (!ConnectionParams.IsEmpty())
  2133. {
  2134. UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);
  2135. UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);
  2136. if (SameText(ConnectionParamName, UrlHostKeyParamName))
  2137. {
  2138. HostKey = DecodeUrlChars(ConnectionParam);
  2139. FOverrideCachedHostKey = false;
  2140. }
  2141. else if (StartsText(UrlRawSettingsParamNamePrefix, ConnectionParamName))
  2142. {
  2143. UnicodeString AName = RightStr(ConnectionParamName, ConnectionParamName.Length() - UrlRawSettingsParamNamePrefix.Length());
  2144. AName = DecodeUrlChars(AName);
  2145. UnicodeString Value = DecodeUrlChars(ConnectionParam);
  2146. if (SameText(AName, L"Name"))
  2147. {
  2148. Name = Value;
  2149. }
  2150. else
  2151. {
  2152. RawSettings->Values[AName] = Value;
  2153. }
  2154. }
  2155. }
  2156. if (RawSettings->Count > 0) // optimization
  2157. {
  2158. ApplyRawSettings(RawSettings.get(), FLAGSET(Flags, pufUnsafe));
  2159. }
  2160. bool HasPassword = (UserInfo.Pos(L':') > 0);
  2161. UnicodeString RawUserName = CutToChar(UserInfo, L':', false);
  2162. UserName = DecodeUrlChars(RawUserName);
  2163. Password = DecodeUrlChars(UserInfo);
  2164. if (HasPassword && Password.IsEmpty())
  2165. {
  2166. Password = EmptyString;
  2167. }
  2168. UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);
  2169. ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);
  2170. UnicodeString SessionParams = RemoteDirectoryWithSessionParams;
  2171. // We should handle session params in "stored session" branch too.
  2172. // And particularly if there's a "save" param, we should actually not try to match the
  2173. // URL against site names
  2174. while (!SessionParams.IsEmpty())
  2175. {
  2176. UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);
  2177. UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);
  2178. if (SameText(SessionParamName, UrlSaveParamName))
  2179. {
  2180. FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);
  2181. }
  2182. }
  2183. if (MaskedUrl != NULL)
  2184. {
  2185. (*MaskedUrl) += RawUserName;
  2186. if (HasPassword)
  2187. {
  2188. (*MaskedUrl) += L":" + PasswordMask;
  2189. }
  2190. if (!RawUserName.IsEmpty() || HasPassword)
  2191. {
  2192. (*MaskedUrl) += L"@";
  2193. }
  2194. (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;
  2195. }
  2196. }
  2197. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L"/"))
  2198. {
  2199. if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&
  2200. (FileName != NULL))
  2201. {
  2202. *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));
  2203. ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);
  2204. }
  2205. RemoteDirectory = DecodeUrlChars(ARemoteDirectory);
  2206. }
  2207. DefaultsOnly = false;
  2208. }
  2209. else
  2210. {
  2211. // This happens when pasting URL on Login dialog
  2212. if (StoredSessions != NULL)
  2213. {
  2214. CopyData(StoredSessions->DefaultSettings);
  2215. }
  2216. DefaultsOnly = true;
  2217. }
  2218. if (ProtocolDefined)
  2219. {
  2220. FSProtocol = AFSProtocol;
  2221. }
  2222. if (Options != NULL)
  2223. {
  2224. // we deliberately do keep defaultonly to false, in presence of any option,
  2225. // as the option should not make session "connectable"
  2226. UnicodeString Value;
  2227. if (Options->FindSwitch(USERNAME_SWITCH, Value))
  2228. {
  2229. UserName = Value;
  2230. }
  2231. if (Options->FindSwitch(PASSWORD_SWITCH, Value))
  2232. {
  2233. Password = Value;
  2234. }
  2235. if (Options->FindSwitch(SESSIONNAME_SWICH, Value))
  2236. {
  2237. Name = Value;
  2238. }
  2239. if (Options->FindSwitch(NEWPASSWORD_SWITCH, Value))
  2240. {
  2241. ChangePassword = true;
  2242. NewPassword = Value;
  2243. }
  2244. if (Options->FindSwitch(L"privatekey", Value))
  2245. {
  2246. PublicKeyFile = Value;
  2247. }
  2248. if (Options->FindSwitch(L"clientcert", Value))
  2249. {
  2250. TlsCertificateFile = Value;
  2251. }
  2252. if (Options->FindSwitch(PassphraseOption, Value))
  2253. {
  2254. Passphrase = Value;
  2255. }
  2256. if (Options->FindSwitch(L"timeout", Value))
  2257. {
  2258. Timeout = StrToInt(Value);
  2259. }
  2260. if (Options->FindSwitch(L"hostkey", Value) ||
  2261. Options->FindSwitch(L"certificate", Value))
  2262. {
  2263. HostKey = Value;
  2264. FOverrideCachedHostKey = true;
  2265. }
  2266. FtpPasvMode = Options->SwitchValue(L"passive", FtpPasvMode);
  2267. if (Options->FindSwitch(L"implicit"))
  2268. {
  2269. bool Enabled = Options->SwitchValue(L"implicit", true);
  2270. Ftps = Enabled ? ftpsImplicit : ftpsNone;
  2271. if (!PortNumberDefined && Enabled)
  2272. {
  2273. PortNumber = FtpsImplicitPortNumber;
  2274. }
  2275. }
  2276. // BACKWARD COMPATIBILITY with 5.5.x
  2277. if (Options->FindSwitch(L"explicitssl"))
  2278. {
  2279. bool Enabled = Options->SwitchValue(L"explicitssl", true);
  2280. Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;
  2281. if (!PortNumberDefined && Enabled)
  2282. {
  2283. PortNumber = FtpPortNumber;
  2284. }
  2285. }
  2286. if (Options->FindSwitch(L"explicit") ||
  2287. // BACKWARD COMPATIBILITY with 5.5.x
  2288. Options->FindSwitch(L"explicittls"))
  2289. {
  2290. UnicodeString SwitchName =
  2291. Options->FindSwitch(L"explicit") ? L"explicit" : L"explicittls";
  2292. bool Enabled = Options->SwitchValue(SwitchName, true);
  2293. Ftps = Enabled ? ftpsExplicitTls : ftpsNone;
  2294. if (!PortNumberDefined && Enabled)
  2295. {
  2296. PortNumber = FtpPortNumber;
  2297. }
  2298. }
  2299. if (Options->FindSwitch(RawSettingsOption))
  2300. {
  2301. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2302. if (Options->FindSwitch(RawSettingsOption, RawSettings.get()))
  2303. {
  2304. ApplyRawSettings(RawSettings.get(), Unsafe);
  2305. }
  2306. }
  2307. }
  2308. return true;
  2309. }
  2310. //---------------------------------------------------------------------
  2311. void __fastcall TSessionData::ApplyRawSettings(TStrings * RawSettings, bool Unsafe)
  2312. {
  2313. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings, false));
  2314. ApplyRawSettings(OptionsStorage.get(), Unsafe);
  2315. }
  2316. //---------------------------------------------------------------------
  2317. void __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage, bool Unsafe)
  2318. {
  2319. bool Dummy;
  2320. DoLoad(Storage, false, Dummy, Unsafe);
  2321. }
  2322. //---------------------------------------------------------------------
  2323. void __fastcall TSessionData::ConfigureTunnel(int APortNumber)
  2324. {
  2325. FOrigHostName = HostName;
  2326. FOrigPortNumber = PortNumber;
  2327. FOrigProxyMethod = ProxyMethod;
  2328. HostName = L"127.0.0.1";
  2329. PortNumber = APortNumber;
  2330. // proxy settings is used for tunnel
  2331. ProxyMethod = ::pmNone;
  2332. FLogicalHostName = FOrigHostName;
  2333. }
  2334. //---------------------------------------------------------------------
  2335. void __fastcall TSessionData::RollbackTunnel()
  2336. {
  2337. HostName = FOrigHostName;
  2338. PortNumber = FOrigPortNumber;
  2339. ProxyMethod = FOrigProxyMethod;
  2340. FLogicalHostName = L"";
  2341. }
  2342. //---------------------------------------------------------------------
  2343. TSessionData * TSessionData::CreateTunnelData(int TunnelLocalPortNumber)
  2344. {
  2345. std::unique_ptr<TSessionData> TunnelData(new TSessionData(EmptyStr));
  2346. TunnelData->Assign(StoredSessions->DefaultSettings);
  2347. TunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (SessionName));
  2348. TunnelData->Tunnel = false;
  2349. TunnelData->HostName = TunnelHostName;
  2350. TunnelData->PortNumber = TunnelPortNumber;
  2351. TunnelData->UserName = TunnelUserName;
  2352. TunnelData->Password = TunnelPassword;
  2353. TunnelData->PublicKeyFile = TunnelPublicKeyFile;
  2354. TunnelData->Passphrase = TunnelPassphrase;
  2355. UnicodeString AHostName = HostNameExpanded;
  2356. if (IsIPv6Literal(AHostName))
  2357. {
  2358. AHostName = EscapeIPv6Literal(AHostName);
  2359. }
  2360. TunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  2361. (TunnelLocalPortNumber, AHostName, PortNumber));
  2362. TunnelData->HostKey = TunnelHostKey;
  2363. // inherit proxy options on the main session
  2364. TunnelData->ProxyMethod = ProxyMethod;
  2365. TunnelData->ProxyHost = ProxyHost;
  2366. TunnelData->ProxyPort = ProxyPort;
  2367. TunnelData->ProxyUsername = ProxyUsername;
  2368. TunnelData->ProxyPassword = ProxyPassword;
  2369. TunnelData->ProxyTelnetCommand = ProxyTelnetCommand;
  2370. TunnelData->ProxyLocalCommand = ProxyLocalCommand;
  2371. TunnelData->ProxyDNS = ProxyDNS;
  2372. TunnelData->ProxyLocalhost = ProxyLocalhost;
  2373. // inherit most SSH options of the main session (except for private key and bugs)
  2374. TunnelData->Compression = Compression;
  2375. TunnelData->CipherList = CipherList;
  2376. TunnelData->Ssh2DES = Ssh2DES;
  2377. TunnelData->KexList = KexList;
  2378. TunnelData->RekeyData = RekeyData;
  2379. TunnelData->RekeyTime = RekeyTime;
  2380. TunnelData->SshNoUserAuth = SshNoUserAuth;
  2381. TunnelData->AuthGSSAPI = AuthGSSAPI;
  2382. TunnelData->AuthGSSAPIKEX = AuthGSSAPIKEX;
  2383. TunnelData->GSSAPIFwdTGT = GSSAPIFwdTGT;
  2384. TunnelData->TryAgent = TryAgent;
  2385. TunnelData->AgentFwd = AgentFwd;
  2386. TunnelData->AuthKI = AuthKI;
  2387. TunnelData->AuthKIPassword = AuthKIPassword;
  2388. return TunnelData.release();
  2389. }
  2390. //---------------------------------------------------------------------
  2391. void __fastcall TSessionData::ExpandEnvironmentVariables()
  2392. {
  2393. HostName = HostNameExpanded;
  2394. UserName = UserNameExpanded;
  2395. PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);
  2396. }
  2397. //---------------------------------------------------------------------
  2398. void __fastcall TSessionData::ValidatePath(const UnicodeString Path)
  2399. {
  2400. // noop
  2401. }
  2402. //---------------------------------------------------------------------
  2403. void __fastcall TSessionData::ValidateName(const UnicodeString Name)
  2404. {
  2405. // keep consistent with MakeValidName
  2406. if (Name.LastDelimiter(L"/") > 0)
  2407. {
  2408. throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L"/")));
  2409. }
  2410. }
  2411. //---------------------------------------------------------------------
  2412. UnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)
  2413. {
  2414. // keep consistent with ValidateName
  2415. return ReplaceStr(Name, L"/", L"\\");
  2416. }
  2417. //---------------------------------------------------------------------
  2418. RawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)
  2419. {
  2420. return Configuration->EncryptPassword(Password, Key);
  2421. }
  2422. //---------------------------------------------------------------------
  2423. RawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)
  2424. {
  2425. return Configuration->StronglyRecryptPassword(Password, Key);
  2426. }
  2427. //---------------------------------------------------------------------
  2428. UnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)
  2429. {
  2430. UnicodeString Result;
  2431. try
  2432. {
  2433. Result = Configuration->DecryptPassword(Password, Key);
  2434. }
  2435. catch(EAbort &)
  2436. {
  2437. // silently ignore aborted prompts for master password and return empty password
  2438. }
  2439. return Result;
  2440. }
  2441. //---------------------------------------------------------------------
  2442. bool __fastcall TSessionData::GetCanLogin()
  2443. {
  2444. return !FHostName.IsEmpty();
  2445. }
  2446. //---------------------------------------------------------------------------
  2447. int TSessionData::GetDefaultPort()
  2448. {
  2449. return DefaultPort(FSProtocol, Ftps);
  2450. }
  2451. //---------------------------------------------------------------------------
  2452. UnicodeString __fastcall TSessionData::GetSessionKey()
  2453. {
  2454. UnicodeString Result = FORMAT(L"%s@%s", (UserName, HostName));
  2455. if (PortNumber != GetDefaultPort())
  2456. {
  2457. Result += FORMAT(L":%d", (PortNumber));
  2458. }
  2459. return Result;
  2460. }
  2461. //---------------------------------------------------------------------
  2462. UnicodeString __fastcall TSessionData::GetInternalStorageKey()
  2463. {
  2464. // This is probably useless remnant of previous use of this method from OpenSessionInPutty
  2465. // that needs the method to return something even for ad-hoc sessions
  2466. if (Name.IsEmpty())
  2467. {
  2468. return SessionKey;
  2469. }
  2470. else
  2471. {
  2472. return Name;
  2473. }
  2474. }
  2475. //---------------------------------------------------------------------
  2476. UnicodeString __fastcall TSessionData::GetStorageKey()
  2477. {
  2478. return SessionName;
  2479. }
  2480. //---------------------------------------------------------------------
  2481. UnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)
  2482. {
  2483. return FORMAT(L"%s:%d", (HostName, PortNumber));
  2484. }
  2485. //---------------------------------------------------------------------
  2486. UnicodeString __fastcall TSessionData::GetSiteKey()
  2487. {
  2488. return FormatSiteKey(HostNameExpanded, PortNumber);
  2489. }
  2490. //---------------------------------------------------------------------
  2491. void __fastcall TSessionData::SetHostName(UnicodeString value)
  2492. {
  2493. if (FHostName != value)
  2494. {
  2495. // HostName is key for password encryption
  2496. UnicodeString XPassword = Password;
  2497. UnicodeString XNewPassword = NewPassword;
  2498. UnicodeString XEncryptKey = EncryptKey;
  2499. // This is now hardly used as hostname is parsed directly on login dialog.
  2500. // But can be used when importing sites from PuTTY, as it allows same format too.
  2501. int P = value.LastDelimiter(L"@");
  2502. if (P > 0)
  2503. {
  2504. UserName = value.SubString(1, P - 1);
  2505. value = value.SubString(P + 1, value.Length() - P);
  2506. }
  2507. FHostName = value;
  2508. Modify();
  2509. Password = XPassword;
  2510. NewPassword = XNewPassword;
  2511. EncryptKey = XEncryptKey;
  2512. Shred(XPassword);
  2513. Shred(XNewPassword);
  2514. Shred(XEncryptKey);
  2515. }
  2516. }
  2517. //---------------------------------------------------------------------
  2518. UnicodeString __fastcall TSessionData::GetHostNameExpanded()
  2519. {
  2520. return ::ExpandEnvironmentVariables(HostName);
  2521. }
  2522. //---------------------------------------------------------------------
  2523. UnicodeString TSessionData::GetHostNameSource()
  2524. {
  2525. UnicodeString Result;
  2526. if (HostName != HostNameExpanded)
  2527. {
  2528. Result = HostName;
  2529. }
  2530. return Result;
  2531. }
  2532. //---------------------------------------------------------------------
  2533. void __fastcall TSessionData::SetPortNumber(int value)
  2534. {
  2535. SET_SESSION_PROPERTY(PortNumber);
  2536. }
  2537. //---------------------------------------------------------------------------
  2538. void __fastcall TSessionData::SetShell(UnicodeString value)
  2539. {
  2540. SET_SESSION_PROPERTY(Shell);
  2541. }
  2542. //---------------------------------------------------------------------------
  2543. void __fastcall TSessionData::SetSftpServer(UnicodeString value)
  2544. {
  2545. SET_SESSION_PROPERTY(SftpServer);
  2546. }
  2547. //---------------------------------------------------------------------------
  2548. void __fastcall TSessionData::SetClearAliases(bool value)
  2549. {
  2550. SET_SESSION_PROPERTY(ClearAliases);
  2551. }
  2552. //---------------------------------------------------------------------------
  2553. void __fastcall TSessionData::SetListingCommand(UnicodeString value)
  2554. {
  2555. SET_SESSION_PROPERTY(ListingCommand);
  2556. }
  2557. //---------------------------------------------------------------------------
  2558. void __fastcall TSessionData::SetIgnoreLsWarnings(bool value)
  2559. {
  2560. SET_SESSION_PROPERTY(IgnoreLsWarnings);
  2561. }
  2562. //---------------------------------------------------------------------------
  2563. void __fastcall TSessionData::SetUnsetNationalVars(bool value)
  2564. {
  2565. SET_SESSION_PROPERTY(UnsetNationalVars);
  2566. }
  2567. //---------------------------------------------------------------------
  2568. void __fastcall TSessionData::SetUserName(UnicodeString value)
  2569. {
  2570. // Avoid password recryption (what may popup master password prompt)
  2571. if (FUserName != value)
  2572. {
  2573. // UserName is key for password encryption
  2574. UnicodeString XPassword = Password;
  2575. UnicodeString XNewPassword = NewPassword;
  2576. UnicodeString XEncryptKey = EncryptKey;
  2577. SET_SESSION_PROPERTY(UserName);
  2578. Password = XPassword;
  2579. NewPassword = XNewPassword;
  2580. EncryptKey = XEncryptKey;
  2581. Shred(XPassword);
  2582. Shred(XNewPassword);
  2583. Shred(XEncryptKey);
  2584. }
  2585. }
  2586. //---------------------------------------------------------------------
  2587. UnicodeString __fastcall TSessionData::GetUserNameExpanded()
  2588. {
  2589. UnicodeString Result = ::ExpandEnvironmentVariables(UserName);
  2590. if (Result.IsEmpty() && HasS3AutoCredentials())
  2591. {
  2592. Result = S3EnvUserName();
  2593. }
  2594. return Result;
  2595. }
  2596. //---------------------------------------------------------------------
  2597. UnicodeString TSessionData::GetUserNameSource()
  2598. {
  2599. UnicodeString Result;
  2600. if (UserName.IsEmpty() && HasS3AutoCredentials())
  2601. {
  2602. S3EnvUserName(&Result);
  2603. }
  2604. if (Result.IsEmpty() && (UserName != UserNameExpanded))
  2605. {
  2606. Result = UserName;
  2607. }
  2608. return Result;
  2609. }
  2610. //---------------------------------------------------------------------
  2611. void __fastcall TSessionData::SetPassword(UnicodeString avalue)
  2612. {
  2613. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  2614. SET_SESSION_PROPERTY(Password);
  2615. }
  2616. //---------------------------------------------------------------------
  2617. UnicodeString __fastcall TSessionData::GetPassword() const
  2618. {
  2619. return DecryptPassword(FPassword, UserName+HostName);
  2620. }
  2621. //---------------------------------------------------------------------
  2622. void __fastcall TSessionData::SetNewPassword(UnicodeString avalue)
  2623. {
  2624. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  2625. SET_SESSION_PROPERTY(NewPassword);
  2626. }
  2627. //---------------------------------------------------------------------
  2628. UnicodeString __fastcall TSessionData::GetNewPassword() const
  2629. {
  2630. return DecryptPassword(FNewPassword, UserName+HostName);
  2631. }
  2632. //---------------------------------------------------------------------
  2633. void __fastcall TSessionData::SetChangePassword(bool value)
  2634. {
  2635. SET_SESSION_PROPERTY(ChangePassword);
  2636. }
  2637. //---------------------------------------------------------------------
  2638. void __fastcall TSessionData::SetPingInterval(int value)
  2639. {
  2640. SET_SESSION_PROPERTY(PingInterval);
  2641. }
  2642. //---------------------------------------------------------------------
  2643. void __fastcall TSessionData::SetTryAgent(bool value)
  2644. {
  2645. SET_SESSION_PROPERTY(TryAgent);
  2646. }
  2647. //---------------------------------------------------------------------
  2648. void __fastcall TSessionData::SetAgentFwd(bool value)
  2649. {
  2650. SET_SESSION_PROPERTY(AgentFwd);
  2651. }
  2652. //---------------------------------------------------------------------
  2653. void __fastcall TSessionData::SetAuthKI(bool value)
  2654. {
  2655. SET_SESSION_PROPERTY(AuthKI);
  2656. }
  2657. //---------------------------------------------------------------------
  2658. void __fastcall TSessionData::SetAuthKIPassword(bool value)
  2659. {
  2660. SET_SESSION_PROPERTY(AuthKIPassword);
  2661. }
  2662. //---------------------------------------------------------------------
  2663. void __fastcall TSessionData::SetAuthGSSAPI(bool value)
  2664. {
  2665. SET_SESSION_PROPERTY(AuthGSSAPI);
  2666. }
  2667. //---------------------------------------------------------------------
  2668. void __fastcall TSessionData::SetAuthGSSAPIKEX(bool value)
  2669. {
  2670. SET_SESSION_PROPERTY(AuthGSSAPIKEX);
  2671. }
  2672. //---------------------------------------------------------------------
  2673. void __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)
  2674. {
  2675. SET_SESSION_PROPERTY(GSSAPIFwdTGT);
  2676. }
  2677. //---------------------------------------------------------------------
  2678. void __fastcall TSessionData::SetChangeUsername(bool value)
  2679. {
  2680. SET_SESSION_PROPERTY(ChangeUsername);
  2681. }
  2682. //---------------------------------------------------------------------
  2683. void __fastcall TSessionData::SetCompression(bool value)
  2684. {
  2685. SET_SESSION_PROPERTY(Compression);
  2686. }
  2687. //---------------------------------------------------------------------
  2688. void __fastcall TSessionData::SetSsh2DES(bool value)
  2689. {
  2690. SET_SESSION_PROPERTY(Ssh2DES);
  2691. }
  2692. //---------------------------------------------------------------------
  2693. void __fastcall TSessionData::SetSshNoUserAuth(bool value)
  2694. {
  2695. SET_SESSION_PROPERTY(SshNoUserAuth);
  2696. }
  2697. //---------------------------------------------------------------------
  2698. bool __fastcall TSessionData::GetUsesSsh()
  2699. {
  2700. return IsSshProtocol(FSProtocol);
  2701. }
  2702. //---------------------------------------------------------------------
  2703. void __fastcall TSessionData::SetCipher(int Index, TCipher value)
  2704. {
  2705. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2706. SET_SESSION_PROPERTY(Ciphers[Index]);
  2707. }
  2708. //---------------------------------------------------------------------
  2709. TCipher __fastcall TSessionData::GetCipher(int Index) const
  2710. {
  2711. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2712. return FCiphers[Index];
  2713. }
  2714. //---------------------------------------------------------------------
  2715. template<class AlgoT>
  2716. void __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,
  2717. int Count, AlgoT WarnAlgo, UnicodeString value)
  2718. {
  2719. std::vector<bool> Used(Count); // initialized to false
  2720. std::vector<AlgoT> NewList(Count);
  2721. bool HasWarnAlgo = (WarnAlgo >= AlgoT());
  2722. const AlgoT * WarnPtr;
  2723. int WarnDefaultIndex;
  2724. if (!HasWarnAlgo)
  2725. {
  2726. WarnPtr = NULL;
  2727. WarnDefaultIndex = -1;
  2728. }
  2729. else
  2730. {
  2731. WarnPtr = std::find(DefaultList, DefaultList + Count, WarnAlgo);
  2732. DebugAssert(WarnPtr != NULL);
  2733. WarnDefaultIndex = (WarnPtr - DefaultList);
  2734. }
  2735. int Index = 0;
  2736. while (!value.IsEmpty())
  2737. {
  2738. UnicodeString AlgoStr = CutToChar(value, L',', true);
  2739. for (int Algo = 0; Algo < Count; Algo++)
  2740. {
  2741. if (!AlgoStr.CompareIC(Names[Algo]) &&
  2742. !Used[Algo] && DebugAlwaysTrue(Index < Count))
  2743. {
  2744. NewList[Index] = (AlgoT)Algo;
  2745. Used[Algo] = true;
  2746. Index++;
  2747. break;
  2748. }
  2749. }
  2750. }
  2751. if (HasWarnAlgo && !Used[WarnAlgo] && DebugAlwaysTrue(Index < Count))
  2752. {
  2753. NewList[Index] = WarnAlgo;
  2754. Used[WarnAlgo] = true;
  2755. Index++;
  2756. }
  2757. int WarnIndex = -1;
  2758. if (HasWarnAlgo)
  2759. {
  2760. WarnIndex = std::find(NewList.begin(), NewList.end(), WarnAlgo) - NewList.begin();
  2761. }
  2762. bool Priority = true;
  2763. for (int DefaultIndex = 0; (DefaultIndex < Count); DefaultIndex++)
  2764. {
  2765. AlgoT DefaultAlgo = DefaultList[DefaultIndex];
  2766. if (!Used[DefaultAlgo] && DebugAlwaysTrue(Index < Count))
  2767. {
  2768. int TargetIndex;
  2769. // Unused algs that are prioritized in the default list,
  2770. // should be merged before the existing custom list
  2771. if (Priority)
  2772. {
  2773. TargetIndex = DefaultIndex;
  2774. }
  2775. else
  2776. {
  2777. if (HasWarnAlgo && (DefaultIndex < WarnDefaultIndex))
  2778. {
  2779. TargetIndex = WarnIndex;
  2780. }
  2781. else
  2782. {
  2783. TargetIndex = Index;
  2784. }
  2785. }
  2786. NewList.insert(NewList.begin() + TargetIndex, DefaultAlgo);
  2787. DebugAssert(NewList.back() == AlgoT());
  2788. NewList.pop_back();
  2789. if (HasWarnAlgo && (TargetIndex <= WarnIndex))
  2790. {
  2791. WarnIndex++;
  2792. }
  2793. Index++;
  2794. }
  2795. else
  2796. {
  2797. Priority = false;
  2798. }
  2799. }
  2800. if (!std::equal(NewList.begin(), NewList.end(), List))
  2801. {
  2802. std::copy(NewList.begin(), NewList.end(), List);
  2803. Modify();
  2804. }
  2805. }
  2806. //---------------------------------------------------------------------
  2807. void __fastcall TSessionData::SetCipherList(UnicodeString value)
  2808. {
  2809. SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, cipWarn, value);
  2810. }
  2811. //---------------------------------------------------------------------
  2812. UnicodeString __fastcall TSessionData::GetCipherList() const
  2813. {
  2814. UnicodeString Result;
  2815. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  2816. {
  2817. Result += UnicodeString(Index ? L"," : L"") + CipherNames[Cipher[Index]];
  2818. }
  2819. return Result;
  2820. }
  2821. //---------------------------------------------------------------------
  2822. void __fastcall TSessionData::SetKex(int Index, TKex value)
  2823. {
  2824. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2825. SET_SESSION_PROPERTY(Kex[Index]);
  2826. }
  2827. //---------------------------------------------------------------------
  2828. TKex __fastcall TSessionData::GetKex(int Index) const
  2829. {
  2830. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2831. return FKex[Index];
  2832. }
  2833. //---------------------------------------------------------------------
  2834. void __fastcall TSessionData::SetKexList(UnicodeString value)
  2835. {
  2836. SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, kexWarn, value);
  2837. }
  2838. //---------------------------------------------------------------------
  2839. UnicodeString __fastcall TSessionData::GetKexList() const
  2840. {
  2841. UnicodeString Result;
  2842. for (int Index = 0; Index < KEX_COUNT; Index++)
  2843. {
  2844. Result += UnicodeString(Index ? L"," : L"") + KexNames[Kex[Index]];
  2845. }
  2846. return Result;
  2847. }
  2848. //---------------------------------------------------------------------
  2849. void __fastcall TSessionData::SetHostKeys(int Index, THostKey value)
  2850. {
  2851. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  2852. SET_SESSION_PROPERTY(HostKeys[Index]);
  2853. }
  2854. //---------------------------------------------------------------------
  2855. THostKey __fastcall TSessionData::GetHostKeys(int Index) const
  2856. {
  2857. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  2858. return FHostKeys[Index];
  2859. }
  2860. //---------------------------------------------------------------------
  2861. void __fastcall TSessionData::SetHostKeyList(UnicodeString value)
  2862. {
  2863. SetAlgoList(FHostKeys, DefaultHostKeyList, HostKeyNames, HOSTKEY_COUNT, hkWarn, value);
  2864. }
  2865. //---------------------------------------------------------------------
  2866. UnicodeString __fastcall TSessionData::GetHostKeyList() const
  2867. {
  2868. UnicodeString Result;
  2869. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  2870. {
  2871. Result += UnicodeString(Index ? L"," : L"") + HostKeyNames[HostKeys[Index]];
  2872. }
  2873. return Result;
  2874. }
  2875. //---------------------------------------------------------------------
  2876. void __fastcall TSessionData::SetGssLib(int Index, TGssLib value)
  2877. {
  2878. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  2879. SET_SESSION_PROPERTY(GssLib[Index]);
  2880. }
  2881. //---------------------------------------------------------------------
  2882. TGssLib __fastcall TSessionData::GetGssLib(int Index) const
  2883. {
  2884. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  2885. return FGssLib[Index];
  2886. }
  2887. //---------------------------------------------------------------------
  2888. void __fastcall TSessionData::SetGssLibList(UnicodeString value)
  2889. {
  2890. SetAlgoList(FGssLib, DefaultGssLibList, GssLibNames, GSSLIB_COUNT, TGssLib(-1), value);
  2891. }
  2892. //---------------------------------------------------------------------
  2893. UnicodeString __fastcall TSessionData::GetGssLibList() const
  2894. {
  2895. UnicodeString Result;
  2896. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  2897. {
  2898. Result += UnicodeString(Index ? L"," : L"") + GssLibNames[GssLib[Index]];
  2899. }
  2900. return Result;
  2901. }
  2902. //---------------------------------------------------------------------
  2903. void __fastcall TSessionData::SetGssLibCustom(UnicodeString value)
  2904. {
  2905. SET_SESSION_PROPERTY(GssLibCustom);
  2906. }
  2907. //---------------------------------------------------------------------
  2908. void __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)
  2909. {
  2910. if (FPublicKeyFile != value)
  2911. {
  2912. // PublicKeyFile is key for Passphrase encryption
  2913. UnicodeString XPassphrase = Passphrase;
  2914. // StripPathQuotes should not be needed as we do not feed quotes anymore
  2915. FPublicKeyFile = StripPathQuotes(value);
  2916. Modify();
  2917. Passphrase = XPassphrase;
  2918. Shred(XPassphrase);
  2919. }
  2920. }
  2921. //---------------------------------------------------------------------
  2922. void __fastcall TSessionData::SetPassphrase(UnicodeString avalue)
  2923. {
  2924. RawByteString value = EncryptPassword(avalue, PublicKeyFile);
  2925. SET_SESSION_PROPERTY(Passphrase);
  2926. }
  2927. //---------------------------------------------------------------------
  2928. UnicodeString __fastcall TSessionData::GetPassphrase() const
  2929. {
  2930. return DecryptPassword(FPassphrase, PublicKeyFile);
  2931. }
  2932. //---------------------------------------------------------------------
  2933. void __fastcall TSessionData::SetReturnVar(UnicodeString value)
  2934. {
  2935. SET_SESSION_PROPERTY(ReturnVar);
  2936. }
  2937. //---------------------------------------------------------------------
  2938. void __fastcall TSessionData::SetExitCode1IsError(bool value)
  2939. {
  2940. SET_SESSION_PROPERTY(ExitCode1IsError);
  2941. }
  2942. //---------------------------------------------------------------------------
  2943. void __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)
  2944. {
  2945. SET_SESSION_PROPERTY(LookupUserGroups);
  2946. }
  2947. //---------------------------------------------------------------------------
  2948. void __fastcall TSessionData::SetEOLType(TEOLType value)
  2949. {
  2950. SET_SESSION_PROPERTY(EOLType);
  2951. }
  2952. //---------------------------------------------------------------------------
  2953. void __fastcall TSessionData::SetTrimVMSVersions(bool value)
  2954. {
  2955. SET_SESSION_PROPERTY(TrimVMSVersions);
  2956. }
  2957. //---------------------------------------------------------------------------
  2958. void __fastcall TSessionData::SetVMSAllRevisions(bool value)
  2959. {
  2960. SET_SESSION_PROPERTY(VMSAllRevisions);
  2961. }
  2962. //---------------------------------------------------------------------------
  2963. TDateTime __fastcall TSessionData::GetTimeoutDT()
  2964. {
  2965. return SecToDateTime(Timeout);
  2966. }
  2967. //---------------------------------------------------------------------------
  2968. void __fastcall TSessionData::SetTimeout(int value)
  2969. {
  2970. SET_SESSION_PROPERTY(Timeout);
  2971. }
  2972. //---------------------------------------------------------------------------
  2973. void __fastcall TSessionData::SetFSProtocol(TFSProtocol value)
  2974. {
  2975. SET_SESSION_PROPERTY(FSProtocol);
  2976. }
  2977. //---------------------------------------------------------------------
  2978. UnicodeString __fastcall TSessionData::GetFSProtocolStr()
  2979. {
  2980. DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);
  2981. return FSProtocolNames[FSProtocol];
  2982. }
  2983. //---------------------------------------------------------------------------
  2984. void __fastcall TSessionData::SetDetectReturnVar(bool value)
  2985. {
  2986. if (value != DetectReturnVar)
  2987. {
  2988. ReturnVar = value ? L"" : L"$?";
  2989. }
  2990. }
  2991. //---------------------------------------------------------------------------
  2992. bool __fastcall TSessionData::GetDetectReturnVar()
  2993. {
  2994. return ReturnVar.IsEmpty();
  2995. }
  2996. //---------------------------------------------------------------------------
  2997. void __fastcall TSessionData::SetDefaultShell(bool value)
  2998. {
  2999. if (value != DefaultShell)
  3000. {
  3001. Shell = value ? L"" : L"/bin/bash";
  3002. }
  3003. }
  3004. //---------------------------------------------------------------------------
  3005. bool __fastcall TSessionData::GetDefaultShell()
  3006. {
  3007. return Shell.IsEmpty();
  3008. }
  3009. //---------------------------------------------------------------------------
  3010. void __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)
  3011. {
  3012. SET_SESSION_PROPERTY(PuttyProtocol);
  3013. }
  3014. //---------------------------------------------------------------------
  3015. UnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const
  3016. {
  3017. return DefaultStr(PuttyProtocol, PuttySshProtocol);
  3018. }
  3019. //---------------------------------------------------------------------
  3020. void __fastcall TSessionData::SetPingIntervalDT(TDateTime value)
  3021. {
  3022. unsigned short hour, min, sec, msec;
  3023. value.DecodeTime(&hour, &min, &sec, &msec);
  3024. PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;
  3025. }
  3026. //---------------------------------------------------------------------------
  3027. TDateTime __fastcall TSessionData::GetPingIntervalDT()
  3028. {
  3029. return SecToDateTime(PingInterval);
  3030. }
  3031. //---------------------------------------------------------------------------
  3032. void __fastcall TSessionData::SetPingType(TPingType value)
  3033. {
  3034. SET_SESSION_PROPERTY(PingType);
  3035. }
  3036. //---------------------------------------------------------------------------
  3037. void __fastcall TSessionData::SetAddressFamily(TAddressFamily value)
  3038. {
  3039. SET_SESSION_PROPERTY(AddressFamily);
  3040. }
  3041. //---------------------------------------------------------------------------
  3042. void __fastcall TSessionData::SetRekeyData(UnicodeString value)
  3043. {
  3044. SET_SESSION_PROPERTY(RekeyData);
  3045. }
  3046. //---------------------------------------------------------------------------
  3047. void __fastcall TSessionData::SetRekeyTime(unsigned int value)
  3048. {
  3049. SET_SESSION_PROPERTY(RekeyTime);
  3050. }
  3051. //---------------------------------------------------------------------
  3052. UnicodeString __fastcall TSessionData::GetDefaultSessionName()
  3053. {
  3054. UnicodeString Result;
  3055. if (!HostName.IsEmpty() && !UserName.IsEmpty())
  3056. {
  3057. // If we ever choose to include port number,
  3058. // we have to escape IPv6 literals in HostName
  3059. Result = FORMAT(L"%s@%s", (UserName, HostName));
  3060. }
  3061. else if (!HostName.IsEmpty())
  3062. {
  3063. Result = HostName;
  3064. }
  3065. else
  3066. {
  3067. Result = L"session";
  3068. }
  3069. Result = MakeValidName(Result);
  3070. return Result;
  3071. }
  3072. //---------------------------------------------------------------------
  3073. UnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()
  3074. {
  3075. UnicodeString Result = Name;
  3076. if (Hidden)
  3077. {
  3078. Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());
  3079. }
  3080. return Result;
  3081. }
  3082. //---------------------------------------------------------------------
  3083. bool __fastcall TSessionData::HasSessionName()
  3084. {
  3085. return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName));
  3086. }
  3087. //---------------------------------------------------------------------
  3088. UnicodeString __fastcall TSessionData::GetSessionName()
  3089. {
  3090. UnicodeString Result;
  3091. if (HasSessionName())
  3092. {
  3093. Result = GetNameWithoutHiddenPrefix();
  3094. }
  3095. else
  3096. {
  3097. Result = DefaultSessionName;
  3098. }
  3099. return Result;
  3100. }
  3101. //---------------------------------------------------------------------
  3102. bool __fastcall TSessionData::IsSecure()
  3103. {
  3104. bool Result;
  3105. switch (FSProtocol)
  3106. {
  3107. case fsSCPonly:
  3108. case fsSFTP:
  3109. case fsSFTPonly:
  3110. Result = true;
  3111. break;
  3112. case fsFTP:
  3113. case fsWebDAV:
  3114. case fsS3:
  3115. Result = (Ftps != ftpsNone);
  3116. break;
  3117. default:
  3118. DebugFail();
  3119. break;
  3120. }
  3121. return Result;
  3122. }
  3123. //---------------------------------------------------------------------
  3124. UnicodeString __fastcall TSessionData::GetProtocolUrl(bool HttpForWebDAV)
  3125. {
  3126. UnicodeString Url;
  3127. switch (FSProtocol)
  3128. {
  3129. case fsSCPonly:
  3130. Url = ScpProtocol;
  3131. break;
  3132. default:
  3133. DebugFail();
  3134. // fallback
  3135. case fsSFTP:
  3136. case fsSFTPonly:
  3137. Url = SftpProtocol;
  3138. break;
  3139. case fsFTP:
  3140. if (Ftps == ftpsImplicit)
  3141. {
  3142. Url = FtpsProtocol;
  3143. }
  3144. else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))
  3145. {
  3146. Url = FtpesProtocol;
  3147. }
  3148. else
  3149. {
  3150. Url = FtpProtocol;
  3151. }
  3152. break;
  3153. case fsWebDAV:
  3154. if (HttpForWebDAV)
  3155. {
  3156. if (Ftps == ftpsImplicit)
  3157. {
  3158. Url = HttpsProtocol;
  3159. }
  3160. else
  3161. {
  3162. Url = HttpProtocol;
  3163. }
  3164. }
  3165. else
  3166. {
  3167. if (Ftps == ftpsImplicit)
  3168. {
  3169. Url = WebDAVSProtocol;
  3170. }
  3171. else
  3172. {
  3173. Url = WebDAVProtocol;
  3174. }
  3175. }
  3176. break;
  3177. case fsS3:
  3178. Url = S3Protocol;
  3179. break;
  3180. }
  3181. Url += ProtocolSeparator;
  3182. return Url;
  3183. }
  3184. //---------------------------------------------------------------------
  3185. static bool HasIP6LiteralBrackets(const UnicodeString & HostName)
  3186. {
  3187. return
  3188. (HostName.Length() >= 2) &&
  3189. (HostName[1] == L'[') &&
  3190. (HostName[HostName.Length()] == L']');
  3191. }
  3192. //---------------------------------------------------------------------
  3193. static UnicodeString StripIP6LiteralBrackets(const UnicodeString & HostName)
  3194. {
  3195. UnicodeString Result = HostName;
  3196. if (DebugAlwaysTrue(HasIP6LiteralBrackets(Result)))
  3197. {
  3198. Result = Result.SubString(2, Result.Length() - 2);
  3199. }
  3200. return Result;
  3201. }
  3202. //---------------------------------------------------------------------
  3203. bool __fastcall IsIPv6Literal(const UnicodeString & HostName)
  3204. {
  3205. UnicodeString Buf = HostName;
  3206. if (HasIP6LiteralBrackets(Buf))
  3207. {
  3208. Buf = StripIP6LiteralBrackets(Buf);
  3209. }
  3210. int Colons = 0;
  3211. bool Result = true;
  3212. for (int Index = 1; Result && (Index <= Buf.Length()); Index++)
  3213. {
  3214. wchar_t C = Buf[Index];
  3215. if (C == L'%')
  3216. {
  3217. break;
  3218. }
  3219. else if (C == L':')
  3220. {
  3221. Colons++;
  3222. }
  3223. else
  3224. {
  3225. Result = IsHex(C);
  3226. }
  3227. }
  3228. Result = Result && (Colons >= 2);
  3229. return Result;
  3230. }
  3231. //---------------------------------------------------------------------
  3232. UnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP)
  3233. {
  3234. UnicodeString Result = IP;
  3235. if (!HasIP6LiteralBrackets(Result))
  3236. {
  3237. Result = L"[" + IP + L"]";
  3238. }
  3239. return Result;
  3240. }
  3241. //---------------------------------------------------------------------
  3242. TStrings * __fastcall TSessionData::GetRawSettingsForUrl()
  3243. {
  3244. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3245. std::unique_ptr<TSessionData> SessionData(Clone());
  3246. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3247. SessionData->HostName = FactoryDefaults->HostName;
  3248. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3249. SessionData->UserName = FactoryDefaults->UserName;
  3250. SessionData->Password = FactoryDefaults->Password;
  3251. SessionData->Ftps = FactoryDefaults->Ftps;
  3252. SessionData->HostKey = FactoryDefaults->HostKey;
  3253. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3254. // Cannot be decided in SaveToOptions as it does not have HostName and UserName, so it cannot calculate DefaultSessionName.
  3255. bool SaveName = HasSessionName() && (Name != DefaultSessionName);
  3256. return SessionData->SaveToOptions(FactoryDefaults.get(), SaveName, false);
  3257. }
  3258. //---------------------------------------------------------------------
  3259. bool __fastcall TSessionData::HasRawSettingsForUrl()
  3260. {
  3261. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3262. return (RawSettings->Count > 0);
  3263. }
  3264. //---------------------------------------------------------------------
  3265. UnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)
  3266. {
  3267. UnicodeString Url;
  3268. if (FLAGSET(Flags, sufSpecific))
  3269. {
  3270. Url += WinSCPProtocolPrefix;
  3271. }
  3272. Url += GetProtocolUrl(FLAGSET(Flags, sufHttpForWebDAV));
  3273. // Add username only if it was somehow explicitly specified (so not with S3CredentialsEnv), but if it was, add it in the expanded form.
  3274. // For scripting, we might use unexpanded form (keeping the environment variables),
  3275. // but for consistency with code generation (where explicit expansion code would need to be added), we do not.
  3276. if (FLAGSET(Flags, sufUserName) && !UserName.IsEmpty())
  3277. {
  3278. Url += EncodeUrlString(UserNameExpanded);
  3279. if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())
  3280. {
  3281. Url += L":" + EncodeUrlString(NormalizeString(Password));
  3282. }
  3283. if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())
  3284. {
  3285. UnicodeString KeyName;
  3286. UnicodeString Fingerprint = HostKey;
  3287. NormalizeFingerprint(Fingerprint, KeyName);
  3288. UnicodeString S = Fingerprint;
  3289. if (!KeyName.IsEmpty())
  3290. {
  3291. S = KeyName + NormalizedFingerprintSeparator + S;
  3292. }
  3293. S = Base64ToUrlSafe(S); // Noop for MD5 (both in SSH host keys and TLS/SSL)
  3294. S = MD5ToUrlSafe(S); // TLS/SSL fingerprints
  3295. UnicodeString S2 = EncodeUrlString(S);
  3296. DebugAssert(S2 == S2); // There should be nothing left for encoding
  3297. Url +=
  3298. UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +
  3299. UnicodeString(UrlParamValueSeparator) + S2;
  3300. }
  3301. if (FLAGSET(Flags, sufRawSettings))
  3302. {
  3303. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3304. for (int Index = 0; Index < RawSettings->Count; Index++)
  3305. {
  3306. Url +=
  3307. UnicodeString(UrlParamSeparator) +
  3308. UrlRawSettingsParamNamePrefix + EncodeUrlString(LowerCase(RawSettings->Names[Index])) +
  3309. UnicodeString(UrlParamValueSeparator) + EncodeUrlString(RawSettings->ValueFromIndex[Index]);
  3310. }
  3311. }
  3312. Url += L"@";
  3313. }
  3314. DebugAssert(!HostNameExpanded.IsEmpty());
  3315. if (IsIPv6Literal(HostNameExpanded))
  3316. {
  3317. Url += EscapeIPv6Literal(HostNameExpanded);
  3318. }
  3319. else
  3320. {
  3321. Url += EncodeUrlString(HostNameExpanded);
  3322. }
  3323. if (PortNumber != GetDefaultPort())
  3324. {
  3325. Url += L":" + IntToStr(PortNumber);
  3326. }
  3327. Url += L"/";
  3328. return Url;
  3329. }
  3330. //---------------------------------------------------------------------
  3331. UnicodeString ScriptCommandOpenLink(TraceInitStr(ScriptCommandLink(L"open")));
  3332. //---------------------------------------------------------------------
  3333. void __fastcall TSessionData::AddSwitch(
  3334. UnicodeString & Result, const UnicodeString & Name, bool Rtf)
  3335. {
  3336. Result += RtfSwitch(Name, ScriptCommandOpenLink, Rtf);
  3337. }
  3338. //---------------------------------------------------------------------
  3339. void __fastcall TSessionData::AddSwitch(
  3340. UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf)
  3341. {
  3342. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3343. }
  3344. //---------------------------------------------------------------------
  3345. void __fastcall TSessionData::AddSwitch(
  3346. UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf)
  3347. {
  3348. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3349. }
  3350. //---------------------------------------------------------------------
  3351. void __fastcall TSessionData::LookupLastFingerprint()
  3352. {
  3353. UnicodeString FingerprintType;
  3354. if (IsSshProtocol(FSProtocol))
  3355. {
  3356. FingerprintType = SshFingerprintType;
  3357. }
  3358. else if (Ftps != ftpsNone)
  3359. {
  3360. FingerprintType = TlsFingerprintType;
  3361. }
  3362. if (!FingerprintType.IsEmpty())
  3363. {
  3364. HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);
  3365. }
  3366. if (Tunnel)
  3367. {
  3368. // not used anyway
  3369. int TunnelPortNumber = std::max(TunnelLocalPortNumber, Configuration->TunnelLocalPortNumberLow);
  3370. std::unique_ptr<TSessionData> TunnelData(CreateTunnelData(TunnelPortNumber));
  3371. TunnelHostKey = Configuration->LastFingerprint(TunnelData->SiteKey, SshFingerprintType);
  3372. }
  3373. }
  3374. //---------------------------------------------------------------------
  3375. UnicodeString __fastcall TSessionData::GenerateOpenCommandArgs(bool Rtf)
  3376. {
  3377. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3378. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3379. SessionData->Assign(this);
  3380. UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);
  3381. // Before we reset the FSProtocol
  3382. bool AUsesSsh = SessionData->UsesSsh;
  3383. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3384. if (SessionData->FSProtocol != fsSFTPonly)
  3385. {
  3386. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3387. }
  3388. SessionData->HostName = FactoryDefaults->HostName;
  3389. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3390. SessionData->UserName = FactoryDefaults->UserName;
  3391. SessionData->Password = FactoryDefaults->Password;
  3392. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3393. SessionData->Ftps = FactoryDefaults->Ftps;
  3394. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3395. {
  3396. UnicodeString SwitchName = AUsesSsh ? L"hostkey" : L"certificate";
  3397. AddSwitch(Result, SwitchName, SessionData->HostKey, Rtf);
  3398. SessionData->HostKey = FactoryDefaults->HostKey;
  3399. }
  3400. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3401. {
  3402. AddSwitch(Result, L"privatekey", SessionData->PublicKeyFile, Rtf);
  3403. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3404. }
  3405. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3406. {
  3407. AddSwitch(Result, L"clientcert", SessionData->TlsCertificateFile, Rtf);
  3408. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3409. }
  3410. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3411. {
  3412. AddSwitch(Result, PassphraseOption, SessionData->Passphrase, Rtf);
  3413. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3414. }
  3415. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3416. {
  3417. AddSwitch(Result, L"passive", SessionData->FtpPasvMode ? 1 : 0, Rtf);
  3418. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3419. }
  3420. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3421. {
  3422. AddSwitch(Result, L"timeout", SessionData->Timeout, Rtf);
  3423. SessionData->Timeout = FactoryDefaults->Timeout;
  3424. }
  3425. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3426. if (RawSettings->Count > 0)
  3427. {
  3428. AddSwitch(Result, RawSettingsOption, Rtf);
  3429. Result += StringsToParams(RawSettings.get());
  3430. }
  3431. return Result;
  3432. }
  3433. //---------------------------------------------------------------------
  3434. UnicodeString SessionOptionsClassName(L"SessionOptions");
  3435. //---------------------------------------------------------------------
  3436. void __fastcall TSessionData::AddAssemblyProperty(
  3437. UnicodeString & Result, TAssemblyLanguage Language,
  3438. const UnicodeString & Name, const UnicodeString & Type,
  3439. const UnicodeString & Member)
  3440. {
  3441. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Type, Member, false);
  3442. }
  3443. //---------------------------------------------------------------------
  3444. void __fastcall TSessionData::AddAssemblyProperty(
  3445. UnicodeString & Result, TAssemblyLanguage Language,
  3446. const UnicodeString & Name, const UnicodeString & Value)
  3447. {
  3448. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3449. }
  3450. //---------------------------------------------------------------------
  3451. void __fastcall TSessionData::AddAssemblyProperty(
  3452. UnicodeString & Result, TAssemblyLanguage Language,
  3453. const UnicodeString & Name, int Value)
  3454. {
  3455. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3456. }
  3457. //---------------------------------------------------------------------
  3458. void __fastcall TSessionData::AddAssemblyProperty(
  3459. UnicodeString & Result, TAssemblyLanguage Language,
  3460. const UnicodeString & Name, bool Value)
  3461. {
  3462. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3463. }
  3464. //---------------------------------------------------------------------
  3465. void __fastcall TSessionData::GenerateAssemblyCode(
  3466. TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent)
  3467. {
  3468. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3469. std::unique_ptr<TSessionData> SessionData(Clone());
  3470. switch (Language)
  3471. {
  3472. case alCSharp:
  3473. case alVBNET:
  3474. // noop
  3475. break;
  3476. case alPowerShell:
  3477. Head +=
  3478. AssemblyCommentLine(Language, LoadStr(CODE_PS_ADD_TYPE)) +
  3479. RtfKeyword(L"Add-Type") + RtfText(" -Path ") + AssemblyString(Language, "WinSCPnet.dll") + RtfPara +
  3480. RtfPara;
  3481. break;
  3482. default:
  3483. DebugFail();
  3484. break;
  3485. }
  3486. Head +=
  3487. AssemblyCommentLine(Language, LoadStr(CODE_SESSION_OPTIONS)) +
  3488. AssemblyNewClassInstanceStart(Language, SessionOptionsClassName, false);
  3489. UnicodeString ProtocolMember;
  3490. switch (SessionData->FSProtocol)
  3491. {
  3492. case fsSCPonly:
  3493. ProtocolMember = "Scp";
  3494. break;
  3495. default:
  3496. DebugFail();
  3497. // fallback
  3498. case fsSFTP:
  3499. case fsSFTPonly:
  3500. ProtocolMember = "Sftp";
  3501. break;
  3502. case fsFTP:
  3503. ProtocolMember = "Ftp";
  3504. break;
  3505. case fsWebDAV:
  3506. ProtocolMember = "Webdav";
  3507. break;
  3508. case fsS3:
  3509. ProtocolMember = "S3";
  3510. break;
  3511. }
  3512. // Before we reset the FSProtocol
  3513. bool AUsesSsh = SessionData->UsesSsh;
  3514. // Protocol is set unconditionally, we want even the default SFTP
  3515. AddAssemblyProperty(Head, Language, L"Protocol", L"Protocol", ProtocolMember);
  3516. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3517. if (SessionData->FSProtocol != fsSFTPonly)
  3518. {
  3519. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3520. }
  3521. if (SessionData->HostName != FactoryDefaults->HostName)
  3522. {
  3523. AddAssemblyProperty(Head, Language, L"HostName", HostName);
  3524. SessionData->HostName = FactoryDefaults->HostName;
  3525. }
  3526. int ADefaultPort = GetDefaultPort();
  3527. if (SessionData->PortNumber != ADefaultPort)
  3528. {
  3529. AddAssemblyProperty(Head, Language, L"PortNumber", PortNumber);
  3530. }
  3531. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3532. if (SessionData->UserName != FactoryDefaults->UserName)
  3533. {
  3534. AddAssemblyProperty(Head, Language, L"UserName", UserName);
  3535. SessionData->UserName = FactoryDefaults->UserName;
  3536. }
  3537. if (SessionData->Password != FactoryDefaults->Password)
  3538. {
  3539. AddAssemblyProperty(Head, Language, L"Password", NormalizeString(Password));
  3540. SessionData->Password = FactoryDefaults->Password;
  3541. }
  3542. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3543. if (SessionData->Ftps != FactoryDefaults->Ftps)
  3544. {
  3545. // SessionData->FSProtocol is reset already
  3546. switch (FSProtocol)
  3547. {
  3548. case fsFTP:
  3549. {
  3550. UnicodeString FtpSecureMember;
  3551. switch (SessionData->Ftps)
  3552. {
  3553. case ftpsNone:
  3554. // noop
  3555. break;
  3556. case ftpsImplicit:
  3557. FtpSecureMember = L"Implicit";
  3558. break;
  3559. case ftpsExplicitTls:
  3560. case ftpsExplicitSsl:
  3561. FtpSecureMember = L"Explicit";
  3562. break;
  3563. default:
  3564. DebugFail();
  3565. break;
  3566. }
  3567. AddAssemblyProperty(Head, Language, L"FtpSecure", L"FtpSecure", FtpSecureMember);
  3568. }
  3569. break;
  3570. case fsWebDAV:
  3571. AddAssemblyProperty(Head, Language, L"WebdavSecure", (SessionData->Ftps != ftpsNone));
  3572. break;
  3573. case fsS3:
  3574. // implicit
  3575. break;
  3576. default:
  3577. DebugFail();
  3578. break;
  3579. }
  3580. SessionData->Ftps = FactoryDefaults->Ftps;
  3581. }
  3582. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3583. {
  3584. UnicodeString PropertyName = AUsesSsh ? L"SshHostKeyFingerprint" : L"TlsHostCertificateFingerprint";
  3585. AddAssemblyProperty(Head, Language, PropertyName, SessionData->HostKey);
  3586. SessionData->HostKey = FactoryDefaults->HostKey;
  3587. }
  3588. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3589. {
  3590. AddAssemblyProperty(Head, Language, L"SshPrivateKeyPath", SessionData->PublicKeyFile);
  3591. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3592. }
  3593. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3594. {
  3595. AddAssemblyProperty(Head, Language, L"TlsClientCertificatePath", SessionData->TlsCertificateFile);
  3596. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3597. }
  3598. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3599. {
  3600. AddAssemblyProperty(Head, Language, L"PrivateKeyPassphrase", SessionData->Passphrase);
  3601. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3602. }
  3603. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3604. {
  3605. AddAssemblyProperty(Head, Language, L"FtpMode", L"FtpMode", (SessionData->FtpPasvMode ? L"Passive" : L"Active"));
  3606. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3607. }
  3608. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3609. {
  3610. AddAssemblyProperty(Head, Language, L"TimeoutInMilliseconds", SessionData->Timeout * 1000);
  3611. SessionData->Timeout = FactoryDefaults->Timeout;
  3612. }
  3613. Head += AssemblyNewClassInstanceEnd(Language, false);
  3614. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3615. UnicodeString SessionOptionsVariableName = AssemblyVariableName(Language, SessionOptionsClassName);
  3616. if (RawSettings->Count > 0)
  3617. {
  3618. Head +=
  3619. RtfPara +
  3620. AssemblyAddRawSettings(Language, RawSettings.get(), SessionOptionsClassName, L"AddRawSettings");
  3621. }
  3622. Head += RtfPara;
  3623. UnicodeString Indentation = L" ";
  3624. UnicodeString SessionVariableName = AssemblyVariableName(Language, SessionClassName);
  3625. UnicodeString RtfSessionClass = RtfLibraryClass(SessionClassName);
  3626. UnicodeString RtfSessionOpenMethod = RtfLibraryMethod(SessionClassName, L"Open", false);
  3627. UnicodeString NewSessionInstance = AssemblyNewClassInstance(Language, SessionClassName, false);
  3628. UnicodeString OpenCall =
  3629. Indentation + AssemblyCommentLine(Language, LoadStr(CODE_CONNECT)) +
  3630. Indentation + RtfText(SessionVariableName + L".") + RtfSessionOpenMethod + RtfText(L"(" + SessionOptionsVariableName + L")") +
  3631. AssemblyStatementSeparator(Language) + RtfPara;
  3632. switch (Language)
  3633. {
  3634. case alCSharp:
  3635. Head +=
  3636. RtfKeyword(L"using") + RtfText(" (") + NewSessionInstance + RtfText(L"())") + RtfPara +
  3637. RtfText(L"{") + RtfPara +
  3638. OpenCall;
  3639. Tail =
  3640. RtfText(L"}") + RtfPara;
  3641. break;
  3642. case alVBNET:
  3643. Head +=
  3644. RtfKeyword(L"Using") + RtfText(L" ") + NewSessionInstance + RtfPara +
  3645. OpenCall;
  3646. Tail =
  3647. RtfKeyword(L"End Using") + RtfPara;
  3648. break;
  3649. case alPowerShell:
  3650. Head +=
  3651. NewSessionInstance + RtfPara +
  3652. RtfPara +
  3653. RtfKeyword(L"try") + RtfPara +
  3654. RtfText(L"{") + RtfPara +
  3655. OpenCall;
  3656. Tail =
  3657. RtfText(L"}") + RtfPara +
  3658. RtfKeyword(L"finally") + RtfPara +
  3659. RtfText(L"{") + RtfPara +
  3660. RtfText(Indentation + SessionVariableName + L".") +
  3661. RtfLibraryMethod(SessionClassName, L"Dispose", false) + RtfText(L"()") + RtfPara +
  3662. RtfText(L"}") + RtfPara;
  3663. break;
  3664. }
  3665. Head += RtfPara;
  3666. Indent = 4; // the same for all languages so far
  3667. }
  3668. //---------------------------------------------------------------------
  3669. void __fastcall TSessionData::SetTimeDifference(TDateTime value)
  3670. {
  3671. SET_SESSION_PROPERTY(TimeDifference);
  3672. }
  3673. //---------------------------------------------------------------------
  3674. void __fastcall TSessionData::SetTimeDifferenceAuto(bool value)
  3675. {
  3676. SET_SESSION_PROPERTY(TimeDifferenceAuto);
  3677. }
  3678. //---------------------------------------------------------------------
  3679. void __fastcall TSessionData::SetLocalDirectory(UnicodeString value)
  3680. {
  3681. SET_SESSION_PROPERTY(LocalDirectory);
  3682. }
  3683. //---------------------------------------------------------------------
  3684. UnicodeString __fastcall TSessionData::GetLocalDirectoryExpanded()
  3685. {
  3686. return ExpandFileName(::ExpandEnvironmentVariables(LocalDirectory));
  3687. }
  3688. //---------------------------------------------------------------------
  3689. void __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)
  3690. {
  3691. SET_SESSION_PROPERTY(RemoteDirectory);
  3692. }
  3693. //---------------------------------------------------------------------
  3694. void __fastcall TSessionData::SetSynchronizeBrowsing(bool value)
  3695. {
  3696. SET_SESSION_PROPERTY(SynchronizeBrowsing);
  3697. }
  3698. //---------------------------------------------------------------------
  3699. void __fastcall TSessionData::SetUpdateDirectories(bool value)
  3700. {
  3701. SET_SESSION_PROPERTY(UpdateDirectories);
  3702. }
  3703. //---------------------------------------------------------------------
  3704. void __fastcall TSessionData::SetCacheDirectories(bool value)
  3705. {
  3706. SET_SESSION_PROPERTY(CacheDirectories);
  3707. }
  3708. //---------------------------------------------------------------------
  3709. void __fastcall TSessionData::SetCacheDirectoryChanges(bool value)
  3710. {
  3711. SET_SESSION_PROPERTY(CacheDirectoryChanges);
  3712. }
  3713. //---------------------------------------------------------------------
  3714. void __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)
  3715. {
  3716. SET_SESSION_PROPERTY(PreserveDirectoryChanges);
  3717. }
  3718. //---------------------------------------------------------------------
  3719. void __fastcall TSessionData::SetResolveSymlinks(bool value)
  3720. {
  3721. SET_SESSION_PROPERTY(ResolveSymlinks);
  3722. }
  3723. //---------------------------------------------------------------------
  3724. void __fastcall TSessionData::SetFollowDirectorySymlinks(bool value)
  3725. {
  3726. SET_SESSION_PROPERTY(FollowDirectorySymlinks);
  3727. }
  3728. //---------------------------------------------------------------------------
  3729. void __fastcall TSessionData::SetDSTMode(TDSTMode value)
  3730. {
  3731. SET_SESSION_PROPERTY(DSTMode);
  3732. }
  3733. //---------------------------------------------------------------------------
  3734. void __fastcall TSessionData::SetDeleteToRecycleBin(bool value)
  3735. {
  3736. SET_SESSION_PROPERTY(DeleteToRecycleBin);
  3737. }
  3738. //---------------------------------------------------------------------------
  3739. void __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)
  3740. {
  3741. SET_SESSION_PROPERTY(OverwrittenToRecycleBin);
  3742. }
  3743. //---------------------------------------------------------------------------
  3744. void __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)
  3745. {
  3746. SET_SESSION_PROPERTY(RecycleBinPath);
  3747. }
  3748. //---------------------------------------------------------------------------
  3749. void __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)
  3750. {
  3751. SET_SESSION_PROPERTY(PostLoginCommands);
  3752. }
  3753. //---------------------------------------------------------------------
  3754. void __fastcall TSessionData::SetSpecial(bool value)
  3755. {
  3756. SET_SESSION_PROPERTY(Special);
  3757. }
  3758. //---------------------------------------------------------------------------
  3759. void __fastcall TSessionData::SetScp1Compatibility(bool value)
  3760. {
  3761. SET_SESSION_PROPERTY(Scp1Compatibility);
  3762. }
  3763. //---------------------------------------------------------------------
  3764. void __fastcall TSessionData::SetTcpNoDelay(bool value)
  3765. {
  3766. SET_SESSION_PROPERTY(TcpNoDelay);
  3767. }
  3768. //---------------------------------------------------------------------
  3769. void __fastcall TSessionData::SetSendBuf(int value)
  3770. {
  3771. SET_SESSION_PROPERTY(SendBuf);
  3772. }
  3773. //---------------------------------------------------------------------
  3774. void __fastcall TSessionData::SetSourceAddress(const UnicodeString & value)
  3775. {
  3776. SET_SESSION_PROPERTY(SourceAddress);
  3777. }
  3778. //---------------------------------------------------------------------
  3779. void __fastcall TSessionData::SetProtocolFeatures(const UnicodeString & value)
  3780. {
  3781. SET_SESSION_PROPERTY(ProtocolFeatures);
  3782. }
  3783. //---------------------------------------------------------------------
  3784. void __fastcall TSessionData::SetSshSimple(bool value)
  3785. {
  3786. SET_SESSION_PROPERTY(SshSimple);
  3787. }
  3788. //---------------------------------------------------------------------
  3789. void __fastcall TSessionData::SetProxyMethod(TProxyMethod value)
  3790. {
  3791. SET_SESSION_PROPERTY(ProxyMethod);
  3792. }
  3793. //---------------------------------------------------------------------
  3794. void __fastcall TSessionData::SetProxyHost(UnicodeString value)
  3795. {
  3796. SET_SESSION_PROPERTY(ProxyHost);
  3797. }
  3798. //---------------------------------------------------------------------
  3799. void __fastcall TSessionData::SetProxyPort(int value)
  3800. {
  3801. SET_SESSION_PROPERTY(ProxyPort);
  3802. }
  3803. //---------------------------------------------------------------------
  3804. void __fastcall TSessionData::SetProxyUsername(UnicodeString value)
  3805. {
  3806. SET_SESSION_PROPERTY(ProxyUsername);
  3807. }
  3808. //---------------------------------------------------------------------
  3809. void __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)
  3810. {
  3811. RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);
  3812. SET_SESSION_PROPERTY(ProxyPassword);
  3813. }
  3814. //---------------------------------------------------------------------
  3815. UnicodeString __fastcall TSessionData::GetProxyPassword() const
  3816. {
  3817. return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);
  3818. }
  3819. //---------------------------------------------------------------------
  3820. void __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)
  3821. {
  3822. SET_SESSION_PROPERTY(ProxyTelnetCommand);
  3823. }
  3824. //---------------------------------------------------------------------
  3825. void __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)
  3826. {
  3827. SET_SESSION_PROPERTY(ProxyLocalCommand);
  3828. }
  3829. //---------------------------------------------------------------------
  3830. void __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)
  3831. {
  3832. SET_SESSION_PROPERTY(ProxyDNS);
  3833. }
  3834. //---------------------------------------------------------------------
  3835. void __fastcall TSessionData::SetProxyLocalhost(bool value)
  3836. {
  3837. SET_SESSION_PROPERTY(ProxyLocalhost);
  3838. }
  3839. //---------------------------------------------------------------------
  3840. void __fastcall TSessionData::SetFtpProxyLogonType(int value)
  3841. {
  3842. SET_SESSION_PROPERTY(FtpProxyLogonType);
  3843. }
  3844. //---------------------------------------------------------------------
  3845. void __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)
  3846. {
  3847. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  3848. SET_SESSION_PROPERTY(Bugs[Bug]);
  3849. }
  3850. //---------------------------------------------------------------------
  3851. TAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const
  3852. {
  3853. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  3854. return FBugs[Bug];
  3855. }
  3856. //---------------------------------------------------------------------
  3857. void __fastcall TSessionData::SetPuttySettings(UnicodeString value)
  3858. {
  3859. SET_SESSION_PROPERTY(PuttySettings);
  3860. }
  3861. //---------------------------------------------------------------------
  3862. void __fastcall TSessionData::SetCustomParam1(UnicodeString value)
  3863. {
  3864. SET_SESSION_PROPERTY(CustomParam1);
  3865. }
  3866. //---------------------------------------------------------------------
  3867. void __fastcall TSessionData::SetCustomParam2(UnicodeString value)
  3868. {
  3869. SET_SESSION_PROPERTY(CustomParam2);
  3870. }
  3871. //---------------------------------------------------------------------
  3872. void __fastcall TSessionData::SetSFTPDownloadQueue(int value)
  3873. {
  3874. SET_SESSION_PROPERTY(SFTPDownloadQueue);
  3875. }
  3876. //---------------------------------------------------------------------
  3877. void __fastcall TSessionData::SetSFTPUploadQueue(int value)
  3878. {
  3879. SET_SESSION_PROPERTY(SFTPUploadQueue);
  3880. }
  3881. //---------------------------------------------------------------------
  3882. void __fastcall TSessionData::SetSFTPListingQueue(int value)
  3883. {
  3884. SET_SESSION_PROPERTY(SFTPListingQueue);
  3885. }
  3886. //---------------------------------------------------------------------
  3887. void __fastcall TSessionData::SetSFTPMaxVersion(int value)
  3888. {
  3889. SET_SESSION_PROPERTY(SFTPMaxVersion);
  3890. }
  3891. //---------------------------------------------------------------------
  3892. void __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)
  3893. {
  3894. SET_SESSION_PROPERTY(SFTPMaxPacketSize);
  3895. }
  3896. //---------------------------------------------------------------------
  3897. void __fastcall TSessionData::SetSFTPRealPath(TAutoSwitch value)
  3898. {
  3899. SET_SESSION_PROPERTY(SFTPRealPath);
  3900. }
  3901. //---------------------------------------------------------------------
  3902. void __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)
  3903. {
  3904. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  3905. SET_SESSION_PROPERTY(SFTPBugs[Bug]);
  3906. }
  3907. //---------------------------------------------------------------------
  3908. TAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const
  3909. {
  3910. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  3911. return FSFTPBugs[Bug];
  3912. }
  3913. //---------------------------------------------------------------------
  3914. void __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)
  3915. {
  3916. SET_SESSION_PROPERTY(SCPLsFullTime);
  3917. }
  3918. //---------------------------------------------------------------------------
  3919. void __fastcall TSessionData::SetColor(int value)
  3920. {
  3921. SET_SESSION_PROPERTY(Color);
  3922. }
  3923. //---------------------------------------------------------------------------
  3924. void __fastcall TSessionData::SetTunnel(bool value)
  3925. {
  3926. SET_SESSION_PROPERTY(Tunnel);
  3927. }
  3928. //---------------------------------------------------------------------
  3929. void __fastcall TSessionData::SetTunnelHostName(UnicodeString value)
  3930. {
  3931. if (FTunnelHostName != value)
  3932. {
  3933. // HostName is key for password encryption
  3934. UnicodeString XTunnelPassword = TunnelPassword;
  3935. int P = value.LastDelimiter(L"@");
  3936. if (P > 0)
  3937. {
  3938. TunnelUserName = value.SubString(1, P - 1);
  3939. value = value.SubString(P + 1, value.Length() - P);
  3940. }
  3941. FTunnelHostName = value;
  3942. Modify();
  3943. TunnelPassword = XTunnelPassword;
  3944. Shred(XTunnelPassword);
  3945. }
  3946. }
  3947. //---------------------------------------------------------------------
  3948. void __fastcall TSessionData::SetTunnelPortNumber(int value)
  3949. {
  3950. SET_SESSION_PROPERTY(TunnelPortNumber);
  3951. }
  3952. //---------------------------------------------------------------------
  3953. void __fastcall TSessionData::SetTunnelUserName(UnicodeString value)
  3954. {
  3955. // Avoid password recryption (what may popup master password prompt)
  3956. if (FTunnelUserName != value)
  3957. {
  3958. // TunnelUserName is key for password encryption
  3959. UnicodeString XTunnelPassword = TunnelPassword;
  3960. SET_SESSION_PROPERTY(TunnelUserName);
  3961. TunnelPassword = XTunnelPassword;
  3962. Shred(XTunnelPassword);
  3963. }
  3964. }
  3965. //---------------------------------------------------------------------
  3966. void __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)
  3967. {
  3968. RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);
  3969. SET_SESSION_PROPERTY(TunnelPassword);
  3970. }
  3971. //---------------------------------------------------------------------
  3972. UnicodeString __fastcall TSessionData::GetTunnelPassword() const
  3973. {
  3974. return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);
  3975. }
  3976. //---------------------------------------------------------------------
  3977. void __fastcall TSessionData::SetTunnelPassphrase(UnicodeString avalue)
  3978. {
  3979. RawByteString value = EncryptPassword(avalue, TunnelPublicKeyFile);
  3980. SET_SESSION_PROPERTY(TunnelPassphrase);
  3981. }
  3982. //---------------------------------------------------------------------
  3983. UnicodeString __fastcall TSessionData::GetTunnelPassphrase() const
  3984. {
  3985. return DecryptPassword(FTunnelPassphrase, TunnelPublicKeyFile);
  3986. }
  3987. //---------------------------------------------------------------------
  3988. void __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)
  3989. {
  3990. if (FTunnelPublicKeyFile != value)
  3991. {
  3992. // TunnelPublicKeyFile is key for TunnelPassphrase encryption
  3993. UnicodeString XTunnelPassphrase = TunnelPassphrase;
  3994. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3995. FTunnelPublicKeyFile = StripPathQuotes(value);
  3996. Modify();
  3997. TunnelPassphrase = XTunnelPassphrase;
  3998. Shred(XTunnelPassphrase);
  3999. }
  4000. }
  4001. //---------------------------------------------------------------------
  4002. void __fastcall TSessionData::SetTunnelLocalPortNumber(int value)
  4003. {
  4004. SET_SESSION_PROPERTY(TunnelLocalPortNumber);
  4005. }
  4006. //---------------------------------------------------------------------
  4007. bool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()
  4008. {
  4009. return (FTunnelLocalPortNumber <= 0);
  4010. }
  4011. //---------------------------------------------------------------------
  4012. void __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)
  4013. {
  4014. SET_SESSION_PROPERTY(TunnelPortFwd);
  4015. }
  4016. //---------------------------------------------------------------------
  4017. void __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)
  4018. {
  4019. SET_SESSION_PROPERTY(TunnelHostKey);
  4020. }
  4021. //---------------------------------------------------------------------
  4022. void __fastcall TSessionData::SetFtpPasvMode(bool value)
  4023. {
  4024. SET_SESSION_PROPERTY(FtpPasvMode);
  4025. }
  4026. //---------------------------------------------------------------------
  4027. void __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)
  4028. {
  4029. SET_SESSION_PROPERTY(FtpForcePasvIp);
  4030. }
  4031. //---------------------------------------------------------------------
  4032. void __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)
  4033. {
  4034. SET_SESSION_PROPERTY(FtpUseMlsd);
  4035. }
  4036. //---------------------------------------------------------------------
  4037. void __fastcall TSessionData::SetFtpAccount(UnicodeString value)
  4038. {
  4039. SET_SESSION_PROPERTY(FtpAccount);
  4040. }
  4041. //---------------------------------------------------------------------
  4042. void __fastcall TSessionData::SetFtpPingInterval(int value)
  4043. {
  4044. SET_SESSION_PROPERTY(FtpPingInterval);
  4045. }
  4046. //---------------------------------------------------------------------------
  4047. TDateTime __fastcall TSessionData::GetFtpPingIntervalDT()
  4048. {
  4049. return SecToDateTime(FtpPingInterval);
  4050. }
  4051. //---------------------------------------------------------------------------
  4052. void __fastcall TSessionData::SetFtpPingType(TPingType value)
  4053. {
  4054. SET_SESSION_PROPERTY(FtpPingType);
  4055. }
  4056. //---------------------------------------------------------------------------
  4057. void __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)
  4058. {
  4059. SET_SESSION_PROPERTY(FtpTransferActiveImmediately);
  4060. }
  4061. //---------------------------------------------------------------------------
  4062. void __fastcall TSessionData::SetFtps(TFtps value)
  4063. {
  4064. SET_SESSION_PROPERTY(Ftps);
  4065. }
  4066. //---------------------------------------------------------------------------
  4067. void __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)
  4068. {
  4069. SET_SESSION_PROPERTY(MinTlsVersion);
  4070. }
  4071. //---------------------------------------------------------------------------
  4072. void __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)
  4073. {
  4074. SET_SESSION_PROPERTY(MaxTlsVersion);
  4075. }
  4076. //---------------------------------------------------------------------------
  4077. void __fastcall TSessionData::SetLogicalHostName(UnicodeString value)
  4078. {
  4079. SET_SESSION_PROPERTY(LogicalHostName);
  4080. }
  4081. //---------------------------------------------------------------------
  4082. void __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)
  4083. {
  4084. SET_SESSION_PROPERTY(FtpListAll);
  4085. }
  4086. //---------------------------------------------------------------------
  4087. void __fastcall TSessionData::SetFtpHost(TAutoSwitch value)
  4088. {
  4089. SET_SESSION_PROPERTY(FtpHost);
  4090. }
  4091. //---------------------------------------------------------------------
  4092. void __fastcall TSessionData::SetFtpWorkFromCwd(TAutoSwitch value)
  4093. {
  4094. SET_SESSION_PROPERTY(FtpWorkFromCwd);
  4095. }
  4096. //---------------------------------------------------------------------
  4097. void TSessionData::SetFtpAnyCodeForPwd(bool value)
  4098. {
  4099. SET_SESSION_PROPERTY(FtpAnyCodeForPwd);
  4100. }
  4101. //---------------------------------------------------------------------
  4102. void __fastcall TSessionData::SetSslSessionReuse(bool value)
  4103. {
  4104. SET_SESSION_PROPERTY(SslSessionReuse);
  4105. }
  4106. //---------------------------------------------------------------------
  4107. void __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)
  4108. {
  4109. SET_SESSION_PROPERTY(TlsCertificateFile);
  4110. }
  4111. //---------------------------------------------------------------------
  4112. void __fastcall TSessionData::SetNotUtf(TAutoSwitch value)
  4113. {
  4114. SET_SESSION_PROPERTY(NotUtf);
  4115. }
  4116. //---------------------------------------------------------------------
  4117. void __fastcall TSessionData::SetInternalEditorEncoding(int value)
  4118. {
  4119. SET_SESSION_PROPERTY(InternalEditorEncoding);
  4120. }
  4121. //---------------------------------------------------------------------
  4122. void __fastcall TSessionData::SetS3DefaultRegion(UnicodeString value)
  4123. {
  4124. SET_SESSION_PROPERTY(S3DefaultRegion);
  4125. }
  4126. //---------------------------------------------------------------------
  4127. void __fastcall TSessionData::SetS3SessionToken(UnicodeString value)
  4128. {
  4129. SET_SESSION_PROPERTY(S3SessionToken);
  4130. }
  4131. //---------------------------------------------------------------------
  4132. void __fastcall TSessionData::SetS3UrlStyle(TS3UrlStyle value)
  4133. {
  4134. SET_SESSION_PROPERTY(S3UrlStyle);
  4135. }
  4136. //---------------------------------------------------------------------
  4137. void __fastcall TSessionData::SetS3MaxKeys(TAutoSwitch value)
  4138. {
  4139. SET_SESSION_PROPERTY(S3MaxKeys);
  4140. }
  4141. //---------------------------------------------------------------------
  4142. void __fastcall TSessionData::SetS3CredentialsEnv(bool value)
  4143. {
  4144. SET_SESSION_PROPERTY(S3CredentialsEnv);
  4145. }
  4146. //---------------------------------------------------------------------
  4147. void __fastcall TSessionData::SetIsWorkspace(bool value)
  4148. {
  4149. SET_SESSION_PROPERTY(IsWorkspace);
  4150. }
  4151. //---------------------------------------------------------------------
  4152. void __fastcall TSessionData::SetLink(UnicodeString value)
  4153. {
  4154. SET_SESSION_PROPERTY(Link);
  4155. }
  4156. //---------------------------------------------------------------------
  4157. void __fastcall TSessionData::SetNameOverride(UnicodeString value)
  4158. {
  4159. SET_SESSION_PROPERTY(NameOverride);
  4160. }
  4161. //---------------------------------------------------------------------
  4162. void __fastcall TSessionData::SetHostKey(UnicodeString value)
  4163. {
  4164. SET_SESSION_PROPERTY(HostKey);
  4165. }
  4166. //---------------------------------------------------------------------
  4167. void __fastcall TSessionData::SetNote(UnicodeString value)
  4168. {
  4169. SET_SESSION_PROPERTY(Note);
  4170. }
  4171. //---------------------------------------------------------------------
  4172. void __fastcall TSessionData::SetWinTitle(UnicodeString value)
  4173. {
  4174. SET_SESSION_PROPERTY(WinTitle);
  4175. }
  4176. //---------------------------------------------------------------------
  4177. UnicodeString __fastcall TSessionData::GetEncryptKey() const
  4178. {
  4179. return DecryptPassword(FEncryptKey, UserName+HostName);
  4180. }
  4181. //---------------------------------------------------------------------
  4182. void __fastcall TSessionData::SetEncryptKey(UnicodeString avalue)
  4183. {
  4184. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  4185. SET_SESSION_PROPERTY(EncryptKey);
  4186. }
  4187. //---------------------------------------------------------------------
  4188. void __fastcall TSessionData::SetWebDavLiberalEscaping(bool value)
  4189. {
  4190. SET_SESSION_PROPERTY(WebDavLiberalEscaping);
  4191. }
  4192. //---------------------------------------------------------------------
  4193. UnicodeString __fastcall TSessionData::GetInfoTip()
  4194. {
  4195. if (UsesSsh)
  4196. {
  4197. return FMTLOAD(SESSION_INFO_TIP2,
  4198. (HostName, UserName,
  4199. (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),
  4200. FSProtocolStr));
  4201. }
  4202. else
  4203. {
  4204. return FMTLOAD(SESSION_INFO_TIP_NO_SSH,
  4205. (HostName, UserName, FSProtocolStr));
  4206. }
  4207. }
  4208. //---------------------------------------------------------------------
  4209. UnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)
  4210. {
  4211. UnicodeString Result = Name;
  4212. int P = Result.LastDelimiter(L"/");
  4213. if (P > 0)
  4214. {
  4215. Result.Delete(1, P);
  4216. }
  4217. return Result;
  4218. }
  4219. //---------------------------------------------------------------------
  4220. UnicodeString __fastcall TSessionData::GetLocalName()
  4221. {
  4222. UnicodeString Result;
  4223. if (HasSessionName())
  4224. {
  4225. Result = ExtractLocalName(Name);
  4226. }
  4227. else
  4228. {
  4229. Result = DefaultSessionName;
  4230. }
  4231. return Result;
  4232. }
  4233. //---------------------------------------------------------------------
  4234. UnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)
  4235. {
  4236. UnicodeString Result;
  4237. int P = Name.LastDelimiter(L"/");
  4238. if (P > 0)
  4239. {
  4240. Result = Name.SubString(1, P - 1);
  4241. }
  4242. return Result;
  4243. }
  4244. //---------------------------------------------------------------------
  4245. UnicodeString __fastcall TSessionData::GetFolderName()
  4246. {
  4247. UnicodeString Result;
  4248. if (HasSessionName() || IsWorkspace)
  4249. {
  4250. Result = ExtractFolderName(Name);
  4251. }
  4252. return Result;
  4253. }
  4254. //---------------------------------------------------------------------
  4255. UnicodeString __fastcall TSessionData::ComposePath(
  4256. const UnicodeString & Path, const UnicodeString & Name)
  4257. {
  4258. return UnixIncludeTrailingBackslash(Path) + Name;
  4259. }
  4260. //---------------------------------------------------------------------
  4261. void __fastcall TSessionData::DisableAuthentationsExceptPassword()
  4262. {
  4263. SshNoUserAuth = false;
  4264. AuthKI = false;
  4265. AuthKIPassword = false;
  4266. AuthGSSAPI = false;
  4267. AuthGSSAPIKEX = false;
  4268. PublicKeyFile = L"";
  4269. TlsCertificateFile = L"";
  4270. Passphrase = L"";
  4271. TryAgent = false;
  4272. }
  4273. //---------------------------------------------------------------------
  4274. TStrings * TSessionData::GetAllOptionNames(bool PuttyExport)
  4275. {
  4276. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4277. return FactoryDefaults->SaveToOptions(NULL, false, PuttyExport);
  4278. }
  4279. //---------------------------------------------------------------------
  4280. bool TSessionData::HasS3AutoCredentials()
  4281. {
  4282. return (FSProtocol == fsS3) && S3CredentialsEnv;
  4283. }
  4284. //---------------------------------------------------------------------
  4285. bool TSessionData::HasAutoCredentials()
  4286. {
  4287. return HasS3AutoCredentials();
  4288. }
  4289. //=== TStoredSessionList ----------------------------------------------
  4290. __fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):
  4291. TNamedObjectList(), FReadOnly(aReadOnly)
  4292. {
  4293. DebugAssert(Configuration);
  4294. FDefaultSettings = new TSessionData(DefaultName);
  4295. FPendingRemovals.reset(new TStringList());
  4296. }
  4297. //---------------------------------------------------------------------
  4298. __fastcall TStoredSessionList::~TStoredSessionList()
  4299. {
  4300. DebugAssert(Configuration);
  4301. delete FDefaultSettings;
  4302. }
  4303. //---------------------------------------------------------------------
  4304. void __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,
  4305. bool AsModified, bool UseDefaults, bool PuttyImport)
  4306. {
  4307. TStringList *SubKeys = new TStringList();
  4308. TList * Loaded = new TList;
  4309. try
  4310. {
  4311. DebugAssert(AutoSort);
  4312. AutoSort = false;
  4313. bool WasEmpty = (Count == 0);
  4314. Storage->GetSubKeyNames(SubKeys);
  4315. for (int Index = 0; Index < SubKeys->Count; Index++)
  4316. {
  4317. UnicodeString SessionName = SubKeys->Strings[Index];
  4318. bool ValidName = true;
  4319. try
  4320. {
  4321. TSessionData::ValidatePath(SessionName);
  4322. }
  4323. catch(...)
  4324. {
  4325. ValidName = false;
  4326. }
  4327. if (ValidName)
  4328. {
  4329. TSessionData * SessionData;
  4330. if (SessionName == FDefaultSettings->Name)
  4331. {
  4332. SessionData = FDefaultSettings;
  4333. }
  4334. else
  4335. {
  4336. // if the list was empty before loading, do not waste time trying to
  4337. // find existing sites to overwrite (we rely on underlying storage
  4338. // to secure uniqueness of the key names)
  4339. if (WasEmpty)
  4340. {
  4341. SessionData = NULL;
  4342. }
  4343. else
  4344. {
  4345. SessionData = (TSessionData*)FindByName(SessionName);
  4346. }
  4347. }
  4348. if ((SessionData != FDefaultSettings) || !UseDefaults)
  4349. {
  4350. if (SessionData == NULL)
  4351. {
  4352. SessionData = new TSessionData(L"");
  4353. if (UseDefaults)
  4354. {
  4355. SessionData->CopyData(DefaultSettings);
  4356. }
  4357. SessionData->Name = SessionName;
  4358. Add(SessionData);
  4359. }
  4360. Loaded->Add(SessionData);
  4361. SessionData->Load(Storage, PuttyImport);
  4362. if (AsModified)
  4363. {
  4364. SessionData->Modified = true;
  4365. }
  4366. }
  4367. }
  4368. }
  4369. if (!AsModified)
  4370. {
  4371. for (int Index = 0; Index < TObjectList::Count; Index++)
  4372. {
  4373. if (Loaded->IndexOf(Items[Index]) < 0)
  4374. {
  4375. Delete(Index);
  4376. Index--;
  4377. }
  4378. }
  4379. }
  4380. }
  4381. __finally
  4382. {
  4383. AutoSort = true;
  4384. AlphaSort();
  4385. delete SubKeys;
  4386. delete Loaded;
  4387. }
  4388. }
  4389. //---------------------------------------------------------------------
  4390. void __fastcall TStoredSessionList::Reload()
  4391. {
  4392. if (Count <= Configuration->DontReloadMoreThanSessions)
  4393. {
  4394. bool SessionList = true;
  4395. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  4396. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))
  4397. {
  4398. Load(Storage.get());
  4399. }
  4400. }
  4401. }
  4402. //---------------------------------------------------------------------
  4403. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4404. TSessionData * Data, bool All, bool RecryptPasswordOnly,
  4405. TSessionData * FactoryDefaults)
  4406. {
  4407. if (All || Data->Modified)
  4408. {
  4409. if (RecryptPasswordOnly)
  4410. {
  4411. Data->SaveRecryptedPasswords(Storage);
  4412. }
  4413. else
  4414. {
  4415. Data->Save(Storage, false, FactoryDefaults);
  4416. }
  4417. }
  4418. }
  4419. //---------------------------------------------------------------------
  4420. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4421. bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4422. {
  4423. TSessionData * FactoryDefaults = new TSessionData(L"");
  4424. try
  4425. {
  4426. while (FPendingRemovals->Count > 0)
  4427. {
  4428. TSessionData::Remove(Storage, FPendingRemovals->Strings[0]);
  4429. FPendingRemovals->Delete(0);
  4430. }
  4431. DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);
  4432. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4433. {
  4434. TSessionData * SessionData = (TSessionData *)Items[Index];
  4435. try
  4436. {
  4437. DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);
  4438. }
  4439. catch (Exception & E)
  4440. {
  4441. UnicodeString Message;
  4442. if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&
  4443. ExceptionMessage(&E, Message))
  4444. {
  4445. RecryptPasswordErrors->Add(FORMAT("%s: %s", (SessionData->SessionName, Message)));
  4446. }
  4447. else
  4448. {
  4449. throw;
  4450. }
  4451. }
  4452. }
  4453. }
  4454. __finally
  4455. {
  4456. delete FactoryDefaults;
  4457. }
  4458. }
  4459. //---------------------------------------------------------------------
  4460. void __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)
  4461. {
  4462. DoSave(Storage, All, false, NULL);
  4463. }
  4464. //---------------------------------------------------------------------
  4465. void __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,
  4466. bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4467. {
  4468. bool SessionList = true;
  4469. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  4470. try
  4471. {
  4472. Storage->AccessMode = smReadWrite;
  4473. Storage->Explicit = Explicit;
  4474. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4475. {
  4476. DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);
  4477. }
  4478. }
  4479. __finally
  4480. {
  4481. delete Storage;
  4482. }
  4483. Saved();
  4484. }
  4485. //---------------------------------------------------------------------
  4486. void __fastcall TStoredSessionList::Save(bool All, bool Explicit)
  4487. {
  4488. DoSave(All, Explicit, false, NULL);
  4489. }
  4490. //---------------------------------------------------------------------
  4491. void __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)
  4492. {
  4493. DoSave(true, true, true, RecryptPasswordErrors);
  4494. }
  4495. //---------------------------------------------------------------------
  4496. void __fastcall TStoredSessionList::Saved()
  4497. {
  4498. FDefaultSettings->Modified = false;
  4499. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4500. {
  4501. ((TSessionData *)Items[Index])->Modified = false;
  4502. }
  4503. }
  4504. //---------------------------------------------------------------------
  4505. void __fastcall TStoredSessionList::ImportLevelFromFilezilla(
  4506. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  4507. {
  4508. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  4509. {
  4510. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  4511. if (ChildNode->NodeName == L"Server")
  4512. {
  4513. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  4514. SessionData->CopyData(DefaultSettings);
  4515. SessionData->ImportFromFilezilla(ChildNode, Path, SettingsNode);
  4516. Add(SessionData.release());
  4517. }
  4518. else if (ChildNode->NodeName == L"Folder")
  4519. {
  4520. UnicodeString Name;
  4521. for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)
  4522. {
  4523. _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);
  4524. if (PossibleTextMode->NodeType == ntText)
  4525. {
  4526. UnicodeString NodeValue = PossibleTextMode->NodeValue;
  4527. AddToList(Name, NodeValue.Trim(), L" ");
  4528. }
  4529. }
  4530. Name = TSessionData::MakeValidName(Name).Trim();
  4531. ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name), SettingsNode);
  4532. }
  4533. }
  4534. }
  4535. //---------------------------------------------------------------------
  4536. void __fastcall TStoredSessionList::ImportFromFilezilla(
  4537. const UnicodeString FileName, const UnicodeString ConfigurationFileName)
  4538. {
  4539. // not sure if the document must exists if we want to use its node
  4540. _di_IXMLDocument ConfigurationDocument;
  4541. _di_IXMLNode SettingsNode;
  4542. if (FileExists(ApiPath(ConfigurationFileName)))
  4543. {
  4544. ConfigurationDocument = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4545. ConfigurationDocument->LoadFromFile(ConfigurationFileName);
  4546. _di_IXMLNode FileZilla3Node = ConfigurationDocument->ChildNodes->FindNode(L"FileZilla3");
  4547. if (FileZilla3Node != NULL)
  4548. {
  4549. SettingsNode = FileZilla3Node->ChildNodes->FindNode(L"Settings");
  4550. }
  4551. }
  4552. const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4553. Document->LoadFromFile(FileName);
  4554. _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L"FileZilla3");
  4555. if (FileZilla3Node != NULL)
  4556. {
  4557. _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L"Servers");
  4558. if (ServersNode != NULL)
  4559. {
  4560. ImportLevelFromFilezilla(ServersNode, L"", SettingsNode);
  4561. }
  4562. }
  4563. }
  4564. //---------------------------------------------------------------------
  4565. UnicodeString FormatKnownHostName(const UnicodeString & HostName, int PortNumber)
  4566. {
  4567. return FORMAT(L"%s:%d", (HostName, PortNumber));
  4568. }
  4569. //---------------------------------------------------------------------
  4570. void __fastcall TStoredSessionList::ImportFromKnownHosts(TStrings * Lines)
  4571. {
  4572. bool SessionList = false;
  4573. std::unique_ptr<THierarchicalStorage> HostKeyStorage(Configuration->CreateScpStorage(SessionList));
  4574. std::unique_ptr<TStrings> KeyList(new TStringList());
  4575. if (OpenHostKeysSubKey(HostKeyStorage.get(), false))
  4576. {
  4577. HostKeyStorage->GetValueNames(KeyList.get());
  4578. }
  4579. HostKeyStorage.reset(NULL);
  4580. UnicodeString FirstError;
  4581. for (int Index = 0; Index < Lines->Count; Index++)
  4582. {
  4583. try
  4584. {
  4585. UnicodeString Line = Lines->Strings[Index];
  4586. Line = Trim(Line);
  4587. if (IsValidOpensshLine(Line))
  4588. {
  4589. int P = Pos(L' ', Line);
  4590. if (P > 0)
  4591. {
  4592. UnicodeString HostNameStr = Line.SubString(1, P - 1);
  4593. Line = Line.SubString(P + 1, Line.Length() - P);
  4594. P = Pos(L',', HostNameStr);
  4595. if (P > 0)
  4596. {
  4597. HostNameStr.SetLength(P - 1);
  4598. }
  4599. P = Pos(L':', HostNameStr);
  4600. int PortNumber = -1;
  4601. if (P > 0)
  4602. {
  4603. UnicodeString PortNumberStr = HostNameStr.SubString(P + 1, HostNameStr.Length() - P);
  4604. PortNumber = StrToInt(PortNumberStr);
  4605. HostNameStr.SetLength(P - 1);
  4606. }
  4607. if (HasIP6LiteralBrackets(HostNameStr))
  4608. {
  4609. HostNameStr = StripIP6LiteralBrackets(HostNameStr);
  4610. }
  4611. UnicodeString NameStr = HostNameStr;
  4612. if (PortNumber >= 0)
  4613. {
  4614. NameStr = FormatKnownHostName(NameStr, PortNumber);
  4615. }
  4616. std::unique_ptr<TSessionData> SessionDataOwner;
  4617. TSessionData * SessionData = dynamic_cast<TSessionData *>(FindByName(NameStr));
  4618. if (SessionData == NULL)
  4619. {
  4620. SessionData = new TSessionData(L"");
  4621. SessionDataOwner.reset(SessionData);
  4622. SessionData->CopyData(DefaultSettings);
  4623. SessionData->Name = NameStr;
  4624. SessionData->HostName = HostNameStr;
  4625. if (PortNumber >= 0)
  4626. {
  4627. SessionData->PortNumber = PortNumber;
  4628. }
  4629. }
  4630. const struct ssh_keyalg * Algorithm;
  4631. UnicodeString Key = ParseOpenSshPubLine(Line, Algorithm);
  4632. UnicodeString KeyKey =
  4633. FORMAT(L"%s@%d:%s", (Algorithm->cache_id, SessionData->PortNumber, HostNameStr));
  4634. UnicodeString HostKey =
  4635. FORMAT(L"%s:%s=%s", (Algorithm->ssh_id, KeyKey, Key));
  4636. UnicodeString HostKeyList = SessionData->HostKey;
  4637. AddToList(HostKeyList, HostKey, L";");
  4638. SessionData->HostKey = HostKeyList;
  4639. // If there's at least one unknown key type for this host, select it
  4640. if (KeyList->IndexOf(KeyKey) < 0)
  4641. {
  4642. SessionData->Selected = true;
  4643. }
  4644. if (SessionDataOwner.get() != NULL)
  4645. {
  4646. Add(SessionDataOwner.release());
  4647. }
  4648. }
  4649. }
  4650. }
  4651. catch (Exception & E)
  4652. {
  4653. if (FirstError.IsEmpty())
  4654. {
  4655. FirstError = E.Message;
  4656. }
  4657. }
  4658. }
  4659. if (Count == 0)
  4660. {
  4661. UnicodeString Message = LoadStr(KNOWN_HOSTS_NO_SITES);
  4662. if (!FirstError.IsEmpty())
  4663. {
  4664. Message = FORMAT(L"%s\n(%s)", (Message, FirstError));
  4665. }
  4666. throw Exception(Message);
  4667. }
  4668. }
  4669. //---------------------------------------------------------------------
  4670. void TStoredSessionList::ImportFromOpenssh(TStrings * Lines)
  4671. {
  4672. std::unique_ptr<TStrings> Hosts(CreateSortedStringList());
  4673. for (int Index = 0; Index < Lines->Count; Index++)
  4674. {
  4675. UnicodeString Line = Lines->Strings[Index];
  4676. UnicodeString Directive, Value;
  4677. if (ParseOpensshDirective(Line, Directive, Value) &&
  4678. SameText(Directive, OpensshHostDirective))
  4679. {
  4680. while (!Value.IsEmpty())
  4681. {
  4682. UnicodeString Name = CutOpensshToken(Value);
  4683. if ((Hosts->IndexOf(Name) < 0) && (Name.LastDelimiter(L"*?") == 0))
  4684. {
  4685. std::unique_ptr<TSessionData> Data(new TSessionData(EmptyStr));
  4686. Data->CopyData(DefaultSettings);
  4687. Data->Name = Name;
  4688. Data->HostName = Name;
  4689. Data->ImportFromOpenssh(Lines);
  4690. Add(Data.release());
  4691. Hosts->Add(Name);
  4692. }
  4693. }
  4694. }
  4695. }
  4696. }
  4697. //---------------------------------------------------------------------
  4698. void __fastcall TStoredSessionList::Export(const UnicodeString FileName)
  4699. {
  4700. THierarchicalStorage * Storage = TIniFileStorage::CreateFromPath(FileName);
  4701. try
  4702. {
  4703. Storage->AccessMode = smReadWrite;
  4704. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4705. {
  4706. Save(Storage, true);
  4707. }
  4708. }
  4709. __finally
  4710. {
  4711. delete Storage;
  4712. }
  4713. }
  4714. //---------------------------------------------------------------------
  4715. void __fastcall TStoredSessionList::SelectAll(bool Select)
  4716. {
  4717. for (int Index = 0; Index < Count; Index++)
  4718. Sessions[Index]->Selected = Select;
  4719. }
  4720. //---------------------------------------------------------------------
  4721. void __fastcall TStoredSessionList::Import(TStoredSessionList * From,
  4722. bool OnlySelected, TList * Imported)
  4723. {
  4724. for (int Index = 0; Index < From->Count; Index++)
  4725. {
  4726. if (!OnlySelected || From->Sessions[Index]->Selected)
  4727. {
  4728. TSessionData *Session = new TSessionData(L"");
  4729. Session->Assign(From->Sessions[Index]);
  4730. Session->Modified = true;
  4731. Session->MakeUniqueIn(this);
  4732. Add(Session);
  4733. if (Imported != NULL)
  4734. {
  4735. Imported->Add(Session);
  4736. }
  4737. }
  4738. }
  4739. // only modified, explicit
  4740. Save(false, true);
  4741. }
  4742. //---------------------------------------------------------------------
  4743. void __fastcall TStoredSessionList::SelectSessionsToImport
  4744. (TStoredSessionList * Dest, bool SSHOnly)
  4745. {
  4746. for (int Index = 0; Index < Count; Index++)
  4747. {
  4748. Sessions[Index]->Selected =
  4749. (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&
  4750. !Dest->FindByName(Sessions[Index]->Name);
  4751. }
  4752. }
  4753. //---------------------------------------------------------------------
  4754. void __fastcall TStoredSessionList::Cleanup()
  4755. {
  4756. try
  4757. {
  4758. if (Configuration->Storage == stRegistry) Clear();
  4759. TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);
  4760. try
  4761. {
  4762. Storage->AccessMode = smReadWrite;
  4763. if (Storage->OpenRootKey(False))
  4764. Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);
  4765. }
  4766. __finally
  4767. {
  4768. delete Storage;
  4769. }
  4770. }
  4771. catch (Exception &E)
  4772. {
  4773. throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));
  4774. }
  4775. }
  4776. //---------------------------------------------------------------------------
  4777. void __fastcall TStoredSessionList::UpdateStaticUsage()
  4778. {
  4779. int SCP = 0;
  4780. int SFTP = 0;
  4781. int FTP = 0;
  4782. int FTPS = 0;
  4783. int WebDAV = 0;
  4784. int WebDAVS = 0;
  4785. int S3 = 0;
  4786. int Password = 0;
  4787. int Advanced = 0;
  4788. int Color = 0;
  4789. int Note = 0;
  4790. int Tunnel = 0;
  4791. bool Folders = false;
  4792. bool Workspaces = false;
  4793. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4794. std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());
  4795. for (int Index = 0; Index < Count; Index++)
  4796. {
  4797. TSessionData * Data = Sessions[Index];
  4798. if (Data->IsWorkspace)
  4799. {
  4800. Workspaces = true;
  4801. }
  4802. else
  4803. {
  4804. switch (Data->FSProtocol)
  4805. {
  4806. case fsSCPonly:
  4807. SCP++;
  4808. break;
  4809. case fsSFTP:
  4810. case fsSFTPonly:
  4811. SFTP++;
  4812. break;
  4813. case fsFTP:
  4814. if (Data->Ftps == ftpsNone)
  4815. {
  4816. FTP++;
  4817. }
  4818. else
  4819. {
  4820. FTPS++;
  4821. }
  4822. break;
  4823. case fsWebDAV:
  4824. if (Data->Ftps == ftpsNone)
  4825. {
  4826. WebDAV++;
  4827. }
  4828. else
  4829. {
  4830. WebDAVS++;
  4831. }
  4832. break;
  4833. case fsS3:
  4834. S3++;
  4835. break;
  4836. }
  4837. if (Data->HasAnySessionPassword())
  4838. {
  4839. Password++;
  4840. }
  4841. if (Data->Color != 0)
  4842. {
  4843. Color++;
  4844. }
  4845. if (!Data->Note.IsEmpty())
  4846. {
  4847. Note++;
  4848. }
  4849. // This would not work for passwords, as they are compared in their encrypted form.
  4850. // But there are no passwords set in factory defaults anyway.
  4851. if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get(), false))
  4852. {
  4853. Advanced++;
  4854. }
  4855. if (Data->Tunnel)
  4856. {
  4857. Tunnel++;
  4858. }
  4859. if (!Data->FolderName.IsEmpty())
  4860. {
  4861. Folders = true;
  4862. }
  4863. }
  4864. }
  4865. Configuration->Usage->Set(L"StoredSessionsCountSCP", SCP);
  4866. Configuration->Usage->Set(L"StoredSessionsCountSFTP", SFTP);
  4867. Configuration->Usage->Set(L"StoredSessionsCountFTP", FTP);
  4868. Configuration->Usage->Set(L"StoredSessionsCountFTPS", FTPS);
  4869. Configuration->Usage->Set(L"StoredSessionsCountWebDAV", WebDAV);
  4870. Configuration->Usage->Set(L"StoredSessionsCountWebDAVS", WebDAVS);
  4871. Configuration->Usage->Set(L"StoredSessionsCountS3", S3);
  4872. Configuration->Usage->Set(L"StoredSessionsCountPassword", Password);
  4873. Configuration->Usage->Set(L"StoredSessionsCountColor", Color);
  4874. Configuration->Usage->Set(L"StoredSessionsCountNote", Note);
  4875. Configuration->Usage->Set(L"StoredSessionsCountAdvanced", Advanced);
  4876. DifferentAdvancedProperties->Delimiter = L',';
  4877. Configuration->Usage->Set(L"StoredSessionsAdvancedSettings", DifferentAdvancedProperties->DelimitedText);
  4878. Configuration->Usage->Set(L"StoredSessionsCountTunnel", Tunnel);
  4879. // actually default might be true, see below for when the default is actually used
  4880. bool CustomDefaultStoredSession = false;
  4881. try
  4882. {
  4883. // this can throw, when the default session settings have password set
  4884. // (and no other basic property, like hostname/username),
  4885. // and master password is enabled as we are called before master password
  4886. // handler is set
  4887. CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);
  4888. }
  4889. catch (...)
  4890. {
  4891. }
  4892. Configuration->Usage->Set(L"UsingDefaultStoredSession", CustomDefaultStoredSession);
  4893. Configuration->Usage->Set(L"UsingStoredSessionsFolders", Folders);
  4894. Configuration->Usage->Set(L"UsingWorkspaces", Workspaces);
  4895. }
  4896. //---------------------------------------------------------------------------
  4897. TSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)
  4898. {
  4899. TSessionData * Result;
  4900. if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)
  4901. {
  4902. Result = NULL;
  4903. }
  4904. else
  4905. {
  4906. Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));
  4907. }
  4908. return Result;
  4909. }
  4910. //---------------------------------------------------------------------------
  4911. int __fastcall TStoredSessionList::IndexOf(TSessionData * Data)
  4912. {
  4913. for (int Index = 0; Index < Count; Index++)
  4914. if (Data == Sessions[Index]) return Index;
  4915. return -1;
  4916. }
  4917. //---------------------------------------------------------------------------
  4918. TSessionData * __fastcall TStoredSessionList::NewSession(
  4919. UnicodeString SessionName, TSessionData * Session)
  4920. {
  4921. TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);
  4922. if (!DuplicateSession)
  4923. {
  4924. DuplicateSession = new TSessionData(L"");
  4925. DuplicateSession->Assign(Session);
  4926. DuplicateSession->Name = SessionName;
  4927. // make sure, that new stored session is saved to registry
  4928. DuplicateSession->Modified = true;
  4929. Add(DuplicateSession);
  4930. }
  4931. else
  4932. {
  4933. DuplicateSession->Assign(Session);
  4934. DuplicateSession->Name = SessionName;
  4935. DuplicateSession->Modified = true;
  4936. }
  4937. // list was saved here before to default storage, but it would not allow
  4938. // to work with special lists (export/import) not using default storage
  4939. return DuplicateSession;
  4940. }
  4941. //---------------------------------------------------------------------------
  4942. void __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)
  4943. {
  4944. DebugAssert(FDefaultSettings);
  4945. if (FDefaultSettings != value)
  4946. {
  4947. FDefaultSettings->Assign(value);
  4948. // make sure default settings are saved
  4949. FDefaultSettings->Modified = true;
  4950. FDefaultSettings->Name = DefaultName;
  4951. if (!FReadOnly)
  4952. {
  4953. // only modified, explicit
  4954. Save(false, true);
  4955. }
  4956. }
  4957. }
  4958. //---------------------------------------------------------------------------
  4959. bool __fastcall TStoredSessionList::OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate)
  4960. {
  4961. return
  4962. Storage->OpenRootKey(CanCreate) &&
  4963. Storage->OpenSubKey(Configuration->SshHostKeysSubKey, CanCreate);
  4964. }
  4965. //---------------------------------------------------------------------------
  4966. THierarchicalStorage * __fastcall TStoredSessionList::CreateHostKeysStorageForWritting()
  4967. {
  4968. bool SessionList = false;
  4969. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  4970. Storage->Explicit = true;
  4971. Storage->AccessMode = smReadWrite;
  4972. return Storage.release();
  4973. }
  4974. //---------------------------------------------------------------------------
  4975. void __fastcall TStoredSessionList::ImportHostKeys(
  4976. THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected)
  4977. {
  4978. if (OpenHostKeysSubKey(SourceStorage, false) &&
  4979. OpenHostKeysSubKey(TargetStorage, true))
  4980. {
  4981. std::auto_ptr<TStringList> KeyList(new TStringList());
  4982. SourceStorage->GetValueNames(KeyList.get());
  4983. DebugAssert(Sessions != NULL);
  4984. for (int Index = 0; Index < Sessions->Count; Index++)
  4985. {
  4986. TSessionData * Session = Sessions->Sessions[Index];
  4987. if (!OnlySelected || Session->Selected)
  4988. {
  4989. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"@%d:%s", (Session->PortNumber, Session->HostNameExpanded)));
  4990. for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)
  4991. {
  4992. UnicodeString KeyName = KeyList->Strings[KeyIndex];
  4993. if (EndsText(HostKeyName, KeyName))
  4994. {
  4995. TargetStorage->WriteStringRaw(KeyName, SourceStorage->ReadStringRaw(KeyName, L""));
  4996. }
  4997. }
  4998. }
  4999. }
  5000. }
  5001. }
  5002. //---------------------------------------------------------------------------
  5003. void __fastcall TStoredSessionList::ImportHostKeys(
  5004. const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected)
  5005. {
  5006. std::auto_ptr<THierarchicalStorage> TargetStorage(CreateHostKeysStorageForWritting());
  5007. std::auto_ptr<THierarchicalStorage> SourceStorage(new TRegistryStorage(SourceKey));
  5008. ImportHostKeys(SourceStorage.get(), TargetStorage.get(), Sessions, OnlySelected);
  5009. }
  5010. //---------------------------------------------------------------------------
  5011. void __fastcall TStoredSessionList::ImportSelectedKnownHosts(TStoredSessionList * Sessions)
  5012. {
  5013. std::unique_ptr<THierarchicalStorage> Storage(CreateHostKeysStorageForWritting());
  5014. if (OpenHostKeysSubKey(Storage.get(), true))
  5015. {
  5016. for (int Index = 0; Index < Sessions->Count; Index++)
  5017. {
  5018. TSessionData * Session = Sessions->Sessions[Index];
  5019. if (Session->Selected)
  5020. {
  5021. UnicodeString Algs;
  5022. UnicodeString HostKeys = Session->HostKey;
  5023. while (!HostKeys.IsEmpty())
  5024. {
  5025. UnicodeString HostKey = CutToChar(HostKeys, L';', true);
  5026. // skip alg
  5027. CutToChar(HostKey, L':', true);
  5028. UnicodeString Key = CutToChar(HostKey, L'=', true);
  5029. Storage->WriteStringRaw(Key, HostKey);
  5030. }
  5031. }
  5032. }
  5033. }
  5034. }
  5035. //---------------------------------------------------------------------------
  5036. void TStoredSessionList::SelectKnownHostsForSelectedSessions(
  5037. TStoredSessionList * KnownHosts, TStoredSessionList * Sessions)
  5038. {
  5039. for (int SessionIndex = 0; SessionIndex < Sessions->Count; SessionIndex++)
  5040. {
  5041. TSessionData * Session = Sessions->Sessions[SessionIndex];
  5042. if (Session->Selected)
  5043. {
  5044. UnicodeString Key = Session->HostName;
  5045. if (Session->PortNumber != Session->GetDefaultPort())
  5046. {
  5047. Key = FormatKnownHostName(Key, Session->PortNumber);
  5048. }
  5049. TSessionData * KnownHost = dynamic_cast<TSessionData *>(KnownHosts->FindByName(Key));
  5050. if (KnownHost != NULL)
  5051. {
  5052. KnownHost->Selected = true;
  5053. }
  5054. }
  5055. }
  5056. }
  5057. //---------------------------------------------------------------------------
  5058. bool __fastcall TStoredSessionList::IsFolderOrWorkspace(
  5059. const UnicodeString & Name, bool Workspace)
  5060. {
  5061. bool Result = false;
  5062. TSessionData * FirstData = NULL;
  5063. if (!Name.IsEmpty())
  5064. {
  5065. for (int Index = 0; !Result && (Index < Count); Index++)
  5066. {
  5067. Result = Sessions[Index]->IsInFolderOrWorkspace(Name);
  5068. if (Result)
  5069. {
  5070. FirstData = Sessions[Index];
  5071. }
  5072. }
  5073. }
  5074. return
  5075. Result &&
  5076. DebugAlwaysTrue(FirstData != NULL) &&
  5077. (FirstData->IsWorkspace == Workspace);
  5078. }
  5079. //---------------------------------------------------------------------------
  5080. bool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)
  5081. {
  5082. return IsFolderOrWorkspace(Name, false);
  5083. }
  5084. //---------------------------------------------------------------------------
  5085. bool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)
  5086. {
  5087. return IsFolderOrWorkspace(Name, true);
  5088. }
  5089. //---------------------------------------------------------------------------
  5090. TSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(
  5091. TSessionData * Data, const UnicodeString & Name)
  5092. {
  5093. if (Data->IsInFolderOrWorkspace(Name))
  5094. {
  5095. Data = ResolveWorkspaceData(Data);
  5096. if ((Data != NULL) && Data->CanLogin &&
  5097. DebugAlwaysTrue(Data->Link.IsEmpty()))
  5098. {
  5099. return Data;
  5100. }
  5101. }
  5102. return NULL;
  5103. }
  5104. //---------------------------------------------------------------------------
  5105. void __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)
  5106. {
  5107. DoGetFolderOrWorkspace(Name, List, false);
  5108. }
  5109. //---------------------------------------------------------------------------
  5110. void __fastcall TStoredSessionList::DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt)
  5111. {
  5112. for (int Index = 0; (Index < Count); Index++)
  5113. {
  5114. TSessionData * RawData = Sessions[Index];
  5115. TSessionData * Data =
  5116. CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);
  5117. if (Data != NULL)
  5118. {
  5119. TSessionData * Data2 = new TSessionData(L"");
  5120. if (NoRecrypt)
  5121. {
  5122. Data2->CopyDataNoRecrypt(Data);
  5123. }
  5124. else
  5125. {
  5126. Data2->Assign(Data);
  5127. }
  5128. if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&
  5129. // BACKWARD COMPATIBILITY
  5130. // When loading pre-5.6.4 workspace, that does not have state saved,
  5131. // do not overwrite the site "state" defaults
  5132. // with (empty) workspace state
  5133. RawData->HasStateData())
  5134. {
  5135. Data2->CopyStateData(RawData);
  5136. }
  5137. if (!RawData->NameOverride.IsEmpty())
  5138. {
  5139. Data2->Name = RawData->NameOverride;
  5140. }
  5141. else if (RawData->Link.IsEmpty() && RawData->IsWorkspace)
  5142. {
  5143. // Newly opened ad-hoc session has no name, so restore the workspace that way too.
  5144. // Otherwise we would persist the generated internal workspace name as a real name.
  5145. Data2->Name = UnicodeString();
  5146. }
  5147. List->Add(Data2);
  5148. }
  5149. }
  5150. }
  5151. //---------------------------------------------------------------------------
  5152. TStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(
  5153. const UnicodeString & Name)
  5154. {
  5155. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5156. DoGetFolderOrWorkspace(Name, DataList.get(), true);
  5157. std::unique_ptr<TStringList> Result(new TStringList());
  5158. for (int Index = 0; (Index < DataList->Count); Index++)
  5159. {
  5160. Result->Add(dynamic_cast<TSessionData *>(DataList->Items[Index])->SessionName);
  5161. }
  5162. return Result.release();
  5163. }
  5164. //---------------------------------------------------------------------------
  5165. TStrings * __fastcall TStoredSessionList::GetWorkspaces()
  5166. {
  5167. std::unique_ptr<TStringList> Result(CreateSortedStringList());
  5168. for (int Index = 0; (Index < Count); Index++)
  5169. {
  5170. TSessionData * Data = Sessions[Index];
  5171. if (Data->IsWorkspace)
  5172. {
  5173. Result->Add(Data->FolderName);
  5174. }
  5175. }
  5176. return Result.release();
  5177. }
  5178. //---------------------------------------------------------------------------
  5179. void __fastcall TStoredSessionList::NewWorkspace(
  5180. UnicodeString Name, TList * DataList)
  5181. {
  5182. for (int Index = 0; (Index < Count); Index++)
  5183. {
  5184. TSessionData * Data = Sessions[Index];
  5185. if (Data->IsInFolderOrWorkspace(Name))
  5186. {
  5187. FPendingRemovals->Add(Data->Name);
  5188. Remove(Data);
  5189. Index--;
  5190. }
  5191. }
  5192. for (int Index = 0; (Index < DataList->Count); Index++)
  5193. {
  5194. TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);
  5195. TSessionData * Data2 = new TSessionData(L"");
  5196. Data2->Assign(Data);
  5197. Data2->Name = TSessionData::ComposePath(Name, Data->Name);
  5198. // make sure, that new stored session is saved to registry
  5199. Data2->Modified = true;
  5200. Add(Data2);
  5201. }
  5202. }
  5203. //---------------------------------------------------------------------------
  5204. bool __fastcall TStoredSessionList::HasAnyWorkspace()
  5205. {
  5206. bool Result = false;
  5207. for (int Index = 0; !Result && (Index < Count); Index++)
  5208. {
  5209. TSessionData * Data = Sessions[Index];
  5210. Result = Data->IsWorkspace;
  5211. }
  5212. return Result;
  5213. }
  5214. //---------------------------------------------------------------------------
  5215. TSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,
  5216. TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,
  5217. bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)
  5218. {
  5219. TSessionData * Data = new TSessionData(L"");
  5220. try
  5221. {
  5222. Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl, Flags);
  5223. }
  5224. catch(...)
  5225. {
  5226. delete Data;
  5227. throw;
  5228. }
  5229. return Data;
  5230. }
  5231. //---------------------------------------------------------------------
  5232. bool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)
  5233. {
  5234. bool DefaultsOnly;
  5235. bool ProtocolDefined = false;
  5236. std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));
  5237. bool Result = ProtocolDefined;
  5238. return Result;
  5239. }
  5240. //---------------------------------------------------------------------
  5241. TSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)
  5242. {
  5243. if (!Data->Link.IsEmpty())
  5244. {
  5245. Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));
  5246. if (Data != NULL)
  5247. {
  5248. Data = ResolveWorkspaceData(Data);
  5249. }
  5250. }
  5251. return Data;
  5252. }
  5253. //---------------------------------------------------------------------
  5254. TSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data, int Index)
  5255. {
  5256. std::unique_ptr<TSessionData> Result(new TSessionData(L""));
  5257. TSessionData * SameData = StoredSessions->FindSame(Data);
  5258. if (SameData != NULL)
  5259. {
  5260. Result->CopyStateData(Data);
  5261. Result->Link = Data->Name;
  5262. }
  5263. else
  5264. {
  5265. Result->Assign(Data);
  5266. Result->NameOverride = Data->Name;
  5267. }
  5268. Result->IsWorkspace = true;
  5269. Result->Name = IntToHex(Index, 4); // See HasSessionName()
  5270. return Result.release();
  5271. }
  5272. //---------------------------------------------------------------------
  5273. bool __fastcall TStoredSessionList::CanLogin(TSessionData * Data)
  5274. {
  5275. Data = ResolveWorkspaceData(Data);
  5276. return (Data != NULL) && Data->CanLogin;
  5277. }
  5278. //---------------------------------------------------------------------
  5279. UnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData)
  5280. {
  5281. // StripPathQuotes should not be needed as we do not feed quotes anymore
  5282. UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));
  5283. for (int Index = 1; Index < ANewFileName.Length(); Index++)
  5284. {
  5285. if (ANewFileName[Index] == L'!')
  5286. {
  5287. UnicodeString Replacement;
  5288. // keep consistent with TFileCustomCommand::PatternReplacement
  5289. switch (tolower(ANewFileName[Index + 1]))
  5290. {
  5291. case L'y':
  5292. Replacement = FormatDateTime(L"yyyy", Started);
  5293. break;
  5294. case L'm':
  5295. Replacement = FormatDateTime(L"mm", Started);
  5296. break;
  5297. case L'd':
  5298. Replacement = FormatDateTime(L"dd", Started);
  5299. break;
  5300. case L't':
  5301. Replacement = FormatDateTime(L"hhnnss", Started);
  5302. break;
  5303. case 'p':
  5304. Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));
  5305. break;
  5306. case L'@':
  5307. if (SessionData != NULL)
  5308. {
  5309. Replacement = MakeValidFileName(SessionData->HostNameExpanded);
  5310. }
  5311. else
  5312. {
  5313. Replacement = L"nohost";
  5314. }
  5315. break;
  5316. case L's':
  5317. if (SessionData != NULL)
  5318. {
  5319. Replacement = MakeValidFileName(SessionData->SessionName);
  5320. }
  5321. else
  5322. {
  5323. Replacement = L"nosession";
  5324. }
  5325. break;
  5326. case L'!':
  5327. Replacement = L"!";
  5328. break;
  5329. default:
  5330. Replacement = UnicodeString(L"!") + ANewFileName[Index + 1];
  5331. break;
  5332. }
  5333. ANewFileName.Delete(Index, 2);
  5334. ANewFileName.Insert(Replacement, Index);
  5335. Index += Replacement.Length() - 1;
  5336. }
  5337. }
  5338. return ANewFileName;
  5339. }
  5340. //---------------------------------------------------------------------
  5341. bool __fastcall IsSshProtocol(TFSProtocol FSProtocol)
  5342. {
  5343. return
  5344. (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||
  5345. (FSProtocol == fsSCPonly);
  5346. }
  5347. //---------------------------------------------------------------------------
  5348. int __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)
  5349. {
  5350. int Result;
  5351. switch (FSProtocol)
  5352. {
  5353. case fsFTP:
  5354. if (Ftps == ftpsImplicit)
  5355. {
  5356. Result = FtpsImplicitPortNumber;
  5357. }
  5358. else
  5359. {
  5360. Result = FtpPortNumber;
  5361. }
  5362. break;
  5363. case fsWebDAV:
  5364. case fsS3:
  5365. if (Ftps == ftpsNone)
  5366. {
  5367. Result = HTTPPortNumber;
  5368. }
  5369. else
  5370. {
  5371. Result = HTTPSPortNumber;
  5372. }
  5373. break;
  5374. default:
  5375. if (IsSshProtocol(FSProtocol))
  5376. {
  5377. Result = SshPortNumber;
  5378. }
  5379. else
  5380. {
  5381. DebugFail();
  5382. Result = -1;
  5383. }
  5384. break;
  5385. }
  5386. return Result;
  5387. }
  5388. //---------------------------------------------------------------------