File
Blob: spec/tun/tun.go
| 1 | package tun |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | |
| 8 | "go.miragespace.co/specter/spec/chord" |
| 9 | "go.miragespace.co/specter/spec/protocol" |
| 10 | "go.miragespace.co/specter/spec/rpc" |
| 11 | "go.miragespace.co/specter/spec/transport" |
| 12 | ) |
| 13 | |
| 14 | const ( |
| 15 | NumRedundantLinks = 3 |
| 16 | ) |
| 17 | |
| 18 | func IsNoDirect(err error) bool { |
| 19 | return errors.Is(err, transport.ErrNoDirect) || |
| 20 | errors.Is(err, ErrTunnelClientNotConnected) |
| 21 | } |
| 22 | |
| 23 | func SendStatusProto(dest io.Writer, err error) { |
| 24 | status := &protocol.TunnelStatus{} |
| 25 | if err != nil { |
| 26 | if IsNoDirect(err) { |
| 27 | status.Status = protocol.TunnelStatusCode_NO_DIRECT |
| 28 | } else { |
| 29 | status.Status = protocol.TunnelStatusCode_UNKNOWN_ERROR |
| 30 | } |
| 31 | status.Error = err.Error() |
| 32 | } |
| 33 | rpc.Send(dest, status) |
| 34 | } |
| 35 | |
| 36 | func DrainStatusProto(src io.Reader) (err error) { |
| 37 | var b [rpc.LengthSize]byte |
| 38 | _, err = io.ReadFull(src, b[:]) |
| 39 | return |
| 40 | } |
| 41 | |
| 42 | func SaveCustomHostname(ctx context.Context, kv chord.KV, hostname string, bundle *protocol.CustomHostname) (err error) { |
| 43 | data, err := bundle.MarshalVT() |
| 44 | if err != nil { |
| 45 | return nil |
| 46 | } |
| 47 | |
| 48 | err = kv.Put(ctx, []byte(CustomHostnameKey(hostname)), data) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | |
| 53 | return nil |
| 54 | } |
| 55 | |
| 56 | func FindCustomHostname(ctx context.Context, kv chord.KV, hostname string) (*protocol.CustomHostname, error) { |
| 57 | val, err := kv.Get(ctx, []byte(CustomHostnameKey(hostname))) |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | |
| 62 | if len(val) == 0 { |
| 63 | return nil, ErrHostnameNotFound |
| 64 | } |
| 65 | |
| 66 | bundle := &protocol.CustomHostname{} |
| 67 | |
| 68 | if err := bundle.UnmarshalVT(val); err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | |
| 72 | return bundle, nil |
| 73 | } |
| 74 | |
| 75 | func RemoveCustomHostname(ctx context.Context, kv chord.KV, hostname string) error { |
| 76 | return kv.Delete(ctx, []byte(CustomHostnameKey(hostname))) |
| 77 | } |