lawn-protocol 0.5.0

protocol types, traits, and codes for Lawn
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
#![allow(non_upper_case_globals)]
/// # Overview
///
/// The protocol is relatively simple.  Each request consists of a 32-bit size of the resulting
/// message, a 32-bit request ID, a 32-bit message type, and an optional per-message CBOR blob
/// representing message data.  For performance and security reasons, the message size is limited
/// to 2^24 in size.  The size includes all fields other than the size.
///
/// Each response consists of a 32-bit size of the message, the 32-bit request ID, a 32-bit
/// response code, and an optional per-response code CBOR blob.
///
/// The bottom 31 bits of the request ID may be any value; the response will use the same ID.  No
/// check is made for duplicates, so the requestor should prefer not repeating IDs that are in
/// flight.  The top bit is clear if the request is client-to-server request and it is set if the
/// request is a server-to-client request.  This helps eliminate confusion as to whether a message
/// is a request or a response.
///
/// All data is serialized in a little-endian format.
///
/// ## Extension Messages
///
/// Extension values (message types and response codes) are assigned with
/// values `0xff000000` and larger.  These can be dynamically allocated using
/// the `CreateExtensionRange` message, and once allocated, will allow the
/// extension to use the given codes both as message types and response codes.
///
/// Note that an implementation is not obligated to allocate or use extension
/// codes.  For example, an implementation which offers a new sort of channel may
/// well choose to use the existing channel codes, or it may choose to use new
/// message types with existing response codes.
///
/// Lawn currently allocates these by allocating a 12-bit range internally, so
/// the first code of the first extension is `0xff000000`, the first code of the next is
/// `0xfff001000`,  and so on.  This provides 4096 codes per extension while
/// allowing 4096 extensions.  However, this algorithm is subject to change at any
/// time.
use crate::config::Config;
use bitflags::bitflags;
use bytes::{Bytes, BytesMut};
use num_traits::FromPrimitive;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_cbor::Value;
use std::collections::{BTreeMap, BTreeSet};
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::io;
use std::io::{Seek, SeekFrom};

/// The response codes for the protocol.
///
/// The response codes are based around IMAP's response codes, and the top two bytes of the
/// response indicates the type:
///
/// * 00: success
/// * 01: no (roughly, the request was understood, but not completed)
/// * 02: bad (roughly, the request was not understood)
/// * ff: extension message (dynamically allocated)
#[derive(FromPrimitive, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum ResponseCode {
    /// The request was successful.  The response contains the requested data.
    Success = 0x00000000,
    /// The request is incomplete, but is so far successful.  The request should continue,
    /// referencing the ID of the last request.
    Continuation = 0x00000001,

    /// The request requires authentication.
    ///
    /// The semantics for this message are equivalent to an HTTP 401 response.
    NeedsAuthentication = 0x00010000,
    /// The message was not allowed.
    ///
    /// The semantics for this message are equivalent to an HTTP 403 response.
    Forbidden = 0x00010001,
    /// The server is shutting down.
    Closing = 0x00010002,
    /// The message failed for a system error reason.
    ///
    /// This is generally only useful for certain types of channels.
    Errno = 0x00010003,
    AuthenticationFailed = 0x00010004,
    /// The other end of the channel has disappeared.
    Gone = 0x00010005,
    NotFound = 0x00010006,
    InternalError = 0x00010007,
    /// The channel has ceased to produce new data and this operation cannot complete.
    ChannelDead = 0x00010008,
    /// The operation was aborted.
    Aborted = 0x00010009,
    /// There is no continuation with the specified parameters.
    ContinuationNotFound = 0x0001000a,
    /// The result was out of range.
    ///
    /// The semantics for this message are equivalent to `ERANGE`.
    OutOfRange = 0x0001000b,
    /// There is no more space for the requested item.
    NoSpace = 0x0001000c,
    /// The requested operation would conflict with something already existing.
    ///
    /// The semantics for this message are equivalent to an HTTP 409 response.
    Conflict = 0x0001000d,
    /// The contents of the object cannot be listed or specified by name.
    ///
    /// For example, when using a Git-protocol credential helper, it is not possible to enumerate
    /// all credentials or pick a credential by ID.
    Unlistable = 0x0001000e,

    /// The message type was not enabled.
    NotEnabled = 0x00020000,
    /// The message type or operation was not supported.
    NotSupported = 0x00020001,
    /// The parameters were not supported.
    ParametersNotSupported = 0x00020002,
    /// The message type was received, but was not valid.
    Invalid = 0x00020003,
    /// The message was too large.
    TooLarge = 0x00020004,
    /// There are too many pending messages.
    TooManyMessages = 0x00020005,
    /// The parameters are supported, but not correct.
    ///
    /// For example, if a selector is not valid for a channel, this message may be sent.
    InvalidParameters = 0x00020006,
}

impl ResponseCode {
    fn from_u32(val: u32) -> Self {
        FromPrimitive::from_u32(val).unwrap_or(Self::Invalid)
    }
}

pub struct WrongTypeError(pub Error);

#[derive(Debug, Clone)]
pub struct Error {
    pub code: ResponseCode,
    pub body: Option<ErrorBody>,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        fmt::Debug::fmt(self, f)
    }
}

impl std::error::Error for Error {}

impl Error {
    pub fn from_errno(err: i32) -> Error {
        io::Error::from_raw_os_error(err).into()
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        let lerr: lawn_constants::Error = err.into();
        Error {
            code: ResponseCode::Errno,
            body: Some(ErrorBody::Errno(Errno { errno: lerr as u32 })),
        }
    }
}

impl From<ResponseCode> for Error {
    fn from(code: ResponseCode) -> Error {
        Error { code, body: None }
    }
}

impl TryInto<io::Error> for Error {
    type Error = WrongTypeError;
    fn try_into(self) -> Result<io::Error, Self::Error> {
        if self.code == ResponseCode::Errno {
            if let Some(ErrorBody::Errno(Errno { errno })) = self.body {
                if let Some(e) = lawn_constants::Error::from_u32(errno) {
                    return Ok(e.into());
                }
            }
        }
        Err(WrongTypeError(self))
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
pub struct Empty {}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Errno {
    errno: u32,
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(untagged)]
pub enum ErrorBody {
    Errno(Errno),
    Exit(i32),
}

#[derive(FromPrimitive, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum MessageKind {
    /// Requests that the other side provide a list of supported versions and capabilities.
    Capability = 0x00000000,
    /// Requests a specific version and capabilities.
    ///
    /// This request aborts all other in-flight requests by this sender.  Consequently, it should
    /// be sent at the beginning of the connection right after a successful `Capability` message.
    ///
    /// Authentication is not required for this message.
    Version = 0x00000001,
    /// Indicates a no-op request which should always be successful.
    ///
    /// Authentication is not required for this message.
    Ping = 0x00000002,
    /// Requests authentication.
    ///
    /// This request aborts all other in-flight requests by this sender.  Consequently, it should
    /// be sent at the beginning of the connection right after a successful `Capability` message.
    ///
    /// Authentication is not required for this message (obviously).
    Authenticate = 0x00000003,
    /// Continue an in-progress request.
    ///
    /// This request can be used to continue an operation when the `Continuation` response is
    /// provided.
    Continue = 0x00000004,
    /// Abort an in-progress request.
    ///
    /// This request can be used to abort an operation when the `Continuation` response is
    /// provided.
    Abort = 0x00000005,

    /// Indicates a graceful shutdown.
    ///
    /// Authentication is not required for this message.
    CloseAlert = 0x00001000,

    /// Requests a channel to be created.
    CreateChannel = 0x00010000,
    /// Requests a channel to be deleted.
    ///
    /// This request is made from the client to the server to terminate the connection.
    DeleteChannel = 0x00010001,
    /// Requests a read on the channel.
    ReadChannel = 0x00010002,
    /// Requests a write on the channel.
    WriteChannel = 0x00010003,
    /// Requests the status of the selectors on the channel.
    PollChannel = 0x00010004,
    /// Requests the status of the object on the other end of the channel.
    ///
    /// For command channels, this can be used to check if the child has exited.
    PingChannel = 0x00010005,
    // Not implemented:
    // AttachChannelSelector = 0x00010010,
    DetachChannelSelector = 0x00010011,
    /// Provides notification of some sort of metadata condition on the channel.
    ///
    /// For command channels, this is used by the server to notify the client that the process has
    /// terminated.
    ChannelMetadataNotification = 0x00011000,

    /// Allocates a range of IDs for an extension.
    CreateExtensionRange = 0x00020000,

    /// Deallocates a range of IDs for an extension.
    DeleteExtensionRange = 0x00020001,

    /// Lists all allocated ranges of IDs for extensions.
    ListExtensionRanges = 0x00020002,

    /// Open a store and associate an ID with it.
    OpenStore = 0x00030000,

    /// Close a store and associate an ID with it.
    CloseStore = 0x00030001,

    /// Lists all elements of a given type in the given store.
    ListStoreElements = 0x00030002,

    /// Acquire a handle to an element in the given store.
    AcquireStoreElement = 0x00030003,

    /// Release the handle of a store element.
    CloseStoreElement = 0x00030004,

    /// Authenticate to a store element if that's required to open it.
    AuthenticateStoreElement = 0x00030005,

    /// Create a store element.
    CreateStoreElement = 0x00030006,

    /// Delete a store element.
    DeleteStoreElement = 0x00030007,

    /// Update a store element.
    UpdateStoreElement = 0x00030008,

    /// Read a store element.
    ReadStoreElement = 0x00030009,

    /// Rename a store element.
    RenameStoreElement = 0x0003000a,

    /// Copy a store element.
    CopyStoreElement = 0x0003000b,

    /// Search store elements.
    SearchStoreElements = 0x0003000c,

    /// Read a server context.
    ReadServerContext = 0x00040000,

    /// Write a server context.
    WriteServerContext = 0x00040001,
}

#[derive(Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub enum Capability {
    AuthExternal,
    AuthKeyboardInteractive,
    AuthPlain,
    ChannelCommand,
    ChannelCommandTTY,
    Channel9P,
    ChannelSFTP,
    ChannelClipboard,
    ChannelBlockingIO,
    ExtensionAllocate,
    StoreCredential,
    ContextTemplate,
    Other(Bytes, Option<Bytes>),
}

impl Capability {
    #[allow(clippy::mutable_key_type)]
    pub fn implemented() -> BTreeSet<Capability> {
        [
            Self::AuthExternal,
            Self::AuthKeyboardInteractive,
            Self::AuthPlain,
            Self::ChannelCommand,
            Self::ChannelClipboard,
            Self::Channel9P,
            Self::ChannelSFTP,
            Self::ChannelBlockingIO,
            Self::ChannelCommandTTY,
            Self::ExtensionAllocate,
            Self::StoreCredential,
            Self::ContextTemplate,
        ]
        .iter()
        .cloned()
        .collect()
    }

    pub fn is_implemented(&self) -> bool {
        matches!(
            self,
            Self::AuthExternal
                | Self::AuthKeyboardInteractive
                | Self::AuthPlain
                | Self::ChannelCommand
                | Self::ChannelClipboard
                | Self::Channel9P
                | Self::ChannelSFTP
                | Self::ChannelBlockingIO
                | Self::ChannelCommandTTY
                | Self::ExtensionAllocate
                | Self::StoreCredential
                | Self::ContextTemplate
        )
    }
}

impl From<Capability> for (Bytes, Option<Bytes>) {
    fn from(capa: Capability) -> (Bytes, Option<Bytes>) {
        match capa {
            Capability::AuthExternal => (
                (b"auth" as &[u8]).into(),
                Some((b"EXTERNAL" as &[u8]).into()),
            ),
            Capability::AuthKeyboardInteractive => (
                (b"auth" as &[u8]).into(),
                Some((b"keyboard-interactive" as &[u8]).into()),
            ),
            Capability::AuthPlain => ((b"auth" as &[u8]).into(), Some((b"PLAIN" as &[u8]).into())),
            Capability::ChannelCommand => (
                (b"channel" as &[u8]).into(),
                Some((b"command" as &[u8]).into()),
            ),
            Capability::ChannelCommandTTY => (
                (b"channel" as &[u8]).into(),
                Some((b"command/tty" as &[u8]).into()),
            ),
            Capability::Channel9P => ((b"channel" as &[u8]).into(), Some((b"9p" as &[u8]).into())),
            Capability::ChannelSFTP => (
                (b"channel" as &[u8]).into(),
                Some((b"sftp" as &[u8]).into()),
            ),
            Capability::ChannelClipboard => (
                (b"channel" as &[u8]).into(),
                Some((b"clipboard" as &[u8]).into()),
            ),
            Capability::ChannelBlockingIO => (
                (b"channel" as &[u8]).into(),
                Some((b"blocking-io" as &[u8]).into()),
            ),
            Capability::StoreCredential => (
                (b"store" as &[u8]).into(),
                Some((b"credential" as &[u8]).into()),
            ),
            Capability::ExtensionAllocate => (
                (b"extension" as &[u8]).into(),
                Some((b"allocate" as &[u8]).into()),
            ),
            Capability::ContextTemplate => (
                (b"context" as &[u8]).into(),
                Some((b"template" as &[u8]).into()),
            ),
            Capability::Other(name, subtype) => (name, subtype),
        }
    }
}

impl From<(&[u8], Option<&[u8]>)> for Capability {
    fn from(data: (&[u8], Option<&[u8]>)) -> Capability {
        match data {
            (b"auth", Some(b"EXTERNAL")) => Capability::AuthExternal,
            (b"auth", Some(b"PLAIN")) => Capability::AuthPlain,
            (b"auth", Some(b"keyboard-interactive")) => Capability::AuthKeyboardInteractive,
            (b"channel", Some(b"command")) => Capability::ChannelCommand,
            (b"channel", Some(b"command/tty")) => Capability::ChannelCommandTTY,
            (b"channel", Some(b"9p")) => Capability::Channel9P,
            (b"channel", Some(b"sftp")) => Capability::ChannelSFTP,
            (b"channel", Some(b"clipboard")) => Capability::ChannelClipboard,
            (b"channel", Some(b"blocking-io")) => Capability::ChannelBlockingIO,
            (b"store", Some(b"credential")) => Capability::StoreCredential,
            (b"extension", Some(b"allocate")) => Capability::ExtensionAllocate,
            (b"context", Some(b"template")) => Capability::ContextTemplate,
            (name, subtype) => {
                Capability::Other(name.to_vec().into(), subtype.map(|s| s.to_vec().into()))
            }
        }
    }
}

impl From<(Bytes, Option<Bytes>)> for Capability {
    fn from(data: (Bytes, Option<Bytes>)) -> Capability {
        match data {
            (a, Some(b)) => (&a as &[u8], Some(&b as &[u8])).into(),
            (a, None) => (&a as &[u8], None).into(),
        }
    }
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CapabilityResponse {
    pub version: Vec<u32>,
    pub capabilities: Vec<(Bytes, Option<Bytes>)>,
    pub user_agent: Option<String>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct VersionRequest {
    pub version: u32,
    pub enable: Vec<(Bytes, Option<Bytes>)>,
    pub id: Option<Bytes>,
    pub user_agent: Option<String>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct AuthenticateRequest {
    pub last_id: Option<u32>,
    // All uppercase methods are SASL methods as defined by IANA.  Other methods are defined
    // internally.
    pub method: Bytes,
    pub message: Option<Bytes>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct AuthenticateResponse {
    // All uppercase methods are SASL methods as defined by IANA.  Other methods are defined
    // internally.
    pub method: Bytes,
    pub message: Option<Bytes>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct PartialContinueRequest {
    pub id: u32,
    pub kind: u32,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ContinueRequest<T> {
    pub id: u32,
    pub kind: u32,
    pub message: Option<T>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct AbortRequest {
    pub id: u32,
    pub kind: u32,
}

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
#[serde(transparent)]
pub struct ChannelID(pub u32);

impl fmt::Display for ChannelID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
#[serde(transparent)]
pub struct ChannelSelectorID(pub u32);

/// A message to create a channel.
///
/// The following channel types are known:
///
/// * `command`: Invoke a command on the remote side.  `args` is the command-line arguments and
///   `env` is the environment.
/// * `9p`: Create a channel implementing the 9p2000.L protocol.  `args[0]` is the desired mount
///   point as specified by the server.
///
/// Custom channel types can be created with an at sign and domain name representing the custom
/// extension.
#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CreateChannelRequest {
    pub kind: Bytes,
    pub kind_args: Option<Vec<Bytes>>,
    pub args: Option<Vec<Bytes>>,
    pub env: Option<BTreeMap<Bytes, Bytes>>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
    pub selectors: Vec<u32>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CreateChannelResponse {
    pub id: ChannelID,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ChannelCommandTTYMetadata {
    pub tty: bool,
    pub tty_selectors: Vec<u32>,
    pub term: Bytes,
    pub modes: BTreeMap<u32, Value>,
    #[serde(flatten)]
    pub size: ChannelCommandTTYSizeMetadata,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ChannelCommandTTYSizeMetadata {
    pub height_cells: u32,
    pub width_cells: u32,
    pub height_pixels: u32,
    pub width_pixels: u32,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct DeleteChannelRequest {
    pub id: ChannelID,
    pub termination: Option<u32>,
}

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ReadChannelRequest {
    pub id: ChannelID,
    pub selector: u32,
    pub count: u64,
    #[serde(default)]
    pub stream_sync: Option<u64>,
    #[serde(default)]
    pub blocking: Option<bool>,
    #[serde(default)]
    pub complete: bool,
}

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ReadChannelResponse {
    pub bytes: Bytes,
    #[serde(default)]
    pub offset: Option<u64>,
}

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct WriteChannelRequest {
    pub id: ChannelID,
    pub selector: u32,
    pub bytes: Bytes,
    #[serde(default)]
    pub stream_sync: Option<u64>,
    #[serde(default)]
    pub blocking: Option<bool>,
}

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct WriteChannelResponse {
    pub count: u64,
    #[serde(default)]
    pub offset: Option<u64>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct DetachChannelSelectorRequest {
    pub id: ChannelID,
    pub selector: u32,
}

bitflags! {
    #[derive(Default)]
    pub struct PollChannelFlags: u64 {
        const Input   = 0x00000001;
        const Output  = 0x00000002;
        const Error   = 0x00000004;
        const Hangup  = 0x00000008;
        const Invalid = 0x00000010;
        const Gone    = 0x00000020;
    }
}

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CreateExtensionRangeRequest {
    pub extension: (Bytes, Option<Bytes>),
    pub count: u32,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CreateExtensionRangeResponse {
    pub range: (u32, u32),
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct DeleteExtensionRangeRequest {
    pub extension: (Bytes, Option<Bytes>),
    pub range: (u32, u32),
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ListExtensionRangesResponse {
    pub ranges: Vec<ExtensionRange>,
}

impl IntoIterator for ListExtensionRangesResponse {
    type Item = ExtensionRange;
    type IntoIter = std::vec::IntoIter<ExtensionRange>;

    fn into_iter(self) -> Self::IntoIter {
        self.ranges.into_iter()
    }
}

impl<'a> IntoIterator for &'a ListExtensionRangesResponse {
    type Item = &'a ExtensionRange;
    type IntoIter = std::slice::Iter<'a, ExtensionRange>;

    fn into_iter(self) -> Self::IntoIter {
        self.ranges.iter()
    }
}

impl<'a> IntoIterator for &'a mut ListExtensionRangesResponse {
    type Item = &'a mut ExtensionRange;
    type IntoIter = std::slice::IterMut<'a, ExtensionRange>;

    fn into_iter(self) -> Self::IntoIter {
        self.ranges.iter_mut()
    }
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ExtensionRange {
    pub extension: (Bytes, Option<Bytes>),
    pub range: (u32, u32),
}

#[derive(FromPrimitive, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum ChannelMetadataNotificationKind {
    WaitStatus = 0,
    TerminalWindowChange = 1,
}

#[derive(FromPrimitive, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum ChannelMetadataStatusKind {
    Exited = 0,
    Signalled = 1,
    SignalledWithCore = 2,
    Stopped = 3,
    Unknown = 0x7fffffff,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct PingChannelRequest {
    pub id: ChannelID,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct PollChannelRequest {
    pub id: ChannelID,
    pub selectors: Vec<u32>,
    pub milliseconds: Option<u32>,
    pub wanted: Option<Vec<u64>>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct PollChannelResponse {
    pub id: ChannelID,
    pub selectors: BTreeMap<u32, u64>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ChannelMetadataNotification {
    pub id: ChannelID,
    pub kind: u32,
    pub status: Option<u32>,
    pub status_kind: Option<u32>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ChannelMetadataNotificationTyped<T> {
    pub id: ChannelID,
    pub kind: u32,
    pub status: Option<u32>,
    pub status_kind: Option<u32>,
    pub meta: Option<T>,
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone)]
pub enum ClipboardChannelTarget {
    Primary,
    Clipboard,
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone)]
pub enum ClipboardChannelOperation {
    Copy,
    Paste,
}

#[derive(Serialize, Deserialize, Hash, Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
#[serde(transparent)]
pub struct StoreID(pub u32);

#[derive(Serialize, Deserialize, Hash, Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
#[serde(transparent)]
pub struct StoreSelectorID(pub u32);

#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum StoreSelector {
    Path(Bytes),
    #[serde(rename = "id")]
    ID(StoreSelectorID),
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct OpenStoreRequest {
    pub kind: Bytes,
    pub path: Option<Bytes>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct OpenStoreResponse {
    pub id: StoreID,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CloseStoreRequest {
    pub id: StoreID,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ListStoreElementsRequest {
    pub id: StoreID,
    pub selector: StoreSelector,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ListStoreElementsResponse {
    pub elements: Vec<StoreElement>,
}

impl IntoIterator for ListStoreElementsResponse {
    type Item = StoreElement;
    type IntoIter = std::vec::IntoIter<StoreElement>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.into_iter()
    }
}

impl<'a> IntoIterator for &'a ListStoreElementsResponse {
    type Item = &'a StoreElement;
    type IntoIter = std::slice::Iter<'a, StoreElement>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.iter()
    }
}

impl<'a> IntoIterator for &'a mut ListStoreElementsResponse {
    type Item = &'a mut StoreElement;
    type IntoIter = std::slice::IterMut<'a, StoreElement>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.iter_mut()
    }
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct AcquireStoreElementRequest {
    pub id: StoreID,
    pub selector: Bytes,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct AcquireStoreElementResponse {
    pub selector: StoreSelectorID,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CloseStoreElementRequest {
    pub id: StoreID,
    pub selector: StoreSelectorID,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct AuthenticateStoreElementRequest {
    pub id: StoreID,
    pub selector: StoreSelectorID,
    pub method: Bytes,
    pub message: Option<Bytes>,
}

#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct AuthenticateStoreElementResponse {
    pub method: Bytes,
    pub message: Option<Bytes>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct StoreElementBareRequest {
    pub id: StoreID,
    pub selector: StoreSelector,
    pub kind: String,
    pub needs_authentication: Option<bool>,
    pub authentication_methods: Option<Vec<Bytes>>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CreateStoreElementRequest<T> {
    pub id: StoreID,
    pub selector: StoreSelector,
    pub kind: String,
    pub needs_authentication: Option<bool>,
    pub authentication_methods: Option<Vec<Bytes>>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
    pub body: T,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct DeleteStoreElementRequest {
    pub id: StoreID,
    pub selector: StoreSelector,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct UpdateStoreElementRequest<T> {
    pub id: StoreID,
    pub selector: StoreSelector,
    pub kind: String,
    pub needs_authentication: Option<bool>,
    pub authentication_methods: Option<Vec<Bytes>>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
    pub body: T,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ReadStoreElementRequest {
    pub id: StoreID,
    pub selector: StoreSelector,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ReadStoreElementResponse<T> {
    pub kind: String,
    pub needs_authentication: Option<bool>,
    pub authentication_methods: Option<Vec<Bytes>>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
    pub body: T,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum StoreSearchRecursionLevel {
    Boolean(bool),
    Levels(u32),
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct SearchStoreElementsBareRequest {
    pub id: StoreID,
    pub selector: StoreSelector,
    pub recurse: StoreSearchRecursionLevel,
    pub kind: Option<String>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct SearchStoreElementsRequest<T> {
    pub id: StoreID,
    pub selector: StoreSelector,
    pub recurse: StoreSearchRecursionLevel,
    pub kind: Option<String>,
    pub body: Option<T>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct SearchStoreElementsResponse<T> {
    pub elements: Vec<StoreElementWithBody<T>>,
}

impl<T> IntoIterator for SearchStoreElementsResponse<T> {
    type Item = StoreElementWithBody<T>;
    type IntoIter = std::vec::IntoIter<StoreElementWithBody<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a SearchStoreElementsResponse<T> {
    type Item = &'a StoreElementWithBody<T>;
    type IntoIter = std::slice::Iter<'a, StoreElementWithBody<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut SearchStoreElementsResponse<T> {
    type Item = &'a mut StoreElementWithBody<T>;
    type IntoIter = std::slice::IterMut<'a, StoreElementWithBody<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.iter_mut()
    }
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct StoreElement {
    pub path: Bytes,
    pub id: Option<StoreSelectorID>,
    pub kind: String,
    pub needs_authentication: Option<bool>,
    pub authentication_methods: Option<Vec<Bytes>>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct StoreElementWithBody<T> {
    pub path: Bytes,
    pub id: Option<StoreSelectorID>,
    pub kind: String,
    pub needs_authentication: Option<bool>,
    pub authentication_methods: Option<Vec<Bytes>>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
    pub body: T,
}

impl<T> StoreElementWithBody<T> {
    pub fn new(elem: StoreElement, body: T) -> Self {
        Self {
            path: elem.path,
            id: elem.id,
            kind: elem.kind,
            needs_authentication: elem.needs_authentication,
            authentication_methods: elem.authentication_methods,
            meta: elem.meta,
            body,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum SearchStoreElementType {
    Literal(Value),
    Set(BTreeSet<SearchStoreElementType>),
    Sequence(Vec<SearchStoreElementType>),
    // The unit value here exists to keep the same form across all serializations.
    Any(()),
    None(()),
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct CredentialStoreSearchElement {
    pub username: SearchStoreElementType,
    pub secret: SearchStoreElementType,
    pub authtype: SearchStoreElementType,
    pub kind: SearchStoreElementType,
    pub protocol: SearchStoreElementType,
    pub host: SearchStoreElementType,
    pub title: SearchStoreElementType,
    pub description: SearchStoreElementType,
    pub path: SearchStoreElementType,
    pub service: SearchStoreElementType,
    pub extra: BTreeMap<String, SearchStoreElementType>,
    pub id: SearchStoreElementType,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CredentialStoreLocation {
    pub protocol: Option<String>,
    pub host: Option<String>,
    pub port: Option<u16>,
    pub path: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct CredentialStoreElement {
    pub username: Option<Bytes>,
    pub secret: Option<Bytes>,
    pub authtype: Option<String>,
    #[serde(rename = "type")]
    pub kind: String,
    pub title: Option<String>,
    pub description: Option<String>,
    pub location: Vec<CredentialStoreLocation>,
    pub service: Option<String>,
    pub extra: BTreeMap<String, Value>,
    pub id: Bytes,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub struct KeyboardInteractiveAuthenticationPrompt {
    pub prompt: String,
    pub echo: bool,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub struct KeyboardInteractiveAuthenticationRequest {
    pub name: String,
    pub instruction: String,
    pub prompts: Vec<KeyboardInteractiveAuthenticationPrompt>,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub struct KeyboardInteractiveAuthenticationResponse {
    pub responses: Vec<String>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ReadServerContextRequest {
    pub kind: String,
    pub id: Option<Bytes>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ReadServerContextResponse {
    pub id: Option<Bytes>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct ReadServerContextResponseWithBody<T> {
    pub id: Option<Bytes>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
    pub body: Option<T>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct WriteServerContextRequest {
    pub kind: String,
    pub id: Option<Bytes>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct WriteServerContextRequestWithBody<T> {
    pub kind: String,
    pub id: Option<Bytes>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
    pub body: Option<T>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct WriteServerContextResponse {
    pub id: Option<Bytes>,
    pub meta: Option<BTreeMap<Bytes, Value>>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct TemplateServerContextBody {
    pub senv: Option<BTreeMap<Bytes, Bytes>>,
    pub cenv: Option<BTreeMap<Bytes, Bytes>>,
    pub ctxsenv: Option<BTreeMap<Bytes, Bytes>>,
    pub args: Option<Vec<Bytes>>,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct TemplateServerContextBodyWithBody<T> {
    pub senv: Option<BTreeMap<Bytes, Bytes>>,
    pub cenv: Option<BTreeMap<Bytes, Bytes>>,
    pub ctxsenv: Option<BTreeMap<Bytes, Bytes>>,
    pub args: Option<Vec<Bytes>>,
    pub body: Option<T>,
}

#[derive(Hash, Debug, FromPrimitive, Eq, PartialEq, Ord, PartialOrd, Copy, Clone)]
#[allow(non_camel_case_types)]
pub enum TerminalMode {
    VINTR = 1,
    VQUIT = 2,
    VERASE = 3,
    VKILL = 4,
    VEOF = 5,
    VEOL = 6,
    VEOL2 = 7,
    VSTART = 8,
    VSTOP = 9,
    VSUSP = 10,
    VDSUSP = 11,
    VREPRINT = 12,
    VWERASE = 13,
    VLNEXT = 14,
    VFLUSH = 15,
    VSWTCH = 16,
    VSTATUS = 17,
    VDISCARD = 18,
    IGNPAR = 30,
    PARMRK = 31,
    INPCK = 32,
    ISTRIP = 33,
    INLCR = 34,
    IGNCR = 35,
    ICRNL = 36,
    IUCLC = 37,
    IXON = 38,
    IXANY = 39,
    IXOFF = 40,
    IMAXBEL = 41,
    IUTF8 = 42,
    ISIG = 50,
    ICANON = 51,
    XCASE = 52,
    ECHO = 53,
    ECHOE = 54,
    ECHOK = 55,
    ECHONL = 56,
    NOFLSH = 57,
    TOSTOP = 58,
    IEXTEN = 59,
    ECHOCTL = 60,
    ECHOKE = 61,
    PENDIN = 62,
    OPOST = 70,
    OLCUC = 71,
    ONLCR = 72,
    OCRNL = 73,
    ONOCR = 74,
    ONLRET = 75,
    CS7 = 90,
    CS8 = 91,
    PARENB = 92,
    PARODD = 93,
    TTY_OP_ISPEED = 128,
    TTY_OP_OSPEED = 129,
    VMIN = 0x00010000,
    VTIME = 0x00010001,
}

/// A message for the protocol.
#[derive(Clone, Debug)]
pub struct Message {
    pub id: u32,
    pub kind: u32,
    pub message: Option<Bytes>,
}

#[derive(Clone, Debug)]
pub struct Response {
    pub id: u32,
    pub code: u32,
    pub message: Option<Bytes>,
}

#[derive(Default)]
pub struct ProtocolSerializer {}

pub enum Data {
    Message(Message),
    Response(Response),
}

#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub enum ResponseValue<T: DeserializeOwned, U: DeserializeOwned> {
    Success(T),
    Continuation((u32, U)),
}

impl ProtocolSerializer {
    const MAX_MESSAGE_SIZE: u32 = 0x00ffffff;

    pub fn new() -> ProtocolSerializer {
        Self {}
    }

    pub fn is_valid_size(&self, size: u32) -> bool {
        (8..=Self::MAX_MESSAGE_SIZE).contains(&size)
    }

    pub fn serialize_header(&self, id: u32, next: u32, data_len: usize) -> Option<Bytes> {
        let size = data_len as u64 + 8;
        if size > Self::MAX_MESSAGE_SIZE as u64 {
            return None;
        }
        let mut b = BytesMut::with_capacity(size as usize);
        let size = size as u32;
        b.extend(&size.to_le_bytes());
        b.extend(&id.to_le_bytes());
        b.extend(&next.to_le_bytes());
        Some(b.into())
    }

    pub fn serialize_message_simple(&self, msg: &Message) -> Option<Bytes> {
        let size = 8 + match &msg.message {
            Some(m) => m.len(),
            None => 0,
        };
        if size > Self::MAX_MESSAGE_SIZE as usize {
            return None;
        }
        let mut b = BytesMut::with_capacity(size);
        let size = size as u32;
        b.extend(&size.to_le_bytes());
        b.extend(&msg.id.to_le_bytes());
        b.extend(&msg.kind.to_le_bytes());
        if let Some(m) = &msg.message {
            b.extend(m);
        }
        Some(b.into())
    }

    pub fn serialize_message_typed<S: Serialize>(&self, msg: &Message, obj: &S) -> Option<Bytes> {
        let mut v: Vec<u8> = Vec::with_capacity(12);
        // Write a dummy size that we'll then fill in later.
        v.extend(&0u32.to_le_bytes());
        v.extend(&msg.id.to_le_bytes());
        v.extend(&msg.kind.to_le_bytes());
        let mut cursor = std::io::Cursor::new(&mut v);
        let _ = cursor.seek(SeekFrom::End(0));
        if serde_cbor::to_writer(&mut cursor, obj).is_err() {
            return None;
        }
        let size = match u32::try_from(v.len()) {
            Ok(sz) if (4..=Self::MAX_MESSAGE_SIZE).contains(&sz) => sz - 4,
            _ => return None,
        };
        v[0..4].copy_from_slice(&size.to_le_bytes());
        Some(v.into())
    }

    pub fn serialize_body<S: Serialize>(&self, obj: &S) -> Option<Bytes> {
        match serde_cbor::to_vec(obj) {
            Ok(m) => Some(m.into()),
            Err(_) => None,
        }
    }

    pub fn serialize_response_simple(&self, resp: &Response) -> Option<Bytes> {
        let size = 8 + match &resp.message {
            Some(m) => m.len(),
            None => 0,
        };
        if size > Self::MAX_MESSAGE_SIZE as usize {
            return None;
        }
        let mut b = BytesMut::with_capacity(size);
        let size = size as u32;
        b.extend(&size.to_le_bytes());
        b.extend(&resp.id.to_le_bytes());
        b.extend(&resp.code.to_le_bytes());
        if let Some(m) = &resp.message {
            b.extend(m);
        }
        Some(b.into())
    }

    pub fn serialize_response_typed<S: Serialize>(&self, msg: &Response, obj: &S) -> Option<Bytes> {
        let mut v: Vec<u8> = Vec::with_capacity(12);
        // Write a dummy size that we'll then fill in later.
        v.extend(&0u32.to_le_bytes());
        v.extend(&msg.id.to_le_bytes());
        v.extend(&msg.code.to_le_bytes());
        let mut cursor = std::io::Cursor::new(&mut v);
        let _ = cursor.seek(SeekFrom::End(0));
        if serde_cbor::to_writer(&mut cursor, obj).is_err() {
            return None;
        }
        let size = match u32::try_from(v.len()) {
            Ok(sz) if (4..=Self::MAX_MESSAGE_SIZE).contains(&sz) => sz - 4,
            _ => return None,
        };
        v[0..4].copy_from_slice(&size.to_le_bytes());
        Some(v.into())
    }

    pub fn deserialize_data(
        &self,
        config: &Config,
        header: &[u8],
        body: Bytes,
    ) -> Result<Data, Error> {
        fn is_sender(config: &Config, id: u32) -> bool {
            let sender_mask = if config.is_server() { 0x80000000 } else { 0 };
            (id & 0x80000000) == sender_mask
        }
        let _size: u32 = u32::from_le_bytes(header[0..4].try_into().unwrap());
        let id: u32 = u32::from_le_bytes(header[4..8].try_into().unwrap());
        let arg: u32 = u32::from_le_bytes(header[8..12].try_into().unwrap());
        if is_sender(config, id) {
            Ok(Data::Response(Response {
                id,
                code: arg,
                message: if body.is_empty() { None } else { Some(body) },
            }))
        } else {
            Ok(Data::Message(Message {
                id,
                kind: arg,
                message: if body.is_empty() { None } else { Some(body) },
            }))
        }
    }

    pub fn deserialize_message_typed<'a, D: Deserialize<'a>>(
        &self,
        msg: &'a Message,
    ) -> Result<Option<D>, Error> {
        match &msg.message {
            Some(body) => match serde_cbor::from_slice(body) {
                Ok(decoded) => Ok(Some(decoded)),
                Err(_) => Err(Error {
                    code: ResponseCode::Invalid,
                    body: None,
                }),
            },
            None => Ok(None),
        }
    }

    pub fn deserialize_response_typed<D1: DeserializeOwned, D2: DeserializeOwned>(
        &self,
        resp: &Response,
    ) -> Result<Option<ResponseValue<D1, D2>>, Error> {
        if resp.code == ResponseCode::Success as u32 {
            match &resp.message {
                Some(body) => match serde_cbor::from_slice(body) {
                    Ok(decoded) => Ok(Some(ResponseValue::Success(decoded))),
                    Err(_) => Err(Error {
                        code: ResponseCode::Invalid,
                        body: None,
                    }),
                },
                None => Ok(None),
            }
        } else if resp.code == ResponseCode::Continuation as u32 {
            match &resp.message {
                Some(body) => match serde_cbor::from_slice(body) {
                    Ok(decoded) => Ok(Some(ResponseValue::Continuation((resp.id, decoded)))),
                    Err(_) => Err(Error {
                        code: ResponseCode::Invalid,
                        body: None,
                    }),
                },
                None => Ok(None),
            }
        } else {
            match &resp.message {
                Some(body) => match serde_cbor::from_slice(body) {
                    Ok(decoded) => Err(Error {
                        code: ResponseCode::from_u32(resp.code),
                        body: Some(decoded),
                    }),
                    Err(_) => Err(Error {
                        code: ResponseCode::from_u32(resp.code),
                        body: None,
                    }),
                },
                None => Err(Error {
                    code: ResponseCode::from_u32(resp.code),
                    body: None,
                }),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ChannelID, Empty, Message, ProtocolSerializer, Response, ResponseValue,
        SearchStoreElementType, StoreID, StoreSelector, StoreSelectorID,
    };
    use bytes::Bytes;
    use serde::{de::DeserializeOwned, Deserialize, Serialize};
    use serde_cbor::Value;
    use std::convert::TryFrom;
    use std::fmt::Debug;

    #[test]
    fn serialize_header() {
        let cases: &[(u32, u32, usize, Option<&[u8]>)] = &[
            (
                0x01234567,
                0xffeeddcc,
                0x00000000,
                Some(b"\x08\x00\x00\x00\x67\x45\x23\x01\xcc\xdd\xee\xff"),
            ),
            (
                0x87654321,
                0x00000000,
                0x00000099,
                Some(b"\xa1\x00\x00\x00\x21\x43\x65\x87\x00\x00\x00\x00"),
            ),
            (
                0x87654321,
                0x00000000,
                0x00fffff7,
                Some(b"\xff\xff\xff\x00\x21\x43\x65\x87\x00\x00\x00\x00"),
            ),
            (0x87654321, 0x00000000, 0x00fffff8, None),
        ];
        let ser = ProtocolSerializer::new();
        for (id, next, data_len, response) in cases {
            assert_eq!(
                ser.serialize_header(*id, *next, *data_len).as_deref(),
                *response
            );
        }
    }

    fn assert_encode<'a, S: Serialize + Deserialize<'a> + Debug + Clone + PartialEq>(
        desc: &str,
        s: &S,
        seq: &[u8],
    ) {
        let id = 0x01234567u32;
        let next = 0xffeeddccu32;
        let mut header = [0u8; 12];

        header[0..4].copy_from_slice(&u32::try_from(seq.len() + 8).unwrap().to_le_bytes());
        header[4..8].copy_from_slice(&id.to_le_bytes());
        header[8..12].copy_from_slice(&next.to_le_bytes());

        let ser = ProtocolSerializer::new();
        let msg = Message {
            id,
            kind: next,
            message: Some(Bytes::copy_from_slice(seq)),
        };

        let res = ser.serialize_header(id, next, seq.len()).unwrap();
        assert_eq!(&res, &header as &[u8], "header: {}", desc);

        let res = ser.serialize_message_simple(&msg).unwrap();
        assert_eq!(res[0..12], header, "simple header: {}", desc);
        assert_eq!(res[12..], *seq, "simple body: {}", desc);

        let res = ser.serialize_body(s).unwrap();
        assert_eq!(res, *seq, "body: {}", desc);

        let msg = Message {
            id,
            kind: next,
            message: None,
        };
        let res = ser.serialize_message_typed(&msg, s).unwrap();
        assert_eq!(res[0..12], header, "typed header: {}", desc);
        assert_eq!(res[12..], *seq, "typed body: {}", desc);
    }

    fn assert_round_trip<S: Serialize + DeserializeOwned + Debug + Clone + PartialEq>(
        desc: &str,
        s: &S,
        seq: &[u8],
    ) {
        assert_encode(desc, s, seq);
        assert_decode(desc, s, seq);
    }

    fn assert_decode<S: Serialize + DeserializeOwned + Debug + Clone + PartialEq>(
        desc: &str,
        s: &S,
        seq: &[u8],
    ) {
        let id = 0x01234567u32;
        let next = 0u32;
        let mut header = [0u8; 12];

        header[0..4].copy_from_slice(&u32::try_from(seq.len() + 8).unwrap().to_le_bytes());
        header[4..8].copy_from_slice(&id.to_le_bytes());
        header[8..12].copy_from_slice(&next.to_le_bytes());

        let body = Bytes::copy_from_slice(seq);

        let ser = ProtocolSerializer::new();
        let resp = Response {
            id,
            code: next,
            message: Some(body.clone()),
        };

        let mut full_msg: Vec<u8> = header.into();
        full_msg.extend(seq);

        let res = ser.deserialize_response_typed::<S, Empty>(&resp);
        assert_eq!(
            res.unwrap().unwrap(),
            ResponseValue::Success(s.clone()),
            "deserialize typed response: {}",
            desc
        );
    }

    #[test]
    fn serialize_basic_types() {
        assert_round_trip("0u32", &0u32, b"\x00");
        assert_round_trip("all ones u32", &0xfedcba98u32, b"\x1a\xfe\xdc\xba\x98");
        assert_round_trip(
            "simple Bytes",
            &Bytes::from(b"Hello, world!\n" as &'static [u8]),
            b"\x4eHello, world!\n",
        );
        assert_encode("simple &str", &"Hello, world!\n", b"\x6eHello, world!\n");
        assert_round_trip(
            "simple String",
            &String::from("Hello, world!\n"),
            b"\x6eHello, world!\n",
        );
    }

    #[test]
    fn serialize_encoded_types() {
        assert_round_trip("ChannelID 0", &ChannelID(0), b"\x00");
        assert_round_trip(
            "ChannelID all ones u32",
            &ChannelID(0xfedcba98u32),
            b"\x1a\xfe\xdc\xba\x98",
        );
        assert_round_trip("StoreID 0", &StoreID(0), b"\x00");
        assert_round_trip(
            "StoreID pattern",
            &StoreID(0xfedcba98u32),
            b"\x1a\xfe\xdc\xba\x98",
        );
        assert_round_trip("StoreSelectorID 0", &StoreSelectorID(0), b"\x00");
        assert_round_trip(
            "StoreSelectorID pattern",
            &StoreSelectorID(0xfedcba98u32),
            b"\x1a\xfe\xdc\xba\x98",
        );
        assert_round_trip(
            "StoreSelector path",
            &StoreSelector::Path(Bytes::from(b"/dev/null" as &[u8])),
            b"\xa1\x64path\x49/dev/null",
        );
        assert_round_trip(
            "StoreSelector ID",
            &StoreSelector::ID(StoreSelectorID(0xfedcba98u32)),
            b"\xa1\x62id\x1a\xfe\xdc\xba\x98",
        );
        assert_round_trip(
            "SearchStoreElementType literal text",
            &SearchStoreElementType::Literal(Value::Text(String::from("abc123"))),
            b"\xa1\x67literal\x66abc123",
        );
        assert_round_trip(
            "SearchStoreElementType literal bytes",
            &SearchStoreElementType::Literal(Value::Bytes("abc123".into())),
            b"\xa1\x67literal\x46abc123",
        );
        assert_round_trip(
            "SearchStoreElementType literal null",
            &SearchStoreElementType::Literal(Value::Null),
            b"\xa1\x67literal\xf6",
        );
        assert_round_trip(
            "SearchStoreElementType any",
            &SearchStoreElementType::Any(()),
            b"\xa1\x63any\xf6",
        );
        assert_round_trip(
            "SearchStoreElementType none",
            &SearchStoreElementType::None(()),
            b"\xa1\x64none\xf6",
        );
    }

    #[test]
    fn serialize_requests() {
        assert_round_trip(
            "CreateExtensionRangeRequest with no second part",
            &super::CreateExtensionRangeRequest {
                extension: (
                    Bytes::from(b"foobar@test.ns.crustytoothpaste.net" as &[u8]),
                    None,
                ),
                count: 5,
            },
            b"\xa2\x69extension\x82\x58\x23foobar@test.ns.crustytoothpaste.net\xf6\x65count\x05",
        );
        assert_round_trip(
            "CreateExtensionRangeRequest with second part",
            &super::CreateExtensionRangeRequest {
                extension: (
                    Bytes::from(b"foobar@test.ns.crustytoothpaste.net" as &[u8]),
                    Some(Bytes::from(b"v1" as &[u8])),
                ),
                count: 5,
            },
            b"\xa2\x69extension\x82\x58\x23foobar@test.ns.crustytoothpaste.net\x42v1\x65count\x05",
        );
    }

    #[test]
    fn deserialize_requests() {
        assert_decode(
            "CreateExtensionRangeRequest with extension field",
            &super::CreateExtensionRangeRequest {
                extension: (
                    Bytes::from(b"foobar@test.ns.crustytoothpaste.net" as &[u8]),
                    None,
                ),
                count: 5,
            },
            b"\xa3\x69extension\x82\x58\x23foobar@test.ns.crustytoothpaste.net\xf6\x58\x26extension@test.ns.crustytoothpaste.net\xf5\x65count\x05",
        );
    }

    #[test]
    fn deserialize_requests_rw_compatible() {
        #[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
        #[serde(rename_all = "kebab-case")]
        struct ReadChannelLegacyRequest {
            pub id: ChannelID,
            pub selector: u32,
            pub count: u64,
        }

        let cases: &[(&[u8], &str)] = &[
            (b"\xa3\x62id\x00\x68selector\x02\x65count\x1a\xfe\xdc\xba\x98", "legacy"),
            (b"\xa6\x62id\x00\x68selector\x02\x65count\x1a\xfe\xdc\xba\x98\x6bstream-sync\xf6\x68blocking\xf6\x68complete\xf4", "modern"),
        ];
        for (b, desc) in cases {
            assert_decode(
                &format!("ReadChannelRequest without blocking I/O: {}", desc),
                &super::ReadChannelRequest {
                    id: ChannelID(0),
                    selector: 2,
                    count: 0xfedcba98,
                    stream_sync: None,
                    blocking: None,
                    complete: false,
                },
                b,
            );
            assert_decode(
                &format!("ReadChannelRequest (legacy): {}", desc),
                &ReadChannelLegacyRequest {
                    id: ChannelID(0),
                    selector: 2,
                    count: 0xfedcba98,
                },
                b,
            );
        }

        #[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Clone)]
        #[serde(rename_all = "kebab-case")]
        struct WriteChannelLegacyRequest {
            pub id: ChannelID,
            pub selector: u32,
            pub bytes: Bytes,
        }

        let cases: &[(&[u8], &str)] = &[
            (b"\xa3\x62id\x00\x68selector\x02\x65bytes\x44\xff\xfe\xc2\xa9", "legacy"),
            (b"\xa5\x62id\x00\x68selector\x02\x65bytes\x44\xff\xfe\xc2\xa9\x6bstream-sync\xf6\x68blocking\xf6", "modern"),
        ];
        for (b, desc) in cases {
            assert_decode(
                &format!("WriteChannelRequest without blocking I/O: {}", desc),
                &super::WriteChannelRequest {
                    id: ChannelID(0),
                    selector: 2,
                    bytes: vec![0xffu8, 0xfe, 0xc2, 0xa9].into(),
                    stream_sync: None,
                    blocking: None,
                },
                b,
            );
            assert_decode(
                &format!("WriteChannelRequest (legacy): {}", desc),
                &WriteChannelLegacyRequest {
                    id: ChannelID(0),
                    selector: 2,
                    bytes: vec![0xffu8, 0xfe, 0xc2, 0xa9].into(),
                },
                b,
            );
        }
    }
}