ppp_server.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. package vpn
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "net"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "syscall"
  17. "time"
  18. )
  19. // ======================== PPP Profiles (/ppp profile) ========================
  20. type PPPProfile struct {
  21. ID string `json:"id"`
  22. Name string `json:"name"` // e.g. "default", "default-encryption", "pool-lan"
  23. LocalAddress string `json:"local_address"` // e.g. "10.10.10.1" (server IP on tunnel)
  24. RemoteAddress string `json:"remote_address"` // e.g. "10.10.10.10-10.10.10.50" or "10.10.10.10"
  25. DNSServers string `json:"dns_servers"` // e.g. "1.1.1.1,8.8.8.8"
  26. UseEncryption string `json:"use_encryption"` // "no", "yes", "required" (MPPE-128)
  27. OnlyOne bool `json:"only_one"` // One session per user
  28. Comment string `json:"comment,omitempty"`
  29. }
  30. // ======================== PPP Secrets (/ppp secret) ========================
  31. type PPPSecret struct {
  32. ID string `json:"id"`
  33. Name string `json:"name"` // Username
  34. Password string `json:"password"` // Password
  35. Service string `json:"service"` // "any", "pppoe", "pptp", "l2tp"
  36. Profile string `json:"profile"` // Profile name
  37. LocalAddress string `json:"local_address,omitempty"`
  38. RemoteAddress string `json:"remote_address,omitempty"`
  39. CallerID string `json:"caller_id,omitempty"`
  40. Comment string `json:"comment,omitempty"`
  41. Disabled bool `json:"disabled"`
  42. }
  43. // ======================== PPPoE Server (/interface pppoe-server server) ========================
  44. type PPPoEServerConfig struct {
  45. Enabled bool `json:"enabled"`
  46. ServiceName string `json:"service_name"` // e.g. "isp-service"
  47. Interface string `json:"interface"` // e.g. "eth0", "eth0.10", "br0"
  48. DefaultProfile string `json:"default_profile"`
  49. OneSessionPerHost bool `json:"one_session_per_host"`
  50. MaxMTU int `json:"max_mtu"` // default 1480 / 1492
  51. MaxMRU int `json:"max_mru"` // default 1480 / 1492
  52. Running bool `json:"running"`
  53. ActiveSessions int `json:"active_sessions"`
  54. LastError string `json:"last_error,omitempty"`
  55. }
  56. // ======================== PPTP Server (/interface pptp-server server) ========================
  57. type PPTPServerConfig struct {
  58. Enabled bool `json:"enabled"`
  59. Port int `json:"port"` // default 1723
  60. DefaultProfile string `json:"default_profile"`
  61. RequireMPPE bool `json:"require_mppe"` // 128-bit MPPE
  62. Running bool `json:"running"`
  63. ActiveSessions int `json:"active_sessions"`
  64. LastError string `json:"last_error,omitempty"`
  65. }
  66. // ======================== L2TP Server (/interface l2tp-server server) ========================
  67. type L2TPServerConfig struct {
  68. Enabled bool `json:"enabled"`
  69. Port int `json:"port"` // default 1701
  70. DefaultProfile string `json:"default_profile"`
  71. UseIPSec string `json:"use_ipsec"` // "no", "yes", "required"
  72. IPSecSecret string `json:"ipsec_secret,omitempty"`
  73. Running bool `json:"running"`
  74. ActiveSessions int `json:"active_sessions"`
  75. LastError string `json:"last_error,omitempty"`
  76. }
  77. // ======================== IPSec Roadwarrior Server ========================
  78. type IPSecServerConfig struct {
  79. Enabled bool `json:"enabled"`
  80. PoolAddress string `json:"pool_address"` // e.g. "10.10.30.0/24"
  81. PresharedKey string `json:"preshared_key"`
  82. LocalSubnet string `json:"local_subnet"` // e.g. "0.0.0.0/0"
  83. DNSServers string `json:"dns_servers"` // e.g. "1.1.1.1,8.8.8.8"
  84. Running bool `json:"running"`
  85. ActiveSessions int `json:"active_sessions"`
  86. LastError string `json:"last_error,omitempty"`
  87. }
  88. // ======================== Active PPP Session (/ppp active) ========================
  89. type ActivePPPSession struct {
  90. ID string `json:"id"`
  91. Interface string `json:"interface"` // e.g. "ppp0"
  92. Username string `json:"username"`
  93. Service string `json:"service"` // "pppoe", "pptp", "l2tp"
  94. CallerID string `json:"caller_id,omitempty"`
  95. Address string `json:"address"` // client assigned IP
  96. Uptime string `json:"uptime"`
  97. RxBytes uint64 `json:"rx_bytes"`
  98. TxBytes uint64 `json:"tx_bytes"`
  99. RxHuman string `json:"rx_human,omitempty"`
  100. TxHuman string `json:"tx_human,omitempty"`
  101. }
  102. // ======================== Central PPP & Server Manager ========================
  103. type PPPServerManager struct {
  104. mu sync.RWMutex
  105. baseDir string
  106. pppDir string
  107. profiles map[string]*PPPProfile
  108. secrets map[string]*PPPSecret
  109. pppoeServer PPPoEServerConfig
  110. pptpServer PPTPServerConfig
  111. l2tpServer L2TPServerConfig
  112. ipsecServer IPSecServerConfig
  113. pppoePIDFile string
  114. }
  115. func NewPPPServerManager() *PPPServerManager {
  116. mgr := &PPPServerManager{
  117. baseDir: "/etc/debtik/vpn",
  118. pppDir: "/etc/ppp",
  119. profiles: make(map[string]*PPPProfile),
  120. secrets: make(map[string]*PPPSecret),
  121. pppoePIDFile: "/var/run/debtik-pppoe-server.pid",
  122. pppoeServer: PPPoEServerConfig{
  123. Enabled: false,
  124. ServiceName: "debtik-pppoe",
  125. Interface: "eth0",
  126. DefaultProfile: "default",
  127. MaxMTU: 1480,
  128. MaxMRU: 1480,
  129. },
  130. pptpServer: PPTPServerConfig{
  131. Enabled: false,
  132. Port: 1723,
  133. DefaultProfile: "default-encryption",
  134. RequireMPPE: true,
  135. },
  136. l2tpServer: L2TPServerConfig{
  137. Enabled: false,
  138. Port: 1701,
  139. DefaultProfile: "default",
  140. UseIPSec: "no",
  141. },
  142. ipsecServer: IPSecServerConfig{
  143. Enabled: false,
  144. PoolAddress: "10.10.30.0/24",
  145. PresharedKey: "DebTikSecret123",
  146. LocalSubnet: "0.0.0.0/0",
  147. DNSServers: "1.1.1.1,8.8.8.8",
  148. },
  149. }
  150. mgr.initDefaults()
  151. mgr.loadAll()
  152. if err := mgr.SyncSecretsToSystem(); err != nil {
  153. log.Printf("[PPP] Failed to synchronize secrets: %v", err)
  154. }
  155. mgr.applyAll()
  156. return mgr
  157. }
  158. func (m *PPPServerManager) initDefaults() {
  159. m.profiles["default"] = &PPPProfile{
  160. ID: "default",
  161. Name: "default",
  162. LocalAddress: "10.10.10.1",
  163. RemoteAddress: "10.10.10.10-10.10.10.50",
  164. DNSServers: "1.1.1.1,8.8.8.8",
  165. UseEncryption: "no",
  166. OnlyOne: true,
  167. Comment: "Default PPP profile for unencrypted/standard tunnels",
  168. }
  169. m.profiles["default-encryption"] = &PPPProfile{
  170. ID: "default-encryption",
  171. Name: "default-encryption",
  172. LocalAddress: "10.10.20.1",
  173. RemoteAddress: "10.10.20.10-10.10.20.50",
  174. DNSServers: "1.1.1.1,8.8.8.8",
  175. UseEncryption: "required",
  176. OnlyOne: true,
  177. Comment: "Default PPP profile with required MPPE-128 encryption",
  178. }
  179. }
  180. func (m *PPPServerManager) loadAll() {
  181. _ = os.MkdirAll(m.baseDir, 0755)
  182. // Profiles
  183. if data, err := os.ReadFile(filepath.Join(m.baseDir, "ppp_profiles.json")); err == nil {
  184. var list []*PPPProfile
  185. if err := json.Unmarshal(data, &list); err == nil {
  186. for _, p := range list {
  187. m.profiles[p.Name] = p
  188. }
  189. }
  190. }
  191. // Secrets
  192. if data, err := os.ReadFile(filepath.Join(m.baseDir, "ppp_secrets.json")); err == nil {
  193. var list []*PPPSecret
  194. if err := json.Unmarshal(data, &list); err == nil {
  195. for _, s := range list {
  196. m.secrets[s.ID] = s
  197. }
  198. }
  199. }
  200. // PPPoE Server
  201. if data, err := os.ReadFile(filepath.Join(m.baseDir, "pppoe_server.json")); err == nil {
  202. _ = json.Unmarshal(data, &m.pppoeServer)
  203. }
  204. // PPTP Server
  205. if data, err := os.ReadFile(filepath.Join(m.baseDir, "pptp_server.json")); err == nil {
  206. _ = json.Unmarshal(data, &m.pptpServer)
  207. }
  208. // L2TP Server
  209. if data, err := os.ReadFile(filepath.Join(m.baseDir, "l2tp_server.json")); err == nil {
  210. _ = json.Unmarshal(data, &m.l2tpServer)
  211. }
  212. // IPSec Server
  213. if data, err := os.ReadFile(filepath.Join(m.baseDir, "ipsec_server.json")); err == nil {
  214. _ = json.Unmarshal(data, &m.ipsecServer)
  215. }
  216. }
  217. func (m *PPPServerManager) save(filename string, v any) error {
  218. if err := os.MkdirAll(m.baseDir, 0755); err != nil {
  219. return err
  220. }
  221. data, err := json.MarshalIndent(v, "", " ")
  222. if err != nil {
  223. return err
  224. }
  225. f, err := os.CreateTemp(m.baseDir, ".ppp-*.tmp")
  226. if err != nil {
  227. return err
  228. }
  229. name := f.Name()
  230. defer os.Remove(name)
  231. if err = f.Chmod(0600); err == nil {
  232. _, err = f.Write(data)
  233. }
  234. if err == nil {
  235. err = f.Sync()
  236. }
  237. if closeErr := f.Close(); err == nil {
  238. err = closeErr
  239. }
  240. if err != nil {
  241. return err
  242. }
  243. return os.Rename(name, filepath.Join(m.baseDir, filename))
  244. }
  245. // ======================== PPP Profiles CRUD ========================
  246. func (m *PPPServerManager) ListProfiles() []*PPPProfile {
  247. m.mu.RLock()
  248. defer m.mu.RUnlock()
  249. list := make([]*PPPProfile, 0)
  250. for _, p := range m.profiles {
  251. list = append(list, p)
  252. }
  253. sort.Slice(list, func(i, j int) bool {
  254. return list[i].Name < list[j].Name
  255. })
  256. return list
  257. }
  258. func (m *PPPServerManager) GetProfile(name string) *PPPProfile {
  259. m.mu.RLock()
  260. defer m.mu.RUnlock()
  261. return m.profiles[name]
  262. }
  263. func (m *PPPServerManager) SaveProfile(p *PPPProfile) error {
  264. m.mu.Lock()
  265. defer m.mu.Unlock()
  266. if p.Name == "" {
  267. return fmt.Errorf("profile name is required")
  268. }
  269. if p.LocalAddress == "" {
  270. p.LocalAddress = "10.10.10.1"
  271. }
  272. if p.RemoteAddress == "" {
  273. p.RemoteAddress = "10.10.10.10-10.10.10.50"
  274. }
  275. if p.ID == "" {
  276. p.ID = p.Name
  277. }
  278. m.profiles[p.Name] = p
  279. var list []*PPPProfile
  280. for _, pr := range m.profiles {
  281. list = append(list, pr)
  282. }
  283. if err := m.save("ppp_profiles.json", list); err != nil {
  284. return err
  285. }
  286. // Re-synchronize secrets to system since secrets may inherit IP addresses from this profile
  287. if err := m.syncSecretsToSystemLocked(); err != nil {
  288. return fmt.Errorf("profile saved, but PPP secrets could not be applied: %w", err)
  289. }
  290. // Re-apply servers if their configured DefaultProfile was updated
  291. var applyErrors []error
  292. if m.l2tpServer.Enabled && m.l2tpServer.DefaultProfile == p.Name {
  293. if err := m.applyL2TPServer(); err != nil {
  294. applyErrors = append(applyErrors, fmt.Errorf("L2TP: %w", err))
  295. }
  296. }
  297. if m.pptpServer.Enabled && m.pptpServer.DefaultProfile == p.Name {
  298. if err := m.applyPPTPServer(); err != nil {
  299. applyErrors = append(applyErrors, fmt.Errorf("PPTP: %w", err))
  300. }
  301. }
  302. if m.pppoeServer.Enabled && m.pppoeServer.DefaultProfile == p.Name {
  303. if err := m.applyPPPoEServer(); err != nil {
  304. applyErrors = append(applyErrors, fmt.Errorf("PPPoE: %w", err))
  305. }
  306. }
  307. if err := errors.Join(applyErrors...); err != nil {
  308. return fmt.Errorf("profile saved but server reapply failed: %w", err)
  309. }
  310. return nil
  311. }
  312. func (m *PPPServerManager) DeleteProfile(name string) error {
  313. m.mu.Lock()
  314. defer m.mu.Unlock()
  315. if name == "default" || name == "default-encryption" {
  316. return fmt.Errorf("cannot delete default profile")
  317. }
  318. delete(m.profiles, name)
  319. var list []*PPPProfile
  320. for _, pr := range m.profiles {
  321. list = append(list, pr)
  322. }
  323. if err := m.save("ppp_profiles.json", list); err != nil {
  324. return err
  325. }
  326. return m.syncSecretsToSystemLocked()
  327. }
  328. // ======================== PPP Secrets CRUD ========================
  329. func (m *PPPServerManager) ListSecrets() []*PPPSecret {
  330. m.mu.RLock()
  331. defer m.mu.RUnlock()
  332. list := make([]*PPPSecret, 0)
  333. for _, s := range m.secrets {
  334. list = append(list, s)
  335. }
  336. sort.Slice(list, func(i, j int) bool {
  337. return list[i].Name < list[j].Name
  338. })
  339. return list
  340. }
  341. func (m *PPPServerManager) snapshotSecretsLocked() map[string]*PPPSecret {
  342. before := make(map[string]*PPPSecret, len(m.secrets))
  343. for id, secret := range m.secrets {
  344. copy := *secret
  345. before[id] = &copy
  346. }
  347. return before
  348. }
  349. func (m *PPPServerManager) saveSecretsLocked() error {
  350. list := make([]*PPPSecret, 0, len(m.secrets))
  351. for _, secret := range m.secrets {
  352. list = append(list, secret)
  353. }
  354. return m.save("ppp_secrets.json", list)
  355. }
  356. func (m *PPPServerManager) commitSecretsLocked(before map[string]*PPPSecret) error {
  357. if err := m.saveSecretsLocked(); err != nil {
  358. m.secrets = before
  359. return fmt.Errorf("saving PPP secrets: %w", err)
  360. }
  361. if err := m.syncSecretsToSystemLocked(); err != nil {
  362. m.secrets = before
  363. saveErr := m.saveSecretsLocked()
  364. if saveErr != nil {
  365. saveErr = fmt.Errorf("restoring saved PPP secrets: %w", saveErr)
  366. }
  367. syncErr := m.syncSecretsToSystemLocked()
  368. if syncErr != nil {
  369. syncErr = fmt.Errorf("reapplying previous PPP secrets: %w", syncErr)
  370. }
  371. return errors.Join(fmt.Errorf("applying PPP secrets: %w", err), saveErr, syncErr)
  372. }
  373. return nil
  374. }
  375. func (m *PPPServerManager) SaveSecret(s *PPPSecret) error {
  376. m.mu.Lock()
  377. defer m.mu.Unlock()
  378. if s.Name == "" || s.Password == "" {
  379. return fmt.Errorf("username and password are required")
  380. }
  381. if s.Service == "" {
  382. s.Service = "any"
  383. }
  384. if s.Profile == "" {
  385. s.Profile = "default"
  386. }
  387. if s.ID == "" {
  388. s.ID = fmt.Sprintf("secret-%d", time.Now().UnixNano())
  389. }
  390. before := m.snapshotSecretsLocked()
  391. copy := *s
  392. m.secrets[s.ID] = &copy
  393. return m.commitSecretsLocked(before)
  394. }
  395. func (m *PPPServerManager) SetSecretState(id string, disabled bool) error {
  396. m.mu.Lock()
  397. defer m.mu.Unlock()
  398. secret, ok := m.secrets[id]
  399. if !ok {
  400. return fmt.Errorf("secret not found")
  401. }
  402. before := m.snapshotSecretsLocked()
  403. secret.Disabled = disabled
  404. return m.commitSecretsLocked(before)
  405. }
  406. func (m *PPPServerManager) DeleteSecret(id string) error {
  407. m.mu.Lock()
  408. defer m.mu.Unlock()
  409. if _, ok := m.secrets[id]; !ok {
  410. return fmt.Errorf("secret not found")
  411. }
  412. before := m.snapshotSecretsLocked()
  413. delete(m.secrets, id)
  414. return m.commitSecretsLocked(before)
  415. }
  416. // Helper IP math utilities for dynamic pool allocation per profile
  417. func parseIPRange(r string) (net.IP, net.IP, error) {
  418. r = strings.TrimSpace(r)
  419. parts := strings.Split(r, "-")
  420. if len(parts) != 2 {
  421. return nil, nil, fmt.Errorf("invalid range format")
  422. }
  423. startIP := net.ParseIP(strings.TrimSpace(parts[0])).To4()
  424. endIP := net.ParseIP(strings.TrimSpace(parts[1])).To4()
  425. if startIP == nil || endIP == nil {
  426. return nil, nil, fmt.Errorf("invalid IP in range")
  427. }
  428. return startIP, endIP, nil
  429. }
  430. func firstAvailableIPFromRange(r string, used map[string]bool) string {
  431. startIP, endIP, err := parseIPRange(r)
  432. if err != nil {
  433. return ""
  434. }
  435. startInt := ipToUint32(startIP)
  436. endInt := ipToUint32(endIP)
  437. if startInt > endInt {
  438. startInt, endInt = endInt, startInt
  439. }
  440. for cur := startInt; cur <= endInt; cur++ {
  441. ipStr := uint32ToIP(cur).String()
  442. if !used[ipStr] {
  443. return ipStr
  444. }
  445. }
  446. return startIP.String()
  447. }
  448. func ipToUint32(ip net.IP) uint32 {
  449. return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
  450. }
  451. func uint32ToIP(n uint32) net.IP {
  452. return net.IPv4(byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  453. }
  454. // SyncSecretsToSystem synchronizes all enabled secrets into /etc/ppp/chap-secrets and /etc/ppp/pap-secrets
  455. func (m *PPPServerManager) SyncSecretsToSystem() error {
  456. m.mu.Lock()
  457. defer m.mu.Unlock()
  458. return m.syncSecretsToSystemLocked()
  459. }
  460. func (m *PPPServerManager) syncSecretsToSystemLocked() error {
  461. var lines []string
  462. lines = append(lines, "# Autogenerated by DebTik - DO NOT EDIT MANUALLY")
  463. lines = append(lines, "# client\tserver\tsecret\tIP addresses")
  464. // Track allocated IPs to avoid assigning duplicate static IPs from pools
  465. allocatedIPs := make(map[string]bool)
  466. for _, s := range m.secrets {
  467. if !s.Disabled && s.RemoteAddress != "" && !strings.Contains(s.RemoteAddress, "-") {
  468. allocatedIPs[strings.TrimSpace(s.RemoteAddress)] = true
  469. }
  470. }
  471. var secretList []*PPPSecret
  472. for _, s := range m.secrets {
  473. secretList = append(secretList, s)
  474. }
  475. sort.Slice(secretList, func(i, j int) bool {
  476. return secretList[i].Name < secretList[j].Name
  477. })
  478. for _, s := range secretList {
  479. if s.Disabled {
  480. continue
  481. }
  482. // In Linux pppd, the second field is the system name of the server (e.g. "l2tpd" from xl2tpd).
  483. // Setting this to "*" allows pppd to authenticate the user across L2TP, PPTP, and PPPoE daemons.
  484. serviceName := "*"
  485. ipAddr := "*"
  486. if s.RemoteAddress != "" {
  487. trimmed := strings.TrimSpace(s.RemoteAddress)
  488. if strings.Contains(trimmed, "-") {
  489. avail := firstAvailableIPFromRange(trimmed, allocatedIPs)
  490. if avail != "" {
  491. ipAddr = avail
  492. allocatedIPs[avail] = true
  493. }
  494. } else {
  495. ipAddr = trimmed
  496. }
  497. } else if s.Profile != "" {
  498. if prof, ok := m.profiles[s.Profile]; ok && prof != nil && prof.RemoteAddress != "" {
  499. trimmed := strings.TrimSpace(prof.RemoteAddress)
  500. if !strings.Contains(trimmed, "-") {
  501. // Single static IP defined in profile
  502. ipAddr = trimmed
  503. allocatedIPs[trimmed] = true
  504. } else {
  505. // Range defined in profile (e.g. 192.168.133.2-192.168.133.254)
  506. avail := firstAvailableIPFromRange(trimmed, allocatedIPs)
  507. if avail != "" {
  508. ipAddr = avail
  509. allocatedIPs[avail] = true
  510. }
  511. }
  512. }
  513. }
  514. if ipAddr == "" {
  515. ipAddr = "*"
  516. }
  517. lines = append(lines, fmt.Sprintf("\"%s\"\t%s\t\"%s\"\t%s", s.Name, serviceName, s.Password, ipAddr))
  518. }
  519. content := strings.Join(lines, "\n") + "\n"
  520. dir := m.pppDir
  521. if dir == "" {
  522. dir = "/etc/ppp"
  523. }
  524. for _, name := range []string{"chap-secrets", "pap-secrets"} {
  525. if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0600); err != nil {
  526. return fmt.Errorf("writing %s: %w", name, err)
  527. }
  528. }
  529. return nil
  530. }
  531. // ======================== PPPoE Server Management ========================
  532. func (m *PPPServerManager) GetPPPoEServer() PPPoEServerConfig {
  533. m.mu.Lock()
  534. defer m.mu.Unlock()
  535. // Check if running
  536. m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
  537. m.pppoeServer.ActiveSessions = m.countPPPSessions("pppoe")
  538. return m.pppoeServer
  539. }
  540. func (m *PPPServerManager) SetPPPoEServer(cfg PPPoEServerConfig) error {
  541. m.mu.Lock()
  542. defer m.mu.Unlock()
  543. previous := m.pppoeServer
  544. m.pppoeServer.Enabled = cfg.Enabled
  545. if cfg.ServiceName != "" {
  546. m.pppoeServer.ServiceName = cfg.ServiceName
  547. }
  548. if cfg.Interface != "" {
  549. m.pppoeServer.Interface = cfg.Interface
  550. }
  551. if cfg.DefaultProfile != "" {
  552. m.pppoeServer.DefaultProfile = cfg.DefaultProfile
  553. }
  554. m.pppoeServer.OneSessionPerHost = cfg.OneSessionPerHost
  555. if cfg.MaxMTU > 0 {
  556. m.pppoeServer.MaxMTU = cfg.MaxMTU
  557. }
  558. if cfg.MaxMRU > 0 {
  559. m.pppoeServer.MaxMRU = cfg.MaxMRU
  560. }
  561. if err := m.save("pppoe_server.json", m.pppoeServer); err != nil {
  562. m.pppoeServer = previous
  563. return fmt.Errorf("saving PPPoE configuration: %w", err)
  564. }
  565. if err := m.applyPPPoEServer(); err != nil {
  566. return fmt.Errorf("PPPoE configuration saved but could not be applied: %w", err)
  567. }
  568. return nil
  569. }
  570. func (m *PPPServerManager) applyPPPoEServer() error {
  571. m.stopPPPoEServer()
  572. if !m.pppoeServer.Enabled {
  573. m.pppoeServer.Running = false
  574. m.pppoeServer.LastError = ""
  575. return nil
  576. }
  577. // Prepare pppoe-server-options
  578. profile := m.profiles[m.pppoeServer.DefaultProfile]
  579. if profile == nil {
  580. profile = m.profiles["default"]
  581. }
  582. localIP := "10.10.10.1"
  583. if profile != nil && profile.LocalAddress != "" {
  584. localIP = profile.LocalAddress
  585. }
  586. startIP := "10.10.10.10"
  587. poolCount := 50
  588. if profile != nil && profile.RemoteAddress != "" {
  589. if strings.Contains(profile.RemoteAddress, "-") {
  590. parts := strings.Split(profile.RemoteAddress, "-")
  591. startIP = strings.TrimSpace(parts[0])
  592. } else {
  593. startIP = profile.RemoteAddress
  594. }
  595. }
  596. // Write /etc/ppp/pppoe-server-options
  597. dns1 := "1.1.1.1"
  598. dns2 := "8.8.8.8"
  599. if profile != nil && profile.DNSServers != "" {
  600. parts := strings.Split(profile.DNSServers, ",")
  601. if len(parts) > 0 {
  602. dns1 = strings.TrimSpace(parts[0])
  603. }
  604. if len(parts) > 1 {
  605. dns2 = strings.TrimSpace(parts[1])
  606. }
  607. }
  608. opts := fmt.Sprintf(`auth
  609. require-chap
  610. login
  611. lcp-echo-interval 10
  612. lcp-echo-failure 2
  613. ms-dns %s
  614. ms-dns %s
  615. netmask 255.255.255.0
  616. default-mru
  617. default-asyncmap
  618. proxyarp
  619. `, dns1, dns2)
  620. if err := os.WriteFile("/etc/ppp/pppoe-server-options", []byte(opts), 0644); err != nil {
  621. m.pppoeServer.LastError = err.Error()
  622. return fmt.Errorf("writing PPPoE options: %w", err)
  623. }
  624. // Launch pppoe-server
  625. // pppoe-server -I <if> -L <local_ip> -R <start_ip> -N <count> -S <service> -O /etc/ppp/pppoe-server-options -X <pidfile>
  626. args := []string{
  627. "-I", m.pppoeServer.Interface,
  628. "-L", localIP,
  629. "-R", startIP,
  630. "-N", strconv.Itoa(poolCount),
  631. "-S", m.pppoeServer.ServiceName,
  632. "-O", "/etc/ppp/pppoe-server-options",
  633. "-X", m.pppoePIDFile,
  634. }
  635. if m.pppoeServer.OneSessionPerHost {
  636. args = append(args, "-x", "1")
  637. }
  638. cmd := exec.Command("/usr/sbin/pppoe-server", args...)
  639. if out, err := cmd.CombinedOutput(); err != nil {
  640. m.pppoeServer.LastError = fmt.Sprintf("start failed: %s - %v", strings.TrimSpace(string(out)), err)
  641. m.pppoeServer.Running = false
  642. return fmt.Errorf("%s", m.pppoeServer.LastError)
  643. }
  644. time.Sleep(300 * time.Millisecond)
  645. m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
  646. if !m.pppoeServer.Running {
  647. m.pppoeServer.LastError = "PPPoE server did not become active"
  648. return errors.New(m.pppoeServer.LastError)
  649. }
  650. m.pppoeServer.LastError = ""
  651. return nil
  652. }
  653. func (m *PPPServerManager) stopPPPoEServer() {
  654. if data, err := os.ReadFile(m.pppoePIDFile); err == nil {
  655. pid, _ := strconv.Atoi(strings.TrimSpace(string(data)))
  656. if pid > 0 {
  657. _ = syscall.Kill(pid, syscall.SIGTERM)
  658. time.Sleep(200 * time.Millisecond)
  659. _ = syscall.Kill(pid, syscall.SIGKILL)
  660. }
  661. _ = os.Remove(m.pppoePIDFile)
  662. }
  663. _ = exec.Command("pkill", "-f", "/usr/sbin/pppoe-server").Run()
  664. }
  665. // ======================== PPTP Server Management ========================
  666. func (m *PPPServerManager) GetPPTPServer() PPTPServerConfig {
  667. m.mu.Lock()
  668. defer m.mu.Unlock()
  669. out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
  670. m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
  671. m.pptpServer.ActiveSessions = m.countPPPSessions("pptp")
  672. return m.pptpServer
  673. }
  674. func (m *PPPServerManager) SetPPTPServer(cfg PPTPServerConfig) error {
  675. m.mu.Lock()
  676. defer m.mu.Unlock()
  677. previous := m.pptpServer
  678. m.pptpServer.Enabled = cfg.Enabled
  679. if cfg.Port > 0 {
  680. m.pptpServer.Port = cfg.Port
  681. }
  682. if cfg.DefaultProfile != "" {
  683. m.pptpServer.DefaultProfile = cfg.DefaultProfile
  684. }
  685. m.pptpServer.RequireMPPE = cfg.RequireMPPE
  686. if err := m.save("pptp_server.json", m.pptpServer); err != nil {
  687. m.pptpServer = previous
  688. return fmt.Errorf("saving PPTP configuration: %w", err)
  689. }
  690. if err := m.applyPPTPServer(); err != nil {
  691. return fmt.Errorf("PPTP configuration saved but could not be applied: %w", err)
  692. }
  693. return nil
  694. }
  695. func (m *PPPServerManager) applyPPTPServer() error {
  696. if !m.pptpServer.Enabled {
  697. if out, err := exec.Command("systemctl", "stop", "pptpd").CombinedOutput(); err != nil {
  698. m.pptpServer.LastError = strings.TrimSpace(string(out))
  699. return fmt.Errorf("stopping pptpd: %s: %w", m.pptpServer.LastError, err)
  700. }
  701. m.pptpServer.Running = false
  702. m.pptpServer.LastError = ""
  703. return nil
  704. }
  705. profile := m.profiles[m.pptpServer.DefaultProfile]
  706. if profile == nil {
  707. profile = m.profiles["default-encryption"]
  708. }
  709. localIP := "10.10.20.1"
  710. if profile != nil && profile.LocalAddress != "" {
  711. localIP = profile.LocalAddress
  712. }
  713. remotePool := "10.10.20.10-50"
  714. if profile != nil && profile.RemoteAddress != "" {
  715. remotePool = profile.RemoteAddress
  716. }
  717. // Write /etc/pptpd.conf
  718. pptpdConf := fmt.Sprintf(`option /etc/ppp/pptpd-options
  719. logwtmp
  720. delegate
  721. localip %s
  722. remoteip %s
  723. `, localIP, remotePool)
  724. if err := os.WriteFile("/etc/pptpd.conf", []byte(pptpdConf), 0644); err != nil {
  725. m.pptpServer.LastError = err.Error()
  726. return fmt.Errorf("writing /etc/pptpd.conf: %w", err)
  727. }
  728. // Write /etc/ppp/pptpd-options
  729. dns1 := "1.1.1.1"
  730. dns2 := "8.8.8.8"
  731. if profile != nil && profile.DNSServers != "" {
  732. parts := strings.Split(profile.DNSServers, ",")
  733. if len(parts) > 0 {
  734. dns1 = strings.TrimSpace(parts[0])
  735. }
  736. if len(parts) > 1 {
  737. dns2 = strings.TrimSpace(parts[1])
  738. }
  739. }
  740. mppeRule := "require-mppe-128"
  741. if !m.pptpServer.RequireMPPE {
  742. mppeRule = "# require-mppe-128"
  743. }
  744. pptpdOpts := fmt.Sprintf(`name pptpd
  745. refuse-pap
  746. refuse-chap
  747. refuse-mschap
  748. require-mschap-v2
  749. %s
  750. ms-dns %s
  751. ms-dns %s
  752. proxyarp
  753. nodefaultroute
  754. lock
  755. nobsdcomp
  756. novj
  757. novjccomp
  758. nologfd
  759. `, mppeRule, dns1, dns2)
  760. if err := os.WriteFile("/etc/ppp/pptpd-options", []byte(pptpdOpts), 0644); err != nil {
  761. m.pptpServer.LastError = err.Error()
  762. return fmt.Errorf("writing /etc/ppp/pptpd-options: %w", err)
  763. }
  764. if out, err := exec.Command("systemctl", "restart", "pptpd").CombinedOutput(); err != nil {
  765. m.pptpServer.LastError = strings.TrimSpace(string(out))
  766. return fmt.Errorf("restarting pptpd: %s: %w", m.pptpServer.LastError, err)
  767. }
  768. time.Sleep(300 * time.Millisecond)
  769. out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
  770. m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
  771. if !m.pptpServer.Running {
  772. m.pptpServer.LastError = "pptpd is not active"
  773. return errors.New(m.pptpServer.LastError)
  774. }
  775. m.pptpServer.LastError = ""
  776. return nil
  777. }
  778. // ======================== L2TP Server Management ========================
  779. func (m *PPPServerManager) GetL2TPServer() L2TPServerConfig {
  780. m.mu.Lock()
  781. defer m.mu.Unlock()
  782. out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
  783. m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
  784. m.l2tpServer.ActiveSessions = m.countPPPSessions("l2tp")
  785. return m.l2tpServer
  786. }
  787. func (m *PPPServerManager) SetL2TPServer(cfg L2TPServerConfig) error {
  788. m.mu.Lock()
  789. defer m.mu.Unlock()
  790. previous := m.l2tpServer
  791. m.l2tpServer.Enabled = cfg.Enabled
  792. if cfg.Port > 0 {
  793. m.l2tpServer.Port = cfg.Port
  794. }
  795. if cfg.DefaultProfile != "" {
  796. m.l2tpServer.DefaultProfile = cfg.DefaultProfile
  797. }
  798. if cfg.UseIPSec != "" {
  799. m.l2tpServer.UseIPSec = cfg.UseIPSec
  800. }
  801. m.l2tpServer.IPSecSecret = cfg.IPSecSecret
  802. if err := m.save("l2tp_server.json", m.l2tpServer); err != nil {
  803. m.l2tpServer = previous
  804. return fmt.Errorf("saving L2TP configuration: %w", err)
  805. }
  806. if err := m.applyL2TPServer(); err != nil {
  807. return fmt.Errorf("L2TP configuration saved but could not be applied: %w", err)
  808. }
  809. return nil
  810. }
  811. func (m *PPPServerManager) applyL2TPServer() error {
  812. if !m.l2tpServer.Enabled {
  813. // When disabled, don't stop xl2tpd completely as client may need it, just reload without LNS
  814. if err := os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte("# disabled\n"), 0644); err != nil {
  815. m.l2tpServer.LastError = err.Error()
  816. return fmt.Errorf("writing L2TP options: %w", err)
  817. }
  818. if out, err := exec.Command("systemctl", "reload-or-restart", "xl2tpd").CombinedOutput(); err != nil {
  819. m.l2tpServer.LastError = strings.TrimSpace(string(out))
  820. return fmt.Errorf("reloading xl2tpd: %s: %w", m.l2tpServer.LastError, err)
  821. }
  822. m.l2tpServer.Running = false
  823. m.l2tpServer.LastError = ""
  824. return nil
  825. }
  826. profile := m.profiles[m.l2tpServer.DefaultProfile]
  827. if profile == nil {
  828. profile = m.profiles["default"]
  829. }
  830. localIP := "10.10.40.1"
  831. if profile != nil && profile.LocalAddress != "" {
  832. localIP = profile.LocalAddress
  833. }
  834. remotePool := "10.10.40.10-10.10.40.50"
  835. if profile != nil && profile.RemoteAddress != "" {
  836. remotePool = strings.TrimSpace(profile.RemoteAddress)
  837. }
  838. // xl2tpd requires range format A-B. If a single IP is provided, convert to IP-IP
  839. if !strings.Contains(remotePool, "-") {
  840. remotePool = fmt.Sprintf("%s-%s", remotePool, remotePool)
  841. }
  842. // Write /etc/xl2tpd/xl2tpd.conf with [lns default]
  843. if err := os.MkdirAll("/etc/xl2tpd", 0755); err != nil {
  844. m.l2tpServer.LastError = err.Error()
  845. return fmt.Errorf("creating L2TP directory: %w", err)
  846. }
  847. xl2tpdConf := fmt.Sprintf(`[global]
  848. port = %d
  849. [lns default]
  850. ip range = %s
  851. local ip = %s
  852. require chap = yes
  853. refuse pap = yes
  854. require authentication = yes
  855. name = l2tpd
  856. pppoptfile = /etc/ppp/options.xl2tpd.server
  857. length bit = yes
  858. `, m.l2tpServer.Port, remotePool, localIP)
  859. if err := os.WriteFile("/etc/xl2tpd/xl2tpd.conf", []byte(xl2tpdConf), 0644); err != nil {
  860. m.l2tpServer.LastError = err.Error()
  861. return fmt.Errorf("writing /etc/xl2tpd/xl2tpd.conf: %w", err)
  862. }
  863. // Write /etc/ppp/options.xl2tpd.server
  864. dns1 := "1.1.1.1"
  865. dns2 := "8.8.8.8"
  866. if profile != nil && profile.DNSServers != "" {
  867. parts := strings.Split(profile.DNSServers, ",")
  868. if len(parts) > 0 {
  869. dns1 = strings.TrimSpace(parts[0])
  870. }
  871. if len(parts) > 1 {
  872. dns2 = strings.TrimSpace(parts[1])
  873. }
  874. }
  875. opts := fmt.Sprintf(`require-mschap-v2
  876. ms-dns %s
  877. ms-dns %s
  878. auth
  879. ipcp-accept-local
  880. ipcp-accept-remote
  881. mtu 1400
  882. mru 1400
  883. proxyarp
  884. nodefaultroute
  885. `, dns1, dns2)
  886. if err := os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte(opts), 0644); err != nil {
  887. m.l2tpServer.LastError = err.Error()
  888. return fmt.Errorf("writing /etc/ppp/options.xl2tpd.server: %w", err)
  889. }
  890. // Clean restart of xl2tpd to avoid stale PID locks
  891. _ = exec.Command("systemctl", "stop", "xl2tpd").Run()
  892. time.Sleep(100 * time.Millisecond)
  893. _ = exec.Command("pkill", "-9", "-x", "xl2tpd").Run()
  894. _ = os.Remove("/var/run/xl2tpd.pid")
  895. _ = os.Remove("/run/xl2tpd.pid")
  896. if out, err := exec.Command("systemctl", "start", "xl2tpd").CombinedOutput(); err != nil {
  897. m.l2tpServer.LastError = strings.TrimSpace(string(out))
  898. return fmt.Errorf("starting xl2tpd: %s: %w", m.l2tpServer.LastError, err)
  899. }
  900. time.Sleep(300 * time.Millisecond)
  901. out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
  902. m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
  903. if !m.l2tpServer.Running {
  904. m.l2tpServer.LastError = "xl2tpd is not active"
  905. return errors.New(m.l2tpServer.LastError)
  906. }
  907. m.l2tpServer.LastError = ""
  908. return nil
  909. }
  910. // ======================== IPSec Server Management ========================
  911. func (m *PPPServerManager) GetIPSecServer() IPSecServerConfig {
  912. m.mu.Lock()
  913. defer m.mu.Unlock()
  914. out, _ := exec.Command("swanctl", "--list-conns").Output()
  915. m.ipsecServer.Running = strings.Contains(string(out), "rw-server")
  916. m.ipsecServer.ActiveSessions = m.countIPSecSessions()
  917. return m.ipsecServer
  918. }
  919. func (m *PPPServerManager) SetIPSecServer(cfg IPSecServerConfig) error {
  920. m.mu.Lock()
  921. defer m.mu.Unlock()
  922. previous := m.ipsecServer
  923. m.ipsecServer.Enabled = cfg.Enabled
  924. if cfg.PoolAddress != "" {
  925. m.ipsecServer.PoolAddress = cfg.PoolAddress
  926. }
  927. if cfg.PresharedKey != "" {
  928. m.ipsecServer.PresharedKey = cfg.PresharedKey
  929. }
  930. if cfg.LocalSubnet != "" {
  931. m.ipsecServer.LocalSubnet = cfg.LocalSubnet
  932. }
  933. if cfg.DNSServers != "" {
  934. m.ipsecServer.DNSServers = cfg.DNSServers
  935. }
  936. if err := m.save("ipsec_server.json", m.ipsecServer); err != nil {
  937. m.ipsecServer = previous
  938. return fmt.Errorf("saving IPSec configuration: %w", err)
  939. }
  940. if err := m.applyIPSecServer(); err != nil {
  941. return fmt.Errorf("IPSec configuration saved but could not be applied: %w", err)
  942. }
  943. return nil
  944. }
  945. func (m *PPPServerManager) applyIPSecServer() error {
  946. confFile := "/etc/swanctl/conf.d/rw-server.conf"
  947. if !m.ipsecServer.Enabled {
  948. if err := os.Remove(confFile); err != nil && !os.IsNotExist(err) {
  949. return fmt.Errorf("removing IPsec server configuration: %w", err)
  950. }
  951. if out, err := exec.Command("swanctl", "--load-all").CombinedOutput(); err != nil {
  952. return fmt.Errorf("reloading IPsec configuration: %w: %s", err, strings.TrimSpace(string(out)))
  953. }
  954. out, err := exec.Command("swanctl", "--list-conns").CombinedOutput()
  955. if err != nil {
  956. return fmt.Errorf("checking IPsec connections: %w: %s", err, strings.TrimSpace(string(out)))
  957. }
  958. for _, line := range strings.Split(string(out), "\n") {
  959. if strings.HasPrefix(strings.TrimSpace(line), "rw-server:") {
  960. return fmt.Errorf("IPsec server connection remains loaded after reload")
  961. }
  962. }
  963. m.ipsecServer.Running = false
  964. m.ipsecServer.LastError = ""
  965. return nil
  966. }
  967. if err := os.MkdirAll("/etc/swanctl/conf.d", 0755); err != nil {
  968. return fmt.Errorf("creating IPsec configuration directory: %w", err)
  969. }
  970. swanConf := fmt.Sprintf(`connections {
  971. rw-server {
  972. local_addrs = %%any
  973. pools = rw-pool
  974. local {
  975. auth = psk
  976. id = %%any
  977. }
  978. remote {
  979. auth = psk
  980. }
  981. children {
  982. rw-net {
  983. local_ts = %s
  984. esp_proposals = aes256gcm128-sha256-modp2048,aes256-sha256-modp2048
  985. }
  986. }
  987. }
  988. }
  989. pools {
  990. rw-pool {
  991. addrs = %s
  992. dns = %s
  993. }
  994. }
  995. secrets {
  996. ike-rw {
  997. secret = "%s"
  998. }
  999. }
  1000. `, m.ipsecServer.LocalSubnet, m.ipsecServer.PoolAddress, m.ipsecServer.DNSServers, m.ipsecServer.PresharedKey)
  1001. if err := os.WriteFile(confFile, []byte(swanConf), 0600); err != nil {
  1002. m.ipsecServer.LastError = err.Error()
  1003. return err
  1004. }
  1005. if out, err := exec.Command("swanctl", "--load-all").CombinedOutput(); err != nil {
  1006. m.ipsecServer.LastError = strings.TrimSpace(string(out))
  1007. return err
  1008. }
  1009. m.ipsecServer.Running = true
  1010. m.ipsecServer.LastError = ""
  1011. return nil
  1012. }
  1013. // ======================== Active Connections & Kill ========================
  1014. func (m *PPPServerManager) ListActiveSessions() []ActivePPPSession {
  1015. list := make([]ActivePPPSession, 0)
  1016. // Read network interfaces matching ppp*
  1017. ifaces, err := net.Interfaces()
  1018. if err != nil {
  1019. return list
  1020. }
  1021. for _, iface := range ifaces {
  1022. if !strings.HasPrefix(iface.Name, "ppp") {
  1023. continue
  1024. }
  1025. addrs, _ := iface.Addrs()
  1026. var assignedIP string
  1027. for _, a := range addrs {
  1028. if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
  1029. assignedIP = ipNet.IP.String()
  1030. break
  1031. }
  1032. }
  1033. sess := ActivePPPSession{
  1034. ID: iface.Name,
  1035. Interface: iface.Name,
  1036. Address: assignedIP,
  1037. Uptime: "active",
  1038. }
  1039. // Try to detect service from process or default
  1040. sess.Service = "ppp"
  1041. sess.Username = "client-" + iface.Name
  1042. m.populateIfaceTraffic(iface.Name, &sess)
  1043. list = append(list, sess)
  1044. }
  1045. sort.Slice(list, func(i, j int) bool {
  1046. return list[i].Interface < list[j].Interface
  1047. })
  1048. return list
  1049. }
  1050. func (m *PPPServerManager) DisconnectSession(ifaceName string) error {
  1051. if !strings.HasPrefix(ifaceName, "ppp") {
  1052. return fmt.Errorf("invalid ppp interface")
  1053. }
  1054. _ = exec.Command("ip", "link", "set", ifaceName, "down").Run()
  1055. _ = exec.Command("pkill", "-f", ifaceName).Run()
  1056. return nil
  1057. }
  1058. func (m *PPPServerManager) populateIfaceTraffic(ifaceName string, sess *ActivePPPSession) {
  1059. file, err := os.Open("/proc/net/dev")
  1060. if err != nil {
  1061. return
  1062. }
  1063. defer file.Close()
  1064. scanner := bufio.NewScanner(file)
  1065. for scanner.Scan() {
  1066. line := scanner.Text()
  1067. if strings.Contains(line, ifaceName+":") {
  1068. parts := strings.Fields(line)
  1069. if len(parts) >= 10 {
  1070. rxBytes, _ := strconv.ParseUint(parts[1], 10, 64)
  1071. txBytes, _ := strconv.ParseUint(parts[9], 10, 64)
  1072. sess.RxBytes = rxBytes
  1073. sess.TxBytes = txBytes
  1074. sess.RxHuman = formatBytes(rxBytes)
  1075. sess.TxHuman = formatBytes(txBytes)
  1076. }
  1077. break
  1078. }
  1079. }
  1080. }
  1081. func (m *PPPServerManager) countPPPSessions(service string) int {
  1082. ifaces, err := net.Interfaces()
  1083. if err != nil {
  1084. return 0
  1085. }
  1086. count := 0
  1087. for _, i := range ifaces {
  1088. if strings.HasPrefix(i.Name, "ppp") {
  1089. count++
  1090. }
  1091. }
  1092. return count
  1093. }
  1094. func (m *PPPServerManager) countIPSecSessions() int {
  1095. out, err := exec.Command("swanctl", "--list-sas").Output()
  1096. if err != nil {
  1097. return 0
  1098. }
  1099. return strings.Count(string(out), "ESTABLISHED")
  1100. }
  1101. func (m *PPPServerManager) isProcessRunning(pidFile string) bool {
  1102. data, err := os.ReadFile(pidFile)
  1103. if err != nil {
  1104. return false
  1105. }
  1106. pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
  1107. if err != nil || pid <= 0 {
  1108. return false
  1109. }
  1110. return syscall.Kill(pid, 0) == nil
  1111. }
  1112. func (m *PPPServerManager) applyAll() {
  1113. if m.pppoeServer.Enabled {
  1114. _ = m.applyPPPoEServer()
  1115. }
  1116. if m.pptpServer.Enabled {
  1117. _ = m.applyPPTPServer()
  1118. }
  1119. if m.l2tpServer.Enabled {
  1120. _ = m.applyL2TPServer()
  1121. }
  1122. if m.ipsecServer.Enabled {
  1123. _ = m.applyIPSecServer()
  1124. }
  1125. }