aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/netaddr/NetworkConfigurationWatcher.java
blob: ecf40339719bcc11d461eebd9e2d3ef0576b90d5 (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
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
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.netaddr;

import java.net.*;
import java.util.*;

import net.java.sip.communicator.service.netaddr.event.*;
import net.java.sip.communicator.service.sysactivity.*;
import net.java.sip.communicator.service.sysactivity.event.*;
import net.java.sip.communicator.util.*;

import org.osgi.framework.*;

/**
 * Periodically checks the current network interfaces to track changes
 * and fire events on those changes.
 *
 * @author Damian Minkov
 */
public class NetworkConfigurationWatcher
    implements SystemActivityChangeListener,
               ServiceListener,
               Runnable
{
    /**
     * Our class logger.
     */
    private static  Logger logger =
        Logger.getLogger(NetworkConfigurationWatcher.class);

    /**
     * The current active interfaces.
     */
    private Map<String, List<InetAddress>> activeInterfaces
            = new HashMap<String, List<InetAddress>>();

    /**
     * Interval between check of network configuration.
     */
    private static final int CHECK_INTERVAL = 3000; // 3 sec.

    /**
     * Whether thread checking for network notifications is running.
     */
    private boolean isRunning = false;

    /**
     * Service we use to listen for network changes.
     */
    private SystemActivityNotificationsService
            systemActivityNotificationsService = null;

    /**
     * The thread dispatcher of network change events.
     */
    private NetworkEventDispatcher eventDispatcher =
            new NetworkEventDispatcher();

    /**
     * Inits configuration watcher.
     */
    NetworkConfigurationWatcher()
    {
        try
        {
            checkNetworkInterfaces(false, 0, true);
        } catch (SocketException e)
        {
            logger.error("Error checking network interfaces", e);
        }
    }

    /**
     * Adds new <tt>NetworkConfigurationChangeListener</tt> which will
     * be informed for network configuration changes.
     * @param listener the listener.
     */
    void addNetworkConfigurationChangeListener(
        NetworkConfigurationChangeListener listener)
    {
        eventDispatcher.addNetworkConfigurationChangeListener(listener);

        initialFireEvents(listener);

        NetaddrActivator.getBundleContext().addServiceListener(this);

        if(this.systemActivityNotificationsService == null)
        {
            SystemActivityNotificationsService systActService
                = ServiceUtils.getService(
                        NetaddrActivator.getBundleContext(),
                        SystemActivityNotificationsService.class);

            handleNewSystemActivityNotificationsService(systActService);
        }
    }

    /**
     * Used to fire initial events to newly added listers.
     * @param listener the listener to fire.
     */
    private void initialFireEvents(
            NetworkConfigurationChangeListener listener)
    {
        try
        {
            Enumeration<NetworkInterface> e =
            NetworkInterface.getNetworkInterfaces();

            while (e.hasMoreElements())
            {
                NetworkInterface networkInterface = e.nextElement();

                if(networkInterface.isLoopback())
                    continue;

                // if interface is up and has some valid(non-local) address
                // add it to currently active
                if(networkInterface.isUp())
                {
                    Enumeration<InetAddress> as =
                        networkInterface.getInetAddresses();
                    boolean hasAddress = false;
                    while (as.hasMoreElements())
                    {
                        InetAddress inetAddress = as.nextElement();
                        if(inetAddress.isLinkLocalAddress())
                            continue;

                        hasAddress = true;
                        NetworkEventDispatcher.fireChangeEvent(
                            new ChangeEvent(
                                    networkInterface.getName(),
                                    ChangeEvent.ADDRESS_UP,
                                    inetAddress,
                                    false,
                                    true),
                            listener);
                    }

                    if(hasAddress)
                        NetworkEventDispatcher.fireChangeEvent(
                            new ChangeEvent(networkInterface.getName(),
                                ChangeEvent.IFACE_UP, null, false, true),
                            listener);
                }
            }


        } catch (SocketException e)
        {
            logger.error("Error checking network interfaces", e);
        }
    }

    /**
     * Saves the reference for the service and
     * add a listener if the desired events are supported. Or start
     * the checking thread otherwise.
     * @param newService
     */
    private void handleNewSystemActivityNotificationsService(
            SystemActivityNotificationsService newService)
    {
        if(newService == null)
            return;

        this.systemActivityNotificationsService = newService;

        if(this.systemActivityNotificationsService
                    .isSupported(SystemActivityEvent.EVENT_NETWORK_CHANGE))
        {
            this.systemActivityNotificationsService
                .addSystemActivityChangeListener(this);
        }
        else
        {
            if(!isRunning)
            {
                isRunning = true;
                Thread th = new Thread(this);
                // set to max priority to prevent detecting sleep if the cpu is
                // overloaded
                th.setPriority(Thread.MAX_PRIORITY);
                th.start();
            }
        }
    }

    /**
     * Remove <tt>NetworkConfigurationChangeListener</tt>.
     * @param listener the listener.
     */
    void removeNetworkConfigurationChangeListener(
        NetworkConfigurationChangeListener listener)
    {
        eventDispatcher.removeNetworkConfigurationChangeListener(listener);
    }

    /**
     * When new protocol provider is registered we add needed listeners.
     *
     * @param serviceEvent ServiceEvent
     */
    public void serviceChanged(ServiceEvent serviceEvent)
    {
        ServiceReference serviceRef = serviceEvent.getServiceReference();

        // if the event is caused by a bundle being stopped, we don't want to
        // know we are shutting down
        if (serviceRef.getBundle().getState() == Bundle.STOPPING)
        {
            return;
        }

        Object sService = NetaddrActivator.getBundleContext()
                .getService(serviceRef);

        if(sService instanceof SystemActivityNotificationsService)
        {
            switch (serviceEvent.getType())
            {
                case ServiceEvent.REGISTERED:
                    if(this.systemActivityNotificationsService != null)
                        break;

                    handleNewSystemActivityNotificationsService(
                        (SystemActivityNotificationsService)sService);
                    break;
                case ServiceEvent.UNREGISTERING:
                    ((SystemActivityNotificationsService)sService)
                        .removeSystemActivityChangeListener(this);
                    break;
            }

            return;
        }
    }

    /**
     * Stop.
     */
    void stop()
    {
        if(isRunning)
        {
            synchronized(this)
            {
                isRunning = false;
                notifyAll();
            }
        }

        if(eventDispatcher != null)
            eventDispatcher.stop();
    }

    /**
     * This method gets called when a notification action for a particular event
     * type has been changed. We are interested in sleep and network
     * changed events.
     *
     * @param event the <tt>NotificationActionTypeEvent</tt>, which is
     * dispatched when an action has been changed.
     */
    public void activityChanged(SystemActivityEvent event)
    {
        if(event.getEventID() == SystemActivityEvent.EVENT_SLEEP)
        {
            // oo standby lets fire down to all interfaces
            // so they can reconnect
            downAllInterfaces();
        }
        else if(event.getEventID() == SystemActivityEvent.EVENT_NETWORK_CHANGE)
        {
            try
            {
                checkNetworkInterfaces(true, 0, true);
            } catch (SocketException e)
            {
                logger.error("Error checking network interfaces", e);
            }
        }
        else if(event.getEventID() == SystemActivityEvent.EVENT_DNS_CHANGE)
        {
            try
            {
                eventDispatcher.fireChangeEvent(
                    new ChangeEvent(event.getSource(), ChangeEvent.DNS_CHANGE));
            }
            catch(Throwable t)
            {
                logger.error("Error dispatching dns change.");
            }
        }
    }

    /**
     * Down all interfaces and fire events for it.
     */
    private void downAllInterfaces()
    {
        Iterator<String> iter = activeInterfaces.keySet().iterator();
        while (iter.hasNext())
        {
            String niface = iter.next();
            eventDispatcher.fireChangeEvent(new ChangeEvent(niface,
                    ChangeEvent.IFACE_DOWN, true));
        }
        activeInterfaces.clear();
    }

    /**
     * Checks current interfaces configuration against the last saved
     * active interfaces.
     * @param fireEvents whether we will fire events when we detect
     * that interface is changed. When we start we query the interfaces
     * just to check which are online, without firing events.
     * @param waitBeforeFiringUpEvents milliseconds to wait before
     * firing events for interfaces up, sometimes we must wait a little bit
     * and give time for interfaces to configure fully (dns on linux).
     * @param printDebugInfo whether to print debug info, do not print
     * anything if we are constantly checking as it will flood logs and made
     * them unusable.
     */
    private void checkNetworkInterfaces(
            boolean fireEvents,
            int waitBeforeFiringUpEvents,
            boolean printDebugInfo)
        throws SocketException
    {
        Enumeration<NetworkInterface> e =
            NetworkInterface.getNetworkInterfaces();

        Map<String, List<InetAddress>> currentActiveInterfaces =
            new HashMap<String, List<InetAddress>>();

        while (e.hasMoreElements())
        {
            NetworkInterface networkInterface = e.nextElement();

            if(networkInterface.isLoopback())
                continue;

            // if interface is up and has some valid(non-local) address
            // add it to currently active
            if(networkInterface.isUp())
            {
                List<InetAddress> addresses =
                    new ArrayList<InetAddress>();

                Enumeration<InetAddress> as =
                    networkInterface.getInetAddresses();
                while (as.hasMoreElements())
                {
                    InetAddress inetAddress = as.nextElement();
                    if(inetAddress.isLinkLocalAddress())
                        continue;

                    addresses.add(inetAddress);
                }

                if(addresses.size() > 0)
                    currentActiveInterfaces.put(
                        networkInterface.getName(), addresses);
            }
        }

        // add network debug info, to track wake up problems
        if(logger.isInfoEnabled() && printDebugInfo)
        {
            for(Map.Entry<String, List<InetAddress>> en :
                activeInterfaces.entrySet())
            {
                logger.info("Previously Active " + en.getKey()
                    + ":" + en.getValue());
            }

            for(Map.Entry<String, List<InetAddress>> en :
                currentActiveInterfaces.entrySet())
            {
                logger.info("Currently Active " + en.getKey()
                    + ":" + en.getValue());
            }
        }

        // search for down interface
        List<String> inactiveActiveInterfaces =
            new ArrayList<String>(activeInterfaces.keySet());
        List<String> currentActiveInterfacesSet
            = new ArrayList<String>(currentActiveInterfaces.keySet());
        inactiveActiveInterfaces.removeAll(currentActiveInterfacesSet);

        // fire that interface has gone down
        for (int i = 0; i < inactiveActiveInterfaces.size(); i++)
        {
            String iface = inactiveActiveInterfaces.get(i);

            if(!currentActiveInterfacesSet.contains(iface))
            {
                if(fireEvents)
                    eventDispatcher.fireChangeEvent(new ChangeEvent(iface,
                        ChangeEvent.IFACE_DOWN));

                activeInterfaces.remove(iface);
            }
        }

        // now look at the addresses of the connected interfaces
        // if something has gown down
        Iterator<Map.Entry<String, List<InetAddress>>>
                activeEntriesIter = activeInterfaces.entrySet().iterator();
        while(activeEntriesIter.hasNext())
        {
            Map.Entry<String, List<InetAddress>>
                entry = activeEntriesIter.next();
            Iterator<InetAddress> addrIter = entry.getValue().iterator();
            while(addrIter.hasNext())
            {
                InetAddress addr = addrIter.next();

                // if address is missing in current active interfaces
                // it means it has gone done
                List<InetAddress> addresses =
                        currentActiveInterfaces.get(entry.getKey());

                if(addresses != null && !addresses.contains(addr))
                {
                    if(fireEvents)
                        eventDispatcher.fireChangeEvent(
                            new ChangeEvent(entry.getKey(),
                                    ChangeEvent.ADDRESS_DOWN, addr));

                    addrIter.remove();
                }
            }
        }

        if(waitBeforeFiringUpEvents > 0
            && currentActiveInterfaces.size() != 0)
        {
            // calm for a while, we sometimes receive those events and
            // configuration has not yet finished (dns can be the old one)
            synchronized(this)
            {
                try{
                    wait(waitBeforeFiringUpEvents);
                }catch(InterruptedException ex){}
            }
        }

        // now look at the addresses of the connected interfaces
        // if something has gown up
        activeEntriesIter = currentActiveInterfaces.entrySet().iterator();
        while(activeEntriesIter.hasNext())
        {
            Map.Entry<String, List<InetAddress>>
                entry = activeEntriesIter.next();
            for(InetAddress addr : entry.getValue())
            {
                // if address is missing in active interfaces
                // it means it has gone up
                List<InetAddress> addresses =
                        activeInterfaces.get(entry.getKey());
                if(addresses != null && !addresses.contains(addr))
                {
                    if(fireEvents)
                        eventDispatcher.fireChangeEvent(
                                new ChangeEvent(entry.getKey(),
                                                ChangeEvent.ADDRESS_UP,
                                                addr));

                    addresses.add(addr);
                }
            }
        }

        // now we leave with only with the new and up interfaces
        // in currentActiveInterfaces Map
        Iterator<String> ifaceIter
                = activeInterfaces.keySet().iterator();
        while(ifaceIter.hasNext())
        {
            currentActiveInterfaces.remove(ifaceIter.next());
        }

        // fire that interface has gone up
        activeEntriesIter = currentActiveInterfaces.entrySet().iterator();
        while(activeEntriesIter.hasNext())
        {
            final Map.Entry<String, List<InetAddress>>
                entry = activeEntriesIter.next();
            for(InetAddress addr : entry.getValue())
            {
                if(fireEvents)
                    eventDispatcher.fireChangeEvent(
                            new ChangeEvent(entry.getKey(),
                                            ChangeEvent.ADDRESS_UP,
                                            addr));
            }

            if(fireEvents)
            {
                // if we haven't waited before, lets wait here
                // and give time to underlying os to configure fully the
                // network interface (receive and store dns config)
                int wait = waitBeforeFiringUpEvents;
                if(wait == 0)
                {
                    wait = 500;
                }

                eventDispatcher.fireChangeEvent(
                        new ChangeEvent(entry.getKey(), ChangeEvent.IFACE_UP),
                        wait);
            }

            activeInterfaces.put(entry.getKey(), entry.getValue());
        }
    }

    /**
     * Main loop of this thread.
     */
    public void run()
    {
        long last = 0;
        boolean isAfterStandby = false;

        while(isRunning)
        {
            long curr = System.currentTimeMillis();

            // if time spent between checks is more than 4 times
            // longer than the check interval we consider it as a
            // new check after standby
            if(!isAfterStandby && last != 0)
                isAfterStandby = (last + 4*CHECK_INTERVAL - curr) < 0;

            if(isAfterStandby)
            {
                // oo standby lets fire down to all interfaces
                // so they can reconnect
                downAllInterfaces();

                // we have fired events for standby, make it to false now
                // so we can calculate it again next time
                isAfterStandby = false;

                last = curr;

                // give time to interfaces
                synchronized(this)
                {
                    try{
                        wait(CHECK_INTERVAL);
                    }
                    catch (Exception e){}
                }

                continue;
            }

            try
            {
                boolean networkIsUP = activeInterfaces.size() > 0;

                checkNetworkInterfaces(true, 1000, false);

                // fire that network has gone up
                if(!networkIsUP && activeInterfaces.size() > 0)
                {
                    isAfterStandby = false;
                }

                // save the last time that we checked
                last = System.currentTimeMillis();
            } catch (SocketException e)
            {
                logger.error("Error checking network interfaces", e);
            }

            synchronized(this)
            {
                try{
                    wait(CHECK_INTERVAL);
                }
                catch (Exception e){}
            }
        }
    }
}