-
Notifications
You must be signed in to change notification settings - Fork 10
/
brutal.go
61 lines (54 loc) · 1.42 KB
/
brutal.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
package mux
import (
"encoding/binary"
"io"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/rw"
)
const (
BrutalExchangeDomain = "_BrutalBwExchange"
BrutalMinSpeedBPS = 65536
)
func WriteBrutalRequest(writer io.Writer, receiveBPS uint64) error {
return binary.Write(writer, binary.BigEndian, receiveBPS)
}
func ReadBrutalRequest(reader io.Reader) (uint64, error) {
var receiveBPS uint64
err := binary.Read(reader, binary.BigEndian, &receiveBPS)
return receiveBPS, err
}
func WriteBrutalResponse(writer io.Writer, receiveBPS uint64, ok bool, message string) error {
buffer := buf.New()
defer buffer.Release()
common.Must(binary.Write(buffer, binary.BigEndian, ok))
if ok {
common.Must(binary.Write(buffer, binary.BigEndian, receiveBPS))
} else {
err := rw.WriteVString(buffer, message)
if err != nil {
return err
}
}
return common.Error(writer.Write(buffer.Bytes()))
}
func ReadBrutalResponse(reader io.Reader) (uint64, error) {
var ok bool
err := binary.Read(reader, binary.BigEndian, &ok)
if err != nil {
return 0, err
}
if ok {
var receiveBPS uint64
err = binary.Read(reader, binary.BigEndian, &receiveBPS)
return receiveBPS, err
} else {
var message string
message, err = rw.ReadVString(reader)
if err != nil {
return 0, err
}
return 0, E.New("remote error: ", message)
}
}