-
Notifications
You must be signed in to change notification settings - Fork 177
/
socket.go
292 lines (247 loc) · 7.29 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright (c) 2012-2014 Jeremy Latt
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package irc
import (
"bufio"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"errors"
"io"
"net"
"strings"
"sync"
"time"
"github.com/oragono/oragono/irc/utils"
)
var (
handshakeTimeout, _ = time.ParseDuration("5s")
errSendQExceeded = errors.New("SendQ exceeded")
sendQExceededMessage = []byte("\r\nERROR :SendQ Exceeded\r\n")
)
// Socket represents an IRC socket.
type Socket struct {
sync.Mutex
conn net.Conn
reader *bufio.Reader
maxSendQBytes int
// this is a trylock enforcing that only one goroutine can write to `conn` at a time
writerSemaphore utils.Semaphore
buffers [][]byte
totalLength int
closed bool
sendQExceeded bool
finalData []byte // what to send when we die
finalized bool
}
// NewSocket returns a new Socket.
func NewSocket(conn net.Conn, maxReadQBytes int, maxSendQBytes int) *Socket {
result := Socket{
conn: conn,
reader: bufio.NewReaderSize(conn, maxReadQBytes),
maxSendQBytes: maxSendQBytes,
}
result.writerSemaphore.Initialize(1)
return &result
}
// Close stops a Socket from being able to send/receive any more data.
func (socket *Socket) Close() {
socket.Lock()
socket.closed = true
socket.Unlock()
socket.wakeWriter()
}
// CertFP returns the fingerprint of the certificate provided by the client.
func (socket *Socket) CertFP() (string, error) {
var tlsConn, isTLS = socket.conn.(*tls.Conn)
if !isTLS {
return "", errNotTLS
}
// ensure handehake is performed, and timeout after a few seconds
tlsConn.SetDeadline(time.Now().Add(handshakeTimeout))
err := tlsConn.Handshake()
tlsConn.SetDeadline(time.Time{})
if err != nil {
return "", err
}
peerCerts := tlsConn.ConnectionState().PeerCertificates
if len(peerCerts) < 1 {
return "", errNoPeerCerts
}
rawCert := sha256.Sum256(peerCerts[0].Raw)
fingerprint := hex.EncodeToString(rawCert[:])
return fingerprint, nil
}
// Read returns a single IRC line from a Socket.
func (socket *Socket) Read() (string, error) {
if socket.IsClosed() {
return "", io.EOF
}
lineBytes, isPrefix, err := socket.reader.ReadLine()
if isPrefix {
return "", errReadQ
}
// convert bytes to string
line := string(lineBytes)
// read last message properly (such as ERROR/QUIT/etc), just fail next reads/writes
if err == io.EOF {
socket.Close()
}
if err == io.EOF && strings.TrimSpace(line) != "" {
// don't do anything
} else if err != nil {
return "", err
}
return line, nil
}
// Write sends the given string out of Socket. Requirements:
// 1. MUST NOT block for macroscopic amounts of time
// 2. MUST NOT reorder messages
// 3. MUST provide mutual exclusion for socket.conn.Write
// 4. SHOULD NOT tie up additional goroutines, beyond the one blocked on socket.conn.Write
func (socket *Socket) Write(data []byte) (err error) {
if len(data) == 0 {
return
}
socket.Lock()
if socket.closed {
err = io.EOF
} else {
prospectiveLen := socket.totalLength + len(data)
if prospectiveLen > socket.maxSendQBytes {
socket.sendQExceeded = true
socket.closed = true
err = errSendQExceeded
} else {
socket.buffers = append(socket.buffers, data)
socket.totalLength = prospectiveLen
}
}
socket.Unlock()
socket.wakeWriter()
return
}
// BlockingWrite sends the given string out of Socket. Requirements:
// 1. MUST block until the message is sent
// 2. MUST bypass sendq (calls to BlockingWrite cannot, on their own, cause a sendq overflow)
// 3. MUST provide mutual exclusion for socket.conn.Write
// 4. MUST respect the same ordering guarantees as Write (i.e., if a call to Write that sends
// message m1 happens-before a call to BlockingWrite that sends message m2,
// m1 must be sent on the wire before m2
// Callers MUST be writing to the client's socket from the client's own goroutine;
// other callers must use the nonblocking Write call instead. Otherwise, a client
// with a slow/unreliable connection risks stalling the progress of the system as a whole.
func (socket *Socket) BlockingWrite(data []byte) (err error) {
if len(data) == 0 {
return
}
// after releasing the semaphore, we must check for fresh data, same as `send`
defer func() {
if socket.readyToWrite() {
socket.wakeWriter()
}
}()
// blocking acquire of the trylock
socket.writerSemaphore.Acquire()
defer socket.writerSemaphore.Release()
// first, flush any buffered data, to preserve the ordering guarantees
closed := socket.performWrite()
if closed {
return io.EOF
}
_, err = socket.conn.Write(data)
if err != nil {
socket.finalize()
}
return
}
// wakeWriter starts the goroutine that actually performs the write, without blocking
func (socket *Socket) wakeWriter() {
if socket.writerSemaphore.TryAcquire() {
// acquired the trylock; send() will release it
go socket.send()
}
// else: do nothing, the holder will check for more data after releasing it
}
// SetFinalData sets the final data to send when the SocketWriter closes.
func (socket *Socket) SetFinalData(data []byte) {
socket.Lock()
defer socket.Unlock()
socket.finalData = data
}
// IsClosed returns whether the socket is closed.
func (socket *Socket) IsClosed() bool {
socket.Lock()
defer socket.Unlock()
return socket.closed
}
// is there data to write?
func (socket *Socket) readyToWrite() bool {
socket.Lock()
defer socket.Unlock()
// on the first time observing socket.closed, we still have to write socket.finalData
return !socket.finalized && (socket.totalLength > 0 || socket.closed)
}
// send actually writes messages to socket.Conn; it may block
func (socket *Socket) send() {
for {
// we are holding the trylock: actually do the write
socket.performWrite()
// surrender the trylock, avoiding a race where a write comes in after we've
// checked readyToWrite() and it returned false, but while we still hold the trylock:
socket.writerSemaphore.Release()
// check if more data came in while we held the trylock:
if !socket.readyToWrite() {
return
}
if !socket.writerSemaphore.TryAcquire() {
// failed to acquire; exit and wait for the holder to observe readyToWrite()
// after releasing it
return
}
// got the lock again, loop back around and write
}
}
// write the contents of the buffer, then see if we need to close
// returns whether we closed
func (socket *Socket) performWrite() (closed bool) {
// retrieve the buffered data, clear the buffer
socket.Lock()
buffers := socket.buffers
socket.buffers = nil
socket.totalLength = 0
closed = socket.closed
socket.Unlock()
var err error
if 0 < len(buffers) {
// on Linux, the runtime will optimize this into a single writev(2) call:
_, err = (*net.Buffers)(&buffers).WriteTo(socket.conn)
}
closed = closed || err != nil
if closed {
socket.finalize()
}
return
}
// mark closed and send final data. you must be holding the semaphore to call this:
func (socket *Socket) finalize() {
// mark the socket closed (if someone hasn't already), then write error lines
socket.Lock()
socket.closed = true
finalized := socket.finalized
socket.finalized = true
finalData := socket.finalData
if socket.sendQExceeded {
finalData = sendQExceededMessage
}
socket.Unlock()
if finalized {
return
}
if len(finalData) != 0 {
socket.conn.Write(finalData)
}
// close the connection
socket.conn.Close()
}