-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathipc.js
More file actions
201 lines (176 loc) · 5.06 KB
/
ipc.js
File metadata and controls
201 lines (176 loc) · 5.06 KB
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
'use strict';
const net = require('net');
const EventEmitter = require('events');
const fetch = require('node-fetch');
const { uuid } = require('../util');
const OPCodes = {
HANDSHAKE: 0,
FRAME: 1,
CLOSE: 2,
PING: 3,
PONG: 4,
};
function getIPCPath(id) {
if (process.platform === 'win32') {
return `\\\\?\\pipe\\discord-ipc-${id}`;
}
const { env: { XDG_RUNTIME_DIR, TMPDIR, TMP, TEMP } } = process;
const prefix = XDG_RUNTIME_DIR || TMPDIR || TMP || TEMP || '/tmp';
return `${prefix.replace(/\/$/, '')}/discord-ipc-${id}`;
}
function getIPC(id = 0) {
return new Promise((resolve, reject) => {
const path = getIPCPath(id);
const onerror = () => {
if (id < 10) {
resolve(getIPC(id + 1));
} else {
reject(new Error('Could not connect'));
}
};
const sock = net.createConnection(path, () => {
sock.removeListener('error', onerror);
resolve(sock);
});
sock.once('error', onerror);
});
}
async function findEndpoint(tries = 0) {
if (tries > 30) {
throw new Error('Could not find endpoint');
}
const endpoint = `http://127.0.0.1:${6463 + (tries % 10)}`;
try {
const r = await fetch(endpoint);
if (r.status === 404) {
return endpoint;
}
return findEndpoint(tries + 1);
} catch (e) {
return findEndpoint(tries + 1);
}
}
function encode(op, data) {
data = JSON.stringify(data);
const len = Buffer.byteLength(data);
const packet = Buffer.alloc(8 + len);
packet.writeInt32LE(op, 0);
packet.writeInt32LE(len, 4);
packet.write(data, 8, len);
return packet;
}
const accumulatedData = {
payload: Buffer.alloc(0),
op: undefined,
expectedLength: 0,
};
function decode(socket, callback) {
const packet = socket.read();
if (!packet) {
return;
}
accumulatedData.payload = Buffer.concat([accumulatedData.payload, packet]);
while (accumulatedData.payload.length > 0) {
if (accumulatedData.expectedLength === 0) {
// We are at the start of a new payload
accumulatedData.op = accumulatedData.payload.readInt32LE(0);
accumulatedData.expectedLength = accumulatedData.payload.readInt32LE(4);
accumulatedData.payload = accumulatedData.payload.subarray(8); // Remove opcode and length
}
if (accumulatedData.payload.length < accumulatedData.expectedLength) {
// Full payload hasn't been received yet, wait for more data
break;
}
// Accumulated data has the full payload and possibly the beginning of the next payload
const currentPayload = accumulatedData.payload.subarray(0, accumulatedData.expectedLength);
const nextPayload = accumulatedData.payload.subarray(accumulatedData.expectedLength);
accumulatedData.payload = nextPayload; // Keep remainder for next payload
try {
callback({
op: accumulatedData.op,
data: JSON.parse(currentPayload.toString('utf8')),
});
// Reset for next payload
accumulatedData.op = undefined;
accumulatedData.expectedLength = 0;
} catch (err) {
// Full payload has been received, but is not valid JSON
callback({ error: new Error('Received payload with malformed JSON', { cause: err }) });
// Reset for next payload
accumulatedData.op = undefined;
accumulatedData.expectedLength = 0;
break;
}
}
decode(socket, callback);
}
class IPCTransport extends EventEmitter {
constructor(client) {
super();
this.client = client;
this.socket = null;
}
async connect() {
const socket = this.socket = await getIPC();
socket.on('close', this.onClose.bind(this));
socket.on('error', this.onClose.bind(this));
this.emit('open');
socket.write(encode(OPCodes.HANDSHAKE, {
v: 1,
client_id: this.client.clientId,
}));
socket.pause();
socket.on('readable', () => {
decode(socket, ({ error, op, data }) => {
if (error) {
this.client.emit('error', error);
return;
}
switch (op) {
case OPCodes.PING:
this.send(data, OPCodes.PONG);
break;
case OPCodes.FRAME:
if (!data) {
return;
}
if (data.cmd === 'AUTHORIZE' && data.evt !== 'ERROR') {
findEndpoint()
.then((endpoint) => {
this.client.request.endpoint = endpoint;
})
.catch((e) => {
this.client.emit('error', e);
});
}
this.emit('message', data);
break;
case OPCodes.CLOSE:
this.emit('close', data);
break;
default:
break;
}
});
});
}
onClose(e) {
this.emit('close', e);
}
send(data, op = OPCodes.FRAME) {
this.socket.write(encode(op, data));
}
async close() {
return new Promise((r) => {
this.once('close', r);
this.send({}, OPCodes.CLOSE);
this.socket.end();
});
}
ping() {
this.send(uuid(), OPCodes.PING);
}
}
module.exports = IPCTransport;
module.exports.encode = encode;
module.exports.decode = decode;