-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmeshtastic_decoder.cpp
More file actions
3676 lines (3392 loc) · 103 KB
/
meshtastic_decoder.cpp
File metadata and controls
3676 lines (3392 loc) · 103 KB
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 "meshtastic_decoder.h"
#include "aes_barebones.h"
#include <cstring>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const std::vector<uint8_t> MeshtasticDecoder::DEFAULT_PSK = {
0xd4, 0xf1, 0xbb, 0x3a, 0x20, 0x29, 0x07, 0x59,
0xf0, 0xbc, 0xff, 0xab, 0xcf, 0x4e, 0x69, 0x01
};
MeshtasticDecoder::DecodedPacket
MeshtasticDecoder::decodePacket(const std::vector<uint8_t>& raw_data)
{
DecodedPacket result;
result.success = false;
result.error_message = "";
result.debug_info = "";
// Initialize default values
result.to_address = 0;
result.from_address = 0;
result.packet_id = 0;
result.flags = 0;
result.channel = 0;
result.next_hop = 0;
result.relay_node = 0;
result.port = 0;
result.app_name = "UNKNOWN";
result.latitude = 0.0;
result.longitude = 0.0;
result.altitude = 0;
result.timestamp = 0;
result.sats_in_view = 0;
result.sats_in_use = 0;
result.ground_speed = 0;
result.ground_track = -1.0; // Use -1.0 as sentinel for "not set"
result.gps_accuracy = 0;
result.pdop = 0.0;
result.hdop = 0.0;
result.vdop = 0.0;
result.fix_quality = 0;
result.fix_type = 0;
result.precision_bits = 0;
result.altitude_hae = 0;
result.altitude_geoidal_separation = 0;
result.location_source = 0;
result.altitude_source = 0;
result.timestamp_millis_adjust = 0;
result.sensor_id = 0;
result.next_update = 0;
result.seq_number = 0;
result.node_id = "";
result.long_name = "";
result.short_name = "";
result.macaddr = "";
result.hw_model = "";
result.firmware_version = "";
result.mqtt_id = "";
result.text_message = "";
result.from_node = "";
result.to_node = "";
result.route_nodes.clear();
result.route_back_nodes.clear();
result.snr_towards.clear();
result.snr_back.clear();
result.route_path = "";
result.route_back_path = "";
result.route_count = 0;
result.route_back_count = 0;
result.route_type = "";
result.skip_count = 0;
result.heard_directly = false;
result.hop_limit = 0;
result.routing_info = "";
result.telemetry_type = "";
result.telemetry_time = 0;
result.battery_level = 0;
result.voltage = 0.0f;
result.channel_utilization = 0.0f;
result.air_util_tx = 0.0f;
result.uptime_seconds = 0;
result.temperature = 0.0f;
result.relative_humidity = 0.0f;
result.barometric_pressure = 0.0f;
result.gas_resistance = 0.0f;
result.current = 0.0f;
result.iaq = 0;
result.distance = 0.0f;
result.lux = 0.0f;
result.white_lux = 0.0f;
result.ir_lux = 0.0f;
result.uv_lux = 0.0f;
result.wind_direction = 0;
result.wind_speed = 0.0f;
result.weight = 0.0f;
result.wind_gust = 0.0f;
result.wind_lull = 0.0f;
result.radiation = 0.0f;
result.rainfall_1h = 0.0f;
result.rainfall_24h = 0.0f;
result.soil_moisture = 0;
result.soil_temperature = 0.0f;
result.pm10_standard = 0;
result.pm25_standard = 0;
result.pm100_standard = 0;
result.pm10_environmental = 0;
result.pm25_environmental = 0;
result.pm100_environmental = 0;
result.particles_03um = 0;
result.particles_05um = 0;
result.particles_10um = 0;
result.particles_25um = 0;
result.particles_50um = 0;
result.particles_100um = 0;
result.co2 = 0;
result.co2_temperature = 0.0f;
result.co2_humidity = 0.0f;
result.form_formaldehyde = 0.0f;
result.form_humidity = 0.0f;
result.form_temperature = 0.0f;
result.ch1_voltage = result.ch1_current = 0.0f;
result.ch2_voltage = result.ch2_current = 0.0f;
result.ch3_voltage = result.ch3_current = 0.0f;
result.ch4_voltage = result.ch4_current = 0.0f;
result.ch5_voltage = result.ch5_current = 0.0f;
result.ch6_voltage = result.ch6_current = 0.0f;
result.ch7_voltage = result.ch7_current = 0.0f;
result.ch8_voltage = result.ch8_current = 0.0f;
result.num_packets_tx = 0;
result.num_packets_rx = 0;
result.num_packets_rx_bad = 0;
result.num_online_nodes = 0;
result.num_total_nodes = 0;
result.num_rx_dupe = 0;
result.num_tx_relay = 0;
result.num_tx_relay_canceled = 0;
result.heap_total_bytes = 0;
result.heap_free_bytes = 0;
result.num_tx_dropped = 0;
result.heart_bpm = 0;
result.spO2 = 0;
result.body_temperature = 0.0f;
result.freemem_bytes = 0;
result.diskfree1_bytes = 0;
result.diskfree2_bytes = 0;
result.diskfree3_bytes = 0;
result.load1 = 0;
result.load5 = 0;
result.load15 = 0;
result.host_user_string = "";
result.request_id = 0;
result.reply_id = 0;
result.want_response = false;
// Parse header
if (!parseHeader(raw_data, result))
{
result.error_message = "Failed to parse packet header";
return result;
}
// Calculate skip count and routing information
calculateSkipAndRouting(result);
// Extract payload
if (raw_data.size() < 16)
{
result.error_message = "Packet too short for header";
return result;
}
std::vector<uint8_t> encrypted_payload(raw_data.begin() + 16,
raw_data.end());
// Check if payload is already unencrypted
// Unencrypted packets have protobuf data directly in the payload
// They MUST start with:
// - 0x08 (field 1 tag for portnum, wire type 0 = varint)
// - 0x12 (field 2 tag for payload, wire type 2 = length-delimited)
//
// NOTE: We cannot use a generic "looks like protobuf" check because encrypted
// data can randomly look like valid protobuf tags, causing false positives.
// We must be strict and only accept known-good patterns.
std::vector<uint8_t> decrypted_payload;
bool is_unencrypted = false;
if (encrypted_payload.size() > 0) {
uint8_t first_byte = encrypted_payload[0];
// Only accept if it explicitly starts with known Data message fields
// Field 1 (portnum): 0x08 (field 1, wire type 0)
// Field 2 (payload): 0x12 (field 2, wire type 2)
// However, 0x12 alone is not definitive - encrypted data can also start with 0x12
// So we'll try unencrypted first, but fall back to decryption if parsing fails
if (first_byte == 0x08) {
// Definitely looks like unencrypted (starts with port field)
is_unencrypted = true;
decrypted_payload = encrypted_payload;
} else if (first_byte == 0x12) {
// Might be unencrypted (starts with payload field), but could also be encrypted
// Try as unencrypted first, but we'll validate and fall back to decryption if needed
is_unencrypted = true;
decrypted_payload = encrypted_payload;
}
// Otherwise, assume it's encrypted and decrypt it
}
if (!is_unencrypted) {
// Try to decrypt payload
if (!decryptPayload(encrypted_payload, result, decrypted_payload))
{
result.error_message = "Failed to decrypt payload";
return result;
}
}
// Store decrypted payload as hex
result.decrypted_payload_hex = bytesToHexString(decrypted_payload);
// Store nonce and key information
std::vector<uint8_t> nonce = buildNonce(result);
result.nonce_hex = bytesToHexString(nonce);
result.key_used = "1PG7OiApB1nwvP+rz05pAQ==";
// Parse protobuf
if (decrypted_payload.size() < 1)
{
result.error_message = "Decrypted payload too short";
return result;
}
// Debug: Check if payload looks like valid protobuf
// Valid protobuf tags are: 0x08 (field 1), 0x0A (field 1, length-delimited), 0x10 (field 2), 0x12 (field 2, length-delimited), etc.
// Check for any valid protobuf field tags in the first few bytes
bool has_protobuf_tag = false;
for (size_t i = 0; i < decrypted_payload.size() && i < 32; i++) {
uint8_t byte = decrypted_payload[i];
uint8_t field_num = byte >> 3;
uint8_t wire_type = byte & 0x07;
// Valid protobuf tags have field_num 1-15 and wire_type 0-5
if (field_num >= 1 && field_num <= 15 && wire_type <= 5) {
has_protobuf_tag = true;
break;
}
}
// Extract port number and set app name
// The Data protobuf message structure:
// Field 1 (portnum): tag byte 0x08 (field 1, wire type 0 = varint), then port value as varint
// Field 2 (payload): tag byte 0x12 (field 2, wire type 2 = length-delimited), then length, then data
// Other fields may come before field 1, so we need to scan the entire payload
// So we need to parse the port as a varint, not read it directly
size_t offset = 0;
result.port = 0;
// Scan the entire payload for the port field (0x08 tag)
// Don't limit to first 16 bytes - valid packets may have other fields first
for (size_t i = 0; i < decrypted_payload.size() - 1; i++) {
if (decrypted_payload[i] == 0x08) {
// Found field 1 tag (0x08 = field 1, wire type 0)
offset = i + 1;
if (offset < decrypted_payload.size()) {
// Decode port as varint
size_t varint_offset = offset;
uint64_t port_value = decodeVarint(decrypted_payload, varint_offset);
if (port_value > 0 && port_value < 256) { // Valid port range
result.port = (uint8_t)port_value;
break; // Found valid port, stop scanning
} else {
// Invalid port value, continue scanning
result.port = 0;
}
}
}
}
// DEBUG: If port not found, collect detailed analysis
if (result.port == 0 && decrypted_payload.size() > 0) {
std::stringstream debug_ss;
debug_ss << "Port field not found. Decrypted payload ("
<< decrypted_payload.size() << " bytes, first 64): ";
for (size_t i = 0; i < decrypted_payload.size() && i < 64; i++) {
debug_ss << std::hex << std::setfill('0') << std::setw(2)
<< (int)decrypted_payload[i] << " ";
}
debug_ss << std::dec << "\nProtobuf field analysis:\n";
// Analyze protobuf structure
size_t debug_offset = 0;
int field_count = 0;
while (debug_offset < decrypted_payload.size() && field_count < 20) {
if (debug_offset >= decrypted_payload.size()) break;
size_t saved_offset = debug_offset;
uint8_t first_byte = decrypted_payload[debug_offset];
uint64_t tag_wire_type = decodeVarint(decrypted_payload, debug_offset);
if (tag_wire_type == 0) break;
uint8_t field_number = tag_wire_type >> 3;
uint8_t wire_type = tag_wire_type & 0x07;
// Validate field number is reasonable (protobuf field numbers are typically 1-19000 for valid messages)
// Very high field numbers (>100) in the first few fields suggest invalid decryption
bool suspicious_field = (field_count < 3 && field_number > 100);
debug_ss << " Field " << (int)field_number
<< ", wire_type " << (int)wire_type
<< " (offset " << saved_offset << ", byte=0x"
<< std::hex << std::setfill('0') << std::setw(2) << (int)first_byte << std::dec << ")";
if (suspicious_field) {
debug_ss << " <-- SUSPICIOUS: Very high field number suggests invalid decryption!";
}
if (field_number == 1 && wire_type == 0) {
debug_ss << " <-- PORT FIELD!";
// Decode the port value
size_t port_offset = debug_offset;
uint64_t port_value = decodeVarint(decrypted_payload, port_offset);
debug_ss << " (port=" << port_value << ")";
}
debug_ss << "\n";
// Skip field value
if (wire_type == 0) { // Varint
uint64_t varint_val = decodeVarint(decrypted_payload, debug_offset);
debug_ss << " Value (varint): " << varint_val << "\n";
} else if (wire_type == 1) { // Fixed64
debug_offset += 8;
debug_ss << " Value (fixed64): 8 bytes\n";
} else if (wire_type == 2 || wire_type == 3) { // Length-delimited
uint64_t length = decodeVarint(decrypted_payload, debug_offset);
debug_ss << " Value (length-delimited): length=" << length << "\n";
if (debug_offset + length <= decrypted_payload.size()) {
debug_ss << " Data: ";
for (size_t i = 0; i < length && i < 16; i++) {
debug_ss << std::hex << std::setfill('0') << std::setw(2)
<< (int)decrypted_payload[debug_offset + i] << " ";
}
debug_ss << std::dec << "\n";
}
debug_offset += length;
} else if (wire_type == 5) { // Fixed32
debug_offset += 4;
debug_ss << " Value (fixed32): 4 bytes\n";
} else {
// Invalid wire type - skip one byte and continue
debug_offset = saved_offset + 1;
debug_ss << " Invalid wire type, skipping\n";
}
field_count++;
}
result.debug_info = debug_ss.str();
}
// SPECIAL CASE: If packet starts with field 2 (0x12) and we haven't found port yet,
// the port might be missing or the packet might use a different format.
// Some Meshtastic packets might not include the port field explicitly if it's implied.
// Try to infer port from the payload content or use a default.
if (result.port == 0 && decrypted_payload.size() > 0 && decrypted_payload[0] == 0x12) {
// Packet starts with field 2 (payload) - port might be missing
// Try to parse the payload field and see if we can infer the port from content
size_t payload_start = 1; // Skip 0x12 tag
if (payload_start < decrypted_payload.size()) {
size_t length_offset = payload_start;
uint64_t payload_length = decodeVarint(decrypted_payload, payload_start);
// Validate payload length
size_t remaining = decrypted_payload.size() - payload_start;
if (payload_length > remaining) {
// Invalid length - use remaining bytes
payload_length = remaining;
payload_start = length_offset + 1; // Skip tag, use remaining as payload
}
if (payload_start + payload_length <= decrypted_payload.size() && payload_length > 0) {
std::vector<uint8_t> inner_payload(
decrypted_payload.begin() + payload_start,
decrypted_payload.begin() + payload_start + payload_length
);
// Try to find port in the inner payload (some packet formats nest the port)
for (size_t i = 0; i < inner_payload.size() - 1; i++) {
if (inner_payload[i] == 0x08) {
size_t port_offset = i + 1;
uint64_t port_value = decodeVarint(inner_payload, port_offset);
if (port_value > 0 && port_value < 256) {
result.port = (uint8_t)port_value;
break;
}
}
}
// If still no port, try to continue parsing after the payload field
// to see if port comes after
size_t after_payload = payload_start + payload_length;
if (result.port == 0 && after_payload < decrypted_payload.size()) {
for (size_t i = after_payload; i < decrypted_payload.size() - 1; i++) {
if (decrypted_payload[i] == 0x08) {
size_t port_offset = i + 1;
uint64_t port_value = decodeVarint(decrypted_payload, port_offset);
if (port_value > 0 && port_value < 256) {
result.port = (uint8_t)port_value;
break;
}
}
}
}
}
}
}
// If port field not found, try parsing as full protobuf Data message
// Some packets might have the Data message structure with other fields first
// Protobuf fields can appear in any order, so we need to scan through all fields
if (result.port == 0) {
// Try to parse the entire payload as a Data message
// This will find the port field even if it's not at the start
size_t data_offset = 0;
std::vector<uint8_t> payload_data; // Store field 2 (payload) if we find it
while (data_offset < decrypted_payload.size()) {
size_t saved_offset = data_offset;
if (data_offset >= decrypted_payload.size())
break;
uint64_t tag_wire_type = decodeVarint(decrypted_payload, data_offset);
if (tag_wire_type == 0 || data_offset >= decrypted_payload.size())
break;
uint8_t field_number = tag_wire_type >> 3;
uint8_t wire_type = tag_wire_type & 0x07;
if (field_number == 1 && wire_type == 0) {
// Found field 1: portnum
uint64_t port_value = decodeVarint(decrypted_payload, data_offset);
if (port_value > 0 && port_value < 256) {
result.port = (uint8_t)port_value;
// Don't break - continue to find payload field
}
} else if (field_number == 2 && (wire_type == 2 || wire_type == 3)) {
// Found field 2: payload (length-delimited)
// Handle both wire type 2 (normal) and 3 (deprecated groups, but seen in practice)
// For wire type 3, treat it the same as wire type 2 (length-delimited)
size_t length_offset = data_offset;
uint64_t length = decodeVarint(decrypted_payload, data_offset);
// Validate length is reasonable (not larger than remaining payload)
// Some malformed packets may have invalid varint lengths
size_t remaining = decrypted_payload.size() - data_offset;
if (length > remaining) {
// Length is too large - likely invalid varint decoding or malformed packet
// Try to recover by using remaining bytes as the payload
// This handles cases where the varint length is corrupted
length = remaining;
// Reset offset to where length decoding started, then skip just the tag byte
data_offset = length_offset + 1; // Skip the 0x12 tag byte
}
if (data_offset + length <= decrypted_payload.size() && length > 0 && length < 10000) {
payload_data = std::vector<uint8_t>(
decrypted_payload.begin() + data_offset,
decrypted_payload.begin() + data_offset + length
);
data_offset += length;
// The payload field contains the actual app data (Text, Position, etc.)
// But the port should be in the Data message, not in the payload
// However, if we haven't found port yet, maybe this packet format is different
// Check if the payload itself contains the port field
if (result.port == 0 && payload_data.size() > 0) {
// Scan the payload for port field
for (size_t p = 0; p < payload_data.size() - 1; p++) {
if (payload_data[p] == 0x08) {
size_t port_offset = p + 1;
uint64_t port_value = decodeVarint(payload_data, port_offset);
if (port_value > 0 && port_value < 256) {
result.port = (uint8_t)port_value;
break;
}
}
}
}
} else {
// Invalid length, try to recover by treating as single-byte length
if (data_offset < decrypted_payload.size() && decrypted_payload[data_offset] < 128) {
length = decrypted_payload[data_offset];
data_offset++;
if (data_offset + length <= decrypted_payload.size() && length > 0) {
payload_data = std::vector<uint8_t>(
decrypted_payload.begin() + data_offset,
decrypted_payload.begin() + data_offset + length
);
data_offset += length;
// Check for port in payload
if (result.port == 0 && payload_data.size() > 0) {
for (size_t p = 0; p < payload_data.size() - 1; p++) {
if (payload_data[p] == 0x08) {
size_t port_offset = p + 1;
uint64_t port_value = decodeVarint(payload_data, port_offset);
if (port_value > 0 && port_value < 256) {
result.port = (uint8_t)port_value;
break;
}
}
}
}
} else {
data_offset = saved_offset + 1;
}
} else {
// Invalid length, skip
data_offset = saved_offset + 1;
}
}
} else {
// Skip other fields
if (wire_type == 0) { // Varint
decodeVarint(decrypted_payload, data_offset);
} else if (wire_type == 1) { // Fixed64
if (data_offset + 8 <= decrypted_payload.size()) {
data_offset += 8;
} else {
break;
}
} else if (wire_type == 2 || wire_type == 3) { // Length-delimited or deprecated groups
uint64_t length = decodeVarint(decrypted_payload, data_offset);
if (data_offset + length <= decrypted_payload.size() && length < 10000) {
data_offset += length;
} else {
break;
}
} else if (wire_type == 5) { // Fixed32
if (data_offset + 4 <= decrypted_payload.size()) {
data_offset += 4;
} else {
break;
}
} else {
// Unknown wire type, skip one byte and continue
data_offset = saved_offset + 1;
}
}
}
}
// If still no port found, this is likely invalid or encrypted incorrectly
// However, if we tried as unencrypted (starting with 0x12) and failed,
// try decrypting it as encrypted data - it might be encrypted after all
if (result.port == 0 && is_unencrypted && encrypted_payload.size() > 0 && encrypted_payload[0] == 0x12) {
// Packet started with 0x12 but we couldn't find port - might actually be encrypted
// Try decrypting it
std::vector<uint8_t> encrypted_try = encrypted_payload;
std::vector<uint8_t> decrypted_try;
if (decryptPayload(encrypted_try, result, decrypted_try)) {
// Decryption succeeded - try parsing again
decrypted_payload = decrypted_try;
result.decrypted_payload_hex = bytesToHexString(decrypted_payload);
// Try to find port in decrypted payload
for (size_t i = 0; i < decrypted_payload.size() - 1; i++) {
if (decrypted_payload[i] == 0x08) {
size_t offset = i + 1;
size_t varint_offset = offset;
uint64_t port_value = decodeVarint(decrypted_payload, varint_offset);
if (port_value > 0 && port_value < 256) {
result.port = (uint8_t)port_value;
break;
}
}
}
// If still no port, continue with the fallback error handling below
}
}
if (result.port == 0) {
// Provide more detailed error message
std::string hex_preview = bytesToHexString(std::vector<uint8_t>(
decrypted_payload.begin(),
decrypted_payload.begin() + (decrypted_payload.size() > 32 ? 32 : decrypted_payload.size())
));
// Check if we have suspicious field numbers (suggests wrong decryption key)
bool has_suspicious_fields = false;
size_t check_offset = 0;
int suspicious_count = 0;
for (int i = 0; i < 5 && check_offset < decrypted_payload.size(); i++) {
uint64_t tag = decodeVarint(decrypted_payload, check_offset);
if (tag == 0) break;
uint8_t field_num = tag >> 3;
if (field_num > 100) {
suspicious_count++;
}
}
has_suspicious_fields = (suspicious_count >= 2);
result.error_message = "Port field (0x08 tag) not found in decrypted payload - may be invalid encryption or corrupted packet. First bytes: " + hex_preview;
if (has_suspicious_fields) {
result.error_message += " (WARNING: Suspiciously high field numbers detected - likely wrong decryption key/channel!)";
} else if (has_protobuf_tag) {
result.error_message += " (contains valid protobuf tags but no port field)";
} else {
result.error_message += " (does not appear to be valid protobuf)";
}
return result;
}
switch (result.port)
{
case 1:
result.app_name = "TEXT_MESSAGE_APP";
break;
case 3:
result.app_name = "POSITION_APP";
break;
case 4:
result.app_name = "NODEINFO_APP";
break;
case 8:
result.app_name = "WAYPOINT_APP";
break;
case 66:
result.app_name = "RANGE_TEST_APP";
break;
case 67:
result.app_name = "TELEMETRY_APP";
break;
case 70:
result.app_name = "TRACEROUTE_APP";
break;
default:
result.app_name = "UNKNOWN_APP";
break;
}
// Decode MeshPacket protobuf fields (if present in decrypted payload)
// This extracts fields like relay_node (field 19) and next_hop (field 18) from the MeshPacket structure
decodeMeshPacketFields(decrypted_payload, result);
// Decode protobuf data based on app type
if (!decodeProtobuf(decrypted_payload, result))
{
result.error_message = "Failed to decode protobuf data";
return result;
}
// Set node_id from from_address (only if not already set by protobuf parsing)
if (result.node_id.empty())
{
std::stringstream ss;
ss << "!" << std::hex << std::setfill('0') << std::setw(8)
<< result.from_address;
result.node_id = ss.str();
}
result.success = true;
return result;
}
bool MeshtasticDecoder::parseHeader(const std::vector<uint8_t>& data,
DecodedPacket& packet)
{
if (data.size() < 16)
{
return false;
}
// Parse header fields (little-endian)
packet.to_address =
data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
packet.from_address =
data[4] | (data[5] << 8) | (data[6] << 16) | (data[7] << 24);
packet.packet_id =
data[8] | (data[9] << 8) | (data[10] << 16) | (data[11] << 24);
packet.flags = data[12];
packet.channel = data[13];
packet.next_hop = data[14];
packet.relay_node = data[15];
return true;
}
std::vector<uint8_t> MeshtasticDecoder::buildNonce(
const DecodedPacket& packet)
{
std::vector<uint8_t> nonce(16, 0);
// Packet ID (4 bytes, little-endian)
nonce[0] = packet.packet_id & 0xFF;
nonce[1] = (packet.packet_id >> 8) & 0xFF;
nonce[2] = (packet.packet_id >> 16) & 0xFF;
nonce[3] = (packet.packet_id >> 24) & 0xFF;
// Zero padding (4 bytes) - already zero
// Sender Address (4 bytes, little-endian)
nonce[8] = packet.from_address & 0xFF;
nonce[9] = (packet.from_address >> 8) & 0xFF;
nonce[10] = (packet.from_address >> 16) & 0xFF;
nonce[11] = (packet.from_address >> 24) & 0xFF;
// Zero padding (4 bytes) - already zero
return nonce;
}
bool MeshtasticDecoder::decryptPayload(
const std::vector<uint8_t>& encrypted_payload,
const DecodedPacket& packet,
std::vector<uint8_t>& decrypted)
{
// Build nonce
std::vector<uint8_t> nonce = buildNonce(packet);
// Initialize AES
AES128Barebones aes;
aes.setKey(DEFAULT_PSK.data());
// Decrypt
decrypted.resize(encrypted_payload.size());
aes.decryptCTR(encrypted_payload.data(),
decrypted.data(),
encrypted_payload.size(),
nonce.data());
return true;
}
bool MeshtasticDecoder::decodeProtobuf(
const std::vector<uint8_t>& data,
DecodedPacket& packet)
{
if (data.empty())
{
return false;
}
// Decode Data message fields (request_id, reply_id, want_response, etc.)
// These fields are in the full Data message, not just the payload
decodeDataMessageFields(data, packet);
// Parse the Data message to find the payload field (field 2)
// We can't assume it's at a fixed offset because other fields might come before it
std::vector<uint8_t> protobuf_data;
size_t offset = 0;
while (offset < data.size())
{
// Read field tag and wire type
uint64_t tag_wire_type = decodeVarint(data, offset);
if (tag_wire_type == 0)
break;
uint8_t field_number = tag_wire_type >> 3;
uint8_t wire_type = tag_wire_type & 0x07;
if (field_number == 1 && wire_type == 0) // Field 1: portnum (varint)
{
// Already decoded, skip
decodeVarint(data, offset);
}
else if (field_number == 2 && wire_type == 2) // Field 2: payload (length-delimited)
{
// Found the payload field!
uint64_t length = decodeVarint(data, offset);
if (offset + length <= data.size())
{
// Extract protobuf data
protobuf_data = std::vector<uint8_t>(data.begin() + offset,
data.begin() + offset + length);
offset += length;
break; // Found payload, stop parsing
}
}
else
{
// Skip other fields
if (wire_type == 0) // Varint
{
decodeVarint(data, offset);
}
else if (wire_type == 1) // Fixed64
{
offset += 8;
}
else if (wire_type == 2) // Length-delimited
{
uint64_t length = decodeVarint(data, offset);
offset += length;
}
else if (wire_type == 5) // Fixed32
{
offset += 4;
}
}
}
// Decode based on app type
if (!protobuf_data.empty())
{
switch (packet.port)
{
case 1: // TEXT_MESSAGE_APP
return decodeTextMessage(protobuf_data, packet);
case 3: // POSITION_APP
return decodePosition(protobuf_data, packet);
case 4: // NODEINFO_APP
return decodeNodeInfo(data, packet);
case 8: // WAYPOINT_APP
// For waypoint, just return success without decoding
return true;
case 66: // RANGE_TEST_APP
// For range test, just return success without decoding
return true;
case 67: // TELEMETRY_APP
return decodeTelemetry(protobuf_data, packet);
case 70: // TRACEROUTE_APP
// For traceroute, the protobuf_data is the Routing message
// (field 2 of Data message contains the Routing message)
return decodeTraceroute(protobuf_data, packet);
default:
// For unknown apps, just return success without decoding
return true;
}
}
return true;
}
void MeshtasticDecoder::decodeMeshPacketFields(
const std::vector<uint8_t>& data,
DecodedPacket& packet)
{
// Decode MeshPacket protobuf fields from the decrypted payload
// MeshPacket structure may contain additional routing information
// Fields we're interested in:
// - field 18: next_hop (uint32 varint in protobuf) - represents last byte of next hop node
// - field 19: relay_node (uint32 varint in protobuf) - represents last byte of relay node
// Note: Protobuf defines these as uint32, but semantically they represent the last byte
// of the node number. We decode the full uint32 value and extract the last byte.
if (data.empty())
{
return;
}
size_t offset = 0;
// Parse MeshPacket fields
while (offset < data.size())
{
if (offset >= data.size())
break;
// Read field tag and wire type
uint64_t tag_wire_type = decodeVarint(data, offset);
if (tag_wire_type == 0)
break;
uint8_t field_number = tag_wire_type >> 3;
uint8_t wire_type = tag_wire_type & 0x07;
switch (field_number)
{
case 18: // next_hop (uint32 varint) - last byte of next hop node
if (wire_type == 0) // Varint
{
uint64_t next_hop_val = decodeVarint(data, offset);
// Protobuf defines this as uint32, but semantically it represents
// the last byte of the node number. Decode full uint32 and extract last byte.
// Only update if we got a non-zero value (0 means not set)
if (next_hop_val > 0)
{
packet.next_hop = (next_hop_val & 0xFF);
}
}
break;
case 19: // relay_node (uint32 varint) - last byte of relay node
if (wire_type == 0) // Varint
{
uint64_t relay_node_val = decodeVarint(data, offset);
// Protobuf defines this as uint32, but semantically it represents
// the last byte of the node number. Decode full uint32 and extract last byte.
// Only update if we got a non-zero value (0 means not set)
if (relay_node_val > 0)
{
packet.relay_node = (relay_node_val & 0xFF);
}
}
break;
default:
// Skip other fields - we only care about routing fields here
// The actual Data message decoding happens in decodeProtobuf
if (wire_type == 0)
{
decodeVarint(data, offset);
}
else if (wire_type == 2)
{
uint64_t field_length = decodeVarint(data, offset);
offset += field_length;
}
else if (wire_type == 5)
{
offset += 4; // Skip fixed32
}
else
{
offset++;
}
break;
}
}
}
void MeshtasticDecoder::decodeDataMessageFields(
const std::vector<uint8_t>& data,
DecodedPacket& packet)
{
// Decode Data message protobuf fields from the decrypted payload
// Data message structure (from mesh.proto):
// - field 1: portnum (uint32 varint) - already decoded
// - field 2: payload (bytes) - already decoded
// - field 7: request_id (fixed32) - packet_id of message being replied to
// - field 8: reply_id (fixed32) - reply_id field
// - field 9: want_response (bool varint) - want_response flag
// - field 10: dest (uint32 varint) - destination address
// - field 11: source (uint32 varint) - source address
// - field 12: emoji (uint32 varint) - emoji field
// - field 13: want_ack (bool varint) - want_ack flag
if (data.empty())
{
return;
}
size_t offset = 0;
// Parse Data message fields
while (offset < data.size())
{
if (offset >= data.size())
break;
// Read field tag and wire type
uint64_t tag_wire_type = decodeVarint(data, offset);
if (tag_wire_type == 0)
break;
uint8_t field_number = tag_wire_type >> 3;
uint8_t wire_type = tag_wire_type & 0x07;
switch (field_number)
{
case 1: // portnum (uint32 varint) - already decoded, skip
if (wire_type == 0) // Varint
{
decodeVarint(data, offset);
}
break;
case 2: // payload (bytes) - already decoded, skip
if (wire_type == 2) // Length-delimited
{
uint64_t field_length = decodeVarint(data, offset);
offset += field_length;
}
break;
case 7: // request_id (fixed32) - packet_id of message being replied to
if (wire_type == 5) // Fixed32
{
if (offset + 4 <= data.size())
{
packet.request_id = data[offset] |
(data[offset + 1] << 8) |
(data[offset + 2] << 16) |
(data[offset + 3] << 24);
offset += 4;
}
}
break;
case 8: // reply_id (fixed32)
if (wire_type == 5) // Fixed32
{
if (offset + 4 <= data.size())
{
packet.reply_id = data[offset] |
(data[offset + 1] << 8) |
(data[offset + 2] << 16) |
(data[offset + 3] << 24);