UNPKG

domotz-remote-pawn

Version:

Domotz Agent

62 lines (56 loc) 2.36 kB
/** This file is part of Domotz Agent. * Copyright (C) 2016 Domotz Ltd * * Domotz Agent is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Domotz Agent is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>. **/ /** * Created by Massimiliano Cuzzoli <mcuzzoli@domotz.com> on 26/08/15. * */ const MODULE_NAME = 'SOCKET LISTENER'; var factory = function (http, fs, requestHandler) { var httpSocketFile = process.env.DOMOTZ_HTTP_ON_UNIX_SOCKET_FILE; var server; server = http.createServer(function (request, response) { // Route on the user agent basis if (request.headers && request.headers['user-agent'].indexOf('domotz') === 0) { requestHandler.handleRequest(request, response); return; } console.warn('%s - Received invalid user agent: %s', MODULE_NAME, request.headers['user-agent']); response.writeHead(400); response.end(); }); server.on('error', function (err) { if (err.code === 'EADDRINUSE') { console.debug('%s - Removed existing unix socket: %s', MODULE_NAME, httpSocketFile); fs.unlink(httpSocketFile, function (exception) { if (exception) { console.warn('%s - Error on unix socket unlink', MODULE_NAME); throw exception; } console.debug('%s - Retry to listen on: %s', MODULE_NAME, httpSocketFile); server.listen(httpSocketFile); }); } }); return { socketName: httpSocketFile, listen: function listen() { console.info('%s - Created socket server for: %s. Start listening on: %s', MODULE_NAME, httpSocketFile, this.socketName); return server.listen(this.socketName); }, }; }; module.exports.socketListener = factory;