/*
functions
 
createServer

@exports createServer
@function createServer
@param {Number|String} listen - listen type
@param {Object} [opt] - various options. Check README.md
@return {Object}
343940
function createServer(listen, opt) {

  if (!listen) {
    throw new TypeError('listen required');
  }
  var options = opt || Object.create(null);
  var my = {
    keepalive: Number(options.keepalive) || 2000,
    callback: typeof options.callback === 'function' ? options.callback : false,
    http: false,
    https: false
  };
  if (typeof options.http === 'object') {
    my.http = {
      port: Number(options.http.port) || 3000,
      host: String(options.http.host || '127.0.0.1')
    };
  }
  if (typeof options.https === 'object') {
    my.https = options.https;
    my.https.port = Number(options.https.port) || 3000;
    my.https.host = String(options.https.host || '127.0.0.1');
  }

  var hosts = Object.create(null);
  var server = net.createServer(function(sock) {

    sock.setKeepAlive(true, my.keepalive); // https://en.wikipedia.org/wiki/Keepalive
    sock.on('data', function(buff) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      } else if (buff.length > 1) { // set client id
        var _id = String(buff);
        hosts[_id] = {
          state: sock.readyState,
          beat: Date.now()
        };
        sock._id = _id;
      }
      return;

    }).on('close', function(had_error) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      }
      // error hook [with client id]
      return my.callback !== false ? my.callback(had_error, sock._id) : null;
    });
  });

  if (options.host && typeof listen === 'number') { // tpc only
    server.listen(listen, options.host);
  } else {
    server.listen(listen);
  }

  if (my.http || my.https) {
    var web = function(req, res) {

      var out = '';
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      var url = decodeURI(req.url);
      url = url.substr(1, url.length);
      if (url === '') {
        out = JSON.stringify(hosts);
      } else if (hosts[url] !== undefined) {
        out = JSON.stringify(hosts[url]);
      } else {
        res.statusCode = 404;
      }
      return res.end(out);
    };
    if (my.http) {
      require('http').createServer(web).listen(my.http.port, my.http.host);
    }
    if (my.https) {
      require('https').createServer(my.https, web).listen(my.https.port,
        my.https.host);
    }
  }

  server._hosts = hosts; // hosts reference
  return server;
}
151627
function Dispatcher (opts) {
    // provide some default value
    this.opts=
        { debug      : opts.debug    || 3              // default no debug
        , dumpfile   : opts.dumpfile || null           // filename for log file or NMEA generated commands
        , hostname   : opts.hostname || 'localhost'    // default localhost for client connect host
        , srvmod     : opts.srvmod   || false          // default is client mode
        , port       : opts.port     || 1234           // no default for port
        , cltmod     : opts.cltmod   || true           // default mode is client connect
        , timeout    : opts.timeout*1000  || 180000    // reconnect timeout default 180s
    };

    // verbose flag is global
    if (opts.verbose) Verbose = true;

    // if needed check dumpfile can be create
    if (this.opts.dumpfile !== null) {
        try { // dump fd is global
            DumpFD= fs.openSync (this.opts.dumpfile, "w+");
        } catch (err) {
            console.log ("hoops file to open [%s] err=[%s]",this.opts.dumpfile, err);
        }
    }

    // if needed start a Tcp server
    if (this.opts.srvmod) {
        this.opts.cltmod=false;    // when server cannot be a client
        this.TcpServer (); // start a server waiting on --port/localhost
    }

    // in client mode we connect onto a remote server
    if (this.opts.cltmod) {
        this.TcpClient();  // when connected will enter ClientListener() event handler
    }

    // validate Queue where position will be posted
     QJhandle  = async.queue  (QJpost, 1);
}
730389
function createBroker (ascoltatore, moscaOpts) {
  const moscaSettings = {
    // port: 1883,
    backend: ascoltatore,
    persistence: {
      factory: mosca.persistence.Redis
    }
  }

  moscaOpts = Object.assign({}, moscaSettings, moscaOpts)
  const server = new mosca.Server(moscaOpts)
  server.on('ready', setup)

  // fired when a message is received
  server.on('published', function (packet, client) {
    const presence = packet.topic.match(/^\$SYS\/.*\/(new|disconnect)\/clients$/)
    if (presence) {
      const clientId = packet.payload
      const type = presence[1] === 'new' ? 'connected' : 'disconnected'
      server.publish({
        topic: `$aws/events/presence/${type}/${clientId}`,
        payload: JSON.stringify(createAWSLifecycleEvent({
          type,
          clientId
        }))
      })
    }

    const subscription = packet.topic.match(/^\$SYS\/.*\/new\/(subscribes|unsubscribes)$/)
    if (subscription) {
      const type = subscription[1] === 'subscribes' ? 'subscribed' : 'unsubscribed'
      const { clientId, topic } = JSON.parse(packet.payload)
      server.publish({
        topic: `$aws/events/subscriptions/${type}/${clientId}`,
        payload: JSON.stringify(createAWSLifecycleEvent({
          type,
          clientId,
          topics: [topic]
        }))
      })
    }
  })

  return server
}
1107809
function WebServer(data) {
  // Use a closure to preserve `this`
  var self = this;
  self.data = data;

  this.RequestHandler = bind(this.RequestHandler, this);
  this.callbackExecutor = bind(this.callbackExecutor, this);

  self.server = http.createServer(self.RequestHandler);

  // Use random port if port settings is not provided.
  if (!self.data.port) {
    self.data.port = 0;
  }

  // Use address if provided.
  if (self.data.hostname) {
    self.server.listen(self.data.port, self.data.hostname);
  } else {
    self.server.listen(self.data.port);
  }

  self.server.on('listening', function() {
    self.debug.log('Listen on :%s', self.server.address().port);
  });
}
1265940
function HiddenServer(opts) {
  if (!(this instanceof HiddenServer)) return new HiddenServer(opts);

  this.set(require('../settings.json'));
  this.set(opts);
  this.uri = this.get('publicServer') + this.get('pingUri').replace(':hiddenServerName', this.get('hiddenServerName'));
  debug('uri', this.uri);
  this.init();
}
1370706
function Application(options) {
  var self = this;

  if (!(self instanceof Application)) {
    return new Application(options);
  }

  stream.Duplex.call(self, { objectMode: true });

  self.id = hat();
  self.server = net.createServer(self._handleInbound.bind(self));
  self.options = merge(Object.create(Application.DEFAULTS), options);
  self.connections = { inbound: [], outbound: [] };

  // setup middlware stack with initial entry a simple passthrough
  self.stack = [function(socket) {
    return through(function(data) {
      this.queue(data);
    });
  }];

  Object.defineProperty(self, 'log', {
    value: this.options.logger || {
      info: NOOP, warn: NOOP, error: NOOP
    }
  });

  // connect to seeds
  self._enterNetwork();
  setInterval(self._enterNetwork.bind(self), self.options.retryInterval);
}
1211538
function(opts) {
  opts = opts || {};
  this._context = opts.context;
  this._routeContext = opts.routeContext;
  this.router = opts.router || router.df;
  this.routerType = opts.routerType;
  this.rpcDebugLog = opts.rpcDebugLog;
  if (this._context) {
    opts.clientId = this._context.serverId;
  }
  this.opts = opts;
  this.proxies = {};
  this._station = createStation(opts);
  this.state = STATE_INITED;
}
976273
function createServer(webhook)
{
  var self = this

  var onError = this.emit.bind(this, 'error')

  var port     = webhook.port     || 0
  var hostname = webhook.hostname || HOSTNAME

  var server = http.createServer(function(req, res)
  {
    if(req.method === 'GET')
    {
      res.end()

      return self.push(parse(req.url).query)
    }

    req.pipe(concat(function(body)
    {
      res.end()

      self.push(body.toString())
    }))
  })
  .listen(port, hostname, function()
  {
    var address = this.address()

    if(hostname === HOSTNAME) hostname = getHostname()

    if(!hostname)
    {
      self.emit('error', new Error("There's no public available interfaces"))

      return this.close()
    }

    self.emit('open', 'http://'+hostname+':'+address.port)
  })
  .on('error'      , onError)
  .on('clientError', onError)

  return server
}
949886
function startServer(alerts, params, port, resources) {
    const compiledAlerts = compileMarkdown(alerts);
    const app = http.createServer((req, res) =>
        res.end(resources[req.url] || resources['/index.html']));
    const io = listen(app);
    io.on('connection', socket => {
        emitInfo(`new session for ${socket.handshake.address}`);
        socket.emit('update', compiledAlerts);
        socket.on('disconnect', () => {
            emitInfo(`disconnected session ${socket.handshake.address}`);
        });
    });

    return new Promise(resolve => app.listen(port, emitRungEmoji & resolve))
        .then(~watchChanges(io, params));
}
1056160
function HybridConnectionsWebSocketServer(options, callback) {
  if (this instanceof HybridConnectionsWebSocketServer === false) {
    return new HybridConnectionsWebSocketServer(options, callback);
  }

  EventEmitter.call(this);

  options = Object.assign({
    server: null,
    token: null,
    id: null,
    verifyClient: null,
    handleProtocols: null,
    disableHixie: false,
    clientTracking: true,
    perMessageDeflate: true,
    maxPayload: 100 * 1024 * 1024,
    backlog: null // use default (511 as implemented in net.js)
  }, options);

  if (!isDefinedAndNonNull(options, 'server')) {
    throw new TypeError('\'server\' must be provided');
  }

  if (!isDefinedAndNonNull(options, 'token')) {
    throw new TypeError('A \'token\' string or function must be provided');
  }

  var self = this;

  this.listenUri = options.server;
  if (isDefinedAndNonNull(options, 'id')) {
    this.listenUri = listenUri + '&id=' + options.id;
  }

  this.closeRequested = false;
  this.options = options;
  this.path = options.path;
  this.clients = [];

  connectControlChannel(this);
}
202908
function setupListener (host_port, listenerDone) {

            const hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
            if (!hp) return listenerDone(
                new Error('Invalid "listen" format in smtp.ini'));

            const host = hp[1];
            const port = parseInt(hp[2], 10);

            Server.get_smtp_server(host, port, inactivity_timeout, (server) => {
                if (!server) return listenerDone();

                server.notes = Server.notes;
                if (Server.cluster) server.cluster = Server.cluster;

                server
                    .on('listening', function () {
                        const addr = this.address();
                        logger.lognotice(`Listening on ${addr.address}:${addr.port}`);
                        listenerDone();
                    })
                    .on('close', () => {
                        logger.loginfo(`Listener ${host}:${port} stopped`);
                    })
                    .on('error', e => {
                        if (e.code !== 'EAFNOSUPPORT') return listenerDone(e);
                        // Fallback from IPv6 to IPv4 if not supported
                        // But only if we supplied the default of [::0]:25
                        if (/^::0/.test(host) && Server.default_host) {
                            server.listen(port, '0.0.0.0', 0);
                            return;
                        }
                        // Pass error to callback
                        listenerDone(e);
                    })
                    .listen(port, host, 0);
            });
        }
96421
function createWebservice (opts) {
    var server = new Hapi.Server(opts.host, opts.port, {
        cors: {
            methods: ['GET']
        }
    });
    defineRoutes(server, opts);
    return {
        address: 'http://' + opts.host + ':' + opts.port + '/',
        hapi: server,
        options: opts,
        start: server.start.bind(server)
    };
}
733045
function createServer() {
  function app(req, res, next){ app.handle(req, res, function(){
    res.end("", 'utf8');
  }); }
  merge(app, proto);
  merge(app, EventEmitter.prototype);
  app.route = '/';
  app.stack = [];
  return app;
}
937019
function Server(svc, opts) {
  opts = opts || {};
  events.EventEmitter.call(this);

  this.service = svc;
  this._handlers = {};
  this._fns = []; // Middleware functions.
  this._channels = {}; // Active channels.
  this._nextChannelId = 1;

  this._cache = opts.cache || {}; // Deprecated.
  this._defaultHandler = opts.defaultHandler;
  this._sysErrFormatter = opts.systemErrorFormatter;
  this._silent = !!opts.silent;
  this._strict = !!opts.strictTypes;

  if (opts.remoteProtocols) {
    insertRemoteProtocols(this._cache, opts.remoteProtocols, svc, false);
  }

  svc.messages.forEach(function (msg) {
    var name = msg.name;
    if (!opts.noCapitalize) {
      name = utils.capitalize(name);
    }
    this['on' + name] = this._createMessageHandler(msg);
  }, this);
}
879063
function knStartServer(args, callback)
{
	var host, port, server;

	if (!mod_restify)
		mod_restify = require('restify');

	mod_assert.ok('uri_base' in args);
	mod_assert.equal('string', typeof (args['uri_base']));

	port = 'port' in args ? args['port'] : 80;
	host = 'host' in args ? args['host'] : '::';
	server = mod_restify.createServer({ serverName: 'Kang' });
	server.get(new RegExp(args['uri_base'] + '/.*'),
	    knRestifyHandler(args));
	server.listen(port, host, function () { callback(null, server); });
}
280192
function ChickadeeServer(options) {
  options = options || {};
  var specifiedHttpPort = options.httpPort || HTTP_PORT;
  var httpPort = process.env.PORT || specifiedHttpPort;

  var app = express();
  app.use(bodyParser.json());

  var instance = new Chickadee(options);
  options.app = app;
  instance.configureRoutes(options);

  app.listen(httpPort, function() {
    console.log('chickadee is listening on port', httpPort);
  });

  return instance;
}
1158712
function(server, opts) {
  EventEmitter.call(this);
  this.server = server;
  this.wsprocessor = new WSProcessor();
  this.tcpprocessor = new TCPProcessor(opts.closeMethod);
  this.id = 1;
  this.timeout = (opts.timeout || DEFAULT_TIMEOUT) * 1000;
  this.setNoDelay = opts.setNoDelay;

  if (!opts.ssl) {
    this.server.on('connection', this.newSocket.bind(this));
  } else {
    this.server.on('secureConnection', this.newSocket.bind(this));
    this.server.on('clientError', function(e, tlsSo) {
      logger.warn('an ssl error occured before handshake established: ', e);
      tlsSo.destroy();
    });
  }

  this.wsprocessor.on('connection', this.emit.bind(this, 'connection'));
  this.tcpprocessor.on('connection', this.emit.bind(this, 'connection'));

  this.state = ST_STARTED;
}