summaryrefslogtreecommitdiff
path: root/dom/network/EthernetManager.js
blob: 4b11e566663a0c989e64a23be168816e8e62df34 (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
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
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

const TOPIC_INTERFACE_STATE_CHANGED = "network-interface-state-changed";

const ETHERNET_NETWORK_IFACE_PREFIX = "eth";
const DEFAULT_ETHERNET_NETWORK_IFACE = "eth0";

const INTERFACE_IPADDR_NULL = "0.0.0.0";
const INTERFACE_GATEWAY_NULL = "0.0.0.0";
const INTERFACE_PREFIX_NULL = 0;
const INTERFACE_MACADDR_NULL = "00:00:00:00:00:00";

const NETWORK_INTERFACE_UP   = "up";
const NETWORK_INTERFACE_DOWN = "down";

const IP_MODE_DHCP = "dhcp";
const IP_MODE_STATIC = "static";

const PREF_NETWORK_DEBUG_ENABLED = "network.debugging.enabled";

XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
                                   "@mozilla.org/network/manager;1",
                                   "nsINetworkManager");

XPCOMUtils.defineLazyServiceGetter(this, "gNetworkService",
                                   "@mozilla.org/network/service;1",
                                   "nsINetworkService");

let debug;
function updateDebug() {
  let debugPref = false; // set default value here.
  try {
    debugPref = debugPref || Services.prefs.getBoolPref(PREF_NETWORK_DEBUG_ENABLED);
  } catch (e) {}

  if (debugPref) {
    debug = function(s) {
      dump("-*- EthernetManager: " + s + "\n");
    };
  } else {
    debug = function(s) {};
  }
}
updateDebug();

// nsINetworkInterface

function EthernetInterface(attr) {
  this.info.state = attr.state;
  this.info.type = attr.type;
  this.info.name = attr.name;
  this.info.ipMode = attr.ipMode;
  this.info.ips = [attr.ip];
  this.info.prefixLengths = [attr.prefixLength];
  this.info.gateways = [attr.gateway];
  this.info.dnses = attr.dnses;
  this.httpProxyHost = "";
  this.httpProxyPort = 0;
}
EthernetInterface.prototype = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterface]),

  updateConfig: function(config) {
    debug("Interface " + this.info.name + " updateConfig " + JSON.stringify(config));
    this.info.state = (config.state != undefined) ?
                  config.state : this.info.state;
    this.info.ips = (config.ip != undefined) ? [config.ip] : this.info.ips;
    this.info.prefixLengths = (config.prefixLength != undefined) ?
                         [config.prefixLength] : this.info.prefixLengths;
    this.info.gateways = (config.gateway != undefined) ?
                    [config.gateway] : this.info.gateways;
    this.info.dnses = (config.dnses != undefined) ? config.dnses : this.info.dnses;
    this.httpProxyHost = (config.httpProxyHost != undefined) ?
                          config.httpProxyHost : this.httpProxyHost;
    this.httpProxyPort = (config.httpProxyPort != undefined) ?
                          config.httpProxyPort : this.httpProxyPort;
    this.info.ipMode = (config.ipMode != undefined) ?
                   config.ipMode : this.info.ipMode;
  },

  info: {
    getAddresses: function(ips, prefixLengths) {
      ips.value = this.ips.slice();
      prefixLengths.value = this.prefixLengths.slice();

      return this.ips.length;
    },

    getGateways: function(count) {
      if (count) {
        count.value = this.gateways.length;
      }
      return this.gateways.slice();
    },

    getDnses: function(count) {
      if (count) {
        count.value = this.dnses.length;
      }
      return this.dnses.slice();
    }
  }
};

// nsIEthernetManager

/*
 *  Network state transition diagram
 *
 *   ----------  enable  ---------  connect   -----------   disconnect   --------------
 *  | Disabled | -----> | Enabled | -------> | Connected | <----------> | Disconnected |
 *   ----------          ---------            -----------    connect     --------------
 *       ^                  |                      |                           |
 *       |     disable      |                      |                           |
 *       -----------------------------------------------------------------------
 */

function EthernetManager() {
  debug("EthernetManager start");

  // Interface list.
  this.ethernetInterfaces = {};

  // Used to memorize last connection information.
  this.lastStaticConfig = {};

  Services.obs.addObserver(this, "xpcom-shutdown", false);
}

EthernetManager.prototype = {
  classID: Components.ID("a96441dd-36b3-4f7f-963b-2c032e28a039"),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIEthernetManager]),

  ethernetInterfaces: null,
  lastStaticConfig: null,

  observer: function(subject, topic, data) {
    switch (topic) {
      case "xpcom-shutdown":
        debug("xpcom-shutdown");

        this._shutdown();

        Services.obs.removeObserver(this, "xpcom-shutdown");
        break;
    }
  },

  _shutdown: function() {
    debug("Shuting down");
    (function onRemove(ifnameList) {
      if (!ifnameList.length) {
        return;
      }

      let ifname = ifnameList.shift();
      this.removeInterface(ifname, { notify: onRemove.bind(this, ifnameList) });
    }).call(this, Object.keys(this.ethernetInterfaces));
  },

  get interfaceList() {
    return Object.keys(this.ethernetInterfaces);
  },

  scan: function(callback) {
    debug("Scan");

    gNetworkService.getInterfaces(function(success, list) {
      let ethList = [];

      if (!success) {
        if (callback) {
          callback.notify(ethList);
        }
        return;
      }

      for (let i = 0; i < list.length; i++) {
        debug("Found interface " + list[i]);
        if (!list[i].startsWith(ETHERNET_NETWORK_IFACE_PREFIX)) {
          continue;
        }
        ethList.push(list[i]);
      }

      if (callback) {
        callback.notify(ethList);
      }
    });
  },

  addInterface: function(ifname, callback) {
    debug("Add interface " + ifname);

    if (!ifname || !ifname.startsWith(ETHERNET_NETWORK_IFACE_PREFIX)) {
      if (callback) {
        callback.notify(false, "Invalid interface.");
      }
      return;
    }

    if (this.ethernetInterfaces[ifname]) {
      if (callback) {
        callback.notify(true, "Interface already exists.");
      }
      return;
    }

    gNetworkService.getInterfaceConfig(ifname, function(success, result) {
      if (!success) {
        if (callback) {
          callback.notify(false, "Netd error.");
        }
        return;
      }

      // Since the operation may still succeed with an invalid interface name,
      // check the mac address as well.
      if (result.macAddr == INTERFACE_MACADDR_NULL) {
        if (callback) {
          callback.notify(false, "Interface not found.");
        }
        return;
      }

      this.ethernetInterfaces[ifname] = new EthernetInterface({
        state:        result.link == NETWORK_INTERFACE_UP ?
                        Ci.nsINetworkInfo.NETWORK_STATE_DISABLED :
                        Ci.nsINetworkInfo.NETWORK_STATE_ENABLED,
        name:         ifname,
        type:         Ci.nsINetworkInfo.NETWORK_TYPE_ETHERNET,
        ip:           result.ip,
        prefixLength: result.prefix,
        ipMode:       IP_MODE_DHCP
      });

      // Register the interface to NetworkManager.
      gNetworkManager.registerNetworkInterface(this.ethernetInterfaces[ifname]);

      debug("Add interface " + ifname + " succeeded with " +
            JSON.stringify(this.ethernetInterfaces[ifname]));

      if (callback) {
        callback.notify(true, "ok");
      }
    }.bind(this));
  },

  removeInterface: function(ifname, callback) {
    debug("Remove interface " + ifname);

    if (!ifname || !ifname.startsWith(ETHERNET_NETWORK_IFACE_PREFIX)) {
      if (callback) {
        callback.notify(false, "Invalid interface.");
      }
      return;
    }

    if (!this.ethernetInterfaces[ifname]) {
      if (callback) {
        callback.notify(true, "Interface does not exist.");
      }
      return;
    }

    // Make sure interface is disable before removing.
    this.disable(ifname, { notify: function(success, message) {
      // Unregister the interface from NetworkManager and also remove it from
      // the interface list.
      gNetworkManager.unregisterNetworkInterface(this.ethernetInterfaces[ifname]);
      delete this.ethernetInterfaces[ifname];

      debug("Remove interface " + ifname + " succeeded.");

      if (callback) {
        callback.notify(true, "ok");
      }
    }.bind(this)});
  },

  updateInterfaceConfig: function(ifname, config, callback) {
    debug("Update interface config with " + ifname);

    this._ensureIfname(ifname, callback, function(iface) {
      if (!config) {
        if (callback) {
          callback.notify(false, "No config to update.");
        }
        return;
      }

      // Network state can not be modified externally.
      if (config.state) {
        delete config.state;
      }

      let currentIpMode = iface.info.ipMode;

      // Update config.
      this.ethernetInterfaces[iface.info.name].updateConfig(config);

      // Do not automatically re-connect if the interface is not in connected
      // state.
      if (iface.info.state != Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
        if (callback) {
          callback.notify(true, "ok");
        }
        return;
      }

      let newIpMode = this.ethernetInterfaces[iface.info.name].info.ipMode;

      if (newIpMode == IP_MODE_STATIC) {
        this._setStaticIP(iface.info.name, callback);
        return;
      }
      if ((currentIpMode == IP_MODE_STATIC) && (newIpMode == IP_MODE_DHCP)) {
        gNetworkService.stopDhcp(iface.info.name, function(success) {
          if (success) {
            debug("DHCP for " + iface.info.name + " stopped.");
          }
        });

        // Clear the current network settings before do dhcp request, otherwise
        // dhcp settings could fail.
        this.disconnect(iface.info.name, { notify: function(success, message) {
          if (!success) {
            if (callback) {
              callback.notify("Disconnect failed.");
            }
            return;
          }
          this._runDhcp(iface.info.name, callback);
        }.bind(this) });
        return;
      }

      if (callback) {
        callback.notify(true, "ok");
      }
    }.bind(this));
  },

  enable: function(ifname, callback) {
    debug("Enable interface " + ifname);

    this._ensureIfname(ifname, callback, function(iface) {
      // Interface can be only enabled in the state of disabled.
      if (iface.info.state != Ci.nsINetworkInfo.NETWORK_STATE_DISABLED) {
        if (callback) {
          callback.notify(true, "Interface already enabled.");
        }
        return;
      }

      let ips = {};
      let prefixLengths = {};
      iface.info.getAddresses(ips, prefixLengths);
      let config = { ifname: iface.info.name,
                     ip:     ips.value[0],
                     prefix: prefixLengths.value[0],
                     link:   NETWORK_INTERFACE_UP };
      gNetworkService.setInterfaceConfig(config, function(success) {
        if (!success) {
          if (callback) {
            callback.notify(false, "Netd Error.");
          }
          return;
        }

        this.ethernetInterfaces[iface.info.name].updateConfig({
          state: Ci.nsINetworkInfo.NETWORK_STATE_ENABLED
        });

        debug("Enable interface " + iface.info.name + " succeeded.");

        if (callback) {
          callback.notify(true, "ok");
        }
      }.bind(this));
    }.bind(this));
  },

  disable: function(ifname, callback) {
    debug("Disable interface " + ifname);

    this._ensureIfname(ifname, callback, function(iface) {
      if (iface.info.state == Ci.nsINetworkInfo.NETWORK_STATE_DISABLED) {
        if (callback) {
          callback.notify(true, "Interface already disabled.");
        }
        return;
      }

      if (iface.info.state == Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
        gNetworkService.stopDhcp(iface.info.name, function(success) {
          if (success) {
            debug("DHCP for " + iface.info.name + " stopped.");
          }
        });
      }

      let ips = {};
      let prefixLengths = {};
      iface.info.getAddresses(ips, prefixLengths);
      let config = { ifname: iface.info.name,
                     ip:     ips.value[0],
                     prefix: prefixLengths.value[0],
                     link:   NETWORK_INTERFACE_DOWN };
      gNetworkService.setInterfaceConfig(config, function(success) {
        if (!success) {
          if (callback) {
            callback.notify(false, "Netd Error.");
          }
          return;
        }

        this.ethernetInterfaces[iface.info.name].updateConfig({
          state: Ci.nsINetworkInfo.NETWORK_STATE_DISABLED
        });

        debug("Disable interface " + iface.info.name + " succeeded.");

        if (callback) {
          callback.notify(true, "ok");
        }
      }.bind(this));
    }.bind(this));
  },

  connect: function(ifname, callback) {
    debug("Connect interface " + ifname);

    this._ensureIfname(ifname, callback, function(iface) {
      // Interface can only be connected in the state of enabled or
      // disconnected.
      if (iface.info.state == Ci.nsINetworkInfo.NETWORK_STATE_DISABLED ||
          iface.info.state == Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
        if (callback) {
          callback.notify(true, "Interface " + ifname + " is not available or "
                                 + " already connected.");
        }
        return;
      }

      if (iface.info.ipMode == IP_MODE_DHCP) {
        this._runDhcp(iface.info.name, callback);
        return;
      }

      if (iface.info.ipMode == IP_MODE_STATIC) {
        if (this._checkConfigNull(iface) && this.lastStaticConfig[iface.info.name]) {
          debug("Connect with lastStaticConfig " +
                JSON.stringify(this.lastStaticConfig[iface.info.name]));
          this.ethernetInterfaces[iface.info.name].updateConfig(
            this.lastStaticConfig[iface.info.name]);
        }
        this._setStaticIP(iface.info.name, callback);
        return;
      }

      if (callback) {
        callback.notify(false, "IP mode is wrong or not set.");
      }
    }.bind(this));
  },

  disconnect: function(ifname, callback) {
    debug("Disconnect interface " + ifname);

    this._ensureIfname(ifname, callback, function(iface) {
      // Interface can be only disconnected in the state of connected.
      if (iface.info.state != Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
        if (callback) {
          callback.notify(true, "Interface is already disconnected");
        }
        return;
      }

      let config = { ifname: iface.info.name,
                     ip:     INTERFACE_IPADDR_NULL,
                     prefix: INTERFACE_PREFIX_NULL,
                     link:   NETWORK_INTERFACE_UP };
      gNetworkService.setInterfaceConfig(config, function(success) {
        if (!success) {
          if (callback) {
            callback.notify(false, "Netd error.");
          }
          return;
        }

        // Stop dhcp daemon.
        gNetworkService.stopDhcp(iface.info.name, function(success) {
          if (success) {
            debug("DHCP for " + iface.info.name + " stopped.");
          }
        });

        this.ethernetInterfaces[iface.info.name].updateConfig({
          state:        Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED,
          ip:           INTERFACE_IPADDR_NULL,
          prefixLength: INTERFACE_PREFIX_NULL,
          gateway:      INTERFACE_GATEWAY_NULL
        });

        gNetworkManager.updateNetworkInterface(this.ethernetInterfaces[ifname]);

        debug("Disconnect interface " + iface.info.name + " succeeded.");

        if (callback) {
          callback.notify(true, "ok");
        }
      }.bind(this));
    }.bind(this));
  },

  _checkConfigNull: function(iface) {
    let ips = {};
    let prefixLengths = {};
    let gateways = iface.info.getGateways();
    iface.info.getAddresses(ips, prefixLengths);

    if (ips.value[0] == INTERFACE_IPADDR_NULL &&
        prefixLengths.value[0] == INTERFACE_PREFIX_NULL &&
        gateways[0] == INTERFACE_GATEWAY_NULL) {
      return true;
    }

    return false;
  },

  _ensureIfname: function(ifname, callback, func) {
    // If no given ifname, use the default one.
    if (!ifname) {
      ifname = DEFAULT_ETHERNET_NETWORK_IFACE;
    }

    let iface = this.ethernetInterfaces[ifname];
    if (!iface) {
      if (callback) {
        callback.notify(true, "Interface " + ifname + " is not available.");
      }
      return;
    }

    func.call(this, iface);
  },

  _runDhcp: function(ifname, callback) {
    debug("runDhcp with " + ifname);

    if (!this.ethernetInterfaces[ifname]) {
      if (callback) {
        callback.notify(false, "Invalid interface.");
      }
      return;
    }

    gNetworkService.dhcpRequest(ifname, function(success, result) {
      if (!success) {
        if (callback) {
          callback.notify(false, "DHCP failed.");
        }
        return;
      }

      debug("DHCP succeeded with " + JSON.stringify(result));

      // Clear last static network information when connecting with dhcp mode.
      if (this.lastStaticConfig[ifname]) {
        this.lastStaticConfig[ifname] = null;
      }

      this.ethernetInterfaces[ifname].updateConfig({
        state:        Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED,
        ip:           result.ipaddr_str,
        gateway:      result.gateway_str,
        prefixLength: result.prefixLength,
        dnses:        [result.dns1_str, result.dns2_str]
      });

      gNetworkManager.updateNetworkInterface(this.ethernetInterfaces[ifname]);

      debug("Connect interface " + ifname + " with DHCP succeeded.");

      if (callback) {
        callback.notify(true, "ok");
      }
    }.bind(this));
  },

  _setStaticIP: function(ifname, callback) {
    let iface = this.ethernetInterfaces[ifname];
    if (!iface) {
      if (callback) {
        callback.notify(false, "Invalid interface.");
      }
      return;
    }

    let ips = {};
    let prefixLengths = {};
    iface.info.getAddresses(ips, prefixLengths);

    let config = { ifname: iface.info.name,
                   ip:     ips.value[0],
                   prefix: prefixLengths.value[0],
                   link:   NETWORK_INTERFACE_UP };
    gNetworkService.setInterfaceConfig(config, function(success) {
      if (!success) {
        if (callback) {
          callback.notify(false, "Netd Error.");
        }
        return;
      }

      // Keep the lastest static network information.
      let ips = {};
      let prefixLengths = {};
      let gateways = iface.info.getGateways();
      iface.info.getAddresses(ips, prefixLengths);

      this.lastStaticConfig[iface.info.name] = {
        ip:           ips.value[0],
        prefixLength: prefixLengths.value[0],
        gateway:      gateways[0]
      };

      this.ethernetInterfaces[ifname].updateConfig({
        state: Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED,
      });

      gNetworkManager.updateNetworkInterface(this.ethernetInterfaces[ifname]);

      debug("Connect interface " + ifname + " with static ip succeeded.");

      if (callback) {
        callback.notify(true, "ok");
      }
    }.bind(this));
  },
}

this.NSGetFactory = XPCOMUtils.generateNSGetFactory([EthernetManager]);