summaryrefslogtreecommitdiff
path: root/gio/gwin32networkmonitor.c
blob: e219225f0bd14c4f3d5b176edca4ccc85454928a (plain)
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
/* GIO - GLib Input, Output and Streaming Library
 *
 * Copyright 2014-2018 Jan-Michael Brummer <jan.brummer@tabos.org>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 * This library 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 2 of the License, or (at your option) any later version.
 *
 * This library 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 this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "config.h"

#include <errno.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>

#include "gwin32networkmonitor.h"
#include "ginetaddress.h"
#include "ginetaddressmask.h"
#include "ginitable.h"
#include "giomodule-priv.h"
#include "glibintl.h"
#include "glib/gstdio.h"
#include "gnetworkingprivate.h"
#include "gsocket.h"
#include "gnetworkmonitor.h"
#include "gioerror.h"

static GInitableIface *initable_parent_iface;
static void g_win32_network_monitor_iface_init (GNetworkMonitorInterface *iface);
static void g_win32_network_monitor_initable_iface_init (GInitableIface *iface);

struct _GWin32NetworkMonitorPrivate
{
  gboolean initialized;
  GError *init_error;
  GMainContext *main_context;
  GSource *route_change_source;
  HANDLE handle;
};

#define g_win32_network_monitor_get_type _g_win32_network_monitor_get_type
G_DEFINE_TYPE_WITH_CODE (GWin32NetworkMonitor, g_win32_network_monitor, G_TYPE_NETWORK_MONITOR_BASE,
                         G_ADD_PRIVATE (GWin32NetworkMonitor)
                         G_IMPLEMENT_INTERFACE (G_TYPE_NETWORK_MONITOR,
                                                g_win32_network_monitor_iface_init)
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
                                                g_win32_network_monitor_initable_iface_init)
                         _g_io_modules_ensure_extension_points_registered ();
                         g_io_extension_point_implement (G_NETWORK_MONITOR_EXTENSION_POINT_NAME,
                                                         g_define_type_id,
                                                         "win32",
                                                         20))

static void
g_win32_network_monitor_init (GWin32NetworkMonitor *win)
{
  win->priv = g_win32_network_monitor_get_instance_private (win);
}

static gboolean
win_network_monitor_get_ip_info (const IP_ADDRESS_PREFIX  *prefix,
                                 GSocketFamily            *family,
                                 const guint8            **dest,
                                 gsize                    *len)
{
  switch (prefix->Prefix.si_family)
    {
      case AF_UNSPEC:
        /* Fall-through: AF_UNSPEC deliveres both IPV4 and IPV6 infos, let`s stick with IPV4 here */
      case AF_INET:
        *family = G_SOCKET_FAMILY_IPV4;
        *dest = (guint8 *) &(prefix->Prefix.Ipv4.sin_addr);
        *len = prefix->PrefixLength;
        break;
      case AF_INET6:
        *family = G_SOCKET_FAMILY_IPV6;
        *dest = (guint8 *) &(prefix->Prefix.Ipv6.sin6_addr);
        *len = prefix->PrefixLength;
        break;
      default:
        return FALSE;
    }

  return TRUE;
}

static GInetAddressMask *
get_network_mask (GSocketFamily  family,
                  const guint8  *dest,
                  gsize          len)
{
  GInetAddressMask *network;
  GInetAddress *dest_addr;

  if (dest != NULL)
    dest_addr = g_inet_address_new_from_bytes (dest, family);
  else
    dest_addr = g_inet_address_new_any (family);

  network = g_inet_address_mask_new (dest_addr, len, NULL);
  g_object_unref (dest_addr);

  return network;
}

static gboolean
win_network_monitor_process_table (GWin32NetworkMonitor  *win,
                                   GError                 **error)
{
  DWORD ret = 0;
  GPtrArray *networks;
  gsize i;
  MIB_IPFORWARD_TABLE2 *routes = NULL;
  MIB_IPFORWARD_ROW2 *route;

  ret = GetIpForwardTable2 (AF_UNSPEC, &routes);
  if (ret != ERROR_SUCCESS)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "GetIpForwardTable2 () failed: %ld", ret);

      return FALSE;
    }

  networks = g_ptr_array_new_full (routes->NumEntries, g_object_unref);
  for (i = 0; i < routes->NumEntries; i++)
    {
      GInetAddressMask *network;
      const guint8 *dest;
      gsize len;
      GSocketFamily family;

      route = routes->Table + i;

      if (!win_network_monitor_get_ip_info (&route->DestinationPrefix, &family, &dest, &len))
        continue;

      network = get_network_mask (family, dest, len);
      if (network == NULL)
        continue;

      g_ptr_array_add (networks, network);
    }

  g_network_monitor_base_set_networks (G_NETWORK_MONITOR_BASE (win),
                                       (GInetAddressMask **) networks->pdata,
                                       networks->len);

  return TRUE;
}

static void
add_network (GWin32NetworkMonitor *win,
             GSocketFamily         family,
             const guint8         *dest,
             gsize                 dest_len)
{
  GInetAddressMask *network;

  network = get_network_mask (family, dest, dest_len);
  if (network != NULL)
    {
      g_network_monitor_base_add_network (G_NETWORK_MONITOR_BASE (win), network);
      g_object_unref (network);
    }
}

static void
remove_network (GWin32NetworkMonitor *win,
                GSocketFamily         family,
                const guint8         *dest,
                gsize                 dest_len)
{
  GInetAddressMask *network;

  network = get_network_mask (family, dest, dest_len);
  if (network != NULL)
    {
      g_network_monitor_base_remove_network (G_NETWORK_MONITOR_BASE (win), network);
      g_object_unref (network);
    }
}

typedef struct {
  PMIB_IPFORWARD_ROW2 route;
  MIB_NOTIFICATION_TYPE type;
  GWin32NetworkMonitor *win;
} RouteData;

static gboolean
win_network_monitor_invoke_route_changed (gpointer user_data)
{
  GSocketFamily family;
  RouteData *route_data = user_data;
  const guint8 *dest;
  gsize len;

  switch (route_data->type)
    {
      case MibDeleteInstance:
        if (!win_network_monitor_get_ip_info (&route_data->route->DestinationPrefix, &family, &dest, &len))
          break;

        remove_network (route_data->win, family, dest, len);
        break;
      case MibAddInstance:
        if (!win_network_monitor_get_ip_info (&route_data->route->DestinationPrefix, &family, &dest, &len))
            break;

        add_network (route_data->win, family, dest, len);
        break;
      case MibInitialNotification:
      default:
        break;
    }

  return G_SOURCE_REMOVE;
}

static VOID WINAPI
win_network_monitor_route_changed_cb (PVOID                 context,
                                      PMIB_IPFORWARD_ROW2   route,
                                      MIB_NOTIFICATION_TYPE type)
{
  GWin32NetworkMonitor *win = context;
  RouteData *route_data;

  route_data = g_new0 (RouteData, 1);
  route_data->route = route;
  route_data->type = type;
  route_data->win = win;

  win->priv->route_change_source = g_idle_source_new ();
  g_source_set_priority (win->priv->route_change_source, G_PRIORITY_DEFAULT);
  g_source_set_callback (win->priv->route_change_source,
                         win_network_monitor_invoke_route_changed,
                         route_data,
                         g_free);

  g_source_attach (win->priv->route_change_source, win->priv->main_context);
}

static gboolean
g_win32_network_monitor_initable_init (GInitable     *initable,
                                       GCancellable  *cancellable,
                                       GError       **error)
{
  GWin32NetworkMonitor *win = G_WIN32_NETWORK_MONITOR (initable);
  NTSTATUS status;
  gboolean read;

  if (!win->priv->initialized)
    {
      win->priv->main_context = g_main_context_ref_thread_default ();

      /* Read current IP routing table. */
      read = win_network_monitor_process_table (win, &win->priv->init_error);
      if (read)
        {
          /* Register for IPv4 and IPv6 route updates. */
          status = NotifyRouteChange2 (AF_UNSPEC, (PIPFORWARD_CHANGE_CALLBACK) win_network_monitor_route_changed_cb, win, FALSE, &win->priv->handle);
          if (status != NO_ERROR)
            g_set_error (&win->priv->init_error, G_IO_ERROR, G_IO_ERROR_FAILED,
                         "NotifyRouteChange2() error: %ld", status);
        }

      win->priv->initialized = TRUE;
    }

  /* Forward the results. */
  if (win->priv->init_error != NULL)
    {
      g_propagate_error (error, g_error_copy (win->priv->init_error));
      return FALSE;
    }

  return initable_parent_iface->init (initable, cancellable, error);
}

static void
g_win32_network_monitor_finalize (GObject *object)
{
  GWin32NetworkMonitor *win = G_WIN32_NETWORK_MONITOR (object);

  /* Cancel notification event */
  if (win->priv->handle)
    CancelMibChangeNotify2 (win->priv->handle);

  g_clear_error (&win->priv->init_error);

  if (win->priv->route_change_source != NULL)
    {
      g_source_destroy (win->priv->route_change_source);
      g_source_unref (win->priv->route_change_source);
    }

  g_main_context_unref (win->priv->main_context);

  G_OBJECT_CLASS (g_win32_network_monitor_parent_class)->finalize (object);
}

static void
g_win32_network_monitor_class_init (GWin32NetworkMonitorClass *win_class)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (win_class);

  gobject_class->finalize = g_win32_network_monitor_finalize;
}

static void
g_win32_network_monitor_iface_init (GNetworkMonitorInterface *monitor_iface)
{
}

static void
g_win32_network_monitor_initable_iface_init (GInitableIface *iface)
{
  initable_parent_iface = g_type_interface_peek_parent (iface);

  iface->init = g_win32_network_monitor_initable_init;
}