forked from oznetmaster/SSharpWebSocketLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ext.cs
2268 lines (1993 loc) · 62.7 KB
/
Ext.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region License
/*
* Ext.cs
*
* Some parts of this code are derived from Mono (http://www.mono-project.com):
* - GetStatusDescription is derived from HttpListenerResponse.cs (System.Net)
* - IsPredefinedScheme is derived from Uri.cs (System)
* - MaybeUri is derived from SUri.cs (System)
*
* The MIT License
*
* Copyright (c) 2001 Garrett Rooney
* Copyright (c) 2003 Ian MacLean
* Copyright (c) 2003 Ben Maurer
* Copyright (c) 2003, 2005, 2009 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2009 Stephane Delcroix
* Copyright (c) 2010-2016 sta.blockhead
* Copyright © 2016 Nivloc Enterprises Ltd
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <[email protected]>
* - Nikola Kovacevic <[email protected]>
* - Chris Swiedler
*/
#endregion
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
#if SSHARP
using Crestron.SimplSharp;
using Crestron.SimplSharp.CrestronIO;
using Crestron.SimplSharp.CrestronIO.Compression;
using Crestron.SimplSharp.Cryptography.X509Certificates;
using TcpClient = Crestron.SimplSharp.CrestronSockets.CrestronServerSocket;
using SSMono.Net;
using CookieCollection = WebSocketSharp.Net.CookieCollection;
using SSMono.Web;
using HttpUtility = SSMono.Web.HttpUtility;
using AsyncCallback = Crestron.SimplSharp.CrestronIO.AsyncCallback;
#else
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
#endif
#if NETCF
using OpenNETCF;
#endif
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
#if !CLIENT
using WebSocketSharp.Server;
#endif
using System.Globalization;
namespace WebSocketSharp
{
/// <summary>
/// Provides a set of static methods for websocket-sharp.
/// </summary>
public static class Ext
{
#region Private Fields
private static readonly byte[] _last = new byte[] {0x00};
private static readonly int _retry = 5;
private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";
#endregion
#region Private Methods
private static byte[] compress (this byte[] data)
{
#if NETCF
if (data.Length == 0)
#else
if (data.LongLength == 0)
#endif
//return new byte[] { 0x00, 0x00, 0x00, 0xff, 0xff };
return data;
using (var input = new MemoryStream (data))
return input.compressToArray ();
}
private static MemoryStream compress (this Stream stream)
{
var output = new MemoryStream ();
if (stream.Length == 0)
return output;
stream.Position = 0;
using (var ds = new DeflateStream (output, CompressionMode.Compress, true))
{
stream.CopyTo (ds, 1024);
ds.Close (); // BFINAL set to 1.
output.Write (_last, 0, 1);
output.Position = 0;
return output;
}
}
private static byte[] compressToArray (this Stream stream)
{
using (var output = stream.compress ())
{
output.Close ();
return output.ToArray ();
}
}
private static byte[] decompress (this byte[] data)
{
#if NETCF
if (data.Length == 0)
#else
if (data.LongLength == 0)
#endif
return data;
using (var input = new MemoryStream (data))
return input.decompressToArray ();
}
private static MemoryStream decompress (this Stream stream)
{
var output = new MemoryStream ();
if (stream.Length == 0)
return output;
stream.Position = 0;
using (var ds = new DeflateStream (stream, CompressionMode.Decompress, true))
{
ds.CopyTo (output, 1024);
output.Position = 0;
return output;
}
}
private static byte[] decompressToArray (this Stream stream)
{
using (var output = stream.decompress ())
{
output.Close ();
return output.ToArray ();
}
}
private static void times (this ulong n, Action action)
{
for (ulong i = 0; i < n; i++)
action ();
}
private static string toResponseStringVersion0 (this Cookie cookie)
{
var output = new StringBuilder (64);
output.AppendFormat ("{0}={1}", cookie.Name, cookie.Value);
if (cookie.Expires != DateTime.MinValue)
{
output.AppendFormat ("; Expires={0}",
cookie.Expires.ToUniversalTime ().ToString ("ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", CultureInfo.CreateSpecificCulture ("en-US")));
}
if (!cookie.Path.IsNullOrEmpty ())
output.AppendFormat ("; Path={0}", cookie.Path);
if (!cookie.Domain.IsNullOrEmpty ())
output.AppendFormat ("; Domain={0}", cookie.Domain);
if (cookie.Secure)
output.Append ("; Secure");
if (cookie.HttpOnly)
output.Append ("; HttpOnly");
return output.ToString ();
}
private static string toResponseStringVersion1 (this Cookie cookie)
{
var output = new StringBuilder (64);
output.AppendFormat ("{0}={1}; Version={2}", cookie.Name, cookie.Value, cookie.Version);
if (cookie.Expires != DateTime.MinValue)
output.AppendFormat ("; Max-Age={0}", cookie.MaxAge ());
if (!cookie.Path.IsNullOrEmpty ())
output.AppendFormat ("; Path={0}", cookie.Path);
if (!cookie.Domain.IsNullOrEmpty ())
output.AppendFormat ("; Domain={0}", cookie.Domain);
if (!cookie.Port.IsNullOrEmpty ())
{
if (cookie.Port == "\"\"")
output.Append ("; Port");
else
output.AppendFormat ("; Port={0}", cookie.Port);
}
if (!cookie.Comment.IsNullOrEmpty ())
output.AppendFormat ("; Comment={0}", cookie.Comment.UrlEncode ());
if (cookie.CommentUri != null)
{
var url = cookie.CommentUri.OriginalString;
output.AppendFormat ("; CommentURL={0}", url.IsToken () ? url : url.Quote ());
}
if (cookie.Discard)
output.Append ("; Discard");
if (cookie.Secure)
output.Append ("; Secure");
return output.ToString ();
}
#endregion
#region Internal Methods
internal static byte[] Append (this ushort code, string reason)
{
var ret = code.InternalToByteArray (ByteOrder.Big);
if (reason != null && reason.Length > 0)
{
var buff = new List<byte> (ret);
buff.AddRange (Encoding.UTF8.GetBytes (reason));
ret = buff.ToArray ();
}
return ret;
}
#if !CLIENT
internal static string CheckIfAvailable (this ServerState state, bool ready, bool start, bool shutting)
{
return (!ready && (state == ServerState.Ready || state == ServerState.Stop)) || (!start && state == ServerState.Start)
|| (!shutting && state == ServerState.ShuttingDown) ? "This operation isn't available in: " + state.ToString ().ToLower () : null;
}
#endif
internal static string CheckIfAvailable (this WebSocketState state, bool connecting, bool open, bool closing, bool closed)
{
return (!connecting && state == WebSocketState.Connecting) || (!open && state == WebSocketState.Open) || (!closing && state == WebSocketState.Closing)
|| (!closed && state == WebSocketState.Closed) ? "This operation isn't available in: " + state.ToString ().ToLower () : null;
}
internal static string CheckIfValidProtocols (this string[] protocols)
{
return protocols.Contains (protocol => protocol == null || protocol.Length == 0 || !protocol.IsToken ())
? "Contains an invalid value." : protocols.ContainsTwice () ? "Contains a value twice." : null;
}
internal static string CheckIfValidServicePath (this string path)
{
return path == null || path.Length == 0
? "'path' is null or empty."
: path[0] != '/'
? "'path' isn't an absolute path."
: path.IndexOfAny (new[] {'?', '#'}) > -1 ? "'path' includes either or both query and fragment components." : null;
}
internal static string CheckIfValidSessionID (this string id)
{
return id == null || id.Length == 0 ? "'id' is null or empty." : null;
}
internal static string CheckIfValidWaitTime (this TimeSpan time)
{
return time <= TimeSpan.Zero ? "A wait time is zero or less." : null;
}
internal static bool CheckWaitTime (this TimeSpan time, out string message)
{
message = null;
if (time <= TimeSpan.Zero)
{
message = "A wait time is zero or less.";
return false;
}
return true;
}
#if !CLIENT
internal static void Close (this HttpListenerResponse response, HttpStatusCode code)
{
response.StatusCode = (int)code;
response.OutputStream.Close ();
}
internal static void CloseWithAuthChallenge (this HttpListenerResponse response, string challenge)
{
response.Headers.InternalSet ("WWW-Authenticate", challenge, true);
response.Close (HttpStatusCode.Unauthorized);
}
#endif
internal static byte[] Compress (this byte[] data, CompressionMethod method)
{
return method == CompressionMethod.Deflate ? data.compress () : data;
}
internal static Stream Compress (this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate ? stream.compress () : stream;
}
internal static byte[] CompressToArray (this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate ? stream.compressToArray () : stream.ToByteArray ();
}
internal static bool Contains<T> (this IEnumerable<T> source, Func<T, bool> condition)
{
foreach (T elm in source)
{
if (condition (elm))
return true;
}
return false;
}
internal static bool ContainsTwice (this string[] values)
{
var len = values.Length;
Func<int, bool> contains = null;
contains = idx =>
{
if (idx < len - 1)
{
for (var i = idx + 1; i < len; i++)
{
if (values[i] == values[idx])
return true;
}
return contains (++idx);
}
return false;
};
return contains (0);
}
internal static T[] Copy<T> (this T[] source, int length)
{
var dest = new T[length];
Array.Copy (source, 0, dest, 0, length);
return dest;
}
internal static T[] Copy<T> (this T[] source, long length)
{
var dest = new T[length];
#if NETCF
Array.Copy (source, 0, dest, 0, (int)length);
#else
Array.Copy (source, 0, dest, 0, length);
#endif
return dest;
}
internal static void CopyTo (this Stream source, Stream destination, int bufferLength)
{
var buff = new byte[bufferLength];
var nread = 0;
while ((nread = source.Read (buff, 0, bufferLength)) > 0)
destination.Write (buff, 0, nread);
}
internal static void CopyToAsync (this Stream source, Stream destination, int bufferLength, Action completed, Action<Exception> error)
{
var buff = new byte[bufferLength];
AsyncCallback callback = null;
callback = ar =>
{
try
{
var nread = source.EndRead (ar);
if (nread <= 0)
{
if (completed != null)
completed ();
return;
}
destination.Write (buff, 0, nread);
source.BeginRead (buff, 0, bufferLength, callback, null);
}
catch (Exception ex)
{
if (error != null)
error (ex);
}
};
try
{
source.BeginRead (buff, 0, bufferLength, callback, null);
}
catch (Exception ex)
{
if (error != null)
error (ex);
}
}
internal static byte[] Decompress (this byte[] data, CompressionMethod method)
{
return method == CompressionMethod.Deflate ? data.decompress () : data;
}
internal static Stream Decompress (this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate ? stream.decompress () : stream;
}
internal static byte[] DecompressToArray (this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate ? stream.decompressToArray () : stream.ToByteArray ();
}
/// <summary>
/// Determines whether the specified <see cref="int"/> equals the specified <see cref="char"/>,
/// and invokes the specified <c>Action<int></c> delegate at the same time.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> equals <paramref name="c"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// An <see cref="int"/> to compare.
/// </param>
/// <param name="c">
/// A <see cref="char"/> to compare.
/// </param>
/// <param name="action">
/// An <c>Action<int></c> delegate that references the method(s) called
/// at the same time as comparing. An <see cref="int"/> parameter to pass to
/// the method(s) is <paramref name="value"/>.
/// </param>
internal static bool EqualsWith (this int value, char c, Action<int> action)
{
action (value);
return value == c - 0;
}
/// <summary>
/// Gets the absolute path from the specified <see cref="Uri"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the absolute path if it's successfully found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="uri">
/// A <see cref="Uri"/> that represents the URI to get the absolute path from.
/// </param>
internal static string GetAbsolutePath (this Uri uri)
{
if (uri.IsAbsoluteUri)
return uri.AbsolutePath;
var original = uri.OriginalString;
if (original[0] != '/')
return null;
var idx = original.IndexOfAny (new[] {'?', '#'});
return idx > 0 ? original.Substring (0, idx) : original;
}
internal static string GetMessage (this CloseStatusCode code)
{
return code == CloseStatusCode.ProtocolError
? "A WebSocket protocol error has occurred."
: code == CloseStatusCode.UnsupportedData
? "An incorrect data has been received."
: code == CloseStatusCode.Abnormal
? "An exception has occurred."
: code == CloseStatusCode.InvalidData
? "An inconsistent data has been received."
: code == CloseStatusCode.PolicyViolation
? "A policy violation has occurred."
: code == CloseStatusCode.TooBig
? "A too big data has been received."
: code == CloseStatusCode.MandatoryExtension
? "WebSocket client didn't receive expected extension(s)."
: code == CloseStatusCode.ServerError
? "WebSocket server got an internal error."
: code == CloseStatusCode.TlsHandshakeFailure ? "An error has occurred durreng a TLS handshake." : String.Empty;
}
/// <summary>
/// Gets the name from the specified <see cref="string"/> that contains a pair of name and
/// value separated by a separator character.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the name if any; otherwise, <c>null</c>.
/// </returns>
/// <param name="nameAndValue">
/// A <see cref="string"/> that contains a pair of name and value separated by a separator
/// character.
/// </param>
/// <param name="separator">
/// A <see cref="char"/> that represents the separator character.
/// </param>
internal static string GetName (this string nameAndValue, char separator)
{
var idx = nameAndValue.IndexOf (separator);
return idx > 0 ? nameAndValue.Substring (0, idx).Trim () : null;
}
/// <summary>
/// Gets the value from the specified <see cref="string"/> that contains a pair of name and
/// value separated by a separator character.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the value if any; otherwise, <c>null</c>.
/// </returns>
/// <param name="nameAndValue">
/// A <see cref="string"/> that contains a pair of name and value separated by a separator
/// character.
/// </param>
/// <param name="separator">
/// A <see cref="char"/> that represents the separator character.
/// </param>
internal static string GetValue (this string nameAndValue, char separator)
{
var idx = nameAndValue.IndexOf (separator);
return idx > -1 && idx < nameAndValue.Length - 1 ? nameAndValue.Substring (idx + 1).Trim () : null;
}
internal static string GetValue (this string nameAndValue, char separator, bool unquote)
{
var idx = nameAndValue.IndexOf (separator);
if (idx < 0 || idx == nameAndValue.Length - 1)
return null;
var val = nameAndValue.Substring (idx + 1).Trim ();
return unquote ? val.Unquote () : val;
}
#if !CLIENT
internal static TcpListenerWebSocketContext GetWebSocketContext (this TcpClient tcpClient, string protocol, bool secure,
#if !NETCF || BCC || SSL
ServerSslConfiguration sslConfig,
#endif
Logger logger)
{
return new TcpListenerWebSocketContext (tcpClient, protocol, secure,
#if !NETCF || BCC || SSL
sslConfig,
#endif
logger);
}
#endif
internal static byte[] InternalToByteArray (this ushort value, ByteOrder order)
{
var bytes = BitConverter.GetBytes (value);
if (!order.IsHostOrder ())
Array.Reverse (bytes);
return bytes;
}
internal static byte[] InternalToByteArray (this ulong value, ByteOrder order)
{
var bytes = BitConverter.GetBytes (value);
if (!order.IsHostOrder ())
Array.Reverse (bytes);
return bytes;
}
internal static bool IsCompressionExtension (this string value, CompressionMethod method)
{
return value.StartsWith (method.ToExtensionString ());
}
internal static bool IsControl (this byte opcode)
{
return opcode > 0x7 && opcode < 0x10;
}
internal static bool IsControl (this Opcode opcode)
{
return opcode >= Opcode.Close;
}
internal static bool IsData (this byte opcode)
{
return opcode == 0x1 || opcode == 0x2;
}
internal static bool IsData (this Opcode opcode)
{
return opcode == Opcode.Text || opcode == Opcode.Binary;
}
internal static bool IsPortNumber (this int value)
{
return value > 0 && value < 65536;
}
internal static bool IsReserved (this ushort code)
{
return code == 1004
|| code == 1005
|| code == 1006
|| code == 1015;
}
internal static bool IsReserved (this CloseStatusCode code)
{
return code == CloseStatusCode.Undefined
|| code == CloseStatusCode.NoStatus
|| code == CloseStatusCode.Abnormal
|| code == CloseStatusCode.TlsHandshakeFailure;
}
internal static bool IsSupported (this byte opcode)
{
return Enum.IsDefined (typeof(Opcode), opcode);
}
internal static bool IsText (this string value)
{
var len = value.Length;
for (var i = 0; i < len; i++)
{
var c = value[i];
if (c < 0x20 && !"\r\n\t".Contains (c))
return false;
if (c == 0x7f)
return false;
if (c == '\n' && ++i < len)
{
c = value[i];
if (!" \t".Contains (c))
return false;
}
}
return true;
}
internal static bool IsToken (this string value)
{
foreach (var c in value)
{
if (c < 0x20 || c >= 0x7f || _tspecials.Contains (c))
return false;
}
return true;
}
internal static string Quote (this string value)
{
return String.Format ("\"{0}\"", value.Replace ("\"", "\\\""));
}
internal static byte[] ReadBytes (this Stream stream, int length)
{
var buff = new byte[length];
var offset = 0;
try
{
var nread = 0;
while (length > 0)
{
nread = stream.Read (buff, offset, length);
if (nread == 0)
break;
offset += nread;
length -= nread;
}
}
catch
{
}
return buff.SubArray (0, offset);
}
internal static byte[] ReadBytes (this Stream stream, long length, int bufferLength)
{
using (var dest = new MemoryStream ())
{
try
{
var buff = new byte[bufferLength];
var nread = 0;
while (length > 0)
{
if (length < bufferLength)
bufferLength = (int)length;
nread = stream.Read (buff, 0, bufferLength);
if (nread == 0)
break;
dest.Write (buff, 0, nread);
length -= nread;
}
}
catch
{
}
dest.Close ();
return dest.ToArray ();
}
}
internal static void ReadBytesAsync (this Stream stream, int length, Action<byte[]> completed, Action<Exception> error)
{
var buff = new byte[length];
var offset = 0;
var retry = 0;
AsyncCallback callback = null;
callback = ar =>
{
try
{
var nread = stream.EndRead (ar);
if (nread == 0 && retry < _retry)
{
retry++;
stream.BeginRead (buff, offset, length, callback, null);
return;
}
if (nread == 0 || nread == length)
{
if (completed != null)
completed (buff.SubArray (0, offset + nread));
return;
}
retry = 0;
offset += nread;
length -= nread;
stream.BeginRead (buff, offset, length, callback, null);
}
catch (Exception ex)
{
if (error != null)
error (ex);
}
};
try
{
stream.BeginRead (buff, offset, length, callback, null);
}
catch (Exception ex)
{
if (error != null)
error (ex);
}
}
internal static void ReadBytesAsync (this Stream stream, long length, int bufferLength, Action<byte[]> completed, Action<Exception> error)
{
var dest = new MemoryStream ();
var buff = new byte[bufferLength];
var retry = 0;
Action<long> read = null;
read = len =>
{
if (len < bufferLength)
bufferLength = (int)len;
stream.BeginRead (buff, 0, bufferLength, ar =>
{
try
{
var nread = stream.EndRead (ar);
if (nread > 0)
dest.Write (buff, 0, nread);
if (nread == 0 && retry < _retry)
{
retry++;
read (len);
return;
}
if (nread == 0 || nread == len)
{
if (completed != null)
{
dest.Close ();
completed (dest.ToArray ());
}
dest.Dispose ();
return;
}
retry = 0;
read (len - nread);
}
catch (Exception ex)
{
dest.Dispose ();
if (error != null)
error (ex);
}
}, null);
};
try
{
read (length);
}
catch (Exception ex)
{
dest.Dispose ();
if (error != null)
error (ex);
}
}
internal static string RemovePrefix (this string value, params string[] prefixes)
{
var idx = 0;
foreach (var prefix in prefixes)
{
if (value.StartsWith (prefix))
{
idx = prefix.Length;
break;
}
}
return idx > 0 ? value.Substring (idx) : value;
}
internal static T[] Reverse<T> (this T[] array)
{
var len = array.Length;
var reverse = new T[len];
var end = len - 1;
for (var i = 0; i <= end; i++)
reverse[i] = array[end - i];
return reverse;
}
internal static IEnumerable<string> SplitHeaderValue (this string value, params char[] separators)
{
var len = value.Length;
var seps = new string (separators);
var buff = new StringBuilder (32);
var escaped = false;
var quoted = false;
for (var i = 0; i < len; i++)
{
var c = value[i];
if (c == '"')
{
if (escaped)
escaped = !escaped;
else
quoted = !quoted;
}
else if (c == '\\')
{
if (i < len - 1 && value[i + 1] == '"')
escaped = true;
}
else if (seps.Contains (c))
{
if (!quoted)
{
yield return buff.ToString ();
buff.Length = 0;
continue;
}
}
else
{
}
buff.Append (c);
}
if (buff.Length > 0)
yield return buff.ToString ();
}
internal static byte[] ToByteArray (this Stream stream)
{
using (var output = new MemoryStream ())
{
stream.Position = 0;
stream.CopyTo (output, 1024);
output.Close ();
return output.ToArray ();
}
}
internal static CompressionMethod ToCompressionMethod (this string value)
{
#if NETCF
foreach (CompressionMethod method in Enum2.GetValues (typeof(CompressionMethod)))
{
#else
foreach (CompressionMethod method in Enum.GetValues (typeof (CompressionMethod)))
#endif
if (method.ToExtensionString () == value)
return method;
}
return CompressionMethod.None;
}
internal static string ToExtensionString (this CompressionMethod method, params string[] parameters)
{
if (method == CompressionMethod.None)
return String.Empty;
var m = String.Format ("permessage-{0}", method.ToString ().ToLower ());
if (parameters == null || parameters.Length == 0)
return m;
return String.Format ("{0}; {1}", m, parameters.ToString ("; "));
}
internal static IPAddress ToIPAddress (this string value)
{
IPAddress addr;
#if SSHARP
if (IPAddressTryParser.IPAddressTryParse (value, out addr))
#else
if (IPAddress.TryParse (hostnameOrAddress, out addr))
#endif