summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/cryptotoken/gnubbies.js
blob: 8cd25282f983fc260d486d7ef5c5bfe6b432b40f (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
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview A class for managing all enumerated gnubby devices.
 */
'use strict';

/**
 * @typedef {{
 *   namespace: string,
 *   device: number
 * }}
 */
var GnubbyDeviceId;

/**
 * @typedef {{
 *   isSharedAccess: boolean,
 *   enumerate: function(function(Array)),
 *   deviceToDeviceId: function(*): GnubbyDeviceId,
 *   open: function(Gnubbies, number, *, function(number, GnubbyDevice=))
 * }}
 */
var GnubbyNamespaceImpl;

/**
 * Manager of opened devices.
 * @constructor
 */
function Gnubbies() {
  /** @private {Object<string, Array>} */
  this.devs_ = {};
  this.pendingEnumerate = [];  // clients awaiting an enumerate
  /**
   * The distinct namespaces registered in this Gnubbies instance, in order of
   * registration.
   * @private {Array<string>}
   */
  this.namespaces_ = [];
  /** @private {Object<string, GnubbyNamespaceImpl>} */
  this.impl_ = {};
  /** @private {Object<string, Object<number, !GnubbyDevice>>} */
  this.openDevs_ = {};
  /** @private {Object<string, Object<number, *>>} */
  this.pendingOpens_ = {};  // clients awaiting an open
}

/**
 * Registers a new gnubby namespace, i.e. an implementation of the
 * enumerate/open functions for all devices within a namespace.
 * @param {string} namespace The namespace of the numerator, e.g. 'usb'.
 * @param {GnubbyNamespaceImpl} impl The implementation.
 */
Gnubbies.prototype.registerNamespace = function(namespace, impl) {
  if (!this.impl_.hasOwnProperty(namespace)) {
    this.namespaces_.push(namespace);
  }
  this.impl_[namespace] = impl;
};

/**
 * @param {GnubbyDeviceId} id The device id.
 * @return {boolean} Whether the device is a shared access device.
 */
Gnubbies.prototype.isSharedAccess = function(id) {
  if (!this.impl_.hasOwnProperty(id.namespace)) return false;
  return this.impl_[id.namespace].isSharedAccess;
};

/**
 * @param {GnubbyDeviceId} which The device to remove.
 */
Gnubbies.prototype.removeOpenDevice = function(which) {
  if (this.openDevs_[which.namespace] &&
      this.openDevs_[which.namespace].hasOwnProperty(which.device)) {
    delete this.openDevs_[which.namespace][which.device];
  }
};

/** Close all enumerated devices. */
Gnubbies.prototype.closeAll = function() {
  if (this.inactivityTimer) {
    this.inactivityTimer.clearTimeout();
    this.inactivityTimer = undefined;
  }
  // Close and stop talking to any gnubbies we have enumerated.
  for (var namespace in this.openDevs_) {
    for (var dev in this.openDevs_[namespace]) {
      var deviceId = Number(dev);
      this.openDevs_[namespace][deviceId].destroy();
    }
  }
  this.devs_ = {};
  this.openDevs_ = {};
};

/**
 * @param {function(number, Array<GnubbyDeviceId>)} cb Called back with the
 *     result of enumerating.
 */
Gnubbies.prototype.enumerate = function(cb) {
  if (!cb) {
    cb = function(rc, indexes) {
      var msg = 'defaultEnumerateCallback(' + rc;
      if (indexes) {
        msg += ', [';
        for (var i = 0; i < indexes.length; i++) {
          msg += JSON.stringify(indexes[i]);
        }
        msg += ']';
      }
      msg += ')';
      console.log(UTIL_fmt(msg));
    };
  }

  if (!this.namespaces_.length) {
    cb(-GnubbyDevice.OK, []);
    return;
  }

  var namespacesEnumerated = 0;
  var self = this;

  /**
   * @param {string} namespace The namespace that was enumerated.
   * @param {Array<GnubbyDeviceId>} existingDeviceIds Previously enumerated
   *     device IDs (from other namespaces), if any.
   * @param {Array} devs The devices in the namespace.
   */
  function enumerated(namespace, existingDeviceIds, devs) {
    namespacesEnumerated++;
    var lastNamespace = (namespacesEnumerated == self.namespaces_.length);

    if (chrome.runtime.lastError) {
      console.warn(UTIL_fmt('lastError: ' + chrome.runtime.lastError));
      console.log(chrome.runtime.lastError);
      devs = [];
    }

    console.log(UTIL_fmt('Enumerated ' + devs.length + ' gnubbies'));
    console.log(devs);

    var presentDevs = {};
    var deviceIds = [];
    var deviceToDeviceId = self.impl_[namespace].deviceToDeviceId;
    for (var i = 0; i < devs.length; ++i) {
      var deviceId = deviceToDeviceId(devs[i]);
      deviceIds.push(deviceId);
      presentDevs[deviceId.device] = devs[i];
    }

    var toRemove = [];
    for (var dev in self.openDevs_[namespace]) {
      if (!presentDevs.hasOwnProperty(dev)) {
        toRemove.push(dev);
      }
    }

    for (var i = 0; i < toRemove.length; i++) {
      dev = toRemove[i];
      if (self.openDevs_[namespace][dev]) {
        self.openDevs_[namespace][dev].destroy();
        delete self.openDevs_[namespace][dev];
      }
    }

    self.devs_[namespace] = devs;
    existingDeviceIds.push.apply(existingDeviceIds, deviceIds);
    if (lastNamespace) {
      while (self.pendingEnumerate.length != 0) {
        var cb = self.pendingEnumerate.shift();
        cb(-GnubbyDevice.OK, existingDeviceIds);
      }
    }
  }

  var deviceIds = [];
  function makeEnumerateCb(namespace) {
    return function(devs) {
      enumerated(namespace, deviceIds, devs);
    }
  }

  this.pendingEnumerate.push(cb);
  if (this.pendingEnumerate.length == 1) {
    for (var i = 0; i < this.namespaces_.length; i++) {
      var namespace = this.namespaces_[i];
      var enumerator = this.impl_[namespace].enumerate;
      enumerator(makeEnumerateCb(namespace));
    }
  }
};

/**
 * Amount of time past last activity to set the inactivity timer to, in millis.
 * @const
 */
Gnubbies.INACTIVITY_TIMEOUT_MARGIN_MILLIS = 30000;

/**
 * Private instance of timers based on window's timer functions.
 * @const
 * @private
 */
Gnubbies.SYS_TIMER_ = new WindowTimer();

/**
 * @param {number|undefined} opt_timeoutMillis Timeout in milliseconds
 */
Gnubbies.prototype.resetInactivityTimer = function(opt_timeoutMillis) {
  var millis = opt_timeoutMillis ?
      opt_timeoutMillis + Gnubbies.INACTIVITY_TIMEOUT_MARGIN_MILLIS :
      Gnubbies.INACTIVITY_TIMEOUT_MARGIN_MILLIS;
  if (!this.inactivityTimer) {
    this.inactivityTimer =
        new CountdownTimer(
            Gnubbies.SYS_TIMER_, millis, this.inactivityTimeout_.bind(this));
  } else if (millis > this.inactivityTimer.millisecondsUntilExpired()) {
    this.inactivityTimer.clearTimeout();
    this.inactivityTimer.setTimeout(millis, this.inactivityTimeout_.bind(this));
  }
};

/**
 * Called when the inactivity timeout expires.
 * @private
 */
Gnubbies.prototype.inactivityTimeout_ = function() {
  this.inactivityTimer = undefined;
  for (var namespace in this.openDevs_) {
    for (var dev in this.openDevs_[namespace]) {
      var deviceId = Number(dev);
      console.warn(namespace + ' device ' + deviceId +
          ' still open after inactivity, closing');
      this.openDevs_[namespace][deviceId].destroy();
    }
  }
};

/**
 * Opens and adds a new client of the specified device.
 * @param {GnubbyDeviceId} which Which device to open.
 * @param {*} who Client of the device.
 * @param {function(number, GnubbyDevice=)} cb Called back with the result of
 *     opening the device.
 */
Gnubbies.prototype.addClient = function(which, who, cb) {
  this.resetInactivityTimer();

  var self = this;

  function opened(gnubby, who, cb) {
    if (gnubby.closing) {
      // Device is closing or already closed.
      self.removeClient(gnubby, who);
      if (cb) { cb(-GnubbyDevice.NODEVICE); }
    } else {
      gnubby.registerClient(who);
      if (cb) { cb(-GnubbyDevice.OK, gnubby); }
    }
  }

  function notifyOpenResult(rc) {
    if (self.pendingOpens_[which.namespace]) {
      while (self.pendingOpens_[which.namespace][which.device].length != 0) {
        var client = self.pendingOpens_[which.namespace][which.device].shift();
        client.cb(rc);
      }
      delete self.pendingOpens_[which.namespace][which.device];
    }
  }

  var dev = null;
  var deviceToDeviceId = this.impl_[which.namespace].deviceToDeviceId;
  if (this.devs_[which.namespace]) {
    for (var i = 0; i < this.devs_[which.namespace].length; i++) {
      var device = this.devs_[which.namespace][i];
      if (deviceToDeviceId(device).device == which.device) {
        dev = device;
        break;
      }
    }
  }
  if (!dev) {
    // Index out of bounds. Device does not exist in current enumeration.
    this.removeClient(null, who);
    if (cb) { cb(-GnubbyDevice.NODEVICE); }
    return;
  }

  function openCb(rc, opt_gnubby) {
    if (rc) {
      notifyOpenResult(rc);
      return;
    }
    if (!opt_gnubby) {
      notifyOpenResult(-GnubbyDevice.NODEVICE);
      return;
    }
    var gnubby = /** @type {!GnubbyDevice} */ (opt_gnubby);
    if (!self.openDevs_[which.namespace]) {
      self.openDevs_[which.namespace] = {};
    }
    self.openDevs_[which.namespace][which.device] = gnubby;
    while (self.pendingOpens_[which.namespace][which.device].length != 0) {
      var client = self.pendingOpens_[which.namespace][which.device].shift();
      opened(gnubby, client.who, client.cb);
    }
    delete self.pendingOpens_[which.namespace][which.device];
  }

  if (this.openDevs_[which.namespace] &&
      this.openDevs_[which.namespace].hasOwnProperty(which.device)) {
    var gnubby = this.openDevs_[which.namespace][which.device];
    opened(gnubby, who, cb);
  } else {
    var opener = {who: who, cb: cb};
    if (!this.pendingOpens_.hasOwnProperty(which.namespace)) {
      this.pendingOpens_[which.namespace] = {};
    }
    if (this.pendingOpens_[which.namespace].hasOwnProperty(which.device)) {
      this.pendingOpens_[which.namespace][which.device].push(opener);
    } else {
      this.pendingOpens_[which.namespace][which.device] = [opener];
      var openImpl = this.impl_[which.namespace].open;
      openImpl(this, which.device, dev, openCb);
    }
  }
};

/**
 * Removes a client from a low-level gnubby.
 * @param {GnubbyDevice} whichDev The gnubby.
 * @param {*} who The client.
 */
Gnubbies.prototype.removeClient = function(whichDev, who) {
  console.log(UTIL_fmt('Gnubbies.removeClient()'));

  this.resetInactivityTimer();

  // De-register client from all known devices.
  for (var namespace in this.openDevs_) {
    for (var devId in this.openDevs_[namespace]) {
      var deviceId = Number(devId);
      if (isNaN(deviceId))
        deviceId = devId;
      var dev = this.openDevs_[namespace][deviceId];
      if (dev.hasClient(who)) {
        if (whichDev && dev != whichDev) {
          console.warn('Gnubby attached to more than one device!?');
        }
        if (!dev.deregisterClient(who)) {
          dev.destroy();
        }
      }
    }
  }
};