-
Notifications
You must be signed in to change notification settings - Fork 4
/
pseudotcp.cs
2977 lines (2526 loc) · 113 KB
/
pseudotcp.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
/*
* This file is part of the Nice GLib ICE library.
*
* (C) 2010, 2014 Collabora Ltd.
* Contact: Philip Withnall
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Nice GLib ICE library.
*
* The Initial Developers of the Original Code are Collabora Ltd and Nokia
* Corporation. All Rights Reserved.
*
* Contributors:
* Youness Alaoui, Collabora Ltd.
* Philip Withnall, Collabora Ltd.
*
* Alternatively, the contents of this file may be used under the terms of the
* the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
* case the provisions of LGPL are applicable instead of those above. If you
* wish to allow use of your version of this file only under the terms of the
* LGPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replace
* them with the notice and other provisions required by the LGPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the LGPL.
*/
/* Reproducing license from libjingle for copied code */
/*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <glib.h>
#ifndef G_OS_WIN32
# include <arpa/inet.h>
#endif
#include "pseudotcp.h"
#include "agent-priv.h"*/
using System;
using System.Collections.Generic;
using size_t = System.UInt32;
using gint = System.Int32;
using gint32 = System.Int32;
using guint16 = System.UInt16;
using guint32 = System.UInt32;
using guint64 = System.UInt64;
using gboolean = System.Boolean;
using guint8 = System.Byte;
using gsize = System.UInt32; // it should be 64 for 64 bit platforms...
namespace PseudoTcp
{
public class PseudoTcpSocket
{
internal PseudoTcpSocketPrivate priv;
/**
* PseudoTcpWriteResult:
* @WR_SUCCESS: The write operation was successful
* @WR_TOO_LARGE: The socket type requires that message be sent atomically
* and the size of the message to be sent made this impossible.
* @WR_FAIL: There was an error sending the message
*
* An enum representing the result value of the write operation requested by
* the #PseudoTcpSocket.
* <para> See also: %PseudoTcpCallbacks:WritePacket </para>
*
* Since: 0.0.11
*/
public enum WriteResult
{
WR_SUCCESS,
WR_TOO_LARGE,
WR_FAIL
}
/**
* PseudoTcpShutdown:
* @PSEUDO_TCP_SHUTDOWN_RD: Shut down the local reader only
* @PSEUDO_TCP_SHUTDOWN_WR: Shut down the local writer only
* @PSEUDO_TCP_SHUTDOWN_RDWR: Shut down both reading and writing
*
* Options for which parts of a connection to shut down when calling
* pseudo_tcp_socket_shutdown(). These correspond to the values passed to POSIX
* shutdown().
*
* Since: 0.1.8
*/
public enum PseudoTcpShutdown
{
PSEUDO_TCP_SHUTDOWN_RD,
PSEUDO_TCP_SHUTDOWN_WR,
PSEUDO_TCP_SHUTDOWN_RDWR,
}
// G_DEFINE_TYPE (PseudoTcpSocket, pseudo_tcp_socket, G_TYPE_OBJECT);
//////////////////////////////////////////////////////////////////////
// Network Constants
//////////////////////////////////////////////////////////////////////
const int EINVAL = 22;
const int EMSGSIZE = 90;
const int ECONNABORTED = 103; /* Software caused connection abort */
const int ENOTCONN = 107; /* Transport endpoint is not connected */
const int EAGAIN = 11; /* Try again */
public const int EWOULDBLOCK = EAGAIN; /* Operation would block */
const int EPIPE = 32; /* Broken pipe */
const int ECONNRESET = 104; /* Connection reset by peer */
const int ETIMEDOUT = 110; /* Connection timed out */
// Standard MTUs
static guint16[] PACKET_MAXIMUMS = new guint16[]{
65535, // Theoretical maximum, Hyperchannel
32000, // Nothing
17914, // 16Mb IBM Token Ring
8166, // IEEE 802.4
//4464, // IEEE 802.5 (4Mb max)
4352, // FDDI
//2048, // Wideband Network
2002, // IEEE 802.5 (4Mb recommended)
//1536, // Expermental Ethernet Networks
//1500, // Ethernet, Point-to-Point (default)
1492, // IEEE 802.3
1006, // SLIP, ARPANET
//576, // X.25 Networks
//544, // DEC IP Portal
//512, // NETBIOS
508, // IEEE 802/Source-Rt Bridge, ARCNET
296, // Point-to-Point (low delay)
//68, // Official minimum
0, // End of list marker
};
// FIXME: This is a reasonable MTU, but we should get it from the lower layer
const int DEF_MTU = 1400;
const int MAX_PACKET = 65532;
// Note: we removed lowest level because packet overhead was larger!
const int MIN_PACKET = 296;
// (+ up to 40 bytes of options?)
const int IP_HEADER_SIZE = 20;
const int ICMP_HEADER_SIZE = 8;
const int UDP_HEADER_SIZE = 8;
// TODO: Make JINGLE_HEADER_SIZE transparent to this code?
// when relay framing is in use
const int JINGLE_HEADER_SIZE = 64;
//////////////////////////////////////////////////////////////////////
// Global Constants and Functions
//////////////////////////////////////////////////////////////////////
//
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 0 | Conversation Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 4 | Sequence Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 8 | Acknowledgment Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | | |U|A|P|R|S|F| |
// 12 | Control | |R|C|S|S|Y|I| Window |
// | | |G|K|H|T|N|N| |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 16 | Timestamp sending |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 20 | Timestamp receiving |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 24 | data |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//////////////////////////////////////////////////////////////////////
const uint MAX_SEQ = 0xFFFFFFFF;
const int HEADER_SIZE = 24;
const int PACKET_OVERHEAD = HEADER_SIZE + UDP_HEADER_SIZE + IP_HEADER_SIZE + JINGLE_HEADER_SIZE;
// MIN_RTO = 1 second (RFC6298, Sec 2.4)
const int MIN_RTO = 1000;
const int DEF_RTO = 1000; /* 1 seconds (RFC 6298 sect 2.1) */
const int MAX_RTO = 60000; /* 60 seconds */
const int DEFAULT_ACK_DELAY = 100; /* 100 milliseconds */
const bool DEFAULT_NO_DELAY = false;
const int DEFAULT_RCV_BUF_SIZE = 60 * 1024;
const int DEFAULT_SND_BUF_SIZE = 90 * 1024;
/* NOTE: This must fit in 8 bits. This is used on the wire. */
enum TcpOption : byte
{
/* Google-provided options: */
TCP_OPT_EOL = 0, /* end of list */
TCP_OPT_NOOP = 1, /* no-op */
TCP_OPT_MSS = 2, /* maximum segment size */
TCP_OPT_WND_SCALE = 3, /* window scale factor */
/* libnice extensions: */
TCP_OPT_FIN_ACK = 254, /* FIN-ACK support */
}
/*
#define FLAG_SYN 0x02
#define FLAG_ACK 0x10
*/
/* NOTE: This must fit in 5 bits. This is used on the wire. */
internal enum TcpFlags
{
FLAG_NONE = 0,
FLAG_FIN = 1 << 0,
FLAG_CTL = 1 << 1,
FLAG_RST = 1 << 2
}
const int CTL_CONNECT = 0;
//#define CTL_REDIRECT 1
const int CTL_EXTRA = 255;
const uint CTRL_BOUND = 0x80000000;
/* Maximum segment lifetime (1 minute).
* RFC 793, §3.3 specifies 2 minutes; but Linux uses 1 minute, so let’s go with
* that. */
const int TCP_MSL = 60 * 1000;
// If there are no pending clocks, wake up every 4 seconds
const int DEFAULT_TIMEOUT = 4000;
// If the connection is closed, once per minute
const int CLOSED_TIMEOUT = (60 * 1000);
/* Timeout after reaching the TIME_WAIT state, in milliseconds.
* See: RFC 1122, §4.2.2.13.
*
* XXX: Since we can control the underlying layer’s channel ID, we can guarantee
* delayed segments won’t affect subsequent connections, so can radically
* shorten the TIME-WAIT timeout (to the extent that it basically doesn’t
* exist). It would normally be (2 * TCP_MSL). */
const int TIME_WAIT_TIMEOUT = 1;
//////////////////////////////////////////////////////////////////////
// Helper Functions
//////////////////////////////////////////////////////////////////////
/*#ifndef G_OS_WIN32
# define min(first, second) ((first) < (second) ? (first) : (second))
# define max(first, second) ((first) > (second) ? (first) : (second))
#endif*/
static guint32
bound(guint32 lower, guint32 middle, guint32 upper)
{
return Math.Min(Math.Max(lower, middle), upper);
}
static gboolean
time_is_between(guint32 later, guint32 middle, guint32 earlier)
{
if (earlier <= later)
{
return ((earlier <= middle) && (middle <= later));
}
else
{
return !((later < middle) && (middle < earlier));
}
}
static gint32
time_diff(guint32 later, guint32 earlier)
{
guint32 LAST = 0xFFFFFFFF;
guint32 HALF = 0x80000000;
#warning originally all conversions cast to "long" in C
if (time_is_between(earlier + HALF, later, earlier))
{
if (earlier <= later)
{
return (gint32)(later - earlier);
}
else
{
return (gint32)(later + (LAST - earlier) + 1);
}
}
else
{
if (later <= earlier)
{
return (gint32)(-(earlier - later));
}
else
{
return (gint32)(-(earlier + (LAST - later) + 1));
}
}
}
////////////////////////////////////////////////////////
// PseudoTcpFifo works exactly like FifoBuffer in libjingle
////////////////////////////////////////////////////////
internal class PseudoTcpFifo
{
internal guint8[] buffer;
internal gsize buffer_length;
internal gsize data_length;
internal gsize read_position;
static internal PseudoTcpFifo Init(gsize size)
{
PseudoTcpFifo b = new PseudoTcpFifo();
b.buffer = new byte[size];
b.buffer_length = size;
return b;
}
static internal void Clear(PseudoTcpFifo b)
{
if (b.buffer != null)
{
// g_slice_free1 (b.buffer_length, b.buffer);
}
b.buffer = null;
b.buffer_length = 0;
}
static internal gsize GetBuffered(PseudoTcpFifo b)
{
return b.data_length;
}
static internal gboolean SetCapacity(PseudoTcpFifo b, gsize size)
{
if (b.data_length > size)
return false;
if (size != b.data_length)
{
guint8[] buffer = new guint8[size];
gsize copy = b.data_length;
gsize tail_copy = Math.Min(copy, b.buffer_length - b.read_position);
memcpy(buffer, 0, b.buffer, b.read_position, tail_copy);
memcpy(buffer, tail_copy, b.buffer, 0, copy - tail_copy);
//g_slice_free1 (b.buffer_length, b.buffer);
b.buffer = buffer;
b.buffer_length = size;
b.read_position = 0;
}
return true;
}
static internal void ConsumeReadData(PseudoTcpFifo b, gsize size)
{
g_assert(size <= b.data_length);
b.read_position = (b.read_position + size) % b.buffer_length;
b.data_length -= size;
}
static internal void ConsumeWriteBuffer(PseudoTcpFifo b, gsize size)
{
g_assert(size <= b.buffer_length - b.data_length);
b.data_length += size;
}
static internal gsize GetWriteRemaining(PseudoTcpFifo b)
{
return b.buffer_length - b.data_length;
}
static internal gsize ReadOffset(PseudoTcpFifo b, byte[] buffer, gsize bufferPos, gsize bytes,
gsize offset)
{
gsize available = b.data_length - offset;
gsize read_position = (b.read_position + offset) % b.buffer_length;
gsize copy = Math.Min(bytes, available);
gsize tail_copy = Math.Min(copy, b.buffer_length - read_position);
/* EOS */
if (offset >= b.data_length)
return 0;
memcpy(buffer, bufferPos, b.buffer, read_position, tail_copy);
memcpy(buffer, tail_copy + bufferPos, b.buffer, 0, copy - tail_copy);
return copy;
}
static internal gsize WriteOffset(PseudoTcpFifo b, byte[] buffer,
gsize bytes, gsize offset)
{
gsize available = b.buffer_length - b.data_length - offset;
gsize write_position = (b.read_position + b.data_length + offset)
% b.buffer_length;
gsize copy = Math.Min(bytes, available);
gsize tail_copy = Math.Min(copy, b.buffer_length - write_position);
if (b.data_length + offset >= b.buffer_length)
{
return 0;
}
memcpy(b.buffer, write_position, buffer, 0, tail_copy);
memcpy(b.buffer, 0, buffer, tail_copy, copy - tail_copy);
return copy;
}
static internal gsize Read(PseudoTcpFifo b, byte[] buffer, gsize bytes)
{
gsize copy;
copy = ReadOffset(b, buffer, 0, bytes, 0);
b.read_position = (b.read_position + copy) % b.buffer_length;
b.data_length -= copy;
return copy;
}
static internal gsize Write(PseudoTcpFifo b, byte[] buffer, gsize bytes)
{
gsize copy;
copy = WriteOffset(b, buffer, bytes, 0);
b.data_length += copy;
return copy;
}
}
static void memcpy(byte[] dst, gsize dstPos, byte[] src, gsize srcPos, gsize size)
{
if (size == 0)
return;
Buffer.BlockCopy(src, (int)srcPos, dst, (int)dstPos, (int)size);
}
static void g_assert(bool cond)
{
if (cond)
return;
throw new Exception("g_assert");
}
//////////////////////////////////////////////////////////////////////
// PseudoTcp
//////////////////////////////////////////////////////////////////////
/* Only used if FIN-ACK support is disabled. */
internal enum ShutdownType
{
SD_NONE,
SD_GRACEFUL,
SD_FORCEFUL
}
enum SendFlags
{
sfNone,
sfDelayedAck,
sfImmediateAck,
sfFin,
sfRst,
sfDuplicateAck,
}
class Segment
{
internal guint32 conv, seq, ack;
internal TcpFlags flags;
internal guint16 wnd;
internal byte[] data;
internal guint32 len;
internal guint32 tsval, tsecr;
}
internal class SSegment
{
internal guint32 seq, len;
internal guint8 xmit;
internal TcpFlags flags;
}
internal class RSegment
{
internal guint32 seq, len;
}
/**
* ClosedownSource:
* @CLOSEDOWN_LOCAL: Error detected locally, or connection forcefully closed
* locally.
* @CLOSEDOWN_REMOTE: RST segment received from the peer.
*
* Reasons for calling closedown().
*
* Since: 0.1.8
*/
enum ClosedownSource
{
CLOSEDOWN_LOCAL,
CLOSEDOWN_REMOTE
}
/**
* PseudoTcpState:
* @TCP_LISTEN: The socket's initial state. The socket isn't connected and is
* listening for an incoming connection
* @TCP_SYN_SENT: The socket has sent a connection request (SYN) packet and is
* waiting for an answer
* @TCP_SYN_RECEIVED: The socket has received a connection request (SYN) packet.
* @TCP_ESTABLISHED: The socket is connected
* @TCP_CLOSED: The socket has been closed
* @TCP_FIN_WAIT_1: The socket has been closed locally but not remotely
* (Since: 0.1.8)
* @TCP_FIN_WAIT_2: The socket has been closed locally but not remotely
* (Since: 0.1.8)
* @TCP_CLOSING: The socket has been closed locally and remotely
* (Since: 0.1.8)
* @TCP_TIME_WAIT: The socket has been closed locally and remotely
* (Since: 0.1.8)
* @TCP_CLOSE_WAIT: The socket has been closed remotely but not locally
* (Since: 0.1.8)
* @TCP_LAST_ACK: The socket has been closed locally and remotely
* (Since: 0.1.8)
*
* An enum representing the state of the #PseudoTcpSocket. These states
* correspond to the TCP states in RFC 793.
* <para> See also: #PseudoTcpSocket:state </para>
*
* Since: 0.0.11
*/
internal static class PseudoTcpState
{
internal enum Values
{
TCP_LISTEN,
TCP_SYN_SENT,
TCP_SYN_RECEIVED,
TCP_ESTABLISHED,
TCP_CLOSED,
TCP_FIN_WAIT_1,
TCP_FIN_WAIT_2,
TCP_CLOSING,
TCP_TIME_WAIT,
TCP_CLOSE_WAIT,
TCP_LAST_ACK,
}
/* State names are capitalised and formatted as in RFC 793. */
static internal string GetName(Values state)
{
switch (state)
{
case Values.TCP_LISTEN: return "LISTEN";
case Values.TCP_SYN_SENT: return "SYN-SENT";
case Values.TCP_SYN_RECEIVED: return "SYN-RECEIVED";
case Values.TCP_ESTABLISHED: return "ESTABLISHED";
case Values.TCP_CLOSED: return "CLOSED";
case Values.TCP_FIN_WAIT_1: return "FIN-WAIT-1";
case Values.TCP_FIN_WAIT_2: return "FIN-WAIT-2";
case Values.TCP_CLOSING: return "CLOSING";
case Values.TCP_TIME_WAIT: return "TIME-WAIT";
case Values.TCP_CLOSE_WAIT: return "CLOSE-WAIT";
case Values.TCP_LAST_ACK: return "LAST-ACK";
default: return "UNKNOWN";
}
}
/* True iff the @state requires that a FIN has already been sent by this
* host. */
static internal gboolean HasSentFin(Values state)
{
switch (state)
{
case Values.TCP_LISTEN:
case Values.TCP_SYN_SENT:
case Values.TCP_SYN_RECEIVED:
case Values.TCP_ESTABLISHED:
case Values.TCP_CLOSE_WAIT:
return false;
case Values.TCP_CLOSED:
case Values.TCP_FIN_WAIT_1:
case Values.TCP_FIN_WAIT_2:
case Values.TCP_CLOSING:
case Values.TCP_TIME_WAIT:
case Values.TCP_LAST_ACK:
return true;
default:
return false;
}
}
/* True iff the @state requires that a FIN has already been received from the
* peer. */
static internal gboolean HasReceivedFin(Values state)
{
switch (state)
{
case Values.TCP_LISTEN:
case Values.TCP_SYN_SENT:
case Values.TCP_SYN_RECEIVED:
case Values.TCP_ESTABLISHED:
case Values.TCP_FIN_WAIT_1:
case Values.TCP_FIN_WAIT_2:
return false;
case Values.TCP_CLOSED:
case Values.TCP_CLOSING:
case Values.TCP_TIME_WAIT:
case Values.TCP_CLOSE_WAIT:
case Values.TCP_LAST_ACK:
return true;
default:
return false;
}
}
/* True iff the @state requires that a FIN-ACK has already been received from
* the peer. */
static internal gboolean HasReceivedFinAck(Values state)
{
switch (state)
{
case Values.TCP_LISTEN:
case Values.TCP_SYN_SENT:
case Values.TCP_SYN_RECEIVED:
case Values.TCP_ESTABLISHED:
case Values.TCP_FIN_WAIT_1:
case Values.TCP_FIN_WAIT_2:
case Values.TCP_CLOSING:
case Values.TCP_CLOSE_WAIT:
case Values.TCP_LAST_ACK:
return false;
case Values.TCP_CLOSED:
case Values.TCP_TIME_WAIT:
return true;
default:
return false;
}
}
}
/**
* PseudoTcpCallbacks:
* @user_data: A user defined pointer to be passed to the callbacks
* @PseudoTcpOpened: The #PseudoTcpSocket is now connected
* @PseudoTcpReadable: The socket is readable
* @PseudoTcpWritable: The socket is writable
* @PseudoTcpClosed: The socket was closed (both sides)
* @WritePacket: This callback is called when the socket needs to send data.
*
* A structure containing callbacks functions that will be called by the
* #PseudoTcpSocket when some events happen.
* <para> See also: #PseudoTcpWriteResult </para>
*
* Since: 0.0.11
*/
public class Callbacks
{
/*gpointer user_data;
void (*PseudoTcpOpened) (PseudoTcpSocket *tcp, gpointer data);
void (*PseudoTcpReadable) (PseudoTcpSocket *tcp, gpointer data);
void (*PseudoTcpWritable) (PseudoTcpSocket *tcp, gpointer data);
void (*PseudoTcpClosed) (PseudoTcpSocket *tcp, guint32 error, gpointer data);
PseudoTcpWriteResult (*WritePacket) (PseudoTcpSocket *tcp,
const gchar * buffer, guint32 len, gpointer data);*/
public delegate void Callback(PseudoTcpSocket tcp, object data);
public delegate void ClosedCallback(PseudoTcpSocket tcp, uint error, object data);
public delegate WriteResult WritePacketCallback(PseudoTcpSocket tcp, byte[] buffer, uint len, object data);
public object user_data;
public Callback PseudoTcpOpened;
public Callback PseudoTcpReadable;
public Callback PseudoTcpWritable;
public ClosedCallback PseudoTcpClosed;
public WritePacketCallback WritePacket;
// return PseudoTcpWriteResult.WR_SUCCESS;
}
internal class PseudoTcpSocketPrivate
{
internal Callbacks callbacks;
internal ShutdownType shutdown; /* only used if !support_fin_ack */
internal gboolean shutdown_reads;
internal gint error;
// TCB data
internal PseudoTcpState.Values state;
internal guint32 conv;
internal gboolean bReadEnable, bWriteEnable, bOutgoing;
internal guint32 last_traffic;
// Incoming data
internal List<RSegment> rlist;
internal guint32 rbuf_len, rcv_nxt, rcv_wnd, lastrecv;
internal guint8 rwnd_scale; // Window scale factor
internal PseudoTcpFifo rbuf;
internal guint32 rcv_fin; /* sequence number of the received FIN octet, or 0 */
// Outgoing data
internal List<SSegment> slist;
internal List<SSegment> unsent_slist;
internal guint32 sbuf_len, snd_nxt, snd_wnd, lastsend;
internal guint32 snd_una; /* oldest unacknowledged sequence number */
internal guint8 swnd_scale; // Window scale factor
internal PseudoTcpFifo sbuf;
// Maximum segment size, estimated protocol level, largest segment sent
internal guint32 mss, msslevel, largest, mtu_advise;
// Retransmit timer
internal guint32 rto_base;
// Timestamp tracking
internal guint32 ts_recent, ts_lastack;
// Round-trip calculation
internal guint32 rx_rttvar, rx_srtt, rx_rto;
// Congestion avoidance, Fast retransmit/recovery, Delayed ACKs
internal guint32 ssthresh, cwnd;
internal guint8 dup_acks;
internal guint32 recover;
internal gboolean fast_recovery;
internal guint32 t_ack; /* time a delayed ack was scheduled; 0 if no acks scheduled */
internal guint32 last_acked_ts;
internal gboolean use_nagling;
internal guint32 ack_delay;
// This is used by unit tests to test backward compatibility of
// PseudoTcp implementations that don't support window scaling.
internal gboolean support_wnd_scale;
/* Current time. Typically only used for testing, when non-zero. When zero,
* the system monotonic clock is used. Units: monotonic milliseconds. */
internal guint32 current_time;
/* This is used by compatible implementations (with the TCP_OPT_FIN_ACK
* option) to enable correct FIN-ACK connection termination. Defaults to
* true unless no compatible option is received. */
internal gboolean support_fin_ack;
}
static bool LARGER(uint a, uint b) { return (((a) - (b) - 1) < (uint.MaxValue >> 1)); }
static bool LARGER_OR_EQUAL(uint a, uint b) { return (((a) - (b)) < (uint.MaxValue >> 1)); }
static bool SMALLER(uint a, uint b) { return LARGER(b, a); }
static bool SMALLER_OR_EQUAL(uint a, uint b) { return LARGER_OR_EQUAL((b), (a)); }
/* properties */
enum Props
{
PROP_CONVERSATION = 1,
PROP_CALLBACKS,
PROP_STATE,
PROP_ACK_DELAY,
PROP_NO_DELAY,
PROP_RCV_BUF,
PROP_SND_BUF,
PROP_SUPPORT_FIN_ACK,
LAST_PROPERTY
};
/*
static void pseudo_tcp_socket_get_property (GObject *object, guint property_id,
GValue *value, GParamSpec *pspec);
static void pseudo_tcp_socket_set_property (GObject *object, guint property_id,
const GValue *value, GParamSpec *pspec);
static void pseudo_tcp_socket_finalize (GObject *object);
static void queue_connect_message (PseudoTcpSocket *self);
static uint queue (PseudoTcpSocket *self, const gchar *data,
uint len, TcpFlags flags);
static PseudoTcpWriteResult packet(PseudoTcpSocket *self, uint seq,
TcpFlags flags, uint offset, uint len, uint now);
static bool parse (PseudoTcpSocket *self,
const byte *_header_buf, gsize header_buf_len,
const byte *data_buf, gsize data_buf_len);
static bool process(PseudoTcpSocket *self, Segment *seg);
static int transmit(PseudoTcpSocket *self, SSegment *sseg, uint now);
static void attempt_send(PseudoTcpSocket *self, SendFlags sflags);
static void closedown (PseudoTcpSocket *self, uint err,
ClosedownSource source);
static void adjustMTU(PseudoTcpSocket *self);
static void parse_options (PseudoTcpSocket *self, const byte *data,
uint len);
static void resize_send_buffer (PseudoTcpSocket *self, uint new_size);
static void resize_receive_buffer (PseudoTcpSocket *self, uint new_size);
static void set_state (PseudoTcpSocket *self, PseudoTcpState new_state);
static void set_state_established (PseudoTcpSocket *self);
static void set_state_closed (PseudoTcpSocket *self, uint err);
static const string PseudoTcpState.GetName (PseudoTcpState state);
static bool pseudo_tcp_state_has_sent_fin (PseudoTcpState state);
static bool pseudo_tcp_state_has_received_fin (PseudoTcpState state);
static bool pseudo_tcp_state_has_received_fin_ack (PseudoTcpState state);*/
/**
* PseudoTcpDebugLevel:
* @PSEUDO_TCP_DEBUG_NONE: Disable debug messages
* @PSEUDO_TCP_DEBUG_NORMAL: Enable basic debug messages
* @PSEUDO_TCP_DEBUG_VERBOSE: Enable verbose debug messages
*
* Valid values of debug levels to be set.
*
* Since: 0.0.11
*/
enum PseudoTcpDebugLevel
{
PSEUDO_TCP_DEBUG_NONE = 0,
PSEUDO_TCP_DEBUG_NORMAL,
PSEUDO_TCP_DEBUG_VERBOSE
}
// The following logging is for detailed (packet-level) pseudotcp analysis only.
static PseudoTcpDebugLevel debug_level = PseudoTcpDebugLevel.PSEUDO_TCP_DEBUG_NONE;
static void DEBUG(
PseudoTcpSocket self,
PseudoTcpDebugLevel level, string fmt, params object[] args)
{
return;
if (debug_level >= level)
Console.WriteLine(level == PseudoTcpDebugLevel.PSEUDO_TCP_DEBUG_NORMAL ? "libnice-pseudotcp" : "libnice-pseudotcp-verbose" +
/*G_LOG_LEVEL_DEBUG,*/
string.Format("PseudoTcpSocket {0} {1}",
self, PseudoTcpState.GetName(self.priv.state)) + string.Format(fmt, args));
}
void
pseudo_tcp_set_debug_level(PseudoTcpDebugLevel level)
{
debug_level = level;
}
static guint32 GetCurrentTime(PseudoTcpSocket socket)
{
if (/*G_UNLIKELY*/ (socket.priv.current_time != 0))
return socket.priv.current_time;
return GetMonotonicTime() /*/ 1000*/;
}
static public uint GetMonotonicTime()
{
// probably use StopWatch or something similar
return (uint)Environment.TickCount;
}
void SetTime(guint32 current_time)
{
priv.current_time = current_time;
}
/*static void
pseudo_tcp_socket_finalize (GObject *object)
{
PseudoTcpSocket *self = PSEUDO_TCP_SOCKET (object);
PseudoTcpSocketPrivate *priv = self.priv;
GList *i;
SSegment *sseg;
if (priv == NULL)
return;
while ((sseg = g_queue_pop_head (&priv.slist)))
g_slice_free (SSegment, sseg);
g_queue_clear (&priv.unsent_slist);
for (i = priv.rlist; i; i = i.next) {
RSegment *rseg = i.data;
g_slice_free (RSegment, rseg);
}
g_list_free (priv.rlist);
priv.rlist = NULL;
pseudo_tcp_fifo_clear (&priv.rbuf);
pseudo_tcp_fifo_clear (&priv.sbuf);
g_free (priv);
self.priv = NULL;
if (G_OBJECT_CLASS (pseudo_tcp_socket_parent_class).finalize)
G_OBJECT_CLASS (pseudo_tcp_socket_parent_class).finalize (object);
}*/
static void Init(PseudoTcpSocket obj)
{
/* Use g_new0, and do not use g_object_set_private because the size of
* our private data is too big (150KB+) and the g_slice_allow cannot allocate
* it. So we handle the private ourselves */
PseudoTcpSocketPrivate priv = new PseudoTcpSocketPrivate();
obj.priv = priv;
priv.rlist = new List<RSegment>();
priv.shutdown = ShutdownType.SD_NONE;
priv.error = 0;
priv.rbuf_len = DEFAULT_RCV_BUF_SIZE;
priv.rbuf = PseudoTcpFifo.Init(priv.rbuf_len);
priv.sbuf_len = DEFAULT_SND_BUF_SIZE;
priv.sbuf = PseudoTcpFifo.Init(priv.sbuf_len);
priv.state = PseudoTcpState.Values.TCP_LISTEN;
priv.conv = 0;
priv.slist = new List<SSegment>();
priv.unsent_slist = new List<SSegment>();
priv.rcv_wnd = priv.rbuf_len;
priv.rwnd_scale = priv.swnd_scale = 0;
priv.snd_nxt = 0;
priv.snd_wnd = 1;
priv.snd_una = priv.rcv_nxt = 0;
priv.bReadEnable = true;
priv.bWriteEnable = false;
priv.rcv_fin = 0;
priv.t_ack = 0;
priv.msslevel = 0;
priv.largest = 0;
priv.mss = MIN_PACKET - PACKET_OVERHEAD;
priv.mtu_advise = DEF_MTU;
priv.rto_base = 0;
priv.cwnd = 2 * priv.mss;
priv.ssthresh = priv.rbuf_len;
priv.lastrecv = priv.lastsend = priv.last_traffic = 0;