fea: access in name proxy.

This commit is contained in:
Daniel Ding
2025-04-21 10:42:51 +08:00
parent 84c638ffe8
commit d8a24744d7
40 changed files with 243 additions and 213 deletions

View File

@@ -7,8 +7,8 @@ import (
)
func main() {
c := config.NewPoint()
p := access.NewPoint(c)
c := config.NewAccess()
p := access.NewAccess(c)
p.Initialize()
libol.Go(p.Start)

View File

@@ -5,11 +5,11 @@ import (
"github.com/urfave/cli/v2"
)
type Point struct {
type Access struct {
Cmd
}
func (u Point) Url(prefix, name string) string {
func (u Access) Url(prefix, name string) string {
if name == "" {
return prefix + "/api/point"
} else {
@@ -17,7 +17,7 @@ func (u Point) Url(prefix, name string) string {
}
}
func (u Point) Tmpl() string {
func (u Access) Tmpl() string {
return `# total {{ len . }}
{{ps -16 "uuid"}} {{ps -8 "alive"}} {{ ps -8 "device" }} {{ps -16 "alias"}} {{ps -8 "user"}} {{ps -22 "remote"}} {{ps -8 "network"}} {{ ps -6 "state"}}
{{- range . }}
@@ -26,10 +26,10 @@ func (u Point) Tmpl() string {
`
}
func (u Point) List(c *cli.Context) error {
func (u Access) List(c *cli.Context) error {
url := u.Url(c.String("url"), "")
clt := u.NewHttp(c.String("token"))
var items []schema.Point
var items []schema.Access
if err := clt.GetJSON(url, &items); err != nil {
return err
}
@@ -46,7 +46,7 @@ func (u Point) List(c *cli.Context) error {
return u.Out(items, c.String("format"), u.Tmpl())
}
func (u Point) Commands() *cli.Command {
func (u Access) Commands() *cli.Command {
return &cli.Command{
Name: "access",
Usage: "access to this switch",

View File

@@ -58,10 +58,10 @@ func (u Config) Check(c *cli.Context) error {
}
}
// Check OLAP configurations.
out.Info("%15s: %s", "check", "point")
file = filepath.Join(dir, "point.json")
out.Info("%15s: %s", "check", "access")
file = filepath.Join(dir, "access", "access.json")
if err := libol.FileExist(file); err == nil {
obj := &config.Point{}
obj := &config.Access{}
if err := libol.UnmarshalLoad(obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {
@@ -124,7 +124,7 @@ func (u Config) Check(c *cli.Context) error {
pattern = filepath.Join(dir, "switch", "link", "*.json")
if files, err := filepath.Glob(pattern); err == nil {
for _, file := range files {
var obj []config.Point
var obj []config.Access
if err := libol.UnmarshalLoad(&obj, file); err != nil {
out.Warn("%15s: %s", filepath.Base(file), err)
} else {

View File

@@ -154,7 +154,7 @@ func (u Network) Commands(app *api.App) {
},
Action: u.Save,
},
Point{}.Commands(),
Access{}.Commands(),
Qos{}.Commands(),
VPNClient{}.Commands(),
OpenVPN{}.Commands(),

View File

@@ -1,12 +1,15 @@
listen: 127.0.0.1
access:
- connection: <remote-server>
protocol: tcp
username: <username>@<network>
password: <password>
forward:
- 8.8.8.8
- 8.8.4.4
nameto: 114.114.114.114
backends:
- server: 192.168.11.1
nameto: 8.8.8.8
match:
- openai.com
- chatgpt.com
- server: 192.168.11.2
nameto: 8.8.8.8
match:

View File

@@ -10,7 +10,7 @@ import (
"github.com/luscis/openlan/pkg/network"
)
type Pointer interface {
type Acceser interface {
Addr() string
IfName() string
IfAddr() string
@@ -24,27 +24,27 @@ type Pointer interface {
Record() map[string]int64
Tenant() string
Alias() string
Config() *config.Point
Config() *config.Access
Network() *models.Network
}
type MixPoint struct {
type MixAccess struct {
uuid string
worker *Worker
config *config.Point
config *config.Access
out *libol.SubLogger
http *http.Http
}
func NewMixPoint(config *config.Point) MixPoint {
return MixPoint{
func NewMixAccess(config *config.Access) MixAccess {
return MixAccess{
worker: NewWorker(config),
config: config,
out: libol.NewSubLogger(config.Id()),
}
}
func (p *MixPoint) Initialize() {
func (p *MixAccess) Initialize() {
libol.Info("MixAccess.Initialize")
p.worker.SetUUID(p.UUID())
p.worker.Initialize()
@@ -53,7 +53,7 @@ func (p *MixPoint) Initialize() {
}
}
func (p *MixPoint) Start() {
func (p *MixAccess) Start() {
p.out.Info("MixAccess.Start %s", runtime.GOOS)
if p.config.PProf != "" {
f := libol.PProf{Listen: p.config.PProf}
@@ -62,7 +62,7 @@ func (p *MixPoint) Start() {
p.worker.Start()
}
func (p *MixPoint) Stop() {
func (p *MixAccess) Stop() {
defer libol.Catch("MixAccess.Stop")
if p.http != nil {
p.http.Shutdown()
@@ -70,14 +70,14 @@ func (p *MixPoint) Stop() {
p.worker.Stop()
}
func (p *MixPoint) UUID() string {
func (p *MixAccess) UUID() string {
if p.uuid == "" {
p.uuid = libol.GenString(13)
}
return p.uuid
}
func (p *MixPoint) Status() libol.SocketStatus {
func (p *MixAccess) Status() libol.SocketStatus {
client := p.Client()
if client == nil {
return 0
@@ -85,11 +85,11 @@ func (p *MixPoint) Status() libol.SocketStatus {
return client.Status()
}
func (p *MixPoint) Addr() string {
func (p *MixAccess) Addr() string {
return p.config.Connection
}
func (p *MixPoint) IfName() string {
func (p *MixAccess) IfName() string {
device := p.Device()
if device == nil {
return ""
@@ -97,54 +97,54 @@ func (p *MixPoint) IfName() string {
return device.Name()
}
func (p *MixPoint) Client() libol.SocketClient {
func (p *MixAccess) Client() libol.SocketClient {
if p.worker.conWorker == nil {
return nil
}
return p.worker.conWorker.client
}
func (p *MixPoint) Device() network.Taper {
func (p *MixAccess) Device() network.Taper {
if p.worker.tapWorker == nil {
return nil
}
return p.worker.tapWorker.device
}
func (p *MixPoint) UpTime() int64 {
func (p *MixAccess) UpTime() int64 {
return p.worker.UpTime()
}
func (p *MixPoint) IfAddr() string {
func (p *MixAccess) IfAddr() string {
return p.worker.ifAddr
}
func (p *MixPoint) Tenant() string {
func (p *MixAccess) Tenant() string {
return p.config.Network
}
func (p *MixPoint) User() string {
func (p *MixAccess) User() string {
return p.config.Username
}
func (p *MixPoint) Alias() string {
func (p *MixAccess) Alias() string {
return p.config.Alias
}
func (p *MixPoint) Record() map[string]int64 {
func (p *MixAccess) Record() map[string]int64 {
rt := p.worker.conWorker.record
// TODO padding data from tapWorker
return rt.Data()
}
func (p *MixPoint) Config() *config.Point {
func (p *MixAccess) Config() *config.Access {
return p.config
}
func (p *MixPoint) Network() *models.Network {
func (p *MixAccess) Network() *models.Network {
return p.worker.network
}
func (p *MixPoint) Protocol() string {
func (p *MixAccess) Protocol() string {
return p.config.Protocol
}

View File

@@ -7,41 +7,41 @@ import (
"github.com/luscis/openlan/pkg/network"
)
type Point struct {
MixPoint
type Access struct {
MixAccess
// private
brName string
addr string
}
func NewPoint(config *config.Point) *Point {
p := Point{
brName: config.Interface.Bridge,
MixPoint: NewMixPoint(config),
func NewAccess(config *config.Access) *Access {
p := Access{
brName: config.Interface.Bridge,
MixAccess: NewMixAccess(config),
}
return &p
}
func (p *Point) Initialize() {
func (p *Access) Initialize() {
w := p.worker
w.listener.AddAddr = p.AddAddr
w.listener.DelAddr = p.DelAddr
p.MixPoint.Initialize()
p.MixAccess.Initialize()
}
func (p *Point) routeAdd(prefix string) ([]byte, error) {
func (p *Access) routeAdd(prefix string) ([]byte, error) {
network.RouteDel("", prefix, "")
out, err := network.RouteAdd(p.IfName(), prefix, "")
return out, err
}
func (p *Point) AddAddr(ipStr string) error {
func (p *Access) AddAddr(ipStr string) error {
if ipStr == "" {
return nil
}
// add point-to-point
// add Access-to-Access
ips := strings.SplitN(ipStr, "/", 2)
out, err := network.AddrAdd(p.IfName(), ips[0], ips[0])
if err != nil {
@@ -62,7 +62,7 @@ func (p *Point) AddAddr(ipStr string) error {
return nil
}
func (p *Point) DelAddr(ipStr string) error {
func (p *Access) DelAddr(ipStr string) error {
// delete directly route.
out, err := network.RouteDel(p.IfName(), ipStr, "")
if err != nil {
@@ -70,7 +70,7 @@ func (p *Point) DelAddr(ipStr string) error {
}
p.out.Info("Access.DelAddr: route %s via %s", ipStr, p.IfName())
// delete point-to-point
// delete Access-to-Access
ip4 := strings.SplitN(ipStr, "/", 2)[0]
out, err = network.AddrDel(p.IfName(), ip4)
if err != nil {
@@ -83,7 +83,7 @@ func (p *Point) DelAddr(ipStr string) error {
return nil
}
func (p *Point) AddRoute() error {
func (p *Access) AddRoute() error {
to := p.config.Forward
if to == nil {
return nil

View File

@@ -7,8 +7,8 @@ import (
"github.com/vishvananda/netlink"
)
type Point struct {
MixPoint
type Access struct {
MixAccess
// private
brName string
ipMtu int
@@ -19,30 +19,30 @@ type Point struct {
uuid string
}
func NewPoint(config *config.Point) *Point {
func NewAccess(config *config.Access) *Access {
ipMtu := config.Interface.IPMtu
if ipMtu == 0 {
ipMtu = 1500
}
p := Point{
ipMtu: ipMtu,
brName: config.Interface.Bridge,
MixPoint: NewMixPoint(config),
p := Access{
ipMtu: ipMtu,
brName: config.Interface.Bridge,
MixAccess: NewMixAccess(config),
}
return &p
}
func (p *Point) Initialize() {
func (p *Access) Initialize() {
w := p.worker
w.listener.AddAddr = p.AddAddr
w.listener.DelAddr = p.DelAddr
w.listener.OnTap = p.OnTap
p.MixPoint.Initialize()
p.MixAccess.Initialize()
}
func (p *Point) DelAddr(ipStr string) error {
func (p *Access) DelAddr(ipStr string) error {
if p.link == nil || ipStr == "" {
return nil
}
@@ -59,7 +59,7 @@ func (p *Point) DelAddr(ipStr string) error {
return nil
}
func (p *Point) AddAddr(ipStr string) error {
func (p *Access) AddAddr(ipStr string) error {
if ipStr == "" || p.link == nil {
return nil
}
@@ -81,7 +81,7 @@ func (p *Point) AddAddr(ipStr string) error {
return nil
}
func (p *Point) UpBr(name string) *netlink.Bridge {
func (p *Access) UpBr(name string) *netlink.Bridge {
if name == "" {
return nil
}
@@ -105,7 +105,7 @@ func (p *Point) UpBr(name string) *netlink.Bridge {
return br
}
func (p *Point) OnTap(w *TapWorker) error {
func (p *Access) OnTap(w *TapWorker) error {
p.out.Info("Access.OnTap")
tap := w.device
name := tap.Name()
@@ -141,7 +141,7 @@ func (p *Point) OnTap(w *TapWorker) error {
return nil
}
func (p *Point) AddRoute() error {
func (p *Access) AddRoute() error {
to := p.config.Forward
route := p.Network()
if to == nil || route == nil {

View File

@@ -9,31 +9,31 @@ import (
"github.com/luscis/openlan/pkg/network"
)
type Point struct {
MixPoint
type Access struct {
MixAccess
// private
brName string
addr string
routes []*models.Route
config *config.Point
config *config.Access
}
func NewPoint(config *config.Point) *Point {
p := Point{
brName: config.Interface.Bridge,
MixPoint: NewMixPoint(config),
func NewAccess(config *config.Access) *Access {
p := Access{
brName: config.Interface.Bridge,
MixAccess: NewMixAccess(config),
}
return &p
}
func (p *Point) Initialize() {
func (p *Access) Initialize() {
p.worker.listener.AddAddr = p.AddAddr
p.worker.listener.DelAddr = p.DelAddr
p.worker.listener.OnTap = p.OnTap
p.MixPoint.Initialize()
p.MixAccess.Initialize()
}
func (p *Point) OnTap(w *TapWorker) error {
func (p *Access) OnTap(w *TapWorker) error {
// clean routes previous
routes := make([]*models.Route, 0, 32)
if err := libol.UnmarshalLoad(&routes, ".routes.json"); err == nil {
@@ -45,11 +45,11 @@ func (p *Point) OnTap(w *TapWorker) error {
return nil
}
func (p *Point) Trim(out []byte) string {
func (p *Access) Trim(out []byte) string {
return strings.TrimSpace(string(out))
}
func (p *Point) AddAddr(ipStr string) error {
func (p *Access) AddAddr(ipStr string) error {
if ipStr == "" {
return nil
}
@@ -69,7 +69,7 @@ func (p *Point) AddAddr(ipStr string) error {
return nil
}
func (p *Point) DelAddr(ipStr string) error {
func (p *Access) DelAddr(ipStr string) error {
ipv4 := strings.Split(ipStr, "/")[0]
out, err := network.AddrDel(p.IfName(), ipv4)
if err != nil {

View File

@@ -2,13 +2,14 @@ package http
import (
"context"
"net/http"
"github.com/gorilla/mux"
"github.com/luscis/openlan/pkg/libol"
"net/http"
)
type Http struct {
pointer Pointer
acc Accesser
listen string
server *http.Server
crtFile string
@@ -18,11 +19,11 @@ type Http struct {
token string
}
func NewHttp(pointer Pointer) (h *Http) {
func NewHttp(acc Accesser) (h *Http) {
h = &Http{
pointer: pointer,
acc: acc,
}
if config := pointer.Config(); config != nil {
if config := acc.Config(); config != nil {
if config.Http != nil {
h.listen = config.Http.Listen
h.pubDir = config.Http.Public
@@ -80,17 +81,17 @@ func (h *Http) LoadRouter() {
router.HandleFunc("/current/uuid", func(w http.ResponseWriter, r *http.Request) {
format := GetQueryOne(r, "format")
if format == "yaml" {
ResponseYaml(w, h.pointer.UUID())
ResponseYaml(w, h.acc.UUID())
} else {
ResponseJson(w, h.pointer.UUID())
ResponseJson(w, h.acc.UUID())
}
})
router.HandleFunc("/current/config", func(w http.ResponseWriter, r *http.Request) {
format := GetQueryOne(r, "format")
if format == "yaml" {
ResponseYaml(w, h.pointer.Config())
ResponseYaml(w, h.acc.Config())
} else {
ResponseJson(w, h.pointer.Config())
ResponseJson(w, h.acc.Config())
}
})
}

View File

@@ -2,7 +2,7 @@ package http
import "github.com/luscis/openlan/pkg/config"
type Pointer interface {
type Accesser interface {
UUID() string
Config() *config.Point
Config() *config.Access
}

View File

@@ -43,7 +43,7 @@ type SocketWorker struct {
keepalive KeepAlive
done chan bool
ticker *time.Ticker
pinCfg *config.Point
pinCfg *config.Access
eventQueue chan *WorkerEvent
writeQueue chan *libol.FrameMessage
jobber []jobTimer
@@ -52,7 +52,7 @@ type SocketWorker struct {
wlFrame *libol.FrameMessage // Last frame from write.
}
func NewSocketWorker(client libol.SocketClient, c *config.Point) *SocketWorker {
func NewSocketWorker(client libol.SocketClient, c *config.Access) *SocketWorker {
t := &SocketWorker{
client: client,
network: models.NewNetwork(c.Network, c.Interface.Address),

View File

@@ -32,7 +32,7 @@ type TapWorker struct {
ether TunEther
neighbor Neighbors
devCfg network.TapConfig
pinCfg *config.Point
pinCfg *config.Access
ifAddr string
writeQueue chan *libol.FrameMessage
done chan bool
@@ -40,7 +40,7 @@ type TapWorker struct {
eventQueue chan *WorkerEvent
}
func NewTapWorker(devCfg network.TapConfig, pinCfg *config.Point) (a *TapWorker) {
func NewTapWorker(devCfg network.TapConfig, pinCfg *config.Access) (a *TapWorker) {
a = &TapWorker{
devCfg: devCfg,
pinCfg: pinCfg,

View File

@@ -2,23 +2,24 @@ package access
import (
"fmt"
"github.com/chzyer/readline"
"github.com/luscis/openlan/pkg/libol"
"io"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"github.com/chzyer/readline"
"github.com/luscis/openlan/pkg/libol"
)
type Terminal struct {
Pointer Pointer
Acceser Acceser
Console *readline.Instance
}
func NewTerminal(pointer Pointer) *Terminal {
t := &Terminal{Pointer: pointer}
func NewTerminal(Acceser Acceser) *Terminal {
t := &Terminal{Acceser: Acceser}
completer := readline.NewPrefixCompleter(
readline.PcItem("quit"),
readline.PcItem("help"),
@@ -52,7 +53,7 @@ func NewTerminal(pointer Pointer) *Terminal {
}
func (t *Terminal) Prompt() string {
user := t.Pointer.User()
user := t.Acceser.User()
cur := os.Getenv("PWD")
home := os.Getenv("HOME")
if strings.HasPrefix(cur, home) {
@@ -71,24 +72,24 @@ func (t *Terminal) CmdShow(args []string) {
}
switch action {
case "record":
v := t.Pointer.Record()
v := t.Acceser.Record()
if out, err := libol.Marshal(v, true); err == nil {
fmt.Printf("%s\n", out)
}
case "statistics":
if c := t.Pointer.Client(); c != nil {
if c := t.Acceser.Client(); c != nil {
v := c.Statistics()
if out, err := libol.Marshal(v, true); err == nil {
fmt.Printf("%s\n", out)
}
}
case "config":
cfg := t.Pointer.Config()
cfg := t.Acceser.Config()
if str, err := libol.Marshal(cfg, true); err == nil {
fmt.Printf("%s\n", str)
}
case "network":
cfg := t.Pointer.Network()
cfg := t.Acceser.Network()
if str, err := libol.Marshal(cfg, true); err == nil {
fmt.Printf("%s\n", str)
}
@@ -99,10 +100,10 @@ func (t *Terminal) CmdShow(args []string) {
Device string
Status string
}{
UUID: t.Pointer.UUID(),
UpTime: t.Pointer.UpTime(),
Device: t.Pointer.IfName(),
Status: t.Pointer.Status().String(),
UUID: t.Acceser.UUID(),
UpTime: t.Acceser.UpTime(),
Device: t.Acceser.IfName(),
Status: t.Acceser.Status().String(),
}
if str, err := libol.Marshal(v, true); err == nil {
fmt.Printf("%s\n", str)

View File

@@ -82,7 +82,7 @@ type PrefixRule struct {
NextHop net.IP
}
func GetSocketClient(p *config.Point) libol.SocketClient {
func GetSocketClient(p *config.Access) libol.SocketClient {
crypt := p.Crypt
block := libol.NewBlockCrypt(crypt.Algo, crypt.Secret)
switch p.Protocol {
@@ -142,7 +142,7 @@ func GetSocketClient(p *config.Point) libol.SocketClient {
}
}
func GetTapCfg(c *config.Point) network.TapConfig {
func GetTapCfg(c *config.Access) network.TapConfig {
cfg := network.TapConfig{
Provider: c.Interface.Provider,
Name: c.Interface.Name,
@@ -164,7 +164,7 @@ type Worker struct {
listener WorkerListener
conWorker *SocketWorker
tapWorker *TapWorker
cfg *config.Point
cfg *config.Access
uuid string
network *models.Network
routes map[string]PrefixRule
@@ -176,7 +176,7 @@ type Worker struct {
lock sync.RWMutex
}
func NewWorker(cfg *config.Point) *Worker {
func NewWorker(cfg *config.Access) *Worker {
return &Worker{
ifAddr: cfg.Interface.Address,
cfg: cfg,
@@ -247,7 +247,7 @@ func (w *Worker) SaveStatus() {
}
sts := client.Statistics()
access := &schema.Point{
access := &schema.Access{
RxBytes: uint64(sts[libol.CsRecvOkay]),
TxBytes: uint64(sts[libol.CsSendOkay]),
ErrPkt: uint64(sts[libol.CsSendError]),

View File

@@ -1,37 +1,38 @@
package api
import (
"net/http"
"github.com/gorilla/mux"
"github.com/luscis/openlan/pkg/cache"
"github.com/luscis/openlan/pkg/models"
"github.com/luscis/openlan/pkg/schema"
"net/http"
)
type Point struct {
type Access struct {
}
func (h Point) Router(router *mux.Router) {
func (h Access) Router(router *mux.Router) {
router.HandleFunc("/api/point", h.List).Methods("GET")
router.HandleFunc("/api/point/{id}", h.Get).Methods("GET")
}
func (h Point) List(w http.ResponseWriter, r *http.Request) {
points := make([]schema.Point, 0, 1024)
for u := range cache.Point.List() {
func (h Access) List(w http.ResponseWriter, r *http.Request) {
points := make([]schema.Access, 0, 1024)
for u := range cache.Access.List() {
if u == nil {
break
}
points = append(points, models.NewPointSchema(u))
points = append(points, models.NewAccessSchema(u))
}
ResponseJson(w, points)
}
func (h Point) Get(w http.ResponseWriter, r *http.Request) {
func (h Access) Get(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
point := cache.Point.Get(vars["id"])
point := cache.Access.Get(vars["id"])
if point != nil {
ResponseJson(w, models.NewPointSchema(point))
ResponseJson(w, models.NewAccessSchema(point))
} else {
http.Error(w, vars["id"], http.StatusNotFound)
}

View File

@@ -6,7 +6,7 @@ func Add(router *mux.Router, switcher Switcher) {
Link{Switcher: switcher}.Router(router)
User{}.Router(router)
Neighbor{}.Router(router)
Point{}.Router(router)
Access{}.Router(router)
Network{Switcher: switcher}.Router(router)
OnLine{}.Router(router)
Lease{}.Router(router)

View File

@@ -2,6 +2,7 @@ package app
import (
"encoding/json"
"github.com/luscis/openlan/pkg/cache"
"github.com/luscis/openlan/pkg/libol"
"github.com/luscis/openlan/pkg/models"
@@ -95,15 +96,15 @@ func (p *Access) onAuth(client libol.SocketClient, user *models.User) error {
}
out.Info("Access.onAuth: on >>> %s <<<", dev.Name())
proto := p.master.Protocol()
m := models.NewPoint(client, dev, proto)
m := models.NewAccess(client, dev, proto)
m.SetUser(user)
// free point has same uuid.
if om := cache.Point.GetByUUID(m.UUID); om != nil {
if om := cache.Access.GetByUUID(m.UUID); om != nil {
out.Info("Access.onAuth: OffClient %s", om.Client)
p.master.OffClient(om.Client)
}
client.SetPrivate(m)
cache.Point.Add(m)
cache.Access.Add(m)
libol.Go(func() {
p.master.ReadTap(dev, func(f *libol.FrameMessage) error {
if err := client.WriteMsg(f); err != nil {

View File

@@ -66,7 +66,7 @@ func (r *Request) onNeighbor(client libol.SocketClient, data []byte) {
}
}
func findLease(ifAddr string, p *models.Point) *schema.Lease {
func findLease(ifAddr string, p *models.Access) *schema.Lease {
alias := p.Alias
network := p.Network
lease := cache.Network.GetLease(alias, network) // try by alias firstly
@@ -116,7 +116,7 @@ func (r *Request) onIpAddr(client libol.SocketClient, data []byte) {
return
}
out.Cmd("Request.onIpAddr: find %s", n)
p := cache.Point.Get(client.String())
p := cache.Access.Get(client.String())
if p == nil {
out.Error("Request.onIpAddr: point notFound")
return

View File

@@ -5,51 +5,51 @@ import (
"github.com/luscis/openlan/pkg/models"
)
type point struct {
type access struct {
Clients *libol.SafeStrMap
UUIDAddr *libol.SafeStrStr
AddrUUID *libol.SafeStrStr
}
func (p *point) Init(size int) {
func (p *access) Init(size int) {
p.Clients = libol.NewSafeStrMap(size)
p.UUIDAddr = libol.NewSafeStrStr(size)
p.AddrUUID = libol.NewSafeStrStr(size)
}
func (p *point) Add(m *models.Point) {
func (p *access) Add(m *models.Access) {
_ = p.UUIDAddr.Reset(m.UUID, m.Client.String())
_ = p.AddrUUID.Set(m.Client.String(), m.UUID)
_ = p.Clients.Set(m.Client.String(), m)
}
func (p *point) Get(addr string) *models.Point {
func (p *access) Get(addr string) *models.Access {
if v := p.Clients.Get(addr); v != nil {
m := v.(*models.Point)
m := v.(*models.Access)
m.Update()
return m
}
return nil
}
func (p *point) GetByUUID(uuid string) *models.Point {
func (p *access) GetByUUID(uuid string) *models.Access {
if addr := p.GetAddr(uuid); addr != "" {
return p.Get(addr)
}
return nil
}
func (p *point) GetUUID(addr string) string {
func (p *access) GetUUID(addr string) string {
return p.AddrUUID.Get(addr)
}
func (p *point) GetAddr(uuid string) string {
func (p *access) GetAddr(uuid string) string {
return p.UUIDAddr.Get(uuid)
}
func (p *point) Del(addr string) {
func (p *access) Del(addr string) {
if v := p.Clients.Get(addr); v != nil {
m := v.(*models.Point)
m := v.(*models.Access)
if m.Device != nil {
_ = m.Device.Close()
}
@@ -61,12 +61,12 @@ func (p *point) Del(addr string) {
}
}
func (p *point) List() <-chan *models.Point {
c := make(chan *models.Point, 128)
func (p *access) List() <-chan *models.Access {
c := make(chan *models.Access, 128)
go func() {
p.Clients.Iter(func(k string, v interface{}) {
if m, ok := v.(*models.Point); ok {
if m, ok := v.(*models.Access); ok {
m.Update()
c <- m
}
@@ -77,7 +77,7 @@ func (p *point) List() <-chan *models.Point {
return c
}
var Point = point{
var Access = access{
Clients: libol.NewSafeStrMap(1024),
UUIDAddr: libol.NewSafeStrStr(1024),
AddrUUID: libol.NewSafeStrStr(1024),

2
pkg/cache/store.go vendored
View File

@@ -5,7 +5,7 @@ import (
)
func Init(cfg *config.Perf) {
Point.Init(cfg.Point)
Access.Init(cfg.Access)
Link.Init(cfg.Link)
Neighbor.Init(cfg.Neighbor)
Online.Init(cfg.OnLine)

View File

@@ -22,10 +22,10 @@ func TestInit(t *testing.T) {
cfg := &config.Perf{}
cfg.Correct()
Init(cfg)
fmt.Println(Point)
Point.Add(&models.Point{
fmt.Println(Access)
Access.Add(&models.Access{
UUID: "fake",
Client: &SocketClientMock{},
})
assert.Equal(t, 1, Point.Clients.Len(), "MUST be same")
assert.Equal(t, 1, Access.Clients.Len(), "MUST be same")
}

View File

@@ -17,7 +17,7 @@ type Interface struct {
Cost int `json:"cost,omitempty"`
}
type Point struct {
type Access struct {
File string `json:"file,omitempty"`
Alias string `json:"alias,omitempty"`
Connection string `json:"connection"`
@@ -49,27 +49,27 @@ func (i *Interface) Correct() {
}
}
func NewPoint() *Point {
p := &Point{RequestAddr: true}
func NewAccess() *Access {
p := &Access{RequestAddr: true}
p.Parse()
p.Initialize()
return p
}
func (ap *Point) Parse() {
flag.StringVar(&ap.Alias, "alias", "", "Alias for this point")
func (ap *Access) Parse() {
flag.StringVar(&ap.Alias, "alias", "", "Alias for this Access")
flag.StringVar(&ap.Log.File, "log:file", "", "File log saved to")
flag.StringVar(&ap.Conf, "conf", "", "The configuration file")
flag.Parse()
}
func (ap *Point) Id() string {
func (ap *Access) Id() string {
return ap.Connection + ":" + ap.Network
}
func (ap *Point) Initialize() error {
func (ap *Access) Initialize() error {
if err := ap.Load(); err != nil {
libol.Warn("NewPoint.Initialize %s", err)
libol.Warn("NewAccess.Initialize %s", err)
return err
}
ap.Correct()
@@ -77,7 +77,7 @@ func (ap *Point) Initialize() error {
return nil
}
func (ap *Point) Correct() {
func (ap *Access) Correct() {
if ap.Alias == "" {
ap.Alias = GetAlias()
}
@@ -116,7 +116,7 @@ func (ap *Point) Correct() {
ap.Queue.Correct()
}
func (ap *Point) Load() error {
func (ap *Access) Load() error {
if err := libol.FileExist(ap.Conf); err == nil {
return libol.UnmarshalLoad(ap, ap.Conf)
}

View File

@@ -9,8 +9,8 @@ import (
"github.com/stretchr/testify/assert"
)
func TestPointFlags(t *testing.T) {
ap := Point{}
func TestAccessFlags(t *testing.T) {
ap := Access{}
os.Args = []string{
"app",
"-conf", "/etc/openlan/fake.json",
@@ -22,8 +22,8 @@ func TestPointFlags(t *testing.T) {
assert.Equal(t, "/etc/openlan/fake.json", ap.Conf, "be the same.")
}
func TestPoint(t *testing.T) {
ap := Point{
func TestAccess(t *testing.T) {
ap := Access{
Username: "user0@fake",
}
ap.Correct()

View File

@@ -16,7 +16,7 @@ type Network struct {
Bridge *Bridge `json:"bridge,omitempty"`
Subnet *Subnet `json:"subnet,omitempty"`
OpenVPN *OpenVPN `json:"openvpn,omitempty"`
Links []Point `json:"links,omitempty"`
Links []Access `json:"links,omitempty"`
Hosts []HostLease `json:"hosts,omitempty"`
Routes []PrefixRoute `json:"routes,omitempty"`
Acl string `json:"acl,omitempty"`

View File

@@ -236,11 +236,12 @@ func (p *Proxy) Save() {
}
type NameProxy struct {
Conf string `json:"-" yaml:"-"`
Listen string `json:"listen,omitempty"`
Nameto string `json:"nameto,omitempty" yaml:"nameto,omitempty"`
Metric int
Conf string `json:"-" yaml:"-"`
Listen string `json:"listen,omitempty"`
Nameto string `json:"nameto,omitempty" yaml:"nameto,omitempty"`
Metric int `json:"metric,omitempty" yaml:"metric,omitempty"`
Backends ToForwards `json:"backends,omitempty" yaml:"backends,omitempty"`
Access []*Access `json:"access,omitempty" yaml:"access,omitempty"`
}
func (t *NameProxy) Initialize() error {
@@ -258,6 +259,10 @@ func (t *NameProxy) Correct() {
if t.Metric == 0 {
t.Metric = 300
}
for _, acc := range t.Access {
acc.RequestAddr = true
acc.Correct()
}
}
func (t *NameProxy) Load() error {

View File

@@ -8,7 +8,7 @@ import (
)
type Perf struct {
Point int `json:"point"`
Access int `json:"access"`
Neighbor int `json:"neighbor"`
OnLine int `json:"online"`
Link int `json:"link"`
@@ -20,8 +20,8 @@ type Perf struct {
}
func (p *Perf) Correct() {
if p.Point == 0 {
p.Point = 64
if p.Access == 0 {
p.Access = 64
}
if p.Neighbor == 0 {
p.Neighbor = 64

View File

@@ -5,7 +5,7 @@ import (
"github.com/luscis/openlan/pkg/network"
)
type Point struct {
type Access struct {
UUID string `json:"uuid"`
Alias string `json:"alias"`
Network string `json:"network"`
@@ -20,8 +20,8 @@ type Point struct {
System string `json:"system"`
}
func NewPoint(c libol.SocketClient, d network.Taper, proto string) (w *Point) {
return &Point{
func NewAccess(c libol.SocketClient, d network.Taper, proto string) (w *Access) {
return &Access{
Alias: "",
Server: c.LocalAddr(),
Client: c,
@@ -30,7 +30,7 @@ func NewPoint(c libol.SocketClient, d network.Taper, proto string) (w *Point) {
}
}
func (p *Point) Update() *Point {
func (p *Access) Update() *Access {
client := p.Client
if client != nil {
p.Uptime = client.UpTime()
@@ -43,7 +43,7 @@ func (p *Point) Update() *Point {
return p
}
func (p *Point) SetUser(user *User) {
func (p *Access) SetUser(user *User) {
p.User = user.Name
p.UUID = user.UUID
if len(p.UUID) > 13 {

View File

@@ -12,12 +12,12 @@ type Link struct {
StatusFile string
}
func (l *Link) reload() *schema.Point {
status := &schema.Point{}
func (l *Link) reload() *schema.Access {
status := &schema.Access{}
_ = libol.UnmarshalLoad(status, l.StatusFile)
return status
}
func (l *Link) Status() *schema.Point {
func (l *Link) Status() *schema.Access {
return l.reload()
}

View File

@@ -1,9 +1,10 @@
package models
import (
"github.com/luscis/openlan/pkg/libol"
"net"
"time"
"github.com/luscis/openlan/pkg/libol"
)
type Neighbor struct {
@@ -47,9 +48,9 @@ func (e *Neighbor) Update(client libol.SocketClient) {
if private == nil {
return
}
if point, ok := private.(*Point); ok {
e.Network = point.Network
e.Device = point.IfName
if acc, ok := private.(*Access); ok {
e.Network = acc.Network
e.Device = acc.IfName
e.Client = client.String()
}
}

View File

@@ -5,10 +5,10 @@ import (
"github.com/luscis/openlan/pkg/schema"
)
func NewPointSchema(p *Point) schema.Point {
func NewAccessSchema(p *Access) schema.Access {
client, dev := p.Client, p.Device
sts := client.Statistics()
return schema.Point{
return schema.Access{
Uptime: p.Uptime,
UUID: p.UUID,
Alias: p.Alias,

View File

@@ -6,6 +6,7 @@ import (
"sync"
"time"
"github.com/luscis/openlan/pkg/access"
"github.com/luscis/openlan/pkg/config"
"github.com/luscis/openlan/pkg/libol"
"github.com/luscis/openlan/pkg/network"
@@ -20,19 +21,27 @@ type NameProxy struct {
lock sync.RWMutex
names map[string]string
addrs map[string]string
access []*access.Access
}
func NewNameProxy(cfg *config.NameProxy) *NameProxy {
return &NameProxy{
n := &NameProxy{
listen: cfg.Listen,
cfg: cfg,
out: libol.NewSubLogger(cfg.Listen),
names: make(map[string]string),
addrs: make(map[string]string),
}
n.Initialize()
return n
}
func (n *NameProxy) Initialize() {
for _, cfg := range n.cfg.Access {
acc := access.NewAccess(cfg)
acc.Initialize()
n.access = append(n.access, acc)
}
}
func (n *NameProxy) Forward(name, addr, nexthop string) {
@@ -130,14 +139,22 @@ func (n *NameProxy) handleDNS(conn dns.ResponseWriter, r *dns.Msg) {
func (n *NameProxy) Start() {
dns.HandleFunc(".", n.handleDNS)
n.server = &dns.Server{Addr: n.listen, Net: "udp"}
n.out.Info("NameProxy.StartDNS on %s", n.listen)
for _, acc := range n.access {
libol.Go(acc.Start)
}
if err := n.server.ListenAndServe(); err != nil {
n.out.Error("NameProxy.StartDNS server: %v", err)
}
}
func (n *NameProxy) Stop() {
for _, acc := range n.access {
acc.Stop()
}
n.access = nil
if n.server != nil {
n.server.Shutdown()
n.server = nil

View File

@@ -1,6 +1,6 @@
package schema
type Point struct {
type Access struct {
Uptime int64 `json:"uptime"`
UUID string `json:"uuid"`
Network string `json:"network"`

View File

@@ -3,7 +3,7 @@ package schema
type Index struct {
Version Version `json:"version"`
Worker Worker `json:"worker"`
Points []Point `json:"points"`
Access []Access `json:"access"`
Links []Link `json:"links"`
Neighbors []Neighbor `json:"neighbors"`
OnLines []OnLine `json:"online"`

View File

@@ -246,16 +246,16 @@ func (h *Http) getIndex(body *schema.Index) *schema.Index {
body.Version = schema.NewVersionSchema()
body.Worker = api.NewWorkerSchema(h.switcher)
// display accessed point.
for p := range cache.Point.List() {
// display accessed Access.
for p := range cache.Access.List() {
if p == nil {
break
}
body.Points = append(body.Points, models.NewPointSchema(p))
body.Access = append(body.Access, models.NewAccessSchema(p))
}
sort.SliceStable(body.Points, func(i, j int) bool {
ii := body.Points[i]
jj := body.Points[j]
sort.SliceStable(body.Access, func(i, j int) bool {
ii := body.Access[i]
jj := body.Access[j]
return ii.Network+ii.Remote > jj.Network+jj.Remote
})
// display neighbor.

View File

@@ -19,12 +19,12 @@ const (
)
type Link struct {
cfg *co.Point
cfg *co.Access
out *libol.SubLogger
uuid string
}
func NewLink(cfg *co.Point) *Link {
func NewLink(cfg *co.Access) *Link {
uuid := libol.GenString(13)
return &Link{
uuid: uuid,
@@ -50,7 +50,7 @@ func (l *Link) Initialize() {
_ = libol.MarshalSave(l.cfg, file, true)
}
func (l *Link) Conf() *co.Point {
func (l *Link) Conf() *co.Access {
return l.cfg
}

View File

@@ -207,7 +207,7 @@ func (w *WorkerImpl) addOutput(bridge string, port *co.Output) {
port.Link = cn.Taps.GenName()
name, pass := SplitCombined(port.Secret)
algo, secret := SplitCombined(port.Crypt)
ac := co.Point{
ac := co.Access{
Alias: w.cfg.Alias,
Network: w.cfg.Name,
RequestAddr: false,

View File

@@ -174,7 +174,7 @@ func (w *OpenLANWorker) UpTime() int64 {
return 0
}
func (w *OpenLANWorker) AddLink(c co.Point) {
func (w *OpenLANWorker) AddLink(c co.Access) {
br := w.cfg.Bridge
c.Alias = w.alias

View File

@@ -189,7 +189,7 @@ func (v *Switch) preNetwork() {
}
func (v *Switch) preApplication() {
// Append accessed auth for point
// Append accessed auth for Access
v.apps.Auth = app.NewAccess(v)
v.hooks = append(v.hooks, v.apps.Auth.OnFrame)
// Append request process
@@ -331,14 +331,14 @@ func (v *Switch) SignIn(client libol.SocketClient) error {
return nil
}
func client2Point(client libol.SocketClient) (*models.Point, error) {
func client2Access(client libol.SocketClient) (*models.Access, error) {
addr := client.RemoteAddr()
if private := client.Private(); private == nil {
return nil, libol.NewErr("point %s notFound.", addr)
return nil, libol.NewErr("Access %s notFound.", addr)
} else {
obj, ok := private.(*models.Point)
obj, ok := private.(*models.Access)
if !ok {
return nil, libol.NewErr("point %s notRight.", addr)
return nil, libol.NewErr("Access %s notRight.", addr)
}
return obj, nil
}
@@ -353,7 +353,7 @@ func (v *Switch) ReadClient(client libol.SocketClient, frame *libol.FrameMessage
if err := v.onFrame(client, frame); err != nil {
v.out.Debug("Switch.ReadClient: %s dropping by %s", addr, err)
if frame.Action() == libol.PingReq {
// send sign message to point require login.
// send sign message to Access require login.
_ = v.SignIn(client)
}
return nil
@@ -362,7 +362,7 @@ func (v *Switch) ReadClient(client libol.SocketClient, frame *libol.FrameMessage
return nil
}
// process ethernet frame message.
obj, err := client2Point(client)
obj, err := client2Access(client)
if err != nil {
return err
}
@@ -380,10 +380,10 @@ func (v *Switch) ReadClient(client libol.SocketClient, frame *libol.FrameMessage
func (v *Switch) OnClose(client libol.SocketClient) error {
addr := client.RemoteAddr()
v.out.Info("Switch.OnClose: %s", addr)
if obj, err := client2Point(client); err == nil {
if obj, err := client2Access(client); err == nil {
cache.Network.DelLease(obj.Alias, obj.Network)
}
cache.Point.Del(addr)
cache.Access.Del(addr)
return nil
}
@@ -428,9 +428,9 @@ func (v *Switch) Stop() {
}
w.Stop()
}
v.out.Info("Switch.Stop left points")
// notify leave to point.
for p := range cache.Point.List() {
v.out.Info("Switch.Stop left Accesss")
// notify leave to Access.
for p := range cache.Access.List() {
if p == nil {
break
}