Add UPnP support to tincd.
[tinc] / src / upnp.c
1 /*
2     upnp.c -- UPnP-IGD client
3     Copyright (C) 2015 Guus Sliepen <guus@tinc-vpn.org>,
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "upnp.h"
21
22 #include <pthread.h>
23
24 #include "miniupnpc/miniupnpc.h"
25 #include "miniupnpc/upnpcommands.h"
26 #include "miniupnpc/upnperrors.h"
27
28 #include "system.h"
29 #include "logger.h"
30 #include "names.h"
31 #include "net.h"
32 #include "netutl.h"
33 #include "utils.h"
34
35 static bool upnp_tcp;
36 static bool upnp_udp;
37 static int upnp_discover_wait = 5;
38 static int upnp_refresh_period = 60;
39
40 static void upnp_add_mapping(struct UPNPUrls *urls, struct IGDdatas *data, const char *myaddr, int socket, const char *proto) {
41         // Extract the port from the listening socket.
42         // Note that we can't simply use listen_socket[].sa because this won't have the port
43         // if we're running with Port=0 (dynamically assigned port).
44         sockaddr_t sa;
45         socklen_t salen = sizeof sa;
46         if (getsockname(socket, &sa.sa, &salen)) {
47                 logger(DEBUG_PROTOCOL, LOG_ERR, "[upnp] Unable to get socket address: [%d] %s", sockerrno, sockstrerror(sockerrno));
48                 return;
49         }
50         char *port;
51         sockaddr2str(&sa, NULL, &port);
52         if (!port) {
53                 logger(DEBUG_PROTOCOL, LOG_ERR, "[upnp] Unable to get socket port");
54                 return;
55         }
56
57         // Use a lease twice as long as the refresh period so that the mapping won't expire before we refresh.
58         char lease_duration[16];
59         snprintf(lease_duration, sizeof lease_duration, "%d", upnp_refresh_period * 2);
60
61         int error = UPNP_AddPortMapping(urls->controlURL, data->first.servicetype, port, port, myaddr, identname, proto, NULL, lease_duration);
62         if (error == 0) {
63                 logger(DEBUG_PROTOCOL, LOG_INFO, "[upnp] Successfully set port mapping (%s:%s %s for %s seconds)", myaddr, port, proto, lease_duration);
64         } else {
65                 logger(DEBUG_PROTOCOL, LOG_ERR, "[upnp] Failed to set port mapping (%s:%s %s for %s seconds): [%d] %s", myaddr, port, proto, lease_duration, error, strupnperror(error));
66         }
67
68         free(port);
69 }
70
71 static void upnp_refresh() {
72         logger(DEBUG_PROTOCOL, LOG_INFO, "[upnp] Discovering IGD devices");
73
74         int error;
75         struct UPNPDev *devices = upnpDiscover(upnp_discover_wait * 1000, NULL, NULL, false, false, &error);
76         if (!devices) {
77                 logger(DEBUG_PROTOCOL, LOG_WARNING, "[upnp] Unable to find IGD devices: [%d] %s", error, strupnperror(error));
78                 freeUPNPDevlist(devices);
79                 return;
80         }
81
82         struct UPNPUrls urls;
83         struct IGDdatas data;
84         char myaddr[64];
85         int result = UPNP_GetValidIGD(devices, &urls, &data, myaddr, sizeof myaddr);
86         if (result <= 0) {
87                 logger(DEBUG_PROTOCOL, LOG_WARNING, "[upnp] No IGD found");
88                 freeUPNPDevlist(devices);
89                 return;
90         }
91         logger(DEBUG_PROTOCOL, LOG_INFO, "[upnp] IGD found: [%d] %s (local address: %s, service type: %s)", result, urls.controlURL, myaddr, data.first.servicetype);
92
93         for (int i = 0; i < listen_sockets; i++) {
94                 if (upnp_tcp) upnp_add_mapping(&urls, &data, myaddr, listen_socket[i].tcp.fd, "TCP");
95                 if (upnp_udp) upnp_add_mapping(&urls, &data, myaddr, listen_socket[i].udp.fd, "UDP");
96         }
97
98         FreeUPNPUrls(&urls);
99         freeUPNPDevlist(devices);
100 }
101
102 static void *upnp_thread(void *data) {
103         while (true) {
104                 time_t start = time(NULL);
105                 upnp_refresh();
106
107                 // Make sure we'll stick to the refresh period no matter how long upnp_refresh() takes.
108                 time_t refresh_time = start + upnp_refresh_period;
109                 time_t now = time(NULL);
110                 if (now < refresh_time) sleep(refresh_time - now);
111         }
112
113         // TODO: we don't have a clean thread shutdown procedure, so we can't remove the mapping.
114         //       this is probably not a concern as long as the UPnP device honors the lease duration,
115         //       but considering how bug-riddled these devices often are, that's a big "if".
116         return NULL;
117 }
118
119 void upnp_init(bool tcp, bool udp) {
120         upnp_tcp = tcp;
121         upnp_udp = udp;
122
123         get_config_int(lookup_config(config_tree, "UPnPDiscoverWait"), &upnp_discover_wait);
124         get_config_int(lookup_config(config_tree, "UPnPRefreshPeriod"), &upnp_refresh_period);
125
126         pthread_t thread;
127         int error = pthread_create(&thread, NULL, upnp_thread, NULL);
128         if (error) {
129                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to start UPnP-IGD client thread: [%d] %s", error, strerror(error));
130         }
131 }