saltyrtc-client 0.8.0

Asynchronous SaltyRTC client implementation for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
//! Protocol implementation.
//!
//! Incoming messages can be passed to a [`Signaling`](trait.Signaling.html)
//! implementation where they will be processed. Instead of sending responses
//! through the network directly, a [`HandleAction`](types/enum.HandleAction.html)
//! is returned.
//!
//! All peer related state is contained in the [context
//! structs](context/index.html), depending on the role.

use std::{
    collections::{HashMap, HashSet},
    mem,
    sync::{Arc, Mutex},
    time::Duration,
};

use crypto_box::aead::{
    generic_array::{typenum::U24, GenericArray},
    Aead,
};
use rmpv::Value;

use crate::{
    boxes::{ByteBox, OpenBox},
    crypto::{AuthToken, KeyPair, PublicKey},
    errors::{SaltyError, SignalingError, SignalingResult, ValidationError},
};

pub(crate) mod context;
pub(crate) mod cookie;
pub(crate) mod csn;
pub(crate) mod messages;
pub(crate) mod nonce;
pub(crate) mod send_error;
pub(crate) mod state;
pub(crate) mod types;

#[cfg(test)]
mod tests;

use self::context::{InitiatorContext, PeerContext, ResponderContext, ServerContext};
pub(crate) use self::cookie::Cookie;
use self::messages::{
    Auth, ClientAuth, ClientHello, Close, Disconnected, DropReason, DropResponder,
    InitiatorAuthBuilder, Key, Message, NewInitiator, NewResponder, ResponderAuthBuilder,
    SendError, ServerAuth, ServerHello, Token,
};
pub(crate) use self::nonce::Nonce;
use self::state::{
    InitiatorHandshakeState, ResponderHandshakeState, ServerHandshakeState, SignalingState,
};
pub(crate) use self::types::HandleAction;
pub use self::types::Role;
use self::types::{Address, ClientIdentity, Identity};
use crate::tasks::{BoxedTask, TaskMessage, Tasks};
use crate::{CloseCode, Event};

/// The main signaling trait.
///
/// This is implemented by both the initiator and responder signaling structs.
/// It handles all signaling state and processes incoming messages.
pub(crate) trait Signaling {
    /// Return reference to the common data.
    fn common(&self) -> &Common;

    /// Return mutable reference to the common data.
    fn common_mut(&mut self) -> &mut Common;

    /// Return reference to the server context.
    fn server(&self) -> &ServerContext {
        &self.common().server
    }

    /// Return mutable reference to the server context.
    fn server_mut(&mut self) -> &mut ServerContext {
        &mut self.common_mut().server
    }

    /// Return the identity.
    fn identity(&self) -> ClientIdentity {
        self.common().identity
    }

    /// Return the role.
    fn role(&self) -> Role {
        self.common().role
    }

    /// Return the auth token (if set).
    fn auth_token(&self) -> Option<&AuthToken> {
        if let Some(AuthProvider::Token(ref token)) = self.common().auth_provider {
            Some(token)
        } else {
            None
        }
    }

    /// Return the server handshake state.
    fn server_handshake_state(&self) -> ServerHandshakeState {
        self.server().handshake_state()
    }

    /// Validate the nonce.
    fn validate_nonce(&mut self, nonce: &Nonce) -> Result<(), ValidationError> {
        self.validate_nonce_destination(nonce)?;
        self.validate_nonce_source(nonce)?;
        self.validate_nonce_csn(nonce)?;
        self.validate_nonce_cookie(nonce)?;
        Ok(())
    }

    /// Validate the repeated cookie from the `Auth` message.
    fn validate_repeated_cookie(
        &self,
        repeated_cookie: &Cookie,
        our_cookie: &Cookie,
        identity: Identity,
    ) -> Result<(), SignalingError> {
        if repeated_cookie != our_cookie {
            debug!("Our cookie: {:?}", our_cookie);
            debug!("Their cookie: {:?}", repeated_cookie);
            return Err(SignalingError::Protocol(format!(
                "Repeated cookie in auth message from {} does not match our cookie",
                identity
            )));
        }
        Ok(())
    }

    /// Return the peer context.
    ///
    /// May return `None` if the peer is not yet set.
    fn get_peer(&self) -> Option<&dyn PeerContext>;

    /// Return the peer context with the specified address.
    fn get_peer_with_address_mut(&mut self, addr: Address) -> Option<&mut dyn PeerContext>;

    /// Return the initiator public permanent key.
    fn initiator_pubkey(&self) -> &PublicKey;

    /// If the peer is already determined, return the current incoming and
    /// outgoing sequence numbers.
    fn current_peer_sequence_numbers(&self) -> Option<csn::PeerSequenceNumbers> {
        self.get_peer()
            // Get reference to peer CSN pair
            .map(|peer: &dyn PeerContext| peer.csn_pair())
            // Acquire read lock
            .map(|csn_pair_lock| csn_pair_lock.read().expect("CSN pair rwlock is poisoned"))
            // If both our and their CNS are available, return a snapshot.
            // Otherwise, return None.
            .and_then(|csn_pair| match csn_pair.theirs {
                Some(ref theirs) => Some(csn::PeerSequenceNumbers {
                    outgoing: csn_pair.ours.combined_sequence_number(),
                    incoming: theirs.combined_sequence_number(),
                }),
                None => None,
            })
    }

    /// Validate the nonce destination.
    fn validate_nonce_destination(&mut self, nonce: &Nonce) -> Result<(), ValidationError>;

    /// Validate the nonce source.
    fn validate_nonce_source(&mut self, nonce: &Nonce) -> Result<(), ValidationError>;

    /// Validate the nonce CSN.
    fn validate_nonce_csn(&mut self, nonce: &Nonce) -> Result<(), ValidationError> {
        // Validate CSN
        //
        // In case this is the first message received from the sender, the peer:
        //
        // * MUST check that the overflow number of the source peer is 0 and,
        // * if the peer has already sent a message to the sender, MUST check
        //   that the sender's cookie is different than its own cookie, and
        // * MUST store the combined sequence number for checks on further messages.
        // * The above number(s) SHALL be stored and updated separately for
        //   each other peer by its identity (source address in this case).
        //
        // Otherwise, the peer:
        //
        // * MUST check that the combined sequence number of the source peer
        //   has been increased by 1 and has not reset to 0.
        let role = self.role();
        let peer: &mut dyn PeerContext = self
            .get_peer_with_address_mut(nonce.source())
            .ok_or_else(|| {
                if role == Role::Initiator && nonce.source().is_responder() {
                    // Note: This can happen since a message from a responder may still be in flight.
                    ValidationError::DropMsg(format!(
                        "Could not find responder with address {}",
                        nonce.source()
                    ))
                } else {
                    ValidationError::Crash(
                        "Got message from invalid sender that wasn't dropped".into(),
                    )
                }
            })?;

        let peer_identity = peer.identity();
        let mut csn_pair = peer.csn_pair().try_write()?;

        // If we already have the CSN of the peer,
        // ensure that it has been increased properly.
        if let Some(ref mut csn) = csn_pair.theirs {
            let previous = csn;
            let current = nonce.csn();
            if current < previous {
                let msg = format!("The {} CSN is lower than last time", peer_identity);
                return Err(ValidationError::Fail(msg));
            } else if current == previous {
                let msg = format!("The {} CSN hasn't been incremented", peer_identity);
                return Err(ValidationError::Fail(msg));
            } else {
                *previous = current.clone();
            }
        }

        // Otherwise, this is the first message from that peer.
        if csn_pair.theirs.is_none() {
            // Validate the overflow number...
            if nonce.csn().overflow_number() != 0 {
                let msg = format!(
                    "First message from {} must have set the overflow number to 0",
                    peer.identity()
                );
                return Err(ValidationError::Fail(msg));
            }
            // ...and store the CSN.
            csn_pair.theirs = Some(nonce.csn().clone());
        }

        Ok(())
    }

    /// Validate the nonce cookie.
    fn validate_nonce_cookie(&mut self, nonce: &Nonce) -> Result<(), ValidationError> {
        // Validate cookie
        //
        // In case this is the first message received from the sender:
        //
        // * If the peer has already sent a message to the sender, it MUST
        //   check that the sender's cookie is different than its own cookie, and
        // * MUST store cookie for checks on further messages
        // * The above number(s) SHALL be stored and updated separately for
        //   each other peer by its identity (source address in this case).
        //
        // Otherwise, the peer:
        //
        // * MUST ensure that the 16 byte cookie of the sender has not changed
        let role = self.role();
        let peer: &mut dyn PeerContext = self
            .get_peer_with_address_mut(nonce.source())
            .ok_or_else(|| {
                if role == Role::Initiator && nonce.source().is_responder() {
                    // Note: This can happen since a message from a responder may still be in flight.
                    ValidationError::DropMsg(format!(
                        "Could not find responder with address {}",
                        nonce.source()
                    ))
                } else {
                    ValidationError::Crash(
                        "Got message from invalid sender that wasn't dropped".into(),
                    )
                }
            })?;

        let peer_identity = peer.identity();
        let cookie_pair = peer.cookie_pair_mut();

        match cookie_pair.theirs {
            None => {
                // This is the first message from that peer,
                if *nonce.cookie() == cookie_pair.ours {
                    // validate the cookie...
                    Err(ValidationError::Fail(format!(
                        "Cookie from {} is identical to our own cookie",
                        peer_identity
                    )))
                } else {
                    // ...and store it.
                    cookie_pair.theirs = Some(nonce.cookie().clone());
                    Ok(())
                }
            }
            Some(ref cookie) => {
                // Ensure that the cookie has not changed
                if nonce.cookie() != cookie {
                    Err(ValidationError::Fail(format!(
                        "Cookie from {} has changed",
                        peer_identity
                    )))
                } else {
                    Ok(())
                }
            }
        }
    }

    /// Handle an incoming message.
    fn handle_message(&mut self, bbox: ByteBox) -> SignalingResult<Vec<HandleAction>> {
        trace!("handle_message");

        // Validate the nonce
        match self.validate_nonce(&bbox.nonce) {
            // It's valid! Carry on.
            Ok(_) => {}

            // Drop and ignore some of the messages
            Err(ValidationError::DropMsg(warning)) => {
                warn!("Invalid nonce: {}", warning);
                return Ok(vec![]);
            }

            // Nonce is invalid, fail the signaling
            Err(ValidationError::Fail(reason)) => return Err(SignalingError::InvalidNonce(reason)),

            // A critical error occurred
            Err(ValidationError::Crash(reason)) => return Err(SignalingError::Crash(reason)),
        };

        if bbox.nonce.source().is_server() {
            // We need to clone the nonce here, in case we need it to verify
            // the signed keys sent in the 'server-auth' message.
            // Unfortunately at this point in time we don't know yet whether
            // the message actually is a 'server-auth' message...
            let nonce_unsafe_clone = unsafe { bbox.nonce.clone() };

            // Decode the message from the server
            let obox: OpenBox<Message> = self.decode_server_message(bbox)?;

            // Only keep the nonce clone if this is a 'server-auth' message
            let nonce_clone_opt = if obox.message.get_type() == "server-auth" {
                Some(nonce_unsafe_clone)
            } else {
                None
            };

            // Process the server message
            self.handle_server_message(obox, nonce_clone_opt)
        } else {
            match self.common().signaling_state() {
                SignalingState::ServerHandshake => self.handle_handshake_peer_message(bbox),
                SignalingState::PeerHandshake => self.handle_handshake_peer_message(bbox),
                SignalingState::Task => self.handle_task_peer_message(bbox),
            }
        }
    }

    /// Handle an incoming handshake message from a peer.
    fn handle_handshake_peer_message(
        &mut self,
        bbox: ByteBox,
    ) -> SignalingResult<Vec<HandleAction>> {
        trace!("handle_handshake_peer_message");

        // Sanity check
        if bbox.nonce.source().is_server() {
            return Err(SignalingError::Crash(
                "Message in handle_handshake_peer_message is from server!".into(),
            ));
        }

        // Decode message
        let obox: OpenBox<Message> = {
            let source_address = bbox.nonce.source();
            match self.decode_peer_message(bbox) {
                Ok(obox) => obox,
                Err(SignalingError::InitiatorCouldNotDecrypt) => {
                    let drop_responder = self.send_drop_responder(
                        source_address,
                        DropReason::InitiatorCouldNotDecrypt,
                    )?;
                    debug!(
                        "<-- Enqueuing drop-responder to {}",
                        self.server().identity()
                    );
                    return Ok(vec![drop_responder]);
                }
                Err(e) => return Err(e),
            }
        };

        // Handle message depending on state
        match self.common().signaling_state() {
            // Server handshake
            SignalingState::ServerHandshake => Err(SignalingError::Crash(
                "Illegal signaling state: ServerHandshake".into(),
            )),

            // Peer handshake
            SignalingState::PeerHandshake if obox.nonce.source().is_server() => {
                self.handle_server_message(obox, None)
            }
            SignalingState::PeerHandshake => self.handle_peer_message(obox),

            // Task
            SignalingState::Task => Err(SignalingError::Crash(
                "Illegal signaling state: Task".into(),
            )),
        }
    }

    /// Handle an incoming task message from a peer.
    fn handle_task_peer_message(&mut self, bbox: ByteBox) -> SignalingResult<Vec<HandleAction>> {
        trace!("handle_task_peer_message");

        // Sanity check
        if bbox.nonce.source().is_server() {
            return Err(SignalingError::Crash(
                "Message in handle_task_peer_message is from server!".into(),
            ));
        }

        // Decode message
        let obox: OpenBox<Value> = self.decode_task_message(bbox)?;

        // Convert to HashMap
        let mut map: HashMap<String, Value> = HashMap::new();
        match obox.message {
            Value::Map(pairs) => {
                for (k, v) in pairs {
                    let key = k.as_str().ok_or_else(|| {
                        SignalingError::InvalidMessage(
                            "Task message map contains non-hashable key".into(),
                        )
                    })?;
                    map.insert(key.into(), v);
                }
            }
            _ => {
                return Err(SignalingError::InvalidMessage(
                    "Task message is not a map".into(),
                ))
            }
        };

        // Check msg type
        let msg_type = map
            .get("type")
            .ok_or_else(|| {
                SignalingError::InvalidMessage("Task message does not contain type field".into())
            })?
            .as_str()
            .ok_or_else(|| {
                SignalingError::InvalidMessage("Task message type is not a string".into())
            })?
            .to_owned();
        debug!("Received {} message from peer", msg_type);

        // Handle application messages
        if msg_type == "application" {
            let data: Value = map
                .get("data")
                .ok_or_else(|| {
                    SignalingError::InvalidMessage(
                        "Application message does not contain a data field".into(),
                    )
                })?
                .to_owned();
            return Ok(vec![HandleAction::TaskMessage(TaskMessage::Application(
                data,
            ))]);
        }

        // Handle close messages
        if msg_type == "close" {
            let reason: CloseCode = map
                .get("reason")
                .ok_or_else(|| {
                    SignalingError::InvalidMessage(
                        "Close message does not contain a reason field".into(),
                    )
                })?
                .as_u64()
                .ok_or_else(|| {
                    SignalingError::InvalidMessage("Close message reason is not an integer".into())
                })
                .and_then(|val: u64| {
                    if val > u64::from(::std::u16::MAX) {
                        Err(SignalingError::InvalidMessage(
                            "Close message reason code is too large".into(),
                        ))
                    } else {
                        Ok(val as u16)
                    }
                })
                .map(CloseCode::from_number)?;
            return Ok(vec![HandleAction::TaskMessage(TaskMessage::Close(reason))]);
        }

        // Pass supported task message to task
        let task_supported_types = self
            .common()
            .task_supported_types
            .ok_or_else(|| SignalingError::Crash("Task supported types not set".into()))?;
        if task_supported_types.iter().any(|t| *t == msg_type) {
            return Ok(vec![HandleAction::TaskMessage(TaskMessage::Value(map))]);
        }

        warn!(
            "Received task message with unsupported type: {}. Ignoring.",
            msg_type
        );
        Ok(vec![])
    }

    // Message decoding

    /// Decode or decrypt a binary message coming from the server.
    fn decode_server_message(&self, bbox: ByteBox) -> SignalingResult<OpenBox<Message>> {
        // The very first message from the server is unencrypted
        if self.common().signaling_state() == SignalingState::ServerHandshake
            && self.server_handshake_state() == ServerHandshakeState::New
        {
            return OpenBox::decode(bbox);
        }

        // Otherwise, decrypt with server key
        match self.server().session_key {
            Some(ref pubkey) => {
                OpenBox::<Message>::decrypt(bbox, &self.common().permanent_keypair, pubkey)
            }
            None => Err(SignalingError::Crash("Missing server session key".into())),
        }
    }

    /// Decrypt a binary message coming from a peer.
    fn decode_peer_message(&self, bbox: ByteBox) -> SignalingResult<OpenBox<Message>>;

    /// Decrypt a binary message after the handshake has been finished.
    fn decode_task_message(&self, bbox: ByteBox) -> SignalingResult<OpenBox<Value>> {
        let peer = self
            .get_peer()
            .ok_or_else(|| SignalingError::Crash("Peer not set".into()))?;
        let session_key = peer
            .session_key()
            .ok_or_else(|| SignalingError::Crash("Peer session key not set".into()))?;
        OpenBox::<Value>::decrypt(
            bbox,
            peer.keypair().ok_or_else(|| {
                SignalingError::Crash("Peer session keypair not available".into())
            })?,
            session_key,
        )
    }

    // Message encoding

    /// Encode and encrypt a `Value` for the chosen peer. This is used by the task.
    fn encode_task_message(&self, value: Value) -> SignalingResult<ByteBox> {
        // Check state
        let signaling_state = self.common().signaling_state();
        if signaling_state != SignalingState::Task {
            return Err(SignalingError::Crash(format!(
                "Called encode_task_message in state {:?}",
                signaling_state
            )));
        }

        // Get peer
        let peer = self
            .get_peer()
            .ok_or_else(|| SignalingError::Crash("Peer not set".into()))?;

        // Create and encrypt message
        let nonce = Nonce::new(
            // Cookie
            peer.cookie_pair().ours.clone(),
            // Src
            self.common().identity.into(),
            // Dst
            peer.identity().into(),
            // Csn
            peer.csn_pair().try_write()?.ours.increment()?,
        );
        let obox = OpenBox::<Value>::new(value, nonce);
        let bbox = obox.encrypt(
            peer.keypair()
                .ok_or_else(|| SignalingError::Crash("Session keypair not available".into()))?,
            peer.session_key()
                .ok_or_else(|| SignalingError::Crash("Peer session key not set".into()))?,
        )?;

        Ok(bbox)
    }

    /// Encode and encrypt a close message for the chosen peer.
    ///
    /// The `peer_ctx` parameter must only be provided during handshake.
    fn encode_close_message(
        &self,
        reason: CloseCode,
        peer_ctx: Option<&dyn PeerContext>,
    ) -> SignalingResult<ByteBox> {
        // Get peer
        let peer = match peer_ctx {
            Some(p) => p,
            None => {
                // Check state
                let signaling_state = self.common().signaling_state();
                if signaling_state != SignalingState::Task {
                    return Err(SignalingError::Crash(format!(
                        "Called encode_close_message in state {:?}",
                        signaling_state
                    )));
                }

                self.get_peer()
                    .ok_or_else(|| SignalingError::Crash("Peer not set".into()))?
            }
        };

        // Create and encrypt message
        let nonce = Nonce::new(
            // Cookie
            peer.cookie_pair().ours.clone(),
            // Src
            self.common().identity.into(),
            // Dst
            peer.identity().into(),
            // Csn
            peer.csn_pair().try_write()?.ours.increment()?,
        );
        let msg = Close::from_close_code(reason).into_message();
        let obox = OpenBox::<Message>::new(msg, nonce);
        let bbox = obox.encrypt(
            peer.keypair()
                .ok_or_else(|| SignalingError::Crash("Session keypair not available".into()))?,
            peer.session_key()
                .ok_or_else(|| SignalingError::Crash("Peer session key not set".into()))?,
        )?;

        Ok(bbox)
    }

    // Message handling: Dispatching

    /// Determine the next server handshake state based on the incoming
    /// server-to-client message and the current state.
    ///
    /// This method call may have some side effects, like updates in the peer
    /// context (cookie, CSN, etc).
    ///
    /// Note: The `nonce_clone` parameter is only set to a value if needed to
    /// verify the signed keys inside the `server-auth` message. Otherwise it's
    /// `None`.
    fn handle_server_message(
        &mut self,
        obox: OpenBox<Message>,
        nonce_clone: Option<Nonce>,
    ) -> SignalingResult<Vec<HandleAction>> {
        let old_state = self.server_handshake_state();
        match (old_state, obox.message) {
            // Valid state transitions
            (ServerHandshakeState::New, Message::ServerHello(msg)) => self.handle_server_hello(msg),
            (ServerHandshakeState::ClientInfoSent, Message::ServerAuth(msg)) => {
                self.handle_server_auth(msg, nonce_clone)
            }
            (ServerHandshakeState::Done, Message::NewInitiator(msg)) => {
                self.handle_new_initiator(msg)
            }
            (ServerHandshakeState::Done, Message::NewResponder(msg)) => {
                self.handle_new_responder(msg)
            }
            (ServerHandshakeState::Done, Message::DropResponder(_msg)) => {
                unimplemented!("TODO (#36): Handling DropResponder messages not yet implemented")
            }
            (ServerHandshakeState::Done, Message::SendError(msg)) => self.handle_send_error(msg),
            (ServerHandshakeState::Done, Message::Disconnected(msg)) => {
                self.handle_disconnected(msg)
            }

            // Any undefined state transition results in an error
            (s, message) => Err(SignalingError::InvalidStateTransition(format!(
                "Got '{}' message from server in {:?} state",
                message.get_type(),
                s
            ))),
        }
    }

    /// Determine the next peer handshake state based on the incoming
    /// client-to-client message and the current state.
    ///
    /// This method call may have some side effects, like updates in the peer
    /// context (cookie, CSN, etc).
    fn handle_peer_message(&mut self, obox: OpenBox<Message>)
        -> SignalingResult<Vec<HandleAction>>;

    // Message handling: Handling

    /// Handle an incoming [`ServerHello`](messages/struct.ServerHello.html) message.
    fn handle_server_hello(&mut self, msg: ServerHello) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received server-hello from server");

        let mut actions = Vec::with_capacity(2);

        // Set the server public session key
        trace!("Server session key is {:?}", msg.key);
        if self.server().session_key.is_some() {
            return Err(SignalingError::Protocol(
                "Got a server-hello message, but server session key is already set".to_string(),
            ));
        }
        self.common_mut().server.session_key = Some(msg.key);

        // Reply with client-hello message if we're a responder
        if self.role() == Role::Responder {
            let client_hello = {
                let key = self.common().permanent_keypair.public_key().clone();
                ClientHello::new(key).into_message()
            };
            let client_hello_nonce = Nonce::new(
                // Cookie
                self.server().cookie_pair().ours.clone(),
                // Src
                self.common().identity.into(),
                // Dst
                self.server().identity().into(),
                // Csn
                self.server().csn_pair().try_write()?.ours.increment()?,
            );
            let reply = OpenBox::<Message>::new(client_hello, client_hello_nonce);
            debug!("<-- Enqueuing client-hello to server");
            actions.push(HandleAction::Reply(reply.encode()));
        }

        // Send client-auth message
        let ping_interval = self
            .common()
            .ping_interval
            .map(|duration| duration.as_secs())
            .map(|secs| {
                if secs > u64::from(::std::u32::MAX) {
                    warn!(
                        "Ping interval is too large. Truncating it to {} seconds.",
                        ::std::u32::MAX
                    );
                    ::std::u32::MAX
                } else {
                    secs as u32
                }
            })
            .unwrap_or(0u32);
        match ping_interval {
            0 => debug!("Requesting WebSocket ping messages to be disabled"),
            n => debug!("Requesting WebSocket ping messages every {}s", n),
        };
        let client_auth = ClientAuth {
            your_cookie: self.server().cookie_pair().theirs.clone().unwrap(),
            subprotocols: vec![crate::SUBPROTOCOL.into()],
            ping_interval,
            your_key: self.server().permanent_key().cloned(),
        }
        .into_message();
        let client_auth_nonce = Nonce::new(
            self.server().cookie_pair().ours.clone(),
            self.identity().into(),
            self.server().identity().into(),
            self.server().csn_pair().try_write()?.ours.increment()?,
        );
        let reply = OpenBox::<Message>::new(client_auth, client_auth_nonce);
        match self.server().session_key {
            Some(ref pubkey) => {
                debug!("<-- Enqueuing client-auth to server");
                actions.push(HandleAction::Reply(
                    reply.encrypt(&self.common().permanent_keypair, pubkey)?,
                ));
            }
            None => return Err(SignalingError::Crash("Missing server permanent key".into())),
        };

        // TODO (#13): Can we prevent confusing an incoming and an outgoing nonce?
        self.server_mut()
            .set_handshake_state(ServerHandshakeState::ClientInfoSent);
        Ok(actions)
    }

    /// Handle an incoming [`ServerAuth`](messages/struct.ServerAuth.html) message.
    fn handle_server_auth(
        &mut self,
        msg: ServerAuth,
        nonce_clone: Option<Nonce>,
    ) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received server-auth from server");

        // When the client receives a 'server-auth' message, it MUST
        // have accepted and set its identity as described in the
        // Receiving a Signalling Message section.
        if self.identity() == ClientIdentity::Unknown {
            return Err(SignalingError::Crash(
                "No identity assigned when receiving server-auth message".into(),
            ));
        }

        // It MUST check that the cookie provided in the your_cookie
        // field contains the cookie the client has used in its
        // previous and messages to the server.
        self.validate_repeated_cookie(
            &msg.your_cookie,
            &self.server().cookie_pair().ours,
            self.server().identity(),
        )?;

        if let Some(server_public_permanent_key) = self.server().permanent_key() {
            // If the client has knowledge of the server's public permanent
            // key, it SHALL decrypt the signed_keys field by using the
            // message's nonce, the client's private permanent key and the
            // server's public permanent key.
            let nonce = nonce_clone.ok_or_else(|| {
                SignalingError::Crash(
                    "This is a server-auth message, but no nonce clone was passed in".into(),
                )
            })?;
            let signed_keys = msg.signed_keys.as_ref().ok_or_else(|| {
                SignalingError::Protocol(
                    "Server's public permanent key is known, but server did not send signed keys"
                        .into(),
                )
            })?;
            let decrypted = signed_keys.decrypt(
                &self.common().permanent_keypair,
                server_public_permanent_key,
                nonce,
            )?;

            // The decrypted message MUST match the concatenation of the
            // server's public session key and the client's public permanent
            // key (in that order).
            let server_public_session_key = self
                .server()
                .session_key()
                .ok_or_else(|| SignalingError::Crash("Server session key not set".into()))?;
            if &decrypted.server_public_session_key != server_public_session_key {
                return Err(SignalingError::Protocol(
                    "Server public session key sent in `signed_keys` is not valid".into(),
                ));
            }
            if &decrypted.client_public_permanent_key
                != self.common().permanent_keypair.public_key()
            {
                return Err(SignalingError::Protocol(
                    "Our public permanent key sent in `signed_keys` is not valid".into(),
                ));
            }
        } else if msg.signed_keys.is_some() {
            // If the signed_keys is present but the client does not have
            // knowledge of the server's permanent key, it SHALL log a
            // warning.
            warn!("Server sent signed keys, but we're not verifying them");
        }

        // Moreover, the client MUST do some checks depending on its role
        let actions = self.handle_server_auth_impl(&msg)?;

        info!("Server handshake completed");
        self.server_mut()
            .set_handshake_state(ServerHandshakeState::Done);
        self.common_mut()
            .set_signaling_state(SignalingState::PeerHandshake)?;
        Ok(actions)
    }

    /// Role-specific handling of an incoming [`ServerAuth`](messages/struct.ServerAuth.html) message.
    fn handle_server_auth_impl(&mut self, msg: &ServerAuth) -> SignalingResult<Vec<HandleAction>>;

    /// Handle an incoming [`NewInitiator`](messages/struct.NewInitiator.html) message.
    fn handle_new_initiator(&mut self, msg: NewInitiator) -> SignalingResult<Vec<HandleAction>>;

    /// Handle an incoming [`NewResponder`](messages/struct.NewResponder.html) message.
    fn handle_new_responder(&mut self, msg: NewResponder) -> SignalingResult<Vec<HandleAction>>;

    /// Handle an incoming [`SendError`](messages/struct.ServerAuth.html) message.
    fn handle_send_error(&mut self, msg: SendError) -> SignalingResult<Vec<HandleAction>> {
        warn!("--> Received send-error from server");
        debug!("Message that could not be relayed: {:#?}", msg.id);
        Err(SignalingError::SendError)
    }

    /// Handle an incoming [`Disconnected`](messages/struct.Disconnected.html) message.
    fn handle_disconnected(&mut self, msg: Disconnected) -> SignalingResult<Vec<HandleAction>>;

    // Helper methods

    /// Encode and return a DropResponder message.
    fn send_drop_responder(
        &self,
        addr: Address,
        reason: DropReason,
    ) -> SignalingResult<HandleAction> {
        // Note: We need to define this method here instead of in the
        // `InitiatorSignaling` impl because the `handle_handshake_peer_message`
        // method on the `Signaling` trait needs to be able to call it.

        // Sanity check
        if self.role() != Role::Initiator {
            return Err(SignalingError::Crash(
                "Non-initiator should never need to encode a DropResponder message".into(),
            ));
        }

        // Create message and nonce
        let drop = DropResponder::with_reason(addr, reason).into_message();
        let drop_nonce = Nonce::new(
            self.server().cookie_pair.ours.clone(),
            self.common().identity.into(),
            self.server().identity().into(),
            self.server().csn_pair().try_write()?.ours.increment()?,
        );

        // Encrypt message
        let obox = OpenBox::<Message>::new(drop, drop_nonce);
        let bbox = obox.encrypt(
            &self.common().permanent_keypair,
            self.server()
                .session_key()
                .ok_or_else(|| SignalingError::Crash("Server session key not set".into()))?,
        )?;

        Ok(HandleAction::Reply(bbox))
    }

    // Raw encryption / decryption

    fn get_crypto_box(&self) -> SignalingResult<crypto_box::Box> {
        let peer = self.get_peer().ok_or_else(|| SignalingError::NoPeer)?;
        let peer_session_public_key = peer
            .session_key()
            .ok_or_else(|| SignalingError::Crash("Peer session public key not set".into()))?;
        let our_session_private_key = peer
            .keypair()
            .map(|keypair: &KeyPair| keypair.private_key())
            .ok_or_else(|| SignalingError::Crash("Our session private key not set".into()))?;
        Ok(crypto_box::Box::new(
            peer_session_public_key,
            our_session_private_key,
        ))
    }

    /// Encrypt raw bytes for the peer using the session keys.
    ///
    /// If this function is called before the peer has been established,
    /// it will return a `SignalingError::NoPeer`.
    fn encrypt_raw_with_session_keys(
        &self,
        data: &[u8],
        nonce: &GenericArray<u8, U24>,
    ) -> SignalingResult<Vec<u8>> {
        self.get_crypto_box()?
            .encrypt(nonce, data)
            .map_err(|_| SignalingError::Crypto("Could not encrypt bytes".to_string()))
    }

    /// Decrypt raw bytes for the peer using the session keys.
    ///
    /// If this function is called before the peer has been established,
    /// it will return a `SignalingError::NoPeer`.
    fn decrypt_raw_with_session_keys(
        &self,
        data: &[u8],
        nonce: &GenericArray<u8, U24>,
    ) -> SignalingResult<Vec<u8>> {
        self.get_crypto_box()?
            .decrypt(nonce, data)
            .map_err(|_| SignalingError::Crypto("Could not decrypt bytes".into()))
    }
}

/// A peer can be authenticated either through a one-time auth token, or
/// through a trusted peer public key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AuthProvider {
    Token(AuthToken),
    TrustedKey(PublicKey),
}

/// Common functionality and state for all signaling types.
pub(crate) struct Common {
    /// The signaling state.
    signaling_state: SignalingState,

    /// Our permanent keypair.
    pub(crate) permanent_keypair: KeyPair,

    /// Either an auth token (for untrusted sessions) or a trusted peer public
    /// key (for trusted sessions).
    pub(crate) auth_provider: Option<AuthProvider>,

    /// The assigned role.
    pub(crate) role: Role,

    /// The assigned client identity.
    pub(crate) identity: ClientIdentity,

    /// The server context.
    pub(crate) server: ServerContext,

    /// The list of possible task instances.
    pub(crate) tasks: Option<Tasks>,

    /// The chosen task.
    ///
    /// Be careful when locking the mutex, it's easy to end up with deadlocks!
    pub(crate) task: Option<Arc<Mutex<BoxedTask>>>,

    /// The list of message types that the task accepts.
    ///
    /// This will be set once a task is chosen.
    pub(crate) task_supported_types: Option<&'static [&'static str]>,

    /// The interval at which the server should send WebSocket ping messages.
    pub(crate) ping_interval: Option<Duration>,
}

impl Common {
    /// Return the current signaling state.
    fn signaling_state(&self) -> SignalingState {
        self.signaling_state
    }

    /// Set the current signaling state.
    fn set_signaling_state(&mut self, state: SignalingState) -> SignalingResult<()> {
        if self.signaling_state == state {
            trace!(
                "Ignoring signaling state transition: {:?} -> {:?}",
                self.signaling_state(),
                state
            );
            return Ok(());
        }
        if !self.signaling_state.may_transition_to(state) {
            return Err(SignalingError::InvalidStateTransition(format!(
                "Signaling state: {:?} -> {:?}",
                self.signaling_state(),
                state
            )));
        }
        trace!(
            "Signaling state transition: {:?} -> {:?}",
            self.signaling_state(),
            state
        );
        self.signaling_state = state;
        Ok(())
    }

    /// Set the current signaling state.
    #[cfg(test)]
    fn set_signaling_state_forced(&mut self, state: SignalingState) -> SignalingResult<()> {
        trace!("Setting signaling state to {:?} for tests", state);
        self.signaling_state = state;
        Ok(())
    }
}

/// This struct is used to give each responder a unique incrementing serial.
/// This helps identifying the oldest responder when doing path cleaning.
pub(crate) struct ResponderCounter(u32);

impl ResponderCounter {
    /// Create a new responder counter, initialized to `0`.
    fn new() -> Self {
        ResponderCounter(0)
    }

    /// Get the current counter and increment it.
    fn increment(&mut self) -> SignalingResult<u32> {
        let old_val = self.0;
        self.0 = self.0.checked_add(1).ok_or_else(|| {
            SignalingError::Crash("Overflow when incrementing responder counter".into())
        })?;
        Ok(old_val)
    }
}

/// Signaling data for the initiator.
pub(crate) struct InitiatorSignaling {
    // Common state and functionality
    pub(crate) common: Common,

    // The list of responders
    pub(crate) responders: HashMap<Address, ResponderContext>,

    // The chosen responder
    pub(crate) responder: Option<ResponderContext>,

    // The responder counter, used to give every responder
    // an incrementing serial.
    pub(crate) responder_counter: ResponderCounter,
}

impl Signaling for InitiatorSignaling {
    /// Return a reference to the `Common` struct.
    fn common(&self) -> &Common {
        &self.common
    }

    /// Return a mutable reference to the `Common` struct.
    fn common_mut(&mut self) -> &mut Common {
        &mut self.common
    }

    fn get_peer(&self) -> Option<&dyn PeerContext> {
        self.responder.as_ref().map(|p| p as &dyn PeerContext)
    }

    fn get_peer_with_address_mut(&mut self, addr: Address) -> Option<&mut dyn PeerContext> {
        let identity: Identity = addr.into();
        match identity {
            // Server can always send us messages
            Identity::Server => Some(&mut self.common.server as &mut dyn PeerContext),

            // We're the initiator, this doesn't make any sense
            Identity::Initiator => None,

            // Return correct responder instance
            Identity::Responder(_) => {
                if self.common().signaling_state() == SignalingState::Task {
                    // If we've already selected a peer, return it if it matches the address.
                    // Note: This is a deviation from the SaltyRTC protocol which allows
                    //       connections to multiple responders.
                    let peer = self.responder.as_mut().map(|p| p as &mut dyn PeerContext);
                    let valid = match peer {
                        Some(ref p) => {
                            let peer_addr: Address = p.identity().into();
                            peer_addr == addr
                        }
                        None => false,
                    };
                    if valid {
                        peer
                    } else {
                        None
                    }
                } else {
                    // Otherwise look in the list of known responders.
                    self.responders
                        .get_mut(&addr)
                        .map(|r| r as &mut dyn PeerContext)
                }
            }
        }
    }

    fn initiator_pubkey(&self) -> &PublicKey {
        self.common().permanent_keypair.public_key()
    }

    fn validate_nonce_destination(&mut self, nonce: &Nonce) -> Result<(), ValidationError> {
        // A client MUST check that the destination address targets its
        // assigned identity (or `0x00` during authentication).
        if self.identity() == ClientIdentity::Unknown
            && !nonce.destination().is_unknown()
            && self.server_handshake_state() != ServerHandshakeState::New
        {
            // The first message received with a destination address different
            // to `0x00` SHALL be accepted as the client's assigned identity.
            // However, the client MUST validate that the identity fits its
            // role – initiators SHALL ONLY accept `0x01`. The identity MUST
            // be stored as the client's assigned identity.
            if nonce.destination().is_initiator() {
                self.common.identity = ClientIdentity::Initiator;
                debug!("Assigned identity: {}", self.identity());
            } else {
                return Err(ValidationError::Fail(format!(
                    "cannot assign address {} to initiator",
                    nonce.destination()
                )));
            };
        }
        if nonce.destination() != self.identity().into() {
            return Err(ValidationError::Fail(format!(
                "Bad destination: {} (our identity is {})",
                nonce.destination(),
                self.identity()
            )));
        }

        Ok(())
    }

    fn validate_nonce_source(&mut self, nonce: &Nonce) -> Result<(), ValidationError> {
        // An initiator SHALL ONLY process messages from the server (0x00). As
        // soon as the initiator has been assigned an identity, it MAY ALSO accept
        // messages from other responders (0x02..0xff). Other messages SHALL be
        // discarded and SHOULD trigger a warning.
        match nonce.source() {
            // From server
            Address(0x00) => Ok(()),

            // From initiator
            Address(0x01) => Err(ValidationError::DropMsg(format!(
                "Bad source: {} (our identity is {})",
                nonce.source(),
                self.identity()
            ))),

            // From responder
            Address(0x02..=0xff) => {
                if self.identity() == ClientIdentity::Initiator {
                    Ok(())
                } else {
                    Err(ValidationError::DropMsg(format!(
                        "Bad source: {} (our identity is {})",
                        nonce.source(),
                        self.identity()
                    )))
                }
            }
        }
    }

    fn decode_peer_message(&self, bbox: ByteBox) -> SignalingResult<OpenBox<Message>> {
        // Validate source again
        if !bbox.nonce.source().is_responder() {
            return Err(SignalingError::Crash(
                "Received message from an initiator".to_string(),
            ));
        }

        // Find responder
        let source = bbox.nonce.source();
        let responder = match self.responders.get(&source) {
            Some(responder) => responder,
            None => {
                return Err(SignalingError::Crash(format!(
                    "Did not find responder with address {}",
                    source
                )))
            }
        };

        // Helper functions
        fn responder_permanent_key(responder: &ResponderContext) -> SignalingResult<&PublicKey> {
            responder.permanent_key.as_ref().ok_or_else(|| {
                SignalingError::Crash(format!(
                    "Did not find public permanent key for responder {}",
                    responder.address.0
                ))
            })
        }
        fn responder_session_key(responder: &ResponderContext) -> SignalingResult<&PublicKey> {
            responder.session_key.as_ref().ok_or_else(|| {
                SignalingError::Crash(format!(
                    "Did not find public session key for responder {}",
                    responder.address.0
                ))
            })
        }

        // Decrypt depending on state
        match responder.handshake_state() {
            ResponderHandshakeState::New => {
                // Expect token message, encrypted with authentication token.
                debug!("Expect token message");
                match self.common.auth_provider {
                    Some(AuthProvider::Token(ref token)) => OpenBox::decrypt_token(bbox, token),
                    Some(AuthProvider::TrustedKey(_)) => Err(SignalingError::Crash(
                        "Handshake state is \"New\" even though a trusted key is available".into(),
                    )),
                    None => Err(SignalingError::Crash(
                        "Handshake state is \"New\" without an auth provider available".into(),
                    )),
                }
            }
            ResponderHandshakeState::TokenReceived => {
                // Expect key message, encrypted with our public permanent key
                // and responder private permanent key
                debug!("Expect key message");
                OpenBox::<Message>::decrypt(
                    bbox,
                    &self.common.permanent_keypair,
                    responder_permanent_key(&responder)?,
                )
                .map_err(|e| match e {
                    SignalingError::Decode(_) => {
                        warn!("Could not decrypt key message");
                        SignalingError::InitiatorCouldNotDecrypt
                    }
                    e => e,
                })
            }
            ResponderHandshakeState::KeySent => {
                // Expect auth message, encrypted with our public session key
                // and responder private session key
                OpenBox::<Message>::decrypt(
                    bbox,
                    &responder.keypair,
                    responder_session_key(&responder)?,
                )
            }
            other => {
                // TODO (#14): Maybe remove these states?
                Err(SignalingError::Crash(format!(
                    "Invalid responder handshake state: {:?}",
                    other
                )))
            }
        }
    }

    /// Determine the next peer handshake state based on the incoming
    /// client-to-client message and the current state.
    ///
    /// This method call may have some side effects, like updates in the peer
    /// context (cookie, CSN, etc).
    fn handle_peer_message(
        &mut self,
        obox: OpenBox<Message>,
    ) -> SignalingResult<Vec<HandleAction>> {
        let source = obox.nonce.source();
        let old_state = {
            let responder = self.responders.get(&source).ok_or_else(|| {
                SignalingError::Crash(format!("Did not find responder with address {}", source))
            })?;
            responder.handshake_state()
        };

        // State transitions
        match (old_state, obox.message) {
            // Valid state transitions
            (ResponderHandshakeState::New, Message::Token(msg)) => self.handle_token(msg, source),
            (ResponderHandshakeState::TokenReceived, Message::Key(msg)) => {
                self.handle_key(msg, source)
            }
            (ResponderHandshakeState::KeySent, Message::Auth(msg)) => self.handle_auth(msg, source),

            // Any undefined state transition results in an error
            (s, message) => Err(SignalingError::InvalidStateTransition(format!(
                "Got {} message from responder {} in {:?} state",
                message.get_type(),
                obox.nonce.source().0,
                s
            ))),
        }
    }

    fn handle_server_auth_impl(&mut self, msg: &ServerAuth) -> SignalingResult<Vec<HandleAction>> {
        // In case the client is the initiator, it SHALL check that the
        // responders field is set and contains an Array of responder
        // identities.
        if msg.initiator_connected.is_some() {
            return Err(SignalingError::InvalidMessage(
                "We're the initiator, but the `initiator_connected` field in the server-auth message is set".into()
            ));
        }
        let responders = match msg.responders {
            Some(ref responders) => responders,
            None => {
                return Err(SignalingError::InvalidMessage(
                    "`responders` field in server-auth message not set".into(),
                ))
            }
        };

        // The responder identities MUST be validated and SHALL neither contain
        // addresses outside the range 0x02..0xff
        let responders_set: HashSet<Address> = responders.iter().cloned().collect();
        if responders_set.contains(&Address(0x00)) || responders_set.contains(&Address(0x01)) {
            return Err(SignalingError::InvalidMessage(
                "`responders` field in server-auth message may not contain addresses <0x02".into(),
            ));
        }

        // ...nor SHALL an address be repeated in the Array.
        if responders.len() != responders_set.len() {
            return Err(SignalingError::InvalidMessage(
                "`responders` field in server-auth message may not contain duplicates".into(),
            ));
        }

        // An empty Array SHALL be considered valid. However, Nil SHALL NOT be
        // considered a valid value of that field.
        // -> Already covered by Rust's type system.

        // It SHOULD store the responder's identities in its internal list of
        // responders. Additionally, the initiator MUST keep its path clean by
        // following the procedure described in the Path Cleaning section.
        let mut actions = vec![];
        for address in responders_set {
            if let Some(drop_responder) = self.process_new_responder(address)? {
                actions.push(drop_responder);
            }
        }

        actions.push(HandleAction::Event(Event::ServerHandshakeDone(
            responders.is_empty(),
        )));
        Ok(actions)
    }

    /// Handle an incoming [`NewInitiator`](messages/struct.Initiator.html) message.
    fn handle_new_initiator(&mut self, _msg: NewInitiator) -> SignalingResult<Vec<HandleAction>> {
        Err(SignalingError::Protocol(
            "Received 'new-responder' message as initiator".into(),
        ))
    }

    /// Handle an incoming [`NewResponder`](messages/struct.NewResponder.html) message.
    fn handle_new_responder(&mut self, msg: NewResponder) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received new-responder ({}) from server", msg.id);

        // An initiator who receives a 'new-responder' message SHALL validate
        // that the id field contains a valid responder address (0x02..0xff).
        if !msg.id.is_responder() {
            return Err(SignalingError::InvalidMessage(
                "`id` field in new-responder message is not a valid responder address".into(),
            ));
        }

        // Process responder
        match self.process_new_responder(msg.id)? {
            Some(drop_responder) => Ok(vec![drop_responder]),
            None => Ok(vec![]),
        }
    }

    /// Handle an incoming [`Disconnected`](messages/struct.Disconnected.html) message.
    fn handle_disconnected(&mut self, msg: Disconnected) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received disconnected from server");

        // An initiator who receives a 'disconnected' message SHALL validate
        // that the id field contains a valid responder address (0x02..0xff).
        if !msg.id.is_responder() {
            return Err(SignalingError::Protocol(
                "Received 'disconnected' message with non-responder id".into(),
            ));
        }

        Ok(vec![HandleAction::Event(Event::Disconnected(msg.id.0))])
    }
}

impl InitiatorSignaling {
    pub(crate) fn new(
        permanent_keypair: KeyPair,
        tasks: Tasks,
        responder_trusted_pubkey: Option<PublicKey>,
        server_public_permanent_key: Option<PublicKey>,
        ping_interval: Option<Duration>,
    ) -> Self {
        InitiatorSignaling {
            common: Common {
                signaling_state: SignalingState::ServerHandshake,
                role: Role::Initiator,
                identity: ClientIdentity::Unknown,
                permanent_keypair,
                auth_provider: Some(match responder_trusted_pubkey {
                    Some(key) => AuthProvider::TrustedKey(key),
                    None => AuthProvider::Token(AuthToken::new()),
                }),
                server: {
                    let mut ctx = ServerContext::new();
                    ctx.permanent_key = server_public_permanent_key;
                    ctx
                },
                tasks: Some(tasks),
                task: None,
                task_supported_types: None,
                ping_interval,
            },
            responders: HashMap::new(),
            responder: None,
            responder_counter: ResponderCounter::new(),
        }
    }

    /// Handle an incoming [`Token`](messages/struct.Token.html) message.
    #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
    fn handle_token(&mut self, msg: Token, source: Address) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received token from {}", Identity::from(source));

        {
            // Find responder instance
            let responder = self.responders.get_mut(&source).ok_or_else(|| {
                SignalingError::Crash(format!("Did not find responder with address {}", source))
            })?;

            // Sanity check
            if responder.permanent_key.is_some() {
                return Err(SignalingError::Crash(
                    "Responder already has a permanent key set!".into(),
                ));
            }

            // Set public permanent key
            responder.permanent_key = Some(msg.key);

            // State transition
            responder.set_handshake_state(ResponderHandshakeState::TokenReceived);
        } // Waiting for NLL

        // Invalidate auth token
        match self.common().auth_provider {
            Some(AuthProvider::Token(_)) => {}
            _ => return Err(SignalingError::Crash("Auth provider is not a token".into())),
        }
        self.common_mut().auth_provider = None;

        Ok(vec![])
    }

    /// Handle an incoming [`Key`](messages/struct.Key.html) message.
    #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
    fn handle_key(&mut self, msg: Key, source: Address) -> SignalingResult<Vec<HandleAction>> {
        let source_identity = Identity::from(source);
        debug!("--> Received key from {}", source_identity);

        // Find responder instance
        let responder = self.responders.get_mut(&source).ok_or_else(|| {
            SignalingError::Crash(format!("Did not find responder with address {}", source))
        })?;

        // Sanity check
        if responder.session_key.is_some() {
            return Err(SignalingError::Crash(
                "Responder already has a session key set!".into(),
            ));
        }

        // Ensure that session key != permanent key
        match &responder.permanent_key {
            Some(pk) if pk == &msg.key => {
                return Err(SignalingError::Protocol(
                    "Responder session key and permanent key are equal".into(),
                ));
            }
            Some(_) => {}
            None => {
                return Err(SignalingError::Crash(
                    "Responder permanent key not set".into(),
                ));
            }
        };

        // Set public session key
        responder.session_key = Some(msg.key);

        // State transition
        responder.set_handshake_state(ResponderHandshakeState::KeyReceived);

        // Reply with our own key msg
        let key: Message = Key {
            key: responder.keypair.public_key().clone(),
        }
        .into_message();
        let key_nonce = Nonce::new(
            responder.cookie_pair().ours.clone(),
            self.common.identity.into(),
            responder.identity().into(),
            responder.csn_pair().try_write()?.ours.increment()?,
        );
        let obox = OpenBox::<Message>::new(key, key_nonce);
        let bbox = obox.encrypt(
            &self.common.permanent_keypair,
            responder
                .permanent_key
                .as_ref()
                .ok_or_else(|| SignalingError::Crash("Responder permanent key not set".into()))?,
        )?;

        // State transition
        responder.set_handshake_state(ResponderHandshakeState::KeySent);

        debug!("<-- Enqueuing key to {}", source_identity);
        Ok(vec![HandleAction::Reply(bbox)])
    }

    /// Handle an incoming [`Auth`](messages/struct.Auth.html) message.
    fn handle_auth(&mut self, msg: Auth, source: Address) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received auth from {}", Identity::from(source));

        let mut actions = vec![];

        // Find responder instance
        let mut responder = self.responders.remove(&source).ok_or_else(|| {
            SignalingError::Crash(format!("Did not find responder with address {}", source))
        })?;

        // The cookie provided in the `your_cookie` field SHALL contain the cookie
        // we have used in our previous messages to the responder.
        self.validate_repeated_cookie(
            &msg.your_cookie,
            &responder.cookie_pair().ours,
            responder.identity(),
        )?;

        // An initiator SHALL validate that the tasks field contains an array with at least one element.
        if msg.task.is_some() {
            return Err(SignalingError::InvalidMessage(
                "We're an initiator, but the `task` field in the auth message is set".into(),
            ));
        }
        let proposed_tasks = match msg.tasks {
            None => {
                return Err(SignalingError::InvalidMessage(
                    "The `tasks` field in the auth message is not set".into(),
                ))
            }
            Some(ref tasks) if tasks.is_empty() => {
                return Err(SignalingError::InvalidMessage(
                    "The `tasks` field in the auth message is empty".into(),
                ))
            }
            Some(tasks) => tasks,
        };

        // Each element in the Array SHALL be a string.
        // -> Already covered in deserialization

        // Validate data field
        if msg.data.len() != proposed_tasks.len() {
            return Err(SignalingError::InvalidMessage("The `tasks` and `data` fields in the auth message have a different number of entries".into()));
        };
        for task in &proposed_tasks {
            if !msg.data.contains_key(task) {
                return Err(SignalingError::InvalidMessage(format!(
                    "The task \"{}\" in the auth message does not have a corresponding data entry",
                    task
                )));
            }
        }

        // The initiator SHALL continue by comparing the provided tasks
        // to its own array of supported tasks.
        // It MUST choose the first task in its own list of supported tasks
        // that is also contained in the list of supported tasks provided by the responder.
        // In case no common task could be found, the initiator SHALL send a 'close' message
        // to the responder containing the close code 3006 (No Shared Task Found) as reason
        // and raise an error event indicating that no common signalling task could be found.
        let our_tasks = mem::replace(&mut self.common_mut().tasks, None)
            .ok_or_else(|| SignalingError::Crash("No tasks defined".into()))?;
        trace!("Our tasks: {:?}", &our_tasks);
        trace!("Proposed tasks: {:?}", &proposed_tasks);
        let mut chosen_task: BoxedTask = match our_tasks.choose_shared_task(&proposed_tasks) {
            Some(task) => task,
            None => {
                // In case no common task could be found, the initiator SHALL
                // send a 'close' message to the responder containing the close
                // code 3006 (No Shared Task Found) as reason and raise an
                // error event indicating that no common signalling task could
                // be found.
                let mut actions = vec![];
                match self.encode_close_message(CloseCode::NoSharedTask, Some(&responder)) {
                    Ok(bbox) => actions.push(HandleAction::Reply(bbox)),
                    Err(e) => error!("Could not encode close message: {}", e),
                };
                actions.push(HandleAction::HandshakeError(SaltyError::NoSharedTask));
                return Ok(actions);
            }
        };

        // Both initiator an responder SHALL verify that the data field contains a Map
        // and SHALL look up the chosen task's data value.
        let task_data = msg
            .data
            .get(&*chosen_task.name())
            .ok_or_else(|| SignalingError::Crash("Task data not found".into()))?;

        // The value MUST be handed over to the corresponding task
        // after processing this message is complete.
        chosen_task
            .init(task_data)
            .map_err(|e| SignalingError::TaskInitialization(format!("{}", e)))?;

        // After the above procedure has been followed, the other client has successfully
        // authenticated it towards the client. The other client's public key MAY be stored
        // as trusted for that path if the application desires it.
        info!("Responder {:#04x} authenticated", source.0);

        // The initiator MUST drop all other connected responders with a 'drop-responder'
        // message containing the close code 3004 (Dropped by Initiator) in the reason field.
        if !self.responders.is_empty() {
            info!("Dropping {} other responders", self.responders.len());
            for addr in self.responders.keys() {
                let drop_responder =
                    self.send_drop_responder(*addr, DropReason::DroppedByInitiator)?;
                debug!(
                    "<-- Enqueuing drop-responder to {}",
                    self.server().identity()
                );
                actions.push(drop_responder);
            }

            // Remove responders
            self.responders.clear();

            // Free the memory used for tracking responders
            self.responders.shrink_to_fit();
        }

        // State transition
        responder.set_handshake_state(ResponderHandshakeState::AuthReceived);

        // Respond with auth message
        let responder_cookie = responder
            .cookie_pair
            .theirs
            .as_ref()
            .cloned()
            .ok_or_else(|| SignalingError::Crash("Responder cookie not set".into()))?;
        let auth: Message = InitiatorAuthBuilder::new(responder_cookie)
            .set_task(chosen_task.name(), chosen_task.data())
            .build()?
            .into_message();
        let auth_nonce = Nonce::new(
            responder.cookie_pair().ours.clone(),
            self.common.identity.into(),
            responder.address,
            responder.csn_pair().try_write()?.ours.increment()?,
        );
        let obox = OpenBox::<Message>::new(auth, auth_nonce);
        let bbox = obox.encrypt(
            &responder.keypair,
            responder
                .session_key
                .as_ref()
                .ok_or_else(|| SignalingError::Crash("Responder session key not set".into()))?,
        )?;
        debug!("<-- Enqueuing auth to {}", &responder.identity());
        actions.push(HandleAction::Reply(bbox));

        // Store chosen task
        self.common_mut().task_supported_types = Some(chosen_task.supported_types());
        self.common_mut().task = Some(Arc::new(Mutex::new(chosen_task)));

        // State transitions
        responder.set_handshake_state(ResponderHandshakeState::AuthSent);
        self.common.set_signaling_state(SignalingState::Task)?;
        info!("Peer handshake completed");
        actions.push(HandleAction::HandshakeDone);

        self.responder = Some(responder);
        Ok(actions)
    }

    fn process_new_responder(&mut self, address: Address) -> SignalingResult<Option<HandleAction>> {
        // If a responder with the same id already exists,
        // all currently cached information about and for the previous responder
        // (such as cookies and the sequence number) MUST be deleted first.
        if self.responders.contains_key(&address) {
            warn!("Overwriting responder context for address {:?}", address);
            self.responders.remove(&address);
        } else {
            info!("Registering new responder with address {:?}", address);
        }

        // Create responder context
        let mut responder = ResponderContext::new(address, self.responder_counter.increment()?);

        // If we trust the responder…
        if let Some(AuthProvider::TrustedKey(key)) = &self.common.auth_provider {
            // …set the public permanent key
            if responder.permanent_key.is_some() {
                // Sanity check
                return Err(SignalingError::Crash(
                    "Responder already has a permanent key set!".into(),
                ));
            }
            responder.permanent_key = Some(key.clone());

            // …don't expect a token message
            responder.set_handshake_state(ResponderHandshakeState::TokenReceived);
        }

        // The initiator SHOULD store the responder's identity in its internal
        // list of responders.
        self.responders.insert(address, responder);

        let mut action = None;

        // Furthermore, the initiator MUST keep its path clean by following the
        // procedure described in the Path Cleaning section.
        // To implement this requirement, if we almost reached the responder limit,
        // drop the oldest responder that hasn't sent any valid data so far.
        if self.responders.len() > (254 - 2) {
            if let Some(drop_action) = self.drop_oldest_inactive_responder()? {
                debug!(
                    "<-- Enqueuing drop-responder to {}",
                    self.server().identity()
                );
                action = Some(drop_action);
            }
        }

        Ok(action)
    }

    /// Drop the oldest responder that hasn't sent any valid data so far.
    /// Return a result with a 'drop-responder' handle action if a drop
    /// candidate has been found.
    fn drop_oldest_inactive_responder(&mut self) -> SignalingResult<Option<HandleAction>> {
        debug!("Path almost full, dropping the oldest inactive responder.");

        // Find address of drop candidate
        let address = self
            .responders
            .values()
            .filter(|r| r.handshake_state() == ResponderHandshakeState::New)
            .min_by_key(|r| r.counter)
            .map(|r| r.address);

        // Remove responder from internal list of responders
        let responder: ResponderContext = match address {
            Some(ref addr) => self.responders.remove(addr).ok_or_else(|| {
                SignalingError::Crash(
                    "Inactive responder not found anymore in responders list".into(),
                )
            })?,
            None => {
                warn!("Did not find a valid responder candidate to drop!");
                return Ok(None);
            }
        };

        // Enqueue a drop-responder message
        self.send_drop_responder(responder.address, DropReason::DroppedByInitiator)
            .map(Option::Some)
    }
}

/// Signaling data for the responder.
pub(crate) struct ResponderSignaling {
    // Common state and functionality
    pub(crate) common: Common,

    // The initiator context
    pub(crate) initiator: InitiatorContext,
}

impl Signaling for ResponderSignaling {
    /// Return a reference to the `Common` struct.
    fn common(&self) -> &Common {
        &self.common
    }

    /// Return a mutable reference to the `Common` struct.
    fn common_mut(&mut self) -> &mut Common {
        &mut self.common
    }

    fn get_peer(&self) -> Option<&dyn PeerContext> {
        Some(&self.initiator as &dyn PeerContext)
    }

    fn get_peer_with_address_mut(&mut self, addr: Address) -> Option<&mut dyn PeerContext> {
        let identity: Identity = addr.into();
        match identity {
            Identity::Server => Some(&mut self.common.server),
            Identity::Initiator => Some(&mut self.initiator),
            Identity::Responder(_) => None,
        }
    }

    fn initiator_pubkey(&self) -> &PublicKey {
        &self.initiator.permanent_key
    }

    fn validate_nonce_destination(&mut self, nonce: &Nonce) -> Result<(), ValidationError> {
        // A client MUST check that the destination address targets its
        // assigned identity (or `0x00` during authentication).
        if self.identity() == ClientIdentity::Unknown
            && !nonce.destination().is_unknown()
            && self.server_handshake_state() != ServerHandshakeState::New
        {
            // The first message received with a destination address different
            // to `0x00` SHALL be accepted as the client's assigned identity.
            // However, the client MUST validate that the identity fits its
            // role – responders SHALL ONLY an identity from the range
            // `0x02..0xff`. The identity MUST be stored as the client's
            // assigned identity.
            if nonce.destination().is_responder() {
                self.common.identity = ClientIdentity::Responder(nonce.destination().0);
                debug!("Assigned identity: {}", self.identity());
            } else {
                return Err(ValidationError::Fail(format!(
                    "cannot assign address {} to a responder",
                    nonce.destination()
                )));
            };
        }
        if nonce.destination() != self.identity().into() {
            return Err(ValidationError::Fail(format!(
                "Bad destination: {} (our identity is {})",
                nonce.destination(),
                self.identity()
            )));
        }

        Ok(())
    }

    fn validate_nonce_source(&mut self, nonce: &Nonce) -> Result<(), ValidationError> {
        // A responder SHALL ONLY process messages from the server (0x00). As soon
        // as the responder has been assigned an identity, it MAY ALSO accept
        // messages from the initiator (0x01). Other messages SHALL be discarded
        // and SHOULD trigger a warning.
        match nonce.source() {
            // From server
            Address(0x00) => Ok(()),

            // From initiator
            Address(0x01) => {
                if let ClientIdentity::Responder(_) = self.identity() {
                    Ok(())
                } else {
                    Err(ValidationError::DropMsg(format!(
                        "Bad source: {} (our identity is {})",
                        nonce.source(),
                        self.identity()
                    )))
                }
            }

            // From responder
            Address(0x02..=0xff) => Err(ValidationError::DropMsg(format!(
                "Bad source: {} (our identity is {})",
                nonce.source(),
                self.identity()
            ))),
        }
    }

    fn decode_peer_message(&self, bbox: ByteBox) -> SignalingResult<OpenBox<Message>> {
        // Validate source again
        if !bbox.nonce.source().is_initiator() {
            return Err(SignalingError::Crash(
                "Received message from a responder".to_string(),
            ));
        }

        // Decrypt depending on state
        match self.initiator.handshake_state() {
            InitiatorHandshakeState::KeySent => {
                // Expect key message, encrypted with our public permanent key
                // and initiator private permanent key
                OpenBox::<Message>::decrypt(
                    bbox,
                    &self.common.permanent_keypair,
                    &self.initiator.permanent_key,
                )
            }
            InitiatorHandshakeState::AuthSent => {
                // Expect an auth message, encrypted with our public session
                // key and initiator private session key
                let initiator_session_key =
                    self.initiator.session_key.as_ref().ok_or_else(|| {
                        SignalingError::Crash("Initiator session key not set".into())
                    })?;
                OpenBox::<Message>::decrypt(bbox, &self.initiator.keypair, initiator_session_key)
            }
            other => {
                // TODO (#14): Maybe remove these states?
                Err(SignalingError::Crash(format!(
                    "Invalid initiator handshake state: {:?}",
                    other
                )))
            }
        }
    }

    /// Determine the next peer handshake state based on the incoming
    /// client-to-client message and the current state.
    ///
    /// This method call may have some side effects, like updates in the peer
    /// context (cookie, CSN, etc).
    fn handle_peer_message(
        &mut self,
        obox: OpenBox<Message>,
    ) -> SignalingResult<Vec<HandleAction>> {
        let old_state = self.initiator.handshake_state();
        match (old_state, obox.message) {
            // Valid state transitions
            (InitiatorHandshakeState::KeySent, Message::Key(msg)) => {
                self.handle_key(msg, &obox.nonce)
            }
            (InitiatorHandshakeState::AuthSent, Message::Auth(msg)) => {
                self.handle_auth(msg, obox.nonce.source())
            }
            (InitiatorHandshakeState::AuthSent, Message::Close(msg)) => {
                self.handle_peer_handshake_close(msg)
            }

            // Any undefined state transition results in an error
            (s, message) => Err(SignalingError::InvalidStateTransition(format!(
                "Got {} message from initiator in {:?} state",
                message.get_type(),
                s
            ))),
        }
    }

    fn handle_server_auth_impl(&mut self, msg: &ServerAuth) -> SignalingResult<Vec<HandleAction>> {
        // In case the client is the responder, it SHALL check
        // that the initiator_connected field contains a
        // boolean value.
        if msg.responders.is_some() {
            return Err(SignalingError::InvalidMessage(
                "We're a responder, but the `responders` field in the server-auth message is set"
                    .into(),
            ));
        }
        let mut actions: Vec<HandleAction> = vec![];
        match msg.initiator_connected {
            Some(true) => {
                let mut send_token = false;
                match self.common().auth_provider {
                    Some(AuthProvider::Token(_)) => {
                        send_token = true;
                    },
                    Some(AuthProvider::TrustedKey(_)) => {
                        debug!("Trusted key available, skipping token message");
                    },
                    None => {
                        return Err(SignalingError::Crash("No auth provider set".into()));
                    },
                }
                if send_token {
                    let old_auth_provider = mem::replace(&mut self.common_mut().auth_provider, None);
                    if let Some(AuthProvider::Token(token)) = old_auth_provider {
                        actions.push(self.send_token(token)?);
                    } else {
                        return Err(SignalingError::Crash("Auth provider is not a token".into()));
                    }
                }
                actions.push(self.send_key()?);
                actions.push(HandleAction::Event(Event::ServerHandshakeDone(true)));
                self.initiator.set_handshake_state(InitiatorHandshakeState::KeySent);
            },
            Some(false) => {
                debug!("No initiator connected so far");
                actions.push(HandleAction::Event(Event::ServerHandshakeDone(false)));
            },
            None => return Err(SignalingError::InvalidMessage(
                "We're a responder, but the `initiator_connected` field in the server-auth message is not set".into()
            )),
        }
        Ok(actions)
    }

    fn handle_new_initiator(&mut self, _msg: NewInitiator) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received new-initiator from server");

        let mut actions: Vec<HandleAction> = vec![];

        // A responder who receives a 'new-initiator' message MUST proceed by
        // deleting all currently cached information about and for the previous
        // initiator (such as cookies and the sequence numbers)...
        self.initiator = InitiatorContext::new(self.initiator.permanent_key.clone());

        // ...and continue by sending a 'token' or 'key' client-to-client
        // message described in the Client-to-Client Messages section.
        let mut send_token = false;
        match self.common().auth_provider {
            Some(AuthProvider::Token(_)) => {
                send_token = true;
            }
            Some(AuthProvider::TrustedKey(_)) => {
                debug!("Trusted key available, skipping token message");
            }
            None => {
                return Err(SignalingError::Crash("No auth provider set".into()));
            }
        }
        if send_token {
            let old_auth_provider = mem::replace(&mut self.common_mut().auth_provider, None);
            if let Some(AuthProvider::Token(token)) = old_auth_provider {
                actions.push(self.send_token(token)?);
            } else {
                return Err(SignalingError::Crash("Auth provider is not a token".into()));
            }
        }
        actions.push(self.send_key()?);
        self.initiator
            .set_handshake_state(InitiatorHandshakeState::KeySent);

        Ok(actions)
    }

    fn handle_new_responder(&mut self, _msg: NewResponder) -> SignalingResult<Vec<HandleAction>> {
        Err(SignalingError::Protocol(
            "Received 'new-responder' message as responder".into(),
        ))
    }

    /// Handle an incoming [`Disconnected`](messages/struct.Disconnected.html) message.
    fn handle_disconnected(&mut self, msg: Disconnected) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received disconnected from server");

        // A responder who receives a 'disconnected' message SHALL validate
        // that the id field contains a valid initiator address (0x01).
        if !msg.id.is_initiator() {
            return Err(SignalingError::Protocol(
                "Received 'disconnected' message with non-initiator id".into(),
            ));
        }

        Ok(vec![HandleAction::Event(Event::Disconnected(msg.id.0))])
    }
}

impl ResponderSignaling {
    pub(crate) fn new(
        permanent_keypair: KeyPair,
        initiator_pubkey: PublicKey,
        auth_token: Option<AuthToken>,
        server_public_permanent_key: Option<PublicKey>,
        tasks: Tasks,
        ping_interval: Option<Duration>,
    ) -> Self {
        ResponderSignaling {
            common: Common {
                signaling_state: SignalingState::ServerHandshake,
                role: Role::Responder,
                identity: ClientIdentity::Unknown,
                permanent_keypair,
                auth_provider: Some(match auth_token {
                    Some(token) => AuthProvider::Token(token),
                    None => AuthProvider::TrustedKey(initiator_pubkey.clone()),
                }),
                server: {
                    let mut ctx = ServerContext::new();
                    ctx.permanent_key = server_public_permanent_key;
                    ctx
                },
                tasks: Some(tasks),
                task: None,
                task_supported_types: None,
                ping_interval,
            },
            initiator: InitiatorContext::new(initiator_pubkey),
        }
    }

    /// Build a `Token` message.
    ///
    /// The token is consumed to avoid accidentally reusing it.
    #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
    fn send_token(&self, token: AuthToken) -> SignalingResult<HandleAction> {
        // The responder MUST set the public key (32 bytes) of the permanent
        // key pair in the key field of this message.
        let msg: Message = Token {
            key: self.common().permanent_keypair.public_key().to_owned(),
        }
        .into_message();
        let nonce = Nonce::new(
            self.initiator.cookie_pair().ours.clone(),
            self.identity().into(),
            self.initiator.identity().into(),
            self.initiator.csn_pair().try_write()?.ours.increment()?,
        );
        let obox = OpenBox::<Message>::new(msg, nonce);

        // The message SHALL be NaCl secret key encrypted by the token the
        // initiator created and issued to the responder.
        let bbox = obox.encrypt_token(&token)?;

        debug!("<-- Enqueuing token to {}", self.initiator.identity());
        Ok(HandleAction::Reply(bbox))
    }

    /// Build a `Key` message.
    fn send_key(&self) -> SignalingResult<HandleAction> {
        // It MUST set the public key (32 bytes) of that key pair in the key field.
        let msg: Message = Key {
            key: self.initiator.keypair.public_key().to_owned(),
        }
        .into_message();
        let nonce = Nonce::new(
            self.initiator.cookie_pair().ours.clone(),
            self.identity().into(),
            self.initiator.identity().into(),
            self.initiator.csn_pair().try_write()?.ours.increment()?,
        );
        let obox = OpenBox::<Message>::new(msg, nonce);

        // The message SHALL be NaCl public-key encrypted by the client's
        // permanent key pair and the other client's permanent key pair.
        let bbox = obox.encrypt(
            &self.common().permanent_keypair,
            &self.initiator.permanent_key,
        )?;

        debug!("<-- Enqueuing key to {}", self.initiator.identity());
        Ok(HandleAction::Reply(bbox))
    }

    /// Handle an incoming [`Key`](messages/struct.Key.html) message.
    #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
    fn handle_key(&mut self, msg: Key, nonce: &Nonce) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received key from {}", nonce.source_identity());

        // Sanity check
        if self.initiator.session_key.is_some() {
            return Err(SignalingError::Crash(
                "Initiator already has a session key set!".into(),
            ));
        }

        // Ensure that session key != permanent key
        if msg.key == self.initiator.permanent_key {
            return Err(SignalingError::Protocol(
                "Responder session key and permanent key are equal".into(),
            ));
        }

        // Set public session key
        self.initiator.session_key = Some(msg.key);

        // State transition
        self.initiator
            .set_handshake_state(InitiatorHandshakeState::KeyReceived);

        // Reply with auth msg
        let auth: Message = ResponderAuthBuilder::new(nonce.cookie().clone())
            .add_tasks(
                self.common()
                    .tasks
                    .as_ref()
                    .ok_or_else(|| SignalingError::Crash("Tasks are not set".into()))?,
            )
            .build()?
            .into_message();
        let auth_nonce = Nonce::new(
            self.initiator.cookie_pair().ours.clone(),
            self.common().identity.into(),
            self.initiator.identity().into(),
            self.initiator.csn_pair().try_write()?.ours.increment()?,
        );
        let obox = OpenBox::<Message>::new(auth, auth_nonce);
        let bbox = obox.encrypt(
            &self.initiator.keypair,
            self.initiator
                .session_key
                .as_ref()
                .ok_or_else(|| SignalingError::Crash("Initiator session key not set".into()))?,
        )?;

        // State transition
        self.initiator
            .set_handshake_state(InitiatorHandshakeState::AuthSent);

        debug!("<-- Enqueuing auth to {}", self.initiator.identity());
        Ok(vec![HandleAction::Reply(bbox)])
    }

    /// Handle an incoming [`Auth`](messages/struct.Auth.html) message.
    fn handle_auth(&mut self, msg: Auth, source: Address) -> SignalingResult<Vec<HandleAction>> {
        debug!("--> Received auth from {}", Identity::from(source));

        // The cookie provided in the `your_cookie` field SHALL contain the cookie
        // we have used in our previous messages to the responder.
        self.validate_repeated_cookie(
            &msg.your_cookie,
            &self.initiator.cookie_pair().ours,
            self.initiator.identity(),
        )?;

        // A responder SHALL validate that the task field is present and contains one of the tasks it has previously offered to the initiator.
        if msg.tasks.is_some() {
            return Err(SignalingError::InvalidMessage(
                "We're a responder, but the `tasks` field in the auth message is set".into(),
            ));
        }
        let mut chosen_task: BoxedTask = match msg.task {
            Some(task) => {
                let our_tasks = mem::replace(&mut self.common_mut().tasks, None)
                    .ok_or_else(|| SignalingError::Crash("No tasks defined".into()))?;
                our_tasks
                    .into_iter()
                    .find(|t: &BoxedTask| t.name() == task)
                    .ok_or_else(|| {
                        SignalingError::Protocol(
                            "The `task` field in the auth message contains an unknown task".into(),
                        )
                    })?
            }
            None => {
                return Err(SignalingError::InvalidMessage(
                    "The `task` field in the auth message is not set".into(),
                ))
            }
        };

        // Make sure that there is only one data entry.
        if msg.data.is_empty() {
            return Err(SignalingError::Protocol(
                "The `data` field in the auth message is empty".into(),
            ));
        }
        if msg.data.len() > 1 {
            return Err(SignalingError::Protocol(
                "The `data` field in the auth message contains more than one entry".into(),
            ));
        }

        // Both initiator an responder SHALL verify that the data field contains a Map
        // and SHALL look up the chosen task's data value.
        let task_data = msg.data.get(&*chosen_task.name()).ok_or_else(|| {
            SignalingError::Protocol(
                "The task in the auth message does not have a corresponding data entry".into(),
            )
        })?;

        // The value MUST be handed over to the corresponding task
        // after processing this message is complete.
        chosen_task
            .init(task_data)
            .map_err(|e| SignalingError::TaskInitialization(format!("{}", e)))?;

        // After the above procedure has been followed, the other client has successfully
        // authenticated it towards the client. The other client's public key MAY be stored
        // as trusted for that path if the application desires it.
        info!("Initiator authenticated");

        // Store chosen task
        self.common_mut().task_supported_types = Some(chosen_task.supported_types());
        self.common_mut().task = Some(Arc::new(Mutex::new(chosen_task)));

        // State transitions
        self.initiator
            .set_handshake_state(InitiatorHandshakeState::AuthReceived);
        self.common.set_signaling_state(SignalingState::Task)?;
        info!("Peer handshake completed");

        Ok(vec![HandleAction::HandshakeDone])
    }

    /// Handle an incoming [`Close`](messages/struct.Close.html) message during peer handshake.
    #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
    fn handle_peer_handshake_close(&mut self, msg: Close) -> SignalingResult<Vec<HandleAction>> {
        let close_code = CloseCode::from_number(msg.reason);
        match close_code {
            CloseCode::NoSharedTask => Err(SignalingError::NoSharedTask),
            _ => Err(SignalingError::Protocol(format!(
                "Received unexpected close message with code {} during peer handshake",
                msg.reason
            ))),
        }
    }
}