Imported Upstream version 2.66.6
[platform/upstream/glib.git] / gio / gwin32networkmonitor.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright 2014-2018 Jan-Michael Brummer <jan.brummer@tabos.org>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library 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 GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include <errno.h>
24
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28
29 #include <winsock2.h>
30 #include <ws2tcpip.h>
31 #include <iphlpapi.h>
32 #include <stdio.h>
33
34 #include "gwin32networkmonitor.h"
35 #include "ginetaddress.h"
36 #include "ginetaddressmask.h"
37 #include "ginitable.h"
38 #include "giomodule-priv.h"
39 #include "glibintl.h"
40 #include "glib/gstdio.h"
41 #include "gnetworkingprivate.h"
42 #include "gsocket.h"
43 #include "gnetworkmonitor.h"
44 #include "gioerror.h"
45
46 static GInitableIface *initable_parent_iface;
47 static void g_win32_network_monitor_iface_init (GNetworkMonitorInterface *iface);
48 static void g_win32_network_monitor_initable_iface_init (GInitableIface *iface);
49
50 struct _GWin32NetworkMonitorPrivate
51 {
52   gboolean initialized;
53   GError *init_error;
54   GMainContext *main_context;
55   GSource *route_change_source;
56   HANDLE handle;
57 };
58
59 #define g_win32_network_monitor_get_type _g_win32_network_monitor_get_type
60 G_DEFINE_TYPE_WITH_CODE (GWin32NetworkMonitor, g_win32_network_monitor, G_TYPE_NETWORK_MONITOR_BASE,
61                          G_ADD_PRIVATE (GWin32NetworkMonitor)
62                          G_IMPLEMENT_INTERFACE (G_TYPE_NETWORK_MONITOR,
63                                                 g_win32_network_monitor_iface_init)
64                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
65                                                 g_win32_network_monitor_initable_iface_init)
66                          _g_io_modules_ensure_extension_points_registered ();
67                          g_io_extension_point_implement (G_NETWORK_MONITOR_EXTENSION_POINT_NAME,
68                                                          g_define_type_id,
69                                                          "win32",
70                                                          20))
71
72 static void
73 g_win32_network_monitor_init (GWin32NetworkMonitor *win)
74 {
75   win->priv = g_win32_network_monitor_get_instance_private (win);
76 }
77
78 static gboolean
79 win_network_monitor_get_ip_info (IP_ADDRESS_PREFIX  prefix,
80                                  GSocketFamily     *family,
81                                  const guint8     **dest,
82                                  gsize             *len)
83 {
84   switch (prefix.Prefix.si_family)
85     {
86       case AF_UNSPEC:
87         /* Fall-through: AF_UNSPEC deliveres both IPV4 and IPV6 infos, let`s stick with IPV4 here */
88       case AF_INET:
89         *family = G_SOCKET_FAMILY_IPV4;
90         *dest = (guint8 *) &prefix.Prefix.Ipv4.sin_addr;
91         *len = prefix.PrefixLength;
92         break;
93       case AF_INET6:
94         *family = G_SOCKET_FAMILY_IPV6;
95         *dest = (guint8 *) &prefix.Prefix.Ipv6.sin6_addr;
96         *len = prefix.PrefixLength;
97         break;
98       default:
99         return FALSE;
100     }
101
102   return TRUE;
103 }
104
105 static GInetAddressMask *
106 get_network_mask (GSocketFamily  family,
107                   const guint8  *dest,
108                   gsize          len)
109 {
110   GInetAddressMask *network;
111   GInetAddress *dest_addr;
112
113   if (dest != NULL)
114     dest_addr = g_inet_address_new_from_bytes (dest, family);
115   else
116     dest_addr = g_inet_address_new_any (family);
117
118   network = g_inet_address_mask_new (dest_addr, len, NULL);
119   g_object_unref (dest_addr);
120
121   return network;
122 }
123
124 static gboolean
125 win_network_monitor_process_table (GWin32NetworkMonitor  *win,
126                                    GError                 **error)
127 {
128   DWORD ret = 0;
129   GPtrArray *networks;
130   gsize i;
131   MIB_IPFORWARD_TABLE2 *routes = NULL;
132   MIB_IPFORWARD_ROW2 *route;
133
134   ret = GetIpForwardTable2 (AF_UNSPEC, &routes);
135   if (ret != ERROR_SUCCESS)
136     {
137       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
138                    "GetIpForwardTable2 () failed: %ld", ret);
139
140       return FALSE;
141     }
142
143   networks = g_ptr_array_new_full (routes->NumEntries, g_object_unref);
144   for (i = 0; i < routes->NumEntries; i++)
145     {
146       GInetAddressMask *network;
147       const guint8 *dest;
148       gsize len;
149       GSocketFamily family;
150
151       route = routes->Table + i;
152
153       if (!win_network_monitor_get_ip_info (route->DestinationPrefix, &family, &dest, &len))
154         continue;
155
156       network = get_network_mask (family, dest, len);
157       if (network == NULL)
158         continue;
159
160       g_ptr_array_add (networks, network);
161     }
162
163   g_network_monitor_base_set_networks (G_NETWORK_MONITOR_BASE (win),
164                                        (GInetAddressMask **) networks->pdata,
165                                        networks->len);
166
167   return TRUE;
168 }
169
170 static void
171 add_network (GWin32NetworkMonitor *win,
172              GSocketFamily         family,
173              const guint8         *dest,
174              gsize                 dest_len)
175 {
176   GInetAddressMask *network;
177
178   network = get_network_mask (family, dest, dest_len);
179   if (network != NULL)
180     {
181       g_network_monitor_base_add_network (G_NETWORK_MONITOR_BASE (win), network);
182       g_object_unref (network);
183     }
184 }
185
186 static void
187 remove_network (GWin32NetworkMonitor *win,
188                 GSocketFamily         family,
189                 const guint8         *dest,
190                 gsize                 dest_len)
191 {
192   GInetAddressMask *network;
193
194   network = get_network_mask (family, dest, dest_len);
195   if (network != NULL)
196     {
197       g_network_monitor_base_remove_network (G_NETWORK_MONITOR_BASE (win), network);
198       g_object_unref (network);
199     }
200 }
201
202 typedef struct {
203   PMIB_IPFORWARD_ROW2 route;
204   MIB_NOTIFICATION_TYPE type;
205   GWin32NetworkMonitor *win;
206 } RouteData;
207
208 static gboolean
209 win_network_monitor_invoke_route_changed (gpointer user_data)
210 {
211   GSocketFamily family;
212   RouteData *route_data = user_data;
213   const guint8 *dest;
214   gsize len;
215
216   switch (route_data->type)
217     {
218       case MibDeleteInstance:
219         if (!win_network_monitor_get_ip_info (route_data->route->DestinationPrefix, &family, &dest, &len))
220           break;
221
222         remove_network (route_data->win, family, dest, len);
223         break;
224       case MibAddInstance:
225         if (!win_network_monitor_get_ip_info (route_data->route->DestinationPrefix, &family, &dest, &len))
226             break;
227
228         add_network (route_data->win, family, dest, len);
229         break;
230       case MibInitialNotification:
231       default:
232         break;
233     }
234
235   return G_SOURCE_REMOVE;
236 }
237
238 static VOID WINAPI
239 win_network_monitor_route_changed_cb (PVOID                 context,
240                                       PMIB_IPFORWARD_ROW2   route,
241                                       MIB_NOTIFICATION_TYPE type)
242 {
243   GWin32NetworkMonitor *win = context;
244   RouteData *route_data;
245
246   route_data = g_new0 (RouteData, 1);
247   route_data->route = route;
248   route_data->type = type;
249   route_data->win = win;
250
251   win->priv->route_change_source = g_idle_source_new ();
252   g_source_set_priority (win->priv->route_change_source, G_PRIORITY_DEFAULT);
253   g_source_set_callback (win->priv->route_change_source,
254                          win_network_monitor_invoke_route_changed,
255                          route_data,
256                          g_free);
257
258   g_source_attach (win->priv->route_change_source, win->priv->main_context);
259 }
260
261 static gboolean
262 g_win32_network_monitor_initable_init (GInitable     *initable,
263                                        GCancellable  *cancellable,
264                                        GError       **error)
265 {
266   GWin32NetworkMonitor *win = G_WIN32_NETWORK_MONITOR (initable);
267   NTSTATUS status;
268   gboolean read;
269
270   if (!win->priv->initialized)
271     {
272       win->priv->main_context = g_main_context_ref_thread_default ();
273
274       /* Read current IP routing table. */
275       read = win_network_monitor_process_table (win, &win->priv->init_error);
276       if (read)
277         {
278           /* Register for IPv4 and IPv6 route updates. */
279           status = NotifyRouteChange2 (AF_UNSPEC, (PIPFORWARD_CHANGE_CALLBACK) win_network_monitor_route_changed_cb, win, FALSE, &win->priv->handle);
280           if (status != NO_ERROR)
281             g_set_error (&win->priv->init_error, G_IO_ERROR, G_IO_ERROR_FAILED,
282                          "NotifyRouteChange2() error: %ld", status);
283         }
284
285       win->priv->initialized = TRUE;
286     }
287
288   /* Forward the results. */
289   if (win->priv->init_error != NULL)
290     {
291       g_propagate_error (error, g_error_copy (win->priv->init_error));
292       return FALSE;
293     }
294
295   return initable_parent_iface->init (initable, cancellable, error);
296 }
297
298 static void
299 g_win32_network_monitor_finalize (GObject *object)
300 {
301   GWin32NetworkMonitor *win = G_WIN32_NETWORK_MONITOR (object);
302
303   /* Cancel notification event */
304   if (win->priv->handle)
305     CancelMibChangeNotify2 (win->priv->handle);
306
307   g_clear_error (&win->priv->init_error);
308
309   if (win->priv->route_change_source != NULL)
310     {
311       g_source_destroy (win->priv->route_change_source);
312       g_source_unref (win->priv->route_change_source);
313     }
314
315   g_main_context_unref (win->priv->main_context);
316
317   G_OBJECT_CLASS (g_win32_network_monitor_parent_class)->finalize (object);
318 }
319
320 static void
321 g_win32_network_monitor_class_init (GWin32NetworkMonitorClass *win_class)
322 {
323   GObjectClass *gobject_class = G_OBJECT_CLASS (win_class);
324
325   gobject_class->finalize = g_win32_network_monitor_finalize;
326 }
327
328 static void
329 g_win32_network_monitor_iface_init (GNetworkMonitorInterface *monitor_iface)
330 {
331 }
332
333 static void
334 g_win32_network_monitor_initable_iface_init (GInitableIface *iface)
335 {
336   initable_parent_iface = g_type_interface_peek_parent (iface);
337
338   iface->init = g_win32_network_monitor_initable_init;
339 }