1
0

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