/
dial.go
64 lines (51 loc) · 1.45 KB
/
dial.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
package websocket
import (
cryptorand "crypto/rand"
"crypto/sha1"
"encoding/base64"
"errors"
"github.com/AlexxIT/go2rtc/pkg/tcp"
"net"
"net/http"
"strings"
)
func Dial(address string) (net.Conn, error) {
if strings.HasPrefix(address, "ws") {
address = "http" + address[2:] // support http and https
}
// using custom client for support Digest Auth
// https://github.com/AlexxIT/go2rtc/issues/415
ctx, pconn := tcp.WithConn()
req, err := http.NewRequestWithContext(ctx, "GET", address, nil)
if err != nil {
return nil, err
}
key, accept := GetKeyAccept()
// Version, Key, Protocol important for Axis cameras
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "websocket")
req.Header.Set("Sec-WebSocket-Version", "13")
req.Header.Set("Sec-WebSocket-Key", key)
req.Header.Set("Sec-WebSocket-Protocol", "binary")
res, err := tcp.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusSwitchingProtocols {
return nil, errors.New("wrong status: " + res.Status)
}
if res.Header.Get("Sec-Websocket-Accept") != accept {
return nil, errors.New("wrong websocket accept")
}
return NewClient(*pconn), nil
}
func GetKeyAccept() (key, accept string) {
b := make([]byte, 16)
_, _ = cryptorand.Read(b)
key = base64.StdEncoding.EncodeToString(b)
h := sha1.New()
h.Write([]byte(key))
h.Write([]byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
accept = base64.StdEncoding.EncodeToString(h.Sum(nil))
return
}