index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. //
  2. // ZeroTier One - Global Peer to Peer Ethernet
  3. // Copyright (C) 2011-2014 ZeroTier Networks LLC
  4. //
  5. // This program is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU General Public License
  16. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. //
  18. // --
  19. //
  20. // ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. // are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. //
  23. // If you would like to embed ZeroTier into a commercial application or
  24. // redistribute it in a modified binary form, please contact ZeroTier Networks
  25. // LLC. Start here: http://www.zerotier.com/
  26. //
  27. var config = require('./config.js');
  28. // Fields in netconf response dictionary
  29. var ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES = "et";
  30. var ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID = "nwid";
  31. var ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP = "ts";
  32. var ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO = "id";
  33. var ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_PREFIX_BITS = "mpb";
  34. var ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_DEPTH = "md";
  35. var ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES = "mr";
  36. var ZT_NETWORKCONFIG_DICT_KEY_PRIVATE = "p";
  37. var ZT_NETWORKCONFIG_DICT_KEY_NAME = "n";
  38. var ZT_NETWORKCONFIG_DICT_KEY_DESC = "d";
  39. var ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC = "v4s";
  40. var ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC = "v6s";
  41. var ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP = "com";
  42. var ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST = "eb";
  43. var ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING = "pb";
  44. var ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES = "ab";
  45. // Path to zerotier-idtool binary, invoked to enerate certificates of membership
  46. var ZEROTIER_IDTOOL = '/usr/local/bin/zerotier-idtool';
  47. // From Constants.hpp in node/
  48. var ZT_NETWORK_AUTOCONF_DELAY = 60000;
  49. var ZT_NETWORK_CERTIFICATE_TTL_WINDOW = (ZT_NETWORK_AUTOCONF_DELAY * 4);
  50. // Connect to redis, assuming database 0 and no auth (for now)
  51. var async = require('async');
  52. var redis = require('redis');
  53. var DB = redis.createClient();
  54. DB.on("error",function(err) { console.error('redis query error: '+err); });
  55. DB.select(config.redisDb,function() {});
  56. // Global variables -- these are initialized on startup or netconf-init message
  57. var netconfSigningIdentity = null; // identity of netconf master, with private key portion
  58. // spawn() function to launch sub-processes
  59. var spawn = require('child_process').spawn;
  60. // Returns true for fields that are "true" according to ZT redis schema
  61. function ztDbTrue(v) { return ((v === '1')||(v === 'true')||(v > 0)); }
  62. //
  63. // ZeroTier One Dictionary -- encoding-compatible with Dictionary in C++ code base
  64. //
  65. function Dictionary(fromStr)
  66. {
  67. var self = this;
  68. this.data = {};
  69. this._esc = function(data) {
  70. var es = '';
  71. for(var i=0;i<data.length;++i) {
  72. var c = data.charAt(i);
  73. switch(c) {
  74. case '\0': es += '\\0'; break;
  75. case '\r': es += '\\r'; break;
  76. case '\n': es += '\\n'; break;
  77. case '\\': es += '\\\\'; break;
  78. case '=': es += '\\='; break;
  79. default: es += c; break;
  80. }
  81. }
  82. return es;
  83. };
  84. this._unesc = function(s) {
  85. if (typeof s !== 'string')
  86. return '';
  87. var uns = '';
  88. var escapeState = false;
  89. for(var i=0;i<s.length;++i) {
  90. var c = s.charAt(i);
  91. if (escapeState) {
  92. escapeState = false;
  93. switch(c) {
  94. case '0': uns += '\0'; break;
  95. case 'r': uns += '\r'; break;
  96. case 'n': uns += '\n'; break;
  97. default: uns += c; break;
  98. }
  99. } else{
  100. if ((c !== '\r')&&(c !== '\n')&&(c !== '\0')) {
  101. if (c === '\\')
  102. escapeState = true;
  103. else uns += c;
  104. }
  105. }
  106. }
  107. return uns;
  108. };
  109. this.toString = function() {
  110. var str = '';
  111. for(var key in self.data) {
  112. str += self._esc(key);
  113. str += '=';
  114. var value = self.data[key];
  115. if (value)
  116. str += self._esc(value.toString());
  117. str += '\n';
  118. }
  119. return str;
  120. };
  121. this.fromString = function(str) {
  122. self.data = {};
  123. if (typeof str !== 'string')
  124. return self;
  125. var lines = str.split('\n');
  126. for(var l=0;l<lines.length;++l) {
  127. var escapeState = false;
  128. var eqAt = 0;
  129. for(;eqAt<lines[l].length;++eqAt) {
  130. var c = lines[l].charAt(eqAt);
  131. if (escapeState)
  132. escapeState = false;
  133. else if (c === '\\')
  134. escapeState = true;
  135. else if (c === '=')
  136. break;
  137. }
  138. var k = self._unesc(lines[l].substr(0,eqAt));
  139. ++eqAt;
  140. if ((k)&&(k.length > 0))
  141. self.data[k] = self._unesc((eqAt < lines[l].length) ? lines[l].substr(eqAt) : '');
  142. }
  143. return self;
  144. };
  145. if ((typeof fromStr === 'string')&&(fromStr.length > 0))
  146. self.fromString(fromStr);
  147. };
  148. //
  149. // Identity implementation using zerotier-idtool as subprocess to do actual crypto work
  150. //
  151. function Identity(idstr)
  152. {
  153. var self = this;
  154. this.str = '';
  155. this.fields = [];
  156. this.toString = function() {
  157. return self.str;
  158. };
  159. this.address = function() {
  160. return ((self.fields.length > 0) ? self.fields[0] : '0000000000');
  161. };
  162. this.fromString = function(str) {
  163. self.str = '';
  164. self.fields = [];
  165. if (typeof str !== 'string')
  166. return;
  167. for(var i=0;i<str.length;++i) {
  168. if ("0123456789abcdef:".indexOf(str.charAt(i)) < 0)
  169. return; // invalid character in identity
  170. }
  171. var fields = str.split(':');
  172. if ((fields.length < 3)||(fields[0].length !== 10)||(fields[1] !== '0'))
  173. return;
  174. self.str = str;
  175. self.fields = fields;
  176. };
  177. this.isValid = function() {
  178. return (! ((self.fields.length < 3)||(self.fields[0].length !== 10)||(self.fields[1] !== '0')) );
  179. };
  180. this.hasPrivate = function() {
  181. return ((self.isValid())&&(self.fields.length >= 4));
  182. };
  183. if (typeof idstr === 'string')
  184. self.fromString(idstr);
  185. };
  186. //
  187. // Invokes zerotier-idtool to generate certificates for private networks
  188. //
  189. function generateCertificateOfMembership(nwid,peerAddress,callback)
  190. {
  191. // The first fields of these COM tuples come from
  192. // CertificateOfMembership.hpp's enum of required
  193. // certificate default fields.
  194. var comTimestamp = '0,' + Date.now().toString(16) + ',' + ZT_NETWORK_CERTIFICATE_TTL_WINDOW.toString(16);
  195. var comNwid = '1,' + nwid + ',0';
  196. var comIssuedTo = '2,' + peerAddress + ',ffffffffffffffff';
  197. var cert = '';
  198. var certErr = '';
  199. var idtool = spawn(ZEROTIER_IDTOOL,[ 'mkcom',netconfSigningIdentity,comTimestamp,comNwid,comIssuedTo ]);
  200. idtool.stdout.on('data',function(data) {
  201. cert += data;
  202. });
  203. idtool.stderr.on('data',function(data) {
  204. certErr += data;
  205. });
  206. idtool.on('close',function(exitCode) {
  207. if (certErr.length > 0)
  208. console.error('zerotier-idtool stderr returned: '+certErr);
  209. return callback((cert.length > 0) ? cert : null,exitCode);
  210. });
  211. }
  212. //
  213. // Message handler for messages over ZeroTier One service bus
  214. //
  215. function doNetconfInit(message)
  216. {
  217. netconfSigningIdentity = new Identity(message.data['netconfId']);
  218. if (!netconfSigningIdentity.hasPrivate()) {
  219. netconfSigningIdentity = null;
  220. console.error('got invalid netconf signing identity in netconf-init');
  221. } // else console.error('got netconf-init, running! id: '+netconfSigningIdentity.address());
  222. }
  223. function doNetconfRequest(message)
  224. {
  225. if ((netconfSigningIdentity === null)||(!netconfSigningIdentity.hasPrivate())) {
  226. console.error('got netconf-request before netconf-init, ignored');
  227. return;
  228. }
  229. var peerId = new Identity(message.data['peerId']);
  230. var nwid = message.data['nwid'];
  231. var requestId = message.data['requestId'];
  232. if ((!peerId)||(!peerId.isValid())||(!nwid)||(nwid.length !== 16)||(!requestId)) {
  233. console.error('missing one or more required fields in netconf-request');
  234. return;
  235. }
  236. var networkKey = 'zt1:network:'+nwid+':~';
  237. var memberKey = 'zt1:network:'+nwid+':member:'+peerId.address()+':~';
  238. var ipAssignmentsKey = 'zt1:network:'+nwid+':ipAssignments';
  239. var network = null;
  240. var member = null;
  241. var authorized = false;
  242. var v4NeedAssign = false;
  243. var v6NeedAssign = false;
  244. var v4Assignments = [];
  245. var v6Assignments = [];
  246. var ipAssignments = []; // both v4 and v6
  247. var activeBridges = '';
  248. async.series([function(next) {
  249. // network lookup
  250. DB.hgetall(networkKey,function(err,obj) {
  251. if (!obj.id)
  252. return next(new Error('invalid network record'));
  253. network = obj;
  254. return next(null);
  255. });
  256. },function(next) {
  257. // member lookup
  258. if ((!network)||(!('id' in network))||(network['id'] !== nwid))
  259. return next(null);
  260. DB.hgetall(memberKey,function(err,obj) {
  261. if (err)
  262. return next(err);
  263. if (obj) {
  264. // Update existing member record with new last seen time, etc.
  265. member = obj;
  266. authorized = ((!ztDbTrue(network['private'])) || ztDbTrue(member['authorized']));
  267. var updatedFields = {
  268. 'lastSeen': Date.now(),
  269. 'authorized': authorized ? '1' : '0' // reset authorized to unhide in UI, since UI uses -1 to hide
  270. };
  271. if (!('identity' in member))
  272. updatedFields['identity'] = peerId.toString();
  273. if (!('firstSeen' in member))
  274. updatedFields['firstSeen'] = Date.now();
  275. if (message.data['from'])
  276. updatedFields['lastAt'] = message.data['from'];
  277. if (message.data['clientVersion'])
  278. updatedFields['clientVersion'] = message.data['clientVersion'];
  279. if (message.data['clientOs'])
  280. updatedFields['clientOs'] = message.data['clientOs'];
  281. DB.hmset(memberKey,updatedFields,next);
  282. } else {
  283. // Add member record to network for newly seen peer
  284. authorized = ztDbTrue(network['private']) ? false : true; // public networks authorize everyone by default
  285. var now = Date.now().toString();
  286. member = {
  287. 'id': peerId.address(),
  288. 'nwid': nwid,
  289. 'authorized': authorized ? '1' : '0',
  290. 'identity': peerId.toString(),
  291. 'firstSeen': now,
  292. 'lastSeen': now
  293. };
  294. if (message.data['from'])
  295. member['lastAt'] = message.data['from'];
  296. if (message.data['clientVersion'])
  297. member['clientVersion'] = message.data['clientVersion'];
  298. if (message.data['clientOs'])
  299. member['clientOs'] = message.data['clientOs'];
  300. DB.hmset(memberKey,member,next);
  301. }
  302. });
  303. },function(next) {
  304. // Figure out which IP address auto-assignments we need to look up or make
  305. if (!authorized)
  306. return next(null);
  307. v4NeedAssign = (network['v4AssignMode'] === 'zt');
  308. v6NeedAssign = (network['v6AssignMode'] === 'zt');
  309. var ipacsv = member['ipAssignments'];
  310. if (ipacsv) {
  311. var ipa = ipacsv.split(',');
  312. for(var i=0;i<ipa.length;++i) {
  313. if (ipa[i]) {
  314. ipAssignments.push(ipa[i]);
  315. if ((ipa[i].indexOf('.') > 0)&&(v4NeedAssign))
  316. v4Assignments.push(ipa[i]);
  317. else if ((ipa[i].indexOf(':') > 0)&&(v6NeedAssign))
  318. v6Assignments.push(ipa[i]);
  319. }
  320. }
  321. }
  322. return next(null);
  323. },function(next) {
  324. // assign IPv4 if needed
  325. if ((!authorized)||(!v4NeedAssign)||(v4Assignments.length > 0))
  326. return next(null);
  327. var peerAddress = peerId.address();
  328. var ipnetwork = 0;
  329. var netmask = 0;
  330. var netmaskBits = 0;
  331. var v4pool = network['v4AssignPool']; // technically csv but only one netblock currently supported
  332. if (v4pool) {
  333. var v4poolSplit = v4pool.split('/');
  334. if (v4poolSplit.length === 2) {
  335. var networkSplit = v4poolSplit[0].split('.');
  336. if (networkSplit.length === 4) {
  337. ipnetwork |= (parseInt(networkSplit[0],10) << 24) & 0xff000000;
  338. ipnetwork |= (parseInt(networkSplit[1],10) << 16) & 0x00ff0000;
  339. ipnetwork |= (parseInt(networkSplit[2],10) << 8) & 0x0000ff00;
  340. ipnetwork |= parseInt(networkSplit[3],10) & 0x000000ff;
  341. netmaskBits = parseInt(v4poolSplit[1],10);
  342. if (netmaskBits > 32)
  343. netmaskBits = 32; // sanity check
  344. for(var i=0;i<netmaskBits;++i)
  345. netmask |= (0x80000000 >> i);
  346. netmask &= 0xffffffff;
  347. }
  348. }
  349. }
  350. if ((ipnetwork === 0)||(netmask === 0xffffffff))
  351. return next(null);
  352. var invmask = netmask ^ 0xffffffff;
  353. var abcd = 0;
  354. var ipAssignmentAttempts = 0;
  355. async.whilst(
  356. function() { return ((v4Assignments.length === 0)&&(ipAssignmentAttempts < 1000)); },
  357. function(next2) {
  358. ++ipAssignmentAttempts;
  359. // Generate or increment IP address source bits
  360. if (abcd === 0) {
  361. var a = parseInt(peerAddress.substr(2,2),16) & 0xff;
  362. var b = parseInt(peerAddress.substr(4,2),16) & 0xff;
  363. var c = parseInt(peerAddress.substr(6,2),16) & 0xff;
  364. var d = parseInt(peerAddress.substr(8,2),16) & 0xff;
  365. abcd = (a << 24) | (b << 16) | (c << 8) | d;
  366. } else ++abcd;
  367. if ((abcd & 0xff) === 0)
  368. abcd |= 1;
  369. abcd &= 0xffffffff;
  370. // Derive an IP to test and generate assignment ip/bits string
  371. var ip = (abcd & invmask) | (ipnetwork & netmask);
  372. var assignment = ((ip >> 24) & 0xff).toString(10) + '.' + ((ip >> 16) & 0xff).toString(10) + '.' + ((ip >> 8) & 0xff).toString(10) + '.' + (ip & 0xff).toString(10) + '/' + netmaskBits.toString(10);
  373. // Check :ipAssignments to see if this IP is already taken
  374. DB.hget(ipAssignmentsKey,assignment,function(err,value) {
  375. if (err)
  376. return next2(err);
  377. // IP is already taken, try again via async.whilst()
  378. if ((value)&&(value !== peerAddress))
  379. return next2(null); // if someone's already got this IP, keep looking
  380. v4Assignments.push(assignment);
  381. ipAssignments.push(assignment);
  382. // Save assignment to :ipAssignments hash
  383. DB.hset(ipAssignmentsKey,assignment,peerAddress,function(err) {
  384. if (err)
  385. return next2(err);
  386. // Save updated CSV list of assignments to member record
  387. var ipacsv = ipAssignments.join(',');
  388. member['ipAssignments'] = ipacsv;
  389. DB.hset(memberKey,'ipAssignments',ipacsv,next2);
  390. });
  391. });
  392. },
  393. next
  394. );
  395. },function(next) {
  396. // assign IPv6 if needed -- TODO
  397. if ((!authorized)||(!v6NeedAssign)||(v6Assignments.length > 0))
  398. return next(null);
  399. return next(null);
  400. },function(next) {
  401. // Get active bridges
  402. DB.keys('zt1:network:'+nwid+':member:*:~',function(err,keys) {
  403. if (keys) {
  404. async.eachSeries(keys,function(key,nextKey) {
  405. DB.hgetall(key,funciton(err,abr) {
  406. if ((abr)&&(abr.id)&&(abr.id.length === 10)&&(ztDbTrue(abr['activeBridge']))) {
  407. if (activeBridges.length)
  408. activeBridges += ',';
  409. activeBridges += abr.id;
  410. }
  411. return nextKey(null);
  412. });
  413. },next);
  414. } else return next(null);
  415. });
  416. }],function(err) {
  417. if (err) {
  418. console.error('error answering netconf-request for '+peerId.address()+': '+err);
  419. return;
  420. }
  421. var response = new Dictionary();
  422. response.data['peer'] = peerId.address();
  423. response.data['nwid'] = nwid;
  424. response.data['type'] = 'netconf-response';
  425. response.data['requestId'] = requestId;
  426. if (authorized) {
  427. var certificateOfMembership = null;
  428. var privateNetwork = ztDbTrue(network['private']);
  429. async.series([function(next) {
  430. // Generate certificate of membership if necessary
  431. if (privateNetwork) {
  432. generateCertificateOfMembership(nwid,peerId.address(),function(cert,exitCode) {
  433. if (cert) {
  434. certificateOfMembership = cert;
  435. return next(null);
  436. } else return next(new Error('zerotier-idtool returned '+exitCode));
  437. });
  438. } else return next(null);
  439. }],function(err) {
  440. // Send response to parent process
  441. if (err) {
  442. console.error('unable to generate certificate for peer '+peerId.address()+' on network '+nwid+': '+err);
  443. response.data['error'] = 'ACCESS_DENIED'; // unable to generate certificate
  444. } else {
  445. var netconf = new Dictionary();
  446. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES] = network['etherTypes'];
  447. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID] = nwid;
  448. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP] = Date.now().toString(16);
  449. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO] = peerId.address();
  450. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_PREFIX_BITS] = 0;
  451. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_DEPTH] = 0;
  452. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES] = '';
  453. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_PRIVATE] = privateNetwork ? '1' : '0';
  454. if (network['name'])
  455. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_NAME] = network['name'];
  456. if (network['desc'])
  457. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_DESC] = network['desc'];
  458. if ((v4NeedAssign)&&(v4Assignments.length > 0))
  459. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC] = v4Assignments.join(',');
  460. if ((v6NeedAssign)&&(v6Assignments.length > 0))
  461. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC] = v6Assignments.join(',');
  462. if (certificateOfMembership !== null)
  463. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = certificateOfMembership;
  464. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST] = ztDbTrue(network['enableBroadcast']) ? '1' : '0';
  465. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING] = ztDbTrue(network['allowPassiveBridging']) ? '1' : '0';
  466. if ((activeBridges)&&(activeBridges.length > 0))
  467. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES] = activeBridges; // comma-delimited list
  468. response.data['netconf'] = netconf.toString();
  469. }
  470. process.stdout.write(response.toString()+'\n');
  471. });
  472. } else {
  473. // Peer not authorized to join network
  474. response.data['error'] = 'ACCESS_DENIED';
  475. process.stdout.write(response.toString()+'\n');
  476. }
  477. });
  478. }
  479. function handleMessage(dictStr)
  480. {
  481. var message = new Dictionary(dictStr);
  482. if (!('type' in message.data)) {
  483. console.error('ignored message without request type field');
  484. return;
  485. } else if (message.data['type'] === 'netconf-init') {
  486. doNetconfInit(message);
  487. } else if (message.data['type'] === 'netconf-request') {
  488. doNetconfRequest(message);
  489. } else {
  490. console.error('ignored unrecognized message type: '+message.data['type']);
  491. }
  492. };
  493. //
  494. // Read stream of double-CR-terminated dictionaries from stdin until close/EOF
  495. //
  496. var stdinReadBuffer = '';
  497. process.stdin.on('readable',function() {
  498. var chunk = process.stdin.read();
  499. if (chunk)
  500. stdinReadBuffer += chunk;
  501. for(;;) {
  502. var boundary = stdinReadBuffer.indexOf('\n\n');
  503. if (boundary >= 0) {
  504. handleMessage(stdinReadBuffer.substr(0,boundary + 1));
  505. stdinReadBuffer = stdinReadBuffer.substr(boundary + 2);
  506. } else break;
  507. }
  508. });
  509. process.stdin.on('end',function() {
  510. process.exit(0);
  511. });
  512. process.stdin.on('close',function() {
  513. process.exit(0);
  514. });
  515. process.stdin.on('error',function() {
  516. process.exit(0);
  517. });
  518. // Tell ZeroTier One that the service is running, solicit netconf-init
  519. process.stdout.write('type=ready\n\n');