SessionData.cpp 190 KB

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