<commit_before>/**
 * TCP / TLS transport
 * Implements:
 *     .connect({host, port, tls/ssl, localAddress})
 *     .writeLine(line, cb)
 *     .close(optional_error)
 *     .isConnected()
 * Events:
 *     line
 *     open
 *     close
 */

var net             = require('net');
var tls             = require('tls');
var util            = require('util');
var EventEmitter    = require('events').EventEmitter;
var Socks           = require('socksjs');
var iconv           = require('iconv-lite');

var SOCK_DISCONNECTED = 0;
var SOCK_CONNECTING = 1;
var SOCK_CONNECTED = 2;

function Connection(options) {
    EventEmitter.call(this);

    this.options = options || {};

    this.socket = null;
    this.state = SOCK_DISCONNECTED;
    this.last_socket_error = null;
    this.socket_events = [];

    this.encoding = 'utf8';
    this.incoming_buffer = '';
}

util.inherits(Connection, EventEmitter);

module.exports = Connection;

Connection.prototype.isConnected = function() {
    return this.state === SOCK_CONNECTED;
};

Connection.prototype.writeLine = function writeLine(line, cb) {
	if (this.socket && this.isConnected()) {
		if (this.encoding !== 'utf8') {
			this.socket.write(iconv.encode(line + '\n', this.encoding), cb);
		} else {
			this.socket.write(line + '\n', cb);
		}
	}
};

Connection.prototype.debugOut = function(out) {
    this.emit('debug', 'NetTransport ' + out);
};

Connection.prototype._bindEvent = function _bindEvent(obj, event, fn) {
	obj.on(event, fn);
	var unbindEvent = () => {
		obj.off(event, fn);
	};
	this.socket_events.push(unbindEvent);
	return unbindEvent;
};
Connection.prototype._unbindEvents = function _unbindEvents() {
	this.socket_events.forEach(fn => fn());
};

Connection.prototype.connect = function() {
    var socket_connect_event_name = 'connect';
    var options = this.options;
    var ircd_host = options.host;
    var ircd_port = options.port || 6667;
    var socket = null;

    this.debugOut('connect()');

    this.disposeSocket();
    this.requested_disconnect = false;

    if (!options.encoding || !this.setEncoding(options.encoding)) {
        this.setEncoding('utf8');
    }

    this.state = SOCK_CONNECTING;
    this.debugOut('Connecting socket..');

    if (options.socks) {
        this.debugOut('Using SOCKS proxy');
        socket = this.socket = Socks.connect({
            host: ircd_host,
            port: ircd_port,
            ssl: options.tls,
            rejectUnauthorized: options.rejectUnauthorized
        }, {
            host: options.socks.host,
            port: options.socks.port || 8080,
            user: options.socks.user,
            pass: options.socks.pass,
            localAddress: options.outgoing_addr
        });
    } else {
        if (options.tls || options.ssl) {
            socket = this.socket = tls.connect({
                host: ircd_host,
                port: ircd_port,
                rejectUnauthorized: options.rejectUnauthorized,
                localAddress: options.outgoing_addr
            });

            socket_connect_event_name = 'secureConnect';

        } else {
            socket = this.socket = net.connect({
                host: ircd_host,
                port: ircd_port,
                localAddress: options.outgoing_addr
            });

            socket_connect_event_name = 'connect';
        }
    }

    // We need the raw socket connect event.
    // node.js 0.12 no longer has a .socket property.
    this._bindEvent(socket.socket || socket, 'connect', this.onSocketRawConnected.bind(this));
    this._bindEvent(socket, socket_connect_event_name, this.onSocketFullyConnected.bind(this));

    this._bindEvent(socket, 'close', this.onSocketClose.bind(this));
    this._bindEvent(socket, 'error', this.onSocketError.bind(this));
    this._bindEvent(socket, 'data', this.onSocketData.bind(this));
};

// Called when the socket is connected and before any TLS handshaking if applicable.
// This is when it's ideal to read socket pairs for identd.
Connection.prototype.onSocketRawConnected = function onSocketRawConnected() {
    this.debugOut('socketRawConnected()');
    this.state = SOCK_CONNECTED;
    this.emit('extra', 'raw socket connected', (this.socket.socket || this.socket));
};

// Called when the socket is connected and ready to start sending/receiving data.
Connection.prototype.onSocketFullyConnected = function onSocketFullyConnected() {
    this.debugOut('socketFullyConnected()');
    this.last_socket_error = null;
    this.emit('open');
};

Connection.prototype.onSocketClose = function onSocketClose() {
	this.debugOut('socketClose()');
    this.state = SOCK_DISCONNECTED;
    this.emit('close', this.last_socket_error ? this.last_socket_error : false);
};

Connection.prototype.onSocketError = function onSocketError(err) {
    this.debugOut('socketError() ' + err.message);
    this.last_socket_error = err;
    //this.emit('error', err);
};

Connection.prototype.onSocketData = function onSocketData(data) {
	this.debugOut('socketData()');

	this.incoming_buffer += iconv.decode(data, this.encoding);

	var lines = this.incoming_buffer.split('\n');
	if (lines[lines.length - 1] !== '') {
		this.incoming_buffer = lines.pop();
	} else {
		lines.pop();
		this.incoming_buffer = '';
	}

	lines.forEach(_line => {
		var line = _line.trim();
		this.emit('line', line);
	});
};

Connection.prototype.disposeSocket = function() {
    this.debugOut('disposeSocket() connected=' + this.isConnected());

    if (this.socket && this.state !== SOCK_DISCONNECTED) {
        this.socket.destroy();
    }

    if (this.socket) {
        this._unbindEvents();
        this.socket = null;
    }
};

Connection.prototype.close = function() {
    // Cleanly close the socket if we can
    if (this.socket && this.state === SOCK_CONNECTING) {
        this.debugOut('close() destroying');
        this.socket.destroy();
    } else if (this.socket && this.state === SOCK_CONNECTED) {
        this.debugOut('close() ending');
        this.socket.end();
    }
};

Connection.prototype.setEncoding = function(encoding) {
    var encoded_test;

    this.debugOut('Connection.setEncoding() encoding=' + encoding);

    try {
        encoded_test = iconv.encode('TEST', encoding);
        // This test is done to check if this encoding also supports
        // the ASCII charset required by the IRC protocols
        // (Avoid the use of base64 or incompatible encodings)
        if (encoded_test == 'TEST') { // jshint ignore:line
            this.encoding = encoding;
            return true;
        }
        return false;
    } catch (err) {
        return false;
    }
};
<commit_msg>Checking for tls or ssl connection options<commit_after>/**
 * TCP / TLS transport
 * Implements:
 *     .connect({host, port, tls/ssl, localAddress})
 *     .writeLine(line, cb)
 *     .close(optional_error)
 *     .isConnected()
 * Events:
 *     line
 *     open
 *     close
 */

var net             = require('net');
var tls             = require('tls');
var util            = require('util');
var EventEmitter    = require('events').EventEmitter;
var Socks           = require('socksjs');
var iconv           = require('iconv-lite');

var SOCK_DISCONNECTED = 0;
var SOCK_CONNECTING = 1;
var SOCK_CONNECTED = 2;

function Connection(options) {
    EventEmitter.call(this);

    this.options = options || {};

    this.socket = null;
    this.state = SOCK_DISCONNECTED;
    this.last_socket_error = null;
    this.socket_events = [];

    this.encoding = 'utf8';
    this.incoming_buffer = '';
}

util.inherits(Connection, EventEmitter);

module.exports = Connection;

Connection.prototype.isConnected = function() {
    return this.state === SOCK_CONNECTED;
};

Connection.prototype.writeLine = function writeLine(line, cb) {
	if (this.socket && this.isConnected()) {
		if (this.encoding !== 'utf8') {
			this.socket.write(iconv.encode(line + '\n', this.encoding), cb);
		} else {
			this.socket.write(line + '\n', cb);
		}
	}
};

Connection.prototype.debugOut = function(out) {
    this.emit('debug', 'NetTransport ' + out);
};

Connection.prototype._bindEvent = function _bindEvent(obj, event, fn) {
	obj.on(event, fn);
	var unbindEvent = () => {
		obj.off(event, fn);
	};
	this.socket_events.push(unbindEvent);
	return unbindEvent;
};
Connection.prototype._unbindEvents = function _unbindEvents() {
	this.socket_events.forEach(fn => fn());
};

Connection.prototype.connect = function() {
    var socket_connect_event_name = 'connect';
    var options = this.options;
    var ircd_host = options.host;
    var ircd_port = options.port || 6667;
    var socket = null;

    this.debugOut('connect()');

    this.disposeSocket();
    this.requested_disconnect = false;

    if (!options.encoding || !this.setEncoding(options.encoding)) {
        this.setEncoding('utf8');
    }

    this.state = SOCK_CONNECTING;
    this.debugOut('Connecting socket..');

    if (options.socks) {
        this.debugOut('Using SOCKS proxy');
        socket = this.socket = Socks.connect({
            host: ircd_host,
            port: ircd_port,
            ssl: options.tls || options.ssl,
            rejectUnauthorized: options.rejectUnauthorized
        }, {
            host: options.socks.host,
            port: options.socks.port || 8080,
            user: options.socks.user,
            pass: options.socks.pass,
            localAddress: options.outgoing_addr
        });
    } else {
        if (options.tls || options.ssl) {
            socket = this.socket = tls.connect({
                host: ircd_host,
                port: ircd_port,
                rejectUnauthorized: options.rejectUnauthorized,
                localAddress: options.outgoing_addr
            });

            socket_connect_event_name = 'secureConnect';

        } else {
            socket = this.socket = net.connect({
                host: ircd_host,
                port: ircd_port,
                localAddress: options.outgoing_addr
            });

            socket_connect_event_name = 'connect';
        }
    }

    // We need the raw socket connect event.
    // node.js 0.12 no longer has a .socket property.
    this._bindEvent(socket.socket || socket, 'connect', this.onSocketRawConnected.bind(this));
    this._bindEvent(socket, socket_connect_event_name, this.onSocketFullyConnected.bind(this));

    this._bindEvent(socket, 'close', this.onSocketClose.bind(this));
    this._bindEvent(socket, 'error', this.onSocketError.bind(this));
    this._bindEvent(socket, 'data', this.onSocketData.bind(this));
};

// Called when the socket is connected and before any TLS handshaking if applicable.
// This is when it's ideal to read socket pairs for identd.
Connection.prototype.onSocketRawConnected = function onSocketRawConnected() {
    this.debugOut('socketRawConnected()');
    this.state = SOCK_CONNECTED;
    this.emit('extra', 'raw socket connected', (this.socket.socket || this.socket));
};

// Called when the socket is connected and ready to start sending/receiving data.
Connection.prototype.onSocketFullyConnected = function onSocketFullyConnected() {
    this.debugOut('socketFullyConnected()');
    this.last_socket_error = null;
    this.emit('open');
};

Connection.prototype.onSocketClose = function onSocketClose() {
	this.debugOut('socketClose()');
    this.state = SOCK_DISCONNECTED;
    this.emit('close', this.last_socket_error ? this.last_socket_error : false);
};

Connection.prototype.onSocketError = function onSocketError(err) {
    this.debugOut('socketError() ' + err.message);
    this.last_socket_error = err;
    //this.emit('error', err);
};

Connection.prototype.onSocketData = function onSocketData(data) {
	this.debugOut('socketData()');

	this.incoming_buffer += iconv.decode(data, this.encoding);

	var lines = this.incoming_buffer.split('\n');
	if (lines[lines.length - 1] !== '') {
		this.incoming_buffer = lines.pop();
	} else {
		lines.pop();
		this.incoming_buffer = '';
	}

	lines.forEach(_line => {
		var line = _line.trim();
		this.emit('line', line);
	});
};

Connection.prototype.disposeSocket = function() {
    this.debugOut('disposeSocket() connected=' + this.isConnected());

    if (this.socket && this.state !== SOCK_DISCONNECTED) {
        this.socket.destroy();
    }

    if (this.socket) {
        this._unbindEvents();
        this.socket = null;
    }
};

Connection.prototype.close = function() {
    // Cleanly close the socket if we can
    if (this.socket && this.state === SOCK_CONNECTING) {
        this.debugOut('close() destroying');
        this.socket.destroy();
    } else if (this.socket && this.state === SOCK_CONNECTED) {
        this.debugOut('close() ending');
        this.socket.end();
    }
};

Connection.prototype.setEncoding = function(encoding) {
    var encoded_test;

    this.debugOut('Connection.setEncoding() encoding=' + encoding);

    try {
        encoded_test = iconv.encode('TEST', encoding);
        // This test is done to check if this encoding also supports
        // the ASCII charset required by the IRC protocols
        // (Avoid the use of base64 or incompatible encodings)
        if (encoded_test == 'TEST') { // jshint ignore:line
            this.encoding = encoding;
            return true;
        }
        return false;
    } catch (err) {
        return false;
    }
};
<|endoftext|>


<commit_before>// $Revision$

Ensembl.Panel.ModalContainer = Ensembl.Panel.Overlay.extend({
  constructor: function (id) {
    this.base(id);

    Ensembl.EventManager.register('modalOpen', this, this.open);
    Ensembl.EventManager.register('modalClose', this, this.hide);
    Ensembl.EventManager.register('queuePageReload', this, this.setPageReload);
  },

  init: function () {
    var panel = this;
    var dims  = this.getDimensions();

    this.base(dims.w, dims.h);

    this.elLk.content     = $('.modal_content', this.el);
    this.elLk.title       = $('.modal_title', this.el);
    this.elLk.menu        = $('ul.tabs', this.el);
    this.elLk.tabs        = $('li', this.elLk.menu);
    this.elLk.caption     = $('.modal_caption', this.el);
    this.elLk.closeButton = $('.modal_close', this.el);

    this.pageReload    = false;
    this.sectionReload = {};
    this.activePanel   = '';

    // TODO: check functionality. panel.open() is probably wrong
    $('.modal_confirm', '#' + this.id).live('click', function () {
      var c = confirm(this.title + '\nAre you sure you want to continue?');

      this.title = '';

      if (c === true) {
        panel.open(this);
      }

      return false;
    });

    $('.modal_close', '#' + this.id).live('click', function () { panel.hide(); });

    // Changing tabs - update configuration and get new content
    $('a', this.elLk.tabs).bind('click', function () {
      var li = $(this).parent();

      if (!li.hasClass('active')) {
        Ensembl.EventManager.trigger('updateConfiguration', true);

        panel.elLk.tabs.removeClass('active');
        li.addClass('active');

        panel.getContent(this.href, this.rel);
      }

      li = null;
      return false;
    });
  },

  setDimensions: function (width, height) {
    this.base(width, height);

    if (this.elLk.content) {
      this.elLk.content.height(this.elementHeight - 18);
    }
  },

  open: function (el) {
    var rel = $(this.el).is(':visible') ? el.rel : this.activePanel.match(/config/) && el.rel.match(/config/) ? this.activePanel : el.rel;

    this.elLk.menu.hide();
    this.elLk.caption.html(el.title || el.innerHTML).show();
    this.elLk.closeButton.attr({ title: 'Close', alt: 'Close' });
    this.show();
    this.getContent(el.href, rel);

    return true;
  },

  hide: function (escape) {
    this.base();

    if ((escape !== true && !Ensembl.EventManager.trigger('updateConfiguration') && (this.pageReload || this.sectionReload.count)) || this.pageReload == 'force') {
      this.setPageReload(false, true);
    }
  },

  getContent: function (url, id, failures) {
    id = id || 'modal_default';

    var contentEl = this.elLk.content.filter('#' + id);
    var reload    = url.match(/reset=1/) || $('.modal_reload', this.el).remove().length;
    var hash      = (url.match(/#(.+)$/) || [])[1];

    this.elLk.content.hide();
    this.activePanel = id;

    if (reload) {
      contentEl.empty();
    } else if (id.match(/config/) && contentEl.children(':not(.spinner, .ajax_error)').length) {
      Ensembl.EventManager.triggerSpecific('showConfiguration', id, hash);
      this.changeTab(this.elLk.tabs.children('[rel=' + id + ']').parent());
      this.elLk.closeButton.attr({ title: 'Save and close', alt: 'Save and close' });

      return;
    }

    contentEl.html('
Loading Content
').show();

    $.ajax({
      url: Ensembl.replaceTimestamp(url),
      dataType: 'json',
      context: this,
      success: function (json) {
        var params = hash ? $.extend(json.params || {}, { hash: hash }) : json.params;
        var buttonText, forceReload;

        if (json.redirectURL) {
          return this.getContent(json.redirectURL, id);
        }

        switch (json.panelType) {
          case 'ModalContent': buttonText = 'Close'; break;
          case 'Configurator': buttonText = 'Save and close'; break;
          default: buttonText = 'Update options'; break;
        }

        if (json.activeTab) {
          this.changeTab(this.elLk.tabs.filter('[textContent=' + json.activeTab + ']'));
        }

        Ensembl.EventManager.trigger('destroyPanel', id, 'empty'); // clean up handlers, save memory

        if (!json.nav) {
          json.wrapper = $(json.wrapper).addClass('no_local_context');
        }

        contentEl.html(json.content).wrapInner(json.wrapper).prepend(json.nav);

        this.elLk.closeButton.attr({ title: buttonText, alt: buttonText });

        forceReload = !!$('.modal_reload', contentEl).length;

        if (reload || forceReload) {
          this.setPageReload((url.match(/\bconfig=(\w+)\b/) || [])[1], false, forceReload);
        }

        Ensembl.EventManager.trigger('createPanel', id, $((json.content.match(/<input[^<]*class=".*?panel_type.*?".*?>/) || [])[0]).val() || json.panelType, params);
      },
      error: function (e) {
        failures = failures || 1;

        if (e.status != 500 && failures < 3) {
          var panel = this;
          setTimeout(function () { panel.getContent(url, id, ++failures); }, 2000);
        } else {
          contentEl.html('
Sorry, the page request falied to load.
');
        }
      }
    });
  },

  changeTab: function (tab) {
    if (!tab.hasClass('active')) {
      this.elLk.tabs.removeClass('active');
      tab.addClass('active');
    }

    this.elLk.caption.hide();
    this.elLk.menu.show();

    tab = null;
  },

  setPageReload: function (section, reload, force) {
    if (section) {
      this.sectionReload[section] = 1;
      this.sectionReload.count = (this.sectionReload.count || 0) + 1;
    } else if (section !== false) {
      this.pageReload = true;
    }

    if (force === true) {
      this.pageReload = 'force';
    }

    if (reload === true) {
      Ensembl.EventManager.trigger('reloadPage', !!this.pageReload || this.sectionReload);
      this.sectionReload = {};
    }
  }
});
<commit_msg>modal title height set as a constant<commit_after>// $Revision$

Ensembl.Panel.ModalContainer = Ensembl.Panel.Overlay.extend({
  constructor: function (id) {
    this.base(id);

    Ensembl.EventManager.register('modalOpen', this, this.open);
    Ensembl.EventManager.register('modalClose', this, this.hide);
    Ensembl.EventManager.register('queuePageReload', this, this.setPageReload);
  },

  init: function () {
    var panel = this;
    var dims  = this.getDimensions();

    this.base(dims.w, dims.h);

    this.elLk.content     = $('.modal_content', this.el);
    this.elLk.title       = $('.modal_title', this.el);
    this.elLk.menu        = $('ul.tabs', this.el);
    this.elLk.tabs        = $('li', this.elLk.menu);
    this.elLk.caption     = $('.modal_caption', this.el);
    this.elLk.closeButton = $('.modal_close', this.el);

    this.pageReload    = false;
    this.sectionReload = {};
    this.activePanel   = '';

    // TODO: check functionality. panel.open() is probably wrong
    $('.modal_confirm', '#' + this.id).live('click', function () {
      var c = confirm(this.title + '\nAre you sure you want to continue?');

      this.title = '';

      if (c === true) {
        panel.open(this);
      }

      return false;
    });

    $('.modal_close', '#' + this.id).live('click', function () { panel.hide(); });

    // Changing tabs - update configuration and get new content
    $('a', this.elLk.tabs).bind('click', function () {
      var li = $(this).parent();

      if (!li.hasClass('active')) {
        Ensembl.EventManager.trigger('updateConfiguration', true);

        panel.elLk.tabs.removeClass('active');
        li.addClass('active');

        panel.getContent(this.href, this.rel);
      }

      li = null;
      return false;
    });
  },

  setDimensions: function (width, height) {
    this.base(width, height);

    if (this.elLk.content) {
      this.elLk.content.height(this.elementHeight - this.constant.titleHeight);
    }
  },

  open: function (el) {
    var rel = $(this.el).is(':visible') ? el.rel : this.activePanel.match(/config/) && el.rel.match(/config/) ? this.activePanel : el.rel;

    this.elLk.menu.hide();
    this.elLk.caption.html(el.title || el.innerHTML).show();
    this.elLk.closeButton.attr({ title: 'Close', alt: 'Close' });
    this.show();
    this.getContent(el.href, rel);

    return true;
  },

  hide: function (escape) {
    this.base();

    if ((escape !== true && !Ensembl.EventManager.trigger('updateConfiguration') && (this.pageReload || this.sectionReload.count)) || this.pageReload == 'force') {
      this.setPageReload(false, true);
    }
  },

  getContent: function (url, id, failures) {
    id = id || 'modal_default';

    var contentEl = this.elLk.content.filter('#' + id);
    var reload    = url.match(/reset=1/) || $('.modal_reload', this.el).remove().length;
    var hash      = (url.match(/#(.+)$/) || [])[1];

    this.elLk.content.hide();
    this.activePanel = id;

    if (reload) {
      contentEl.empty();
    } else if (id.match(/config/) && contentEl.children(':not(.spinner, .ajax_error)').length) {
      Ensembl.EventManager.triggerSpecific('showConfiguration', id, hash);
      this.changeTab(this.elLk.tabs.children('[rel=' + id + ']').parent());
      this.elLk.closeButton.attr({ title: 'Save and close', alt: 'Save and close' });

      return;
    }

    contentEl.html('
Loading Content
').show();

    $.ajax({
      url: Ensembl.replaceTimestamp(url),
      dataType: 'json',
      context: this,
      success: function (json) {
        var params = hash ? $.extend(json.params || {}, { hash: hash }) : json.params;
        var buttonText, forceReload;

        if (json.redirectURL) {
          return this.getContent(json.redirectURL, id);
        }

        switch (json.panelType) {
          case 'ModalContent': buttonText = 'Close'; break;
          case 'Configurator': buttonText = 'Save and close'; break;
          default: buttonText = 'Update options'; break;
        }

        if (json.activeTab) {
          this.changeTab(this.elLk.tabs.filter('[textContent=' + json.activeTab + ']'));
        }

        Ensembl.EventManager.trigger('destroyPanel', id, 'empty'); // clean up handlers, save memory

        if (!json.nav) {
          json.wrapper = $(json.wrapper).addClass('no_local_context');
        }

        contentEl.html(json.content).wrapInner(json.wrapper).prepend(json.nav);

        this.elLk.closeButton.attr({ title: buttonText, alt: buttonText });

        forceReload = !!$('.modal_reload', contentEl).length;

        if (reload || forceReload) {
          this.setPageReload((url.match(/\bconfig=(\w+)\b/) || [])[1], false, forceReload);
        }

        Ensembl.EventManager.trigger('createPanel', id, $((json.content.match(/<input[^<]*class=".*?panel_type.*?".*?>/) || [])[0]).val() || json.panelType, params);
      },
      error: function (e) {
        failures = failures || 1;

        if (e.status != 500 && failures < 3) {
          var panel = this;
          setTimeout(function () { panel.getContent(url, id, ++failures); }, 2000);
        } else {
          contentEl.html('
Sorry, the page request falied to load.
');
        }
      }
    });
  },

  changeTab: function (tab) {
    if (!tab.hasClass('active')) {
      this.elLk.tabs.removeClass('active');
      tab.addClass('active');
    }

    this.elLk.caption.hide();
    this.elLk.menu.show();

    tab = null;
  },

  setPageReload: function (section, reload, force) {
    if (section) {
      this.sectionReload[section] = 1;
      this.sectionReload.count = (this.sectionReload.count || 0) + 1;
    } else if (section !== false) {
      this.pageReload = true;
    }

    if (force === true) {
      this.pageReload = 'force';
    }

    if (reload === true) {
      Ensembl.EventManager.trigger('reloadPage', !!this.pageReload || this.sectionReload);
      this.sectionReload = {};
    }
  }
});
<|endoftext|>


<commit_before>var tcpServer;

var activeConnections = [];

function handleClientAccept(client) {
	activeConnections.push(new Socks5Proxy(client));
};

function startup() {
	tcpServer = new TcpServer("127.0.0.1", 8123);
	tcpServer.listen(handleClientAccept);
}

function Socks5Proxy(client) {
	this.client = client;
	this.callbacks = {
		request: null,  // Called when a resource is requested.
		recv: null  // Called when data is received for an outbound connection.
	};
	this.buffer = null;
	this.client.addDataReceivedListener(this._onDataRead.bind(this));
	this.state = SocksState.NEW;
}

const SocksState = {
	NEW: 0,
	CONNECTING: 1,
	CONNECTED: 2,
	ERROR: 3
};

Socks5Proxy.prototype._onDataRead = function(data) {
	if (!this.buffer && data.byteLength) {
		this.buffer = new Uint8Array(data);
	}

	// Parse Initial Connection Messages.
	if (this.state == SocksState.NEW && this.buffer) {
		if (this.buffer[0] != 5) {
			this._error("Client Handshake was invalid");
		}
		var length = this.buffer[1];
		if (this.buffer.length == length + 2) {
			this.buffer = null;
			this._sendHello();
			this.state = SocksState.CONNECTING;
		} else {
			// For now, fragmented handshake can be treated as an error
			this._error("Client Handshake was fragmented");
		}
	}
	// Parse Connection message.
	else if (this.state == SocksState.CONNECTING && this.buffer) {
		if (this.buffer[0] != 5 || this.buffer[2] != 0) {
			this._error("Client connect req had invalid protocol.");
		} else if (this.buffer[1] != 1) {
			this._error("Client requested either UDP or to bind a port. Unsupported!");
		}
		var hostType = this.buffer[3];
		var host = null;
		var offset = 4;
		if (hostType == 1) { // IPv4
			host = this.buffer[4] + "." + this.buffer[5] + "." + this.buffer[6] + "." + this.buffer[7];
			offset = 8;
		} else if (hostType == 3) { // Domain
			var len = this.buffer[4];
			host = ;
			offset = 4 + len;
		} else if (hostType == 4) { // IPv6
			this._error("TODO: ipv6 support!");
			offset = 20;
		} else {
			this._error("Invliad host specified");
		}
		console.log("Connecting to " + host);
	}
};

Socks5Proxy.prototype._error = function(msg) {
	this.state = SocksState.ERROR;
	console.log("Socks error:" + msg);
	this.client.disconnect();
}

Socks5Proxy.prototype._sendHello = function() {
	var msg = new Uint8Array(2);
	msg[0] = 5; // Version.
	msg[1] = 0; // No Authentication.
	this.client.sendRawMessage(msg.buffer);
};

window.addEventListener('load', startup, true);<commit_msg>connection request extracted<commit_after>var tcpServer;

var activeConnections = [];

function handleClientAccept(client) {
	activeConnections.push(new Socks5Proxy(client));
};

function startup() {
	tcpServer = new TcpServer("127.0.0.1", 8123);
	tcpServer.listen(handleClientAccept);
}

function Socks5Proxy(client) {
	this.client = client;
	this.callbacks = {
		request: null,  // Called when a resource is requested.
		recv: null  // Called when data is received for an outbound connection.
	};
	this.buffer = null;
	this.client.addDataReceivedListener(this._onDataRead.bind(this));
	this.state = SocksState.NEW;
}

const SocksState = {
	NEW: 0,
	CONNECTING: 1,
	CONNECTED: 2,
	ERROR: 3
};

Socks5Proxy.prototype._onDataRead = function(data) {
	if (!this.buffer && data.byteLength) {
		this.buffer = new Uint8Array(data);
	}

	// Parse Initial Connection Messages.
	if (this.state == SocksState.NEW && this.buffer) {
		if (this.buffer[0] != 5) {
			this._error("Client Handshake was invalid");
		}
		var length = this.buffer[1];
		if (this.buffer.length == length + 2) {
			this.buffer = null;
			this._sendHello();
			this.state = SocksState.CONNECTING;
		} else {
			// For now, fragmented handshake can be treated as an error
			this._error("Client Handshake was fragmented");
		}
	}
	// Parse Connection message.
	else if (this.state == SocksState.CONNECTING && this.buffer) {
		if (this.buffer[0] != 5 || this.buffer[2] != 0) {
			this._error("Client connect req had invalid protocol.");
		} else if (this.buffer[1] != 1) {
			this._error("Client requested either UDP or to bind a port. Unsupported!");
		}
		var hostType = this.buffer[3];
		var host = null;
		var offset = 4;
		if (hostType == 1) { // IPv4
			host = this.buffer[4] + "." + this.buffer[5] + "." + this.buffer[6] + "." + this.buffer[7];
			offset = 8;
		} else if (hostType == 3) { // Domain
			var len = this.buffer[4];
			host = _arrayToStringSynch(this.buffer.subarray(5, 5 + len));
			offset = 5 + len;
		} else if (hostType == 4) { // IPv6
			this._error("TODO: ipv6 support!");
			offset = 20;
		} else {
			this._error("Invalid host specified");
		}
		var port = this.buffer[offset] * 256 + this.buffer[offset + 1];

		console.log("Connecting to " + host + ":" + port);
	}
};

Socks5Proxy.prototype._error = function(msg) {
	this.state = SocksState.ERROR;
	console.log("Socks error:" + msg);
	this.client.disconnect();
}

Socks5Proxy.prototype._sendHello = function() {
	var msg = new Uint8Array(2);
	msg[0] = 5; // Version.
	msg[1] = 0; // No Authentication.
	this.client.sendRawMessage(msg.buffer);
};

function _arrayToStringSynch(array) {
	return Array.prototype.map.call(array, function(c) {return String.fromCharCode(c);}).join("");
}

window.addEventListener('load', startup, true);<|endoftext|>


<commit_before>/**
 * Create mappings between the names parsed from useragent to caniuse
 * name equivalents.  We support the caniuse names listed in the
 * `baselineVersion` map below.  This module must return one of these
 * family names, with a version matching the baseline range, for any
 * polyfills to be served.
 *
 * Multiple names may map to the same canonical caniuse family
 */

'use strict';

const useragent = require('useragent');

// Load additional useragent features: primarily to use: agent.satisfies to
// test a browser version against a semver string
require('useragent/features');

// Longest genuine UA seen so far: 255 chars (Facebook in-app on iOS):
const MAX_UA_LEN = 300;

// Use a local LRU cache rather than the one built into useragent, since that cannot be configured
const cache = require('lru-cache')({
	max: 5000
});

const baseLineVersions = {
	"ie": ">=7",
	"ie_mob": ">=8",
	"chrome": "*",
	"safari": ">=4",
	"ios_saf": ">=4",
	"ios_chr": ">=4",
	"firefox": ">=3.6",
	"firefox_mob": ">=4",
	"android": ">=3",
	"opera": ">=11",
	"op_mob": ">=10",
	"op_mini": ">=5",
	"bb": ">=6",
	"samsung_mob": ">=4"
};

/* Aliases may be expressed in three formats:
    1. <detectedfamily>: <targetfamily>
       The browser family is renamed, version is maintained
    2. <detectedfamily>: [<targetfamily>, <targetmajor>, <targetminor>, <targetpatch>]
       The browser family is renamed and the version is set to the one specified
    3. <detectedfamily>: { <semver>: [<targetfamily>, <targetmajor>, <targetminor>, <targetpatch>], ... }
       Specific version ranges of this family are mapped to the specified browsers
	4. <detectedfamily>: <function(uaObj)>
	   The function is called with the parsed UA object, and must return it (but may modify it first)
*/
const aliases = {
	"blackberry webkit": "bb",
	"blackberry": "bb",

	"pale moon (firefox variant)": "firefox",
	"pale moon": "firefox",
	"firefox mobile": "firefox_mob",
	"firefox namoroka": "firefox",
	"firefox shiretoko": "firefox",
	"firefox minefield": "firefox",
	"firefox alpha": "firefox",
	"firefox beta": "firefox",
	"microb": "firefox",
	"mozilladeveloperpreview": "firefox",
	"iceweasel": "firefox",

	"opera tablet": "opera",

	"opera mobile": "op_mob",
	"opera mini": "op_mini",

	"chrome mobile": "chrome",
	"chrome frame": "chrome",
	"chromium": "chrome",

	"ie mobile": "ie_mob",

	"ie large screen": "ie",
	"internet explorer": "ie",
	"edge": "ie",
	"edge mobile": "ie",
	"uc browser": {
		"9.9.*": ["ie", 10]
	},

	"chrome mobile ios": "ios_chr", // comes back as ios_saf

	"mobile safari": "ios_saf",
	"iphone": "ios_saf", // can't find a uastring which useragent returns iphone as family
	"iphone simulator": "ios_saf", // useragent returns either mobile safari or mobile safari uiwebview
	"mobile safari uiwebview": "ios_saf",
	"mobile safari ui/wkwebview": "ios_saf",

	"samsung internet": "samsung_mob",

	"phantomjs": ["safari", 5],

	"yandex browser": {
		"14.10": ["chrome", 37],
		"14.8": ["chrome", 36],
		"14.7": ["chrome", 35],
		"14.5": ["chrome", 34],
		"14.4": ["chrome", 33],
		"14.2": ["chrome", 32],
		"13.12": ["chrome", 30],
		"13.10": ["chrome", 28]
	},

	"opera": {
		"20": ["chrome", 33],
		"21": ["chrome", 34],
		"22": ["chrome", 35],
		"23": ["chrome", 36],
		"24": ["chrome", 37],
		"25": ["chrome", 38],
		"26": ["chrome", 39],
		"27": ["chrome", 40],
		"28": ["chrome", 41],
		"29": ["chrome", 42],
		"30": ["chrome", 43],
		"31": ["chrome", 44],
		"32": ["chrome", 45],
		"33": ["chrome", 46],
		"34": ["chrome", 47],
		"35": ["chrome", 48],
		"36": ["chrome", 49],
		"37": ["chrome", 50],
		"38": ["chrome", 51],
		"39": ["chrome", 52],
		"40": ["chrome", 53],
		"41": ["chrome", 54],
		"42": ["chrome", 55],
		"43": ["chrome", 56],
		"44": ["chrome", 57],
		"45": ["chrome", 58],
		"46": ["chrome", 59],
		"47": ["chrome", 60]
	}
};

function UA(uaString) {

	// Limit the length of the UA to avoid perf issues in UA parsing
	uaString = uaString.substr(0, MAX_UA_LEN);

	// The longest string that can possibly be a normalized browser name that we
	// support is XXXXXXXXXX/###.###.### (22 chars), so avoid doing the regex if
	// the input string is longer than that
	let normalized = (uaString.length < 22) && uaString.match(/^(\w+)\/(\d+)(?:\.(\d+)(?:\.(\d+))?)?$/i);
	if (!normalized) {
		normalized = cache.get(uaString);
	}
	if (normalized) {
		this.ua = new useragent.Agent(normalized[1], normalized[2], (normalized[3] || 0), (normalized[4] || 0));
	} else {

		/* Remove UA tokens that unnecessarily complicate UA parsing */

		// Chrome and Opera on iOS uses a UIWebView of the underlying platform to render
		// content. By stripping the CriOS or OPiOS strings, the useragent parser will alias the
		// user agent to ios_saf for the UIWebView, which is closer to the actual renderer
		uaString = uaString.replace(/((CriOS|OPiOS)\/(\d+)\.(\d+)\.(\d+)\.(\d+)|(FxiOS\/(\d+)\.(\d+)))/, '');

		// Vivaldi browser is recognised by UA module but is actually identical to Chrome, so
		// the best way to get accurate targeting is to remove the vivaldi token from the UA
		uaString = uaString.replace(/ vivaldi\/[\d\.]+\d+/i, '');

		// Facebook in-app browser `[FBAN/.....]` or `[FB_IAB/.....]` (see #990)
		uaString = uaString.replace(/ \[(FB_IAB|FBAN|FBIOS|FB4A)\/[^\]]+\]/i, '');

		// Electron ` Electron/X.Y.Z` (see #1129)
		uaString = uaString.replace(/ Electron\/[\d\.]+\d+/i, '');

		this.ua = useragent.parse(uaString);

		// For improved CDN cache performance, remove the patch version.  There are few cases in which a patch release drops the requirement for a polyfill, but if so, the polyfill can simply be served unnecessarily to the patch versions that contain the fix, and we can stop targeting at the next minor release.
		this.ua.patch = '0';

		// Resolve aliases
		this.ua.family = this.ua.family.toLowerCase();
		if (aliases[this.ua.family]) {

			// Custom aliasing
			if (typeof aliases[this.ua.family] === 'function') {
				Object.assign(this.ua, aliases[this.ua.family](this.ua));

			// Map to different family, use same version scheme
			} else if (typeof aliases[this.ua.family] === 'string') {
				this.ua.family = aliases[this.ua.family];

			// Map to different family with constant version
			} else if (Array.isArray(aliases[this.ua.family]) && aliases[this.ua.family].length >= 2) {
				const a = aliases[this.ua.family];
				this.ua = new useragent.Agent(a[0], a[1], (a[2] || 0), (a[3] || 0));

			// Map to different family with per-version mapping
			} else if (typeof aliases[this.ua.family] === 'object') {
				for (let semverExpr in aliases[this.ua.family]) {   // eslint-disable-line prefer-const
					if (this.ua.satisfies(semverExpr) && Array.isArray(aliases[this.ua.family][semverExpr])) {
						const a = aliases[this.ua.family][semverExpr];
						this.ua = new useragent.Agent(a[0], a[1], (a[2] || 0), (a[3] || 0));
						break;
					}
				}
			}
		}
		cache.set(uaString, ["", this.ua.family, this.ua.major, this.ua.minor, this.ua.patch]);
	}
}

UA.prototype.getFamily = function() {
	return this.ua.family;
};

UA.prototype.getVersion = function() {
	return this.ua.toVersion();
};

UA.prototype.satisfies = function() {
	return (
		this.ua.satisfies.apply(this.ua, arguments) &&
		this.ua.family in baseLineVersions &&
		this.ua.satisfies(baseLineVersions[this.ua.family])
	);
};
UA.prototype.getBaseline = function() {
	return baseLineVersions[this.ua.family];
};
UA.prototype.meetsBaseline = function() {
	return (this.ua.satisfies(baseLineVersions[this.ua.family]));
};
UA.prototype.isUnknown = function() {
	return (Object.keys(baseLineVersions).indexOf(this.ua.family) === -1) || !this.meetsBaseline();
};

UA.normalize = function(uaString) {
	if (uaString.match(/^\w+\/\d+(\.\d+(\.\d+)?)?$/i)) {
		return uaString.toLowerCase();
	}
	const ua = new UA(uaString);
	return ua ? ua.getFamily() + '/' + ua.getVersion() : undefined;
};

UA.getBaselines = function() {
	return baseLineVersions;
};

module.exports = UA;
<commit_msg>Remove code branch which can never be reached (#1302)<commit_after>/**
 * Create mappings between the names parsed from useragent to caniuse
 * name equivalents.  We support the caniuse names listed in the
 * `baselineVersion` map below.  This module must return one of these
 * family names, with a version matching the baseline range, for any
 * polyfills to be served.
 *
 * Multiple names may map to the same canonical caniuse family
 */

'use strict';

const useragent = require('useragent');

// Load additional useragent features: primarily to use: agent.satisfies to
// test a browser version against a semver string
require('useragent/features');

// Longest genuine UA seen so far: 255 chars (Facebook in-app on iOS):
const MAX_UA_LEN = 300;

// Use a local LRU cache rather than the one built into useragent, since that cannot be configured
const cache = require('lru-cache')({
	max: 5000
});

const baseLineVersions = {
	"ie": ">=7",
	"ie_mob": ">=8",
	"chrome": "*",
	"safari": ">=4",
	"ios_saf": ">=4",
	"ios_chr": ">=4",
	"firefox": ">=3.6",
	"firefox_mob": ">=4",
	"android": ">=3",
	"opera": ">=11",
	"op_mob": ">=10",
	"op_mini": ">=5",
	"bb": ">=6",
	"samsung_mob": ">=4"
};

/* Aliases may be expressed in three formats:
    1. <detectedfamily>: <targetfamily>
       The browser family is renamed, version is maintained
    2. <detectedfamily>: [<targetfamily>, <targetmajor>, <targetminor>, <targetpatch>]
       The browser family is renamed and the version is set to the one specified
    3. <detectedfamily>: { <semver>: [<targetfamily>, <targetmajor>, <targetminor>, <targetpatch>], ... }
       Specific version ranges of this family are mapped to the specified browsers
	4. <detectedfamily>: <function(uaObj)>
	   The function is called with the parsed UA object, and must return it (but may modify it first)
*/
const aliases = {
	"blackberry webkit": "bb",
	"blackberry": "bb",

	"pale moon (firefox variant)": "firefox",
	"pale moon": "firefox",
	"firefox mobile": "firefox_mob",
	"firefox namoroka": "firefox",
	"firefox shiretoko": "firefox",
	"firefox minefield": "firefox",
	"firefox alpha": "firefox",
	"firefox beta": "firefox",
	"microb": "firefox",
	"mozilladeveloperpreview": "firefox",
	"iceweasel": "firefox",

	"opera tablet": "opera",

	"opera mobile": "op_mob",
	"opera mini": "op_mini",

	"chrome mobile": "chrome",
	"chrome frame": "chrome",
	"chromium": "chrome",

	"ie mobile": "ie_mob",

	"ie large screen": "ie",
	"internet explorer": "ie",
	"edge": "ie",
	"edge mobile": "ie",
	"uc browser": {
		"9.9.*": ["ie", 10]
	},

	"chrome mobile ios": "ios_chr", // comes back as ios_saf

	"mobile safari": "ios_saf",
	"iphone": "ios_saf", // can't find a uastring which useragent returns iphone as family
	"iphone simulator": "ios_saf", // useragent returns either mobile safari or mobile safari uiwebview
	"mobile safari uiwebview": "ios_saf",
	"mobile safari ui/wkwebview": "ios_saf",

	"samsung internet": "samsung_mob",

	"phantomjs": ["safari", 5],

	"yandex browser": {
		"14.10": ["chrome", 37],
		"14.8": ["chrome", 36],
		"14.7": ["chrome", 35],
		"14.5": ["chrome", 34],
		"14.4": ["chrome", 33],
		"14.2": ["chrome", 32],
		"13.12": ["chrome", 30],
		"13.10": ["chrome", 28]
	},

	"opera": {
		"20": ["chrome", 33],
		"21": ["chrome", 34],
		"22": ["chrome", 35],
		"23": ["chrome", 36],
		"24": ["chrome", 37],
		"25": ["chrome", 38],
		"26": ["chrome", 39],
		"27": ["chrome", 40],
		"28": ["chrome", 41],
		"29": ["chrome", 42],
		"30": ["chrome", 43],
		"31": ["chrome", 44],
		"32": ["chrome", 45],
		"33": ["chrome", 46],
		"34": ["chrome", 47],
		"35": ["chrome", 48],
		"36": ["chrome", 49],
		"37": ["chrome", 50],
		"38": ["chrome", 51],
		"39": ["chrome", 52],
		"40": ["chrome", 53],
		"41": ["chrome", 54],
		"42": ["chrome", 55],
		"43": ["chrome", 56],
		"44": ["chrome", 57],
		"45": ["chrome", 58],
		"46": ["chrome", 59],
		"47": ["chrome", 60]
	}
};

function UA(uaString) {

	// Limit the length of the UA to avoid perf issues in UA parsing
	uaString = uaString.substr(0, MAX_UA_LEN);

	// The longest string that can possibly be a normalized browser name that we
	// support is XXXXXXXXXX/###.###.### (22 chars), so avoid doing the regex if
	// the input string is longer than that
	let normalized = (uaString.length < 22) && uaString.match(/^(\w+)\/(\d+)(?:\.(\d+)(?:\.(\d+))?)?$/i);
	if (!normalized) {
		normalized = cache.get(uaString);
	}
	if (normalized) {
		this.ua = new useragent.Agent(normalized[1], normalized[2], (normalized[3] || 0), (normalized[4] || 0));
	} else {

		/* Remove UA tokens that unnecessarily complicate UA parsing */

		// Chrome and Opera on iOS uses a UIWebView of the underlying platform to render
		// content. By stripping the CriOS or OPiOS strings, the useragent parser will alias the
		// user agent to ios_saf for the UIWebView, which is closer to the actual renderer
		uaString = uaString.replace(/((CriOS|OPiOS)\/(\d+)\.(\d+)\.(\d+)\.(\d+)|(FxiOS\/(\d+)\.(\d+)))/, '');

		// Vivaldi browser is recognised by UA module but is actually identical to Chrome, so
		// the best way to get accurate targeting is to remove the vivaldi token from the UA
		uaString = uaString.replace(/ vivaldi\/[\d\.]+\d+/i, '');

		// Facebook in-app browser `[FBAN/.....]` or `[FB_IAB/.....]` (see #990)
		uaString = uaString.replace(/ \[(FB_IAB|FBAN|FBIOS|FB4A)\/[^\]]+\]/i, '');

		// Electron ` Electron/X.Y.Z` (see #1129)
		uaString = uaString.replace(/ Electron\/[\d\.]+\d+/i, '');

		this.ua = useragent.parse(uaString);

		// For improved CDN cache performance, remove the patch version.  There are few cases in which a patch release drops the requirement for a polyfill, but if so, the polyfill can simply be served unnecessarily to the patch versions that contain the fix, and we can stop targeting at the next minor release.
		this.ua.patch = '0';

		// Resolve aliases
		this.ua.family = this.ua.family.toLowerCase();
		if (aliases[this.ua.family]) {

			// Custom aliasing
			if (typeof aliases[this.ua.family] === 'function') {
				Object.assign(this.ua, aliases[this.ua.family](this.ua));

			// Map to different family, use same version scheme
			} else if (typeof aliases[this.ua.family] === 'string') {
				this.ua.family = aliases[this.ua.family];

			// Map to different family with constant version
			} else if (Array.isArray(aliases[this.ua.family]) && aliases[this.ua.family].length >= 2) {
				const a = aliases[this.ua.family];
				this.ua = new useragent.Agent(a[0], a[1], (a[2] || 0), (a[3] || 0));

			// Map to different family with per-version mapping
			} else if (typeof aliases[this.ua.family] === 'object') {
				for (let semverExpr in aliases[this.ua.family]) {   // eslint-disable-line prefer-const
					if (this.ua.satisfies(semverExpr) && Array.isArray(aliases[this.ua.family][semverExpr])) {
						const a = aliases[this.ua.family][semverExpr];
						this.ua = new useragent.Agent(a[0], a[1], (a[2] || 0), (a[3] || 0));
						break;
					}
				}
			}
		}
		cache.set(uaString, ["", this.ua.family, this.ua.major, this.ua.minor, this.ua.patch]);
	}
}

UA.prototype.getFamily = function() {
	return this.ua.family;
};

UA.prototype.getVersion = function() {
	return this.ua.toVersion();
};

UA.prototype.satisfies = function() {
	return (
		this.ua.satisfies.apply(this.ua, arguments) &&
		this.ua.family in baseLineVersions &&
		this.ua.satisfies(baseLineVersions[this.ua.family])
	);
};
UA.prototype.getBaseline = function() {
	return baseLineVersions[this.ua.family];
};
UA.prototype.meetsBaseline = function() {
	return (this.ua.satisfies(baseLineVersions[this.ua.family]));
};
UA.prototype.isUnknown = function() {
	return (Object.keys(baseLineVersions).indexOf(this.ua.family) === -1) || !this.meetsBaseline();
};

UA.normalize = function(uaString) {
	if (uaString.match(/^\w+\/\d+(\.\d+(\.\d+)?)?$/i)) {
		return uaString.toLowerCase();
	}
	const ua = new UA(uaString);
	return ua.getFamily() + '/' + ua.getVersion();
};

UA.getBaselines = function() {
	return baseLineVersions;
};

module.exports = UA;
<|endoftext|>


<commit_before>/**
 * UDPING client
 */
"use strict";
const dgram = require("dgram");
const ip = require("ip");
const fs = require("fs");

class Client {
    constructor(host, port, wait, path, time, errCallback) {

        // この host,portは送り先を指す。
        this.host = host;
        this.port = port;
        this.count = 0;
        //何ミリ秒おきに送るか
        this.wait = wait || 1000;
        //回数制限
        this.time = Number(time) || 0;
        //保存先のパス
        this.savepath = path;
        //送ったらtrueになる
        this.sentflag = false;
        //最後に送った時間
        this.LaststartTime;
        //TimeoutやError が起こった際に呼ばれる関数。ない場合はfalseを入れる。
        this.errCallback = errCallback || false;

        //ソケット
        this.socket = dgram.createSocket("udp4");

        //スタンバイ
        this.stanby();

    }

    stanby() {
        //関数内でこのインスタンスのパラメーターにアクセスするために宣言。多分あんまり良くない
        let thisclient = this;
        //client側のポートは0を指定して自動指定させる。
        this.socket.bind(0, ip.address());
        thisclient.socket.on("listening", function() {
            let address = thisclient.socket.address();
            //サーバーの情報
            let host = thisclient.host;
            let port = thisclient.port;

            //logを表示する。
            let log_msg = `[UDPING]:CLIENT Client : ${address.address}:${address.port}\n[UDPING]:CLIENT Server : ${host}:${port}`;
            console.log(log_msg);

            fs.writeFileSync(thisclient.savepath, `${log_msg}\n`, "utf8");
        });

        //メッセージを受信した時、
        thisclient.socket.on("message", function(msg, rinfo) {
            ///受け取ったmsgの13文字目までが時間。なので、msgの13文字目までを切り取る。
            let endTime = new Date();
            let RTT = endTime.getTime() - Number(msg.slice(0, 13));
            //シーケンス番号を受け取る。 最初の13文字をなくしたものがそれ。
            let msg_count = Number(msg.slice(13));
            //logを表示する。
            let log_msg = `[UDPING]:CLIENT ${endTime.getTime()} ${rinfo.address}:${rinfo.port} RTT: ${RTT} ms. COUNT: ${msg_count}`;
            console.log(log_msg);
            //ファイルにログを書き込む
            fs.appendFileSync(thisclient.savepath, `${log_msg}\n`, 'utf8');

            //LaststartTimeを更新しておく
            thisclient.LaststartTime = endTime.getTime();

            //受け取ったのでfalseに。
            thisclient.sentflag = false;

        });
        //絶えず送信する
        setInterval(function() {
            thisclient.send();
        }, this.wait);
    }

    send() {
        let sendTime = new Date();
        //最後に発射した時間を入れておく
        this.LaststartTime = sendTime.getTime();
        //bufferの中身は
        /**
         * bufferInside = 時間count番号 (文字列連結)
         *
         */
        let bufferInside = this.LaststartTime.toString();
        //13文字目まではUNIXTIME。(UNIXTIMEが終わるまではなんとかなる。)
        let message = new Buffer(bufferInside + this.count);

        //現在のflagを確認
        let flag = this.sentflag;
        //関数内でこのインスタンスのパラメーターにアクセスするために宣言。多分あんまり良くない
        let thisclient = this;
        thisclient.socket.send(message, 0, message.length, thisclient.port, thisclient.host, function(err, bytes) {
            if (err) throw err;

            //まだ前に送ったやつを受け取ってなければ(sentflagがtrueのままなら)タイムアウト表示する。今送ったやつの-2個目がタイムアウトしてるやつ。
            if (flag) {
                //最初にerr用のコールバックがあれば実行。
                if (thisclient.errCallback) {
                    thisclient.errCallback();
                }

                let now = new Date();
                //2個前のもの
                let timeoutCount = thisclient.count - 2;
                //log表示
                let log_msg = `[UDPING]:CLIENT ${now.getTime()} REQUEST TIME OUT. COUNT: ${timeoutCount}`;
                console.log(log_msg);
                fs.appendFileSync(thisclient.savepath, `${log_msg}\n`, 'utf8');
            } else {
                //console.log('UDP message sent to ' + SERVER_INFO.ip +':'+ SERVER_INFO.port + ":");
            }
        });
        //送ったのでflagをtrueに。
        this.sentflag = true;
        //シーケンス番号を足す
        this.count++;

        //もし、-tオプションで設定した制限回数に達していて、その回数だけレスポンスが帰ってきていたら、(かつ、thisclient.time !== 0)
        if (this.time != 0 && this.count > this.time + 1) {
            console.log("[UDPING]:CLIENT PROCESS FINISH.");
            process.exit(0);
        }

    }

    stop() {
        //止める。
        this.socket.close();
    }

}

//モジュールに
module.exports = Client;<commit_msg>無駄なバインドを削除<commit_after>/**
 * UDPING client
 */
"use strict";
const dgram = require("dgram");
const ip = require("ip");
const fs = require("fs");

class Client {
    constructor(host, port, wait, path, time, errCallback) {

        // この host,portは送り先を指す。
        this.host = host;
        this.port = port;
        this.count = 0;
        //何ミリ秒おきに送るか
        this.wait = wait || 1000;
        //回数制限
        this.time = Number(time) || 0;
        //保存先のパス
        this.savepath = path;
        //送ったらtrueになる
        this.sentflag = false;
        //最後に送った時間
        this.LaststartTime;
        //TimeoutやError が起こった際に呼ばれる関数。ない場合はfalseを入れる。
        this.errCallback = errCallback || false;

        //ソケット
        this.socket = dgram.createSocket("udp4");

        //スタンバイ
        this.stanby();

    }

    stanby() {
        //関数内でこのインスタンスのパラメーターにアクセスするために宣言。多分あんまり良くない
        let thisclient = this;
        //client側のポートは0を指定して自動指定させる。
        this.socket.bind();
        thisclient.socket.on("listening", function() {
            let address = thisclient.socket.address();
            //サーバーの情報
            let host = thisclient.host;
            let port = thisclient.port;

            //logを表示する。
            let log_msg = `[UDPING]:CLIENT Client : ${address.address}:${address.port}\n[UDPING]:CLIENT Server : ${host}:${port}`;
            console.log(log_msg);

            fs.writeFileSync(thisclient.savepath, `${log_msg}\n`, "utf8");
        });

        //メッセージを受信した時、
        thisclient.socket.on("message", function(msg, rinfo) {
            ///受け取ったmsgの13文字目までが時間。なので、msgの13文字目までを切り取る。
            let endTime = new Date();
            let RTT = endTime.getTime() - Number(msg.slice(0, 13));
            //シーケンス番号を受け取る。 最初の13文字をなくしたものがそれ。
            let msg_count = Number(msg.slice(13));
            //logを表示する。
            let log_msg = `[UDPING]:CLIENT ${endTime.getTime()} ${rinfo.address}:${rinfo.port} RTT: ${RTT} ms. COUNT: ${msg_count}`;
            console.log(log_msg);
            //ファイルにログを書き込む
            fs.appendFileSync(thisclient.savepath, `${log_msg}\n`, 'utf8');

            //LaststartTimeを更新しておく
            thisclient.LaststartTime = endTime.getTime();

            //受け取ったのでfalseに。
            thisclient.sentflag = false;

        });
        //絶えず送信する
        setInterval(function() {
            thisclient.send();
        }, this.wait);
    }

    send() {
        let sendTime = new Date();
        //最後に発射した時間を入れておく
        this.LaststartTime = sendTime.getTime();
        //bufferの中身は
        /**
         * bufferInside = 時間count番号 (文字列連結)
         *
         */
        let bufferInside = this.LaststartTime.toString();
        //13文字目まではUNIXTIME。(UNIXTIMEが終わるまではなんとかなる。)
        let message = new Buffer(bufferInside + this.count);

        //現在のflagを確認
        let flag = this.sentflag;
        //関数内でこのインスタンスのパラメーターにアクセスするために宣言。多分あんまり良くない
        let thisclient = this;
        thisclient.socket.send(message, 0, message.length, thisclient.port, thisclient.host, function(err, bytes) {
            if (err) throw err;

            //まだ前に送ったやつを受け取ってなければ(sentflagがtrueのままなら)タイムアウト表示する。今送ったやつの-2個目がタイムアウトしてるやつ。
            if (flag) {
                //最初にerr用のコールバックがあれば実行。
                if (thisclient.errCallback) {
                    thisclient.errCallback();
                }

                let now = new Date();
                //2個前のもの
                let timeoutCount = thisclient.count - 2;
                //log表示
                let log_msg = `[UDPING]:CLIENT ${now.getTime()} REQUEST TIME OUT. COUNT: ${timeoutCount}`;
                console.log(log_msg);
                fs.appendFileSync(thisclient.savepath, `${log_msg}\n`, 'utf8');
            } else {
                //console.log('UDP message sent to ' + SERVER_INFO.ip +':'+ SERVER_INFO.port + ":");
            }
        });
        //送ったのでflagをtrueに。
        this.sentflag = true;
        //シーケンス番号を足す
        this.count++;

        //もし、-tオプションで設定した制限回数に達していて、その回数だけレスポンスが帰ってきていたら、(かつ、thisclient.time !== 0)
        if (this.time != 0 && this.count > this.time + 1) {
            console.log("[UDPING]:CLIENT PROCESS FINISH.");
            process.exit(0);
        }

    }

    stop() {
        //止める。
        this.socket.close();
    }

}

//モジュールに
module.exports = Client;
<|endoftext|>


<commit_before>var mongodbClient = require('mongodb').MongoClient;

var mongoUri =  process.env.MONGOLAB_URI ||
                process.env.MONGOHQ_URL ||
                'mongodb://localhost/mydb';
// var url = 'mongodb://127.0.0.1:27017/Communique';

var app = exports = module.exports = {};

app.init = function () {
    mongodbClient.connect(mongoUri, function (err, db) {
        db.dropDatabase(function (err, result) {
            db.dropCollection('item', function (err, result) {
                db.createCollection('item', function (err, collection){
                    if (err) {
                        console.log('Create Error');
                    } else {
                        console.log('Create Successed');
                    }
                    db.close();
                });
            });
        });
    });
};

app.insertData = function (data) {
    mongodbClient.connect(mongoUri, function (err, db) {
        db.collection('item').insert(data, function (err, records) {
            if (err) {
                console.log('Insert Error');
            } else {
                // console.log("Insert Successed");
                // console.log("Record added as", records[0]._id);
            }
            db.close();
        });
    });
};

app.queryData = function (filter, getResult) {
    mongodbClient.connect(mongoUri, function (err, db) {
        var collection = db.collection('item');
        collection.find(filter, {'sort':[['date','desc']]}).toArray(function (err, docs) {
            db.close();
            getResult(docs);
        });
    });
};
<commit_msg>fix bug<commit_after>var mongodbClient = require('mongodb').MongoClient;

var mongoUri =  process.env.MONGOLAB_URI ||
                process.env.MONGOHQ_URL ||
                'mongodb://localhost/mydb';
// var url = 'mongodb://127.0.0.1:27017/Communique';

var app = exports = module.exports = {};

app.init = function () {
    mongodbClient.connect(mongoUri, function (err, db) {
        db.dropDatabase(function (err, result) {
            db.dropCollection('item', function (err, result) {
                db.createCollection('item', function (err, collection){
                    if (err) {
                        console.log('Create Error');
                    } else {
                        console.log('Create Successed');
                    }
                    db.close();
                });
            });
        });
    });
};

app.insertData = function (data) {
    mongodbClient.connect(mongoUri, function (err, db) {
        if (err)
        {
            console.log(err);
        }
        var collection = db.collection('item');
        collection.insert(data, function (err, records) {
            if (err) {
                console.log('Insert Error');
            } else {
                // console.log("Insert Successed");
                // console.log("Record added as", records[0]._id);
            }
            db.close();
        });
    });
};

app.queryData = function (filter, getResult) {
    mongodbClient.connect(mongoUri, function (err, db) {
        var collection = db.collection('item');
        collection.find(filter, {'sort':[['date','desc']]}).toArray(function (err, docs) {
            db.close();
            getResult(docs);
        });
    });
};
<|endoftext|>


<commit_before>var mongo = require("mongodb");
var async = require("async");

exports.driver = db = null;

/*
 * Test and create db catalogs if not exists based on config object.
 */
exports.prepare = function( db_config, end_handler ){

	checkdb();

	var catalogs = db_config.system_catalogs.concat(db_config.user_catalogs);
	async.series(
	[
	function(next){//create system and user collections.
		async.forEach(catalogs,function(catalog_name,next){

			db.collection( catalog_name, function(err, collection){

				if( !collection ){

					db.createCollection( catalog_name, function(err, collection){

						if(err)
							throw err;
						else
							next();
					});
				}else
					next();
			});

		},function(err){

			next(err);
		});
	},
	function(next){//create journal index

		db.collection("events", function(err,collection){

			collection.ensureIndex("ev_data.wid",{unique:false},function(err){
				next(err);
			});
		});
	},
	function(next){//create users index.

		db.collection("users", function(err,collection){

			collection.ensureIndex("uid",{unique:false},function(err){
				next(err);
			});
		});
	}
	],function(err){

		end_handler(err, catalogs);
	});

}

/*
 * Close connection to db
 */
exports.close = function(){

	db && db.close();
	db = null;
}

/*
 * Connect to db before any other db operation.
 */
exports.connect = function( params, ret_handler ){

	if( db ){

		db.close();
	}

	params = params || {};
	params.dbhost = params.dbhost || "localhost";
	params.dbport = params.dbport || 27017;
	params.dbname = params.dbname || "jsa";

	exports.driver = db = new mongo.Db(params.dbname, new mongo.Server(params.dbhost,params.dbport,{auto_reconnect:true, socketOptions:{timeout:5000}}),{strict:true, safe:true}); //,poolSize:5,socketOptions:{timeout:1}

	db.open( function(err, client){

		if(client){
			if( params.dbuser !== undefined && params.dbpass !== undefined ){

				db.authenticate(params.dbuser,params.dbpass,function(err,client){

					if(client){
						console.log('**MongoDb driver auth-connected');
						if(ret_handler)
							ret_handler(null,1);
					}else{

						db = null;
						if(ret_handler)
							ret_handler(err,0);
					}
				});
			}else{
				if(ret_handler)
					ret_handler(null,1);
			}
		}else{

			db = null;
			if(ret_handler)
				ret_handler(err,0);
		}

	});

}

/*
 * Check db availability before any db operation.
 */
function checkdb(){

	if( !db )
		throw new Error("Driver not connected, should call connect first.");
}

/*
 * Save object to db.
 *
 */
var save = exports.save = function( col_name, obj, ret_handler ){

    checkdb();

	db.collection(col_name, function(err, collection){

	    collection.save( obj, {safe:true}, function(err, val){

			if( !err )
			    	ret_handler( null, val);
			else
				ret_handler(err,null);
	    });
	});

}

/*
 * Retrieve object from db by ID.
 *
 */
var select = exports.select = function( col_name, id_str, ret_handler ){

    checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    var ObjectID = require('mongodb').ObjectID;
	    collection.findOne({_id:new ObjectID(id_str)},function(err, object){

			if( !err )
			    ret_handler( null,object );
			else
				ret_handler(err,null);
	    });
	});

}

/*
 * Funcion para seleccionar documentos de la bbdd.
 */
var criteria = exports.criteria = function( col_name, criteria, order_field, ret_handler ){

  	checkdb();

	db.collection( col_name, function(err, collection){

    	collection.find(criteria,{}).sort(order_field).toArray(function(err, objects){

			if(!err)
				ret_handler(null,objects);
			else
				ret_handler( err, null );
		});

	});
}

/*
 * Remove object from db by ID.
 */
var removeById = exports.removeById = function( col_name, id_str, ret_handler){

	checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    var ObjectID = require('mongodb').ObjectID;
	    collection.remove( {_id:new ObjectID(id_str)} ,{safe:true},function(err, n){

			if( ret_handler )
				if( !err )
				    ret_handler( null, n );
			    else
			    	ret_handler(err,null);
	    });
	});

}

/*
 * Remove object from db by criteria.
 */
var remove = exports.remove = function( col_name, criteria, ret_handler){

	checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    collection.remove( criteria ,{safe:true},function(err, n){//n: number of rows/docs removed

			if( ret_handler )
				if( !err )
				    ret_handler( null, n );
			    else
			    	ret_handler(err,null);
	    });
	});

}

/*
 * Remove expired document from db, its events and timer.
 */
var remove_global = exports.remove_global = function( col_name, id_str, ret_handler ){

	async.series([
		function(end_handler){

			var rcpts;
			async.series([
				function(next){

					select(col_name, id_str,function(err,doc){

						if(err)
							next(err);
						else{
							rcpts = doc.rcpts;
							next();
						}

					});
				},function(next){

					async.forEach(rcpts, function(rcpt,next){

						select("users",rcpt,function(err,user){//remove wid from all users wids list

							var index = user.wids.indexOf(id_str);
							if(index != -1){
								user.wids.splice(index,1);
								save("users",user,function(err){next(err);});
							}else
								next();
						});
					},function(err){

						next(err);
					});
				}
			],function(err){

				end_handler(err);
			});

		},
		function( end_handler ){//remove doc by id

			removeById(col_name, id_str, function(err){

				end_handler(err);
			});
		},
		function( end_handler ){//remove  events related to doc id

			remove("events",{"ev_data.wid":id_str}, function(err,n){

				end_handler(err);
			});
		}
	], function(err,results){

		if(err)
			throw err;
		else
			ret_handler(null,1);
	});

}

<commit_msg>_noload:0 parameter added as a select projection.<commit_after>var mongo = require("mongodb");
var async = require("async");

exports.driver = db = null;

/*
 * Test and create db catalogs if not exists based on config object.
 */
exports.prepare = function( db_config, end_handler ){

	checkdb();

	var catalogs = db_config.system_catalogs.concat(db_config.user_catalogs);
	async.series(
	[
	function(next){//create system and user collections.
		async.forEach(catalogs,function(catalog_name,next){

			db.collection( catalog_name, function(err, collection){

				if( !collection ){

					db.createCollection( catalog_name, function(err, collection){

						if(err)
							throw err;
						else
							next();
					});
				}else
					next();
			});

		},function(err){

			next(err);
		});
	},
	function(next){//create journal index

		db.collection("events", function(err,collection){

			collection.ensureIndex("ev_data.wid",{unique:false},function(err){
				next(err);
			});
		});
	},
	function(next){//create users index.

		db.collection("users", function(err,collection){

			collection.ensureIndex("uid",{unique:false},function(err){
				next(err);
			});
		});
	}
	],function(err){

		end_handler(err, catalogs);
	});

}

/*
 * Close connection to db
 */
exports.close = function(){

	db && db.close();
	db = null;
}

/*
 * Connect to db before any other db operation.
 */
exports.connect = function( params, ret_handler ){

	if( db ){

		db.close();
	}

	params = params || {};
	params.dbhost = params.dbhost || "localhost";
	params.dbport = params.dbport || 27017;
	params.dbname = params.dbname || "jsa";

	exports.driver = db = new mongo.Db(params.dbname, new mongo.Server(params.dbhost,params.dbport,{auto_reconnect:true, socketOptions:{timeout:5000}}),{strict:true, safe:true}); //,poolSize:5,socketOptions:{timeout:1}

	db.open( function(err, client){

		if(client){
			if( params.dbuser !== undefined && params.dbpass !== undefined ){

				db.authenticate(params.dbuser,params.dbpass,function(err,client){

					if(client){
						console.log('**MongoDb driver auth-connected');
						if(ret_handler)
							ret_handler(null,1);
					}else{

						db = null;
						if(ret_handler)
							ret_handler(err,0);
					}
				});
			}else{
				if(ret_handler)
					ret_handler(null,1);
			}
		}else{

			db = null;
			if(ret_handler)
				ret_handler(err,0);
		}

	});

}

/*
 * Check db availability before any db operation.
 */
function checkdb(){

	if( !db )
		throw new Error("Driver not connected, should call connect first.");
}

/*
 * Save object to db.
 *
 */
var save = exports.save = function( col_name, obj, ret_handler ){

    checkdb();

	db.collection(col_name, function(err, collection){

	    collection.save( obj, {safe:true}, function(err, val){

			if( !err )
			    	ret_handler( null, val);
			else
				ret_handler(err,null);
	    });
	});

}

/*
 * Retrieve object from db by ID.
 *
 */
var select = exports.select = function( col_name, id_str, ret_handler ){

    checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    var ObjectID = require('mongodb').ObjectID;
	    collection.findOne({_id:new ObjectID(id_str)},{_noload:0},function(err, object){

			if( !err )
			    ret_handler( null,object );
			else
				ret_handler(err,null);
	    });
	});

}

/*
 * Funcion para seleccionar documentos de la bbdd.
 */
var criteria = exports.criteria = function( col_name, criteria, order_field, ret_handler ){

  	checkdb();

	db.collection( col_name, function(err, collection){

    	collection.find(criteria,{}).sort(order_field).toArray(function(err, objects){

			if(!err)
				ret_handler(null,objects);
			else
				ret_handler( err, null );
		});

	});
}

/*
 * Remove object from db by ID.
 */
var removeById = exports.removeById = function( col_name, id_str, ret_handler){

	checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    var ObjectID = require('mongodb').ObjectID;
	    collection.remove( {_id:new ObjectID(id_str)} ,{safe:true},function(err, n){

			if( ret_handler )
				if( !err )
				    ret_handler( null, n );
			    else
			    	ret_handler(err,null);
	    });
	});

}

/*
 * Remove object from db by criteria.
 */
var remove = exports.remove = function( col_name, criteria, ret_handler){

	checkdb();

	db.collection( col_name, function(err, collection){

		if(err){

			ret_handler(err,null);
			return;
		}

	    collection.remove( criteria ,{safe:true},function(err, n){//n: number of rows/docs removed

			if( ret_handler )
				if( !err )
				    ret_handler( null, n );
			    else
			    	ret_handler(err,null);
	    });
	});

}

/*
 * Remove expired document from db, its events and timer.
 */
var remove_global = exports.remove_global = function( col_name, id_str, ret_handler ){

	async.series([
		function(end_handler){

			var rcpts;
			async.series([
				function(next){

					select(col_name, id_str,function(err,doc){

						if(err)
							next(err);
						else{
							rcpts = doc.rcpts;
							next();
						}

					});
				},function(next){

					async.forEach(rcpts, function(rcpt,next){

						select("users",rcpt,function(err,user){//remove wid from all users wids list

							var index = user.wids.indexOf(id_str);
							if(index != -1){
								user.wids.splice(index,1);
								save("users",user,function(err){next(err);});
							}else
								next();
						});
					},function(err){

						next(err);
					});
				}
			],function(err){

				end_handler(err);
			});

		},
		function( end_handler ){//remove doc by id

			removeById(col_name, id_str, function(err){

				end_handler(err);
			});
		},
		function( end_handler ){//remove  events related to doc id

			remove("events",{"ev_data.wid":id_str}, function(err,n){

				end_handler(err);
			});
		}
	], function(err,results){

		if(err)
			throw err;
		else
			ret_handler(null,1);
	});

}

<|endoftext|>


<commit_before>var indexes = require("./indexes");

var db = {};
var options = {
    server: {
        auto_reconnect: true,
        poolSize: 10,
        socketOptions: {
            keepAlive: 1,
            socketTimeoutMS: 120000
        }
    },
    replSet: {
        strategy: "statistical"
    }
};

module.exports.init = function(config, mongo, plugin, callback){
    mongo.connect(config.connectionString, options, function(err, conn){
        if(err){
            return callback(err);
        }

        db[config.name] = conn;

        conn.on("error", function (err) {
            plugin.log(["database", "error"], err.toString());
        });

        conn.on("timeout", function (err) {
            plugin.log(["database", "timeout"], err.toString());
        });

        if(config.manageIndexes === false){
          return callback();
        }

        indexes.ensure(conn, config.indexes, plugin, callback);
    });
};

module.exports.get = function(name){
  return db[name];
};
<commit_msg>remove stringify on error object<commit_after>var indexes = require("./indexes");

var db = {};
var options = {
    server: {
        auto_reconnect: true,
        poolSize: 10,
        socketOptions: {
            keepAlive: 1,
            socketTimeoutMS: 120000
        }
    },
    replSet: {
        strategy: "statistical"
    }
};

module.exports.init = function(config, mongo, plugin, callback){
    mongo.connect(config.connectionString, options, function(err, conn){
        if(err){
            return callback(err);
        }

        db[config.name] = conn;

        conn.on("error", function (err) {
            plugin.log(["database", "error"], err);
        });

        conn.on("timeout", function (err) {
            plugin.log(["database", "timeout"], err);
        });

        if(config.manageIndexes === false){
          return callback();
        }

        indexes.ensure(conn, config.indexes, plugin, callback);
    });
};

module.exports.get = function(name){
  return db[name];
};
<|endoftext|>