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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package tunnel
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"net"
"strings"
"time"
)
const (
KindWebRTC = "webrtc"
SignalOffer = "offer"
SignalAnswer = "answer"
NetworkWebRTC = "webrtc"
DefaultSTUN = "stun:stun.cloudflare.com:3478"
)
type Offer struct {
Kind string `json:"kind"`
ID string `json:"id"`
Session string `json:"session"`
Peer string `json:"peer"`
Type string `json:"type"`
SDP string `json:"sdp"`
}
type Answer struct {
Kind string `json:"kind"`
ID string `json:"id"`
Session string `json:"session"`
Peer string `json:"peer"`
Type string `json:"type"`
SDP string `json:"sdp"`
}
type ServiceOptions struct {
STUN []string
SessionTTL time.Duration
MaxSessions int
}
type Service interface {
Offer(ctx context.Context, owner, peer string) (Offer, error)
Accept(ctx context.Context, answer Answer) error
Close() error
}
type Answerer interface {
Answer(ctx context.Context, offer Offer) (Answer, error)
}
type Dialer interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
func ID(owner string) string {
owner = strings.TrimSpace(owner)
if owner == "" {
return ""
}
sum := sha256.Sum256([]byte("socialweb.computer/ingress/" + owner))
return hex.EncodeToString(sum[:16])
}
func Ref(id string) string {
if id == "" {
return ""
}
return KindWebRTC + "://" + id
}
func ParseRef(raw string) (string, bool) {
rest, ok := strings.CutPrefix(strings.TrimSpace(raw), KindWebRTC+"://")
if !ok || rest == "" || strings.ContainsAny(rest, "/?#@ \t\r\n") {
return "", false
}
return rest, true
}
func IsRef(raw string) bool {
_, ok := ParseRef(raw)
return ok
}
func NewSession() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return ""
}
return hex.EncodeToString(b)
}
func ValidOffer(offer Offer) bool {
return offer.Kind == KindWebRTC && offer.ID != "" && offer.Session != "" && offer.Peer != "" && offer.Type == SignalOffer && offer.SDP != ""
}
func ValidAnswer(answer Answer) bool {
return answer.Kind == KindWebRTC && answer.ID != "" && answer.Session != "" && answer.Peer != "" && answer.Type == SignalAnswer && answer.SDP != ""
}