forked from MarcFletcher/NetworkComms.Net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Packet.cs
321 lines (280 loc) · 15.3 KB
/
Packet.cs
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using NetworkCommsDotNet.DPSBase;
using System.IO;
using System.Reflection;
using NetworkCommsDotNet.Tools;
namespace NetworkCommsDotNet
{
/// <summary>
/// Interface for defining Application Layer Protocol packets
/// </summary>
public interface IPacket
{
/// <summary>
/// The packet header for this packet
/// </summary>
PacketHeader PacketHeader { get; }
/// <summary>
/// The payload data stream
/// </summary>
StreamTools.StreamSendWrapper PacketData { get; }
/// <summary>
/// Returns the serialised bytes of the packet header appended by the serialised header size. This is required to
/// rebuild the header on receive.
/// </summary>
/// <returns>The serialised header as byte[]</returns>
byte[] SerialiseHeader(SendReceiveOptions options);
/// <summary>
/// Dispose of internal packet resources
/// </summary>
void Dispose();
}
/// <summary>
/// Wrapper for <see cref="PacketHeader"/> and packetData.
/// </summary>
public class Packet : IDisposable, IPacket, IExplicitlySerialize
{
/// <summary>
/// If we serialise a whole packet we include the packet header
/// </summary>
PacketHeader _packetHeader;
/// <summary>
/// And the payload object as byte[]. We cannot use type T here because we do not know the type of T
/// on deserialisation until we have the nested packet header.
/// </summary>
internal byte[] _payloadObjectBytes;
internal int _payloadSize;
StreamTools.StreamSendWrapper payloadStream;
/// <summary>
/// Parameterless constructor for deserialisation
/// </summary>
private Packet()
{
}
/// <summary>
/// Create a new packet
/// </summary>
/// <param name="sendingPacketTypeStr">The sending packet type</param>
/// <param name="payloadObject">The object to be sent</param>
/// <param name="options">The <see cref="SendReceiveOptions"/> to be used to create this packet</param>
public Packet(string sendingPacketTypeStr, object payloadObject, SendReceiveOptions options)
{
Constructor(sendingPacketTypeStr, null, payloadObject, options, false);
}
/// <summary>
/// Create a new packet
/// </summary>
/// <param name="sendingPacketTypeStr">The sending packet type</param>
/// <param name="requestReturnPacketTypeStr">The expected return packet type</param>
/// <param name="payloadObject">The object to be sent</param>
/// <param name="options">The <see cref="SendReceiveOptions"/> to be used to create this packet</param>
public Packet(string sendingPacketTypeStr, string requestReturnPacketTypeStr, object payloadObject, SendReceiveOptions options)
{
Constructor(sendingPacketTypeStr, requestReturnPacketTypeStr, payloadObject, options, false);
}
/// <summary>
/// Private constructor used for nesting packets
/// </summary>
/// <param name="sendingPacketTypeStr"></param>
/// <param name="requestReturnPacketTypeStr"></param>
/// <param name="payloadObject"></param>
/// <param name="options"></param>
/// <param name="isNested"></param>
private Packet(string sendingPacketTypeStr, string requestReturnPacketTypeStr, object payloadObject, SendReceiveOptions options, bool isNested)
{
Constructor(sendingPacketTypeStr, requestReturnPacketTypeStr, payloadObject, options, isNested);
}
private void Constructor<payloadObjectType>(string sendingPacketTypeStr, string requestReturnPacketTypeStr, payloadObjectType payloadObject, SendReceiveOptions options, bool isNested)
{
if (sendingPacketTypeStr == null || sendingPacketTypeStr == "") throw new ArgumentNullException("sendingPacketTypeStr", "The provided string can not be null or zero length.");
if (options == null) throw new ArgumentNullException("options", "The provided SendReceiveOptions cannot be null.");
if (options.DataSerializer == null) throw new ArgumentNullException("options", "The provided SendReceiveOptions.DataSerializer cannot be null. Consider using NullSerializer instead.");
//Check for security critical data processors
//There may be performance issues here
bool containsSecurityCritialDataProcessors = false;
if (!options.Options.ContainsKey("UseNestedPacketType") && //We only need to perform this check if we are not already using a nested packet
!isNested) //We do not perform this check within a nested packet
{
foreach (DataProcessor processor in options.DataProcessors)
{
if (processor.IsSecurityCritical)
{
containsSecurityCritialDataProcessors = true;
break;
}
}
}
//By default the object to serialise will be the payloadObject
object objectToSerialise = payloadObject;
bool objectToSerialiseIsNull = false;
//We only replace the null with an empty stream if this is either in the nested packet
//or we will not be nesting
if (objectToSerialise == null &&
((!options.Options.ContainsKey("UseNestedPacketType") &&
!containsSecurityCritialDataProcessors) || isNested))
{
#if NETFX_CORE
var emptyStream = new MemoryStream(new byte[0], 0, 0, false);
#else
var emptyStream = new MemoryStream(new byte[0], 0, 0, false, true);
#endif
//If the sending object is null we set objectToSerialiseIsNull and create a zero length StreamSendWrapper
//The zero length StreamSendWrapper can then be passed to any data serializers
objectToSerialiseIsNull = true;
objectToSerialise = new StreamTools.StreamSendWrapper(new StreamTools.ThreadSafeStream(emptyStream, true));
}
//If we need to nest this packet
if ((containsSecurityCritialDataProcessors || options.Options.ContainsKey("UseNestedPacketType")) && !isNested)
{
//We set the objectToSerialise to a nested packet
objectToSerialise = new Packet(sendingPacketTypeStr, requestReturnPacketTypeStr, payloadObject, options, true);
}
else if (isNested)
{
//Serialise the payload object into byte[]
//We do not use any data processors at this stage as the object will be processed again one level higher.
#if NETFX_CORE
_payloadObjectBytes = options.DataSerializer.SerialiseDataObject(payloadObject).ThreadSafeStream.ToArray();
_payloadSize = _payloadObjectBytes.Length;
#else
NetworkCommsDotNet.Tools.StreamTools.ThreadSafeStream tempStream = options.DataSerializer.SerialiseDataObject(objectToSerialise).ThreadSafeStream;
_payloadObjectBytes = tempStream.GetBuffer();
_payloadSize = (int)tempStream.Length;
#endif
//Set the packet header
//THe nulls represent internal SendReceiveOptions and no checksum
this._packetHeader = new PacketHeader(sendingPacketTypeStr, _payloadSize, null, requestReturnPacketTypeStr, null);
//Set the deserialiser information in the nested packet header, excluding data processors
this._packetHeader.SetOption(PacketHeaderLongItems.SerializerProcessors, DPSManager.CreateSerializerDataProcessorIdentifier(options.DataSerializer, null));
}
//If we are at the top level packet we can finish off the serialisation
if (!isNested)
{
//Set the payload stream data.
if (objectToSerialiseIsNull && options.DataProcessors.Count == 0)
//Only if there are no data processors can we use a zero length array for nulls
//This ensures that should there be any required padding we can include it
this.payloadStream = (StreamTools.StreamSendWrapper)objectToSerialise;
else
{
if (objectToSerialise is Packet)
//We have to use the internal explicit serializer for nested packets (the nested data is already byte[])
this.payloadStream = NetworkComms.InternalFixedSendReceiveOptions.DataSerializer.SerialiseDataObject(objectToSerialise, options.DataProcessors, options.Options);
else
this.payloadStream = options.DataSerializer.SerialiseDataObject(objectToSerialise, options.DataProcessors, options.Options);
}
//We only calculate the checkSum if we are going to use it
string hashStr = null;
if (NetworkComms.EnablePacketCheckSumValidation)
hashStr = StreamTools.MD5(payloadStream.ThreadSafeStream.ToArray(payloadStream.Start, payloadStream.Length));
//Choose the sending and receiving packet type depending on if it is being used with a nested packet
string _sendingPacketTypeStr;
string _requestReturnPacketTypeStr = null;
if (containsSecurityCritialDataProcessors || options.Options.ContainsKey("UseNestedPacketType"))
_sendingPacketTypeStr = Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.NestedPacket);
else
{
_sendingPacketTypeStr = sendingPacketTypeStr;
_requestReturnPacketTypeStr = requestReturnPacketTypeStr;
}
this._packetHeader = new PacketHeader(_sendingPacketTypeStr, payloadStream.Length, options, _requestReturnPacketTypeStr, hashStr);
//Add an identifier specifying the serialisers and processors we have used
if (objectToSerialise is Packet)
this._packetHeader.SetOption(PacketHeaderLongItems.SerializerProcessors, DPSManager.CreateSerializerDataProcessorIdentifier(NetworkComms.InternalFixedSendReceiveOptions.DataSerializer, options.DataProcessors));
else
this._packetHeader.SetOption(PacketHeaderLongItems.SerializerProcessors, DPSManager.CreateSerializerDataProcessorIdentifier(options.DataSerializer, options.DataProcessors));
}
//Set the null data header section if required
if (objectToSerialiseIsNull &&
((!containsSecurityCritialDataProcessors && !options.Options.ContainsKey("UseNestedPacketType")) || isNested))
this._packetHeader.SetOption(PacketHeaderStringItems.NullDataSection, "");
if (NetworkComms.LoggingEnabled)
{
if (isNested)
NetworkComms.Logger.Trace(" ... created nested packet of type " + sendingPacketTypeStr);
else
NetworkComms.Logger.Trace(" ... created packet of type " + sendingPacketTypeStr + ". PacketObject data size is " + payloadStream.Length.ToString() + " bytes");
}
}
/// <inheritdoc />
public PacketHeader PacketHeader
{
get { return _packetHeader; }
}
/// <inheritdoc />
public StreamTools.StreamSendWrapper PacketData
{
get { return payloadStream; }
}
/// <inheritdoc />
public byte[] SerialiseHeader(SendReceiveOptions options)
{
if (options == null) throw new ArgumentNullException("options", "Provided SendReceiveOptions cannot be null.");
//We need to start of by serialising the header
byte[] serialisedHeader;
using (StreamTools.StreamSendWrapper sendWrapper = options.DataSerializer.SerialiseDataObject(_packetHeader, options.DataProcessors, null))
serialisedHeader = sendWrapper.ThreadSafeStream.ToArray(1);
if (serialisedHeader.Length - 1 > byte.MaxValue)
throw new SerialisationException("Unable to send packet as header size is larger than Byte.MaxValue. Try reducing the length of provided packetTypeStr or turning off checkSum validation.");
//The first byte now specifies the header size (allows for variable header size)
serialisedHeader[0] = (byte)(serialisedHeader.Length - 1);
if (serialisedHeader == null)
throw new SerialisationException("Serialised header bytes should never be null.");
return serialisedHeader;
}
/// <inheritdoc />
public void Dispose()
{
payloadStream.Dispose();
}
#region IExplicitlySerialize Members
/// <inheritdoc />
public void Serialize(Stream outputStream)
{
_packetHeader.Serialize(outputStream);
outputStream.Write(BitConverter.GetBytes(_payloadSize), 0, sizeof(int));
outputStream.Write(_payloadObjectBytes, 0, _payloadSize);
}
/// <inheritdoc />
public void Deserialize(Stream inputStream)
{
PacketHeader.Deserialize(inputStream, out _packetHeader);
byte[] payloadLengthData = new byte[sizeof(int)];
inputStream.Read(payloadLengthData, 0, sizeof(int));
_payloadSize = BitConverter.ToInt32(payloadLengthData, 0);
_payloadObjectBytes = new byte[_payloadSize];
inputStream.Read(_payloadObjectBytes, 0, _payloadSize);
}
#endregion
/// <summary>
/// Deserializes from a memory stream to a <see cref="Packet"/> object
/// </summary>
/// <param name="inputStream">The memory stream containing the serialized <see cref="Packet"/></param>
/// <param name="result">The deserialized <see cref="Packet"/></param>
public static void Deserialize(Stream inputStream, out Packet result)
{
result = new Packet();
result.Deserialize(inputStream);
}
}
}