summaryrefslogtreecommitdiff
path: root/src/mesh/gnunet-service-mesh_channel.c
blob: fef789d565fe99e2ba27bd781cfb6916a8b3d29a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
/*
     This file is part of GNUnet.
     (C) 2013 Christian Grothoff (and other contributing authors)

     GNUnet is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published
     by the Free Software Foundation; either version 3, or (at your
     option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
*/


#include "platform.h"
#include "gnunet_util_lib.h"

#include "gnunet_statistics_service.h"

#include "mesh_enc.h"
#include "mesh_protocol_enc.h"

#include "gnunet-service-mesh_channel.h"
#include "gnunet-service-mesh_local.h"
#include "gnunet-service-mesh_tunnel.h"
#include "gnunet-service-mesh_peer.h"

#define LOG(level, ...) GNUNET_log_from(level,"mesh-chn",__VA_ARGS__)

#define MESH_RETRANSMIT_TIME    GNUNET_TIME_UNIT_SECONDS
#define MESH_RETRANSMIT_MARGIN  4


/**
 * All the states a connection can be in.
 */
enum MeshChannelState
{
  /**
   * Uninitialized status, should never appear in operation.
   */
  MESH_CHANNEL_NEW,

  /**
   * Connection create message sent, waiting for ACK.
   */
  MESH_CHANNEL_SENT,

  /**
   * Connection confirmed, ready to carry traffic.
   */
  MESH_CHANNEL_READY,
};



/**
 * Info needed to retry a message in case it gets lost.
 */
struct MeshReliableMessage
{
    /**
     * Double linked list, FIFO style
     */
  struct MeshReliableMessage    *next;
  struct MeshReliableMessage    *prev;

    /**
     * Type of message (payload, channel management).
     */
  int16_t type;

    /**
     * Tunnel Reliability queue this message is in.
     */
  struct MeshChannelReliability  *rel;

    /**
     * ID of the message (ACK needed to free)
     */
  uint32_t                      mid;

    /**
     * When was this message issued (to calculate ACK delay)
     */
  struct GNUNET_TIME_Absolute   timestamp;

  /* struct GNUNET_MESH_Data with payload */
};


/**
 * Info about the traffic state for a client in a channel.
 */
struct MeshChannelReliability
{
    /**
     * Channel this is about.
     */
  struct MeshChannel *ch;

    /**
     * DLL of messages sent and not yet ACK'd.
     */
  struct MeshReliableMessage        *head_sent;
  struct MeshReliableMessage        *tail_sent;

    /**
     * DLL of messages received out of order.
     */
  struct MeshReliableMessage        *head_recv;
  struct MeshReliableMessage        *tail_recv;

    /**
     * Messages received.
     */
  unsigned int                      n_recv;

    /**
     * Next MID to use for outgoing traffic.
     */
  uint32_t                          mid_send;

    /**
     * Next MID expected for incoming traffic.
     */
  uint32_t                          mid_recv;

    /**
     * Can we send data to the client?
     */
  int                               client_ready;

  /**
   * Can the client send data to us?
   */
  int                               client_allowed;

    /**
     * Task to resend/poll in case no ACK is received.
     */
  GNUNET_SCHEDULER_TaskIdentifier   retry_task;

    /**
     * Counter for exponential backoff.
     */
  struct GNUNET_TIME_Relative       retry_timer;

    /**
     * How long does it usually take to get an ACK.
     */
  struct GNUNET_TIME_Relative       expected_delay;
};


/**
 * Struct containing all information regarding a channel to a remote client.
 */
struct MeshChannel
{
    /**
     * Tunnel this channel is in.
     */
  struct MeshTunnel3 *t;

    /**
     * Destination port of the channel.
     */
  uint32_t port;

    /**
     * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
     */
  MESH_ChannelNumber gid;

    /**
     * Local tunnel number for root (owner) client.
     * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
     */
  MESH_ChannelNumber lid_root;

    /**
     * Local tunnel number for local destination clients (incoming number)
     * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
     */
  MESH_ChannelNumber lid_dest;

    /**
     * Channel state.
     */
  enum MeshChannelState state;

    /**
     * Is the tunnel bufferless (minimum latency)?
     */
  int nobuffer;

    /**
     * Is the tunnel reliable?
     */
  int reliable;

    /**
     * Last time the channel was used
     */
  struct GNUNET_TIME_Absolute timestamp;

    /**
     * Client owner of the tunnel, if any
     */
  struct MeshClient *root;

    /**
     * Client destination of the tunnel, if any.
     */
  struct MeshClient *dest;

    /**
     * Flag to signal the destruction of the channel.
     * If this is set GNUNET_YES the channel will be destroyed
     * when the queue is empty.
     */
  int destroy;

    /**
     * Total messages pending for this channel, payload or not.
     */
  unsigned int pending_messages;

    /**
     * Reliability data.
     * Only present (non-NULL) at the owner of a tunnel.
     */
  struct MeshChannelReliability *root_rel;

    /**
     * Reliability data.
     * Only present (non-NULL) at the destination of a tunnel.
     */
  struct MeshChannelReliability *dest_rel;

};


/******************************************************************************/
/*******************************   GLOBALS  ***********************************/
/******************************************************************************/

/**
 * Global handle to the statistics service.
 */
extern struct GNUNET_STATISTICS_Handle *stats;

/**
 * Local peer own ID (memory efficient handle).
 */
extern GNUNET_PEER_Id myid;


/******************************************************************************/
/********************************   STATIC  ***********************************/
/******************************************************************************/

/**
 * Destroy a reliable message after it has been acknowledged, either by
 * direct mid ACK or bitfield. Updates the appropriate data structures and
 * timers and frees all memory.
 *
 * @param copy Message that is no longer needed: remote peer got it.
 * @param update_time Is the timing information relevant?
 *                    If this message is ACK in a batch the timing information
 *                    is skewed by the retransmission, count only for the
 *                    retransmitted message.
 */
static void
rel_message_free (struct MeshReliableMessage *copy, int update_time);

/**
 * We have received a message out of order, or the client is not ready.
 * Buffer it until we receive an ACK from the client or the missing
 * message from the channel.
 *
 * @param msg Message to buffer (MUST be of type MESH_DATA).
 * @param rel Reliability data to the corresponding direction.
 */
static void
add_buffered_data (const struct GNUNET_MESH_Data *msg,
                   struct MeshChannelReliability *rel)
{
  struct MeshReliableMessage *copy;
  struct MeshReliableMessage *prev;
  uint32_t mid;
  uint16_t size;

  size = ntohs (msg->header.size);
  mid = ntohl (msg->mid);

  LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);

  copy = GNUNET_malloc (sizeof (*copy) + size);
  copy->mid = mid;
  copy->rel = rel;
  copy->type = GNUNET_MESSAGE_TYPE_MESH_DATA;
  memcpy (&copy[1], msg, size);

  rel->n_recv++;

  // FIXME do something better than O(n), although n < 64...
  // FIXME start from the end (most messages are the latest ones)
  for (prev = rel->head_recv; NULL != prev; prev = prev->next)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
    if (GMC_is_pid_bigger (prev->mid, mid))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
      GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
                                          prev, copy);
      return;
    }
  }
    LOG (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
    GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
}

/**
 * Add a destination client to a channel, initializing all data structures
 * in the channel and the client.
 *
 * @param ch Channel to which add the destination.
 * @param c Client which to add to the channel.
 */
static void
add_destination (struct MeshChannel *ch, struct MeshClient *c)
{
  if (NULL != ch->dest)
  {
    GNUNET_break (0);
    return;
  }

  /* Assign local id as destination */
  ch->lid_dest = GML_get_next_chid (c);

  /* Store in client's hashmap */
  GML_channel_add (c, ch->lid_dest, ch);

  GNUNET_break (NULL == ch->dest_rel);
  ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
  ch->dest_rel->ch = ch;
  ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;

  ch->dest = c;
}


/**
 * Send data to a client.
 *
 * If the client is ready, send directly, otherwise buffer while listening
 * for a local ACK.
 *
 * @param ch Channel
 * @param msg Message.
 * @param fwd Is this a fwd (root->dest) message?
 */
static void
send_client_data (struct MeshChannel *ch,
                  const struct GNUNET_MESH_Data *msg,
                  int fwd)
{
  if (fwd)
  {
    if (ch->dest_rel->client_ready)
      GML_send_data (ch->dest, msg, ch->lid_dest);
    else
      add_buffered_data (msg, ch->dest_rel);
  }
  else
  {
    if (ch->root_rel->client_ready)
      GML_send_data (ch->root, msg, ch->lid_root);
    else
      add_buffered_data (msg, ch->root_rel);
  }
}


/**
 * Send a buffered message to the client, for in order delivery or
 * as result of client ACK.
 *
 * @param ch Channel on which to empty the message buffer.
 * @param c Client to send to.
 * @param fwd Is this to send FWD data?.
 */
static void
send_client_buffered_data (struct MeshChannel *ch,
                           struct MeshClient *c,
                           int fwd)
{
  struct MeshReliableMessage *copy;
  struct MeshChannelReliability *rel;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
  rel = fwd ? ch->dest_rel : ch->root_rel;
  if (GNUNET_NO == rel->client_ready)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
    return;
  }

  copy = rel->head_recv;
  /* We never buffer channel management messages */
  if (NULL != copy)
  {
    if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
    {
      struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];

      LOG (GNUNET_ERROR_TYPE_DEBUG,
           " have %u! now expecting %u\n",
           copy->mid, rel->mid_recv + 1);
      send_client_data (ch, msg, fwd);
      rel->n_recv--;
      rel->mid_recv++;
      GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
      GNUNET_free (copy);
    }
    else
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           " reliable && don't have %u, next is %u\n",
           rel->mid_recv,
           copy->mid);
      return;
    }
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
}


/**
 * Allow a client to send more data.
 *
 * In case the client was already allowed to send data, do nothing.
 *
 * @param ch Channel.
 * @param fwd Is this a FWD ACK? (FWD ACKs are sent to root)
 */
static void
send_client_ack (struct MeshChannel *ch, int fwd)
{
  struct MeshChannelReliability *rel = fwd ? ch->root_rel : ch->dest_rel;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "  sending %s ack to client on channel %s\n",
       fwd ? "FWD" : "BCK", GMCH_2s (ch));

  if (NULL == rel)
  {
    GNUNET_break (0);
    return;
  }

  if (GNUNET_YES == rel->client_allowed)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  already allowed\n");
    return;
  }
  rel->client_allowed = GNUNET_YES;

  GML_send_ack (fwd ? ch->root : ch->dest, fwd ? ch->lid_root : ch->lid_dest);
}


/**
 * Notify the root that the destination rejected the channel.
 *
 * @param ch Rejected channel.
 */
static void
send_client_nack (struct MeshChannel *ch)
{
  if (NULL == ch->root)
  {
    GNUNET_break (0);
    return;
  }
  GML_send_nack (ch->root, ch->lid_root);
}


/**
 * Destroy all reliable messages queued for a channel,
 * during a channel destruction.
 * Frees the reliability structure itself.
 *
 * @param rel Reliability data for a channel.
 */
static void
channel_rel_free_all (struct MeshChannelReliability *rel)
{
  struct MeshReliableMessage *copy;
  struct MeshReliableMessage *next;

  if (NULL == rel)
    return;

  for (copy = rel->head_recv; NULL != copy; copy = next)
  {
    next = copy->next;
    GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
    GNUNET_free (copy);
  }
  for (copy = rel->head_sent; NULL != copy; copy = next)
  {
    next = copy->next;
    GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
    GNUNET_free (copy);
  }
  if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
    GNUNET_SCHEDULER_cancel (rel->retry_task);
  GNUNET_free (rel);
}


/**
 * Mark future messages as ACK'd.
 *
 * @param rel Reliability data.
 * @param msg DataACK message with a bitfield of future ACK'd messages.
 */
static void
channel_rel_free_sent (struct MeshChannelReliability *rel,
                       const struct GNUNET_MESH_DataACK *msg)
{
  struct MeshReliableMessage *copy;
  struct MeshReliableMessage *next;
  uint64_t bitfield;
  uint64_t mask;
  uint32_t mid;
  uint32_t target;
  unsigned int i;

  bitfield = msg->futures;
  mid = ntohl (msg->mid);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
              "!!! free_sent_reliable %u %llX\n",
              mid, bitfield);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
              " rel %p, head %p\n",
              rel, rel->head_sent);
  for (i = 0, copy = rel->head_sent;
       i < 64 && NULL != copy && 0 != bitfield;
       i++)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
                " trying bit %u (mid %u)\n",
                i, mid + i + 1);
    mask = 0x1LL << i;
    if (0 == (bitfield & mask))
     continue;

    LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
    /* Bit was set, clear the bit from the bitfield */
    bitfield &= ~mask;

    /* The i-th bit was set. Do we have that copy? */
    /* Skip copies with mid < target */
    target = mid + i + 1;
    LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
    while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
     copy = copy->next;

    /* Did we run out of copies? (previously freed, it's ok) */
    if (NULL == copy)
    {
     LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
     return;
    }

    /* Did we overshoot the target? (previously freed, it's ok) */
    if (GMC_is_pid_bigger (copy->mid, target))
    {
     LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
     continue;
    }

    /* Now copy->mid == target, free it */
    next = copy->next;
    rel_message_free (copy, GNUNET_YES);
    copy = next;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
}


/**
 * We haven't received an ACK after a certain time: restransmit the message.
 *
 * @param cls Closure (MeshReliableMessage with the message to restransmit)
 * @param tc TaskContext.
 */
static void
channel_retransmit_message (void *cls,
                            const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct MeshChannelReliability *rel = cls;
  struct MeshReliableMessage *copy;
  struct MeshChannel *ch;
  struct GNUNET_MESH_Data *payload;
  int fwd;

  rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    return;

  ch = rel->ch;
  copy = rel->head_sent;
  if (NULL == copy)
  {
    GNUNET_break (0);
    return;
  }

  /* Search the message to be retransmitted in the outgoing queue.
   * Check only the queue for the connection that is going to be used,
   * if the message is stuck in some other connection's queue we shouldn't
   * act upon it:
   * - cancelling it and sending the new one doesn't guarantee it's delivery,
   *   the old connection could be temporary stalled or the queue happened to
   *   be long at time of insertion.
   * - not sending the new one could cause terrible delays the old connection
   *   is stalled.
   */
//   FIXME access to queue elements is limited
  payload = (struct GNUNET_MESH_Data *) &copy[1];
  fwd = (rel == ch->root_rel);
//   c = GMT_get_connection (ch->t, fwd);
//   hop = connection_get_hop (c, fwd);
//   for (q = hop->queue_head; NULL != q; q = q->next)
//   {
//     if (ntohs (payload->header.type) == q->type && ch == q->ch)
//     {
//       struct GNUNET_MESH_Data *queued_data = q->cls;
// 
//       if (queued_data->mid == payload->mid)
//         break;
//     }
//   }

  /* Message not found in the queue that we are going to use. */
//   if (NULL == q)
//   {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);

    GMCH_send_prebuilt_message (&payload->header, ch, fwd);
    GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
//   }
//   else
//   {
//     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
//   }

  copy->timestamp = GNUNET_TIME_absolute_get();
  rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
  rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
                                                  &channel_retransmit_message,
                                                  cls);
}


/**
 * Destroy a reliable message after it has been acknowledged, either by
 * direct mid ACK or bitfield. Updates the appropriate data structures and
 * timers and frees all memory.
 *
 * @param copy Message that is no longer needed: remote peer got it.
 * @param update_time Is the timing information relevant?
 *                    If this message is ACK in a batch the timing information
 *                    is skewed by the retransmission, count only for the
 *                    retransmitted message.
 */
static void
rel_message_free (struct MeshReliableMessage *copy, int update_time)
{
  struct MeshChannelReliability *rel;
  struct GNUNET_TIME_Relative time;

  rel = copy->rel;
  LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
  if (update_time)
  {
    time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
    rel->expected_delay.rel_value_us *= 7;
    rel->expected_delay.rel_value_us += time.rel_value_us;
    rel->expected_delay.rel_value_us /= 8;
    LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
                GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
    LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
                GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
                                                        GNUNET_NO));
    rel->retry_timer = rel->expected_delay;
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! batch free, ignoring timing\n");
  }
  GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
  GNUNET_free (copy);
}


/**
 * Confirm we got a channel create.
 *
 * @param ch The channel to confirm.
 * @param fwd Should we send a FWD ACK? (going dest->root)
 */
static void
channel_send_ack (struct MeshChannel *ch, int fwd)
{
  struct GNUNET_MESH_ChannelManage msg;

  msg.header.size = htons (sizeof (msg));
  msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
              "  sending channel %s ack for channel %s\n",
              fwd ? "FWD" : "BCK", GMCH_2s (ch));

  msg.chid = htonl (ch->gid);
  GMCH_send_prebuilt_message (&msg.header, ch, !fwd);
}


/**
 * Notify that a channel create didn't succeed.
 *
 * @param ch The channel to reject.
 */
static void
channel_send_nack (struct MeshChannel *ch)
{
  struct GNUNET_MESH_ChannelManage msg;

  msg.header.size = htons (sizeof (msg));
  msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "  sending channel NACK for channel %s\n",
       GMCH_2s (ch));

  msg.chid = htonl (ch->gid);
  GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO);
}


/**
 * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
 *
 * @param ch Channel to mark as ready.
 * @param fwd Was the ACK message a FWD ACK? (dest->root, SYNACK)
 */
static void
channel_confirm (struct MeshChannel *ch, int fwd)
{
  struct MeshChannelReliability *rel;
  struct MeshReliableMessage *copy;
  struct MeshReliableMessage *next;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
              "  channel confirm %s %s:%X\n",
              fwd ? "FWD" : "BCK", GMT_2s (ch->t), ch->gid);
  ch->state = MESH_CHANNEL_READY;

  rel = fwd ? ch->root_rel : ch->dest_rel;
  rel->client_ready = GNUNET_YES;
  for (copy = rel->head_sent; NULL != copy; copy = next)
  {
    struct GNUNET_MessageHeader *msg;

    next = copy->next;
    msg = (struct GNUNET_MessageHeader *) &copy[1];
    if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
    {
      rel_message_free (copy, GNUNET_YES);
      /* TODO return? */
    }
  }
  send_client_ack (ch, fwd);

  /* In case of a FWD ACK (SYNACK) send a BCK ACK (ACK). */
  if (fwd)
    channel_send_ack (ch, !fwd);
}


/**
 * Save a copy to retransmit in case it gets lost.
 *
 * Initializes all needed callbacks and timers.
 *
 * @param ch Channel this message goes on.
 * @param msg Message to copy.
 * @param fwd Is this fwd traffic?
 */
static void
channel_save_copy (struct MeshChannel *ch,
                   const struct GNUNET_MessageHeader *msg,
                   int fwd)
{
  struct MeshChannelReliability *rel;
  struct MeshReliableMessage *copy;
  uint32_t mid;
  uint16_t type;
  uint16_t size;

  rel = fwd ? ch->root_rel : ch->dest_rel;
  mid = rel->mid_send - 1;
  type = ntohs (msg->type);
  size = ntohs (msg->size);

  LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u %s\n",
       mid, GNUNET_MESH_DEBUG_M2S (type));
  copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
  copy->mid = mid;
  copy->timestamp = GNUNET_TIME_absolute_get ();
  copy->rel = rel;
  copy->type = type;
  memcpy (&copy[1], msg, size);
  GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
  if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
  {
    rel->retry_timer =
        GNUNET_TIME_relative_multiply (rel->expected_delay,
                                        MESH_RETRANSMIT_MARGIN);
    rel->retry_task =
        GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
                                      &channel_retransmit_message,
                                      rel);
  }
}


/**
 * Destroy a channel and free all resources.
 *
 * @param ch Channel to destroy.
 */
static void
channel_destroy (struct MeshChannel *ch)
{
  struct MeshClient *c;

  if (NULL == ch)
    return;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
              GMT_2s (ch->t), ch->gid);
  GMCH_debug (ch);

  c = ch->root;
  if (NULL != c)
  {
    GML_channel_remove (c, ch->lid_root, ch);
  }

  c = ch->dest;
  if (NULL != c)
  {
    GML_channel_remove (c, ch->lid_dest, ch);
  }

  channel_rel_free_all (ch->root_rel);
  channel_rel_free_all (ch->dest_rel);

  GMT_remove_channel (ch->t, ch);
  GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);

  GNUNET_free (ch);
}


/**
 * Create a new channel.
 *
 * @param t Tunnel this channel is in.
 * @param owner Client that owns the channel, NULL for foreign channels.
 * @param lid_root Local ID for root client.
 *
 * @return A new initialized channel. NULL on error.
 */
static struct MeshChannel *
channel_new (struct MeshTunnel3 *t,
             struct MeshClient *owner,
             MESH_ChannelNumber lid_root)
{
  struct MeshChannel *ch;

  ch = GNUNET_new (struct MeshChannel);
  ch->root = owner;
  ch->lid_root = lid_root;
  ch->t = t;

  GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);

  if (NULL != owner)
  {
    ch->gid = GMT_get_next_chid (t);
    GML_channel_add (owner, lid_root, ch);
  }
  GMT_add_channel (t, ch);

  return ch;
}


/**
 * Set options in a channel, extracted from a bit flag field
 *
 * @param ch Channel to set options to.
 * @param options Bit array in host byte order.
 */
static void
channel_set_options (struct MeshChannel *ch, uint32_t options)
{
  ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
                 GNUNET_YES : GNUNET_NO;
  ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
                 GNUNET_YES : GNUNET_NO;
}

static int
is_loopback (const struct MeshChannel *ch)
{
  if (NULL != ch->t)
    return GMT_is_loopback (ch->t);

  return (NULL != ch->root && NULL != ch->dest);
}


/**
 * Handle a loopback message: call the appropriate handler for the message type.
 *
 * @param ch Channel this message is on.
 * @param msgh Message header.
 * @param fwd Is this FWD traffic?
 */
void
handle_loopback (struct MeshChannel *ch,
                 const struct GNUNET_MessageHeader *msgh,
                 int fwd)
{
  uint16_t type;

  type = ntohs (msgh->type);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Loopback %s %s message!\n",
       fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (type));

  switch (type)
  {
    case GNUNET_MESSAGE_TYPE_MESH_DATA:
      /* Don't send hop ACK, wait for client to ACK */
      GMCH_handle_data (ch, (struct GNUNET_MESH_Data *) msgh, fwd);
      break;

    case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
      GMCH_handle_data_ack (ch, (struct GNUNET_MESH_DataACK *) msgh, fwd);
      break;

    case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
      GMCH_handle_create (ch->t,
                          (struct GNUNET_MESH_ChannelCreate *) msgh);
      break;

    case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
      GMCH_handle_ack (ch,
                       (struct GNUNET_MESH_ChannelManage *) msgh,
                       fwd);
      break;

    case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
      GMCH_handle_nack (ch);
      break;

    case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
      GMCH_handle_destroy (ch,
                           (struct GNUNET_MESH_ChannelManage *) msgh,
                           fwd);
      break;

    default:
      GNUNET_break_op (0);
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "end-to-end message not known (%u)\n",
           ntohs (msgh->type));
  }
}



/******************************************************************************/
/********************************    API    ***********************************/
/******************************************************************************/


/**
 * Get channel ID.
 *
 * @param ch Channel.
 *
 * @return ID
 */
MESH_ChannelNumber
GMCH_get_id (const struct MeshChannel *ch)
{
  return ch->gid;
}


/**
 * Get the channel tunnel.
 *
 * @param ch Channel to get the tunnel from.
 *
 * @return tunnel of the channel.
 */
struct MeshTunnel3 *
GMCH_get_tunnel (const struct MeshChannel *ch)
{
  return ch->t;
}


/**
 * Get free buffer space towards the client on a specific channel.
 *
 * @param ch Channel.
 * @param fwd Is query about FWD traffic?
 *
 * @return Free buffer space [0 - 64]
 */
unsigned int
GMCH_get_buffer (struct MeshChannel *ch, int fwd)
{
  struct MeshChannelReliability *rel;

  rel = fwd ? ch->dest_rel : ch->root_rel;

  /* If rel is NULL it means that the end is not yet created,
   * most probably is a loopback channel at the point of sending
   * the ChannelCreate to itself.
   */
  if (NULL == rel)
    return 64;

  return (64 - rel->n_recv);
}


/**
 * Get flow control status of end point: is client allow to send?
 *
 * @param ch Channel.
 * @param fwd Is query about FWD traffic? (Request root status).
 *
 * @return #GNUNET_YES if client is allowed to send us data.
 */
int
GMCH_get_allowed (struct MeshChannel *ch, int fwd)
{
  struct MeshChannelReliability *rel;

  rel = fwd ? ch->root_rel : ch->dest_rel;

  return rel->client_allowed;
}


/**
 * Is the root client for this channel on this peer?
 *
 * @param ch Channel.
 * @param fwd Is this for fwd traffic?
 *
 * @return #GNUNET_YES in case it is.
 */
int
GMCH_is_origin (struct MeshChannel *ch, int fwd)
{
  struct MeshClient *c;

  c = fwd ? ch->root : ch->dest;
  return NULL != c;
}


/**
 * Is the destination client for this channel on this peer?
 *
 * @param ch Channel.
 * @param fwd Is this for fwd traffic?
 *
 * @return #GNUNET_YES in case it is.
 */
int
GMCH_is_terminal (struct MeshChannel *ch, int fwd)
{
  struct MeshClient *c;

  c = fwd ? ch->dest : ch->root;
  return NULL != c;
}


/**
 * Notify the destination client that a new incoming channel was created.
 *
 * @param ch Channel that was created.
 */
void
GMCH_send_create (struct MeshChannel *ch)
{
  uint32_t opt;

  if (NULL == ch->dest)
    return;

  opt = 0;
  opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
  opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
  GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
                           GMT_get_destination (ch->t));

}

/**
 * Notify a client that the channel is no longer valid.
 *
 * @param ch Channel that is destroyed.
 */
void
GMCH_send_destroy (struct MeshChannel *ch)
{
  struct GNUNET_MESH_ChannelManage msg;

  msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
  msg.header.size = htons (sizeof (msg));
  msg.chid = htonl (ch->gid);

  /* If root is not NULL, notify.
   * If it's NULL, check lid_root. When a local destroy comes in, root 
   * is set to NULL but lid_root is left untouched. In this case, do nothing,
   * the client is the one who reuqested the channel to be destroyed.
   */
  if (NULL != ch->root)
    GML_send_channel_destroy (ch->root, ch->lid_root);
  else if (0 == ch->lid_root)
    GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO);

  if (NULL != ch->dest)
    GML_send_channel_destroy (ch->dest, ch->lid_dest);
  else if (0 == ch->lid_dest)
    GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_YES);
}


/**
 * Send data on a channel.
 *
 * If the destination is local, send it to client, otherwise encrypt and
 * send to next hop.
 *
 * @param ch Channel
 * @param msg Message.
 * @param fwd Is this a fwd (root->dest) message?
 */
void
GMCH_send_data (struct MeshChannel *ch,
                const struct GNUNET_MESH_Data *msg,
                int fwd)
{
  if (GMCH_is_terminal (ch, fwd))
  {
    GML_send_data (fwd ? ch->dest : ch->root,
                   msg,
                   fwd ? ch->lid_dest : ch->lid_root);
  }
  else
  {
    GMT_send_prebuilt_message (&msg->header, ch->t, ch, fwd);
  }
}


/**
 * Send an end-to-end ACK message for the most recent in-sequence payload.
 *
 * If channel is not reliable, do nothing.
 *
 * @param ch Channel this is about.
 * @param fwd Is for FWD traffic? (ACK dest->owner)
 */
void
GMCH_send_data_ack (struct MeshChannel *ch, int fwd)
{
  struct GNUNET_MESH_DataACK msg;
  struct MeshChannelReliability *rel;
  struct MeshReliableMessage *copy;
  unsigned int delta;
  uint64_t mask;
  uint32_t ack;

  if (GNUNET_NO == ch->reliable)
  {
    return;
  }
  rel = fwd ? ch->dest_rel : ch->root_rel;
  ack = rel->mid_recv - 1;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
              "!!! Send DATA_ACK for %u\n",
              ack);

  msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA_ACK);
  msg.header.size = htons (sizeof (msg));
  msg.chid = htonl (ch->gid);
  msg.futures = 0;
  for (copy = rel->head_recv; NULL != copy; copy = copy->next)
  {
    if (copy->type != GNUNET_MESSAGE_TYPE_MESH_DATA)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "!!  Type %s, expected DATA\n",
           GNUNET_MESH_DEBUG_M2S (copy->type));
      continue;
    }
    if (copy->mid == ack + 1)
    {
      ack++;
      continue;
    }
    delta = copy->mid - (ack + 1);
    if (63 < delta)
      break;
    mask = 0x1LL << delta;
    msg.futures |= mask;
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         " !! setting bit for %u (delta %u) (%llX) -> %llX\n",
         copy->mid, delta, mask, msg.futures);
  }
  msg.mid = htonl (ack);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! final futures %llX\n", msg.futures);

  GMCH_send_prebuilt_message (&msg.header, ch, !fwd);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
}


/**
 * Allow a client to send us more data, in case it was choked.
 *
 * @param ch Channel.
 * @param fwd Is this about FWD traffic? (Root client).
 */
void
GMCH_allow_client (struct MeshChannel *ch, int fwd)
{
  struct MeshChannelReliability *rel;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH allow\n");

  if (MESH_CHANNEL_READY != ch->state)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " not ready yet!\n");
    return;
  }

  if (GNUNET_YES == ch->reliable)
  {
    rel = fwd ? ch->root_rel : ch->dest_rel;
    if (NULL == rel)
    {
      GNUNET_break (0);
      return;
    }
    if (NULL != rel->head_sent && 64 <= rel->mid_send - rel->head_sent->mid)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           " too big mid gap! Wait for ACK.\n");
      return;
    }
  }

  send_client_ack (ch, fwd);
}


/**
 * Log channel info.
 *
 * @param ch Channel.
 */
void
GMCH_debug (struct MeshChannel *ch)
{
  if (NULL == ch)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X (%p)\n",
              GMT_2s (ch->t), ch->gid, ch);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
              ch->root, ch->root_rel);
  if (NULL != ch->root)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->root));
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
                ch->root_rel->client_ready ? "YES" : "NO");
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  dest %p/%p\n",
              ch->dest, ch->dest_rel);
  if (NULL != ch->dest)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->dest));
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
                ch->dest_rel->client_ready ? "YES" : "NO");
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
  }
}


/**
 * Handle an ACK given by a client.
 *
 * Mark client as ready and send him any buffered data we could have for him.
 *
 * @param ch Channel.
 * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by dest and go BCK)
 */
void
GMCH_handle_local_ack (struct MeshChannel *ch, int fwd)
{
  struct MeshChannelReliability *rel;
  struct MeshClient *c;

  rel = fwd ? ch->dest_rel : ch->root_rel;
  c   = fwd ? ch->dest     : ch->root;

  rel->client_ready = GNUNET_YES;
  send_client_buffered_data (ch, c, fwd);
  if (is_loopback (ch))
  {
    unsigned int buffer;

    buffer = GMCH_get_buffer (ch, fwd);
    if (0 < buffer)
      GMCH_allow_client (ch, fwd);

    return;
  }
  GMT_send_connection_acks (ch->t);
}


/**
 * Handle data given by a client.
 *
 * Check whether the client is allowed to send in this tunnel, save if channel
 * is reliable and send an ACK to the client if there is still buffer space
 * in the tunnel.
 *
 * @param ch Channel.
 * @param c Client which sent the data.
 * @param message Message.
 * @param fwd Is this a FWD data?
 *
 * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
 */
int
GMCH_handle_local_data (struct MeshChannel *ch,
                        struct MeshClient *c,
                        struct GNUNET_MessageHeader *message,
                        int fwd)
{
  struct MeshChannelReliability *rel;
  struct GNUNET_MESH_Data *payload;
  size_t size = ntohs (message->size);
  uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
  unsigned char cbuf[p2p_size];

  /* Is the client in the channel? */
  if ( !( (fwd &&
           ch->root == c)
         ||
          (!fwd &&
           ch->dest == c) ) )
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  rel = fwd ? ch->root_rel : ch->dest_rel;

  if (GNUNET_NO == rel->client_allowed)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  rel->client_allowed = GNUNET_NO;

  /* Ok, everything is correct, send the message. */
  payload = (struct GNUNET_MESH_Data *) cbuf;
  payload->mid = htonl (rel->mid_send);
  rel->mid_send++;
  memcpy (&payload[1], message, size);
  payload->header.size = htons (p2p_size);
  payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
  payload->chid = htonl (ch->gid);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
  if (GNUNET_YES == ch->reliable)
    channel_save_copy (ch, &payload->header, fwd);
  GMCH_send_prebuilt_message (&payload->header, ch, fwd);

  if (is_loopback (ch))
  {
    if (GMCH_get_buffer (ch, fwd) > 0);
      send_client_ack (ch, fwd);

    return GNUNET_OK;
  }

  if (GMT_get_connections_buffer (ch->t) > 0)
  {
    send_client_ack (ch, fwd);
  }

  return GNUNET_OK;
}


/**
 * Handle a channel destroy requested by a client.
 *
 * Destroy the channel and the tunnel in case this was the last channel.
 *
 * @param ch Channel.
 * @param c Client that requested the destruction (to avoid notifying him).
 */
void
GMCH_handle_local_destroy (struct MeshChannel *ch,
                           struct MeshClient *c)
{
  struct MeshTunnel3 *t;

  /* Cleanup after the tunnel */
  if (c == ch->dest)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
    GML_client_delete_channel (c, ch, ch->lid_dest);
    ch->dest = NULL;
  }
  if (c == ch->root)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
    GML_client_delete_channel (c, ch, ch->lid_root);
    ch->root = NULL;
  }

  t = ch->t;
  GMCH_send_destroy (ch);
  channel_destroy (ch);
  GMT_destroy_if_empty (t);
}


/**
 * Handle a channel create requested by a client.
 *
 * Create the channel and the tunnel in case this was the first0 channel.
 *
 * @param c Client that requested the creation (will be the root).
 * @param msg Create Channel message.
 *
 * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
 */
int
GMCH_handle_local_create (struct MeshClient *c,
                          struct GNUNET_MESH_ChannelMessage *msg)
{
  struct MeshChannel *ch;
  struct MeshTunnel3 *t;
  struct MeshPeer *peer;
  MESH_ChannelNumber chid;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
              GNUNET_i2s (&msg->peer), ntohl (msg->port));
  chid = ntohl (msg->channel_id);

  /* Sanity check for duplicate channel IDs */
  if (NULL != GML_channel_get (c, chid))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  peer = GMP_get (&msg->peer);
  GMP_add_tunnel (peer);
  t = GMP_get_tunnel (peer);

  if (GMP_get_short_id (peer) == myid)
  {
    GMT_change_state (t, MESH_TUNNEL3_READY);
  }
  else
  {
    GMP_connect (peer);
  }

  /* Create channel */
  ch = channel_new (t, c, chid);
  if (NULL == ch)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  ch->port = ntohl (msg->port);
  channel_set_options (ch, ntohl (msg->opt));

  /* In unreliable channels, we'll use the DLL to buffer BCK data */
  ch->root_rel = GNUNET_new (struct MeshChannelReliability);
  ch->root_rel->ch = ch;
  ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;

  LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GMCH_2s (ch));

  /* Send create channel */
  {
    struct GNUNET_MESH_ChannelCreate msgcc;

    msgcc.header.size = htons (sizeof (msgcc));
    msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
    msgcc.chid = htonl (ch->gid);
    msgcc.port = msg->port;
    msgcc.opt = msg->opt;

    GMT_send_prebuilt_message (&msgcc.header, t, ch, GNUNET_YES);
  }
  return GNUNET_OK;
}


/**
 * Handler for mesh network payload traffic.
 *
 * @param ch Channel for the message.
 * @param msg Unencryted data message.
 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
 *            #GNUNET_YES if message is FWD on the respective channel (loopback)
 *            #GNUNET_NO if message is BCK on the respective channel (loopback)
 *            #GNUNET_SYSERR if message on a one-ended channel (remote)
 */
void
GMCH_handle_data (struct MeshChannel *ch,
                  const struct GNUNET_MESH_Data *msg,
                  int fwd)
{
  struct MeshChannelReliability *rel;
  struct MeshClient *c;
  uint32_t mid;

  /* If this is a remote (non-loopback) channel, find 'fwd'. */
  if (GNUNET_SYSERR == fwd)
  {
    if (is_loopback (ch))
    {
      /* It is a loopback channel after all... */
      GNUNET_break (0);
      return;
    }
    fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
  }

  /*  Initialize FWD/BCK data */
  c   = fwd ? ch->dest     : ch->root;
  rel = fwd ? ch->dest_rel : ch->root_rel;

  if (NULL == c)
  {
    GNUNET_break (0);
    return;
  }

  GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);

  mid = ntohl (msg->mid);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "!! got mid %u\n", mid);

  if (GNUNET_NO == ch->reliable ||
      ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
        GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
    if (GNUNET_YES == ch->reliable)
    {
      /* Is this the exact next expected messasge? */
      if (mid == rel->mid_recv)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
        rel->mid_recv++;
        send_client_data (ch, msg, fwd);
      }
      else
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
        add_buffered_data (msg, rel);
      }
    }
    else
    {
      /* Tunnel is unreliable: send to clients directly */
      /* FIXME: accept Out Of Order traffic */
      rel->mid_recv = mid + 1;
      send_client_data (ch, msg, fwd);
    }
  }
  else
  {
    GNUNET_break_op (0);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
                " MID %u not expected (%u - %u), dropping!\n",
                mid, rel->mid_recv, rel->mid_recv + 63);
  }

  GMCH_send_data_ack (ch, fwd);
}


/**
 * Handler for mesh network traffic end-to-end ACKs.
 *
 * @param ch Channel on which we got this message.
 * @param msg Data message.
 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
 *            #GNUNET_YES if message is FWD on the respective channel (loopback)
 *            #GNUNET_NO if message is BCK on the respective channel (loopback)
 *            #GNUNET_SYSERR if message on a one-ended channel (remote)
 */
void
GMCH_handle_data_ack (struct MeshChannel *ch,
                      const struct GNUNET_MESH_DataACK *msg,
                      int fwd)
{
  struct MeshChannelReliability *rel;
  struct MeshReliableMessage *copy;
  struct MeshReliableMessage *next;
  uint32_t ack;
  int work;

  /* If this is a remote (non-loopback) channel, find 'fwd'. */
  if (GNUNET_SYSERR == fwd)
  {
    if (is_loopback (ch))
    {
      /* It is a loopback channel after all... */
      GNUNET_break (0);
      return;
    }
    /* Inverted: if message came 'FWD' is a 'BCK ACK'. */
    fwd = (NULL != ch->dest) ? GNUNET_NO : GNUNET_YES;
  }

  ack = ntohl (msg->mid);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
       (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);

  if (GNUNET_YES == fwd)
  {
    rel = ch->root_rel;
  }
  else
  {
    rel = ch->dest_rel;
  }
  if (NULL == rel)
  {
    GNUNET_break_op (0);
    return;
  }

  /* Free ACK'd copies: no need to retransmit those anymore */
  for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
  {
    if (GMC_is_pid_bigger (copy->mid, ack))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
      channel_rel_free_sent (rel, msg);
      break;
    }
    work = GNUNET_YES;
    LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
    next = copy->next;
    rel_message_free (copy, GNUNET_YES);
  }

  /* ACK client if needed */
  GMCH_allow_client (ch, fwd);

  /* If some message was free'd, update the retransmission delay */
  if (GNUNET_YES == work)
  {
    if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
    {
      GNUNET_SCHEDULER_cancel (rel->retry_task);
      if (NULL == rel->head_sent)
      {
        rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
      }
      else
      {
        struct GNUNET_TIME_Absolute new_target;
        struct GNUNET_TIME_Relative delay;

        delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
                                               MESH_RETRANSMIT_MARGIN);
        new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
                                               delay);
        delay = GNUNET_TIME_absolute_get_remaining (new_target);
        rel->retry_task =
            GNUNET_SCHEDULER_add_delayed (delay,
                                          &channel_retransmit_message,
                                          rel);
      }
    }
    else
      GNUNET_break (0);
  }
}


/**
 * Handler for channel create messages.
 *
 * Does not have fwd parameter because it's always 'FWD': channel is incoming.
 *
 * @param t Tunnel this channel will be in.
 * @param msg Channel crate message.
 */
struct MeshChannel *
GMCH_handle_create (struct MeshTunnel3 *t,
                    const struct GNUNET_MESH_ChannelCreate *msg)
{
  MESH_ChannelNumber chid;
  struct MeshChannel *ch;
  struct MeshClient *c;
  uint32_t port;

  chid = ntohl (msg->chid);

  ch = GMT_get_channel (t, chid);
  if (NULL == ch)
  {
    /* Create channel */
    ch = channel_new (t, NULL, 0);
    ch->gid = chid;
  }
  channel_set_options (ch, ntohl (msg->opt));

  /* Find a destination client */
  port = ntohl (msg->port);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
  c = GML_client_get_by_port (port);
  if (NULL == c)
  {
    /* TODO send reject */
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
    if (is_loopback (ch))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback: destroy on handler\n");
      channel_send_nack (ch);
    }
    else
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "  not loopback: destroy now\n");
      channel_send_nack (ch);
      channel_destroy (ch);
    }
    return NULL;
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  client %p has port registered\n", c);
  }

  add_destination (ch, c);
  if (GNUNET_YES == ch->reliable)
    LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
  else
    LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Not Reliable\n");

  GMCH_send_create (ch);
  channel_send_ack (ch, GNUNET_YES);

  return ch;
}


/**
 * Handler for channel NACK messages.
 *
 * NACK messages always go dest -> root, no need for 'fwd' or 'msg' parameter.
 *
 * @param ch Channel.
 */
void
GMCH_handle_nack (struct MeshChannel *ch)
{
  send_client_nack (ch);
  channel_destroy (ch);
}


/**
 * Handler for channel ack messages.
 *
 * @param ch Channel.
 * @param msg Message.
 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
 *            #GNUNET_YES if message is FWD on the respective channel (loopback)
 *            #GNUNET_NO if message is BCK on the respective channel (loopback)
 *            #GNUNET_SYSERR if message on a one-ended channel (remote)
 */
void
GMCH_handle_ack (struct MeshChannel *ch,
                 const struct GNUNET_MESH_ChannelManage *msg,
                 int fwd)
{
  /* If this is a remote (non-loopback) channel, find 'fwd'. */
  if (GNUNET_SYSERR == fwd)
  {
    if (is_loopback (ch))
    {
      /* It is a loopback channel after all... */
      GNUNET_break (0);
      return;
    }
    fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
  }

  channel_confirm (ch, !fwd);
}


/**
 * Handler for channel destroy messages.
 *
 * @param ch Channel to be destroyed of.
 * @param msg Message.
 * @param fwd Is this message fwd? This only is meaningful in loopback channels.
 *            #GNUNET_YES if message is FWD on the respective channel (loopback)
 *            #GNUNET_NO if message is BCK on the respective channel (loopback)
 *            #GNUNET_SYSERR if message on a one-ended channel (remote)
 */
void
GMCH_handle_destroy (struct MeshChannel *ch,
                     const struct GNUNET_MESH_ChannelManage *msg,
                     int fwd)
{
  struct MeshTunnel3 *t;

  /* If this is a remote (non-loopback) channel, find 'fwd'. */
  if (GNUNET_SYSERR == fwd)
  {
    if (is_loopback (ch))
    {
      /* It is a loopback channel after all... */
      GNUNET_break (0);
      return;
    }
    fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
  }

  GMCH_debug (ch);
  if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
  {
    /* Not for us (don't destroy twice a half-open loopback channel) */
    return;
  }

  t = ch->t;
  GMCH_send_destroy (ch);
  channel_destroy (ch);
  GMT_destroy_if_empty (t);
}


/**
 * Sends an already built message on a channel.
 *
 * If the channel is on a loopback tunnel, notifies the appropriate destination
 * client locally.
 *
 * On a normal channel passes the message to the tunnel for encryption and
 * sending on a connection.
 *
 * This function DOES NOT save the message for retransmission.
 *
 * @param message Message to send. Function makes a copy of it.
 * @param ch Channel on which this message is transmitted.
 * @param fwd Is this a fwd message?
 */
void
GMCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
                            struct MeshChannel *ch, int fwd)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH Send %s %s on channel %s\n",
       fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (ntohs (message->type)), 
       GMCH_2s (ch));

  if (GMT_is_loopback (ch->t))
  {
    handle_loopback (ch, message, fwd);
    return;
  }

  GMT_send_prebuilt_message (message, ch->t, ch, fwd);
}


/**
 * Get the static string for identification of the channel.
 *
 * @param ch Channel.
 *
 * @return Static string with the channel IDs.
 */
const char *
GMCH_2s (const struct MeshChannel *ch)
{
  static char buf[64];

  if (NULL == ch)
    return "(NULL Channel)";

  sprintf (buf, "%s:%X (%X / %X)",
           GMT_2s (ch->t), ch->gid, ch->lid_root, ch->lid_dest);

  return buf;
}