-
-
Notifications
You must be signed in to change notification settings - Fork 978
/
upnp.cpp
1681 lines (1468 loc) · 43.2 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
/*
Copyright (c) 2019, Amir Abrams
Copyright (c) 2007-2022, Arvid Norberg
Copyright (c) 2009, Andrew Resch
Copyright (c) 2015, Mike Tzou
Copyright (c) 2016-2019, Alden Torres
Copyright (c) 2016-2017, Andrei Kurushin
Copyright (c) 2016-2017, Pavel Pimenov
Copyright (c) 2016, Steven Siloti
Copyright (c) 2020, Paul-Louis Ageneau
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/config.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/socket_io.hpp"
#include "libtorrent/upnp.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/parse_url.hpp"
#include "libtorrent/xml_parse.hpp"
#include "libtorrent/random.hpp"
#include "libtorrent/aux_/time.hpp" // for aux::time_now()
#include "libtorrent/aux_/escape_string.hpp" // for convert_from_native
#include "libtorrent/http_connection.hpp"
#include "libtorrent/ssl.hpp"
#include "libtorrent/aux_/scope_end.hpp"
#if defined TORRENT_ASIO_DEBUGGING
#include "libtorrent/debug.hpp"
#endif
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/multicast.hpp>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
#include <cstdlib>
#include <cstdio> // for snprintf
#include <cstdarg>
#include <functional>
using namespace std::placeholders;
namespace libtorrent {
using namespace aux;
// due to the recursive nature of update_map, it's necessary to
// limit the internal list of global mappings to a small size
// this can be changed once the entire UPnP code is refactored
constexpr std::size_t max_global_mappings = 50;
namespace upnp_errors
{
boost::system::error_code make_error_code(error_code_enum e)
{ return {e, upnp_category()}; }
} // upnp_errors namespace
static error_code ignore_error;
upnp::rootdevice::rootdevice() = default;
#if TORRENT_USE_ASSERTS
upnp::rootdevice::~rootdevice()
{
TORRENT_ASSERT(magic == 1337);
magic = 0;
}
#else
upnp::rootdevice::~rootdevice() = default;
#endif
upnp::rootdevice::rootdevice(rootdevice const&) = default;
upnp::rootdevice& upnp::rootdevice::operator=(rootdevice const&) & = default;
upnp::rootdevice::rootdevice(rootdevice&&) noexcept = default;
upnp::rootdevice& upnp::rootdevice::operator=(rootdevice&&) & = default;
// TODO: 2 use boost::asio::ip::network instead of netmask
upnp::upnp(io_context& ios
, aux::session_settings const& settings
, aux::portmap_callback& cb
, address_v4 const listen_address
, address_v4 const netmask
, std::string listen_device
, listen_socket_handle ls)
: m_settings(settings)
, m_callback(cb)
, m_io_service(ios)
, m_resolver(ios)
, m_multicast(ios)
, m_unicast(ios)
, m_broadcast_timer(ios)
, m_refresh_timer(ios)
, m_map_timer(ios)
, m_listen_address(listen_address)
, m_netmask(netmask)
, m_device(std::move(listen_device))
#if TORRENT_USE_SSL
, m_ssl_ctx(ssl::context::sslv23_client)
#endif
, m_listen_handle(std::move(ls))
{
#if TORRENT_USE_SSL
m_ssl_ctx.set_verify_mode(ssl::context::verify_none);
#endif
}
void upnp::start()
{
TORRENT_ASSERT(is_single_thread());
error_code ec;
open_multicast_socket(m_multicast, ec);
#ifndef TORRENT_DISABLE_LOGGING
if (ec && should_log())
{
log("failed to open multicast socket: \"%s\""
, convert_from_native(ec.message()).c_str());
m_disabled = true;
return;
}
#endif
open_unicast_socket(m_unicast, ec);
#ifndef TORRENT_DISABLE_LOGGING
if (ec && should_log())
{
log("failed to open unicast socket: \"%s\""
, convert_from_native(ec.message()).c_str());
m_disabled = true;
return;
}
#endif
m_mappings.reserve(2);
discover_device_impl();
}
namespace {
address_v4 const ssdp_multicast_addr = make_address_v4("239.255.255.250");
int const ssdp_port = 1900;
}
void upnp::open_multicast_socket(aux::socket_package& s, error_code& ec)
{
using namespace boost::asio::ip::multicast;
s.socket.open(udp::v4(), ec);
if (ec) return;
s.socket.set_option(udp::socket::reuse_address(true), ec);
if (ec) return;
s.socket.bind(udp::endpoint(m_listen_address, ssdp_port), ec);
if (ec) return;
s.socket.set_option(join_group(ssdp_multicast_addr), ec);
if (ec) return;
s.socket.set_option(hops(255), ec);
if (ec) return;
s.socket.set_option(enable_loopback(true), ec);
if (ec) return;
s.socket.set_option(outbound_interface(m_listen_address), ec);
if (ec) return;
ADD_OUTSTANDING_ASYNC("upnp::on_reply");
s.socket.async_receive_from(boost::asio::buffer(s.buffer), s.remote
, std::bind(&upnp::on_reply, self(), std::ref(s), _1, _2));
}
void upnp::open_unicast_socket(aux::socket_package& s, error_code& ec)
{
s.socket.open(udp::v4(), ec);
if (ec) return;
s.socket.bind(udp::endpoint(m_listen_address, 0), ec);
if (ec) return;
ADD_OUTSTANDING_ASYNC("upnp::on_reply");
s.socket.async_receive_from(boost::asio::buffer(s.buffer), s.remote
, std::bind(&upnp::on_reply, self(), std::ref(s), _1, _2));
}
upnp::~upnp() = default;
#ifndef TORRENT_DISABLE_LOGGING
bool upnp::should_log() const
{
return m_callback.should_log_portmap(portmap_transport::upnp);
}
TORRENT_FORMAT(2,3)
void upnp::log(char const* fmt, ...) const
{
TORRENT_ASSERT(is_single_thread());
if (!should_log()) return;
va_list v;
va_start(v, fmt);
char msg[1024];
std::vsnprintf(msg, sizeof(msg), fmt, v);
va_end(v);
m_callback.log_portmap(portmap_transport::upnp, msg, m_listen_handle);
}
#endif
void upnp::discover_device_impl()
{
TORRENT_ASSERT(is_single_thread());
static const char msearch[] =
"M-SEARCH * HTTP/1.1\r\n"
"HOST: 239.255.255.250:1900\r\n"
"ST:upnp:rootdevice\r\n"
"MAN:\"ssdp:discover\"\r\n"
"MX:3\r\n"
"\r\n\r\n";
#ifdef TORRENT_DEBUG_UPNP
// simulate packet loss
if (m_retry_count & 1)
#endif
error_code mcast_ec;
error_code ucast_ec;
m_multicast.socket.send_to(boost::asio::buffer(msearch, sizeof(msearch) - 1)
, udp::endpoint(ssdp_multicast_addr, ssdp_port), 0, mcast_ec);
m_unicast.socket.send_to(boost::asio::buffer(msearch, sizeof(msearch) - 1)
, udp::endpoint(ssdp_multicast_addr, ssdp_port), 0, ucast_ec);
if (mcast_ec && ucast_ec)
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("multicast send failed: \"%s\" and \"%s\". Aborting."
, convert_from_native(mcast_ec.message()).c_str()
, convert_from_native(ucast_ec.message()).c_str());
}
#endif
disable(mcast_ec);
return;
}
ADD_OUTSTANDING_ASYNC("upnp::resend_request");
++m_retry_count;
m_broadcast_timer.expires_after(seconds(2 * m_retry_count));
m_broadcast_timer.async_wait(std::bind(&upnp::resend_request
, self(), _1));
#ifndef TORRENT_DISABLE_LOGGING
log("broadcasting search for rootdevice");
#endif
}
// returns a reference to a mapping or -1 on failure
port_mapping_t upnp::add_mapping(portmap_protocol const p, int const external_port
, tcp::endpoint const local_ep, std::string const& device)
{
TORRENT_ASSERT(is_single_thread());
// external port 0 means _every_ port
TORRENT_ASSERT(external_port != 0);
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("adding port map: [ protocol: %s ext_port: %d "
"local_ep: %s device: %s] %s", (p == portmap_protocol::tcp?"tcp":"udp")
, external_port
, print_endpoint(local_ep).c_str(), device.c_str()
, m_disabled ? "DISABLED": "");
}
#endif
if (m_disabled) return port_mapping_t{-1};
auto mapping_it = std::find_if(m_mappings.begin(), m_mappings.end()
, [](global_mapping_t const& m) { return m.protocol == portmap_protocol::none; });
if (mapping_it == m_mappings.end())
{
TORRENT_ASSERT(m_mappings.size() <= max_global_mappings);
if (m_mappings.size() >= max_global_mappings)
{
#ifndef TORRENT_DISABLE_LOGGING
log("too many mappings registered");
#endif
return port_mapping_t{-1};
}
m_mappings.push_back(global_mapping_t());
mapping_it = m_mappings.end() - 1;
}
mapping_it->protocol = p;
mapping_it->external_port = external_port;
mapping_it->local_ep = local_ep;
mapping_it->device = device;
port_mapping_t const mapping_index{static_cast<int>(mapping_it - m_mappings.begin())};
for (auto const& dev : m_devices)
{
auto& d = const_cast<rootdevice&>(dev);
TORRENT_ASSERT(d.magic == 1337);
if (d.disabled) continue;
if (d.mapping.end_index() <= mapping_index)
d.mapping.resize(static_cast<int>(mapping_index) + 1);
mapping_t& m = d.mapping[mapping_index];
m.act = portmap_action::add;
m.protocol = p;
m.external_port = external_port;
m.local_ep = local_ep;
m.device = device;
if (!d.service_namespace.empty()) update_map(d, mapping_index);
}
return port_mapping_t{mapping_index};
}
void upnp::delete_mapping(port_mapping_t const mapping)
{
TORRENT_ASSERT(is_single_thread());
if (mapping >= m_mappings.end_index()) return;
global_mapping_t const& m = m_mappings[mapping];
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("deleting port map: [ protocol: %s ext_port: %u "
"local_ep: %s device: %s]"
, (m.protocol == portmap_protocol::tcp?"tcp":"udp"), m.external_port
, print_endpoint(m.local_ep).c_str()
, m.device.c_str());
}
#endif
if (m.protocol == portmap_protocol::none) return;
for (auto const& dev : m_devices)
{
auto& d = const_cast<rootdevice&>(dev);
TORRENT_ASSERT(d.magic == 1337);
if (d.disabled) continue;
TORRENT_ASSERT(mapping < d.mapping.end_index());
d.mapping[mapping].act = portmap_action::del;
if (!d.service_namespace.empty()) update_map(d, mapping);
}
}
bool upnp::get_mapping(port_mapping_t const index
, tcp::endpoint& local_ep
, int& external_port
, portmap_protocol& protocol) const
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(index < m_mappings.end_index() && index >= port_mapping_t{0});
if (index >= m_mappings.end_index() || index < port_mapping_t{0}) return false;
global_mapping_t const& m = m_mappings[index];
if (m.protocol == portmap_protocol::none) return false;
local_ep = m.local_ep;
external_port = m.external_port;
protocol = m.protocol;
return true;
}
void upnp::resend_request(error_code const& ec)
{
TORRENT_ASSERT(is_single_thread());
COMPLETE_ASYNC("upnp::resend_request");
if (ec) return;
std::shared_ptr<upnp> me(self());
if (m_closing) return;
if (m_retry_count < 12
&& (m_devices.empty() || m_retry_count < 4))
{
discover_device_impl();
return;
}
if (m_devices.empty())
{
disable(errors::no_router);
return;
}
for (auto const& dev : m_devices)
{
if (!dev.control_url.empty()
|| dev.upnp_connection
|| dev.disabled)
{
continue;
}
// we don't have a WANIP or WANPPP url for this device,
// ask for it
connect(const_cast<rootdevice&>(dev));
}
}
void upnp::connect(rootdevice& d)
{
TORRENT_ASSERT(d.magic == 1337);
try
{
#ifndef TORRENT_DISABLE_LOGGING
log("connecting to: %s", d.url.c_str());
#endif
if (d.upnp_connection) d.upnp_connection->close();
d.upnp_connection = std::make_shared<http_connection>(m_io_service
, m_resolver
, std::bind(&upnp::on_upnp_xml, self(), _1, _2
, std::ref(d), _4), true, default_max_bottled_buffer_size
, http_connect_handler()
, http_filter_handler()
, hostname_filter_handler()
#if TORRENT_USE_SSL
, &m_ssl_ctx
#endif
);
d.upnp_connection->get(d.url, seconds(30));
}
catch (std::exception const& exc)
{
TORRENT_UNUSED(exc);
#ifndef TORRENT_DISABLE_LOGGING
log("connection failed to: %s %s", d.url.c_str(), exc.what());
#endif
d.disabled = true;
}
}
void upnp::on_reply(aux::socket_package& s, error_code const& ec, std::size_t const len)
{
TORRENT_ASSERT(is_single_thread());
COMPLETE_ASYNC("upnp::on_reply");
if (ec == boost::asio::error::operation_aborted) return;
if (m_closing) return;
std::shared_ptr<upnp> me(self());
udp::endpoint const from = s.remote;
// parse out the url for the device
/*
the response looks like this:
HTTP/1.1 200 OK
ST:upnp:rootdevice
USN:uuid:000f-66d6-7296000099dc::upnp:rootdevice
Location: http://192.168.1.1:5431/dyndev/uuid:000f-66d6-7296000099dc
Server: Custom/1.0 UPnP/1.0 Proc/Ver
EXT:
Cache-Control:max-age=180
DATE: Fri, 02 Jan 1970 08:10:38 GMT
a notification looks like this:
NOTIFY * HTTP/1.1
Host:239.255.255.250:1900
NT:urn:schemas-upnp-org:device:MediaServer:1
NTS:ssdp:alive
Location:http://10.0.3.169:2869/upnphost/udhisapi.dll?content=uuid:c17f0c32-d19b-4938-ae94-65f945c3a26e
USN:uuid:c17f0c32-d19b-4938-ae94-65f945c3a26e::urn:schemas-upnp-org:device:MediaServer:1
Cache-Control:max-age=900
Server:Microsoft-Windows-NT/5.1 UPnP/1.0 UPnP-Device-Host/1.0
*/
// reissue the async receive as we exit the function. We can't do this
// earlier because we still need to use s.buffer
auto reissue_receive = scope_end([&] {
ADD_OUTSTANDING_ASYNC("upnp::on_reply");
s.socket.async_receive_from(boost::asio::buffer(s.buffer), s.remote
, std::bind(&upnp::on_reply, self(), std::ref(s), _1, _2));
});
if (ec) return;
if (m_settings.get_bool(settings_pack::upnp_ignore_nonrouters)
&& !match_addr_mask(m_listen_address, from.address(), m_netmask))
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("ignoring response from: %s. IP is not on local network. (addr: %s mask: %s)"
, print_endpoint(from).c_str()
, m_listen_address.to_string().c_str()
, m_netmask.to_string().c_str());
}
#endif
return;
}
http_parser p;
bool error = false;
p.incoming({s.buffer.data(), std::ptrdiff_t(len)}, error);
if (error)
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("received malformed HTTP from: %s"
, print_endpoint(from).c_str());
}
#endif
return;
}
if (p.status_code() != 200 && p.method() != "notify")
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
if (p.method().empty())
{
log("HTTP status %u from %s"
, p.status_code(), print_endpoint(from).c_str());
}
else
{
log("HTTP method %s from %s"
, p.method().c_str(), print_endpoint(from).c_str());
}
}
#endif
return;
}
if (!p.header_finished())
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("incomplete HTTP packet from %s"
, print_endpoint(from).c_str());
}
#endif
return;
}
std::string url = p.header("location");
if (url.empty())
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("missing location header from %s"
, print_endpoint(from).c_str());
}
#endif
return;
}
rootdevice d;
d.url = url;
auto i = m_devices.find(d);
if (i == m_devices.end())
{
std::string protocol;
std::string auth;
error_code err;
// we don't have this device in our list. Add it
std::tie(protocol, auth, d.hostname, d.port, d.path)
= parse_url_components(d.url, err);
if (d.port == -1) d.port = protocol == "http" ? 80 : 443;
if (err)
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("invalid URL %s from %s: %s"
, d.url.c_str(), print_endpoint(from).c_str(), convert_from_native(err.message()).c_str());
}
#endif
return;
}
// ignore the auth here. It will be re-parsed
// by the http connection later
if (protocol != "http")
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("unsupported protocol %s from %s"
, protocol.c_str(), print_endpoint(from).c_str());
}
#endif
return;
}
if (d.port == 0)
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("URL with port 0 from %s", print_endpoint(from).c_str());
}
#endif
return;
}
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("found rootdevice: %s (%d)"
, d.url.c_str(), int(m_devices.size()));
}
#endif
if (m_devices.size() >= 50)
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("too many rootdevices: (%d). Ignoring %s"
, int(m_devices.size()), d.url.c_str());
}
#endif
return;
}
TORRENT_ASSERT(d.mapping.empty());
for (auto const& j : m_mappings)
{
mapping_t m;
m.act = portmap_action::add;
m.local_ep = j.local_ep;
m.device = j.device;
m.external_port = j.external_port;
m.protocol = j.protocol;
d.mapping.push_back(m);
}
std::tie(i, std::ignore) = m_devices.insert(d);
}
// iterate over the devices we know and connect and issue the mappings
try_map_upnp();
// check back in a little bit to see if we have seen any
// devices at one of our default routes. If not, we want to override
// ignoring them and use them instead (better than not working).
m_map_timer.expires_after(seconds(1));
ADD_OUTSTANDING_ASYNC("upnp::map_timer");
m_map_timer.async_wait(std::bind(&upnp::map_timer, self(), _1));
}
void upnp::map_timer(error_code const& ec)
{
TORRENT_ASSERT(is_single_thread());
COMPLETE_ASYNC("upnp::map_timer");
if (ec) return;
if (m_closing) return;
try_map_upnp();
}
void upnp::try_map_upnp()
{
TORRENT_ASSERT(is_single_thread());
if (m_devices.empty()) return;
for (auto i = m_devices.begin(), end(m_devices.end()); i != end; ++i)
{
if (i->control_url.empty() && !i->upnp_connection && !i->disabled)
{
// we don't have a WANIP or WANPPP url for this device,
// ask for it
connect(const_cast<rootdevice&>(*i));
}
}
}
void upnp::post(upnp::rootdevice const& d, char const* soap
, char const* soap_action)
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(d.magic == 1337);
TORRENT_ASSERT(d.upnp_connection);
TORRENT_ASSERT(!d.disabled);
char header[2048];
std::snprintf(header, sizeof(header), "POST %s HTTP/1.1\r\n"
"Host: %s:%d\r\n"
"Content-Type: text/xml; charset=\"utf-8\"\r\n"
"Content-Length: %d\r\n"
"Soapaction: \"%s#%s\"\r\n\r\n"
"%s"
, d.path.c_str(), d.hostname.c_str(), d.port
, int(strlen(soap)), d.service_namespace.c_str(), soap_action
, soap);
d.upnp_connection->m_sendbuffer = header;
#ifndef TORRENT_DISABLE_LOGGING
log("sending: %s", header);
#endif
}
int upnp::lease_duration(rootdevice const& d) const
{
return d.use_lease_duration
? m_settings.get_int(settings_pack::upnp_lease_duration)
: 0;
}
void upnp::create_port_mapping(http_connection& c, rootdevice& d
, port_mapping_t const i)
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(d.magic == 1337);
if (!d.upnp_connection)
{
TORRENT_ASSERT(d.disabled);
#ifndef TORRENT_DISABLE_LOGGING
log("mapping %u aborted", static_cast<int>(i));
#endif
return;
}
char const* soap_action = "AddPortMapping";
error_code ec;
std::string local_endpoint = print_address(c.socket().local_endpoint(ec).address());
char soap[1024];
std::snprintf(soap, sizeof(soap), "<?xml version=\"1.0\"?>\n"
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body><u:%s xmlns:u=\"%s\">"
"<NewRemoteHost></NewRemoteHost>"
"<NewExternalPort>%u</NewExternalPort>"
"<NewProtocol>%s</NewProtocol>"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%d</NewLeaseDuration>"
"</u:%s></s:Body></s:Envelope>"
, soap_action, d.service_namespace.c_str(), d.mapping[i].external_port
, to_string(d.mapping[i].protocol)
, d.mapping[i].local_ep.port()
, local_endpoint.c_str()
, m_settings.get_bool(settings_pack::anonymous_mode)
? "" : m_settings.get_str(settings_pack::user_agent).c_str()
, lease_duration(d), soap_action);
post(d, soap, soap_action);
}
void upnp::next(rootdevice& d, port_mapping_t const i)
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(!d.disabled);
if (i < prev(m_mappings.end_index()))
{
update_map(d, lt::next(i));
}
else
{
auto const j = std::find_if(d.mapping.begin(), d.mapping.end()
, [](mapping_t const& m) { return m.act != portmap_action::none; });
if (j == d.mapping.end()) return;
update_map(d, port_mapping_t{static_cast<int>(j - d.mapping.begin())});
}
}
void upnp::update_map(rootdevice& d, port_mapping_t const i)
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(d.magic == 1337);
TORRENT_ASSERT(i < d.mapping.end_index());
TORRENT_ASSERT(d.mapping.size() == m_mappings.size());
TORRENT_ASSERT(!d.disabled);
if (d.upnp_connection) return;
// this should not happen, but in case it does, don't fail at runtime
if (i >= d.mapping.end_index()) return;
std::shared_ptr<upnp> me(self());
mapping_t& m = d.mapping[i];
if (m.act == portmap_action::none
|| m.protocol == portmap_protocol::none)
{
#ifndef TORRENT_DISABLE_LOGGING
log("mapping %u does not need updating, skipping", static_cast<int>(i));
#endif
m.act = portmap_action::none;
next(d, i);
return;
}
TORRENT_ASSERT(!d.upnp_connection);
TORRENT_ASSERT(!d.service_namespace.empty());
#ifndef TORRENT_DISABLE_LOGGING
log("connecting to %s", d.hostname.c_str());
#endif
if (m.act == portmap_action::add)
{
if (m.failcount > 5)
{
m.act = portmap_action::none;
// giving up
next(d, i);
return;
}
if (d.upnp_connection) d.upnp_connection->close();
d.upnp_connection = std::make_shared<http_connection>(m_io_service
, m_resolver
, std::bind(&upnp::on_upnp_map_response, self(), _1, _2
, std::ref(d), i, _4), true, default_max_bottled_buffer_size
, std::bind(&upnp::create_port_mapping, self(), _1, std::ref(d), i)
, http_filter_handler()
, hostname_filter_handler()
#if TORRENT_USE_SSL
, &m_ssl_ctx
#endif
);
bind_info_t bi{m.device, m.local_ep.address()};
d.upnp_connection->start(d.hostname, d.port
, seconds(10), nullptr, false, 5, bi);
}
else if (m.act == portmap_action::del)
{
if (d.upnp_connection) d.upnp_connection->close();
d.upnp_connection = std::make_shared<http_connection>(m_io_service
, m_resolver
, std::bind(&upnp::on_upnp_unmap_response, self(), _1, _2
, std::ref(d), i, _4), true, default_max_bottled_buffer_size
, std::bind(&upnp::delete_port_mapping, self(), std::ref(d), i)
, http_filter_handler()
, hostname_filter_handler()
#if TORRENT_USE_SSL
, &m_ssl_ctx
#endif
);
bind_info_t bi{m.device, m.local_ep.address()};
d.upnp_connection->start(d.hostname, d.port
, seconds(10), nullptr, false, 5, bi);
}
m.act = portmap_action::none;
m.expires = aux::time_now() + seconds(30);
}
void upnp::delete_port_mapping(rootdevice& d, port_mapping_t const i)
{
TORRENT_ASSERT(is_single_thread());
TORRENT_ASSERT(d.magic == 1337);
if (!d.upnp_connection)
{
TORRENT_ASSERT(d.disabled);
#ifndef TORRENT_DISABLE_LOGGING
log("unmapping %u aborted", static_cast<int>(i));
#endif
return;
}
char const* soap_action = "DeletePortMapping";
char soap[1024];
std::snprintf(soap, sizeof(soap), "<?xml version=\"1.0\"?>\n"
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body><u:%s xmlns:u=\"%s\">"
"<NewRemoteHost></NewRemoteHost>"
"<NewExternalPort>%u</NewExternalPort>"
"<NewProtocol>%s</NewProtocol>"
"</u:%s></s:Body></s:Envelope>"
, soap_action, d.service_namespace.c_str()
, d.mapping[i].external_port
, to_string(d.mapping[i].protocol)
, soap_action);
post(d, soap, soap_action);
}
void find_control_url(int const type, string_view str, parse_state& state)
{
if (type == xml_start_tag)
{
state.tag_stack.push_back(str);
}
else if (type == xml_end_tag)
{
if (!state.tag_stack.empty())
{
if (state.in_service && string_equal_no_case(state.tag_stack.back(), "service"))
state.in_service = false;
state.tag_stack.pop_back();
}
}
else if (type == xml_string)
{
if (state.tag_stack.empty()) return;
// default to the first (or only) control url in the router's listing
if (!state.in_service
&& state.top_tags("service", "servicetype")
&& state.service_type.empty())
{
if (string_equal_no_case(str, "urn:schemas-upnp-org:service:WANIPConnection:1")
|| string_equal_no_case(str, "urn:schemas-upnp-org:service:WANIPConnection:2")
|| string_equal_no_case(str, "urn:schemas-upnp-org:service:WANPPPConnection:1"))
{
state.service_type.assign(str.begin(), str.end());
state.in_service = true;
}
}
else if (state.control_url.empty() && state.in_service
&& state.top_tags("service", "controlurl") && str.size() > 0)
{
// default to the first (or only) control url in the router's listing
state.control_url.assign(str.begin(), str.end());
}
else if (state.model.empty() && state.top_tags("device", "modelname"))
{
state.model.assign(str.begin(), str.end());
}
else if (string_equal_no_case(state.tag_stack.back(), "urlbase"))
{
state.url_base.assign(str.begin(), str.end());
}
}
}
void upnp::on_upnp_xml(error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, http_connection& c)
{
TORRENT_ASSERT(is_single_thread());
std::shared_ptr<upnp> me(self());
TORRENT_ASSERT(d.magic == 1337);
if (d.upnp_connection && d.upnp_connection.get() == &c)
{
d.upnp_connection->close();
d.upnp_connection.reset();
}
if (m_closing) return;
if (e && e != boost::asio::error::eof)
{
#ifndef TORRENT_DISABLE_LOGGING
if (should_log())
{
log("error while fetching control url from: %s: %s"
, d.url.c_str(), convert_from_native(e.message()).c_str());
}
#endif
d.disabled = true;