-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUPnP.cpp
1315 lines (1148 loc) · 40.9 KB
/
UPnP.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
/**
* @file UPnP.cpp
* @author Phil Hilger ([email protected])
* @brief
* @version 0.1
* @date 2023-03-02
*
* CAN-talk. A library for microcontrollers that allows decent comms
* over a CAN bus.
*
* Copyright (C) 2023, PeerGum
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https: //www.gnu.org/licenses/>.
*
*/
#include "Wifi.h"
#include "SoftTimer.h"
#include <string>
#include "esp_log.h"
#include <cstring>
#include "esp_log.h"
#include "UPnP.h"
static const char *TAG = "UPnP";
IPAddress ipMulti(239, 255, 255, 250); // multicast address for SSDP
IPAddress connectivityTestIp(64, 233, 187, 99); // Google
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet
// UDP_TX_PACKET_MAX_SIZE=8192
char responseBuffer[UDP_TX_RESPONSE_MAX_SIZE];
char tmpBody[1200];
char integerString[32];
SOAPAction SOAPActionGetSpecificPortMappingEntry = {
.name = "GetSpecificPortMappingEntry"};
SOAPAction SOAPActionDeletePortMapping = {.name = "DeletePortMapping"};
static const char *const deviceListUpnp[] = {
"urn:schemas-upnp-org:device:InternetGatewayDevice:1",
"urn:schemas-upnp-org:device:InternetGatewayDevice:2",
"urn:schemas-upnp-org:service:WANIPConnection:1",
"urn:schemas-upnp-org:service:WANIPConnection:2",
"urn:schemas-upnp-org:service:WANPPPConnection:1",
// "upnp:rootdevice",
0};
static const char *const deviceListSsdpAll[] = {"ssdp:all", 0};
const char *UPNP_SERVICE_TYPE_TAG_NAME = "serviceType";
const char *UPNP_SERVICE_TYPE_TAG_START = "<serviceType>";
const char *UPNP_SERVICE_TYPE_TAG_END = "</serviceType>";
void trim(char *text) {
size_t len = strlen(text);
for (int i = 1; i < len; i++) {
if (text[len - i] == ' ') {
text[len - i] = 0;
}
}
len = strlen(text);
int i;
for (i = 0; i < len; i++) {
if (text[i] != ' ') {
break;
}
}
if (i>0) {
memcpy((void *)text, (void *)(text + i), len - i + 1);
}
}
void replace(std::string str, const char *str1, const char *str2) {
std::string newstr;
int pos = str.find(str1);
int len = strlen(str1);
newstr = str.substr(0, pos) + str2 + str.substr(pos + len);
str = newstr;
}
// timeoutMs - timeout in milli seconds for the operations of this class, 0 for
// blocking operation
UPnP::UPnP(unsigned long timeoutMs) {
_timeoutMs = timeoutMs;
_lastUpdateTime = 0;
_consecutiveFails = 0;
_headRuleNode = NULL;
clearGatewayInfo(&_gwInfo);
}
UPnP::~UPnP() {}
void UPnP::addPortMappingConfig(IPAddress ruleIP, int rulePort,
const char *ruleProtocol, int ruleLeaseDuration,
const char *ruleFriendlyName) {
static int index = 0;
upnpRule *newUpnpRule = new upnpRule();
newUpnpRule->index = index++;
newUpnpRule->internalAddr = (ruleIP == wifi.localIP())
? ipNull
: ruleIP; // for automatic IP change handling
newUpnpRule->internalPort = rulePort;
newUpnpRule->externalPort = rulePort;
newUpnpRule->leaseDuration = ruleLeaseDuration;
newUpnpRule->protocol = strdup(ruleProtocol);
newUpnpRule->devFriendlyName = strdup(ruleFriendlyName);
// linked list insert
upnpRuleNode *newUpnpRuleNode = new upnpRuleNode();
newUpnpRuleNode->upnpRule = newUpnpRule;
newUpnpRuleNode->next = NULL;
if (_headRuleNode == NULL) {
_headRuleNode = newUpnpRuleNode;
} else {
upnpRuleNode *currNode = _headRuleNode;
while (currNode->next != NULL) {
currNode = currNode->next;
}
currNode->next = newUpnpRuleNode;
}
}
portMappingResult UPnP::commitPortMappings() {
if (!_headRuleNode) {
ESP_LOGD(TAG, "ERROR: No UPnP port mapping was set.");
return EMPTY_PORT_MAPPING_CONFIG;
}
// verify wifi is connected
if (!testConnectivity()) {
ESP_LOGD(TAG, "ERROR: not connected to wifi, cannot continue");
return NETWORK_ERROR;
}
SoftTimer t;
// get all the needed IGD information using SSDP if we don't have it already
if (!isGatewayInfoValid(&_gwInfo)) {
getGatewayInfo(&_gwInfo);
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGD(TAG, "ERROR: Invalid router info, cannot continue");
_tcpClient.close();
return NETWORK_ERROR;
}
delay(1000); // longer delay to allow more time for the router to update
// its rules
}
ESP_LOGD(TAG, "port [%d] actionPort [%d]", _gwInfo.port, _gwInfo.actionPort);
// double verify gateway information is valid
if (!isGatewayInfoValid(&_gwInfo)) {
ESP_LOGD(TAG, "ERROR: Invalid router info, cannot continue");
return NETWORK_ERROR;
}
if (_gwInfo.port != _gwInfo.actionPort) {
// in this case we need to connect to a different port
ESP_LOGD(TAG, "Connection port changed, disconnecting from IGD");
_tcpClient.close();
}
bool allPortMappingsAlreadyExist = true; // for debug
int addedPortMappings = 0; // for debug
upnpRuleNode *currNode = _headRuleNode;
t.reset();
while (currNode != NULL) {
ESP_LOGI(TAG, "Verify port mapping for rule [%s]",
currNode->upnpRule->devFriendlyName);
bool currPortMappingAlreadyExists = true; // for debug
// TODO: since verifyPortMapping connects to the IGD then
// addPortMappingEntry can skip it
if (!verifyPortMapping(&_gwInfo, currNode->upnpRule)) {
// need to add the port mapping
currPortMappingAlreadyExists = false;
allPortMappingsAlreadyExist = false;
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGD(TAG, "Timeout expired while trying to add a port mapping");
_tcpClient.close();
return TIMEOUT;
}
addPortMappingEntry(&_gwInfo, currNode->upnpRule);
int tries = 0;
while (tries <= 3) {
delay(2000); // longer delay to allow more time for the router to
// update its rules
if (verifyPortMapping(&_gwInfo, currNode->upnpRule)) {
break;
}
tries++;
}
if (tries > 3) {
_tcpClient.close();
return VERIFICATION_FAILED;
}
}
if (!currPortMappingAlreadyExists) {
addedPortMappings++;
ESP_LOGI(TAG, "Port mapping [%s] was added",
currNode->upnpRule->devFriendlyName);
}
currNode = currNode->next;
vTaskDelay(pdMS_TO_TICKS(100));
}
_tcpClient.close();
if (allPortMappingsAlreadyExist) {
ESP_LOGI(
TAG,
"All port mappings were already found in the IGD, not doing anything");
return ALREADY_MAPPED;
} else {
// addedPortMappings is at least 1 here
if (addedPortMappings > 1) {
ESP_LOGI(TAG, "%d UPnP port mappings were added", addedPortMappings);
} else {
ESP_LOGI(TAG, "One UPnP port mapping was added");
}
}
return SUCCESS;
}
bool UPnP::getGatewayInfo(gatewayInfo *deviceInfo) {
SoftTimer t;
while (!connectUDP()) {
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGD(TAG, "Timeout expired while connecting UDP");
_udpClient.stop();
return false;
}
delay(500);
}
broadcastMSearch();
IPAddress gatewayIP = wifi.gatewayIP();
ESP_LOGD(TAG, "Gateway IP [%s]", gatewayIP.toChar());
t.reset();
ssdpDevice *ssdpDevice_ptr = NULL;
while ((ssdpDevice_ptr = waitForUnicastResponseToMSearch(gatewayIP)) ==
NULL) {
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGD(
TAG,
"Timeout expired while waiting for the gateway router to respond to "
"M-SEARCH message");
_udpClient.stop();
return false;
}
delay(1);
}
deviceInfo->host = ssdpDevice_ptr->host;
deviceInfo->port = ssdpDevice_ptr->port;
deviceInfo->path = ssdpDevice_ptr->path;
// the following is the default and may be overridden if URLBase tag is
// specified
deviceInfo->actionPort = ssdpDevice_ptr->port;
// close the UDP connection
_udpClient.stop();
t.reset();
// connect to IGD (TCP connection)
while (!connectToIGD(deviceInfo->host, deviceInfo->port)) {
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGD(TAG, "Timeout expired while trying to connect to the IGD");
_tcpClient.close();
return false;
}
delay(500);
}
t.reset();
// get event urls from the gateway IGD
while (!getIGDEventURLs(deviceInfo)) {
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGD(TAG, "Timeout expired while adding a new port mapping");
_tcpClient.close();
return false;
}
delay(500);
}
return true;
}
void UPnP::clearGatewayInfo(gatewayInfo *deviceInfo) {
deviceInfo->host = IPAddress(0, 0, 0, 0);
deviceInfo->port = 0;
deviceInfo->path = strdup("");
deviceInfo->actionPort = 0;
deviceInfo->actionPath = strdup("");
deviceInfo->serviceTypeName = strdup("");
}
bool UPnP::isGatewayInfoValid(gatewayInfo *deviceInfo) {
ESP_LOGD(TAG,
"isGatewayInfoValid [%s] port [%d] path [%s] actionPort [%d] "
"actionPath [%s] serviceTypeName [%s]",
deviceInfo->host.toChar(), deviceInfo->port, deviceInfo->path,
deviceInfo->actionPort, deviceInfo->actionPath,
deviceInfo->serviceTypeName);
if (deviceInfo->host == ipNull || deviceInfo->port == 0 ||
strlen(deviceInfo->path) == 0 || deviceInfo->actionPort == 0) {
ESP_LOGD(TAG, "Gateway info is not valid");
return false;
}
ESP_LOGD(TAG, "Gateway info is valid");
return true;
}
portMappingResult UPnP::updatePortMappings(unsigned long intervalMs,
callback_function fallback) {
if (millis() - _lastUpdateTime >= intervalMs) {
ESP_LOGD(TAG, "Updating port mapping");
// fallback
if (_consecutiveFails >= MAX_NUM_OF_UPDATES_WITH_NO_EFFECT) {
ESP_LOGD(
TAG,
"ERROR: Too many times with no effect on updatePortMappings. Current "
"number of fallbacks times [%lu]",
_consecutiveFails);
_consecutiveFails = 0;
clearGatewayInfo(&_gwInfo);
if (fallback != NULL) {
ESP_LOGD(TAG, "Executing fallback method");
fallback();
}
return TIMEOUT;
}
// } else if (_consecutiveFails > 300) {
// ESP.restart(); // should test as last resort
// return;
// }
portMappingResult result = commitPortMappings();
if (result == SUCCESS || result == ALREADY_MAPPED) {
_lastUpdateTime = millis();
_tcpClient.close();
_consecutiveFails = 0;
return result;
} else {
_lastUpdateTime += intervalMs / 2; // delay next try
ESP_LOGD(TAG,
"ERROR: While updating UPnP port mapping. Failed with error "
"code [%d]",
result);
_tcpClient.close();
_consecutiveFails++;
return result;
}
}
_tcpClient.close();
return NOP; // no need to check yet
}
bool UPnP::testConnectivity() {
SoftTimer t;
ESP_LOGI(TAG, "Testing wifi connection for [%s]", wifi.localIP().toChar());
while (wifi.status() != CONNECTED) {
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGW(TAG, " ==> Timeout expired while verifying wifi connection");
_tcpClient.close();
return false;
}
delay(200);
// ESP_LOGD(TAG,".";
}
ESP_LOGD(TAG, "Wifi Connected"); // \n
ESP_LOGD(TAG, "Testing internet connection");
_tcpClient.connect(connectivityTestIp, 80);
t.reset();
while (!_tcpClient.connected()) {
if (t.check(TCP_CONNECTION_TIMEOUT_MS)) {
ESP_LOGW(TAG, "-> Fail");
_tcpClient.close();
return false;
}
}
ESP_LOGI(TAG, "-> Success");
_tcpClient.close();
return true;
}
bool UPnP::verifyPortMapping(gatewayInfo *deviceInfo, upnpRule *rule_ptr) {
if (!applyActionOnSpecificPortMapping(&SOAPActionGetSpecificPortMappingEntry,
deviceInfo, rule_ptr)) {
return false;
}
ESP_LOGD(TAG, "verifyPortMapping called");
// TODO: extract the current lease duration and return it instead of a bool
bool success = false;
bool newIP = false;
while (_tcpClient.available()) {
std::string line = _tcpClient.readUntil('\r');
// ESP_LOGD(TAG, "%s", line.c_str());
if (line.find("errorCode") != -1) {
success = false;
// flush response and exit loop
while (_tcpClient.available()) {
line = _tcpClient.readUntil('\r');
// ESP_LOGD(TAG, "%s", line.c_str());
}
continue;
}
if (line.find("NewInternalClient") != -1) {
const char *content = getTagContent(line.c_str(), "NewInternalClient");
if (content) {
IPAddress ipAddressToVerify = (rule_ptr->internalAddr == ipNull)
? wifi.localIP()
: rule_ptr->internalAddr;
if (!strcmp(content, ipAddressToVerify.toChar())) {
success = true;
} else {
newIP = true;
}
}
}
}
_tcpClient.close();
if (success) {
ESP_LOGI(TAG, "Port mapping found in IGD");
} else if (newIP) {
ESP_LOGI(TAG, "Detected a change in IP");
removeAllPortMappingsFromIGD();
} else {
ESP_LOGI(TAG, "Could not find port mapping in IGD");
}
return success;
}
bool UPnP::deletePortMapping(gatewayInfo *deviceInfo, upnpRule *rule_ptr) {
if (!applyActionOnSpecificPortMapping(&SOAPActionDeletePortMapping,
deviceInfo, rule_ptr)) {
return false;
}
bool isSuccess = false;
while (_tcpClient.available()) {
std::string line = _tcpClient.readUntil('\r');
// ESP_LOGD(TAG, "%s", line.c_str());
if (line.find("errorCode") != -1) {
isSuccess = false;
// flush response and exit loop
while (_tcpClient.available()) {
line = _tcpClient.readUntil('\r');
// ESP_LOGD(TAG, "%s", line.c_str());
}
continue;
}
if (line.find("DeletePortMappingResponse") != -1) {
isSuccess = true;
}
}
return isSuccess;
}
bool UPnP::applyActionOnSpecificPortMapping(SOAPAction *soapAction,
gatewayInfo *deviceInfo,
upnpRule *rule_ptr) {
ESP_LOGD(TAG, "Apply action [%s] on port mapping [%s]", soapAction->name,
rule_ptr->devFriendlyName);
// connect to IGD (TCP connection) again, if needed, in case we got
// disconnected after the previous query
SoftTimer t;
if (!_tcpClient.connected()) {
while (!connectToIGD(deviceInfo->host, deviceInfo->actionPort)) {
if (t.check(TCP_CONNECTION_TIMEOUT_MS)) {
ESP_LOGD(TAG, "Timeout expired while trying to connect to the IGD");
_tcpClient.close();
return false;
}
delay(500);
}
}
strcpy(tmpBody,
"<?xml version=\"1.0\"?>\r\n<s:Envelope "
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/"
"\">\r\n<s:Body>\r\n<u:");
strcat(tmpBody, soapAction->name);
strcat(tmpBody, " xmlns:u=\"");
strcat(tmpBody, deviceInfo->serviceTypeName);
strcat(tmpBody,
"\">\r\n<NewRemoteHost></NewRemoteHost>\r\n<NewExternalPort>");
sprintf(integerString, "%d", rule_ptr->internalPort);
strcat(tmpBody, integerString);
strcat(tmpBody, "</NewExternalPort>\r\n<NewProtocol>");
strcat(tmpBody, rule_ptr->protocol);
strcat(tmpBody, "</NewProtocol>\r\n</u:");
strcat(tmpBody, soapAction->name);
strcat(tmpBody, ">\r\n</s:Body>\r\n</s:Envelope>\r\n");
// printf(tmpBody);
sprintf(buffer,
"POST %s HTTP/1.1\r\n"
"Connection: close\r\n"
"Content-Type: text/xml; charset=\"utf-8\"\r\n"
"Host: %s:%d\r\n"
"SOAPAction: \"%s#%s\"\r\n"
"Content-Length: %d\r\n\r\n",
deviceInfo->actionPath, deviceInfo->host.toChar(),
deviceInfo->actionPort, deviceInfo->serviceTypeName, soapAction->name,
strlen(tmpBody));
_tcpClient.write(buffer, strlen(buffer));
_tcpClient.write(tmpBody,strlen(tmpBody));
t.reset();
while (!_tcpClient.available()) {
if (t.check(TCP_CONNECTION_TIMEOUT_MS)) {
ESP_LOGD(TAG, "TCP connection timeout while retrieving port mappings");
_tcpClient.close();
// TODO: in this case we might not want to add the ports right away
// might want to try again or only start adding the ports after we
// definitely did not see them in the router list
return false;
}
}
return true;
}
void UPnP::removeAllPortMappingsFromIGD() {
upnpRuleNode *currNode = _headRuleNode;
while (currNode != NULL) {
deletePortMapping(&_gwInfo, currNode->upnpRule);
currNode = currNode->next;
}
}
// a single try to connect UDP multicast address and port of UPnP
// (239.255.255.250 and 1900 respectively) this will enable receiving SSDP
// packets after the M-SEARCH multicast message will be broadcasted
bool UPnP::connectUDP() {
if (_udpClient.beginMulticast(ipMulti, UPNP_SSDP_PORT)) {
return true;
}
ESP_LOGD(TAG, "UDP connection failed");
return false;
}
// broadcast an M-SEARCH message to initiate messages from SSDP devices
// the router should respond to this message by a packet sent to this device's
// unicast addresss on the same UPnP port (1900)
void UPnP::broadcastMSearch(bool isSsdpAll /*=false*/) {
ESP_LOGD(TAG, "Sending M-SEARCH to [%s] port [%d]", ipMulti.toChar(),
UPNP_SSDP_PORT);
uint8_t beginMulticastPacketRes = _udpClient.beginMulticastPacket();
ESP_LOGD(TAG, "beginMulticastPacketRes [%d]", beginMulticastPacketRes);
const char *const *deviceList = deviceListUpnp;
if (isSsdpAll) {
deviceList = deviceListSsdpAll;
}
for (int i = 0; deviceList[i]; i++) {
sprintf(tmpBody,
"M-SEARCH * HTTP/1.1\r\n"
"HOST: 239.255.255.250:%d\r\n"
"MAN: \"ssdp:discover\"\r\n"
"MX: 2\r\n" // allowed number of seconds to wait before
"ST: %s\r\n"
"USER-AGENT: unix/5.1 UPnP/2.0 UPnP/1.0\r\n"
"\r\n\r\n",
UPNP_SSDP_PORT, deviceList[i]);
// ESP_LOGD(TAG, "%s", tmpBody);
size_t len = strlen(tmpBody);
ESP_LOGD(TAG, "M-SEARCH packet length is [%d]", len);
_udpClient.printf(tmpBody);
int endPacketRes = _udpClient.endPacket();
ESP_LOGD(TAG, "endPacketRes [%d]", endPacketRes);
}
ESP_LOGD(TAG, "M-SEARCH packets sent");
}
ssdpDeviceNode *UPnP::listSsdpDevices() {
if (_timeoutMs <= 0) {
ESP_LOGD(TAG,
"Timeout must be set when initializing UPnP to use this method, "
"exiting.");
return NULL;
}
SoftTimer t;
while (!connectUDP()) {
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGD(TAG, "Timeout expired while connecting UDP");
_udpClient.stop();
return NULL;
}
delay(500);
}
broadcastMSearch(true);
IPAddress gatewayIP = wifi.gatewayIP();
ESP_LOGI(TAG, "Gateway IP [%s]", gatewayIP.toChar());
ssdpDeviceNode *ssdpDeviceNode_head = NULL;
ssdpDeviceNode *ssdpDeviceNode_tail = NULL;
ssdpDeviceNode *ssdpDeviceNode_ptr = NULL;
ssdpDevice *ssdpDevice_ptr;
t.reset();
while (true) {
ssdpDevice_ptr = waitForUnicastResponseToMSearch(
ipNull); // NULL will cause finding all SSDP device (not just the IGD)
if (_timeoutMs > 0 && t.check(_timeoutMs)) {
ESP_LOGD(
TAG,
"Timeout expired while waiting for the gateway router to respond to "
"M-SEARCH message");
_udpClient.stop();
break;
}
ssdpDevicePrint(ssdpDevice_ptr);
if (ssdpDevice_ptr != NULL) {
if (ssdpDeviceNode_head == NULL) {
ssdpDeviceNode_head = new ssdpDeviceNode();
ssdpDeviceNode_head->ssdpDevice = ssdpDevice_ptr;
ssdpDeviceNode_head->next = NULL;
ssdpDeviceNode_tail = ssdpDeviceNode_head;
} else {
ssdpDeviceNode_ptr = new ssdpDeviceNode();
ssdpDeviceNode_ptr->ssdpDevice = ssdpDevice_ptr;
ssdpDeviceNode_tail->next = ssdpDeviceNode_ptr;
ssdpDeviceNode_tail = ssdpDeviceNode_ptr;
}
}
delay(5);
}
// close the UDP connection
_udpClient.stop();
// dedup SSDP devices fromt the list - O(n^2)
ssdpDeviceNode_ptr = ssdpDeviceNode_head;
while (ssdpDeviceNode_ptr != NULL) {
ssdpDeviceNode *ssdpDeviceNodePrev_ptr = ssdpDeviceNode_ptr;
ssdpDeviceNode *ssdpDeviceNodeCurr_ptr = ssdpDeviceNode_ptr->next;
while (ssdpDeviceNodeCurr_ptr != NULL) {
if (ssdpDeviceNodeCurr_ptr->ssdpDevice->host ==
ssdpDeviceNode_ptr->ssdpDevice->host &&
ssdpDeviceNodeCurr_ptr->ssdpDevice->port ==
ssdpDeviceNode_ptr->ssdpDevice->port &&
ssdpDeviceNodeCurr_ptr->ssdpDevice->path ==
ssdpDeviceNode_ptr->ssdpDevice->path) {
// delete ssdpDeviceNode from the list
ssdpDeviceNodePrev_ptr->next = ssdpDeviceNodeCurr_ptr->next;
free(ssdpDeviceNodeCurr_ptr->ssdpDevice);
free(ssdpDeviceNodeCurr_ptr);
ssdpDeviceNodeCurr_ptr = ssdpDeviceNodePrev_ptr->next;
} else {
ssdpDeviceNodePrev_ptr = ssdpDeviceNodeCurr_ptr;
ssdpDeviceNodeCurr_ptr = ssdpDeviceNodeCurr_ptr->next;
}
}
ssdpDeviceNode_ptr = ssdpDeviceNode_ptr->next;
}
return ssdpDeviceNode_head;
}
// Assuming an M-SEARCH message was broadcaseted, wait for the response from the
// IGD (Internet Gateway Device) Note: the response from the IGD is sent back as
// unicast to this device Note: only gateway defined IGD response will be
// considered, the rest will be ignored
ssdpDevice *UPnP::waitForUnicastResponseToMSearch(IPAddress gatewayIP) {
int packetSize = _udpClient.parsePacket();
// only continue if a packet is available
if (packetSize <= 0) {
return NULL;
}
IPAddress remoteIP = _udpClient.remoteIP();
// only continue if the packet was received from the gateway router
// for SSDP discovery we continue anyway
if (gatewayIP != ipNull && remoteIP != gatewayIP) {
ESP_LOGD(TAG,
"Discarded packet not originating from IGD - gatewayIP [%s] "
"remoteIP [%s]",
gatewayIP.toChar(), ipMulti.toChar());
return NULL;
}
ESP_LOGD(TAG, "Received packet of size [%d] ip [%s] port [%d]", packetSize,
remoteIP.toChar(), _udpClient.remotePort());
// sanity check
if (packetSize > UDP_TX_RESPONSE_MAX_SIZE) {
ESP_LOGD(
TAG,
"Received packet with size larged than the response buffer, cannot "
"proceed.");
return NULL;
}
int idx = 0;
while (idx < packetSize) {
memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE);
int len = _udpClient.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
if (len <= 0) {
break;
}
ESP_LOGD(TAG, "UDP packet read bytes [%d] out of [%d]", len, packetSize);
memcpy(responseBuffer + idx, packetBuffer, len);
idx += len;
}
responseBuffer[idx] = '\0';
// ESP_LOGD(TAG, "Gateway packet content: %s", responseBuffer);
const char *const *deviceList = deviceListUpnp;
if (gatewayIP == ipNull) {
deviceList = deviceListSsdpAll;
}
// only continue if the packet is a response to M-SEARCH and it originated
// from a gateway device for SSDP discovery we continue anyway
if (gatewayIP != ipNull) { // for the use of listSsdpDevices
bool foundIGD = false;
for (int i = 0; deviceList[i]; i++) {
if (strstr(responseBuffer, deviceList[i]) != NULL) {
foundIGD = true;
ESP_LOGI(TAG, "IGD of type [%s] found", deviceList[i]);
break;
}
}
if (!foundIGD) {
ESP_LOGW(TAG, "IGD was not found");
return NULL;
}
}
char *location;
char *location_indexStart = strstr(responseBuffer, "location:");
if (location_indexStart == NULL) {
location_indexStart = strstr(responseBuffer, "Location:");
}
if (location_indexStart == NULL) {
location_indexStart = strstr(responseBuffer, "LOCATION:");
}
if (location_indexStart != NULL) {
location_indexStart += 10; // "location:".length()
char *location_indexEnd = strstr(location_indexStart, "\r\n");
if (location_indexEnd != NULL) {
int urlLength = location_indexEnd - location_indexStart;
int arrLength = urlLength + 1; // + 1 for '\0'
// converting the start index to be inside the packetBuffer rather than
// responseBuffer
location = (char *)malloc(arrLength);
memcpy(location, location_indexStart, urlLength);
location[arrLength - 1] = '\0';
} else {
ESP_LOGD(TAG, "ERROR: could not extract value from LOCATION param");
return NULL;
}
} else {
ESP_LOGD(TAG, "ERROR: LOCATION param was not found");
return NULL;
}
ESP_LOGD(TAG, "Device location found [%s]", location);
IPAddress host;
char port[6];
char path[1024];
char hostname[256];
char protocol[30];
parseUrl(location, protocol, hostname, port, path);
free(location);
ssdpDevice *newSsdpDevice_ptr = new ssdpDevice();
if (!newSsdpDevice_ptr) {
return NULL;
}
newSsdpDevice_ptr->host.fromChar(hostname);
newSsdpDevice_ptr->port = atoi(port);
newSsdpDevice_ptr->path = strdup(path);
// ESP_LOGD(TAG,host.toChar());
// ESP_LOGD(TAG,char *(port));
// ESP_LOGD(TAG,path);
return newSsdpDevice_ptr;
}
// a single trial to connect to the IGD (with TCP)
bool UPnP::connectToIGD(IPAddress host, int port) {
ESP_LOGD(TAG, "Connecting to IGD with host [%s] port [%d]", host.toChar(),
port);
if (_tcpClient.connect(host, port)) {
ESP_LOGD(TAG, "Connected to IGD");
return true;
}
return false;
}
// updates deviceInfo with the commands' information of the IGD
bool UPnP::getIGDEventURLs(gatewayInfo *deviceInfo) {
ESP_LOGD(TAG, "called getIGDEventURLs");
ESP_LOGD(TAG, "deviceInfo->actionPath [%s] deviceInfo->path [%s]",
deviceInfo->actionPath, deviceInfo->path);
// make an HTTP request
sprintf(buffer,
"GET %s HTTP/1.1\r\n"
"Content-Type: text/xml; charset=\"utf-8\"\r\n"
"Host: %s:%d\r\n"
"Content-Length: 0\r\n\r\n",
deviceInfo->path, deviceInfo->host.toChar(), deviceInfo->actionPort);
_tcpClient.write(buffer, strlen(buffer));
SoftTimer t;
// wait for the response
while (_tcpClient.available() == 0) {
if (t.check(TCP_CONNECTION_TIMEOUT_MS)) {
ESP_LOGD(TAG, "TCP connection timeout while executing getIGDEventURLs");
_tcpClient.close();
return false;
}
}
// read all the lines of the reply from server
bool upnpServiceFound = false;
bool urlBaseFound = false;
std::string line;
while (_tcpClient.available()) {
line = _tcpClient.readUntil('\r');
int index_in_line = 0;
if (!urlBaseFound && line.find("<URLBase>") != -1) {
// e.g. <URLBase>http://192.168.1.1:5432/</URLBase>
// Note: assuming URL path will only be found in a specific action under
// the 'controlURL' xml tag
char *baseUrl = strdup(getTagContent(line.c_str(), "URLBase"));
if (strlen(baseUrl) > 0) {
trim(baseUrl);
IPAddress host = getHost(baseUrl); // this is ignored, assuming router
// host IP will not change
int port = getPort(baseUrl);
deviceInfo->actionPort = port;
ESP_LOGD(TAG,"URLBase tag found [%s]", baseUrl);
ESP_LOGD(TAG, "Translated to base host [%s] and base port [%d]",
host.toChar(), port);
urlBaseFound = true;
}
}
// to support multiple <serviceType> tags
int service_type_index_start = 0;
for (int i = 0; deviceListUpnp[i]; i++) {
char serviceTag[100];
sprintf(serviceTag, "%s%s", UPNP_SERVICE_TYPE_TAG_START,
deviceListUpnp[i]);
int service_type_index =
line.find(serviceTag);
if (service_type_index >= 0) {
ESP_LOGD(TAG, "[%s] service_type_index [%d]",
deviceInfo->serviceTypeName, service_type_index);
service_type_index_start = service_type_index;
service_type_index =
line.find(UPNP_SERVICE_TYPE_TAG_END, service_type_index_start);
}
if (!upnpServiceFound && service_type_index >= 0) {
index_in_line += service_type_index;
upnpServiceFound = true;
deviceInfo->serviceTypeName = strdup(getTagContent(
line.substr(service_type_index_start).c_str(), UPNP_SERVICE_TYPE_TAG_NAME));
ESP_LOGD(TAG, "[%s] service found! deviceType [%s]",
deviceInfo->serviceTypeName, deviceListUpnp[i]);
break; // will start looking for 'controlURL' now
}
}
if (upnpServiceFound &&
(index_in_line = line.find("<controlURL>", index_in_line)) >= 0) {
const char *controlURLContent =
getTagContent(line.substr(index_in_line).c_str(), "controlURL");
if (strlen(controlURLContent) > 0) {
deviceInfo->actionPath = strdup(controlURLContent);
ESP_LOGD(TAG, "controlURL tag found! setting actionPath to [%s]",
controlURLContent);
// clear buffer
ESP_LOGD(TAG, "Flushing the rest of the response");
while (_tcpClient.available()) {
_tcpClient.read();
}
// now we have (upnpServiceFound && controlURLFound)
return true;
}
}
}
return false;
}
// assuming a connection to the IGD has been formed
// will add the port mapping to the IGD
bool UPnP::addPortMappingEntry(gatewayInfo *deviceInfo, upnpRule *rule_ptr) {
ESP_LOGD(TAG, "called addPortMappingEntry");
// connect to IGD (TCP connection) again, if needed, in case we got
// disconnected after the previous query
SoftTimer t;
if (!_tcpClient.connected()) {
while (!connectToIGD(_gwInfo.host, _gwInfo.actionPort)) {
if (t.check(TCP_CONNECTION_TIMEOUT_MS)) {
ESP_LOGD(TAG, "Timeout expired while trying to connect to the IGD");
_tcpClient.close();
return false;
}
delay(500);
}
}
ESP_LOGD(TAG, "deviceInfo->actionPath [%s]", deviceInfo->actionPath);
ESP_LOGD(TAG, "deviceInfo->serviceTypeName [%s]",
deviceInfo->serviceTypeName);
sprintf(integerString, "%d", rule_ptr->internalPort);
IPAddress ipAddress = (rule_ptr->internalAddr == ipNull)
? wifi.localIP()
: rule_ptr->internalAddr;
strcat(tmpBody, ipAddress.toChar());
strcpy(tmpBody,
"<?xml version=\"1.0\"?><s:Envelope "
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/"
"\"><s:Body><u:AddPortMapping xmlns:u=\"");
strcat(tmpBody, deviceInfo->serviceTypeName);
strcat(tmpBody, "\"><NewRemoteHost></NewRemoteHost><NewExternalPort>");
strcat(tmpBody, integerString);
strcat(tmpBody, "</NewExternalPort><NewProtocol>");
strcat(tmpBody, rule_ptr->protocol);
strcat(tmpBody, "</NewProtocol><NewInternalPort>");
strcat(tmpBody, integerString);
strcat(tmpBody, "</NewInternalPort><NewInternalClient>");
strcat(tmpBody, ipAddress.toChar());
strcat(tmpBody,