84 lines
1.5 KiB
Go
84 lines
1.5 KiB
Go
package host
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"lux/proto"
|
|
"lux/rpc"
|
|
)
|
|
|
|
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)
|
|
}
|
|
}
|
|
|
|
// RPC
|
|
|
|
func (state *LuxState) IntoRpc() rpc.LuxRpcState {
|
|
rpcState := rpc.LuxRpcState{
|
|
Options: make([]rpc.LuxRpcOption, 0),
|
|
}
|
|
|
|
for optType, opt := range state.Options {
|
|
switch optType {
|
|
case LuxOptionTypeWAN:
|
|
wan := opt.(*LuxOptionWAN)
|
|
rpcState.WAN = rpc.LuxRpcWAN{
|
|
Addr4: wan.Addr4.String(),
|
|
Addr6: wan.Addr4.String(),
|
|
}
|
|
default:
|
|
// encode option in base64 blob
|
|
wd := proto.NewLuxBuffer()
|
|
opt.Write(&wd)
|
|
|
|
rpcState.Options = append(rpcState.Options, rpc.LuxRpcOption{
|
|
Type: int(optType),
|
|
Blob: base64.StdEncoding.EncodeToString(wd.AllBytes()),
|
|
})
|
|
}
|
|
}
|
|
|
|
return rpcState
|
|
}
|