forked from tramseyer/cell-geolocation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcell-geolocation.js
423 lines (403 loc) · 23.3 KB
/
cell-geolocation.js
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
const http = require('http');
const sqlite3 = require('sqlite3');
const path = require('path');
const Url = require('url');
const util = require('util');
const fs = require('fs');
const request = require(path.join(__dirname, 'request.js'));
const mlsDb = new sqlite3.Database(path.join(__dirname, 'mls_cells.sqlite'), sqlite3.OPEN_READONLY);
const ociDb = new sqlite3.Database(path.join(__dirname, 'oci_cells.sqlite'), sqlite3.OPEN_READONLY);
const glmDb = new sqlite3.Database(path.join(__dirname, 'glm_cells.sqlite'), sqlite3.OPEN_READWRITE);
const uwlDb = new sqlite3.Database(path.join(__dirname, 'uwl_cells.sqlite'), sqlite3.OPEN_READWRITE);
const ownDb = new sqlite3.Database(path.join(__dirname, 'own_cells.sqlite'), sqlite3.OPEN_READWRITE);
const approximatedRange = 2147483648;
const defaultLatitude = 46.909009;
const defaultLongitude = 7.360584;
const defaultRange = 4294967295;
const mlsDbMtime = new Date(fs.statSync(path.join(__dirname, 'mls_cells.sqlite')).mtime).getTime()/1000|0;
console.log('Main database (Mozilla) last modifed at:', mlsDbMtime);
const OPENCELLID_API_KEY = process.env.OPENCELLID_API_KEY;
if (typeof OPENCELLID_API_KEY != 'undefined') {
console.log('Using OpenCellId API key:', OPENCELLID_API_KEY);
} else {
console.warn('No OpenCellId API key supplied via: OPENCELLID_API_KEY');
}
// https://carto.com/blog/center-of-points/
const CENTER_OF_CELLS_QUERY = '\
SELECT \
s.avg_lat AS lat, \
180 * atan2(s.zeta, s.xi) / pi() AS lon \
FROM \
( \
SELECT \
avg(lat) AS avg_lat, \
avg(sin(pi() * lon / 180)) AS zeta, \
avg(cos(pi() * lon / 180)) AS xi \
FROM cells WHERE mcc = ? AND mnc = ? AND lac = ? \
) AS s'
ociDb.loadExtension(path.join(__dirname,'libsqlitefunctions.so'), function(err) {
if (err) {
console.error('Could not load libsqlitefunctions.so extension');
}
});
var numValidRequests = 0;
var numOpenCellIdResponses = 0;
var numMozillaResponses = 0;
var numGoogleResponses = 0;
var numUnwiredLabsResponses = 0;
var numApproximatedResponses = 0;
var numDefaultResponses = 0;
var numApproximatedCells = 0;
var numUnknownCells = 0;
http.createServer(function(req, res) {
const url = Url.parse(req.url, true);
const forwarded = req.headers['x-forwarded-for']
const ip = forwarded ? forwarded.split(/, /)[0] : req.connection.remoteAddress
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
if (req.method === 'GET' && url.pathname === '/') {
if (!url.query.mcc || !url.query.mnc || !url.query.lac || !url.query.cellid) {
res.writeHead(400);
return res.end('Need mcc, mnc, lac, cellid passed in as query parameters');
} else if ((url.query.mcc > 999) || (url.query.mnc > 999) || (url.query.lac > 65535) || (url.query.cellid > 268435455)) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({"lat":defaultLatitude,"lon":defaultLongitude,"range":defaultRange}));
return;
}
numValidRequests++;
// -1- query Mozilla Location Service database
mlsDb.get('SELECT lat, lon, range FROM cells WHERE mcc = ? AND mnc = ? AND lac = ? AND cellid = ?', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid
}, function(err, row) {
if (err) {
console.error('Error querying Mozilla Location Service database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
// -2- if Mozilla Location Service database did not have a match, query OpenCellId database
if (typeof row == 'undefined') {
ociDb.get('SELECT lat, lon, range FROM cells WHERE mcc = ? AND mnc = ? AND lac = ? AND cellid = ?', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid
}, function(err, row) {
if (err) {
console.error('Error querying OpenCellId database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
// -3- if OpenCellId database did not have a match, query GLM MMAP cache database
if (typeof row == 'undefined') {
glmDb.get('SELECT lat, lon, range FROM cells WHERE mcc = ? AND mnc = ? AND lac = ? AND cellid = ?', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid
}, function(err, row) {
if (err) {
console.error('Error querying Google GLM MMAP cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
// -4- if Google GLM MMAP cache database did not have a match, query OpenCellId cache database
if (typeof row == 'undefined') {
uwlDb.get('SELECT lat, lon, range FROM cells WHERE mcc = ? AND mnc = ? AND lac = ? AND cellid = ?', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid
}, function(err, row) {
if (err) {
console.error('Error querying OpenCellId cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
// -5- if OpenCellId cache database did not have a match, query own cache database
if (typeof row == 'undefined') {
ownDb.get('SELECT lat, lon, range FROM cells WHERE mcc = ? AND mnc = ? AND lac = ? AND cellid = ?', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid
}, function(err, row) {
if (err) {
console.error('Error querying own cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
// -6- if OpenCellId cache database did not have a match, query Google GLM MMAP online service
if (typeof row == 'undefined') {
request.glm(url.query.mcc,url.query.mnc,url.query.lac,url.query.cellid).then(coords => {
glmDb.run('INSERT INTO cells (mcc, mnc, lac, cellid, lat, lon, range, created_at, updated_at) VALUES(?,?,?,?,?,?,?,?,?)', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid,
5: coords.lat,
6: coords.lon,
7: coords.range,
8: Math.floor(new Date().getTime()/1000|0),
9: Math.floor(new Date().getTime()/1000|0)
}, function(err, result) {
if (err) {
console.error('Error inserting queried location into Google GLM MMAP cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
console.log(util.format('Req#%d M#%d O#%d G#%d U#%d Own#%d/%d A#%d D#%d: Queried Google GLM MMAP for %s: %s, %s, %s, %s -> %s, %s, %s',
numValidRequests, numMozillaResponses, numOpenCellIdResponses, numGoogleResponses, numUnwiredLabsResponses,
numApproximatedResponses, numDefaultResponses, numApproximatedCells, numUnknownCells,
ip,
url.query.mcc, url.query.mnc, url.query.lac, url.query.cellid,
coords.lat, coords.lon, coords.range));
numGoogleResponses++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({"lat":coords.lat,"lon":coords.lon,"range":coords.range}));
return;
});
}).catch(err => {
// -7- if Google GLM MMAP did not have a match, query OpenCellId online service
request.oci(url.query.mcc,url.query.mnc,url.query.lac,url.query.cellid, OPENCELLID_API_KEY).then(coords => {
if (coords.statusCode == 200) { // ok
uwlDb.run('INSERT INTO cells (mcc, mnc, lac, cellid, lat, lon, range, created_at, updated_at) VALUES(?,?,?,?,?,?,?,?,?)', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid,
5: coords.lat,
6: coords.lon,
7: coords.range,
8: Math.floor(new Date().getTime()/1000|0),
9: Math.floor(new Date().getTime()/1000|0)
}, function(err, result) {
if (err) {
console.error('Error inserting queried location into OpenCellId cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
console.log(util.format('Req#%d M#%d O#%d G#%d U#%d Own#%d/%d A#%d D#%d: Queried OpenCellId for %s: %s, %s, %s, %s -> %s, %s, %s',
numValidRequests, numMozillaResponses, numOpenCellIdResponses, numGoogleResponses, numUnwiredLabsResponses,
numApproximatedResponses, numDefaultResponses, numApproximatedCells, numUnknownCells,
ip,
url.query.mcc, url.query.mnc, url.query.lac, url.query.cellid,
coords.lat, coords.lon, coords.range));
numUnwiredLabsResponses++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({"lat":coords.lat,"lon":coords.lon,"range":coords.range}));
return;
});
}
else if (coords.statusCode == 404) { // cell not found
// -8a- if OpenCellId did not have a match, query OpenCellId database and calculate approximate location
ociDb.get(CENTER_OF_CELLS_QUERY, {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac
}, function(err, row) {
if (err) {
console.error('Error querying OpenCellId database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
} else if ((null != row.lat) && (null != row.lon)) {
numApproximatedCells++;
ownDb.run('INSERT INTO cells (mcc, mnc, lac, cellid, lat, lon, range, created_at, updated_at) VALUES(?,?,?,?,?,?,?,?,?)', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid,
5: row.lat,
6: row.lon,
7: approximatedRange,
8: Math.floor(new Date().getTime()/1000|0),
9: Math.floor(new Date().getTime()/1000|0)
}, function(err, result) {
if (err) {
console.error('Error inserting default location into own cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
console.log(util.format('Req#%d M#%d O#%d G#%d U#%d Own#%d/%d A#%d D#%d: Replying with approximated location to %s due to %d: %s, %s, %s, %s -> %s, %s, %s',
numValidRequests, numMozillaResponses, numOpenCellIdResponses, numGoogleResponses, numUnwiredLabsResponses,
numApproximatedResponses, numDefaultResponses, numApproximatedCells, numUnknownCells,
ip, coords.statusCode,
url.query.mcc, url.query.mnc, url.query.lac, url.query.cellid,
row.lat,row.lon,approximatedRange));
numApproximatedResponses++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({"lat":row.lat,"lon":row.lon,"range":approximatedRange}));
return;
});
} else {
// -9a- use default location if approximate location could not be calculated
numUnknownCells++;
ownDb.run('INSERT INTO cells (mcc, mnc, lac, cellid, lat, lon, range, created_at, updated_at) VALUES(?,?,?,?,?,?,?,?,?)', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid,
5: defaultLatitude,
6: defaultLongitude,
7: defaultRange,
8: Math.floor(new Date().getTime()/1000|0),
9: Math.floor(new Date().getTime()/1000|0)
}, function(err, result) {
if (err) {
console.error('Error inserting default location into own cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
console.log(util.format('Req#%d M#%d O#%d G#%d U#%d Own#%d/%d A#%d D#%d: Replying with default location to %s due to %d: %s, %s, %s, %s',
numValidRequests, numMozillaResponses, numOpenCellIdResponses, numGoogleResponses, numUnwiredLabsResponses,
numApproximatedResponses, numDefaultResponses, numApproximatedCells, numUnknownCells,
ip, coords.statusCode,
url.query.mcc, url.query.mnc, url.query.lac, url.query.cellid));
numDefaultResponses++;
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({"lat":defaultLatitude,"lon":defaultLongitude,"range":defaultRange}));
return;
});
}
});
} else if (coords.statusCode == 429) { // daily limit of UnwiredLabs requests exceeded
// -8b- if OpenCellId did not have a match, query OpenCellId database and calculate approximate location
ociDb.get(CENTER_OF_CELLS_QUERY, {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac
}, function(err, row) {
if (err) {
console.error('Error querying OpenCellId database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
} else if ((null != row.lat) && (null != row.lon)) {
numApproximatedCells++;
ownDb.run('INSERT INTO cells (mcc, mnc, lac, cellid, lat, lon, range) VALUES(?,?,?,?,?,?,?)', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid,
5: row.lat,
6: row.lon,
7: approximatedRange
}, function(err, result) {
if (err) {
console.error('Error inserting default location into own cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
console.log(util.format('Req#%d M#%d O#%d G#%d U#%d Own#%d/%d A#%d D#%d: Replying with approximated location to %s due to %d: %s, %s, %s, %s -> %s, %s, %s',
numValidRequests, numMozillaResponses, numOpenCellIdResponses, numGoogleResponses, numUnwiredLabsResponses,
numApproximatedResponses, numDefaultResponses, numApproximatedCells, numUnknownCells,
ip, coords.statusCode,
url.query.mcc, url.query.mnc, url.query.lac, url.query.cellid,
row.lat, row.lon, approximatedRange));
numApproximatedResponses++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({"lat":row.lat,"lon":row.lon,"range":approximatedRange}));
return;
});
} else {
// -9b- use default location if approximate location could not be calculated
numUnknownCells++;
ownDb.run('INSERT INTO cells (mcc, mnc, lac, cellid, lat, lon, range) VALUES(?,?,?,?,?,?,?)', {
1: url.query.mcc,
2: url.query.mnc,
3: url.query.lac,
4: url.query.cellid,
5: defaultLatitude,
6: defaultLongitude,
7: defaultRange
}, function(err, result) {
if (err) {
console.error('Error inserting default location into own cache database');
res.writeHead(500);
res.end(JSON.stringify(err));
return;
}
console.log(util.format('Req#%d M#%d O#%d G#%d U#%d Own#%d/%d A#%d D#%d: Replying with default location to %s due to %d: %s, %s, %s, %s',
numValidRequests, numMozillaResponses, numOpenCellIdResponses, numGoogleResponses, numUnwiredLabsResponses,
numApproximatedResponses, numDefaultResponses, numApproximatedCells, numUnknownCells,
ip, coords.statusCode,
url.query.mcc, url.query.mnc, url.query.lac, url.query.cellid));
numDefaultResponses++;
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({"lat":defaultLatitude,"lon":defaultLongitude,"range":defaultRange}));
return;
});
}
});
}
}).catch(err => {
console.warn(err);
res.writeHead(500);
res.end(JSON.stringify(err));
return;
});
});
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
if (approximatedRange == row.range) {
numApproximatedResponses++;
res.end(JSON.stringify(row));
} else {
numDefaultResponses++;
res.end(JSON.stringify(row));
}
}
});
} else {
numUnwiredLabsResponses++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(row));
}
});
} else {
numGoogleResponses++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(row));
}
});
} else {
numOpenCellIdResponses++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(row));
}
});
} else {
numMozillaResponses++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(row));
}
});
} else if (req.method === 'GET' && url.pathname === '/version') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(mlsDbMtime.toString());
} else {
res.writeHead(404);
res.end('Nothing to see here');
}
}).listen(process.env.PORT || 5265, process.env.IP || '0.0.0.0');
process.on('exit', function() {
mlsDb.close();
ociDb.close();
glmDb.close();
uwlDb.close();
ownDb.close();
});
console.log('Running at port:', process.env.PORT || 5265);