eoip.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package vpn
  2. import (
  3. "bufio"
  4. "crypto/rand"
  5. "encoding/json"
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. // EoIPInstance represents a MikroTik Ethernet-over-IP (GRETAP) tunnel
  16. type EoIPInstance struct {
  17. ID string `json:"id"`
  18. Name string `json:"name"` // e.g. "eoip-tunnel1"
  19. TunnelID int `json:"tunnel_id"` // 1 - 65535
  20. RemoteAddress string `json:"remote_address"` // Remote router IPv4
  21. LocalAddress string `json:"local_address"` // Local router IPv4 (optional)
  22. MACAddress string `json:"mac_address"` // e.g. "02:00:00:00:00:01"
  23. MTU int `json:"mtu"` // default 1500
  24. ClampMSS bool `json:"clamp_mss"` // Clamp TCP MSS for PMTUD
  25. Comment string `json:"comment,omitempty"`
  26. Disabled bool `json:"disabled"`
  27. Running bool `json:"running"` // MikroTik 'R' flag
  28. RxPackets uint64 `json:"rx_packets"`
  29. TxPackets uint64 `json:"tx_packets"`
  30. RxBytes uint64 `json:"rx_bytes"`
  31. TxBytes uint64 `json:"tx_bytes"`
  32. RxHuman string `json:"rx_human,omitempty"`
  33. TxHuman string `json:"tx_human,omitempty"`
  34. LastError string `json:"last_error,omitempty"`
  35. }
  36. type EoIPManager struct {
  37. mu sync.RWMutex
  38. storePath string
  39. tunnels map[string]*EoIPInstance
  40. }
  41. func NewEoIPManager() *EoIPManager {
  42. mgr := &EoIPManager{
  43. storePath: "/etc/proxmox-router/vpn/eoip.json",
  44. tunnels: make(map[string]*EoIPInstance),
  45. }
  46. mgr.load()
  47. mgr.syncAll()
  48. return mgr
  49. }
  50. func (m *EoIPManager) load() {
  51. if data, err := os.ReadFile(m.storePath); err == nil {
  52. var list []*EoIPInstance
  53. if err := json.Unmarshal(data, &list); err == nil {
  54. for _, t := range list {
  55. m.tunnels[t.ID] = t
  56. }
  57. }
  58. }
  59. }
  60. func (m *EoIPManager) save() error {
  61. _ = os.MkdirAll(filepath.Dir(m.storePath), 0755)
  62. var list []*EoIPInstance
  63. for _, t := range m.tunnels {
  64. list = append(list, t)
  65. }
  66. data, err := json.MarshalIndent(list, "", " ")
  67. if err != nil {
  68. return err
  69. }
  70. return os.WriteFile(m.storePath, data, 0644)
  71. }
  72. func (m *EoIPManager) List() []*EoIPInstance {
  73. m.mu.Lock()
  74. defer m.mu.Unlock()
  75. list := make([]*EoIPInstance, 0)
  76. for _, t := range m.tunnels {
  77. m.updateStats(t)
  78. list = append(list, t)
  79. }
  80. return list
  81. }
  82. func (m *EoIPManager) Get(id string) (*EoIPInstance, bool) {
  83. m.mu.Lock()
  84. defer m.mu.Unlock()
  85. t, ok := m.tunnels[id]
  86. if ok {
  87. m.updateStats(t)
  88. }
  89. return t, ok
  90. }
  91. func (m *EoIPManager) Save(inst *EoIPInstance) error {
  92. m.mu.Lock()
  93. defer m.mu.Unlock()
  94. if inst.Name == "" {
  95. inst.Name = fmt.Sprintf("eoip-tunnel%d", inst.TunnelID)
  96. }
  97. if inst.TunnelID <= 0 || inst.TunnelID > 65535 {
  98. return fmt.Errorf("tunnel_id must be between 1 and 65535")
  99. }
  100. if inst.RemoteAddress == "" {
  101. return fmt.Errorf("remote_address is required")
  102. }
  103. if inst.MTU <= 0 {
  104. inst.MTU = 1500
  105. }
  106. if inst.MACAddress == "" {
  107. inst.MACAddress = generateMAC()
  108. }
  109. if inst.ID == "" {
  110. inst.ID = fmt.Sprintf("eoip-%d", time.Now().UnixNano())
  111. }
  112. // Stop previous interface if name changed or existing
  113. if prev, exists := m.tunnels[inst.ID]; exists && prev.Name != inst.Name {
  114. m.destroyInterface(prev.Name)
  115. }
  116. m.tunnels[inst.ID] = inst
  117. _ = m.save()
  118. return m.applyTunnel(inst)
  119. }
  120. func (m *EoIPManager) SetState(id string, disabled bool) error {
  121. m.mu.Lock()
  122. defer m.mu.Unlock()
  123. t, ok := m.tunnels[id]
  124. if !ok {
  125. return fmt.Errorf("tunnel not found")
  126. }
  127. t.Disabled = disabled
  128. _ = m.save()
  129. if disabled {
  130. m.destroyInterface(t.Name)
  131. t.Running = false
  132. return nil
  133. }
  134. return m.applyTunnel(t)
  135. }
  136. func (m *EoIPManager) Delete(id string) error {
  137. m.mu.Lock()
  138. defer m.mu.Unlock()
  139. t, ok := m.tunnels[id]
  140. if !ok {
  141. return fmt.Errorf("tunnel not found")
  142. }
  143. m.destroyInterface(t.Name)
  144. delete(m.tunnels, id)
  145. return m.save()
  146. }
  147. func (m *EoIPManager) syncAll() {
  148. m.mu.Lock()
  149. defer m.mu.Unlock()
  150. for _, t := range m.tunnels {
  151. if !t.Disabled {
  152. _ = m.applyTunnel(t)
  153. } else {
  154. m.destroyInterface(t.Name)
  155. t.Running = false
  156. }
  157. }
  158. }
  159. func (m *EoIPManager) applyTunnel(t *EoIPInstance) error {
  160. m.destroyInterface(t.Name)
  161. if t.Disabled {
  162. t.Running = false
  163. return nil
  164. }
  165. // Construct ip link add command:
  166. // ip link add <name> type gretap remote <remote_ip> [local <local_ip>] key <tunnel_id>
  167. args := []string{"link", "add", t.Name, "type", "gretap", "remote", t.RemoteAddress}
  168. if t.LocalAddress != "" {
  169. args = append(args, "local", t.LocalAddress)
  170. }
  171. args = append(args, "key", strconv.Itoa(t.TunnelID))
  172. if out, err := exec.Command("ip", args...).CombinedOutput(); err != nil {
  173. t.LastError = fmt.Sprintf("create failed: %s - %v", strings.TrimSpace(string(out)), err)
  174. t.Running = false
  175. return fmt.Errorf("%s", t.LastError)
  176. }
  177. // Set MAC address if provided
  178. if t.MACAddress != "" {
  179. _ = exec.Command("ip", "link", "set", t.Name, "address", t.MACAddress).Run()
  180. }
  181. // Set MTU
  182. if t.MTU > 0 {
  183. _ = exec.Command("ip", "link", "set", t.Name, "mtu", strconv.Itoa(t.MTU)).Run()
  184. }
  185. // Bring UP
  186. if out, err := exec.Command("ip", "link", "set", t.Name, "up").CombinedOutput(); err != nil {
  187. t.LastError = fmt.Sprintf("up failed: %s - %v", strings.TrimSpace(string(out)), err)
  188. t.Running = false
  189. return fmt.Errorf("%s", t.LastError)
  190. }
  191. // TCP MSS Clamping if enabled
  192. if t.ClampMSS {
  193. _ = exec.Command("iptables", "-t", "mangle", "-D", "FORWARD", "-o", t.Name, "-p", "tcp", "--tcp-flags", "SYN,RST", "SYN", "-j", "TCPMSS", "--clamp-mss-to-pmtu").Run()
  194. _ = exec.Command("iptables", "-t", "mangle", "-A", "FORWARD", "-o", t.Name, "-p", "tcp", "--tcp-flags", "SYN,RST", "SYN", "-j", "TCPMSS", "--clamp-mss-to-pmtu").Run()
  195. }
  196. t.Running = true
  197. t.LastError = ""
  198. return nil
  199. }
  200. func (m *EoIPManager) destroyInterface(name string) {
  201. if name == "" {
  202. return
  203. }
  204. _ = exec.Command("iptables", "-t", "mangle", "-D", "FORWARD", "-o", name, "-p", "tcp", "--tcp-flags", "SYN,RST", "SYN", "-j", "TCPMSS", "--clamp-mss-to-pmtu").Run()
  205. _ = exec.Command("ip", "link", "del", name).Run()
  206. }
  207. func (m *EoIPManager) updateStats(t *EoIPInstance) {
  208. // Check if interface is up
  209. out, err := exec.Command("ip", "link", "show", t.Name).Output()
  210. if err != nil || !strings.Contains(string(out), "UP") {
  211. t.Running = false
  212. } else {
  213. t.Running = true
  214. }
  215. // Read /proc/net/dev for RX/TX bytes
  216. file, err := os.Open("/proc/net/dev")
  217. if err != nil {
  218. return
  219. }
  220. defer file.Close()
  221. scanner := bufio.NewScanner(file)
  222. for scanner.Scan() {
  223. line := scanner.Text()
  224. if strings.Contains(line, t.Name+":") {
  225. parts := strings.Fields(line)
  226. if len(parts) >= 10 {
  227. rxBytes, _ := strconv.ParseUint(parts[1], 10, 64)
  228. rxPackets, _ := strconv.ParseUint(parts[2], 10, 64)
  229. txBytes, _ := strconv.ParseUint(parts[9], 10, 64)
  230. txPackets, _ := strconv.ParseUint(parts[10], 10, 64)
  231. t.RxBytes = rxBytes
  232. t.RxPackets = rxPackets
  233. t.TxBytes = txBytes
  234. t.TxPackets = txPackets
  235. t.RxHuman = formatBytes(rxBytes)
  236. t.TxHuman = formatBytes(txBytes)
  237. }
  238. break
  239. }
  240. }
  241. }
  242. func generateMAC() string {
  243. buf := make([]byte, 3)
  244. _, _ = rand.Read(buf)
  245. return fmt.Sprintf("02:64:%02x:%02x:%02x:%02x", buf[0], buf[1], buf[2], time.Now().UnixNano()%256)
  246. }
  247. func formatBytes(b uint64) string {
  248. const unit = 1024
  249. if b < unit {
  250. return fmt.Sprintf("%d B", b)
  251. }
  252. div, exp := uint64(unit), 0
  253. for n := b / unit; n >= unit; n /= unit {
  254. div *= unit
  255. exp++
  256. }
  257. return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "KMGTPE"[exp])
  258. }