aboutsummaryrefslogtreecommitdiff
path: root/src/cadet/gnunet-service-cadet.c
blob: 23a4bc2476a1a061bb0fc10b75904976acf17fc3 (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
/*
     This file is part of GNUnet.
     Copyright (C) 2001-2013, 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/gnunet-service-cadet.c
 * @brief GNUnet CADET service with encryption
 * @author Bartlomiej Polot
 * @author Christian Grothoff
 *
 * Dictionary:
 * - peer: other cadet instance. If there is direct connection it's a neighbor.
 * - path: series of directly connected peer from one peer to another.
 * - connection: path which is being used in a tunnel.
 * - tunnel: encrypted connection to a peer, neighbor or not.
 * - channel: logical link between two clients, on the same or different peers.
 *            have properties like reliability.
 */

#include "platform.h"
#include "gnunet_util_lib.h"
#include "cadet.h"
#include "gnunet_statistics_service.h"
#include "gnunet-service-cadet.h"
#include "gnunet-service-cadet_channel.h"
#include "gnunet-service-cadet_connection.h"
#include "gnunet-service-cadet_core.h"
#include "gnunet-service-cadet_dht.h"
#include "gnunet-service-cadet_hello.h"
#include "gnunet-service-cadet_tunnels.h"
#include "gnunet-service-cadet_peer.h"
#include "gnunet-service-cadet_paths.h"

#define LOG(level, ...) GNUNET_log (level,__VA_ARGS__)


/**
 * Struct containing information about a client of the service
 */
struct CadetClient
{
  /**
   * Linked list next
   */
  struct CadetClient *next;

  /**
   * Linked list prev
   */
  struct CadetClient *prev;

  /**
   * Tunnels that belong to this client, indexed by local id,
   * value is a `struct CadetChannel`.
   */
  struct GNUNET_CONTAINER_MultiHashMap32 *channels;

  /**
   * Handle to communicate with the client
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * Client handle.
   */
  struct GNUNET_SERVICE_Client *client;

  /**
   * Ports that this client has declared interest in.
   * Indexed by port, contains `struct OpenPort`
   */
  struct GNUNET_CONTAINER_MultiHashMap *ports;

  /**
   * Channel ID to use for the next incoming channel for this client.
   * Wraps around (in theory).
   */
  struct GNUNET_CADET_ClientChannelNumber next_ccn;

  /**
   * ID of the client, mainly for debug messages. Purely internal to this file.
   */
  unsigned int id;
};


/******************************************************************************/
/***********************      GLOBAL VARIABLES     ****************************/
/******************************************************************************/

/****************************** Global variables ******************************/

/**
 * Handle to our configuration.
 */
const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * Handle to the statistics service.
 */
struct GNUNET_STATISTICS_Handle *stats;

/**
 * Handle to communicate with ATS.
 */
struct GNUNET_ATS_ConnectivityHandle *ats_ch;

/**
 * Local peer own ID.
 */
struct GNUNET_PeerIdentity my_full_id;

/**
 * Own private key.
 */
struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;

/**
 * Signal that shutdown is happening: prevent recovery measures.
 */
int shutting_down;

/**
 * DLL with all the clients, head.
 */
static struct CadetClient *clients_head;

/**
 * DLL with all the clients, tail.
 */
static struct CadetClient *clients_tail;

/**
 * Next ID to assign to a client.
 */
static unsigned int next_client_id;

/**
 * All ports clients of this peer have opened.  Maps from
 * a hashed port to a `struct OpenPort`.
 */
struct GNUNET_CONTAINER_MultiHashMap *open_ports;

/**
 * Map from ports to channels where the ports were closed at the
 * time we got the inbound connection.
 * Indexed by h_port, contains `struct CadetChannel`.
 */
struct GNUNET_CONTAINER_MultiHashMap *loose_channels;

/**
 * Map from PIDs to `struct CadetPeer` entries.
 */
struct GNUNET_CONTAINER_MultiPeerMap *peers;

/**
 * Map from `struct GNUNET_CADET_ConnectionTunnelIdentifier`
 * hash codes to `struct CadetConnection` objects.
 */
struct GNUNET_CONTAINER_MultiShortmap *connections;

/**
 * How many messages are needed to trigger an AXOLOTL ratchet advance.
 */
unsigned long long ratchet_messages;

/**
 * How long until we trigger a ratched advance due to time.
 */
struct GNUNET_TIME_Relative ratchet_time;

/**
 * How frequently do we send KEEPALIVE messages on idle connections?
 */
struct GNUNET_TIME_Relative keepalive_period;

/**
 * Set to non-zero values to create random drops to test retransmissions.
 */
unsigned long long drop_percent;


/**
 * Send a message to a client.
 *
 * @param c client to get the message
 * @param env envelope with the message
 */
void
GSC_send_to_client (struct CadetClient *c,
                    struct GNUNET_MQ_Envelope *env)
{
  GNUNET_MQ_send (c->mq,
                  env);
}


/**
 * Return identifier for a client as a string.
 *
 * @param c client to identify
 * @return string for debugging
 */
const char *
GSC_2s (struct CadetClient *c)
{
  static char buf[32];

  GNUNET_snprintf (buf,
                   sizeof (buf),
                   "Client(%u)",
                   c->id);
  return buf;
}


/**
 * Lookup channel of client @a c by @a ccn.
 *
 * @param c client to look in
 * @param ccn channel ID to look up
 * @return NULL if no such channel exists
 */
static struct CadetChannel *
lookup_channel (struct CadetClient *c,
                struct GNUNET_CADET_ClientChannelNumber ccn)
{
  return GNUNET_CONTAINER_multihashmap32_get (c->channels,
                                              ntohl (ccn.channel_of_client));
}


/**
 * Obtain the next LID to use for incoming connections to
 * the given client.
 *
 * @param c client handle
 */
static struct GNUNET_CADET_ClientChannelNumber
client_get_next_ccn (struct CadetClient *c)
{
  struct GNUNET_CADET_ClientChannelNumber ccn = c->next_ccn;

  /* increment until we have a free one... */
  while (NULL !=
         lookup_channel (c,
                         ccn))
  {
    ccn.channel_of_client
      = htonl (1 + (ntohl (ccn.channel_of_client)));
    if (ntohl (ccn.channel_of_client) >=
        GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
      ccn.channel_of_client = htonl (0);
  }
  c->next_ccn.channel_of_client
    = htonl (1 + (ntohl (ccn.channel_of_client)));
  return ccn;
}


/**
 * Bind incoming channel to this client, and notify client about
 * incoming connection.  Caller is responsible for notifying the other
 * peer about our acceptance of the channel.
 *
 * @param c client to bind to
 * @param ch channel to be bound
 * @param dest peer that establishes the connection
 * @param port port number
 * @param options options
 * @return local channel number assigned to the new client
 */
struct GNUNET_CADET_ClientChannelNumber
GSC_bind (struct CadetClient *c,
          struct CadetChannel *ch,
          struct CadetPeer *dest,
          const struct GNUNET_HashCode *port,
          uint32_t options)
{
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_LocalChannelCreateMessage *cm;
  struct GNUNET_CADET_ClientChannelNumber ccn;

  ccn = client_get_next_ccn (c);
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap32_put (c->channels,
                                                      ntohl (ccn.channel_of_client),
                                                      ch,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Accepting incoming %s from %s on open port %s (%u), assigning ccn %X\n",
       GCCH_2s (ch),
       GCP_2s (dest),
       GNUNET_h2s (port),
       (uint32_t) ntohl (options),
       (uint32_t) ntohl (ccn.channel_of_client));
  /* notify local client about incoming connection! */
  env = GNUNET_MQ_msg (cm,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE);
  cm->ccn = ccn;
  cm->port = *port;
  cm->opt = htonl (options);
  cm->peer = *GCP_get_id (dest);
  GSC_send_to_client (c,
                      env);
  return ccn;
}


/**
 * Callback invoked on all peers to destroy all tunnels
 * that may still exist.
 *
 * @param cls NULL
 * @param pid identify of a peer
 * @param value a `struct CadetPeer` that may still have a tunnel
 * @return #GNUNET_OK (iterate over all entries)
 */
static int
destroy_tunnels_now (void *cls,
                     const struct GNUNET_PeerIdentity *pid,
                     void *value)
{
  struct CadetPeer *cp = value;
  struct CadetTunnel *t = GCP_get_tunnel (cp,
                                          GNUNET_NO);

  if (NULL != t)
    GCT_destroy_tunnel_now (t);
  return GNUNET_OK;
}


/**
 * Callback invoked on all peers to destroy all tunnels
 * that may still exist.
 *
 * @param cls NULL
 * @param pid identify of a peer
 * @param value a `struct CadetPeer` that may still have a tunnel
 * @return #GNUNET_OK (iterate over all entries)
 */
static int
destroy_paths_now (void *cls,
                   const struct GNUNET_PeerIdentity *pid,
                   void *value)
{
  struct CadetPeer *cp = value;

  GCP_drop_owned_paths (cp);
  return GNUNET_OK;
}


/**
 * Shutdown everything once the clients have disconnected.
 */
static void
shutdown_rest ()
{
  if (NULL != stats)
  {
    GNUNET_STATISTICS_destroy (stats,
                               GNUNET_NO);
    stats = NULL;
  }
  if (NULL != open_ports)
  {
    GNUNET_CONTAINER_multihashmap_destroy (open_ports);
    open_ports = NULL;
  }
  if (NULL != loose_channels)
  {
    GNUNET_CONTAINER_multihashmap_destroy (loose_channels);
    loose_channels = NULL;
  }
  /* Destroy tunnels.  Note that all channels must be destroyed first! */
  GCP_iterate_all (&destroy_tunnels_now,
                   NULL);
  /* All tunnels, channels, connections and CORE must be down before this point. */
  GCP_iterate_all (&destroy_paths_now,
                   NULL);
  /* All paths, tunnels, channels, connections and CORE must be down before this point. */
  GCP_destroy_all_peers ();
  if (NULL != peers)
  {
    GNUNET_CONTAINER_multipeermap_destroy (peers);
    peers = NULL;
  }
  if (NULL != connections)
  {
    GNUNET_CONTAINER_multishortmap_destroy (connections);
    connections = NULL;
  }
  if (NULL != ats_ch)
  {
    GNUNET_ATS_connectivity_done (ats_ch);
    ats_ch = NULL;
  }
  GCD_shutdown ();
  GCH_shutdown ();
  GNUNET_free_non_null (my_private_key);
  my_private_key = NULL;
}


/**
 * Task run during shutdown.
 *
 * @param cls unused
 */
static void
shutdown_task (void *cls)
{
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Shutting down\n");
  shutting_down = GNUNET_YES;
  GCO_shutdown ();
  if (NULL == clients_head)
    shutdown_rest ();
}


/**
 * We had a remote connection @a value to port @a h_port before
 * client @a cls opened port @a port.  Bind them now.
 *
 * @param cls the `struct CadetClient`
 * @param h_port the hashed port
 * @param value the `struct CadetChannel`
 * @return #GNUNET_YES (iterate over all such channels)
 */
static int
bind_loose_channel (void *cls,
                    const struct GNUNET_HashCode *port,
                    void *value)
{
  struct OpenPort *op = cls;
  struct CadetChannel *ch = value;

  GCCH_bind (ch,
             op->c,
	     &op->port);
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (loose_channels,
                                                       &op->h_port,
                                                       ch));
  return GNUNET_YES;
}


/**
 * Handle port open request.  Creates a mapping from the
 * port to the respective client and checks whether we have
 * loose channels trying to bind to the port.  If so, those
 * are bound.
 *
 * @param cls Identification of the client.
 * @param pmsg The actual message.
 */
static void
handle_port_open (void *cls,
                  const struct GNUNET_CADET_PortMessage *pmsg)
{
  struct CadetClient *c = cls;
  struct OpenPort *op;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Open port %s requested by %s\n",
       GNUNET_h2s (&pmsg->port),
       GSC_2s (c));
  if (NULL == c->ports)
    c->ports = GNUNET_CONTAINER_multihashmap_create (4,
						     GNUNET_NO);
  op = GNUNET_new (struct OpenPort);
  op->c = c;
  op->port = pmsg->port;
  GCCH_hash_port (&op->h_port,
		  &pmsg->port,
		  &my_full_id);
  if (GNUNET_OK !=
      GNUNET_CONTAINER_multihashmap_put (c->ports,
                                         &op->port,
                                         op,
                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
  {
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (c->client);
    return;
  }
  (void) GNUNET_CONTAINER_multihashmap_put (open_ports,
                                            &op->h_port,
                                            op,
                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
  GNUNET_CONTAINER_multihashmap_get_multiple (loose_channels,
                                              &op->h_port,
                                              &bind_loose_channel,
                                              op);
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Handler for port close requests.  Marks this port as closed
 * (unless of course we have another client with the same port
 * open).  Note that existing channels accepted on the port are
 * not affected.
 *
 * @param cls Identification of the client.
 * @param pmsg The actual message.
 */
static void
handle_port_close (void *cls,
                   const struct GNUNET_CADET_PortMessage *pmsg)
{
  struct CadetClient *c = cls;
  struct OpenPort *op;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Closing port %s as requested by %s\n",
       GNUNET_h2s (&pmsg->port),
       GSC_2s (c));
  if (NULL == c->ports)
  {
    /* Client closed a port despite _never_ having opened one? */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (c->client);
    return;
  }
  op = GNUNET_CONTAINER_multihashmap_get (c->ports,
					  &pmsg->port);
  if (NULL == op)
  {
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (c->client);
    return;
  }
  GNUNET_assert (GNUNET_YES ==
		 GNUNET_CONTAINER_multihashmap_remove (c->ports,
						       &op->port,
						       op));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (open_ports,
                                                       &op->h_port,
                                                       op));
  GNUNET_free (op);
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Handler for requests for us creating a new channel to another peer and port.
 *
 * @param cls Identification of the client.
 * @param tcm The actual message.
 */
static void
handle_channel_create (void *cls,
                       const struct GNUNET_CADET_LocalChannelCreateMessage *tcm)
{
  struct CadetClient *c = cls;
  struct CadetChannel *ch;

  if (ntohl (tcm->ccn.channel_of_client) < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
  {
    /* Channel ID not in allowed range. */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (c->client);
    return;
  }
  ch = lookup_channel (c,
                       tcm->ccn);
  if (NULL != ch)
  {
    /* Channel ID already in use. Not allowed. */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (c->client);
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "New channel to %s at port %s requested by %s\n",
       GNUNET_i2s (&tcm->peer),
       GNUNET_h2s (&tcm->port),
       GSC_2s (c));

  /* Create channel */
  ch = GCCH_channel_local_new (c,
                               tcm->ccn,
                               GCP_get (&tcm->peer,
                                        GNUNET_YES),
                               &tcm->port,
                               ntohl (tcm->opt));
  if (NULL == ch)
  {
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (c->client);
    return;
  }
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap32_put (c->channels,
                                                      ntohl (tcm->ccn.channel_of_client),
                                                      ch,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));

  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Handler for requests of destroying an existing channel.
 *
 * @param cls client identification of the client
 * @param msg the actual message
 */
static void
handle_channel_destroy (void *cls,
                        const struct GNUNET_CADET_LocalChannelDestroyMessage *msg)
{
  struct CadetClient *c = cls;
  struct CadetChannel *ch;

  ch = lookup_channel (c,
                       msg->ccn);
  if (NULL == ch)
  {
    /* Client attempted to destroy unknown channel.
       Can happen if the other side went down at the same time.*/
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "%s tried to destroy unknown channel %X\n",
         GSC_2s(c),
         (uint32_t) ntohl (msg->ccn.channel_of_client));
    GNUNET_SERVICE_client_continue (c->client);
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s is destroying %s\n",
       GSC_2s(c),
       GCCH_2s (ch));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap32_remove (c->channels,
                                                         ntohl (msg->ccn.channel_of_client),
                                                         ch));
  GCCH_channel_local_destroy (ch,
                              c,
                              msg->ccn);
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Check for client traffic data message is well-formed.
 *
 * @param cls identification of the client
 * @param msg the actual message
 * @return #GNUNET_OK if @a msg is OK, #GNUNET_SYSERR if not
 */
static int
check_local_data (void *cls,
                  const struct GNUNET_CADET_LocalData *msg)
{
  size_t payload_size;
  size_t payload_claimed_size;
  const char *buf;
  struct GNUNET_MessageHeader pa;

  /* FIXME: what is the format we shall allow for @a msg?
     ONE payload item or multiple? Seems current cadet_api
     at least in theory allows more than one. Next-gen
     cadet_api will likely no more, so we could then
     simplify this mess again. */
  /* Sanity check for message size */
  payload_size = ntohs (msg->header.size) - sizeof (*msg);
  buf = (const char *) &msg[1];
  while (payload_size >= sizeof (struct GNUNET_MessageHeader))
  {
    /* need to memcpy() for alignment */
    GNUNET_memcpy (&pa,
                   buf,
                   sizeof (pa));
    payload_claimed_size = ntohs (pa.size);
    if ( (payload_size < payload_claimed_size) ||
         (payload_claimed_size < sizeof (struct GNUNET_MessageHeader)) ||
         (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < payload_claimed_size) )
    {
      GNUNET_break (0);
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Local data of %u total size had sub-message %u at %u with %u bytes\n",
           ntohs (msg->header.size),
           ntohs (pa.type),
           (unsigned int) (buf - (const char *) &msg[1]),
           (unsigned int) payload_claimed_size);
      return GNUNET_SYSERR;
    }
    payload_size -= payload_claimed_size;
    buf += payload_claimed_size;
  }
  if (0 != payload_size)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Handler for client payload traffic to be send on a channel to
 * another peer.
 *
 * @param cls identification of the client
 * @param msg the actual message
 */
static void
handle_local_data (void *cls,
                   const struct GNUNET_CADET_LocalData *msg)
{
  struct CadetClient *c = cls;
  struct CadetChannel *ch;
  size_t payload_size;
  const char *buf;

  ch = lookup_channel (c,
                       msg->ccn);
  if (NULL == ch)
  {
    /* Channel does not exist (anymore) */
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "Dropping payload for channel %u from client (channel unknown, other endpoint may have disconnected)\n",
         (unsigned int) ntohl (msg->ccn.channel_of_client));
    GNUNET_SERVICE_client_continue (c->client);
    return;
  }
  payload_size = ntohs (msg->header.size) - sizeof (*msg);
  GNUNET_STATISTICS_update (stats,
                            "# payload received from clients",
                            payload_size,
                            GNUNET_NO);
  buf = (const char *) &msg[1];
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Received %u bytes payload from %s for %s\n",
       (unsigned int) payload_size,
       GSC_2s (c),
       GCCH_2s (ch));
  if (GNUNET_OK !=
      GCCH_handle_local_data (ch,
                              msg->ccn,
                              buf,
                              payload_size))
  {
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (c->client);
    return;
  }
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Handler for client's ACKs for payload traffic.
 *
 * @param cls identification of the client.
 * @param msg The actual message.
 */
static void
handle_local_ack (void *cls,
                  const struct GNUNET_CADET_LocalAck *msg)
{
  struct CadetClient *c = cls;
  struct CadetChannel *ch;

  ch = lookup_channel (c,
                       msg->ccn);
  if (NULL == ch)
  {
    /* Channel does not exist (anymore) */
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "Ignoring local ACK for channel %u from client (channel unknown, other endpoint may have disconnected)\n",
         (unsigned int) ntohl (msg->ccn.channel_of_client));
    GNUNET_SERVICE_client_continue (c->client);
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got a local ACK from %s for %s\n",
       GSC_2s(c),
       GCCH_2s (ch));
  GCCH_handle_local_ack (ch,
                         msg->ccn);
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Iterator over all peers to send a monitoring client info about each peer.
 *
 * @param cls Closure ().
 * @param peer Peer ID (tunnel remote peer).
 * @param value Peer info.
 * @return #GNUNET_YES, to keep iterating.
 */
static int
get_all_peers_iterator (void *cls,
                        const struct GNUNET_PeerIdentity *peer,
                        void *value)
{
  struct CadetClient *c = cls;
  struct CadetPeer *p = value;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_LocalInfoPeer *msg;

  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
  msg->destination = *peer;
  msg->paths = htons (GCP_count_paths (p));
  msg->tunnel = htons (NULL != GCP_get_tunnel (p,
                                               GNUNET_NO));
  GNUNET_MQ_send (c->mq,
                  env);
  return GNUNET_YES;
}


/**
 * Handler for client's INFO PEERS request.
 *
 * @param cls Identification of the client.
 * @param message The actual message.
 */
static void
handle_get_peers (void *cls,
                  const struct GNUNET_MessageHeader *message)
{
  struct CadetClient *c = cls;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_MessageHeader *reply;

  GCP_iterate_all (&get_all_peers_iterator,
                   c);
  env = GNUNET_MQ_msg (reply,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
  GNUNET_MQ_send (c->mq,
                  env);
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Iterator over all paths of a peer to build an InfoPeer message.
 * Message contains blocks of peers, first not included.
 *
 * @param cls message queue for transmission
 * @param path Path itself
 * @param off offset of the peer on @a path
 * @return #GNUNET_YES if should keep iterating.
 *         #GNUNET_NO otherwise.
 */
static int
path_info_iterator (void *cls,
                    struct CadetPeerPath *path,
                    unsigned int off)
{
  struct GNUNET_MQ_Handle *mq = cls;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_MessageHeader *resp;
  struct GNUNET_PeerIdentity *id;
  uint16_t path_size;
  unsigned int i;
  unsigned int path_length;

  path_length = GCPP_get_length (path);
  path_size = sizeof (struct GNUNET_PeerIdentity) * (path_length - 1);
  if (sizeof (*resp) + path_size > UINT16_MAX)
  {
    LOG (GNUNET_ERROR_TYPE_WARNING,
         "Path of %u entries is too long for info message\n",
         path_length);
    return GNUNET_YES;
  }
  env = GNUNET_MQ_msg_extra (resp,
                             path_size,
                             GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
  id = (struct GNUNET_PeerIdentity *) &resp[1];

  /* Don't copy first peer.  First peer is always the local one.  Last
   * peer is always the destination (leave as 0, EOL).
   */
  for (i = 0; i < off; i++)
    id[i] = *GCP_get_id (GCPP_get_peer_at_offset (path,
                                                  i + 1));
  GNUNET_MQ_send (mq,
                  env);
  return GNUNET_YES;
}


/**
 * Handler for client's SHOW_PEER request.
 *
 * @param cls Identification of the client.
 * @param msg The actual message.
 */
static void
handle_show_peer (void *cls,
                  const struct GNUNET_CADET_LocalInfo *msg)
{
  struct CadetClient *c = cls;
  struct CadetPeer *p;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_MessageHeader *resp;

  p = GCP_get (&msg->peer,
               GNUNET_NO);
  if (NULL != p)
    GCP_iterate_paths (p,
                       &path_info_iterator,
                       c->mq);
  /* Send message with 0/0 to indicate the end */
  env = GNUNET_MQ_msg (resp,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER_END);
  GNUNET_MQ_send (c->mq,
                  env);
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Iterator over all tunnels to send a monitoring client info about each tunnel.
 *
 * @param cls Closure ().
 * @param peer Peer ID (tunnel remote peer).
 * @param value a `struct CadetPeer`
 * @return #GNUNET_YES, to keep iterating.
 */
static int
get_all_tunnels_iterator (void *cls,
                          const struct GNUNET_PeerIdentity *peer,
                          void *value)
{
  struct CadetClient *c = cls;
  struct CadetPeer *p = value;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_LocalInfoTunnel *msg;
  struct CadetTunnel *t;

  t = GCP_get_tunnel (p,
                      GNUNET_NO);
  if (NULL == t)
    return GNUNET_YES;
  env = GNUNET_MQ_msg (msg,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
  msg->destination = *peer;
  msg->channels = htonl (GCT_count_channels (t));
  msg->connections = htonl (GCT_count_any_connections (t));
  msg->cstate = htons (0);
  msg->estate = htons ((uint16_t) GCT_get_estate (t));
  GNUNET_MQ_send (c->mq,
                  env);
  return GNUNET_YES;
}


/**
 * Handler for client's #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS request.
 *
 * @param cls client Identification of the client.
 * @param message The actual message.
 */
static void
handle_info_tunnels (void *cls,
                     const struct GNUNET_MessageHeader *message)
{
  struct CadetClient *c = cls;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_MessageHeader *reply;

  GCP_iterate_all (&get_all_tunnels_iterator,
                   c);
  env = GNUNET_MQ_msg (reply,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
  GNUNET_MQ_send (c->mq,
                  env);
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Update the message with information about the connection.
 *
 * @param cls a `struct GNUNET_CADET_LocalInfoTunnel` message to update
 * @param ct a connection about which we should store information in @a cls
 */
static void
iter_connection (void *cls,
                 struct CadetTConnection *ct)
{
  struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
  struct CadetConnection *cc = ct->cc;
  struct GNUNET_CADET_ConnectionTunnelIdentifier *h;

  h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
  h[msg->connections++] = *(GCC_get_id (cc));
}


/**
 * Update the message with information about the channel.
 *
 * @param cls a `struct GNUNET_CADET_LocalInfoTunnel` message to update
 * @param ch a channel about which we should store information in @a cls
 */
static void
iter_channel (void *cls,
              struct CadetChannel *ch)
{
  struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
  struct GNUNET_CADET_ConnectionTunnelIdentifier *h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
  struct GNUNET_CADET_ChannelTunnelNumber *chn
    = (struct GNUNET_CADET_ChannelTunnelNumber *) &h[msg->connections];

  chn[msg->channels++] = GCCH_get_id (ch);
}


/**
 * Handler for client's #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL request.
 *
 * @param cls Identification of the client.
 * @param msg The actual message.
 */
static void
handle_info_tunnel (void *cls,
                    const struct GNUNET_CADET_LocalInfo *msg)
{
  struct CadetClient *c = cls;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_LocalInfoTunnel *resp;
  struct CadetTunnel *t;
  struct CadetPeer *p;
  unsigned int ch_n;
  unsigned int c_n;

  p = GCP_get (&msg->peer,
               GNUNET_NO);
  t = GCP_get_tunnel (p,
                      GNUNET_NO);
  if (NULL == t)
  {
    /* We don't know the tunnel */
    struct GNUNET_MQ_Envelope *env;
    struct GNUNET_CADET_LocalInfoTunnel *warn;

    LOG (GNUNET_ERROR_TYPE_INFO,
         "Tunnel to %s unknown\n",
         GNUNET_i2s_full (&msg->peer));
    env = GNUNET_MQ_msg (warn,
                         GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
    warn->destination = msg->peer;
    GNUNET_MQ_send (c->mq,
                    env);
    GNUNET_SERVICE_client_continue (c->client);
    return;
  }

  /* Initialize context */
  ch_n = GCT_count_channels (t);
  c_n = GCT_count_any_connections (t);
  env = GNUNET_MQ_msg_extra (resp,
                             c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier) +
                             ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber),
                             GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
  resp->destination = msg->peer;
  /* Do not reorder! #iter_channel needs counters in HBO! */
  GCT_iterate_connections (t,
                           &iter_connection,
                           resp);
  GCT_iterate_channels (t,
                        &iter_channel,
                        resp);
  resp->connections = htonl (resp->connections);
  resp->channels = htonl (resp->channels);
  resp->cstate = htons (0);
  resp->estate = htons (GCT_get_estate (t));
  GNUNET_MQ_send (c->mq,
                  env);
  GNUNET_SERVICE_client_continue (c->client);
}


/**
 * Iterator over all peers to dump info for each peer.
 *
 * @param cls Closure (unused).
 * @param peer Peer ID (tunnel remote peer).
 * @param value Peer info.
 *
 * @return #GNUNET_YES, to keep iterating.
 */
static int
show_peer_iterator (void *cls,
                    const struct GNUNET_PeerIdentity *peer,
                    void *value)
{
  struct CadetPeer *p = value;
  struct CadetTunnel *t;

  t = GCP_get_tunnel (p,
                      GNUNET_NO);
  if (NULL != t)
    GCT_debug (t,
               GNUNET_ERROR_TYPE_ERROR);
  LOG (GNUNET_ERROR_TYPE_ERROR, "\n");
  return GNUNET_YES;
}


/**
 * Handler for client's INFO_DUMP request.
 *
 * @param cls Identification of the client.
 * @param message The actual message.
 */
static void
handle_info_dump (void *cls,
                  const struct GNUNET_MessageHeader *message)
{
  struct CadetClient *c = cls;

  LOG (GNUNET_ERROR_TYPE_INFO,
       "Received dump info request from client %u\n",
       c->id);

  LOG (GNUNET_ERROR_TYPE_ERROR,
       "*************************** DUMP START ***************************\n");
  for (struct CadetClient *ci = clients_head;
       NULL != ci;
       ci = ci->next)
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
         "Client %u (%p), handle: %p, ports: %u, channels: %u\n",
         ci->id,
         ci,
         ci->client,
         (NULL != c->ports)
         ? GNUNET_CONTAINER_multihashmap_size (ci->ports)
         : 0,
         GNUNET_CONTAINER_multihashmap32_size (ci->channels));
  }
  LOG (GNUNET_ERROR_TYPE_ERROR, "***************************\n");
  GCP_iterate_all (&show_peer_iterator,
                   NULL);

  LOG (GNUNET_ERROR_TYPE_ERROR,
       "**************************** DUMP END ****************************\n");

  GNUNET_SERVICE_client_continue (c->client);
}



/**
 * Callback called when a client connects to the service.
 *
 * @param cls closure for the service
 * @param client the new client that connected to the service
 * @param mq the message queue used to send messages to the client
 * @return @a c
 */
static void *
client_connect_cb (void *cls,
		   struct GNUNET_SERVICE_Client *client,
		   struct GNUNET_MQ_Handle *mq)
{
  struct CadetClient *c;

  c = GNUNET_new (struct CadetClient);
  c->client = client;
  c->mq = mq;
  c->id = next_client_id++; /* overflow not important: just for debug */
  c->channels
    = GNUNET_CONTAINER_multihashmap32_create (32);
  GNUNET_CONTAINER_DLL_insert (clients_head,
                               clients_tail,
                               c);
  GNUNET_STATISTICS_update (stats,
                            "# clients",
                            +1,
                            GNUNET_NO);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s connected\n",
       GSC_2s (c));
  return c;
}


/**
 * A channel was destroyed by the other peer. Tell our client.
 *
 * @param c client that lost a channel
 * @param ccn channel identification number for the client
 * @param ch the channel object
 */
void
GSC_handle_remote_channel_destroy (struct CadetClient *c,
                                   struct GNUNET_CADET_ClientChannelNumber ccn,
                                   struct CadetChannel *ch)
{
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CADET_LocalChannelDestroyMessage *tdm;

  env = GNUNET_MQ_msg (tdm,
                       GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
  tdm->ccn = ccn;
  GSC_send_to_client (c,
                      env);
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap32_remove (c->channels,
                                                         ntohl (ccn.channel_of_client),
                                                         ch));
}


/**
 * A client that created a loose channel that was not bound to a port
 * disconnected, drop it from the #loose_channels list.
 *
 * @param h_port the hashed port the channel was trying to bind to
 * @param ch the channel that was lost
 */
void
GSC_drop_loose_channel (const struct GNUNET_HashCode *h_port,
                        struct CadetChannel *ch)
{
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (loose_channels,
                                                       h_port,
                                                       ch));
}


/**
 * Iterator for deleting each channel whose client endpoint disconnected.
 *
 * @param cls Closure (client that has disconnected).
 * @param key The local channel id in host byte order
 * @param value The value stored at the key (channel to destroy).
 * @return #GNUNET_OK, keep iterating.
 */
static int
channel_destroy_iterator (void *cls,
                          uint32_t key,
                          void *value)
{
  struct CadetClient *c = cls;
  struct GNUNET_CADET_ClientChannelNumber ccn;
  struct CadetChannel *ch = value;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Destroying %s, due to %s disconnecting.\n",
       GCCH_2s (ch),
       GSC_2s (c));
  ccn.channel_of_client = htonl (key);
  GCCH_channel_local_destroy (ch,
                              c,
                              ccn);
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap32_remove (c->channels,
                                                         key,
                                                         ch));
  return GNUNET_OK;
}


/**
 * Remove client's ports from the global hashmap on disconnect.
 *
 * @param cls the `struct CadetClient`
 * @param port the port.
 * @param value the `struct OpenPort` to remove
 * @return #GNUNET_OK, keep iterating.
 */
static int
client_release_ports (void *cls,
                      const struct GNUNET_HashCode *port,
                      void *value)
{
  struct CadetClient *c = cls;
  struct OpenPort *op = value;

  GNUNET_assert (c == op->c);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Closing port %s due to %s disconnect.\n",
       GNUNET_h2s (port),
       GSC_2s (c));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (open_ports,
                                                       &op->h_port,
                                                       op));
  GNUNET_assert (GNUNET_YES ==
                 GNUNET_CONTAINER_multihashmap_remove (c->ports,
                                                       port,
                                                       op));
  GNUNET_free (op);
  return GNUNET_OK;
}


/**
 * Callback called when a client disconnected from the service
 *
 * @param cls closure for the service
 * @param client the client that disconnected
 * @param internal_cls should be equal to @a c
 */
static void
client_disconnect_cb (void *cls,
		      struct GNUNET_SERVICE_Client *client,
		      void *internal_cls)
{
  struct CadetClient *c = internal_cls;

  GNUNET_assert (c->client == client);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "%s is disconnecting.\n",
       GSC_2s (c));
  if (NULL != c->channels)
  {
    GNUNET_CONTAINER_multihashmap32_iterate (c->channels,
                                             &channel_destroy_iterator,
                                             c);
    GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (c->channels));
    GNUNET_CONTAINER_multihashmap32_destroy (c->channels);
  }
  if (NULL != c->ports)
  {
    GNUNET_CONTAINER_multihashmap_iterate (c->ports,
                                           &client_release_ports,
                                           c);
    GNUNET_CONTAINER_multihashmap_destroy (c->ports);
  }
  GNUNET_CONTAINER_DLL_remove (clients_head,
                               clients_tail,
                               c);
  GNUNET_STATISTICS_update (stats,
                            "# clients",
                            -1,
                            GNUNET_NO);
  GNUNET_free (c);
  if ( (NULL == clients_head) &&
       (GNUNET_YES == shutting_down) )
    shutdown_rest ();
}


/**
 * Setup CADET internals.
 *
 * @param cls closure
 * @param server the initialized server
 * @param c configuration to use
 */
static void
run (void *cls,
     const struct GNUNET_CONFIGURATION_Handle *c,
     struct GNUNET_SERVICE_Handle *service)
{
  cfg = c;
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_number (c,
                                             "CADET",
                                             "RATCHET_MESSAGES",
                                             &ratchet_messages))
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
                               "CADET",
                               "RATCHET_MESSAGES",
                               "needs to be a number");
    ratchet_messages = 64;
  }
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_time (c,
                                           "CADET",
                                           "RATCHET_TIME",
                                           &ratchet_time))
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
                               "CADET",
                               "RATCHET_TIME",
                               "need delay value");
    ratchet_time = GNUNET_TIME_UNIT_HOURS;
  }
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_time (c,
                                           "CADET",
                                           "REFRESH_CONNECTION_TIME",
                                           &keepalive_period))
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
                               "CADET",
                               "REFRESH_CONNECTION_TIME",
                               "need delay value");
    keepalive_period = GNUNET_TIME_UNIT_MINUTES;
  }
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_number (c,
                                             "CADET",
                                             "DROP_PERCENT",
                                             &drop_percent))
  {
    drop_percent = 0;
  }
  else
  {
    LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
    LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
  }
  my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
  if (NULL == my_private_key)
  {
    GNUNET_break (0);
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
                                      &my_full_id.public_key);
  stats = GNUNET_STATISTICS_create ("cadet",
                                    c);
  GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
				 NULL);
  ats_ch = GNUNET_ATS_connectivity_init (c);
  /* FIXME: optimize code to allow GNUNET_YES here! */
  open_ports = GNUNET_CONTAINER_multihashmap_create (16,
                                                     GNUNET_NO);
  loose_channels = GNUNET_CONTAINER_multihashmap_create (16,
                                                         GNUNET_NO);
  peers = GNUNET_CONTAINER_multipeermap_create (16,
                                                GNUNET_YES);
  connections = GNUNET_CONTAINER_multishortmap_create (256,
                                                       GNUNET_YES);
  GCH_init (c);
  GCD_init (c);
  GCO_init (c);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "CADET started for peer %s\n",
              GNUNET_i2s (&my_full_id));

}


/**
 * Define "main" method using service macro.
 */
GNUNET_SERVICE_MAIN
("cadet",
 GNUNET_SERVICE_OPTION_NONE,
 &run,
 &client_connect_cb,
 &client_disconnect_cb,
 NULL,
 GNUNET_MQ_hd_fixed_size (port_open,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN,
                          struct GNUNET_CADET_PortMessage,
                          NULL),
 GNUNET_MQ_hd_fixed_size (port_close,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE,
                          struct GNUNET_CADET_PortMessage,
                          NULL),
 GNUNET_MQ_hd_fixed_size (channel_create,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
                          struct GNUNET_CADET_LocalChannelCreateMessage,
                          NULL),
 GNUNET_MQ_hd_fixed_size (channel_destroy,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
                          struct GNUNET_CADET_LocalChannelDestroyMessage,
                          NULL),
 GNUNET_MQ_hd_var_size (local_data,
                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
                        struct GNUNET_CADET_LocalData,
                        NULL),
 GNUNET_MQ_hd_fixed_size (local_ack,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
                          struct GNUNET_CADET_LocalAck,
                          NULL),
 GNUNET_MQ_hd_fixed_size (get_peers,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
                          struct GNUNET_MessageHeader,
                          NULL),
 GNUNET_MQ_hd_fixed_size (show_peer,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
                          struct GNUNET_CADET_LocalInfo,
                          NULL),
 GNUNET_MQ_hd_fixed_size (info_tunnels,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
                          struct GNUNET_MessageHeader,
                          NULL),
 GNUNET_MQ_hd_fixed_size (info_tunnel,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
                          struct GNUNET_CADET_LocalInfo,
                          NULL),
 GNUNET_MQ_hd_fixed_size (info_dump,
                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP,
                          struct GNUNET_MessageHeader,
                          NULL),
 GNUNET_MQ_handler_end ());

/* end of gnunet-service-cadet-new.c */