app.js 650 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null,
  48. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. initLiveTrafficStream();
  80. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  81. setInterval(() => {
  82. if (state.isPolling) {
  83. fetchData(false);
  84. }
  85. }, 5000);
  86. });
  87. let trafficEventSource = null;
  88. let trafficPollFallback = null;
  89. function initLiveTrafficStream() {
  90. if (trafficEventSource) {
  91. try { trafficEventSource.close(); } catch(e) {}
  92. trafficEventSource = null;
  93. }
  94. if (trafficPollFallback) {
  95. clearInterval(trafficPollFallback);
  96. trafficPollFallback = null;
  97. }
  98. if (window.EventSource) {
  99. try {
  100. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  101. trafficEventSource.onmessage = (event) => {
  102. try {
  103. const data = JSON.parse(event.data);
  104. updateLiveInterfaceTraffic(data);
  105. } catch (e) {
  106. console.error('Error parsing live traffic event:', e);
  107. }
  108. };
  109. trafficEventSource.onerror = () => {
  110. // Fallback polling if SSE disconnects
  111. if (!trafficPollFallback) {
  112. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  113. }
  114. };
  115. trafficEventSource.onopen = () => {
  116. if (trafficPollFallback) {
  117. clearInterval(trafficPollFallback);
  118. trafficPollFallback = null;
  119. }
  120. };
  121. return;
  122. } catch (e) {
  123. console.warn('EventSource failed, using 1s polling fallback:', e);
  124. }
  125. }
  126. // Fallback if EventSource is unavailable
  127. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  128. }
  129. async function pollLiveTrafficSnapshot() {
  130. try {
  131. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  132. if (res.ok) {
  133. const data = await res.json();
  134. updateLiveInterfaceTraffic(data);
  135. }
  136. } catch (e) {}
  137. }
  138. function updateLiveInterfaceTraffic(data) {
  139. if (!data || !data.interfaces) return;
  140. state.latestTraffic = data;
  141. // 1. Update Top & Dashboard Total Bandwidth Indicators
  142. const rxHuman = data.total_rx_human || '0 B/s';
  143. const txHuman = data.total_tx_human || '0 B/s';
  144. const statRx = document.getElementById('stat-traffic-rx');
  145. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  146. const statTx = document.getElementById('stat-traffic-tx');
  147. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  148. // 2. Update state.interfaces rates in-memory
  149. if (Array.isArray(state.interfaces)) {
  150. state.interfaces.forEach(i => {
  151. const live = data.interfaces[i.name];
  152. if (live) {
  153. i.rate = {
  154. rx_bytes_sec: live.rx_bytes_sec,
  155. tx_bytes_sec: live.tx_bytes_sec,
  156. rx_human: live.rx_human,
  157. tx_human: live.tx_human
  158. };
  159. i.stats = {
  160. rx_bytes: live.rx_bytes,
  161. tx_bytes: live.tx_bytes,
  162. rx_packets: live.rx_packets,
  163. tx_packets: live.tx_packets,
  164. rx_errors: live.rx_errors,
  165. tx_errors: live.tx_errors,
  166. rx_dropped: live.rx_dropped,
  167. tx_dropped: live.tx_dropped
  168. };
  169. }
  170. });
  171. }
  172. // 3. Update all live UI rate spans in-place (ZERO flicker)
  173. Object.keys(data.interfaces).forEach(name => {
  174. const live = data.interfaces[name];
  175. // Dashboard Port Matrix Card
  176. const cardRate = document.getElementById(`port-card-rate-${name}`);
  177. if (cardRate && cardRate.innerText !== live.rx_human) {
  178. cardRate.innerText = live.rx_human;
  179. }
  180. // Dashboard Quick Interfaces Table
  181. const quickRx = document.getElementById(`quick-rx-${name}`);
  182. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  183. const quickTx = document.getElementById(`quick-tx-${name}`);
  184. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  185. // Main Interfaces Tree Table
  186. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  187. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  188. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  189. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  190. // VLAN Sub-interfaces Table
  191. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  192. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  193. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  194. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  195. // VLAN Page Table
  196. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  197. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  198. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  199. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  200. });
  201. }
  202. // Navigation Handler
  203. function navigate(tabName) {
  204. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  205. navigate('bgp');
  206. return;
  207. }
  208. if (tabName === 'vlans') {
  209. navigate('interfaces');
  210. return;
  211. }
  212. state.activeTab = tabName;
  213. window.location.hash = tabName;
  214. // Update nav links styling
  215. document.querySelectorAll('.nav-link').forEach(link => {
  216. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  217. });
  218. const activeNav = document.getElementById(`nav-${tabName}`);
  219. if (activeNav) {
  220. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  221. }
  222. // Update page headers
  223. const titles = {
  224. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  225. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  226. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  227. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  228. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  229. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  230. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  231. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  232. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  233. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  234. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  235. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  236. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  237. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  238. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  239. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  240. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  241. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  242. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  243. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  244. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  245. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  246. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  247. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  248. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' }
  249. };
  250. const header = titles[tabName] || titles.dashboard;
  251. const pTitle = document.getElementById('page-title');
  252. if (pTitle) pTitle.innerText = header.title;
  253. const pSub = document.getElementById('page-subtitle');
  254. if (pSub) pSub.innerText = header.sub;
  255. // Toggle sections dynamically for all section elements
  256. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  257. if (el.id === `section-${tabName}`) {
  258. el.classList.remove('hidden');
  259. } else {
  260. el.classList.add('hidden');
  261. }
  262. });
  263. if (tabName === 'bridge') loadBridge();
  264. if (tabName === 'firewall') loadFirewall();
  265. if (tabName === 'routes') loadRoutes();
  266. if (tabName === 'bgp') {
  267. loadDynamicRouting();
  268. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  269. }
  270. if (tabName === 'ospf') {
  271. loadDynamicRouting();
  272. switchOspfTab(state.activeOspfTab || 'instances');
  273. }
  274. if (tabName === 'routing-filters') loadDynamicRouting();
  275. if (tabName === 'dynamic-routing') loadDynamicRouting();
  276. if (tabName === 'ppp') loadPPP();
  277. if (tabName === 'eoip') loadEoIP();
  278. if (tabName === 'aerotun') loadAeroTUN();
  279. if (tabName === 'persistence') loadDebianConfig();
  280. if (tabName === 'pppoe') loadPPPoE();
  281. if (tabName === 'wireguard') loadWireGuard();
  282. if (tabName === 'ipsec') loadIPSec();
  283. if (tabName === 'l2tp') loadL2TP();
  284. if (tabName === 'pptp') loadPPTP();
  285. if (tabName === 'tools') loadToolsView();
  286. if (tabName === 'dhcp-client') loadDHCPClients();
  287. if (tabName === 'dhcp-server') loadDHCPServer();
  288. if (tabName === 'vrrp') loadVRRP();
  289. if (tabName === 'bwtest') loadBwTestView();
  290. if (tabName === 'settings') loadSettingsData();
  291. setTimeout(initTableSorting, 50);
  292. }
  293. // Fetch all core system, network and VPN telemetry
  294. async function fetchData(isManual = false) {
  295. const spinner = document.getElementById('refresh-spinner');
  296. if (isManual && spinner) spinner.classList.add('animate-spin');
  297. try {
  298. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes] = await Promise.all([
  299. fetch(`${API_BASE}/system/status`),
  300. fetch(`${API_BASE}/interfaces`),
  301. fetch(`${API_BASE}/vlans`),
  302. fetch(`${API_BASE}/vpn/status`),
  303. fetch(`${API_BASE}/firewall/summary`),
  304. fetch(`${API_BASE}/routing/dynamic/summary`),
  305. fetch(`${API_BASE}/bridge/summary`),
  306. fetch(`${API_BASE}/dhcp/clients/summary`),
  307. fetch(`${API_BASE}/dhcp/clients`),
  308. fetch(`${API_BASE}/vrrp/summary`).catch(() => null)
  309. ]);
  310. if (vrrpSumRes && vrrpSumRes.ok) {
  311. state.vrrpSummary = await vrrpSumRes.json();
  312. renderVRRPSummary();
  313. }
  314. if (dhcpSumRes && dhcpSumRes.ok) {
  315. state.dhcpSummary = await dhcpSumRes.json();
  316. const bDhcp = document.getElementById('badge-dhcp-client-count');
  317. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  318. }
  319. if (dhcpClientsRes && dhcpClientsRes.ok) {
  320. state.dhcpClients = await dhcpClientsRes.json();
  321. }
  322. if (brSummaryRes.ok) {
  323. state.bridgeSummary = await brSummaryRes.json();
  324. const bBridge = document.getElementById('badge-bridge-count');
  325. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  326. const sBr = document.getElementById('bridge-stat-bridges');
  327. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  328. const sPorts = document.getElementById('bridge-stat-ports');
  329. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  330. const sHosts = document.getElementById('bridge-stat-hosts');
  331. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  332. }
  333. if (statusRes.ok) state.systemStatus = await statusRes.json();
  334. if (ifacesRes.ok) {
  335. const ifacesData = await ifacesRes.json();
  336. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  337. state.interfaces = rawIfaces.filter(i => {
  338. if (!i.name) return false;
  339. if (i.name.startsWith('ep_')) return false;
  340. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  341. });
  342. try { populateToolsInterfaces(); } catch (e) {}
  343. }
  344. if (vlansRes.ok) {
  345. const vlansData = await vlansRes.json();
  346. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  347. }
  348. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  349. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  350. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  351. updateSystemMetrics();
  352. updateBadges();
  353. if (state.activeTab === 'dashboard') renderDashboard();
  354. if (state.activeTab === 'interfaces') renderInterfacesList();
  355. if (state.activeTab === 'vlans') renderVlansList();
  356. if (state.activeTab === 'firewall') loadFirewall(false);
  357. if (state.activeTab === 'routes') loadRoutes(false);
  358. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  359. if (state.activeTab === 'ppp') loadPPP(false);
  360. if (state.activeTab === 'eoip') loadEoIP(false);
  361. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  362. if (state.activeTab === 'pppoe') loadPPPoE(false);
  363. if (state.activeTab === 'wireguard') loadWireGuard(false);
  364. if (state.activeTab === 'ipsec') loadIPSec(false);
  365. if (state.activeTab === 'l2tp') loadL2TP(false);
  366. if (state.activeTab === 'pptp') loadPPTP(false);
  367. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  368. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  369. if (state.activeTab === 'vrrp') loadVRRP(false);
  370. if (state.activeTab === 'settings') loadSettingsData(false);
  371. fetchBwTestServerStatus();
  372. } catch (err) {
  373. console.error('Failed to fetch router state:', err);
  374. } finally {
  375. if (isManual && spinner) {
  376. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  377. }
  378. }
  379. }
  380. // Update Top KPI and Sidebar Telemetry
  381. function updateSystemMetrics() {
  382. const s = state.systemStatus;
  383. const v = state.vpnStatus;
  384. if (!s) return;
  385. // Sidebar Host & Uptime
  386. const sideHost = document.getElementById('side-hostname');
  387. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  388. const sideUp = document.getElementById('side-uptime');
  389. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  390. const sideGw = document.getElementById('side-gateway-ip');
  391. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  392. // Compute CPU Metrics
  393. let cpuPct = 0;
  394. if (s.cpu_pct !== undefined) {
  395. cpuPct = s.cpu_pct;
  396. } else if (s.cpu_load && s.cpu_load.length > 0) {
  397. const cores = s.cpu_cores || 1;
  398. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  399. }
  400. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  401. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  402. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  403. // Sidebar CPU
  404. const sideCpuVal = document.getElementById('side-cpu-val');
  405. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  406. const sideCpuBar = document.getElementById('side-cpu-bar');
  407. if (sideCpuBar) {
  408. sideCpuBar.style.width = cpuWidth;
  409. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  410. }
  411. // Dashboard CPU Card
  412. const dashCpuVal = document.getElementById('dash-cpu-val');
  413. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  414. const dashCpuBar = document.getElementById('dash-cpu-bar');
  415. if (dashCpuBar) {
  416. dashCpuBar.style.width = cpuWidth;
  417. if (cpuPct > 85) {
  418. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  419. } else if (cpuPct > 65) {
  420. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  421. } else {
  422. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  423. }
  424. }
  425. const dashCpuCores = document.getElementById('dash-cpu-cores');
  426. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  427. const dashCpuLoad = document.getElementById('dash-cpu-load');
  428. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  429. const dashCpuStatus = document.getElementById('dash-cpu-status');
  430. if (dashCpuStatus) {
  431. if (cpuPct > 85) {
  432. dashCpuStatus.innerText = 'High';
  433. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  434. } else if (cpuPct > 65) {
  435. dashCpuStatus.innerText = 'Heavy';
  436. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  437. } else {
  438. dashCpuStatus.innerText = 'Normal';
  439. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  440. }
  441. }
  442. // Compute RAM Metrics
  443. const memPct = Math.round(s.mem_usage_pct || 0);
  444. const memPctStr = `${memPct}%`;
  445. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  446. const usedMB = s.mem_used_mb || 0;
  447. const totalMB = s.mem_total_mb || 0;
  448. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  449. function fmtMemMB(mb) {
  450. if (mb >= 1024) {
  451. return `${(mb / 1024).toFixed(1)} GB`;
  452. }
  453. return `${mb} MB`;
  454. }
  455. // Sidebar RAM
  456. const sideRamVal = document.getElementById('side-ram-val');
  457. if (sideRamVal) sideRamVal.innerText = memPctStr;
  458. const sideRamBar = document.getElementById('side-ram-bar');
  459. if (sideRamBar) sideRamBar.style.width = memWidth;
  460. // Dashboard RAM Card
  461. const dashRamVal = document.getElementById('dash-ram-val');
  462. if (dashRamVal) dashRamVal.innerText = memPctStr;
  463. const dashRamBar = document.getElementById('dash-ram-bar');
  464. if (dashRamBar) {
  465. dashRamBar.style.width = memWidth;
  466. if (memPct > 85) {
  467. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  468. } else if (memPct > 70) {
  469. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  470. } else {
  471. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  472. }
  473. }
  474. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  475. if (dashRamUsedTotal) {
  476. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  477. }
  478. const dashRamFree = document.getElementById('dash-ram-free');
  479. if (dashRamFree) {
  480. dashRamFree.innerText = fmtMemMB(freeMB);
  481. }
  482. const dashRamStatus = document.getElementById('dash-ram-status');
  483. if (dashRamStatus) {
  484. if (memPct > 85) {
  485. dashRamStatus.innerText = 'High';
  486. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  487. } else {
  488. dashRamStatus.innerText = 'Active';
  489. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  490. }
  491. }
  492. // Legacy Dashboard Stats (Safe checks)
  493. const elIfacesUp = document.getElementById('stat-ifaces-up');
  494. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  495. const elIfacesTot = document.getElementById('stat-ifaces-total');
  496. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  497. const elIfacesDown = document.getElementById('stat-ifaces-down');
  498. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  499. const elVlans = document.getElementById('stat-vlans-count');
  500. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  501. // VPN Status Indicators
  502. if (v) {
  503. const totalActive = v.total_active_tunnels || 0;
  504. const statVpnActive = document.getElementById('stat-vpn-active');
  505. if (statVpnActive) statVpnActive.innerText = totalActive;
  506. const tunnelsDot = document.getElementById('tunnels-dot');
  507. const tunnelsLabel = document.getElementById('tunnels-label');
  508. if (tunnelsDot && tunnelsLabel) {
  509. if (totalActive > 0) {
  510. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  511. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  512. } else {
  513. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  514. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  515. }
  516. }
  517. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  518. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  519. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  520. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  521. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  522. }
  523. // Total Live Bandwidth Rate
  524. let totalRx = 0;
  525. let totalTx = 0;
  526. (state.interfaces || []).forEach(i => {
  527. if (i.rate) {
  528. totalRx += i.rate.rx_bytes_sec || 0;
  529. totalTx += i.rate.tx_bytes_sec || 0;
  530. }
  531. });
  532. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  533. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  534. }
  535. function setDotBadge(id, active) {
  536. const el = document.getElementById(id);
  537. if (!el) return;
  538. if (active) {
  539. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  540. } else {
  541. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  542. }
  543. }
  544. function updateBadges() {
  545. const bIfaces = document.getElementById('badge-ifaces-count');
  546. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  547. const bVlans = document.getElementById('badge-vlans-count');
  548. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  549. if (state.fwSummary) {
  550. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  551. const badgeFw = document.getElementById('badge-firewall-count');
  552. if (badgeFw) badgeFw.innerText = totalFwRules;
  553. }
  554. if (state.vpnStatus) {
  555. const v = state.vpnStatus;
  556. const bEoIP = document.getElementById('badge-eoip-count');
  557. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  558. const bAero = document.getElementById('badge-aerotun-count');
  559. if (bAero) bAero.innerText = v.total_aerotun || 0;
  560. const bPPPSess = document.getElementById('badge-ppp-sessions');
  561. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  562. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  563. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  564. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  565. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  566. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  567. }
  568. if (state.dynSummary) {
  569. const d = state.dynSummary;
  570. setDotBadge('badge-bgp-dot', d.bgp_running);
  571. setDotBadge('badge-ospf-dot', d.ospf_running);
  572. const bBgp = document.getElementById('badge-bgp-count');
  573. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  574. const bOspf = document.getElementById('badge-ospf-count');
  575. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  576. const bFilters = document.getElementById('badge-filters-count');
  577. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  578. }
  579. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  580. if (bDhcpServer) {
  581. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  582. }
  583. }
  584. // Render Dashboard View
  585. function renderDashboard() {
  586. const matrix = document.getElementById('port-matrix');
  587. if (!matrix) return;
  588. const ifaces = state.interfaces || [];
  589. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  590. if (matrix.dataset.sig === sig) {
  591. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  592. }
  593. matrix.dataset.sig = sig;
  594. matrix.innerHTML = '';
  595. (state.interfaces || []).forEach(iface => {
  596. const isUp = iface.state === 'UP';
  597. const isVlan = iface.is_vlan;
  598. const portCard = document.createElement('div');
  599. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  600. isUp
  601. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  602. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  603. }`;
  604. portCard.onclick = () => openIfaceModal(iface.name);
  605. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  606. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  607. portCard.innerHTML = `
  608. <div class="flex items-center justify-between mb-2">
  609. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  610. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  611. </div>
  612. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  613. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  614. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  615. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  616. </div>
  617. `;
  618. matrix.appendChild(portCard);
  619. });
  620. const ifaceTbody = document.getElementById('quick-interfaces-table');
  621. if (ifaceTbody) {
  622. ifaceTbody.innerHTML = '';
  623. (state.interfaces || []).forEach(i => {
  624. const isUp = i.state === 'UP';
  625. const tr = document.createElement('tr');
  626. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  627. tr.onclick = () => openIfaceModal(i.name);
  628. const rxStr = i.rate?.rx_human || '0 B/s';
  629. const txStr = i.rate?.tx_human || '0 B/s';
  630. tr.innerHTML = `
  631. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  632. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  633. <span>${i.name}</span>
  634. </td>
  635. <td class="py-2.5 text-slate-300 font-sans">
  636. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  637. </td>
  638. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  639. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  640. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  641. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  642. </td>
  643. <td class="py-2.5 text-right font-sans font-semibold">
  644. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  645. </td>
  646. `;
  647. ifaceTbody.appendChild(tr);
  648. });
  649. }
  650. const vlanTbody = document.getElementById('quick-vlans-table');
  651. if (vlanTbody) {
  652. vlanTbody.innerHTML = '';
  653. }
  654. }
  655. // Expand / Collapse Handlers
  656. function toggleExpand(parentName) {
  657. if (state.expandedParents.has(parentName)) {
  658. state.expandedParents.delete(parentName);
  659. } else {
  660. state.expandedParents.add(parentName);
  661. }
  662. renderInterfacesList();
  663. }
  664. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  665. function supportsVLAN(iface) {
  666. if (!iface) return false;
  667. if (iface.is_vlan) return false;
  668. const name = (iface.name || '').toLowerCase();
  669. const type = (iface.type || '').toLowerCase();
  670. const role = (iface.role || '').toLowerCase();
  671. // Exclude loopback
  672. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  673. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  674. if (type === 'wireguard' || name.startsWith('wg')) return false;
  675. // Exclude PPP / PPPoE
  676. if (type === 'ppp' || name.startsWith('ppp')) return false;
  677. // Exclude other Layer 3 tunnels and dummy devices
  678. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  679. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  680. return false;
  681. }
  682. // If name already contains a dot, it's already a sub-interface
  683. if (name.includes('.')) return false;
  684. return true;
  685. }
  686. // Expand / Collapse Handlers
  687. function toggleExpand(parentName) {
  688. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  689. if (childVlans.length === 0) {
  690. // Cannot expand an interface with no VLANs
  691. state.expandedParents.delete(parentName);
  692. return;
  693. }
  694. if (state.expandedParents.has(parentName)) {
  695. state.expandedParents.delete(parentName);
  696. } else {
  697. state.expandedParents.add(parentName);
  698. }
  699. renderInterfacesList();
  700. }
  701. function expandAllIfaces(expand) {
  702. if (expand) {
  703. (state.interfaces || []).forEach(i => {
  704. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  705. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  706. });
  707. } else {
  708. state.expandedParents.clear();
  709. }
  710. renderInterfacesList();
  711. }
  712. // Filter and Render Hierarchical Interfaces List
  713. function filterIfaces(filter) {
  714. state.ifaceFilter = filter || 'all';
  715. renderInterfacesList();
  716. }
  717. function renderInterfacesList() {
  718. const tbody = document.getElementById('interfaces-tree-tbody');
  719. const emptyState = document.getElementById('interfaces-empty-state');
  720. const summary = document.getElementById('ifaces-list-summary');
  721. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  722. const allIfaces = state.interfaces || [];
  723. const allVlans = state.vlans || [];
  724. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  725. const filteredParents = parentIfaces.filter(parent => {
  726. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  727. if (query) {
  728. const matchName = parent.name.toLowerCase().includes(query);
  729. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  730. const matchRole = (parent.role || '').toLowerCase().includes(query);
  731. const matchType = (parent.type || '').toLowerCase().includes(query);
  732. const matchVlan = childVlans.some(v =>
  733. v.name.toLowerCase().includes(query) ||
  734. String(v.vlan_id).includes(query) ||
  735. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  736. (v.description || '').toLowerCase().includes(query)
  737. );
  738. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  739. }
  740. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  741. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  742. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  743. return true;
  744. });
  745. if (summary) {
  746. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  747. }
  748. if (filteredParents.length === 0) {
  749. emptyState?.classList.remove('hidden');
  750. tbody.innerHTML = '';
  751. return;
  752. }
  753. emptyState?.classList.add('hidden');
  754. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  755. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  756. return `${p.name}:${p.state}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}`;
  757. }).join(';');
  758. if (tbody.dataset.sig === sig) {
  759. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  760. }
  761. tbody.dataset.sig = sig;
  762. tbody.innerHTML = '';
  763. filteredParents.forEach(parent => {
  764. const isUp = parent.state === 'UP';
  765. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  766. const hasVlans = childVlans.length > 0;
  767. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  768. const canHaveVlan = supportsVLAN(parent);
  769. const parentRow = document.createElement('tr');
  770. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  771. parentRow.innerHTML = `
  772. <td class="py-3 px-3 text-center">
  773. ${hasVlans ? `
  774. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  775. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  776. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  777. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  778. </svg>
  779. </button>
  780. ` : `
  781. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  782. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  783. </div>
  784. `}
  785. </td>
  786. <td class="py-3 px-4">
  787. <div class="flex items-center space-x-2.5">
  788. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  789. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  790. </div>
  791. <div>
  792. <div class="flex items-center gap-2">
  793. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  794. <span>${parent.name}</span>
  795. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  796. </span>
  797. ${hasVlans ? `
  798. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  799. ` : `
  800. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  801. `}
  802. </div>
  803. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  804. </div>
  805. </div>
  806. </td>
  807. <td class="py-3 px-4 font-sans">
  808. <div class="flex items-center gap-1.5">
  809. <span class="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-800 text-slate-300 border border-slate-700/60">${parent.role || 'LAN'}</span>
  810. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  811. </div>
  812. </td>
  813. <td class="py-3 px-4">
  814. ${parent.ipv4 && parent.ipv4.length > 0
  815. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  816. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  817. }
  818. ${(() => {
  819. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  820. if (!c) return '';
  821. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  822. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  823. })()}
  824. </td>
  825. <td class="py-3 px-4 text-slate-400 text-[11px]">
  826. <div>${parent.mac || 'N/A'}</div>
  827. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  828. </td>
  829. <td class="py-3 px-4 text-[11px]">
  830. <div class="flex items-center space-x-2">
  831. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  832. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  833. </div>
  834. </td>
  835. <td class="py-3 px-4 font-sans">
  836. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  837. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  838. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  839. }" title="Click to toggle link status">
  840. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  841. <span>${parent.state}</span>
  842. </button>
  843. </td>
  844. <td class="py-3 px-4 text-right space-x-2 font-sans">
  845. ${(() => {
  846. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  847. if (c) {
  848. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  849. }
  850. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  851. })()}
  852. ${canHaveVlan ? `
  853. <button onclick="openVlanModal('${parent.name}')"
  854. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  855. + Add VLAN
  856. </button>
  857. ` : ''}
  858. <button onclick="openIfaceModal('${parent.name}')"
  859. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  860. Configure
  861. </button>
  862. </td>
  863. `;
  864. tbody.appendChild(parentRow);
  865. if (isExpanded) {
  866. const drawerRow = document.createElement('tr');
  867. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  868. const drawerCell = document.createElement('td');
  869. drawerCell.colSpan = 8;
  870. drawerCell.className = 'p-0';
  871. drawerCell.innerHTML = `
  872. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  873. <div class="flex items-center justify-between mb-3">
  874. <div class="flex items-center space-x-3">
  875. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  876. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  877. </span>
  878. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  879. ${childVlans.length} Attached
  880. </span>
  881. </div>
  882. <button onclick="openVlanModal('${parent.name}')"
  883. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  884. <span>+ Create VLAN on ${parent.name}</span>
  885. </button>
  886. </div>
  887. ${childVlans.length === 0 ? `
  888. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  889. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  890. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  891. <span>+ Create Your First VLAN on ${parent.name}</span>
  892. </button>
  893. </div>
  894. ` : `
  895. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  896. <table class="w-full text-left text-xs font-mono">
  897. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  898. <tr>
  899. <th class="py-2.5 px-4">VLAN ID</th>
  900. <th class="py-2.5 px-4">Interface Device</th>
  901. <th class="py-2.5 px-4">Subnet Gateway</th>
  902. <th class="py-2.5 px-4">Role / Alias</th>
  903. <th class="py-2.5 px-4">MTU</th>
  904. <th class="py-2.5 px-4">Throughput</th>
  905. <th class="py-2.5 px-4">Status</th>
  906. <th class="py-2.5 px-4 text-right">Actions</th>
  907. </tr>
  908. </thead>
  909. <tbody class="divide-y divide-slate-800/70">
  910. ${childVlans.map(v => {
  911. const isVlanUp = v.state === 'UP';
  912. return `
  913. <tr class="hover:bg-slate-800/40 transition">
  914. <td class="py-2.5 px-4">
  915. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  916. VLAN ${v.vlan_id}
  917. </span>
  918. </td>
  919. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  920. <span class="text-cyan-500">└─</span>
  921. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  922. <span>${v.name}</span>
  923. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  924. </span>
  925. </td>
  926. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  927. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  928. ${(() => {
  929. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  930. if (!c) return '';
  931. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  932. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  933. })()}
  934. </td>
  935. <td class="py-2.5 px-4 font-sans text-slate-300">
  936. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  937. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  938. </td>
  939. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  940. <td class="py-2.5 px-4 text-[11px]">
  941. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  942. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  943. </td>
  944. <td class="py-2.5 px-4 font-sans">
  945. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  946. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  947. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  948. }">
  949. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  950. <span>${v.state}</span>
  951. </button>
  952. </td>
  953. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  954. ${(() => {
  955. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  956. if (c) {
  957. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  958. }
  959. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  960. })()}
  961. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  962. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  963. </td>
  964. </tr>
  965. `;
  966. }).join('')}
  967. </tbody>
  968. </table>
  969. </div>
  970. `}
  971. </div>
  972. `;
  973. drawerRow.appendChild(drawerCell);
  974. tbody.appendChild(drawerRow);
  975. }
  976. });
  977. }
  978. // Render VLANs Dedicated View
  979. function renderVlansList() {
  980. const tbody = document.getElementById('vlans-table-body');
  981. if (!tbody) return;
  982. const emptyState = document.getElementById('vlans-empty-state');
  983. const countBadge = document.getElementById('vlans-table-count');
  984. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  985. const allVlans = state.vlans || [];
  986. if (countBadge) countBadge.innerText = allVlans.length;
  987. const filtered = allVlans.filter(v => {
  988. if (!query) return true;
  989. return v.name.toLowerCase().includes(query) ||
  990. String(v.vlan_id).includes(query) ||
  991. (v.description || '').toLowerCase().includes(query) ||
  992. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  993. });
  994. if (allVlans.length === 0) {
  995. emptyState.classList.remove('hidden');
  996. tbody.innerHTML = '';
  997. return;
  998. }
  999. emptyState.classList.add('hidden');
  1000. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1001. if (tbody.dataset.sig === sig) return;
  1002. tbody.dataset.sig = sig;
  1003. tbody.innerHTML = '';
  1004. filtered.forEach(v => {
  1005. const isUp = v.state === 'UP';
  1006. const tr = document.createElement('tr');
  1007. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1008. tr.innerHTML = `
  1009. <td class="py-3 px-4">
  1010. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  1011. VLAN ${v.vlan_id}
  1012. </span>
  1013. </td>
  1014. <td class="py-3 px-4 font-bold text-white">
  1015. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1016. <span>${v.name}</span>
  1017. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1018. </span>
  1019. </td>
  1020. <td class="py-3 px-4 text-slate-300">
  1021. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1022. </td>
  1023. <td class="py-3 px-4 text-emerald-400 font-medium">
  1024. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1025. </td>
  1026. <td class="py-3 px-4 text-slate-300 font-sans">
  1027. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1028. </td>
  1029. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1030. <td class="py-3 px-4 font-sans">
  1031. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1032. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1033. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1034. }">
  1035. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1036. <span>${v.state}</span>
  1037. </button>
  1038. </td>
  1039. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1040. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  1041. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  1042. </td>
  1043. `;
  1044. tbody.appendChild(tr);
  1045. });
  1046. }
  1047. // Toggle interface UP / DOWN
  1048. async function toggleInterfaceState(name, newState) {
  1049. try {
  1050. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1051. method: 'POST',
  1052. headers: { 'Content-Type': 'application/json' },
  1053. body: JSON.stringify({ state: newState })
  1054. });
  1055. const data = await res.json();
  1056. if (res.ok) {
  1057. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1058. fetchData(false);
  1059. } else {
  1060. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1061. }
  1062. } catch (err) {
  1063. showToast('Error', err.message, 'error');
  1064. }
  1065. }
  1066. // ---------------- MikroTik Flag & Utilities ----------------
  1067. function renderMikroTikFlag(running, disabled) {
  1068. if (running) {
  1069. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  1070. }
  1071. if (disabled) {
  1072. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  1073. }
  1074. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  1075. }
  1076. function copyToClipboard(text, label = 'Text') {
  1077. navigator.clipboard.writeText(text).then(() => {
  1078. showToast('Copied', `${label} copied to clipboard`, 'success');
  1079. }).catch(() => {
  1080. prompt('Copy value:', text);
  1081. });
  1082. }
  1083. // ======================== PPP Profiles Shared Helper ========================
  1084. async function fetchPPPProfilesList() {
  1085. try {
  1086. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1087. if (res.ok) {
  1088. state.pppProfiles = await res.json();
  1089. }
  1090. } catch (err) {
  1091. console.error('Failed to load PPP profiles:', err);
  1092. }
  1093. }
  1094. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1095. const sel = document.getElementById(selectId);
  1096. if (!sel) return;
  1097. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1098. { name: 'default', use_encryption: 'no' },
  1099. { name: 'default-encryption', use_encryption: 'required' }
  1100. ];
  1101. sel.innerHTML = '';
  1102. profiles.forEach(p => {
  1103. const opt = document.createElement('option');
  1104. opt.value = p.name;
  1105. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1106. opt.innerText = `${p.name}${encBadge}`;
  1107. sel.appendChild(opt);
  1108. });
  1109. if (selectedVal) {
  1110. sel.value = selectedVal;
  1111. } else {
  1112. sel.value = defaultVal;
  1113. }
  1114. if (!sel.value && sel.options.length > 0) {
  1115. sel.selectedIndex = 0;
  1116. }
  1117. }
  1118. // ======================== PPPoE Multi-Instance ========================
  1119. async function loadPPPoE(populateInputs = true) {
  1120. try {
  1121. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1122. await fetchPPPProfilesList();
  1123. }
  1124. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1125. const list = await res.json();
  1126. state.pppoeList = Array.isArray(list) ? list : [];
  1127. const badge = document.getElementById('pppoe-count-badge');
  1128. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1129. const tbody = document.getElementById('pppoe-table-body');
  1130. const empty = document.getElementById('pppoe-empty');
  1131. if (!tbody) return;
  1132. tbody.innerHTML = '';
  1133. if (state.pppoeList.length === 0) {
  1134. if (empty) empty.classList.remove('hidden');
  1135. } else {
  1136. if (empty) empty.classList.add('hidden');
  1137. state.pppoeList.forEach(inst => {
  1138. const tr = document.createElement('tr');
  1139. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1140. tr.innerHTML = `
  1141. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1142. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1143. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1144. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1145. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1146. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1147. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1148. <td class="py-2.5 px-3 text-center">
  1149. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1150. ${inst.default_route ? 'Yes' : 'No'}
  1151. </span>
  1152. </td>
  1153. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1154. ${inst.running ? `
  1155. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1156. ` : `
  1157. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  1158. `}
  1159. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1160. ${inst.disabled ? 'Enable' : 'Disable'}
  1161. </button>
  1162. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1163. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1164. </td>
  1165. `;
  1166. tbody.appendChild(tr);
  1167. });
  1168. }
  1169. } catch (err) {
  1170. console.error('Failed to load PPPoE:', err);
  1171. }
  1172. }
  1173. function openAddPPPoEModal() {
  1174. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1175. document.getElementById('pppoe-modal-edit-orig').value = '';
  1176. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1177. document.getElementById('pppoe-modal-name').readOnly = false;
  1178. document.getElementById('pppoe-modal-user').value = '';
  1179. document.getElementById('pppoe-modal-pass').value = '';
  1180. document.getElementById('pppoe-modal-service').value = '';
  1181. document.getElementById('pppoe-modal-mtu').value = '1492';
  1182. document.getElementById('pppoe-modal-defroute').checked = true;
  1183. document.getElementById('pppoe-modal-reconnect').checked = true;
  1184. document.getElementById('pppoe-modal-disabled').checked = false;
  1185. // Populate profiles
  1186. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1187. // Populate interfaces
  1188. const sel = document.getElementById('pppoe-modal-iface');
  1189. sel.innerHTML = '';
  1190. (state.interfaces || []).forEach(i => {
  1191. if (i.name === 'lo') return;
  1192. const opt = document.createElement('option');
  1193. opt.value = i.name;
  1194. opt.innerText = `${i.name} (${i.role || i.type})`;
  1195. sel.appendChild(opt);
  1196. });
  1197. document.getElementById('pppoe-modal').classList.remove('hidden');
  1198. }
  1199. function openEditPPPoEModal(name) {
  1200. const inst = (state.pppoeList || []).find(i => i.name === name);
  1201. if (!inst) return;
  1202. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1203. document.getElementById('pppoe-modal-edit-orig').value = name;
  1204. document.getElementById('pppoe-modal-name').value = inst.name;
  1205. document.getElementById('pppoe-modal-name').readOnly = true;
  1206. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1207. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1208. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1209. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1210. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1211. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1212. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1213. // Populate profiles
  1214. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1215. const sel = document.getElementById('pppoe-modal-iface');
  1216. sel.innerHTML = '';
  1217. (state.interfaces || []).forEach(i => {
  1218. if (i.name === 'lo') return;
  1219. const opt = document.createElement('option');
  1220. opt.value = i.name;
  1221. opt.innerText = `${i.name} (${i.role || i.type})`;
  1222. if (i.name === inst.interface) opt.selected = true;
  1223. sel.appendChild(opt);
  1224. });
  1225. document.getElementById('pppoe-modal').classList.remove('hidden');
  1226. }
  1227. function closePPPoEModal() {
  1228. document.getElementById('pppoe-modal').classList.add('hidden');
  1229. }
  1230. async function submitSavePPPoE(e) {
  1231. e.preventDefault();
  1232. const name = document.getElementById('pppoe-modal-name').value.trim();
  1233. const iface = document.getElementById('pppoe-modal-iface').value;
  1234. const user = document.getElementById('pppoe-modal-user').value.trim();
  1235. const pass = document.getElementById('pppoe-modal-pass').value;
  1236. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1237. const service = document.getElementById('pppoe-modal-service').value.trim();
  1238. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1239. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1240. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1241. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1242. try {
  1243. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1244. method: 'POST',
  1245. headers: { 'Content-Type': 'application/json' },
  1246. body: JSON.stringify({
  1247. name,
  1248. interface: iface,
  1249. username: user,
  1250. password: pass,
  1251. profile: profile,
  1252. service_name: service,
  1253. mtu,
  1254. default_route: defRoute,
  1255. auto_reconnect: reconnect,
  1256. disabled
  1257. })
  1258. });
  1259. if (res.ok) {
  1260. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1261. closePPPoEModal();
  1262. loadPPPoE(false);
  1263. fetchData(false);
  1264. } else {
  1265. const err = await res.json();
  1266. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1267. }
  1268. } catch (err) {
  1269. showToast('Error', err.message, 'error');
  1270. }
  1271. }
  1272. async function connectPPPoEInstance(name) {
  1273. try {
  1274. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1275. if (res.ok) {
  1276. showToast('Connecting', `Dialing ${name}...`, 'info');
  1277. setTimeout(() => loadPPPoE(false), 2000);
  1278. }
  1279. } catch (err) {
  1280. showToast('Error', err.message, 'error');
  1281. }
  1282. }
  1283. async function disconnectPPPoEInstance(name) {
  1284. try {
  1285. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1286. if (res.ok) {
  1287. showToast('Disconnected', `${name} session terminated`, 'info');
  1288. setTimeout(() => loadPPPoE(false), 1000);
  1289. }
  1290. } catch (err) {
  1291. showToast('Error', err.message, 'error');
  1292. }
  1293. }
  1294. async function togglePPPoEState(name, enable) {
  1295. try {
  1296. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1297. method: 'POST',
  1298. headers: { 'Content-Type': 'application/json' },
  1299. body: JSON.stringify({ enabled: enable })
  1300. });
  1301. if (res.ok) {
  1302. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1303. loadPPPoE(false);
  1304. }
  1305. } catch (err) {
  1306. showToast('Error', err.message, 'error');
  1307. }
  1308. }
  1309. async function deletePPPoEInstance(name) {
  1310. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1311. try {
  1312. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1313. if (res.ok) {
  1314. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1315. loadPPPoE(false);
  1316. fetchData(false);
  1317. }
  1318. } catch (err) {
  1319. showToast('Error', err.message, 'error');
  1320. }
  1321. }
  1322. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1323. state.wgSubTab = 'ifaces';
  1324. function switchWGSubTab(tab) {
  1325. state.wgSubTab = tab;
  1326. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1327. const peersPanel = document.getElementById('wg-subtab-peers');
  1328. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1329. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1330. if (tab === 'ifaces') {
  1331. ifacesPanel?.classList.remove('hidden');
  1332. peersPanel?.classList.add('hidden');
  1333. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1334. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1335. } else {
  1336. ifacesPanel?.classList.add('hidden');
  1337. peersPanel?.classList.remove('hidden');
  1338. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1339. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1340. renderWGPeers();
  1341. }
  1342. }
  1343. async function loadWireGuard(populateInputs = true) {
  1344. try {
  1345. const [ifacesRes, peersRes] = await Promise.all([
  1346. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1347. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1348. ]);
  1349. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1350. const peers = peersRes.ok ? await peersRes.json() : [];
  1351. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1352. state.wgPeers = Array.isArray(peers) ? peers : [];
  1353. // Badges
  1354. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1355. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1356. const peersCountBadge = document.getElementById('wg-peers-count');
  1357. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1358. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1359. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1360. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1361. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1362. // Render Interfaces
  1363. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1364. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1365. if (ifacesTbody) {
  1366. ifacesTbody.innerHTML = '';
  1367. if (state.wgInterfaces.length === 0) {
  1368. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1369. } else {
  1370. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1371. state.wgInterfaces.forEach(iface => {
  1372. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1373. const tr = document.createElement('tr');
  1374. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1375. tr.innerHTML = `
  1376. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1377. <td class="py-2.5 px-3">
  1378. <div class="flex items-center gap-1.5">
  1379. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1380. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1381. </div>
  1382. </td>
  1383. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1384. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1385. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1386. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1387. ${(iface.public_key || '').substring(0, 10)}... 📋
  1388. </span>
  1389. </td>
  1390. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1391. <td class="py-2.5 px-3 text-center">
  1392. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1393. </td>
  1394. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1395. ${iface.running ? `
  1396. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1397. ` : `
  1398. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1399. `}
  1400. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1401. ${iface.disabled ? 'Enable' : 'Disable'}
  1402. </button>
  1403. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1404. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1405. </td>
  1406. `;
  1407. ifacesTbody.appendChild(tr);
  1408. });
  1409. }
  1410. }
  1411. // Populate filter dropdown in peers tab
  1412. const filterSel = document.getElementById('wg-peers-filter-iface');
  1413. if (filterSel) {
  1414. const currentVal = filterSel.value;
  1415. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1416. state.wgInterfaces.forEach(i => {
  1417. const opt = document.createElement('option');
  1418. opt.value = i.name;
  1419. opt.innerText = i.name;
  1420. if (i.name === currentVal) opt.selected = true;
  1421. filterSel.appendChild(opt);
  1422. });
  1423. }
  1424. renderWGPeers();
  1425. } catch (err) {
  1426. console.error('Failed to load WireGuard:', err);
  1427. }
  1428. }
  1429. function formatWGPeerEndpoint(address, port) {
  1430. if (!address || address === '(none)') return '--';
  1431. let addr = address.trim();
  1432. let p = port || 0;
  1433. while (addr.includes(':') && !addr.startsWith('[')) {
  1434. const lastColon = addr.lastIndexOf(':');
  1435. const maybePort = addr.substring(lastColon + 1);
  1436. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1437. if (!p) p = parseInt(maybePort, 10);
  1438. addr = addr.substring(0, lastColon);
  1439. } else {
  1440. break;
  1441. }
  1442. }
  1443. return p ? `${addr}:${p}` : addr;
  1444. }
  1445. function renderWGPeers() {
  1446. const filterSel = document.getElementById('wg-peers-filter-iface');
  1447. const selectedIface = filterSel ? filterSel.value : '';
  1448. const tbody = document.getElementById('wg-peers-table-body');
  1449. const empty = document.getElementById('wg-peers-empty');
  1450. if (!tbody) return;
  1451. tbody.innerHTML = '';
  1452. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1453. if (filtered.length === 0) {
  1454. if (empty) empty.classList.remove('hidden');
  1455. } else {
  1456. if (empty) empty.classList.add('hidden');
  1457. filtered.forEach(p => {
  1458. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1459. const tr = document.createElement('tr');
  1460. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1461. tr.innerHTML = `
  1462. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1463. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1464. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1465. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1466. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1467. ${(p.public_key || '').substring(0, 10)}... 📋
  1468. </span>
  1469. </td>
  1470. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1471. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1472. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1473. <td class="py-2.5 px-3 font-mono text-[11px]">
  1474. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1475. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1476. </td>
  1477. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1478. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1479. ${p.disabled ? 'Enable' : 'Disable'}
  1480. </button>
  1481. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1482. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1483. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1484. </td>
  1485. `;
  1486. tbody.appendChild(tr);
  1487. });
  1488. }
  1489. }
  1490. function openAddWGInterfaceModal() {
  1491. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1492. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1493. const nameEl = document.getElementById('wg-iface-modal-name');
  1494. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1495. nameEl.readOnly = false;
  1496. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1497. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1498. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1499. document.getElementById('wg-iface-modal-comment').value = '';
  1500. document.getElementById('wg-iface-modal-pubkey').value = '';
  1501. document.getElementById('wg-iface-modal-privkey').value = '';
  1502. document.getElementById('wg-iface-modal-disabled').checked = false;
  1503. generateWGInterfaceKeys();
  1504. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1505. }
  1506. function openEditWGInterfaceModal(name) {
  1507. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1508. if (!iface) return;
  1509. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1510. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1511. const nameEl = document.getElementById('wg-iface-modal-name');
  1512. nameEl.value = iface.name;
  1513. nameEl.readOnly = false; // ALLOW RENAMING
  1514. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1515. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1516. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1517. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1518. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1519. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1520. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1521. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1522. }
  1523. function closeAddWGInterfaceModal() {
  1524. document.getElementById('wg-iface-modal').classList.add('hidden');
  1525. }
  1526. async function generateWGInterfaceKeys() {
  1527. try {
  1528. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1529. const keys = await res.json();
  1530. if (res.ok) {
  1531. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1532. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1533. }
  1534. } catch (err) {
  1535. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1536. }
  1537. }
  1538. async function onWGInterfacePrivKeyInput() {
  1539. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1540. if (!privKey) return;
  1541. try {
  1542. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1543. method: 'POST',
  1544. headers: { 'Content-Type': 'application/json' },
  1545. body: JSON.stringify({ private_key: privKey })
  1546. });
  1547. if (res.ok) {
  1548. const data = await res.json();
  1549. if (data.public_key) {
  1550. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1551. }
  1552. }
  1553. } catch (err) {
  1554. // Ignore while typing
  1555. }
  1556. }
  1557. function toggleWGPrivKeyVisibility() {
  1558. const el = document.getElementById('wg-iface-modal-privkey');
  1559. const btn = document.getElementById('btn-toggle-wg-privkey');
  1560. if (el.type === 'password') {
  1561. el.type = 'text';
  1562. btn.innerText = '🙈 Hide';
  1563. } else {
  1564. el.type = 'password';
  1565. btn.innerText = '👁️ Show';
  1566. }
  1567. }
  1568. function copyWGInterfacePubKey() {
  1569. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1570. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1571. }
  1572. async function submitSaveWGInterface(e) {
  1573. e.preventDefault();
  1574. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1575. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1576. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1577. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1578. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1579. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1580. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1581. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1582. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1583. try {
  1584. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1585. method: 'POST',
  1586. headers: { 'Content-Type': 'application/json' },
  1587. body: JSON.stringify({
  1588. orig_name: origName,
  1589. name,
  1590. listen_port: port,
  1591. address: addr,
  1592. mtu,
  1593. comment,
  1594. public_key: pub,
  1595. private_key: priv,
  1596. disabled
  1597. })
  1598. });
  1599. const data = await res.json();
  1600. if (res.ok) {
  1601. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1602. closeAddWGInterfaceModal();
  1603. loadWireGuard(false);
  1604. fetchData(false);
  1605. } else {
  1606. showToast('Error', data.error || 'Failed to save interface', 'error');
  1607. }
  1608. } catch (err) {
  1609. showToast('Error', err.message, 'error');
  1610. }
  1611. }
  1612. async function startWGInterface(name) {
  1613. try {
  1614. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1615. if (res.ok) {
  1616. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1617. loadWireGuard(false);
  1618. fetchData(false);
  1619. }
  1620. } catch (err) {
  1621. showToast('Error', err.message, 'error');
  1622. }
  1623. }
  1624. async function stopWGInterface(name) {
  1625. try {
  1626. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1627. if (res.ok) {
  1628. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1629. loadWireGuard(false);
  1630. fetchData(false);
  1631. }
  1632. } catch (err) {
  1633. showToast('Error', err.message, 'error');
  1634. }
  1635. }
  1636. async function toggleWGInterfaceState(name, enable) {
  1637. try {
  1638. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1639. method: 'POST',
  1640. headers: { 'Content-Type': 'application/json' },
  1641. body: JSON.stringify({ enabled: enable })
  1642. });
  1643. if (res.ok) {
  1644. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1645. loadWireGuard(false);
  1646. fetchData(false);
  1647. }
  1648. } catch (err) {
  1649. showToast('Error', err.message, 'error');
  1650. }
  1651. }
  1652. async function deleteWGInterface(name) {
  1653. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1654. try {
  1655. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1656. if (res.ok) {
  1657. showToast('Deleted', `Interface ${name} removed`, 'success');
  1658. loadWireGuard(false);
  1659. fetchData(false);
  1660. }
  1661. } catch (err) {
  1662. showToast('Error', err.message, 'error');
  1663. }
  1664. }
  1665. function populateWGPeerIfaceSelect(selectedIface = '') {
  1666. const sel = document.getElementById('wg-peer-modal-iface');
  1667. if (!sel) return;
  1668. sel.innerHTML = '';
  1669. (state.wgInterfaces || []).forEach(i => {
  1670. const opt = document.createElement('option');
  1671. opt.value = i.name;
  1672. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1673. if (i.name === selectedIface) opt.selected = true;
  1674. sel.appendChild(opt);
  1675. });
  1676. }
  1677. function openAddWGPeerModal() {
  1678. if ((state.wgInterfaces || []).length === 0) {
  1679. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1680. openAddWGInterfaceModal();
  1681. return;
  1682. }
  1683. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1684. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1685. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1686. populateWGPeerIfaceSelect();
  1687. document.getElementById('wg-peer-modal-name').value = '';
  1688. document.getElementById('wg-peer-modal-pubkey').value = '';
  1689. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1690. document.getElementById('wg-peer-modal-endpoint').value = '';
  1691. document.getElementById('wg-peer-modal-port').value = '';
  1692. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1693. document.getElementById('wg-peer-modal-preshared').value = '';
  1694. document.getElementById('wg-peer-modal-disabled').checked = false;
  1695. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1696. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1697. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1698. }
  1699. function openEditWGPeerModal(ifaceName, pubKey) {
  1700. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1701. if (!peer) {
  1702. showToast('Not Found', 'Peer not found', 'warning');
  1703. return;
  1704. }
  1705. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1706. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1707. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1708. populateWGPeerIfaceSelect(peer.interface);
  1709. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1710. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1711. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1712. let epHost = (peer.endpoint_address || '').trim();
  1713. let epPort = peer.endpoint_port || '';
  1714. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1715. const lastColon = epHost.lastIndexOf(':');
  1716. const maybePort = epHost.substring(lastColon + 1);
  1717. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1718. if (!epPort) epPort = parseInt(maybePort, 10);
  1719. epHost = epHost.substring(0, lastColon);
  1720. } else {
  1721. break;
  1722. }
  1723. }
  1724. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  1725. document.getElementById('wg-peer-modal-port').value = epPort;
  1726. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1727. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1728. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1729. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1730. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1731. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1732. }
  1733. function closeAddWGPeerModal() {
  1734. document.getElementById('wg-peer-modal').classList.add('hidden');
  1735. }
  1736. async function generatePeerKeypairHelper() {
  1737. try {
  1738. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1739. const keys = await res.json();
  1740. if (res.ok) {
  1741. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1742. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1743. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1744. checkWGPeerKeyValidity();
  1745. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1746. }
  1747. } catch (err) {
  1748. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1749. }
  1750. }
  1751. function copyGeneratedPeerPrivKey() {
  1752. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1753. if (priv) copyToClipboard(priv, 'Client Private Key');
  1754. }
  1755. async function generatePeerPSK() {
  1756. try {
  1757. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1758. const keys = await res.json();
  1759. if (res.ok && keys.private_key) {
  1760. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1761. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1762. }
  1763. } catch (err) {
  1764. showToast('Error', err.message, 'error');
  1765. }
  1766. }
  1767. function checkWGPeerKeyValidity() {
  1768. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1769. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1770. const warningEl = document.getElementById('wg-peer-key-warning');
  1771. if (!warningEl) return;
  1772. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1773. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1774. warningEl.classList.remove('hidden');
  1775. } else {
  1776. warningEl.classList.add('hidden');
  1777. }
  1778. }
  1779. async function submitSaveWGPeer(e) {
  1780. e.preventDefault();
  1781. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1782. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1783. const iface = document.getElementById('wg-peer-modal-iface').value;
  1784. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1785. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1786. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1787. .split(',')
  1788. .map(s => s.trim())
  1789. .filter(s => s.length > 0);
  1790. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1791. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1792. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1793. const lastColon = epHost.lastIndexOf(':');
  1794. const maybePort = epHost.substring(lastColon + 1);
  1795. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1796. if (!epPort) epPort = parseInt(maybePort, 10);
  1797. epHost = epHost.substring(0, lastColon);
  1798. } else {
  1799. break;
  1800. }
  1801. }
  1802. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1803. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1804. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1805. // Validation
  1806. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1807. if (targetIface && targetIface.public_key === pub) {
  1808. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1809. return;
  1810. }
  1811. try {
  1812. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1813. method: 'POST',
  1814. headers: { 'Content-Type': 'application/json' },
  1815. body: JSON.stringify({
  1816. orig_interface: origIface,
  1817. orig_public_key: origPubKey,
  1818. interface: iface,
  1819. name,
  1820. public_key: pub,
  1821. allowed_ips: allowed,
  1822. endpoint_address: epHost,
  1823. endpoint_port: epPort,
  1824. persistent_keepalive: keepalive,
  1825. preshared_key: psk,
  1826. disabled
  1827. })
  1828. });
  1829. const data = await res.json();
  1830. if (res.ok) {
  1831. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1832. closeAddWGPeerModal();
  1833. loadWireGuard(false);
  1834. } else {
  1835. showToast('Error', data.error || 'Failed to save peer', 'error');
  1836. }
  1837. } catch (err) {
  1838. showToast('Error', err.message, 'error');
  1839. }
  1840. }
  1841. async function toggleWGPeerState(iface, pubkey, enable) {
  1842. try {
  1843. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1844. method: 'POST',
  1845. headers: { 'Content-Type': 'application/json' },
  1846. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1847. });
  1848. const data = await res.json();
  1849. if (res.ok) {
  1850. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1851. loadWireGuard(false);
  1852. } else {
  1853. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1854. }
  1855. } catch (err) {
  1856. showToast('Error', err.message, 'error');
  1857. }
  1858. }
  1859. async function deleteWGPeer(iface, pubkey) {
  1860. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1861. try {
  1862. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1863. method: 'POST',
  1864. headers: { 'Content-Type': 'application/json' },
  1865. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1866. });
  1867. const data = await res.json();
  1868. if (res.ok) {
  1869. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1870. loadWireGuard(false);
  1871. } else {
  1872. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1873. }
  1874. } catch (err) {
  1875. showToast('Error', err.message, 'error');
  1876. }
  1877. }
  1878. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1879. function switchIpsecModalTab(tab) {
  1880. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1881. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1882. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1883. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1884. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1885. if (tab === 'p1') {
  1886. if (p1Tab) {
  1887. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  1888. }
  1889. if (p2Tab) {
  1890. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1891. }
  1892. if (p1Content) p1Content.classList.remove('hidden');
  1893. if (p2Content) p2Content.classList.add('hidden');
  1894. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1895. } else {
  1896. if (p1Tab) {
  1897. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1898. }
  1899. if (p2Tab) {
  1900. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  1901. }
  1902. if (p1Content) p1Content.classList.add('hidden');
  1903. if (p2Content) p2Content.classList.remove('hidden');
  1904. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1905. }
  1906. }
  1907. function toggleIpsecPhaseStep() {
  1908. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1909. if (p1Content && !p1Content.classList.contains('hidden')) {
  1910. switchIpsecModalTab('p2');
  1911. } else {
  1912. switchIpsecModalTab('p1');
  1913. }
  1914. }
  1915. function toggleIpsecPskVisibility() {
  1916. const pskInput = document.getElementById('ipsec-modal-psk');
  1917. if (!pskInput) return;
  1918. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1919. }
  1920. function addIpsecLocalSubnet(val = '') {
  1921. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1922. if (!container) return;
  1923. const row = document.createElement('div');
  1924. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1925. row.innerHTML = `
  1926. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  1927. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  1928. `;
  1929. container.appendChild(row);
  1930. }
  1931. function addIpsecRemoteSubnet(val = '') {
  1932. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1933. if (!container) return;
  1934. const row = document.createElement('div');
  1935. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1936. row.innerHTML = `
  1937. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  1938. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  1939. `;
  1940. container.appendChild(row);
  1941. }
  1942. function updateIpsecEspProposalFromPFS(val) {
  1943. const prop = document.getElementById('ipsec-modal-espprop');
  1944. if (!prop) return;
  1945. if (val === 'none') {
  1946. prop.value = 'aes256-sha256,aes128-sha256,default';
  1947. } else {
  1948. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1949. }
  1950. }
  1951. function updateIpsecIkeProposalFromDH(dh) {
  1952. const el = document.getElementById('ipsec-modal-ikeprop');
  1953. if (el) {
  1954. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1955. }
  1956. }
  1957. function safeSetVal(id, val) {
  1958. const el = document.getElementById(id);
  1959. if (el) el.value = val;
  1960. }
  1961. function safeSetChecked(id, val) {
  1962. const el = document.getElementById(id);
  1963. if (el) el.checked = !!val;
  1964. }
  1965. function safeGetVal(id, def = '') {
  1966. const el = document.getElementById(id);
  1967. return el ? el.value : def;
  1968. }
  1969. async function loadIPSec(populateInputs = true) {
  1970. try {
  1971. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1972. const list = await res.json();
  1973. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1974. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1975. const badge = document.getElementById('ipsec-sas-badge');
  1976. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1977. const tbody = document.getElementById('ipsec-table-body');
  1978. const empty = document.getElementById('ipsec-empty');
  1979. if (!tbody) return;
  1980. tbody.innerHTML = '';
  1981. if (state.ipsecTunnels.length === 0) {
  1982. if (empty) empty.classList.remove('hidden');
  1983. } else {
  1984. if (empty) empty.classList.add('hidden');
  1985. state.ipsecTunnels.forEach(c => {
  1986. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1987. const tr = document.createElement('tr');
  1988. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1989. // Local subnets tags
  1990. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1991. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  1992. // Remote subnets tags
  1993. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1994. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  1995. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1996. const p2Name = c.phase2_name || `${c.name}_p2`;
  1997. tr.innerHTML = `
  1998. <td class="py-2.5 px-3 text-center">
  1999. ${isEstablished ? `
  2000. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2001. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2002. <span>UP</span>
  2003. </span>
  2004. ` : (c.disabled ? `
  2005. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2006. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2007. <span>DOWN</span>
  2008. </span>
  2009. ` : `
  2010. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2011. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2012. <span>IDLE</span>
  2013. </span>
  2014. `)}
  2015. </td>
  2016. <td class="py-2.5 px-4 font-bold text-white">
  2017. <div class="flex items-center gap-2">
  2018. <span class="text-amber-400">🛡</span>
  2019. <div>
  2020. <div>${escapeHtml(c.name)}</div>
  2021. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2022. </div>
  2023. </div>
  2024. </td>
  2025. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2026. <td class="py-2.5 px-4 font-sans">
  2027. <div class="flex items-center gap-1.5">
  2028. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  2029. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2030. </div>
  2031. </td>
  2032. <td class="py-2.5 px-4">
  2033. <div class="space-y-1">
  2034. <div class="flex items-center flex-wrap gap-1">
  2035. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2036. ${localBadges}
  2037. </div>
  2038. <div class="flex items-center flex-wrap gap-1">
  2039. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2040. ${remoteBadges}
  2041. </div>
  2042. </div>
  2043. </td>
  2044. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2045. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2046. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2047. </div>
  2048. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2049. </td>
  2050. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2051. ${isEstablished ? `
  2052. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  2053. ` : `
  2054. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  2055. `}
  2056. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2057. ${c.disabled ? 'Enable' : 'Disable'}
  2058. </button>
  2059. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2060. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2061. </td>
  2062. `;
  2063. tbody.appendChild(tr);
  2064. });
  2065. }
  2066. } catch (err) {
  2067. console.error('Failed to load IPSec:', err);
  2068. }
  2069. }
  2070. function openAddIPSecModal() {
  2071. const modal = document.getElementById('ipsec-modal');
  2072. if (!modal) return;
  2073. const title = document.getElementById('ipsec-modal-title');
  2074. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2075. // Phase 1 Fields
  2076. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2077. const nameEl = document.getElementById('ipsec-modal-name');
  2078. if (nameEl) nameEl.readOnly = false;
  2079. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2080. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2081. safeSetVal('ipsec-modal-remotegw', '');
  2082. safeSetVal('ipsec-modal-localaddrs', '');
  2083. safeSetVal('ipsec-modal-comments', '');
  2084. safeSetVal('ipsec-modal-psk', '');
  2085. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2086. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2087. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2088. safeSetVal('ipsec-modal-localid', '');
  2089. safeSetVal('ipsec-modal-remoteid', '');
  2090. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2091. // Phase 2 Fields
  2092. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2093. safeSetVal('ipsec-modal-espkeylife', '28800');
  2094. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2095. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2096. safeSetChecked('ipsec-modal-autostart', true);
  2097. safeSetChecked('ipsec-modal-disabled', false);
  2098. // Clear & Populate default dynamic subnets
  2099. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2100. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2101. if (localContainer) {
  2102. localContainer.innerHTML = '';
  2103. addIpsecLocalSubnet('192.168.10.0/24');
  2104. }
  2105. if (remoteContainer) {
  2106. remoteContainer.innerHTML = '';
  2107. addIpsecRemoteSubnet('192.168.20.0/24');
  2108. }
  2109. switchIpsecModalTab('p1');
  2110. modal.classList.remove('hidden');
  2111. }
  2112. function openEditIPSecModal(name) {
  2113. const modal = document.getElementById('ipsec-modal');
  2114. if (!modal) return;
  2115. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2116. if (!conn) return;
  2117. const title = document.getElementById('ipsec-modal-title');
  2118. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2119. // Phase 1 Fields
  2120. safeSetVal('ipsec-modal-name', conn.name);
  2121. const nameEl = document.getElementById('ipsec-modal-name');
  2122. if (nameEl) nameEl.readOnly = true;
  2123. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2124. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2125. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2126. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2127. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2128. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2129. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2130. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2131. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2132. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2133. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2134. // Phase 2 Fields
  2135. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2136. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2137. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2138. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2139. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2140. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2141. // Populate dynamic subnets
  2142. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2143. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2144. if (localContainer) {
  2145. localContainer.innerHTML = '';
  2146. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2147. locals.forEach(s => addIpsecLocalSubnet(s));
  2148. }
  2149. if (remoteContainer) {
  2150. remoteContainer.innerHTML = '';
  2151. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2152. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2153. }
  2154. switchIpsecModalTab('p1');
  2155. modal.classList.remove('hidden');
  2156. }
  2157. function closeAddIPSecModal() {
  2158. const modal = document.getElementById('ipsec-modal');
  2159. if (modal) modal.classList.add('hidden');
  2160. }
  2161. async function submitSaveIPSec(e) {
  2162. if (e) e.preventDefault();
  2163. const name = safeGetVal('ipsec-modal-name').trim();
  2164. if (!name) {
  2165. showToast('Error', 'Tunnel name is required', 'error');
  2166. return;
  2167. }
  2168. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2169. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2170. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2171. const comments = safeGetVal('ipsec-modal-comments').trim();
  2172. const psk = safeGetVal('ipsec-modal-psk');
  2173. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2174. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2175. const localId = safeGetVal('ipsec-modal-localid').trim();
  2176. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2177. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2178. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2179. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2180. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2181. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2182. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2183. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2184. // Scrape dynamic local and remote subnets
  2185. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2186. const localSubnets = [];
  2187. localInputs.forEach(inp => {
  2188. const v = inp.value.trim();
  2189. if (v) localSubnets.push(v);
  2190. });
  2191. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2192. const remoteSubnets = [];
  2193. remoteInputs.forEach(inp => {
  2194. const v = inp.value.trim();
  2195. if (v) remoteSubnets.push(v);
  2196. });
  2197. try {
  2198. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2199. method: 'POST',
  2200. headers: { 'Content-Type': 'application/json' },
  2201. body: JSON.stringify({
  2202. name,
  2203. comment: comments,
  2204. ike_version: ikeVersion,
  2205. local_addrs: localAddrs,
  2206. remote_addrs: remotegw,
  2207. preshared_key: psk,
  2208. ike_proposals: ikeProposals,
  2209. ike_keylife: ikeKeylife,
  2210. local_id: localId,
  2211. remote_id: remoteId,
  2212. dpd: dpd,
  2213. phase2_name: phase2Name,
  2214. esp_proposals: espProposals,
  2215. esp_keylife: espKeylife,
  2216. pfs_group: pfsGroup,
  2217. pfs: pfsGroup !== 'none',
  2218. local_subnets: localSubnets,
  2219. remote_subnets: remoteSubnets,
  2220. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2221. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2222. auto_start: autostart,
  2223. disabled
  2224. })
  2225. });
  2226. if (res.ok) {
  2227. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2228. closeAddIPSecModal();
  2229. loadIPSec(false);
  2230. } else {
  2231. const err = await res.json();
  2232. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2233. }
  2234. } catch (err) {
  2235. showToast('Error', err.message, 'error');
  2236. }
  2237. }
  2238. async function startIPSecTunnel(name) {
  2239. try {
  2240. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2241. if (res.ok) {
  2242. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2243. setTimeout(() => loadIPSec(false), 2000);
  2244. }
  2245. } catch (err) {
  2246. showToast('Error', err.message, 'error');
  2247. }
  2248. }
  2249. async function stopIPSecTunnel(name) {
  2250. try {
  2251. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2252. if (res.ok) {
  2253. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2254. loadIPSec(false);
  2255. }
  2256. } catch (err) {
  2257. showToast('Error', err.message, 'error');
  2258. }
  2259. }
  2260. async function toggleIPSecState(name, enable) {
  2261. try {
  2262. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2263. method: 'POST',
  2264. headers: { 'Content-Type': 'application/json' },
  2265. body: JSON.stringify({ enabled: enable })
  2266. });
  2267. if (res.ok) {
  2268. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2269. loadIPSec(false);
  2270. }
  2271. } catch (err) {
  2272. showToast('Error', err.message, 'error');
  2273. }
  2274. }
  2275. async function deleteIPSecConn(name) {
  2276. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2277. try {
  2278. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2279. if (res.ok) {
  2280. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2281. loadIPSec(false);
  2282. fetchData(false);
  2283. }
  2284. } catch (err) {
  2285. showToast('Error', err.message, 'error');
  2286. }
  2287. }
  2288. // ======================== L2TP Multi-Instance ========================
  2289. async function loadL2TP(populateInputs = true) {
  2290. try {
  2291. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2292. await fetchPPPProfilesList();
  2293. }
  2294. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2295. const list = await res.json();
  2296. state.l2tpList = Array.isArray(list) ? list : [];
  2297. const badge = document.getElementById('l2tp-count-badge');
  2298. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2299. const tbody = document.getElementById('l2tp-table-body');
  2300. const empty = document.getElementById('l2tp-empty');
  2301. if (!tbody) return;
  2302. tbody.innerHTML = '';
  2303. if (state.l2tpList.length === 0) {
  2304. if (empty) empty.classList.remove('hidden');
  2305. } else {
  2306. if (empty) empty.classList.add('hidden');
  2307. state.l2tpList.forEach(inst => {
  2308. const tr = document.createElement('tr');
  2309. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2310. tr.innerHTML = `
  2311. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2312. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2313. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2314. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2315. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2316. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2317. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2318. <td class="py-2.5 px-3 text-center">
  2319. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  2320. ${inst.default_route ? 'Yes' : 'No'}
  2321. </span>
  2322. </td>
  2323. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2324. ${inst.running ? `
  2325. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2326. ` : `
  2327. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2328. `}
  2329. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2330. ${inst.disabled ? 'Enable' : 'Disable'}
  2331. </button>
  2332. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2333. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2334. </td>
  2335. `;
  2336. tbody.appendChild(tr);
  2337. });
  2338. }
  2339. } catch (err) {
  2340. console.error('Failed to load L2TP:', err);
  2341. }
  2342. }
  2343. async function openAddL2TPModal() {
  2344. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2345. await fetchPPPProfilesList();
  2346. }
  2347. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2348. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2349. document.getElementById('l2tp-modal-name').readOnly = false;
  2350. document.getElementById('l2tp-modal-server').value = '';
  2351. document.getElementById('l2tp-modal-user').value = '';
  2352. document.getElementById('l2tp-modal-pass').value = '';
  2353. document.getElementById('l2tp-modal-ipsec').value = '';
  2354. document.getElementById('l2tp-modal-defroute').checked = true;
  2355. document.getElementById('l2tp-modal-disabled').checked = false;
  2356. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2357. document.getElementById('l2tp-modal').classList.remove('hidden');
  2358. }
  2359. async function openEditL2TPModal(name) {
  2360. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2361. await fetchPPPProfilesList();
  2362. }
  2363. const inst = (state.l2tpList || []).find(i => i.name === name);
  2364. if (!inst) return;
  2365. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2366. document.getElementById('l2tp-modal-name').value = inst.name;
  2367. document.getElementById('l2tp-modal-name').readOnly = true;
  2368. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2369. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2370. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2371. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2372. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2373. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2374. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2375. document.getElementById('l2tp-modal').classList.remove('hidden');
  2376. }
  2377. function closeL2TPModal() {
  2378. document.getElementById('l2tp-modal').classList.add('hidden');
  2379. }
  2380. async function submitSaveL2TP(e) {
  2381. e.preventDefault();
  2382. const name = document.getElementById('l2tp-modal-name').value.trim();
  2383. const server = document.getElementById('l2tp-modal-server').value.trim();
  2384. const user = document.getElementById('l2tp-modal-user').value.trim();
  2385. const pass = document.getElementById('l2tp-modal-pass').value;
  2386. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2387. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2388. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2389. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2390. try {
  2391. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2392. method: 'POST',
  2393. headers: { 'Content-Type': 'application/json' },
  2394. body: JSON.stringify({
  2395. name,
  2396. connect_to: server,
  2397. username: user,
  2398. password: pass,
  2399. profile: profile,
  2400. ipsec_secret: ipsec,
  2401. default_route: defRoute,
  2402. disabled
  2403. })
  2404. });
  2405. if (res.ok) {
  2406. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2407. closeL2TPModal();
  2408. loadL2TP(false);
  2409. fetchData(false);
  2410. }
  2411. } catch (err) {
  2412. showToast('Error', err.message, 'error');
  2413. }
  2414. }
  2415. async function connectL2TPInstance(name) {
  2416. try {
  2417. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2418. if (res.ok) {
  2419. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2420. setTimeout(() => loadL2TP(false), 2000);
  2421. }
  2422. } catch (err) {
  2423. showToast('Error', err.message, 'error');
  2424. }
  2425. }
  2426. async function disconnectL2TPInstance(name) {
  2427. try {
  2428. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2429. if (res.ok) {
  2430. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2431. loadL2TP(false);
  2432. }
  2433. } catch (err) {
  2434. showToast('Error', err.message, 'error');
  2435. }
  2436. }
  2437. async function toggleL2TPState(name, enable) {
  2438. try {
  2439. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2440. method: 'POST',
  2441. headers: { 'Content-Type': 'application/json' },
  2442. body: JSON.stringify({ enabled: enable })
  2443. });
  2444. if (res.ok) {
  2445. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2446. loadL2TP(false);
  2447. }
  2448. } catch (err) {
  2449. showToast('Error', err.message, 'error');
  2450. }
  2451. }
  2452. async function deleteL2TPInstance(name) {
  2453. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2454. try {
  2455. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2456. if (res.ok) {
  2457. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2458. loadL2TP(false);
  2459. fetchData(false);
  2460. }
  2461. } catch (err) {
  2462. showToast('Error', err.message, 'error');
  2463. }
  2464. }
  2465. // ======================== PPTP Multi-Instance ========================
  2466. async function loadPPTP(populateInputs = true) {
  2467. try {
  2468. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2469. await fetchPPPProfilesList();
  2470. }
  2471. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2472. const list = await res.json();
  2473. state.pptpList = Array.isArray(list) ? list : [];
  2474. const badge = document.getElementById('pptp-count-badge');
  2475. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2476. const tbody = document.getElementById('pptp-table-body');
  2477. const empty = document.getElementById('pptp-empty');
  2478. if (!tbody) return;
  2479. tbody.innerHTML = '';
  2480. if (state.pptpList.length === 0) {
  2481. if (empty) empty.classList.remove('hidden');
  2482. } else {
  2483. if (empty) empty.classList.add('hidden');
  2484. state.pptpList.forEach(inst => {
  2485. const tr = document.createElement('tr');
  2486. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2487. tr.innerHTML = `
  2488. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2489. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2490. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2491. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2492. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2493. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2494. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2495. <td class="py-2.5 px-3 text-center">
  2496. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  2497. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2498. </span>
  2499. </td>
  2500. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2501. ${inst.running ? `
  2502. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2503. ` : `
  2504. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2505. `}
  2506. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2507. ${inst.disabled ? 'Enable' : 'Disable'}
  2508. </button>
  2509. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2510. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2511. </td>
  2512. `;
  2513. tbody.appendChild(tr);
  2514. });
  2515. }
  2516. } catch (err) {
  2517. console.error('Failed to load PPTP:', err);
  2518. }
  2519. }
  2520. async function openAddPPTPModal() {
  2521. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2522. await fetchPPPProfilesList();
  2523. }
  2524. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2525. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2526. document.getElementById('pptp-modal-name').readOnly = false;
  2527. document.getElementById('pptp-modal-server').value = '';
  2528. document.getElementById('pptp-modal-user').value = '';
  2529. document.getElementById('pptp-modal-pass').value = '';
  2530. document.getElementById('pptp-modal-mppe').checked = true;
  2531. document.getElementById('pptp-modal-defroute').checked = true;
  2532. document.getElementById('pptp-modal-disabled').checked = false;
  2533. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2534. document.getElementById('pptp-modal').classList.remove('hidden');
  2535. }
  2536. async function openEditPPTPModal(name) {
  2537. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2538. await fetchPPPProfilesList();
  2539. }
  2540. const inst = (state.pptpList || []).find(i => i.name === name);
  2541. if (!inst) return;
  2542. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2543. document.getElementById('pptp-modal-name').value = inst.name;
  2544. document.getElementById('pptp-modal-name').readOnly = true;
  2545. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2546. document.getElementById('pptp-modal-user').value = inst.username || '';
  2547. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2548. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2549. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2550. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2551. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2552. document.getElementById('pptp-modal').classList.remove('hidden');
  2553. }
  2554. function closePPTPModal() {
  2555. document.getElementById('pptp-modal').classList.add('hidden');
  2556. }
  2557. async function submitSavePPTP(e) {
  2558. e.preventDefault();
  2559. const name = document.getElementById('pptp-modal-name').value.trim();
  2560. const server = document.getElementById('pptp-modal-server').value.trim();
  2561. const user = document.getElementById('pptp-modal-user').value.trim();
  2562. const pass = document.getElementById('pptp-modal-pass').value;
  2563. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2564. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2565. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2566. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2567. try {
  2568. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2569. method: 'POST',
  2570. headers: { 'Content-Type': 'application/json' },
  2571. body: JSON.stringify({
  2572. name,
  2573. connect_to: server,
  2574. username: user,
  2575. password: pass,
  2576. profile: profile,
  2577. require_mppe: mppe,
  2578. default_route: defRoute,
  2579. auto_reconnect: true,
  2580. disabled
  2581. })
  2582. });
  2583. if (res.ok) {
  2584. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2585. closePPTPModal();
  2586. loadPPTP(false);
  2587. fetchData(false);
  2588. }
  2589. } catch (err) {
  2590. showToast('Error', err.message, 'error');
  2591. }
  2592. }
  2593. async function connectPPTPInstance(name) {
  2594. try {
  2595. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2596. if (res.ok) {
  2597. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2598. setTimeout(() => loadPPTP(false), 2000);
  2599. }
  2600. } catch (err) {
  2601. showToast('Error', err.message, 'error');
  2602. }
  2603. }
  2604. async function disconnectPPTPInstance(name) {
  2605. try {
  2606. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2607. if (res.ok) {
  2608. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2609. loadPPTP(false);
  2610. }
  2611. } catch (err) {
  2612. showToast('Error', err.message, 'error');
  2613. }
  2614. }
  2615. async function togglePPTPState(name, enable) {
  2616. try {
  2617. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2618. method: 'POST',
  2619. headers: { 'Content-Type': 'application/json' },
  2620. body: JSON.stringify({ enabled: enable })
  2621. });
  2622. if (res.ok) {
  2623. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2624. loadPPTP(false);
  2625. }
  2626. } catch (err) {
  2627. showToast('Error', err.message, 'error');
  2628. }
  2629. }
  2630. async function deletePPTPInstance(name) {
  2631. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2632. try {
  2633. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2634. if (res.ok) {
  2635. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2636. loadPPTP(false);
  2637. fetchData(false);
  2638. }
  2639. } catch (err) {
  2640. showToast('Error', err.message, 'error');
  2641. }
  2642. }
  2643. // ---------------- Modal & Helper Functions ----------------
  2644. function openVlanModal(defaultParent = '') {
  2645. const select = document.getElementById('vlan-parent');
  2646. select.innerHTML = '';
  2647. const allIfaces = state.interfaces || [];
  2648. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2649. if (eligible.length === 0) {
  2650. const opt = document.createElement('option');
  2651. opt.value = '';
  2652. opt.innerText = 'No VLAN-capable interfaces available';
  2653. select.appendChild(opt);
  2654. } else {
  2655. eligible.forEach(i => {
  2656. const opt = document.createElement('option');
  2657. opt.value = i.name;
  2658. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2659. if (i.name === defaultParent) opt.selected = true;
  2660. select.appendChild(opt);
  2661. });
  2662. }
  2663. document.getElementById('vlan-id').value = '';
  2664. document.getElementById('vlan-name').value = '';
  2665. document.getElementById('vlan-ip').value = '';
  2666. document.getElementById('vlan-desc').value = '';
  2667. autoSuggestVlanName();
  2668. document.getElementById('vlan-modal').classList.remove('hidden');
  2669. }
  2670. function closeVlanModal() {
  2671. document.getElementById('vlan-modal').classList.add('hidden');
  2672. }
  2673. function autoSuggestVlanName() {
  2674. const parent = document.getElementById('vlan-parent').value;
  2675. if (!parent) return;
  2676. const id = document.getElementById('vlan-id').value;
  2677. const nameInput = document.getElementById('vlan-name');
  2678. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2679. }
  2680. function setSubnetPreset(cidr) {
  2681. const ipInput = document.getElementById('vlan-ip');
  2682. const id = document.getElementById('vlan-id').value || '10';
  2683. ipInput.value = `192.168.${id}.1${cidr}`;
  2684. }
  2685. async function submitCreateVlan(e) {
  2686. e.preventDefault();
  2687. const btn = document.getElementById('vlan-submit-btn');
  2688. btn.disabled = true;
  2689. btn.innerText = 'Creating...';
  2690. const parent = document.getElementById('vlan-parent').value;
  2691. if (!parent) {
  2692. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2693. btn.disabled = false;
  2694. btn.innerText = 'Create VLAN';
  2695. return;
  2696. }
  2697. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2698. const name = document.getElementById('vlan-name').value.trim();
  2699. const ip = document.getElementById('vlan-ip').value.trim();
  2700. const role = document.getElementById('vlan-role').value;
  2701. const desc = document.getElementById('vlan-desc').value.trim();
  2702. try {
  2703. const res = await fetch(`${API_BASE}/vlans`, {
  2704. method: 'POST',
  2705. headers: { 'Content-Type': 'application/json' },
  2706. body: JSON.stringify({
  2707. parent_name: parent,
  2708. vlan_id: id,
  2709. name: name,
  2710. ip_address: ip,
  2711. role: role,
  2712. description: desc,
  2713. mtu: 1500,
  2714. auto_up: true
  2715. })
  2716. });
  2717. const data = await res.json();
  2718. if (res.ok) {
  2719. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2720. state.expandedParents.add(parent);
  2721. closeVlanModal();
  2722. await fetchData(true);
  2723. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2724. } else {
  2725. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2726. }
  2727. } catch (err) {
  2728. showToast('Error', err.message, 'error');
  2729. } finally {
  2730. btn.disabled = false;
  2731. btn.innerText = 'Create VLAN';
  2732. }
  2733. }
  2734. async function confirmDeleteVlan(name) {
  2735. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2736. try {
  2737. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2738. if (res.ok) {
  2739. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2740. closeIfaceModal();
  2741. fetchData(true);
  2742. }
  2743. } catch (err) {
  2744. showToast('Error', err.message, 'error');
  2745. }
  2746. }
  2747. function openIfaceModal(name) {
  2748. const iface = (state.interfaces || []).find(i => i.name === name);
  2749. if (!iface) return;
  2750. state.currentModalIface = iface.name;
  2751. document.getElementById('modal-iface-name').innerText = iface.name;
  2752. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2753. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2754. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2755. document.getElementById('modal-iface-desc').value = iface.description || '';
  2756. const nameInput = document.getElementById('modal-iface-new-name');
  2757. const renameBtn = document.getElementById('modal-btn-rename');
  2758. const renameHelp = document.getElementById('modal-iface-rename-help');
  2759. if (nameInput) {
  2760. nameInput.value = iface.name;
  2761. if (iface.name === 'lo' || iface.type === 'loopback') {
  2762. nameInput.disabled = true;
  2763. if (renameBtn) renameBtn.disabled = true;
  2764. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  2765. } else {
  2766. nameInput.disabled = false;
  2767. if (renameBtn) renameBtn.disabled = false;
  2768. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  2769. }
  2770. }
  2771. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2772. if (iface.is_vlan) {
  2773. delBtn.classList.remove('hidden');
  2774. } else {
  2775. delBtn.classList.add('hidden');
  2776. }
  2777. renderModalIPs(iface);
  2778. document.getElementById('iface-modal').classList.remove('hidden');
  2779. }
  2780. function renderModalIPs(iface) {
  2781. const container = document.getElementById('modal-ip-list');
  2782. container.innerHTML = '';
  2783. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2784. if (addrs.length === 0) {
  2785. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2786. return;
  2787. }
  2788. addrs.forEach(addr => {
  2789. const row = document.createElement('div');
  2790. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2791. row.innerHTML = `
  2792. <span class="text-white">${addr}</span>
  2793. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2794. `;
  2795. container.appendChild(row);
  2796. });
  2797. }
  2798. function closeIfaceModal() {
  2799. document.getElementById('iface-modal').classList.add('hidden');
  2800. state.currentModalIface = null;
  2801. }
  2802. async function setIfaceState(name, newState) {
  2803. const target = name || state.currentModalIface;
  2804. if (!target) return;
  2805. await toggleInterfaceState(target, newState);
  2806. const updated = (state.interfaces || []).find(i => i.name === target);
  2807. if (updated) openIfaceModal(target);
  2808. }
  2809. async function applyMTU() {
  2810. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2811. try {
  2812. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2813. method: 'POST',
  2814. headers: { 'Content-Type': 'application/json' },
  2815. body: JSON.stringify({ mtu })
  2816. });
  2817. if (res.ok) {
  2818. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2819. fetchData(false);
  2820. }
  2821. } catch (err) {
  2822. showToast('Error', err.message, 'error');
  2823. }
  2824. }
  2825. async function addInterfaceIP() {
  2826. const ip = document.getElementById('modal-new-ip').value.trim();
  2827. if (!ip) return;
  2828. try {
  2829. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2830. method: 'POST',
  2831. headers: { 'Content-Type': 'application/json' },
  2832. body: JSON.stringify({ ip })
  2833. });
  2834. if (res.ok) {
  2835. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2836. document.getElementById('modal-new-ip').value = '';
  2837. await fetchData(false);
  2838. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2839. if (iface) renderModalIPs(iface);
  2840. } else {
  2841. const err = await res.json();
  2842. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2843. }
  2844. } catch (err) {
  2845. showToast('Error', err.message, 'error');
  2846. }
  2847. }
  2848. async function removeInterfaceIP(ip) {
  2849. if (!confirm(`Remove IP ${ip}?`)) return;
  2850. try {
  2851. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2852. method: 'DELETE',
  2853. headers: { 'Content-Type': 'application/json' },
  2854. body: JSON.stringify({ ip })
  2855. });
  2856. if (res.ok) {
  2857. showToast('IP Removed', `Removed ${ip}`, 'success');
  2858. await fetchData(false);
  2859. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2860. if (iface) renderModalIPs(iface);
  2861. }
  2862. } catch (err) {
  2863. showToast('Error', err.message, 'error');
  2864. }
  2865. }
  2866. async function renameInterface() {
  2867. const oldName = state.currentModalIface;
  2868. const newNameInput = document.getElementById('modal-iface-new-name');
  2869. const newName = (newNameInput?.value || '').trim();
  2870. if (!oldName) return;
  2871. if (!newName) {
  2872. showToast('Warning', 'Interface name cannot be empty', 'warning');
  2873. return;
  2874. }
  2875. if (newName === oldName) {
  2876. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  2877. return;
  2878. }
  2879. if (newName.length > 15) {
  2880. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  2881. return;
  2882. }
  2883. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  2884. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  2885. return;
  2886. }
  2887. const renameBtn = document.getElementById('modal-btn-rename');
  2888. if (renameBtn) {
  2889. renameBtn.disabled = true;
  2890. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  2891. }
  2892. try {
  2893. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2894. method: 'POST',
  2895. headers: { 'Content-Type': 'application/json' },
  2896. body: JSON.stringify({ new_name: newName })
  2897. });
  2898. const data = await res.json();
  2899. if (!res.ok) {
  2900. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  2901. return;
  2902. }
  2903. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  2904. state.currentModalIface = newName;
  2905. document.getElementById('modal-iface-name').innerText = newName;
  2906. // Refresh application state
  2907. await fetchData(false);
  2908. const updated = (state.interfaces || []).find(i => i.name === newName);
  2909. if (updated) {
  2910. openIfaceModal(newName);
  2911. } else {
  2912. closeIfaceModal();
  2913. }
  2914. } catch (err) {
  2915. showToast('Error', err.message, 'error');
  2916. } finally {
  2917. if (renameBtn) {
  2918. renameBtn.disabled = false;
  2919. renameBtn.innerHTML = `
  2920. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  2921. <span>Rename</span>
  2922. `;
  2923. }
  2924. }
  2925. }
  2926. async function saveInterfaceMetadata() {
  2927. const oldName = state.currentModalIface;
  2928. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  2929. const role = document.getElementById('modal-iface-role').value;
  2930. const desc = document.getElementById('modal-iface-desc').value.trim();
  2931. let targetName = oldName;
  2932. // If user changed the name before clicking Save Changes, execute rename first
  2933. if (newName && newName !== oldName && oldName !== 'lo') {
  2934. try {
  2935. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2936. method: 'POST',
  2937. headers: { 'Content-Type': 'application/json' },
  2938. body: JSON.stringify({ new_name: newName })
  2939. });
  2940. const data = await renameRes.json();
  2941. if (!renameRes.ok) {
  2942. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  2943. return;
  2944. }
  2945. targetName = newName;
  2946. state.currentModalIface = newName;
  2947. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  2948. } catch (err) {
  2949. showToast('Error', err.message, 'error');
  2950. return;
  2951. }
  2952. }
  2953. try {
  2954. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  2955. method: 'POST',
  2956. headers: { 'Content-Type': 'application/json' },
  2957. body: JSON.stringify({ role, description: desc })
  2958. });
  2959. if (res.ok) {
  2960. showToast('Saved', 'Interface configuration updated', 'success');
  2961. closeIfaceModal();
  2962. fetchData(false);
  2963. } else {
  2964. const err = await res.json();
  2965. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  2966. }
  2967. } catch (err) {
  2968. showToast('Error', err.message, 'error');
  2969. }
  2970. }
  2971. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2972. state.fwSubTab = 'filter';
  2973. state.routesSubTab = 'routes';
  2974. function renderRuleFlag(disabled, hasComment) {
  2975. let flags = '';
  2976. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2977. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2978. return flags || '<span class="text-slate-600">-</span>';
  2979. }
  2980. function renderActionBadge(action) {
  2981. const act = (action || '').toLowerCase();
  2982. let color = 'bg-slate-800 text-slate-300';
  2983. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2984. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2985. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2986. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2987. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2988. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2989. }
  2990. function switchFWSubTab(tab) {
  2991. state.fwSubTab = tab;
  2992. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2993. tabs.forEach(t => {
  2994. const panel = document.getElementById(`fw-subtab-${t}`);
  2995. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2996. if (panel) {
  2997. if (t === tab) panel.classList.remove('hidden');
  2998. else panel.classList.add('hidden');
  2999. }
  3000. if (btn) {
  3001. if (t === tab) {
  3002. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3003. } else {
  3004. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  3005. }
  3006. }
  3007. });
  3008. const addBtn = document.getElementById('fw-primary-add-btn');
  3009. if (addBtn) {
  3010. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3011. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3012. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3013. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3014. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3015. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3016. }
  3017. if (tab === 'geo') loadGeoIP();
  3018. if (tab === 'connections') loadConnections();
  3019. setTimeout(initTableSorting, 50);
  3020. }
  3021. function openCurrentFWModal() {
  3022. if (state.fwSubTab === 'filter') openAddFilterModal();
  3023. else if (state.fwSubTab === 'nat') openAddNATModal();
  3024. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3025. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3026. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3027. else if (state.fwSubTab === 'connections') loadConnections();
  3028. }
  3029. async function loadFirewall(populateDropdowns = true) {
  3030. try {
  3031. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3032. fetch(`${API_BASE}/firewall/summary`),
  3033. fetch(`${API_BASE}/firewall/filter`),
  3034. fetch(`${API_BASE}/firewall/nat`),
  3035. fetch(`${API_BASE}/firewall/mangle`),
  3036. fetch(`${API_BASE}/firewall/address-lists`),
  3037. fetch(`${API_BASE}/firewall/geoip/status`),
  3038. fetch(`${API_BASE}/firewall/geoip/countries`)
  3039. ]);
  3040. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3041. if (filterRes.ok) state.filterRules = await filterRes.json();
  3042. if (natRes.ok) state.natRules = await natRes.json();
  3043. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3044. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3045. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3046. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3047. // Badges
  3048. const bFilter = document.getElementById('fw-badge-filter');
  3049. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3050. const bNat = document.getElementById('fw-badge-nat');
  3051. if (bNat) bNat.innerText = (state.natRules || []).length;
  3052. const bMangle = document.getElementById('fw-badge-mangle');
  3053. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3054. const bAddr = document.getElementById('fw-badge-addrlist');
  3055. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3056. const bGeo = document.getElementById('fw-badge-geo');
  3057. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3058. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3059. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3060. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3061. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3062. const tbodyFilter = document.getElementById('filter-rules-table-body');
  3063. if (tbodyFilter && (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter)) {
  3064. tbodyFilter.dataset.sig = sigFilter;
  3065. renderFilterRules();
  3066. }
  3067. const tbodyNat = document.getElementById('nat-rules-table-body');
  3068. if (tbodyNat && (populateDropdowns || tbodyNat.dataset.sig !== sigNat)) {
  3069. tbodyNat.dataset.sig = sigNat;
  3070. renderNATRules();
  3071. }
  3072. const tbodyMangle = document.getElementById('mangle-rules-table-body');
  3073. if (tbodyMangle && (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle)) {
  3074. tbodyMangle.dataset.sig = sigMangle;
  3075. renderMangleRules();
  3076. }
  3077. const tbodyAddr = document.getElementById('addr-list-table-body');
  3078. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3079. tbodyAddr.dataset.sig = sigAddr;
  3080. renderAddressLists();
  3081. }
  3082. renderGeoCountries();
  3083. if (state.fwSubTab === 'connections') {
  3084. loadConnections();
  3085. }
  3086. } catch (err) {
  3087. console.error('Failed to load firewall:', err);
  3088. }
  3089. }
  3090. // ----------------- Filter Rules -----------------
  3091. function renderFilterRules() {
  3092. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3093. const tbody = document.getElementById('filter-table-body');
  3094. const empty = document.getElementById('filter-empty');
  3095. if (!tbody) return;
  3096. tbody.innerHTML = '';
  3097. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3098. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3099. if (rules.length === 0) {
  3100. empty?.classList.remove('hidden');
  3101. return;
  3102. }
  3103. empty?.classList.add('hidden');
  3104. rules.forEach((r, idx) => {
  3105. const tr = document.createElement('tr');
  3106. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3107. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3108. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3109. let actionExtra = '';
  3110. if (r.action === 'reject') {
  3111. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3112. } else if (r.action === 'jump') {
  3113. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3114. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3115. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3116. } else if (r.action === 'log' && r.log_prefix) {
  3117. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3118. }
  3119. tr.innerHTML = `
  3120. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3121. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3122. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3123. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3124. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3125. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3126. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3127. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3128. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3129. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3130. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3131. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3132. </td>
  3133. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3134. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3135. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3136. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3137. <button onclick="toggleFilterRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  3138. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3139. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3140. </td>
  3141. `;
  3142. tbody.appendChild(tr);
  3143. });
  3144. }
  3145. function formatTarget(addr, list, geo) {
  3146. const parts = [];
  3147. if (addr) parts.push(`<span>${addr}</span>`);
  3148. if (list) {
  3149. const inv = list.startsWith('!') ? '!' : '';
  3150. const clean = list.replace(/^!/, '');
  3151. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950/80 border border-amber-800/40 text-amber-300 font-mono" title="Address List: ${list}">${inv}list:${clean}</span>`);
  3152. }
  3153. if (geo) {
  3154. const inv = geo.startsWith('!') ? '!' : '';
  3155. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3156. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-950/80 border border-emerald-800/40 text-emerald-300 font-mono" title="Geo-Location: ${geo}">🌍 ${inv}${clean}</span>`);
  3157. }
  3158. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3159. return parts.join(' ');
  3160. }
  3161. function populateInterfaceSelect(selectId, currentVal = '') {
  3162. const sel = document.getElementById(selectId);
  3163. if (!sel) return;
  3164. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3165. (state.interfaces || []).forEach(i => {
  3166. const opt = document.createElement('option');
  3167. opt.value = i.name;
  3168. opt.innerText = `${i.name} (${i.role || i.type})`;
  3169. if (i.name === currentVal) opt.selected = true;
  3170. sel.appendChild(opt);
  3171. });
  3172. }
  3173. function populateAddressListSelect(selectId, currentVal = '') {
  3174. const sel = document.getElementById(selectId);
  3175. if (!sel) return;
  3176. sel.innerHTML = '<option value="">(None)</option>';
  3177. const cleanVal = (currentVal || '').replace(/^!/, '');
  3178. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3179. customNames.forEach(name => {
  3180. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3181. const opt = document.createElement('option');
  3182. opt.value = name;
  3183. opt.innerText = `${name} (${count} entries)`;
  3184. if (name === cleanVal) opt.selected = true;
  3185. sel.appendChild(opt);
  3186. });
  3187. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3188. const opt = document.createElement('option');
  3189. opt.value = cleanVal;
  3190. opt.innerText = cleanVal;
  3191. opt.selected = true;
  3192. sel.appendChild(opt);
  3193. }
  3194. populateCommonAddrListDatalist();
  3195. }
  3196. function populateCommonAddrListDatalist() {
  3197. const dl = document.getElementById('fw-addrlist-datalist');
  3198. if (!dl) return;
  3199. dl.innerHTML = '';
  3200. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3201. names.forEach(name => {
  3202. const opt = document.createElement('option');
  3203. opt.value = name;
  3204. dl.appendChild(opt);
  3205. });
  3206. }
  3207. function populateGeoIPSelect(selectId, currentVal = '') {
  3208. const sel = document.getElementById(selectId);
  3209. if (!sel) return;
  3210. sel.innerHTML = '<option value="">(None)</option>';
  3211. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3212. // Presets optgroup
  3213. const grpPresets = document.createElement('optgroup');
  3214. grpPresets.label = '⚡ Regional Presets';
  3215. const presets = [
  3216. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3217. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3218. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3219. ];
  3220. presets.forEach(p => {
  3221. const opt = document.createElement('option');
  3222. opt.value = p.code;
  3223. opt.innerText = p.label;
  3224. if (p.code === cleanVal) opt.selected = true;
  3225. grpPresets.appendChild(opt);
  3226. });
  3227. sel.appendChild(grpPresets);
  3228. // All Countries optgroup
  3229. const grpCountries = document.createElement('optgroup');
  3230. grpCountries.label = '🌍 All Countries';
  3231. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3232. countries.forEach(c => {
  3233. const opt = document.createElement('option');
  3234. opt.value = c.code;
  3235. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3236. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3237. if (c.code === cleanVal) opt.selected = true;
  3238. grpCountries.appendChild(opt);
  3239. });
  3240. sel.appendChild(grpCountries);
  3241. }
  3242. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3243. function switchFwRuleTab(tab) {
  3244. state.activeFwRuleTab = tab;
  3245. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3246. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3247. btn.classList.add('text-slate-400', 'border-transparent');
  3248. });
  3249. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3250. if (activeBtn) {
  3251. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3252. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3253. }
  3254. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3255. const activePane = document.getElementById(`fw-pane-${tab}`);
  3256. if (activePane) activePane.classList.remove('hidden');
  3257. if (tab === 'statistics') {
  3258. startFwStatPolling();
  3259. } else {
  3260. stopFwStatPolling();
  3261. }
  3262. }
  3263. function toggleFwField(fieldKey, expand) {
  3264. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3265. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3266. if (!plusBtn || !fieldBox) return;
  3267. if (expand) {
  3268. plusBtn.classList.add('hidden');
  3269. fieldBox.classList.remove('hidden');
  3270. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3271. if (valInput) valInput.focus();
  3272. } else {
  3273. fieldBox.classList.add('hidden');
  3274. plusBtn.classList.remove('hidden');
  3275. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3276. if (valInput) {
  3277. if (valInput.tagName === 'SELECT') {
  3278. valInput.selectedIndex = 0;
  3279. } else {
  3280. valInput.value = '';
  3281. }
  3282. }
  3283. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3284. if (invInput) invInput.checked = false;
  3285. if (fieldKey === 'cs') {
  3286. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3287. const el = document.getElementById(id);
  3288. if (el) el.checked = false;
  3289. });
  3290. }
  3291. if (fieldKey === 'natstate') {
  3292. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3293. const el = document.getElementById(id);
  3294. if (el) el.checked = false;
  3295. });
  3296. }
  3297. if (fieldKey === 'days') {
  3298. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3299. const el = document.getElementById(`fw-day-${d}`);
  3300. if (el) el.checked = true;
  3301. });
  3302. }
  3303. }
  3304. }
  3305. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3306. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3307. toggleFwField(fieldKey, true);
  3308. let strVal = String(value);
  3309. if (hasInvert) {
  3310. const inv = strVal.startsWith('!');
  3311. if (inv) strVal = strVal.slice(1);
  3312. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3313. if (invEl) invEl.checked = inv;
  3314. }
  3315. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3316. if (valEl) valEl.value = strVal;
  3317. } else {
  3318. toggleFwField(fieldKey, false);
  3319. }
  3320. }
  3321. function getFwFieldVal(fieldKey, hasInvert = false) {
  3322. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3323. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3324. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3325. let v = valEl ? valEl.value.trim() : '';
  3326. if (!v) return '';
  3327. if (hasInvert) {
  3328. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3329. if (invEl && invEl.checked) {
  3330. v = '!' + v.replace(/^!/, '');
  3331. }
  3332. }
  3333. return v;
  3334. }
  3335. function toggleMaximizeFilterModal() {
  3336. const win = document.getElementById('filter-modal-window');
  3337. if (!win) return;
  3338. if (win.classList.contains('max-w-[720px]')) {
  3339. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3340. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3341. } else {
  3342. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3343. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3344. }
  3345. }
  3346. function openAddFilterModal() {
  3347. switchFwRuleTab('general');
  3348. const badge = document.getElementById('fw-modal-badge');
  3349. if (badge) badge.innerText = 'New...';
  3350. document.getElementById('filter-modal-id').value = '';
  3351. document.getElementById('filter-modal-enabled').checked = true;
  3352. document.getElementById('filter-modal-comment').value = '';
  3353. document.getElementById('filter-modal-chain').value = 'forward';
  3354. document.getElementById('filter-modal-action').value = 'accept';
  3355. document.getElementById('filter-modal-log').checked = false;
  3356. populateInterfaceSelect('fw-val-iniface');
  3357. populateInterfaceSelect('fw-val-outiface');
  3358. populateAddressListSelect('fw-val-srclist');
  3359. populateAddressListSelect('fw-val-dstlist');
  3360. populateGeoIPSelect('fw-val-srcgeo');
  3361. populateGeoIPSelect('fw-val-dstgeo');
  3362. const allFieldKeys = [
  3363. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3364. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3365. 'routingmark', 'conntype', 'cs', 'natstate',
  3366. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3367. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3368. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3369. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3370. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3371. ];
  3372. allFieldKeys.forEach(k => toggleFwField(k, false));
  3373. resetCurrentRuleCounters();
  3374. toggleFilterActionFields();
  3375. document.getElementById('filter-modal').classList.remove('hidden');
  3376. }
  3377. function openEditFilterModal(id) {
  3378. const r = (state.filterRules || []).find(rule => rule.id === id);
  3379. if (!r) return;
  3380. switchFwRuleTab('general');
  3381. const badge = document.getElementById('fw-modal-badge');
  3382. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3383. document.getElementById('filter-modal-id').value = r.id;
  3384. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3385. document.getElementById('filter-modal-comment').value = r.comment || '';
  3386. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3387. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3388. document.getElementById('filter-modal-log').checked = !!r.log;
  3389. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3390. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3391. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3392. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3393. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3394. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3395. setFwFieldVal('src', r.src_address, true);
  3396. setFwFieldVal('dst', r.dst_address, true);
  3397. setFwFieldVal('srclist', r.src_address_list, true);
  3398. setFwFieldVal('dstlist', r.dst_address_list, true);
  3399. setFwFieldVal('srcgeo', r.src_geoip, true);
  3400. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3401. if (r.protocol && r.protocol !== 'all') {
  3402. setFwFieldVal('proto', r.protocol, true);
  3403. } else {
  3404. toggleFwField('proto', false);
  3405. }
  3406. setFwFieldVal('sport', r.src_port, true);
  3407. setFwFieldVal('dport', r.dst_port, true);
  3408. setFwFieldVal('anyport', r.any_port, true);
  3409. setFwFieldVal('iniface', r.in_interface, true);
  3410. setFwFieldVal('outiface', r.out_interface, true);
  3411. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3412. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3413. setFwFieldVal('pktmark', r.packet_mark, true);
  3414. setFwFieldVal('connmark', r.connection_mark, true);
  3415. setFwFieldVal('routingmark', r.routing_mark, true);
  3416. setFwFieldVal('conntype', r.connection_type, false);
  3417. const states = r.connection_state || [];
  3418. if (states.length > 0) {
  3419. toggleFwField('cs', true);
  3420. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3421. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3422. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3423. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3424. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3425. } else {
  3426. toggleFwField('cs', false);
  3427. }
  3428. const natStates = r.connection_nat_state || [];
  3429. if (natStates.length > 0) {
  3430. toggleFwField('natstate', true);
  3431. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3432. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3433. } else {
  3434. toggleFwField('natstate', false);
  3435. }
  3436. // Advanced tab fields
  3437. setFwFieldVal('layer7', r.layer7_protocol, false);
  3438. setFwFieldVal('content', r.content, false);
  3439. setFwFieldVal('connbytes', r.connection_bytes, false);
  3440. setFwFieldVal('connrate', r.connection_rate, false);
  3441. setFwFieldVal('pcc', r.pcc, false);
  3442. setFwFieldVal('srcmac', r.src_mac_address, true);
  3443. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3444. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3445. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3446. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3447. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3448. setFwFieldVal('tlshost', r.tls_host, false);
  3449. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3450. setFwFieldVal('priority', r.priority, false);
  3451. setFwFieldVal('dscp', r.dscp, false);
  3452. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3453. if (r.tos) {
  3454. const tosEl = document.getElementById('fw-val-tos');
  3455. if (tosEl) tosEl.value = r.tos;
  3456. }
  3457. setFwFieldVal('pktsize', r.packet_size, false);
  3458. setFwFieldVal('random', r.random, false);
  3459. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3460. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3461. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3462. setFwFieldVal('ttl', r.ttl, false);
  3463. // Extra tab fields
  3464. setFwFieldVal('time', r.time, false);
  3465. if (r.days) {
  3466. toggleFwField('days', true);
  3467. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3468. const chk = document.getElementById(`fw-day-${d}`);
  3469. if (chk) chk.checked = r.days.includes(d);
  3470. });
  3471. } else {
  3472. toggleFwField('days', false);
  3473. }
  3474. setFwFieldVal('limit', r.limit, false);
  3475. setFwFieldVal('dstlimit', r.dst_limit, false);
  3476. setFwFieldVal('psd', r.psd, false);
  3477. // Action fields
  3478. if (r.reject_with) {
  3479. const rwEl = document.getElementById('filter-modal-rejectwith');
  3480. if (rwEl) rwEl.value = r.reject_with;
  3481. }
  3482. if (r.jump_target) {
  3483. const jtEl = document.getElementById('filter-modal-jumptarget');
  3484. if (jtEl) jtEl.value = r.jump_target;
  3485. }
  3486. if (r.address_list) {
  3487. const alEl = document.getElementById('filter-modal-action-addrlist');
  3488. if (alEl) alEl.value = r.address_list;
  3489. }
  3490. if (r.address_list_timeout) {
  3491. const toEl = document.getElementById('filter-modal-action-timeout');
  3492. if (toEl) toEl.value = r.address_list_timeout;
  3493. }
  3494. setFwFieldVal('logprefix', r.log_prefix, false);
  3495. // Statistics
  3496. const bEl = document.getElementById('fw-stat-bytes');
  3497. const pEl = document.getElementById('fw-stat-packets');
  3498. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3499. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3500. state.fwLastBytes = r.bytes || 0;
  3501. state.fwLastPackets = r.packets || 0;
  3502. state.fwLastTimestamp = Date.now();
  3503. state.fwStatRateHistory = new Array(30).fill(0);
  3504. state.fwStatPktHistory = new Array(30).fill(0);
  3505. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3506. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3507. toggleFilterActionFields();
  3508. document.getElementById('filter-modal').classList.remove('hidden');
  3509. }
  3510. function closeFilterModal() {
  3511. stopFwStatPolling();
  3512. document.getElementById('filter-modal').classList.add('hidden');
  3513. }
  3514. function toggleFilterActionFields() {
  3515. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3516. const rejectBox = document.getElementById('filter-action-reject-box');
  3517. const jumpBox = document.getElementById('filter-action-jump-box');
  3518. const addrBox = document.getElementById('filter-action-addrlist-box');
  3519. if (rejectBox) {
  3520. if (act === 'reject') rejectBox.classList.remove('hidden');
  3521. else rejectBox.classList.add('hidden');
  3522. }
  3523. if (jumpBox) {
  3524. if (act === 'jump') jumpBox.classList.remove('hidden');
  3525. else jumpBox.classList.add('hidden');
  3526. }
  3527. if (addrBox) {
  3528. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3529. addrBox.classList.remove('hidden');
  3530. } else {
  3531. addrBox.classList.add('hidden');
  3532. }
  3533. }
  3534. if (act === 'log') {
  3535. const logEl = document.getElementById('filter-modal-log');
  3536. if (logEl) logEl.checked = true;
  3537. toggleFwField('logprefix', true);
  3538. }
  3539. }
  3540. function toggleFwLogPrefix() {
  3541. const isLog = document.getElementById('filter-modal-log')?.checked;
  3542. toggleFwField('logprefix', !!isLog);
  3543. }
  3544. function copyFilterRule() {
  3545. document.getElementById('filter-modal-id').value = '';
  3546. const badge = document.getElementById('fw-modal-badge');
  3547. if (badge) badge.innerText = 'New...';
  3548. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3549. }
  3550. function resetCurrentRuleCounters() {
  3551. state.fwStatRateHistory = new Array(30).fill(0);
  3552. state.fwStatPktHistory = new Array(30).fill(0);
  3553. state.fwLastBytes = 0;
  3554. state.fwLastPackets = 0;
  3555. state.fwLastTimestamp = Date.now();
  3556. const bEl = document.getElementById('fw-stat-bytes');
  3557. const pEl = document.getElementById('fw-stat-packets');
  3558. const rEl = document.getElementById('fw-stat-rate');
  3559. const prEl = document.getElementById('fw-stat-pktrate');
  3560. if (bEl) bEl.value = '0 B';
  3561. if (pEl) pEl.value = '0';
  3562. if (rEl) rEl.value = '0 bps';
  3563. if (prEl) prEl.value = '0 p/s';
  3564. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3565. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3566. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3567. }
  3568. async function resetAllFwCounters() {
  3569. try {
  3570. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3571. if (res.ok) {
  3572. resetCurrentRuleCounters();
  3573. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3574. loadFirewall(false);
  3575. }
  3576. } catch (err) {
  3577. showToast('Error', err.message, 'error');
  3578. }
  3579. }
  3580. async function applyFilterRule(closeAfter = false) {
  3581. const id = document.getElementById('filter-modal-id').value;
  3582. const chain = document.getElementById('filter-modal-chain').value;
  3583. const action = document.getElementById('filter-modal-action').value;
  3584. const comment = document.getElementById('filter-modal-comment').value.trim();
  3585. const enabled = document.getElementById('filter-modal-enabled').checked;
  3586. const src = getFwFieldVal('src', true);
  3587. const dst = getFwFieldVal('dst', true);
  3588. const srclist = getFwFieldVal('srclist', true);
  3589. const dstlist = getFwFieldVal('dstlist', true);
  3590. const srcgeo = getFwFieldVal('srcgeo', true);
  3591. const dstgeo = getFwFieldVal('dstgeo', true);
  3592. const proto = getFwFieldVal('proto', true);
  3593. const sport = getFwFieldVal('sport', true);
  3594. const dport = getFwFieldVal('dport', true);
  3595. const anyport = getFwFieldVal('anyport', true);
  3596. const iniface = getFwFieldVal('iniface', true);
  3597. const outiface = getFwFieldVal('outiface', true);
  3598. const inifacelist = getFwFieldVal('inifacelist', true);
  3599. const outifacelist = getFwFieldVal('outifacelist', true);
  3600. const pktmark = getFwFieldVal('pktmark', true);
  3601. const connmark = getFwFieldVal('connmark', true);
  3602. const routingmark = getFwFieldVal('routingmark', true);
  3603. const conntype = getFwFieldVal('conntype', false);
  3604. const states = [];
  3605. const csBox = document.getElementById('fw-field-cs');
  3606. if (csBox && !csBox.classList.contains('hidden')) {
  3607. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3608. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3609. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3610. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3611. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3612. }
  3613. const natStates = [];
  3614. const natBox = document.getElementById('fw-field-natstate');
  3615. if (natBox && !natBox.classList.contains('hidden')) {
  3616. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3617. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3618. }
  3619. const payload = {
  3620. id,
  3621. chain,
  3622. action,
  3623. protocol: proto || 'all',
  3624. src_address: src,
  3625. dst_address: dst,
  3626. src_port: sport,
  3627. dst_port: dport,
  3628. any_port: anyport,
  3629. in_interface: iniface,
  3630. out_interface: outiface,
  3631. in_interface_list: inifacelist,
  3632. out_interface_list: outifacelist,
  3633. packet_mark: pktmark,
  3634. connection_mark: connmark,
  3635. routing_mark: routingmark,
  3636. connection_type: conntype,
  3637. connection_state: states,
  3638. connection_nat_state: natStates,
  3639. src_address_list: srclist,
  3640. dst_address_list: dstlist,
  3641. src_geoip: srcgeo,
  3642. dst_geoip: dstgeo,
  3643. comment,
  3644. disabled: !enabled,
  3645. // Advanced tab
  3646. layer7_protocol: getFwFieldVal('layer7', false),
  3647. content: getFwFieldVal('content', false),
  3648. connection_bytes: getFwFieldVal('connbytes', false),
  3649. connection_rate: getFwFieldVal('connrate', false),
  3650. pcc: getFwFieldVal('pcc', false),
  3651. src_mac_address: getFwFieldVal('srcmac', true),
  3652. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3653. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3654. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3655. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3656. ipsec_policy: getFwFieldVal('ipsec', false),
  3657. tls_host: getFwFieldVal('tlshost', false),
  3658. ingress_priority: getFwFieldVal('ingresspriority', false),
  3659. priority: getFwFieldVal('priority', false),
  3660. dscp: getFwFieldVal('dscp', false),
  3661. tcp_mss: getFwFieldVal('tcpmss', false),
  3662. tos: document.getElementById('fw-val-tos')?.value || '',
  3663. packet_size: getFwFieldVal('pktsize', false),
  3664. random: getFwFieldVal('random', false),
  3665. tcp_flags: getFwFieldVal('tcpflags', false),
  3666. icmp_options: getFwFieldVal('icmpoptions', false),
  3667. ipv4_options: getFwFieldVal('ipv4options', false),
  3668. ttl: getFwFieldVal('ttl', false),
  3669. // Extra tab
  3670. time: getFwFieldVal('time', false),
  3671. limit: getFwFieldVal('limit', false),
  3672. dst_limit: getFwFieldVal('dstlimit', false),
  3673. psd: getFwFieldVal('psd', false),
  3674. // Action tab
  3675. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3676. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3677. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3678. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3679. log: document.getElementById('filter-modal-log')?.checked || false,
  3680. log_prefix: getFwFieldVal('logprefix', false)
  3681. };
  3682. try {
  3683. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3684. method: 'POST',
  3685. headers: { 'Content-Type': 'application/json' },
  3686. body: JSON.stringify(payload)
  3687. });
  3688. if (res.ok) {
  3689. const data = await res.json();
  3690. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3691. loadFirewall(false);
  3692. if (closeAfter) {
  3693. closeFilterModal();
  3694. } else {
  3695. if (data.id) {
  3696. document.getElementById('filter-modal-id').value = data.id;
  3697. const badge = document.getElementById('fw-modal-badge');
  3698. if (badge) badge.innerText = `#${data.id}`;
  3699. }
  3700. }
  3701. } else {
  3702. const err = await res.json();
  3703. showToast('Error', err.message || 'Failed to save rule', 'error');
  3704. }
  3705. } catch (err) {
  3706. showToast('Error', err.message, 'error');
  3707. }
  3708. }
  3709. function submitSaveFilterRule(e) {
  3710. if (e && e.preventDefault) e.preventDefault();
  3711. return applyFilterRule(true);
  3712. }
  3713. function startFwStatPolling() {
  3714. stopFwStatPolling();
  3715. pollRuleStats();
  3716. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3717. }
  3718. function stopFwStatPolling() {
  3719. if (state.fwStatInterval) {
  3720. clearInterval(state.fwStatInterval);
  3721. state.fwStatInterval = null;
  3722. }
  3723. }
  3724. async function pollRuleStats() {
  3725. const id = document.getElementById('filter-modal-id')?.value;
  3726. if (!id) {
  3727. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3728. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3729. return;
  3730. }
  3731. try {
  3732. const res = await fetch(`${API_BASE}/firewall/filter`);
  3733. if (!res.ok) return;
  3734. const rules = await res.json();
  3735. const r = rules.find(x => x.id === id);
  3736. if (!r) return;
  3737. const now = Date.now();
  3738. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3739. state.fwLastTimestamp = now;
  3740. const curBytes = r.bytes || 0;
  3741. const curPackets = r.packets || 0;
  3742. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3743. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3744. state.fwLastBytes = curBytes;
  3745. state.fwLastPackets = curPackets;
  3746. const rateBps = Math.round((deltaBytes * 8) / dt);
  3747. const ratePkt = Math.round(deltaPkts / dt);
  3748. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3749. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3750. state.fwStatRateHistory.push(rateBps);
  3751. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3752. state.fwStatPktHistory.push(ratePkt);
  3753. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3754. const bEl = document.getElementById('fw-stat-bytes');
  3755. const pEl = document.getElementById('fw-stat-packets');
  3756. const rEl = document.getElementById('fw-stat-rate');
  3757. const prEl = document.getElementById('fw-stat-pktrate');
  3758. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3759. if (pEl) pEl.value = curPackets.toLocaleString();
  3760. if (rEl) rEl.value = formatBps(rateBps);
  3761. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3762. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3763. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3764. } catch (e) {
  3765. console.error('Error polling rule stats', e);
  3766. }
  3767. }
  3768. function formatBps(bps) {
  3769. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3770. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3771. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3772. return bps + ' bps';
  3773. }
  3774. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3775. const svg = document.getElementById(svgId);
  3776. if (!svg) return;
  3777. const w = 500;
  3778. const h = 100;
  3779. const paddingRight = 45;
  3780. const graphWidth = w - paddingRight;
  3781. const maxVal = Math.max(5, ...dataArray);
  3782. const currentVal = dataArray[dataArray.length - 1] || 0;
  3783. const leg = document.getElementById(legendId);
  3784. if (leg) {
  3785. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3786. }
  3787. let gridLines = '';
  3788. for (let i = 0; i <= 5; i++) {
  3789. const y = 8 + (i * (h - 18) / 5);
  3790. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3791. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3792. gridLines += `
  3793. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3794. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3795. `;
  3796. }
  3797. const step = graphWidth / (dataArray.length - 1);
  3798. const points = dataArray.map((val, idx) => {
  3799. const x = idx * step;
  3800. const y = (h - 10) - (val / maxVal) * (h - 20);
  3801. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3802. });
  3803. const polylineStr = points.join(' ');
  3804. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3805. svg.innerHTML = `
  3806. ${gridLines}
  3807. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3808. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3809. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3810. `;
  3811. }
  3812. async function moveFilterRule(id, dir) {
  3813. try {
  3814. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3815. method: 'POST',
  3816. headers: { 'Content-Type': 'application/json' },
  3817. body: JSON.stringify({ direction: dir })
  3818. });
  3819. if (res.ok) loadFirewall(false);
  3820. } catch (err) {
  3821. showToast('Error', err.message, 'error');
  3822. }
  3823. }
  3824. async function toggleFilterRuleState(id, disabled) {
  3825. try {
  3826. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3827. method: 'POST',
  3828. headers: { 'Content-Type': 'application/json' },
  3829. body: JSON.stringify({ disabled })
  3830. });
  3831. if (res.ok) loadFirewall(false);
  3832. } catch (err) {
  3833. showToast('Error', err.message, 'error');
  3834. }
  3835. }
  3836. async function deleteFilterRule(id) {
  3837. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3838. try {
  3839. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3840. if (res.ok) {
  3841. showToast('Deleted', 'Filter rule removed', 'success');
  3842. loadFirewall(false);
  3843. }
  3844. } catch (err) {
  3845. showToast('Error', err.message, 'error');
  3846. }
  3847. }
  3848. // ----------------- NAT Rules -----------------
  3849. function renderNATRules() {
  3850. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3851. const tbody = document.getElementById('nat-table-body');
  3852. const empty = document.getElementById('nat-empty');
  3853. if (!tbody) return;
  3854. tbody.innerHTML = '';
  3855. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3856. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3857. if (rules.length === 0) {
  3858. empty?.classList.remove('hidden');
  3859. return;
  3860. }
  3861. empty?.classList.add('hidden');
  3862. rules.forEach((r, idx) => {
  3863. const tr = document.createElement('tr');
  3864. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3865. let toTarget = '-';
  3866. if (r.action === 'jump') {
  3867. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3868. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3869. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3870. } else if (r.action === 'redirect') {
  3871. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3872. } else if (r.action === 'masquerade') {
  3873. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  3874. } else if (r.action === 'log') {
  3875. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3876. } else {
  3877. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3878. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3879. }
  3880. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3881. tr.innerHTML = `
  3882. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3883. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3884. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3885. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3886. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3887. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3888. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3889. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3890. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3891. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3892. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3893. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3894. </td>
  3895. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3896. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3897. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3898. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3899. <button onclick="toggleNATRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  3900. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3901. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3902. </td>
  3903. `;
  3904. tbody.appendChild(tr);
  3905. });
  3906. }
  3907. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3908. function switchNATRuleTab(tab) {
  3909. state.activeNATRuleTab = tab;
  3910. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3911. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3912. btn.classList.add('text-slate-400', 'border-transparent');
  3913. });
  3914. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3915. if (activeBtn) {
  3916. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3917. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3918. }
  3919. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3920. const activePane = document.getElementById(`nat-pane-${tab}`);
  3921. if (activePane) activePane.classList.remove('hidden');
  3922. if (tab === 'statistics') {
  3923. startNATStatPolling();
  3924. } else {
  3925. stopNATStatPolling();
  3926. }
  3927. }
  3928. function toggleNATField(fieldKey, expand) {
  3929. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3930. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3931. if (!plusBtn || !fieldBox) return;
  3932. if (expand) {
  3933. plusBtn.classList.add('hidden');
  3934. fieldBox.classList.remove('hidden');
  3935. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3936. if (valInput) valInput.focus();
  3937. } else {
  3938. fieldBox.classList.add('hidden');
  3939. plusBtn.classList.remove('hidden');
  3940. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3941. if (valInput) {
  3942. if (valInput.tagName === 'SELECT') {
  3943. valInput.selectedIndex = 0;
  3944. } else {
  3945. valInput.value = '';
  3946. }
  3947. }
  3948. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3949. if (invInput) invInput.checked = false;
  3950. if (fieldKey === 'days') {
  3951. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3952. const el = document.getElementById(`nat-day-${d}`);
  3953. if (el) el.checked = true;
  3954. });
  3955. }
  3956. }
  3957. }
  3958. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3959. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3960. toggleNATField(fieldKey, true);
  3961. let strVal = String(value);
  3962. if (hasInvert) {
  3963. const inv = strVal.startsWith('!');
  3964. if (inv) strVal = strVal.slice(1);
  3965. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3966. if (invEl) invEl.checked = inv;
  3967. }
  3968. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3969. if (valEl) valEl.value = strVal;
  3970. } else {
  3971. toggleNATField(fieldKey, false);
  3972. }
  3973. }
  3974. function getNATFieldVal(fieldKey, hasInvert = false) {
  3975. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3976. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3977. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3978. let v = valEl ? valEl.value.trim() : '';
  3979. if (!v) return '';
  3980. if (hasInvert) {
  3981. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3982. if (invEl && invEl.checked) {
  3983. v = '!' + v.replace(/^!/, '');
  3984. }
  3985. }
  3986. return v;
  3987. }
  3988. function toggleMaximizeNATModal() {
  3989. const win = document.getElementById('nat-modal-window');
  3990. if (!win) return;
  3991. if (win.classList.contains('max-w-[720px]')) {
  3992. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3993. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3994. } else {
  3995. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3996. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3997. }
  3998. }
  3999. function handleNATChainChange() {
  4000. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4001. const actSel = document.getElementById('nat-modal-action');
  4002. if (actSel) {
  4003. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4004. actSel.value = 'masquerade';
  4005. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4006. actSel.value = 'dst-nat';
  4007. }
  4008. }
  4009. toggleNATActionFields();
  4010. }
  4011. function toggleNATActionFields() {
  4012. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4013. const rowAddr = document.getElementById('nat-row-toaddr');
  4014. const rowPort = document.getElementById('nat-row-toport');
  4015. const jumpBox = document.getElementById('nat-action-jump-box');
  4016. const addrBox = document.getElementById('nat-action-addrlist-box');
  4017. // Hide all dynamic rows first
  4018. if (rowAddr) rowAddr.classList.add('hidden');
  4019. if (rowPort) rowPort.classList.add('hidden');
  4020. if (jumpBox) jumpBox.classList.add('hidden');
  4021. if (addrBox) addrBox.classList.add('hidden');
  4022. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4023. if (rowAddr) rowAddr.classList.remove('hidden');
  4024. if (rowPort) rowPort.classList.remove('hidden');
  4025. } else if (act === 'redirect' || act === 'masquerade') {
  4026. if (rowPort) rowPort.classList.remove('hidden');
  4027. } else if (act === 'jump') {
  4028. if (jumpBox) jumpBox.classList.remove('hidden');
  4029. } else if (act.includes('address-list') || act.includes('address list')) {
  4030. if (addrBox) addrBox.classList.remove('hidden');
  4031. }
  4032. if (act === 'log') {
  4033. const logEl = document.getElementById('nat-modal-log');
  4034. if (logEl) logEl.checked = true;
  4035. toggleNATField('logprefix', true);
  4036. }
  4037. }
  4038. function toggleNATLogPrefix() {
  4039. const isLog = document.getElementById('nat-modal-log')?.checked;
  4040. toggleNATField('logprefix', !!isLog);
  4041. }
  4042. function openAddNATModal() {
  4043. switchNATRuleTab('general');
  4044. const badge = document.getElementById('nat-modal-badge');
  4045. if (badge) badge.innerText = 'New...';
  4046. document.getElementById('nat-modal-id').value = '';
  4047. document.getElementById('nat-modal-enabled').checked = true;
  4048. document.getElementById('nat-modal-comment').value = '';
  4049. document.getElementById('nat-modal-chain').value = 'srcnat';
  4050. document.getElementById('nat-modal-action').value = 'masquerade';
  4051. document.getElementById('nat-modal-toaddr').value = '';
  4052. document.getElementById('nat-modal-toport').value = '';
  4053. document.getElementById('nat-modal-log').checked = false;
  4054. populateInterfaceSelect('nat-val-iniface');
  4055. populateInterfaceSelect('nat-val-outiface');
  4056. populateAddressListSelect('nat-val-srclist');
  4057. populateAddressListSelect('nat-val-dstlist');
  4058. populateGeoIPSelect('nat-val-srcgeo');
  4059. populateGeoIPSelect('nat-val-dstgeo');
  4060. const allFieldKeys = [
  4061. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4062. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4063. 'routingmark', 'conntype',
  4064. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4065. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4066. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4067. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4068. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4069. ];
  4070. allFieldKeys.forEach(k => toggleNATField(k, false));
  4071. resetCurrentNATRuleCounters();
  4072. toggleNATActionFields();
  4073. document.getElementById('nat-modal').classList.remove('hidden');
  4074. }
  4075. function openEditNATModal(id) {
  4076. const r = (state.natRules || []).find(rule => rule.id === id);
  4077. if (!r) return;
  4078. switchNATRuleTab('general');
  4079. const badge = document.getElementById('nat-modal-badge');
  4080. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4081. document.getElementById('nat-modal-id').value = r.id;
  4082. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4083. document.getElementById('nat-modal-comment').value = r.comment || '';
  4084. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4085. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4086. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4087. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4088. document.getElementById('nat-modal-log').checked = !!r.log;
  4089. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4090. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4091. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4092. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4093. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4094. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4095. setNATFieldVal('src', r.src_address, true);
  4096. setNATFieldVal('dst', r.dst_address, true);
  4097. setNATFieldVal('srclist', r.src_address_list, true);
  4098. setNATFieldVal('dstlist', r.dst_address_list, true);
  4099. setNATFieldVal('srcgeo', r.src_geoip, true);
  4100. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4101. if (r.protocol && r.protocol !== 'all') {
  4102. setNATFieldVal('proto', r.protocol, true);
  4103. } else {
  4104. toggleNATField('proto', false);
  4105. }
  4106. setNATFieldVal('sport', r.src_port, true);
  4107. setNATFieldVal('dport', r.dst_port, true);
  4108. setNATFieldVal('anyport', r.any_port, true);
  4109. setNATFieldVal('iniface', r.in_interface, true);
  4110. setNATFieldVal('outiface', r.out_interface, true);
  4111. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4112. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4113. setNATFieldVal('pktmark', r.packet_mark, true);
  4114. setNATFieldVal('connmark', r.connection_mark, true);
  4115. setNATFieldVal('routingmark', r.routing_mark, true);
  4116. setNATFieldVal('conntype', r.connection_type, false);
  4117. // Advanced tab fields
  4118. setNATFieldVal('layer7', r.layer7_protocol, false);
  4119. setNATFieldVal('content', r.content, false);
  4120. setNATFieldVal('connbytes', r.connection_bytes, false);
  4121. setNATFieldVal('connrate', r.connection_rate, false);
  4122. setNATFieldVal('pcc', r.pcc, false);
  4123. setNATFieldVal('srcmac', r.src_mac_address, true);
  4124. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4125. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4126. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4127. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4128. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4129. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4130. setNATFieldVal('priority', r.priority, false);
  4131. setNATFieldVal('dscp', r.dscp, false);
  4132. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4133. if (r.tos) {
  4134. const tosEl = document.getElementById('nat-val-tos');
  4135. if (tosEl) tosEl.value = r.tos;
  4136. }
  4137. setNATFieldVal('pktsize', r.packet_size, false);
  4138. setNATFieldVal('random', r.random, false);
  4139. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4140. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4141. setNATFieldVal('ttl', r.ttl, false);
  4142. // Extra tab fields
  4143. setNATFieldVal('time', r.time, false);
  4144. if (r.days) {
  4145. toggleNATField('days', true);
  4146. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4147. const chk = document.getElementById(`nat-day-${d}`);
  4148. if (chk) chk.checked = r.days.includes(d);
  4149. });
  4150. } else {
  4151. toggleNATField('days', false);
  4152. }
  4153. setNATFieldVal('limit', r.limit, false);
  4154. setNATFieldVal('dstlimit', r.dst_limit, false);
  4155. setNATFieldVal('psd', r.psd, false);
  4156. // Action fields
  4157. if (r.jump_target) {
  4158. const jtEl = document.getElementById('nat-modal-jumptarget');
  4159. if (jtEl) jtEl.value = r.jump_target;
  4160. }
  4161. if (r.address_list) {
  4162. const alEl = document.getElementById('nat-modal-action-addrlist');
  4163. if (alEl) alEl.value = r.address_list;
  4164. }
  4165. if (r.address_list_timeout) {
  4166. const toEl = document.getElementById('nat-modal-action-timeout');
  4167. if (toEl) toEl.value = r.address_list_timeout;
  4168. }
  4169. setNATFieldVal('logprefix', r.log_prefix, false);
  4170. // Statistics
  4171. const bEl = document.getElementById('nat-stat-bytes');
  4172. const pEl = document.getElementById('nat-stat-packets');
  4173. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4174. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4175. state.natLastBytes = r.bytes || 0;
  4176. state.natLastPackets = r.packets || 0;
  4177. state.natLastTimestamp = Date.now();
  4178. state.natStatRateHistory = new Array(30).fill(0);
  4179. state.natStatPktHistory = new Array(30).fill(0);
  4180. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4181. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4182. toggleNATActionFields();
  4183. document.getElementById('nat-modal').classList.remove('hidden');
  4184. }
  4185. function closeNATModal() {
  4186. stopNATStatPolling();
  4187. document.getElementById('nat-modal').classList.add('hidden');
  4188. }
  4189. function copyNATRule() {
  4190. document.getElementById('nat-modal-id').value = '';
  4191. const badge = document.getElementById('nat-modal-badge');
  4192. if (badge) badge.innerText = 'New...';
  4193. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4194. }
  4195. function resetCurrentNATRuleCounters() {
  4196. state.natStatRateHistory = new Array(30).fill(0);
  4197. state.natStatPktHistory = new Array(30).fill(0);
  4198. state.natLastBytes = 0;
  4199. state.natLastPackets = 0;
  4200. state.natLastTimestamp = Date.now();
  4201. const bEl = document.getElementById('nat-stat-bytes');
  4202. const pEl = document.getElementById('nat-stat-packets');
  4203. const rEl = document.getElementById('nat-stat-rate');
  4204. const prEl = document.getElementById('nat-stat-pktrate');
  4205. if (bEl) bEl.value = '0 B';
  4206. if (pEl) pEl.value = '0';
  4207. if (rEl) rEl.value = '0 bps';
  4208. if (prEl) prEl.value = '0 p/s';
  4209. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4210. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4211. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4212. }
  4213. async function applyNATRule(closeAfter = false) {
  4214. const id = document.getElementById('nat-modal-id').value;
  4215. const chain = document.getElementById('nat-modal-chain').value;
  4216. const action = document.getElementById('nat-modal-action').value;
  4217. const comment = document.getElementById('nat-modal-comment').value.trim();
  4218. const enabled = document.getElementById('nat-modal-enabled').checked;
  4219. const src = getNATFieldVal('src', true);
  4220. const dst = getNATFieldVal('dst', true);
  4221. const srclist = getNATFieldVal('srclist', true);
  4222. const dstlist = getNATFieldVal('dstlist', true);
  4223. const srcgeo = getNATFieldVal('srcgeo', true);
  4224. const dstgeo = getNATFieldVal('dstgeo', true);
  4225. const proto = getNATFieldVal('proto', true);
  4226. const sport = getNATFieldVal('sport', true);
  4227. const dport = getNATFieldVal('dport', true);
  4228. const anyport = getNATFieldVal('anyport', true);
  4229. const iniface = getNATFieldVal('iniface', true);
  4230. const outiface = getNATFieldVal('outiface', true);
  4231. const inifacelist = getNATFieldVal('inifacelist', true);
  4232. const outifacelist = getNATFieldVal('outifacelist', true);
  4233. const pktmark = getNATFieldVal('pktmark', true);
  4234. const connmark = getNATFieldVal('connmark', true);
  4235. const routingmark = getNATFieldVal('routingmark', true);
  4236. const conntype = getNATFieldVal('conntype', false);
  4237. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4238. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4239. const payload = {
  4240. id,
  4241. chain,
  4242. action,
  4243. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4244. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4245. protocol: proto || 'all',
  4246. src_address: src,
  4247. dst_address: dst,
  4248. src_port: sport,
  4249. dst_port: dport,
  4250. any_port: anyport,
  4251. in_interface: iniface,
  4252. out_interface: outiface,
  4253. in_interface_list: inifacelist,
  4254. out_interface_list: outifacelist,
  4255. packet_mark: pktmark,
  4256. connection_mark: connmark,
  4257. routing_mark: routingmark,
  4258. connection_type: conntype,
  4259. src_address_list: srclist,
  4260. dst_address_list: dstlist,
  4261. src_geoip: srcgeo,
  4262. dst_geoip: dstgeo,
  4263. comment,
  4264. disabled: !enabled,
  4265. // Advanced tab
  4266. layer7_protocol: getNATFieldVal('layer7', false),
  4267. content: getNATFieldVal('content', false),
  4268. connection_bytes: getNATFieldVal('connbytes', false),
  4269. connection_rate: getNATFieldVal('connrate', false),
  4270. pcc: getNATFieldVal('pcc', false),
  4271. src_mac_address: getNATFieldVal('srcmac', true),
  4272. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4273. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4274. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4275. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4276. ipsec_policy: getNATFieldVal('ipsec', false),
  4277. ingress_priority: getNATFieldVal('ingresspriority', false),
  4278. priority: getNATFieldVal('priority', false),
  4279. dscp: getNATFieldVal('dscp', false),
  4280. tcp_mss: getNATFieldVal('tcpmss', false),
  4281. tos: document.getElementById('nat-val-tos')?.value || '',
  4282. packet_size: getNATFieldVal('pktsize', false),
  4283. random: getNATFieldVal('random', false),
  4284. icmp_options: getNATFieldVal('icmpoptions', false),
  4285. ipv4_options: getNATFieldVal('ipv4options', false),
  4286. ttl: getNATFieldVal('ttl', false),
  4287. // Extra tab
  4288. time: getNATFieldVal('time', false),
  4289. limit: getNATFieldVal('limit', false),
  4290. dst_limit: getNATFieldVal('dstlimit', false),
  4291. psd: getNATFieldVal('psd', false),
  4292. // Action tab
  4293. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4294. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4295. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4296. log: document.getElementById('nat-modal-log')?.checked || false,
  4297. log_prefix: getNATFieldVal('logprefix', false)
  4298. };
  4299. try {
  4300. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4301. method: 'POST',
  4302. headers: { 'Content-Type': 'application/json' },
  4303. body: JSON.stringify(payload)
  4304. });
  4305. if (res.ok) {
  4306. const data = await res.json();
  4307. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4308. loadFirewall(false);
  4309. if (closeAfter) {
  4310. closeNATModal();
  4311. } else {
  4312. if (data.id) {
  4313. document.getElementById('nat-modal-id').value = data.id;
  4314. const badge = document.getElementById('nat-modal-badge');
  4315. if (badge) badge.innerText = `#${data.id}`;
  4316. }
  4317. }
  4318. } else {
  4319. const err = await res.json();
  4320. showToast('Error', err.message || 'Failed to save rule', 'error');
  4321. }
  4322. } catch (err) {
  4323. showToast('Error', err.message, 'error');
  4324. }
  4325. }
  4326. function submitSaveNATRule(e) {
  4327. if (e && e.preventDefault) e.preventDefault();
  4328. return applyNATRule(true);
  4329. }
  4330. function startNATStatPolling() {
  4331. stopNATStatPolling();
  4332. pollNATRuleStats();
  4333. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4334. }
  4335. function stopNATStatPolling() {
  4336. if (state.natStatInterval) {
  4337. clearInterval(state.natStatInterval);
  4338. state.natStatInterval = null;
  4339. }
  4340. }
  4341. async function pollNATRuleStats() {
  4342. const id = document.getElementById('nat-modal-id')?.value;
  4343. if (!id) {
  4344. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4345. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4346. return;
  4347. }
  4348. try {
  4349. const res = await fetch(`${API_BASE}/firewall/nat`);
  4350. if (!res.ok) return;
  4351. const rules = await res.json();
  4352. const r = rules.find(x => x.id === id);
  4353. if (!r) return;
  4354. const now = Date.now();
  4355. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4356. state.natLastTimestamp = now;
  4357. const curBytes = r.bytes || 0;
  4358. const curPackets = r.packets || 0;
  4359. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4360. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4361. state.natLastBytes = curBytes;
  4362. state.natLastPackets = curPackets;
  4363. const rateBps = Math.round((deltaBytes * 8) / dt);
  4364. const ratePkt = Math.round(deltaPkts / dt);
  4365. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4366. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4367. state.natStatRateHistory.push(rateBps);
  4368. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4369. state.natStatPktHistory.push(ratePkt);
  4370. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4371. const bEl = document.getElementById('nat-stat-bytes');
  4372. const pEl = document.getElementById('nat-stat-packets');
  4373. const rEl = document.getElementById('nat-stat-rate');
  4374. const prEl = document.getElementById('nat-stat-pktrate');
  4375. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4376. if (pEl) pEl.value = curPackets.toLocaleString();
  4377. if (rEl) rEl.value = formatBps(rateBps);
  4378. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4379. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4380. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4381. } catch (e) {
  4382. console.error('Error polling NAT rule stats', e);
  4383. }
  4384. }
  4385. async function moveNATRule(id, dir) {
  4386. try {
  4387. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4388. method: 'POST',
  4389. headers: { 'Content-Type': 'application/json' },
  4390. body: JSON.stringify({ direction: dir })
  4391. });
  4392. if (res.ok) loadFirewall(false);
  4393. } catch (err) {
  4394. showToast('Error', err.message, 'error');
  4395. }
  4396. }
  4397. async function toggleNATRuleState(id, disabled) {
  4398. try {
  4399. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4400. method: 'POST',
  4401. headers: { 'Content-Type': 'application/json' },
  4402. body: JSON.stringify({ disabled })
  4403. });
  4404. if (res.ok) loadFirewall(false);
  4405. } catch (err) {
  4406. showToast('Error', err.message, 'error');
  4407. }
  4408. }
  4409. async function deleteNATRule(id) {
  4410. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4411. try {
  4412. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4413. if (res.ok) {
  4414. showToast('Deleted', 'NAT rule removed', 'success');
  4415. loadFirewall(false);
  4416. }
  4417. } catch (err) {
  4418. showToast('Error', err.message, 'error');
  4419. }
  4420. }
  4421. // ----------------- Mangle Rules -----------------
  4422. function renderMangleRules() {
  4423. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4424. const tbody = document.getElementById('mangle-table-body');
  4425. const empty = document.getElementById('mangle-empty');
  4426. if (!tbody) return;
  4427. tbody.innerHTML = '';
  4428. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4429. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4430. if (rules.length === 0) {
  4431. empty?.classList.remove('hidden');
  4432. return;
  4433. }
  4434. empty?.classList.add('hidden');
  4435. rules.forEach((r, idx) => {
  4436. const tr = document.createElement('tr');
  4437. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4438. let markVal = '<span class="text-slate-500">-</span>';
  4439. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4440. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4441. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4442. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4443. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4444. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4445. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4446. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4447. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4448. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4449. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4450. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4451. tr.innerHTML = `
  4452. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4453. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4454. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4455. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4456. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4457. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4458. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4459. <td class="py-2.5 px-3 text-center">${r.passthrough ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  4460. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4461. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4462. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4463. </td>
  4464. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4465. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4466. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4467. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4468. <button onclick="toggleMangleRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4469. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4470. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4471. </td>
  4472. `;
  4473. tbody.appendChild(tr);
  4474. });
  4475. }
  4476. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4477. function switchMangleRuleTab(tab) {
  4478. state.activeMangleRuleTab = tab;
  4479. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4480. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4481. btn.classList.add('text-slate-400', 'border-transparent');
  4482. });
  4483. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4484. if (activeBtn) {
  4485. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4486. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4487. }
  4488. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4489. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4490. if (activePane) activePane.classList.remove('hidden');
  4491. if (tab === 'statistics') {
  4492. startMangleStatPolling();
  4493. } else {
  4494. stopMangleStatPolling();
  4495. }
  4496. }
  4497. function toggleMangleField(fieldKey, expand) {
  4498. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4499. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4500. if (!plusBtn || !fieldBox) return;
  4501. if (expand) {
  4502. plusBtn.classList.add('hidden');
  4503. fieldBox.classList.remove('hidden');
  4504. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4505. if (valInput) valInput.focus();
  4506. } else {
  4507. fieldBox.classList.add('hidden');
  4508. plusBtn.classList.remove('hidden');
  4509. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4510. if (valInput) {
  4511. if (valInput.tagName === 'SELECT') {
  4512. valInput.selectedIndex = 0;
  4513. } else {
  4514. valInput.value = '';
  4515. }
  4516. }
  4517. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4518. if (invInput) invInput.checked = false;
  4519. if (fieldKey === 'cs') {
  4520. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4521. const el = document.getElementById(id);
  4522. if (el) el.checked = false;
  4523. });
  4524. }
  4525. if (fieldKey === 'natstate') {
  4526. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4527. const el = document.getElementById(id);
  4528. if (el) el.checked = false;
  4529. });
  4530. }
  4531. }
  4532. }
  4533. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4534. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4535. toggleMangleField(fieldKey, true);
  4536. let strVal = String(value);
  4537. if (hasInvert) {
  4538. const inv = strVal.startsWith('!');
  4539. if (inv) strVal = strVal.slice(1);
  4540. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4541. if (invEl) invEl.checked = inv;
  4542. }
  4543. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4544. if (valEl) valEl.value = strVal;
  4545. } else {
  4546. toggleMangleField(fieldKey, false);
  4547. }
  4548. }
  4549. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4550. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4551. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4552. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4553. let v = valEl ? valEl.value.trim() : '';
  4554. if (!v) return '';
  4555. if (hasInvert) {
  4556. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4557. if (invEl && invEl.checked) {
  4558. v = '!' + v.replace(/^!/, '');
  4559. }
  4560. }
  4561. return v;
  4562. }
  4563. function toggleMaximizeMangleModal() {
  4564. const win = document.getElementById('mangle-modal-window');
  4565. if (!win) return;
  4566. if (win.classList.contains('max-w-[720px]')) {
  4567. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4568. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4569. } else {
  4570. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4571. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4572. }
  4573. }
  4574. function toggleMangleActionFields() {
  4575. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4576. // Hide all dynamic rows first
  4577. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4578. const el = document.getElementById(`mangle-row-${id}`);
  4579. if (el) el.classList.add('hidden');
  4580. });
  4581. const jumpBox = document.getElementById('mangle-action-jump-box');
  4582. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4583. if (jumpBox) jumpBox.classList.add('hidden');
  4584. if (addrBox) addrBox.classList.add('hidden');
  4585. // Activate matching rows
  4586. if (act === 'mark-connection') {
  4587. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4588. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4589. } else if (act === 'mark-routing') {
  4590. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4591. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4592. } else if (act === 'mark-packet') {
  4593. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4594. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4595. } else if (act === 'change-mss') {
  4596. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4597. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4598. } else if (act === 'change-dscp') {
  4599. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4600. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4601. } else if (act === 'change-ttl') {
  4602. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4603. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4604. } else if (act === 'set-priority') {
  4605. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4606. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4607. } else if (act === 'route') {
  4608. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4609. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4610. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4611. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4612. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4613. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4614. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4615. } else if (act === 'jump') {
  4616. if (jumpBox) jumpBox.classList.remove('hidden');
  4617. } else if (act.includes('address-list') || act.includes('address list')) {
  4618. if (addrBox) addrBox.classList.remove('hidden');
  4619. }
  4620. if (act === 'log') {
  4621. const logEl = document.getElementById('mangle-modal-log');
  4622. if (logEl) logEl.checked = true;
  4623. toggleMangleField('logprefix', true);
  4624. }
  4625. }
  4626. function toggleMangleLogPrefix() {
  4627. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4628. toggleMangleField('logprefix', !!isLog);
  4629. }
  4630. const allMangleFieldKeys = [
  4631. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4632. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4633. 'routingmark', 'conntype', 'cs', 'natstate',
  4634. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4635. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4636. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4637. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4638. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4639. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4640. ];
  4641. function openAddMangleModal() {
  4642. switchMangleRuleTab('general');
  4643. const badge = document.getElementById('mangle-modal-badge');
  4644. if (badge) badge.innerText = 'New...';
  4645. document.getElementById('mangle-modal-id').value = '';
  4646. document.getElementById('mangle-modal-enabled').checked = true;
  4647. document.getElementById('mangle-modal-comment').value = '';
  4648. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4649. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4650. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4651. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4652. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4653. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4654. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4655. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4656. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4657. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4658. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4659. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4660. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4661. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4662. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4663. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4664. populateInterfaceSelect('mangle-val-iniface');
  4665. populateInterfaceSelect('mangle-val-outiface');
  4666. populateAddressListSelect('mangle-val-srclist');
  4667. populateAddressListSelect('mangle-val-dstlist');
  4668. populateGeoIPSelect('mangle-val-srcgeo');
  4669. populateGeoIPSelect('mangle-val-dstgeo');
  4670. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4671. resetCurrentMangleRuleCounters();
  4672. toggleMangleActionFields();
  4673. document.getElementById('mangle-modal').classList.remove('hidden');
  4674. }
  4675. function openEditMangleModal(id) {
  4676. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4677. if (!r) return;
  4678. switchMangleRuleTab('general');
  4679. const badge = document.getElementById('mangle-modal-badge');
  4680. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4681. document.getElementById('mangle-modal-id').value = r.id;
  4682. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4683. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4684. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4685. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4686. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4687. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4688. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4689. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4690. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4691. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4692. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4693. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4694. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4695. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4696. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4697. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4698. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4699. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4700. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4701. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4702. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4703. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4704. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4705. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4706. setMangleFieldVal('src', r.src_address, true);
  4707. setMangleFieldVal('dst', r.dst_address, true);
  4708. setMangleFieldVal('srclist', r.src_address_list, true);
  4709. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4710. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4711. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4712. if (r.protocol && r.protocol !== 'all') {
  4713. setMangleFieldVal('proto', r.protocol, true);
  4714. } else {
  4715. toggleMangleField('proto', false);
  4716. }
  4717. setMangleFieldVal('sport', r.src_port, true);
  4718. setMangleFieldVal('dport', r.dst_port, true);
  4719. setMangleFieldVal('anyport', r.any_port, true);
  4720. setMangleFieldVal('iniface', r.in_interface, true);
  4721. setMangleFieldVal('outiface', r.out_interface, true);
  4722. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4723. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4724. setMangleFieldVal('pktmark', r.packet_mark, true);
  4725. setMangleFieldVal('connmark', r.connection_mark, true);
  4726. setMangleFieldVal('routingmark', r.routing_mark, true);
  4727. setMangleFieldVal('conntype', r.connection_type, false);
  4728. // Connection State
  4729. const states = r.connection_state || [];
  4730. if (states.length > 0) {
  4731. toggleMangleField('cs', true);
  4732. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4733. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4734. if (el) el.checked = states.includes(s);
  4735. });
  4736. } else {
  4737. toggleMangleField('cs', false);
  4738. }
  4739. // Connection NAT State
  4740. const natStates = r.connection_nat_state || [];
  4741. if (natStates.length > 0) {
  4742. toggleMangleField('natstate', true);
  4743. ['srcnat', 'dstnat'].forEach(s => {
  4744. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4745. if (el) el.checked = natStates.includes(s);
  4746. });
  4747. } else {
  4748. toggleMangleField('natstate', false);
  4749. }
  4750. // Advanced tab fields
  4751. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4752. setMangleFieldVal('content', r.content, false);
  4753. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4754. setMangleFieldVal('connrate', r.connection_rate, false);
  4755. setMangleFieldVal('pcc', r.pcc, false);
  4756. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4757. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4758. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4759. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4760. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4761. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4762. setMangleFieldVal('tlshost', r.tls_host, false);
  4763. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4764. setMangleFieldVal('priority', r.priority, false);
  4765. setMangleFieldVal('dscp', r.dscp, false);
  4766. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4767. if (r.tos) {
  4768. const tosEl = document.getElementById('mangle-val-tos');
  4769. if (tosEl) tosEl.value = r.tos;
  4770. }
  4771. setMangleFieldVal('pktsize', r.packet_size, false);
  4772. setMangleFieldVal('random', r.random, false);
  4773. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4774. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4775. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4776. setMangleFieldVal('ttl', r.ttl, false);
  4777. // Extra tab fields
  4778. setMangleFieldVal('nth', r.nth, false);
  4779. setMangleFieldVal('connlimit', r.connection_limit, false);
  4780. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4781. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4782. setMangleFieldVal('hotspot', r.hotspot, false);
  4783. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4784. setMangleFieldVal('limit', r.limit, false);
  4785. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4786. setMangleFieldVal('time', r.time, false);
  4787. setMangleFieldVal('psd', r.psd, false);
  4788. // Action fields
  4789. if (r.jump_target) {
  4790. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4791. if (jtEl) jtEl.value = r.jump_target;
  4792. }
  4793. if (r.address_list) {
  4794. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4795. if (alEl) alEl.value = r.address_list;
  4796. }
  4797. if (r.address_list_timeout) {
  4798. const toEl = document.getElementById('mangle-modal-action-timeout');
  4799. if (toEl) toEl.value = r.address_list_timeout;
  4800. }
  4801. setMangleFieldVal('logprefix', r.log_prefix, false);
  4802. // Statistics
  4803. const bEl = document.getElementById('mangle-stat-bytes');
  4804. const pEl = document.getElementById('mangle-stat-packets');
  4805. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4806. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4807. state.mangleLastBytes = r.bytes || 0;
  4808. state.mangleLastPackets = r.packets || 0;
  4809. state.mangleLastTimestamp = Date.now();
  4810. state.mangleStatRateHistory = new Array(30).fill(0);
  4811. state.mangleStatPktHistory = new Array(30).fill(0);
  4812. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4813. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4814. toggleMangleActionFields();
  4815. document.getElementById('mangle-modal').classList.remove('hidden');
  4816. }
  4817. function closeMangleModal() {
  4818. stopMangleStatPolling();
  4819. document.getElementById('mangle-modal').classList.add('hidden');
  4820. }
  4821. function copyMangleRule() {
  4822. document.getElementById('mangle-modal-id').value = '';
  4823. const badge = document.getElementById('mangle-modal-badge');
  4824. if (badge) badge.innerText = 'New...';
  4825. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4826. }
  4827. function resetCurrentMangleRuleCounters() {
  4828. state.mangleStatRateHistory = new Array(30).fill(0);
  4829. state.mangleStatPktHistory = new Array(30).fill(0);
  4830. state.mangleLastBytes = 0;
  4831. state.mangleLastPackets = 0;
  4832. state.mangleLastTimestamp = Date.now();
  4833. const bEl = document.getElementById('mangle-stat-bytes');
  4834. const pEl = document.getElementById('mangle-stat-packets');
  4835. const rEl = document.getElementById('mangle-stat-rate');
  4836. const prEl = document.getElementById('mangle-stat-pktrate');
  4837. if (bEl) bEl.value = '0 B';
  4838. if (pEl) pEl.value = '0';
  4839. if (rEl) rEl.value = '0 bps';
  4840. if (prEl) prEl.value = '0 p/s';
  4841. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4842. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4843. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4844. }
  4845. async function applyMangleRule(closeAfter = false) {
  4846. const id = document.getElementById('mangle-modal-id').value;
  4847. const chain = document.getElementById('mangle-modal-chain').value;
  4848. const action = document.getElementById('mangle-modal-action').value;
  4849. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4850. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4851. const src = getMangleFieldVal('src', true);
  4852. const dst = getMangleFieldVal('dst', true);
  4853. const srclist = getMangleFieldVal('srclist', true);
  4854. const dstlist = getMangleFieldVal('dstlist', true);
  4855. const srcgeo = getMangleFieldVal('srcgeo', true);
  4856. const dstgeo = getMangleFieldVal('dstgeo', true);
  4857. const proto = getMangleFieldVal('proto', true);
  4858. const sport = getMangleFieldVal('sport', true);
  4859. const dport = getMangleFieldVal('dport', true);
  4860. const anyport = getMangleFieldVal('anyport', true);
  4861. const iniface = getMangleFieldVal('iniface', true);
  4862. const outiface = getMangleFieldVal('outiface', true);
  4863. const inifacelist = getMangleFieldVal('inifacelist', true);
  4864. const outifacelist = getMangleFieldVal('outifacelist', true);
  4865. const pktmark = getMangleFieldVal('pktmark', true);
  4866. const connmark = getMangleFieldVal('connmark', true);
  4867. const routingmark = getMangleFieldVal('routingmark', true);
  4868. const conntype = getMangleFieldVal('conntype', false);
  4869. const states = [];
  4870. const csBox = document.getElementById('mangle-field-cs');
  4871. if (csBox && !csBox.classList.contains('hidden')) {
  4872. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4873. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4874. });
  4875. }
  4876. const natStates = [];
  4877. const natBox = document.getElementById('mangle-field-natstate');
  4878. if (natBox && !natBox.classList.contains('hidden')) {
  4879. ['srcnat', 'dstnat'].forEach(s => {
  4880. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4881. });
  4882. }
  4883. const payload = {
  4884. id,
  4885. chain,
  4886. action,
  4887. protocol: proto || 'all',
  4888. src_address: src,
  4889. dst_address: dst,
  4890. src_port: sport,
  4891. dst_port: dport,
  4892. any_port: anyport,
  4893. in_interface: iniface,
  4894. out_interface: outiface,
  4895. in_interface_list: inifacelist,
  4896. out_interface_list: outifacelist,
  4897. packet_mark: pktmark,
  4898. connection_mark: connmark,
  4899. routing_mark: routingmark,
  4900. connection_type: conntype,
  4901. connection_state: states,
  4902. connection_nat_state: natStates,
  4903. src_address_list: srclist,
  4904. dst_address_list: dstlist,
  4905. src_geoip: srcgeo,
  4906. dst_geoip: dstgeo,
  4907. comment,
  4908. disabled: !enabled,
  4909. // Advanced tab
  4910. layer7_protocol: getMangleFieldVal('layer7', false),
  4911. content: getMangleFieldVal('content', false),
  4912. connection_bytes: getMangleFieldVal('connbytes', false),
  4913. connection_rate: getMangleFieldVal('connrate', false),
  4914. pcc: getMangleFieldVal('pcc', false),
  4915. src_mac_address: getMangleFieldVal('srcmac', true),
  4916. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4917. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4918. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4919. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4920. ipsec_policy: getMangleFieldVal('ipsec', false),
  4921. tls_host: getMangleFieldVal('tlshost', false),
  4922. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4923. priority: getMangleFieldVal('priority', false),
  4924. dscp: getMangleFieldVal('dscp', false),
  4925. tcp_mss: getMangleFieldVal('tcpmss', false),
  4926. tos: document.getElementById('mangle-val-tos')?.value || '',
  4927. packet_size: getMangleFieldVal('pktsize', false),
  4928. random: getMangleFieldVal('random', false),
  4929. tcp_flags: getMangleFieldVal('tcpflags', false),
  4930. icmp_options: getMangleFieldVal('icmpoptions', false),
  4931. ipv4_options: getMangleFieldVal('ipv4options', false),
  4932. ttl: getMangleFieldVal('ttl', false),
  4933. // Extra tab
  4934. nth: getMangleFieldVal('nth', false),
  4935. connection_limit: getMangleFieldVal('connlimit', false),
  4936. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4937. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4938. hotspot: getMangleFieldVal('hotspot', false),
  4939. ip_fragment: getMangleFieldVal('ipfragment', false),
  4940. limit: getMangleFieldVal('limit', false),
  4941. dst_limit: getMangleFieldVal('dstlimit', false),
  4942. time: getMangleFieldVal('time', false),
  4943. psd: getMangleFieldVal('psd', false),
  4944. // Action tab
  4945. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4946. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4947. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4948. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4949. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4950. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4951. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4952. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4953. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4954. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4955. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4956. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4957. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4958. log: document.getElementById('mangle-modal-log')?.checked || false,
  4959. log_prefix: getMangleFieldVal('logprefix', false)
  4960. };
  4961. try {
  4962. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4963. method: 'POST',
  4964. headers: { 'Content-Type': 'application/json' },
  4965. body: JSON.stringify(payload)
  4966. });
  4967. if (res.ok) {
  4968. const data = await res.json();
  4969. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4970. loadFirewall(false);
  4971. if (closeAfter) {
  4972. closeMangleModal();
  4973. } else {
  4974. if (data.id) {
  4975. document.getElementById('mangle-modal-id').value = data.id;
  4976. const badge = document.getElementById('mangle-modal-badge');
  4977. if (badge) badge.innerText = `#${data.id}`;
  4978. }
  4979. }
  4980. } else {
  4981. const err = await res.json();
  4982. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4983. }
  4984. } catch (err) {
  4985. showToast('Error', err.message, 'error');
  4986. }
  4987. }
  4988. function submitSaveMangleRule(e) {
  4989. if (e && e.preventDefault) e.preventDefault();
  4990. return applyMangleRule(true);
  4991. }
  4992. function startMangleStatPolling() {
  4993. stopMangleStatPolling();
  4994. pollMangleRuleStats();
  4995. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4996. }
  4997. function stopMangleStatPolling() {
  4998. if (state.mangleStatInterval) {
  4999. clearInterval(state.mangleStatInterval);
  5000. state.mangleStatInterval = null;
  5001. }
  5002. }
  5003. async function pollMangleRuleStats() {
  5004. const id = document.getElementById('mangle-modal-id')?.value;
  5005. if (!id) {
  5006. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5007. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5008. return;
  5009. }
  5010. try {
  5011. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5012. if (!res.ok) return;
  5013. const rules = await res.json();
  5014. const r = rules.find(x => x.id === id);
  5015. if (!r) return;
  5016. const now = Date.now();
  5017. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5018. state.mangleLastTimestamp = now;
  5019. const curBytes = r.bytes || 0;
  5020. const curPackets = r.packets || 0;
  5021. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5022. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5023. state.mangleLastBytes = curBytes;
  5024. state.mangleLastPackets = curPackets;
  5025. const rateBps = Math.round((deltaBytes * 8) / dt);
  5026. const ratePkt = Math.round(deltaPkts / dt);
  5027. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5028. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5029. state.mangleStatRateHistory.push(rateBps);
  5030. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5031. state.mangleStatPktHistory.push(ratePkt);
  5032. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5033. const bEl = document.getElementById('mangle-stat-bytes');
  5034. const pEl = document.getElementById('mangle-stat-packets');
  5035. const rEl = document.getElementById('mangle-stat-rate');
  5036. const prEl = document.getElementById('mangle-stat-pktrate');
  5037. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5038. if (pEl) pEl.value = curPackets.toLocaleString();
  5039. if (rEl) rEl.value = formatBps(rateBps);
  5040. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5041. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5042. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5043. } catch (e) {
  5044. console.error('Error polling Mangle rule stats', e);
  5045. }
  5046. }
  5047. async function moveMangleRule(id, dir) {
  5048. try {
  5049. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5050. method: 'POST',
  5051. headers: { 'Content-Type': 'application/json' },
  5052. body: JSON.stringify({ direction: dir })
  5053. });
  5054. if (res.ok) loadFirewall(false);
  5055. } catch (err) {
  5056. showToast('Error', err.message, 'error');
  5057. }
  5058. }
  5059. async function toggleMangleRuleState(id, disabled) {
  5060. try {
  5061. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5062. method: 'POST',
  5063. headers: { 'Content-Type': 'application/json' },
  5064. body: JSON.stringify({ disabled })
  5065. });
  5066. if (res.ok) loadFirewall(false);
  5067. } catch (err) {
  5068. showToast('Error', err.message, 'error');
  5069. }
  5070. }
  5071. async function deleteMangleRule(id) {
  5072. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5073. try {
  5074. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5075. if (res.ok) {
  5076. showToast('Deleted', 'Mangle rule removed', 'success');
  5077. loadFirewall(false);
  5078. }
  5079. } catch (err) {
  5080. showToast('Error', err.message, 'error');
  5081. }
  5082. }
  5083. // ----------------- Address Lists -----------------
  5084. function renderAddressLists() {
  5085. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5086. const tbody = document.getElementById('addrlist-table-body');
  5087. const empty = document.getElementById('addrlist-empty');
  5088. if (!tbody) return;
  5089. tbody.innerHTML = '';
  5090. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5091. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5092. // Update filter select
  5093. const sel = document.getElementById('addrlist-filter-name');
  5094. if (sel) {
  5095. const cur = sel.value;
  5096. sel.innerHTML = '<option value="">All Lists</option>';
  5097. const set = new Set((state.addressLists || []).map(a => a.name));
  5098. set.forEach(n => {
  5099. const opt = document.createElement('option');
  5100. opt.value = n;
  5101. opt.innerText = n;
  5102. if (n === cur) opt.selected = true;
  5103. sel.appendChild(opt);
  5104. });
  5105. }
  5106. if (entries.length === 0) {
  5107. empty?.classList.remove('hidden');
  5108. return;
  5109. }
  5110. empty?.classList.add('hidden');
  5111. entries.forEach((e, idx) => {
  5112. const tr = document.createElement('tr');
  5113. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5114. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5115. tr.innerHTML = `
  5116. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5117. <td class="py-2.5 px-3 text-center">${e.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400 font-bold">✓</span>'}</td>
  5118. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5119. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5120. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5121. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5122. <button onclick="toggleAddrListState('${e.id}', ${!e.disabled})" class="text-xs ${e.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${e.disabled ? 'Enable' : 'Disable'}</button>
  5123. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5124. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5125. </td>
  5126. `;
  5127. tbody.appendChild(tr);
  5128. });
  5129. populateCommonAddrListDatalist();
  5130. }
  5131. function openAddAddrListModal() {
  5132. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5133. document.getElementById('addrlist-modal-id').value = '';
  5134. document.getElementById('addrlist-modal-name').value = '';
  5135. document.getElementById('addrlist-modal-addr').value = '';
  5136. document.getElementById('addrlist-modal-comment').value = '';
  5137. document.getElementById('addrlist-modal-disabled').checked = false;
  5138. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5139. if (submitBtn) submitBtn.innerText = 'Add to List';
  5140. document.getElementById('addrlist-modal').classList.remove('hidden');
  5141. }
  5142. function openEditAddrListModal(id) {
  5143. const e = (state.addressLists || []).find(item => item.id === id);
  5144. if (!e) return;
  5145. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5146. document.getElementById('addrlist-modal-id').value = e.id;
  5147. document.getElementById('addrlist-modal-name').value = e.name;
  5148. document.getElementById('addrlist-modal-addr').value = e.address;
  5149. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5150. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5151. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5152. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5153. document.getElementById('addrlist-modal').classList.remove('hidden');
  5154. }
  5155. function closeAddrListModal() {
  5156. document.getElementById('addrlist-modal').classList.add('hidden');
  5157. }
  5158. async function submitSaveAddrList(e) {
  5159. e.preventDefault();
  5160. const id = document.getElementById('addrlist-modal-id').value;
  5161. const name = document.getElementById('addrlist-modal-name').value.trim();
  5162. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5163. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5164. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5165. try {
  5166. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5167. method: 'POST',
  5168. headers: { 'Content-Type': 'application/json' },
  5169. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5170. });
  5171. if (res.ok) {
  5172. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5173. closeAddrListModal();
  5174. loadFirewall(false);
  5175. } else {
  5176. const err = await res.json();
  5177. showToast('Error', err.message || 'Failed to save address list', 'error');
  5178. }
  5179. } catch (err) {
  5180. showToast('Error', err.message, 'error');
  5181. }
  5182. }
  5183. async function toggleAddrListState(id, disabled) {
  5184. try {
  5185. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5186. method: 'POST',
  5187. headers: { 'Content-Type': 'application/json' },
  5188. body: JSON.stringify({ disabled })
  5189. });
  5190. if (res.ok) {
  5191. loadFirewall(false);
  5192. }
  5193. } catch (err) {
  5194. showToast('Error', err.message, 'error');
  5195. }
  5196. }
  5197. async function deleteAddrList(id) {
  5198. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5199. try {
  5200. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5201. if (res.ok) {
  5202. showToast('Deleted', 'Address list item removed', 'info');
  5203. loadFirewall(false);
  5204. }
  5205. } catch (err) {
  5206. showToast('Error', err.message, 'error');
  5207. }
  5208. }
  5209. // ----------------- Geo-Location IP Management -----------------
  5210. async function loadGeoIP() {
  5211. try {
  5212. const [statusRes, countriesRes] = await Promise.all([
  5213. fetch(`${API_BASE}/firewall/geoip/status`),
  5214. fetch(`${API_BASE}/firewall/geoip/countries`)
  5215. ]);
  5216. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5217. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5218. updateGeoHeader();
  5219. renderGeoCountries();
  5220. } catch (err) {
  5221. console.error('Failed to load GeoIP:', err);
  5222. }
  5223. }
  5224. function getGeoUsageMap() {
  5225. const usage = {};
  5226. const checkRule = (r, type) => {
  5227. ['src_geoip', 'dst_geoip'].forEach(field => {
  5228. let val = (r && r[field]) || '';
  5229. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5230. if (code) {
  5231. if (!usage[code]) usage[code] = [];
  5232. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5233. if (!usage[code].includes(label)) usage[code].push(label);
  5234. }
  5235. });
  5236. };
  5237. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5238. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5239. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5240. return usage;
  5241. }
  5242. function updateGeoHeader() {
  5243. const s = state.geoStatus || {};
  5244. const statusBadge = document.getElementById('geo-status-badge');
  5245. if (statusBadge) {
  5246. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5247. statusBadge.className = s.auto_update
  5248. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5249. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5250. }
  5251. const intervalLabel = document.getElementById('geo-interval-label');
  5252. if (intervalLabel) {
  5253. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5254. }
  5255. const usageMap = getGeoUsageMap();
  5256. const inUseCount = Object.keys(usageMap).length;
  5257. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5258. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5259. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5260. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5261. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5262. if (lastSyncEl) {
  5263. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5264. const d = new Date(s.last_updated);
  5265. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5266. } else {
  5267. lastSyncEl.innerText = 'Never (Sync Pending)';
  5268. }
  5269. }
  5270. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5271. if (nextSyncEl) {
  5272. if (s.next_update && !s.next_update.startsWith('0001')) {
  5273. const d = new Date(s.next_update);
  5274. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5275. } else {
  5276. nextSyncEl.innerText = '-';
  5277. }
  5278. }
  5279. const badge = document.getElementById('fw-badge-geo');
  5280. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5281. }
  5282. function renderGeoCountries() {
  5283. const tbody = document.getElementById('geo-table-body');
  5284. const empty = document.getElementById('geo-empty');
  5285. if (!tbody) return;
  5286. tbody.innerHTML = '';
  5287. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5288. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5289. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5290. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5291. const usageMap = getGeoUsageMap();
  5292. const countries = (state.geoCountries || []).filter(c => {
  5293. const isUsed = !!usageMap[c.code];
  5294. if (inUseOnly && !isUsed) return false;
  5295. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5296. if (continent && c.continent !== continent) return false;
  5297. if (q) {
  5298. const matchCode = c.code.toLowerCase().includes(q);
  5299. const matchName = c.name.toLowerCase().includes(q);
  5300. if (!matchCode && !matchName) return false;
  5301. }
  5302. return true;
  5303. });
  5304. if (countries.length === 0) {
  5305. empty?.classList.remove('hidden');
  5306. return;
  5307. }
  5308. empty?.classList.add('hidden');
  5309. countries.forEach(c => {
  5310. const tr = document.createElement('tr');
  5311. const isUsed = !!usageMap[c.code];
  5312. const rulesUsing = usageMap[c.code] || [];
  5313. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5314. let statusHtml = '';
  5315. if (isUsed) {
  5316. statusHtml = `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40" title="Assigned in: ${rulesUsing.join(', ')}">IN USE (${rulesUsing.length})</span>`;
  5317. } else if (c.subnet_count > 0) {
  5318. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-cyan-300 bg-cyan-950/40 border border-cyan-800/40">CACHED</span>';
  5319. } else {
  5320. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5321. }
  5322. tr.innerHTML = `
  5323. <td class="py-2.5 px-3 text-center">
  5324. <span class="px-2 py-0.5 rounded font-mono font-bold ${isUsed ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  5325. ${c.code}
  5326. </span>
  5327. </td>
  5328. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5329. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5330. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5331. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5332. </td>
  5333. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5334. <td class="py-2.5 px-3">
  5335. ${statusHtml}
  5336. </td>
  5337. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5338. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium" title="Re-download latest country IP blocks">Sync</button>
  5339. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5340. </td>
  5341. `;
  5342. tbody.appendChild(tr);
  5343. });
  5344. }
  5345. function quickFilterGeo(preset) {
  5346. const searchInput = document.getElementById('geo-search-input');
  5347. const continentSel = document.getElementById('geo-continent-filter');
  5348. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5349. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5350. if (searchInput) searchInput.value = '';
  5351. if (continentSel) continentSel.value = '';
  5352. if (inUseCheck) inUseCheck.checked = false;
  5353. if (cachedCheck) cachedCheck.checked = false;
  5354. if (preset === 'GR') {
  5355. if (searchInput) searchInput.value = 'Greece';
  5356. } else if (preset === 'Europe') {
  5357. if (continentSel) continentSel.value = 'Europe';
  5358. } else if (preset === 'HIGHRISK') {
  5359. if (searchInput) searchInput.value = 'China';
  5360. }
  5361. renderGeoCountries();
  5362. }
  5363. async function toggleGeoCountry(code, enabled) {
  5364. try {
  5365. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5366. method: 'POST',
  5367. headers: { 'Content-Type': 'application/json' },
  5368. body: JSON.stringify({ enabled })
  5369. });
  5370. if (res.ok) {
  5371. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5372. loadGeoIP();
  5373. } else {
  5374. const err = await res.json();
  5375. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5376. }
  5377. } catch (err) {
  5378. showToast('Error', err.message, 'error');
  5379. }
  5380. }
  5381. async function updateGeoCountry(code) {
  5382. try {
  5383. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5384. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5385. if (res.ok) {
  5386. const data = await res.json();
  5387. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5388. loadGeoIP();
  5389. } else {
  5390. const err = await res.json();
  5391. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5392. }
  5393. } catch (err) {
  5394. showToast('Error', err.message, 'error');
  5395. }
  5396. }
  5397. async function triggerGeoUpdateNow() {
  5398. const spinner = document.getElementById('geo-update-spinner');
  5399. if (spinner) spinner.classList.remove('hidden');
  5400. try {
  5401. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5402. if (res.ok) {
  5403. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5404. setTimeout(() => {
  5405. loadGeoIP();
  5406. if (spinner) spinner.classList.add('hidden');
  5407. }, 2500);
  5408. } else {
  5409. const err = await res.json();
  5410. showToast('Notice', err.message || 'Update in progress', 'info');
  5411. if (spinner) spinner.classList.add('hidden');
  5412. }
  5413. } catch (err) {
  5414. showToast('Error', err.message, 'error');
  5415. if (spinner) spinner.classList.add('hidden');
  5416. }
  5417. }
  5418. async function applyGeoPreset(preset) {
  5419. try {
  5420. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5421. method: 'POST',
  5422. headers: { 'Content-Type': 'application/json' },
  5423. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5424. });
  5425. if (res.ok) {
  5426. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5427. loadGeoIP();
  5428. }
  5429. } catch (err) {
  5430. showToast('Error', err.message, 'error');
  5431. }
  5432. }
  5433. function openGeoIntervalModal() {
  5434. const s = state.geoStatus || {};
  5435. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5436. const sel = document.getElementById('geo-cfg-interval');
  5437. const customBox = document.getElementById('geo-cfg-custom-box');
  5438. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5439. const curHours = s.interval_hours || 24;
  5440. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5441. if (matchOption) {
  5442. sel.value = String(curHours);
  5443. customBox.classList.add('hidden');
  5444. } else {
  5445. sel.value = 'custom';
  5446. customHoursInput.value = curHours;
  5447. customBox.classList.remove('hidden');
  5448. }
  5449. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5450. }
  5451. function closeGeoIntervalModal() {
  5452. document.getElementById('geo-interval-modal').classList.add('hidden');
  5453. }
  5454. function toggleCustomGeoInterval() {
  5455. const val = document.getElementById('geo-cfg-interval').value;
  5456. const customBox = document.getElementById('geo-cfg-custom-box');
  5457. if (val === 'custom') {
  5458. customBox.classList.remove('hidden');
  5459. } else {
  5460. customBox.classList.add('hidden');
  5461. }
  5462. }
  5463. async function submitGeoIntervalSettings(e) {
  5464. e.preventDefault();
  5465. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5466. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5467. let hours = 24;
  5468. if (intervalVal === 'custom') {
  5469. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5470. } else {
  5471. hours = parseInt(intervalVal, 10) || 24;
  5472. }
  5473. try {
  5474. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5475. method: 'POST',
  5476. headers: { 'Content-Type': 'application/json' },
  5477. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5478. });
  5479. if (res.ok) {
  5480. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5481. closeGeoIntervalModal();
  5482. loadGeoIP();
  5483. } else {
  5484. const err = await res.json();
  5485. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5486. }
  5487. } catch (err) {
  5488. showToast('Error', err.message, 'error');
  5489. }
  5490. }
  5491. async function viewGeoSubnets(code, name) {
  5492. if (!name) {
  5493. const found = (state.geoCountries || []).find(x => x.code === code);
  5494. name = found ? found.name : code;
  5495. }
  5496. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5497. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5498. const listEl = document.getElementById('geo-subnets-list');
  5499. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5500. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5501. try {
  5502. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5503. if (res.ok) {
  5504. const data = await res.json();
  5505. const subnets = data.subnets || [];
  5506. if (subnets.length === 0) {
  5507. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5508. } else {
  5509. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5510. }
  5511. } else {
  5512. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5513. }
  5514. } catch (err) {
  5515. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5516. }
  5517. }
  5518. function closeGeoSubnetsModal() {
  5519. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5520. }
  5521. // ----------------- Active Connections Tracking -----------------
  5522. async function loadConnections() {
  5523. try {
  5524. const res = await fetch(`${API_BASE}/firewall/connections`);
  5525. const data = await res.json();
  5526. state.connections = Array.isArray(data) ? data : [];
  5527. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5528. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5529. renderConnections();
  5530. } catch (err) {
  5531. console.error('Failed to load connections:', err);
  5532. }
  5533. }
  5534. function renderConnections() {
  5535. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5536. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5537. const tbody = document.getElementById('conns-table-body');
  5538. const empty = document.getElementById('conns-empty');
  5539. if (!tbody) return;
  5540. tbody.innerHTML = '';
  5541. const conns = (state.connections || []).filter(c => {
  5542. if (protoFilter && c.protocol !== protoFilter) return false;
  5543. if (search) {
  5544. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5545. if (!line.includes(search)) return false;
  5546. }
  5547. return true;
  5548. });
  5549. if (conns.length === 0) {
  5550. empty?.classList.remove('hidden');
  5551. return;
  5552. }
  5553. empty?.classList.add('hidden');
  5554. conns.slice(0, 150).forEach(c => {
  5555. const tr = document.createElement('tr');
  5556. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5557. let stateColor = 'text-slate-400';
  5558. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5559. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5560. tr.innerHTML = `
  5561. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5562. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5563. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5564. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_src_address ? c.reply_src_address + ':' + c.reply_src_port : '-'}</td>
  5565. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_dst_address ? c.reply_dst_address + ':' + c.reply_dst_port : '-'}</td>
  5566. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5567. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5568. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5569. <td class="py-2.5 px-3 text-right font-sans">
  5570. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  5571. </td>
  5572. `;
  5573. tbody.appendChild(tr);
  5574. });
  5575. }
  5576. async function killConnection(protocol, src, sport, dst, dport) {
  5577. try {
  5578. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5579. method: 'POST',
  5580. headers: { 'Content-Type': 'application/json' },
  5581. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5582. });
  5583. if (res.ok) {
  5584. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5585. loadConnections();
  5586. }
  5587. } catch (err) {
  5588. showToast('Error', err.message, 'error');
  5589. }
  5590. }
  5591. async function resetFirewallCounters() {
  5592. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5593. try {
  5594. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5595. if (res.ok) {
  5596. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5597. loadFirewall(false);
  5598. }
  5599. } catch (err) {
  5600. showToast('Error', err.message, 'error');
  5601. }
  5602. }
  5603. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5604. function switchRoutesSubTab(tab) {
  5605. state.routesSubTab = tab;
  5606. const tabs = ['routes', 'rules', 'tables'];
  5607. tabs.forEach(t => {
  5608. const panel = document.getElementById(`routes-subtab-${t}`);
  5609. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5610. if (panel) {
  5611. if (t === tab) panel.classList.remove('hidden');
  5612. else panel.classList.add('hidden');
  5613. }
  5614. if (btn) {
  5615. if (t === tab) {
  5616. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-cyan-500 text-white transition flex items-center gap-2';
  5617. } else {
  5618. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  5619. }
  5620. }
  5621. });
  5622. setTimeout(initTableSorting, 50);
  5623. }
  5624. async function loadRoutes() {
  5625. try {
  5626. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5627. fetch(`${API_BASE}/routes`),
  5628. fetch(`${API_BASE}/routing/rules`),
  5629. fetch(`${API_BASE}/routing/tables`)
  5630. ]);
  5631. if (routesRes.ok) state.routes = await routesRes.json();
  5632. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5633. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5634. const bRoutes = document.getElementById('routes-badge-routes');
  5635. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5636. const showSystem = document.getElementById('prule-show-system')?.checked;
  5637. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5638. const bRules = document.getElementById('routes-badge-rules');
  5639. if (bRules) bRules.innerText = userRules.length;
  5640. const bTables = document.getElementById('routes-badge-tables');
  5641. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5642. const bRoutesCount = document.getElementById('badge-routes-count');
  5643. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5644. renderRoutesList();
  5645. renderPolicyRules();
  5646. renderRoutingTables();
  5647. } catch (err) {
  5648. console.error('Failed to load routing:', err);
  5649. }
  5650. }
  5651. function getRouteProtocolBadge(proto) {
  5652. const p = (proto || 'static').toLowerCase();
  5653. switch (p) {
  5654. case 'bgp':
  5655. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
  5656. case 'ibgp':
  5657. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
  5658. case 'ospf':
  5659. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
  5660. case 'rip':
  5661. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
  5662. case 'static':
  5663. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
  5664. case 'connected':
  5665. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
  5666. case 'dhcp':
  5667. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
  5668. case 'multicast':
  5669. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
  5670. default:
  5671. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
  5672. }
  5673. }
  5674. function renderRoutesList() {
  5675. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5676. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5677. const tbody = document.getElementById('routes-table-body');
  5678. const empty = document.getElementById('routes-empty');
  5679. if (!tbody) return;
  5680. // Update table filter select
  5681. const sel = document.getElementById('routes-filter-table');
  5682. if (sel) {
  5683. const cur = sel.value;
  5684. sel.innerHTML = '<option value="">All Tables</option>';
  5685. (state.routingTables || []).forEach(t => {
  5686. const opt = document.createElement('option');
  5687. opt.value = t.name;
  5688. opt.innerText = t.name;
  5689. if (t.name === cur) opt.selected = true;
  5690. sel.appendChild(opt);
  5691. });
  5692. }
  5693. const routes = (state.routes || []).filter(r => {
  5694. if (tableFilter && r.routing_table !== tableFilter) return false;
  5695. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5696. if (typeFilter === 'multicast' && !r.multicast) return false;
  5697. if (typeFilter === 'static' && !r.static) return false;
  5698. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5699. if (typeFilter === 'connected' && !r.connect) return false;
  5700. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  5701. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  5702. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  5703. return true;
  5704. });
  5705. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5706. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5707. let summaryText = `${routes.length} Routes`;
  5708. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5709. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5710. const badgeEl = document.getElementById('routes-count-badge');
  5711. if (badgeEl) badgeEl.innerText = summaryText;
  5712. if (routes.length === 0) {
  5713. empty?.classList.remove('hidden');
  5714. tbody.innerHTML = '';
  5715. return;
  5716. }
  5717. empty?.classList.add('hidden');
  5718. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  5719. if (tbody.dataset.sig === sig) {
  5720. return; // Routes table unchanged! Do not wipe DOM or flicker!
  5721. }
  5722. tbody.dataset.sig = sig;
  5723. tbody.innerHTML = '';
  5724. routes.forEach(r => {
  5725. const tr = document.createElement('tr');
  5726. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5727. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5728. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  5729. let flags = '';
  5730. if (r.dynamic) flags += 'D';
  5731. if (r.active) flags += 'A';
  5732. if (r.connect) flags += 'C';
  5733. if (r.static) flags += 'S';
  5734. if (r.ecmp) flags += 'E';
  5735. if (r.multicast) flags += 'M';
  5736. if (r.disabled) flags += 'X';
  5737. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5738. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  5739. if (r.check_gateway === 'internet') {
  5740. if (r.health_status === 'online') {
  5741. const ms = (r.health_rtt_ms || 0).toFixed(0);
  5742. healthCell = `
  5743. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
  5744. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  5745. <span>Internet OK (${ms}ms)</span>
  5746. </span>
  5747. `;
  5748. } else if (r.health_status === 'offline') {
  5749. healthCell = `
  5750. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
  5751. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5752. <span>Internet Down</span>
  5753. </span>
  5754. `;
  5755. } else {
  5756. healthCell = `
  5757. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
  5758. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  5759. <span>Checking...</span>
  5760. </span>
  5761. `;
  5762. }
  5763. } else if (r.check_gateway === 'ping') {
  5764. if (r.health_status === 'online') {
  5765. healthCell = `
  5766. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
  5767. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  5768. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  5769. </span>
  5770. `;
  5771. } else if (r.health_status === 'offline') {
  5772. healthCell = `
  5773. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
  5774. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5775. <span>Gateway Dead</span>
  5776. </span>
  5777. `;
  5778. }
  5779. }
  5780. const flagDescriptions = [];
  5781. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  5782. if (r.active) flagDescriptions.push('Active (A)');
  5783. if (r.connect) flagDescriptions.push('Connected (C)');
  5784. if (r.static) flagDescriptions.push('Static (S)');
  5785. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  5786. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  5787. if (r.disabled) flagDescriptions.push('Disabled (X)');
  5788. tr.innerHTML = `
  5789. <td class="py-2.5 px-3 text-center">
  5790. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  5791. r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
  5792. }" title="Flags: ${flagDescriptions.join(', ')}">
  5793. ${flags || '-'}
  5794. </span>
  5795. </td>
  5796. <td class="py-2.5 px-3">
  5797. <div class="flex items-center gap-1.5 flex-wrap">
  5798. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  5799. ${r.ecmp ? `
  5800. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
  5801. <span>⚡ ECMP</span>
  5802. </span>
  5803. ` : ''}
  5804. ${r.multicast ? `
  5805. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
  5806. <span>IGMP</span>
  5807. </span>
  5808. ` : ''}
  5809. </div>
  5810. </td>
  5811. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  5812. <td class="py-2.5 px-3 text-slate-300 font-mono">${r.gateway || '<span class="text-slate-600 font-sans">Direct link</span>'}</td>
  5813. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5814. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5815. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5816. <td class="py-2.5 px-3">${healthCell}</td>
  5817. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5818. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5819. ${r.static ? `
  5820. <button onclick="toggleRouteState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  5821. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5822. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5823. ` : `
  5824. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5825. `}
  5826. </td>
  5827. `;
  5828. tbody.appendChild(tr);
  5829. });
  5830. }
  5831. function openAddRouteModal() {
  5832. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5833. document.getElementById('route-modal-id').value = '';
  5834. document.getElementById('route-modal-old-dst').value = '';
  5835. document.getElementById('route-modal-old-gw').value = '';
  5836. document.getElementById('route-modal-old-distance').value = '';
  5837. document.getElementById('route-modal-old-table').value = '';
  5838. document.getElementById('route-modal-old-iface').value = '';
  5839. const dstInput = document.getElementById('route-modal-dst');
  5840. const gwInput = document.getElementById('route-modal-gw');
  5841. const distInput = document.getElementById('route-modal-distance');
  5842. const ifaceSelect = document.getElementById('route-modal-iface');
  5843. const tableSelect = document.getElementById('route-modal-table');
  5844. const commentInput = document.getElementById('route-modal-comment');
  5845. const disCheck = document.getElementById('route-modal-disabled');
  5846. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5847. dstInput.disabled = false;
  5848. dstInput.value = '0.0.0.0/0';
  5849. gwInput.disabled = false;
  5850. gwInput.value = '';
  5851. distInput.disabled = false;
  5852. distInput.value = '1';
  5853. ifaceSelect.disabled = false;
  5854. tableSelect.disabled = false;
  5855. commentInput.disabled = false;
  5856. commentInput.value = '';
  5857. disCheck.disabled = false;
  5858. disCheck.checked = false;
  5859. if (saveBtn) saveBtn.classList.remove('hidden');
  5860. const checkGw = document.getElementById('route-modal-check-gw');
  5861. if (checkGw) checkGw.value = 'internet';
  5862. const checkTarget = document.getElementById('route-modal-check-target');
  5863. if (checkTarget) checkTarget.value = '1.1.1.1';
  5864. const checkInterval = document.getElementById('route-modal-check-interval');
  5865. if (checkInterval) checkInterval.value = '5';
  5866. const checkThresh = document.getElementById('route-modal-check-threshold');
  5867. if (checkThresh) checkThresh.value = '3';
  5868. toggleRouteCheckModeUI();
  5869. populateInterfaceSelect('route-modal-iface');
  5870. // Populate tables
  5871. tableSelect.innerHTML = '';
  5872. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5873. const opt = document.createElement('option');
  5874. opt.value = t.name;
  5875. opt.innerText = t.name;
  5876. if (t.name === 'main') opt.selected = true;
  5877. tableSelect.appendChild(opt);
  5878. });
  5879. document.getElementById('route-modal').classList.remove('hidden');
  5880. }
  5881. function openEditRouteModal(id) {
  5882. const r = (state.routes || []).find(route => route.id === id);
  5883. if (!r) return;
  5884. const isStatic = !!r.static;
  5885. document.getElementById('route-modal-title').innerText = isStatic
  5886. ? `Edit Route: ${r.dst_address}`
  5887. : `Route Properties (Read Only): ${r.dst_address}`;
  5888. document.getElementById('route-modal-id').value = r.id;
  5889. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5890. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5891. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5892. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5893. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5894. const dstInput = document.getElementById('route-modal-dst');
  5895. const gwInput = document.getElementById('route-modal-gw');
  5896. const distInput = document.getElementById('route-modal-distance');
  5897. const ifaceSelect = document.getElementById('route-modal-iface');
  5898. const tableSelect = document.getElementById('route-modal-table');
  5899. const commentInput = document.getElementById('route-modal-comment');
  5900. const disCheck = document.getElementById('route-modal-disabled');
  5901. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5902. dstInput.value = r.dst_address;
  5903. gwInput.value = r.gateway || '';
  5904. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5905. commentInput.value = r.comment || '';
  5906. disCheck.checked = !!r.disabled;
  5907. const checkGw = document.getElementById('route-modal-check-gw');
  5908. if (checkGw) checkGw.value = r.check_gateway || 'none';
  5909. const checkTarget = document.getElementById('route-modal-check-target');
  5910. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  5911. const checkInterval = document.getElementById('route-modal-check-interval');
  5912. if (checkInterval) checkInterval.value = r.check_interval || 5;
  5913. const checkThresh = document.getElementById('route-modal-check-threshold');
  5914. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  5915. toggleRouteCheckModeUI();
  5916. dstInput.disabled = !isStatic;
  5917. gwInput.disabled = !isStatic;
  5918. distInput.disabled = !isStatic;
  5919. ifaceSelect.disabled = !isStatic;
  5920. tableSelect.disabled = !isStatic;
  5921. commentInput.disabled = !isStatic;
  5922. disCheck.disabled = !isStatic;
  5923. if (checkGw) checkGw.disabled = !isStatic;
  5924. if (checkTarget) checkTarget.disabled = !isStatic;
  5925. if (checkInterval) checkInterval.disabled = !isStatic;
  5926. if (checkThresh) checkThresh.disabled = !isStatic;
  5927. if (saveBtn) {
  5928. if (isStatic) {
  5929. saveBtn.classList.remove('hidden');
  5930. } else {
  5931. saveBtn.classList.add('hidden');
  5932. }
  5933. }
  5934. populateInterfaceSelect('route-modal-iface', r.interface);
  5935. tableSelect.innerHTML = '';
  5936. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5937. const opt = document.createElement('option');
  5938. opt.value = t.name;
  5939. opt.innerText = t.name;
  5940. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5941. tableSelect.appendChild(opt);
  5942. });
  5943. document.getElementById('route-modal').classList.remove('hidden');
  5944. }
  5945. function closeRouteModal() {
  5946. document.getElementById('route-modal').classList.add('hidden');
  5947. }
  5948. function setRouteCheckTarget(ip) {
  5949. const inp = document.getElementById('route-modal-check-target');
  5950. if (inp) inp.value = ip;
  5951. }
  5952. function toggleRouteCheckModeUI() {
  5953. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  5954. const targetRow = document.getElementById('route-row-check-target');
  5955. const paramsRow = document.getElementById('route-row-check-params');
  5956. if (mode === 'none') {
  5957. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5958. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  5959. } else if (mode === 'ping') {
  5960. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5961. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5962. } else { // internet
  5963. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  5964. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5965. }
  5966. }
  5967. async function submitSaveRoute(e) {
  5968. e.preventDefault();
  5969. const id = document.getElementById('route-modal-id').value;
  5970. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5971. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5972. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5973. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5974. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5975. const dst = document.getElementById('route-modal-dst').value.trim();
  5976. const gw = document.getElementById('route-modal-gw').value.trim();
  5977. const table = document.getElementById('route-modal-table').value;
  5978. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5979. const iface = document.getElementById('route-modal-iface').value;
  5980. const comment = document.getElementById('route-modal-comment').value.trim();
  5981. const disabled = document.getElementById('route-modal-disabled').checked;
  5982. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  5983. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  5984. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  5985. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  5986. if (!dst) {
  5987. showToast('Error', 'Destination address is required', 'error');
  5988. return;
  5989. }
  5990. if (!gw && !iface) {
  5991. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5992. return;
  5993. }
  5994. const payload = {
  5995. id,
  5996. old_dst_address: oldDst,
  5997. old_gateway: oldGw,
  5998. old_routing_table: oldTable,
  5999. old_interface: oldIface,
  6000. dst_address: dst,
  6001. gateway: gw || iface,
  6002. routing_table: table,
  6003. distance,
  6004. interface: iface,
  6005. comment,
  6006. disabled,
  6007. check_gateway,
  6008. check_target,
  6009. check_interval,
  6010. check_threshold
  6011. };
  6012. if (oldDistStr !== undefined && oldDistStr !== '') {
  6013. payload.old_distance = parseInt(oldDistStr, 10);
  6014. }
  6015. try {
  6016. const res = await fetch(`${API_BASE}/routes`, {
  6017. method: 'POST',
  6018. headers: { 'Content-Type': 'application/json' },
  6019. body: JSON.stringify(payload)
  6020. });
  6021. if (res.ok) {
  6022. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6023. closeRouteModal();
  6024. loadRoutes();
  6025. } else {
  6026. const err = await res.json();
  6027. showToast('Error', err.message || 'Failed to save route', 'error');
  6028. }
  6029. } catch (err) {
  6030. showToast('Error', err.message, 'error');
  6031. }
  6032. }
  6033. async function toggleRouteState(id, disabled) {
  6034. try {
  6035. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6036. method: 'POST',
  6037. headers: { 'Content-Type': 'application/json' },
  6038. body: JSON.stringify({ disabled })
  6039. });
  6040. if (res.ok) loadRoutes();
  6041. } catch (err) {
  6042. showToast('Error', err.message, 'error');
  6043. }
  6044. }
  6045. async function deleteRoute(id) {
  6046. if (!confirm('Are you sure you want to delete this route?')) return;
  6047. try {
  6048. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6049. if (res.ok) {
  6050. showToast('Deleted', 'Route removed', 'success');
  6051. loadRoutes();
  6052. }
  6053. } catch (err) {
  6054. showToast('Error', err.message, 'error');
  6055. }
  6056. }
  6057. // ----------------- Policy Rules (/ip route rule) -----------------
  6058. function renderPolicyRules() {
  6059. const tbody = document.getElementById('rules-table-body');
  6060. const empty = document.getElementById('rules-empty');
  6061. if (!tbody) return;
  6062. const showSystem = document.getElementById('prule-show-system')?.checked;
  6063. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6064. const countBadge = document.getElementById('rules-count-badge');
  6065. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6066. const bRules = document.getElementById('routes-badge-rules');
  6067. if (bRules) bRules.innerText = filtered.length;
  6068. if (filtered.length === 0) {
  6069. empty?.classList.remove('hidden');
  6070. tbody.innerHTML = '';
  6071. return;
  6072. }
  6073. empty?.classList.add('hidden');
  6074. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6075. if (tbody.dataset.sig === sig) return;
  6076. tbody.dataset.sig = sig;
  6077. tbody.innerHTML = '';
  6078. filtered.forEach(pr => {
  6079. const isSys = pr.is_default || pr.is_system;
  6080. const tr = document.createElement('tr');
  6081. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6082. tr.innerHTML = `
  6083. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6084. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6085. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6086. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6087. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6088. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6089. <td class="py-2.5 px-3 text-right font-sans">
  6090. ${!pr.is_default ? `
  6091. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6092. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6093. </td>
  6094. `;
  6095. tbody.appendChild(tr);
  6096. });
  6097. }
  6098. function openAddPolicyRuleModal() {
  6099. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6100. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6101. document.getElementById('prule-modal-mark').value = '';
  6102. document.getElementById('prule-modal-src').value = '';
  6103. document.getElementById('prule-modal-dst').value = '';
  6104. const sel = document.getElementById('prule-modal-table');
  6105. sel.innerHTML = '';
  6106. (state.routingTables || []).forEach(t => {
  6107. const opt = document.createElement('option');
  6108. opt.value = t.name;
  6109. opt.innerText = t.name;
  6110. sel.appendChild(opt);
  6111. });
  6112. document.getElementById('prule-modal').classList.remove('hidden');
  6113. }
  6114. function closePolicyRuleModal() {
  6115. document.getElementById('prule-modal').classList.add('hidden');
  6116. }
  6117. async function submitSavePolicyRule(e) {
  6118. e.preventDefault();
  6119. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6120. const mark = document.getElementById('prule-modal-mark').value.trim();
  6121. const src = document.getElementById('prule-modal-src').value.trim();
  6122. const dst = document.getElementById('prule-modal-dst').value.trim();
  6123. const table = document.getElementById('prule-modal-table').value;
  6124. const action = document.getElementById('prule-modal-action').value;
  6125. try {
  6126. const res = await fetch(`${API_BASE}/routing/rules`, {
  6127. method: 'POST',
  6128. headers: { 'Content-Type': 'application/json' },
  6129. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6130. });
  6131. if (res.ok) {
  6132. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6133. closePolicyRuleModal();
  6134. loadRoutes();
  6135. } else {
  6136. const err = await res.json();
  6137. showToast('Error', err.message, 'error');
  6138. }
  6139. } catch (err) {
  6140. showToast('Error', err.message, 'error');
  6141. }
  6142. }
  6143. async function deletePolicyRule(id) {
  6144. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6145. try {
  6146. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6147. if (res.ok) {
  6148. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6149. loadRoutes();
  6150. }
  6151. } catch (err) {
  6152. showToast('Error', err.message, 'error');
  6153. }
  6154. }
  6155. // ----------------- Routing Tables -----------------
  6156. function renderRoutingTables() {
  6157. const tbody = document.getElementById('tables-table-body');
  6158. if (!tbody) return;
  6159. const tables = state.routingTables || [];
  6160. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6161. if (tbody.dataset.sig === sig) return;
  6162. tbody.dataset.sig = sig;
  6163. tbody.innerHTML = '';
  6164. (state.routingTables || []).forEach(t => {
  6165. const tr = document.createElement('tr');
  6166. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6167. tr.innerHTML = `
  6168. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6169. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6170. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6171. `;
  6172. tbody.appendChild(tr);
  6173. });
  6174. }
  6175. function openAddTableModal() {
  6176. document.getElementById('table-modal-name').value = '';
  6177. document.getElementById('table-modal-id').value = '';
  6178. document.getElementById('table-modal-comment').value = '';
  6179. document.getElementById('table-modal').classList.remove('hidden');
  6180. }
  6181. function closeTableModal() {
  6182. document.getElementById('table-modal').classList.add('hidden');
  6183. }
  6184. async function submitSaveTable(e) {
  6185. e.preventDefault();
  6186. const name = document.getElementById('table-modal-name').value.trim();
  6187. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6188. const comment = document.getElementById('table-modal-comment').value.trim();
  6189. try {
  6190. const res = await fetch(`${API_BASE}/routing/tables`, {
  6191. method: 'POST',
  6192. headers: { 'Content-Type': 'application/json' },
  6193. body: JSON.stringify({ name, table_id: id, comment })
  6194. });
  6195. if (res.ok) {
  6196. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6197. closeTableModal();
  6198. loadRoutes();
  6199. } else {
  6200. const err = await res.json();
  6201. showToast('Error', err.message, 'error');
  6202. }
  6203. } catch (err) {
  6204. showToast('Error', err.message, 'error');
  6205. }
  6206. }
  6207. async function loadDebianConfig() {
  6208. const view = document.getElementById('debian-config-view');
  6209. view.innerText = 'Generating live configuration...';
  6210. try {
  6211. const res = await fetch(`${API_BASE}/debian/config`);
  6212. const data = await res.json();
  6213. view.innerText = data.content || '# Empty config';
  6214. } catch (err) {
  6215. view.innerText = 'Failed to generate Debian network config.';
  6216. }
  6217. }
  6218. async function saveDebianConfig() {
  6219. try {
  6220. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6221. const data = await res.json();
  6222. if (res.ok) {
  6223. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6224. loadDebianConfig();
  6225. }
  6226. } catch (err) {
  6227. showToast('Error', err.message, 'error');
  6228. }
  6229. }
  6230. function showToast(title, message, type = 'info') {
  6231. const container = document.getElementById('toast-container');
  6232. const toast = document.createElement('div');
  6233. const borderColors = {
  6234. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6235. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6236. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6237. };
  6238. toast.className = `pointer-events-auto border rounded-xl p-4 shadow-2xl backdrop-blur-md flex items-start space-x-3 w-80 transform transition-all duration-300 translate-y-2 opacity-0 ${borderColors[type] || borderColors.info}`;
  6239. toast.innerHTML = `
  6240. <div class="flex-1">
  6241. <div class="font-bold text-xs text-white">${title}</div>
  6242. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6243. </div>
  6244. `;
  6245. container.appendChild(toast);
  6246. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6247. setTimeout(() => {
  6248. toast.classList.add('opacity-0', 'translate-y-2');
  6249. setTimeout(() => toast.remove(), 300);
  6250. }, 4000);
  6251. }
  6252. function formatTraffic(bytesPerSec) {
  6253. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6254. const kb = bytesPerSec / 1024;
  6255. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6256. const mb = kb / 1024;
  6257. return `${mb.toFixed(2)} MB/s`;
  6258. }
  6259. function toggleSidebar() {
  6260. const sb = document.getElementById('sidebar');
  6261. sb.classList.toggle('-translate-x-full');
  6262. }
  6263. // ======================== EoIP (Ethernet over IP) ========================
  6264. async function loadEoIP(populate = true) {
  6265. try {
  6266. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6267. const data = await res.json();
  6268. state.eoipTunnels = Array.isArray(data) ? data : [];
  6269. const badge = document.getElementById('eoip-count-badge');
  6270. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6271. const sideBadge = document.getElementById('badge-eoip-count');
  6272. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6273. renderEoIPTunnels();
  6274. } catch (err) {
  6275. console.error('Failed to load EoIP:', err);
  6276. }
  6277. }
  6278. function renderEoIPTunnels() {
  6279. const tbody = document.getElementById('eoip-table-body');
  6280. const empty = document.getElementById('eoip-empty');
  6281. if (!tbody) return;
  6282. tbody.innerHTML = '';
  6283. const tunnels = state.eoipTunnels || [];
  6284. if (tunnels.length === 0) {
  6285. empty?.classList.remove('hidden');
  6286. return;
  6287. }
  6288. empty?.classList.add('hidden');
  6289. tunnels.forEach(t => {
  6290. const tr = document.createElement('tr');
  6291. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6292. tr.innerHTML = `
  6293. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6294. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6295. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6296. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${t.ip_address || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  6297. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6298. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6299. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6300. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6301. <td class="py-2.5 px-3 font-mono text-[11px]">
  6302. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6303. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6304. </td>
  6305. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6306. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6307. <button onclick="toggleEoIPState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6308. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6309. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6310. </td>
  6311. `;
  6312. tbody.appendChild(tr);
  6313. });
  6314. }
  6315. function openAddEoIPModal() {
  6316. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6317. document.getElementById('eoip-modal-id').value = '';
  6318. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6319. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6320. document.getElementById('eoip-modal-remote').value = '';
  6321. document.getElementById('eoip-modal-ip').value = '';
  6322. document.getElementById('eoip-modal-local').value = '';
  6323. document.getElementById('eoip-modal-mac').value = '';
  6324. document.getElementById('eoip-modal-mtu').value = '1500';
  6325. document.getElementById('eoip-modal-comment').value = '';
  6326. document.getElementById('eoip-modal-clampmss').checked = true;
  6327. document.getElementById('eoip-modal-disabled').checked = false;
  6328. document.getElementById('eoip-modal').classList.remove('hidden');
  6329. }
  6330. function openEditEoIPModal(id) {
  6331. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6332. if (!t) return;
  6333. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6334. document.getElementById('eoip-modal-id').value = t.id;
  6335. document.getElementById('eoip-modal-name').value = t.name;
  6336. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6337. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6338. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6339. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6340. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6341. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6342. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6343. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6344. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6345. document.getElementById('eoip-modal').classList.remove('hidden');
  6346. }
  6347. function closeEoIPModal() {
  6348. document.getElementById('eoip-modal').classList.add('hidden');
  6349. }
  6350. async function submitSaveEoIP(e) {
  6351. e.preventDefault();
  6352. const id = document.getElementById('eoip-modal-id').value;
  6353. const name = document.getElementById('eoip-modal-name').value.trim();
  6354. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6355. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6356. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6357. const local = document.getElementById('eoip-modal-local').value.trim();
  6358. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6359. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6360. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6361. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6362. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6363. try {
  6364. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6365. method: 'POST',
  6366. headers: { 'Content-Type': 'application/json' },
  6367. body: JSON.stringify({
  6368. id,
  6369. name,
  6370. tunnel_id: tunnelId,
  6371. remote_address: remote,
  6372. ip_address: ipAddress,
  6373. local_address: local,
  6374. mac_address: mac,
  6375. mtu,
  6376. clamp_mss: clampMss,
  6377. comment,
  6378. disabled
  6379. })
  6380. });
  6381. if (res.ok) {
  6382. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6383. closeEoIPModal();
  6384. loadEoIP(false);
  6385. fetchData(false);
  6386. } else {
  6387. const err = await res.json();
  6388. showToast('Error', err.message, 'error');
  6389. }
  6390. } catch (err) {
  6391. showToast('Error', err.message, 'error');
  6392. }
  6393. }
  6394. async function toggleEoIPState(id, disabled) {
  6395. try {
  6396. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6397. method: 'POST',
  6398. headers: { 'Content-Type': 'application/json' },
  6399. body: JSON.stringify({ disabled })
  6400. });
  6401. if (res.ok) {
  6402. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6403. loadEoIP(false);
  6404. fetchData(false);
  6405. }
  6406. } catch (err) {
  6407. showToast('Error', err.message, 'error');
  6408. }
  6409. }
  6410. async function deleteEoIP(id) {
  6411. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6412. try {
  6413. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6414. if (res.ok) {
  6415. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6416. loadEoIP(false);
  6417. fetchData(false);
  6418. }
  6419. } catch (err) {
  6420. showToast('Error', err.message, 'error');
  6421. }
  6422. }
  6423. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6424. async function loadAeroTUN(populate = true) {
  6425. try {
  6426. const [tunnelsRes, statsRes] = await Promise.all([
  6427. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6428. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6429. ]);
  6430. if (tunnelsRes.ok) {
  6431. const data = await tunnelsRes.json();
  6432. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6433. }
  6434. if (statsRes.ok) {
  6435. state.aerotunStats = await statsRes.json();
  6436. }
  6437. const countBadge = document.getElementById('aerotun-count-badge');
  6438. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6439. const sideBadge = document.getElementById('badge-aerotun-count');
  6440. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6441. renderAeroTUN();
  6442. } catch (err) {
  6443. console.error('Failed to load AeroTUN:', err);
  6444. }
  6445. }
  6446. function renderAeroTUN() {
  6447. const tbody = document.getElementById('aerotun-table-body');
  6448. const empty = document.getElementById('aerotun-empty');
  6449. // Update summary cards
  6450. const stats = state.aerotunStats || {};
  6451. const tunnels = state.aerotunTunnels || [];
  6452. const statActive = document.getElementById('aerotun-stat-active');
  6453. if (statActive) {
  6454. const activeCount = tunnels.filter(t => t.running).length;
  6455. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6456. }
  6457. const statSaved = document.getElementById('aerotun-stat-saved');
  6458. if (statSaved) {
  6459. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6460. }
  6461. const statRatio = document.getElementById('aerotun-stat-ratio');
  6462. if (statRatio) {
  6463. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6464. }
  6465. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6466. if (statTraffic) {
  6467. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6468. }
  6469. if (!tbody) return;
  6470. tbody.innerHTML = '';
  6471. if (tunnels.length === 0) {
  6472. empty?.classList.remove('hidden');
  6473. return;
  6474. }
  6475. empty?.classList.add('hidden');
  6476. tunnels.forEach(t => {
  6477. const tr = document.createElement('tr');
  6478. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6479. const modeBadge = t.mode === 'server'
  6480. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  6481. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  6482. const endpointInfo = t.mode === 'server'
  6483. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6484. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6485. const compBadge = t.compression
  6486. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  6487. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6488. const activePeer = t.active_peer_endpoint
  6489. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6490. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6491. const rawRx = formatBytes(t.rx_bytes || 0);
  6492. const rawTx = formatBytes(t.tx_bytes || 0);
  6493. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6494. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6495. tr.innerHTML = `
  6496. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6497. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6498. <span>${escapeHtml(t.name)}</span>
  6499. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6500. </td>
  6501. <td class="py-2.5 px-3">${modeBadge}</td>
  6502. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6503. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6504. <td class="py-2.5 px-3">${compBadge}</td>
  6505. <td class="py-2.5 px-3">${activePeer}</td>
  6506. <td class="py-2.5 px-3 font-mono text-[11px]">
  6507. <span class="text-emerald-400">↓ ${rawRx}</span>
  6508. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6509. </td>
  6510. <td class="py-2.5 px-3 font-mono text-[11px]">
  6511. <span class="text-slate-400">↓ ${wireRx}</span>
  6512. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6513. </td>
  6514. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6515. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6516. ${t.running
  6517. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6518. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6519. }
  6520. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6521. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6522. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6523. </td>
  6524. `;
  6525. tbody.appendChild(tr);
  6526. });
  6527. }
  6528. function onAeroTUNModeChange() {
  6529. const mode = document.getElementById('aerotun-modal-mode').value;
  6530. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6531. const portInput = document.getElementById('aerotun-modal-port');
  6532. if (mode === 'server') {
  6533. if (!portInput.value) portInput.value = '51830';
  6534. endpointInput.placeholder = 'Optional / learned roaming peer';
  6535. } else {
  6536. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6537. if (!portInput.value) portInput.value = '';
  6538. }
  6539. }
  6540. async function generateAeroTUNKey() {
  6541. try {
  6542. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6543. if (res.ok) {
  6544. const data = await res.json();
  6545. document.getElementById('aerotun-modal-psk').value = data.key;
  6546. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6547. }
  6548. } catch (err) {
  6549. const arr = new Uint8Array(32);
  6550. crypto.getRandomValues(arr);
  6551. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6552. document.getElementById('aerotun-modal-psk').value = hex;
  6553. }
  6554. }
  6555. function openAddAeroTUNModal() {
  6556. const tunnels = state.aerotunTunnels || [];
  6557. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6558. document.getElementById('aerotun-modal-id').value = '';
  6559. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6560. document.getElementById('aerotun-modal-mode').value = 'server';
  6561. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6562. document.getElementById('aerotun-modal-endpoint').value = '';
  6563. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6564. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6565. document.getElementById('aerotun-modal-psk').value = '';
  6566. document.getElementById('aerotun-modal-mtu').value = '1420';
  6567. document.getElementById('aerotun-modal-comment').value = '';
  6568. document.getElementById('aerotun-modal-compression').checked = true;
  6569. document.getElementById('aerotun-modal-defroute').checked = false;
  6570. document.getElementById('aerotun-modal-disabled').checked = false;
  6571. generateAeroTUNKey();
  6572. onAeroTUNModeChange();
  6573. document.getElementById('aerotun-modal').classList.remove('hidden');
  6574. }
  6575. function openEditAeroTUNModal(id) {
  6576. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6577. if (!t) return;
  6578. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6579. document.getElementById('aerotun-modal-id').value = t.id;
  6580. document.getElementById('aerotun-modal-name').value = t.name;
  6581. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6582. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6583. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6584. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6585. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6586. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6587. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6588. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6589. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6590. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6591. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6592. onAeroTUNModeChange();
  6593. document.getElementById('aerotun-modal').classList.remove('hidden');
  6594. }
  6595. function closeAeroTUNModal() {
  6596. document.getElementById('aerotun-modal').classList.add('hidden');
  6597. }
  6598. async function submitSaveAeroTUN(e) {
  6599. e.preventDefault();
  6600. const id = document.getElementById('aerotun-modal-id').value;
  6601. const name = document.getElementById('aerotun-modal-name').value.trim();
  6602. const mode = document.getElementById('aerotun-modal-mode').value;
  6603. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6604. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6605. const local = document.getElementById('aerotun-modal-local').value.trim();
  6606. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6607. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6608. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6609. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6610. const compression = document.getElementById('aerotun-modal-compression').checked;
  6611. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6612. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6613. if (mode === 'client' && !endpoint) {
  6614. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6615. return;
  6616. }
  6617. if (!psk) {
  6618. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6619. return;
  6620. }
  6621. try {
  6622. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6623. method: 'POST',
  6624. headers: { 'Content-Type': 'application/json' },
  6625. body: JSON.stringify({
  6626. id,
  6627. name,
  6628. mode,
  6629. listen_port: port,
  6630. remote_endpoint: endpoint,
  6631. local_address: local,
  6632. peer_address: peer,
  6633. psk,
  6634. mtu,
  6635. compression,
  6636. default_route: defaultRoute,
  6637. comment,
  6638. disabled
  6639. })
  6640. });
  6641. if (res.ok) {
  6642. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6643. closeAeroTUNModal();
  6644. loadAeroTUN(false);
  6645. fetchData(false);
  6646. } else {
  6647. const err = await res.text();
  6648. showToast('Error Saving Tunnel', err, 'error');
  6649. }
  6650. } catch (err) {
  6651. showToast('Network Error', err.message, 'error');
  6652. }
  6653. }
  6654. async function startAeroTUNTunnel(id) {
  6655. try {
  6656. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6657. if (res.ok) {
  6658. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6659. loadAeroTUN(false);
  6660. fetchData(false);
  6661. } else {
  6662. const err = await res.text();
  6663. showToast('Failed to Start', err, 'error');
  6664. }
  6665. } catch (err) {
  6666. showToast('Error', err.message, 'error');
  6667. }
  6668. }
  6669. async function stopAeroTUNTunnel(id) {
  6670. try {
  6671. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6672. if (res.ok) {
  6673. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6674. loadAeroTUN(false);
  6675. fetchData(false);
  6676. } else {
  6677. const err = await res.text();
  6678. showToast('Failed to Stop', err, 'error');
  6679. }
  6680. } catch (err) {
  6681. showToast('Error', err.message, 'error');
  6682. }
  6683. }
  6684. async function toggleAeroTUNState(id, disabled) {
  6685. try {
  6686. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6687. method: 'POST',
  6688. headers: { 'Content-Type': 'application/json' },
  6689. body: JSON.stringify({ disabled })
  6690. });
  6691. if (res.ok) {
  6692. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6693. loadAeroTUN(false);
  6694. fetchData(false);
  6695. }
  6696. } catch (err) {
  6697. showToast('Error', err.message, 'error');
  6698. }
  6699. }
  6700. async function deleteAeroTUN(id) {
  6701. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6702. try {
  6703. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6704. if (res.ok) {
  6705. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6706. loadAeroTUN(false);
  6707. fetchData(false);
  6708. }
  6709. } catch (err) {
  6710. showToast('Error', err.message, 'error');
  6711. }
  6712. }
  6713. // ======================== PPP Central Hub & Servers ========================
  6714. function switchPPPSubTab(tab) {
  6715. state.pppSubTab = tab;
  6716. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6717. tabs.forEach(t => {
  6718. const panel = document.getElementById(`ppp-subtab-${t}`);
  6719. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6720. if (panel) {
  6721. if (t === tab) panel.classList.remove('hidden');
  6722. else panel.classList.add('hidden');
  6723. }
  6724. if (btn) {
  6725. if (t === tab) {
  6726. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-violet-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  6727. } else {
  6728. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  6729. }
  6730. }
  6731. });
  6732. const addBtn = document.getElementById('ppp-primary-add-btn');
  6733. if (addBtn) {
  6734. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6735. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6736. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6737. else addBtn.innerHTML = '<span>Save Config</span>';
  6738. }
  6739. if (tab === 'active') loadPPPSessions();
  6740. }
  6741. function openCurrentPPPModal() {
  6742. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6743. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6744. else if (state.pppSubTab === 'active') loadPPPSessions();
  6745. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6746. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6747. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6748. }
  6749. async function loadPPP(populateDropdowns = true) {
  6750. await Promise.all([
  6751. loadPPPSecrets(),
  6752. loadPPPProfiles(),
  6753. loadPPPServers(),
  6754. loadPPPSessions()
  6755. ]);
  6756. }
  6757. async function loadPPPSecrets() {
  6758. try {
  6759. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6760. const data = await res.json();
  6761. state.pppSecrets = Array.isArray(data) ? data : [];
  6762. const b = document.getElementById('ppp-badge-secrets');
  6763. if (b) b.innerText = state.pppSecrets.length;
  6764. const b2 = document.getElementById('secrets-count-badge');
  6765. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6766. renderPPPSecrets();
  6767. } catch (err) {
  6768. console.error('Failed to load PPP secrets:', err);
  6769. }
  6770. }
  6771. function renderPPPSecrets() {
  6772. const tbody = document.getElementById('secrets-table-body');
  6773. const empty = document.getElementById('secrets-empty');
  6774. if (!tbody) return;
  6775. tbody.innerHTML = '';
  6776. const secrets = state.pppSecrets || [];
  6777. if (secrets.length === 0) {
  6778. empty?.classList.remove('hidden');
  6779. return;
  6780. }
  6781. empty?.classList.add('hidden');
  6782. secrets.forEach(s => {
  6783. const tr = document.createElement('tr');
  6784. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6785. tr.innerHTML = `
  6786. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6787. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6788. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6789. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6790. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6791. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6792. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6793. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6794. <button onclick="togglePPPSecretState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  6795. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6796. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6797. </td>
  6798. `;
  6799. tbody.appendChild(tr);
  6800. });
  6801. }
  6802. async function loadPPPProfiles() {
  6803. try {
  6804. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6805. const data = await res.json();
  6806. state.pppProfiles = Array.isArray(data) ? data : [];
  6807. const b = document.getElementById('ppp-badge-profiles');
  6808. if (b) b.innerText = state.pppProfiles.length;
  6809. const b2 = document.getElementById('profiles-count-badge');
  6810. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6811. // Populate profile selects across modals
  6812. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6813. selects.forEach(sid => {
  6814. const el = document.getElementById(sid);
  6815. if (!el) return;
  6816. const cur = el.value;
  6817. el.innerHTML = '';
  6818. state.pppProfiles.forEach(p => {
  6819. const opt = document.createElement('option');
  6820. opt.value = p.name;
  6821. opt.innerText = `${p.name} (${p.remote_address})`;
  6822. if (p.name === cur) opt.selected = true;
  6823. el.appendChild(opt);
  6824. });
  6825. });
  6826. renderPPPProfiles();
  6827. } catch (err) {
  6828. console.error('Failed to load PPP profiles:', err);
  6829. }
  6830. }
  6831. function renderPPPProfiles() {
  6832. const tbody = document.getElementById('profiles-table-body');
  6833. if (!tbody) return;
  6834. tbody.innerHTML = '';
  6835. (state.pppProfiles || []).forEach(p => {
  6836. const isDefault = p.name.startsWith('default');
  6837. const tr = document.createElement('tr');
  6838. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6839. tr.innerHTML = `
  6840. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6841. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6842. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6843. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6844. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6845. <td class="py-2.5 px-3 text-center">${p.only_one ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  6846. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6847. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6848. ${!isDefault ? `<button onclick="deletePPPProfile('${p.name}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>` : `<span class="text-slate-600 text-[10px]">Built-in</span>`}
  6849. </td>
  6850. `;
  6851. tbody.appendChild(tr);
  6852. });
  6853. }
  6854. async function loadPPPServers() {
  6855. try {
  6856. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6857. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6858. fetch(`${API_BASE}/vpn/servers/pptp`),
  6859. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6860. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6861. ]);
  6862. if (pppoeRes.ok) {
  6863. state.pppoeServer = await pppoeRes.json();
  6864. const s = state.pppoeServer;
  6865. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6866. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6867. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6868. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6869. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6870. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6871. const pill = document.getElementById('pppoe-server-status-pill');
  6872. if (pill) {
  6873. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6874. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-blue-500/20 text-blue-300 border border-blue-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  6875. }
  6876. setDotBadge('ppp-badge-pppoe-state', s.running);
  6877. }
  6878. if (pptpRes.ok) {
  6879. state.pptpServer = await pptpRes.json();
  6880. const s = state.pptpServer;
  6881. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6882. document.getElementById('pptp-server-port').value = s.port || 1723;
  6883. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6884. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6885. const pill = document.getElementById('pptp-server-status-pill');
  6886. if (pill) {
  6887. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6888. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-purple-500/20 text-purple-300 border border-purple-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  6889. }
  6890. setDotBadge('ppp-badge-pptp-state', s.running);
  6891. }
  6892. if (l2tpRes.ok) {
  6893. state.l2tpServer = await l2tpRes.json();
  6894. const s = state.l2tpServer;
  6895. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6896. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6897. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6898. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6899. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6900. const pill = document.getElementById('l2tp-server-status-pill');
  6901. if (pill) {
  6902. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6903. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  6904. }
  6905. setDotBadge('ppp-badge-l2tp-state', s.running);
  6906. }
  6907. if (ipsecRes.ok) {
  6908. state.ipsecServer = await ipsecRes.json();
  6909. const s = state.ipsecServer;
  6910. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6911. if (modalEn) modalEn.checked = !!s.enabled;
  6912. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6913. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6914. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6915. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6916. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6917. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6918. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6919. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6920. const pill = document.getElementById('modal-ipsec-server-status');
  6921. if (pill) {
  6922. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6923. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  6924. }
  6925. }
  6926. } catch (err) {
  6927. console.error('Failed to load VPN servers:', err);
  6928. }
  6929. }
  6930. async function loadPPPSessions() {
  6931. try {
  6932. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6933. const data = await res.json();
  6934. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6935. const b = document.getElementById('ppp-badge-active');
  6936. if (b) b.innerText = state.pppActiveSessions.length;
  6937. const sideB = document.getElementById('badge-ppp-sessions');
  6938. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6939. renderPPPSessions();
  6940. } catch (err) {
  6941. console.error('Failed to load active PPP sessions:', err);
  6942. }
  6943. }
  6944. function renderPPPSessions() {
  6945. const tbody = document.getElementById('active-ppp-table-body');
  6946. const empty = document.getElementById('active-ppp-empty');
  6947. if (!tbody) return;
  6948. tbody.innerHTML = '';
  6949. const list = state.pppActiveSessions || [];
  6950. if (list.length === 0) {
  6951. empty?.classList.remove('hidden');
  6952. return;
  6953. }
  6954. empty?.classList.add('hidden');
  6955. list.forEach(s => {
  6956. const tr = document.createElement('tr');
  6957. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6958. tr.innerHTML = `
  6959. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6960. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6961. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6962. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6963. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6964. <td class="py-2.5 px-3 text-[11px]">
  6965. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6966. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6967. </td>
  6968. <td class="py-2.5 px-3 text-right font-sans">
  6969. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6970. </td>
  6971. `;
  6972. tbody.appendChild(tr);
  6973. });
  6974. }
  6975. async function disconnectPPPSession(iface) {
  6976. if (!confirm(`Disconnect session ${iface}?`)) return;
  6977. try {
  6978. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6979. if (res.ok) {
  6980. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6981. loadPPPSessions();
  6982. }
  6983. } catch (err) {
  6984. showToast('Error', err.message, 'error');
  6985. }
  6986. }
  6987. // PPP Secret Modal handlers
  6988. function openAddPPPSecretModal() {
  6989. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6990. document.getElementById('secret-modal-id').value = '';
  6991. document.getElementById('secret-modal-name').value = '';
  6992. document.getElementById('secret-modal-password').value = '';
  6993. document.getElementById('secret-modal-service').value = 'any';
  6994. document.getElementById('secret-modal-profile').value = 'default';
  6995. document.getElementById('secret-modal-local').value = '';
  6996. document.getElementById('secret-modal-remote').value = '';
  6997. document.getElementById('secret-modal-comment').value = '';
  6998. document.getElementById('secret-modal-disabled').checked = false;
  6999. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7000. }
  7001. function openEditPPPSecretModal(id) {
  7002. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7003. if (!s) return;
  7004. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7005. document.getElementById('secret-modal-id').value = s.id;
  7006. document.getElementById('secret-modal-name').value = s.name;
  7007. document.getElementById('secret-modal-password').value = s.password;
  7008. document.getElementById('secret-modal-service').value = s.service || 'any';
  7009. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7010. document.getElementById('secret-modal-local').value = s.local_address || '';
  7011. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7012. document.getElementById('secret-modal-comment').value = s.comment || '';
  7013. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7014. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7015. }
  7016. function closePPPSecretModal() {
  7017. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7018. }
  7019. async function submitSavePPPSecret(e) {
  7020. e.preventDefault();
  7021. const id = document.getElementById('secret-modal-id').value;
  7022. const name = document.getElementById('secret-modal-name').value.trim();
  7023. const password = document.getElementById('secret-modal-password').value.trim();
  7024. const service = document.getElementById('secret-modal-service').value;
  7025. const profile = document.getElementById('secret-modal-profile').value;
  7026. const local = document.getElementById('secret-modal-local').value.trim();
  7027. const remote = document.getElementById('secret-modal-remote').value.trim();
  7028. const comment = document.getElementById('secret-modal-comment').value.trim();
  7029. const disabled = document.getElementById('secret-modal-disabled').checked;
  7030. try {
  7031. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7032. method: 'POST',
  7033. headers: { 'Content-Type': 'application/json' },
  7034. body: JSON.stringify({
  7035. id,
  7036. name,
  7037. password,
  7038. service,
  7039. profile,
  7040. local_address: local,
  7041. remote_address: remote,
  7042. comment,
  7043. disabled
  7044. })
  7045. });
  7046. if (res.ok) {
  7047. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7048. closePPPSecretModal();
  7049. loadPPPSecrets();
  7050. } else {
  7051. const err = await res.json();
  7052. showToast('Error', err.message, 'error');
  7053. }
  7054. } catch (err) {
  7055. showToast('Error', err.message, 'error');
  7056. }
  7057. }
  7058. async function togglePPPSecretState(id, disabled) {
  7059. try {
  7060. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7061. method: 'POST',
  7062. headers: { 'Content-Type': 'application/json' },
  7063. body: JSON.stringify({ disabled })
  7064. });
  7065. if (res.ok) {
  7066. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7067. loadPPPSecrets();
  7068. }
  7069. } catch (err) {
  7070. showToast('Error', err.message, 'error');
  7071. }
  7072. }
  7073. async function deletePPPSecret(id) {
  7074. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7075. try {
  7076. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7077. if (res.ok) {
  7078. showToast('Deleted', 'Secret account removed', 'success');
  7079. loadPPPSecrets();
  7080. }
  7081. } catch (err) {
  7082. showToast('Error', err.message, 'error');
  7083. }
  7084. }
  7085. // PPP Profile Modal handlers
  7086. function openAddPPPProfileModal() {
  7087. document.getElementById('profile-modal-name').value = '';
  7088. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7089. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7090. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7091. document.getElementById('profile-modal-encryption').value = 'required';
  7092. document.getElementById('profile-modal-onlyone').checked = true;
  7093. document.getElementById('profile-modal-comment').value = '';
  7094. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7095. }
  7096. function closePPPProfileModal() {
  7097. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7098. }
  7099. async function submitSavePPPProfile(e) {
  7100. e.preventDefault();
  7101. const name = document.getElementById('profile-modal-name').value.trim();
  7102. const local = document.getElementById('profile-modal-local').value.trim();
  7103. const remote = document.getElementById('profile-modal-remote').value.trim();
  7104. const dns = document.getElementById('profile-modal-dns').value.trim();
  7105. const enc = document.getElementById('profile-modal-encryption').value;
  7106. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7107. const comment = document.getElementById('profile-modal-comment').value.trim();
  7108. try {
  7109. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7110. method: 'POST',
  7111. headers: { 'Content-Type': 'application/json' },
  7112. body: JSON.stringify({
  7113. id: name,
  7114. name,
  7115. local_address: local,
  7116. remote_address: remote,
  7117. dns_servers: dns,
  7118. use_encryption: enc,
  7119. only_one: onlyone,
  7120. comment
  7121. })
  7122. });
  7123. if (res.ok) {
  7124. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7125. closePPPProfileModal();
  7126. loadPPPProfiles();
  7127. } else {
  7128. const err = await res.json();
  7129. showToast('Error', err.message, 'error');
  7130. }
  7131. } catch (err) {
  7132. showToast('Error', err.message, 'error');
  7133. }
  7134. }
  7135. async function deletePPPProfile(name) {
  7136. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7137. try {
  7138. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7139. if (res.ok) {
  7140. showToast('Deleted', 'Profile removed', 'success');
  7141. loadPPPProfiles();
  7142. } else {
  7143. const err = await res.json();
  7144. showToast('Error', err.message, 'error');
  7145. }
  7146. } catch (err) {
  7147. showToast('Error', err.message, 'error');
  7148. }
  7149. }
  7150. // Server Config submissions
  7151. async function savePPPoEServerConfig(e) {
  7152. e.preventDefault();
  7153. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7154. const name = document.getElementById('pppoe-server-name').value.trim();
  7155. const iface = document.getElementById('pppoe-server-iface').value;
  7156. const profile = document.getElementById('pppoe-server-profile').value;
  7157. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7158. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7159. try {
  7160. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7161. method: 'POST',
  7162. headers: { 'Content-Type': 'application/json' },
  7163. body: JSON.stringify({
  7164. enabled,
  7165. service_name: name,
  7166. interface: iface,
  7167. default_profile: profile,
  7168. max_mtu: mtu,
  7169. max_mru: mtu,
  7170. one_session_per_host: onesession
  7171. })
  7172. });
  7173. if (res.ok) {
  7174. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7175. loadPPPServers();
  7176. fetchData(false);
  7177. } else {
  7178. const err = await res.json();
  7179. showToast('Error', err.message, 'error');
  7180. }
  7181. } catch (err) {
  7182. showToast('Error', err.message, 'error');
  7183. }
  7184. }
  7185. async function savePPTPServerConfig(e) {
  7186. e.preventDefault();
  7187. const enabled = document.getElementById('pptp-server-enabled').checked;
  7188. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7189. const profile = document.getElementById('pptp-server-profile').value;
  7190. const mppe = document.getElementById('pptp-server-mppe').checked;
  7191. try {
  7192. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7193. method: 'POST',
  7194. headers: { 'Content-Type': 'application/json' },
  7195. body: JSON.stringify({
  7196. enabled,
  7197. port,
  7198. default_profile: profile,
  7199. require_mppe: mppe
  7200. })
  7201. });
  7202. if (res.ok) {
  7203. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7204. loadPPPServers();
  7205. fetchData(false);
  7206. } else {
  7207. const err = await res.json();
  7208. showToast('Error', err.message, 'error');
  7209. }
  7210. } catch (err) {
  7211. showToast('Error', err.message, 'error');
  7212. }
  7213. }
  7214. async function saveL2TPServerConfig(e) {
  7215. e.preventDefault();
  7216. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7217. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7218. const profile = document.getElementById('l2tp-server-profile').value;
  7219. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7220. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7221. try {
  7222. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7223. method: 'POST',
  7224. headers: { 'Content-Type': 'application/json' },
  7225. body: JSON.stringify({
  7226. enabled,
  7227. port,
  7228. default_profile: profile,
  7229. use_ipsec: useipsec,
  7230. ipsec_secret: psk
  7231. })
  7232. });
  7233. if (res.ok) {
  7234. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7235. loadPPPServers();
  7236. fetchData(false);
  7237. } else {
  7238. const err = await res.json();
  7239. showToast('Error', err.message, 'error');
  7240. }
  7241. } catch (err) {
  7242. showToast('Error', err.message, 'error');
  7243. }
  7244. }
  7245. // IPSec Server Modal
  7246. function openIPSecServerModal() {
  7247. loadPPPServers();
  7248. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7249. }
  7250. function closeIPSecServerModal() {
  7251. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7252. }
  7253. async function submitSaveIPSecServer(e) {
  7254. e.preventDefault();
  7255. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7256. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7257. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7258. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7259. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7260. try {
  7261. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7262. method: 'POST',
  7263. headers: { 'Content-Type': 'application/json' },
  7264. body: JSON.stringify({
  7265. enabled,
  7266. preshared_key: psk,
  7267. pool_address: pool,
  7268. dns_servers: dns,
  7269. local_subnet: subnet
  7270. })
  7271. });
  7272. if (res.ok) {
  7273. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7274. closeIPSecServerModal();
  7275. loadPPPServers();
  7276. fetchData(false);
  7277. } else {
  7278. const err = await res.json();
  7279. showToast('Error', err.message, 'error');
  7280. }
  7281. } catch (err) {
  7282. showToast('Error', err.message, 'error');
  7283. }
  7284. }
  7285. // WireGuard Client Config Viewer
  7286. let currentWGClientConf = '';
  7287. async function openWGClientConfModal(iface, clientIP) {
  7288. try {
  7289. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7290. method: 'POST',
  7291. headers: { 'Content-Type': 'application/json' },
  7292. body: JSON.stringify({
  7293. interface: iface,
  7294. address: clientIP || '10.10.0.2/32',
  7295. dns: '1.1.1.1, 8.8.8.8'
  7296. })
  7297. });
  7298. if (res.ok) {
  7299. const data = await res.json();
  7300. currentWGClientConf = data.config;
  7301. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7302. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7303. } else {
  7304. const err = await res.json();
  7305. showToast('Error', err.message, 'error');
  7306. }
  7307. } catch (err) {
  7308. showToast('Error', err.message, 'error');
  7309. }
  7310. }
  7311. function closeWGClientConfModal() {
  7312. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7313. }
  7314. function copyWGClientConf() {
  7315. if (!currentWGClientConf) return;
  7316. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7317. }
  7318. function downloadWGClientConf() {
  7319. if (!currentWGClientConf) return;
  7320. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7321. const a = document.createElement('a');
  7322. a.href = URL.createObjectURL(blob);
  7323. a.download = 'wireguard-client.conf';
  7324. document.body.appendChild(a);
  7325. a.click();
  7326. document.body.removeChild(a);
  7327. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7328. }
  7329. // =========================================================================
  7330. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7331. // =========================================================================
  7332. state.activeDynSubTab = 'bgp-peers';
  7333. state.activeBgpSubTab = 'bgp-peers';
  7334. state.activeOspfTab = 'instances';
  7335. state.bgpInstance = null;
  7336. state.bgpPeers = [];
  7337. state.bgpNets = [];
  7338. state.bgpRoutes = [];
  7339. state.ospfInstance = null;
  7340. state.ospfInstances = [];
  7341. state.ospfAreas = [];
  7342. state.ospfAreaRanges = [];
  7343. state.ospfTemplates = [];
  7344. state.ospfLiveInterfaces = [];
  7345. state.ospfStaticNbrs = [];
  7346. state.ospfNeighbors = [];
  7347. state.ospfLSA = [];
  7348. state.ospfRoutes = [];
  7349. state.selectedOspfRow = {
  7350. instances: null,
  7351. areas: null,
  7352. 'area-ranges': null,
  7353. templates: null,
  7354. interfaces: null,
  7355. 'static-nbrs': null,
  7356. neighbors: null,
  7357. lsa: null,
  7358. };
  7359. state.ospfSort = {
  7360. instances: { col: 'name', asc: true },
  7361. areas: { col: 'name', asc: true },
  7362. ranges: { col: 'area', asc: true },
  7363. templates: { col: 'interfaces', asc: true },
  7364. live_ifaces: { col: 'interface', asc: true },
  7365. snbrs: { col: 'address', asc: true },
  7366. neighbors: { col: 'address', asc: true },
  7367. lsa: { col: 'instance', asc: true },
  7368. };
  7369. function switchBgpSubTab(subTab) {
  7370. state.activeBgpSubTab = subTab;
  7371. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7372. tabs.forEach(t => {
  7373. const el = document.getElementById(`dyn-subtab-${t}`);
  7374. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7375. if (el) el.classList.toggle('hidden', t !== subTab);
  7376. if (btn) {
  7377. if (t === subTab) {
  7378. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-purple-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  7379. } else {
  7380. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  7381. }
  7382. }
  7383. });
  7384. }
  7385. function switchOspfTab(tabName) {
  7386. state.activeOspfTab = tabName;
  7387. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7388. tabs.forEach(t => {
  7389. const pane = document.getElementById(`ospf-pane-${t}`);
  7390. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7391. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7392. if (btn) {
  7393. if (t === tabName) {
  7394. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7395. } else {
  7396. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7397. }
  7398. }
  7399. });
  7400. }
  7401. function switchOspfSubTab(tab) {
  7402. // Legacy alias
  7403. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7404. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7405. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7406. else switchOspfTab('instances');
  7407. }
  7408. function switchDynSubTab(subTab) {
  7409. if (subTab.startsWith('bgp')) {
  7410. if (state.activeTab !== 'bgp') navigate('bgp');
  7411. switchBgpSubTab(subTab);
  7412. } else if (subTab.startsWith('ospf')) {
  7413. if (state.activeTab !== 'ospf') navigate('ospf');
  7414. switchOspfTab('instances');
  7415. }
  7416. }
  7417. async function loadDynamicRouting(showToastMsg = false) {
  7418. try {
  7419. const fetchSafeJson = async (url) => {
  7420. try {
  7421. const r = await fetch(url);
  7422. return r.ok ? await r.json() : null;
  7423. } catch (e) {
  7424. return null;
  7425. }
  7426. };
  7427. const [
  7428. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7429. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7430. selectRules, commLists, asLists
  7431. ] = await Promise.all([
  7432. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7433. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7434. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7435. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7436. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7437. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7438. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7439. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7440. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7441. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7442. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7443. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7444. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7445. fetchSafeJson(`${API_BASE}/routing/filters`),
  7446. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7447. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7448. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7449. ]);
  7450. if (sum) state.dynSummary = sum;
  7451. if (bgpInst) state.bgpInstance = bgpInst;
  7452. if (bgpPeers) state.bgpPeers = bgpPeers;
  7453. if (bgpNets) state.bgpNets = bgpNets;
  7454. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7455. if (ospfInsts) state.ospfInstances = ospfInsts;
  7456. if (ospfAreas) state.ospfAreas = ospfAreas;
  7457. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7458. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7459. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7460. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7461. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7462. if (ospfLsa) state.ospfLSA = ospfLsa;
  7463. if (filters) state.routingFilters = filters;
  7464. if (selectRules) state.routingSelectRules = selectRules;
  7465. if (commLists) state.routingCommunityLists = commLists;
  7466. if (asLists) state.routingASLists = asLists;
  7467. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7468. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7469. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7470. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7471. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7472. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7473. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7474. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7475. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7476. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7477. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7478. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7479. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7480. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7481. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7482. } catch (err) {
  7483. console.error('Failed to load dynamic routing:', err);
  7484. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7485. }
  7486. }
  7487. async function loadOspfAll() {
  7488. await loadDynamicRouting(true);
  7489. }
  7490. function renderBgpStatusPill() {
  7491. const pill = document.getElementById('bgp-live-status-pill');
  7492. if (!pill) return;
  7493. const inst = state.bgpInstance;
  7494. if (!inst || !inst.enabled) {
  7495. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7496. pill.innerText = 'BGP DISABLED';
  7497. } else if (inst.running) {
  7498. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  7499. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7500. } else {
  7501. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  7502. pill.innerText = 'BGP STARTING...';
  7503. }
  7504. }
  7505. function renderBgpPeers() {
  7506. const tbody = document.getElementById('bgp-peers-table-body');
  7507. if (!tbody) return;
  7508. const empty = document.getElementById('bgp-peers-empty');
  7509. const countBadge = document.getElementById('bgp-peers-count-badge');
  7510. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7511. const peers = state.bgpPeers || [];
  7512. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7513. if (navBadge) navBadge.innerText = peers.length;
  7514. if (peers.length === 0) {
  7515. tbody.innerHTML = '';
  7516. if (empty) empty.classList.remove('hidden');
  7517. return;
  7518. }
  7519. if (empty) empty.classList.add('hidden');
  7520. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7521. if (tbody.dataset.sig === sig) return;
  7522. tbody.dataset.sig = sig;
  7523. tbody.innerHTML = peers.map(p => {
  7524. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7525. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7526. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7527. let stateBadge = '';
  7528. if (p.disabled) {
  7529. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>';
  7530. } else if (p.state === 'Established') {
  7531. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Established</span>';
  7532. } else if (p.state === 'Connect' || p.state === 'Active') {
  7533. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">${p.state}</span>`;
  7534. } else {
  7535. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">${p.state || 'Idle'}</span>`;
  7536. }
  7537. return `
  7538. <tr class="hover:bg-slate-800/40 transition">
  7539. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7540. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7541. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7542. <td class="py-2.5 px-3">
  7543. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7544. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  7545. </td>
  7546. <td class="py-2.5 px-3">${stateBadge}</td>
  7547. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7548. <td class="py-2.5 px-3 text-slate-300">
  7549. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7550. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7551. </td>
  7552. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7553. ${p.in_filter ? `<span class="px-1.5 py-0.5 rounded bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(p.in_filter)}</span> ` : ''}
  7554. ${p.out_filter ? `<span class="px-1.5 py-0.5 rounded bg-amber-950 text-amber-300 border border-amber-800/50" title="Out Filter">OUT: ${escapeHtml(p.out_filter)}</span>` : ''}
  7555. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7556. </td>
  7557. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7558. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7559. <button onclick="toggleBgpPeerState('${p.id}', ${!p.disabled})" class="px-2 py-1 rounded text-[11px] ${p.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  7560. ${p.disabled ? 'Enable' : 'Disable'}
  7561. </button>
  7562. <button onclick="openEditBgpPeerModal('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-purple-300 border border-slate-700">
  7563. Edit
  7564. </button>
  7565. <button onclick="deleteBgpPeer('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7566. Delete
  7567. </button>
  7568. </td>
  7569. </tr>
  7570. `;
  7571. }).join('');
  7572. }
  7573. function renderBgpNetworks() {
  7574. const tbody = document.getElementById('bgp-nets-table-body');
  7575. if (!tbody) return;
  7576. const empty = document.getElementById('bgp-nets-empty');
  7577. const countBadge = document.getElementById('bgp-nets-count-badge');
  7578. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7579. const nets = state.bgpNets || [];
  7580. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7581. if (navBadge) navBadge.innerText = nets.length;
  7582. if (nets.length === 0) {
  7583. tbody.innerHTML = '';
  7584. if (empty) empty.classList.remove('hidden');
  7585. return;
  7586. }
  7587. if (empty) empty.classList.add('hidden');
  7588. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7589. if (tbody.dataset.sig === sig) return;
  7590. tbody.dataset.sig = sig;
  7591. tbody.innerHTML = nets.map(n => `
  7592. <tr class="hover:bg-slate-800/40 transition">
  7593. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7594. <td class="py-2.5 px-3">
  7595. ${n.disabled
  7596. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7597. : '<span class="px-2 py-0.5 rounded-full text-[10px] bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Announcing</span>'}
  7598. </td>
  7599. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7600. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7601. <button onclick="deleteBgpNetwork('${n.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7602. Delete
  7603. </button>
  7604. </td>
  7605. </tr>
  7606. `).join('');
  7607. }
  7608. function renderBgpRoutes() {
  7609. const tbody = document.getElementById('bgp-routes-table-body');
  7610. if (!tbody) return;
  7611. const empty = document.getElementById('bgp-routes-empty');
  7612. const countBadge = document.getElementById('bgp-routes-count-badge');
  7613. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7614. const routes = state.bgpRoutes || [];
  7615. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7616. if (navBadge) navBadge.innerText = routes.length;
  7617. if (routes.length === 0) {
  7618. tbody.innerHTML = '';
  7619. if (empty) empty.classList.remove('hidden');
  7620. return;
  7621. }
  7622. if (empty) empty.classList.add('hidden');
  7623. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7624. if (tbody.dataset.sig === sig) return;
  7625. tbody.dataset.sig = sig;
  7626. tbody.innerHTML = routes.map(r => `
  7627. <tr class="hover:bg-slate-800/40 transition">
  7628. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7629. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7630. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7631. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7632. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7633. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7634. </tr>
  7635. `).join('');
  7636. }
  7637. // =========================================================================
  7638. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7639. // =========================================================================
  7640. function sortOspfTable(tab, col) {
  7641. if (!state.ospfSort) state.ospfSort = {};
  7642. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7643. if (state.ospfSort[tab].col === col) {
  7644. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7645. } else {
  7646. state.ospfSort[tab].col = col;
  7647. state.ospfSort[tab].asc = true;
  7648. }
  7649. const asc = state.ospfSort[tab].asc;
  7650. let list = [];
  7651. if (tab === 'instances') list = state.ospfInstances || [];
  7652. else if (tab === 'areas') list = state.ospfAreas || [];
  7653. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7654. else if (tab === 'templates') list = state.ospfTemplates || [];
  7655. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7656. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7657. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7658. else if (tab === 'lsa') list = state.ospfLSA || [];
  7659. list.sort((a, b) => {
  7660. let valA = a[col] ?? '';
  7661. let valB = b[col] ?? '';
  7662. if (typeof valA === 'number' && typeof valB === 'number') {
  7663. return asc ? valA - valB : valB - valA;
  7664. }
  7665. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7666. });
  7667. if (tab === 'instances') renderOspfInstances();
  7668. else if (tab === 'areas') renderOspfAreas();
  7669. else if (tab === 'ranges') renderOspfAreaRanges();
  7670. else if (tab === 'templates') renderOspfTemplates();
  7671. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7672. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7673. else if (tab === 'neighbors') renderOspfNeighbors();
  7674. else if (tab === 'lsa') renderOspfLSA();
  7675. }
  7676. function selectOspfRow(tab, id) {
  7677. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7678. state.selectedOspfRow[tab] = id;
  7679. if (tab === 'instances') {
  7680. renderOspfInstances();
  7681. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7682. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7683. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7684. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7685. if (btnEn) btnEn.disabled = false;
  7686. if (btnDis) btnDis.disabled = false;
  7687. if (btnRem) btnRem.disabled = false;
  7688. if (btnCom) btnCom.disabled = false;
  7689. } else if (tab === 'areas') {
  7690. renderOspfAreas();
  7691. const btnEn = document.getElementById('btn-ospf-area-enable');
  7692. const btnDis = document.getElementById('btn-ospf-area-disable');
  7693. const btnRem = document.getElementById('btn-ospf-area-remove');
  7694. const btnCom = document.getElementById('btn-ospf-area-comment');
  7695. if (btnEn) btnEn.disabled = false;
  7696. if (btnDis) btnDis.disabled = false;
  7697. if (btnRem) btnRem.disabled = false;
  7698. if (btnCom) btnCom.disabled = false;
  7699. } else if (tab === 'ranges') {
  7700. renderOspfAreaRanges();
  7701. const btnEn = document.getElementById('btn-ospf-range-enable');
  7702. const btnDis = document.getElementById('btn-ospf-range-disable');
  7703. const btnRem = document.getElementById('btn-ospf-range-remove');
  7704. const btnCom = document.getElementById('btn-ospf-range-comment');
  7705. if (btnEn) btnEn.disabled = false;
  7706. if (btnDis) btnDis.disabled = false;
  7707. if (btnRem) btnRem.disabled = false;
  7708. if (btnCom) btnCom.disabled = false;
  7709. } else if (tab === 'templates') {
  7710. renderOspfTemplates();
  7711. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7712. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7713. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7714. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7715. if (btnEn) btnEn.disabled = false;
  7716. if (btnDis) btnDis.disabled = false;
  7717. if (btnRem) btnRem.disabled = false;
  7718. if (btnCom) btnCom.disabled = false;
  7719. } else if (tab === 'snbrs') {
  7720. renderOspfStaticNbrs();
  7721. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7722. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7723. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7724. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7725. if (btnEn) btnEn.disabled = false;
  7726. if (btnDis) btnDis.disabled = false;
  7727. if (btnRem) btnRem.disabled = false;
  7728. if (btnCom) btnCom.disabled = false;
  7729. }
  7730. }
  7731. // TAB 1: INSTANCES
  7732. function renderOspfInstances() {
  7733. const tbody = document.getElementById('ospf-instances-table-body');
  7734. if (!tbody) return;
  7735. const countEl = document.getElementById('ospf-instances-footer-count');
  7736. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7737. let list = state.ospfInstances || [];
  7738. if (filter) {
  7739. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7740. }
  7741. if (countEl) countEl.innerText = list.length;
  7742. const selId = state.selectedOspfRow?.instances;
  7743. tbody.innerHTML = list.map((inst, idx) => {
  7744. const isSel = inst.id === selId;
  7745. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7746. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7747. return `
  7748. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7749. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7750. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7751. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7752. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7753. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7754. </td>
  7755. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7756. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7757. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7758. </tr>
  7759. `;
  7760. }).join('');
  7761. }
  7762. // TAB 2: AREAS
  7763. function renderOspfAreas() {
  7764. const tbody = document.getElementById('ospf-areas-table-body');
  7765. if (!tbody) return;
  7766. const countEl = document.getElementById('ospf-areas-footer-count');
  7767. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7768. let list = state.ospfAreas || [];
  7769. if (filter) {
  7770. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7771. }
  7772. if (countEl) countEl.innerText = list.length;
  7773. const selId = state.selectedOspfRow?.areas;
  7774. tbody.innerHTML = list.map((a, idx) => {
  7775. const isSel = a.id === selId;
  7776. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7777. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7778. return `
  7779. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7780. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7781. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7782. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7783. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7784. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7785. </td>
  7786. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7787. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7788. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7789. </tr>
  7790. `;
  7791. }).join('');
  7792. }
  7793. // TAB 3: AREA RANGES
  7794. function renderOspfAreaRanges() {
  7795. const tbody = document.getElementById('ospf-ranges-table-body');
  7796. if (!tbody) return;
  7797. const countEl = document.getElementById('ospf-ranges-footer-count');
  7798. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7799. let list = state.ospfAreaRanges || [];
  7800. if (filter) {
  7801. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7802. }
  7803. if (countEl) countEl.innerText = list.length;
  7804. const selId = state.selectedOspfRow?.['area-ranges'];
  7805. tbody.innerHTML = list.map((r, idx) => {
  7806. const isSel = r.id === selId;
  7807. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7808. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7809. return `
  7810. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7811. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7812. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7813. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7814. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7815. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7816. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7817. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7818. </tr>
  7819. `;
  7820. }).join('');
  7821. }
  7822. // TAB 4: INTERFACE TEMPLATES
  7823. function renderOspfTemplates() {
  7824. const tbody = document.getElementById('ospf-templates-table-body');
  7825. if (!tbody) return;
  7826. const countEl = document.getElementById('ospf-templates-footer-count');
  7827. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7828. let list = state.ospfTemplates || [];
  7829. if (filter) {
  7830. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7831. }
  7832. if (countEl) countEl.innerText = list.length;
  7833. const selId = state.selectedOspfRow?.templates;
  7834. tbody.innerHTML = list.map((t, idx) => {
  7835. const isSel = t.id === selId;
  7836. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7837. const ifaces = t.interfaces || t.interface || 'all';
  7838. const nets = t.networks || t.network || '';
  7839. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7840. return `
  7841. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7842. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7843. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7844. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7845. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7846. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7847. </td>
  7848. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7849. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7850. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7851. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7852. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7853. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7854. </tr>
  7855. `;
  7856. }).join('');
  7857. }
  7858. // TAB 5: LIVE INTERFACES
  7859. function renderOspfLiveInterfaces() {
  7860. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7861. if (!tbody) return;
  7862. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7863. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7864. let list = state.ospfLiveInterfaces || [];
  7865. if (filter) {
  7866. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7867. }
  7868. if (countEl) countEl.innerText = list.length;
  7869. tbody.innerHTML = list.map(i => `
  7870. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7871. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7872. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7873. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7874. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7875. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7876. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7877. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7878. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7879. </tr>
  7880. `).join('');
  7881. }
  7882. // TAB 6: STATIC NEIGHBORS
  7883. function renderOspfStaticNbrs() {
  7884. const tbody = document.getElementById('ospf-snbrs-table-body');
  7885. if (!tbody) return;
  7886. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7887. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7888. let list = state.ospfStaticNbrs || [];
  7889. if (filter) {
  7890. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7891. }
  7892. if (countEl) countEl.innerText = list.length;
  7893. const selId = state.selectedOspfRow?.['static-nbrs'];
  7894. tbody.innerHTML = list.map((n, idx) => {
  7895. const isSel = n.id === selId;
  7896. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7897. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7898. return `
  7899. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7900. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7901. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7902. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7903. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7904. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7905. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7906. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7907. </tr>
  7908. `;
  7909. }).join('');
  7910. }
  7911. // TAB 7: LIVE NEIGHBORS
  7912. function renderOspfNeighbors() {
  7913. const tbody = document.getElementById('ospf-neighbors-table-body');
  7914. if (!tbody) return;
  7915. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7916. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7917. let list = state.ospfNeighbors || [];
  7918. if (filter) {
  7919. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7920. }
  7921. if (countEl) countEl.innerText = list.length;
  7922. tbody.innerHTML = list.map(n => `
  7923. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7924. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7925. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7926. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7927. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7928. </td>
  7929. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7930. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7931. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7932. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7933. </tr>
  7934. `).join('');
  7935. }
  7936. // TAB 8: LINK-STATE DATABASE (LSA)
  7937. function renderOspfLSA() {
  7938. const tbody = document.getElementById('ospf-lsa-table-body');
  7939. if (!tbody) return;
  7940. const countEl = document.getElementById('ospf-lsa-footer-count');
  7941. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7942. let list = state.ospfLSA || [];
  7943. if (filter) {
  7944. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7945. }
  7946. if (countEl) countEl.innerText = list.length;
  7947. tbody.innerHTML = list.map(l => `
  7948. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7949. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7950. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7951. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7952. </td>
  7953. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7954. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7955. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7956. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7957. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7958. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7959. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7960. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7961. </tr>
  7962. `).join('');
  7963. }
  7964. function renderOspfStatusPill() {
  7965. // Maintained for backward compatibility
  7966. const pill = document.getElementById('ospf-live-status-pill');
  7967. if (!pill) return;
  7968. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-indigo-950 text-indigo-300 border border-indigo-800/60 font-semibold';
  7969. pill.innerText = 'OSPF ACTIVE';
  7970. }
  7971. function renderOspfInterfaces() {
  7972. renderOspfTemplates();
  7973. }
  7974. function renderOspfRoutes() {
  7975. // Routes retained in background
  7976. }
  7977. // BGP Modals & Actions
  7978. function openBgpInstanceModal() {
  7979. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7980. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7981. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7982. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7983. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7984. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7985. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7986. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7987. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7988. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7989. }
  7990. function closeBgpInstanceModal() {
  7991. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7992. }
  7993. async function submitBgpInstance(e) {
  7994. e.preventDefault();
  7995. const payload = {
  7996. enabled: document.getElementById('modal-bgp-enabled').checked,
  7997. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7998. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7999. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8000. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8001. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8002. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8003. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8004. };
  8005. try {
  8006. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8007. method: 'POST',
  8008. headers: { 'Content-Type': 'application/json' },
  8009. body: JSON.stringify(payload)
  8010. });
  8011. if (res.ok) {
  8012. closeBgpInstanceModal();
  8013. showToast('Success', 'BGP instance configuration updated', 'success');
  8014. loadDynamicRouting();
  8015. } else {
  8016. const err = await res.json();
  8017. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8018. }
  8019. } catch (err) {
  8020. showToast('Error', err.message, 'error');
  8021. }
  8022. }
  8023. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8024. function switchBgpPeerModalTab(tab) {
  8025. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8026. tabs.forEach(t => {
  8027. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8028. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8029. if (t === tab) {
  8030. if (pane) pane.classList.remove('hidden');
  8031. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8032. } else {
  8033. if (pane) pane.classList.add('hidden');
  8034. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8035. }
  8036. });
  8037. }
  8038. function addOutputNetworkRow(val = '') {
  8039. const container = document.getElementById('modal-bgp-output-networks-container');
  8040. if (!container) return;
  8041. const row = document.createElement('div');
  8042. row.className = 'flex items-center gap-2 output-net-row';
  8043. row.innerHTML = `
  8044. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  8045. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  8046. `;
  8047. container.appendChild(row);
  8048. }
  8049. function parseBgpTime(val) {
  8050. if (!val) return 0;
  8051. val = String(val).trim();
  8052. if (val.includes(':')) {
  8053. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8054. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8055. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8056. }
  8057. return parseInt(val, 10) || 0;
  8058. }
  8059. function formatBgpTime(secs) {
  8060. if (!secs || secs <= 0) return '00:00:00';
  8061. const h = Math.floor(secs / 3600);
  8062. const m = Math.floor((secs % 3600) / 60);
  8063. const s = secs % 60;
  8064. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8065. }
  8066. function populateBgpRoutingTables() {
  8067. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8068. if (!sel) return;
  8069. const cur = sel.value || 'main';
  8070. sel.innerHTML = '<option value="main">main</option>';
  8071. (state.routingTables || []).forEach(t => {
  8072. if (t.name !== 'main') {
  8073. const opt = document.createElement('option');
  8074. opt.value = t.name;
  8075. opt.innerText = t.name;
  8076. sel.appendChild(opt);
  8077. }
  8078. });
  8079. sel.value = cur;
  8080. }
  8081. function openAddBgpPeerModal() {
  8082. document.getElementById('bgp-peer-form').reset();
  8083. document.getElementById('modal-bgp-peer-id').value = '';
  8084. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8085. // General Tab
  8086. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8087. document.getElementById('modal-bgp-peer-comment').value = '';
  8088. document.getElementById('modal-bgp-peer-name').value = '';
  8089. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8090. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8091. document.getElementById('modal-bgp-peer-local-as').value = '';
  8092. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8093. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8094. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8095. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8096. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8097. document.getElementById('modal-bgp-peer-router-id').value = '';
  8098. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8099. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8100. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8101. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8102. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8103. document.getElementById('modal-bgp-peer-local-port').value = '';
  8104. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8105. document.getElementById('modal-bgp-peer-password').value = '';
  8106. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8107. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8108. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8109. document.getElementById('modal-bgp-peer-connect').checked = true;
  8110. document.getElementById('modal-bgp-peer-listen').checked = true;
  8111. // Extra Tab
  8112. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8113. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8114. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8115. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8116. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8117. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8118. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8119. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8120. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8121. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8122. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8123. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8124. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8125. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8126. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8127. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8128. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8129. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8130. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8131. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8132. // Attributes Tab
  8133. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8134. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8135. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8136. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8137. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8138. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8139. // Filter Tab
  8140. populateFilterChainsDatalist();
  8141. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8142. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8143. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8144. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8145. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8146. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8147. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8148. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8149. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8150. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8151. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8152. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8153. populateBgpRoutingTables();
  8154. const container = document.getElementById('modal-bgp-output-networks-container');
  8155. if (container) {
  8156. container.innerHTML = '';
  8157. addOutputNetworkRow('');
  8158. }
  8159. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8160. if (removeBtn) removeBtn.classList.add('hidden');
  8161. switchBgpPeerModalTab('general');
  8162. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8163. }
  8164. function populateFilterChainsDatalist() {
  8165. const dl = document.getElementById('filter-chains-list');
  8166. if (!dl) return;
  8167. const chains = new Set();
  8168. (state.routingFilters || []).forEach(f => {
  8169. if (f.chain) chains.add(f.chain);
  8170. });
  8171. if (chains.size === 0) {
  8172. chains.add('awmn');
  8173. chains.add('bgp-in');
  8174. chains.add('bgp-out');
  8175. }
  8176. dl.innerHTML = '';
  8177. chains.forEach(c => {
  8178. const opt = document.createElement('option');
  8179. opt.value = c;
  8180. dl.appendChild(opt);
  8181. });
  8182. }
  8183. function openEditBgpPeerModal(id) {
  8184. const p = (state.bgpPeers || []).find(item => item.id === id);
  8185. if (!p) return;
  8186. populateBgpRoutingTables();
  8187. populateFilterChainsDatalist();
  8188. document.getElementById('modal-bgp-peer-id').value = p.id;
  8189. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8190. // General Tab
  8191. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8192. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8193. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8194. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8195. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8196. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8197. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8198. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8199. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8200. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8201. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8202. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8203. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8204. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8205. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8206. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8207. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8208. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8209. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8210. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8211. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8212. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8213. // Extra Tab
  8214. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8215. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8216. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8217. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8218. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8219. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8220. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8221. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8222. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8223. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8224. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8225. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8226. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8227. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  8228. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8229. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8230. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8231. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8232. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8233. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8234. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8235. // Attributes Tab
  8236. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8237. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8238. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8239. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  8240. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8241. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8242. // Filter Tab
  8243. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8244. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8245. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8246. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  8247. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  8248. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8249. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  8250. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  8251. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8252. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8253. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8254. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8255. // Output Networks
  8256. const container = document.getElementById('modal-bgp-output-networks-container');
  8257. if (container) {
  8258. container.innerHTML = '';
  8259. if (p.output_networks && p.output_networks.length > 0) {
  8260. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8261. } else {
  8262. addOutputNetworkRow('');
  8263. }
  8264. }
  8265. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8266. if (removeBtn) removeBtn.classList.remove('hidden');
  8267. switchBgpPeerModalTab('general');
  8268. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8269. }
  8270. function copyCurrentBgpPeer() {
  8271. document.getElementById('modal-bgp-peer-id').value = '';
  8272. const nameEl = document.getElementById('modal-bgp-peer-name');
  8273. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8274. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8275. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8276. if (removeBtn) removeBtn.classList.add('hidden');
  8277. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8278. }
  8279. function removeCurrentBgpPeer() {
  8280. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8281. if (!id) return;
  8282. deleteBgpPeer(id);
  8283. closeBgpPeerModal();
  8284. }
  8285. function closeBgpPeerModal() {
  8286. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8287. }
  8288. function getBgpPeerFormData() {
  8289. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8290. const outputNetworks = [];
  8291. netInputs.forEach(inp => {
  8292. const v = inp.value.trim();
  8293. if (v) outputNetworks.push(v);
  8294. });
  8295. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8296. return {
  8297. id: document.getElementById('modal-bgp-peer-id').value,
  8298. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8299. enabled: enabled,
  8300. disabled: !enabled,
  8301. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8302. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8303. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8304. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8305. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8306. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8307. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8308. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8309. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8310. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8311. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8312. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8313. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8314. password: document.getElementById('modal-bgp-peer-password').value,
  8315. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8316. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8317. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8318. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8319. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8320. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8321. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8322. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8323. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8324. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8325. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8326. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8327. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8328. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8329. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8330. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8331. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8332. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8333. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8334. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8335. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8336. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8337. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8338. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8339. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8340. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8341. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8342. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8343. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8344. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8345. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8346. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8347. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8348. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8349. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8350. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8351. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8352. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8353. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8354. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8355. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8356. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8357. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8358. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8359. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8360. output_networks: outputNetworks
  8361. };
  8362. }
  8363. async function submitBgpPeer(e) {
  8364. if (e) e.preventDefault();
  8365. const payload = getBgpPeerFormData();
  8366. try {
  8367. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8368. method: 'POST',
  8369. headers: { 'Content-Type': 'application/json' },
  8370. body: JSON.stringify(payload)
  8371. });
  8372. if (res.ok) {
  8373. closeBgpPeerModal();
  8374. showToast('Success', 'BGP Connection saved', 'success');
  8375. loadDynamicRouting();
  8376. } else {
  8377. const err = await res.json();
  8378. showToast('Error', err.error || 'Failed to save peer', 'error');
  8379. }
  8380. } catch (err) {
  8381. showToast('Error', err.message, 'error');
  8382. }
  8383. }
  8384. async function applyBgpPeerModal(e) {
  8385. if (e) e.preventDefault();
  8386. const payload = getBgpPeerFormData();
  8387. try {
  8388. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8389. method: 'POST',
  8390. headers: { 'Content-Type': 'application/json' },
  8391. body: JSON.stringify(payload)
  8392. });
  8393. if (res.ok) {
  8394. const data = await res.json();
  8395. if (data.peer && data.peer.id) {
  8396. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8397. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8398. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8399. }
  8400. showToast('Applied', 'BGP Connection applied', 'success');
  8401. loadDynamicRouting();
  8402. } else {
  8403. const err = await res.json();
  8404. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8405. }
  8406. } catch (err) {
  8407. showToast('Error', err.message, 'error');
  8408. }
  8409. }
  8410. async function deleteBgpPeer(id) {
  8411. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8412. try {
  8413. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8414. if (res.ok) {
  8415. showToast('Deleted', 'BGP peer removed', 'success');
  8416. loadDynamicRouting();
  8417. }
  8418. } catch (err) {
  8419. showToast('Error', err.message, 'error');
  8420. }
  8421. }
  8422. async function toggleBgpPeerState(id, disabled) {
  8423. try {
  8424. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8425. method: 'POST',
  8426. headers: { 'Content-Type': 'application/json' },
  8427. body: JSON.stringify({ disabled })
  8428. });
  8429. if (res.ok) {
  8430. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8431. loadDynamicRouting();
  8432. }
  8433. } catch (err) {
  8434. showToast('Error', err.message, 'error');
  8435. }
  8436. }
  8437. function openAddBgpNetworkModal() {
  8438. document.getElementById('bgp-network-form').reset();
  8439. document.getElementById('modal-bgp-net-id').value = '';
  8440. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8441. }
  8442. function closeBgpNetworkModal() {
  8443. document.getElementById('bgp-network-modal').classList.add('hidden');
  8444. }
  8445. async function submitBgpNetwork(e) {
  8446. e.preventDefault();
  8447. const payload = {
  8448. id: document.getElementById('modal-bgp-net-id').value,
  8449. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8450. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8451. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8452. };
  8453. try {
  8454. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8455. method: 'POST',
  8456. headers: { 'Content-Type': 'application/json' },
  8457. body: JSON.stringify(payload)
  8458. });
  8459. if (res.ok) {
  8460. closeBgpNetworkModal();
  8461. showToast('Success', 'BGP network advertisement saved', 'success');
  8462. loadDynamicRouting();
  8463. } else {
  8464. const err = await res.json();
  8465. showToast('Error', err.error || 'Failed to save network', 'error');
  8466. }
  8467. } catch (err) {
  8468. showToast('Error', err.message, 'error');
  8469. }
  8470. }
  8471. async function deleteBgpNetwork(id) {
  8472. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8473. try {
  8474. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8475. if (res.ok) {
  8476. showToast('Deleted', 'Network advertisement removed', 'success');
  8477. loadDynamicRouting();
  8478. }
  8479. } catch (err) {
  8480. showToast('Error', err.message, 'error');
  8481. }
  8482. }
  8483. // =========================================================================
  8484. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8485. // =========================================================================
  8486. // --- 1. OSPF INSTANCE ---
  8487. function openOspfInstanceModal(id = null) {
  8488. const isEdit = !!id;
  8489. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8490. id: '',
  8491. name: 'Default',
  8492. version: 2,
  8493. vrf: 'main',
  8494. router_id: '192.168.131.56',
  8495. routing_table: 'main',
  8496. enabled: true,
  8497. redistribute_connected: false,
  8498. redistribute_static: true,
  8499. redistribute_bgp: false,
  8500. comment: ''
  8501. };
  8502. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8503. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8504. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8505. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8506. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8507. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8508. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8509. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8510. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8511. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8512. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8513. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8514. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8515. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8516. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8517. }
  8518. function openEditOspfInstanceModal(id) {
  8519. openOspfInstanceModal(id);
  8520. }
  8521. function closeOspfInstanceModal() {
  8522. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8523. }
  8524. async function submitOspfInstance(e) {
  8525. if (e) e.preventDefault();
  8526. const payload = {
  8527. id: document.getElementById('modal-ospf-inst-id').value,
  8528. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8529. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8530. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8531. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8532. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8533. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8534. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8535. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8536. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8537. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8538. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8539. };
  8540. try {
  8541. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8542. method: 'POST',
  8543. headers: { 'Content-Type': 'application/json' },
  8544. body: JSON.stringify(payload)
  8545. });
  8546. if (res.ok) {
  8547. closeOspfInstanceModal();
  8548. showToast('Saved', 'OSPF instance updated', 'success');
  8549. loadDynamicRouting();
  8550. } else {
  8551. const err = await res.json();
  8552. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8553. }
  8554. } catch (err) {
  8555. showToast('Error', err.message, 'error');
  8556. }
  8557. }
  8558. function applyOspfInstanceForm() {
  8559. submitOspfInstance(null);
  8560. }
  8561. function copyOspfInstance() {
  8562. document.getElementById('modal-ospf-inst-id').value = '';
  8563. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8564. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8565. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8566. }
  8567. async function deleteCurrentOspfInstance() {
  8568. const id = document.getElementById('modal-ospf-inst-id').value;
  8569. if (!id) return;
  8570. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8571. try {
  8572. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8573. if (res.ok) {
  8574. closeOspfInstanceModal();
  8575. showToast('Removed', 'OSPF instance deleted', 'success');
  8576. loadDynamicRouting();
  8577. }
  8578. } catch (err) {
  8579. showToast('Error', err.message, 'error');
  8580. }
  8581. }
  8582. async function enableSelectedOspfInstance() {
  8583. const id = state.selectedOspfRow?.instances;
  8584. if (!id) return;
  8585. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8586. method: 'POST',
  8587. headers: { 'Content-Type': 'application/json' },
  8588. body: JSON.stringify({ disabled: false })
  8589. });
  8590. loadDynamicRouting();
  8591. }
  8592. async function disableSelectedOspfInstance() {
  8593. const id = state.selectedOspfRow?.instances;
  8594. if (!id) return;
  8595. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8596. method: 'POST',
  8597. headers: { 'Content-Type': 'application/json' },
  8598. body: JSON.stringify({ disabled: true })
  8599. });
  8600. loadDynamicRouting();
  8601. }
  8602. async function removeSelectedOspfInstance() {
  8603. const id = state.selectedOspfRow?.instances;
  8604. if (!id) return;
  8605. if (!confirm('Delete selected OSPF instance?')) return;
  8606. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8607. loadDynamicRouting();
  8608. }
  8609. async function promptCommentOspfInstance() {
  8610. const id = state.selectedOspfRow?.instances;
  8611. if (!id) return;
  8612. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8613. if (!inst) return;
  8614. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8615. if (comment === null) return;
  8616. inst.comment = comment;
  8617. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8618. method: 'POST',
  8619. headers: { 'Content-Type': 'application/json' },
  8620. body: JSON.stringify(inst)
  8621. });
  8622. loadDynamicRouting();
  8623. }
  8624. // --- 2. OSPF AREA ---
  8625. function populateOspfAreaDropdowns() {
  8626. const instSelect = document.getElementById('modal-ospf-area-instance');
  8627. if (instSelect) {
  8628. const cur = instSelect.value;
  8629. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8630. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8631. if (cur) instSelect.value = cur;
  8632. }
  8633. }
  8634. function openOspfAreaModal(id = null) {
  8635. const isEdit = !!id;
  8636. populateOspfAreaDropdowns();
  8637. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8638. id: '',
  8639. name: 'Default',
  8640. instance: 'Default',
  8641. area_id: '0.0.0.0',
  8642. area_type: 'default',
  8643. default_cost: 1,
  8644. no_summaries: false,
  8645. disabled: false,
  8646. comment: ''
  8647. };
  8648. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8649. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8650. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8651. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8652. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8653. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8654. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8655. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8656. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8657. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8658. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8659. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8660. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8661. }
  8662. function openEditOspfAreaModal(id) {
  8663. openOspfAreaModal(id);
  8664. }
  8665. function closeOspfAreaModal() {
  8666. document.getElementById('ospf-area-modal').classList.add('hidden');
  8667. }
  8668. async function submitOspfArea(e) {
  8669. if (e) e.preventDefault();
  8670. const payload = {
  8671. id: document.getElementById('modal-ospf-area-id').value,
  8672. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8673. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8674. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8675. area_type: document.getElementById('modal-ospf-area-type').value,
  8676. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8677. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8678. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8679. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8680. };
  8681. try {
  8682. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8683. method: 'POST',
  8684. headers: { 'Content-Type': 'application/json' },
  8685. body: JSON.stringify(payload)
  8686. });
  8687. if (res.ok) {
  8688. closeOspfAreaModal();
  8689. showToast('Saved', 'OSPF area saved', 'success');
  8690. loadDynamicRouting();
  8691. } else {
  8692. const err = await res.json();
  8693. showToast('Error', err.error || 'Failed to save area', 'error');
  8694. }
  8695. } catch (err) {
  8696. showToast('Error', err.message, 'error');
  8697. }
  8698. }
  8699. function applyOspfAreaForm() {
  8700. submitOspfArea(null);
  8701. }
  8702. function copyOspfArea() {
  8703. document.getElementById('modal-ospf-area-id').value = '';
  8704. document.getElementById('modal-ospf-area-name').value += '-copy';
  8705. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8706. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8707. }
  8708. async function deleteCurrentOspfArea() {
  8709. const id = document.getElementById('modal-ospf-area-id').value;
  8710. if (!id) return;
  8711. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8712. try {
  8713. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8714. if (res.ok) {
  8715. closeOspfAreaModal();
  8716. showToast('Removed', 'OSPF area deleted', 'success');
  8717. loadDynamicRouting();
  8718. }
  8719. } catch (err) {
  8720. showToast('Error', err.message, 'error');
  8721. }
  8722. }
  8723. async function enableSelectedOspfArea() {
  8724. const id = state.selectedOspfRow?.areas;
  8725. if (!id) return;
  8726. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8727. method: 'POST',
  8728. headers: { 'Content-Type': 'application/json' },
  8729. body: JSON.stringify({ disabled: false })
  8730. });
  8731. loadDynamicRouting();
  8732. }
  8733. async function disableSelectedOspfArea() {
  8734. const id = state.selectedOspfRow?.areas;
  8735. if (!id) return;
  8736. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8737. method: 'POST',
  8738. headers: { 'Content-Type': 'application/json' },
  8739. body: JSON.stringify({ disabled: true })
  8740. });
  8741. loadDynamicRouting();
  8742. }
  8743. async function removeSelectedOspfArea() {
  8744. const id = state.selectedOspfRow?.areas;
  8745. if (!id) return;
  8746. if (!confirm('Delete selected OSPF area?')) return;
  8747. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8748. loadDynamicRouting();
  8749. }
  8750. async function promptCommentOspfArea() {
  8751. const id = state.selectedOspfRow?.areas;
  8752. if (!id) return;
  8753. const area = (state.ospfAreas || []).find(a => a.id === id);
  8754. if (!area) return;
  8755. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8756. if (comment === null) return;
  8757. area.comment = comment;
  8758. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8759. method: 'POST',
  8760. headers: { 'Content-Type': 'application/json' },
  8761. body: JSON.stringify(area)
  8762. });
  8763. loadDynamicRouting();
  8764. }
  8765. // --- 3. OSPF AREA RANGE ---
  8766. function populateAreaRangeDropdowns() {
  8767. const select = document.getElementById('modal-ospf-range-area');
  8768. if (select) {
  8769. const cur = select.value;
  8770. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8771. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8772. if (cur) select.value = cur;
  8773. }
  8774. }
  8775. function openOspfAreaRangeModal(id = null) {
  8776. const isEdit = !!id;
  8777. populateAreaRangeDropdowns();
  8778. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8779. id: '',
  8780. area: 'Default',
  8781. prefix: '',
  8782. cost: 1,
  8783. advertise: true,
  8784. disabled: false,
  8785. comment: ''
  8786. };
  8787. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8788. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8789. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8790. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8791. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8792. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8793. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8794. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8795. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8796. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8797. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8798. }
  8799. function openEditOspfAreaRangeModal(id) {
  8800. openOspfAreaRangeModal(id);
  8801. }
  8802. function closeOspfAreaRangeModal() {
  8803. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8804. }
  8805. async function submitOspfAreaRange(e) {
  8806. if (e) e.preventDefault();
  8807. const payload = {
  8808. id: document.getElementById('modal-ospf-range-id').value,
  8809. area: document.getElementById('modal-ospf-range-area').value,
  8810. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8811. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8812. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8813. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8814. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8815. };
  8816. try {
  8817. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8818. method: 'POST',
  8819. headers: { 'Content-Type': 'application/json' },
  8820. body: JSON.stringify(payload)
  8821. });
  8822. if (res.ok) {
  8823. closeOspfAreaRangeModal();
  8824. showToast('Saved', 'Area range saved', 'success');
  8825. loadDynamicRouting();
  8826. } else {
  8827. const err = await res.json();
  8828. showToast('Error', err.error || 'Failed to save area range', 'error');
  8829. }
  8830. } catch (err) {
  8831. showToast('Error', err.message, 'error');
  8832. }
  8833. }
  8834. function applyOspfAreaRangeForm() {
  8835. submitOspfAreaRange(null);
  8836. }
  8837. async function deleteCurrentOspfAreaRange() {
  8838. const id = document.getElementById('modal-ospf-range-id').value;
  8839. if (!id) return;
  8840. if (!confirm('Delete this area range?')) return;
  8841. try {
  8842. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8843. closeOspfAreaRangeModal();
  8844. showToast('Removed', 'Area range removed', 'success');
  8845. loadDynamicRouting();
  8846. } catch (err) {
  8847. showToast('Error', err.message, 'error');
  8848. }
  8849. }
  8850. async function enableSelectedOspfAreaRange() {
  8851. const id = state.selectedOspfRow?.['area-ranges'];
  8852. if (!id) return;
  8853. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8854. if (!r) return;
  8855. r.disabled = false;
  8856. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8857. loadDynamicRouting();
  8858. }
  8859. async function disableSelectedOspfAreaRange() {
  8860. const id = state.selectedOspfRow?.['area-ranges'];
  8861. if (!id) return;
  8862. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8863. if (!r) return;
  8864. r.disabled = true;
  8865. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8866. loadDynamicRouting();
  8867. }
  8868. async function removeSelectedOspfAreaRange() {
  8869. const id = state.selectedOspfRow?.['area-ranges'];
  8870. if (!id) return;
  8871. if (!confirm('Delete selected area range?')) return;
  8872. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8873. loadDynamicRouting();
  8874. }
  8875. async function promptCommentOspfAreaRange() {
  8876. const id = state.selectedOspfRow?.['area-ranges'];
  8877. if (!id) return;
  8878. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8879. if (!r) return;
  8880. const comment = prompt('Enter comment for area range:', r.comment || '');
  8881. if (comment === null) return;
  8882. r.comment = comment;
  8883. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8884. loadDynamicRouting();
  8885. }
  8886. // --- 4. OSPF INTERFACE TEMPLATE ---
  8887. function switchOspfTemplateTab(tab) {
  8888. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8889. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8890. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8891. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8892. if (tab === 'general') {
  8893. if (tabGen) tabGen.classList.remove('hidden');
  8894. if (tabAuth) tabAuth.classList.add('hidden');
  8895. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8896. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8897. } else {
  8898. if (tabGen) tabGen.classList.add('hidden');
  8899. if (tabAuth) tabAuth.classList.remove('hidden');
  8900. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8901. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8902. }
  8903. }
  8904. function populateTemplateAreaDropdowns() {
  8905. const select = document.getElementById('modal-ospf-tmpl-area');
  8906. if (select) {
  8907. const cur = select.value;
  8908. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8909. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8910. if (cur) select.value = cur;
  8911. }
  8912. }
  8913. function openOspfTemplateModal(id = null) {
  8914. const isEdit = !!id;
  8915. populateTemplateAreaDropdowns();
  8916. switchOspfTemplateTab('general');
  8917. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8918. id: '',
  8919. interfaces: '',
  8920. area: 'Default',
  8921. networks: '',
  8922. network_type: 'broadcast',
  8923. cost: 1,
  8924. priority: 128,
  8925. passive: false,
  8926. hello_interval: 10,
  8927. dead_interval: 40,
  8928. auth: 'none',
  8929. auth_key: '',
  8930. disabled: false,
  8931. comment: ''
  8932. };
  8933. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8934. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8935. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8936. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8937. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8938. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8939. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8940. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8941. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8942. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8943. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8944. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8945. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8946. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8947. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8948. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8949. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8950. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8951. }
  8952. function openEditOspfTemplateModal(id) {
  8953. openOspfTemplateModal(id);
  8954. }
  8955. function closeOspfTemplateModal() {
  8956. document.getElementById('ospf-template-modal').classList.add('hidden');
  8957. }
  8958. async function submitOspfTemplate(e) {
  8959. if (e) e.preventDefault();
  8960. const payload = {
  8961. id: document.getElementById('modal-ospf-tmpl-id').value,
  8962. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8963. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8964. area: document.getElementById('modal-ospf-tmpl-area').value,
  8965. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8966. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8967. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8968. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8969. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8970. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8971. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8972. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8973. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8974. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8975. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8976. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8977. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8978. };
  8979. try {
  8980. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8981. method: 'POST',
  8982. headers: { 'Content-Type': 'application/json' },
  8983. body: JSON.stringify(payload)
  8984. });
  8985. if (res.ok) {
  8986. closeOspfTemplateModal();
  8987. showToast('Saved', 'Interface template saved', 'success');
  8988. loadDynamicRouting();
  8989. } else {
  8990. const err = await res.json();
  8991. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8992. }
  8993. } catch (err) {
  8994. showToast('Error', err.message, 'error');
  8995. }
  8996. }
  8997. function applyOspfTemplateForm() {
  8998. submitOspfTemplate(null);
  8999. }
  9000. function copyOspfTemplate() {
  9001. document.getElementById('modal-ospf-tmpl-id').value = '';
  9002. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9003. showToast('Copied', 'Duplicated as new template', 'info');
  9004. }
  9005. async function deleteCurrentOspfTemplate() {
  9006. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9007. if (!id) return;
  9008. if (!confirm('Delete this interface template?')) return;
  9009. try {
  9010. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9011. closeOspfTemplateModal();
  9012. showToast('Removed', 'Interface template deleted', 'success');
  9013. loadDynamicRouting();
  9014. } catch (err) {
  9015. showToast('Error', err.message, 'error');
  9016. }
  9017. }
  9018. async function enableSelectedOspfTemplate() {
  9019. const id = state.selectedOspfRow?.templates;
  9020. if (!id) return;
  9021. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9022. method: 'POST',
  9023. headers: { 'Content-Type': 'application/json' },
  9024. body: JSON.stringify({ disabled: false })
  9025. });
  9026. loadDynamicRouting();
  9027. }
  9028. async function disableSelectedOspfTemplate() {
  9029. const id = state.selectedOspfRow?.templates;
  9030. if (!id) return;
  9031. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9032. method: 'POST',
  9033. headers: { 'Content-Type': 'application/json' },
  9034. body: JSON.stringify({ disabled: true })
  9035. });
  9036. loadDynamicRouting();
  9037. }
  9038. async function removeSelectedOspfTemplate() {
  9039. const id = state.selectedOspfRow?.templates;
  9040. if (!id) return;
  9041. if (!confirm('Delete selected interface template?')) return;
  9042. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9043. loadDynamicRouting();
  9044. }
  9045. async function promptCommentOspfTemplate() {
  9046. const id = state.selectedOspfRow?.templates;
  9047. if (!id) return;
  9048. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9049. if (!tmpl) return;
  9050. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9051. if (comment === null) return;
  9052. tmpl.comment = comment;
  9053. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9054. method: 'POST',
  9055. headers: { 'Content-Type': 'application/json' },
  9056. body: JSON.stringify(tmpl)
  9057. });
  9058. loadDynamicRouting();
  9059. }
  9060. // --- 5. OSPF STATIC NEIGHBOR ---
  9061. function populateStaticNbrAreaDropdowns() {
  9062. const select = document.getElementById('modal-ospf-snbr-area');
  9063. if (select) {
  9064. const cur = select.value;
  9065. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9066. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9067. if (cur) select.value = cur;
  9068. }
  9069. }
  9070. function openOspfStaticNbrModal(id = null) {
  9071. const isEdit = !!id;
  9072. populateStaticNbrAreaDropdowns();
  9073. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9074. id: '',
  9075. address: '',
  9076. area: 'Default',
  9077. poll_interval: 120,
  9078. cost: 1,
  9079. disabled: false,
  9080. comment: ''
  9081. };
  9082. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9083. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9084. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9085. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9086. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9087. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9088. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9089. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9090. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9091. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9092. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9093. }
  9094. function openEditOspfStaticNbrModal(id) {
  9095. openOspfStaticNbrModal(id);
  9096. }
  9097. function closeOspfStaticNbrModal() {
  9098. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9099. }
  9100. async function submitOspfStaticNbr(e) {
  9101. if (e) e.preventDefault();
  9102. const payload = {
  9103. id: document.getElementById('modal-ospf-snbr-id').value,
  9104. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9105. area: document.getElementById('modal-ospf-snbr-area').value,
  9106. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9107. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9108. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9109. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9110. };
  9111. try {
  9112. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9113. method: 'POST',
  9114. headers: { 'Content-Type': 'application/json' },
  9115. body: JSON.stringify(payload)
  9116. });
  9117. if (res.ok) {
  9118. closeOspfStaticNbrModal();
  9119. showToast('Saved', 'Static neighbor saved', 'success');
  9120. loadDynamicRouting();
  9121. } else {
  9122. const err = await res.json();
  9123. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9124. }
  9125. } catch (err) {
  9126. showToast('Error', err.message, 'error');
  9127. }
  9128. }
  9129. function applyOspfStaticNbrForm() {
  9130. submitOspfStaticNbr(null);
  9131. }
  9132. async function deleteCurrentOspfStaticNbr() {
  9133. const id = document.getElementById('modal-ospf-snbr-id').value;
  9134. if (!id) return;
  9135. if (!confirm('Delete this static neighbor?')) return;
  9136. try {
  9137. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9138. closeOspfStaticNbrModal();
  9139. showToast('Removed', 'Static neighbor removed', 'success');
  9140. loadDynamicRouting();
  9141. } catch (err) {
  9142. showToast('Error', err.message, 'error');
  9143. }
  9144. }
  9145. async function enableSelectedOspfStaticNbr() {
  9146. const id = state.selectedOspfRow?.['static-nbrs'];
  9147. if (!id) return;
  9148. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9149. if (!n) return;
  9150. n.disabled = false;
  9151. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9152. loadDynamicRouting();
  9153. }
  9154. async function disableSelectedOspfStaticNbr() {
  9155. const id = state.selectedOspfRow?.['static-nbrs'];
  9156. if (!id) return;
  9157. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9158. if (!n) return;
  9159. n.disabled = true;
  9160. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9161. loadDynamicRouting();
  9162. }
  9163. async function removeSelectedOspfStaticNbr() {
  9164. const id = state.selectedOspfRow?.['static-nbrs'];
  9165. if (!id) return;
  9166. if (!confirm('Delete selected static neighbor?')) return;
  9167. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9168. loadDynamicRouting();
  9169. }
  9170. async function promptCommentOspfStaticNbr() {
  9171. const id = state.selectedOspfRow?.['static-nbrs'];
  9172. if (!id) return;
  9173. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9174. if (!n) return;
  9175. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9176. if (comment === null) return;
  9177. n.comment = comment;
  9178. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9179. loadDynamicRouting();
  9180. }
  9181. // Backward-compat aliases
  9182. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9183. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9184. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9185. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9186. function deleteOspfInterface(id) {
  9187. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9188. }
  9189. function toggleOspfInterfaceState(id, disabled) {
  9190. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9191. method: 'POST',
  9192. headers: { 'Content-Type': 'application/json' },
  9193. body: JSON.stringify({ disabled })
  9194. }).then(() => loadDynamicRouting());
  9195. }
  9196. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9197. function deleteOspfArea(id) {
  9198. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9199. }
  9200. // ============================================================================
  9201. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9202. // ============================================================================
  9203. function switchBridgeSubTab(tab) {
  9204. state.bridgeSubTab = tab;
  9205. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9206. tabs.forEach(t => {
  9207. const panel = document.getElementById(`bridge-subtab-${t}`);
  9208. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9209. if (panel) {
  9210. if (t === tab) panel.classList.remove('hidden');
  9211. else panel.classList.add('hidden');
  9212. }
  9213. if (btn) {
  9214. if (t === tab) {
  9215. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg bg-slate-800 text-white shadow-sm transition flex items-center gap-2';
  9216. } else {
  9217. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  9218. }
  9219. }
  9220. });
  9221. const addBtn = document.getElementById('bridge-top-action-btn');
  9222. if (addBtn) {
  9223. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9224. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9225. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9226. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9227. }
  9228. if (tab === 'hosts') loadBridgeHosts();
  9229. setTimeout(initTableSorting, 50);
  9230. }
  9231. function openCurrentBridgeModal() {
  9232. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9233. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9234. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9235. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9236. }
  9237. async function loadBridge() {
  9238. try {
  9239. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9240. fetch(`${API_BASE}/bridge/bridges`),
  9241. fetch(`${API_BASE}/bridge/ports`),
  9242. fetch(`${API_BASE}/bridge/vlans`),
  9243. fetch(`${API_BASE}/bridge/summary`),
  9244. fetch(`${API_BASE}/vpn/eoip`),
  9245. fetch(`${API_BASE}/vlans`)
  9246. ]);
  9247. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9248. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9249. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9250. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9251. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9252. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9253. // Badges & Stats
  9254. const bBridges = document.getElementById('bridge-badge-bridges');
  9255. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9256. const bPorts = document.getElementById('bridge-badge-ports');
  9257. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9258. const bVlans = document.getElementById('bridge-badge-vlans');
  9259. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9260. const bHosts = document.getElementById('bridge-badge-hosts');
  9261. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9262. const sBr = document.getElementById('bridge-stat-bridges');
  9263. if (sBr) sBr.innerText = (state.bridges || []).length;
  9264. const sPorts = document.getElementById('bridge-stat-ports');
  9265. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9266. const sHosts = document.getElementById('bridge-stat-hosts');
  9267. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9268. renderBridges();
  9269. renderBridgePorts();
  9270. renderBridgeVLANs();
  9271. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9272. } catch (err) {
  9273. console.error('Failed to load bridge subsystem:', err);
  9274. }
  9275. }
  9276. // ----------------- Bridges -----------------
  9277. function renderBridges() {
  9278. const tbody = document.getElementById('bridge-table-body');
  9279. const empty = document.getElementById('bridge-empty-bridges');
  9280. const countBadge = document.getElementById('bridge-count-badge');
  9281. if (!tbody) return;
  9282. tbody.innerHTML = '';
  9283. const bridges = state.bridges || [];
  9284. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9285. if (bridges.length === 0) {
  9286. empty?.classList.remove('hidden');
  9287. return;
  9288. }
  9289. empty?.classList.add('hidden');
  9290. bridges.forEach((b, idx) => {
  9291. const tr = document.createElement('tr');
  9292. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9293. // Format IP addresses pill list
  9294. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9295. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9296. ipsHtml = b.ip_addresses.map(ip => `
  9297. <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-mono bg-sky-950/80 border border-sky-800/40 text-sky-300">
  9298. <span>${ip}</span>
  9299. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9300. </span>
  9301. `).join(' ');
  9302. }
  9303. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9304. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9305. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9306. tr.innerHTML = `
  9307. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9308. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9309. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9310. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9311. </td>
  9312. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9313. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9314. <td class="py-2.5 px-3">
  9315. <span class="px-1.5 py-0.5 rounded text-[10px] font-bold ${b.stp === 'none' ? 'bg-slate-800 text-slate-400' : 'bg-sky-950 text-sky-300 border border-sky-800/40'} uppercase">${b.stp}</span>
  9316. </td>
  9317. <td class="py-2.5 px-3 text-center">
  9318. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9319. </td>
  9320. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9321. <td class="py-2.5 px-3">
  9322. <span class="px-2 py-0.5 rounded-full text-[10px] font-bold ${b.ports_count > 0 ? 'bg-sky-950 text-sky-400 border border-sky-800/40' : 'bg-slate-800 text-slate-500'} font-mono">${b.ports_count}</span>
  9323. </td>
  9324. <td class="py-2.5 px-3">
  9325. <div class="flex items-center gap-1.5 flex-wrap">
  9326. ${ipsHtml}
  9327. <button onclick="openAddBridgeIPModal('${b.id}', '${b.name}')" class="px-1.5 py-0.2 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 font-sans" title="Add IP to Bridge">+ IP</button>
  9328. </div>
  9329. </td>
  9330. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9331. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9332. </td>
  9333. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9334. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9335. <button onclick="toggleBridgeState('${b.id}', ${!b.disabled})" class="text-xs ${b.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${b.disabled ? 'Enable' : 'Disable'}</button>
  9336. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9337. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9338. </td>
  9339. `;
  9340. tbody.appendChild(tr);
  9341. });
  9342. }
  9343. function openAddBridgeModal() {
  9344. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9345. document.getElementById('bridge-modal-id').value = '';
  9346. document.getElementById('bridge-modal-name').value = 'bridge1';
  9347. document.getElementById('bridge-modal-name').disabled = false;
  9348. document.getElementById('bridge-modal-mtu').value = '1500';
  9349. document.getElementById('bridge-modal-mac').value = '';
  9350. document.getElementById('bridge-modal-stp').value = 'rstp';
  9351. document.getElementById('bridge-modal-priority').value = '32768';
  9352. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9353. document.getElementById('bridge-modal-pvid').value = '1';
  9354. document.getElementById('bridge-modal-fastforward').checked = true;
  9355. document.getElementById('bridge-modal-comment').value = '';
  9356. document.getElementById('bridge-modal-disabled').checked = false;
  9357. toggleBridgeModalVlanFiltering();
  9358. document.getElementById('bridge-modal').classList.remove('hidden');
  9359. }
  9360. function openEditBridgeModal(id) {
  9361. const b = (state.bridges || []).find(x => x.id === id);
  9362. if (!b) return;
  9363. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9364. document.getElementById('bridge-modal-id').value = b.id;
  9365. document.getElementById('bridge-modal-name').value = b.name;
  9366. document.getElementById('bridge-modal-name').disabled = true;
  9367. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9368. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9369. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9370. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9371. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9372. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9373. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9374. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9375. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9376. toggleBridgeModalVlanFiltering();
  9377. document.getElementById('bridge-modal').classList.remove('hidden');
  9378. }
  9379. function closeBridgeModal() {
  9380. document.getElementById('bridge-modal').classList.add('hidden');
  9381. }
  9382. function toggleBridgeModalVlanFiltering() {
  9383. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9384. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9385. if (pvidBox) {
  9386. if (chk) pvidBox.classList.remove('opacity-40');
  9387. else pvidBox.classList.add('opacity-40');
  9388. }
  9389. }
  9390. async function submitSaveBridge(e) {
  9391. e.preventDefault();
  9392. const id = document.getElementById('bridge-modal-id').value;
  9393. const name = document.getElementById('bridge-modal-name').value.trim();
  9394. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9395. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9396. const stp = document.getElementById('bridge-modal-stp').value;
  9397. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9398. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9399. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9400. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9401. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9402. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9403. try {
  9404. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9405. method: 'POST',
  9406. headers: { 'Content-Type': 'application/json' },
  9407. body: JSON.stringify({
  9408. id,
  9409. name,
  9410. mtu,
  9411. mac_address: mac,
  9412. stp,
  9413. priority,
  9414. vlan_filtering: vlanFiltering,
  9415. pvid,
  9416. fast_forward: fastForward,
  9417. comment,
  9418. disabled
  9419. })
  9420. });
  9421. if (res.ok) {
  9422. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9423. closeBridgeModal();
  9424. loadBridge();
  9425. fetchData(false);
  9426. } else {
  9427. const err = await res.json();
  9428. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9429. }
  9430. } catch (err) {
  9431. showToast('Error', err.message, 'error');
  9432. }
  9433. }
  9434. async function toggleBridgeState(id, disabled) {
  9435. try {
  9436. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9437. method: 'POST',
  9438. headers: { 'Content-Type': 'application/json' },
  9439. body: JSON.stringify({ disabled })
  9440. });
  9441. if (res.ok) {
  9442. loadBridge();
  9443. fetchData(false);
  9444. }
  9445. } catch (err) {
  9446. showToast('Error', err.message, 'error');
  9447. }
  9448. }
  9449. async function deleteBridge(id) {
  9450. const b = (state.bridges || []).find(x => x.id === id);
  9451. const name = b ? b.name : id;
  9452. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9453. try {
  9454. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9455. if (res.ok) {
  9456. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9457. loadBridge();
  9458. fetchData(false);
  9459. } else {
  9460. const err = await res.json();
  9461. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9462. }
  9463. } catch (err) {
  9464. showToast('Error', err.message, 'error');
  9465. }
  9466. }
  9467. // ----------------- Bridge IP Assignments -----------------
  9468. function openAddBridgeIPModal(id, name) {
  9469. document.getElementById('bridge-ip-modal-id').value = id;
  9470. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9471. document.getElementById('bridge-ip-modal-cidr').value = '';
  9472. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9473. }
  9474. function closeBridgeIPModal() {
  9475. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9476. }
  9477. async function submitAddBridgeIP(e) {
  9478. e.preventDefault();
  9479. const id = document.getElementById('bridge-ip-modal-id').value;
  9480. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9481. try {
  9482. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9483. method: 'POST',
  9484. headers: { 'Content-Type': 'application/json' },
  9485. body: JSON.stringify({ ip })
  9486. });
  9487. if (res.ok) {
  9488. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9489. closeBridgeIPModal();
  9490. loadBridge();
  9491. fetchData(false);
  9492. } else {
  9493. const err = await res.json();
  9494. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9495. }
  9496. } catch (err) {
  9497. showToast('Error', err.message, 'error');
  9498. }
  9499. }
  9500. async function deleteBridgeIP(id, ip) {
  9501. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9502. try {
  9503. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9504. method: 'DELETE',
  9505. headers: { 'Content-Type': 'application/json' },
  9506. body: JSON.stringify({ ip })
  9507. });
  9508. if (res.ok) {
  9509. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9510. loadBridge();
  9511. fetchData(false);
  9512. }
  9513. } catch (err) {
  9514. showToast('Error', err.message, 'error');
  9515. }
  9516. }
  9517. // ----------------- Bridge Ports -----------------
  9518. function renderBridgePorts() {
  9519. const tbody = document.getElementById('bridge-ports-table-body');
  9520. const empty = document.getElementById('bridge-empty-ports');
  9521. const countBadge = document.getElementById('bridge-ports-count-badge');
  9522. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9523. if (!tbody) return;
  9524. tbody.innerHTML = '';
  9525. // Update filter select
  9526. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9527. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9528. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9529. if (ports.length === 0) {
  9530. empty?.classList.remove('hidden');
  9531. return;
  9532. }
  9533. empty?.classList.add('hidden');
  9534. ports.forEach((p, idx) => {
  9535. const tr = document.createElement('tr');
  9536. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9537. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9538. tr.innerHTML = `
  9539. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9540. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9541. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9542. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9543. </td>
  9544. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9545. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9546. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9547. <td class="py-2.5 px-3 text-center">${p.ingress_filtering ? '<span class="text-amber-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  9548. <td class="py-2.5 px-3">
  9549. ${p.horizon > 0 ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">domain ${p.horizon}</span>` : '<span class="text-slate-500">none</span>'}
  9550. </td>
  9551. <td class="py-2.5 px-3">
  9552. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${p.status === 'forwarding' ? 'bg-emerald-950 text-emerald-400 border border-emerald-800/40' : 'bg-slate-800 text-slate-400'} uppercase font-mono">${p.status}</span>
  9553. </td>
  9554. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9555. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9556. <button onclick="toggleBridgePortState('${p.id}', ${!p.disabled})" class="text-xs ${p.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${p.disabled ? 'Enable' : 'Disable'}</button>
  9557. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9558. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9559. </td>
  9560. `;
  9561. tbody.appendChild(tr);
  9562. });
  9563. }
  9564. function openAddBridgePortModal() {
  9565. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9566. document.getElementById('bridge-port-modal-id').value = '';
  9567. populateBridgeSelect('bridge-port-modal-bridge');
  9568. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9569. document.getElementById('bridge-port-modal-pvid').value = '1';
  9570. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9571. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9572. document.getElementById('bridge-port-modal-horizon').value = '0';
  9573. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9574. document.getElementById('bridge-port-modal-priority').value = '128';
  9575. document.getElementById('bridge-port-modal-learn').checked = true;
  9576. document.getElementById('bridge-port-modal-comment').value = '';
  9577. document.getElementById('bridge-port-modal-disabled').checked = false;
  9578. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9579. }
  9580. function openEditBridgePortModal(id) {
  9581. const p = (state.bridgePorts || []).find(x => x.id === id);
  9582. if (!p) return;
  9583. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9584. document.getElementById('bridge-port-modal-id').value = p.id;
  9585. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9586. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9587. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9588. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9589. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9590. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9591. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9592. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9593. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9594. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9595. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9596. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9597. }
  9598. function closeBridgePortModal() {
  9599. document.getElementById('bridge-port-modal').classList.add('hidden');
  9600. }
  9601. async function submitSaveBridgePort(e) {
  9602. e.preventDefault();
  9603. const id = document.getElementById('bridge-port-modal-id').value;
  9604. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9605. const iface = document.getElementById('bridge-port-modal-interface').value;
  9606. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9607. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9608. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9609. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9610. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9611. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9612. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9613. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9614. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9615. try {
  9616. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9617. method: 'POST',
  9618. headers: { 'Content-Type': 'application/json' },
  9619. body: JSON.stringify({
  9620. id,
  9621. bridge,
  9622. interface: iface,
  9623. pvid,
  9624. frame_types: frameTypes,
  9625. ingress_filtering: ingressFiltering,
  9626. horizon,
  9627. path_cost: pathCost,
  9628. priority,
  9629. learn,
  9630. comment,
  9631. disabled
  9632. })
  9633. });
  9634. if (res.ok) {
  9635. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9636. closeBridgePortModal();
  9637. loadBridge();
  9638. fetchData(false);
  9639. } else {
  9640. const err = await res.json();
  9641. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9642. }
  9643. } catch (err) {
  9644. showToast('Error', err.message, 'error');
  9645. }
  9646. }
  9647. async function toggleBridgePortState(id, disabled) {
  9648. try {
  9649. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9650. method: 'POST',
  9651. headers: { 'Content-Type': 'application/json' },
  9652. body: JSON.stringify({ disabled })
  9653. });
  9654. if (res.ok) {
  9655. loadBridge();
  9656. fetchData(false);
  9657. }
  9658. } catch (err) {
  9659. showToast('Error', err.message, 'error');
  9660. }
  9661. }
  9662. async function deleteBridgePort(id) {
  9663. const p = (state.bridgePorts || []).find(x => x.id === id);
  9664. const iface = p ? p.interface : id;
  9665. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9666. try {
  9667. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9668. if (res.ok) {
  9669. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9670. loadBridge();
  9671. fetchData(false);
  9672. }
  9673. } catch (err) {
  9674. showToast('Error', err.message, 'error');
  9675. }
  9676. }
  9677. // ----------------- Bridge VLANs -----------------
  9678. function renderBridgeVLANs() {
  9679. const tbody = document.getElementById('bridge-vlans-table-body');
  9680. const empty = document.getElementById('bridge-empty-vlans');
  9681. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9682. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9683. if (!tbody) return;
  9684. tbody.innerHTML = '';
  9685. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9686. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9687. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9688. if (vlans.length === 0) {
  9689. empty?.classList.remove('hidden');
  9690. return;
  9691. }
  9692. empty?.classList.add('hidden');
  9693. vlans.forEach((v, idx) => {
  9694. const tr = document.createElement('tr');
  9695. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9696. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9697. ? v.tagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/80 border border-cyan-800/40 text-cyan-300 font-mono">${p}</span>`).join(' ')
  9698. : '<span class="text-slate-600">none</span>';
  9699. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9700. ? v.untagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700/60 text-slate-300 font-mono">${p}</span>`).join(' ')
  9701. : '<span class="text-slate-600">none</span>';
  9702. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9703. tr.innerHTML = `
  9704. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9705. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9706. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9707. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9708. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9709. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9710. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9711. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9712. <button onclick="toggleBridgeVLANState('${v.id}', ${!v.disabled})" class="text-xs ${v.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${v.disabled ? 'Enable' : 'Disable'}</button>
  9713. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9714. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9715. </td>
  9716. `;
  9717. tbody.appendChild(tr);
  9718. });
  9719. }
  9720. function openAddBridgeVLANModal() {
  9721. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9722. document.getElementById('bridge-vlan-modal-id').value = '';
  9723. populateBridgeSelect('bridge-vlan-modal-bridge');
  9724. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9725. document.getElementById('bridge-vlan-modal-comment').value = '';
  9726. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9727. updateBridgeVlanPortCheckboxes();
  9728. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9729. }
  9730. function openEditBridgeVLANModal(id) {
  9731. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9732. if (!v) return;
  9733. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9734. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9735. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9736. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9737. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9738. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9739. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9740. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9741. }
  9742. function closeBridgeVlanModal() {
  9743. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9744. }
  9745. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9746. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9747. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9748. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9749. if (!taggedBox || !untaggedBox) return;
  9750. // Ports belonging to the selected bridge
  9751. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9752. if (memberPorts.length === 0) {
  9753. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9754. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9755. return;
  9756. }
  9757. taggedBox.innerHTML = memberPorts.map(p => `
  9758. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9759. <input type="checkbox" name="bvlan-tagged" value="${p.interface}" ${taggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-cyan-500">
  9760. <span>${p.interface}</span>
  9761. </label>
  9762. `).join('');
  9763. untaggedBox.innerHTML = memberPorts.map(p => `
  9764. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9765. <input type="checkbox" name="bvlan-untagged" value="${p.interface}" ${untaggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-slate-400">
  9766. <span>${p.interface}</span>
  9767. </label>
  9768. `).join('');
  9769. }
  9770. async function submitSaveBridgeVLAN(e) {
  9771. e.preventDefault();
  9772. const id = document.getElementById('bridge-vlan-modal-id').value;
  9773. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9774. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9775. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9776. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9777. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9778. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9779. try {
  9780. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9781. method: 'POST',
  9782. headers: { 'Content-Type': 'application/json' },
  9783. body: JSON.stringify({
  9784. id,
  9785. bridge,
  9786. vlan_ids: vlanIDs,
  9787. tagged,
  9788. untagged,
  9789. comment,
  9790. disabled
  9791. })
  9792. });
  9793. if (res.ok) {
  9794. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9795. closeBridgeVlanModal();
  9796. loadBridge();
  9797. } else {
  9798. const err = await res.json();
  9799. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9800. }
  9801. } catch (err) {
  9802. showToast('Error', err.message, 'error');
  9803. }
  9804. }
  9805. async function toggleBridgeVLANState(id, disabled) {
  9806. try {
  9807. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9808. method: 'POST',
  9809. headers: { 'Content-Type': 'application/json' },
  9810. body: JSON.stringify({ disabled })
  9811. });
  9812. if (res.ok) loadBridge();
  9813. } catch (err) {
  9814. showToast('Error', err.message, 'error');
  9815. }
  9816. }
  9817. async function deleteBridgeVLAN(id) {
  9818. if (!confirm('Delete this bridge VLAN entry?')) return;
  9819. try {
  9820. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9821. if (res.ok) {
  9822. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9823. loadBridge();
  9824. }
  9825. } catch (err) {
  9826. showToast('Error', err.message, 'error');
  9827. }
  9828. }
  9829. // ----------------- Hosts / MAC Table -----------------
  9830. async function loadBridgeHosts() {
  9831. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9832. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9833. try {
  9834. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9835. const res = await fetch(url);
  9836. if (res.ok) {
  9837. state.bridgeHosts = await res.json();
  9838. renderBridgeHosts();
  9839. }
  9840. } catch (err) {
  9841. console.error('Failed to load bridge hosts:', err);
  9842. }
  9843. }
  9844. function renderBridgeHosts() {
  9845. const tbody = document.getElementById('bridge-hosts-table-body');
  9846. const empty = document.getElementById('bridge-empty-hosts');
  9847. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9848. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9849. if (!tbody) return;
  9850. tbody.innerHTML = '';
  9851. const hosts = (state.bridgeHosts || []).filter(h => {
  9852. if (!search) return true;
  9853. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9854. });
  9855. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9856. if (hosts.length === 0) {
  9857. empty?.classList.remove('hidden');
  9858. return;
  9859. }
  9860. empty?.classList.add('hidden');
  9861. hosts.forEach(h => {
  9862. const tr = document.createElement('tr');
  9863. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9864. let flagBadges = '';
  9865. if (h.local) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-sky-950 text-sky-400 border border-sky-800/40 font-mono font-bold mr-1" title="Local router interface MAC">L</span>';
  9866. if (h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-purple-950 text-purple-400 border border-purple-800/40 font-mono font-bold mr-1" title="Static entry">S</span>';
  9867. if (!h.local && !h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-emerald-950 text-emerald-400 border border-emerald-800/40 font-mono font-bold mr-1" title="Dynamically learned">D</span>';
  9868. tr.innerHTML = `
  9869. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9870. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9871. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9872. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9873. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9874. <td class="py-2.5 px-3">${flagBadges}</td>
  9875. `;
  9876. tbody.appendChild(tr);
  9877. });
  9878. }
  9879. async function flushBridgeHosts() {
  9880. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9881. if (!selBridge) {
  9882. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9883. return;
  9884. }
  9885. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9886. try {
  9887. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9888. method: 'POST',
  9889. headers: { 'Content-Type': 'application/json' },
  9890. body: JSON.stringify({ bridge: selBridge })
  9891. });
  9892. if (res.ok) {
  9893. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9894. loadBridgeHosts();
  9895. }
  9896. } catch (err) {
  9897. showToast('Error', err.message, 'error');
  9898. }
  9899. }
  9900. // ----------------- Helpers -----------------
  9901. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9902. const sel = document.getElementById(selectId);
  9903. if (!sel) return;
  9904. const prevVal = currentVal || sel.value;
  9905. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9906. (state.bridges || []).forEach(b => {
  9907. const opt = document.createElement('option');
  9908. opt.value = b.name;
  9909. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9910. if (b.name === prevVal) opt.selected = true;
  9911. sel.appendChild(opt);
  9912. });
  9913. }
  9914. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9915. const sel = document.getElementById(selectId);
  9916. if (!sel) return;
  9917. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9918. // 1. Physical Interfaces
  9919. const grpPhys = document.createElement('optgroup');
  9920. grpPhys.label = 'Physical Interfaces';
  9921. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9922. const opt = document.createElement('option');
  9923. opt.value = i.name;
  9924. opt.innerText = `${i.name} (${i.role || i.type})`;
  9925. if (i.name === currentVal) opt.selected = true;
  9926. grpPhys.appendChild(opt);
  9927. });
  9928. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9929. // 2. VLAN Sub-interfaces
  9930. const grpVlans = document.createElement('optgroup');
  9931. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9932. (state.vlans || []).forEach(v => {
  9933. const opt = document.createElement('option');
  9934. opt.value = v.name;
  9935. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9936. if (v.name === currentVal) opt.selected = true;
  9937. grpVlans.appendChild(opt);
  9938. });
  9939. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9940. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9941. const grpEoip = document.createElement('optgroup');
  9942. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9943. (state.eoipTunnels || []).forEach(t => {
  9944. const opt = document.createElement('option');
  9945. opt.value = t.name;
  9946. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9947. if (t.name === currentVal) opt.selected = true;
  9948. grpEoip.appendChild(opt);
  9949. });
  9950. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9951. }
  9952. // -------------------------------------------------------------
  9953. // RouterOS v7 Routing Filters Management (/routing filter)
  9954. // -------------------------------------------------------------
  9955. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9956. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9957. if (!state.rfSort) state.rfSort = {};
  9958. function switchRoutingFilterTab(tab) {
  9959. state.activeRoutingFilterTab = tab;
  9960. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9961. tabs.forEach(t => {
  9962. const btn = document.getElementById(`tab-rf-${t}`);
  9963. const content = document.getElementById(`tab-content-rf-${t}`);
  9964. if (btn) {
  9965. if (t === tab) {
  9966. btn.className = 'px-3 py-1 text-xs font-semibold rounded bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition shadow-sm';
  9967. } else {
  9968. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9969. }
  9970. }
  9971. if (content) {
  9972. if (t === tab) content.classList.remove('hidden');
  9973. else content.classList.add('hidden');
  9974. }
  9975. });
  9976. const chainContainer = document.getElementById('rf-chain-filter-container');
  9977. if (chainContainer) {
  9978. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9979. else chainContainer.classList.add('hidden');
  9980. }
  9981. renderRoutingFilters();
  9982. }
  9983. function selectFilterRow(tab, id) {
  9984. if (state.selectedFilterRow[tab] === id) {
  9985. delete state.selectedFilterRow[tab];
  9986. } else {
  9987. state.selectedFilterRow[tab] = id;
  9988. }
  9989. if (tab === 'rules') renderRoutingFilterRules();
  9990. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9991. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9992. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9993. }
  9994. function openRoutingFilterNewModal() {
  9995. const tab = state.activeRoutingFilterTab || 'rules';
  9996. if (tab === 'rules') openAddRoutingFilterModal();
  9997. else if (tab === 'select-rules') openAddSelectRuleModal();
  9998. else if (tab === 'community-lists') openAddCommunityListModal();
  9999. else if (tab === 'as-lists') openAddASListModal();
  10000. }
  10001. function toggleSelectedRoutingFilter(disabled) {
  10002. const tab = state.activeRoutingFilterTab || 'rules';
  10003. const id = state.selectedFilterRow[tab];
  10004. if (!id) {
  10005. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10006. return;
  10007. }
  10008. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10009. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10010. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10011. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10012. }
  10013. function removeSelectedRoutingFilter() {
  10014. const tab = state.activeRoutingFilterTab || 'rules';
  10015. const id = state.selectedFilterRow[tab];
  10016. if (!id) {
  10017. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10018. return;
  10019. }
  10020. if (tab === 'rules') deleteRoutingFilter(id);
  10021. else if (tab === 'select-rules') deleteSelectRule(id);
  10022. else if (tab === 'community-lists') deleteCommunityList(id);
  10023. else if (tab === 'as-lists') deleteASList(id);
  10024. }
  10025. function searchRoutingFilters(q) {
  10026. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10027. renderRoutingFilters();
  10028. }
  10029. function sortFilterTable(tab, col) {
  10030. if (!state.rfSort) state.rfSort = {};
  10031. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10032. if (state.rfSort[tab].col === col) {
  10033. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10034. } else {
  10035. state.rfSort[tab].col = col;
  10036. state.rfSort[tab].asc = true;
  10037. }
  10038. const asc = state.rfSort[tab].asc;
  10039. let list = [];
  10040. if (tab === 'rules') list = state.routingFilters || [];
  10041. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10042. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10043. else if (tab === 'as-lists') list = state.routingASLists || [];
  10044. list.sort((a, b) => {
  10045. let valA = a[col] ?? '';
  10046. let valB = b[col] ?? '';
  10047. if (col === 'flags') {
  10048. valA = a.disabled ? 'X' : 'A';
  10049. valB = b.disabled ? 'X' : 'A';
  10050. }
  10051. if (typeof valA === 'number' && typeof valB === 'number') {
  10052. return asc ? valA - valB : valB - valA;
  10053. }
  10054. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10055. });
  10056. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10057. allCols.forEach(c => {
  10058. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10059. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10060. });
  10061. if (tab === 'rules') renderRoutingFilterRules();
  10062. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10063. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10064. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10065. }
  10066. function renderRoutingFilters() {
  10067. const navBadge = document.getElementById('badge-filters-count');
  10068. const allRules = state.routingFilters || [];
  10069. if (navBadge) navBadge.innerText = allRules.length;
  10070. // Populate chain filter select options and datalist
  10071. const chainSelect = document.getElementById('routing-filter-chain-select');
  10072. const chainDatalist = document.getElementById('dl-routing-chains');
  10073. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10074. if (chainSelect) {
  10075. const currentVal = state.filterChainSelected || 'all';
  10076. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10077. uniqueChains.map(ch => {
  10078. const count = allRules.filter(r => r.chain === ch).length;
  10079. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10080. }).join('');
  10081. chainSelect.value = currentVal;
  10082. }
  10083. if (chainDatalist) {
  10084. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10085. }
  10086. renderRoutingFilterRules();
  10087. renderRoutingFilterSelectRules();
  10088. renderRoutingFilterCommunityLists();
  10089. renderRoutingFilterASLists();
  10090. }
  10091. function filterRoutingFiltersByChain(chain) {
  10092. state.filterChainSelected = chain;
  10093. renderRoutingFilters();
  10094. }
  10095. // -------------------------------------------------------------
  10096. // TAB 1: RULES (/routing filter rule)
  10097. // -------------------------------------------------------------
  10098. function renderRoutingFilterRules() {
  10099. const tbody = document.getElementById('routing-filter-rules-tbody');
  10100. if (!tbody) return;
  10101. const empty = document.getElementById('rf-rules-empty');
  10102. const statusCount = document.getElementById('rf-status-count');
  10103. let list = (state.routingFilters || []).slice();
  10104. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10105. list = list.filter(r => r.chain === state.filterChainSelected);
  10106. }
  10107. const q = state.rfSearchQuery;
  10108. if (q) {
  10109. list = list.filter(r =>
  10110. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10111. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10112. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10113. (r.comment && r.comment.toLowerCase().includes(q))
  10114. );
  10115. }
  10116. if (!state.rfSort?.['rules']) {
  10117. list.sort((a, b) => {
  10118. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10119. return (a.rule_order || 0) - (b.rule_order || 0);
  10120. });
  10121. }
  10122. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10123. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10124. }
  10125. if (list.length === 0) {
  10126. tbody.innerHTML = '';
  10127. if (empty) empty.classList.remove('hidden');
  10128. return;
  10129. }
  10130. if (empty) empty.classList.add('hidden');
  10131. tbody.innerHTML = list.map(r => {
  10132. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10133. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10134. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10135. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10136. let ruleDisplay = '';
  10137. if (r.rule && r.rule.trim() !== '') {
  10138. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10139. } else {
  10140. let conds = [];
  10141. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10142. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10143. let act = r.action || 'accept';
  10144. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10145. }
  10146. return `
  10147. <tr onclick="selectFilterRow('rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10148. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10149. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10150. <td class="py-2 px-3">
  10151. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  10152. </td>
  10153. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10154. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10155. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10156. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  10157. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  10158. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10159. ${r.disabled ? 'Enable' : 'Disable'}
  10160. </button>
  10161. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10162. Edit
  10163. </button>
  10164. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10165. ✕
  10166. </button>
  10167. </td>
  10168. </tr>
  10169. `;
  10170. }).join('');
  10171. }
  10172. // -------------------------------------------------------------
  10173. // TAB 2: SELECT RULES (/routing filter select-rule)
  10174. // -------------------------------------------------------------
  10175. function renderRoutingFilterSelectRules() {
  10176. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10177. if (!tbody) return;
  10178. const empty = document.getElementById('rf-select-rules-empty');
  10179. const statusCount = document.getElementById('rf-status-count');
  10180. let list = (state.routingSelectRules || []).slice();
  10181. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10182. list = list.filter(r => r.chain === state.filterChainSelected);
  10183. }
  10184. const q = state.rfSearchQuery;
  10185. if (q) {
  10186. list = list.filter(r =>
  10187. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10188. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10189. (r.comment && r.comment.toLowerCase().includes(q))
  10190. );
  10191. }
  10192. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10193. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10194. }
  10195. if (list.length === 0) {
  10196. tbody.innerHTML = '';
  10197. if (empty) empty.classList.remove('hidden');
  10198. return;
  10199. }
  10200. if (empty) empty.classList.add('hidden');
  10201. tbody.innerHTML = list.map(r => {
  10202. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10203. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10204. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10205. return `
  10206. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10207. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10208. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10209. <td class="py-2 px-3">
  10210. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  10211. </td>
  10212. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10213. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10214. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10215. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10216. ${r.disabled ? 'Enable' : 'Disable'}
  10217. </button>
  10218. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10219. Edit
  10220. </button>
  10221. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10222. ✕
  10223. </button>
  10224. </td>
  10225. </tr>
  10226. `;
  10227. }).join('');
  10228. }
  10229. // -------------------------------------------------------------
  10230. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10231. // -------------------------------------------------------------
  10232. function renderRoutingFilterCommunityLists() {
  10233. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10234. if (!tbody) return;
  10235. const empty = document.getElementById('rf-comm-lists-empty');
  10236. const statusCount = document.getElementById('rf-status-count');
  10237. let list = (state.routingCommunityLists || []).slice();
  10238. const q = state.rfSearchQuery;
  10239. if (q) {
  10240. list = list.filter(cl =>
  10241. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10242. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10243. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10244. );
  10245. }
  10246. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10247. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10248. }
  10249. if (list.length === 0) {
  10250. tbody.innerHTML = '';
  10251. if (empty) empty.classList.remove('hidden');
  10252. return;
  10253. }
  10254. if (empty) empty.classList.add('hidden');
  10255. tbody.innerHTML = list.map(cl => {
  10256. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10257. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10258. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10259. const commBadges = (cl.communities || []).map(c =>
  10260. `<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">${escapeHtml(c)}</span>`
  10261. ).join(' ');
  10262. return `
  10263. <tr onclick="selectFilterRow('community-lists', '${cl.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10264. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10265. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10266. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10267. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10268. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10269. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10270. <button onclick="toggleCommunityListState('${cl.id}', ${!cl.disabled})" class="px-2 py-0.5 rounded text-[10px] ${cl.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10271. ${cl.disabled ? 'Enable' : 'Disable'}
  10272. </button>
  10273. <button onclick="openEditCommunityListModal('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10274. Edit
  10275. </button>
  10276. <button onclick="deleteCommunityList('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10277. ✕
  10278. </button>
  10279. </td>
  10280. </tr>
  10281. `;
  10282. }).join('');
  10283. }
  10284. // -------------------------------------------------------------
  10285. // TAB 4: AS LISTS (/routing filter num-list)
  10286. // -------------------------------------------------------------
  10287. function renderRoutingFilterASLists() {
  10288. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10289. if (!tbody) return;
  10290. const empty = document.getElementById('rf-as-lists-empty');
  10291. const statusCount = document.getElementById('rf-status-count');
  10292. let list = (state.routingASLists || []).slice();
  10293. const q = state.rfSearchQuery;
  10294. if (q) {
  10295. list = list.filter(al =>
  10296. (al.name && al.name.toLowerCase().includes(q)) ||
  10297. (al.range && al.range.toLowerCase().includes(q)) ||
  10298. (al.comment && al.comment.toLowerCase().includes(q))
  10299. );
  10300. }
  10301. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10302. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10303. }
  10304. if (list.length === 0) {
  10305. tbody.innerHTML = '';
  10306. if (empty) empty.classList.remove('hidden');
  10307. return;
  10308. }
  10309. if (empty) empty.classList.add('hidden');
  10310. tbody.innerHTML = list.map(al => {
  10311. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10312. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10313. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10314. return `
  10315. <tr onclick="selectFilterRow('as-lists', '${al.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10316. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10317. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10318. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10319. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10320. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10321. <button onclick="toggleASListState('${al.id}', ${!al.disabled})" class="px-2 py-0.5 rounded text-[10px] ${al.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10322. ${al.disabled ? 'Enable' : 'Disable'}
  10323. </button>
  10324. <button onclick="openEditASListModal('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10325. Edit
  10326. </button>
  10327. <button onclick="deleteASList('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10328. ✕
  10329. </button>
  10330. </td>
  10331. </tr>
  10332. `;
  10333. }).join('');
  10334. }
  10335. // -------------------------------------------------------------
  10336. // SNIPPETS & WIZARD HELPERS
  10337. // -------------------------------------------------------------
  10338. function insertRuleSnippet(type) {
  10339. const textarea = document.getElementById('modal-rf-rule');
  10340. if (!textarea) return;
  10341. let snippet = '';
  10342. switch (type) {
  10343. case 'accept-default':
  10344. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10345. break;
  10346. case 'drop-rfc1918':
  10347. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10348. break;
  10349. case 'len-24':
  10350. snippet = 'if (dst-len > 24) { reject; }';
  10351. break;
  10352. case 'local-pref-150':
  10353. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10354. break;
  10355. case 'as-prepend-2':
  10356. snippet = 'set bgp-path-prepend 2; accept;';
  10357. break;
  10358. case 'set-comm':
  10359. snippet = 'set bgp-communities.add 65000:100; accept;';
  10360. break;
  10361. case 'match-comm':
  10362. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10363. break;
  10364. case 'reject-all':
  10365. snippet = 'reject;';
  10366. break;
  10367. }
  10368. if (!snippet) return;
  10369. if (!textarea.value.trim()) {
  10370. textarea.value = snippet;
  10371. } else {
  10372. textarea.value = textarea.value.trim() + '\n' + snippet;
  10373. }
  10374. }
  10375. function generateScriptFromWizard() {
  10376. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10377. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10378. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10379. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10380. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10381. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10382. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10383. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10384. const conds = [];
  10385. if (pfx) {
  10386. if (pfxLen) {
  10387. if (pfxLen.includes('-')) {
  10388. const parts = pfxLen.split('-');
  10389. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10390. } else {
  10391. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10392. }
  10393. } else {
  10394. conds.push(`dst in ${pfx}`);
  10395. }
  10396. }
  10397. if (proto && proto !== 'any') {
  10398. conds.push(`protocol ${proto}`);
  10399. }
  10400. if (asp) {
  10401. conds.push(`bgp-as-path "${asp}"`);
  10402. }
  10403. if (comm) {
  10404. conds.push(`bgp-communities includes ${comm}`);
  10405. }
  10406. const actions = [];
  10407. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10408. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10409. actions.push(`${act};`);
  10410. let code = '';
  10411. if (conds.length > 0) {
  10412. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10413. } else {
  10414. code = actions.join(' ');
  10415. }
  10416. const textarea = document.getElementById('modal-rf-rule');
  10417. if (textarea) textarea.value = code;
  10418. }
  10419. // -------------------------------------------------------------
  10420. // MODAL CRUD: RULES (/routing filter rule)
  10421. // -------------------------------------------------------------
  10422. function openAddRoutingFilterModal(defaultChain = '') {
  10423. const form = document.getElementById('routing-filter-form');
  10424. if (form) form.reset();
  10425. const idEl = document.getElementById('modal-rf-id');
  10426. if (idEl) idEl.value = '';
  10427. const titleEl = document.getElementById('modal-rf-title');
  10428. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10429. const chainEl = document.getElementById('modal-rf-chain');
  10430. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10431. const orderEl = document.getElementById('modal-rf-order');
  10432. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10433. const ruleEl = document.getElementById('modal-rf-rule');
  10434. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10435. const disEl = document.getElementById('modal-rf-disabled');
  10436. if (disEl) disEl.checked = false;
  10437. const modal = document.getElementById('modal-routing-filter');
  10438. if (modal) modal.classList.remove('hidden');
  10439. }
  10440. function openEditRoutingFilterModal(id) {
  10441. const r = (state.routingFilters || []).find(item => item.id === id);
  10442. if (!r) return;
  10443. const idEl = document.getElementById('modal-rf-id');
  10444. if (idEl) idEl.value = r.id;
  10445. const titleEl = document.getElementById('modal-rf-title');
  10446. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10447. const chainEl = document.getElementById('modal-rf-chain');
  10448. if (chainEl) chainEl.value = r.chain || '';
  10449. const orderEl = document.getElementById('modal-rf-order');
  10450. if (orderEl) orderEl.value = r.rule_order || 10;
  10451. const ruleEl = document.getElementById('modal-rf-rule');
  10452. if (ruleEl) {
  10453. if (r.rule) {
  10454. ruleEl.value = r.rule;
  10455. } else {
  10456. let conds = [];
  10457. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10458. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10459. let act = r.action || 'accept';
  10460. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10461. }
  10462. }
  10463. const comEl = document.getElementById('modal-rf-comment');
  10464. if (comEl) comEl.value = r.comment || '';
  10465. const disEl = document.getElementById('modal-rf-disabled');
  10466. if (disEl) disEl.checked = !!r.disabled;
  10467. const modal = document.getElementById('modal-routing-filter');
  10468. if (modal) modal.classList.remove('hidden');
  10469. }
  10470. function closeRoutingFilterModal() {
  10471. const modal = document.getElementById('modal-routing-filter');
  10472. if (modal) modal.classList.add('hidden');
  10473. }
  10474. async function submitRoutingFilter(e) {
  10475. if (e) e.preventDefault();
  10476. const payload = {
  10477. id: document.getElementById('modal-rf-id').value,
  10478. chain: document.getElementById('modal-rf-chain').value.trim(),
  10479. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10480. rule: document.getElementById('modal-rf-rule').value.trim(),
  10481. comment: document.getElementById('modal-rf-comment').value.trim(),
  10482. disabled: document.getElementById('modal-rf-disabled').checked
  10483. };
  10484. try {
  10485. const res = await fetch(`${API_BASE}/routing/filters`, {
  10486. method: 'POST',
  10487. headers: { 'Content-Type': 'application/json' },
  10488. body: JSON.stringify(payload)
  10489. });
  10490. if (res.ok) {
  10491. closeRoutingFilterModal();
  10492. showToast('Success', 'Routing filter rule saved', 'success');
  10493. loadDynamicRouting();
  10494. } else {
  10495. const err = await res.json();
  10496. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10497. }
  10498. } catch (err) {
  10499. showToast('Error', err.message, 'error');
  10500. }
  10501. }
  10502. async function applyRoutingFilterForm() {
  10503. const payload = {
  10504. id: document.getElementById('modal-rf-id').value,
  10505. chain: document.getElementById('modal-rf-chain').value.trim(),
  10506. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10507. rule: document.getElementById('modal-rf-rule').value.trim(),
  10508. comment: document.getElementById('modal-rf-comment').value.trim(),
  10509. disabled: document.getElementById('modal-rf-disabled').checked
  10510. };
  10511. try {
  10512. const res = await fetch(`${API_BASE}/routing/filters`, {
  10513. method: 'POST',
  10514. headers: { 'Content-Type': 'application/json' },
  10515. body: JSON.stringify(payload)
  10516. });
  10517. if (res.ok) {
  10518. const data = await res.json();
  10519. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10520. showToast('Applied', 'Routing filter configuration applied', 'success');
  10521. loadDynamicRouting();
  10522. } else {
  10523. const err = await res.json();
  10524. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10525. }
  10526. } catch (err) {
  10527. showToast('Error', err.message, 'error');
  10528. }
  10529. }
  10530. async function moveRoutingFilterOrder(id, delta) {
  10531. const list = state.routingFilters || [];
  10532. const idx = list.findIndex(r => r.id === id);
  10533. if (idx < 0) return;
  10534. const targetIdx = idx + delta;
  10535. if (targetIdx < 0 || targetIdx >= list.length) return;
  10536. const currentOrder = list[idx].rule_order || 10;
  10537. const targetOrder = list[targetIdx].rule_order || 20;
  10538. list[idx].rule_order = targetOrder;
  10539. list[targetIdx].rule_order = currentOrder;
  10540. try {
  10541. await fetch(`${API_BASE}/routing/filters`, {
  10542. method: 'POST',
  10543. headers: { 'Content-Type': 'application/json' },
  10544. body: JSON.stringify(list[idx])
  10545. });
  10546. await fetch(`${API_BASE}/routing/filters`, {
  10547. method: 'POST',
  10548. headers: { 'Content-Type': 'application/json' },
  10549. body: JSON.stringify(list[targetIdx])
  10550. });
  10551. loadDynamicRouting();
  10552. } catch (e) {
  10553. console.error('Reorder error:', e);
  10554. }
  10555. }
  10556. async function deleteRoutingFilter(id) {
  10557. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10558. try {
  10559. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10560. if (res.ok) {
  10561. showToast('Deleted', 'Routing filter rule removed', 'info');
  10562. loadDynamicRouting();
  10563. } else {
  10564. const err = await res.json();
  10565. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10566. }
  10567. } catch (err) {
  10568. showToast('Error', err.message, 'error');
  10569. }
  10570. }
  10571. async function toggleRoutingFilterState(id, disabled) {
  10572. try {
  10573. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10574. method: 'POST',
  10575. headers: { 'Content-Type': 'application/json' },
  10576. body: JSON.stringify({ disabled })
  10577. });
  10578. if (res.ok) {
  10579. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10580. loadDynamicRouting();
  10581. } else {
  10582. const err = await res.json();
  10583. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10584. }
  10585. } catch (err) {
  10586. showToast('Error', err.message, 'error');
  10587. }
  10588. }
  10589. // -------------------------------------------------------------
  10590. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10591. // -------------------------------------------------------------
  10592. function openAddSelectRuleModal() {
  10593. document.getElementById('modal-rf-sr-id').value = '';
  10594. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10595. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10596. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10597. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10598. document.getElementById('modal-rf-sr-comment').value = '';
  10599. document.getElementById('modal-rf-sr-disabled').checked = false;
  10600. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10601. }
  10602. function openEditSelectRuleModal(id) {
  10603. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10604. if (!r) return;
  10605. document.getElementById('modal-rf-sr-id').value = r.id;
  10606. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10607. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10608. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10609. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10610. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10611. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10612. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10613. }
  10614. function closeSelectRuleModal() {
  10615. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10616. }
  10617. async function submitSelectRule(e) {
  10618. e.preventDefault();
  10619. const payload = {
  10620. id: document.getElementById('modal-rf-sr-id').value,
  10621. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10622. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10623. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10624. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10625. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10626. };
  10627. try {
  10628. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10629. method: 'POST',
  10630. headers: { 'Content-Type': 'application/json' },
  10631. body: JSON.stringify(payload)
  10632. });
  10633. if (res.ok) {
  10634. closeSelectRuleModal();
  10635. showToast('Success', 'Select rule saved', 'success');
  10636. loadDynamicRouting();
  10637. } else {
  10638. const err = await res.json();
  10639. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10640. }
  10641. } catch (err) {
  10642. showToast('Error', err.message, 'error');
  10643. }
  10644. }
  10645. async function deleteSelectRule(id) {
  10646. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10647. try {
  10648. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10649. if (res.ok) {
  10650. showToast('Deleted', 'Select rule removed', 'info');
  10651. loadDynamicRouting();
  10652. } else {
  10653. const err = await res.json();
  10654. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10655. }
  10656. } catch (err) {
  10657. showToast('Error', err.message, 'error');
  10658. }
  10659. }
  10660. async function toggleSelectRuleState(id, disabled) {
  10661. try {
  10662. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10663. method: 'POST',
  10664. headers: { 'Content-Type': 'application/json' },
  10665. body: JSON.stringify({ disabled })
  10666. });
  10667. if (res.ok) {
  10668. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10669. loadDynamicRouting();
  10670. } else {
  10671. const err = await res.json();
  10672. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10673. }
  10674. } catch (err) {
  10675. showToast('Error', err.message, 'error');
  10676. }
  10677. }
  10678. // -------------------------------------------------------------
  10679. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10680. // -------------------------------------------------------------
  10681. function openAddCommunityListModal() {
  10682. document.getElementById('modal-rf-cl-id').value = '';
  10683. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10684. document.getElementById('modal-rf-cl-name').value = '';
  10685. document.getElementById('modal-rf-cl-communities').value = '';
  10686. document.getElementById('modal-rf-cl-regexp').value = '';
  10687. document.getElementById('modal-rf-cl-comment').value = '';
  10688. document.getElementById('modal-rf-cl-disabled').checked = false;
  10689. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10690. }
  10691. function openEditCommunityListModal(id) {
  10692. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10693. if (!cl) return;
  10694. document.getElementById('modal-rf-cl-id').value = cl.id;
  10695. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10696. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10697. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10698. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10699. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10700. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10701. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10702. }
  10703. function closeCommunityListModal() {
  10704. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10705. }
  10706. async function submitCommunityList(e) {
  10707. e.preventDefault();
  10708. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10709. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10710. const payload = {
  10711. id: document.getElementById('modal-rf-cl-id').value,
  10712. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10713. communities: comms,
  10714. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10715. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10716. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10717. };
  10718. try {
  10719. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10720. method: 'POST',
  10721. headers: { 'Content-Type': 'application/json' },
  10722. body: JSON.stringify(payload)
  10723. });
  10724. if (res.ok) {
  10725. closeCommunityListModal();
  10726. showToast('Success', 'Community list saved', 'success');
  10727. loadDynamicRouting();
  10728. } else {
  10729. const err = await res.json();
  10730. showToast('Error', err.error || 'Failed to save community list', 'error');
  10731. }
  10732. } catch (err) {
  10733. showToast('Error', err.message, 'error');
  10734. }
  10735. }
  10736. async function deleteCommunityList(id) {
  10737. if (!confirm('Are you sure you want to delete this community list?')) return;
  10738. try {
  10739. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10740. if (res.ok) {
  10741. showToast('Deleted', 'Community list removed', 'info');
  10742. loadDynamicRouting();
  10743. } else {
  10744. const err = await res.json();
  10745. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10746. }
  10747. } catch (err) {
  10748. showToast('Error', err.message, 'error');
  10749. }
  10750. }
  10751. async function toggleCommunityListState(id, disabled) {
  10752. try {
  10753. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10754. method: 'POST',
  10755. headers: { 'Content-Type': 'application/json' },
  10756. body: JSON.stringify({ disabled })
  10757. });
  10758. if (res.ok) {
  10759. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10760. loadDynamicRouting();
  10761. } else {
  10762. const err = await res.json();
  10763. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10764. }
  10765. } catch (err) {
  10766. showToast('Error', err.message, 'error');
  10767. }
  10768. }
  10769. // -------------------------------------------------------------
  10770. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10771. // -------------------------------------------------------------
  10772. function openAddASListModal() {
  10773. document.getElementById('modal-rf-al-id').value = '';
  10774. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10775. document.getElementById('modal-rf-al-name').value = '';
  10776. document.getElementById('modal-rf-al-range').value = '';
  10777. document.getElementById('modal-rf-al-comment').value = '';
  10778. document.getElementById('modal-rf-al-disabled').checked = false;
  10779. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10780. }
  10781. function openEditASListModal(id) {
  10782. const al = (state.routingASLists || []).find(item => item.id === id);
  10783. if (!al) return;
  10784. document.getElementById('modal-rf-al-id').value = al.id;
  10785. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10786. document.getElementById('modal-rf-al-name').value = al.name || '';
  10787. document.getElementById('modal-rf-al-range').value = al.range || '';
  10788. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10789. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10790. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10791. }
  10792. function closeASListModal() {
  10793. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10794. }
  10795. async function submitASList(e) {
  10796. e.preventDefault();
  10797. const payload = {
  10798. id: document.getElementById('modal-rf-al-id').value,
  10799. name: document.getElementById('modal-rf-al-name').value.trim(),
  10800. range: document.getElementById('modal-rf-al-range').value.trim(),
  10801. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10802. disabled: document.getElementById('modal-rf-al-disabled').checked
  10803. };
  10804. try {
  10805. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10806. method: 'POST',
  10807. headers: { 'Content-Type': 'application/json' },
  10808. body: JSON.stringify(payload)
  10809. });
  10810. if (res.ok) {
  10811. closeASListModal();
  10812. showToast('Success', 'AS number list saved', 'success');
  10813. loadDynamicRouting();
  10814. } else {
  10815. const err = await res.json();
  10816. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10817. }
  10818. } catch (err) {
  10819. showToast('Error', err.message, 'error');
  10820. }
  10821. }
  10822. async function deleteASList(id) {
  10823. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10824. try {
  10825. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10826. if (res.ok) {
  10827. showToast('Deleted', 'AS list removed', 'info');
  10828. loadDynamicRouting();
  10829. } else {
  10830. const err = await res.json();
  10831. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10832. }
  10833. } catch (err) {
  10834. showToast('Error', err.message, 'error');
  10835. }
  10836. }
  10837. async function toggleASListState(id, disabled) {
  10838. try {
  10839. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10840. method: 'POST',
  10841. headers: { 'Content-Type': 'application/json' },
  10842. body: JSON.stringify({ disabled })
  10843. });
  10844. if (res.ok) {
  10845. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10846. loadDynamicRouting();
  10847. } else {
  10848. const err = await res.json();
  10849. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10850. }
  10851. } catch (err) {
  10852. showToast('Error', err.message, 'error');
  10853. }
  10854. }
  10855. // ==========================================
  10856. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10857. // ==========================================
  10858. function loadToolsView() {
  10859. populateToolsInterfaces();
  10860. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10861. }
  10862. function populateToolsInterfaces() {
  10863. const pingSel = document.getElementById('tools-ping-iface');
  10864. const traceSel = document.getElementById('tools-tr-iface');
  10865. let opts = '<option value="">Auto (Default Route)</option>';
  10866. if (Array.isArray(state.interfaces)) {
  10867. state.interfaces.forEach(iface => {
  10868. if (iface.name) {
  10869. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10870. }
  10871. });
  10872. }
  10873. if (pingSel) {
  10874. const cur = pingSel.value;
  10875. pingSel.innerHTML = opts;
  10876. if (cur) pingSel.value = cur;
  10877. }
  10878. if (traceSel) {
  10879. const cur = traceSel.value;
  10880. traceSel.innerHTML = opts;
  10881. if (cur) traceSel.value = cur;
  10882. }
  10883. }
  10884. function switchToolsSubTab(subTab) {
  10885. state.activeToolsSubTab = subTab;
  10886. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10887. tabs.forEach(t => {
  10888. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10889. const view = document.getElementById(`tools-view-${t}`);
  10890. if (btn) {
  10891. if (t === subTab) {
  10892. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-amber-400 text-amber-300 transition flex items-center gap-2 whitespace-nowrap';
  10893. } else {
  10894. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  10895. }
  10896. }
  10897. if (view) {
  10898. if (t === subTab) {
  10899. view.classList.remove('hidden');
  10900. } else {
  10901. view.classList.add('hidden');
  10902. }
  10903. }
  10904. });
  10905. }
  10906. function setPortPreset(port) {
  10907. const input = document.getElementById('tools-port-num');
  10908. if (input) input.value = port;
  10909. }
  10910. let pingAbortController = null;
  10911. let tracerouteAbortController = null;
  10912. function clearPingTable() {
  10913. const tbody = document.getElementById('tools-ping-tbody');
  10914. if (tbody) tbody.innerHTML = '';
  10915. const rawEl = document.getElementById('tools-ping-raw');
  10916. if (rawEl) rawEl.innerText = '';
  10917. const sentEl = document.getElementById('tools-ping-stat-sent');
  10918. if (sentEl) sentEl.innerText = '0';
  10919. const recvEl = document.getElementById('tools-ping-stat-recv');
  10920. if (recvEl) recvEl.innerText = '0';
  10921. const lossEl = document.getElementById('tools-ping-stat-loss');
  10922. if (lossEl) lossEl.innerText = '0%';
  10923. const avgEl = document.getElementById('tools-ping-stat-avg');
  10924. if (avgEl) avgEl.innerText = '0 ms';
  10925. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10926. if (minMaxEl) minMaxEl.innerText = '-';
  10927. const badge = document.getElementById('tools-ping-status-badge');
  10928. if (badge) {
  10929. badge.className = '';
  10930. badge.innerText = '';
  10931. }
  10932. }
  10933. function clearTracerouteTable() {
  10934. const tbody = document.getElementById('tools-tr-tbody');
  10935. if (tbody) tbody.innerHTML = '';
  10936. const rawEl = document.getElementById('tools-tr-raw');
  10937. if (rawEl) rawEl.innerText = '';
  10938. const statHops = document.getElementById('tools-tr-hops-count');
  10939. if (statHops) statHops.innerText = '0 Hops';
  10940. }
  10941. function resetPingButton() {
  10942. const btn = document.getElementById('tools-ping-btn');
  10943. const btnText = document.getElementById('tools-ping-btn-text');
  10944. const spinner = document.getElementById('tools-ping-spinner');
  10945. if (btn) {
  10946. btn.disabled = false;
  10947. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  10948. }
  10949. if (btnText) btnText.innerText = 'Start Ping';
  10950. if (spinner) spinner.classList.add('hidden');
  10951. }
  10952. function setPingRunningButton() {
  10953. const btn = document.getElementById('tools-ping-btn');
  10954. const btnText = document.getElementById('tools-ping-btn-text');
  10955. const spinner = document.getElementById('tools-ping-spinner');
  10956. if (btn) {
  10957. btn.disabled = false;
  10958. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  10959. }
  10960. if (btnText) btnText.innerText = 'Stop Ping';
  10961. if (spinner) spinner.classList.remove('hidden');
  10962. }
  10963. function resetTracerouteButton() {
  10964. const btn = document.getElementById('tools-tr-btn');
  10965. const btnText = document.getElementById('tools-tr-btn-text');
  10966. const spinner = document.getElementById('tools-tr-spinner');
  10967. if (btn) {
  10968. btn.disabled = false;
  10969. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  10970. }
  10971. if (btnText) btnText.innerText = 'Start Traceroute';
  10972. if (spinner) spinner.classList.add('hidden');
  10973. }
  10974. function setTracerouteRunningButton() {
  10975. const btn = document.getElementById('tools-tr-btn');
  10976. const btnText = document.getElementById('tools-tr-btn-text');
  10977. const spinner = document.getElementById('tools-tr-spinner');
  10978. if (btn) {
  10979. btn.disabled = false;
  10980. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  10981. }
  10982. if (btnText) btnText.innerText = 'Stop Traceroute';
  10983. if (spinner) spinner.classList.remove('hidden');
  10984. }
  10985. async function executePing(e) {
  10986. if (e) e.preventDefault();
  10987. // If already running, clicking the button stops the stream!
  10988. if (pingAbortController) {
  10989. pingAbortController.abort();
  10990. pingAbortController = null;
  10991. resetPingButton();
  10992. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10993. return;
  10994. }
  10995. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10996. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10997. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10998. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10999. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11000. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11001. if (!target) {
  11002. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11003. return;
  11004. }
  11005. clearPingTable();
  11006. const resCard = document.getElementById('tools-ping-results');
  11007. if (resCard) resCard.classList.remove('hidden');
  11008. pingAbortController = new AbortController();
  11009. setPingRunningButton();
  11010. try {
  11011. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11012. method: 'POST',
  11013. headers: { 'Content-Type': 'application/json' },
  11014. body: JSON.stringify({
  11015. target,
  11016. count,
  11017. size,
  11018. timeout,
  11019. interface: iface,
  11020. dont_frag: dontFrag
  11021. }),
  11022. signal: pingAbortController.signal
  11023. });
  11024. if (!res.ok) {
  11025. const errText = await res.text();
  11026. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11027. resetPingButton();
  11028. pingAbortController = null;
  11029. return;
  11030. }
  11031. const reader = res.body.getReader();
  11032. const decoder = new TextDecoder('utf-8');
  11033. let buffer = '';
  11034. while (true) {
  11035. const { done, value } = await reader.read();
  11036. if (done) break;
  11037. buffer += decoder.decode(value, { stream: true });
  11038. const blocks = buffer.split('\n\n');
  11039. buffer = blocks.pop() || '';
  11040. for (const block of blocks) {
  11041. const trimmed = block.trim();
  11042. if (!trimmed) continue;
  11043. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11044. try {
  11045. const evt = JSON.parse(line);
  11046. handleLivePingEvent(evt);
  11047. } catch (parseErr) {
  11048. console.warn('Ping SSE parse error:', parseErr, line);
  11049. }
  11050. }
  11051. }
  11052. } catch (err) {
  11053. if (err.name === 'AbortError') {
  11054. // User aborted normally
  11055. } else {
  11056. showToast('Ping Error', err.message, 'error');
  11057. }
  11058. } finally {
  11059. pingAbortController = null;
  11060. resetPingButton();
  11061. }
  11062. }
  11063. function handleLivePingEvent(evt) {
  11064. const sentEl = document.getElementById('tools-ping-stat-sent');
  11065. const recvEl = document.getElementById('tools-ping-stat-recv');
  11066. const lossEl = document.getElementById('tools-ping-stat-loss');
  11067. const avgEl = document.getElementById('tools-ping-stat-avg');
  11068. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11069. const badge = document.getElementById('tools-ping-status-badge');
  11070. const tbody = document.getElementById('tools-ping-tbody');
  11071. const rawEl = document.getElementById('tools-ping-raw');
  11072. if (evt.raw && rawEl) {
  11073. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11074. rawEl.scrollTop = rawEl.scrollHeight;
  11075. }
  11076. if (evt.type === 'reply') {
  11077. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11078. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11079. if (lossEl && evt.packet_loss_pct !== undefined) {
  11080. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11081. lossEl.className = evt.packet_loss_pct === 0
  11082. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11083. : (evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  11084. }
  11085. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11086. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11087. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11088. }
  11089. if (badge) {
  11090. if (evt.packet_loss_pct === 0) {
  11091. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-950 text-emerald-300 border border-emerald-800/60';
  11092. badge.innerText = '100% OK';
  11093. } else {
  11094. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-950 text-amber-300 border border-amber-800/60';
  11095. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11096. }
  11097. }
  11098. if (tbody) {
  11099. const tr = document.createElement('tr');
  11100. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11101. tr.innerHTML = `
  11102. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11103. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11104. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11105. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11106. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11107. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REPLY</span></td>
  11108. `;
  11109. tbody.appendChild(tr);
  11110. }
  11111. } else if (evt.type === 'timeout') {
  11112. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11113. if (lossEl && evt.packet_loss_pct !== undefined) {
  11114. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11115. lossEl.className = evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1';
  11116. }
  11117. if (badge) {
  11118. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  11119. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11120. }
  11121. if (tbody) {
  11122. const tr = document.createElement('tr');
  11123. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11124. tr.innerHTML = `
  11125. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11126. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11127. <td class="py-2 px-3 text-slate-600">--</td>
  11128. <td class="py-2 px-3 text-slate-600">--</td>
  11129. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11130. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span></td>
  11131. `;
  11132. tbody.appendChild(tr);
  11133. }
  11134. } else if (evt.type === 'unreach') {
  11135. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11136. if (lossEl && evt.packet_loss_pct !== undefined) {
  11137. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11138. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11139. }
  11140. if (badge) {
  11141. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  11142. badge.innerText = 'UNREACHABLE';
  11143. }
  11144. if (tbody) {
  11145. const tr = document.createElement('tr');
  11146. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11147. tr.innerHTML = `
  11148. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11149. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11150. <td class="py-2 px-3 text-slate-600">--</td>
  11151. <td class="py-2 px-3 text-slate-600">--</td>
  11152. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11153. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">UNREACH</span></td>
  11154. `;
  11155. tbody.appendChild(tr);
  11156. }
  11157. } else if (evt.type === 'stats') {
  11158. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11159. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11160. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11161. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11162. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11163. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11164. }
  11165. } else if (evt.type === 'done') {
  11166. showToast('Ping Finished', `Sent ${evt.packets_sent}, received ${evt.packets_recv} (${evt.packet_loss_pct?.toFixed(0)}% loss)`, evt.packet_loss_pct === 0 ? 'success' : 'info');
  11167. }
  11168. }
  11169. async function executeTraceroute(e) {
  11170. if (e) e.preventDefault();
  11171. if (tracerouteAbortController) {
  11172. tracerouteAbortController.abort();
  11173. tracerouteAbortController = null;
  11174. resetTracerouteButton();
  11175. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11176. return;
  11177. }
  11178. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11179. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11180. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11181. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11182. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11183. if (!target) {
  11184. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11185. return;
  11186. }
  11187. clearTracerouteTable();
  11188. const resCard = document.getElementById('tools-tr-results');
  11189. if (resCard) resCard.classList.remove('hidden');
  11190. tracerouteAbortController = new AbortController();
  11191. setTracerouteRunningButton();
  11192. try {
  11193. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11194. method: 'POST',
  11195. headers: { 'Content-Type': 'application/json' },
  11196. body: JSON.stringify({
  11197. target,
  11198. max_hops: maxHops,
  11199. protocol,
  11200. interface: iface,
  11201. resolve
  11202. }),
  11203. signal: tracerouteAbortController.signal
  11204. });
  11205. if (!res.ok) {
  11206. const errText = await res.text();
  11207. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11208. resetTracerouteButton();
  11209. tracerouteAbortController = null;
  11210. return;
  11211. }
  11212. const reader = res.body.getReader();
  11213. const decoder = new TextDecoder('utf-8');
  11214. let buffer = '';
  11215. while (true) {
  11216. const { done, value } = await reader.read();
  11217. if (done) break;
  11218. buffer += decoder.decode(value, { stream: true });
  11219. const blocks = buffer.split('\n\n');
  11220. buffer = blocks.pop() || '';
  11221. for (const block of blocks) {
  11222. const trimmed = block.trim();
  11223. if (!trimmed) continue;
  11224. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11225. try {
  11226. const evt = JSON.parse(line);
  11227. handleLiveTracerouteEvent(evt);
  11228. } catch (parseErr) {
  11229. console.warn('Traceroute SSE parse error:', parseErr, line);
  11230. }
  11231. }
  11232. }
  11233. } catch (err) {
  11234. if (err.name === 'AbortError') {
  11235. // User aborted normally
  11236. } else {
  11237. showToast('Traceroute Error', err.message, 'error');
  11238. }
  11239. } finally {
  11240. tracerouteAbortController = null;
  11241. resetTracerouteButton();
  11242. }
  11243. }
  11244. function handleLiveTracerouteEvent(evt) {
  11245. const statHops = document.getElementById('tools-tr-hops-count');
  11246. const tbody = document.getElementById('tools-tr-tbody');
  11247. const rawEl = document.getElementById('tools-tr-raw');
  11248. if (evt.raw && rawEl) {
  11249. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11250. rawEl.scrollTop = rawEl.scrollHeight;
  11251. }
  11252. if (evt.hops_count !== undefined && statHops) {
  11253. statHops.innerText = `${evt.hops_count} Hops`;
  11254. }
  11255. if (evt.type === 'hop' && evt.hop && tbody) {
  11256. const h = evt.hop;
  11257. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11258. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11259. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11260. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11261. const tr = document.createElement('tr');
  11262. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11263. tr.innerHTML = `
  11264. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11265. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11266. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11267. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11268. <td class="py-2.5 px-3 text-right">
  11269. ${isTimeout
  11270. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11271. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">OK</span>'}
  11272. </td>
  11273. `;
  11274. tbody.appendChild(tr);
  11275. } else if (evt.type === 'done') {
  11276. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11277. }
  11278. }
  11279. async function executeMTR(e) {
  11280. if (e) e.preventDefault();
  11281. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11282. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11283. if (!target) {
  11284. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11285. return;
  11286. }
  11287. const btn = document.getElementById('tools-mtr-btn');
  11288. const spinner = document.getElementById('tools-mtr-spinner');
  11289. if (btn) btn.disabled = true;
  11290. if (spinner) spinner.classList.remove('hidden');
  11291. try {
  11292. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11293. method: 'POST',
  11294. headers: { 'Content-Type': 'application/json' },
  11295. body: JSON.stringify({ target, count: cycles })
  11296. });
  11297. const data = await res.json();
  11298. if (!res.ok) {
  11299. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11300. return;
  11301. }
  11302. const resCard = document.getElementById('tools-mtr-results');
  11303. if (resCard) resCard.classList.remove('hidden');
  11304. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11305. const statHops = document.getElementById('tools-mtr-hops-count');
  11306. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11307. const tbody = document.getElementById('tools-mtr-tbody');
  11308. if (tbody) {
  11309. if (hopsCount > 0) {
  11310. tbody.innerHTML = data.hops.map(h => {
  11311. const lossClass = h.loss_pct === 0 ? 'text-emerald-400 font-bold' : (h.loss_pct < 20 ? 'text-amber-400 font-bold' : 'text-rose-400 font-bold');
  11312. return `
  11313. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11314. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11315. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11316. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11317. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11318. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11319. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11320. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11321. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11322. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11323. </tr>
  11324. `;
  11325. }).join('');
  11326. } else {
  11327. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11328. }
  11329. }
  11330. const rawEl = document.getElementById('tools-mtr-raw');
  11331. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11332. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11333. } catch (err) {
  11334. showToast('MTR Error', err.message, 'error');
  11335. } finally {
  11336. if (btn) btn.disabled = false;
  11337. if (spinner) spinner.classList.add('hidden');
  11338. }
  11339. }
  11340. async function executeDNS(e) {
  11341. if (e) e.preventDefault();
  11342. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11343. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11344. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11345. if (!domain) {
  11346. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11347. return;
  11348. }
  11349. const btn = document.getElementById('tools-dns-btn');
  11350. const spinner = document.getElementById('tools-dns-spinner');
  11351. if (btn) btn.disabled = true;
  11352. if (spinner) spinner.classList.remove('hidden');
  11353. try {
  11354. const res = await fetch(`${API_BASE}/tools/dns`, {
  11355. method: 'POST',
  11356. headers: { 'Content-Type': 'application/json' },
  11357. body: JSON.stringify({ domain, type, server })
  11358. });
  11359. const data = await res.json();
  11360. if (!res.ok) {
  11361. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11362. return;
  11363. }
  11364. const resCard = document.getElementById('tools-dns-results');
  11365. if (resCard) resCard.classList.remove('hidden');
  11366. const metaEl = document.getElementById('tools-dns-meta');
  11367. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11368. const tbody = document.getElementById('tools-dns-tbody');
  11369. if (tbody) {
  11370. if (Array.isArray(data.records) && data.records.length > 0) {
  11371. tbody.innerHTML = data.records.map(r => `
  11372. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11373. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11374. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11375. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11376. <td class="py-2.5 px-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/60">${escapeHtml(r.type)}</span></td>
  11377. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11378. </tr>
  11379. `).join('');
  11380. } else {
  11381. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  11382. }
  11383. }
  11384. const rawEl = document.getElementById('tools-dns-raw');
  11385. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11386. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11387. } catch (err) {
  11388. showToast('DNS Error', err.message, 'error');
  11389. } finally {
  11390. if (btn) btn.disabled = false;
  11391. if (spinner) spinner.classList.add('hidden');
  11392. }
  11393. }
  11394. async function executePortProbe(e) {
  11395. if (e) e.preventDefault();
  11396. const target = document.getElementById('tools-port-target')?.value?.trim();
  11397. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11398. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11399. if (!target || !port) {
  11400. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11401. return;
  11402. }
  11403. const btn = document.getElementById('tools-port-btn');
  11404. const spinner = document.getElementById('tools-port-spinner');
  11405. if (btn) btn.disabled = true;
  11406. if (spinner) spinner.classList.remove('hidden');
  11407. try {
  11408. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11409. method: 'POST',
  11410. headers: { 'Content-Type': 'application/json' },
  11411. body: JSON.stringify({ target, port, timeout })
  11412. });
  11413. const data = await res.json();
  11414. if (!res.ok) {
  11415. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11416. return;
  11417. }
  11418. const resCard = document.getElementById('tools-port-results');
  11419. if (resCard) resCard.classList.remove('hidden');
  11420. const banner = document.getElementById('tools-port-banner');
  11421. const icon = document.getElementById('tools-port-icon');
  11422. const title = document.getElementById('tools-port-title');
  11423. const sub = document.getElementById('tools-port-sub');
  11424. const latency = document.getElementById('tools-port-latency');
  11425. if (data.open) {
  11426. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11427. if (icon) {
  11428. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-emerald-500/20 text-emerald-400 border border-emerald-500/40';
  11429. icon.innerText = '✓';
  11430. }
  11431. if (title) {
  11432. title.className = 'text-sm font-bold text-emerald-300';
  11433. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11434. }
  11435. if (sub) {
  11436. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11437. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11438. }
  11439. if (latency) {
  11440. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11441. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11442. }
  11443. } else {
  11444. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11445. if (icon) {
  11446. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-rose-500/20 text-rose-400 border border-rose-500/40';
  11447. icon.innerText = '✕';
  11448. }
  11449. if (title) {
  11450. title.className = 'text-sm font-bold text-rose-300';
  11451. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11452. }
  11453. if (sub) {
  11454. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11455. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11456. }
  11457. if (latency) {
  11458. latency.className = 'text-base font-bold font-mono text-slate-500';
  11459. latency.innerText = '--';
  11460. }
  11461. }
  11462. const rawEl = document.getElementById('tools-port-raw');
  11463. if (rawEl) rawEl.innerText = data.raw_output || (data.open ? `Successfully connected to ${target}:${port} in ${data.latency_ms} ms` : `Connection failed: ${data.error || 'timed out or connection refused'}`);
  11464. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11465. } catch (err) {
  11466. showToast('Probe Error', err.message, 'error');
  11467. } finally {
  11468. if (btn) btn.disabled = false;
  11469. if (spinner) spinner.classList.add('hidden');
  11470. }
  11471. }
  11472. // ==========================================
  11473. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11474. // ==========================================
  11475. async function loadDHCPClients(showToastMsg = false) {
  11476. try {
  11477. const [clientsRes, sumRes] = await Promise.all([
  11478. fetch(`${API_BASE}/dhcp/clients`),
  11479. fetch(`${API_BASE}/dhcp/clients/summary`)
  11480. ]);
  11481. if (clientsRes.ok) {
  11482. state.dhcpClients = await clientsRes.json();
  11483. }
  11484. if (sumRes.ok) {
  11485. state.dhcpSummary = await sumRes.json();
  11486. }
  11487. renderDHCPClients();
  11488. updateDHCPSummaryCards();
  11489. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11490. if (bDhcp && state.dhcpSummary) {
  11491. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11492. }
  11493. if (showToastMsg) {
  11494. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11495. }
  11496. } catch (err) {
  11497. console.error('Failed to load DHCP clients:', err);
  11498. if (showToastMsg) {
  11499. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11500. }
  11501. }
  11502. }
  11503. function updateDHCPSummaryCards() {
  11504. const sum = state.dhcpSummary || {
  11505. total_clients: (state.dhcpClients || []).length,
  11506. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11507. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11508. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11509. };
  11510. const totalEl = document.getElementById('dhcp-stat-total');
  11511. const boundEl = document.getElementById('dhcp-stat-bound');
  11512. const searchEl = document.getElementById('dhcp-stat-searching');
  11513. const disEl = document.getElementById('dhcp-stat-disabled');
  11514. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11515. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11516. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11517. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11518. }
  11519. function renderDHCPClients() {
  11520. const tbody = document.getElementById('dhcp-clients-tbody');
  11521. const emptyState = document.getElementById('dhcp-clients-empty');
  11522. if (!tbody) return;
  11523. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11524. if (clients.length === 0) {
  11525. tbody.innerHTML = '';
  11526. if (emptyState) emptyState.classList.remove('hidden');
  11527. return;
  11528. }
  11529. if (emptyState) emptyState.classList.add('hidden');
  11530. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11531. if (tbody.dataset.sig === sig) return;
  11532. tbody.dataset.sig = sig;
  11533. tbody.innerHTML = clients.map(c => {
  11534. let statusBadge = '';
  11535. if (!c.enabled) {
  11536. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>';
  11537. } else if (c.status === 'bound') {
  11538. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>BOUND</span>';
  11539. } else if (c.status === 'searching') {
  11540. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-950 text-amber-300 border border-amber-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>SEARCHING...</span>';
  11541. } else if (c.status === 'stopped') {
  11542. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">STOPPED</span>';
  11543. } else {
  11544. statusBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">${escapeHtml((c.status || 'UNKNOWN').toUpperCase())}</span>`;
  11545. }
  11546. const ipDisplay = c.ip_address ? `<span class="font-bold text-white">${escapeHtml(c.ip_address)}</span>` : '<span class="text-slate-500 italic">No lease</span>';
  11547. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11548. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11549. const dnsDisplay = (Array.isArray(c.dns_servers) && c.dns_servers.length > 0) ? `<span class="text-cyan-400">${c.dns_servers.map(d => escapeHtml(d)).join(', ')}</span>` : '<span class="text-slate-600">--</span>';
  11550. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11551. // Option flags
  11552. const flags = [];
  11553. if (c.add_default_route) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700" title="Add Default Route">+GW</span>');
  11554. if (c.use_peer_dns) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/60 text-cyan-300 border border-cyan-800/50" title="Use Peer DNS">+DNS</span>');
  11555. if (c.use_peer_ntp) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950/60 text-indigo-300 border border-indigo-800/50" title="Use Peer NTP">+NTP</span>');
  11556. flags.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800/60 text-slate-400" title="Default Route Distance">dist:${c.default_route_distance || 1}</span>`);
  11557. return `
  11558. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11559. <td class="py-3 px-4">
  11560. <div class="flex items-center gap-2">
  11561. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11562. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11563. </div>
  11564. </td>
  11565. <td class="py-3 px-4">${statusBadge}</td>
  11566. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11567. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11568. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11569. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11570. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11571. <td class="py-3 px-4">
  11572. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11573. </td>
  11574. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11575. ${c.enabled ? `
  11576. <button onclick="renewDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-amber-400 text-xs font-medium border border-slate-700 transition" title="Renew Lease">Renew</button>
  11577. <button onclick="releaseDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium border border-slate-700 transition" title="Release Lease">Release</button>
  11578. <button onclick="toggleDHCPClientState('${c.id}', false)" class="px-2 py-1 rounded bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 text-xs font-medium border border-amber-500/30 transition" title="Disable DHCP Client">Disable</button>
  11579. ` : `
  11580. <button onclick="toggleDHCPClientState('${c.id}', true)" class="px-2.5 py-1 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-semibold border border-emerald-500/30 transition" title="Enable DHCP Client">Enable</button>
  11581. `}
  11582. <button onclick="openDHCPClientModal('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-white text-xs font-medium border border-slate-700 transition" title="Edit Settings">Edit</button>
  11583. <button onclick="deleteDHCPClient('${c.id}', '${c.interface}')" class="px-2 py-1 rounded bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 text-xs font-medium border border-rose-500/30 transition" title="Remove Client">✕</button>
  11584. </td>
  11585. </tr>
  11586. `;
  11587. }).join('');
  11588. }
  11589. function openDHCPClientModal(clientId = null) {
  11590. const modal = document.getElementById('modal-dhcp-client');
  11591. if (!modal) return;
  11592. const title = document.getElementById('modal-dhcp-title');
  11593. const idInput = document.getElementById('modal-dhcp-id');
  11594. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11595. const distInput = document.getElementById('modal-dhcp-distance');
  11596. const commentInput = document.getElementById('modal-dhcp-comment');
  11597. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11598. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11599. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11600. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11601. // Populate interfaces
  11602. if (ifaceSelect) {
  11603. let opts = '<option value="">Select interface...</option>';
  11604. const allIfaces = state.interfaces || [];
  11605. const allVlans = state.vlans || [];
  11606. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11607. // Group 1: Physical & Bridge Interfaces
  11608. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11609. allIfaces.forEach(i => {
  11610. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11611. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11612. });
  11613. opts += '</optgroup>';
  11614. // Group 2: VLAN Interfaces
  11615. if (allVlans.length > 0) {
  11616. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11617. allVlans.forEach(v => {
  11618. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11619. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11620. });
  11621. opts += '</optgroup>';
  11622. }
  11623. ifaceSelect.innerHTML = opts;
  11624. }
  11625. if (clientId) {
  11626. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11627. if (client) {
  11628. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11629. if (idInput) idInput.value = client.id;
  11630. if (ifaceSelect) {
  11631. ifaceSelect.value = client.interface;
  11632. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11633. }
  11634. if (distInput) distInput.value = client.default_route_distance || 1;
  11635. if (commentInput) commentInput.value = client.comment || '';
  11636. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11637. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11638. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11639. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11640. }
  11641. } else {
  11642. if (title) title.innerText = 'Add DHCP Client';
  11643. if (idInput) idInput.value = '';
  11644. if (ifaceSelect) {
  11645. ifaceSelect.value = '';
  11646. ifaceSelect.disabled = false;
  11647. }
  11648. if (distInput) distInput.value = 1;
  11649. if (commentInput) commentInput.value = '';
  11650. if (defRouteCheck) defRouteCheck.checked = true;
  11651. if (peerDnsCheck) peerDnsCheck.checked = true;
  11652. if (peerNtpCheck) peerNtpCheck.checked = true;
  11653. if (enabledCheck) enabledCheck.checked = true;
  11654. }
  11655. modal.classList.remove('hidden');
  11656. }
  11657. function openDHCPClientModalForIface(ifaceName) {
  11658. openDHCPClientModal();
  11659. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11660. if (ifaceSelect && ifaceName) {
  11661. ifaceSelect.value = ifaceName;
  11662. }
  11663. }
  11664. function closeDHCPClientModal() {
  11665. const modal = document.getElementById('modal-dhcp-client');
  11666. if (modal) modal.classList.add('hidden');
  11667. }
  11668. async function submitSaveDHCPClient(e) {
  11669. if (e) e.preventDefault();
  11670. const id = document.getElementById('modal-dhcp-id')?.value;
  11671. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11672. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11673. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11674. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11675. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11676. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11677. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11678. if (!id && !iface) {
  11679. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11680. return;
  11681. }
  11682. try {
  11683. let res;
  11684. if (id) {
  11685. // PUT update
  11686. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11687. method: 'PUT',
  11688. headers: { 'Content-Type': 'application/json' },
  11689. body: JSON.stringify({
  11690. enabled,
  11691. add_default_route: defRoute,
  11692. default_route_distance: distance,
  11693. use_peer_dns: peerDns,
  11694. use_peer_ntp: peerNtp,
  11695. comment
  11696. })
  11697. });
  11698. } else {
  11699. // POST create
  11700. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11701. method: 'POST',
  11702. headers: { 'Content-Type': 'application/json' },
  11703. body: JSON.stringify({
  11704. interface: iface,
  11705. enabled,
  11706. add_default_route: defRoute,
  11707. default_route_distance: distance,
  11708. use_peer_dns: peerDns,
  11709. use_peer_ntp: peerNtp,
  11710. comment
  11711. })
  11712. });
  11713. }
  11714. const data = await res.json();
  11715. if (!res.ok) {
  11716. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11717. return;
  11718. }
  11719. closeDHCPClientModal();
  11720. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11721. await loadDHCPClients();
  11722. fetchData(); // refresh interfaces list with new lease/status
  11723. } catch (err) {
  11724. showToast('Error', err.message, 'error');
  11725. }
  11726. }
  11727. async function toggleDHCPClientState(id, enabled) {
  11728. try {
  11729. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11730. method: 'POST',
  11731. headers: { 'Content-Type': 'application/json' },
  11732. body: JSON.stringify({ enabled })
  11733. });
  11734. const data = await res.json();
  11735. if (!res.ok) {
  11736. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11737. return;
  11738. }
  11739. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11740. await loadDHCPClients();
  11741. fetchData();
  11742. } catch (err) {
  11743. showToast('Error', err.message, 'error');
  11744. }
  11745. }
  11746. async function renewDHCPClient(id) {
  11747. try {
  11748. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11749. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11750. method: 'POST'
  11751. });
  11752. const data = await res.json();
  11753. if (!res.ok) {
  11754. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11755. return;
  11756. }
  11757. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11758. setTimeout(() => {
  11759. loadDHCPClients();
  11760. fetchData();
  11761. }, 1500);
  11762. } catch (err) {
  11763. showToast('Error', err.message, 'error');
  11764. }
  11765. }
  11766. async function releaseDHCPClient(id) {
  11767. try {
  11768. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11769. method: 'POST'
  11770. });
  11771. const data = await res.json();
  11772. if (!res.ok) {
  11773. showToast('Error', data.error || 'Failed to release lease', 'error');
  11774. return;
  11775. }
  11776. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11777. await loadDHCPClients();
  11778. fetchData();
  11779. } catch (err) {
  11780. showToast('Error', err.message, 'error');
  11781. }
  11782. }
  11783. async function deleteDHCPClient(id, ifaceName) {
  11784. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11785. return;
  11786. }
  11787. try {
  11788. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11789. method: 'DELETE'
  11790. });
  11791. const data = await res.json();
  11792. if (!res.ok) {
  11793. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11794. return;
  11795. }
  11796. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11797. await loadDHCPClients();
  11798. fetchData();
  11799. } catch (err) {
  11800. showToast('Error', err.message, 'error');
  11801. }
  11802. }
  11803. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11804. async function loadDHCPServer(populate = true) {
  11805. try {
  11806. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11807. fetch(`${API_BASE}/dhcp-server/summary`),
  11808. fetch(`${API_BASE}/dhcp-server/servers`),
  11809. fetch(`${API_BASE}/dhcp-server/networks`),
  11810. fetch(`${API_BASE}/dhcp-server/leases`),
  11811. fetch(`${API_BASE}/dhcp-server/options`)
  11812. ]);
  11813. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11814. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11815. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11816. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11817. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11818. const sum = state.dhcpServerSummary || {};
  11819. const srvs = state.dhcpServers || [];
  11820. const nets = state.dhcpNetworks || [];
  11821. const leases = state.dhcpLeases || [];
  11822. const opts = state.dhcpOptions || [];
  11823. // KPI Cards
  11824. const statActive = document.getElementById('dhcp-server-stat-active');
  11825. if (statActive) {
  11826. const activeCount = srvs.filter(s => s.running).length;
  11827. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11828. }
  11829. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11830. if (statLeases) {
  11831. statLeases.innerText = leases.length;
  11832. }
  11833. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11834. if (statLeasesSub) {
  11835. const dyn = leases.filter(l => l.dynamic).length;
  11836. const st = leases.filter(l => !l.dynamic).length;
  11837. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11838. }
  11839. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11840. if (statNetworks) {
  11841. statNetworks.innerText = nets.length;
  11842. }
  11843. // Subtab Badges
  11844. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11845. if (bSrv) bSrv.innerText = srvs.length;
  11846. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11847. if (bNet) bNet.innerText = nets.length;
  11848. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11849. if (bLease) bLease.innerText = leases.length;
  11850. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11851. if (bOpt) bOpt.innerText = opts.length;
  11852. // Sidebar Badge
  11853. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11854. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11855. renderCurrentDHCPServerTab();
  11856. } catch (err) {
  11857. console.error('Failed to load DHCP Server:', err);
  11858. }
  11859. }
  11860. function switchDHCPServerTab(tab) {
  11861. state.dhcpServerTab = tab;
  11862. const tabs = ['servers', 'networks', 'leases', 'options'];
  11863. tabs.forEach(t => {
  11864. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11865. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11866. if (panel) {
  11867. if (t === tab) panel.classList.remove('hidden');
  11868. else panel.classList.add('hidden');
  11869. }
  11870. if (btn) {
  11871. if (t === tab) {
  11872. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  11873. } else {
  11874. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  11875. }
  11876. }
  11877. });
  11878. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11879. if (addBtn) {
  11880. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11881. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11882. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11883. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11884. }
  11885. renderCurrentDHCPServerTab();
  11886. }
  11887. function handleDHCPServerPrimaryAdd() {
  11888. const tab = state.dhcpServerTab || 'servers';
  11889. if (tab === 'servers') openAddDHCPServerModal();
  11890. else if (tab === 'networks') openAddDHCPNetworkModal();
  11891. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11892. else if (tab === 'options') openAddDHCPOptionModal();
  11893. }
  11894. function renderCurrentDHCPServerTab() {
  11895. const tab = state.dhcpServerTab || 'servers';
  11896. if (tab === 'servers') renderDHCPServers();
  11897. else if (tab === 'networks') renderDHCPNetworks();
  11898. else if (tab === 'leases') renderDHCPLeases();
  11899. else if (tab === 'options') renderDHCPOptions();
  11900. }
  11901. function renderDHCPServers() {
  11902. const tbody = document.getElementById('dhcp-server-tbody');
  11903. const empty = document.getElementById('dhcp-server-empty');
  11904. if (!tbody) return;
  11905. const servers = state.dhcpServers || [];
  11906. if (servers.length === 0) {
  11907. tbody.innerHTML = '';
  11908. empty?.classList.remove('hidden');
  11909. return;
  11910. }
  11911. empty?.classList.add('hidden');
  11912. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  11913. if (tbody.dataset.sig === sig) return;
  11914. tbody.dataset.sig = sig;
  11915. tbody.innerHTML = '';
  11916. servers.forEach(s => {
  11917. const tr = document.createElement('tr');
  11918. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11919. tr.innerHTML = `
  11920. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11921. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11922. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11923. <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
  11924. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11925. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11926. <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  11927. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${s.active_leases || 0}</span></td>
  11928. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11929. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11930. <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  11931. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11932. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11933. </td>
  11934. `;
  11935. tbody.appendChild(tr);
  11936. });
  11937. }
  11938. function renderDHCPNetworks() {
  11939. const tbody = document.getElementById('dhcp-networks-tbody');
  11940. const empty = document.getElementById('dhcp-networks-empty');
  11941. if (!tbody) return;
  11942. tbody.innerHTML = '';
  11943. const networks = state.dhcpNetworks || [];
  11944. if (networks.length === 0) {
  11945. empty?.classList.remove('hidden');
  11946. return;
  11947. }
  11948. empty?.classList.add('hidden');
  11949. networks.forEach(n => {
  11950. const tr = document.createElement('tr');
  11951. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11952. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11953. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11954. tr.innerHTML = `
  11955. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11956. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11957. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11958. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11959. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11960. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11961. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11962. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11963. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11964. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11965. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11966. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11967. </td>
  11968. `;
  11969. tbody.appendChild(tr);
  11970. });
  11971. }
  11972. function renderDHCPLeases() {
  11973. const tbody = document.getElementById('dhcp-leases-tbody');
  11974. const empty = document.getElementById('dhcp-leases-empty');
  11975. if (!tbody) return;
  11976. tbody.innerHTML = '';
  11977. const leases = state.dhcpLeases || [];
  11978. if (leases.length === 0) {
  11979. empty?.classList.remove('hidden');
  11980. return;
  11981. }
  11982. empty?.classList.add('hidden');
  11983. leases.forEach(l => {
  11984. const tr = document.createElement('tr');
  11985. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11986. const flag = l.dynamic ? '<span class="text-sky-400 font-bold" title="Dynamic">D</span>' : '<span class="text-purple-400 font-bold" title="Static Reservation">S</span>';
  11987. const statusBadge = l.status === 'bound'
  11988. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold font-mono">bound</span>'
  11989. : l.status === 'static'
  11990. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 font-semibold font-mono">static</span>'
  11991. : '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700 font-mono">waiting</span>';
  11992. const makeStaticBtn = l.dynamic
  11993. ? `<button onclick="makeDHCPLeaseStatic('${escapeHtml(l.mac_address)}', '${escapeHtml(l.address)}', '${escapeHtml(l.hostname || '')}', '${escapeHtml(l.comment || '')}')" class="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 hover:bg-purple-500/30 font-medium">Make Static</button>`
  11994. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11995. tr.innerHTML = `
  11996. <td class="py-2.5 px-3 text-center">${flag}</td>
  11997. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11998. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11999. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12000. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12001. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12002. <td class="py-2.5 px-3">${statusBadge}</td>
  12003. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12004. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12005. ${makeStaticBtn}
  12006. </td>
  12007. `;
  12008. tbody.appendChild(tr);
  12009. });
  12010. }
  12011. function renderDHCPOptions() {
  12012. const tbody = document.getElementById('dhcp-options-tbody');
  12013. const empty = document.getElementById('dhcp-options-empty');
  12014. if (!tbody) return;
  12015. tbody.innerHTML = '';
  12016. const options = state.dhcpOptions || [];
  12017. if (options.length === 0) {
  12018. empty?.classList.remove('hidden');
  12019. return;
  12020. }
  12021. empty?.classList.add('hidden');
  12022. options.forEach(o => {
  12023. const tr = document.createElement('tr');
  12024. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12025. tr.innerHTML = `
  12026. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12027. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12028. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12029. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12030. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12031. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12032. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12033. </td>
  12034. `;
  12035. tbody.appendChild(tr);
  12036. });
  12037. }
  12038. // ==================== MODALS & ACTIONS: SERVER ====================
  12039. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12040. const sel = document.getElementById(elemId);
  12041. if (!sel) return;
  12042. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12043. const networks = state.dhcpNetworks || [];
  12044. networks.forEach(n => {
  12045. const opt = document.createElement('option');
  12046. opt.value = n.address;
  12047. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12048. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12049. opt.selected = true;
  12050. }
  12051. sel.appendChild(opt);
  12052. });
  12053. }
  12054. function onDHCPServerNetworkChange() {
  12055. const netSel = document.getElementById('dhcp-server-modal-network');
  12056. if (!netSel) return;
  12057. const netVal = netSel.value;
  12058. if (!netVal) return;
  12059. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12060. if (!poolInput) return;
  12061. // Auto-calculate suggested address pool based on subnet CIDR
  12062. const parts = netVal.split('/');
  12063. const ip = parts[0];
  12064. const cidr = parseInt(parts[1] || '24', 10);
  12065. if (cidr === 24) {
  12066. const octets = ip.split('.');
  12067. if (octets.length === 4) {
  12068. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12069. poolInput.value = `${base}.10-${base}.254`;
  12070. }
  12071. }
  12072. }
  12073. function openAddDHCPServerModal() {
  12074. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12075. document.getElementById('dhcp-server-modal-id').value = '';
  12076. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12077. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12078. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12079. document.getElementById('dhcp-server-modal-comment').value = '';
  12080. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12081. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12082. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12083. const networks = state.dhcpNetworks || [];
  12084. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12085. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12086. if (defaultNet) {
  12087. onDHCPServerNetworkChange();
  12088. }
  12089. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12090. }
  12091. function openEditDHCPServerModal(id) {
  12092. const s = (state.dhcpServers || []).find(item => item.id === id);
  12093. if (!s) return;
  12094. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12095. document.getElementById('dhcp-server-modal-id').value = s.id;
  12096. document.getElementById('dhcp-server-modal-name').value = s.name;
  12097. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12098. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12099. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12100. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12101. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12102. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12103. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12104. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12105. }
  12106. function closeDHCPServerModal() {
  12107. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12108. }
  12109. async function submitSaveDHCPServer(e) {
  12110. e.preventDefault();
  12111. const id = document.getElementById('dhcp-server-modal-id').value;
  12112. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12113. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12114. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12115. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12116. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12117. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12118. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12119. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12120. try {
  12121. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12122. method: 'POST',
  12123. headers: { 'Content-Type': 'application/json' },
  12124. body: JSON.stringify({
  12125. id,
  12126. name,
  12127. interface: iface,
  12128. network,
  12129. address_pool: pool,
  12130. lease_time: leaseTime,
  12131. authoritative,
  12132. disabled,
  12133. comment
  12134. })
  12135. });
  12136. if (res.ok) {
  12137. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12138. closeDHCPServerModal();
  12139. loadDHCPServer(false);
  12140. fetchData(false);
  12141. } else {
  12142. const err = await res.text();
  12143. showToast('Error', err, 'error');
  12144. }
  12145. } catch (err) {
  12146. showToast('Error', err.message, 'error');
  12147. }
  12148. }
  12149. async function toggleDHCPServerState(id, disabled) {
  12150. try {
  12151. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12152. method: 'POST',
  12153. headers: { 'Content-Type': 'application/json' },
  12154. body: JSON.stringify({ disabled })
  12155. });
  12156. if (res.ok) {
  12157. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12158. loadDHCPServer(false);
  12159. fetchData(false);
  12160. }
  12161. } catch (err) {
  12162. showToast('Error', err.message, 'error');
  12163. }
  12164. }
  12165. async function deleteDHCPServer(id, name) {
  12166. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12167. try {
  12168. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12169. if (res.ok) {
  12170. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12171. loadDHCPServer(false);
  12172. fetchData(false);
  12173. }
  12174. } catch (err) {
  12175. showToast('Error', err.message, 'error');
  12176. }
  12177. }
  12178. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12179. function openAddDHCPNetworkModal() {
  12180. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12181. document.getElementById('dhcp-network-modal-id').value = '';
  12182. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12183. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12184. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12185. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12186. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  12187. document.getElementById('dhcp-network-modal-tftp').value = '';
  12188. document.getElementById('dhcp-network-modal-bootfile').value = '';
  12189. document.getElementById('dhcp-network-modal-wins').value = '';
  12190. document.getElementById('dhcp-network-modal-netmask').value = '';
  12191. document.getElementById('dhcp-network-modal-comment').value = '';
  12192. renderDHCPNetworkOptionsCheckboxes([]);
  12193. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12194. }
  12195. function openEditDHCPNetworkModal(id) {
  12196. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12197. if (!n) return;
  12198. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12199. document.getElementById('dhcp-network-modal-id').value = n.id;
  12200. document.getElementById('dhcp-network-modal-address').value = n.address;
  12201. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12202. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12203. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12204. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  12205. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  12206. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  12207. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  12208. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12209. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12210. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12211. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12212. }
  12213. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12214. const container = document.getElementById('dhcp-network-modal-options-list');
  12215. if (!container) return;
  12216. container.innerHTML = '';
  12217. const opts = state.dhcpOptions || [];
  12218. if (opts.length === 0) {
  12219. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12220. return;
  12221. }
  12222. opts.forEach(o => {
  12223. const isChecked = selectedIds.includes(o.id);
  12224. const label = document.createElement('label');
  12225. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12226. label.innerHTML = `
  12227. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12228. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12229. `;
  12230. container.appendChild(label);
  12231. });
  12232. }
  12233. function closeDHCPNetworkModal() {
  12234. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12235. }
  12236. async function submitSaveDHCPNetwork(e) {
  12237. e.preventDefault();
  12238. const id = document.getElementById('dhcp-network-modal-id').value;
  12239. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12240. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12241. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12242. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12243. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  12244. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  12245. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  12246. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  12247. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12248. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12249. const selectedOpts = [];
  12250. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12251. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12252. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12253. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12254. try {
  12255. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12256. method: 'POST',
  12257. headers: { 'Content-Type': 'application/json' },
  12258. body: JSON.stringify({
  12259. id,
  12260. address,
  12261. gateway,
  12262. netmask,
  12263. dns_servers: dnsServers,
  12264. domain,
  12265. ntp_servers: ntpServers,
  12266. next_server: tftp,
  12267. boot_file_name: bootfile,
  12268. wins_servers: winsServers,
  12269. dhcp_options: selectedOpts,
  12270. comment
  12271. })
  12272. });
  12273. if (res.ok) {
  12274. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12275. closeDHCPNetworkModal();
  12276. loadDHCPServer(false);
  12277. fetchData(false);
  12278. } else {
  12279. const err = await res.text();
  12280. showToast('Error', err, 'error');
  12281. }
  12282. } catch (err) {
  12283. showToast('Error', err.message, 'error');
  12284. }
  12285. }
  12286. async function deleteDHCPNetwork(id, addr) {
  12287. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12288. try {
  12289. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12290. if (res.ok) {
  12291. showToast('Deleted', `Network ${addr} removed`, 'success');
  12292. loadDHCPServer(false);
  12293. fetchData(false);
  12294. }
  12295. } catch (err) {
  12296. showToast('Error', err.message, 'error');
  12297. }
  12298. }
  12299. // ==================== MODALS & ACTIONS: LEASES ====================
  12300. function openAddDHCPStaticLeaseModal() {
  12301. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12302. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12303. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12304. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12305. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12306. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12307. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12308. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12309. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12310. }
  12311. function closeDHCPStaticLeaseModal() {
  12312. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12313. }
  12314. async function submitSaveDHCPStaticLease(e) {
  12315. e.preventDefault();
  12316. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12317. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12318. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12319. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12320. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12321. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12322. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12323. try {
  12324. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12325. method: 'POST',
  12326. headers: { 'Content-Type': 'application/json' },
  12327. body: JSON.stringify({
  12328. id,
  12329. mac_address: mac,
  12330. address: ip,
  12331. hostname,
  12332. server,
  12333. comment,
  12334. disabled
  12335. })
  12336. });
  12337. if (res.ok) {
  12338. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12339. closeDHCPStaticLeaseModal();
  12340. loadDHCPServer(false);
  12341. fetchData(false);
  12342. } else {
  12343. const err = await res.text();
  12344. showToast('Error', err, 'error');
  12345. }
  12346. } catch (err) {
  12347. showToast('Error', err.message, 'error');
  12348. }
  12349. }
  12350. async function deleteDHCPStaticLease(id) {
  12351. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12352. try {
  12353. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12354. if (res.ok) {
  12355. showToast('Deleted', 'Static lease removed', 'success');
  12356. loadDHCPServer(false);
  12357. fetchData(false);
  12358. }
  12359. } catch (err) {
  12360. showToast('Error', err.message, 'error');
  12361. }
  12362. }
  12363. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12364. try {
  12365. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12366. method: 'POST',
  12367. headers: { 'Content-Type': 'application/json' },
  12368. body: JSON.stringify({
  12369. mac_address: mac,
  12370. address: ip,
  12371. hostname,
  12372. comment: comment || 'Converted to static'
  12373. })
  12374. });
  12375. if (res.ok) {
  12376. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12377. loadDHCPServer(false);
  12378. fetchData(false);
  12379. } else {
  12380. const err = await res.text();
  12381. showToast('Error', err, 'error');
  12382. }
  12383. } catch (err) {
  12384. showToast('Error', err.message, 'error');
  12385. }
  12386. }
  12387. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12388. function openAddDHCPOptionModal() {
  12389. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12390. document.getElementById('dhcp-option-modal-id').value = '';
  12391. document.getElementById('dhcp-option-modal-name').value = '';
  12392. document.getElementById('dhcp-option-modal-code').value = '';
  12393. document.getElementById('dhcp-option-modal-value').value = '';
  12394. document.getElementById('dhcp-option-modal-comment').value = '';
  12395. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12396. }
  12397. function openEditDHCPOptionModal(id) {
  12398. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12399. if (!o) return;
  12400. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12401. document.getElementById('dhcp-option-modal-id').value = o.id;
  12402. document.getElementById('dhcp-option-modal-name').value = o.name;
  12403. document.getElementById('dhcp-option-modal-code').value = o.code;
  12404. document.getElementById('dhcp-option-modal-value').value = o.value;
  12405. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12406. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12407. }
  12408. function closeDHCPOptionModal() {
  12409. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12410. }
  12411. async function submitSaveDHCPOption(e) {
  12412. e.preventDefault();
  12413. const id = document.getElementById('dhcp-option-modal-id').value;
  12414. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12415. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12416. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12417. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12418. try {
  12419. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12420. method: 'POST',
  12421. headers: { 'Content-Type': 'application/json' },
  12422. body: JSON.stringify({ id, name, code, value, comment })
  12423. });
  12424. if (res.ok) {
  12425. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12426. closeDHCPOptionModal();
  12427. loadDHCPServer(false);
  12428. fetchData(false);
  12429. } else {
  12430. const err = await res.text();
  12431. showToast('Error', err, 'error');
  12432. }
  12433. } catch (err) {
  12434. showToast('Error', err.message, 'error');
  12435. }
  12436. }
  12437. async function deleteDHCPOption(id, name) {
  12438. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12439. try {
  12440. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12441. if (res.ok) {
  12442. showToast('Deleted', `Option ${name} removed`, 'success');
  12443. loadDHCPServer(false);
  12444. fetchData(false);
  12445. }
  12446. } catch (err) {
  12447. showToast('Error', err.message, 'error');
  12448. }
  12449. }
  12450. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12451. function openDHCPServerSetupModal() {
  12452. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12453. onDHCPWizardIfaceChange();
  12454. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12455. }
  12456. function closeDHCPServerSetupModal() {
  12457. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12458. }
  12459. function onDHCPWizardIfaceChange() {
  12460. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12461. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12462. let ip = '192.168.88.1';
  12463. let prefix = '24';
  12464. if (iface && iface.ip_address) {
  12465. const parts = iface.ip_address.split('/');
  12466. ip = parts[0];
  12467. if (parts.length > 1) prefix = parts[1];
  12468. }
  12469. // Calculate subnet base (e.g. 192.168.88.0/24)
  12470. const ipParts = ip.split('.');
  12471. if (ipParts.length === 4) {
  12472. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12473. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12474. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12475. document.getElementById('dhcp-wizard-gateway').value = ip;
  12476. document.getElementById('dhcp-wizard-pool').value = pool;
  12477. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12478. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12479. }
  12480. }
  12481. async function submitDHCPServerSetupWizard(e) {
  12482. e.preventDefault();
  12483. const iface = document.getElementById('dhcp-wizard-iface').value;
  12484. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12485. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12486. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12487. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12488. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12489. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12490. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12491. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12492. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12493. try {
  12494. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12495. method: 'POST',
  12496. headers: { 'Content-Type': 'application/json' },
  12497. body: JSON.stringify({
  12498. interface: iface,
  12499. address_space: space,
  12500. gateway: gw,
  12501. address_pool: pool,
  12502. dns_servers: dnsServers,
  12503. lease_time: leaseTime,
  12504. ntp_servers: ntpServers,
  12505. next_server: tftp
  12506. })
  12507. });
  12508. if (res.ok) {
  12509. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12510. closeDHCPServerSetupModal();
  12511. loadDHCPServer(false);
  12512. fetchData(false);
  12513. } else {
  12514. const err = await res.text();
  12515. showToast('Error', err, 'error');
  12516. }
  12517. } catch (err) {
  12518. showToast('Error', err.message, 'error');
  12519. }
  12520. }
  12521. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12522. const sel = document.getElementById(elemId);
  12523. if (!sel) return;
  12524. sel.innerHTML = '<option value="">Select interface...</option>';
  12525. const ifaces = state.interfaces || [];
  12526. ifaces.forEach(i => {
  12527. if (i.name === 'lo') return;
  12528. const opt = document.createElement('option');
  12529. opt.value = i.name;
  12530. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12531. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12532. if (i.name === selectedVal) opt.selected = true;
  12533. sel.appendChild(opt);
  12534. });
  12535. }
  12536. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12537. function initTableSorting() {
  12538. document.querySelectorAll('table').forEach(setupSortableTable);
  12539. }
  12540. function setupSortableTable(table) {
  12541. const thead = table.querySelector('thead');
  12542. const tbody = table.querySelector('tbody');
  12543. if (!thead || !tbody) return;
  12544. const headerRows = thead.querySelectorAll('tr');
  12545. if (headerRows.length === 0) return;
  12546. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12547. ths.forEach((th, colIdx) => {
  12548. if (th._sortBound) return;
  12549. th._sortBound = true;
  12550. const rawText = th.innerText.trim().toLowerCase();
  12551. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12552. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12553. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12554. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12555. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12556. return;
  12557. }
  12558. th.classList.add('table-sortable', 'group');
  12559. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12560. let icon = th.querySelector('.table-sort-icon');
  12561. if (!icon) {
  12562. icon = document.createElement('span');
  12563. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12564. icon.innerHTML = '⇅';
  12565. th.appendChild(icon);
  12566. }
  12567. th.addEventListener('click', (e) => {
  12568. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12569. handleHeaderClick(table, th, colIdx);
  12570. });
  12571. });
  12572. if (!tbody._sortObserved) {
  12573. tbody._sortObserved = true;
  12574. let sortDebounceTimer = null;
  12575. const observer = new MutationObserver((mutations) => {
  12576. if (tbody._isSorting) return;
  12577. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12578. if (!hasChildChanges) return;
  12579. clearTimeout(sortDebounceTimer);
  12580. sortDebounceTimer = setTimeout(() => {
  12581. if (tbody._isSorting) return;
  12582. if (table._activeSort && table._activeSort.dir !== 'none') {
  12583. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12584. } else {
  12585. tagOriginalRowOrder(tbody);
  12586. }
  12587. }, 10);
  12588. });
  12589. observer.observe(tbody, { childList: true });
  12590. }
  12591. tagOriginalRowOrder(tbody);
  12592. }
  12593. function tagOriginalRowOrder(tbody) {
  12594. let idx = 0;
  12595. Array.from(tbody.children).forEach(tr => {
  12596. if (!tr.querySelector('td[colspan]')) {
  12597. if (!tr.hasAttribute('data-orig-idx')) {
  12598. tr.setAttribute('data-orig-idx', idx++);
  12599. }
  12600. }
  12601. });
  12602. }
  12603. function handleHeaderClick(table, th, colIdx) {
  12604. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12605. let newDir = 'asc';
  12606. if (currentSort.colIdx === colIdx) {
  12607. if (currentSort.dir === 'asc') newDir = 'desc';
  12608. else if (currentSort.dir === 'desc') newDir = 'none';
  12609. else newDir = 'asc';
  12610. } else {
  12611. newDir = 'asc';
  12612. }
  12613. table._activeSort = { colIdx, dir: newDir };
  12614. updateHeaderIcons(table, colIdx, newDir);
  12615. applyTableSort(table, colIdx, newDir, true);
  12616. }
  12617. function updateHeaderIcons(table, activeColIdx, dir) {
  12618. const thead = table.querySelector('thead');
  12619. if (!thead) return;
  12620. const ths = thead.querySelectorAll('th');
  12621. ths.forEach((th, idx) => {
  12622. const icon = th.querySelector('.table-sort-icon');
  12623. if (!icon) return;
  12624. if (idx === activeColIdx && dir !== 'none') {
  12625. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12626. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12627. th.classList.add('table-sorted-active');
  12628. } else {
  12629. icon.innerHTML = '⇅';
  12630. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12631. th.classList.remove('table-sorted-active');
  12632. }
  12633. });
  12634. }
  12635. function applyTableSort(table, colIdx, dir, userInitiated) {
  12636. const tbody = table.querySelector('tbody');
  12637. if (!tbody || tbody.children.length <= 1) return;
  12638. tbody._isSorting = true;
  12639. tagOriginalRowOrder(tbody);
  12640. // Group parent rows and any attached drawer/sub-rows
  12641. const groups = [];
  12642. let currentGroup = null;
  12643. Array.from(tbody.children).forEach(tr => {
  12644. if (tr.querySelector('td[colspan]')) {
  12645. if (currentGroup) {
  12646. currentGroup.subRows.push(tr);
  12647. } else {
  12648. groups.push({ mainRow: tr, subRows: [] });
  12649. }
  12650. } else {
  12651. currentGroup = { mainRow: tr, subRows: [] };
  12652. groups.push(currentGroup);
  12653. }
  12654. });
  12655. if (dir === 'none') {
  12656. groups.sort((a, b) => {
  12657. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12658. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12659. return idxA - idxB;
  12660. });
  12661. } else {
  12662. groups.sort((a, b) => {
  12663. const cellA = a.mainRow.children[colIdx];
  12664. const cellB = b.mainRow.children[colIdx];
  12665. const res = compareTableCells(cellA, cellB);
  12666. return dir === 'asc' ? res : -res;
  12667. });
  12668. }
  12669. // Re-append rows in sorted order
  12670. groups.forEach(g => {
  12671. tbody.appendChild(g.mainRow);
  12672. g.subRows.forEach(sub => tbody.appendChild(sub));
  12673. });
  12674. tbody._isSorting = false;
  12675. }
  12676. function getCellRawText(cell) {
  12677. if (!cell) return '';
  12678. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12679. const input = cell.querySelector('input, select');
  12680. if (input) {
  12681. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12682. return input.value;
  12683. }
  12684. return cell.innerText.trim();
  12685. }
  12686. function parseTrafficToNumber(str) {
  12687. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12688. if (!m) return null;
  12689. const num = parseFloat(m[1].replace(/,/g, ''));
  12690. if (isNaN(num)) return null;
  12691. const unit = m[2].toUpperCase();
  12692. let mult = 1;
  12693. if (unit.startsWith('K')) mult = 1024;
  12694. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12695. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12696. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12697. return num * mult;
  12698. }
  12699. function parseIpToNumber(str) {
  12700. const clean = str.replace(/^[!~]/, '').trim();
  12701. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12702. if (!m) return null;
  12703. const o1 = parseInt(m[1], 10);
  12704. const o2 = parseInt(m[2], 10);
  12705. const o3 = parseInt(m[3], 10);
  12706. const o4 = parseInt(m[4], 10);
  12707. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12708. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12709. }
  12710. function parseCompoundPackets(str) {
  12711. const m = str.match(/^([\d,]+)p/);
  12712. if (!m) return null;
  12713. return parseInt(m[1].replace(/,/g, ''), 10);
  12714. }
  12715. function compareTableCells(cellA, cellB) {
  12716. const a = getCellRawText(cellA);
  12717. const b = getCellRawText(cellB);
  12718. if (a === '' && b !== '') return 1;
  12719. if (b === '' && a !== '') return -1;
  12720. if (a === b) return 0;
  12721. // 1. IP Addresses / CIDR
  12722. const ipA = parseIpToNumber(a);
  12723. const ipB = parseIpToNumber(b);
  12724. if (ipA !== null && ipB !== null) return ipA - ipB;
  12725. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12726. const pktA = parseCompoundPackets(a);
  12727. const pktB = parseCompoundPackets(b);
  12728. if (pktA !== null && pktB !== null) return pktA - pktB;
  12729. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12730. const trafA = parseTrafficToNumber(a);
  12731. const trafB = parseTrafficToNumber(b);
  12732. if (trafA !== null && trafB !== null) return trafA - trafB;
  12733. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12734. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12735. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12736. const numA = Number(cleanNumA);
  12737. const numB = Number(cleanNumB);
  12738. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12739. return numA - numB;
  12740. }
  12741. // 5. Natural case-insensitive string compare
  12742. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12743. }
  12744. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12745. async function loadVRRP(showToastNotification = false) {
  12746. try {
  12747. const [instRes, sumRes] = await Promise.all([
  12748. fetch(`${API_BASE}/vrrp/instances`),
  12749. fetch(`${API_BASE}/vrrp/summary`)
  12750. ]);
  12751. if (instRes.ok) {
  12752. state.vrrpInstances = await instRes.json();
  12753. renderVRRP();
  12754. }
  12755. if (sumRes.ok) {
  12756. state.vrrpSummary = await sumRes.json();
  12757. renderVRRPSummary();
  12758. }
  12759. if (showToastNotification) {
  12760. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  12761. }
  12762. } catch (err) {
  12763. console.error('Failed to load VRRP:', err);
  12764. }
  12765. }
  12766. function renderVRRPSummary() {
  12767. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  12768. const elTotal = document.getElementById('vrrp-stat-total');
  12769. if (elTotal) elTotal.innerText = s.total_instances || 0;
  12770. const elMaster = document.getElementById('vrrp-stat-master');
  12771. if (elMaster) elMaster.innerText = s.master_instances || 0;
  12772. const elBackup = document.getElementById('vrrp-stat-backup');
  12773. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  12774. const bCount = document.getElementById('badge-vrrp-count');
  12775. if (bCount) bCount.innerText = s.total_instances || 0;
  12776. const dot = document.getElementById('badge-vrrp-dot');
  12777. if (dot) {
  12778. if (s.master_instances > 0) {
  12779. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12780. } else if (s.backup_instances > 0) {
  12781. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  12782. } else {
  12783. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12784. }
  12785. }
  12786. }
  12787. function renderVRRP() {
  12788. const tbody = document.getElementById('vrrp-table-tbody');
  12789. const empty = document.getElementById('vrrp-table-empty');
  12790. if (!tbody) return;
  12791. tbody.innerHTML = '';
  12792. const instances = state.vrrpInstances || [];
  12793. if (instances.length === 0) {
  12794. empty?.classList.remove('hidden');
  12795. return;
  12796. }
  12797. empty?.classList.add('hidden');
  12798. instances.forEach(inst => {
  12799. const tr = document.createElement('tr');
  12800. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  12801. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  12802. let flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-slate-800 text-slate-500 border border-slate-700">-</span>`;
  12803. if (inst.disabled) {
  12804. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  12805. } else if (inst.state === 'MASTER') {
  12806. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Master (Holding VIP)">M</span>`;
  12807. } else if (inst.state === 'BACKUP') {
  12808. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-sky-500/20 text-sky-400 border border-sky-500/40 shadow-sm" title="Backup (Standby)">B</span>`;
  12809. } else if (inst.state === 'FAULT') {
  12810. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-amber-500/20 text-amber-400 border border-amber-500/40 shadow-sm" title="Fault (Interface Down)">F</span>`;
  12811. }
  12812. // Render State Badge
  12813. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  12814. if (!inst.disabled) {
  12815. if (inst.state === 'MASTER') {
  12816. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>MASTER</span>`;
  12817. } else if (inst.state === 'BACKUP') {
  12818. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 border border-sky-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-sky-400"></span>BACKUP</span>`;
  12819. } else if (inst.state === 'FAULT') {
  12820. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>FAULT</span>`;
  12821. }
  12822. }
  12823. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  12824. tr.innerHTML = `
  12825. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  12826. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  12827. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  12828. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  12829. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  12830. <td class="py-2.5 px-3 font-mono text-emerald-400 font-bold"><span class="px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20">${escapeHtml(vipsStr)}</span></td>
  12831. <td class="py-2.5 px-3 font-mono text-center text-slate-300">${inst.preempt ? '<span class="text-emerald-400 font-semibold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  12832. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  12833. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  12834. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  12835. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12836. <button onclick="toggleVRRPState('${inst.id}', ${!inst.disabled})" class="text-xs ${inst.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${inst.disabled ? 'Enable' : 'Disable'}</button>
  12837. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12838. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12839. </td>
  12840. `;
  12841. tbody.appendChild(tr);
  12842. });
  12843. }
  12844. function populateVRRPIfaceSelect(elemId, selectedIface) {
  12845. const sel = document.getElementById(elemId);
  12846. if (!sel) return;
  12847. sel.innerHTML = '<option value="">Select interface...</option>';
  12848. const ifaces = state.interfaces || [];
  12849. ifaces.forEach(i => {
  12850. const opt = document.createElement('option');
  12851. opt.value = i.name;
  12852. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  12853. if (selectedIface && selectedIface === i.name) opt.selected = true;
  12854. sel.appendChild(opt);
  12855. });
  12856. }
  12857. function openAddVRRPModal() {
  12858. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  12859. document.getElementById('modal-vrrp-id').value = '';
  12860. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  12861. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  12862. document.getElementById('modal-vrrp-priority').value = 100;
  12863. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  12864. document.getElementById('modal-vrrp-version').value = '3';
  12865. document.getElementById('modal-vrrp-interval').value = 1;
  12866. document.getElementById('modal-vrrp-authtype').value = 'none';
  12867. document.getElementById('modal-vrrp-authpass').value = '';
  12868. document.getElementById('modal-vrrp-comment').value = '';
  12869. document.getElementById('modal-vrrp-preempt').checked = true;
  12870. document.getElementById('modal-vrrp-disabled').checked = false;
  12871. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  12872. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12873. }
  12874. function openEditVRRPModal(id) {
  12875. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  12876. if (!inst) return;
  12877. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  12878. document.getElementById('modal-vrrp-id').value = inst.id;
  12879. document.getElementById('modal-vrrp-name').value = inst.name;
  12880. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  12881. document.getElementById('modal-vrrp-priority').value = inst.priority;
  12882. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  12883. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  12884. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  12885. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  12886. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  12887. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  12888. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  12889. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  12890. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  12891. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12892. }
  12893. function closeVRRPModal() {
  12894. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  12895. }
  12896. async function submitSaveVRRP(e) {
  12897. e.preventDefault();
  12898. const id = document.getElementById('modal-vrrp-id').value;
  12899. const name = document.getElementById('modal-vrrp-name').value.trim();
  12900. const iface = document.getElementById('modal-vrrp-iface').value;
  12901. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  12902. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  12903. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  12904. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  12905. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  12906. const authType = document.getElementById('modal-vrrp-authtype').value;
  12907. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  12908. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  12909. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  12910. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  12911. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  12912. try {
  12913. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  12914. method: 'POST',
  12915. headers: { 'Content-Type': 'application/json' },
  12916. body: JSON.stringify({
  12917. id,
  12918. name,
  12919. interface: iface,
  12920. vrid,
  12921. priority,
  12922. virtual_ips: vips,
  12923. version,
  12924. interval,
  12925. auth_type: authType,
  12926. auth_password: authPass,
  12927. comment,
  12928. preempt,
  12929. disabled
  12930. })
  12931. });
  12932. if (res.ok) {
  12933. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  12934. closeVRRPModal();
  12935. loadVRRP(false);
  12936. fetchData(false);
  12937. } else {
  12938. const err = await res.text();
  12939. showToast('Error', err, 'error');
  12940. }
  12941. } catch (err) {
  12942. showToast('Error', err.message, 'error');
  12943. }
  12944. }
  12945. async function deleteVRRP(id, name) {
  12946. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  12947. try {
  12948. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12949. if (res.ok) {
  12950. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  12951. loadVRRP(false);
  12952. fetchData(false);
  12953. } else {
  12954. const err = await res.text();
  12955. showToast('Error', err, 'error');
  12956. }
  12957. } catch (err) {
  12958. showToast('Error', err.message, 'error');
  12959. }
  12960. }
  12961. async function toggleVRRPState(id, disabled) {
  12962. try {
  12963. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  12964. method: 'POST',
  12965. headers: { 'Content-Type': 'application/json' },
  12966. body: JSON.stringify({ disabled })
  12967. });
  12968. if (res.ok) {
  12969. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  12970. loadVRRP(false);
  12971. fetchData(false);
  12972. } else {
  12973. const err = await res.text();
  12974. showToast('Error', err, 'error');
  12975. }
  12976. } catch (err) {
  12977. showToast('Error', err.message, 'error');
  12978. }
  12979. }
  12980. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12981. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12982. const docTableObserver = new MutationObserver((mutations) => {
  12983. let needsInit = false;
  12984. for (const m of mutations) {
  12985. for (const node of m.addedNodes) {
  12986. if (node.nodeType === 1) {
  12987. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12988. needsInit = true;
  12989. break;
  12990. }
  12991. }
  12992. }
  12993. if (needsInit) break;
  12994. }
  12995. if (needsInit) {
  12996. initTableSorting();
  12997. }
  12998. });
  12999. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13000. }
  13001. // =========================================================================
  13002. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13003. // =========================================================================
  13004. const bwtestState = {
  13005. running: false,
  13006. pollTimer: null,
  13007. eventSource: null,
  13008. chartPoints: [],
  13009. maxChartPoints: 60,
  13010. serverConfig: null,
  13011. peakTx: 0,
  13012. peakRx: 0,
  13013. targetDuration: 10,
  13014. lastSampleIndex: 0
  13015. };
  13016. async function loadBwTestView() {
  13017. fetchBwTestServerStatus();
  13018. loadBwTestHistory();
  13019. resizeBwTestCanvas();
  13020. checkActiveBwTest();
  13021. }
  13022. async function fetchBwTestServerStatus() {
  13023. try {
  13024. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13025. if (!res.ok) return;
  13026. const s = await res.json();
  13027. bwtestState.serverConfig = s;
  13028. // Update indicator and badges
  13029. const indicator = document.getElementById('bwtest-server-indicator');
  13030. const badge = document.getElementById('bwtest-server-badge');
  13031. const sideBadge = document.getElementById('badge-bwtest-server');
  13032. if (s.enabled && s.running) {
  13033. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13034. if (badge) {
  13035. badge.innerText = `Port ${s.port} (Active)`;
  13036. badge.className = 'text-emerald-400 font-bold';
  13037. }
  13038. if (sideBadge) {
  13039. sideBadge.innerText = s.port;
  13040. sideBadge.className = 'text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-800/40 px-1.5 py-0.2 rounded-full font-mono';
  13041. }
  13042. } else {
  13043. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13044. if (badge) {
  13045. badge.innerText = `Disabled`;
  13046. badge.className = 'text-slate-500 font-bold';
  13047. }
  13048. if (sideBadge) {
  13049. sideBadge.innerText = 'Off';
  13050. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13051. }
  13052. }
  13053. // Modal fields
  13054. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13055. if (toggle) toggle.checked = !!s.enabled;
  13056. const portInp = document.getElementById('bwtest-server-port-input');
  13057. if (portInp) portInp.value = s.port || 2000;
  13058. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13059. if (actSess) actSess.innerText = s.active_sessions || 0;
  13060. const totServ = document.getElementById('bwtest-modal-total-served');
  13061. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13062. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13063. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13064. } catch (err) {
  13065. console.error('Failed to fetch BwTest server status:', err);
  13066. }
  13067. }
  13068. function openBwTestServerModal() {
  13069. fetchBwTestServerStatus();
  13070. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13071. }
  13072. function closeBwTestServerModal() {
  13073. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13074. }
  13075. async function submitBwTestServerSettings(e) {
  13076. e.preventDefault();
  13077. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13078. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13079. try {
  13080. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13081. method: 'POST',
  13082. headers: { 'Content-Type': 'application/json' },
  13083. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13084. });
  13085. if (!res.ok) {
  13086. const err = await res.json();
  13087. throw new Error(err.error || 'Failed to update server configuration');
  13088. }
  13089. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13090. closeBwTestServerModal();
  13091. fetchBwTestServerStatus();
  13092. } catch (err) {
  13093. showToast('Server Configuration Error', err.message, 'error');
  13094. }
  13095. }
  13096. function setBwTestTarget(target) {
  13097. const inp = document.getElementById('bwtest-input-target');
  13098. if (inp) inp.value = target;
  13099. }
  13100. function setBwTestProtocol(proto) {
  13101. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13102. if (hiddenInp) hiddenInp.value = proto;
  13103. const btnUdp = document.getElementById('bwtest-proto-udp');
  13104. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13105. const badge = document.getElementById('bwtest-proto-badge');
  13106. const pktField = document.getElementById('bwtest-field-pktsize');
  13107. const activeUdpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm flex items-center justify-center gap-2';
  13108. const activeTcpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-blue-600/20 border-blue-500/50 text-blue-300 shadow-sm flex items-center justify-center gap-2';
  13109. const inactiveCls = 'py-2.5 px-3 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center flex items-center justify-center gap-2';
  13110. if (proto === 'udp') {
  13111. if (btnUdp) {
  13112. btnUdp.className = activeUdpCls;
  13113. const dot = btnUdp.querySelector('span');
  13114. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13115. }
  13116. if (btnTcp) {
  13117. btnTcp.className = inactiveCls;
  13118. const dot = btnTcp.querySelector('span');
  13119. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13120. }
  13121. if (badge) {
  13122. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13123. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13124. }
  13125. if (pktField) pktField.classList.remove('opacity-40');
  13126. } else {
  13127. if (btnUdp) {
  13128. btnUdp.className = inactiveCls;
  13129. const dot = btnUdp.querySelector('span');
  13130. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13131. }
  13132. if (btnTcp) {
  13133. btnTcp.className = activeTcpCls;
  13134. const dot = btnTcp.querySelector('span');
  13135. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13136. }
  13137. if (badge) {
  13138. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13139. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13140. }
  13141. if (pktField) pktField.classList.add('opacity-40');
  13142. }
  13143. }
  13144. function setBwTestDirection(dir) {
  13145. const hiddenInp = document.getElementById('bwtest-input-direction');
  13146. if (hiddenInp) hiddenInp.value = dir;
  13147. const btnBoth = document.getElementById('bwtest-dir-both');
  13148. const btnTx = document.getElementById('bwtest-dir-tx');
  13149. const btnRx = document.getElementById('bwtest-dir-rx');
  13150. const activeCls = 'py-2 px-2 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm';
  13151. const inactiveCls = 'py-2 px-2 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center';
  13152. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13153. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13154. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13155. }
  13156. function setBwTestLimit(bps) {
  13157. const sel = document.getElementById('bwtest-input-limit');
  13158. if (sel) sel.value = String(bps);
  13159. }
  13160. async function checkActiveBwTest() {
  13161. try {
  13162. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13163. if (!res.ok) return;
  13164. const st = await res.json();
  13165. if (st.running) {
  13166. setBwTestRunningUI(true);
  13167. if (st.current_sample) handleBwTestSample(st.current_sample);
  13168. startBwTestTelemetry();
  13169. }
  13170. } catch (err) {
  13171. console.error('Failed to check active BwTest:', err);
  13172. }
  13173. }
  13174. async function startBwTest(e) {
  13175. if (e && e.preventDefault) e.preventDefault();
  13176. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13177. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13178. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13179. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13180. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13181. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13182. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13183. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13184. bwtestState.targetDuration = duration;
  13185. bwtestState.chartPoints = [];
  13186. bwtestState.peakTx = 0;
  13187. bwtestState.peakRx = 0;
  13188. bwtestState.lastSampleIndex = 0;
  13189. // Clear UI elements
  13190. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13191. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13192. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13193. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13194. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13195. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13196. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13197. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13198. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13199. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13200. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13201. const tbody = document.getElementById('bwtest-samples-tbody');
  13202. if (tbody) tbody.innerHTML = '';
  13203. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13204. setBwTestRunningUI(true);
  13205. try {
  13206. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13207. method: 'POST',
  13208. headers: { 'Content-Type': 'application/json' },
  13209. body: JSON.stringify({
  13210. target,
  13211. port,
  13212. direction,
  13213. protocol,
  13214. bandwidth_limit,
  13215. packet_size,
  13216. streams,
  13217. duration
  13218. })
  13219. });
  13220. if (!res.ok) {
  13221. const err = await res.json();
  13222. throw new Error(err.error || 'Failed to start bandwidth test');
  13223. }
  13224. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13225. startBwTestTelemetry();
  13226. } catch (err) {
  13227. setBwTestRunningUI(false);
  13228. showToast('Start Failed', err.message, 'error');
  13229. }
  13230. }
  13231. function setBwTestRunningUI(running) {
  13232. bwtestState.running = running;
  13233. const startBtn = document.getElementById('bwtest-btn-start');
  13234. const stopBtn = document.getElementById('bwtest-btn-stop');
  13235. const badge = document.getElementById('bwtest-run-status-badge');
  13236. const ph = document.getElementById('bwtest-chart-placeholder');
  13237. if (running) {
  13238. if (startBtn) {
  13239. startBtn.disabled = true;
  13240. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13241. }
  13242. if (stopBtn) {
  13243. stopBtn.disabled = false;
  13244. stopBtn.classList.remove('opacity-40');
  13245. }
  13246. if (badge) {
  13247. badge.innerText = 'TESTING...';
  13248. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold animate-pulse';
  13249. }
  13250. if (ph) ph.style.display = 'none';
  13251. } else {
  13252. if (startBtn) {
  13253. startBtn.disabled = false;
  13254. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13255. }
  13256. if (stopBtn) {
  13257. stopBtn.disabled = true;
  13258. stopBtn.classList.add('opacity-40');
  13259. }
  13260. if (badge) {
  13261. badge.innerText = 'IDLE';
  13262. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13263. }
  13264. }
  13265. }
  13266. async function stopBwTest() {
  13267. try {
  13268. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13269. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13270. } catch (err) {
  13271. console.error('Failed to stop test:', err);
  13272. }
  13273. }
  13274. function startBwTestTelemetry() {
  13275. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13276. bwtestState.pollTimer = setInterval(async () => {
  13277. try {
  13278. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13279. if (!res.ok) return;
  13280. const st = await res.json();
  13281. if (st.recent_samples && st.recent_samples.length > 0) {
  13282. // Process new samples
  13283. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13284. newSamples.forEach(s => handleBwTestSample(s));
  13285. bwtestState.lastSampleIndex = st.recent_samples.length;
  13286. }
  13287. if (!st.running) {
  13288. clearInterval(bwtestState.pollTimer);
  13289. bwtestState.pollTimer = null;
  13290. setBwTestRunningUI(false);
  13291. handleBwTestFinish(st.summary, st.error);
  13292. }
  13293. } catch (err) {
  13294. console.error('BwTest polling error:', err);
  13295. }
  13296. }, 400);
  13297. }
  13298. function handleBwTestSample(s) {
  13299. if (!s) return;
  13300. const txMbps = s.tx_mbps || 0;
  13301. const rxMbps = s.rx_mbps || 0;
  13302. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13303. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13304. // KPI updates
  13305. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13306. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13307. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13308. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13309. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13310. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13311. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13312. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13313. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13314. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13315. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13316. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13317. const elLoss = document.getElementById('bwtest-stat-loss');
  13318. if (elLoss) {
  13319. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13320. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13321. }
  13322. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13323. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13324. const elJitter = document.getElementById('bwtest-stat-jitter');
  13325. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13326. const elTime = document.getElementById('bwtest-stat-time');
  13327. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13328. const elData = document.getElementById('bwtest-stat-data');
  13329. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13330. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13331. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13332. // Append point to chart buffer
  13333. bwtestState.chartPoints.push({
  13334. elapsed: s.elapsed_sec || 0,
  13335. tx: txMbps,
  13336. rx: rxMbps
  13337. });
  13338. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13339. bwtestState.chartPoints.shift();
  13340. }
  13341. drawBwTestChart();
  13342. // Add row to breakdown table
  13343. const tbody = document.getElementById('bwtest-samples-tbody');
  13344. if (tbody) {
  13345. const tr = document.createElement('tr');
  13346. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13347. tr.innerHTML = `
  13348. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13349. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13350. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13351. <td class="py-1.5 px-3 ${(s.loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'}">${(s.loss_pct || 0).toFixed(1)}%</td>
  13352. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13353. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13354. `;
  13355. tbody.insertBefore(tr, tbody.firstChild);
  13356. const countEl = document.getElementById('bwtest-sample-count');
  13357. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13358. }
  13359. }
  13360. function handleBwTestFinish(summary, error) {
  13361. const badge = document.getElementById('bwtest-run-status-badge');
  13362. if (error) {
  13363. showToast('Benchmark Error', error, 'error');
  13364. if (badge) {
  13365. badge.innerText = 'ERROR';
  13366. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold';
  13367. }
  13368. } else if (summary) {
  13369. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13370. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13371. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13372. if (badge) {
  13373. badge.innerText = 'COMPLETED';
  13374. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold';
  13375. }
  13376. }
  13377. loadBwTestHistory();
  13378. fetchBwTestServerStatus();
  13379. }
  13380. function resizeBwTestCanvas() {
  13381. const canvas = document.getElementById('bwtest-chart');
  13382. if (!canvas || !canvas.parentElement) return;
  13383. const rect = canvas.parentElement.getBoundingClientRect();
  13384. const dpr = window.devicePixelRatio || 1;
  13385. canvas.width = rect.width * dpr;
  13386. canvas.height = rect.height * dpr;
  13387. const ctx = canvas.getContext('2d');
  13388. ctx.scale(dpr, dpr);
  13389. drawBwTestChart();
  13390. }
  13391. window.addEventListener('resize', () => {
  13392. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13393. });
  13394. function drawBwTestChart() {
  13395. const canvas = document.getElementById('bwtest-chart');
  13396. if (!canvas) return;
  13397. const ctx = canvas.getContext('2d');
  13398. const dpr = window.devicePixelRatio || 1;
  13399. const width = canvas.width / dpr;
  13400. const height = canvas.height / dpr;
  13401. ctx.clearRect(0, 0, width, height);
  13402. const points = bwtestState.chartPoints;
  13403. if (!points || points.length === 0) return;
  13404. // Determine scale ceiling
  13405. let maxRate = 10;
  13406. for (const p of points) {
  13407. if (p.tx > maxRate) maxRate = p.tx;
  13408. if (p.rx > maxRate) maxRate = p.rx;
  13409. }
  13410. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13411. const paddingLeft = 55;
  13412. const paddingBottom = 24;
  13413. const paddingTop = 12;
  13414. const paddingRight = 16;
  13415. const chartW = width - paddingLeft - paddingRight;
  13416. const chartH = height - paddingTop - paddingBottom;
  13417. // Grid Lines and Y-Axis labels
  13418. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13419. ctx.lineWidth = 1;
  13420. ctx.fillStyle = '#94a3b8';
  13421. ctx.font = '10px monospace';
  13422. ctx.textAlign = 'right';
  13423. const gridSteps = 4;
  13424. for (let i = 0; i <= gridSteps; i++) {
  13425. const val = (maxRate / gridSteps) * i;
  13426. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13427. ctx.beginPath();
  13428. ctx.moveTo(paddingLeft, y);
  13429. ctx.lineTo(width - paddingRight, y);
  13430. ctx.stroke();
  13431. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13432. }
  13433. // Draw TX Line (Cyan #22d3ee)
  13434. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13435. // Draw RX Line (Purple #a855f7)
  13436. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13437. }
  13438. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13439. if (points.length < 2) return;
  13440. const stepX = w / Math.max(points.length - 1, 1);
  13441. // Gradient area fill
  13442. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13443. grad.addColorStop(0, fillColor);
  13444. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13445. ctx.beginPath();
  13446. points.forEach((p, idx) => {
  13447. const x = left + idx * stepX;
  13448. const val = valFn(p);
  13449. const y = top + h - (val / maxVal) * h;
  13450. if (idx === 0) {
  13451. ctx.moveTo(x, y);
  13452. } else {
  13453. ctx.lineTo(x, y);
  13454. }
  13455. });
  13456. // Complete path for fill
  13457. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13458. ctx.lineTo(left, top + h);
  13459. ctx.closePath();
  13460. ctx.fillStyle = grad;
  13461. ctx.fill();
  13462. // Draw line stroke
  13463. ctx.beginPath();
  13464. ctx.lineWidth = 2.5;
  13465. ctx.strokeStyle = strokeColor;
  13466. points.forEach((p, idx) => {
  13467. const x = left + idx * stepX;
  13468. const val = valFn(p);
  13469. const y = top + h - (val / maxVal) * h;
  13470. if (idx === 0) {
  13471. ctx.moveTo(x, y);
  13472. } else {
  13473. ctx.lineTo(x, y);
  13474. }
  13475. });
  13476. ctx.stroke();
  13477. // Draw end point halo
  13478. const lastP = points[points.length - 1];
  13479. const lastX = left + (points.length - 1) * stepX;
  13480. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13481. ctx.fillStyle = strokeColor;
  13482. ctx.beginPath();
  13483. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13484. ctx.fill();
  13485. }
  13486. async function loadBwTestHistory() {
  13487. try {
  13488. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13489. if (!res.ok) return;
  13490. const list = await res.json();
  13491. renderBwTestHistory(Array.isArray(list) ? list : []);
  13492. } catch (err) {
  13493. console.error('Failed to load BwTest history:', err);
  13494. }
  13495. }
  13496. function renderBwTestHistory(list) {
  13497. const tbody = document.getElementById('bwtest-history-tbody');
  13498. if (!tbody) return;
  13499. if (list.length === 0) {
  13500. tbody.innerHTML = `<tr><td colspan="10" class="p-6 text-center text-slate-500 text-xs font-sans">No past benchmark runs recorded yet.</td></tr>`;
  13501. return;
  13502. }
  13503. tbody.innerHTML = '';
  13504. list.forEach(item => {
  13505. const s = item.summary || {};
  13506. const tr = document.createElement('tr');
  13507. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13508. const dirBadge = item.direction === 'both'
  13509. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 uppercase font-semibold">Both</span>`
  13510. : item.direction === 'tx'
  13511. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 uppercase font-semibold">TX Only</span>`
  13512. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 uppercase font-semibold">RX Only</span>`;
  13513. const protoBadge = item.protocol === 'tcp'
  13514. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-semibold uppercase">TCP</span>`
  13515. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/30 font-semibold uppercase">UDP</span>`;
  13516. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13517. tr.innerHTML = `
  13518. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13519. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13520. <td class="py-2.5 px-4">${protoBadge}</td>
  13521. <td class="py-2.5 px-4">${dirBadge}</td>
  13522. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13523. <td class="py-2.5 px-4 font-bold text-cyan-400 font-mono">${(s.avg_tx_mbps || 0).toFixed(1)} / ${(s.peak_tx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13524. <td class="py-2.5 px-4 font-bold text-purple-400 font-mono">${(s.avg_rx_mbps || 0).toFixed(1)} / ${(s.peak_rx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13525. <td class="py-2.5 px-4 ${(s.avg_loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'} font-mono">${(s.avg_loss_pct || 0).toFixed(1)}% <span class="text-[10px] text-slate-400 font-normal">(${s.total_lost_packets || 0})</span></td>
  13526. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13527. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13528. `;
  13529. tbody.appendChild(tr);
  13530. });
  13531. }
  13532. // ======================== SETTINGS & ROUTER DNS ========================
  13533. state.settingsSubTab = 'dns';
  13534. state.dnsSettings = null;
  13535. state.dnsStaticRecords = [];
  13536. state.dnsStatus = null;
  13537. function switchSettingsSubTab(sub) {
  13538. state.settingsSubTab = sub;
  13539. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13540. const btnSys = document.getElementById('btn-settings-subtab-system');
  13541. const tabDns = document.getElementById('settings-subtab-dns');
  13542. const tabSys = document.getElementById('settings-subtab-system');
  13543. if (sub === 'dns') {
  13544. if (btnDns) {
  13545. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13546. }
  13547. if (btnSys) {
  13548. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13549. }
  13550. tabDns?.classList.remove('hidden');
  13551. tabSys?.classList.add('hidden');
  13552. loadDNSSettings();
  13553. } else {
  13554. if (btnSys) {
  13555. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13556. }
  13557. if (btnDns) {
  13558. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13559. }
  13560. tabSys?.classList.remove('hidden');
  13561. tabDns?.classList.add('hidden');
  13562. loadSystemSettings();
  13563. }
  13564. }
  13565. async function loadSettingsData(showLoading = false) {
  13566. if (state.settingsSubTab === 'system') {
  13567. await loadSystemSettings();
  13568. } else {
  13569. await loadDNSSettings();
  13570. }
  13571. }
  13572. async function loadDNSSettings() {
  13573. try {
  13574. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13575. fetch(`${API_BASE}/dns/settings`),
  13576. fetch(`${API_BASE}/dns/static`),
  13577. fetch(`${API_BASE}/dns/status`)
  13578. ]);
  13579. if (settingsRes.ok) {
  13580. state.dnsSettings = await settingsRes.json();
  13581. populateDNSSettingsForm(state.dnsSettings);
  13582. }
  13583. if (staticRes.ok) {
  13584. state.dnsStaticRecords = await staticRes.json();
  13585. renderStaticDNSList();
  13586. }
  13587. if (statusRes.ok) {
  13588. state.dnsStatus = await statusRes.json();
  13589. updateDNSStatusView(state.dnsStatus);
  13590. }
  13591. } catch (err) {
  13592. console.error('Failed to load DNS settings:', err);
  13593. }
  13594. }
  13595. function populateDNSSettingsForm(s) {
  13596. if (!s) return;
  13597. const dnsForm = document.getElementById('form-dns-settings');
  13598. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13599. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13600. if (dynamicEl) {
  13601. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13602. dynamicEl.innerHTML = s.dynamic_servers.map(d => `<span class="px-2 py-0.5 rounded bg-cyan-950 text-cyan-300 border border-cyan-800 font-mono">${escapeHtml(d)}</span>`).join(' ');
  13603. } else {
  13604. dynamicEl.innerText = 'None';
  13605. }
  13606. }
  13607. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13608. if (isEditing) return;
  13609. const serversInput = document.getElementById('dns-servers-input');
  13610. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13611. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13612. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13613. const domainInput = document.getElementById('dns-domain-input');
  13614. if (domainInput) domainInput.value = s.domain || '';
  13615. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13616. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13617. }
  13618. function updateDNSStatusView(st) {
  13619. if (!st) return;
  13620. const preview = document.getElementById('dns-resolv-preview');
  13621. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13622. const pillText = document.getElementById('dns-live-status-text');
  13623. const pill = document.getElementById('dns-live-status-pill');
  13624. if (pill && pillText) {
  13625. if (st.service_running) {
  13626. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center gap-1.5';
  13627. pillText.innerText = 'DNS Service Active';
  13628. } else {
  13629. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/30 flex items-center gap-1.5';
  13630. pillText.innerText = 'DNS Service Inactive';
  13631. }
  13632. }
  13633. }
  13634. function appendDNSPreset(preset) {
  13635. const input = document.getElementById('dns-servers-input');
  13636. if (!input) return;
  13637. const dnsForm = document.getElementById('form-dns-settings');
  13638. if (dnsForm) dnsForm.dataset.dirty = 'true';
  13639. const current = input.value.trim();
  13640. if (!current) {
  13641. input.value = preset;
  13642. } else {
  13643. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13644. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13645. toAdd.forEach(ip => {
  13646. if (!existing.includes(ip)) existing.push(ip);
  13647. });
  13648. input.value = existing.join(', ');
  13649. }
  13650. }
  13651. async function saveDNSSettings(e) {
  13652. e.preventDefault();
  13653. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13654. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13655. if (servers.length === 0) {
  13656. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13657. return;
  13658. }
  13659. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13660. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13661. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13662. try {
  13663. const res = await fetch(`${API_BASE}/dns/settings`, {
  13664. method: 'POST',
  13665. headers: { 'Content-Type': 'application/json' },
  13666. body: JSON.stringify({
  13667. servers: servers,
  13668. cache_size: cacheSize,
  13669. domain: domain,
  13670. allow_remote_requests: allowRemote
  13671. })
  13672. });
  13673. const data = await res.json();
  13674. if (res.ok) {
  13675. const dnsForm = document.getElementById('form-dns-settings');
  13676. if (dnsForm) dnsForm.dataset.dirty = 'false';
  13677. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  13678. loadDNSSettings();
  13679. } else {
  13680. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  13681. }
  13682. } catch (err) {
  13683. showToast('Error', err.message, 'error');
  13684. }
  13685. }
  13686. async function flushDNSCache() {
  13687. try {
  13688. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  13689. if (res.ok) {
  13690. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  13691. loadDNSSettings();
  13692. } else {
  13693. const err = await res.json();
  13694. showToast('Error', err.error || 'Failed to flush cache', 'error');
  13695. }
  13696. } catch (err) {
  13697. showToast('Error', err.message, 'error');
  13698. }
  13699. }
  13700. function renderStaticDNSList() {
  13701. const tbody = document.getElementById('dns-static-tbody');
  13702. const empty = document.getElementById('dns-static-empty');
  13703. const badge = document.getElementById('dns-static-count-badge');
  13704. if (!tbody) return;
  13705. tbody.innerHTML = '';
  13706. const records = state.dnsStaticRecords || [];
  13707. if (badge) badge.innerText = `${records.length} Records`;
  13708. if (records.length === 0) {
  13709. empty?.classList.remove('hidden');
  13710. return;
  13711. }
  13712. empty?.classList.add('hidden');
  13713. records.forEach(rec => {
  13714. const tr = document.createElement('tr');
  13715. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  13716. tr.innerHTML = `
  13717. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  13718. <td class="py-2.5 px-4">
  13719. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  13720. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  13721. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  13722. }">
  13723. ${rec.type || 'A'}
  13724. </span>
  13725. </td>
  13726. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  13727. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  13728. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  13729. <td class="py-2.5 px-4">
  13730. <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold ${rec.disabled ? 'bg-slate-800 text-slate-500' : 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'}">
  13731. ${rec.disabled ? 'Disabled' : 'Active'}
  13732. </span>
  13733. </td>
  13734. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  13735. <button onclick="toggleStaticDNS('${rec.id}', ${!rec.disabled})" class="text-xs ${rec.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${rec.disabled ? 'Enable' : 'Disable'}</button>
  13736. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  13737. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  13738. </td>
  13739. `;
  13740. tbody.appendChild(tr);
  13741. });
  13742. }
  13743. function openStaticDNSModal(id = null) {
  13744. const modal = document.getElementById('modal-static-dns');
  13745. const title = document.getElementById('modal-static-dns-title');
  13746. const form = document.getElementById('form-static-dns');
  13747. if (!modal || !form) return;
  13748. form.reset();
  13749. document.getElementById('modal-static-dns-id').value = '';
  13750. if (id) {
  13751. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  13752. if (rec) {
  13753. if (title) title.innerText = 'Edit Static DNS Record';
  13754. document.getElementById('modal-static-dns-id').value = rec.id;
  13755. document.getElementById('modal-static-dns-name').value = rec.name;
  13756. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  13757. document.getElementById('modal-static-dns-addr').value = rec.address;
  13758. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  13759. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  13760. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  13761. }
  13762. } else {
  13763. if (title) title.innerText = 'Add Static DNS Record';
  13764. }
  13765. modal.classList.remove('hidden');
  13766. }
  13767. function closeStaticDNSModal() {
  13768. document.getElementById('modal-static-dns')?.classList.add('hidden');
  13769. }
  13770. async function submitSaveStaticDNS(e) {
  13771. e.preventDefault();
  13772. const id = document.getElementById('modal-static-dns-id')?.value || '';
  13773. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  13774. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  13775. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  13776. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  13777. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  13778. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  13779. if (!name || !address) {
  13780. showToast('Validation Error', 'Name and Target Address are required', 'error');
  13781. return;
  13782. }
  13783. try {
  13784. const res = await fetch(`${API_BASE}/dns/static`, {
  13785. method: 'POST',
  13786. headers: { 'Content-Type': 'application/json' },
  13787. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  13788. });
  13789. const data = await res.json();
  13790. if (res.ok) {
  13791. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  13792. closeStaticDNSModal();
  13793. loadDNSSettings();
  13794. } else {
  13795. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  13796. }
  13797. } catch (err) {
  13798. showToast('Error', err.message, 'error');
  13799. }
  13800. }
  13801. async function deleteStaticDNS(id) {
  13802. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  13803. try {
  13804. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13805. if (res.ok) {
  13806. showToast('Deleted', 'Static DNS record deleted', 'success');
  13807. loadDNSSettings();
  13808. }
  13809. } catch (err) {
  13810. showToast('Error', err.message, 'error');
  13811. }
  13812. }
  13813. async function toggleStaticDNS(id, disabled) {
  13814. try {
  13815. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  13816. method: 'POST',
  13817. headers: { 'Content-Type': 'application/json' },
  13818. body: JSON.stringify({ disabled })
  13819. });
  13820. if (res.ok) {
  13821. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  13822. loadDNSSettings();
  13823. }
  13824. } catch (err) {
  13825. showToast('Error', err.message, 'error');
  13826. }
  13827. }
  13828. async function loadSystemSettings() {
  13829. try {
  13830. const sysForm = document.getElementById('form-system-settings');
  13831. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  13832. const res = await fetch(`${API_BASE}/system/settings`);
  13833. if (res.ok) {
  13834. const data = await res.json();
  13835. if (!isEditing) {
  13836. const hostInput = document.getElementById('system-hostname-input');
  13837. if (hostInput) hostInput.value = data.hostname || '';
  13838. const tzInput = document.getElementById('system-timezone-input');
  13839. if (tzInput && data.timezone) tzInput.value = data.timezone;
  13840. }
  13841. }
  13842. } catch (err) {
  13843. console.error('Failed to load system settings:', err);
  13844. }
  13845. }
  13846. async function saveSystemSettings(e) {
  13847. e.preventDefault();
  13848. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  13849. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  13850. try {
  13851. const res = await fetch(`${API_BASE}/system/settings`, {
  13852. method: 'POST',
  13853. headers: { 'Content-Type': 'application/json' },
  13854. body: JSON.stringify({ hostname, timezone })
  13855. });
  13856. const data = await res.json();
  13857. if (res.ok) {
  13858. const sysForm = document.getElementById('form-system-settings');
  13859. if (sysForm) sysForm.dataset.dirty = 'false';
  13860. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  13861. const sideH = document.getElementById('side-hostname');
  13862. if (sideH) sideH.innerText = data.hostname;
  13863. } else {
  13864. showToast('Error', data.error || 'Failed to save system settings', 'error');
  13865. }
  13866. } catch (err) {
  13867. showToast('Error', err.message, 'error');
  13868. }
  13869. }