-
Notifications
You must be signed in to change notification settings - Fork 4
/
snoop_analyze.cxx
1795 lines (1638 loc) · 64.4 KB
/
snoop_analyze.cxx
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
#include <cassert>
#include <cstring>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <dirent.h>
#include <sys/stat.h>
// No ntoh64 on my box :(
template <typename T>
inline T NetSwap(T v)
{
if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
{
switch (sizeof(v))
{
case 2: return __bswap_16(v);
case 4: return __bswap_32(v);
case 8: return __bswap_64(v);
}
}
return v;
}
template <typename T>
inline T BtSwap(T v)
{
if (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
{
switch (sizeof(v))
{
case 1: return v;
case 2: return __bswap_16(v);
case 4: return __bswap_32(v);
case 8: return __bswap_64(v);
}
}
return v;
}
template <typename T>
inline std::string Hex(const T& v)
{
std::stringstream ss;
ss << std::hex << std::setfill('0') << std::setw(sizeof(T)*2) << (uint64_t)v;
return ss.str();
}
template <>
inline std::string Hex(const std::vector<uint8_t>& bytes)
{
std::stringstream ss;
ss << std::hex << std::setfill('0');
bool first = true;
for (uint8_t b: bytes)
{
if (!first)
ss << ' ';
first = false;
ss << std::setw(2) << (uint64_t)b;
}
return ss.str();
}
std::string ToString(const std::vector<uint8_t>& bytes)
{
bool printable = true;
size_t null_count = 0;
for (uint8_t b: bytes)
{
if (b == 0)
++null_count;
// else if (0 < b && b < 7)
// {
// printable = false;
// break;
// }
// else if (13 < b && b < 20)
// {
// printable = false;
// break;
// }
// else if (126 < b)
// {
// printable = false;
// break;
// }
else if (b < ' ' || b > '~')
{
printable = false;
break;
}
}
if (null_count > 1 || null_count == 1 && bytes.back() != 0)
printable = false;
std::string ret;
if (printable)
{
if (bytes.size() > 40)
ret = std::string(bytes.begin(), bytes.begin() + 40).c_str() + std::string("...");
else
ret = std::string(bytes.begin(), bytes.begin() + bytes.size()).c_str();
}
else
{
if (bytes.size() > 20)
ret = Hex(std::vector<uint8_t>(bytes.begin(), bytes.begin() + 20)) + " plus " + std::to_string(bytes.size() - 20) + " more";
else
ret = Hex(bytes);
}
return ret;
}
struct StreamCids
{
// TODO: A lot of the logic that uses this struct relies on the capture
// being from the perspective of the central.
uint16_t rx = 0;
uint16_t tx = 0;
bool operator<(const StreamCids& o) const
{
return (rx == o.rx ? tx < o.tx : rx < o.rx);
}
bool operator==(const StreamCids& o) const
{
return rx == o.rx && tx == o.tx;
}
};
// Monitor snoop opcodes.
static constexpr uint16_t NEW_INDEX = 0;
static constexpr uint16_t DEL_INDEX = 1;
static constexpr uint16_t COMMAND_PKT = 2;
static constexpr uint16_t EVENT_PKT = 3;
static constexpr uint16_t ACL_TX_PKT = 4;
static constexpr uint16_t ACL_RX_PKT = 5;
static constexpr uint16_t SCO_TX_PKT = 6;
static constexpr uint16_t SCO_RX_PKT = 7;
static constexpr uint16_t OPEN_INDEX = 8;
static constexpr uint16_t CLOSE_INDEX = 9;
static constexpr uint16_t INDEX_INFO = 10;
static constexpr uint16_t VENDOR_DIAG = 11;
static constexpr uint16_t SYSTEM_NOTE = 12;
static constexpr uint16_t USER_LOGGING = 13;
static constexpr uint16_t CTRL_OPEN = 14;
static constexpr uint16_t CTRL_CLOSE = 15;
static constexpr uint16_t CTRL_COMMAND = 16;
static constexpr uint16_t CTRL_EVENT = 17;
static constexpr uint16_t ISO_TX_PKT = 18;
static constexpr uint16_t ISO_RX_PKT = 19;
// LE Supported Features (The ones we care about anyways)
static constexpr uint64_t FEATURE_DLE = 0x0020;
static constexpr uint64_t FEATURE_2MPHY = 0x0100;
// Command Opcodes
#define OPCODE(ocf, ogf) ((ocf) << 10 | ogf)
static constexpr uint16_t LE_CREATE_CONNECTION = OPCODE(0x08, 0x00D);
static constexpr uint16_t LE_EXTENDED_CREATE_CONNECTION = OPCODE(0x08, 0x043);
// Special UUIDs
static const std::string GATT_SERVICES = "00002800-0000-1000-8000-00805f9b34fb";
static const std::string GATT_SECONDARY = "00002801-0000-1000-8000-00805f9b34fb";
static const std::string GATT_INCLUDE = "00002802-0000-1000-8000-00805f9b34fb";
static const std::string GATT_CHARACTERISTICS = "00002803-0000-1000-8000-00805f9b34fb";
static const std::string GATT_CHAR_DESCRIPTION = "00002901-0000-1000-8000-00805f9b34fb";
static const std::string GATT_CCC = "00002902-0000-1000-8000-00805f9b34fb";
static const std::string DEVICE_NAME = "00002a00-0000-1000-8000-00805f9b34fb";
static const std::string ASHA_READ_ONLY_PROPERTIES = "6333651e-c481-4a3e-9169-7c902aad37bb";
static const std::string ASHA_AUDIO_CONTROL_POINT = "f0d4de7e-4a88-476c-9d9f-1937b0996cc0";
static const std::string ASHA_AUDIO_STATUS = "38663f1a-e711-4cac-b641-326b56404837";
static const std::string ASHA_VOLUME = "00e4ca9e-ab14-41e4-8823-f9e70c7e91df";
static const std::string ASHA_LE_PSM_OUT = "2d410339-82b6-42aa-b34e-e2e01df8cc1a";
const std::unordered_map<std::string, std::string> KNOWN_UUIDS = {
{ GATT_SERVICES, "Services"},
{ GATT_SECONDARY, "Secondary"},
{ GATT_INCLUDE, "Include"},
{ GATT_CHARACTERISTICS, "Characteristics"},
{ GATT_CHAR_DESCRIPTION, "Description"},
{ GATT_CCC, "CCC"},
{ "0000fdf0-0000-1000-8000-00805f9b34fb", "ASHA"},
{ "6333651e-c481-4a3e-9169-7c902aad37bb", "ReadOnlyProperties"},
{ "f0d4de7e-4a88-476c-9d9f-1937b0996cc0", "AudioControlPoint"},
{ "38663f1a-e711-4cac-b641-326b56404837", "AudioStatus"},
{ "00e4ca9e-ab14-41e4-8823-f9e70c7e91df", "Volume"},
{ "2d410339-82b6-42aa-b34e-e2e01df8cc1a", "LE_PSM_OUT"},
};
// Wrapper around a buffer that can read and convert bytes and make sure we
// don't overflow.
class BtBufferStream
{
public:
BtBufferStream(const char* context, const uint8_t* p, size_t l): m_context{context}, m_p{p}, m_l{l} {}
const uint8_t* Data() const { return m_p; }
size_t Size() const { return m_l; }
uint8_t U8() { return *Bytes(1); }
uint16_t U16() { return BtSwap(*(uint16_t*)(Bytes(2))); }
uint32_t U32() { return BtSwap(*(uint32_t*)(Bytes(4))); }
uint64_t U64() { return BtSwap(*(uint64_t*)(Bytes(8))); }
void Skip(size_t count) { Bytes(count); }
BtBufferStream Sub(const char* context) { return Sub(context, m_l); }
BtBufferStream Sub(const char* context, size_t count) { return BtBufferStream(context, Bytes(context, count), count); }
std::string UUID()
{
if (m_l == 2) return UUID16();
if (m_l == 16) return UUID128();
throw std::logic_error("Not enough context to determine the uuid size");
}
std::string UUID16()
{
uint16_t uuid = U16();
std::stringstream ss;
ss << std::hex << std::setfill('0');
ss << "0000"
<< std::setw(4) << uuid
<< "-0000-1000-8000-00805f9b34fb";
return ss.str();
}
std::string UUID128()
{
const uint8_t* data = Bytes(16);
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (int i = 15; i >= 0; --i)
{
ss << std::setw(2) << (unsigned)data[i];
if (i == 12 || i == 10 || i == 8 || i == 6)
ss << '-';
}
return ss.str();
}
std::string Mac()
{
const uint8_t* data = Bytes(6);
std::stringstream ss;
ss << std::hex << std::setfill('0');
// The mac is in there backwards.
ss << std::setw(2) << (unsigned)data[5] << ':' << std::setw(2) << (unsigned)data[4] << ':' << std::setw(2) << (unsigned)data[3] << ':'
<< std::setw(2) << (unsigned)data[2] << ':' << std::setw(2) << (unsigned)data[1] << ':' << std::setw(2) << (unsigned)data[0];
return ss.str();
}
void Error(const char* e)
{
throw std::runtime_error(std::string(m_context) + " " + e);
}
protected:
const uint8_t* Bytes(size_t count) { return Bytes(m_context, count); }
const uint8_t* Bytes(const char* context, size_t count)
{
if (count > m_l)
throw std::runtime_error(std::string(context) + " truncated");
const uint8_t* ret = m_p;
m_p += count;
m_l -= count;
return ret;
}
private:
const char* m_context = nullptr;
const uint8_t* m_p = nullptr;
size_t m_l = 0;
};
// Can load a btsnoop file, and return packets one at a time.
class BtSnoopFile final
{
public:
BtSnoopFile(std::istream& in): m_in{in}
{
Reset();
}
void Reset()
{
// Read file header.
m_in.seekg(0);
char magic[8] = {};
m_in.read(magic, 8);
uint32_t version;
if (memcmp(magic, "btsnoop\0", 8) != 0 ||
!ReadInt(&version) || version != 1 ||
!ReadInt(&m_type) || !(m_type == MONITOR_FILE || m_type == HCI_FILE))
throw std::runtime_error("Not a bluetooth snoop file");
}
struct Packet
{
uint32_t length;
uint16_t idx;
uint16_t opcode;
uint64_t stamp;
uint8_t data[1024];
bool eof;
operator bool() const { return !eof; }
};
const Packet& Next()
{
uint32_t original_length;
uint32_t drops;
uint32_t flags;
if (ReadInt(&original_length) &&
ReadInt(&m_packet.length) &&
original_length == m_packet.length &&
ReadInt(&flags) &&
ReadInt(&drops) &&
ReadInt(&m_packet.stamp) &&
m_packet.length <= sizeof(m_packet.data) &&
m_in.read((char*)m_packet.data, m_packet.length))
{
// TODO: How to read an HCI file?
if (m_type == MONITOR_FILE)
{
m_packet.opcode = flags & 0xffff;
m_packet.idx = flags >> 16;
}
else
{
m_packet.idx = 0;
switch (flags & 0x3)
{
case 0: m_packet.opcode = ACL_TX_PKT; break;
case 1: m_packet.opcode = ACL_RX_PKT; break;
case 2: m_packet.opcode = COMMAND_PKT; break;
case 3: m_packet.opcode = EVENT_PKT; break;
default: m_packet.opcode = 0xffff;
}
}
m_packet.eof = false;
return m_packet;
}
m_packet.length = 0;
m_packet.eof = true;
return m_packet;
}
static constexpr uint32_t MONITOR_FILE = 2001;
static constexpr uint32_t HCI_FILE = 1001;
uint32_t Type() const { return m_type; }
private:
template<typename T>
bool ReadInt(T* v)
{
if (m_in.read((char*)v, sizeof(*v)))
{
*v = NetSwap(*v);
return true;
}
return false;
}
std::istream& m_in;
Packet m_packet{};
uint32_t m_type = 0;
};
struct GattCharacteristic
{
uint16_t handle;
uint16_t value;
uint16_t ccc;
uint16_t description;
uint8_t properties;
std::string uuid;
bool guess = false;
};
struct GattService
{
uint16_t handle;
uint16_t end_handle;
std::string uuid;
};
struct L2CapCreditConnection
{
bool outgoing = false;
StreamCids cids{};
uint16_t psm = 0;
uint16_t mtu = 0; // Maximum pre-fragmented packet size
uint16_t mps = 0; // Maximum fragment size
int32_t tx_credits = 0;
};
class BtDatabase final
{
public:
BtDatabase()
{
// First, try to load the bluez database. This requires root access though.
LoadPath("/var/lib/bluetooth");
// Next, try to load anything we have stored locally, so that we can
// cache any mac addesses we find in snoop files.
std::string home = getenv("HOME");
LoadPath(home + "/.local/share/snoop_analyze");
}
~BtDatabase()
{
// Dump the database to our local cache.
std::string home = getenv("HOME");
mkdir((home + "/.local/share/snoop_analyze").c_str(), 0770);
mkdir((home + "/.local/share/snoop_analyze/cache").c_str(), 0770);
for (auto& kv: m_info)
{
if (kv.first.empty() || kv.first == s_default_mac)
continue; // Don't dump empty or defaulted macs to the database.
std::ofstream out(home + "/.local/share/snoop_analyze/cache/" + kv.first);
// Index everything first so that we can output the interleaved data
// with the handles in order.
std::vector<std::pair<const GattService*, const GattCharacteristic*>> idx;
idx.reserve(65536);
for (auto& s: kv.second.services)
{
if (idx.size() <= s.handle)
idx.resize(s.handle + 1);
idx[s.handle].first = &s;
}
for (auto& c: kv.second.characteristics)
{
if (idx.size() <= c.handle)
idx.resize(c.handle + 1);
idx[c.handle].second = &c;
}
out << "[Attributes]\n";
for (size_t i = 0; i < idx.size(); ++i)
{
if (idx[i].first)
out << Hex((uint16_t)i) << "=2800:" << Hex(idx[i].first->end_handle) << ":" << idx[i].first->uuid << '\n';
else if (idx[i].second)
{
auto& c = *idx[i].second;
out << Hex((uint16_t)i) << "=2803:" << Hex(c.value) << ":" << Hex(c.properties) << ":" << c.uuid << '\n';
if (c.ccc)
out << Hex(c.ccc) << "=" << GATT_CCC << '\n';
if (c.description)
out << Hex(c.description) << "=" << GATT_CHAR_DESCRIPTION << '\n';
}
}
}
}
static void SetDefaultMac(const std::string& mac)
{
s_default_mac.clear();
for (auto c: mac)
s_default_mac.push_back(std::tolower(c));
}
const std::vector<GattService>& Services(const std::string& mac) const
{
static std::vector<GattService> empty;
auto it = m_info.find(mac.empty() ? s_default_mac : mac);
return it == m_info.end() ? empty : it->second.services;
}
const std::vector<GattCharacteristic>& Characteristics(const std::string& mac) const
{
static std::vector<GattCharacteristic> empty;
auto it = m_info.find(mac.empty() ? s_default_mac : mac);
return it == m_info.end() ? empty : it->second.characteristics;
}
void CacheService(const std::string& mac, const GattService& service)
{
auto& info = m_info[mac.empty() ? s_default_mac : mac];
for (auto& old_service: info.services)
{
if (old_service.uuid == service.uuid)
{
old_service = service;
return;
}
}
info.services.push_back(service);
}
void CacheCharacteristic(const std::string& mac, const GattCharacteristic& characteristic)
{
auto& info = m_info[mac.empty() ? s_default_mac : mac];
for (auto& old_char: info.characteristics)
{
if (old_char.uuid == characteristic.uuid)
{
old_char = characteristic;
return;
}
}
info.characteristics.push_back(characteristic);
}
private:
void LoadPath(const std::string& path)
{
// Recursively search all directories for the "cache" directory, then
// parse all mac address-named files in it.
bool cache = path.size() > 5 && path.substr(path.size() - 5) == "cache";
std::shared_ptr<DIR> d(opendir(path.c_str()), closedir);
if (d)
{
struct dirent* de{};
while ((de = readdir(d.get())))
{
if (de->d_name[0] == '.')
continue;
else if (de->d_type == DT_DIR)
LoadPath(path + "/" + de->d_name);
else if (cache && de->d_type == DT_REG)
{
// Is this filename a mac address?
bool ismac = de->d_name[17] == 0; // Has to be 17 chars long.
for (size_t i = 0; i < 17 && ismac; ++i)
{
if (i % 3 == 2)
ismac = de->d_name[i] == ':';
else
ismac = isxdigit(de->d_name[i]);
}
if (ismac)
LoadDatabase(path + "/" + de->d_name, de->d_name);
}
}
}
}
void LoadDatabase(const std::string& path, const std::string& mac)
{
std::vector<GattService> services;
std::vector<GattCharacteristic> characteristics;
// These are in glib's keyfile format. Kind of like ini files.
auto split = [](const std::string& s, char c) {
std::vector<std::string> ret;
size_t pos = 0;
size_t char_pos = s.find(c);
while (char_pos != std::string::npos)
{
ret.push_back(s.substr(pos, char_pos - pos));
pos = char_pos + 1;
char_pos = s.find(c, pos);
}
ret.push_back(s.substr(pos));
return ret;
};
std::ifstream in(path);
std::string line;
std::string section;
while (std::getline(in, line))
{
// Strip trailing whitespace.
while (!line.empty() && std::isspace(line.back()))
line.pop_back();
// Comment character only allowed on the front.
if (line.empty() || line.front() == '#')
continue;
if (line.front() == '[' && line.back() == ']')
section = line.substr(1, line.size() - 2);
else if (section == "Attributes")
{
size_t eqpos = line.find('=');
if (eqpos == std::string::npos)
continue; // Broken File?
std::string key = line.substr(0, eqpos);
auto values = split(line.substr(eqpos+1), ':');
// service: 2800:end:uuid
// secondary svc: 2801:end:uuid
// include: 2802:start:end:uuid
// characteristic: 2803:value handle:properties:uuid
// descriptor: ext_props:uuid_str
// descriptor: uuid_str
uint16_t handle = std::stoul(key, nullptr, 16);
if (values.size() == 1)
{
// Descriptor for the most recently read characteristic.
assert(!characteristics.empty());
if (characteristics.empty())
continue;
if (values.front() == GATT_CCC)
characteristics.back().ccc = handle;
else if (values.front() == GATT_CHAR_DESCRIPTION)
characteristics.back().description = handle;
}
else if (values.front() == "2800" || values.front() == "2801")
{
assert(values.size() == 3);
if (values.size() != 3)
continue;
uint16_t end_handle = std::stoul(values[1], nullptr, 16);
services.push_back(GattService{handle, end_handle, values[2]});
}
else if (values.front() == "2802")
throw std::runtime_error("Please implement includes");
else if (values.front() == "2803")
{
assert(values.size() == 4);
if (values.size() != 4)
continue;
uint16_t value_handle = std::stoul(values[1], nullptr, 16);
uint8_t properties = std::stoul(values[2], nullptr, 16);
characteristics.push_back(GattCharacteristic{handle, value_handle, 0, 0, properties, values[3]});
}
// else we don't care? or don't support?
}
// else We don't care about other sections.
}
std::string mac_lower;
for (char c: mac) mac_lower.push_back(std::tolower(c));
auto& info = m_info[mac_lower];
info.services = std::move(services);
info.characteristics = std::move(characteristics);
}
private:
struct CacheInfo
{
std::vector<GattService> services;
std::vector<GattCharacteristic> characteristics;
};
std::map<std::string, CacheInfo> m_info;
static std::string s_default_mac;
};
std::string BtDatabase::s_default_mac;
class BtParser final
{
public:
void Parse(uint16_t opcode, BtBufferStream& b)
{
// TODO: Opcode meaning changes depending on the file type.
switch(opcode)
{
case COMMAND_PKT: CommandPkt(b.Sub("HCI Command")); break;
case EVENT_PKT: EventPkt(b.Sub("HCI Event")); break;
case ACL_TX_PKT: AclPkt(false, b.Sub("ACL TX Packet")); break;
case ACL_RX_PKT: AclPkt(true, b.Sub("ACL RX Packet")); break;
case NEW_INDEX: /* TODO: read adapter mac here, to get cache path in /var/lib/bluetooth */ break;
case SYSTEM_NOTE:
if (NoteCallback)
NoteCallback(std::string(b.Data(), b.Data() + b.Size()));
break;
}
}
std::function<void(const std::string& s)> NoteCallback;
std::function<void(uint16_t connection_handle, uint8_t status, const std::string& mac, uint16_t interval, uint16_t latency, uint16_t timeout)> ConnectionCallback;
std::function<void(uint16_t connection_handle, uint16_t tx_dlen, uint16_t tx_time, uint16_t rx_dlen, uint16_t rx_time)> DleChange;
std::function<void(uint16_t connection_handle, uint64_t features)> RemoteFeatures;
std::function<void(uint16_t connection_handle, uint16_t handle, uint16_t end_handle, const std::string& uuid)> Service;
std::function<void(uint16_t connection_handle, uint16_t handle, uint16_t value, uint8_t props, const std::string& uuid)> Characteristic;
std::function<void(uint16_t connection_handle, uint16_t char_handle, uint16_t desc_handle, const std::string& uuid)> Descriptor;
std::function<void(uint16_t connection_handle, uint16_t handle, const std::vector<uint8_t>& bytes)> Write;
std::function<void(uint16_t connection_handle, uint16_t handle, const std::vector<uint8_t>& bytes)> Read;
std::function<void(uint16_t connection_handle, uint16_t handle, uint8_t code)> FailedWrite;
std::function<void(uint16_t connection_handle, uint16_t handle, uint8_t code)> FailedRead;
std::function<void(uint16_t connection_handle, uint16_t status, const L2CapCreditConnection& info)> NewCreditConnection;
std::function<void(uint16_t connection_handle, bool rx, const L2CapCreditConnection& info, const uint8_t* data, size_t len, size_t fragment_count)> Data;
struct HandleInfo
{
enum {INVALID, SERVICE, CHAR, CHAR_CCC, CHAR_DESCRIPTION, CHAR_VALUE, CHAR_DESCRIPTOR} type = INVALID;
uint16_t handle = 0;
GattService* service = nullptr;
GattCharacteristic* characteristic = nullptr;
};
HandleInfo FindHandle(uint16_t connection, uint16_t handle)
{
auto& conn = m_connections[connection];
if (conn.services.empty())
{
for (auto& s: m_db.Services(""))
conn.services[s.handle] = s;
}
if (conn.characteristic.empty())
{
for (auto& c: m_db.Characteristics(""))
conn.characteristic[c.handle] = c;
}
GattService* pservice = nullptr;
// First, check if it is a service. If it isn't, which service does it
// belong to?
for (auto& s: conn.services)
{
if (s.first == handle) return HandleInfo{HandleInfo::SERVICE, handle, &s.second};
if (s.second.handle < handle && handle <= s.second.end_handle)
{
pservice = &s.second;
break;
}
}
// Then check the characteristics.
for (auto& c: conn.characteristic)
{
if (pservice && (pservice->handle > c.first || pservice->end_handle < c.first))
continue;
if (c.second.value == handle) return HandleInfo{HandleInfo::CHAR_VALUE, handle, pservice, &c.second};
if (c.second.ccc == handle) return HandleInfo{HandleInfo::CHAR_CCC, handle, pservice, &c.second};
if (c.second.description == handle) return HandleInfo{HandleInfo::CHAR_DESCRIPTION, handle, pservice, &c.second};
if (c.first == handle) return HandleInfo{HandleInfo::CHAR, handle, pservice, &c.second};
// TODO: handle other descriptor types.
}
// TODO: I'm not sure how, but bluez seems to infer the ccc
// descriptor handles for the service changed characteristic
for (auto& c: conn.characteristic)
{
if (pservice && (pservice->handle > c.first || pservice->end_handle < c.first))
continue;
if ((c.second.value + 1 == handle) && c.second.uuid == "00002a05-0000-1000-8000-00805f9b34fb")
return HandleInfo{HandleInfo::CHAR_CCC, handle, pservice, &c.second};
}
return HandleInfo{};
}
std::string HandleDescription(uint16_t connection, uint16_t handle)
{
return HandleDescription(FindHandle(connection, handle));
}
std::string UuidStr(const std::string& uuid)
{
auto it = KNOWN_UUIDS.find(uuid);
return it == KNOWN_UUIDS.end() ? uuid : it->second;
}
std::string HandleDescription(const HandleInfo& info)
{
switch (info.type)
{
case HandleInfo::SERVICE: return UuidStr(info.service->uuid);
case HandleInfo::CHAR: return UuidStr(info.characteristic->uuid);
case HandleInfo::CHAR_CCC: return UuidStr(info.characteristic->uuid) + " ccc";
case HandleInfo::CHAR_DESCRIPTION: return UuidStr(info.characteristic->uuid) + " description";
case HandleInfo::CHAR_VALUE: return UuidStr(info.characteristic->uuid) + " value";
case HandleInfo::CHAR_DESCRIPTOR: return UuidStr(info.characteristic->uuid) + " descriptor";
default: return "unknown";
}
}
void AddCharacteristicGuess(uint16_t connection, uint16_t value_handle, const std::string& uuid)
{
// We don't know the characteristic handle so just use the value_handle
// instead.
auto& characteristic = m_connections[connection].characteristic[value_handle];
characteristic.value = value_handle;
characteristic.uuid = uuid;
characteristic.guess = true;
}
protected:
void CommandPkt(BtBufferStream pkt)
{
uint16_t opcode = pkt.U16();
switch (opcode)
{
case LE_CREATE_CONNECTION:
{
BtBufferStream b = pkt.Sub("LE Create Connection", 25);
b.Skip(13);
m_pending_connection = PendingConnectionInfo{};
m_pending_connection.phy = 1;
m_pending_connection.p1m.interval_min = b.U16();
m_pending_connection.p1m.interval_max = b.U16();
m_pending_connection.p1m.latency = b.U16();
m_pending_connection.p1m.timeout = b.U16();
m_pending_connection.p1m.celength_min = b.U16();
m_pending_connection.p1m.celength_max = b.U16();
break;
}
case LE_EXTENDED_CREATE_CONNECTION:
{
BtBufferStream b = pkt.Sub("LE Extended Create Connection");
b.Skip(10);
m_pending_connection = PendingConnectionInfo{};
m_pending_connection.phy = b.U8();
auto ReadPhyParam = [&](uint16_t& param1m, uint16_t& param2m){
for (uint8_t i = 0; i < 8; ++i)
{
if (m_pending_connection.phy & (1 << i))
{
uint16_t param = b.U16();
if (i == 0)
param1m = param;
else if (i == 1)
param2m = param;
// else if (i == 2) // coded
}
}
};
uint16_t unused;
ReadPhyParam(unused, unused); // scan interval
ReadPhyParam(unused, unused); // scan window
ReadPhyParam(m_pending_connection.p1m.interval_min, m_pending_connection.p2m.interval_min);
ReadPhyParam(m_pending_connection.p1m.interval_max, m_pending_connection.p2m.interval_max);
ReadPhyParam(m_pending_connection.p1m.latency, m_pending_connection.p2m.latency);
ReadPhyParam(m_pending_connection.p1m.timeout, m_pending_connection.p2m.timeout);
ReadPhyParam(m_pending_connection.p1m.celength_min, m_pending_connection.p2m.celength_min);
ReadPhyParam(m_pending_connection.p1m.celength_max, m_pending_connection.p2m.celength_max);
break;
}
}
}
void LeMetaEvent(BtBufferStream pkt)
{
uint8_t length = pkt.U8();
if (length > pkt.Size())
pkt.Error("bad length");
uint8_t subcode = pkt.U8();
switch(subcode)
{
case 0x01: // LE Connection Complete
{
BtBufferStream b = pkt.Sub("LE Connection Complete");
uint8_t status = b.U8();
uint16_t handle = b.U16();
b.U8(); // Role
auto& conn = m_connections[handle] = ConnectionInfo{};
conn.handle = handle;
conn.type = ConnectionInfo::L2CAP;
conn.mac = b.Mac();
conn.interval = b.U16();
conn.latency = b.U16();
conn.timeout = b.U16();
// b.U8(); // clock accuracy
// TODO: The pending connection object can have both phy2m and
// and phy1m parameters. How do we know which was selected?
conn.celength = m_pending_connection.p1m.celength_min;
conn.phy = m_pending_connection.phy & 2 ? ConnectionInfo::PHY2M : ConnectionInfo::PHY1M;
if (ConnectionCallback)
ConnectionCallback(handle, status, conn.mac, conn.interval, conn.latency, conn.timeout);
// Load any cached services and characteristics.
for (auto& s: m_db.Services(conn.mac))
conn.services[s.handle] = s;
for (auto& c: m_db.Characteristics(conn.mac))
conn.characteristic[c.handle] = c;
break;
}
case 0x0a: // LE Enhanced Connection Complete
{
BtBufferStream b = pkt.Sub("LE Enhanced Connection Complete");
uint8_t status = b.U8();
uint16_t handle = b.U16();
auto& conn = m_connections[handle] = ConnectionInfo{};
conn.handle = handle;
b.Skip(2); // role/peer address type
conn.type = ConnectionInfo::L2CAP;
conn.mac = b.Mac();
b.Skip(12); // local/peer resolvable macs
conn.interval = b.U16();
conn.latency = b.U16();
conn.timeout = b.U16();
b.U8(); // clock accuracy
// TODO: The pending connection object can have both phy2m and
// and phy1m parameters. How do we know which was selected?
conn.celength = m_pending_connection.p1m.celength_min;
conn.phy = m_pending_connection.phy & 2 ? ConnectionInfo::PHY2M : ConnectionInfo::PHY1M;
if (ConnectionCallback)
ConnectionCallback(conn.handle, status, conn.mac, conn.interval, conn.latency, conn.timeout);
// Load any cached services and characteristics.
for (auto& s: m_db.Services(conn.mac))
conn.services[s.handle] = s;
for (auto& c: m_db.Characteristics(conn.mac))
conn.characteristic[c.handle] = c;
break;
}
case 0x07: // LE Data Length Change
{
BtBufferStream b = pkt.Sub("LE Data Length Change");
uint16_t handle = b.U16();
auto& conn = m_connections[handle];
conn.tx_dlen = b.U16();
conn.tx_time = b.U16();
conn.rx_dlen = b.U16();
conn.rx_time = b.U16();
if (DleChange)
DleChange(conn.handle, conn.tx_dlen, conn.tx_time, conn.rx_dlen, conn.rx_time);
break;
}
case 0x04: // LE Read Remote Features
{
BtBufferStream b = pkt.Sub("LE Data Length Change");
uint8_t status = b.U8();
uint16_t handle = b.U16();
uint64_t flags = b.U64();
auto& conn = m_connections[handle];
conn.features = flags;
if (RemoteFeatures)
RemoteFeatures(handle, flags);
break;
}
case 0x0c: // PHY update complete
{
BtBufferStream b = pkt.Sub("PHY update complete");
uint8_t status = b.U8();
uint16_t handle = b.U16();
uint8_t tx = b.U8();
uint8_t rx = b.U8();
auto& conn = m_connections[handle];
if (tx == 1)
conn.phy = ConnectionInfo::PHY1M;
else if (tx == 2)
conn.phy = ConnectionInfo::PHY2M;
else
conn.phy = ConnectionInfo::PHY_UNKNOWN;
break;
}
}
}
void EventPkt(BtBufferStream pkt)
{
switch (pkt.U8())
{
case 0x3e: LeMetaEvent(pkt.Sub("LE Meta Event")); break;
}
}
void FindInformationResponse(bool rx, uint16_t connection_handle, BtBufferStream b)
{
uint8_t format = b.U8();
if (format != 1 && format != 2) // 16 bit / 128 bit uuids
throw std::runtime_error("implement additional uuid types please!"); // don't know what this is.
size_t response_size = format == 1 ? 4 : 18;
size_t count = b.Size() / response_size;
auto& conn = m_connections[connection_handle];
for (size_t i = 0; i < count; ++i)
{
BtBufferStream binfo = b.Sub("Information Data", response_size);
uint16_t handle = binfo.U16();
std::string uuid = format == 1 ? binfo.UUID16() : binfo.UUID128();
// I'm a little fuzzy on how to find the correct handle here. The
// central would request these for any gaps in the handles, and so
// would know which characteristic or service this belongs to.
// For now, assuming that handle is not in the characteristic list,
// lower_bound returns the element after the one we want, so go to the
// previous element to get the associated characteristic.
auto it = conn.characteristic.lower_bound(handle);
if (it != conn.characteristic.begin())
{
--it;