aboutsummaryrefslogtreecommitdiff
path: root/src/cadet/cadet_api.c
blob: 3fdeffe13089a9680ef713afb29faa4f929096d1 (plain) (blame)
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
/*
     This file is part of GNUnet.
     Copyright (C) 2011, 2017 GNUnet e.V.

     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., 51 Franklin Street, Fifth Floor,
     Boston, MA 02110-1301, USA.
*/
/**
 * @file cadet/cadet_api.c
 * @brief cadet api: client implementation of cadet service
 * @author Bartlomiej Polot
 * @author Christian Grothoff
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_constants.h"
#include "gnunet_cadet_service.h"
#include "cadet.h"
#include "cadet_protocol.h"

#define LOG(kind,...) GNUNET_log_from (kind, "cadet-api",__VA_ARGS__)

/**
 * Ugly legacy hack.
 */
union CadetInfoCB
{

  /**
   * Channel callback.
   */
  GNUNET_CADET_ChannelCB channel_cb;

  /**
   * Monitor callback
   */
  GNUNET_CADET_PeersCB peers_cb;

  /**
   * Monitor callback
   */
  GNUNET_CADET_PeerCB peer_cb;

  /**
   * Monitor callback
   */
  GNUNET_CADET_TunnelsCB tunnels_cb;

  /**
   * Tunnel callback.
   */
  GNUNET_CADET_TunnelCB tunnel_cb;
};


/**
 * Opaque handle to the service.
 */
struct GNUNET_CADET_Handle
{
  /**
   * Message queue.
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * Ports open.
   */
  struct GNUNET_CONTAINER_MultiHashMap *ports;

  /**
   * Channels open.
   */
  struct GNUNET_CONTAINER_MultiHashMap32 *channels;

  /**
   * child of the next channel to create (to avoid reusing IDs often)
   */
  struct GNUNET_CADET_ClientChannelNumber next_ccn;

  /**
   * Configuration given by the client, in case of reconnection
   */
  const struct GNUNET_CONFIGURATION_Handle *cfg;

  /**
   * Task for trying to reconnect.
   */
  struct GNUNET_SCHEDULER_Task *reconnect_task;

  /**
   * Callback for an info task (only one active at a time).
   */
  union CadetInfoCB info_cb;

  /**
   * Info callback closure for @c info_cb.
   */
  void *info_cls;

  /**
   * Time to the next reconnect in case one reconnect fails
   */
  struct GNUNET_TIME_Relative reconnect_time;

};


/**
 * Opaque handle to a channel.
 */
struct GNUNET_CADET_Channel
{

  /**
   * Other end of the channel.
   */
  struct GNUNET_PeerIdentity peer;

  /**
   * Handle to the cadet this channel belongs to
   */
  struct GNUNET_CADET_Handle *cadet;

  /**
   * Channel's port, if incoming.
   */
  struct GNUNET_CADET_Port *incoming_port;

  /**
   * Any data the caller wants to put in here, used for the
   * various callbacks (@e disconnects, @e window_changes, handlers).
   */
  void *ctx;

  /**
   * Message Queue for the channel (which we are implementing).
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * Task to allow mq to send more traffic.
   */
  struct GNUNET_SCHEDULER_Task *mq_cont;

  /**
   * Pending envelope with a message to be transmitted to the
   * service as soon as we are allowed to.  Should only be
   * non-NULL if @e allow_send is 0.
   */
  struct GNUNET_MQ_Envelope *pending_env;

  /**
   * Window change handler.
   */
  GNUNET_CADET_WindowSizeEventHandler window_changes;

  /**
   * Disconnect handler.
   */
  GNUNET_CADET_DisconnectEventHandler disconnects;

  /**
   * Local ID of the channel, #GNUNET_CADET_LOCAL_CHANNEL_ID_CLI bit is set if outbound.
   */
  struct GNUNET_CADET_ClientChannelNumber ccn;

  /**
   * Channel options: reliability, etc.
   */
  enum GNUNET_CADET_ChannelOption options;

  /**
   * How many messages are we allowed to send to the service right now?
   */
  unsigned int allow_send;

};


/**
 * Opaque handle to a port.
 */
struct GNUNET_CADET_Port
{

  /**
   * Port "number"
   */
  struct GNUNET_HashCode id;

  /**
   * Handle to the CADET session this port belongs to.
   */
  struct GNUNET_CADET_Handle *cadet;

  /**
   * Closure for @a handler.
   */
  void *cls;

  /**
   * Handler for incoming channels on this port
   */
  GNUNET_CADET_ConnectEventHandler connects;

  /**
   * Closure for @ref connects
   */
  void *connects_cls;

  /**
   * Window size change handler.
   */
  GNUNET_CADET_WindowSizeEventHandler window_changes;

  /**
   * Handler called when an incoming channel is destroyed.
   */
  GNUNET_CADET_DisconnectEventHandler disconnects;

  /**
   * Payload handlers for incoming channels.
   */
  struct GNUNET_MQ_MessageHandler *handlers;
};


/**
 * Find the Port struct for a hash.
 *
 * @param h CADET handle.
 * @param hash HashCode for the port number.
 * @return The port handle if known, NULL otherwise.
 */
static struct GNUNET_CADET_Port *
find_port (const struct GNUNET_CADET_Handle *h,
	   const struct GNUNET_HashCode *hash)
{
  return GNUNET_CONTAINER_multihashmap_get (h->ports,
                                            hash);
}


/**
 * Get the channel handler for the channel specified by id from the given handle
 *
 * @param h Cadet handle
 * @param ccn ID of the wanted channel
 * @return handle to the required channel or NULL if not found
 */
static struct GNUNET_CADET_Channel *
find_channel (struct GNUNET_CADET_Handle *h,
              struct GNUNET_CADET_ClientChannelNumber ccn)
{
  return GNUNET_CONTAINER_multihashmap32_get (h->channels,
                                              ntohl (ccn.channel_of_client));
}


/**
 * Create a new channel and insert it in the channel list of the cadet handle
 *
 * @param h Cadet handle
 * @param ccnp pointer to desired ccn of the channel, NULL to assign one automatically.
 * @return Handle to the created channel.
 */
static struct GNUNET_CADET_Channel *
create_channel (struct GNUNET_CADET_Handle *h,
                const struct GNUNET_CADET_ClientChannelNumber *ccnp)
{
  struct GNUNET_CADET_Channel *ch;
  struct GNUNET_CADET_ClientChannelNumber ccn;

  ch = GNUNET_new (struct GNUNET_CADET_Channel);
  ch->cadet = h;
  if (NULL == ccnp)
  {
    while (NULL !=
           find_channel (h,
                         h->next_ccn))
      h->next_ccn.channel_of_client
        = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI | (1 + ntohl (h->next_ccn.channel_of_client)));
    ccn = h->next_ccn;
  }
  else
  {
    ccn = *ccnp;
  }
  ch->ccn = ccn;
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CONTAINER_multihashmap32_put (h->channels,
                                                      ntohl (ch->ccn.channel_of_client),
                                                      ch,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  return ch;
}


/**
 * Destroy the specified channel.
 * - Destroys all peers, calling the disconnect callback on each if needed
 * - Cancels all outgoing traffic for that channel, calling respective notifys
 * - Calls cleaner if channel was inbound
 * - Frees all memory used
 *
 * @param ch Pointer to the channel.
 * @param call_cleaner Whether to call the cleaner handler.
 */
static void
destroy_channel (struct GNUNET_CADET_Channel *ch)
{
  struct GNUNET_CADET_Handle *h = ch->cadet;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Destroying channel %X of %p\n",
       ch->ccn,
       h);
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap32_remove (h->channels,
                                                         ntohl (ch->ccn.channel_of_client),
                                                         ch));
  if (NULL != ch->mq_cont)
  {
    GNUNET_SCHEDULER_cancel (ch->mq_cont);
    ch->mq_cont = NULL;
  }
  /* signal channel destruction */
  if (NULL != ch->disconnects)
    ch->disconnects (ch->ctx,
                     ch);
  if (NULL != ch->pending_env)
    GNUNET_MQ_discard (ch->pending_env);
  GNUNET_MQ_destroy (ch->mq);
  GNUNET_free (ch);
}


/**
 * Reconnect to the service, retransmit all infomation to try to restore the
 * original state.
 *
 * @param h handle to the cadet
 */
static void
reconnect (struct GNUNET_CADET_Handle *h);


/**
 * Reconnect callback: tries to reconnect again after a failer previous
 * reconnecttion
 *
 * @param cls closure (cadet handle)
 */
static void
reconnect_cbk (void *cls)
{
  struct GNUNET_CADET_Handle *h = cls;

  h->reconnect_task = NULL;
  reconnect (h);
}


/**
 * Function called during #reconnect() to destroy
 * all channels that are still open.
 *
 * @param cls the `struct GNUNET_CADET_Handle`
 * @param cid chanenl ID
 * @param value a `struct GNUNET_CADET_Channel` to destroy
 * @return #GNUNET_OK (continue to iterate)
 */
static int
destroy_channel_on_reconnect_cb (void *cls,
                                 uint32_t cid,
                                 void *value)
{
  /* struct GNUNET_CADET_Handle *handle = cls; */
  struct GNUNET_CADET_Channel *ch = value;

  destroy_channel (ch);
  return GNUNET_OK;
}


/**
 * Reconnect to the service, retransmit all infomation to try to restore the
 * original state.
 *
 * @param h handle to the cadet
 *
 * @return #GNUNET_YES in case of sucess, #GNUNET_NO otherwise (service down...)
 */
static void
schedule_reconnect (struct GNUNET_CADET_Handle *h)
{
  if (NULL != h->reconnect_task)
    return;
  GNUNET_CONTAINER_multihashmap32_iterate (h->channels,
                                           &destroy_channel_on_reconnect_cb,
                                           h);
  h->reconnect_task
    = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
                                    &reconnect_cbk,
                                    h);
  h->reconnect_time
    = GNUNET_TIME_STD_BACKOFF (h->reconnect_time);
}


/**
 * Notify the application about a change in the window size (if needed).
 *
 * @param ch Channel to notify about.
 */
static void
notify_window_size (struct GNUNET_CADET_Channel *ch)
{
  if (NULL != ch->window_changes)
    ch->window_changes (ch->ctx,
                        ch, /* FIXME: remove 'ch'? */
                        ch->allow_send);
}


/**
 * Transmit the next message from our queue.
 *
 * @param cls Closure (channel whose mq to activate).
 */
static void
cadet_mq_send_now (void *cls)
{
  struct GNUNET_CADET_Channel *ch = cls;
  struct GNUNET_MQ_Envelope *env = ch->pending_env;

  ch->mq_cont = NULL;
  if (0 == ch->allow_send)
  {
    /* how did we get here? */
    GNUNET_break (0);
    return;
  }
  if (NULL == env)
  {
    /* how did we get here? */
    GNUNET_break (0);
    return;
  }
  ch->allow_send--;
  ch->pending_env = NULL;
  GNUNET_MQ_send (ch->cadet->mq,
                  env);
  GNUNET_MQ_impl_send_continue (ch->mq);
}


/**
 * Implement sending functionality of a message queue for
 * us sending messages to a peer.
 *
 * Encapsulates the payload message in a #GNUNET_CADET_LocalData message
 * in order to label the message with the channel ID and send the
 * encapsulated message to the service.
 *
 * @param mq the message queue
 * @param msg the message to send
 * @param impl_state state of the implementation
 */
static void
cadet_mq_send_impl (struct GNUNET_MQ_Handle *mq,
                    const struct GNUNET_MessageHeader *msg,
                    void *impl_state)
{
  struct GNUNET_CADET_Channel *ch = impl_state;
  struct GNUNET_CADET_Handle *h = ch->cadet;
  uint16_t msize;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_LocalData *cadet_msg;

  if (NULL == h->mq)
  {
    /* We're currently reconnecting, pretend this worked */
    GNUNET_MQ_impl_send_continue (mq);
    return;
  }

  /* check message size for sanity */
  msize = ntohs (msg->size);
  if (msize > GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE)
  {
    GNUNET_break (0);
    GNUNET_MQ_impl_send_continue (mq);
    return;
  }
  env = GNUNET_MQ_msg_nested_mh (cadet_msg,
                                 GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
                                 msg);
  cadet_msg->ccn = ch->ccn;
  GNUNET_assert (NULL == ch->pending_env);
  ch->pending_env = env;
  if (0 < ch->allow_send)
    ch->mq_cont
      = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now,
                                  ch);
}


/**
 * Handle destruction of a message queue.  Implementations must not
 * free @a mq, but should take care of @a impl_state.
 *
 * @param mq the message queue to destroy
 * @param impl_state state of the implementation
 */
static void
cadet_mq_destroy_impl (struct GNUNET_MQ_Handle *mq,
                       void *impl_state)
{
  struct GNUNET_CADET_Channel *ch = impl_state;

  GNUNET_assert (mq == ch->mq);
  ch->mq = NULL;
}


/**
 * We had an error processing a message we forwarded from a peer to
 * the CADET service.  We should just complain about it but otherwise
 * continue processing.
 *
 * @param cls closure with our `struct GNUNET_CADET_Channel`
 * @param error error code
 */
static void
cadet_mq_error_handler (void *cls,
                        enum GNUNET_MQ_Error error)
{
  struct GNUNET_CADET_Channel *ch = cls;

  GNUNET_break (0);
  if (GNUNET_MQ_ERROR_NO_MATCH == error)
  {
    /* Got a message we did not understand, still try to continue! */
    GNUNET_CADET_receive_done (ch);
  }
  else
  {
    schedule_reconnect (ch->cadet);
  }
}


/**
 * Implementation function that cancels the currently sent message.
 * Should basically undo whatever #mq_send_impl() did.
 *
 * @param mq message queue
 * @param impl_state state specific to the implementation
 */
static void
cadet_mq_cancel_impl (struct GNUNET_MQ_Handle *mq,
                     void *impl_state)
{
  struct GNUNET_CADET_Channel *ch = impl_state;

  GNUNET_assert (NULL != ch->pending_env);
  GNUNET_MQ_discard (ch->pending_env);
  ch->pending_env = NULL;
  if (NULL != ch->mq_cont)
  {
    GNUNET_SCHEDULER_cancel (ch->mq_cont);
    ch->mq_cont = NULL;
  }
}


/**
 * Process the new channel notification and add it to the channels in the handle
 *
 * @param h     The cadet handle
 * @param msg   A message with the details of the new incoming channel
 */
static void
handle_channel_created (void *cls,
                        const struct GNUNET_CADET_LocalChannelCreateMessage *msg)
{
  struct GNUNET_CADET_Handle *h = cls;
  struct GNUNET_CADET_Channel *ch;
  struct GNUNET_CADET_Port *port;
  const struct GNUNET_HashCode *port_number;
  struct GNUNET_CADET_ClientChannelNumber ccn;

  ccn = msg->ccn;
  port_number = &msg->port;
  if (ntohl (ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
  {
    GNUNET_break (0);
    return;
  }
  port = find_port (h,
                    port_number);
  if (NULL == port)
  {
    /* We could have closed the port but the service didn't know about it yet
     * This is not an error.
     */
    struct GNUNET_CADET_LocalChannelDestroyMessage *d_msg;
    struct GNUNET_MQ_Envelope *env;

    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "No handler for incoming channel %X (on port %s, recently closed?)\n",
         ntohl (ccn.channel_of_client),
         GNUNET_h2s (port_number));
    env = GNUNET_MQ_msg (d_msg,
                         GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
    d_msg->ccn = msg->ccn;
    GNUNET_MQ_send (h->mq,
                    env);
    return;
  }

  ch = create_channel (h,
                       &ccn);
  ch->peer = msg->peer;
  ch->cadet = h;
  ch->incoming_port = port;
  ch->options = ntohl (msg->opt);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Creating incoming channel %X [%s] %p\n",
       ntohl (ccn.channel_of_client),
       GNUNET_h2s (port_number),
       ch);

  GNUNET_assert (NULL != port->connects);
  ch->window_changes = port->window_changes;
  ch->disconnects = port->disconnects;
  ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
                                          &cadet_mq_destroy_impl,
                                          &cadet_mq_cancel_impl,
                                          ch,
                                          port->handlers,
                                          &cadet_mq_error_handler,
                                          ch);
  ch->ctx = port->connects (port->cls,
                            ch,
                            &msg->peer);
  GNUNET_MQ_set_handlers_closure (ch->mq,
                                  ch->ctx);
}


/**
 * Process the channel destroy notification and free associated resources
 *
 * @param h     The cadet handle
 * @param msg   A message with the details of the channel being destroyed
 */
static void
handle_channel_destroy (void *cls,
                        const struct GNUNET_CADET_LocalChannelDestroyMessage *msg)
{
  struct GNUNET_CADET_Handle *h = cls;
  struct GNUNET_CADET_Channel *ch;

  ch = find_channel (h,
                     msg->ccn);
  if (NULL == ch)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Received channel destroy for unknown channel %X from CADET service (recently close?)\n",
         ntohl (msg->ccn.channel_of_client));
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received channel destroy for channel %X from CADET service\n",
       ntohl (msg->ccn.channel_of_client));
  destroy_channel (ch);
}


/**
 * Check that message received from CADET service is well-formed.
 *
 * @param cls the `struct GNUNET_CADET_Handle`
 * @param message the message we got
 * @return #GNUNET_OK if the message is well-formed,
 *         #GNUNET_SYSERR otherwise
 */
static int
check_local_data (void *cls,
                  const struct GNUNET_CADET_LocalData *message)
{
  uint16_t size;

  size = ntohs (message->header.size);
  if (sizeof (*message) + sizeof (struct GNUNET_MessageHeader) > size)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Process the incoming data packets, call appropriate handlers.
 *
 * @param h       The cadet handle
 * @param message A message encapsulating the data
 */
static void
handle_local_data (void *cls,
                   const struct GNUNET_CADET_LocalData *message)
{
  struct GNUNET_CADET_Handle *h = cls;
  const struct GNUNET_MessageHeader *payload;
  struct GNUNET_CADET_Channel *ch;
  uint16_t type;
  int fwd;

  ch = find_channel (h,
                     message->ccn);
  if (NULL == ch)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Unknown channel %X for incoming data (recently closed?)\n",
         ntohl (message->ccn.channel_of_client));
    return;
  }

  payload = (const struct GNUNET_MessageHeader *) &message[1];
  type = ntohs (payload->type);
  fwd = ntohl (ch->ccn.channel_of_client) <= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got a %s data on channel %s [%X] of type %u\n",
       fwd ? "FWD" : "BWD",
       GNUNET_i2s (&ch->peer),
       ntohl (message->ccn.channel_of_client),
       type);
  GNUNET_MQ_inject_message (ch->mq,
                            payload);
}


/**
 * Process a local ACK message, enabling the client to send
 * more data to the service.
 *
 * @param h Cadet handle.
 * @param message Message itself.
 */
static void
handle_local_ack (void *cls,
                  const struct GNUNET_CADET_LocalAck *message)
{
  struct GNUNET_CADET_Handle *h = cls;
  struct GNUNET_CADET_Channel *ch;

  ch = find_channel (h,
                     message->ccn);
  if (NULL == ch)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "ACK on unknown channel %X\n",
         ntohl (message->ccn.channel_of_client));
    return;
  }
  ch->allow_send++;
  if (NULL == ch->pending_env)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Got an ACK on mq channel %X, allow send now %u!\n",
         ntohl (ch->ccn.channel_of_client),
         ch->allow_send);
    notify_window_size (ch);
    return;
  }
  if (NULL != ch->mq_cont)
    return; /* already working on it! */
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got an ACK on mq channel %X, sending pending message!\n",
       ntohl (ch->ccn.channel_of_client));
  ch->mq_cont
    = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now,
                                ch);
}


/**
 * Generic error handler, called with the appropriate error code and
 * the same closure specified at the creation of the message queue.
 * Not every message queue implementation supports an error handler.
 *
 * @param cls closure, a `struct GNUNET_CORE_Handle *`
 * @param error error code
 */
static void
handle_mq_error (void *cls,
                 enum GNUNET_MQ_Error error)
{
  struct GNUNET_CADET_Handle *h = cls;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "MQ ERROR: %u\n",
              error);
  GNUNET_MQ_destroy (h->mq);
  h->mq = NULL;
  reconnect (h);
}


/**
 * Process a local reply about info on all tunnels, pass info to the user.
 *
 * @param cls Closure (Cadet handle).
 * @param msg Message itself.
 */
static void
handle_get_peers (void *cls,
                  const struct GNUNET_CADET_LocalInfoPeer *msg)
{
  struct GNUNET_CADET_Handle *h = cls;

  if (NULL == h->info_cb.peers_cb)
    return;
  h->info_cb.peers_cb (h->info_cls,
                       &msg->destination,
                       (int) ntohs (msg->tunnel),
                       (unsigned int) ntohs (msg->paths),
                       0);
}


/**
 * Check that message received from CADET service is well-formed.
 *
 * @param cls the `struct GNUNET_CADET_Handle`
 * @param message the message we got
 * @return #GNUNET_OK if the message is well-formed,
 *         #GNUNET_SYSERR otherwise
 */
static int
check_get_peer (void *cls,
                const struct GNUNET_CADET_LocalInfoPeer *message)
{
  size_t msize = sizeof (struct GNUNET_CADET_LocalInfoPeer);
  const struct GNUNET_PeerIdentity *paths_array;
  size_t esize;
  unsigned int epaths;
  unsigned int paths;
  unsigned int peers;

  esize = ntohs (message->header.size);
  if (esize < msize)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (0 != ((esize - msize) % sizeof (struct GNUNET_PeerIdentity)))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  peers = (esize - msize) / sizeof (struct GNUNET_PeerIdentity);
  epaths = ntohs (message->paths);
  paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
  paths = 0;
  for (unsigned int i = 0; i < peers; i++)
    if (0 == memcmp (&paths_array[i],
                     &message->destination,
                     sizeof (struct GNUNET_PeerIdentity)))
      paths++;
  if (paths != epaths)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Process a local peer info reply, pass info to the user.
 *
 * @param cls Closure (Cadet handle).
 * @param message Message itself.
 */
static void
handle_get_peer (void *cls,
                 const struct GNUNET_CADET_LocalInfoPeer *message)
{
  struct GNUNET_CADET_Handle *h = cls;
  const struct GNUNET_PeerIdentity *paths_array;
  unsigned int paths;
  unsigned int path_length;
  int neighbor;
  unsigned int peers;

  if (NULL == h->info_cb.peer_cb)
    return;
  paths = ntohs (message->paths);
  paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
  peers = (ntohs (message->header.size) - sizeof (*message))
          / sizeof (struct GNUNET_PeerIdentity);
  path_length = 0;
  neighbor = GNUNET_NO;

  for (unsigned int i = 0; i < peers; i++)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                " %s\n",
                GNUNET_i2s (&paths_array[i]));
    path_length++;
    if (0 == memcmp (&paths_array[i], &message->destination,
                     sizeof (struct GNUNET_PeerIdentity)))
    {
      if (1 == path_length)
        neighbor = GNUNET_YES;
      path_length = 0;
    }
  }

  /* Call Callback with tunnel info. */
  paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
  h->info_cb.peer_cb (h->info_cls,
                      &message->destination,
                      (int) ntohs (message->tunnel),
                      neighbor,
                      paths,
                      paths_array);
}


/**
 * Process a local reply about info on all tunnels, pass info to the user.
 *
 * @param cls Closure (Cadet handle).
 * @param message Message itself.
 */
static void
handle_get_tunnels (void *cls,
                    const struct GNUNET_CADET_LocalInfoTunnel *msg)
{
  struct GNUNET_CADET_Handle *h = cls;

  if (NULL == h->info_cb.tunnels_cb)
    return;
  h->info_cb.tunnels_cb (h->info_cls,
                         &msg->destination,
                         ntohl (msg->channels),
                         ntohl (msg->connections),
                         ntohs (msg->estate),
                         ntohs (msg->cstate));

}


/**
 * Check that message received from CADET service is well-formed.
 *
 * @param cls the `struct GNUNET_CADET_Handle`
 * @param msg the message we got
 * @return #GNUNET_OK if the message is well-formed,
 *         #GNUNET_SYSERR otherwise
 */
static int
check_get_tunnel (void *cls,
                  const struct GNUNET_CADET_LocalInfoTunnel *msg)
{
  unsigned int ch_n;
  unsigned int c_n;
  size_t esize;
  size_t msize;

  /* Verify message sanity */
  msize = ntohs (msg->header.size);
  esize = sizeof (struct GNUNET_CADET_LocalInfoTunnel);
  if (esize > msize)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  ch_n = ntohl (msg->channels);
  c_n = ntohl (msg->connections);
  esize += ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber);
  esize += c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier);
  if (msize != esize)
  {
    GNUNET_break_op (0);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "m:%u, e: %u (%u ch, %u conn)\n",
                (unsigned int) msize,
                (unsigned int) esize,
                ch_n,
                c_n);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Process a local tunnel info reply, pass info to the user.
 *
 * @param cls Closure (Cadet handle).
 * @param msg Message itself.
 */
static void
handle_get_tunnel (void *cls,
                   const struct GNUNET_CADET_LocalInfoTunnel *msg)
{
  struct GNUNET_CADET_Handle *h = cls;
  unsigned int ch_n;
  unsigned int c_n;
  const struct GNUNET_CADET_ConnectionTunnelIdentifier *conns;
  const struct GNUNET_CADET_ChannelTunnelNumber *chns;

  if (NULL == h->info_cb.tunnel_cb)
    return;

  ch_n = ntohl (msg->channels);
  c_n = ntohl (msg->connections);

  /* Call Callback with tunnel info. */
  conns = (const struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
  chns = (const struct GNUNET_CADET_ChannelTunnelNumber *) &conns[c_n];
  h->info_cb.tunnel_cb (h->info_cls,
                        &msg->destination,
                        ch_n,
                        c_n,
                        chns,
                        conns,
                        ntohs (msg->estate),
                        ntohs (msg->cstate));
}


/**
 * Reconnect to the service, retransmit all infomation to try to restore the
 * original state.
 *
 * @param h handle to the cadet
 */
static void
reconnect (struct GNUNET_CADET_Handle *h)
{
  struct GNUNET_MQ_MessageHandler handlers[] = {
    GNUNET_MQ_hd_fixed_size (channel_created,
                             GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
                             struct GNUNET_CADET_LocalChannelCreateMessage,
                             h),
    GNUNET_MQ_hd_fixed_size (channel_destroy,
                             GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
                             struct GNUNET_CADET_LocalChannelDestroyMessage,
                             h),
    GNUNET_MQ_hd_var_size (local_data,
                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
                           struct GNUNET_CADET_LocalData,
                           h),
    GNUNET_MQ_hd_fixed_size (local_ack,
                             GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
                             struct GNUNET_CADET_LocalAck,
                             h),
    GNUNET_MQ_hd_fixed_size (get_peers,
                             GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
                             struct GNUNET_CADET_LocalInfoPeer,
                             h),
    GNUNET_MQ_hd_var_size (get_peer,
                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
                           struct GNUNET_CADET_LocalInfoPeer,
                           h),
    GNUNET_MQ_hd_fixed_size (get_tunnels,
                             GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
                             struct GNUNET_CADET_LocalInfoTunnel,
                             h),
    GNUNET_MQ_hd_var_size (get_tunnel,
                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
                           struct GNUNET_CADET_LocalInfoTunnel,
                           h),
    GNUNET_MQ_handler_end ()
  };

  h->mq = GNUNET_CLIENT_connect (h->cfg,
                                 "cadet",
                                 handlers,
                                 &handle_mq_error,
                                 h);
  if (NULL == h->mq)
  {
    schedule_reconnect (h);
    return;
  }
  h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
}


/**
 * Function called during #GNUNET_CADET_disconnect() to destroy
 * all channels that are still open.
 *
 * @param cls the `struct GNUNET_CADET_Handle`
 * @param cid chanenl ID
 * @param value a `struct GNUNET_CADET_Channel` to destroy
 * @return #GNUNET_OK (continue to iterate)
 */
static int
destroy_channel_cb (void *cls,
                    uint32_t cid,
                    void *value)
{
  /* struct GNUNET_CADET_Handle *handle = cls; */
  struct GNUNET_CADET_Channel *ch = value;

  if (ntohl (ch->ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
  {
    GNUNET_break (0);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "channel %X not destroyed\n",
         ntohl (ch->ccn.channel_of_client));
  }
  destroy_channel (ch);
  return GNUNET_OK;
}


/**
 * Function called during #GNUNET_CADET_disconnect() to destroy
 * all ports that are still open.
 *
 * @param cls the `struct GNUNET_CADET_Handle`
 * @param id port ID
 * @param value a `struct GNUNET_CADET_Channel` to destroy
 * @return #GNUNET_OK (continue to iterate)
 */
static int
destroy_port_cb (void *cls,
                 const struct GNUNET_HashCode *id,
                 void *value)
{
  /* struct GNUNET_CADET_Handle *handle = cls; */
  struct GNUNET_CADET_Port *port = value;

  /* This is a warning, the app should have cleanly closed all open ports */
  GNUNET_break (0);
  GNUNET_CADET_close_port (port);
  return GNUNET_OK;
}


/**
 * Disconnect from the cadet service. All channels will be destroyed. All channel
 * disconnect callbacks will be called on any still connected peers, notifying
 * about their disconnection. The registered inbound channel cleaner will be
 * called should any inbound channels still exist.
 *
 * @param handle connection to cadet to disconnect
 */
void
GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle)
{
  GNUNET_CONTAINER_multihashmap_iterate (handle->ports,
                                         &destroy_port_cb,
                                         handle);
  GNUNET_CONTAINER_multihashmap_destroy (handle->ports);
  handle->ports = NULL;
  GNUNET_CONTAINER_multihashmap32_iterate (handle->channels,
                                           &destroy_channel_cb,
                                           handle);
  GNUNET_CONTAINER_multihashmap32_destroy (handle->channels);
  handle->channels = NULL;
  if (NULL != handle->mq)
  {
    GNUNET_MQ_destroy (handle->mq);
    handle->mq = NULL;
  }
  if (NULL != handle->reconnect_task)
  {
    GNUNET_SCHEDULER_cancel (handle->reconnect_task);
    handle->reconnect_task = NULL;
  }
  GNUNET_free (handle);
}


/**
 * Close a port opened with @a GNUNET_CADET_open_port().
 * The @a new_channel callback will no longer be called.
 *
 * @param p Port handle.
 */
void
GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p)
{
  struct GNUNET_CADET_PortMessage *msg;
  struct GNUNET_MQ_Envelope *env;

  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE);
  msg->port = p->id;
  GNUNET_MQ_send (p->cadet->mq,
                  env);
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (p->cadet->ports,
                                                       &p->id,
                                                       p));
  GNUNET_free_non_null (p->handlers);
  GNUNET_free (p);
}


/**
 * Destroy an existing channel.
 *
 * The existing end callback for the channel will be called immediately.
 * Any pending outgoing messages will be sent but no incoming messages will be
 * accepted and no data callbacks will be called.
 *
 * @param channel Channel handle, becomes invalid after this call.
 */
void
GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel)
{
  struct GNUNET_CADET_Handle *h = channel->cadet;
  struct GNUNET_CADET_LocalChannelDestroyMessage *msg;
  struct GNUNET_MQ_Envelope *env;

  if (NULL != h->mq)
  {
    env = GNUNET_MQ_msg (msg,
                         GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
    msg->ccn = channel->ccn;
    GNUNET_MQ_send (h->mq,
                    env);
  }
  destroy_channel (channel);
}


/**
 * Get information about a channel.
 *
 * @param channel Channel handle.
 * @param option Query (GNUNET_CADET_OPTION_*).
 * @param ... dependant on option, currently not used
 *
 * @return Union with an answer to the query.
 */
const union GNUNET_CADET_ChannelInfo *
GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel,
                               enum GNUNET_CADET_ChannelOption option,
                               ...)
{
  static int bool_flag;

  switch (option)
  {
    case GNUNET_CADET_OPTION_NOBUFFER:
    case GNUNET_CADET_OPTION_RELIABLE:
    case GNUNET_CADET_OPTION_OUT_OF_ORDER:
      if (0 != (option & channel->options))
        bool_flag = GNUNET_YES;
      else
        bool_flag = GNUNET_NO;
      return (const union GNUNET_CADET_ChannelInfo *) &bool_flag;
      break;
    case GNUNET_CADET_OPTION_PEER:
      return (const union GNUNET_CADET_ChannelInfo *) &channel->peer;
      break;
    default:
      GNUNET_break (0);
      return NULL;
  }
}


/**
 * Send an ack on the channel to confirm the processing of a message.
 *
 * @param ch Channel on which to send the ACK.
 */
void
GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel)
{
  struct GNUNET_CADET_LocalAck *msg;
  struct GNUNET_MQ_Envelope *env;

  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending ACK on channel %X\n",
       ntohl (channel->ccn.channel_of_client));
  msg->ccn = channel->ccn;
  GNUNET_MQ_send (channel->cadet->mq,
                  env);
}


/**
 * Send message of @a type to CADET service of @a h
 *
 * @param h handle to CADET service
 * @param type message type of trivial information request to send
 */
static void
send_info_request (struct GNUNET_CADET_Handle *h,
                   uint16_t type)
{
  struct GNUNET_MessageHeader *msg;
  struct GNUNET_MQ_Envelope *env;

  env = GNUNET_MQ_msg (msg,
                       type);
  GNUNET_MQ_send (h->mq,
                  env);
}


/**
 * Request a debug dump on the service's STDERR.
 *
 * WARNING: unstable API, likely to change in the future!
 *
 * @param h cadet handle
 */
void
GNUNET_CADET_request_dump (struct GNUNET_CADET_Handle *h)
{
  send_info_request (h,
                     GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP);
}


/**
 * Request information about peers known to the running cadet service.
 * The callback will be called for every peer known to the service.
 * Only one info request (of any kind) can be active at once.
 *
 * WARNING: unstable API, likely to change in the future!
 *
 * @param h Handle to the cadet peer.
 * @param callback Function to call with the requested data.
 * @param callback_cls Closure for @c callback.
 * @return #GNUNET_OK / #GNUNET_SYSERR
 */
int
GNUNET_CADET_get_peers (struct GNUNET_CADET_Handle *h,
                       GNUNET_CADET_PeersCB callback,
                       void *callback_cls)
{
  if (NULL != h->info_cb.peers_cb)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  send_info_request (h,
                     GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
  h->info_cb.peers_cb = callback;
  h->info_cls = callback_cls;
  return GNUNET_OK;
}


/**
 * Cancel a peer info request. The callback will not be called (anymore).
 *
 * WARNING: unstable API, likely to change in the future!
 *
 * @param h Cadet handle.
 * @return Closure given to GNUNET_CADET_get_peers().
 */
void *
GNUNET_CADET_get_peers_cancel (struct GNUNET_CADET_Handle *h)
{
  void *cls = h->info_cls;

  h->info_cb.peers_cb = NULL;
  h->info_cls = NULL;
  return cls;
}


/**
 * Request information about a peer known to the running cadet peer.
 * The callback will be called for the tunnel once.
 * Only one info request (of any kind) can be active at once.
 *
 * WARNING: unstable API, likely to change in the future!
 *
 * @param h Handle to the cadet peer.
 * @param id Peer whose tunnel to examine.
 * @param callback Function to call with the requested data.
 * @param callback_cls Closure for @c callback.
 * @return #GNUNET_OK / #GNUNET_SYSERR
 */
int
GNUNET_CADET_get_peer (struct GNUNET_CADET_Handle *h,
                       const struct GNUNET_PeerIdentity *id,
                       GNUNET_CADET_PeerCB callback,
                       void *callback_cls)
{
  struct GNUNET_CADET_LocalInfo *msg;
  struct GNUNET_MQ_Envelope *env;

  if (NULL != h->info_cb.peer_cb)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
  msg->peer = *id;
  GNUNET_MQ_send (h->mq,
                  env);
  h->info_cb.peer_cb = callback;
  h->info_cls = callback_cls;
  return GNUNET_OK;
}


/**
 * Request information about tunnels of the running cadet peer.
 * The callback will be called for every tunnel of the service.
 * Only one info request (of any kind) can be active at once.
 *
 * WARNING: unstable API, likely to change in the future!
 *
 * @param h Handle to the cadet peer.
 * @param callback Function to call with the requested data.
 * @param callback_cls Closure for @c callback.
 * @return #GNUNET_OK / #GNUNET_SYSERR
 */
int
GNUNET_CADET_get_tunnels (struct GNUNET_CADET_Handle *h,
                         GNUNET_CADET_TunnelsCB callback,
                         void *callback_cls)
{
  if (NULL != h->info_cb.tunnels_cb)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  send_info_request (h,
                     GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
  h->info_cb.tunnels_cb = callback;
  h->info_cls = callback_cls;
  return GNUNET_OK;
}


/**
 * Cancel a monitor request. The monitor callback will not be called.
 *
 * @param h Cadet handle.
 * @return Closure given to GNUNET_CADET_get_tunnels().
 */
void *
GNUNET_CADET_get_tunnels_cancel (struct GNUNET_CADET_Handle *h)
{
  void *cls = h->info_cls;

  h->info_cb.tunnels_cb = NULL;
  h->info_cls = NULL;
  return cls;
}


/**
 * Request information about a tunnel of the running cadet peer.
 * The callback will be called for the tunnel once.
 * Only one info request (of any kind) can be active at once.
 *
 * WARNING: unstable API, likely to change in the future!
 *
 * @param h Handle to the cadet peer.
 * @param id Peer whose tunnel to examine.
 * @param callback Function to call with the requested data.
 * @param callback_cls Closure for @c callback.
 * @return #GNUNET_OK / #GNUNET_SYSERR
 */
int
GNUNET_CADET_get_tunnel (struct GNUNET_CADET_Handle *h,
                        const struct GNUNET_PeerIdentity *id,
                        GNUNET_CADET_TunnelCB callback,
                        void *callback_cls)
{
  struct GNUNET_CADET_LocalInfo *msg;
  struct GNUNET_MQ_Envelope *env;

  if (NULL != h->info_cb.tunnel_cb)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
  msg->peer = *id;
  GNUNET_MQ_send (h->mq,
                  env);
  h->info_cb.tunnel_cb = callback;
  h->info_cls = callback_cls;
  return GNUNET_OK;
}


/**
 * Transitional function to convert an unsigned int port to a hash value.
 * WARNING: local static value returned, NOT reentrant!
 * WARNING: do not use this function for new code!
 *
 * @param port Numerical port (unsigned int format).
 *
 * @return A GNUNET_HashCode usable for the new CADET API.
 */
const struct GNUNET_HashCode *
GC_u2h (uint32_t port)
{
  static struct GNUNET_HashCode hash;

  GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
              "This is a transitional function, use proper crypto hashes as CADET ports\n");
  GNUNET_CRYPTO_hash (&port,
                      sizeof (port),
                      &hash);
  return &hash;
}


/**
 * Connect to the MQ-based cadet service.
 *
 * @param cfg Configuration to use.
 *
 * @return Handle to the cadet service NULL on error.
 */
struct GNUNET_CADET_Handle *
GNUNET_CADET_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
{
  struct GNUNET_CADET_Handle *h;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "GNUNET_CADET_connect()\n");
  h = GNUNET_new (struct GNUNET_CADET_Handle);
  h->cfg = cfg;
  h->ports = GNUNET_CONTAINER_multihashmap_create (4,
                                                   GNUNET_YES);
  h->channels = GNUNET_CONTAINER_multihashmap32_create (4);
  reconnect (h);
  if (NULL == h->mq)
  {
    GNUNET_break (0);
    GNUNET_CADET_disconnect (h);
    return NULL;
  }
  h->next_ccn.channel_of_client = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
  h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
  h->reconnect_task = NULL;

  return h;
}


/**
 * Open a port to receive incomming MQ-based channels.
 *
 * @param h CADET handle.
 * @param port Hash identifying the port.
 * @param connects Function called when an incoming channel is connected.
 * @param connects_cls Closure for the @a connects handler.
 * @param window_changes Function called when the transmit window size changes.
 * @param disconnects Function called when a channel is disconnected.
 * @param handlers Callbacks for messages we care about, NULL-terminated.
 * @return Port handle, NULL if port is in use
 */
struct GNUNET_CADET_Port *
GNUNET_CADET_open_port (struct GNUNET_CADET_Handle *h,
                        const struct GNUNET_HashCode *port,
                        GNUNET_CADET_ConnectEventHandler connects,
                        void * connects_cls,
                        GNUNET_CADET_WindowSizeEventHandler window_changes,
                        GNUNET_CADET_DisconnectEventHandler disconnects,
                        const struct GNUNET_MQ_MessageHandler *handlers)
{
  struct GNUNET_CADET_PortMessage *msg;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_Port *p;

  GNUNET_assert (NULL != connects);
  GNUNET_assert (NULL != disconnects);

  p = GNUNET_new (struct GNUNET_CADET_Port);
  p->cadet = h;
  p->id = *port;
  if (GNUNET_OK !=
      GNUNET_CONTAINER_multihashmap_put (h->ports,
                                         &p->id,
                                         p,
                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
  {
    GNUNET_free (p);
    return NULL;
  }
  p->connects = connects;
  p->cls = connects_cls;
  p->window_changes = window_changes;
  p->disconnects = disconnects;
  p->handlers = GNUNET_MQ_copy_handlers (handlers);


  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN);
  msg->port = p->id;
  GNUNET_MQ_send (h->mq,
                  env);
  return p;
}


/**
 * Create a new channel towards a remote peer.
 *
 * If the destination port is not open by any peer or the destination peer
 * does not accept the channel, #GNUNET_CADET_ChannelEndHandler will be called
 * for this channel.
 *
 * @param h CADET handle.
 * @param channel_cls Closure for the channel. It's given to:
 *                    - The disconnect handler @a disconnects
 *                    - Each message type callback in @a handlers
 * @param destination Peer identity the channel should go to.
 * @param port Identification of the destination port.
 * @param options CadetOption flag field, with all desired option bits set to 1.
 * @param window_changes Function called when the transmit window size changes.
 * @param disconnects Function called when the channel is disconnected.
 * @param handlers Callbacks for messages we care about, NULL-terminated.
 * @return Handle to the channel.
 */
struct GNUNET_CADET_Channel *
GNUNET_CADET_channel_create (struct GNUNET_CADET_Handle *h,
                             void *channel_cls,
                             const struct GNUNET_PeerIdentity *destination,
                             const struct GNUNET_HashCode *port,
                             enum GNUNET_CADET_ChannelOption options,
                             GNUNET_CADET_WindowSizeEventHandler window_changes,
                             GNUNET_CADET_DisconnectEventHandler disconnects,
                             const struct GNUNET_MQ_MessageHandler *handlers)
{
  struct GNUNET_CADET_Channel *ch;
  struct GNUNET_CADET_LocalChannelCreateMessage *msg;
  struct GNUNET_MQ_Envelope *env;

  GNUNET_assert (NULL != disconnects);
  ch = create_channel (h,
                       NULL);
  ch->ctx = channel_cls;
  ch->peer = *destination;
  ch->options = options;
  ch->window_changes = window_changes;
  ch->disconnects = disconnects;

  /* Create MQ for channel */
  ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
                                          &cadet_mq_destroy_impl,
                                          &cadet_mq_cancel_impl,
                                          ch,
                                          handlers,
                                          &cadet_mq_error_handler,
                                          ch);
  GNUNET_MQ_set_handlers_closure (ch->mq, channel_cls);

  /* Request channel creation to service */
  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE);
  msg->ccn = ch->ccn;
  msg->port = *port;
  msg->peer = *destination;
  msg->opt = htonl (options);
  GNUNET_MQ_send (h->mq,
                  env);
  return ch;
}


/**
 * Obtain the message queue for a connected peer.
 *
 * @param channel The channel handle from which to get the MQ.
 *
 * @return NULL if @a channel is not yet connected.
 */
struct GNUNET_MQ_Handle *
GNUNET_CADET_get_mq (const struct GNUNET_CADET_Channel *channel)
{
  return channel->mq;
}

/* end of cadet_api.c */