-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathsockets.js
More file actions
186 lines (160 loc) · 6.42 KB
/
sockets.js
File metadata and controls
186 lines (160 loc) · 6.42 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
const _ = require('lodash');
const cookie = require('cookie');
const sessionDB = require('./utils').redis;
const settings = require('./utils').settings;
const io = require('socket.io')(settings.general.socket);
const app = require('./app').app;
const Generators = app.get('Generators');
const Snippet = require('./models/Snippet');
const Version = require('./models/Version');
const abuseLimit = 20;
let abuseCache = {};
let timeout = {};
function checkAbuse(id) {
// abuse is considered <abuseLimit> requests per second from same socket
// Block further requests until until 5 seconds have passed without another barrage
if (!(id in abuseCache)) {
abuseCache[id] = {
firstAccess: new Date().getTime(),
lastAccess: new Date().getTime(),
total: 1
};
// Update current stats
} else {
abuseCache[id].lastAccess = new Date().getTime();
abuseCache[id].total++;
}
// Check for abuse
if (abuseCache[id] && abuseCache[id].total > abuseLimit && abuseCache[id].lastAccess - abuseCache[id].firstAccess < 1000) {
timeout[id] = new Date().getTime(); // time they were placed into time out
return true;
}
if (id in timeout) {
return true;
}
return false;
}
function checkTimeout() {
_.each(timeout, (a, b) => {
if (new Date().getTime() - a > 1000) {
delete timeout[b];
}
});
}
// Reset abuse cache every second
setInterval(() => {
abuseCache = {};
}, 1000);
setInterval(checkTimeout, 2500);
// Attach the user's session to the socket object
// If user isn't logged in, set session to null for front page demo
io.use((socket, next) => {
let data = socket.handshake || socket.request;
try {
let sessionID = cookie.parse(data.headers.cookie)[settings.session.key].slice(2, 34);
sessionDB.get('sess:' + sessionID, (err, session) => {
if (err) console.log(err);
socket.session = session;
next();
});
} catch(e) {
socket.session = null;
next();
}
});
io.on('connection', socket => {
// Search
socket.on('search', msg => {
if (checkAbuse(socket.id)) return socket.emit('abuse');
let tags = _.uniq(msg.query.slice(0, 255).split(',').map(tag => tag.trim()).filter(tag => tag !== "")).filter(tag => tag.match(/^([a-zA-Z0-9 _\-\.+\[\]\{\}\(\)]{1,32})$/g) !== null);
Snippet.search(tags).then(data => {
let obj = data.reduce(function(o, v, i) {
o[v.id] = v;
return o;
}, {});
socket.emit('searchResults', obj);
});
});
// Snippet info
socket.on('snippet', msg => {
if (checkAbuse(socket.id)) return socket.emit('abuse');
Version.getCond({snippetID: msg.id}).then(snippet => {
Snippet.getCond({['s.id']: snippet.snippetID}).then(orig => {
if (snippet === null) {
socket.emit('snippetResults', null);
} else if (snippet.published === 0) {
Version.getVersion(orig.ref, snippet.version-1).then(ver => {
socket.emit('snippetResults', ver)
});
} else {
socket.emit('snippetResults', snippet)
}
});
});
});
// Generators
socket.on('lintCode', msg => {
if (checkAbuse(socket.id)) return socket.emit('abuse');
msg.code = String(msg.code).slice(0, 8192);
let shortest = Math.floor(Math.random() * Generators.realtime.length);
for (let i = 0; i < Generators.realtime.length; i++) {
if (Generators.realtime[i].queueLength() < Generators.realtime[shortest].queueLength()) {
shortest = i;
}
}
// Check if chosen Generator has crashed and is in middle of restarting
if (!Generators.realtime[shortest].generator.connected) {
socket.emit('codeLinted', {error: {formatted: "Something bad has happened...please try again later."}, results: [], fmt: null});
} else {
// Don't pass along ref/owner info if from front page demo
if (JSON.parse(socket.session).loggedin === undefined) {
Generators.realtime[shortest].queue.push({socket, data: {src: msg.code, ref: null, owner: 'demo', type: 'lint'}});
} else {
Generators.realtime[shortest].queue.push({socket, data: {src: msg.code, ref: msg.ref, owner: JSON.parse(socket.session).user, type: 'lint', uri: msg.uri}});
}
}
});
socket.on('lintDemoCode', msg => {
if (checkAbuse(socket.id)) return socket.emit('abuse');
msg.code = String(msg.code).slice(0, 8192);
let shortest = Math.floor(Math.random() * Generators.demo.length);
for (let i = 0; i < Generators.demo.length; i++) {
if (Generators.demo[i].queueLength() < Generators.demo[shortest].queueLength()) {
shortest = i;
}
}
// Check if chosen Generator has crashed and is in middle of restarting
if (!Generators.demo[shortest].generator.connected) {
socket.emit('codeLinted', {error: {formatted: "Something bad has happened...please try again later."}, results: [], fmt: null});
} else {
// Don't pass along ref/owner info if from front page demo
if (JSON.parse(socket.session).loggedin === undefined) {
Generators.demo[shortest].queue.push({socket, data: {src: msg.code, ref: null, owner: 'demo', type: 'demo'}});
} else {
Generators.demo[shortest].queue.push({socket, data: {src: msg.code, ref: msg.ref, owner: JSON.parse(socket.session).user, type: 'demo'}});
}
}
});
socket.on('lintSnippetCode', msg => {
if (checkAbuse(socket.id)) return socket.emit('abuse');
msg.code = String(msg.code).slice(0, 8192);
let shortest = Math.floor(Math.random() * Generators.realtime.length);
for (let i = 0; i < Generators.realtime.length; i++) {
if (Generators.realtime[i].queueLength() < Generators.realtime[shortest].queueLength()) {
shortest = i;
}
}
// Check if chosen Generator has crashed and is in middle of restarting
if (!Generators.realtime[shortest].generator.connected) {
socket.emit('codeLinted', {error: {formatted: "Something bad has happened...please try again later."}, results: [], fmt: null});
} else {
// Don't pass along ref/owner info if from front page demo
if (JSON.parse(socket.session).loggedin === undefined) {
Generators.realtime[shortest].queue.push({socket, data: {src: msg.code, ref: null, owner: 'demo', type: 'snippet'}});
} else {
Generators.realtime[shortest].queue.push({socket, data: {src: msg.code, ref: msg.ref, owner: JSON.parse(socket.session).user, type: 'snippet'}});
}
}
});
});
module.exports = io;