forked from gozfree/gear-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibptcp.c
2637 lines (2249 loc) · 71.4 KB
/
libptcp.c
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
/*****************************************************************************
* Copyright (C) 2014-2015
* file: libptcp.c
* author: gozfree <[email protected]>
* created: 2015-08-10 00:15
* updated: 2015-08-10 00:15
*****************************************************************************/
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>
#include <inttypes.h>
#include <pthread.h>
#include <semaphore.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <libmacro.h>
#include <liblog.h>
#include "queue.h"
#include "libptcp.h"
#ifndef TRUE
#define TRUE (1 == 1)
#endif
#ifndef FALSE
#define FALSE (0 == 1)
#endif
#define MAX_EPOLL_EVENT 16
typedef enum {
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,
} ptcp_state_t;
//////////////////////////////////////////////////////////////////////
// Network Constants
//////////////////////////////////////////////////////////////////////
// Standard MTUs
static const uint16_t PACKET_MAXIMUMS[] = {
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
};
#define MAX_PACKET 65535
// Note: we removed lowest level because packet overhead was larger!
#define MIN_PACKET 296
// (+ up to 40 bytes of options?)
#define IP_HEADER_SIZE 20
#define ICMP_HEADER_SIZE 8
#define UDP_HEADER_SIZE 8
// TODO: Make JINGLE_HEADER_SIZE transparent to this code?
// when relay framing is in use
#define 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 |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//////////////////////////////////////////////////////////////////////
#define MAX_SEQ 0xFFFFFFFF
#define HEADER_SIZE 24
#define PACKET_OVERHEAD (HEADER_SIZE + UDP_HEADER_SIZE + \
IP_HEADER_SIZE + JINGLE_HEADER_SIZE)
// MIN_RTO = 250 ms (RFC1122, Sec 4.2.3.1 "fractions of a second")
#define MIN_RTO 250
#define DEF_RTO 1000 /* 1 seconds (RFC 6298 sect 2.1) */
#define MAX_RTO 60000 /* 60 seconds */
#define DEFAULT_ACK_DELAY 100 /* 100 milliseconds */
#define DEFAULT_NO_DELAY FALSE
#define DEFAULT_RCV_BUF_SIZE (600 * 1024)
#define DEFAULT_SND_BUF_SIZE (900 * 1024)
/* NOTE: This must fit in 8 bits. This is used on the wire. */
typedef enum {
/* 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 */
} TcpOption;
/*
#define FLAG_SYN 0x02
#define FLAG_ACK 0x10
*/
/* NOTE: This must fit in 5 bits. This is used on the wire. */
typedef enum {
FLAG_NONE = 0,
FLAG_FIN = 1 << 0,
FLAG_CTL = 1 << 1,
FLAG_RST = 1 << 2,
} TcpFlags;
#define CTL_CONNECT 0
//#define CTL_REDIRECT 1
#define CTL_EXTRA 255
#define 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. */
#define TCP_MSL (60 * 1000)
// If there are no pending clocks, wake up every 4 seconds
#define DEFAULT_TIMEOUT 4000
// If the connection is closed, once per minute
#define 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). */
#define TIME_WAIT_TIMEOUT 1
//////////////////////////////////////////////////////////////////////
// Helper Functions
//////////////////////////////////////////////////////////////////////
#ifndef G_OS_WIN32
#undef min
#undef max
# define min(first, second) ((first) < (second) ? (first) : (second))
# define max(first, second) ((first) > (second) ? (first) : (second))
#endif
static uint32_t bound(uint32_t lower, uint32_t middle, uint32_t upper)
{
return min(max(lower, middle), upper);
}
static int time_is_between(uint32_t later, uint32_t middle, uint32_t earlier)
{
if (earlier <= later) {
return ((earlier <= middle) && (middle <= later));
} else {
return !((later < middle) && (middle < earlier));
}
}
static int32_t time_diff(uint32_t later, uint32_t earlier)
{
uint32_t LAST = 0xFFFFFFFF;
uint32_t HALF = 0x80000000;
if (time_is_between(earlier + HALF, later, earlier)) {
if (earlier <= later) {
return (long)(later - earlier);
} else {
return (long)(later + (LAST - earlier) + 1);
}
} else {
if (later <= earlier) {
return -(long) (earlier - later);
} else {
return -(long)(earlier + (LAST - later) + 1);
}
}
}
////////////////////////////////////////////////////////
// PseudoTcpFifo works exactly like FifoBuffer in libjingle
////////////////////////////////////////////////////////
typedef struct {
uint8_t *buffer;
size_t buffer_length;
size_t data_length;
size_t read_position;
} PseudoTcpFifo;
static void ptcp_fifo_init(PseudoTcpFifo *b, size_t size)
{
b->buffer = (uint8_t *)calloc(1, size);
b->buffer_length = size;
}
static void ptcp_fifo_clear(PseudoTcpFifo *b)
{
if (b->buffer) {
free(b->buffer);
}
b->buffer = NULL;
b->buffer_length = 0;
}
static size_t ptcp_fifo_get_buffered(PseudoTcpFifo *b)
{
return b->data_length;
}
static int ptcp_fifo_set_capacity(PseudoTcpFifo *b, size_t size)
{
if (b->data_length > size)
return FALSE;
if (size != b->data_length) {
uint8_t *buffer = calloc(1, size);
size_t copy = b->data_length;
size_t tail_copy = min(copy, b->buffer_length - b->read_position);
memcpy(buffer, &b->buffer[b->read_position], tail_copy);
memcpy(buffer + tail_copy, &b->buffer[0], copy - tail_copy);
free(b->buffer);
b->buffer = buffer;
b->buffer_length = size;
b->read_position = 0;
}
return TRUE;
}
static void ptcp_fifo_consume_read_data(PseudoTcpFifo *b, size_t size)
{
assert(size <= b->data_length);
b->read_position = (b->read_position + size) % b->buffer_length;
b->data_length -= size;
}
static void ptcp_fifo_consume_write_buffer(PseudoTcpFifo *b, size_t size)
{
assert(size <= b->buffer_length - b->data_length);
b->data_length += size;
}
static size_t ptcp_fifo_get_write_remaining(PseudoTcpFifo *b)
{
return b->buffer_length - b->data_length;
}
static size_t ptcp_fifo_read_offset(PseudoTcpFifo *b, uint8_t *buffer, size_t bytes,
size_t offset)
{
size_t available = b->data_length - offset;
size_t read_position = (b->read_position + offset) % b->buffer_length;
size_t copy = min (bytes, available);
size_t tail_copy = min(copy, b->buffer_length - read_position);
/* EOS */
if (offset >= b->data_length)
return 0;
memcpy(buffer, &b->buffer[read_position], tail_copy);
memcpy(buffer + tail_copy, &b->buffer[0], copy - tail_copy);
return copy;
}
static size_t ptcp_fifo_write_offset(PseudoTcpFifo *b, const uint8_t *buffer,
size_t bytes, size_t offset)
{
size_t available = b->buffer_length - b->data_length - offset;
size_t write_position = (b->read_position + b->data_length + offset)
% b->buffer_length;
size_t copy = min (bytes, available);
size_t tail_copy = min(copy, b->buffer_length - write_position);
if (b->data_length + offset >= b->buffer_length) {
return 0;
}
memcpy(&b->buffer[write_position], buffer, tail_copy);
memcpy(&b->buffer[0], buffer + tail_copy, copy - tail_copy);
return copy;
}
static size_t ptcp_fifo_read(PseudoTcpFifo *b, uint8_t *buffer, size_t bytes)
{
size_t copy;
copy = ptcp_fifo_read_offset (b, buffer, bytes, 0);
b->read_position = (b->read_position + copy) % b->buffer_length;
b->data_length -= copy;
return copy;
}
static size_t ptcp_fifo_write(PseudoTcpFifo *b, const uint8_t *buffer, size_t bytes)
{
size_t copy;
copy = ptcp_fifo_write_offset (b, buffer, bytes, 0);
b->data_length += copy;
return copy;
}
//////////////////////////////////////////////////////////////////////
// PseudoTcp
//////////////////////////////////////////////////////////////////////
/* Only used if FIN-ACK support is disabled. */
typedef enum {
SD_NONE,
SD_GRACEFUL,
SD_FORCEFUL
} Shutdown;
typedef enum {
sfNone,
sfDelayedAck,
sfImmediateAck,
sfFin,
sfRst,
} SendFlags;
typedef struct {
uint32_t conv, seq, ack;
TcpFlags flags;
uint16_t wnd;
const char * data;
uint32_t len;
uint32_t tsval, tsecr;
} Segment;
typedef struct {
uint32_t seq, len;
uint8_t xmit;
TcpFlags flags;
} SSegment;
typedef struct {
uint32_t seq, len;
} RSegment;
/**
* ClosedownSource:
* @CLOSEDOWN_LOCAL: Error detected locally, or connection forcefully closed
* locally.
* @CLOSEDOWN_REMOTE: RST segment received from the peer.
*
* Reasons for calling closedown().
*
* Since: UNRELEASED
*/
typedef enum {
CLOSEDOWN_LOCAL,
CLOSEDOWN_REMOTE,
} ClosedownSource;
struct _ptcp_socket {
/*************************/
/*extended paraments*/
int on_read_fd;
int on_write_fd;
int fd;
struct sockaddr_in si;
timer_t timer_id;
sem_t sem;
/**************************/
ptcp_callbacks_t callbacks;
Shutdown shutdown; /* only used if !support_fin_ack */
int shutdown_reads;
int error;
// TCB data
ptcp_state_t state;
uint32_t conv;
int bReadEnable, bWriteEnable, bOutgoing;
uint32_t last_traffic;
// Incoming data
list_t *rlist;
uint32_t rbuf_len, rcv_nxt, rcv_wnd, lastrecv;
uint8_t rwnd_scale; // Window scale factor
PseudoTcpFifo rbuf;
// Outgoing data
queue_t slist;
queue_t unsent_slist;
uint32_t sbuf_len, snd_nxt, snd_wnd, lastsend;
uint32_t snd_una; /* oldest unacknowledged sequence number */
uint8_t swnd_scale; // Window scale factor
PseudoTcpFifo sbuf;
// Maximum segment size, estimated protocol level, largest segment sent
uint32_t mss, msslevel, largest, mtu_advise;
// Retransmit timer
uint32_t rto_base;
// Timestamp tracking
uint32_t ts_recent, ts_lastack;
// Round-trip calculation
uint32_t rx_rttvar, rx_srtt, rx_rto;
// Congestion avoidance, Fast retransmit/recovery, Delayed ACKs
uint32_t ssthresh, cwnd;
uint8_t dup_acks;
uint32_t recover;
uint32_t t_ack; /* time a delayed ack was scheduled; 0 if no acks scheduled */
int use_nagling;
uint32_t ack_delay;
// This is used by unit tests to test backward compatibility of
// PseudoTcp implementations that don't support window scaling.
int support_wnd_scale;
/* Current time. Typically only used for testing, when non-zero. When zero,
* the system monotonic clock is used. Units: monotonic milliseconds. */
uint32_t 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. */
int support_fin_ack;
};
#define G_MAXUINT32 ((uint32_t) 0xffffffff)
#define LARGER(a,b) (((a) - (b) - 1) < (G_MAXUINT32 >> 1))
#define LARGER_OR_EQUAL(a,b) (((a) - (b)) < (G_MAXUINT32 >> 1))
#define SMALLER(a,b) LARGER ((b),(a))
#define SMALLER_OR_EQUAL(a,b) LARGER_OR_EQUAL ((b),(a))
/* properties */
enum
{
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
};
#if 0
static void ptcp_get_property (GObject *object, uint32_t property_id,
GValue *value, GParamSpec *pspec);
static void ptcp_set_property (GObject *object, uint32_t property_id,
const GValue *value, GParamSpec *pspec);
static void ptcp_finalize (GObject *object);
#endif
static void queue_connect_message (ptcp_socket_t *self);
static uint32_t queue (ptcp_socket_t *self, const char *data,
uint32_t len, TcpFlags flags);
static ptcp_write_result_t packet(ptcp_socket_t *self, uint32_t seq,
TcpFlags flags, uint32_t offset, uint32_t len, uint32_t now);
static int parse (ptcp_socket_t *self,
const uint8_t *_header_buf, size_t header_buf_len,
const uint8_t *data_buf, size_t data_buf_len);
static int process(ptcp_socket_t *self, Segment *seg);
static int transmit(ptcp_socket_t *self, SSegment *sseg, uint32_t now);
static int attempt_send(ptcp_socket_t *self, SendFlags sflags);
static void closedown (ptcp_socket_t *self, uint32_t err,
ClosedownSource source);
static void adjustMTU(ptcp_socket_t *self);
static void parse_options (ptcp_socket_t *self, const uint8_t *data,
uint32_t len);
//static void resize_send_buffer (ptcp_socket_t *self, uint32_t new_size);
static void resize_receive_buffer (ptcp_socket_t *self, uint32_t new_size);
static void set_state (ptcp_socket_t *self, ptcp_state_t new_state);
static void set_state_established (ptcp_socket_t *self);
static void set_state_closed (ptcp_socket_t *self, uint32_t err);
static const char *ptcp_state_get_name (ptcp_state_t state);
static int ptcp_state_has_sent_fin (ptcp_state_t state);
static int ptcp_state_has_received_fin (ptcp_state_t state);
// The following logging is for detailed (packet-level) pseudotcp analysis only.
static ptcp_debug_level_t debug_level = PSEUDO_TCP_DEBUG_NONE;
#define DEBUG(...) (void *)0
void ptcp_set_debug_level(ptcp_debug_level_t level)
{
debug_level = level;
}
static int64_t get_monotonic_time(void)
{
struct timespec ts;
int result;
result = clock_gettime(CLOCK_MONOTONIC, &ts);
if(UNLIKELY(result != 0))
;
// DEBUG("GLib requires working CLOCK_MONOTONIC");
return (((int64_t) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
}
static uint32_t get_current_time(ptcp_socket_t *ps)
{
if (UNLIKELY(ps->current_time != 0))
return ps->current_time;
return get_monotonic_time () / 1000;
}
void ptcp_set_time(ptcp_socket_t *ps, uint32_t current_time)
{
ps->current_time = current_time;
}
static void ptcp_destroy(ptcp_socket_t *ps)
{
struct list_head *i, *next;
SSegment *sseg;
if (ps == NULL)
return;
while ((sseg = queue_pop_head(&ps->slist)))
free(sseg);
queue_clear(&ps->unsent_slist);
if (ps->rlist) {
list_for_each_safe(i, next, &ps->rlist->entry) {
RSegment *rseg = (RSegment *)container_of(i, list_t, entry);
free(rseg);
}
}
free(ps->rlist);
ps->rlist = NULL;
ptcp_fifo_clear(&ps->rbuf);
ptcp_fifo_clear(&ps->sbuf);
free(ps);
ps = NULL;
}
static void notify_clock(union sigval sv);
timer_t timeout_add(uint64_t msec, void (*func)(union sigval sv), void *data);
static ptcp_socket_t *ptcp_create(ptcp_callbacks_t *cbs)
{
ptcp_socket_t *ps = (ptcp_socket_t *)calloc(1, sizeof(ptcp_socket_t));
if (ps == NULL) {
loge("malloc failed!\n");
return NULL;
}
ps->timer_id = timeout_add(0, notify_clock, ps);
sem_init(&ps->sem, 0, 0);
ps->callbacks = *cbs;
ps->shutdown = SD_NONE;
ps->error = 0;
ps->rbuf_len = DEFAULT_RCV_BUF_SIZE;
ptcp_fifo_init(&ps->rbuf, ps->rbuf_len);
ps->sbuf_len = DEFAULT_SND_BUF_SIZE;
ptcp_fifo_init(&ps->sbuf, ps->sbuf_len);
ps->state = TCP_LISTEN;
ps->conv = 0;
queue_init(&ps->slist);
queue_init(&ps->unsent_slist);
ps->rcv_wnd = ps->rbuf_len;
ps->rwnd_scale = ps->swnd_scale = 0;
ps->snd_nxt = 0;
ps->snd_wnd = 1;
ps->snd_una = ps->rcv_nxt = 0;
ps->bReadEnable = TRUE;
ps->bWriteEnable = FALSE;
ps->t_ack = 0;
ps->msslevel = 0;
ps->largest = 0;
ps->mss = MIN_PACKET - PACKET_OVERHEAD;
ps->mtu_advise = MAX_PACKET;
ps->rto_base = 0;
ps->cwnd = 2 * ps->mss;
ps->ssthresh = ps->rbuf_len;
ps->lastrecv = ps->lastsend = ps->last_traffic = 0;
ps->bOutgoing = FALSE;
ps->dup_acks = 0;
ps->recover = 0;
ps->ts_recent = ps->ts_lastack = 0;
ps->rx_rto = DEF_RTO;
ps->rx_srtt = ps->rx_rttvar = 0;
ps->ack_delay = DEFAULT_ACK_DELAY;
ps->use_nagling = !DEFAULT_NO_DELAY;
ps->support_wnd_scale = TRUE;
ps->support_fin_ack = TRUE;
return ps;
}
static void queue_connect_message(ptcp_socket_t *ps)
{
uint8_t buf[8];
size_t size = 0;
buf[size++] = CTL_CONNECT;
if (ps->support_wnd_scale) {
buf[size++] = TCP_OPT_WND_SCALE;
buf[size++] = 1;
buf[size++] = ps->rwnd_scale;
}
if (ps->support_fin_ack) {
buf[size++] = TCP_OPT_FIN_ACK;
buf[size++] = 1; /* option length; zero is invalid (RFC 1122, §4.2.2.5) */
buf[size++] = 0; /* currently unused */
}
ps->snd_wnd = size;
queue(ps, (char *)buf, size, FLAG_CTL);
}
static void queue_fin_message(ptcp_socket_t *ps)
{
assert(ps->support_fin_ack);
/* FIN segments are always zero-length. */
queue(ps, "", 0, FLAG_FIN);
}
static void queue_rst_message(ptcp_socket_t *ps)
{
assert(ps->support_fin_ack);
/* RST segments are always zero-length. */
queue (ps, "", 0, FLAG_RST);
}
static int _ptcp_connect(ptcp_socket_t *p)
{
if (p->state != TCP_LISTEN) {
p->error = EINVAL;
return FALSE;
}
set_state(p, TCP_SYN_SENT);
queue_connect_message(p);
return attempt_send(p, sfNone);
}
void ptcp_notify_mtu(ptcp_socket_t *ps, uint16_t mtu)
{
ps->mtu_advise = mtu;
if (ps->state == TCP_ESTABLISHED) {
adjustMTU(ps);
}
}
void ptcp_notify_clock(ptcp_socket_t *ps)
{
uint32_t now = get_current_time(ps);
if (ps->state == TCP_CLOSED)
return;
/* If in the TIME-WAIT state, any delayed segments have passed and the
* connection can be considered closed from both ends.
* FIXME: This should probably actually compare a timestamp before
* operating. */
if (ps->support_fin_ack && ps->state == TCP_TIME_WAIT) {
// DEBUG (PSEUDO_TCP_DEBUG_NORMAL,
// "Notified clock in TIME-WAIT state; closing connection.");
set_state_closed (ps, 0);
}
/* If in the LAST-ACK state, resend the FIN because it hasn’t been ACKed yet.
* FIXME: This should probably actually compare a timestamp before
* operating. */
if (ps->support_fin_ack && ps->state == TCP_LAST_ACK) {
// DEBUG (PSEUDO_TCP_DEBUG_NORMAL,
// "Notified clock in LAST-ACK state; resending FIN segment.");
queue_fin_message (ps);
attempt_send (ps, sfFin);
}
// Check if it's time to retransmit a segment
if (ps->rto_base &&
(time_diff(ps->rto_base + ps->rx_rto, now) <= 0)) {
if (queue_get_length (&ps->slist) == 0) {
// DEBUG(PSEUDO_TCP_DEBUG_NORMAL, "not reached");
} else {
// Note: (ps->slist.front().xmit == 0)) {
// retransmit segments
uint32_t nInFlight;
uint32_t rto_limit;
// DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "timeout retransmit (rto: %d) "
// "(rto_base: %d) (now: %d) (dup_acks: %d)",
// ps->rx_rto, ps->rto_base, now, (uint32_t) ps->dup_acks);
if (!transmit(ps, queue_peek_head (&ps->slist), now)) {
closedown (ps, ECONNABORTED, CLOSEDOWN_LOCAL);
return;
}
nInFlight = ps->snd_nxt - ps->snd_una;
ps->ssthresh = max(nInFlight / 2, 2 * ps->mss);
//LOG(LS_INFO) << "ps->ssthresh: " << ps->ssthresh << " nInFlight: " << nInFlight << " ps->mss: " << ps->mss;
ps->cwnd = ps->mss;
// Back off retransmit timer. Note: the limit is lower when connecting.
rto_limit = (ps->state < TCP_ESTABLISHED) ? DEF_RTO : MAX_RTO;
ps->rx_rto = min(rto_limit, ps->rx_rto * 2);
ps->rto_base = now;
}
}
// Check if it's time to probe closed windows
if ((ps->snd_wnd == 0)
&& (time_diff(ps->lastsend + ps->rx_rto, now) <= 0)) {
if (time_diff(now, ps->lastrecv) >= 15000) {
closedown (ps, ECONNABORTED, CLOSEDOWN_LOCAL);
return;
}
// probe the window
packet(ps, ps->snd_nxt - 1, 0, 0, 0, now);
ps->lastsend = now;
// back off retransmit timer
ps->rx_rto = min(MAX_RTO, ps->rx_rto * 2);
}
// Check if it's time to send delayed acks
if (ps->t_ack && (time_diff(ps->t_ack + ps->ack_delay, now) <= 0)) {
packet(ps, ps->snd_nxt, 0, 0, 0, now);
}
}
int ptcp_notify_packet(ptcp_socket_t *ps, const char *buffer, uint32_t len)
{
int retval;
if (len > MAX_PACKET) {
//LOG_F(WARNING) << "packet too large";
return FALSE;
} else if (len < HEADER_SIZE) {
//LOG_F(WARNING) << "packet too small";
return FALSE;
}
/* Hold a reference to the ptcp_socket_t during parsing, since it may be
* closed from within a callback. */
// g_object_ref (ps);
retval = parse (ps, (uint8_t *) buffer, HEADER_SIZE,
(uint8_t *) buffer + HEADER_SIZE, len - HEADER_SIZE);
// g_object_unref (ps);
return retval;
}
/* Assume there are two buffers in the given #NiceInputMessage: a 24-byte one
* containing the header, and a bigger one for the data. */
#if 0
int
ptcp_notify_message (ptcp_socket_t *ps,
NiceInputMessage *message)
{
int retval;
assert_cmpuint (message->n_buffers, >, 0);
if (message->n_buffers == 1)
return ptcp_notify_packet (ps, message->buffers[0].buffer,
message->buffers[0].size);
assert_cmpuint (message->n_buffers, ==, 2);
assert_cmpuint (message->buffers[0].size, ==, HEADER_SIZE);
if (message->length > MAX_PACKET) {
//LOG_F(WARNING) << "packet too large";
return FALSE;
} else if (message->length < HEADER_SIZE) {
//LOG_F(WARNING) << "packet too small";
return FALSE;
}
/* Hold a reference to the ptcp_socket_t during parsing, since it may be
* closed from within a callback. */
// g_object_ref (self);
retval = parse (ps, message->buffers[0].buffer, message->buffers[0].size,
message->buffers[1].buffer, message->length - message->buffers[0].size);
// g_object_unref (self);
return retval;
}
#endif
int
ptcp_get_next_clock(ptcp_socket_t *ps, uint64_t *timeout)
{
uint32_t now = get_current_time (ps);
size_t snd_buffered;
uint32_t closed_timeout;
if (ps->shutdown == SD_FORCEFUL) {
if (ps->support_fin_ack) {
// DEBUG (PSEUDO_TCP_DEBUG_NORMAL,
// "‘Forceful’ shutdown used when FIN-ACK support is enabled");
}
/* Transition to the CLOSED state. */
closedown (ps, 0, CLOSEDOWN_REMOTE);
return FALSE;
}
snd_buffered = ptcp_fifo_get_buffered (&ps->sbuf);
if ((ps->shutdown == SD_GRACEFUL)
&& ((ps->state != TCP_ESTABLISHED)
|| ((snd_buffered == 0) && (ps->t_ack == 0)))) {
if (ps->support_fin_ack) {
// DEBUG (PSEUDO_TCP_DEBUG_NORMAL,
// "‘Graceful’ shutdown used when FIN-ACK support is enabled");
}
/* Transition to the CLOSED state. */
closedown (ps, 0, CLOSEDOWN_REMOTE);
return FALSE;
}
/* FIN-ACK support. The timeout for closing the socket if nothing is received
* varies depending on whether the socket is waiting in the TIME-WAIT state
* for delayed segments to pass.
*
* See: http://vincent.bernat.im/en/blog/2014-tcp-time-wait-state-linux.html
*/
closed_timeout = CLOSED_TIMEOUT;
if (ps->support_fin_ack && ps->state == TCP_TIME_WAIT)
closed_timeout = TIME_WAIT_TIMEOUT;
if (ps->support_fin_ack && ps->state == TCP_CLOSED) {
return FALSE;
}
if (*timeout == 0 || *timeout < now)
*timeout = now + closed_timeout;
if (ps->support_fin_ack && ps->state == TCP_TIME_WAIT) {
*timeout = min (*timeout, now + TIME_WAIT_TIMEOUT);
return TRUE;
}
if (ps->state == TCP_CLOSED && !ps->support_fin_ack) {
*timeout = min (*timeout, now + CLOSED_TIMEOUT);
return TRUE;
}
*timeout = min (*timeout, now + DEFAULT_TIMEOUT);
if (ps->t_ack) {
*timeout = min(*timeout, ps->t_ack + ps->ack_delay);
}
if (ps->rto_base) {
*timeout = min(*timeout, ps->rto_base + ps->rx_rto);
}
if (ps->snd_wnd == 0) {
*timeout = min(*timeout, ps->lastsend + ps->rx_rto);
}
return TRUE;
}
int
ptcp_recv(ptcp_socket_t *ps, void *buffer, size_t len)
{
size_t bytesread;
size_t available_space;
/* Received a FIN from the peer, so return 0. RFC 793, §3.5, Case 2. */
if (ps->support_fin_ack &&
(ps->shutdown_reads ||
ptcp_state_has_received_fin (ps->state))) {
return 0;
}
/* Return 0 if FIN-ACK is not supported but the socket has been closed. */
if (!ps->support_fin_ack && ptcp_is_closed (ps)) {
return 0;
}
/* Return ENOTCONN if FIN-ACK is not supported and the connection is not
* ESTABLISHED. */
if (!ps->support_fin_ack && ps->state != TCP_ESTABLISHED) {
ps->error = ENOTCONN;
return -1;
}
if (len == 0)
return 0;
bytesread = ptcp_fifo_read (&ps->rbuf, (uint8_t *) buffer, len);
// If there's no data in |m_rbuf|.
if (bytesread == 0) {
ps->bReadEnable = TRUE;
ps->error = EWOULDBLOCK;
return -1;
}
available_space = ptcp_fifo_get_write_remaining (&ps->rbuf);
if (available_space - ps->rcv_wnd >=
min (ps->rbuf_len / 2, ps->mss)) {
// !?! Not sure about this was closed business
int bWasClosed = (ps->rcv_wnd == 0);
ps->rcv_wnd = available_space;
if (bWasClosed) {
attempt_send(ps, sfImmediateAck);
}
}
return bytesread;
}
int
ptcp_send(ptcp_socket_t *ps, const void * buffer, size_t len)