forked from TrippyLighting/EthernetBonjour
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EthernetBonjour.cpp
1440 lines (1156 loc) · 38.7 KB
/
EthernetBonjour.cpp
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
// Copyright (C) 2010 Georg Kaindl
// http://gkaindl.com
//
// This file is part of Arduino EthernetBonjour.
//
// EthernetBonjour is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// EthernetBonjour is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with EthernetBonjour. If not, see
// <http://www.gnu.org/licenses/>.
//
#define HAS_SERVICE_REGISTRATION 1 // disabling saves about 1.25 kilobytes
#define HAS_NAME_BROWSING 1 // disable together with above, additionally saves about 4.3 kilobytes
#include <string.h>
#include <stdlib.h>
#include <Arduino.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
extern "C" {
#include <utility/EthernetUtil.h>
}
#include "EthernetBonjour.h"
#define MDNS_DEFAULT_NAME "arduino"
#define MDNS_TLD ".local"
#define DNS_SD_SERVICE "_services._dns-sd._udp.local"
#define MDNS_SERVER_PORT (5353)
#define MDNS_NQUERY_RESEND_TIME (1000) // 1 second, name query resend timeout
#define MDNS_SQUERY_RESEND_TIME (10000) // 10 seconds, service query resend timeout
#define MDNS_RESPONSE_TTL (120) // two minutes (in seconds)
#define MDNS_MAX_SERVICES_PER_PACKET (6)
//#define _BROKEN_MALLOC_ 1
#undef _USE_MALLOC_
static uint8_t mdnsMulticastIPAddr[] = { 224, 0, 0, 251 };
//static uint8_t mdnsHWAddr[] = { 0x01, 0x00, 0x5e, 0x00, 0x00, 0xfb };
typedef enum _MDNSPacketType_t {
MDNSPacketTypeMyIPAnswer,
MDNSPacketTypeNoIPv6AddrAvailable,
MDNSPacketTypeServiceRecord,
MDNSPacketTypeServiceRecordRelease,
MDNSPacketTypeNameQuery,
MDNSPacketTypeServiceQuery,
} MDNSPacketType_t;
typedef struct _DNSHeader_t {
uint16_t xid;
uint8_t recursionDesired : 1;
uint8_t truncated : 1;
uint8_t authoritiveAnswer : 1;
uint8_t opCode : 4;
uint8_t queryResponse : 1;
uint8_t responseCode : 4;
uint8_t checkingDisabled : 1;
uint8_t authenticatedData : 1;
uint8_t zReserved : 1;
uint8_t recursionAvailable : 1;
uint16_t queryCount;
uint16_t answerCount;
uint16_t authorityCount;
uint16_t additionalCount;
} __attribute__( (__packed__) ) DNSHeader_t;
typedef enum _DNSOpCode_t {
DNSOpQuery = 0,
DNSOpIQuery = 1,
DNSOpStatus = 2,
DNSOpNotify = 4,
DNSOpUpdate = 5
} DNSOpCode_t;
// for some reason, I get data corruption issues with normal malloc() on arduino 0017
void* my_malloc(unsigned s)
{
#if defined(_BROKEN_MALLOC_)
char* b = (char*)malloc(s + 2);
if (b)
b++;
return (void*)b;
#else
return malloc(s);
#endif
}
void my_free(void* ptr)
{
#if defined(_BROKEN_MALLOC_)
char* b = (char*)ptr;
if (b)
b--;
free(b);
#else
free(ptr);
#endif
}
EthernetBonjourClass::EthernetBonjourClass()
{
memset( &this->_mdnsData, 0, sizeof(MDNSDataInternal_t) );
memset( &this->_serviceRecords, 0, sizeof(this->_serviceRecords) );
this->_state = MDNSStateIdle;
// this->_sock = -1;
this->_bonjourName = NULL;
this->_resolveNames[0] = NULL;
this->_resolveNames[1] = NULL;
this->_lastAnnounceMillis = 0;
}
EthernetBonjourClass::~EthernetBonjourClass()
{
this->stop();
}
// return values:
// 1 on success
// 0 otherwise
int EthernetBonjourClass::begin(const char* bonjourName)
{
// if we were called very soon after the board was booted, we need to give the
// EthernetShield (WIZnet) some time to come up. Hence, we delay until millis() is at
// least 3000. This is necessary, so that if we need to add a service record directly
// after begin, the announce packet does not get lost in the bowels of the WIZnet chip.
while (millis() < 3000) delay(100);
int statusCode = 0;
statusCode = this->setBonjourName(bonjourName);
if (statusCode)
statusCode = this->beginMulticast(mdnsMulticastIPAddr, MDNS_SERVER_PORT);
return statusCode;
}
// return values:
// 1 on success
// 0 otherwise
int EthernetBonjourClass::begin()
{
return this->begin(MDNS_DEFAULT_NAME);
}
// return values:
// 1 on success
// 0 otherwise
int EthernetBonjourClass::_initQuery(uint8_t idx, const char* name, unsigned long timeout)
{
int statusCode = 0;
if ( NULL == this->_resolveNames[idx] && NULL != ( (0 == idx) ? (void*)this->_nameFoundCallback :
(void*)this->_serviceFoundCallback ) ) {
this->_resolveNames[idx] = (uint8_t*)name;
if (timeout)
this->_resolveTimeouts[idx] = millis() + timeout;
else
this->_resolveTimeouts[idx] = 0;
statusCode = ( MDNSSuccess == this->_sendMDNSMessage(0,
0,
(idx == 0) ? MDNSPacketTypeNameQuery :
MDNSPacketTypeServiceQuery,
0) );
} else
my_free( (void*)name );
return statusCode;
}
void EthernetBonjourClass::_cancelQuery(uint8_t idx)
{
if (NULL != this->_resolveNames[idx]) {
my_free(this->_resolveNames[idx]);
this->_resolveNames[idx] = NULL;
}
}
// return values:
// 1 on success
// 0 otherwise
int EthernetBonjourClass::resolveName(const char* name, unsigned long timeout)
{
this->cancelResolveName();
char* n = (char*)my_malloc(strlen(name) + 7);
if (NULL == n)
return 0;
strcpy(n, name);
strcat(n, MDNS_TLD);
return this->_initQuery(0, n, timeout);
}
void EthernetBonjourClass::setNameResolvedCallback(BonjourNameFoundCallback newCallback)
{
this->_nameFoundCallback = newCallback;
}
void EthernetBonjourClass::cancelResolveName()
{
this->_cancelQuery(0);
}
int EthernetBonjourClass::isResolvingName()
{
return (NULL != this->_resolveNames[0]);
}
void EthernetBonjourClass::setServiceFoundCallback(BonjourServiceFoundCallback newCallback)
{
this->_serviceFoundCallback = newCallback;
}
// return values:
// 1 on success
// 0 otherwise
int EthernetBonjourClass::startDiscoveringService(const char* serviceName,
MDNSServiceProtocol_t proto,
unsigned long timeout)
{
this->stopDiscoveringService();
char* n = (char*)my_malloc(strlen(serviceName) + 13);
if (NULL == n)
return 0;
strcpy(n, serviceName);
const uint8_t* srv_type = this->_postfixForProtocol(proto);
if (srv_type)
strcat(n, (const char*)srv_type);
this->_resolveServiceProto = proto;
return this->_initQuery(1, n, timeout);
}
void EthernetBonjourClass::stopDiscoveringService()
{
this->_cancelQuery(1);
}
int EthernetBonjourClass::isDiscoveringService()
{
return (NULL != this->_resolveNames[1]);
}
// return value:
// A DNSError_t (DNSSuccess on success, something else otherwise)
// in "int" mode: positive on success, negative on error
MDNSError_t EthernetBonjourClass::_sendMDNSMessage(uint32_t peerAddress, uint32_t xid, int type,
int serviceRecord)
{
MDNSError_t statusCode = MDNSSuccess;
uint16_t ptr = 0;
#if defined(_USE_MALLOC_)
DNSHeader_t* dnsHeader = NULL;
#else
DNSHeader_t dnsHeaderBuf;
DNSHeader_t* dnsHeader = &dnsHeaderBuf;
#endif
uint8_t* buf;
#if defined(_USE_MALLOC_)
dnsHeader = (DNSHeader_t*)my_malloc( sizeof(DNSHeader_t) );
if (NULL == dnsHeader) {
statusCode = MDNSOutOfMemory;
goto errorReturn;
}
#endif
memset( dnsHeader, 0, sizeof(DNSHeader_t) );
dnsHeader->xid = ethutil_htons(xid);
dnsHeader->opCode = DNSOpQuery;
switch (type) {
case MDNSPacketTypeServiceRecordRelease:
case MDNSPacketTypeMyIPAnswer:
dnsHeader->answerCount = ethutil_htons(1);
dnsHeader->queryResponse = 1;
dnsHeader->authoritiveAnswer = 1;
break;
case MDNSPacketTypeServiceRecord:
dnsHeader->answerCount = ethutil_htons(4);
dnsHeader->additionalCount = ethutil_htons(1);
dnsHeader->queryResponse = 1;
dnsHeader->authoritiveAnswer = 1;
break;
case MDNSPacketTypeNameQuery:
case MDNSPacketTypeServiceQuery:
dnsHeader->queryCount = ethutil_htons(1);
break;
case MDNSPacketTypeNoIPv6AddrAvailable:
dnsHeader->queryCount = ethutil_htons(1);
dnsHeader->additionalCount = ethutil_htons(1);
dnsHeader->responseCode = 0x03;
dnsHeader->authoritiveAnswer = 1;
dnsHeader->queryResponse = 1;
break;
}
this->beginPacket(mdnsMulticastIPAddr,MDNS_SERVER_PORT);
this->write( (uint8_t*)dnsHeader,sizeof(DNSHeader_t) );
ptr += sizeof(DNSHeader_t);
buf = (uint8_t*)dnsHeader;
// construct the answer section
switch (type) {
case MDNSPacketTypeMyIPAnswer: {
this->_writeMyIPAnswerRecord( &ptr, buf, sizeof(DNSHeader_t) );
break;
}
#if defined(HAS_SERVICE_REGISTRATION) && HAS_SERVICE_REGISTRATION
case MDNSPacketTypeServiceRecord: {
// SRV location record
this->_writeServiceRecordName(serviceRecord, &ptr, buf, sizeof(DNSHeader_t), 0);
buf[0] = 0x00;
buf[1] = 0x21; // SRV record
buf[2] = 0x80; // cache flush
buf[3] = 0x01; // class IN
// ttl
*( (uint32_t*)&buf[4] ) = ethutil_htonl(MDNS_RESPONSE_TTL);
// data length
*( (uint16_t*)&buf[8] ) = ethutil_htons( 8 + strlen( (char*)this->_bonjourName ) );
this->write( (uint8_t*)buf,10 );
ptr += 10;
// priority and weight
buf[0] = buf[1] = buf[2] = buf[3] = 0;
// port
*( (uint16_t*)&buf[4] ) = ethutil_htons(this->_serviceRecords[serviceRecord]->port);
this->write( (uint8_t*)buf,6 );
ptr += 6;
// target
this->_writeDNSName(this->_bonjourName, &ptr, buf, sizeof(DNSHeader_t), 1);
// TXT record
this->_writeServiceRecordName(serviceRecord, &ptr, buf, sizeof(DNSHeader_t), 0);
buf[0] = 0x00;
buf[1] = 0x10; // TXT record
buf[2] = 0x80; // cache flush
buf[3] = 0x01; // class IN
// ttl
*( (uint32_t*)&buf[4] ) = ethutil_htonl(MDNS_RESPONSE_TTL);
this->write( (uint8_t*)buf,8 );
ptr += 8;
// data length && text
if (NULL == this->_serviceRecords[serviceRecord]->textContent) {
buf[0] = 0x00;
buf[1] = 0x01;
buf[2] = 0x00;
this->write( (uint8_t*)buf,3 );
ptr += 3;
} else {
int slen = strlen( (char*)this->_serviceRecords[serviceRecord]->textContent );
*( (uint16_t*)buf ) = ethutil_htons(slen);
this->write( (uint8_t*)buf,2 );
ptr += 2;
this->write( (uint8_t*)this->_serviceRecords[serviceRecord]->textContent,slen );
ptr += slen;
}
// PTR record (for the dns-sd service in general)
this->_writeDNSName( (const uint8_t*)DNS_SD_SERVICE, &ptr, buf,
sizeof(DNSHeader_t), 1 );
buf[0] = 0x00;
buf[1] = 0x0c; // PTR record
buf[2] = 0x00; // no cache flush
buf[3] = 0x01; // class IN
// ttl
*( (uint32_t*)&buf[4] ) = ethutil_htonl(MDNS_RESPONSE_TTL);
// data length.
uint16_t dlen = strlen( (char*)this->_serviceRecords[serviceRecord]->servName ) + 2;
*( (uint16_t*)&buf[8] ) = ethutil_htons(dlen);
this->write( (uint8_t*)buf, 10 );
ptr += 10;
this->_writeServiceRecordName(serviceRecord, &ptr, buf, sizeof(DNSHeader_t), 1);
// PTR record (our service)
this->_writeServiceRecordPTR(serviceRecord, &ptr, buf, sizeof(DNSHeader_t),
MDNS_RESPONSE_TTL);
// finally, our IP address as additional record
this->_writeMyIPAnswerRecord( &ptr, buf, sizeof(DNSHeader_t) );
break;
}
case MDNSPacketTypeServiceRecordRelease: {
// just send our service PTR with a TTL of zero
this->_writeServiceRecordPTR(serviceRecord, &ptr, buf, sizeof(DNSHeader_t), 0);
break;
}
#endif // defined(HAS_SERVICE_REGISTRATION) && HAS_SERVICE_REGISTRATION
#if defined(HAS_NAME_BROWSING) && HAS_NAME_BROWSING
case MDNSPacketTypeNameQuery:
case MDNSPacketTypeServiceQuery:
{
// construct a query for the currently set _resolveNames[0]
this->_writeDNSName(
(type == MDNSPacketTypeServiceQuery) ? this->_resolveNames[1] :
this->_resolveNames[0],
&ptr, buf, sizeof(DNSHeader_t), 1);
buf[0] = buf[2] = 0x0;
buf[1] = (type == MDNSPacketTypeServiceQuery) ? 0x0c : 0x01;
buf[3] = 0x1;
this->write( (uint8_t*)buf, sizeof(DNSHeader_t) );
ptr += sizeof(DNSHeader_t);
this->_resolveLastSendMillis[(type == MDNSPacketTypeServiceQuery) ? 1 : 0] = millis();
break;
}
#endif // defined(HAS_NAME_BROWSING) && HAS_NAME_BROWSING
case MDNSPacketTypeNoIPv6AddrAvailable: {
// since the WIZnet doesn't have IPv6, we will respond with a Not Found message
this->_writeDNSName(this->_bonjourName, &ptr, buf, sizeof(DNSHeader_t), 1);
buf[0] = buf[2] = 0x0;
buf[1] = 0x1c; // AAAA record
buf[3] = 0x01;
this->write( (uint8_t*)buf, 4 );
ptr += 4;
// send our IPv4 address record as additional record, in case the peer wants it.
this->_writeMyIPAnswerRecord( &ptr, buf, sizeof(DNSHeader_t) );
break;
}
}
this->endPacket();
#if defined(_USE_MALLOC_)
errorReturn:
if (NULL != dnsHeader)
my_free(dnsHeader);
#endif
return statusCode;
}
// return value:
// A DNSError_t (DNSSuccess on success, something else otherwise)
// in "int" mode: positive on success, negative on error
MDNSError_t EthernetBonjourClass::_processMDNSQuery()
{
MDNSError_t statusCode = MDNSSuccess;
#if defined(_USE_MALLOC_)
DNSHeader_t* dnsHeader = NULL;
#else
DNSHeader_t dnsHeaderBuf;
DNSHeader_t* dnsHeader = &dnsHeaderBuf;
#endif
uint16_t i, j;
uint8_t* buf;
uint32_t xid;
uint16_t udp_len, qCnt, aCnt, aaCnt, addCnt;
uint8_t recordsAskedFor[NumMDNSServiceRecords + 2];
uint8_t recordsFound[2];
uint8_t wantsIPv6Addr = 0;
uint8_t * udpBuffer = NULL;
uintptr_t ptr;
memset( recordsAskedFor, 0, sizeof(uint8_t) * (NumMDNSServiceRecords + 2) );
memset(recordsFound, 0, sizeof(uint8_t) * 2);
udp_len = this->parsePacket();
if (0 == udp_len) {
statusCode = MDNSTryLater;
goto errorReturn;
}
udpBuffer = (uint8_t*) my_malloc(udp_len); //allocate memory to hold _remaining UDP packet
if (NULL == udpBuffer) {
this->flush();
statusCode = MDNSOutOfMemory;
goto errorReturn;
}
this->read( (uint8_t*)udpBuffer, udp_len ); //read _remaining UDP packet from W5100/W5200 into memory
ptr = (uintptr_t)udpBuffer;
#if defined(_USE_MALLOC_)
dnsHeader = (DNSHeader_t*)my_malloc( sizeof(DNSHeader_t) );
if (NULL == dnsHeader) {
statusCode = MDNSOutOfMemory;
goto errorReturn;
}
#endif
buf = (uint8_t*)dnsHeader;
memcpy( (uint8_t*)buf, (uint16_t*)ptr,sizeof(DNSHeader_t) );
xid = ethutil_ntohs(dnsHeader->xid);
qCnt = ethutil_ntohs(dnsHeader->queryCount);
aCnt = ethutil_ntohs(dnsHeader->answerCount);
aaCnt = ethutil_ntohs(dnsHeader->authorityCount);
addCnt = ethutil_ntohs(dnsHeader->additionalCount);
if ( 0 == dnsHeader->queryResponse &&
DNSOpQuery == dnsHeader->opCode &&
MDNS_SERVER_PORT == this->remotePort() )
{
// process an MDNS query
int offset = sizeof(DNSHeader_t);
uint8_t* buf = (uint8_t*)dnsHeader;
int rLen = 0, tLen = 0;
// read over the query section
for (i = 0; i < qCnt; i++) {
// construct service name data structures for comparison
const uint8_t* servNames[NumMDNSServiceRecords + 2];
int servLens[NumMDNSServiceRecords + 2];
uint8_t servNamePos[NumMDNSServiceRecords + 2];
uint8_t servMatches[NumMDNSServiceRecords + 2];
// first entry is our own MDNS name, the rest are our services
servNames[0] = (const uint8_t*)this->_bonjourName;
servNamePos[0] = 0;
servLens[0] = strlen( (char*)this->_bonjourName );
servMatches[0] = 1;
// second entry is our own the general DNS-SD service
servNames[1] = (const uint8_t*)DNS_SD_SERVICE;
servNamePos[1] = 0;
servLens[1] = strlen( (char*)DNS_SD_SERVICE );
servMatches[1] = 1;
for (j = 2; j < NumMDNSServiceRecords + 2; j++)
if (NULL != this->_serviceRecords[j - 2] && NULL != this->_serviceRecords[j - 2]->servName) {
servNames[j] = this->_serviceRecords[j - 2]->servName;
servLens[j] = strlen( (char*)servNames[j] );
servMatches[j] = 1;
servNamePos[j] = 0;
} else {
servNames[j] = NULL;
servLens[j] = 0;
servMatches[j] = 0;
servNamePos[j] = 0;
}
tLen = 0;
do {
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),1 );
offset += 1;
rLen = buf[0];
tLen += 1;
if (rLen > 128) {// handle DNS name compression, kinda, sorta
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),1 );
offset += 1;
for (j = 0; j < NumMDNSServiceRecords + 2; j++) {
if (servNamePos[j] && servNamePos[j] != buf[0]) {
servMatches[j] = 0;
}
}
tLen += 1;
} else if (rLen > 0) {
int tr = rLen, ir;
while (tr > 0) {
ir = ( tr > sizeof(DNSHeader_t) ) ? sizeof(DNSHeader_t) : tr;
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),ir );
offset += ir;
tr -= ir;
for (j = 0; j < NumMDNSServiceRecords + 2; j++) {
if (!recordsAskedFor[j] && servMatches[j])
servMatches[j] &= this->_matchStringPart(&servNames[j], &servLens[j], buf,
ir);
}
}
tLen += rLen;
}
} while (rLen > 0 && rLen <= 128);
// if this matched a name of ours (and there are no characters left), then
// check whether this is an A record query (for our own name) or a PTR record query
// (for one of our services).
// if so, we'll note to send a record
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),4 );
offset += 4;
for (j = 0; j < NumMDNSServiceRecords + 2; j++) {
if (!recordsAskedFor[j] && servNames[j] && servMatches[j] && 0 == servLens[j]) {
if (0 == servNamePos[j])
servNamePos[j] = offset - 4 - tLen;
if ( buf[0] == 0 && buf[3] == 0x01 &&
(buf[2] == 0x00 || buf[2] == 0x80) ) {
if ( (0 == j && 0x01 == buf[1]) || ( 0 < j && (0x0c == buf[1] || 0x10 == buf[1] || 0x21 == buf[1]) ) )
recordsAskedFor[j] = 1;
else if (0 == j && 0x1c == buf[1])
wantsIPv6Addr = 1;
}
}
}
}
}
#if (defined(HAS_SERVICE_REGISTRATION) && HAS_SERVICE_REGISTRATION) || (defined(HAS_NAME_BROWSING) && HAS_NAME_BROWSING)
else if ( 1 == dnsHeader->queryResponse &&
DNSOpQuery == dnsHeader->opCode &&
MDNS_SERVER_PORT == remotePort() &&
(NULL != this->_resolveNames[0] || NULL != this->_resolveNames[1]) )
{
int offset = sizeof(DNSHeader_t);
uint8_t* buf = (uint8_t*)dnsHeader;
int rLen = 0, tLen = 0;
uint8_t* ptrNames[MDNS_MAX_SERVICES_PER_PACKET];
uint16_t ptrOffsets[MDNS_MAX_SERVICES_PER_PACKET];
uint16_t ptrPorts[MDNS_MAX_SERVICES_PER_PACKET];
uint8_t ptrIPs[MDNS_MAX_SERVICES_PER_PACKET];
uint8_t servIPs[MDNS_MAX_SERVICES_PER_PACKET][5];
uint8_t* servTxt[MDNS_MAX_SERVICES_PER_PACKET];
memset(servIPs, 0, sizeof(uint8_t) * MDNS_MAX_SERVICES_PER_PACKET * 5);
memset(servTxt, 0, sizeof(uint8_t*) * MDNS_MAX_SERVICES_PER_PACKET);
const uint8_t* ptrNamesCmp[MDNS_MAX_SERVICES_PER_PACKET];
int ptrLensCmp[MDNS_MAX_SERVICES_PER_PACKET];
uint8_t ptrNamesMatches[MDNS_MAX_SERVICES_PER_PACKET];
uint8_t checkAARecords = 0;
memset(ptrNames, 0, sizeof(uint8_t*) * MDNS_MAX_SERVICES_PER_PACKET);
const uint8_t* servNames[2];
uint8_t servNamePos[2];
int servLens[2];
uint8_t servMatches[2];
uint8_t firstNamePtrByte = 0;
uint8_t partMatched[2];
uint8_t lastWasCompressed[2];
uint8_t servWasCompressed[2];
servNamePos[0] = servNamePos[1] = 0;
for (i = 0; i < qCnt + aCnt + aaCnt + addCnt; i++) {
for (j = 0; j < 2; j++) {
if (NULL != this->_resolveNames[j]) {
servNames[j] = this->_resolveNames[j];
servLens[j] = strlen( (const char*)this->_resolveNames[j] );
servMatches[j] = 1;
} else {
servNames[j] = NULL;
servLens[j] = servMatches[j] = 0;
}
}
for (j = 0; j < MDNS_MAX_SERVICES_PER_PACKET; j++) {
if (NULL != ptrNames[j]) {
ptrNamesCmp[j] = ptrNames[j];
ptrLensCmp[j] = strlen( (const char*)ptrNames[j] );
ptrNamesMatches[j] = 1;
}
}
partMatched[0] = partMatched[1] = 0;
lastWasCompressed[0] = lastWasCompressed[1] = 0;
servWasCompressed[0] = servWasCompressed[1] = 0;
firstNamePtrByte = 0;
tLen = 0;
do {
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),1 );
offset += 1;
rLen = buf[0];
tLen += 1;
if (rLen > 128) { // handle DNS name compression, kinda, sorta...
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),1 );
offset += 1;
for (j = 0; j < 2; j++) {
if (servNamePos[j] && servNamePos[j] != buf[0])
servMatches[j] = 0;
else
servWasCompressed[j] = 1;
lastWasCompressed[j] = 1;
}
tLen += 1;
if (0 == firstNamePtrByte)
firstNamePtrByte = buf[0];
} else if (rLen > 0) {
if (i < qCnt)
offset += rLen;
else {
int tr = rLen, ir;
if (0 == firstNamePtrByte)
firstNamePtrByte = offset - 1; // -1, since we already read length (1 byte)
while (tr > 0) {
ir = ( tr > sizeof(DNSHeader_t) ) ? sizeof(DNSHeader_t) : tr;
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),ir );
offset += ir;
tr -= ir;
for (j = 0; j < 2; j++) {
if (!recordsFound[j] && servMatches[j] && servNames[j])
servMatches[j] &= this->_matchStringPart(&servNames[j], &servLens[j],
buf, ir);
if (!partMatched[j])
partMatched[j] = servMatches[j];
lastWasCompressed[j] = 0;
}
for (j = 0; j < MDNS_MAX_SERVICES_PER_PACKET; j++) {
if (NULL != ptrNames[j] && ptrNamesMatches[j]) {
// only compare the part we have. this is incorrect, but good enough,
// since actual MDNS implementations won't go here anyways, as they
// should use name compression. This is just so that multiple Arduinos
// running this MDNSResponder code should be able to find each other's
// services.
if (ptrLensCmp[j] >= ir)
ptrNamesMatches[j] &= this->_matchStringPart(&ptrNamesCmp[j],
&ptrLensCmp[j], buf, ir);
}
}
}
tLen += rLen;
}
}
} while (rLen > 0 && rLen <= 128);
// if this matched a name of ours (and there are no characters left), then
// check wether this is an A record query (for our own name) or a PTR record query
// (for one of our services).
// if so, we'll note to send a record
if (i < qCnt)
offset += 4;
else if (i >= qCnt) {
if (i >= qCnt + aCnt && !checkAARecords)
break;
uint8_t packetHandled = 0;
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),4 );
offset += 4;
if (i < qCnt + aCnt) {
for (j = 0; j < 2; j++) {
if (0 == servNamePos[j])
servNamePos[j] = offset - 4 - tLen;
if ( servNames[j] &&
( (servMatches[j] && 0 == servLens[j]) ||
(partMatched[j] && lastWasCompressed[j]) ||
(servWasCompressed[j] && servMatches[j]) ) ) { // somewhat handle compression by guessing
if (buf[0] == 0 && buf[1] == ( (0 == j) ? 0x01 : 0x0c ) &&
(buf[2] == 0x00 || buf[2] == 0x80) && buf[3] == 0x01) {
recordsFound[j] = 1;
// this is an A or PTR type response. Parse it as such.
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),6 );
offset += 6;
//uint32_t ttl = ethutil_ntohl(*(uint32_t*)buf);
uint16_t dataLen = ethutil_ntohs(*(uint16_t*)&buf[4]);
if (0 == j && 4 == dataLen) {
// ok, this is the IP address. report it via callback.
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),4 );
this->_finishedResolvingName( (char*)this->_resolveNames[0],
(const byte*)buf );
} else if (1 == j) {
uint8_t k;
for (k = 0; k < MDNS_MAX_SERVICES_PER_PACKET; k++)
if (NULL == ptrNames[k])
break;
if (k < MDNS_MAX_SERVICES_PER_PACKET) {
int l = dataLen - 2; // -2: data compression of service postfix
uint8_t* ptrName = (uint8_t*)my_malloc(l);
if (ptrName) {
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),1 );
memcpy( (uint8_t*)ptrName, (uint16_t*)(ptr + offset + 1),l - 1 );
if (buf[0] < l - 1)
ptrName[buf[0]];// this catches uncompressed names
else
ptrName[l - 1] = '\0';
ptrNames[k] = ptrName;
ptrOffsets[k] = (uint16_t)(offset);
checkAARecords = 1;
}
}
}
offset += dataLen;
packetHandled = 1;
}
}
}
} else if (i >= qCnt + aCnt + aaCnt) {
// check whether we find a service description
if (buf[1] == 0x21) {
for (j = 0; j < MDNS_MAX_SERVICES_PER_PACKET; j++) {
if ( ptrNames[j] &&
( (firstNamePtrByte && firstNamePtrByte == ptrOffsets[j]) ||
(0 == ptrLensCmp[j] && ptrNamesMatches[j]) ) ) {
// we have found the matching SRV location packet to a previous SRV domain
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),6 );
offset += 6;
//uint32_t ttl = ethutil_ntohl(*(uint32_t*)buf);
uint16_t dataLen = ethutil_ntohs(*(uint16_t*)&buf[4]);
if (dataLen >= 8) {
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),8 );
ptrPorts[j] = ethutil_ntohs(*(uint16_t*)&buf[4]);
if (buf[6] > 128) { // target is a compressed name
ptrIPs[j] = buf[7];
} else {// target is uncompressed
ptrIPs[j] = offset + 6;
}
}
offset += dataLen;
packetHandled = 1;
break;
}
}
} else if (buf[1] == 0x10) { // txt record
for (j = 0; j < MDNS_MAX_SERVICES_PER_PACKET; j++) {
if ( ptrNames[j] &&
( (firstNamePtrByte && firstNamePtrByte == ptrOffsets[j]) ||
(0 == ptrLensCmp[j] && ptrNamesMatches[j]) ) ) {
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),6 );
offset += 6;
//uint32_t ttl = ethutil_ntohl(*(uint32_t*)buf);
uint16_t dataLen = ethutil_ntohs(*(uint16_t*)&buf[4]);
// if there's a content to this txt record, save it for delivery
if (dataLen > 1 && NULL == servTxt[j]) {
servTxt[j] = (uint8_t*)my_malloc(dataLen + 1);
if (NULL != servTxt[j]) {
memcpy( (uint8_t*)servTxt[j], (uint16_t*)(ptr + offset),dataLen );
// zero-terminate
servTxt[j][dataLen] = '\0';
}
}
offset += dataLen;
packetHandled = 1;
break;
}
}
} else if (buf[1] == 0x01) { // A record (IPv4 address)
for (j = 0; j < MDNS_MAX_SERVICES_PER_PACKET; j++) {
if (0 == servIPs[j][0]) {
servIPs[j][0] = firstNamePtrByte ? firstNamePtrByte : 255;
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset),6 );
offset += 6;
uint16_t dataLen = ethutil_ntohs(*(uint16_t*)&buf[4]);
if (4 == dataLen) {
memcpy( (uint8_t*)&servIPs[j][1], (uint16_t*)(ptr + offset),4 );
}
offset += dataLen;
packetHandled = 1;
break;
}
}
}
}
// eat the answer
if (!packetHandled) {
offset += 4; // ttl
memcpy( (uint8_t*)buf, (uint16_t*)(ptr + offset), 2 );
offset += 2 + ethutil_ntohs(*(uint16_t*)buf); // skip over content
}
}
}
// deliver the services discovered in this packet
if (NULL != this->_resolveNames[1]) {
char* typeName = (char*)this->_resolveNames[1];
char* p = (char*)this->_resolveNames[1];
while(*p && *p != '.')
p++;
*p = '\0';
for (i = 0; i < MDNS_MAX_SERVICES_PER_PACKET; i++)
if (ptrNames[i]) {
const uint8_t* ipAddr = NULL;
const uint8_t* fallbackIpAddr = NULL;
for (j = 0; j < MDNS_MAX_SERVICES_PER_PACKET; j++) {
if (servIPs[j][0] == ptrIPs[i] || servIPs[j][0] == 255) {
// the || part is such a hack, but it will work as long as there's only
// one A record per MDNS packet. fucking DNS name compression.
ipAddr = &servIPs[j][1];
break;
} else if (NULL == fallbackIpAddr && 0 != servIPs[j][0])
fallbackIpAddr = &servIPs[j][1];
}
// if we can't find a matching IP, we try to use the first one we found.
if (NULL == ipAddr) ipAddr = fallbackIpAddr;
if (ipAddr && this->_serviceFoundCallback) {
this->_serviceFoundCallback(typeName,
this->_resolveServiceProto,
(const char*)ptrNames[i],
(const byte*)ipAddr,
(unsigned short)ptrPorts[i],