summaryrefslogtreecommitdiff
path: root/Impostor-dev/src/Impostor.Hazel/Udp/UdpClientConnection.cs
blob: 5125ebe8034522a2e4c8b6b08d73ba81fe34c3c0 (plain)
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
using System;
using System.Buffers;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Impostor.Api.Net.Messages;
using Microsoft.Extensions.ObjectPool;
using Serilog;

namespace Impostor.Hazel.Udp
{
    /// <summary>
    ///     Represents a client's connection to a server that uses the UDP protocol.
    /// </summary>
    /// <inheritdoc/>
    public sealed class UdpClientConnection : UdpConnection
    {
        private static readonly ILogger Logger = Log.ForContext<UdpClientConnection>();

        /// <summary>
        ///     The socket we're connected via.
        /// </summary>
        private readonly UdpClient _socket;

        private readonly Timer _reliablePacketTimer;
        private readonly SemaphoreSlim _connectWaitLock;
        private Task _listenTask;

        /// <summary>
        ///     Creates a new UdpClientConnection.
        /// </summary>
        /// <param name="remoteEndPoint">A <see cref="NetworkEndPoint"/> to connect to.</param>
        public UdpClientConnection(IPEndPoint remoteEndPoint, ObjectPool<MessageReader> readerPool, IPMode ipMode = IPMode.IPv4) : base(null, readerPool)
        {
            EndPoint = remoteEndPoint;
            RemoteEndPoint = remoteEndPoint;
            IPMode = ipMode;

            _socket = new UdpClient
            {
                DontFragment = false
            };

            _reliablePacketTimer = new Timer(ManageReliablePacketsInternal, null, 100, Timeout.Infinite);
            _connectWaitLock = new SemaphoreSlim(1, 1);
        }

        ~UdpClientConnection()
        {
            Dispose(false);
        }

        private async void ManageReliablePacketsInternal(object state)
        {
            await ManageReliablePackets();

            try
            {
                _reliablePacketTimer.Change(100, Timeout.Infinite);
            }
            catch
            {
                // ignored
            }
        }

        /// <inheritdoc />
        protected override ValueTask WriteBytesToConnection(byte[] bytes, int length)
        {
            return WriteBytesToConnectionReal(bytes, length);
        }

        private async ValueTask WriteBytesToConnectionReal(byte[] bytes, int length)
        {
            try
            {
                await _socket.SendAsync(bytes, length);
            }
            catch (NullReferenceException) { }
            catch (ObjectDisposedException)
            {
                // Already disposed and disconnected...
            }
            catch (SocketException ex)
            {
                await DisconnectInternal(HazelInternalErrors.SocketExceptionSend, "Could not send data as a SocketException occurred: " + ex.Message);
            }
        }

        /// <inheritdoc />
        public override async ValueTask ConnectAsync(byte[] bytes = null)
        {
            State = ConnectionState.Connecting;

            try
            {
                _socket.Connect(RemoteEndPoint);
            }
            catch (SocketException e)
            {
                State = ConnectionState.NotConnected;
                throw new HazelException("A SocketException occurred while binding to the port.", e);
            }

            try
            {
                _listenTask = Task.Factory.StartNew(ListenAsync, TaskCreationOptions.LongRunning);
            }
            catch (ObjectDisposedException)
            {
                // If the socket's been disposed then we can just end there but make sure we're in NotConnected state.
                // If we end up here I'm really lost...
                State = ConnectionState.NotConnected;
                return;
            }
            catch (SocketException e)
            {
                Dispose();
                throw new HazelException("A SocketException occurred while initiating a receive operation.", e);
            }

            // Write bytes to the server to tell it hi (and to punch a hole in our NAT, if present)
            // When acknowledged set the state to connected
            await SendHello(bytes, () =>
            {
                State = ConnectionState.Connected;
                InitializeKeepAliveTimer();
            });

            await _connectWaitLock.WaitAsync(TimeSpan.FromSeconds(10));
        }

        private async Task ListenAsync()
        {
            // Start packet handler.
            await StartAsync();

            // Listen.
            while (State != ConnectionState.NotConnected)
            {
                UdpReceiveResult data;

                try
                {
                    data = await _socket.ReceiveAsync();
                }
                catch (SocketException e)
                {
                    await DisconnectInternal(HazelInternalErrors.SocketExceptionReceive, "Socket exception while reading data: " + e.Message);
                    return;
                }
                catch (Exception)
                {
                    return;
                }

                if (data.Buffer.Length == 0)
                {
                    await DisconnectInternal(HazelInternalErrors.ReceivedZeroBytes, "Received 0 bytes");
                    return;
                }

                // Write to client.
                await Pipeline.Writer.WriteAsync(data.Buffer);
            }
        }

        protected override void SetState(ConnectionState state)
        {
            if (state == ConnectionState.Connected)
            {
                _connectWaitLock.Release();
            }
        }

        /// <summary>
        ///     Sends a disconnect message to the end point.
        ///     You may include optional disconnect data. The SendOption must be unreliable.
        /// </summary>
        protected override async ValueTask<bool> SendDisconnect(MessageWriter data = null)
        {
            lock (this)
            {
                if (_state == ConnectionState.NotConnected) return false;
                _state = ConnectionState.NotConnected;
            }

            var bytes = EmptyDisconnectBytes;
            if (data != null && data.Length > 0)
            {
                if (data.SendOption != MessageType.Unreliable)
                {
                    throw new ArgumentException("Disconnect messages can only be unreliable.");
                }

                bytes = data.ToByteArray(true);
                bytes[0] = (byte)UdpSendOption.Disconnect;
            }

            try
            {
                await _socket.SendAsync(bytes, bytes.Length, RemoteEndPoint);
            }
            catch { }

            return true;
        }

        /// <inheritdoc />
        protected override void Dispose(bool disposing)
        {
            State = ConnectionState.NotConnected;

            try { _socket.Close(); } catch { }
            try { _socket.Dispose(); } catch { }

            _reliablePacketTimer.Dispose();
            _connectWaitLock.Dispose();

            base.Dispose(disposing);
        }
    }
}