-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
195 lines (166 loc) · 4.39 KB
/
socket.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package main
import (
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"net"
"strings"
"golang.org/x/crypto/bcrypt"
)
var actitveConnections map[string]net.Conn
func webSocketHandshake(conn net.Conn, req []string) []byte {
var index = 0
for i, s := range req {
if strings.HasPrefix(s, "Sec-WebSocket-Key: ") {
index = i
}
}
var key = strings.Split(req[index], "Sec-WebSocket-Key: ")[1]
var hash = sha1.Sum([]byte(key + GUID))
var accept = base64.StdEncoding.EncodeToString(hash[:])
var content = "Connection: Upgrade" + cr + "Upgrade: websocket" + cr + "Sec-WebSocket-Accept: " + accept
var response = makeResponse(switching, "", nil, []byte(content))
return response
}
func webSocketServer(conn net.Conn, token string) {
var tokens = getTokens()
var userToken = Token{}
for _, t := range tokens {
err := bcrypt.CompareHashAndPassword([]byte(t.Token), []byte(token))
if err == nil {
userToken = t
break
}
}
if (userToken == Token{}) {
var res = makeFrame([]byte(""))
conn.Write(res)
return
}
var username = userToken.Username
if actitveConnections == nil {
actitveConnections = make(map[string]net.Conn)
}
actitveConnections[username] = conn
for {
buffer := make([]byte, 1024)
_, err := conn.Read(buffer)
if err != nil {
fmt.Println("Read error 4: ", err.Error())
delete(actitveConnections, username)
return
}
var opcode = buffer[0] & 15
var maskBit = (buffer[1] & 128) / 128
var length = int(buffer[1] & 127)
var mask []byte
var payloadIndex = 2
if length == 126 {
//Read the next 16 bits
length = int(binary.BigEndian.Uint16(buffer[2:4]))
payloadIndex = 4
} else if length == 127 {
//Read the next 64 bits
length = int(binary.BigEndian.Uint64(buffer[2:10]))
payloadIndex = 10
}
if length > 1024 {
for length > len(buffer) {
newBuffer := make([]byte, 1024)
_, err := conn.Read(newBuffer)
if err != nil {
fmt.Println("Read error 5: ", err.Error())
}
buffer = append(buffer, newBuffer...)
}
}
if maskBit == 1 {
mask = buffer[payloadIndex : payloadIndex+4]
payloadIndex = payloadIndex + 4
}
var payload = buffer[payloadIndex : payloadIndex+length]
if maskBit == 1 {
var counter = 0
for i := range payload {
payload[i] = payload[i] ^ mask[counter]
counter = counter + 1
if counter == 4 {
counter = 0
}
}
}
if opcode == 8 {
delete(actitveConnections, username)
var res = makeFrame([]byte(""))
conn.Write(res)
return
}
if opcode == 1 {
// Format is text
var result map[string]string
json.Unmarshal(payload, &result)
if result["messageType"] == "chatMessage" {
var userToken2 = getTokenByHash(result["token"])
if userToken2.Username == username {
var messageText = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(result["comment"], "&", "&"), "<", "<"), ">", ">")
messageObject := new(Message)
messageObject.Message = messageText
messageObject.Username = username
addMessage(*messageObject)
message := map[string]string{"messageType": "chatMessage", "username": username, "comment": messageText}
response, _ := json.Marshal(&message)
var res = makeFrame(response)
for _, c := range actitveConnections {
c.Write(res)
}
}
} else if result["messageType"] == "webRTC-offer" || result["messageType"] == "webRTC-answer" || result["messageType"] == "webRTC-candidate" {
var frame = makeFrame(payload)
for u, c := range actitveConnections {
if u != username {
c.Write(frame)
}
}
}
}
if opcode == 2 {
//Format is binary
}
}
}
func makeFrame(payload []byte) []byte {
var length = len(payload)
var payloadIndex = 2
var sizeLength = 0
if length < 126 {
sizeLength = 2
} else if length >= 126 && length < 65536 {
sizeLength = 4
} else if length >= 65536 {
sizeLength = 10
}
frame := make([]byte, length+sizeLength)
if length == 0 {
frame[0] = 136
} else {
frame[0] = 129
}
if length < 126 {
frame[1] = byte(length)
} else if length >= 126 && length < 65536 {
frame[1] = 126
binary.BigEndian.PutUint16(frame[2:4], uint16(length))
payloadIndex = 4
} else if length >= 65536 {
frame[1] = 127
binary.BigEndian.PutUint64(frame[2:10], uint64(length))
payloadIndex = 10
}
for _, b := range payload {
frame[payloadIndex] = b
payloadIndex = payloadIndex + 1
}
return frame
}