summaryrefslogtreecommitdiff
path: root/root-watcher/zerotier-root-watcher.js
blob: d4607fc2b435f537e653067d25a512e362c66147 (plain)
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
'use strict';

const pg = require('pg');
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
const async = require('async');

const config = JSON.parse(fs.readFileSync('./config.json'));
const roots = config.roots||{};

const db = new pg.Pool(config.db);

process.on('uncaughtException',function(err) {
	console.error('ERROR: uncaught exception: '+err);
	if (err.stack)
		console.error(err.stack);
});

function httpRequest(host,port,authToken,method,path,args,callback)
{
	var responseBody = [];
	var postData = (args) ? JSON.stringify(args) : null;

	var req = http.request({
		host: host,
		port: port,
		path: path,
		method: method,
		headers: {
			'X-ZT1-Auth': (authToken||''),
			'Content-Length': (postData) ? postData.length : 0
		}
	},function(res) {
		res.on('data',function(chunk) {
			if ((chunk)&&(chunk.length > 0))
				responseBody.push(chunk);
		});
		res.on('timeout',function() {
			try {
				if (typeof callback === 'function') {
					var cb = callback;
					callback = null;
					cb(new Error('connection timed out'),null);
				}
				req.abort();
			} catch (e) {}
		});
		res.on('error',function(e) {
			try {
				if (typeof callback === 'function') {
					var cb = callback;
					callback = null;
					cb(new Error('connection timed out'),null);
				}
				req.abort();
			} catch (e) {}
		});
		res.on('end',function() {
			if (typeof callback === 'function') {
				var cb = callback;
				callback = null;
				if (responseBody.length === 0) {
					return cb(null,{});
				} else {
					responseBody = Buffer.concat(responseBody);

					if (responseBody.length < 2) {
						return cb(null,{});
					}

					if ((responseBody.readUInt8(0,true) === 0x1f)&&(responseBody.readUInt8(1,true) === 0x8b)) {
						try {
							responseBody = zlib.gunzipSync(responseBody);
						} catch (e) {
							return cb(e,null);
						}
					}

					try {
						return cb(null,JSON.parse(responseBody));
					} catch (e) { 
						return cb(e,null);
					}
				}
			}
		});
	}).on('error',function(e) {
		try {
			if (typeof callback === 'function') {
				var cb = callback;
				callback = null;
				cb(e,null);
			}
			req.abort();
		} catch (e) {}
	}).on('timeout',function() {
		try {
			if (typeof callback === 'function') {
				var cb = callback;
				callback = null;
				cb(new Error('connection timed out'),null);
			}
			req.abort();
		} catch (e) {}
	});

	req.setTimeout(30000);
	req.setNoDelay(true);

	if (postData !== null)
		req.end(postData);
	else req.end();
};

var peerStatus = {};

function saveToDb()
{
	db.connect(function(err,client,clientDone) {
		if (err) {
			console.log('WARNING: database error writing peers: '+err.toString());
			clientDone();
			return setTimeout(saveToDb,config.dbSaveInterval||60000);
		}
		client.query('BEGIN',function(err) {
			if (err) {
				console.log('WARNING: database error writing peers: '+err.toString());
				clientDone();
				return setTimeout(saveToDb,config.dbSaveInterval||60000);
			}
			let timeout = Date.now() - (config.peerTimeout||600000);
			let wtotal = 0;
			async.eachSeries(Object.keys(peerStatus),function(address,nextAddress) {
				let s = peerStatus[address];
				if (s[1] <= timeout) {
					delete peerStatus[address];
					return process.nextTick(nextAddress);
				} else {
					++wtotal;
					client.query('INSERT INTO "Peer" ("ztAddress","timestamp","versionMajor","versionMinor","versionRev","rootId","phyPort","phyLinkQuality","phyLastReceive","phyAddress") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)',s,nextAddress);
				}
			},function(err) {
				if (err)
					console.log('WARNING database error writing peers: '+err.toString());
				console.log(Date.now().toString()+' '+wtotal);
				client.query('COMMIT',function(err,result) {
					clientDone();
					return setTimeout(saveToDb,config.dbSaveInterval||60000);
				});
			});
		});
	});
};

function doRootUpdate(name,id,ip,port,peersPath,authToken,interval)
{
	httpRequest(ip,port,authToken,"GET",peersPath,null,function(err,res) {
		if (err) {
			console.log('WARNING: cannot reach '+name+peersPath+' (will try again in 1s): '+err.toString());
			return setTimeout(function() { doRootUpdate(name,id,ip,port,peersPath,authToken,interval); },1000);
		}
		if (!Array.isArray(res)) {
			console.log('WARNING: cannot reach '+name+peersPath+' (will try again in 1s): response is not an array of peers');
			return setTimeout(function() { doRootUpdate(name,id,ip,port,peersPath,authToken,interval); },1000);
		}

		//console.log(name+': '+res.length+' peer entries.');
		let now = Date.now();
		let count = 0;
		for(let pi=0;pi<res.length;++pi) {
			let peer = res[pi];
			let address = peer.address;
			let ztAddress = parseInt(address,16)||0;
			if (!ztAddress)
				continue;

			let paths = peer.paths;
			if ((Array.isArray(paths))&&(paths.length > 0)) {
				let bestPath = null;
				for(let i=0;i<paths.length;++i) {
					if (paths[i].active) {
						let lr = paths[i].lastReceive;
						if ((lr > 0)&&((!bestPath)||(bestPath.lastReceive < lr)))
							bestPath = paths[i];
					}
				}

				if (bestPath) {
					let a = bestPath.address;
					if (typeof a === 'string') {
						let a2 = a.split('/');
						if (a2.length === 2) {
							let vmaj = peer.versionMajor;
							if ((typeof vmaj === 'undefined')||(vmaj === null)) vmaj = -1;
							let vmin = peer.versionMinor;
							if ((typeof vmin === 'undefined')||(vmin === null)) vmin = -1;
							let vrev = peer.versionRev;
							if ((typeof vrev === 'undefined')||(vrev === null)) vrev = -1;
							let lr = parseInt(bestPath.lastReceive)||0;

							let s = peerStatus[address];
							if ((!s)||(s[8] < lr)) {
								peerStatus[address] = [
									ztAddress,
									now,
									vmaj,
									vmin,
									vrev,
									id,
									parseInt(a2[1])||0,
									parseFloat(bestPath.linkQuality)||1.0,
									lr,
									a2[0]
								];
							}
							++count;
						}
					}
				}
			}
		}

		console.log(name+': '+count+' peers with active direct paths.');
		return setTimeout(function() { doRootUpdate(name,id,ip,port,peersPath,authToken,interval); },interval);
	});
};

for(var r in roots) {
	var rr = roots[r];
	if (rr.peers)
		doRootUpdate(r,rr.id,rr.ip,rr.port,rr.peers,rr.authToken||null,config.interval||60000);
}

return setTimeout(saveToDb,config.dbSaveInterval||60000);