Defines a Simple MQTT client.

@param {string} host - the hostname of the broker.
@param {function} [err_cb] - optional callback fired whenever an error occurs
492579
function (host, done_cb, secure) {
    // Initializes the object that stores subscriptions
    this.subscriptions = {};
    // Initializes the object that holds the internal client
    this.client = {};
    // Functions backlog
    this.backlog = [];
    // Connect
    this.client = connectBrowser(this.subscriptions, this.backlog, host, done_cb, secure);
}
889565
function (host, port, cb) {
    var err,
        data = {};

    var openssl = spawn('openssl', ['s_client', '-connect', host + ':' + port, '-servername', host]);

    // Clear timeout when execution was successful
    openssl.on('exit', function(){
      clearTimeout(timeoutTimer);
    });

    // Catch stderr and search for possible errors
    openssl.stderr.on('data', function (out) {
      // Search for possible errors in stderr
      var errorRegexp = /(Connection refused)|(Can't assign requested address)|(gethostbyname failure)|(getaddrinfo: nodename)/;
      var regexTester = errorRegexp.test(out);

      // If match, raise error
      if (regexTester) {
        err = new Error(out.toString().replace(/^\s+|\s+$/g, ''));

        // Callback and return array
        return cb(err, data);
      }
    });

    openssl.stdout.on('data', function (out) {
      var data = out.toString();

      // Search for certificate in stdout
      var matches = data.match(/-----BEGIN CERTIFICATE-----([\s\S.]*)-----END CERTIFICATE-----/);

      try {
        data = matches[0];
      } catch (e) {
        // ... otherwise raise error
        err = new Error('Couldn\'t extract certificate for ' + host + ':' + port);
      }

      // ... callback and return certificate
      return cb(err, data);
    });

    // End stdin (otherwise it'll run indefinitely)
  	openssl.stdin.end();

    // Timeout function to kill in case of errors
    var timeoutTimer = setTimeout(function(){
      openssl.kill();
      // ... otherwise throw error
      err = new Error('Time out while trying to extract certificate for ' + host + ':' + port);

      // and return
      return cb(err, data);
    }, 5000);
  }
1303011
function serverReady (port, ...args) {
  const start = new Date()
  let timeout = serverReady.timeout
  let host, hostOrTimeout, cb

  switch (args.length) {
    case 1:
      [cb] = args
      break
    case 2:
      [hostOrTimeout, cb] = args
      if (typeof hostOrTimeout === 'string') {
        host = hostOrTimeout
      } else {
        timeout = hostOrTimeout
      }
      break
    default:
      [host, timeout, cb] = args
  }

  cb = once(cb)

  let ready = false
  const connect = (port, cb) => {

    const client = net
      .connect({ port, host })
      .on('connect', () => {

        ready = true
        client.destroy()
        cb()

      })
      .on('error', () => {

        client.destroy()

      })
      .once('close', () => {

        if (new Date() - start > timeout) {
          return cb(new Error('Timeout'))
        }

        setTimeout(() => !ready && connect(port, cb), interval)

      })

  }

  connect(port, cb)
}
672327
function HostNotFound(message, code_id) {
    Error.call(this);
    this.message = message || "host not found";
    this.code_id = code_id || null;
    this.statusCode = 400;
}
33982
function Server(host, port, options) {
  var self = this;

  // Needed to convert this constructor into EventEmitter
  EventEmitter.call(this);

  options = options || {};
  this.host = host || '127.0.0.1';
  this.port = port || 59895;
  this.debug = options.debug || false;
  this.json = options.json || true;

  var parser = new xml2js.Parser();
  var responseMessageNumber = 0;

  // TODO: Build up proper ACKS
  var applicationAcceptACK = 'MSH|^~\\&|||||20121217154325.194-0700||ACK^RO1|101|T|2.6\nMSA|AA|17';
  var applicationErrorACK = 'MSH|^~\\&|NES|NINTENDO|TESTSYSTEM|TESTFACILITY|20121217158325.194-0700||ACK^RO1|101|T|2.6\nMSA|AE|17';

  // Bind to TCP socket for HL7
  var hl7TcpSocket = net.createServer({ allowHalfOpen: false}, function(socket){

    socket.setEncoding("utf8");

    function handleError(error){
      socket.write(applicationErrorACK);

      self.emit('error', error);
      console.log("HL7 TCP Server ERROR: ", error);
    }

    function createEL7AckForMessageNumber(messageNumber) {
      var ack = 'MSH|^~\\&|||||' + generateTimeStamp() + '||ACK^RO1|'+ getUniqueMessageNumber() +'|T|2.6\rMSA|AA|' + messageNumber;
      return ack;
    }

    function zeroFill( number, width ) {
      width -= number.toString().length;
      if ( width > 0 ) {
        return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
      }
      return number + ""; // always return a string
    }

    function generateTimeStamp() {
      var now = new Date();

      var month = zeroFill(now.getUTCMonth() + 1, 2);
      var date = zeroFill(now.getUTCDate(), 2);
      var hours = zeroFill(now.getUTCHours(), 2);
      var minutes = zeroFill(now.getUTCMinutes(), 2);
      var seconds = zeroFill(now.getUTCSeconds(), 2);

      var timestamp = now.getUTCFullYear().toString()
        + month 
        + date
        + hours 
        + minutes 
        + seconds
        + '.'
        + now.getUTCMilliseconds().toString()
        + '+0000' 
        return timestamp;
    }

    function getUniqueMessageNumber() {
      responseMessageNumber = responseMessageNumber + 1;
      return responseMessageNumber;
    }

    function createXMLAckForMessageNumber(messageNumber) {
      var ack = String.fromCharCode(0x0b) + '<?xml version="1.0" encoding="UTF-8"?>' +
        '\n<ACK xmlns="urn:hl7-org:v2xml">'+
        '\n<MSH>' +
            '\n<MSH.1>|</MSH.1>' +
            '\n<MSH.2>^~\&amp;</MSH.2>' +
            '\n<MSH.7>' + generateTimeStamp() + '</MSH.7>' +
            '\n<MSH.9>' +
                '\n<MSG.1>ACK</MSG.1>' +
                '\n<MSG.2>R01</MSG.2>' +
            '\n</MSH.9>' +
            '\n<MSH.10>' + getUniqueMessageNumber() + '</MSH.10>' +
            '\n<MSH.11>' +
                '\n<PT.1>T</PT.1>' +
            '\n</MSH.11>' +
            '\n<MSH.12>' +
                '\n<VID.1>2.6</VID.1>' +
            '\n</MSH.12>' +
        '\n</MSH>' +
        '\n<MSA>' +
            '\n<MSA.1>AA</MSA.1>' +
            '\n<MSA.2>' + messageNumber +'</MSA.2>' +
        '\n</MSA>' +
      '\n</ACK>\n' + String.fromCharCode(0x1c) + '\r';
      console.log("Generated ACK: " + ack);
      return ack;
    }

    function handleXML(xml, sendEL7Ack){
      parser.parseString(xml, function(error, result){
        if (error) return handleError(error);

        if (self.debug) {
          console.log("Message: ", util.inspect(result, false, 7, true));
          console.log('Sending ACK');
        }
        self.emit('hl7', result);

        console.log(result);

        var messageNumber = 0;

        for (var key in result) {
          if (result.hasOwnProperty(key)) {
            if (result[key].MSH) {
              var msg = result[key].MSH[0]["MSH.10"][0];
              messageNumber = msg;
            }
          }
        }

        console.log("Sending ACK for messageNumber "+messageNumber);

        if (sendEL7Ack) {
          var ack = createEL7AckForMessageNumber(messageNumber);
          socket.write(ack);
        }
        else {
          var ack = createXMLAckForMessageNumber(messageNumber);
          socket.write(new Buffer(ack, encoding = "utf8"));
        }
        socket.end();
      });
    }

    socket.on('connect', function() {
     if (self.debug) {
       var now = new Date();
       console.log(now + " - HL7 TCP Client Connected");
     }
    });

    socket.on('data', function(packet) {
      if (self.debug) {
        console.log(packet);
      }

      if (!packet) return handleError(new Error('Packet is empty'));

      // It is XML format
      if (packet.indexOf('<?xml') !== -1) {
        handleXML(packet.trim(), false);
      }
      // It is EL7 format
      else {
        hl7.toXml(packet, function(error, xml){
          if (error) return handleError(error);

          handleXML(xml, true);
        });
      }
    });

    socket.on('error', function(error){
      handleError(error);
    });

    socket.on('close', function(){
      if (self.debug) {
        var now = new Date();
        console.log(now + " - HL7 TCP Server Disconnected");
      }
    });

    socket.on('end', function() {
      if (self.debug) {
        var now = new Date();
        console.log(now + " - HL7 TCP Client Disconnected");
      }
    });
  });

  hl7TcpSocket.listen( this.port, function(){
    var address = hl7TcpSocket.address();
    console.log("HL7 TCP Server listening on: " + address.address + ":" + address.port);
  });
}
865473
function(options) {
	events.EventEmitter.call(this); 	// inherit from EventEmitter
    	TRACE 		= options.log;
	IDX 		= options.idx;
	STATUS 		= options.status;
	HOST 		= options.host;
	REQUEST		= options.request;
	this.domoMQTT	= this.connect(HOST);
}
458813
function (host) {
        /*
        * For Host match, we are considering the port with the host, hence we are using getRemote() instead of getHost()
        * We need to address three cases for the host urlStr
        * 1. * It matches all the host + protocol,  hence we are not having any parsing logic for it.
        * 2. *.foo.bar.com Here the prefix could be anything but it should end with foo.bar.com
        * 3. foo.bar.com This is the absolute matching needs to done.
        */
        var matchRegexObject = this._matchPatternObject;
        return (
            this.matchAnyHost(matchRegexObject) ||
            this.matchAbsoluteHostPattern(matchRegexObject, host) ||
            this.matchSuffixHostPattern(matchRegexObject, host)
        );
    }
253551
function connect(port, host) {
    return new Promise((resolve, reject) => {
        let completed = ssocket_helpers.createSimplePromiseCompletedAction(resolve, reject);
        try {
            let client = new Net.Socket();
            client.connect(port, host, (err) => {
                try {
                    if (err) {
                        completed(err);
                    }
                    else {
                        completed(null, createClient(client));
                    }
                }
                catch (e) {
                    completed(e);
                }
            });
        }
        catch (e) {
            completed(e);
        }
    });
}
643527
function(cb) {
    let serverDomain = domain.create();
    serverDomain.on('error', function(err) {
      console.error('Server domain caught an exception: ' + err);
      if (err) {
        console.error(err.stack);
      }
    });

    let web = this;
    serverDomain.run(function() {

      // Initialize the express server and routes.
      web.initServer();
      let http = require('http');

      let alwaysSecure = null;
      if (web.conf.https && web.conf.https.enabled) {
        if (web.conf.https.letsEncrypt) {
          //must do this manuall - npm install --global letsencrypt-cli
          let https = require('https');
          

          let lex = web.getLetsEncryptLex();

          let httpsPort = web.conf.https.port || 443;
          https.createServer(lex.httpsOptions, lex.middleware(web.app))
          .listen(httpsPort, web.conf.ipAddress, function(err, result) {
            if (err) {
              console.error(err);
            }
            console.log('%s: Node https server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, httpsPort);

            if (cb) {
              cb(err, result);
            }
          });



        } else {
          let https = require('https');
          let privateKey = fs.readFileSync(web.conf.https.privateKey, 'utf8');
          let certificate = fs.readFileSync(web.conf.https.certificate, 'utf8');
          let credentials = {key: privateKey, cert: certificate};
          let httpsServer = https.createServer(credentials, web.app);

          httpsServer.listen(web.conf.https.port, web.conf.ipAddress, function(err, result) {
            if (err) {
              console.error(err);
            }
            console.log('%s: Node https server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.https.port);

            if (cb) {
              cb(err, result);
            }
          });
        }

        alwaysSecure = web.conf.https.alwaysSecure;
      }
      
      if (alwaysSecure && alwaysSecure.enabled) {
        let httpRedirecter = http.createServer(function(req, res) {

          if (alwaysSecure.redirectHandler) {
            alwaysSecure.redirectHandler(req, res);
          } else {  
            let nonStandardPort = '';
            if (web.conf.https.port != 443) {
              nonStandardPort = ':' + web.conf.https.port;
            }
            res.writeHead(302, {'Location': 'https://' + req.headers.host.split(':')[0] + nonStandardPort + req.url});
            res.end();
          }
        });

        httpRedirecter.listen(web.conf.port, web.conf.ipAddress, function(err, result) {
           if (err) {
              console.error(err);
            }
            
            console.log('%s: http redirecter server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.port);

            if (cb) {
              cb(err, result);
            }
        });
      } else {
        let httpServer = http.createServer(web.app);
        //  Start the app on the specific interface (and port).
        httpServer.listen(web.conf.port, web.conf.ipAddress, function(err, result) {
           if (err) {
              console.error(err);
            }
            
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.port);

            if (cb) {
              cb(err, result);
            }
        });
      }

    });
  }
921733
function resolveHost (host) {
  const defaultHost = '0.0.0.0'
  host = host || defaultHost
  const displayHost = host === defaultHost
    ? 'localhost'
    : host
  return {
    displayHost,
    host
  }
}
1297413
function cb(err) {
        if (callback) {
            if (err) return callback(err);
            callback(null, rec);
        }
        callback = null;
        if (!err) {
            that.emit('logged', rec);
        }
    }
48507
function (host, clientId) {
    // Initializes the object that stores subscriptions
    this.subscriptions = {};
    // Initializes the object that holds the internal client
    this.client = {};
    // Handles the optional clientId parameter
    if (arguments.length === 1 || clientId === undefined) {
        clientId = generateRandomClientId();
    }
    // Connect
    this.client = connectNode(this.subscriptions, host, clientId);
}
970078
function checkHost(host,callback) {

	if(hostCache.get(host,callback)) {
		console.log('checkHost: Resolved %s from hostCache...',host);
		return true;
	}

	console.log('checkHost: Looking up %s...',host);

	var options = {
		host: host,
		port: 80,
		path: '/',
		method: 'GET'
	};

	var req = http.request(options, function(res) {
		var data = '';
		res.setEncoding('utf8');

		res.on('data', function (chunk) {
			data += chunk;
		});
		res.on('end', function () {
			hostCache.set(host,true);
		});
		res.on('error',function() {
			hostCache.set(host,false);
		});
	});
	req.on('error',function() {
		hostCache.set(host,false);
	});
	req.end();
}
112600
public void setSocketProxy(String host, int port) {
        if (config == null) {
            config = new AipClientConfiguration();
        }
        this.config.setProxy(host, port, Proxy.Type.SOCKS);
    }
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);
            });
        }
318633
private static CloseableHttpClient wrapClient(String host) {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        if (host.startsWith("https://")) {
            httpClient = sslClient();
        }

        return httpClient;
    }
1210863
def _show_retry_warning(host):
        
        sys.stderr.write("\nConnection to {} failed. Retrying.\n".format(host))
        sys.stderr.flush()