From 46dfb3489bcdf652c882d1d686e6511a25ff9291 Mon Sep 17 00:00:00 2001 From: Audric Ackermann Date: Tue, 19 Jan 2021 16:01:53 +1100 Subject: [PATCH] remove mock sockets and websockets unused resources --- Gruntfile.js | 2 - components/mock-socket/dist/mock-socket.js | 635 ------------------ js/background.js | 2 - libtextsecure/crypto.js | 36 - libtextsecure/message_receiver.js | 23 +- libtextsecure/test/.eslintrc | 4 +- libtextsecure/test/_test.js | 2 - libtextsecure/test/index.html | 2 - .../test/websocket-resources_test.js | 214 ------ libtextsecure/websocket-resources.js | 243 ------- mockup_servers/http_server.py | 62 -- mockup_servers/readme.md | 6 - mockup_servers/socket_server.py | 53 -- test/.eslintrc.js | 2 - ts/components/session/ActionsPanel.tsx | 3 + .../conversation/SessionConversation.tsx | 12 +- 16 files changed, 13 insertions(+), 1288 deletions(-) delete mode 100644 components/mock-socket/dist/mock-socket.js delete mode 100644 libtextsecure/test/websocket-resources_test.js delete mode 100644 libtextsecure/websocket-resources.js delete mode 100644 mockup_servers/http_server.py delete mode 100644 mockup_servers/readme.md delete mode 100644 mockup_servers/socket_server.py diff --git a/Gruntfile.js b/Gruntfile.js index a9cdc8b1e..84b39b7bb 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -87,7 +87,6 @@ module.exports = grunt => { 'libtextsecure/stringview.js', 'libtextsecure/event_target.js', 'libtextsecure/account_manager.js', - 'libtextsecure/websocket-resources.js', 'libtextsecure/http-resources.js', 'libtextsecure/message_receiver.js', 'libtextsecure/contacts_parser.js', @@ -115,7 +114,6 @@ module.exports = grunt => { libtextsecuretest: { src: [ 'node_modules/jquery/dist/jquery.js', - 'components/mock-socket/dist/mock-socket.js', 'node_modules/mocha/mocha.js', 'node_modules/chai/chai.js', 'libtextsecure/test/_test.js', diff --git a/components/mock-socket/dist/mock-socket.js b/components/mock-socket/dist/mock-socket.js deleted file mode 100644 index 9ff39d924..000000000 --- a/components/mock-socket/dist/mock-socket.js +++ /dev/null @@ -1,635 +0,0 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 3 ? '/' : '') + url.slice(3, url.length).join('/').split('?')[0].split('#')[0]); - var _p = _l.pathname; - - if (_p.charAt(_p.length-1) === '/') { _p=_p.substring(0, _p.length-1); } - var _h = _l.hostname, _hs = _h.split('.'), _ps = _p.split('/'); - - if (arg === 'hostname') { return _h; } - else if (arg === 'domain') { - if (/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/.test(_h)) { return _h; } - return _hs.slice(-2).join('.'); - } - //else if (arg === 'tld') { return _hs.slice(-1).join('.'); } - else if (arg === 'sub') { return _hs.slice(0, _hs.length - 2).join('.'); } - else if (arg === 'port') { return _l.port; } - else if (arg === 'protocol') { return _l.protocol.split(':')[0]; } - else if (arg === 'auth') { return _l.auth; } - else if (arg === 'user') { return _l.auth.split(':')[0]; } - else if (arg === 'pass') { return _l.auth.split(':')[1] || ''; } - else if (arg === 'path') { return _l.pathname; } - else if (arg.charAt(0) === '.') { - arg = arg.substring(1); - if(isNumeric(arg)) {arg = parseInt(arg, 10); return _hs[arg < 0 ? _hs.length + arg : arg-1] || ''; } - } - else if (isNumeric(arg)) { arg = parseInt(arg, 10); return _ps[arg < 0 ? _ps.length + arg : arg] || ''; } - else if (arg === 'file') { return _ps.slice(-1)[0]; } - else if (arg === 'filename') { return _ps.slice(-1)[0].split('.')[0]; } - else if (arg === 'fileext') { return _ps.slice(-1)[0].split('.')[1] || ''; } - else if (arg.charAt(0) === '?' || arg.charAt(0) === '#') { - var params = _ls, param = null; - - if(arg.charAt(0) === '?') { params = (params.split('?')[1] || '').split('#')[0]; } - else if(arg.charAt(0) === '#') { params = (params.split('#')[1] || ''); } - - if(!arg.charAt(1)) { return params; } - - arg = arg.substring(1); - params = params.split('&'); - - for(var i=0,ii=params.length; i= 0 && newReadyState <= 4) { - this.readyState = newReadyState; - } - } -}; - -module.exports = MockSocket; - -},{"./helpers/delay":2,"./helpers/global-context":3,"./helpers/message-event":4,"./helpers/url-transform":5,"./helpers/websocket-properties":6}],9:[function(require,module,exports){ -var socketMessageEvent = require('./helpers/message-event'); -var globalContext = require('./helpers/global-context'); - -function SocketService() { - this.list = {}; -} - -SocketService.prototype = { - server: null, - - /* - * This notifies the mock server that a client is connecting and also sets up - * the ready state observer. - * - * @param {client: object} the context of the client - * @param {readyStateFunction: function} the function that will be invoked on a ready state change - */ - clientIsConnecting: function(client, readyStateFunction) { - this.observe('updateReadyState', readyStateFunction, client); - - // if the server has not been set then we notify the onclose method of this client - if(!this.server) { - this.notify(client, 'updateReadyState', globalContext.MockSocket.CLOSED); - this.notifyOnlyFor(client, 'clientOnError'); - return false; - } - - this.notifyOnlyFor(client, 'updateReadyState', globalContext.MockSocket.OPEN); - this.notify('clientHasJoined', this.server); - this.notifyOnlyFor(client, 'clientOnOpen', socketMessageEvent('open', null, this.server.url)); - }, - - /* - * Closes a connection from the server's perspective. This should - * close all clients. - * - * @param {messageEvent: object} the mock message event. - */ - closeConnectionFromServer: function(messageEvent) { - this.notify('updateReadyState', globalContext.MockSocket.CLOSING); - this.notify('clientOnclose', messageEvent); - this.notify('updateReadyState', globalContext.MockSocket.CLOSED); - this.notify('clientHasLeft'); - }, - - /* - * Closes a connection from the clients perspective. This - * should only close the client who initiated the close and not - * all of the other clients. - * - * @param {messageEvent: object} the mock message event. - * @param {client: object} the context of the client - */ - closeConnectionFromClient: function(messageEvent, client) { - if(client.readyState === globalContext.MockSocket.OPEN) { - this.notifyOnlyFor(client, 'updateReadyState', globalContext.MockSocket.CLOSING); - this.notifyOnlyFor(client, 'clientOnclose', messageEvent); - this.notifyOnlyFor(client, 'updateReadyState', globalContext.MockSocket.CLOSED); - this.notify('clientHasLeft'); - } - }, - - - /* - * Notifies the mock server that a client has sent a message. - * - * @param {messageEvent: object} the mock message event. - */ - sendMessageToServer: function(messageEvent) { - this.notify('clientHasSentMessage', messageEvent.data, messageEvent); - }, - - /* - * Notifies all clients that the server has sent a message - * - * @param {messageEvent: object} the mock message event. - */ - sendMessageToClients: function(messageEvent) { - this.notify('clientOnMessage', messageEvent); - }, - - /* - * Setup the callback function observers for both the server and client. - * - * @param {observerKey: string} either: connection, message or close - * @param {callback: function} the callback to be invoked - * @param {server: object} the context of the server - */ - setCallbackObserver: function(observerKey, callback, server) { - this.observe(observerKey, callback, server); - }, - - /* - * Binds a callback to a namespace. If notify is called on a namespace all "observers" will be - * fired with the context that is passed in. - * - * @param {namespace: string} - * @param {callback: function} - * @param {context: object} - */ - observe: function(namespace, callback, context) { - - // Make sure the arguments are of the correct type - if( typeof namespace !== 'string' || typeof callback !== 'function' || (context && typeof context !== 'object')) { - return false; - } - - // If a namespace has not been created before then we need to "initialize" the namespace - if(!this.list[namespace]) { - this.list[namespace] = []; - } - - this.list[namespace].push({callback: callback, context: context}); - }, - - /* - * Remove all observers from a given namespace. - * - * @param {namespace: string} The namespace to clear. - */ - clearAll: function(namespace) { - - if(!this.verifyNamespaceArg(namespace)) { - return false; - } - - this.list[namespace] = []; - }, - - /* - * Notify all callbacks that have been bound to the given namespace. - * - * @param {namespace: string} The namespace to notify observers on. - * @param {namespace: url} The url to notify observers on. - */ - notify: function(namespace) { - - // This strips the namespace from the list of args as we dont want to pass that into the callback. - var argumentsForCallback = Array.prototype.slice.call(arguments, 1); - - if(!this.verifyNamespaceArg(namespace)) { - return false; - } - - // Loop over all of the observers and fire the callback function with the context. - for(var i = 0, len = this.list[namespace].length; i < len; i++) { - this.list[namespace][i].callback.apply(this.list[namespace][i].context, argumentsForCallback); - } - }, - - /* - * Notify only the callback of the given context and namespace. - * - * @param {context: object} the context to match against. - * @param {namespace: string} The namespace to notify observers on. - */ - notifyOnlyFor: function(context, namespace) { - - // This strips the namespace from the list of args as we dont want to pass that into the callback. - var argumentsForCallback = Array.prototype.slice.call(arguments, 2); - - if(!this.verifyNamespaceArg(namespace)) { - return false; - } - - // Loop over all of the observers and fire the callback function with the context. - for(var i = 0, len = this.list[namespace].length; i < len; i++) { - if(this.list[namespace][i].context === context) { - this.list[namespace][i].callback.apply(this.list[namespace][i].context, argumentsForCallback); - } - } - }, - - /* - * Verifies that the namespace is valid. - * - * @param {namespace: string} The namespace to verify. - */ - verifyNamespaceArg: function(namespace) { - if(typeof namespace !== 'string' || !this.list[namespace]) { - return false; - } - - return true; - } -}; - -module.exports = SocketService; - -},{"./helpers/global-context":3,"./helpers/message-event":4}]},{},[1]); diff --git a/js/background.js b/js/background.js index e4108818d..742fbea72 100644 --- a/js/background.js +++ b/js/background.js @@ -170,7 +170,6 @@ return; } const ourKey = textsecure.storage.user.getNumber(); - window.feeds = []; window.lokiMessageAPI = new window.LokiMessageAPI(); // singleton to relay events to libtextsecure/message_receiver window.lokiPublicChatAPI = new window.LokiPublicChatAPI(ourKey); @@ -1117,7 +1116,6 @@ window.getDefaultFileServer() ); window.lokiPublicChatAPI = null; - window.feeds = []; messageReceiver = new textsecure.MessageReceiver(); messageReceiver.addEventListener( 'message', diff --git a/libtextsecure/crypto.js b/libtextsecure/crypto.js index 7183330a9..4d0f115e5 100644 --- a/libtextsecure/crypto.js +++ b/libtextsecure/crypto.js @@ -30,42 +30,6 @@ window.textsecure = window.textsecure || {}; window.textsecure.crypto = { - // Decrypts message into a raw string - decryptWebsocketMessage(message, signalingKey) { - const decodedMessage = message.toArrayBuffer(); - - if (signalingKey.byteLength !== 52) { - throw new Error('Got invalid length signalingKey'); - } - if (decodedMessage.byteLength < 1 + 16 + 10) { - throw new Error('Got invalid length message'); - } - if (new Uint8Array(decodedMessage)[0] !== 1) { - throw new Error(`Got bad version number: ${decodedMessage[0]}`); - } - - const aesKey = signalingKey.slice(0, 32); - const macKey = signalingKey.slice(32, 32 + 20); - - const iv = decodedMessage.slice(1, 1 + 16); - const ciphertext = decodedMessage.slice( - 1 + 16, - decodedMessage.byteLength - 10 - ); - const ivAndCiphertext = decodedMessage.slice( - 0, - decodedMessage.byteLength - 10 - ); - const mac = decodedMessage.slice( - decodedMessage.byteLength - 10, - decodedMessage.byteLength - ); - - return verifyMAC(ivAndCiphertext, macKey, mac, 10).then(() => - decrypt(aesKey, ciphertext, iv) - ); - }, - decryptAttachment(encryptedBin, keys, theirDigest) { if (keys.byteLength !== 64) { throw new Error('Got invalid length attachment keys'); diff --git a/libtextsecure/message_receiver.js b/libtextsecure/message_receiver.js index 40615e6d5..f52030485 100644 --- a/libtextsecure/message_receiver.js +++ b/libtextsecure/message_receiver.js @@ -4,7 +4,6 @@ /* global Event: false */ /* global dcodeIO: false */ /* global lokiPublicChatAPI: false */ -/* global feeds: false */ /* eslint-disable more/no-then */ /* eslint-disable no-unreachable */ @@ -63,10 +62,6 @@ MessageReceiver.prototype.extend({ if (lokiPublicChatAPI) { lokiPublicChatAPI.open(); } - // set up pollers for any RSS feeds - feeds.forEach(feed => { - feed.on('rssMessage', window.NewReceiver.handleUnencryptedMessage); - }); // Ensures that an immediate 'empty' event from the websocket will fire only after // all cached envelopes are processed. @@ -87,21 +82,9 @@ MessageReceiver.prototype.extend({ await lokiPublicChatAPI.close(); } }, - onopen() { - window.log.info('websocket open'); - }, - onerror() { - window.log.error('websocket error'); - }, - onclose(ev) { - window.log.info( - 'websocket closed', - ev.code, - ev.reason || '', - 'calledClose:', - this.calledClose - ); - }, + onopen() {}, + onerror() {}, + onclose() {}, }); window.textsecure = window.textsecure || {}; diff --git a/libtextsecure/test/.eslintrc b/libtextsecure/test/.eslintrc index d27f42a0b..82a0b4304 100644 --- a/libtextsecure/test/.eslintrc +++ b/libtextsecure/test/.eslintrc @@ -17,9 +17,7 @@ "dcodeIO": true, "getString": true, "hexToArrayBuffer": true, - "MockServer": true, - "MockSocket": true, "PROTO_ROOT": true, "stringToArrayBuffer": true, } -} +} \ No newline at end of file diff --git a/libtextsecure/test/_test.js b/libtextsecure/test/_test.js index 7edd32586..e6df55a87 100644 --- a/libtextsecure/test/_test.js +++ b/libtextsecure/test/_test.js @@ -59,5 +59,3 @@ window.hexToArrayBuffer = str => { } return ret; }; - -window.MockSocket.prototype.addEventListener = () => null; diff --git a/libtextsecure/test/index.html b/libtextsecure/test/index.html index 216b6c465..20d44b38f 100644 --- a/libtextsecure/test/index.html +++ b/libtextsecure/test/index.html @@ -24,7 +24,6 @@ - @@ -34,7 +33,6 @@ - diff --git a/libtextsecure/test/websocket-resources_test.js b/libtextsecure/test/websocket-resources_test.js deleted file mode 100644 index 4ce99ddd4..000000000 --- a/libtextsecure/test/websocket-resources_test.js +++ /dev/null @@ -1,214 +0,0 @@ -/* global textsecure, WebSocketResource */ - -describe('WebSocket-Resource', () => { - describe('requests and responses', () => { - it('receives requests and sends responses', done => { - // mock socket - const requestId = '1'; - const socket = { - send(data) { - const message = textsecure.protobuf.WebSocketMessage.decode(data); - assert.strictEqual( - message.type, - textsecure.protobuf.WebSocketMessage.Type.RESPONSE - ); - assert.strictEqual(message.response.message, 'OK'); - assert.strictEqual(message.response.status, 200); - assert.strictEqual(message.response.id.toString(), requestId); - done(); - }, - addEventListener() {}, - }; - - // actual test - this.resource = new WebSocketResource(socket, { - handleRequest(request) { - assert.strictEqual(request.verb, 'PUT'); - assert.strictEqual(request.path, '/some/path'); - assertEqualArrayBuffers( - request.body.toArrayBuffer(), - new Uint8Array([1, 2, 3]).buffer - ); - request.respond(200, 'OK'); - }, - }); - - // mock socket request - socket.onmessage({ - data: new Blob([ - new textsecure.protobuf.WebSocketMessage({ - type: textsecure.protobuf.WebSocketMessage.Type.REQUEST, - request: { - id: requestId, - verb: 'PUT', - path: '/some/path', - body: new Uint8Array([1, 2, 3]).buffer, - }, - }) - .encode() - .toArrayBuffer(), - ]), - }); - }); - - it('sends requests and receives responses', done => { - // mock socket and request handler - let requestId; - const socket = { - send(data) { - const message = textsecure.protobuf.WebSocketMessage.decode(data); - assert.strictEqual( - message.type, - textsecure.protobuf.WebSocketMessage.Type.REQUEST - ); - assert.strictEqual(message.request.verb, 'PUT'); - assert.strictEqual(message.request.path, '/some/path'); - assertEqualArrayBuffers( - message.request.body.toArrayBuffer(), - new Uint8Array([1, 2, 3]).buffer - ); - requestId = message.request.id; - }, - addEventListener() {}, - }; - - // actual test - const resource = new WebSocketResource(socket); - resource.sendRequest({ - verb: 'PUT', - path: '/some/path', - body: new Uint8Array([1, 2, 3]).buffer, - error: done, - success(message, status) { - assert.strictEqual(message, 'OK'); - assert.strictEqual(status, 200); - done(); - }, - }); - - // mock socket response - socket.onmessage({ - data: new Blob([ - new textsecure.protobuf.WebSocketMessage({ - type: textsecure.protobuf.WebSocketMessage.Type.RESPONSE, - response: { id: requestId, message: 'OK', status: 200 }, - }) - .encode() - .toArrayBuffer(), - ]), - }); - }); - }); - - describe('close', () => { - before(() => { - window.WebSocket = MockSocket; - }); - after(() => { - window.WebSocket = WebSocket; - }); - it('closes the connection', done => { - const mockServer = new MockServer('ws://localhost:8081'); - mockServer.on('connection', server => { - server.on('close', done); - }); - const resource = new WebSocketResource( - new WebSocket('ws://localhost:8081') - ); - resource.close(); - }); - }); - - describe.skip('with a keepalive config', function thisNeeded() { - before(() => { - window.WebSocket = MockSocket; - }); - after(() => { - window.WebSocket = WebSocket; - }); - this.timeout(60000); - it('sends keepalives once a minute', done => { - const mockServer = new MockServer('ws://localhost:8081'); - mockServer.on('connection', server => { - server.on('message', data => { - const message = textsecure.protobuf.WebSocketMessage.decode(data); - assert.strictEqual( - message.type, - textsecure.protobuf.WebSocketMessage.Type.REQUEST - ); - assert.strictEqual(message.request.verb, 'GET'); - assert.strictEqual(message.request.path, '/v1/keepalive'); - server.close(); - done(); - }); - }); - this.resource = new WebSocketResource( - new WebSocket('ws://loc1alhost:8081'), - { - keepalive: { path: '/v1/keepalive' }, - } - ); - }); - - it('uses / as a default path', done => { - const mockServer = new MockServer('ws://localhost:8081'); - mockServer.on('connection', server => { - server.on('message', data => { - const message = textsecure.protobuf.WebSocketMessage.decode(data); - assert.strictEqual( - message.type, - textsecure.protobuf.WebSocketMessage.Type.REQUEST - ); - assert.strictEqual(message.request.verb, 'GET'); - assert.strictEqual(message.request.path, '/'); - server.close(); - done(); - }); - }); - this.resource = new WebSocketResource( - new WebSocket('ws://localhost:8081'), - { - keepalive: true, - } - ); - }); - - it('optionally disconnects if no response', function thisNeeded1(done) { - this.timeout(65000); - const mockServer = new MockServer('ws://localhost:8081'); - const socket = new WebSocket('ws://localhost:8081'); - mockServer.on('connection', server => { - server.on('close', done); - }); - this.resource = new WebSocketResource(socket, { keepalive: true }); - }); - - it('allows resetting the keepalive timer', function thisNeeded2(done) { - this.timeout(65000); - const mockServer = new MockServer('ws://localhost:8081'); - const socket = new WebSocket('ws://localhost:8081'); - const startTime = Date.now(); - mockServer.on('connection', server => { - server.on('message', data => { - const message = textsecure.protobuf.WebSocketMessage.decode(data); - assert.strictEqual( - message.type, - textsecure.protobuf.WebSocketMessage.Type.REQUEST - ); - assert.strictEqual(message.request.verb, 'GET'); - assert.strictEqual(message.request.path, '/'); - assert( - Date.now() > startTime + 60000, - 'keepalive time should be longer than a minute' - ); - server.close(); - done(); - }); - }); - const resource = new WebSocketResource(socket, { keepalive: true }); - setTimeout(() => { - resource.resetKeepAliveTimer(); - }, 5000); - }); - }); -}); diff --git a/libtextsecure/websocket-resources.js b/libtextsecure/websocket-resources.js deleted file mode 100644 index 0d8473695..000000000 --- a/libtextsecure/websocket-resources.js +++ /dev/null @@ -1,243 +0,0 @@ -/* global window, dcodeIO, Event, textsecure, FileReader, WebSocketResource */ - -// eslint-disable-next-line func-names -(function() { - /* - * 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 - * - */ - - const Request = function Request(options) { - this.verb = options.verb || options.type; - this.path = options.path || options.url; - this.headers = options.headers; - this.body = options.body || options.data; - this.success = options.success; - this.error = options.error; - this.id = options.id; - - if (this.id === undefined) { - const bits = new Uint32Array(2); - window.crypto.getRandomValues(bits); - this.id = dcodeIO.Long.fromBits(bits[0], bits[1], true); - } - - if (this.body === undefined) { - this.body = null; - } - }; - - const IncomingWebSocketRequest = function IncomingWebSocketRequest(options) { - const request = new Request(options); - const { socket } = options; - - this.verb = request.verb; - this.path = request.path; - this.body = request.body; - this.headers = request.headers; - - this.respond = (status, message) => { - socket.send( - new textsecure.protobuf.WebSocketMessage({ - type: textsecure.protobuf.WebSocketMessage.Type.RESPONSE, - response: { id: request.id, message, status }, - }) - .encode() - .toArrayBuffer() - ); - }; - }; - - const outgoing = {}; - const OutgoingWebSocketRequest = function OutgoingWebSocketRequest( - options, - socket - ) { - const request = new Request(options); - 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, - id: request.id, - }, - }) - .encode() - .toArrayBuffer() - ); - }; - - window.WebSocketResource = function WebSocketResource(socket, opts = {}) { - let { handleRequest } = opts; - if (typeof handleRequest !== 'function') { - handleRequest = request => request.respond(404, 'Not found'); - } - this.sendRequest = options => new OutgoingWebSocketRequest(options, socket); - - // eslint-disable-next-line no-param-reassign - socket.onmessage = socketMessage => { - const blob = socketMessage.data; - const handleArrayBuffer = buffer => { - const message = textsecure.protobuf.WebSocketMessage.decode(buffer); - 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, - id: message.request.id, - socket, - }) - ); - } else if ( - message.type === textsecure.protobuf.WebSocketMessage.Type.RESPONSE - ) { - const { response } = message; - const request = outgoing[response.id]; - if (request) { - request.response = response; - let callback = request.error; - if (response.status >= 200 && response.status < 300) { - callback = request.success; - } - - if (typeof callback === 'function') { - callback(response.message, response.status, request); - } - } else { - throw new Error( - `Received response for unknown request ${message.response.id}` - ); - } - } - }; - - if (blob instanceof ArrayBuffer) { - handleArrayBuffer(blob); - } else { - const reader = new FileReader(); - reader.onload = () => handleArrayBuffer(reader.result); - reader.readAsArrayBuffer(blob); - } - }; - - if (opts.keepalive) { - this.keepalive = new KeepAlive(this, { - path: opts.keepalive.path, - disconnect: opts.keepalive.disconnect, - }); - const resetKeepAliveTimer = this.keepalive.reset.bind(this.keepalive); - socket.addEventListener('open', resetKeepAliveTimer); - socket.addEventListener('message', resetKeepAliveTimer); - socket.addEventListener( - 'close', - this.keepalive.stop.bind(this.keepalive) - ); - } - - socket.addEventListener('close', () => { - this.closed = true; - }); - - this.close = (code = 3000, reason) => { - if (this.closed) { - return; - } - - window.log.info('WebSocketResource.close()'); - if (this.keepalive) { - this.keepalive.stop(); - } - - socket.close(code, reason); - // eslint-disable-next-line no-param-reassign - 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. - 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); - }; - }; - window.WebSocketResource.prototype = new textsecure.EventTarget(); - - function KeepAlive(websocketResource, opts = {}) { - 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, - stop() { - clearTimeout(this.keepAliveTimer); - clearTimeout(this.disconnectTimer); - }, - reset() { - clearTimeout(this.keepAliveTimer); - clearTimeout(this.disconnectTimer); - 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); - }, - }; -})(); diff --git a/mockup_servers/http_server.py b/mockup_servers/http_server.py deleted file mode 100644 index dd47bf598..000000000 --- a/mockup_servers/http_server.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -import time -from http.server import BaseHTTPRequestHandler, HTTPServer - -# HTTPRequestHandler class -class testHTTPServer_RequestHandler(BaseHTTPRequestHandler): - def do_POST(self): - print('got POST request to ' + self.path) - # add some latency - time.sleep(2) - # Send response status code - self.send_response(201) - - # Send headers - #self.send_header() - self.end_headers() - - #message = self.rfile.read(int(self.headers.get('Content-Length'))).decode('UTF-8') - length = self.headers.get('Content-Length') - for (k,v) in self.headers.items(): - print(k + ':' + v) - if length: - print ('length: ' + self.headers.get('Content-Length')) - message = self.rfile.read(int(length)) - - array = [] - for k in message: - array += [k] - print(array) - # Send message back to client - #message = "ok" - # Write content as utf-8 data - #self.wfile.write(bytes(message, "utf8")) - - # GET - def do_GET(self): - # Send response status code - time.sleep(1) - self.send_response(200) - - # Send headers - self.send_header('Content-type','text/html') - self.end_headers() - - # Send message back to client - message = "Hello world!" - # Write content as utf-8 data - self.wfile.write(bytes(message, "utf8")) - return - -def run(): - print('starting server...') - - # Server settings - # Choose port 8080, for port 80, which is normally used for a http server, you need root access - server_address = ('127.0.0.1', 80) - httpd = HTTPServer(server_address, testHTTPServer_RequestHandler) - print('running server...') - httpd.serve_forever() - - -run() \ No newline at end of file diff --git a/mockup_servers/readme.md b/mockup_servers/readme.md deleted file mode 100644 index c93419fce..000000000 --- a/mockup_servers/readme.md +++ /dev/null @@ -1,6 +0,0 @@ -http server for mocking up sending message to the server and getting a response back. -websocket server for mocking up opening a connection to receive messages from the server. - -run either server with -`sudo python3