Skip to content

Commit 3c52b6c

Browse files
committed
raknet: Update to go1.22 and use the new range int feature.
1 parent 157aab6 commit 3c52b6c

File tree

10 files changed

+115
-120
lines changed

10 files changed

+115
-120
lines changed

acknowledge.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,8 @@ func (ack *acknowledgement) read(b []byte) error {
9797
if len(b) < 2 {
9898
return io.ErrUnexpectedEOF
9999
}
100-
n := binary.BigEndian.Uint16(b)
101100
offset := 2
102-
for i := uint16(0); i < n; i++ {
101+
for range binary.BigEndian.Uint16(b) {
103102
if len(b)-offset < 4 {
104103
return io.ErrUnexpectedEOF
105104
}

conn.go

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,6 @@ func (conn *Conn) startTicking() {
162162
conn.mu.Lock()
163163
acksLeft = len(conn.retransmission.unacknowledged)
164164
conn.mu.Unlock()
165-
166165
if before != 0 && acksLeft == 0 {
167166
conn.closeImmediately()
168167
}
@@ -383,13 +382,8 @@ func (conn *Conn) send(pk encoding.BinaryMarshaler) error {
383382
return err
384383
}
385384

386-
// packetPool is a sync.Pool used to pool packets that encapsulate their
387-
// content.
388-
var packetPool = sync.Pool{
389-
New: func() interface{} {
390-
return &packet{reliability: reliabilityReliableOrdered}
391-
},
392-
}
385+
// packetPool is used to pool packets that encapsulate their content.
386+
var packetPool = sync.Pool{New: func() any { return &packet{reliability: reliabilityReliableOrdered} }}
393387

394388
// receive receives a packet from the connection, handling it as appropriate.
395389
// If not successful, an error is returned.
@@ -422,13 +416,13 @@ func (conn *Conn) receiveDatagram(b []byte) error {
422416
conn.ackSlice = append(conn.ackSlice, seq)
423417
conn.ackMu.Unlock()
424418

425-
if !conn.win.new(seq) {
426-
// Datagram was already received, this might happen if a packet took a long time to arrive, and we already sent
427-
// a NACK for it. This is expected to happen sometimes under normal circumstances, so no reason to return an
428-
// error.
419+
if !conn.win.add(seq) {
420+
// Datagram was already received, this might happen if a packet took a
421+
// long time to arrive, and we already sent a NACK for it. This is
422+
// expected to happen sometimes under normal circumstances, so no reason
423+
// to return an error.
429424
return nil
430425
}
431-
conn.win.add(seq)
432426
if conn.win.shift() == 0 {
433427
// Datagram window couldn't be shifted up, so we're still missing
434428
// packets.

datagram_window.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,23 @@ func newDatagramWindow() *datagramWindow {
1515
return &datagramWindow{queue: make(map[uint24]time.Time)}
1616
}
1717

18-
// new checks if the index passed is new to the datagramWindow.
19-
func (win *datagramWindow) new(index uint24) bool {
20-
if index < win.lowest {
21-
return true
18+
// add puts an index in the window.
19+
func (win *datagramWindow) add(index uint24) bool {
20+
if win.seen(index) {
21+
return false
2222
}
23-
_, ok := win.queue[index]
24-
return !ok
23+
win.highest = max(win.highest, index+1)
24+
win.queue[index] = time.Now()
25+
return true
2526
}
2627

27-
// add puts an index in the window.
28-
func (win *datagramWindow) add(index uint24) {
29-
if index >= win.highest {
30-
win.highest = index + 1
28+
// seen checks if the index passed is known to the datagramWindow.
29+
func (win *datagramWindow) seen(index uint24) bool {
30+
if index < win.lowest {
31+
return true
3132
}
32-
win.queue[index] = time.Now()
33+
_, ok := win.queue[index]
34+
return ok
3335
}
3436

3537
// shift attempts to delete as many indices from the queue as possible,
@@ -51,9 +53,7 @@ func (win *datagramWindow) shift() (n int) {
5153
// set using add while within the window of lowest and highest index. The queue
5254
// is shifted after this call.
5355
func (win *datagramWindow) missing(since time.Duration) (indices []uint24) {
54-
var (
55-
missing = false
56-
)
56+
missing := false
5757
for index := int(win.highest) - 1; index >= int(win.lowest); index-- {
5858
i := uint24(index)
5959
t, ok := win.queue[i]

dial.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ func (dialer Dialer) DialContext(ctx context.Context, address string) (*Conn, er
230230
}
231231

232232
func (dialer Dialer) connect(ctx context.Context, state *connState) (*Conn, error) {
233-
conn := newConn(internal.ConnToPacketConn(state.conn), state.raddr, state.mtu, &dialerConnectionHandler{})
233+
conn := newConn(internal.ConnToPacketConn(state.conn), state.raddr, state.mtu, dialerConnectionHandler{})
234234
if err := conn.send((&message.ConnectionRequest{ClientGUID: state.id, RequestTimestamp: timestamp()})); err != nil {
235235
return nil, dialer.error("dial", fmt.Errorf("send connection request: %w", err))
236236
}
@@ -313,8 +313,7 @@ func (state *connState) discoverMTU(ctx context.Context) error {
313313
if err := response.UnmarshalBinary(b[1:n]); err != nil {
314314
return fmt.Errorf("read open connection reply 1: %w", err)
315315
}
316-
state.serverSecurity = response.Secure
317-
state.cookie = response.Cookie
316+
state.serverSecurity, state.cookie = response.Secure, response.Cookie
318317
if response.ServerGUID == 0 || response.ServerPreferredMTUSize < 400 || response.ServerPreferredMTUSize > 1500 {
319318
// This is an awful hack we cooked up to deal with OVH 'DDoS'
320319
// protection. For some reason they send a broken MTU size
@@ -342,7 +341,7 @@ func (state *connState) request1(ctx context.Context, sizes []uint16) {
342341
defer ticker.Stop()
343342

344343
for _, size := range sizes {
345-
for attempt := 0; attempt < 3; attempt++ {
344+
for range 3 {
346345
state.openConnectionRequest1(size)
347346
select {
348347
case <-ticker.C:

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module github.com/sandertv/go-raknet
22

3-
go 1.21.0
3+
go 1.22

handler.go

Lines changed: 78 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,22 @@ var (
2121
errUnexpectedAdditionalNIC = errors.New("unexpected additional NEW_INCOMING_CONNECTION packet")
2222
)
2323

24-
func (h *listenerConnectionHandler) handleUnconnected(b []byte, addr net.Addr) error {
24+
func (h listenerConnectionHandler) limitsEnabled() bool {
25+
return true
26+
}
27+
28+
func (h listenerConnectionHandler) close(conn *Conn) {
29+
h.l.connections.Delete(resolve(conn.raddr))
30+
}
31+
32+
func (h listenerConnectionHandler) handleUnconnected(b []byte, addr net.Addr) error {
2533
switch b[0] {
2634
case message.IDUnconnectedPing, message.IDUnconnectedPingOpenConnections:
27-
return handleUnconnectedPing(h.l, b[1:], addr)
35+
return h.handleUnconnectedPing(b[1:], addr)
2836
case message.IDOpenConnectionRequest1:
29-
return handleOpenConnectionRequest1(h.l, b[1:], addr)
37+
return h.handleOpenConnectionRequest1(b[1:], addr)
3038
case message.IDOpenConnectionRequest2:
31-
return handleOpenConnectionRequest2(h.l, b[1:], addr)
39+
return h.handleOpenConnectionRequest2(b[1:], addr)
3240
}
3341
if b[0]&bitFlagDatagram != 0 {
3442
// In some cases, the client will keep trying to send datagrams
@@ -39,14 +47,14 @@ func (h *listenerConnectionHandler) handleUnconnected(b []byte, addr net.Addr) e
3947
return fmt.Errorf("unknown packet received (len=%v): %x", len(b), b)
4048
}
4149

42-
func (h *listenerConnectionHandler) handle(conn *Conn, b []byte) (handled bool, err error) {
50+
func (h listenerConnectionHandler) handle(conn *Conn, b []byte) (handled bool, err error) {
4351
switch b[0] {
4452
case message.IDConnectionRequest:
45-
return true, handleConnectionRequest(conn, b[1:])
53+
return true, h.handleConnectionRequest(conn, b[1:])
4654
case message.IDConnectionRequestAccepted:
4755
return true, errUnexpectedCRA
4856
case message.IDNewIncomingConnection:
49-
return true, handleNewIncomingConnection(conn)
57+
return true, h.handleNewIncomingConnection(conn)
5058
case message.IDConnectedPing:
5159
return true, handleConnectedPing(conn, b[1:])
5260
case message.IDConnectedPong:
@@ -62,62 +70,54 @@ func (h *listenerConnectionHandler) handle(conn *Conn, b []byte) (handled bool,
6270
}
6371
}
6472

65-
func (h *listenerConnectionHandler) limitsEnabled() bool {
66-
return true
67-
}
68-
69-
func (h *listenerConnectionHandler) close(conn *Conn) {
70-
h.l.connections.Delete(resolve(conn.raddr))
71-
}
72-
7373
// handleUnconnectedPing handles an unconnected ping packet stored in buffer b,
7474
// coming from an address.
75-
func handleUnconnectedPing(listener *Listener, b []byte, addr net.Addr) error {
75+
func (h listenerConnectionHandler) handleUnconnectedPing(b []byte, addr net.Addr) error {
7676
pk := &message.UnconnectedPing{}
7777
if err := pk.UnmarshalBinary(b); err != nil {
7878
return fmt.Errorf("read UNCONNECTED_PING: %w", err)
7979
}
80-
data, _ := (&message.UnconnectedPong{ServerGUID: listener.id, SendTimestamp: pk.SendTimestamp, Data: *listener.pongData.Load()}).MarshalBinary()
81-
_, err := listener.conn.WriteTo(data, addr)
80+
data, _ := (&message.UnconnectedPong{ServerGUID: h.l.id, SendTimestamp: pk.SendTimestamp, Data: *h.l.pongData.Load()}).MarshalBinary()
81+
_, err := h.l.conn.WriteTo(data, addr)
8282
return err
8383
}
8484

8585
// handleOpenConnectionRequest1 handles an open connection request 1 packet
8686
// stored in buffer b, coming from an address.
87-
func handleOpenConnectionRequest1(listener *Listener, b []byte, addr net.Addr) error {
87+
func (h listenerConnectionHandler) handleOpenConnectionRequest1(b []byte, addr net.Addr) error {
8888
pk := &message.OpenConnectionRequest1{}
8989
if err := pk.UnmarshalBinary(b); err != nil {
9090
return fmt.Errorf("read OPEN_CONNECTION_REQUEST_1: %w", err)
9191
}
9292
mtuSize := min(pk.MaximumSizeNotDropped, maxMTUSize)
9393

9494
if pk.Protocol != protocolVersion {
95-
data, _ := (&message.IncompatibleProtocolVersion{ServerGUID: listener.id, ServerProtocol: protocolVersion}).MarshalBinary()
96-
_, _ = listener.conn.WriteTo(data, addr)
95+
data, _ := (&message.IncompatibleProtocolVersion{ServerGUID: h.l.id, ServerProtocol: protocolVersion}).MarshalBinary()
96+
_, _ = h.l.conn.WriteTo(data, addr)
9797
return fmt.Errorf("handle OPEN_CONNECTION_REQUEST_1: incompatible protocol version %v (listener protocol = %v)", pk.Protocol, protocolVersion)
9898
}
9999

100-
data, _ := (&message.OpenConnectionReply1{ServerGUID: listener.id, Secure: false, ServerPreferredMTUSize: mtuSize}).MarshalBinary()
101-
_, err := listener.conn.WriteTo(data, addr)
100+
data, _ := (&message.OpenConnectionReply1{ServerGUID: h.l.id, Secure: false, ServerPreferredMTUSize: mtuSize}).MarshalBinary()
101+
_, err := h.l.conn.WriteTo(data, addr)
102102
return err
103103
}
104104

105105
// handleOpenConnectionRequest2 handles an open connection request 2 packet
106106
// stored in buffer b, coming from an address.
107-
func handleOpenConnectionRequest2(listener *Listener, b []byte, addr net.Addr) error {
107+
func (h listenerConnectionHandler) handleOpenConnectionRequest2(b []byte, addr net.Addr) error {
108108
pk := &message.OpenConnectionRequest2{}
109109
if err := pk.UnmarshalBinary(b); err != nil {
110110
return fmt.Errorf("read OPEN_CONNECTION_REQUEST_2: %w", err)
111111
}
112112
mtuSize := min(pk.ClientPreferredMTUSize, maxMTUSize)
113113

114-
data, _ := (&message.OpenConnectionReply2{ServerGUID: listener.id, ClientAddress: resolve(addr), MTUSize: mtuSize}).MarshalBinary()
115-
if _, err := listener.conn.WriteTo(data, addr); err != nil {
114+
data, _ := (&message.OpenConnectionReply2{ServerGUID: h.l.id, ClientAddress: resolve(addr), MTUSize: mtuSize}).MarshalBinary()
115+
if _, err := h.l.conn.WriteTo(data, addr); err != nil {
116116
return fmt.Errorf("send OPEN_CONNECTION_REPLY_2: %w", err)
117117
}
118118

119-
conn := newConn(listener.conn, addr, mtuSize, listener.h)
120-
listener.connections.Store(resolve(addr), conn)
119+
conn := newConn(h.l.conn, addr, mtuSize, h)
120+
h.l.connections.Store(resolve(addr), conn)
121121

122122
go func() {
123123
t := time.NewTimer(time.Second * 10)
@@ -126,8 +126,8 @@ func handleOpenConnectionRequest2(listener *Listener, b []byte, addr net.Addr) e
126126
case <-conn.connected:
127127
// Add the connection to the incoming channel so that a caller of
128128
// Accept() can receive it.
129-
listener.incoming <- conn
130-
case <-listener.closed:
129+
h.l.incoming <- conn
130+
case <-h.l.closed:
131131
_ = conn.Close()
132132
case <-t.C:
133133
// It took too long to complete this connection. We closed it and go
@@ -139,6 +139,28 @@ func handleOpenConnectionRequest2(listener *Listener, b []byte, addr net.Addr) e
139139
return nil
140140
}
141141

142+
// handleConnectionRequest handles a connection request packet inside of buffer
143+
// b. An error is returned if the packet was invalid.
144+
func (h listenerConnectionHandler) handleConnectionRequest(conn *Conn, b []byte) error {
145+
pk := &message.ConnectionRequest{}
146+
if err := pk.UnmarshalBinary(b); err != nil {
147+
return fmt.Errorf("read CONNECTION_REQUEST: %w", err)
148+
}
149+
return conn.send(&message.ConnectionRequestAccepted{ClientAddress: resolve(conn.raddr), RequestTimestamp: pk.RequestTimestamp, AcceptedTimestamp: timestamp()})
150+
}
151+
152+
// handleNewIncomingConnection handles an incoming connection packet from the
153+
// client, finalising the Conn.
154+
func (h listenerConnectionHandler) handleNewIncomingConnection(conn *Conn) error {
155+
select {
156+
case <-conn.connected:
157+
return errUnexpectedAdditionalNIC
158+
default:
159+
close(conn.connected)
160+
}
161+
return nil
162+
}
163+
142164
type dialerConnectionHandler struct{}
143165

144166
var (
@@ -147,12 +169,20 @@ var (
147169
errUnexpectedNIC = errors.New("unexpected NEW_INCOMING_CONNECTION packet")
148170
)
149171

150-
func (h *dialerConnectionHandler) handle(conn *Conn, b []byte) (handled bool, err error) {
172+
func (h dialerConnectionHandler) close(conn *Conn) {
173+
_ = conn.conn.Close()
174+
}
175+
176+
func (h dialerConnectionHandler) limitsEnabled() bool {
177+
return false
178+
}
179+
180+
func (h dialerConnectionHandler) handle(conn *Conn, b []byte) (handled bool, err error) {
151181
switch b[0] {
152182
case message.IDConnectionRequest:
153183
return true, errUnexpectedCR
154184
case message.IDConnectionRequestAccepted:
155-
return true, handleConnectionRequestAccepted(conn, b[1:])
185+
return true, h.handleConnectionRequestAccepted(conn, b[1:])
156186
case message.IDNewIncomingConnection:
157187
return true, errUnexpectedNIC
158188
case message.IDConnectedPing:
@@ -170,12 +200,22 @@ func (h *dialerConnectionHandler) handle(conn *Conn, b []byte) (handled bool, er
170200
}
171201
}
172202

173-
func (h *dialerConnectionHandler) close(conn *Conn) {
174-
_ = conn.conn.Close()
175-
}
176-
177-
func (h *dialerConnectionHandler) limitsEnabled() bool {
178-
return false
203+
// handleConnectionRequestAccepted handles a serialised connection request
204+
// accepted packet in b, and returns an error if not successful.
205+
func (h dialerConnectionHandler) handleConnectionRequestAccepted(conn *Conn, b []byte) error {
206+
pk := &message.ConnectionRequestAccepted{}
207+
if err := pk.UnmarshalBinary(b); err != nil {
208+
return fmt.Errorf("read CONNECTION_REQUEST_ACCEPTED: %w", err)
209+
}
210+
select {
211+
case <-conn.connected:
212+
return errUnexpectedAdditionalCRA
213+
default:
214+
// Make sure to send NewIncomingConnection before closing conn.connected.
215+
err := conn.send(&message.NewIncomingConnection{ServerAddress: resolve(conn.raddr), RequestTimestamp: pk.AcceptedTimestamp, AcceptedTimestamp: timestamp()})
216+
close(conn.connected)
217+
return err
218+
}
179219
}
180220

181221
// handleConnectedPing handles a connected ping packet inside of buffer b. An
@@ -204,43 +244,3 @@ func handleConnectedPong(b []byte) error {
204244
// unreliable and doesn't give a good idea of the connection quality.
205245
return nil
206246
}
207-
208-
// handleConnectionRequest handles a connection request packet inside of buffer
209-
// b. An error is returned if the packet was invalid.
210-
func handleConnectionRequest(conn *Conn, b []byte) error {
211-
pk := &message.ConnectionRequest{}
212-
if err := pk.UnmarshalBinary(b); err != nil {
213-
return fmt.Errorf("read CONNECTION_REQUEST: %w", err)
214-
}
215-
return conn.send(&message.ConnectionRequestAccepted{ClientAddress: resolve(conn.raddr), RequestTimestamp: pk.RequestTimestamp, AcceptedTimestamp: timestamp()})
216-
}
217-
218-
// handleConnectionRequestAccepted handles a serialised connection request
219-
// accepted packet in b, and returns an error if not successful.
220-
func handleConnectionRequestAccepted(conn *Conn, b []byte) error {
221-
pk := &message.ConnectionRequestAccepted{}
222-
if err := pk.UnmarshalBinary(b); err != nil {
223-
return fmt.Errorf("read CONNECTION_REQUEST_ACCEPTED: %w", err)
224-
}
225-
select {
226-
case <-conn.connected:
227-
return errUnexpectedAdditionalCRA
228-
default:
229-
// Make sure to send NewIncomingConnection before closing conn.connected.
230-
err := conn.send(&message.NewIncomingConnection{ServerAddress: resolve(conn.raddr), RequestTimestamp: pk.AcceptedTimestamp, AcceptedTimestamp: timestamp()})
231-
close(conn.connected)
232-
return err
233-
}
234-
}
235-
236-
// handleNewIncomingConnection handles an incoming connection packet from the
237-
// client, finalising the Conn.
238-
func handleNewIncomingConnection(conn *Conn) error {
239-
select {
240-
case <-conn.connected:
241-
return errUnexpectedAdditionalNIC
242-
default:
243-
close(conn.connected)
244-
}
245-
return nil
246-
}

internal/message/connection_request_accepted.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ func (pk *ConnectionRequestAccepted) UnmarshalBinary(data []byte) error {
2020
var offset int
2121
pk.ClientAddress, offset = addr(data)
2222
offset += 2 // Zero int16.
23-
for i := 0; i < 20; i++ {
23+
for i := range 20 {
2424
if len(data) < addrSize(data[offset:]) {
2525
return io.ErrUnexpectedEOF
2626
}

0 commit comments

Comments
 (0)