From 164d23d28ac6c6fb363fd86214fbdf56ba80ba61 Mon Sep 17 00:00:00 2001 From: mykola2312 <49044616+mykola2312@users.noreply.github.com> Date: Sat, 11 Jan 2025 02:28:46 +0200 Subject: [PATCH] implement LuxState --- host/lux_option.go | 31 ++++++++++++++++++++++++++-- host/lux_state.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 host/lux_state.go diff --git a/host/lux_option.go b/host/lux_option.go index 343093f..3b8b818 100644 --- a/host/lux_option.go +++ b/host/lux_option.go @@ -1,6 +1,7 @@ package host import ( + "fmt" "lux/proto" "net" ) @@ -8,8 +9,8 @@ import ( type LuxOptionType uint const ( - LuxOptionTypeWAN = 1 - LuxOptionTypeWAN6 = 2 + LuxOptionTypeWAN = 0 + LuxOptionTypeWAN6 = 1 ) type LuxOption interface { @@ -62,3 +63,29 @@ func (opt *LuxOptionWAN6) Write(wd *proto.LuxBuffer) { func (*LuxOptionWAN6) Type() LuxOptionType { return LuxOptionTypeWAN6 } + +func ReadLuxOption(rd *proto.LuxBuffer) (LuxOption, error) { + var err error + optVal, err := rd.ReadUint16() + if err != nil { + return nil, err + } + + switch LuxOptionType(optVal) { + case LuxOptionTypeWAN: + opt := &LuxOptionWAN{} + err = opt.Read(rd) + return opt, err + case LuxOptionTypeWAN6: + opt := &LuxOptionWAN6{} + err = opt.Read(rd) + return opt, err + default: + return nil, fmt.Errorf("unknown option %d", optVal) + } +} + +func WriteLuxOption(wd *proto.LuxBuffer, opt LuxOption) { + wd.WriteUint16(uint16(opt.Type())) + opt.Write(wd) +} diff --git a/host/lux_state.go b/host/lux_state.go new file mode 100644 index 0000000..dcbfb45 --- /dev/null +++ b/host/lux_state.go @@ -0,0 +1,50 @@ +package host + +import "lux/proto" + +type LuxState struct { + Hostname string + Options map[LuxOptionType]LuxOption +} + +func NewLuxState(hostname string) LuxState { + return LuxState{ + Hostname: hostname, + Options: make(map[LuxOptionType]LuxOption), + } +} + +func (state *LuxState) Read(rd *proto.LuxBuffer) error { + // hostname + hostname, err := rd.ReadString() + if err != nil { + return err + } + state.Hostname = hostname + + // option count + count, err := rd.ReadUint16() + if err != nil { + return nil + } + + for i := 0; i < int(count); i++ { + // read options + opt, err := ReadLuxOption(rd) + if err != nil { + return err + } + + state.Options[opt.Type()] = opt + } + + return nil +} + +func (state *LuxState) Write(wd *proto.LuxBuffer) { + wd.WriteString(state.Hostname) + wd.WriteUint16(uint16(len(state.Options))) + for _, opt := range state.Options { + WriteLuxOption(wd, opt) + } +}