aboutsummaryrefslogtreecommitdiff
path: root/src/multicast/gnunet-service-multicast.c
blob: 55c2698741364deaa9b87afc5fbbd4fab48a7f17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
/*
     This file is part of GNUnet.
     Copyright (C) 2009 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 multicast/gnunet-service-multicast.c
 * @brief program that does multicast
 * @author Christian Grothoff
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_signatures.h"
#include "gnunet_applications.h"
#include "gnunet_statistics_service.h"
#include "gnunet_core_service.h"
#include "gnunet_cadet_service.h"
#include "gnunet_multicast_service.h"
#include "multicast.h"

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

/**
 * Server handle.
 */
static struct GNUNET_SERVER_Handle *server;

/**
 * Core handle.
 * Only used during initialization.
 */
static struct GNUNET_CORE_Handle *core;

/**
 * CADET handle.
 */
static struct GNUNET_CADET_Handle *cadet;

/**
 * Identity of this peer.
 */
static struct GNUNET_PeerIdentity this_peer;

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

/**
 * Notification context, simplifies client broadcasts.
 */
static struct GNUNET_SERVER_NotificationContext *nc;

/**
 * All connected origin clients.
 * Group's pub_key_hash -> struct Origin * (uniq)
 */
static struct GNUNET_CONTAINER_MultiHashMap *origins;

/**
 * All connected member clients.
 * Group's pub_key_hash -> struct Member * (multi)
 */
static struct GNUNET_CONTAINER_MultiHashMap *members;

/**
 * Connected member clients per group.
 * Group's pub_key_hash -> Member's pub_key_hash (uniq) -> struct Member * (uniq)
 */
static struct GNUNET_CONTAINER_MultiHashMap *group_members;

/**
 * Incoming CADET channels with connected children in the tree.
 * Group's pub_key_hash -> struct Channel * (multi)
 */
static struct GNUNET_CONTAINER_MultiHashMap *channels_in;

/**
 * Outgoing CADET channels connecting to parents in the tree.
 * Group's pub_key_hash -> struct Channel * (multi)
 */
static struct GNUNET_CONTAINER_MultiHashMap *channels_out;

/**
 * Incoming replay requests from CADET.
 * Group's pub_key_hash ->
 *   H(fragment_id, message_id, fragment_offset, flags) -> struct Channel *
 */
static struct GNUNET_CONTAINER_MultiHashMap *replay_req_cadet;

/**
 * Incoming replay requests from clients.
 * Group's pub_key_hash ->
 *   H(fragment_id, message_id, fragment_offset, flags) -> struct GNUNET_SERVER_Client *
 */
static struct GNUNET_CONTAINER_MultiHashMap *replay_req_client;


/**
 * Join status of a remote peer.
 */
enum JoinStatus
{
  JOIN_REFUSED  = -1,
  JOIN_NOT_ASKED = 0,
  JOIN_WAITING   = 1,
  JOIN_ADMITTED  = 2,
};

enum ChannelDirection
{
  DIR_INCOMING = 0,
  DIR_OUTGOING = 1,
};


/**
 * Context for a CADET channel.
 */
struct Channel
{
  /**
   * Group the channel belongs to.
   *
   * Only set for outgoing channels.
   */
  struct Group *grp;

  /**
   * CADET channel.
   */
  struct GNUNET_CADET_Channel *channel;

  /**
   * CADET transmission handle.
   */
  struct GNUNET_CADET_TransmitHandle *tmit_handle;

  /**
   * Public key of the target group.
   */
  struct GNUNET_CRYPTO_EddsaPublicKey group_pub_key;

  /**
   * Hash of @a group_pub_key.
   */
  struct GNUNET_HashCode group_pub_hash;

  /**
   * Public key of the joining member.
   */
  struct GNUNET_CRYPTO_EcdsaPublicKey member_pub_key;

  /**
   * Remote peer identity.
   */
  struct GNUNET_PeerIdentity peer;

  /**
   * Is the remote peer admitted to the group?
   * @see enum JoinStatus
   */
  int8_t join_status;

  /**
   * Number of messages waiting to be sent to CADET.
   */
  uint8_t msgs_pending;

  /**
   * Channel direction.
   * @see enum ChannelDirection
   */
  uint8_t direction;
};


/**
 * List of connected clients.
 */
struct ClientList
{
  struct ClientList *prev;
  struct ClientList *next;
  struct GNUNET_SERVER_Client *client;
};

/**
 * Common part of the client context for both an origin and member.
 */
struct Group
{
  struct ClientList *clients_head;
  struct ClientList *clients_tail;

  /**
   * Public key of the group.
   */
  struct GNUNET_CRYPTO_EddsaPublicKey pub_key;

  /**
   * Hash of @a pub_key.
   */
  struct GNUNET_HashCode pub_key_hash;

  /**
   * Is this an origin (#GNUNET_YES), or member (#GNUNET_NO)?
   */
  uint8_t is_origin;

  /**
   * Is the client disconnected? #GNUNET_YES or #GNUNET_NO
   */
  uint8_t disconnected;
};


/**
 * Client context for a group's origin.
 */
struct Origin
{
  struct Group grp;

  /**
   * Private key of the group.
   */
  struct GNUNET_CRYPTO_EddsaPrivateKey priv_key;

  /**
   * Last message fragment ID sent to the group.
   */
  uint64_t max_fragment_id;
};


/**
 * Client context for a group member.
 */
struct Member
{
  struct Group grp;

  /**
   * Private key of the member.
   */
  struct GNUNET_CRYPTO_EcdsaPrivateKey priv_key;

  /**
   * Public key of the member.
   */
  struct GNUNET_CRYPTO_EcdsaPublicKey pub_key;

  /**
   * Hash of @a pub_key.
   */
  struct GNUNET_HashCode pub_key_hash;

  /**
   * Join request sent to the origin / members.
   */
  struct MulticastJoinRequestMessage *join_req;

  /**
   * Join decision sent in reply to our request.
   *
   * Only a positive decision is stored here, in case of a negative decision the
   * client is disconnected.
   */
  struct MulticastJoinDecisionMessageHeader *join_dcsn;

  /**
   * CADET channel to the origin.
   */
  struct Channel *origin_channel;

  /**
   * Peer identity of origin.
   */
  struct GNUNET_PeerIdentity origin;

  /**
   * Peer identity of relays (other members to connect).
   */
  struct GNUNET_PeerIdentity *relays;

  /**
   * Last request fragment ID sent to the origin.
   */
  uint64_t max_fragment_id;

  /**
   * Number of @a relays.
   */
  uint32_t relay_count;
};


struct ReplayRequestKey
{
  uint64_t fragment_id;
  uint64_t message_id;
  uint64_t fragment_offset;
  uint64_t flags;
};


/**
 * Task run during shutdown.
 *
 * @param cls unused
 */
static void
shutdown_task (void *cls)
{
  if (NULL != core)
  {
    GNUNET_CORE_disconnect (core);
    core = NULL;
  }
  if (NULL != cadet)
  {
    GNUNET_CADET_disconnect (cadet);
    cadet = NULL;
  }
  if (NULL != stats)
  {
    GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
    stats = NULL;
  }
  /* FIXME: do more clean up here */
}


/**
 * Clean up origin data structures after a client disconnected.
 */
static void
cleanup_origin (struct Origin *orig)
{
  struct Group *grp = &orig->grp;
  GNUNET_CONTAINER_multihashmap_remove (origins, &grp->pub_key_hash, orig);
}


/**
 * Clean up member data structures after a client disconnected.
 */
static void
cleanup_member (struct Member *mem)
{
  struct Group *grp = &mem->grp;
  struct GNUNET_CONTAINER_MultiHashMap *
    grp_mem = GNUNET_CONTAINER_multihashmap_get (group_members,
                                                 &grp->pub_key_hash);
  GNUNET_assert (NULL != grp_mem);
  GNUNET_CONTAINER_multihashmap_remove (grp_mem, &mem->pub_key_hash, mem);

  if (0 == GNUNET_CONTAINER_multihashmap_size (grp_mem))
  {
    GNUNET_CONTAINER_multihashmap_remove (group_members, &grp->pub_key_hash,
                                          grp_mem);
    GNUNET_CONTAINER_multihashmap_destroy (grp_mem);
  }
  if (NULL != mem->join_dcsn)
  {
    GNUNET_free (mem->join_dcsn);
    mem->join_dcsn = NULL;
  }
  GNUNET_CONTAINER_multihashmap_remove (members, &grp->pub_key_hash, mem);
}


/**
 * Clean up group data structures after a client disconnected.
 */
static void
cleanup_group (struct Group *grp)
{
  (GNUNET_YES == grp->is_origin)
    ? cleanup_origin ((struct Origin *) grp)
    : cleanup_member ((struct Member *) grp);

  GNUNET_free (grp);
}


void
replay_key_hash (uint64_t fragment_id, uint64_t message_id,
                 uint64_t fragment_offset, uint64_t flags,
                 struct GNUNET_HashCode *key_hash)
{
  struct ReplayRequestKey key = {
    .fragment_id = fragment_id,
    .message_id = message_id,
    .fragment_offset = fragment_offset,
    .flags = flags,
  };
  GNUNET_CRYPTO_hash (&key, sizeof (key), key_hash);
}


/**
 * Remove channel from replay request hashmap.
 *
 * @param chn
 *        Channel to remove.
 *
 * @return #GNUNET_YES if there are more entries to process,
 *         #GNUNET_NO when reached end of hashmap.
 */
static int
replay_req_remove_cadet (struct Channel *chn)
{
  struct GNUNET_CONTAINER_MultiHashMap *
    grp_replay_req = GNUNET_CONTAINER_multihashmap_get (replay_req_cadet,
                                                        &chn->grp->pub_key_hash);
  if (NULL == grp_replay_req)
    return GNUNET_NO;

  struct GNUNET_CONTAINER_MultiHashMapIterator *
    it = GNUNET_CONTAINER_multihashmap_iterator_create (grp_replay_req);
  struct GNUNET_HashCode key;
  const struct Channel *c;
  while (GNUNET_YES
         == GNUNET_CONTAINER_multihashmap_iterator_next (it, &key,
                                                         (const void **) &c))
  {
    if (c == chn)
    {
      GNUNET_CONTAINER_multihashmap_remove (grp_replay_req, &key, chn);
      GNUNET_CONTAINER_multihashmap_iterator_destroy (it);
      return GNUNET_YES;
    }
  }
  GNUNET_CONTAINER_multihashmap_iterator_destroy (it);
  return GNUNET_NO;
}


/**
 * Remove client from replay request hashmap.
 *
 * @param client
 *        Client to remove.
 *
 * @return #GNUNET_YES if there are more entries to process,
 *         #GNUNET_NO when reached end of hashmap.
 */
static int
replay_req_remove_client (struct Group *grp, struct GNUNET_SERVER_Client *client)
{
  struct GNUNET_CONTAINER_MultiHashMap *
    grp_replay_req = GNUNET_CONTAINER_multihashmap_get (replay_req_client,
                                                        &grp->pub_key_hash);
  if (NULL == grp_replay_req)
    return GNUNET_NO;

  struct GNUNET_CONTAINER_MultiHashMapIterator *
    it = GNUNET_CONTAINER_multihashmap_iterator_create (grp_replay_req);
  struct GNUNET_HashCode key;
  const struct GNUNET_SERVER_Client *c;
  while (GNUNET_YES
         == GNUNET_CONTAINER_multihashmap_iterator_next (it, &key,
                                                         (const void **) &c))
  {
    if (c == client)
    {
      GNUNET_CONTAINER_multihashmap_remove (replay_req_client, &key, client);
      GNUNET_CONTAINER_multihashmap_iterator_destroy (it);
      return GNUNET_YES;
    }
  }
  GNUNET_CONTAINER_multihashmap_iterator_destroy (it);
  return GNUNET_NO;
}


/**
 * Called whenever a client is disconnected.
 *
 * Frees our resources associated with that client.
 *
 * @param cls  Closure.
 * @param client  Client handle.
 */
static void
client_notify_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
{
  if (NULL == client)
    return;

  struct Group *grp
    = GNUNET_SERVER_client_get_user_context (client, struct Group);

  if (NULL == grp)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "%p User context is NULL in client_disconnect()\n", grp);
    GNUNET_break (0);
    return;
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%p Client (%s) disconnected from group %s\n",
              grp, (GNUNET_YES == grp->is_origin) ? "origin" : "member",
              GNUNET_h2s (&grp->pub_key_hash));

  struct ClientList *cl = grp->clients_head;
  while (NULL != cl)
  {
    if (cl->client == client)
    {
      GNUNET_CONTAINER_DLL_remove (grp->clients_head, grp->clients_tail, cl);
      GNUNET_free (cl);
      break;
    }
    cl = cl->next;
  }

  while (GNUNET_YES == replay_req_remove_client (grp, client));

  if (NULL == grp->clients_head)
  { /* Last client disconnected. */
#if FIXME
    if (NULL != grp->tmit_head)
    { /* Send pending messages via CADET before cleanup. */
      transmit_message (grp);
    }
    else
#endif
    {
      cleanup_group (grp);
    }
  }
}


/**
 * Send message to a client.
 */
static void
client_send (struct GNUNET_SERVER_Client *client,
             const struct GNUNET_MessageHeader *msg)
{
  GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
              "%p Sending message to client.\n", client);

  GNUNET_SERVER_notification_context_add (nc, client);
  GNUNET_SERVER_notification_context_unicast (nc, client, msg, GNUNET_NO);
}


/**
 * Send message to all clients connected to the group.
 */
static void
client_send_group (const struct Group *grp,
                   const struct GNUNET_MessageHeader *msg)
{
  GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
              "%p Sending message to all clients of the group.\n", grp);

  struct ClientList *cl = grp->clients_head;
  while (NULL != cl)
  {
    GNUNET_SERVER_notification_context_add (nc, cl->client);
    GNUNET_SERVER_notification_context_unicast (nc, cl->client, msg, GNUNET_NO);
    cl = cl->next;
  }
}


/**
 * Iterator callback for sending a message to origin clients.
 */
static int
client_send_origin_cb (void *cls, const struct GNUNET_HashCode *pub_key_hash,
                       void *origin)
{
  const struct GNUNET_MessageHeader *msg = cls;
  struct Member *orig = origin;

  client_send_group (&orig->grp, msg);
  return GNUNET_YES;
}


/**
 * Iterator callback for sending a message to member clients.
 */
static int
client_send_member_cb (void *cls, const struct GNUNET_HashCode *pub_key_hash,
                       void *member)
{
  const struct GNUNET_MessageHeader *msg = cls;
  struct Member *mem = member;

  if (NULL != mem->join_dcsn)
  { /* Only send message to admitted members */
    client_send_group (&mem->grp, msg);
  }
  return GNUNET_YES;
}


/**
 * Send message to all origin and member clients connected to the group.
 *
 * @param pub_key_hash
 *        H(key_pub) of the group.
 * @param msg
 *        Message to send.
 */
static int
client_send_all (struct GNUNET_HashCode *pub_key_hash,
                 const struct GNUNET_MessageHeader *msg)
{
  int n = 0;
  n += GNUNET_CONTAINER_multihashmap_get_multiple (origins, pub_key_hash,
                                                   client_send_origin_cb,
                                                   (void *) msg);
  n += GNUNET_CONTAINER_multihashmap_get_multiple (members, pub_key_hash,
                                                   client_send_member_cb,
                                                   (void *) msg);
  return n;
}


/**
 * Send message to a random origin client or a random member client.
 *
 * @param grp  The group to send @a msg to.
 * @param msg  Message to send.
 */
static int
client_send_random (struct GNUNET_HashCode *pub_key_hash,
                    const struct GNUNET_MessageHeader *msg)
{
  int n = 0;
  n = GNUNET_CONTAINER_multihashmap_get_random (origins, client_send_origin_cb,
                                                 (void *) msg);
  if (n <= 0)
    n = GNUNET_CONTAINER_multihashmap_get_random (members, client_send_member_cb,
                                                   (void *) msg);
  return n;
}


/**
 * Send message to all origin clients connected to the group.
 *
 * @param pub_key_hash
 *        H(key_pub) of the group.
 * @param msg
 *        Message to send.
 */
static int
client_send_origin (struct GNUNET_HashCode *pub_key_hash,
                    const struct GNUNET_MessageHeader *msg)
{
  int n = 0;
  n += GNUNET_CONTAINER_multihashmap_get_multiple (origins, pub_key_hash,
                                                   client_send_origin_cb,
                                                   (void *) msg);
  return n;
}


/**
 * Send fragment acknowledgement to all clients of the channel.
 *
 * @param pub_key_hash
 *        H(key_pub) of the group.
 */
static void
client_send_ack (struct GNUNET_HashCode *pub_key_hash)
{
  static struct GNUNET_MessageHeader *msg = NULL;
  if (NULL == msg)
  {
    msg = GNUNET_malloc (sizeof (*msg));
    msg->type = htons (GNUNET_MESSAGE_TYPE_MULTICAST_FRAGMENT_ACK);
    msg->size = htons (sizeof (*msg));
  }
  client_send_all (pub_key_hash, msg);
}


struct CadetTransmitClosure
{
  struct Channel *chn;
  const struct GNUNET_MessageHeader *msg;
};


/**
 * CADET is ready to transmit a message.
 */
size_t
cadet_notify_transmit_ready (void *cls, size_t buf_size, void *buf)
{
  if (0 == buf_size)
  {
    /* FIXME: connection closed */
    return 0;
  }
  struct CadetTransmitClosure *tcls = cls;
  struct Channel *chn = tcls->chn;
  uint16_t msg_size = ntohs (tcls->msg->size);
  GNUNET_assert (msg_size <= buf_size);
  GNUNET_memcpy (buf, tcls->msg, msg_size);
  GNUNET_free (tcls);

  if (0 == chn->msgs_pending)
  {
    GNUNET_break (0);
  }
  else if (0 == --chn->msgs_pending)
  {
    client_send_ack (&chn->group_pub_hash);
  }
  return msg_size;
}


/**
 * Send a message to a CADET channel.
 *
 * @param chn  Channel.
 * @param msg  Message.
 */
static void
cadet_send_channel (struct Channel *chn, const struct GNUNET_MessageHeader *msg)
{
  struct CadetTransmitClosure *tcls = GNUNET_malloc (sizeof (*tcls));
  tcls->chn = chn;
  tcls->msg = msg;

  chn->msgs_pending++;
  chn->tmit_handle
    = GNUNET_CADET_notify_transmit_ready (chn->channel, GNUNET_NO,
                                          GNUNET_TIME_UNIT_FOREVER_REL,
                                          ntohs (msg->size),
                                          &cadet_notify_transmit_ready,
                                          tcls);
  GNUNET_assert (NULL != chn->tmit_handle);
}


/**
 * Create new outgoing CADET channel.
 *
 * @param peer
 *        Peer to connect to.
 * @param group_pub_key
 *        Public key of group the channel belongs to.
 * @param group_pub_hash
 *        Hash of @a group_pub_key.
 *
 * @return Channel.
 */
static struct Channel *
cadet_channel_create (struct Group *grp, struct GNUNET_PeerIdentity *peer)
{
  struct Channel *chn = GNUNET_malloc (sizeof (*chn));
  chn->grp = grp;
  chn->group_pub_key = grp->pub_key;
  chn->group_pub_hash = grp->pub_key_hash;
  chn->peer = *peer;
  chn->direction = DIR_OUTGOING;
  chn->join_status = JOIN_WAITING;
  chn->channel = GNUNET_CADET_channel_create (cadet, chn, &chn->peer,
                                              GNUNET_APPLICATION_TYPE_MULTICAST,
                                              GNUNET_CADET_OPTION_RELIABLE);
  GNUNET_CONTAINER_multihashmap_put (channels_out, &chn->group_pub_hash, chn,
                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
  return chn;
}


/**
 * Create CADET channel and send a join request.
 */
static void
cadet_send_join_request (struct Member *mem)
{
  mem->origin_channel = cadet_channel_create (&mem->grp, &mem->origin);
  cadet_send_channel (mem->origin_channel, &mem->join_req->header);

  uint32_t i;
  for (i = 0; i < mem->relay_count; i++)
  {
    struct Channel *
      chn = cadet_channel_create (&mem->grp, &mem->relays[i]);
    cadet_send_channel (chn, &mem->join_req->header);
  }
}


static int
cadet_send_join_decision_cb (void *cls,
                             const struct GNUNET_HashCode *group_pub_hash,
                             void *channel)
{
  const struct MulticastJoinDecisionMessageHeader *hdcsn = cls;
  struct Channel *chn = channel;

  if (0 == memcmp (&hdcsn->member_pub_key, &chn->member_pub_key, sizeof (chn->member_pub_key))
      && 0 == memcmp (&hdcsn->peer, &chn->peer, sizeof (chn->peer)))
  {
    cadet_send_channel (chn, &hdcsn->header);
    return GNUNET_NO;
  }
  return GNUNET_YES;
}


/**
 * Send join decision to a remote peer.
 */
static void
cadet_send_join_decision (struct Group *grp,
                          const struct MulticastJoinDecisionMessageHeader *hdcsn)
{
  GNUNET_CONTAINER_multihashmap_get_multiple (channels_in, &grp->pub_key_hash,
                                              &cadet_send_join_decision_cb,
                                              (void *) hdcsn);
}


/**
 * Iterator callback for sending a message to origin clients.
 */
static int
cadet_send_cb (void *cls, const struct GNUNET_HashCode *pub_key_hash,
               void *channel)
{
  const struct GNUNET_MessageHeader *msg = cls;
  struct Channel *chn = channel;
  if (JOIN_ADMITTED == chn->join_status)
    cadet_send_channel (chn, msg);
  return GNUNET_YES;
}


/**
 * Send message to all connected children.
 */
static int
cadet_send_children (struct GNUNET_HashCode *pub_key_hash,
                     const struct GNUNET_MessageHeader *msg)
{
  int n = 0;
  if (channels_in != NULL)
    n += GNUNET_CONTAINER_multihashmap_get_multiple (channels_in, pub_key_hash,
                                                     cadet_send_cb, (void *) msg);
  return n;
}


/**
 * Send message to all connected parents.
 */
static int
cadet_send_parents (struct GNUNET_HashCode *pub_key_hash,
                    const struct GNUNET_MessageHeader *msg)
{
  int n = 0;
  if (channels_in != NULL)
    n += GNUNET_CONTAINER_multihashmap_get_multiple (channels_out, pub_key_hash,
                                                     cadet_send_cb, (void *) msg);
  return n;
}


/**
 * Handle a connecting client starting an origin.
 */
static void
client_recv_origin_start (void *cls, struct GNUNET_SERVER_Client *client,
                          const struct GNUNET_MessageHeader *m)
{
  const struct MulticastOriginStartMessage *
    msg = (const struct MulticastOriginStartMessage *) m;

  struct GNUNET_CRYPTO_EddsaPublicKey pub_key;
  struct GNUNET_HashCode pub_key_hash;

  GNUNET_CRYPTO_eddsa_key_get_public (&msg->group_key, &pub_key);
  GNUNET_CRYPTO_hash (&pub_key, sizeof (pub_key), &pub_key_hash);

  struct Origin *
    orig = GNUNET_CONTAINER_multihashmap_get (origins, &pub_key_hash);
  struct Group *grp;

  if (NULL == orig)
  {
    orig = GNUNET_new (struct Origin);
    orig->priv_key = msg->group_key;
    orig->max_fragment_id = GNUNET_ntohll (msg->max_fragment_id);
    grp = &orig->grp;
    grp->is_origin = GNUNET_YES;
    grp->pub_key = pub_key;
    grp->pub_key_hash = pub_key_hash;

    GNUNET_CONTAINER_multihashmap_put (origins, &grp->pub_key_hash, orig,
                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
  }
  else
  {
    grp = &orig->grp;
  }

  struct ClientList *cl = GNUNET_new (struct ClientList);
  cl->client = client;
  GNUNET_CONTAINER_DLL_insert (grp->clients_head, grp->clients_tail, cl);

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%p Client connected as origin to group %s.\n",
              orig, GNUNET_h2s (&grp->pub_key_hash));

  GNUNET_SERVER_client_set_user_context (client, grp);
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Handle a connecting client joining a group.
 */
static void
client_recv_member_join (void *cls, struct GNUNET_SERVER_Client *client,
                         const struct GNUNET_MessageHeader *m)
{
  const struct MulticastMemberJoinMessage *
    msg = (const struct MulticastMemberJoinMessage *) m;
  uint16_t msg_size = ntohs (msg->header.size);

  struct GNUNET_CRYPTO_EcdsaPublicKey mem_pub_key;
  struct GNUNET_HashCode pub_key_hash, mem_pub_key_hash;

  GNUNET_CRYPTO_ecdsa_key_get_public (&msg->member_key, &mem_pub_key);
  GNUNET_CRYPTO_hash (&mem_pub_key, sizeof (mem_pub_key), &mem_pub_key_hash);
  GNUNET_CRYPTO_hash (&msg->group_pub_key, sizeof (msg->group_pub_key), &pub_key_hash);

  struct GNUNET_CONTAINER_MultiHashMap *
    grp_mem = GNUNET_CONTAINER_multihashmap_get (group_members, &pub_key_hash);
  struct Member *mem = NULL;
  struct Group *grp;

  if (NULL != grp_mem)
  {
    mem = GNUNET_CONTAINER_multihashmap_get (grp_mem, &mem_pub_key_hash);
  }
  if (NULL == mem)
  {
    mem = GNUNET_new (struct Member);
    mem->priv_key = msg->member_key;
    mem->pub_key = mem_pub_key;
    mem->pub_key_hash = mem_pub_key_hash;
    mem->max_fragment_id = 0; // FIXME

    grp = &mem->grp;
    grp->is_origin = GNUNET_NO;
    grp->pub_key = msg->group_pub_key;
    grp->pub_key_hash = pub_key_hash;

    if (NULL == grp_mem)
    {
      grp_mem = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
      GNUNET_CONTAINER_multihashmap_put (group_members, &grp->pub_key_hash, grp_mem,
                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
    }
    GNUNET_CONTAINER_multihashmap_put (grp_mem, &mem->pub_key_hash, mem,
                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
    GNUNET_CONTAINER_multihashmap_put (members, &grp->pub_key_hash, mem,
                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
  }
  else
  {
    grp = &mem->grp;
  }

  struct ClientList *cl = GNUNET_new (struct ClientList);
  cl->client = client;
  GNUNET_CONTAINER_DLL_insert (grp->clients_head, grp->clients_tail, cl);

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%p Client connected to group %s..\n",
              mem, GNUNET_h2s (&grp->pub_key_hash));
  char *str = GNUNET_CRYPTO_ecdsa_public_key_to_string (&mem->pub_key);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%p ..as member %s (%s).\n",
              mem, GNUNET_h2s (&mem->pub_key_hash), str);
  GNUNET_free (str);

  GNUNET_SERVER_client_set_user_context (client, grp);

  if (NULL != mem->join_dcsn)
  { /* Already got a join decision, send it to client. */
    GNUNET_SERVER_notification_context_add (nc, client);
    GNUNET_SERVER_notification_context_unicast (nc, client,
                                                (struct GNUNET_MessageHeader *)
                                                mem->join_dcsn,
                                                GNUNET_NO);
  }
  else
  { /* First client of the group, send join request. */
    struct GNUNET_PeerIdentity *relays = (struct GNUNET_PeerIdentity *) &msg[1];
    uint32_t relay_count = ntohl (msg->relay_count);
    uint16_t relay_size = relay_count * sizeof (*relays);
    struct GNUNET_MessageHeader *join_msg = NULL;
    uint16_t join_msg_size = 0;
    if (sizeof (*msg) + relay_size + sizeof (struct GNUNET_MessageHeader)
        <= msg_size)
    {
      join_msg = (struct GNUNET_MessageHeader *)
        (((char *) &msg[1]) + relay_size);
      join_msg_size = ntohs (join_msg->size);
    }
    if (sizeof (*msg) + relay_size + join_msg_size != msg_size)
    {
      GNUNET_break (0);
      GNUNET_SERVER_client_disconnect (client);
      return;
    }

    struct MulticastJoinRequestMessage *
      req = GNUNET_malloc (sizeof (*req) + join_msg_size);
    req->header.size = htons (sizeof (*req) + join_msg_size);
    req->header.type = htons (GNUNET_MESSAGE_TYPE_MULTICAST_JOIN_REQUEST);
    req->group_pub_key = grp->pub_key;
    req->peer = this_peer;
    GNUNET_CRYPTO_ecdsa_key_get_public (&mem->priv_key, &req->member_pub_key);
    if (0 < join_msg_size)
      GNUNET_memcpy (&req[1], join_msg, join_msg_size);

    req->member_pub_key = mem->pub_key;
    req->purpose.size = htonl (msg_size
                               - sizeof (req->header)
                               - sizeof (req->reserved)
                               - sizeof (req->signature));
    req->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MULTICAST_REQUEST);

    if (GNUNET_OK != GNUNET_CRYPTO_ecdsa_sign (&mem->priv_key, &req->purpose,
                                               &req->signature))
    {
      /* FIXME: handle error */
      GNUNET_assert (0);
    }

    if (NULL != mem->join_req)
      GNUNET_free (mem->join_req);
    mem->join_req = req;

    if (0 == client_send_origin (&grp->pub_key_hash, &mem->join_req->header))
    { /* No local origins, send to remote origin */
      cadet_send_join_request (mem);
    }
  }
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


static void
client_send_join_decision (struct Member *mem,
                           const struct MulticastJoinDecisionMessageHeader *hdcsn)
{
  client_send_group (&mem->grp, &hdcsn->header);

  const struct MulticastJoinDecisionMessage *
    dcsn = (const struct MulticastJoinDecisionMessage *) &hdcsn[1];
  if (GNUNET_YES == ntohl (dcsn->is_admitted))
  { /* Member admitted, store join_decision. */
    uint16_t dcsn_size = ntohs (dcsn->header.size);
    mem->join_dcsn = GNUNET_malloc (dcsn_size);
    GNUNET_memcpy (mem->join_dcsn, dcsn, dcsn_size);
  }
  else
  { /* Refused entry, but replay would be still possible for past members. */
  }
}


/**
 * Join decision from client.
 */
static void
client_recv_join_decision (void *cls, struct GNUNET_SERVER_Client *client,
                           const struct GNUNET_MessageHeader *m)
{
  struct Group *
    grp = GNUNET_SERVER_client_get_user_context (client, struct Group);
  const struct MulticastJoinDecisionMessageHeader *
    hdcsn = (const struct MulticastJoinDecisionMessageHeader *) m;

  if (NULL == grp)
  {
    GNUNET_break (0);
    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "%p Got join decision from client for group %s..\n",
              grp, GNUNET_h2s (&grp->pub_key_hash));

  struct GNUNET_CONTAINER_MultiHashMap *
    grp_mem = GNUNET_CONTAINER_multihashmap_get (group_members,
                                                 &grp->pub_key_hash);
  struct Member *mem = NULL;
  if (NULL != grp_mem)
  {
    struct GNUNET_HashCode member_key_hash;
    GNUNET_CRYPTO_hash (&hdcsn->member_pub_key, sizeof (hdcsn->member_pub_key),
                        &member_key_hash);
    mem = GNUNET_CONTAINER_multihashmap_get (grp_mem, &member_key_hash);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "%p ..and member %s: %p\n",
                grp, GNUNET_h2s (&member_key_hash), mem);
  }
  if (NULL != mem)
  { /* Found local member */
    client_send_join_decision (mem, hdcsn);
  }
  else
  { /* Look for remote member */
    cadet_send_join_decision (grp, hdcsn);
  }
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Incoming message from a client.
 */
static void
client_recv_multicast_message (void *cls, struct GNUNET_SERVER_Client *client,
                               const struct GNUNET_MessageHeader *m)
{
  struct Group *
    grp = GNUNET_SERVER_client_get_user_context (client, struct Group);
  struct GNUNET_MULTICAST_MessageHeader *out;
  struct Origin *orig;

  if (NULL == grp)
  {
    GNUNET_break (0);
    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
    return;
  }
  GNUNET_assert (GNUNET_YES == grp->is_origin);
  orig = (struct Origin *) grp;

  /* FIXME: yucky, should use separate message structs for P2P and CS! */
  out = (struct GNUNET_MULTICAST_MessageHeader *) GNUNET_copy_message (m);
  out->fragment_id = GNUNET_htonll (++orig->max_fragment_id);
  out->purpose.size = htonl (ntohs (out->header.size)
                             - sizeof (out->header)
                             - sizeof (out->hop_counter)
                             - sizeof (out->signature));
  out->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MULTICAST_MESSAGE);

  if (GNUNET_OK != GNUNET_CRYPTO_eddsa_sign (&orig->priv_key, &out->purpose,
                                             &out->signature))
  {
    GNUNET_assert (0);
  }

  client_send_all (&grp->pub_key_hash, &out->header);
  if (0 == cadet_send_children (&grp->pub_key_hash, &out->header))
  {
    client_send_ack (&grp->pub_key_hash);
  }
  GNUNET_free (out);

  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Incoming request from a client.
 */
static void
client_recv_multicast_request (void *cls, struct GNUNET_SERVER_Client *client,
                               const struct GNUNET_MessageHeader *m)
{
  struct Group *grp = GNUNET_SERVER_client_get_user_context (client, struct Group);
  struct Member *mem;
  struct GNUNET_MULTICAST_RequestHeader *out;
  if (NULL == grp)
  {
    GNUNET_break (0);
    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
    return;
  }
  GNUNET_assert (GNUNET_NO == grp->is_origin);
  mem = (struct Member *) grp;

  /* FIXME: yucky, should use separate message structs for P2P and CS! */
  out = (struct GNUNET_MULTICAST_RequestHeader *) GNUNET_copy_message (m);
  out->member_pub_key = mem->pub_key;
  out->fragment_id = GNUNET_ntohll (++mem->max_fragment_id);
  out->purpose.size = htonl (ntohs (out->header.size)
                             - sizeof (out->header)
                             - sizeof (out->member_pub_key)
                             - sizeof (out->signature));
  out->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MULTICAST_REQUEST);

  if (GNUNET_OK != GNUNET_CRYPTO_ecdsa_sign (&mem->priv_key, &out->purpose,
                                             &out->signature))
  {
    GNUNET_assert (0);
  }

  uint8_t send_ack = GNUNET_YES;
  if (0 == client_send_origin (&grp->pub_key_hash, &out->header))
  { /* No local origins, send to remote origin */
    if (NULL != mem->origin_channel)
    {
      cadet_send_channel (mem->origin_channel, &out->header);
      send_ack = GNUNET_NO;
    }
    else
    {
      /* FIXME: not yet connected to origin */
      GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
      GNUNET_free (out);
      return;
    }
  }
  if (GNUNET_YES == send_ack)
  {
    client_send_ack (&grp->pub_key_hash);
  }
  GNUNET_free (out);
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Incoming replay request from a client.
 */
static void
client_recv_replay_request (void *cls, struct GNUNET_SERVER_Client *client,
                            const struct GNUNET_MessageHeader *m)
{
  struct Group *grp = GNUNET_SERVER_client_get_user_context (client, struct Group);
  struct Member *mem;
  if (NULL == grp)
  {
    GNUNET_break (0);
    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
    return;
  }
  GNUNET_assert (GNUNET_NO == grp->is_origin);
  mem = (struct Member *) grp;

  struct GNUNET_CONTAINER_MultiHashMap *
    grp_replay_req = GNUNET_CONTAINER_multihashmap_get (replay_req_client,
                                                        &grp->pub_key_hash);
  if (NULL == grp_replay_req)
  {
    grp_replay_req = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
    GNUNET_CONTAINER_multihashmap_put (replay_req_client,
                                       &grp->pub_key_hash, grp_replay_req,
                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
  }
  struct MulticastReplayRequestMessage *
    rep = (struct MulticastReplayRequestMessage *) m;
  struct GNUNET_HashCode key_hash;
  replay_key_hash (rep->fragment_id, rep->message_id, rep->fragment_offset,
                   rep->flags, &key_hash);
  GNUNET_CONTAINER_multihashmap_put (grp_replay_req, &key_hash, client,
                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);

  if (0 == client_send_origin (&grp->pub_key_hash, m))
  { /* No local origin, replay from remote members / origin. */
    if (NULL != mem->origin_channel)
    {
      cadet_send_channel (mem->origin_channel, m);
    }
    else
    {
      /* FIXME: not yet connected to origin */
      GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
      return;
    }
  }
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


static int
cadet_send_replay_response_cb (void *cls,
                               const struct GNUNET_HashCode *key_hash,
                               void *value)
{
  struct Channel *chn = value;
  struct GNUNET_MessageHeader *msg = cls;

  cadet_send_channel (chn, msg);
  return GNUNET_OK;
}


static int
client_send_replay_response_cb (void *cls,
                                const struct GNUNET_HashCode *key_hash,
                                void *value)
{
  struct GNUNET_SERVER_Client *client = value;
  struct GNUNET_MessageHeader *msg = cls;

  client_send (client, msg);
  return GNUNET_OK;
}


/**
 * End of replay response from a client.
 */
static void
client_recv_replay_response_end (void *cls, struct GNUNET_SERVER_Client *client,
                                 const struct GNUNET_MessageHeader *m)
{
  struct Group *grp = GNUNET_SERVER_client_get_user_context (client, struct Group);
  if (NULL == grp)
  {
    GNUNET_break (0);
    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
    return;
  }

  struct MulticastReplayResponseMessage *
    res = (struct MulticastReplayResponseMessage *) m;

  struct GNUNET_HashCode key_hash;
  replay_key_hash (res->fragment_id, res->message_id, res->fragment_offset,
                   res->flags, &key_hash);

  struct GNUNET_CONTAINER_MultiHashMap *
    grp_replay_req_cadet = GNUNET_CONTAINER_multihashmap_get (replay_req_cadet,
                                                                &grp->pub_key_hash);
  if (NULL != grp_replay_req_cadet)
  {
    GNUNET_CONTAINER_multihashmap_remove_all (grp_replay_req_cadet, &key_hash);
  }
  struct GNUNET_CONTAINER_MultiHashMap *
    grp_replay_req_client = GNUNET_CONTAINER_multihashmap_get (replay_req_client,
                                                               &grp->pub_key_hash);
  if (NULL != grp_replay_req_client)
  {
    GNUNET_CONTAINER_multihashmap_remove_all (grp_replay_req_client, &key_hash);
  }
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * Incoming replay response from a client.
 *
 * Respond with a multicast message on success, or otherwise with an error code.
 */
static void
client_recv_replay_response (void *cls, struct GNUNET_SERVER_Client *client,
                             const struct GNUNET_MessageHeader *m)
{
  struct Group *grp = GNUNET_SERVER_client_get_user_context (client, struct Group);
  if (NULL == grp)
  {
    GNUNET_break (0);
    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
    return;
  }

  struct MulticastReplayResponseMessage *
    res = (struct MulticastReplayResponseMessage *) m;

  const struct GNUNET_MessageHeader *msg = m;
  if (GNUNET_MULTICAST_REC_OK == res->error_code)
  {
    msg = (struct GNUNET_MessageHeader *) &res[1];
  }

  struct GNUNET_HashCode key_hash;
  replay_key_hash (res->fragment_id, res->message_id, res->fragment_offset,
                   res->flags, &key_hash);

  struct GNUNET_CONTAINER_MultiHashMap *
    grp_replay_req_cadet = GNUNET_CONTAINER_multihashmap_get (replay_req_cadet,
                                                              &grp->pub_key_hash);
  if (NULL != grp_replay_req_cadet)
  {
    GNUNET_CONTAINER_multihashmap_get_multiple (grp_replay_req_cadet, &key_hash,
                                                cadet_send_replay_response_cb,
                                                (void *) msg);
  }
  if (GNUNET_MULTICAST_REC_OK == res->error_code)
  {
    struct GNUNET_CONTAINER_MultiHashMap *
      grp_replay_req_client = GNUNET_CONTAINER_multihashmap_get (replay_req_client,
                                                                 &grp->pub_key_hash);
    if (NULL != grp_replay_req_client)
    {
      GNUNET_CONTAINER_multihashmap_get_multiple (grp_replay_req_client, &key_hash,
                                                  client_send_replay_response_cb,
                                                  (void *) msg);
    }
  }
  else
  {
    client_recv_replay_response_end (cls, client, m);
    return;
  }
  GNUNET_SERVER_receive_done (client, GNUNET_OK);
}


/**
 * A new client connected.
 */
static void
client_notify_connect (void *cls, struct GNUNET_SERVER_Client *client)
{
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client connected: %p\n", client);
  /* FIXME: send connect ACK */
}


/**
 * Message handlers for the server.
 */
static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
  { client_recv_origin_start, NULL,
    GNUNET_MESSAGE_TYPE_MULTICAST_ORIGIN_START, 0 },

  { client_recv_member_join, NULL,
    GNUNET_MESSAGE_TYPE_MULTICAST_MEMBER_JOIN, 0 },

  { client_recv_join_decision, NULL,
    GNUNET_MESSAGE_TYPE_MULTICAST_JOIN_DECISION, 0 },

  { client_recv_multicast_message, NULL,
    GNUNET_MESSAGE_TYPE_MULTICAST_MESSAGE, 0 },

  { client_recv_multicast_request, NULL,
    GNUNET_MESSAGE_TYPE_MULTICAST_REQUEST, 0 },

  { client_recv_replay_request, NULL,
    GNUNET_MESSAGE_TYPE_MULTICAST_REPLAY_REQUEST, 0 },

  { client_recv_replay_response, NULL,
    GNUNET_MESSAGE_TYPE_MULTICAST_REPLAY_RESPONSE, 0 },

  { client_recv_replay_response_end, NULL,
    GNUNET_MESSAGE_TYPE_MULTICAST_REPLAY_RESPONSE_END, 0 },

  { NULL, NULL, 0, 0 }
};


/**
 * New incoming CADET channel.
 */
static void *
cadet_notify_channel_new (void *cls,
                          struct GNUNET_CADET_Channel *channel,
                          const struct GNUNET_PeerIdentity *initiator,
                          uint32_t port,
                          enum GNUNET_CADET_ChannelOption options)
{
  return NULL;
}


/**
 * CADET channel is being destroyed.
 */
static void
cadet_notify_channel_end (void *cls,
                          const struct GNUNET_CADET_Channel *channel,
                          void *ctx)
{
  if (NULL == ctx)
    return;

  struct Channel *chn = ctx;
  if (NULL != chn->grp)
  {
    if (GNUNET_NO == chn->grp->is_origin)
    {
      struct Member *mem = (struct Member *) chn->grp;
      if (chn == mem->origin_channel)
        mem->origin_channel = NULL;
    }
  }

  while (GNUNET_YES == replay_req_remove_cadet (chn));

  GNUNET_free (chn);
}


/**
 * Incoming join request message from CADET.
 */
int
cadet_recv_join_request (void *cls,
                         struct GNUNET_CADET_Channel *channel,
                         void **ctx,
                         const struct GNUNET_MessageHeader *m)
{
  const struct MulticastJoinRequestMessage *
    req = (const struct MulticastJoinRequestMessage *) m;
  uint16_t size = ntohs (m->size);
  if (size < sizeof (*req))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (NULL != *ctx)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (ntohl (req->purpose.size) != (size
                                    - sizeof (req->header)
                                    - sizeof (req->reserved)
                                    - sizeof (req->signature)))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_MULTICAST_REQUEST,
                                  &req->purpose, &req->signature,
                                  &req->member_pub_key))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  struct GNUNET_HashCode group_pub_hash;
  GNUNET_CRYPTO_hash (&req->group_pub_key, sizeof (req->group_pub_key), &group_pub_hash);

  struct Channel *chn = GNUNET_malloc (sizeof *chn);
  chn->channel = channel;
  chn->group_pub_key = req->group_pub_key;
  chn->group_pub_hash = group_pub_hash;
  chn->member_pub_key = req->member_pub_key;
  chn->peer = req->peer;
  chn->join_status = JOIN_WAITING;
  GNUNET_CONTAINER_multihashmap_put (channels_in, &chn->group_pub_hash, chn,
                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);

  client_send_all (&group_pub_hash, m);
  return GNUNET_OK;
}


/**
 * Incoming join decision message from CADET.
 */
int
cadet_recv_join_decision (void *cls,
                          struct GNUNET_CADET_Channel *channel,
                          void **ctx,
                          const struct GNUNET_MessageHeader *m)
{
  const struct MulticastJoinDecisionMessage *
    dcsn = (const struct MulticastJoinDecisionMessage *) m;
  uint16_t size = ntohs (m->size);
  if (size < sizeof (*dcsn))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  struct Channel *chn = *ctx;
  if (NULL == chn)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (NULL == chn->grp || GNUNET_NO != chn->grp->is_origin)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  switch (chn->join_status)
  {
  case JOIN_REFUSED:
    return GNUNET_SYSERR;

  case JOIN_ADMITTED:
    return GNUNET_OK;

  case JOIN_NOT_ASKED:
  case JOIN_WAITING:
    break;
  }

  struct MulticastJoinDecisionMessageHeader *
    hdcsn = GNUNET_malloc (sizeof (*hdcsn) + size);
  hdcsn->peer = chn->peer;
  GNUNET_memcpy (&hdcsn[1], dcsn, sizeof (*hdcsn) + size);

  struct Member *mem = (struct Member *) chn->grp;
  client_send_join_decision (mem, hdcsn);
  GNUNET_free (hdcsn);
  if (GNUNET_YES == ntohs (dcsn->is_admitted))
  {
    chn->join_status = JOIN_ADMITTED;
    return GNUNET_OK;
  }
  else
  {
    chn->join_status = JOIN_REFUSED;
    return GNUNET_SYSERR;
  }
}

/**
 * Incoming multicast message from CADET.
 */
int
cadet_recv_message (void *cls,
                    struct GNUNET_CADET_Channel *channel,
                    void **ctx,
                    const struct GNUNET_MessageHeader *m)
{
  const struct GNUNET_MULTICAST_MessageHeader *
    msg = (const struct GNUNET_MULTICAST_MessageHeader *) m;
  uint16_t size = ntohs (m->size);
  if (size < sizeof (*msg))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  struct Channel *chn = *ctx;
  if (NULL == chn)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (ntohl (msg->purpose.size) != (size
                                    - sizeof (msg->header)
                                    - sizeof (msg->hop_counter)
                                    - sizeof (msg->signature)))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_MULTICAST_MESSAGE,
                                  &msg->purpose, &msg->signature,
                                  &chn->group_pub_key))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  client_send_all (&chn->group_pub_hash, m);
  return GNUNET_OK;
}


/**
 * Incoming multicast request message from CADET.
 */
int
cadet_recv_request (void *cls,
                    struct GNUNET_CADET_Channel *channel,
                    void **ctx,
                    const struct GNUNET_MessageHeader *m)
{
  const struct GNUNET_MULTICAST_RequestHeader *
    req = (const struct GNUNET_MULTICAST_RequestHeader *) m;
  uint16_t size = ntohs (m->size);
  if (size < sizeof (*req))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  struct Channel *chn = *ctx;
  if (NULL == chn)
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (ntohl (req->purpose.size) != (size
                                    - sizeof (req->header)
                                    - sizeof (req->member_pub_key)
                                    - sizeof (req->signature)))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_OK !=
      GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_MULTICAST_REQUEST,
                                  &req->purpose, &req->signature,
                                  &req->member_pub_key))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  client_send_origin (&chn->group_pub_hash, m);
  return GNUNET_OK;
}


/**
 * Incoming multicast replay request from CADET.
 */
int
cadet_recv_replay_request (void *cls,
                           struct GNUNET_CADET_Channel *channel,
                           void **ctx,
                           const struct GNUNET_MessageHeader *m)
{
  struct MulticastReplayRequestMessage rep;
  uint16_t size = ntohs (m->size);
  if (size < sizeof (rep))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  struct Channel *chn = *ctx;

  GNUNET_memcpy (&rep, m, sizeof (rep));
  GNUNET_memcpy (&rep.member_pub_key, &chn->member_pub_key, sizeof (chn->member_pub_key));

  struct GNUNET_CONTAINER_MultiHashMap *
    grp_replay_req = GNUNET_CONTAINER_multihashmap_get (replay_req_cadet,
                                                        &chn->grp->pub_key_hash);
  if (NULL == grp_replay_req)
  {
    grp_replay_req = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
    GNUNET_CONTAINER_multihashmap_put (replay_req_cadet,
                                       &chn->grp->pub_key_hash, grp_replay_req,
                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
  }
  struct GNUNET_HashCode key_hash;
  replay_key_hash (rep.fragment_id, rep.message_id, rep.fragment_offset,
                   rep.flags, &key_hash);
  GNUNET_CONTAINER_multihashmap_put (grp_replay_req, &key_hash, chn,
                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);

  client_send_random (&chn->group_pub_hash, &rep.header);
  return GNUNET_OK;
}


/**
 * Incoming multicast replay response from CADET.
 */
int
cadet_recv_replay_response (void *cls,
                            struct GNUNET_CADET_Channel *channel,
                            void **ctx,
                            const struct GNUNET_MessageHeader *m)
{
  struct Channel *chn = *ctx;

  /* @todo FIXME: got replay error response, send request to other members */

  return GNUNET_OK;
}


/**
 * Message handlers for CADET.
 */
static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
  { cadet_recv_join_request,
    GNUNET_MESSAGE_TYPE_MULTICAST_JOIN_REQUEST, 0 },

  { cadet_recv_message,
    GNUNET_MESSAGE_TYPE_MULTICAST_MESSAGE, 0 },

  { cadet_recv_request,
    GNUNET_MESSAGE_TYPE_MULTICAST_REQUEST, 0 },

  { cadet_recv_replay_request,
    GNUNET_MESSAGE_TYPE_MULTICAST_REPLAY_REQUEST, 0 },

  { cadet_recv_replay_response,
    GNUNET_MESSAGE_TYPE_MULTICAST_REPLAY_RESPONSE, 0 },

  { NULL, 0, 0 }
};


/**
 * Listening ports for CADET.
 */
static const uint32_t cadet_ports[] = { GNUNET_APPLICATION_TYPE_MULTICAST, 0 };


/**
 * Connected to core service.
 */
static void
core_connected_cb  (void *cls, const struct GNUNET_PeerIdentity *my_identity)
{
  this_peer = *my_identity;

  stats = GNUNET_STATISTICS_create ("multicast", cfg);
  origins = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
  members = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
  group_members = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
  channels_in = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
  channels_out = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
  replay_req_cadet = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
  replay_req_client = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);

  cadet = GNUNET_CADET_connect (cfg, NULL,
                                &cadet_notify_channel_new,
                                &cadet_notify_channel_end,
                                cadet_handlers, cadet_ports);

  nc = GNUNET_SERVER_notification_context_create (server, 1);
  GNUNET_SERVER_add_handlers (server, server_handlers);
  GNUNET_SERVER_disconnect_notify (server,
				   &client_notify_disconnect, NULL);
  GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
				 NULL);
}


/**
 * Service started.
 *
 * @param cls closure
 * @param server the initialized server
 * @param cfg configuration to use
 */
static void
run (void *cls,
     struct GNUNET_SERVER_Handle *srv,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  cfg = c;
  server = srv;
  GNUNET_SERVER_connect_notify (server, &client_notify_connect, NULL);
  core = GNUNET_CORE_connect (cfg, NULL, &core_connected_cb, NULL, NULL,
                              NULL, GNUNET_NO, NULL, GNUNET_NO, NULL);
}


/**
 * The main function for the multicast service.
 *
 * @param argc number of arguments from the command line
 * @param argv command line arguments
 * @return 0 ok, 1 on error
 */
int
main (int argc, char *const *argv)
{
  return (GNUNET_OK ==
          GNUNET_SERVICE_run (argc, argv, "multicast",
                              GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
}

/* end of gnunet-service-multicast.c */