signal-desktop/libtextsecure/websocket-resources.js

244 lines
7.1 KiB
JavaScript
Raw Normal View History

2018-07-21 21:51:20 +00:00
/* global window, dcodeIO, Event, textsecure, FileReader, WebSocketResource */
2018-07-21 21:51:20 +00:00
// eslint-disable-next-line func-names
(function() {
2018-05-02 16:51:22 +00:00
/*
* WebSocket-Resources
*
* Create a request-response interface over websockets using the
* WebSocket-Resources sub-protocol[1].
*
* var client = new WebSocketResource(socket, function(request) {
* request.respond(200, 'OK');
* });
*
* client.sendRequest({
* verb: 'PUT',
* path: '/v1/messages',
* body: '{ some: "json" }',
* success: function(message, status, request) {...},
* error: function(message, status, request) {...}
* });
*
* 1. https://github.com/signalapp/WebSocket-Resources
*
*/
2018-07-21 21:51:20 +00:00
const Request = function Request(options) {
2018-05-02 16:51:22 +00:00
this.verb = options.verb || options.type;
this.path = options.path || options.url;
this.headers = options.headers;
2018-05-02 16:51:22 +00:00
this.body = options.body || options.data;
this.success = options.success;
this.error = options.error;
this.id = options.id;
if (this.id === undefined) {
2018-07-21 21:51:20 +00:00
const bits = new Uint32Array(2);
2018-05-02 16:51:22 +00:00
window.crypto.getRandomValues(bits);
this.id = dcodeIO.Long.fromBits(bits[0], bits[1], true);
}
2018-05-02 16:51:22 +00:00
if (this.body === undefined) {
this.body = null;
}
};
2018-07-21 21:51:20 +00:00
const IncomingWebSocketRequest = function IncomingWebSocketRequest(options) {
const request = new Request(options);
const { socket } = options;
2018-05-02 16:51:22 +00:00
this.verb = request.verb;
this.path = request.path;
this.body = request.body;
this.headers = request.headers;
2018-05-02 16:51:22 +00:00
2018-07-21 21:51:20 +00:00
this.respond = (status, message) => {
2018-05-02 16:51:22 +00:00
socket.send(
new textsecure.protobuf.WebSocketMessage({
type: textsecure.protobuf.WebSocketMessage.Type.RESPONSE,
2018-07-21 21:51:20 +00:00
response: { id: request.id, message, status },
2018-05-02 16:51:22 +00:00
})
.encode()
.toArrayBuffer()
);
};
2018-05-02 16:51:22 +00:00
};
2018-07-21 21:51:20 +00:00
const outgoing = {};
const OutgoingWebSocketRequest = function OutgoingWebSocketRequest(
options,
socket
) {
const request = new Request(options);
2018-05-02 16:51:22 +00:00
outgoing[request.id] = request;
socket.send(
new textsecure.protobuf.WebSocketMessage({
type: textsecure.protobuf.WebSocketMessage.Type.REQUEST,
request: {
verb: request.verb,
path: request.path,
body: request.body,
headers: request.headers,
2018-05-02 16:51:22 +00:00
id: request.id,
},
})
.encode()
.toArrayBuffer()
);
};
2018-07-21 21:51:20 +00:00
window.WebSocketResource = function WebSocketResource(socket, opts = {}) {
let { handleRequest } = opts;
2018-05-02 16:51:22 +00:00
if (typeof handleRequest !== 'function') {
2018-07-21 21:51:20 +00:00
handleRequest = request => request.respond(404, 'Not found');
2018-05-02 16:51:22 +00:00
}
2018-07-21 21:51:20 +00:00
this.sendRequest = options => new OutgoingWebSocketRequest(options, socket);
2018-07-21 21:51:20 +00:00
// eslint-disable-next-line no-param-reassign
socket.onmessage = socketMessage => {
const blob = socketMessage.data;
const handleArrayBuffer = buffer => {
const message = textsecure.protobuf.WebSocketMessage.decode(buffer);
2018-05-02 16:51:22 +00:00
if (
message.type === textsecure.protobuf.WebSocketMessage.Type.REQUEST
) {
handleRequest(
new IncomingWebSocketRequest({
verb: message.request.verb,
path: message.request.path,
body: message.request.body,
headers: message.request.headers,
2018-05-02 16:51:22 +00:00
id: message.request.id,
2018-07-21 21:51:20 +00:00
socket,
2018-05-02 16:51:22 +00:00
})
);
} else if (
message.type === textsecure.protobuf.WebSocketMessage.Type.RESPONSE
) {
2018-07-21 21:51:20 +00:00
const { response } = message;
const request = outgoing[response.id];
2018-05-02 16:51:22 +00:00
if (request) {
request.response = response;
2018-07-21 21:51:20 +00:00
let callback = request.error;
2018-05-02 16:51:22 +00:00
if (response.status >= 200 && response.status < 300) {
callback = request.success;
}
2018-05-02 16:51:22 +00:00
if (typeof callback === 'function') {
callback(response.message, response.status, request);
}
2018-05-02 16:51:22 +00:00
} else {
2018-07-21 21:51:20 +00:00
throw new Error(
`Received response for unknown request ${message.response.id}`
);
2018-05-02 16:51:22 +00:00
}
}
};
if (blob instanceof ArrayBuffer) {
handleArrayBuffer(blob);
} else {
2018-07-21 21:51:20 +00:00
const reader = new FileReader();
reader.onload = () => handleArrayBuffer(reader.result);
2018-05-02 16:51:22 +00:00
reader.readAsArrayBuffer(blob);
}
};
2018-05-02 16:51:22 +00:00
if (opts.keepalive) {
this.keepalive = new KeepAlive(this, {
path: opts.keepalive.path,
disconnect: opts.keepalive.disconnect,
});
2018-07-21 21:51:20 +00:00
const resetKeepAliveTimer = this.keepalive.reset.bind(this.keepalive);
2018-05-02 16:51:22 +00:00
socket.addEventListener('open', resetKeepAliveTimer);
socket.addEventListener('message', resetKeepAliveTimer);
socket.addEventListener(
'close',
this.keepalive.stop.bind(this.keepalive)
);
}
2018-07-21 21:51:20 +00:00
socket.addEventListener('close', () => {
this.closed = true;
});
2018-05-02 16:51:22 +00:00
2018-07-21 21:51:20 +00:00
this.close = (code = 3000, reason) => {
2018-05-02 16:51:22 +00:00
if (this.closed) {
return;
}
window.log.info('WebSocketResource.close()');
2018-05-02 16:51:22 +00:00
if (this.keepalive) {
this.keepalive.stop();
}
socket.close(code, reason);
2018-07-21 21:51:20 +00:00
// eslint-disable-next-line no-param-reassign
2018-05-02 16:51:22 +00:00
socket.onmessage = null;
// On linux the socket can wait a long time to emit its close event if we've
// lost the internet connection. On the order of minutes. This speeds that
// process up.
2018-07-21 21:51:20 +00:00
setTimeout(() => {
if (this.closed) {
return;
}
this.closed = true;
window.log.warn('Dispatching our own socket close event');
const ev = new Event('close');
ev.code = code;
ev.reason = reason;
this.dispatchEvent(ev);
}, 1000);
};
2018-05-02 16:51:22 +00:00
};
window.WebSocketResource.prototype = new textsecure.EventTarget();
2018-07-21 21:51:20 +00:00
function KeepAlive(websocketResource, opts = {}) {
2018-05-02 16:51:22 +00:00
if (websocketResource instanceof WebSocketResource) {
this.path = opts.path;
if (this.path === undefined) {
this.path = '/';
}
this.disconnect = opts.disconnect;
if (this.disconnect === undefined) {
this.disconnect = true;
}
this.wsr = websocketResource;
} else {
throw new TypeError('KeepAlive expected a WebSocketResource');
}
}
KeepAlive.prototype = {
constructor: KeepAlive,
2018-07-21 21:51:20 +00:00
stop() {
2018-05-02 16:51:22 +00:00
clearTimeout(this.keepAliveTimer);
clearTimeout(this.disconnectTimer);
},
2018-07-21 21:51:20 +00:00
reset() {
2018-05-02 16:51:22 +00:00
clearTimeout(this.keepAliveTimer);
clearTimeout(this.disconnectTimer);
2018-07-21 21:51:20 +00:00
this.keepAliveTimer = setTimeout(() => {
if (this.disconnect) {
// automatically disconnect if server doesn't ack
this.disconnectTimer = setTimeout(() => {
clearTimeout(this.keepAliveTimer);
this.wsr.close(3001, 'No response to keepalive request');
}, 1000);
} else {
this.reset();
}
window.log.info('Sending a keepalive message');
this.wsr.sendRequest({
verb: 'GET',
path: this.path,
success: this.reset.bind(this),
});
}, 55000);
2018-05-02 16:51:22 +00:00
},
};
})();