aboutsummaryrefslogtreecommitdiffstats
path: root/extension/background.js
blob: c5938664de14b25e81eb200306e780e7fd881e41 (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
const TESTING = (typeof chrome === 'undefined');

const unix = {
  EPERM: 1,
  ENOENT: 2,
  ESRCH: 3,
  EINTR: 4,
  EIO: 5,
  ENXIO: 6,
  ENOTSUP: 45,

  // Unix file types
  S_IFMT: 0170000, // type of file mask
  S_IFIFO: 010000, // named pipe (fifo)
  S_IFCHR: 020000, // character special
  S_IFDIR: 040000, // directory
  S_IFBLK: 060000, // block special
  S_IFREG: 0100000, // regular
  S_IFLNK: 0120000, // symbolic link
  S_IFSOCK: 0140000, // socket
}

class UnixError extends Error {
  constructor(error) { super(); this.name = "UnixError"; this.error = error; }
}

// tabs/by-id/ID/title
// tabs/by-id/ID/url
// tabs/by-id/ID/console
// tabs/by-id/ID/mem (?)
// tabs/by-id/ID/cpu (?)
// tabs/by-id/ID/screenshot.png
// tabs/by-id/ID/text.txt
// tabs/by-id/ID/printed.pdf
// tabs/by-id/ID/control
// tabs/by-id/ID/sources/

function pathComponent(path, i) {
  const components = path.split('/');
  return components[i >= 0 ? i : components.length + i];
}
function sanitize(s) { return s.replace(/[^A-Za-z0-9_\-\.]/gm, '_'); }
function utf8(str, offset, size) {
  // converts to UTF8, then takes slice
  var utf8 = [];
  for (var i=0; i < str.length; i++) {
    var charcode = str.charCodeAt(i);
    if (charcode < 0x80) utf8.push(charcode);
    else if (charcode < 0x800) {
      utf8.push(0xc0 | (charcode >> 6), 
                0x80 | (charcode & 0x3f));
    }
    else if (charcode < 0xd800 || charcode >= 0xe000) {
      utf8.push(0xe0 | (charcode >> 12), 
                0x80 | ((charcode>>6) & 0x3f), 
                0x80 | (charcode & 0x3f));
    }
    // surrogate pair
    else {
      i++;
      charcode = ((charcode&0x3ff)<<10)|(str.charCodeAt(i)&0x3ff)
      utf8.push(0xf0 | (charcode >>18), 
                0x80 | ((charcode>>12) & 0x3f), 
                0x80 | ((charcode>>6) & 0x3f), 
                0x80 | (charcode & 0x3f));
    }
  }
  return String.fromCharCode(...utf8.slice(offset, offset + size))
}
function stringSize(str) {
  // returns the byte length of an utf8 string
  var s = str.length;
  for (var i=str.length-1; i>=0; i--) {
    var code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s+=2;
    if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
  }
  return s + 1;
}

const debugging = {};
async function debugTab(tabId) {
  if (debugging[tabId]) {
    debugging[tabId] += 1;

  } else {
    await new Promise((resolve, reject) => chrome.debugger.attach({tabId}, "1.3", () => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError);
      } else {
        debugging[tabId] = 1;
        resolve();
      }
    }));
  }
}
function sendDebuggerCommand(tabId, method, commandParams) {
  return new Promise((resolve, reject) =>
    chrome.debugger.sendCommand({tabId}, method, commandParams, result => {
      console.log(method, result);
      if (result) {
        resolve(result);
      } else {
        reject(chrome.runtime.lastError);
      }
    })
  );
}

let lastFocusedWindowId;
browser.windows.getLastFocused().then(window => { lastFocusedWindowId = window.id; });
browser.windows.onFocusChanged.addListener(windowId => {
  if (windowId !== -1) lastFocusedWindowId = windowId;
});

/* if I could specify a custom editor interface for all the routing
   below ... I would highlight the route names in blocks of some color
   that sticks out, and let you collapse them. then you could get a
   view of what the whole filesystem looks like at a glance. */
const router = {};

function withTab(handler) {
  return {
    async getattr({path}) {
      const tab = await browser.tabs.get(parseInt(pathComponent(path, -2)));
      return {
        st_mode: unix.S_IFREG | 0444,
        st_nlink: 1,
        st_size: stringSize(handler(tab))
      };
    },
    async open({path}) { return { fh: 0 }; },
    async read({path, fh, size, offset}) {
      const tab = await browser.tabs.get(parseInt(pathComponent(path, -2)));
      return { buf: utf8(handler(tab), offset, size) };
    }
  };
}
function fromScript(code) {
  return {
    async getattr({path}) {
      const tabId = parseInt(pathComponent(path, -2));
      return {
        st_mode: unix.S_IFREG | 0444,
        st_nlink: 1,
        st_size: stringSize((await browser.tabs.executeScript(tabId, {code}))[0])
      };
    },
    async open({path}) { return { fh: 0 }; },
    async read({path, fh, size, offset}) {
      const tabId = parseInt(pathComponent(path, -2));
      console.log(await browser.tabs.executeScript(tabId, {code})[0]);
      return { buf: utf8(await browser.tabs.executeScript(tabId, {code})[0], offset, size) }
    }
  };
}

router["/tabs/by-id"] = {  
  async readdir() {
    const tabs = await browser.tabs.query({});
    return { entries: tabs.map(tab => String(tab.id)) };
  }
};
router["/tabs/by-id/*/url"] = withTab(tab => tab.url + "\n");
router["/tabs/by-id/*/title"] = withTab(tab => tab.title + "\n");
router["/tabs/by-id/*/text"] = fromScript(`document.body.innerText`);
router["/tabs/by-id/*/screenshot.png"] = {
  async read({path, fh, size, offset}) {
    const tabId = parseInt(pathComponent(path, -2));
    await debugTab(tabId);
    await sendDebuggerCommand(tabId, "Page.enable", {});

    const {data} = await sendDebuggerCommand(tabId, "Page.captureScreenshot");
    return { buf: utf8(atob(data), offset, size) };
  }
};
router["/tabs/by-id/*/resources"] = {
  async opendir({path}) {
    const tabId = parseInt(pathComponent(path, -2));
    await debugTab(tabId);
    return { fh: 0 };
  },
  async readdir({path}) {
    const tabId = parseInt(pathComponent(path, -2));
    const {frameTree} = await sendDebuggerCommand(tabId, "Page.getResourceTree", {});
    return { entries: frameTree.resources.map(r => sanitize(String(r.url).slice(0, 200))) };
  }
};
router["/tabs/by-id/*/resources/*"] = {
  async getattr({path}) {
    // FIXME: cache the file
    const tabId = parseInt(pathComponent(path, -3));
    const suffix = pathComponent(path, -1);

    if (!debugging[tabId]) throw new UnixError(unix.EIO);

    await sendDebuggerCommand(tabId, "Page.enable", {});

    const {frameTree} = await sendDebuggerCommand(tabId, "Page.getResourceTree", {});
    for (let resource of frameTree.resources) {
      const resourceSuffix = sanitize(String(resource.url).slice(0, 200));
      if (resourceSuffix === suffix) {
        let {base64Encoded, content} = await sendDebuggerCommand(tabId, "Page.getResourceContent", {
          frameId: frameTree.frame.id,
          url: resource.url
        });
        if (base64Encoded) {
          content = atob(content);
        }
        return {
          st_mode: unix.S_IFREG | 0444,
          st_nlink: 1,
          st_size: stringSize(content) // FIXME
        };
      }
    }
  },
  async open({path}) {
    // FIXME: cache the file
    return {fh: 3};
  },
  async read({path, fh, size, offset}) {
    const tabId = parseInt(pathComponent(path, -3));
    const suffix = pathComponent(path, -1);

    if (!debugging[tabId]) throw new UnixError(unix.EIO);

    await sendDebuggerCommand(tabId, "Page.enable", {});

    const {frameTree} = await sendDebuggerCommand(tabId, "Page.getResourceTree", {});
    for (let resource of frameTree.resources) {
      const resourceSuffix = sanitize(String(resource.url).slice(0, 200));
      if (resourceSuffix === suffix) {
        let {base64Encoded, content} = await sendDebuggerCommand(tabId, "Page.getResourceContent", {
          frameId: frameTree.frame.id,
          url: resource.url
        });
        return { buf: utf8(base64Encoded ? atob(content) : content, offset, size) };
      }
    }
    throw new UnixError(unix.ENOENT);
  },
  async release({path, fh}) {
    return {};
  }
};

router["/tabs/by-id/*/control"] = {
  // echo remove >> mnt/tabs/by-id/1644/control
  async write({path, buf}) {
    const tabId = parseInt(pathComponent(path, -2));
    const command = buf.trim();
    // can use `discard`, `remove`, `reload`, `goForward`, `goBack`...
    // see https://developer.chrome.com/extensions/tabs
    await new Promise(resolve => chrome.tabs[command](tabId, resolve));
  }
};

router["/tabs/by-title"] = {
  async readdir() {
    const tabs = await browser.tabs.query({});
    return { entries: tabs.map(tab => sanitize(String(tab.title).slice(0, 200)) + "_" + String(tab.id)) };
  }
};
router["/tabs/by-title/*"] = {
  // a symbolic link to /tabs/by-id/[id for this tab]
  async readlink({path}) {
    const parts = path.split("_");
    const id = parts[parts.length - 1];
    return { buf: "../by-id/" + id };
  }
};

router["/tabs/last-focused"] = {
  // a symbolic link to /tabs/by-id/[id for this tab]
  async readlink({path}) {
    const id = (await browser.tabs.query({ active: true, windowId: lastFocusedWindowId }))[0].id;
    return { buf: "by-id/" + id };
  }
}

// Ensure that there are routes for all ancestors. This algorithm is
// probably not correct, but whatever.  I also think it would be
// better to compute this stuff on the fly, so you could patch more
// routes in at runtime, but I need to think a bit about how to make
// that work with wildcards.
for (let key in router) {
  let path = key;
  while (path !== "/") { // walk upward through the path
    path = path.substr(0, path.lastIndexOf("/"));
    if (path == '') path = '/';

    if (!router[path]) {
      // find all direct children
      let children = Object.keys(router)
                           .filter(k => k.startsWith(path) &&
                                      (k.match(/\//g) || []).length ===
                                        (path.match(/\//g) || []).length + 1)
                           .map(k => k.substr((path === '/' ? 0 : path.length) + 1).split('/')[0]);
      children = [...new Set(children)];

      router[path] = { readdir() { return { entries: children }; } };
    }
  }
}
if (TESTING) { // I wish I could color this section with... a pink background, or something.
  const assert = require('assert');
  (async () => {
    assert.deepEqual(await router['/tabs/by-id/*'].readdir(), ['url', 'title', 'text', 'control']);
    assert.deepEqual(await router['/'].readdir(), ['tabs']);
    assert.deepEqual(await router['/tabs'].readdir(), ['by-id', 'by-title']);
    
    assert.deepEqual(findRoute('/tabs/by-id/TABID/url'), router['/tabs/by-id/*/url']);
  })()
}


// fill in default implementations of fs ops
for (let key in router) {
  // if readdir -> directory -> add getattr, opendir, releasedir
  if (router[key].readdir) {
    router[key] = {
      getattr() { 
        return {
          st_mode: unix.S_IFDIR | 0755,
          st_nlink: 3,
          st_size: 0,
        };
      },
      opendir({path}) { return { fh: 0 }; },
      releasedir({path}) { return {}; },
      ...router[key]
    };

  } else if (router[key].readlink) {
    router[key] = {
      async getattr({path}) {
        const st_size = (await this.readlink({path})).length + 1;
        return {
          st_mode: unix.S_IFLNK | 0444,
          st_nlink: 1,
          // You _must_ return correct linkee path length from getattr!
          st_size
        };
      },
      ...router[key]
    };
    
  } else if (router[key].read || router[key].write) {
    router[key] = {
      async getattr() {
        return {
          st_mode: unix.S_IFREG | ((router[key].read && 0444) || (router[key].write && 0222)),
          st_nlink: 1,
          st_size: 100 // FIXME
        };
      },
      open() {
        return { fh: 0 };
      },
      release() {
        return {};
      },
      ...router[key]
    };
  }
}

console.log(router);
function findRoute(path) {
  let pathSegments = path.split("/");
  
  if (pathSegments[pathSegments.length - 1].startsWith("._")) {
    throw new UnixError(unix.ENOTSUP); // Apple Double file for xattrs
  }

  let routingPath = "";
  for (let segment of pathSegments) {
    if (routingPath === "/") { routingPath = ""; }

    if (router[routingPath + "/*"]) {
      routingPath += "/*";
    } else if (router[routingPath + "/" + segment]) {
      routingPath += "/" + segment;
    } else {
      throw new UnixError(unix.ENOENT);
    }
  }
  return router[routingPath];
}

let port;
async function onMessage(req) {
  if (req.buf) req.buf = atob(req.buf);
  console.log('req', req);

  let response = { op: req.op, error: unix.EIO };
  /* console.time(req.op + ':' + req.path);*/
  try {
    response = await findRoute(req.path)[req.op](req);
    response.op = req.op;
    if (response.buf) { response.buf = btoa(response.buf); }

  } catch (e) {
    console.error(e);
    response = {
      op: req.op,
      error: e instanceof UnixError ? e.error : unix.EIO
    }
  }
  /* console.timeEnd(req.op + ':' + req.path);*/

  console.log('resp', response);
  port.postMessage(response);
};

function tryConnect() {
  port = chrome.runtime.connectNative('com.rsnous.tabfs');
  port.onMessage.addListener(onMessage);
  port.onDisconnect.addListener(p => {console.log('disconnect', p)});
}

if (!TESTING) {
  tryConnect();
}