SessionData.cpp 189 KB

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