-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.go
80 lines (65 loc) · 1.8 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// SPDX-FileCopyrightText: 2021 The Secretstream Authors
//
// SPDX-License-Identifier: MIT
package secretstream
import (
"fmt"
"net"
"time"
"github.com/ssbc/go-secretstream/boxstream"
"github.com/ssbc/go-secretstream/secrethandshake"
"github.com/ssbc/go-netwrap"
)
// Server can create net.Listeners
type Server struct {
keyPair secrethandshake.EdKeyPair
appKey []byte
}
// NewServer returns a Server which uses the passed keyPair and appKey
func NewServer(keyPair secrethandshake.EdKeyPair, appKey []byte) (*Server, error) {
return &Server{keyPair: keyPair, appKey: appKey}, nil
}
// ListenerWrapper returns a listener wrapper.
func (s *Server) ListenerWrapper() netwrap.ListenerWrapper {
return netwrap.NewListenerWrapper(s.Addr(), s.ConnWrapper())
}
// ConnWrapper returns a connection wrapper.
func (s *Server) ConnWrapper() netwrap.ConnWrapper {
return func(conn net.Conn) (net.Conn, error) {
state, err := secrethandshake.NewServerState(s.appKey, s.keyPair)
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
errc := make(chan error)
go func() {
errc <- secrethandshake.Server(state, conn)
close(errc)
}()
select {
case err := <-errc:
if err != nil {
return nil, err
}
case <-time.After(2 * time.Minute):
return nil, fmt.Errorf("secretstream: handshake timeout")
}
enKey, enNonce := state.GetBoxstreamEncKeys()
deKey, deNonce := state.GetBoxstreamDecKeys()
remote := state.Remote()
boxed := &Conn{
boxer: boxstream.NewBoxer(conn, &enNonce, &enKey),
unboxer: boxstream.NewUnboxer(conn, &deNonce, &deKey),
conn: conn,
local: s.keyPair.Public[:],
remote: remote[:],
}
return boxed, nil
}
}
// Addr returns the shs-bs address of the server.
func (s *Server) Addr() net.Addr {
return Addr{s.keyPair.Public[:]}
}