Debian Codegraph @

third-party/libhv-v1.3.3/event/kcp/ikcp.c

raw symbols SCIP
1 //=====================================================================
2 //
3 // KCP - A Better ARQ Protocol Implementation
4 // skywind3000 (at) gmail.com, 2010-2011
5 //
6 // Features:
7 // + Average RTT reduce 30% - 40% vs traditional ARQ like tcp.
8 // + Maximum RTT reduce three times vs tcp.
9 // + Lightweight, distributed as a single source file.
10 //
11 //=====================================================================
12 #include "ikcp.h"
13
14 #include <stddef.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <stdarg.h>
18 #include <stdio.h>
19
20
21
22 //=====================================================================
23 // KCP BASIC
24 //=====================================================================
25 const IUINT32 IKCP_RTO_NDL = 30; // no delay min rto
26 const IUINT32 IKCP_RTO_MIN = 100; // normal min rto
27 const IUINT32 IKCP_RTO_DEF = 200;
28 const IUINT32 IKCP_RTO_MAX = 60000;
29 const IUINT32 IKCP_CMD_PUSH = 81; // cmd: push data
30 const IUINT32 IKCP_CMD_ACK = 82; // cmd: ack
31 const IUINT32 IKCP_CMD_WASK = 83; // cmd: window probe (ask)
32 const IUINT32 IKCP_CMD_WINS = 84; // cmd: window size (tell)
33 const IUINT32 IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK
34 const IUINT32 IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS
35 const IUINT32 IKCP_WND_SND = 32;
36 const IUINT32 IKCP_WND_RCV = 128; // must >= max fragment size
37 const IUINT32 IKCP_MTU_DEF = 1400;
38 const IUINT32 IKCP_ACK_FAST = 3;
39 const IUINT32 IKCP_INTERVAL = 100;
40 const IUINT32 IKCP_OVERHEAD = 24;
41 const IUINT32 IKCP_DEADLINK = 20;
42 const IUINT32 IKCP_THRESH_INIT = 2;
43 const IUINT32 IKCP_THRESH_MIN = 2;
44 const IUINT32 IKCP_PROBE_INIT = 7000; // 7 secs to probe window size
45 const IUINT32 IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window
46 const IUINT32 IKCP_FASTACK_LIMIT = 5; // max times to trigger fastack
47
48
49 //---------------------------------------------------------------------
50 // encode / decode
51 //---------------------------------------------------------------------
52
53 /* encode 8 bits unsigned int */
54 static inline char *ikcp_encode8u(char *p, unsigned char c)
55 {
56 *(unsigned char*)p++ = c;
57 return p;
58 }
59
60 /* decode 8 bits unsigned int */
61 static inline const char *ikcp_decode8u(const char *p, unsigned char *c)
62 {
63 *c = *(unsigned char*)p++;
64 return p;
65 }
66
67 /* encode 16 bits unsigned int (lsb) */
68 static inline char *ikcp_encode16u(char *p, unsigned short w)
69 {
70 #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
71 *(unsigned char*)(p + 0) = (w & 255);
72 *(unsigned char*)(p + 1) = (w >> 8);
73 #else
74 memcpy(p, &w, 2);
75 #endif
76 p += 2;
77 return p;
78 }
79
80 /* decode 16 bits unsigned int (lsb) */
81 static inline const char *ikcp_decode16u(const char *p, unsigned short *w)
82 {
83 #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
84 *w = *(const unsigned char*)(p + 1);
85 *w = *(const unsigned char*)(p + 0) + (*w << 8);
86 #else
87 memcpy(w, p, 2);
88 #endif
89 p += 2;
90 return p;
91 }
92
93 /* encode 32 bits unsigned int (lsb) */
94 static inline char *ikcp_encode32u(char *p, IUINT32 l)
95 {
96 #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
97 *(unsigned char*)(p + 0) = (unsigned char)((l >> 0) & 0xff);
98 *(unsigned char*)(p + 1) = (unsigned char)((l >> 8) & 0xff);
99 *(unsigned char*)(p + 2) = (unsigned char)((l >> 16) & 0xff);
100 *(unsigned char*)(p + 3) = (unsigned char)((l >> 24) & 0xff);
101 #else
102 memcpy(p, &l, 4);
103 #endif
104 p += 4;
105 return p;
106 }
107
108 /* decode 32 bits unsigned int (lsb) */
109 static inline const char *ikcp_decode32u(const char *p, IUINT32 *l)
110 {
111 #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
112 *l = *(const unsigned char*)(p + 3);
113 *l = *(const unsigned char*)(p + 2) + (*l << 8);
114 *l = *(const unsigned char*)(p + 1) + (*l << 8);
115 *l = *(const unsigned char*)(p + 0) + (*l << 8);
116 #else
117 memcpy(l, p, 4);
118 #endif
119 p += 4;
120 return p;
121 }
122
123 static inline IUINT32 _imin_(IUINT32 a, IUINT32 b) {
124 return a <= b ? a : b;
125 }
126
127 static inline IUINT32 _imax_(IUINT32 a, IUINT32 b) {
128 return a >= b ? a : b;
129 }
130
131 static inline IUINT32 _ibound_(IUINT32 lower, IUINT32 middle, IUINT32 upper)
132 {
133 return _imin_(_imax_(lower, middle), upper);
134 }
135
136 static inline long _itimediff(IUINT32 later, IUINT32 earlier)
137 {
138 return ((IINT32)(later - earlier));
139 }
140
141 //---------------------------------------------------------------------
142 // manage segment
143 //---------------------------------------------------------------------
144 typedef struct IKCPSEG IKCPSEG;
145
146 static void* (*ikcp_malloc_hook)(size_t) = NULL;
147 static void (*ikcp_free_hook)(void *) = NULL;
148
149 // internal malloc
150 static void* ikcp_malloc(size_t size) {
151 if (ikcp_malloc_hook)
152 return ikcp_malloc_hook(size);
153 return malloc(size);
154 }
155
156 // internal free
157 static void ikcp_free(void *ptr) {
158 if (ikcp_free_hook) {
159 ikcp_free_hook(ptr);
160 } else {
161 free(ptr);
162 }
163 }
164
165 // redefine allocator
166 void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*))
167 {
168 ikcp_malloc_hook = new_malloc;
169 ikcp_free_hook = new_free;
170 }
171
172 // allocate a new kcp segment
173 static IKCPSEG* ikcp_segment_new(ikcpcb *kcp, int size)
174 {
175 return (IKCPSEG*)ikcp_malloc(sizeof(IKCPSEG) + size);
176 }
177
178 // delete a segment
179 static void ikcp_segment_delete(ikcpcb *kcp, IKCPSEG *seg)
180 {
181 ikcp_free(seg);
182 }
183
184 // write log
185 void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...)
186 {
187 char buffer[1024];
188 va_list argptr;
189 if ((mask & kcp->logmask) == 0 || kcp->writelog == 0) return;
190 va_start(argptr, fmt);
191 vsprintf(buffer, fmt, argptr);
192 va_end(argptr);
193 kcp->writelog(buffer, kcp, kcp->user);
194 }
195
196 // check log mask
197 static int ikcp_canlog(const ikcpcb *kcp, int mask)
198 {
199 if ((mask & kcp->logmask) == 0 || kcp->writelog == NULL) return 0;
200 return 1;
201 }
202
203 // output segment
204 static int ikcp_output(ikcpcb *kcp, const void *data, int size)
205 {
206 assert(kcp);
207 assert(kcp->output);
208 if (ikcp_canlog(kcp, IKCP_LOG_OUTPUT)) {
209 ikcp_log(kcp, IKCP_LOG_OUTPUT, "[RO] %ld bytes", (long)size);
210 }
211 if (size == 0) return 0;
212 return kcp->output((const char*)data, size, kcp, kcp->user);
213 }
214
215 // output queue
216 void ikcp_qprint(const char *name, const struct IQUEUEHEAD *head)
217 {
218 #if 0
219 const struct IQUEUEHEAD *p;
220 printf("<%s>: [", name);
221 for (p = head->next; p != head; p = p->next) {
222 const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node);
223 printf("(%lu %d)", (unsigned long)seg->sn, (int)(seg->ts % 10000));
224 if (p->next != head) printf(",");
225 }
226 printf("]\n");
227 #endif
228 }
229
230
231 //---------------------------------------------------------------------
232 // create a new kcpcb
233 //---------------------------------------------------------------------
234 ikcpcb* ikcp_create(IUINT32 conv, void *user)
235 {
236 ikcpcb *kcp = (ikcpcb*)ikcp_malloc(sizeof(struct IKCPCB));
237 if (kcp == NULL) return NULL;
238 kcp->conv = conv;
239 kcp->user = user;
240 kcp->snd_una = 0;
241 kcp->snd_nxt = 0;
242 kcp->rcv_nxt = 0;
243 kcp->ts_recent = 0;
244 kcp->ts_lastack = 0;
245 kcp->ts_probe = 0;
246 kcp->probe_wait = 0;
247 kcp->snd_wnd = IKCP_WND_SND;
248 kcp->rcv_wnd = IKCP_WND_RCV;
249 kcp->rmt_wnd = IKCP_WND_RCV;
250 kcp->cwnd = 0;
251 kcp->incr = 0;
252 kcp->probe = 0;
253 kcp->mtu = IKCP_MTU_DEF;
254 kcp->mss = kcp->mtu - IKCP_OVERHEAD;
255 kcp->stream = 0;
256
257 kcp->buffer = (char*)ikcp_malloc((kcp->mtu + IKCP_OVERHEAD) * 3);
258 if (kcp->buffer == NULL) {
259 ikcp_free(kcp);
260 return NULL;
261 }
262
263 iqueue_init(&kcp->snd_queue);
264 iqueue_init(&kcp->rcv_queue);
265 iqueue_init(&kcp->snd_buf);
266 iqueue_init(&kcp->rcv_buf);
267 kcp->nrcv_buf = 0;
268 kcp->nsnd_buf = 0;
269 kcp->nrcv_que = 0;
270 kcp->nsnd_que = 0;
271 kcp->state = 0;
272 kcp->acklist = NULL;
273 kcp->ackblock = 0;
274 kcp->ackcount = 0;
275 kcp->rx_srtt = 0;
276 kcp->rx_rttval = 0;
277 kcp->rx_rto = IKCP_RTO_DEF;
278 kcp->rx_minrto = IKCP_RTO_MIN;
279 kcp->current = 0;
280 kcp->interval = IKCP_INTERVAL;
281 kcp->ts_flush = IKCP_INTERVAL;
282 kcp->nodelay = 0;
283 kcp->updated = 0;
284 kcp->logmask = 0;
285 kcp->ssthresh = IKCP_THRESH_INIT;
286 kcp->fastresend = 0;
287 kcp->fastlimit = IKCP_FASTACK_LIMIT;
288 kcp->nocwnd = 0;
289 kcp->xmit = 0;
290 kcp->dead_link = IKCP_DEADLINK;
291 kcp->output = NULL;
292 kcp->writelog = NULL;
293
294 return kcp;
295 }
296
297
298 //---------------------------------------------------------------------
299 // release a new kcpcb
300 //---------------------------------------------------------------------
301 void ikcp_release(ikcpcb *kcp)
302 {
303 assert(kcp);
304 if (kcp) {
305 IKCPSEG *seg;
306 while (!iqueue_is_empty(&kcp->snd_buf)) {
307 seg = iqueue_entry(kcp->snd_buf.next, IKCPSEG, node);
308 iqueue_del(&seg->node);
309 ikcp_segment_delete(kcp, seg);
310 }
311 while (!iqueue_is_empty(&kcp->rcv_buf)) {
312 seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
313 iqueue_del(&seg->node);
314 ikcp_segment_delete(kcp, seg);
315 }
316 while (!iqueue_is_empty(&kcp->snd_queue)) {
317 seg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node);
318 iqueue_del(&seg->node);
319 ikcp_segment_delete(kcp, seg);
320 }
321 while (!iqueue_is_empty(&kcp->rcv_queue)) {
322 seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node);
323 iqueue_del(&seg->node);
324 ikcp_segment_delete(kcp, seg);
325 }
326 if (kcp->buffer) {
327 ikcp_free(kcp->buffer);
328 }
329 if (kcp->acklist) {
330 ikcp_free(kcp->acklist);
331 }
332
333 kcp->nrcv_buf = 0;
334 kcp->nsnd_buf = 0;
335 kcp->nrcv_que = 0;
336 kcp->nsnd_que = 0;
337 kcp->ackcount = 0;
338 kcp->buffer = NULL;
339 kcp->acklist = NULL;
340 ikcp_free(kcp);
341 }
342 }
343
344
345 //---------------------------------------------------------------------
346 // set output callback, which will be invoked by kcp
347 //---------------------------------------------------------------------
348 void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len,
349 ikcpcb *kcp, void *user))
350 {
351 kcp->output = output;
352 }
353
354
355 //---------------------------------------------------------------------
356 // user/upper level recv: returns size, returns below zero for EAGAIN
357 //---------------------------------------------------------------------
358 int ikcp_recv(ikcpcb *kcp, char *buffer, int len)
359 {
360 struct IQUEUEHEAD *p;
361 int ispeek = (len < 0)? 1 : 0;
362 int peeksize;
363 int recover = 0;
364 IKCPSEG *seg;
365 assert(kcp);
366
367 if (iqueue_is_empty(&kcp->rcv_queue))
368 return -1;
369
370 if (len < 0) len = -len;
371
372 peeksize = ikcp_peeksize(kcp);
373
374 if (peeksize < 0)
375 return -2;
376
377 if (peeksize > len)
378 return -3;
379
380 if (kcp->nrcv_que >= kcp->rcv_wnd)
381 recover = 1;
382
383 // merge fragment
384 for (len = 0, p = kcp->rcv_queue.next; p != &kcp->rcv_queue; ) {
385 int fragment;
386 seg = iqueue_entry(p, IKCPSEG, node);
387 p = p->next;
388
389 if (buffer) {
390 memcpy(buffer, seg->data, seg->len);
391 buffer += seg->len;
392 }
393
394 len += seg->len;
395 fragment = seg->frg;
396
397 if (ikcp_canlog(kcp, IKCP_LOG_RECV)) {
398 ikcp_log(kcp, IKCP_LOG_RECV, "recv sn=%lu", (unsigned long)seg->sn);
399 }
400
401 if (ispeek == 0) {
402 iqueue_del(&seg->node);
403 ikcp_segment_delete(kcp, seg);
404 kcp->nrcv_que--;
405 }
406
407 if (fragment == 0)
408 break;
409 }
410
411 assert(len == peeksize);
412
413 // move available data from rcv_buf -> rcv_queue
414 while (! iqueue_is_empty(&kcp->rcv_buf)) {
415 seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
416 if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) {
417 iqueue_del(&seg->node);
418 kcp->nrcv_buf--;
419 iqueue_add_tail(&seg->node, &kcp->rcv_queue);
420 kcp->nrcv_que++;
421 kcp->rcv_nxt++;
422 } else {
423 break;
424 }
425 }
426
427 // fast recover
428 if (kcp->nrcv_que < kcp->rcv_wnd && recover) {
429 // ready to send back IKCP_CMD_WINS in ikcp_flush
430 // tell remote my window size
431 kcp->probe |= IKCP_ASK_TELL;
432 }
433
434 return len;
435 }
436
437
438 //---------------------------------------------------------------------
439 // peek data size
440 //---------------------------------------------------------------------
441 int ikcp_peeksize(const ikcpcb *kcp)
442 {
443 struct IQUEUEHEAD *p;
444 IKCPSEG *seg;
445 int length = 0;
446
447 assert(kcp);
448
449 if (iqueue_is_empty(&kcp->rcv_queue)) return -1;
450
451 seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node);
452 if (seg->frg == 0) return seg->len;
453
454 if (kcp->nrcv_que < seg->frg + 1) return -1;
455
456 for (p = kcp->rcv_queue.next; p != &kcp->rcv_queue; p = p->next) {
457 seg = iqueue_entry(p, IKCPSEG, node);
458 length += seg->len;
459 if (seg->frg == 0) break;
460 }
461
462 return length;
463 }
464
465
466 //---------------------------------------------------------------------
467 // user/upper level send, returns below zero for error
468 //---------------------------------------------------------------------
469 int ikcp_send(ikcpcb *kcp, const char *buffer, int len)
470 {
471 IKCPSEG *seg;
472 int count, i;
473
474 assert(kcp->mss > 0);
475 if (len < 0) return -1;
476
477 // append to previous segment in streaming mode (if possible)
478 if (kcp->stream != 0) {
479 if (!iqueue_is_empty(&kcp->snd_queue)) {
480 IKCPSEG *old = iqueue_entry(kcp->snd_queue.prev, IKCPSEG, node);
481 if (old->len < kcp->mss) {
482 int capacity = kcp->mss - old->len;
483 int extend = (len < capacity)? len : capacity;
484 seg = ikcp_segment_new(kcp, old->len + extend);
485 assert(seg);
486 if (seg == NULL) {
487 return -2;
488 }
489 iqueue_add_tail(&seg->node, &kcp->snd_queue);
490 memcpy(seg->data, old->data, old->len);
491 if (buffer) {
492 memcpy(seg->data + old->len, buffer, extend);
493 buffer += extend;
494 }
495 seg->len = old->len + extend;
496 seg->frg = 0;
497 len -= extend;
498 iqueue_del_init(&old->node);
499 ikcp_segment_delete(kcp, old);
500 }
501 }
502 if (len <= 0) {
503 return 0;
504 }
505 }
506
507 if (len <= (int)kcp->mss) count = 1;
508 else count = (len + kcp->mss - 1) / kcp->mss;
509
510 if (count >= (int)IKCP_WND_RCV) return -2;
511
512 if (count == 0) count = 1;
513
514 // fragment
515 for (i = 0; i < count; i++) {
516 int size = len > (int)kcp->mss ? (int)kcp->mss : len;
517 seg = ikcp_segment_new(kcp, size);
518 assert(seg);
519 if (seg == NULL) {
520 return -2;
521 }
522 if (buffer && len > 0) {
523 memcpy(seg->data, buffer, size);
524 }
525 seg->len = size;
526 seg->frg = (kcp->stream == 0)? (count - i - 1) : 0;
527 iqueue_init(&seg->node);
528 iqueue_add_tail(&seg->node, &kcp->snd_queue);
529 kcp->nsnd_que++;
530 if (buffer) {
531 buffer += size;
532 }
533 len -= size;
534 }
535
536 return 0;
537 }
538
539
540 //---------------------------------------------------------------------
541 // parse ack
542 //---------------------------------------------------------------------
543 static void ikcp_update_ack(ikcpcb *kcp, IINT32 rtt)
544 {
545 IINT32 rto = 0;
546 if (kcp->rx_srtt == 0) {
547 kcp->rx_srtt = rtt;
548 kcp->rx_rttval = rtt / 2;
549 } else {
550 long delta = rtt - kcp->rx_srtt;
551 if (delta < 0) delta = -delta;
552 kcp->rx_rttval = (3 * kcp->rx_rttval + delta) / 4;
553 kcp->rx_srtt = (7 * kcp->rx_srtt + rtt) / 8;
554 if (kcp->rx_srtt < 1) kcp->rx_srtt = 1;
555 }
556 rto = kcp->rx_srtt + _imax_(kcp->interval, 4 * kcp->rx_rttval);
557 kcp->rx_rto = _ibound_(kcp->rx_minrto, rto, IKCP_RTO_MAX);
558 }
559
560 static void ikcp_shrink_buf(ikcpcb *kcp)
561 {
562 struct IQUEUEHEAD *p = kcp->snd_buf.next;
563 if (p != &kcp->snd_buf) {
564 IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
565 kcp->snd_una = seg->sn;
566 } else {
567 kcp->snd_una = kcp->snd_nxt;
568 }
569 }
570
571 static void ikcp_parse_ack(ikcpcb *kcp, IUINT32 sn)
572 {
573 struct IQUEUEHEAD *p, *next;
574
575 if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0)
576 return;
577
578 for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) {
579 IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
580 next = p->next;
581 if (sn == seg->sn) {
582 iqueue_del(p);
583 ikcp_segment_delete(kcp, seg);
584 kcp->nsnd_buf--;
585 break;
586 }
587 if (_itimediff(sn, seg->sn) < 0) {
588 break;
589 }
590 }
591 }
592
593 static void ikcp_parse_una(ikcpcb *kcp, IUINT32 una)
594 {
595 struct IQUEUEHEAD *p, *next;
596 for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) {
597 IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
598 next = p->next;
599 if (_itimediff(una, seg->sn) > 0) {
600 iqueue_del(p);
601 ikcp_segment_delete(kcp, seg);
602 kcp->nsnd_buf--;
603 } else {
604 break;
605 }
606 }
607 }
608
609 static void ikcp_parse_fastack(ikcpcb *kcp, IUINT32 sn, IUINT32 ts)
610 {
611 struct IQUEUEHEAD *p, *next;
612
613 if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0)
614 return;
615
616 for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) {
617 IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
618 next = p->next;
619 if (_itimediff(sn, seg->sn) < 0) {
620 break;
621 }
622 else if (sn != seg->sn) {
623 #ifndef IKCP_FASTACK_CONSERVE
624 seg->fastack++;
625 #else
626 if (_itimediff(ts, seg->ts) >= 0)
627 seg->fastack++;
628 #endif
629 }
630 }
631 }
632
633
634 //---------------------------------------------------------------------
635 // ack append
636 //---------------------------------------------------------------------
637 static void ikcp_ack_push(ikcpcb *kcp, IUINT32 sn, IUINT32 ts)
638 {
639 IUINT32 newsize = kcp->ackcount + 1;
640 IUINT32 *ptr;
641
642 if (newsize > kcp->ackblock) {
643 IUINT32 *acklist;
644 IUINT32 newblock;
645
646 for (newblock = 8; newblock < newsize; newblock <<= 1);
647 acklist = (IUINT32*)ikcp_malloc(newblock * sizeof(IUINT32) * 2);
648
649 if (acklist == NULL) {
650 assert(acklist != NULL);
651 abort();
652 }
653
654 if (kcp->acklist != NULL) {
655 IUINT32 x;
656 for (x = 0; x < kcp->ackcount; x++) {
657 acklist[x * 2 + 0] = kcp->acklist[x * 2 + 0];
658 acklist[x * 2 + 1] = kcp->acklist[x * 2 + 1];
659 }
660 ikcp_free(kcp->acklist);
661 }
662
663 kcp->acklist = acklist;
664 kcp->ackblock = newblock;
665 }
666
667 ptr = &kcp->acklist[kcp->ackcount * 2];
668 ptr[0] = sn;
669 ptr[1] = ts;
670 kcp->ackcount++;
671 }
672
673 static void ikcp_ack_get(const ikcpcb *kcp, int p, IUINT32 *sn, IUINT32 *ts)
674 {
675 if (sn) sn[0] = kcp->acklist[p * 2 + 0];
676 if (ts) ts[0] = kcp->acklist[p * 2 + 1];
677 }
678
679
680 //---------------------------------------------------------------------
681 // parse data
682 //---------------------------------------------------------------------
683 void ikcp_parse_data(ikcpcb *kcp, IKCPSEG *newseg)
684 {
685 struct IQUEUEHEAD *p, *prev;
686 IUINT32 sn = newseg->sn;
687 int repeat = 0;
688
689 if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) >= 0 ||
690 _itimediff(sn, kcp->rcv_nxt) < 0) {
691 ikcp_segment_delete(kcp, newseg);
692 return;
693 }
694
695 for (p = kcp->rcv_buf.prev; p != &kcp->rcv_buf; p = prev) {
696 IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
697 prev = p->prev;
698 if (seg->sn == sn) {
699 repeat = 1;
700 break;
701 }
702 if (_itimediff(sn, seg->sn) > 0) {
703 break;
704 }
705 }
706
707 if (repeat == 0) {
708 iqueue_init(&newseg->node);
709 iqueue_add(&newseg->node, p);
710 kcp->nrcv_buf++;
711 } else {
712 ikcp_segment_delete(kcp, newseg);
713 }
714
715 #if 0
716 ikcp_qprint("rcvbuf", &kcp->rcv_buf);
717 printf("rcv_nxt=%lu\n", kcp->rcv_nxt);
718 #endif
719
720 // move available data from rcv_buf -> rcv_queue
721 while (! iqueue_is_empty(&kcp->rcv_buf)) {
722 IKCPSEG *seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
723 if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) {
724 iqueue_del(&seg->node);
725 kcp->nrcv_buf--;
726 iqueue_add_tail(&seg->node, &kcp->rcv_queue);
727 kcp->nrcv_que++;
728 kcp->rcv_nxt++;
729 } else {
730 break;
731 }
732 }
733
734 #if 0
735 ikcp_qprint("queue", &kcp->rcv_queue);
736 printf("rcv_nxt=%lu\n", kcp->rcv_nxt);
737 #endif
738
739 #if 1
740 // printf("snd(buf=%d, queue=%d)\n", kcp->nsnd_buf, kcp->nsnd_que);
741 // printf("rcv(buf=%d, queue=%d)\n", kcp->nrcv_buf, kcp->nrcv_que);
742 #endif
743 }
744
745
746 //---------------------------------------------------------------------
747 // input data
748 //---------------------------------------------------------------------
749 int ikcp_input(ikcpcb *kcp, const char *data, long size)
750 {
751 IUINT32 prev_una = kcp->snd_una;
752 IUINT32 maxack = 0, latest_ts = 0;
753 int flag = 0;
754
755 if (ikcp_canlog(kcp, IKCP_LOG_INPUT)) {
756 ikcp_log(kcp, IKCP_LOG_INPUT, "[RI] %d bytes", (int)size);
757 }
758
759 if (data == NULL || (int)size < (int)IKCP_OVERHEAD) return -1;
760
761 while (1) {
762 IUINT32 ts, sn, len, una, conv;
763 IUINT16 wnd;
764 IUINT8 cmd, frg;
765 IKCPSEG *seg;
766
767 if (size < (int)IKCP_OVERHEAD) break;
768
769 data = ikcp_decode32u(data, &conv);
770 if (conv != kcp->conv) return -1;
771
772 data = ikcp_decode8u(data, &cmd);
773 data = ikcp_decode8u(data, &frg);
774 data = ikcp_decode16u(data, &wnd);
775 data = ikcp_decode32u(data, &ts);
776 data = ikcp_decode32u(data, &sn);
777 data = ikcp_decode32u(data, &una);
778 data = ikcp_decode32u(data, &len);
779
780 size -= IKCP_OVERHEAD;
781
782 if ((long)size < (long)len || (int)len < 0) return -2;
783
784 if (cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK &&
785 cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS)
786 return -3;
787
788 kcp->rmt_wnd = wnd;
789 ikcp_parse_una(kcp, una);
790 ikcp_shrink_buf(kcp);
791
792 if (cmd == IKCP_CMD_ACK) {
793 if (_itimediff(kcp->current, ts) >= 0) {
794 ikcp_update_ack(kcp, _itimediff(kcp->current, ts));
795 }
796 ikcp_parse_ack(kcp, sn);
797 ikcp_shrink_buf(kcp);
798 if (flag == 0) {
799 flag = 1;
800 maxack = sn;
801 latest_ts = ts;
802 } else {
803 if (_itimediff(sn, maxack) > 0) {
804 #ifndef IKCP_FASTACK_CONSERVE
805 maxack = sn;
806 latest_ts = ts;
807 #else
808 if (_itimediff(ts, latest_ts) > 0) {
809 maxack = sn;
810 latest_ts = ts;
811 }
812 #endif
813 }
814 }
815 if (ikcp_canlog(kcp, IKCP_LOG_IN_ACK)) {
816 ikcp_log(kcp, IKCP_LOG_IN_ACK,
817 "input ack: sn=%lu rtt=%ld rto=%ld", (unsigned long)sn,
818 (long)_itimediff(kcp->current, ts),
819 (long)kcp->rx_rto);
820 }
821 }
822 else if (cmd == IKCP_CMD_PUSH) {
823 if (ikcp_canlog(kcp, IKCP_LOG_IN_DATA)) {
824 ikcp_log(kcp, IKCP_LOG_IN_DATA,
825 "input psh: sn=%lu ts=%lu", (unsigned long)sn, (unsigned long)ts);
826 }
827 if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) < 0) {
828 ikcp_ack_push(kcp, sn, ts);
829 if (_itimediff(sn, kcp->rcv_nxt) >= 0) {
830 seg = ikcp_segment_new(kcp, len);
831 seg->conv = conv;
832 seg->cmd = cmd;
833 seg->frg = frg;
834 seg->wnd = wnd;
835 seg->ts = ts;
836 seg->sn = sn;
837 seg->una = una;
838 seg->len = len;
839
840 if (len > 0) {
841 memcpy(seg->data, data, len);
842 }
843
844 ikcp_parse_data(kcp, seg);
845 }
846 }
847 }
848 else if (cmd == IKCP_CMD_WASK) {
849 // ready to send back IKCP_CMD_WINS in ikcp_flush
850 // tell remote my window size
851 kcp->probe |= IKCP_ASK_TELL;
852 if (ikcp_canlog(kcp, IKCP_LOG_IN_PROBE)) {
853 ikcp_log(kcp, IKCP_LOG_IN_PROBE, "input probe");
854 }
855 }
856 else if (cmd == IKCP_CMD_WINS) {
857 // do nothing
858 if (ikcp_canlog(kcp, IKCP_LOG_IN_WINS)) {
859 ikcp_log(kcp, IKCP_LOG_IN_WINS,
860 "input wins: %lu", (unsigned long)(wnd));
861 }
862 }
863 else {
864 return -3;
865 }
866
867 data += len;
868 size -= len;
869 }
870
871 if (flag != 0) {
872 ikcp_parse_fastack(kcp, maxack, latest_ts);
873 }
874
875 if (_itimediff(kcp->snd_una, prev_una) > 0) {
876 if (kcp->cwnd < kcp->rmt_wnd) {
877 IUINT32 mss = kcp->mss;
878 if (kcp->cwnd < kcp->ssthresh) {
879 kcp->cwnd++;
880 kcp->incr += mss;
881 } else {
882 if (kcp->incr < mss) kcp->incr = mss;
883 kcp->incr += (mss * mss) / kcp->incr + (mss / 16);
884 if ((kcp->cwnd + 1) * mss <= kcp->incr) {
885 #if 1
886 kcp->cwnd = (kcp->incr + mss - 1) / ((mss > 0)? mss : 1);
887 #else
888 kcp->cwnd++;
889 #endif
890 }
891 }
892 if (kcp->cwnd > kcp->rmt_wnd) {
893 kcp->cwnd = kcp->rmt_wnd;
894 kcp->incr = kcp->rmt_wnd * mss;
895 }
896 }
897 }
898
899 return 0;
900 }
901
902
903 //---------------------------------------------------------------------
904 // ikcp_encode_seg
905 //---------------------------------------------------------------------
906 static char *ikcp_encode_seg(char *ptr, const IKCPSEG *seg)
907 {
908 ptr = ikcp_encode32u(ptr, seg->conv);
909 ptr = ikcp_encode8u(ptr, (IUINT8)seg->cmd);
910 ptr = ikcp_encode8u(ptr, (IUINT8)seg->frg);
911 ptr = ikcp_encode16u(ptr, (IUINT16)seg->wnd);
912 ptr = ikcp_encode32u(ptr, seg->ts);
913 ptr = ikcp_encode32u(ptr, seg->sn);
914 ptr = ikcp_encode32u(ptr, seg->una);
915 ptr = ikcp_encode32u(ptr, seg->len);
916 return ptr;
917 }
918
919 static int ikcp_wnd_unused(const ikcpcb *kcp)
920 {
921 if (kcp->nrcv_que < kcp->rcv_wnd) {
922 return kcp->rcv_wnd - kcp->nrcv_que;
923 }
924 return 0;
925 }
926
927
928 //---------------------------------------------------------------------
929 // ikcp_flush
930 //---------------------------------------------------------------------
931 void ikcp_flush(ikcpcb *kcp)
932 {
933 IUINT32 current = kcp->current;
934 char *buffer = kcp->buffer;
935 char *ptr = buffer;
936 int count, size, i;
937 IUINT32 resent, cwnd;
938 IUINT32 rtomin;
939 struct IQUEUEHEAD *p;
940 int change = 0;
941 int lost = 0;
942 IKCPSEG seg;
943
944 // 'ikcp_update' haven't been called.
945 if (kcp->updated == 0) return;
946
947 seg.conv = kcp->conv;
948 seg.cmd = IKCP_CMD_ACK;
949 seg.frg = 0;
950 seg.wnd = ikcp_wnd_unused(kcp);
951 seg.una = kcp->rcv_nxt;
952 seg.len = 0;
953 seg.sn = 0;
954 seg.ts = 0;
955
956 // flush acknowledges
957 count = kcp->ackcount;
958 for (i = 0; i < count; i++) {
959 size = (int)(ptr - buffer);
960 if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
961 ikcp_output(kcp, buffer, size);
962 ptr = buffer;
963 }
964 ikcp_ack_get(kcp, i, &seg.sn, &seg.ts);
965 ptr = ikcp_encode_seg(ptr, &seg);
966 }
967
968 kcp->ackcount = 0;
969
970 // probe window size (if remote window size equals zero)
971 if (kcp->rmt_wnd == 0) {
972 if (kcp->probe_wait == 0) {
973 kcp->probe_wait = IKCP_PROBE_INIT;
974 kcp->ts_probe = kcp->current + kcp->probe_wait;
975 }
976 else {
977 if (_itimediff(kcp->current, kcp->ts_probe) >= 0) {
978 if (kcp->probe_wait < IKCP_PROBE_INIT)
979 kcp->probe_wait = IKCP_PROBE_INIT;
980 kcp->probe_wait += kcp->probe_wait / 2;
981 if (kcp->probe_wait > IKCP_PROBE_LIMIT)
982 kcp->probe_wait = IKCP_PROBE_LIMIT;
983 kcp->ts_probe = kcp->current + kcp->probe_wait;
984 kcp->probe |= IKCP_ASK_SEND;
985 }
986 }
987 } else {
988 kcp->ts_probe = 0;
989 kcp->probe_wait = 0;
990 }
991
992 // flush window probing commands
993 if (kcp->probe & IKCP_ASK_SEND) {
994 seg.cmd = IKCP_CMD_WASK;
995 size = (int)(ptr - buffer);
996 if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
997 ikcp_output(kcp, buffer, size);
998 ptr = buffer;
999 }
1000 ptr = ikcp_encode_seg(ptr, &seg);
1001 }
1002
1003 // flush window probing commands
1004 if (kcp->probe & IKCP_ASK_TELL) {
1005 seg.cmd = IKCP_CMD_WINS;
1006 size = (int)(ptr - buffer);
1007 if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
1008 ikcp_output(kcp, buffer, size);
1009 ptr = buffer;
1010 }
1011 ptr = ikcp_encode_seg(ptr, &seg);
1012 }
1013
1014 kcp->probe = 0;
1015
1016 // calculate window size
1017 cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd);
1018 if (kcp->nocwnd == 0) cwnd = _imin_(kcp->cwnd, cwnd);
1019
1020 // move data from snd_queue to snd_buf
1021 while (_itimediff(kcp->snd_nxt, kcp->snd_una + cwnd) < 0) {
1022 IKCPSEG *newseg;
1023 if (iqueue_is_empty(&kcp->snd_queue)) break;
1024
1025 newseg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node);
1026
1027 iqueue_del(&newseg->node);
1028 iqueue_add_tail(&newseg->node, &kcp->snd_buf);
1029 kcp->nsnd_que--;
1030 kcp->nsnd_buf++;
1031
1032 newseg->conv = kcp->conv;
1033 newseg->cmd = IKCP_CMD_PUSH;
1034 newseg->wnd = seg.wnd;
1035 newseg->ts = current;
1036 newseg->sn = kcp->snd_nxt++;
1037 newseg->una = kcp->rcv_nxt;
1038 newseg->resendts = current;
1039 newseg->rto = kcp->rx_rto;
1040 newseg->fastack = 0;
1041 newseg->xmit = 0;
1042 }
1043
1044 // calculate resent
1045 resent = (kcp->fastresend > 0)? (IUINT32)kcp->fastresend : 0xffffffff;
1046 rtomin = (kcp->nodelay == 0)? (kcp->rx_rto >> 3) : 0;
1047
1048 // flush data segments
1049 for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) {
1050 IKCPSEG *segment = iqueue_entry(p, IKCPSEG, node);
1051 int needsend = 0;
1052 if (segment->xmit == 0) {
1053 needsend = 1;
1054 segment->xmit++;
1055 segment->rto = kcp->rx_rto;
1056 segment->resendts = current + segment->rto + rtomin;
1057 }
1058 else if (_itimediff(current, segment->resendts) >= 0) {
1059 needsend = 1;
1060 segment->xmit++;
1061 kcp->xmit++;
1062 if (kcp->nodelay == 0) {
1063 segment->rto += _imax_(segment->rto, (IUINT32)kcp->rx_rto);
1064 } else {
1065 IINT32 step = (kcp->nodelay < 2)?
1066 ((IINT32)(segment->rto)) : kcp->rx_rto;
1067 segment->rto += step / 2;
1068 }
1069 segment->resendts = current + segment->rto;
1070 lost = 1;
1071 }
1072 else if (segment->fastack >= resent) {
1073 if ((int)segment->xmit <= kcp->fastlimit ||
1074 kcp->fastlimit <= 0) {
1075 needsend = 1;
1076 segment->xmit++;
1077 segment->fastack = 0;
1078 segment->resendts = current + segment->rto;
1079 change++;
1080 }
1081 }
1082
1083 if (needsend) {
1084 int need;
1085 segment->ts = current;
1086 segment->wnd = seg.wnd;
1087 segment->una = kcp->rcv_nxt;
1088
1089 size = (int)(ptr - buffer);
1090 need = IKCP_OVERHEAD + segment->len;
1091
1092 if (size + need > (int)kcp->mtu) {
1093 ikcp_output(kcp, buffer, size);
1094 ptr = buffer;
1095 }
1096
1097 ptr = ikcp_encode_seg(ptr, segment);
1098
1099 if (segment->len > 0) {
1100 memcpy(ptr, segment->data, segment->len);
1101 ptr += segment->len;
1102 }
1103
1104 if (segment->xmit >= kcp->dead_link) {
1105 kcp->state = (IUINT32)-1;
1106 }
1107 }
1108 }
1109
1110 // flash remain segments
1111 size = (int)(ptr - buffer);
1112 if (size > 0) {
1113 ikcp_output(kcp, buffer, size);
1114 }
1115
1116 // update ssthresh
1117 if (change) {
1118 IUINT32 inflight = kcp->snd_nxt - kcp->snd_una;
1119 kcp->ssthresh = inflight / 2;
1120 if (kcp->ssthresh < IKCP_THRESH_MIN)
1121 kcp->ssthresh = IKCP_THRESH_MIN;
1122 kcp->cwnd = kcp->ssthresh + resent;
1123 kcp->incr = kcp->cwnd * kcp->mss;
1124 }
1125
1126 if (lost) {
1127 kcp->ssthresh = cwnd / 2;
1128 if (kcp->ssthresh < IKCP_THRESH_MIN)
1129 kcp->ssthresh = IKCP_THRESH_MIN;
1130 kcp->cwnd = 1;
1131 kcp->incr = kcp->mss;
1132 }
1133
1134 if (kcp->cwnd < 1) {
1135 kcp->cwnd = 1;
1136 kcp->incr = kcp->mss;
1137 }
1138 }
1139
1140
1141 //---------------------------------------------------------------------
1142 // update state (call it repeatedly, every 10ms-100ms), or you can ask
1143 // ikcp_check when to call it again (without ikcp_input/_send calling).
1144 // 'current' - current timestamp in millisec.
1145 //---------------------------------------------------------------------
1146 void ikcp_update(ikcpcb *kcp, IUINT32 current)
1147 {
1148 IINT32 slap;
1149
1150 kcp->current = current;
1151
1152 if (kcp->updated == 0) {
1153 kcp->updated = 1;
1154 kcp->ts_flush = kcp->current;
1155 }
1156
1157 slap = _itimediff(kcp->current, kcp->ts_flush);
1158
1159 if (slap >= 10000 || slap < -10000) {
1160 kcp->ts_flush = kcp->current;
1161 slap = 0;
1162 }
1163
1164 if (slap >= 0) {
1165 kcp->ts_flush += kcp->interval;
1166 if (_itimediff(kcp->current, kcp->ts_flush) >= 0) {
1167 kcp->ts_flush = kcp->current + kcp->interval;
1168 }
1169 ikcp_flush(kcp);
1170 }
1171 }
1172
1173
1174 //---------------------------------------------------------------------
1175 // Determine when should you invoke ikcp_update:
1176 // returns when you should invoke ikcp_update in millisec, if there
1177 // is no ikcp_input/_send calling. you can call ikcp_update in that
1178 // time, instead of call update repeatly.
1179 // Important to reduce unnacessary ikcp_update invoking. use it to
1180 // schedule ikcp_update (eg. implementing an epoll-like mechanism,
1181 // or optimize ikcp_update when handling massive kcp connections)
1182 //---------------------------------------------------------------------
1183 IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current)
1184 {
1185 IUINT32 ts_flush = kcp->ts_flush;
1186 IINT32 tm_flush = 0x7fffffff;
1187 IINT32 tm_packet = 0x7fffffff;
1188 IUINT32 minimal = 0;
1189 struct IQUEUEHEAD *p;
1190
1191 if (kcp->updated == 0) {
1192 return current;
1193 }
1194
1195 if (_itimediff(current, ts_flush) >= 10000 ||
1196 _itimediff(current, ts_flush) < -10000) {
1197 ts_flush = current;
1198 }
1199
1200 if (_itimediff(current, ts_flush) >= 0) {
1201 return current;
1202 }
1203
1204 tm_flush = _itimediff(ts_flush, current);
1205
1206 for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) {
1207 const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node);
1208 IINT32 diff = _itimediff(seg->resendts, current);
1209 if (diff <= 0) {
1210 return current;
1211 }
1212 if (diff < tm_packet) tm_packet = diff;
1213 }
1214
1215 minimal = (IUINT32)(tm_packet < tm_flush ? tm_packet : tm_flush);
1216 if (minimal >= kcp->interval) minimal = kcp->interval;
1217
1218 return current + minimal;
1219 }
1220
1221
1222
1223 int ikcp_setmtu(ikcpcb *kcp, int mtu)
1224 {
1225 char *buffer;
1226 if (mtu < 50 || mtu < (int)IKCP_OVERHEAD)
1227 return -1;
1228 buffer = (char*)ikcp_malloc((mtu + IKCP_OVERHEAD) * 3);
1229 if (buffer == NULL)
1230 return -2;
1231 kcp->mtu = mtu;
1232 kcp->mss = kcp->mtu - IKCP_OVERHEAD;
1233 ikcp_free(kcp->buffer);
1234 kcp->buffer = buffer;
1235 return 0;
1236 }
1237
1238 int ikcp_interval(ikcpcb *kcp, int interval)
1239 {
1240 if (interval > 5000) interval = 5000;
1241 else if (interval < 10) interval = 10;
1242 kcp->interval = interval;
1243 return 0;
1244 }
1245
1246 int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc)
1247 {
1248 if (nodelay >= 0) {
1249 kcp->nodelay = nodelay;
1250 if (nodelay) {
1251 kcp->rx_minrto = IKCP_RTO_NDL;
1252 }
1253 else {
1254 kcp->rx_minrto = IKCP_RTO_MIN;
1255 }
1256 }
1257 if (interval >= 0) {
1258 if (interval > 5000) interval = 5000;
1259 else if (interval < 10) interval = 10;
1260 kcp->interval = interval;
1261 }
1262 if (resend >= 0) {
1263 kcp->fastresend = resend;
1264 }
1265 if (nc >= 0) {
1266 kcp->nocwnd = nc;
1267 }
1268 return 0;
1269 }
1270
1271
1272 int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd)
1273 {
1274 if (kcp) {
1275 if (sndwnd > 0) {
1276 kcp->snd_wnd = sndwnd;
1277 }
1278 if (rcvwnd > 0) { // must >= max fragment size
1279 kcp->rcv_wnd = _imax_(rcvwnd, IKCP_WND_RCV);
1280 }
1281 }
1282 return 0;
1283 }
1284
1285 int ikcp_waitsnd(const ikcpcb *kcp)
1286 {
1287 return kcp->nsnd_buf + kcp->nsnd_que;
1288 }
1289
1290
1291 // read conv
1292 IUINT32 ikcp_getconv(const void *ptr)
1293 {
1294 IUINT32 conv;
1295 ikcp_decode32u((const char*)ptr, &conv);
1296 return conv;
1297 }
1298
1299