<commit_before>module.exports = function (args, opts) {
    if (!opts) opts = {};

    var flags = { bools : {}, strings : {} };

    [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
        flags.bools[key] = true;
    });

    [].concat(opts.string).filter(Boolean).forEach(function (key) {
        flags.strings[key] = true;
    });

    var aliases = {};
    Object.keys(opts.alias || {}).forEach(function (key) {
        aliases[key] = [].concat(opts.alias[key]);
        aliases[key].forEach(function (x) {
            aliases[x] = [key].concat(aliases[key].filter(function (y) {
                return x !== y;
            }));
        });
    });

    var defaults = opts['default'] || {};

    var argv = { _ : [] };
    Object.keys(flags.bools).forEach(function (key) {
        setArg(key, defaults[key] === undefined ? false : defaults[key]);
    });

    var notFlags = [];

    if (args.indexOf('--') !== -1) {
        notFlags = args.slice(args.indexOf('--')+1);
        args = args.slice(0, args.indexOf('--'));
    }

    function setArg (key, val) {
        var value = !flags.strings[key] && isNumber(val)
            ? Number(val) : val
        ;
        setKey(argv, key.split('.'), value);

        (aliases[key] || []).forEach(function (x) {
            setKey(argv, x.split('.'), value);
        });
    }

    for (var i = 0; i < args.length; i++) {
        var arg = args[i];

        if (/^--.+=/.test(arg)) {
            // Using [\s\S] instead of . because js doesn't support the
            // 'dotall' regex modifier. See:
            // http://stackoverflow.com/a/1068308/13216
            var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
            setArg(m[1], m[2]);
        }
        else if (/^--no-.+/.test(arg)) {
            var key = arg.match(/^--no-(.+)/)[1];
            setArg(key, false);
        }
        else if (/^--.+/.test(arg)) {
            var key = arg.match(/^--(.+)/)[1];
            var next = args[i + 1];
            if (next !== undefined && !/^-/.test(next)
            && !flags.bools[key]
            && (aliases[key] ? !flags.bools[aliases[key]] : true)) {
                setArg(key, next);
                i++;
            }
            else if (/^(true|false)$/.test(next)) {
                setArg(key, next === 'true');
                i++;
            }
            else {
                setArg(key, flags.strings[key] ? '' : true);
            }
        }
        else if (/^-[^-]+/.test(arg)) {
            var letters = arg.slice(1,-1).split('');

            var broken = false;
            for (var j = 0; j < letters.length; j++) {
                var next = arg.slice(j+2);

                if (next === '-') {
                    setArg(letters[j], next)
                    continue;
                }

                if (/[A-Za-z]/.test(letters[j])
                && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                    setArg(letters[j], next);
                    broken = true;
                    break;
                }

                if (letters[j+1] && letters[j+1].match(/\W/)) {
                    setArg(letters[j], arg.slice(j+2));
                    broken = true;
                    break;
                }
                else {
                    setArg(letters[j], flags.strings[letters[j]] ? '' : true);
                }
            }

            var key = arg.slice(-1)[0];
            if (!broken && key !== '-') {
                if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
                && !flags.bools[key]
                && (aliases[key] ? !flags.bools[aliases[key]] : true)) {
                    setArg(key, args[i+1]);
                    i++;
                }
                else if (args[i+1] && /true|false/.test(args[i+1])) {
                    setArg(key, args[i+1] === 'true');
                    i++;
                }
                else {
                    setArg(key, flags.strings[key] ? '' : true);
                }
            }
        }
        else {
            argv._.push(
                flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
            );
        }
    }

    Object.keys(defaults).forEach(function (key) {
        if (!hasKey(argv, key.split('.'))) {
            setKey(argv, key.split('.'), defaults[key]);

            (aliases[key] || []).forEach(function (x) {
                setKey(argv, x.split('.'), defaults[key]);
            });
        }
    });

    notFlags.forEach(function(key) {
        argv._.push(key);
    });

    return argv;
};

function hasKey (obj, keys) {
    var o = obj;
    keys.slice(0,-1).forEach(function (key) {
        o = (o[key] || {});
    });

    var key = keys[keys.length - 1];
    return key in o;
}

function setKey (obj, keys, value) {
    var o = obj;
    keys.slice(0,-1).forEach(function (key) {
        if (o[key] === undefined) o[key] = {};
        o = o[key];
    });

    var key = keys[keys.length - 1];
    if (o[key] === undefined || typeof o[key] === 'boolean') {
        o[key] = value;
    }
    else if (Array.isArray(o[key])) {
        o[key].push(value);
    }
    else {
        o[key] = [ o[key], value ];
    }
}

function isNumber (x) {
    if (typeof x === 'number') return true;
    if (/^0x[0-9a-f]+$/i.test(x)) return true;
    return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

function longest (xs) {
    return Math.max.apply(null, xs.map(function (x) { return x.length }));
}
<commit_msg>Eliminate `longest` fn.<commit_after>module.exports = function (args, opts) {
    if (!opts) opts = {};

    var flags = { bools : {}, strings : {} };

    [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
        flags.bools[key] = true;
    });

    [].concat(opts.string).filter(Boolean).forEach(function (key) {
        flags.strings[key] = true;
    });

    var aliases = {};
    Object.keys(opts.alias || {}).forEach(function (key) {
        aliases[key] = [].concat(opts.alias[key]);
        aliases[key].forEach(function (x) {
            aliases[x] = [key].concat(aliases[key].filter(function (y) {
                return x !== y;
            }));
        });
    });

    var defaults = opts['default'] || {};

    var argv = { _ : [] };
    Object.keys(flags.bools).forEach(function (key) {
        setArg(key, defaults[key] === undefined ? false : defaults[key]);
    });

    var notFlags = [];

    if (args.indexOf('--') !== -1) {
        notFlags = args.slice(args.indexOf('--')+1);
        args = args.slice(0, args.indexOf('--'));
    }

    function setArg (key, val) {
        var value = !flags.strings[key] && isNumber(val)
            ? Number(val) : val
        ;
        setKey(argv, key.split('.'), value);

        (aliases[key] || []).forEach(function (x) {
            setKey(argv, x.split('.'), value);
        });
    }

    for (var i = 0; i < args.length; i++) {
        var arg = args[i];

        if (/^--.+=/.test(arg)) {
            // Using [\s\S] instead of . because js doesn't support the
            // 'dotall' regex modifier. See:
            // http://stackoverflow.com/a/1068308/13216
            var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
            setArg(m[1], m[2]);
        }
        else if (/^--no-.+/.test(arg)) {
            var key = arg.match(/^--no-(.+)/)[1];
            setArg(key, false);
        }
        else if (/^--.+/.test(arg)) {
            var key = arg.match(/^--(.+)/)[1];
            var next = args[i + 1];
            if (next !== undefined && !/^-/.test(next)
            && !flags.bools[key]
            && (aliases[key] ? !flags.bools[aliases[key]] : true)) {
                setArg(key, next);
                i++;
            }
            else if (/^(true|false)$/.test(next)) {
                setArg(key, next === 'true');
                i++;
            }
            else {
                setArg(key, flags.strings[key] ? '' : true);
            }
        }
        else if (/^-[^-]+/.test(arg)) {
            var letters = arg.slice(1,-1).split('');

            var broken = false;
            for (var j = 0; j < letters.length; j++) {
                var next = arg.slice(j+2);

                if (next === '-') {
                    setArg(letters[j], next)
                    continue;
                }

                if (/[A-Za-z]/.test(letters[j])
                && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                    setArg(letters[j], next);
                    broken = true;
                    break;
                }

                if (letters[j+1] && letters[j+1].match(/\W/)) {
                    setArg(letters[j], arg.slice(j+2));
                    broken = true;
                    break;
                }
                else {
                    setArg(letters[j], flags.strings[letters[j]] ? '' : true);
                }
            }

            var key = arg.slice(-1)[0];
            if (!broken && key !== '-') {
                if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
                && !flags.bools[key]
                && (aliases[key] ? !flags.bools[aliases[key]] : true)) {
                    setArg(key, args[i+1]);
                    i++;
                }
                else if (args[i+1] && /true|false/.test(args[i+1])) {
                    setArg(key, args[i+1] === 'true');
                    i++;
                }
                else {
                    setArg(key, flags.strings[key] ? '' : true);
                }
            }
        }
        else {
            argv._.push(
                flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
            );
        }
    }

    Object.keys(defaults).forEach(function (key) {
        if (!hasKey(argv, key.split('.'))) {
            setKey(argv, key.split('.'), defaults[key]);

            (aliases[key] || []).forEach(function (x) {
                setKey(argv, x.split('.'), defaults[key]);
            });
        }
    });

    notFlags.forEach(function(key) {
        argv._.push(key);
    });

    return argv;
};

function hasKey (obj, keys) {
    var o = obj;
    keys.slice(0,-1).forEach(function (key) {
        o = (o[key] || {});
    });

    var key = keys[keys.length - 1];
    return key in o;
}

function setKey (obj, keys, value) {
    var o = obj;
    keys.slice(0,-1).forEach(function (key) {
        if (o[key] === undefined) o[key] = {};
        o = o[key];
    });

    var key = keys[keys.length - 1];
    if (o[key] === undefined || typeof o[key] === 'boolean') {
        o[key] = value;
    }
    else if (Array.isArray(o[key])) {
        o[key].push(value);
    }
    else {
        o[key] = [ o[key], value ];
    }
}

function isNumber (x) {
    if (typeof x === 'number') return true;
    if (/^0x[0-9a-f]+$/i.test(x)) return true;
    return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

<|endoftext|>


<commit_before>var checksum = require('crc-32');
var dns = require('native-dns');
var winston = require('winston');
winston.cli();

if (process.argv.length < 4) {
  console.log('Usage: renamed <domain name> <public IP of server> <alt IP of server>');
  process.exit();
}
var rootTLD = process.argv[2].toLowerCase();
var myip = process.argv[3];
var altip = process.argv[4];
var sessionDigestKey = require('uuid').v4();

var createChecksum = function (client, server) {
  var str = client + '-' + server + '-' + sessionDigestKey;
  str = str.replace(/\./g, 'a').replace(/:/g, 'b');
  return Math.abs(checksum.str(str));
};

// Return [client,server] if query is valid, or false if not.
var validateQuery = function (query) {
  query = query.replace(/a/g, '.').replace(/b/g, ':');
  var parts = query.split('-');
  if (parts.length != 3) {
    return false;
  }
  var client = parts[0];
  var server = parts[1];
  var expectedChecksum = createChecksum(client, server);
  if (parts[2] === '' + expectedChecksum) {
    return [client, server];
  } else {
    return false;
  }
};

var setRootAuthority = function(resp, noA) {
  resp.authority.push(dns.NS({
    name: rootTLD,
    data: 'ns1.' + rootTLD,
    ttl: 5
  }));
  resp.authority.push(dns.NS({
    name: rootTLD,
    data: 'ns2.' + rootTLD,
    ttl: 5
  }));
  if (!noA) {
    resp.answer.push(dns.A({
      name: 'ns1.' + rootTLD,
      address: myip,
      ttl: 5
    }));
    resp.answer.push(dns.A({
      name: 'ns2.' + rootTLD,
      address: altip,
      ttl: 5
    }));
  }
  resp.authority.push(dns.SOA({
    name: rootTLD,
    primary: 'ns1.' + rootTLD,
    admin: 'measurement.' + rootTLD,
    serial: new Date().valueOf(),
    refresh: 5,
    retry: 5,
    expiration: 5,
    minimum: 5,
    ttl: 5
  }));
};

var setDelegatedAuthority = function(prefix, resp) {
  var delegatedCN = prefix + '.' + rootTLD;
  resp.authority.push(dns.NS({
    name: delegatedCN,
    data: 'ns1.' + delegatedCN,
    ttl: 5
  }));
  resp.authority.push(dns.NS({
    name: delegatedCN,
    data: 'ns2.' + delegatedCN,
    ttl: 5
  }));
  /*
  resp.authority.push(dns.SOA({
    name: delegatedCN,
    primary: 'ns1.' + delegatedCN,
    admin: 'measurement.' + rootTLD,
    serial: new Date().valueOf(),
    refresh: 5,
    retry: 5,
    expiration: 5,
    minimum: 5,
    ttl: 5
  }));
  */
};

var matchServer = function (client) {
  var server = ['208.67.220.220', '208.67.222.222']; //todo: roundrobin.
  return server;
};

var createPrefix = function (client, server) {
  var checksum = createChecksum(client, server);
  var prefix = client + '-' + server + '-' + checksum;
  return prefix.replace(/\./g, 'a').replace(/:/g, 'b');
};

// make a query to populate a server cache, so it can answer non-recursively
// despite not being authoritative
var fillCache = function (prefix, server, cb) {
  var question = dns.Question({
    name: prefix,
    type: 'A'
  });
  var req = dns.Request({
    question: question,
    server: { address: server, port: 53, type: 'udp'},
    timeout: 1000
  });
  req.on('end', cb);
  req.send();
};

var handler = function (req, resp) {
  if (req.question.length === 0) {
    return;
  }
  var query = req.question[0].name.toLowerCase();
  var addr = req.address.address;
  var prefix, resolvers;

  if (req.question[0].type != 1 && req.question[0].type != 2 && req.question[0].type != 255) {
    winston.info(addr + ' [' + req.question[0].type + '] ' + query);
  } else if (req.question[0].type == 2) { // NS request
    winston.info(addr + ' [NS] ' + query);
    setRootAuthority(resp);
    resp.send();
    return;
  } else if (req.question[0].type == 1 || req.question[0].type == 255) { // A/ANY request
    var lookuptype = (req.question[0].type == 255) ? 'ANY' : 'A';
    winston.info(addr + ' [' + lookuptype + '] ' + query);
    // Failures
    if (query.indexOf(rootTLD) === -1) {
      resp.answer.push(dns.A({
        name: query,
        address: myip,
        ttl: 5
      }));
      resp.send();
      return;
    // Initial query
    } else if (query === "ns1." + rootTLD || query === "ns2." + rootTLD) {
      setRootAuthority(resp);
      resp.send();
      return;
    } else if (query === rootTLD) {
      // TODO: record attempt at connectivity
      resolvers = matchServer(addr);
      prefix = createPrefix(addr, resolvers[0]);
      var delegatedCN = prefix + '.' + rootTLD;
      resp.header.ra = false;
      resp.answer.push(dns.CNAME({
        name: query,
        ttl: 5,
        data: 'resolve.' + delegatedCN
      }));
      setDelegatedAuthority(prefix, resp);
      resp.additional.push(dns.A({
        name: 'ns1.' + delegatedCN,
        address: resolvers[0],
        ttl: 5
      }));
      resp.additional.push(dns.A({
        name: 'ns2.' + delegatedCN,
        address: resolvers[1],
        ttl: 5
      }));
      fillCache('precache.' + delegatedCN, resolvers[0], function() {
        resp.send();
      });
      return;
    }

    // Successful indicaton of connectivity
    prefix = query.split(rootTLD)[0];
    prefix = prefix.substr(0, prefix.length - 1);
    var host = '';
    if (prefix.indexOf('.') > 0) {
      host = prefix.split('.');
      prefix = host[1];
      host = host[0];
    } else if (prefix.indexOf('success-') === 0) {
      host = 'success';
      prefix = prefix.substr(8);
    }
    var parts = validateQuery(prefix);
    if (parts === false) {
      resp.answer.push(dns.A({
        name: query,
        address: myip,
        ttl: 5
      }));
      resp.send();
      return;
    } else if (host === 'ns1' || host === 'ns2') {
      setDelegatedAuthority(prefix, resp);
      resolvers = matchServer(parts[0]);
      resp.answer.push(dns.A({
        name: 'ns1.' + prefix + '.' + rootTLD,
        address: resolvers[0],
        ttl: 5
      }));
      resp.answer.push(dns.A({
        name: 'ns2.' + prefix + '.' + rootTLD,
        address: resolvers[1],
        ttl: 5
      }));
      resp.send();
      return;
    } else if (host === 'precache') {
      // "poison" the cache of the authoritative resolver.
      resp.answer.push(dns.A({
        name: query,
        address: myip,
        ttl: 5
      }));
      resp.additional.push(dns.CNAME({
        name: "resolve." + prefix + '.' + rootTLD,
        ttl: 20,
        data: "success-" + prefix + '.' + rootTLD
      }));
      resp.send();
      return;
    } else if (host === 'success') {
      winston.info('Induced Connectivity between ' + parts[0] + ' and ' + parts[1] + ' via cache poisoning [seen by ' + addr + ']');
      resp.answer.push(dns.A({
        name: query,
        address: addr,
        ttl: 5
      }));
      resp.send();
      return;
    } else {
      // Queries for the cname are owned by the appropriate delegee.
      if (addr == parts[0]) {
        setDelegatedAuthority(prefix, resp);
        resolvers = matchServer(parts[0]);
        resp.additional.push(dns.A({
          name: 'ns1.' + prefix + '.' + rootTLD,
          address: resolvers[0],
          ttl: 5
        }));
        resp.additional.push(dns.A({
          name: 'ns2.' + prefix + '.' + rootTLD,
          address: resolvers[1],
          ttl: 5
        }));
        resp.send();
        return;
      } else {
        // TODO: Log success of client-server. query.
        // TODO: See if it's been made recently by same server, indicating response dropped.
        winston.info('Induced Connectivity between ' + parts[0] + ' and ' + parts[1] + ' [exposed as ' + addr + ']');
      /*
      resp.answer.push(dns.CNAME({
        name: query,
        ttl: 5,
        data: 'www.google.com'
      }));
      */
        resp.answer.push(dns.A({
          name: query,
          address: addr,
          ttl: 5
        }));
        resp.send();
        return;
      }
    }
  }
};

var server1 = dns.createServer();
server1.on('request', handler);
server1.on('error', function (err) {
  console.warn(err.stack);
});
var server2 = dns.createServer();
server2.on('request', handler);
server2.on('error', function (err) {
  console.warn(err.stack);
});

server1.serve(53, myip);
server2.serve(53, altip);
winston.info('Running for', rootTLD, myip, altip);
winston.info('Session Key is', sessionDigestKey);
<commit_msg>treat AAAA like A<commit_after>var checksum = require('crc-32');
var dns = require('native-dns');
var winston = require('winston');
winston.cli();

if (process.argv.length < 4) {
  console.log('Usage: renamed <domain name> <public IP of server> <alt IP of server>');
  process.exit();
}
var rootTLD = process.argv[2].toLowerCase();
var myip = process.argv[3];
var altip = process.argv[4];
var sessionDigestKey = require('uuid').v4();

var createChecksum = function (client, server) {
  var str = client + '-' + server + '-' + sessionDigestKey;
  str = str.replace(/\./g, 'a').replace(/:/g, 'b');
  return Math.abs(checksum.str(str));
};

// Return [client,server] if query is valid, or false if not.
var validateQuery = function (query) {
  query = query.replace(/a/g, '.').replace(/b/g, ':');
  var parts = query.split('-');
  if (parts.length != 3) {
    return false;
  }
  var client = parts[0];
  var server = parts[1];
  var expectedChecksum = createChecksum(client, server);
  if (parts[2] === '' + expectedChecksum) {
    return [client, server];
  } else {
    return false;
  }
};

var setRootAuthority = function(resp, noA) {
  resp.authority.push(dns.NS({
    name: rootTLD,
    data: 'ns1.' + rootTLD,
    ttl: 5
  }));
  resp.authority.push(dns.NS({
    name: rootTLD,
    data: 'ns2.' + rootTLD,
    ttl: 5
  }));
  if (!noA) {
    resp.answer.push(dns.A({
      name: 'ns1.' + rootTLD,
      address: myip,
      ttl: 5
    }));
    resp.answer.push(dns.A({
      name: 'ns2.' + rootTLD,
      address: altip,
      ttl: 5
    }));
  }
  resp.authority.push(dns.SOA({
    name: rootTLD,
    primary: 'ns1.' + rootTLD,
    admin: 'measurement.' + rootTLD,
    serial: new Date().valueOf(),
    refresh: 5,
    retry: 5,
    expiration: 5,
    minimum: 5,
    ttl: 5
  }));
};

var setDelegatedAuthority = function(prefix, resp) {
  var delegatedCN = prefix + '.' + rootTLD;
  resp.authority.push(dns.NS({
    name: delegatedCN,
    data: 'ns1.' + delegatedCN,
    ttl: 5
  }));
  resp.authority.push(dns.NS({
    name: delegatedCN,
    data: 'ns2.' + delegatedCN,
    ttl: 5
  }));
  /*
  resp.authority.push(dns.SOA({
    name: delegatedCN,
    primary: 'ns1.' + delegatedCN,
    admin: 'measurement.' + rootTLD,
    serial: new Date().valueOf(),
    refresh: 5,
    retry: 5,
    expiration: 5,
    minimum: 5,
    ttl: 5
  }));
  */
};

var matchServer = function (client) {
  var server = ['208.67.220.220', '208.67.222.222']; //todo: roundrobin.
  return server;
};

var createPrefix = function (client, server) {
  var checksum = createChecksum(client, server);
  var prefix = client + '-' + server + '-' + checksum;
  return prefix.replace(/\./g, 'a').replace(/:/g, 'b');
};

// make a query to populate a server cache, so it can answer non-recursively
// despite not being authoritative
var fillCache = function (prefix, server, cb) {
  var question = dns.Question({
    name: prefix,
    type: 'A'
  });
  var req = dns.Request({
    question: question,
    server: { address: server, port: 53, type: 'udp'},
    timeout: 1000
  });
  req.on('end', cb);
  req.send();
};

var handler = function (req, resp) {
  if (req.question.length === 0) {
    return;
  }
  var query = req.question[0].name.toLowerCase();
  var addr = req.address.address;
  var prefix, resolvers;

  if (req.question[0].type != 1 && req.question[0].type != 2 && req.question[0].type != 28 && req.question[0].type != 255) {
    winston.info(addr + ' [' + req.question[0].type + '] ' + query);
  } else if (req.question[0].type == 2) { // NS request
    winston.info(addr + ' [NS] ' + query);
    setRootAuthority(resp);
    resp.send();
    return;
  } else if (req.question[0].type == 1 || req.question[0].type === 28 || req.question[0].type == 255) { // A/ANY request
    var lookuptype = (req.question[0].type == 255) ? 'ANY' : (req.question[0].type == 28) ? 'AAAA' : 'A';
    winston.info(addr + ' [' + lookuptype + '] ' + query);
    // Failures
    if (query.indexOf(rootTLD) === -1) {
      resp.answer.push(dns.A({
        name: query,
        address: myip,
        ttl: 5
      }));
      resp.send();
      return;
    // Initial query
    } else if (query === "ns1." + rootTLD || query === "ns2." + rootTLD) {
      setRootAuthority(resp);
      resp.send();
      return;
    } else if (query === rootTLD) {
      // TODO: record attempt at connectivity
      resolvers = matchServer(addr);
      prefix = createPrefix(addr, resolvers[0]);
      var delegatedCN = prefix + '.' + rootTLD;
      resp.header.ra = false;
      resp.answer.push(dns.CNAME({
        name: query,
        ttl: 5,
        data: 'resolve.' + delegatedCN
      }));
      setDelegatedAuthority(prefix, resp);
      resp.additional.push(dns.A({
        name: 'ns1.' + delegatedCN,
        address: resolvers[0],
        ttl: 5
      }));
      resp.additional.push(dns.A({
        name: 'ns2.' + delegatedCN,
        address: resolvers[1],
        ttl: 5
      }));
      fillCache('precache.' + delegatedCN, resolvers[0], function() {
        resp.send();
      });
      return;
    }

    // Successful indicaton of connectivity
    prefix = query.split(rootTLD)[0];
    prefix = prefix.substr(0, prefix.length - 1);
    var host = '';
    if (prefix.indexOf('.') > 0) {
      host = prefix.split('.');
      prefix = host[1];
      host = host[0];
    } else if (prefix.indexOf('success-') === 0) {
      host = 'success';
      prefix = prefix.substr(8);
    }
    var parts = validateQuery(prefix);
    if (parts === false) {
      resp.answer.push(dns.A({
        name: query,
        address: myip,
        ttl: 5
      }));
      resp.send();
      return;
    } else if (host === 'ns1' || host === 'ns2') {
      setDelegatedAuthority(prefix, resp);
      resolvers = matchServer(parts[0]);
      resp.answer.push(dns.A({
        name: 'ns1.' + prefix + '.' + rootTLD,
        address: resolvers[0],
        ttl: 5
      }));
      resp.answer.push(dns.A({
        name: 'ns2.' + prefix + '.' + rootTLD,
        address: resolvers[1],
        ttl: 5
      }));
      resp.send();
      return;
    } else if (host === 'precache') {
      // "poison" the cache of the authoritative resolver.
      resp.answer.push(dns.A({
        name: query,
        address: myip,
        ttl: 5
      }));
      resp.additional.push(dns.CNAME({
        name: "resolve." + prefix + '.' + rootTLD,
        ttl: 20,
        data: "success-" + prefix + '.' + rootTLD
      }));
      resp.send();
      return;
    } else if (host === 'success') {
      winston.info('Induced Connectivity between ' + parts[0] + ' and ' + parts[1] + ' via cache poisoning [seen by ' + addr + ']');
      resp.answer.push(dns.A({
        name: query,
        address: addr,
        ttl: 5
      }));
      resp.send();
      return;
    } else {
      // Queries for the cname are owned by the appropriate delegee.
      if (addr == parts[0]) {
        setDelegatedAuthority(prefix, resp);
        resolvers = matchServer(parts[0]);
        resp.additional.push(dns.A({
          name: 'ns1.' + prefix + '.' + rootTLD,
          address: resolvers[0],
          ttl: 5
        }));
        resp.additional.push(dns.A({
          name: 'ns2.' + prefix + '.' + rootTLD,
          address: resolvers[1],
          ttl: 5
        }));
        resp.send();
        return;
      } else {
        // TODO: Log success of client-server. query.
        // TODO: See if it's been made recently by same server, indicating response dropped.
        winston.info('Induced Connectivity between ' + parts[0] + ' and ' + parts[1] + ' [exposed as ' + addr + ']');
      /*
      resp.answer.push(dns.CNAME({
        name: query,
        ttl: 5,
        data: 'www.google.com'
      }));
      */
        resp.answer.push(dns.A({
          name: query,
          address: addr,
          ttl: 5
        }));
        resp.send();
        return;
      }
    }
  }
};

var server1 = dns.createServer();
server1.on('request', handler);
server1.on('error', function (err) {
  console.warn(err.stack);
});
var server2 = dns.createServer();
server2.on('request', handler);
server2.on('error', function (err) {
  console.warn(err.stack);
});

server1.serve(53, myip);
server2.serve(53, altip);
winston.info('Running for', rootTLD, myip, altip);
winston.info('Session Key is', sessionDigestKey);
<|endoftext|>


<commit_before>//Power is connected to pin4 (5V), ground is pin6, tx (output) is pin 8,
// rx (input) is pin10
var ASQ = require('asynquence');
var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
	baudRate: 9600
});
//generic report manager
function report (msg, reportfn) {
	reportfn(msg);
};

function consoleRep (msg) {
	console.log(msg)
};

function emicRep (msg) {
	// body...
};

/*
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
	baudRate: 9600
});
*/
console.log('Successfully loaded SerialPort module');
console.log('Successfully initialised /dev/ttyAMA0');
var EMIC = (function() {
var isOpen = false;
var isReady = true;
var emic = {};

emic.init = function () {
	serialPort.on('open', function () {
		repEmic('Hello world')
		console.log('Port is open')
		isOpen = true;
		serialPort.on('data', function(msg) {
			msg = msg.toString('ascii');
			//console.log(msg);
			serialPort.flush();
			if (msg == ':') {
				isReady = true
				console.log('Emic is ready for an instruction')
			} else { console.log('errorcheck '+msg)}
		});
		//serialPort.write(':P0\r');
		//serialPort.drain();
		serialPort.write(':S[wiy<400,20>wih<300,25>sh<100>yu<200>ax<200,27>meh<200,25>riy<200,24>krih<300,22>s<100>mah<300>s<100>wih<400>wih<300,27>sh<100>yu<200>ax<200,29>meh<200,27>riy<200,25>krih<300,24>s<100>mah<300,20>s<100>wih<400>wih<300,29>sh<100>yu<200>ax<200,30>meh<200,29>riy<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100> GUH<300,20>D<100>TAY<400,25>DIH<200>NX<100>Z<100>TUW<400>YU<800,24>WER<400>EH<400,25>VRR<400,24>YU<400,22>AR<800,20>GUH<300,27>D<100>TAY<400,29>DIH<200,27>NX<100>Z<100>FOR<400,25>KRIH<300,32>S<100>MAH<300,20>S<100>AE<100>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100> WIY<400,20>WIH<300,25>SH<100>YU<200>AX<200,27>MER<200,25>RIY<200,24>KRIH<300,22>S<100>MAH<300>S<100>WIY<400>WIH<300,27>SH<100>YU<200>AX<200,29>MEH<200,27>RIY<200,25>KRIH<300,24>S<100>MAH<300,20>S<100>WIY<400>WIH<300,29>SH<100>YU<200>AX<200,30>MEH<200,29>RIY<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<800,25>]\r');
		//serialPort.write(':S[:PHONE ON] [:nv] [:dv gn 75] [wiy<400,20>wih<300,25>sh<100>yu<200>ax<200,27>meh<200,25>riy<200,24>krih<300,22>s<100>mah<300>s<100>wih<400>wih<300,27>sh<100>yu<200>ax<200,29>meh<200,27>riy<200,25>krih<300,24>s<100>mah<300,20>s<100>wih<400>wih<300,29>sh<100>yu<200>ax<200,30>meh<200,29>riy<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100>]. [GUH<300,20>D<100>TAY<400,25>DIH<200>NX<100>Z<100>TUW<400>YU<800,24>WER<400>EH<400,25>VRR<400,24>YU<400,22>AR<800,20>GUH<300,27>D<100>TAY<400,29>DIH<200,27>NX<100>Z<100>FOR<400,25>KRIH<300,32>S<100>MAH<300,20>S<100>AE<100>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100>]. [WIY<400,20>WIH<300,25>SH<100>YU<200>AX<200,27>MER<200,25>RIY<200,24>KRIH<300,22>S<100>MAH<300>S<100>WIY<400>WIH<300,27>SH<100>YU<200>AX<200,29>MEH<200,27>RIY<200,25>KRIH<300,24>S<100>MAH<300,20>S<100>WIY<400>WIH<300,29>SH<100>YU<200>AX<200,30>MEH<200,29>RIY<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<800,25>].\r');
	});
};
emic.speak = function (data) {
	data = data.toString('ascii');
	while (isOpen == false) {};
	if (data.length > 1000) {
		console.log('Error: Message exceeds the character limit');
	} else {
		//serialPort.write(':SHello World to all\r');
		serialPort.write(':S' + data + '\r');
		console.log(':S' + data + '\r');
		isReady = false
		console.log('Emic is busy')
		io.emit('emic message', 'Emic is busy')
	};
};

emic.demo = function (id) {
	id = id.toString('ascii');
	if (id == '0' || id == '1' || id == '2') {
		serialPort.write(':D' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.stopNow = function () {
	serialPort.write(':X\r');
}

emic.pause = function () {
	serialPort.write(':Z\r');
};

emic.voice = function (id) {
	var idN = id.parseInt();
	if (idN >= 0 && idN <= 8) {
		id.toString('ascii');
		serialPort.write(':N' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.volume = function (level) {
	var levelN = id.parseInt();
	if (levelN >= -48 && levelN <= 18) {
		level = level.toString('ascii');
		serialPort.write(':V' + level + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.rate = function (wpm) {
	var wpmN = wpm.parseInt();
	if (wpmN >= 75 && wpmN <= 600) {
		wpm = wpm.toString('ascii');
		serialPort.write(':W' + wpm + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.parser = function (id) {
	id = id.toString('ascii');
	if (parser == '0' || parser == '1' || parser == '2') {
		serialPort.write(':P' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.revert = function () {
	serialPort.write(':R\r');
};

emic.callCurrentSettings = function () {
	serialPort.write(':C\r');
};

emic.callVersionInfo = function () {
	serialPort.write(':I\r');
};

emic.callCommands = function () {
	serialPort.write(':I\r');
};
return emic
}());

/*function writeLog(logFile, output){
	var logf = new File(logFile);
	logf.writeln(output);
	logf.close()*/

module.exports = EMIC;

<commit_msg>added timeout sequence<commit_after>//Power is connected to pin4 (5V), ground is pin6, tx (output) is pin 8,
// rx (input) is pin10
var ASQ = require('asynquence');
var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
	baudRate: 9600
});
//generic report manager
function report (msg, reportfn) {
	reportfn(msg);
};

function consoleRep (msg) {
	console.log(msg)
};

function emicRep (msg) {
	// body...
};

/*
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
	baudRate: 9600
});
*/
console.log('Successfully loaded SerialPort module');
console.log('Successfully initialised /dev/ttyAMA0');
var EMIC = (function() {
var isOpen = false;
var isReady = true;
var emic = {};
var counter = 10;

emic.init = function () {
	serialPort.on('open', function () {
		repEmic('Hello world')
		console.log('Port is open')
		isOpen = true;
		serialPort.on('data', function(msg) {
			msg = msg.toString('ascii');
			//console.log(msg);
			serialPort.flush();
			if (msg == ':') {
				isReady = true
				console.log('Emic is ready for an instruction')
			} else { console.log('errorcheck '+msg)}
		});
		while (counter > 0) {
			counter -= 1;
			repEmic('hello');
			setTimeout(1000);
		};
		//serialPort.write(':P0\r');
		//serialPort.drain();
		//serialPort.write(':S[wiy<400,20>wih<300,25>sh<100>yu<200>ax<200,27>meh<200,25>riy<200,24>krih<300,22>s<100>mah<300>s<100>wih<400>wih<300,27>sh<100>yu<200>ax<200,29>meh<200,27>riy<200,25>krih<300,24>s<100>mah<300,20>s<100>wih<400>wih<300,29>sh<100>yu<200>ax<200,30>meh<200,29>riy<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100> GUH<300,20>D<100>TAY<400,25>DIH<200>NX<100>Z<100>TUW<400>YU<800,24>WER<400>EH<400,25>VRR<400,24>YU<400,22>AR<800,20>GUH<300,27>D<100>TAY<400,29>DIH<200,27>NX<100>Z<100>FOR<400,25>KRIH<300,32>S<100>MAH<300,20>S<100>AE<100>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100> WIY<400,20>WIH<300,25>SH<100>YU<200>AX<200,27>MER<200,25>RIY<200,24>KRIH<300,22>S<100>MAH<300>S<100>WIY<400>WIH<300,27>SH<100>YU<200>AX<200,29>MEH<200,27>RIY<200,25>KRIH<300,24>S<100>MAH<300,20>S<100>WIY<400>WIH<300,29>SH<100>YU<200>AX<200,30>MEH<200,29>RIY<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<800,25>]\r');
		//serialPort.write(':S[:PHONE ON] [:nv] [:dv gn 75] [wiy<400,20>wih<300,25>sh<100>yu<200>ax<200,27>meh<200,25>riy<200,24>krih<300,22>s<100>mah<300>s<100>wih<400>wih<300,27>sh<100>yu<200>ax<200,29>meh<200,27>riy<200,25>krih<300,24>s<100>mah<300,20>s<100>wih<400>wih<300,29>sh<100>yu<200>ax<200,30>meh<200,29>riy<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100>]. [GUH<300,20>D<100>TAY<400,25>DIH<200>NX<100>Z<100>TUW<400>YU<800,24>WER<400>EH<400,25>VRR<400,24>YU<400,22>AR<800,20>GUH<300,27>D<100>TAY<400,29>DIH<200,27>NX<100>Z<100>FOR<400,25>KRIH<300,32>S<100>MAH<300,20>S<100>AE<100>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<600,25>_<100>]. [WIY<400,20>WIH<300,25>SH<100>YU<200>AX<200,27>MER<200,25>RIY<200,24>KRIH<300,22>S<100>MAH<300>S<100>WIY<400>WIH<300,27>SH<100>YU<200>AX<200,29>MEH<200,27>RIY<200,25>KRIH<300,24>S<100>MAH<300,20>S<100>WIY<400>WIH<300,29>SH<100>YU<200>AX<200,30>MEH<200,29>RIY<200,27>KRIH<300,25>S<100>MAH<300,22>S<100>AE<100,20>N<50>D<50>AX<200>HXAE<400,22>PIY<400,27>NUW<400,24>YXIR<800,25>].\r');
	});
};
emic.speak = function (data) {
	data = data.toString('ascii');
	while (isOpen == false) {};
	if (data.length > 1000) {
		console.log('Error: Message exceeds the character limit');
	} else {
		//serialPort.write(':SHello World to all\r');
		serialPort.write(':S' + data + '\r');
		console.log(':S' + data + '\r');
		isReady = false
		console.log('Emic is busy')
		io.emit('emic message', 'Emic is busy')
	};
};

emic.demo = function (id) {
	id = id.toString('ascii');
	if (id == '0' || id == '1' || id == '2') {
		serialPort.write(':D' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.stopNow = function () {
	serialPort.write(':X\r');
}

emic.pause = function () {
	serialPort.write(':Z\r');
};

emic.voice = function (id) {
	var idN = id.parseInt();
	if (idN >= 0 && idN <= 8) {
		id.toString('ascii');
		serialPort.write(':N' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.volume = function (level) {
	var levelN = id.parseInt();
	if (levelN >= -48 && levelN <= 18) {
		level = level.toString('ascii');
		serialPort.write(':V' + level + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.rate = function (wpm) {
	var wpmN = wpm.parseInt();
	if (wpmN >= 75 && wpmN <= 600) {
		wpm = wpm.toString('ascii');
		serialPort.write(':W' + wpm + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.parser = function (id) {
	id = id.toString('ascii');
	if (parser == '0' || parser == '1' || parser == '2') {
		serialPort.write(':P' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.revert = function () {
	serialPort.write(':R\r');
};

emic.callCurrentSettings = function () {
	serialPort.write(':C\r');
};

emic.callVersionInfo = function () {
	serialPort.write(':I\r');
};

emic.callCommands = function () {
	serialPort.write(':I\r');
};
return emic
}());

/*function writeLog(logFile, output){
	var logf = new File(logFile);
	logf.writeln(output);
	logf.close()*/

module.exports = EMIC;

<|endoftext|>


<commit_before>var tsc = require('typescript-compiler');

var TypescriptCompiler = function (config) {
  // TODO: support for compiler options
};

TypescriptCompiler.prototype.brunchPlugin = true;
TypescriptCompiler.prototype.type = 'javascript';
TypescriptCompiler.prototype.extension = "ts";

TypescriptCompiler.prototype.compile = function (data, path, callback) {
  var compiled = tsc.compileString(data, null, null, function (error) {
    return callback(error.formattedMessage);
  });

  return callback(null, {data: compiled});
};

module.exports = TypescriptCompiler;
<commit_msg>dont invoke callback twice<commit_after>var tsc = require('typescript-compiler');

var TypescriptCompiler = function (config) {
  // TODO: support for compiler options
};

TypescriptCompiler.prototype.brunchPlugin = true;
TypescriptCompiler.prototype.type = 'javascript';
TypescriptCompiler.prototype.extension = "ts";

TypescriptCompiler.prototype.compile = function (data, path, callback) {
  var compiled = tsc.compileString(data, null, null, function (error) {
    callback(error.formattedMessage);
  });

  if (compiled) {
    return callback(null, {data: compiled});
  }
};

module.exports = TypescriptCompiler;
<|endoftext|>


<commit_before>#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var _ = require('underscore')

//
// Configurations
//
var PORT = 5000

//
// Create and start http server
//
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);

    // We're only handling websockets, so return 404 when we receive http request
    response.writeHead(404);
    response.end();
});

server.listen(PORT, function() {
    console.log((new Date()) + ' Server is listening on port ' + PORT);
});

//
// Create websocket server
//
wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: true
});

// Generates an incrementing ID whenever called
var genID = function() {
  var counter = 0;
  return function() {
    return counter++;
  }
}();

// connection ID to connection
OpenConnections = {};

wsServer.on('connect', function(connection) {

    // Give this socket an ID and add it to our collection of open connections
    var socketID = genID();
    OpenConnections[socketID] = connection;
    console.log('Player ' + socketID + ' connected');

    connection.on('message', function(message) {
      // Can't handle binary data
      if (message.type !== 'utf8') {
        console.log('Can only handle utf8 data');
        return;
      }

      console.log('Received Message: ' + message.utf8Data);

      // Forward message to all clients except this one
      _.each(OpenConnections, function(conn, id) {
        if (id != socketID) {
          var msg = {
            "player": socketID,
            "event": "update",
            "data": message.utf8Data
          };
          conn.sendUTF(JSON.stringify(msg));
        }
      });
    });

    connection.on('close', function(reasonCode, description) {
      console.log('Player ' + socketID + ' disconnected.');

      // Remove from our collection of open connections
      delete OpenConnections[socketID]

      // Tell all other clients that a player left
      _.each(OpenConnections, function(conn, id) {
        var msg = {
          "player": socketID,
          "event": "disconnect"
        };
        conn.sendUTF(JSON.stringify(msg));
      });
    });

});
<commit_msg>First deserialize message, then serialize wrapper<commit_after>#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var _ = require('underscore')

//
// Configurations
//
var PORT = 5000

//
// Create and start http server
//
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);

    // We're only handling websockets, so return 404 when we receive http request
    response.writeHead(404);
    response.end();
});

server.listen(PORT, function() {
    console.log((new Date()) + ' Server is listening on port ' + PORT);
});

//
// Create websocket server
//
wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: true
});

// Generates an incrementing ID whenever called
var genID = function() {
  var counter = 0;
  return function() {
    return counter++;
  }
}();

// connection ID to connection
OpenConnections = {};

wsServer.on('connect', function(connection) {

    // Give this socket an ID and add it to our collection of open connections
    var socketID = genID();
    OpenConnections[socketID] = connection;
    console.log('Player ' + socketID + ' connected');

    connection.on('message', function(message) {
      // Can't handle binary data
      if (message.type !== 'utf8') {
        console.log('Can only handle utf8 data');
        return;
      }

      console.log('Received Message: ' + message.utf8Data);

      // Forward message to all clients except this one
      _.each(OpenConnections, function(conn, id) {
        if (id != socketID) {
          var msg = {
            "player": socketID,
            "event": "update",
            "data": JSON.parse(message.utf8Data)
          };
          conn.sendUTF(JSON.stringify(msg));
        }
      });
    });

    connection.on('close', function(reasonCode, description) {
      console.log('Player ' + socketID + ' disconnected.');

      // Remove from our collection of open connections
      delete OpenConnections[socketID]

      // Tell all other clients that a player left
      _.each(OpenConnections, function(conn, id) {
        var msg = {
          "player": socketID,
          "event": "disconnect"
        };
        conn.sendUTF(JSON.stringify(msg));
      });
    });

});
<|endoftext|>


<commit_before>throw new Error
var composers = {
    composeSerializer: require('./composers/serializers/bff'),
    composeParser: require('./composers/parsers/bff'),
    composeSizeOf: require('./composers/sizeof')
}

function padify (pattern) {
    var padded = []
    pattern.forEach(function (field) {
        if (field.padding) {
            padded.push({
                endianess: 'padding',
                padding: field.padding,
                name: field.name,
                bytes: field.bytes,
                repeat: field.repeat
            })
        }
        padded.push(field)
    })
    return padded
}

function rangify (pattern) {
    pattern = padify(pattern)

    pattern.forEach(function (field, index) {
        field.index = index
    })

    var ranges = [{ size: 0, fixed: true, pattern: [] }]

    pattern.forEach(function (field, index) {
        ranges[ranges.length - 1].size += field.bytes * field.repeat
        ranges[ranges.length - 1].pattern.push(field)
        if (field.lengthEncoding) {
            ranges[ranges.length - 1].name = pattern[index + 1].name
            ranges.push({
                lengthEncoded: true,
                size: 0,
                fixed: false,
                pattern: []
            })
        }
    })

    return ranges
}

function Packetizer (options) {
    this._options = options
}

var fs = require('fs'), path = require('path'), namify = require('./t/name')

Packetizer.prototype._load = function (prefix, pattern) {
    var pattern = parse(pattern)
    var name = namify(prefix, pattern)
    return require(path.join(__dirname, 't', 'generated', name + '.js'))
}

Packetizer.prototype.createParser = function (pattern) {
    var _pattern = parse(pattern)
    var ranges = rangify(_pattern)
    var prefix = [ 'parse.bff' ]

    var parser = composers.composeParser(ranges)

    return this._options.precompiler(prefix.join('.'), _pattern, [ 'object', 'callback' ], parser)
}

Packetizer.prototype.createSerializer = function (pattern) {
    var _pattern = parse(pattern)
    var ranges = rangify(_pattern)
    var prefix = [ 'serialize.bff' ]

    var serializer = composers.composeSerializer(ranges)

    return this._options.precompiler(prefix.join('.'), _pattern, [ 'object', 'callback' ], serializer)
}

Packetizer.prototype.createSizeOf = function (pattern) {
    var pattern = parse(pattern)
    var ranges = rangify(pattern)
    var prefix = [ 'sizeOf' ]

    var sizeOf = composers.composeSizeOf(ranges)

    return this._options.precompiler(prefix.join('.'), pattern, [ 'object' ], sizeOf)
}

function createPacketizer (options) {
    return new Packetizer(options || {})
}

exports.createPacketizer = createPacketizer
<commit_msg>Remove old `index.js`.<commit_after><|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')({
    transports: ['websocket'],
});

//app.get('/', function(req, res){
//  res.sendFile(__dirname + '/index.html');
//	res.send(process.env.PORT);
//});
var roomList = [];
var playerList = [];
io.on('connection', function (socket)
{
    //socket.emit('newplayer');
    //socket.broadcast.emit('newplayer');
    var playerId = String(new Date().getTime());
    playerList.push(playerId);
    socket.emit('connected', {playerid: playerId});
    //socket.to('others').emit('newplayer');
//    socket.on('beep', function ()
//    {
//        socket.emit('boopeeeee');
//    });
    socket.on('createroom', function (msg)
    {
        var roomId = String(new Date().getTime());
        roomList.push(new room(roomId, msg.roomname, [msg.playerid]));
        socket.emit('roomid', {roomid: roomId});
    });

    socket.on('addme', function (msg)
    {
        var newPlayerId = String(new Date().getTime());
        socket.emit('playeradded', {playerid: newPlayerId});
        socket.broadcast.emit('newplayer', {playerid: newPlayerId});
        //socket.emit('roomlist', JSON.stringify(roomList));
    });
    socket.on('getrooms', function (msg)
    {
//        socket.emit('roomlist', JSON.stringify(roomList));
        socket.emit('roomlist', {roomlist: roomList});
    });
    socket.on('joinroom', function (msg)
    {
//        var roomId = String(new Date().getTime());
//        roomList.push(roomId);
//        socket.emit('roomid', {roomid: roomId});
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomname) {
                if (!roomList[i].isPlayerHere(msg.playerid))
                {
                    roomList[i].userList.push(msg.playerid);
                    socket.broadcast.emit('newplayer', {playerid: msg.playerid});
                    socket.emit('joined', {roomid: msg.roomname, otherplayers: roomList[i].getOtherPlayers(msg.playerid)});
                }
            }
        }
    });

    socket.on('position', function (msg)
    {
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomid) {
                //socket.emit('joined');
                socket.broadcast.to(msg.roomid).emit('position', msg);
                //io.emit('position', msg);
            }
        }
    });
});
io.attach(process.env.PORT || 5000);
//http.listen(process.env.PORT || 5000);
class room {
    constructor(roomId, roomName, userList) {
        this.roomId = roomId;
        this.roomName = roomName;
        this.userList = userList;
    }
    isPlayerHere(playerid) {
        var playerListSize = this.userList.length;
        for (var i = 0; i < playerListSize; i++) {
            if (this.userList[i] == playerid) {
                return true;
            }
        }
        return false;
    }
    getOtherPlayers(playerid) {
        var playerListSize = this.userList.length;
        var playerList=[];
        for (var i = 0; i < playerListSize; i++) {
            if (userList[i] != playerid) {
                playerList.push(this.userList[i]);
            }
        }
        return playerList;
    }
}<commit_msg>asdasd<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')({
    transports: ['websocket'],
});

//app.get('/', function(req, res){
//  res.sendFile(__dirname + '/index.html');
//	res.send(process.env.PORT);
//});
var roomList = [];
var playerList = [];
io.on('connection', function (socket)
{
    //socket.emit('newplayer');
    //socket.broadcast.emit('newplayer');
    var playerId = String(new Date().getTime());
    playerList.push(playerId);
    socket.emit('connected', {playerid: playerId});
    //socket.to('others').emit('newplayer');
//    socket.on('beep', function ()
//    {
//        socket.emit('boopeeeee');
//    });
    socket.on('createroom', function (msg)
    {
        var roomId = String(new Date().getTime());
        roomList.push(new room(roomId, msg.roomname, [msg.playerid]));
        socket.emit('roomid', {roomid: roomId});
    });

    socket.on('addme', function (msg)
    {
        var newPlayerId = String(new Date().getTime());
        socket.emit('playeradded', {playerid: newPlayerId});
        socket.broadcast.emit('newplayer', {playerid: newPlayerId});
        //socket.emit('roomlist', JSON.stringify(roomList));
    });
    socket.on('getrooms', function (msg)
    {
//        socket.emit('roomlist', JSON.stringify(roomList));
        socket.emit('roomlist', {roomlist: roomList});
    });
    socket.on('joinroom', function (msg)
    {
//        var roomId = String(new Date().getTime());
//        roomList.push(roomId);
//        socket.emit('roomid', {roomid: roomId});
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomname) {
                if (!roomList[i].isPlayerHere(msg.playerid))
                {
                    roomList[i].userList.push(msg.playerid);
                    socket.broadcast.to(msg.roomid).emit('newplayer', {playerid: msg.playerid});
                    socket.emit('joined', {roomid: msg.roomname, otherplayers: roomList[i].getOtherPlayers(msg.playerid)});
                }
            }
        }
    });

    socket.on('position', function (msg)
    {
        var roomListSize = roomList.length;
        for (var i = 0; i < roomListSize; i++) {
            if (roomList[i].roomId == msg.roomid) {
                //socket.emit('joined');
                socket.broadcast.to(msg.roomid).emit('position', msg);
                //io.emit('position', msg);
            }
        }
    });
});
io.attach(process.env.PORT || 5000);
//http.listen(process.env.PORT || 5000);
class room {
    constructor(roomId, roomName, userList) {
        this.roomId = roomId;
        this.roomName = roomName;
        this.userList = userList;
    }
    isPlayerHere(playerid) {
        var playerListSize = this.userList.length;
        for (var i = 0; i < playerListSize; i++) {
            if (this.userList[i] == playerid) {
                return true;
            }
        }
        return false;
    }
    getOtherPlayers(playerid) {
        var playerListSize = this.userList.length;
        var playerList=[];
        for (var i = 0; i < playerListSize; i++) {
            if (userList[i] != playerid) {
                playerList.push(this.userList[i]);
            }
        }
        return playerList;
    }
}<|endoftext|>


<commit_before>var needle = require('needle')
var async = require('async')
var path = require('path')
var os = require('os')
var crypto = require('crypto')
var pump = require('pump')
var gunzip = require('gunzip-maybe')
var url = require('url')
var tar = require('tar-fs')

var reqOpts = { follow_max: 3, open_timeout: 5000, read_timeout: 5000 }

module.exports = function autoUpdater (options) {
  options = this.options = options || { }

  var fs = options.fs || require('fs')

  if (!options.version) throw new Error('specify current version object')
  if (!options.manifestUrl || !options.downloadUrl) throw new Error('specify manifestUrl and downloadUrl')

  options.filter = options.filter || function (ver) { return !(ver.beta || ver.alpha || ver.experimental) && !ver.disabled }
  options.getUpdateUrl = options.getUpdateUrl || function (downloadUrl, version, platform) {
    return downloadUrl + version.version + ({
      asar: '.asar.gz',
      win32: '.exe',
      darwin: '.dmg',
      linux: '.tar.gz'
    })[platform]
  }
  options.runtimeVerProp = options.runtimeVerProp || 'runtimeVersion'

  this.manifest = function (cb) {
    var err, body
    var urls = Array.isArray(options.manifestUrl) ? [].concat(options.manifestUrl) : [options.manifestUrl]

    async.whilst(function () { return !body && urls.length }, function (next) {
      needle.get(urls.shift(), reqOpts, function (e, resp, b) {
        err = e
        body = b
        next()
      })
    }, function () {
      cb(body ? null : err, body)
    })
  }

  this.check = function (cb) {
    this.manifest(function (err, body) {
      if (err) return cb(err)

      if (!Array.isArray(body)) return cb(new Error('expecting array from downloadUrl'))

      var versions = body
        .map(function (x) { x.released = new Date(x.released); return x })
        .sort(function (b, a) { return a.released.getTime() - b.released.getTime() })
        .filter(options.filter)

      var newest = versions[0]
      cb(null, newest.version === options.version.version ? null : newest, body)
    })
  }

  this.prepare = function (version, opts, cb) {
    cb = typeof (opts) === 'function' ? opts : cb
    opts = typeof (opts) === 'function' ? { } : opts

    var isAsarUpdate = version[options.runtimeVerProp] === options.version[options.runtimeVerProp]
    var update = options.getUpdateUrl(options.downloadUrl, version, opts.platform || (isAsarUpdate ? 'asar' : process.platform))
    if (!update) return cb(new Error('getUpdateUrl returned no result'))
    update = typeof (update) === 'string' ? { url: update } : update
    update.ungzip = update.hasOwnProperty('ungzip') ? update.ungzip : (isAsarUpdate && update.url.match('.gz$'))
    update.untar = update.hasOwnProperty('untar') ? update.untar : false

    var saveTo = path.join(os.tmpdir(), update.dest || path.basename(decodeURIComponent(url.parse(update.url).pathname), isAsarUpdate ? '.gz' : undefined))

    var hash = crypto.createHash('sha256')
    // var verify = crypto.createVerify('DSA-SHA1')

    async.auto({
      download: function (next) {
        var stream = needle.get(update.url, { follow_max: 3, headers: opts.headers })
        stream.on('error', next)
        stream.on('headers', function () {
          var res = stream.request.res
          if (!res) return next(new Error('no res'))
          if (res.statusCode !== 200) return next(new Error('downloading returned ' + res.statusCode))

          // Consider using res.headers for verifying content-length and content-disposition for saveTo

          res.on('error', next)

          res.on('data', function (d) { hash.update(d) })

          var pipes = [stream]
          if (update.ungzip) pipes.push(gunzip())

          if (update.untar) pipes.push(tar.extract(saveTo, { fs: fs }))
          else pipes.push(fs.createWriteStream(saveTo))

          pump.apply(null, pipes.concat([ function (err) { next(err) } ]))
        })
      },
      checksum: function (next) {
        needle.get(update.checksumUrl || (update.url + '.sha256'), { follow_max: 3 }, function (err, resp, body) {
          if (err) return next(err)
          if (resp.statusCode !== 200) return next(new Error('checksum status code ' + resp.statusCode))
          next(null, body)
        })
      },
      verify: ['download', 'checksum', function (next, res) {
        // if ( ! verify.verify(options.publicKey, signature, 'base64') return next(new Error('signing verification failed'))
        if (res.checksum.toString() !== hash.digest('hex')) return next(new Error('checksum verification failed'))
        next()
      }]
    }, function (err) {
      cb(err, { saveTo: saveTo, updateUrl: update.url, update: update, isAsarUpdate: isAsarUpdate, version: version, current: options.version })
    })
  }
}
<commit_msg>checksumUrl: ignore query string<commit_after>var needle = require('needle')
var async = require('async')
var path = require('path')
var os = require('os')
var crypto = require('crypto')
var pump = require('pump')
var gunzip = require('gunzip-maybe')
var url = require('url')
var tar = require('tar-fs')

var reqOpts = { follow_max: 3, open_timeout: 5000, read_timeout: 5000 }

module.exports = function autoUpdater (options) {
  options = this.options = options || { }

  var fs = options.fs || require('fs')

  if (!options.version) throw new Error('specify current version object')
  if (!options.manifestUrl || !options.downloadUrl) throw new Error('specify manifestUrl and downloadUrl')

  options.filter = options.filter || function (ver) { return !(ver.beta || ver.alpha || ver.experimental) && !ver.disabled }
  options.getUpdateUrl = options.getUpdateUrl || function (downloadUrl, version, platform) {
    return downloadUrl + version.version + ({
      asar: '.asar.gz',
      win32: '.exe',
      darwin: '.dmg',
      linux: '.tar.gz'
    })[platform]
  }
  options.runtimeVerProp = options.runtimeVerProp || 'runtimeVersion'

  this.manifest = function (cb) {
    var err, body
    var urls = Array.isArray(options.manifestUrl) ? [].concat(options.manifestUrl) : [options.manifestUrl]

    async.whilst(function () { return !body && urls.length }, function (next) {
      needle.get(urls.shift(), reqOpts, function (e, resp, b) {
        err = e
        body = b
        next()
      })
    }, function () {
      cb(body ? null : err, body)
    })
  }

  this.check = function (cb) {
    this.manifest(function (err, body) {
      if (err) return cb(err)

      if (!Array.isArray(body)) return cb(new Error('expecting array from downloadUrl'))

      var versions = body
        .map(function (x) { x.released = new Date(x.released); return x })
        .sort(function (b, a) { return a.released.getTime() - b.released.getTime() })
        .filter(options.filter)

      var newest = versions[0]
      cb(null, newest.version === options.version.version ? null : newest, body)
    })
  }

  this.prepare = function (version, opts, cb) {
    cb = typeof (opts) === 'function' ? opts : cb
    opts = typeof (opts) === 'function' ? { } : opts

    var isAsarUpdate = version[options.runtimeVerProp] === options.version[options.runtimeVerProp]
    var update = options.getUpdateUrl(options.downloadUrl, version, opts.platform || (isAsarUpdate ? 'asar' : process.platform))
    if (!update) return cb(new Error('getUpdateUrl returned no result'))
    update = typeof (update) === 'string' ? { url: update } : update
    update.ungzip = update.hasOwnProperty('ungzip') ? update.ungzip : (isAsarUpdate && update.url.match('.gz$'))
    update.untar = update.hasOwnProperty('untar') ? update.untar : false

    var saveTo = path.join(os.tmpdir(), update.dest || path.basename(decodeURIComponent(url.parse(update.url).pathname), isAsarUpdate ? '.gz' : undefined))

    var hash = crypto.createHash('sha256')
    // var verify = crypto.createVerify('DSA-SHA1')

    async.auto({
      download: function (next) {
        var stream = needle.get(update.url, { follow_max: 3, headers: opts.headers })
        stream.on('error', next)
        stream.on('headers', function () {
          var res = stream.request.res
          if (!res) return next(new Error('no res'))
          if (res.statusCode !== 200) return next(new Error('downloading returned ' + res.statusCode))

          // Consider using res.headers for verifying content-length and content-disposition for saveTo

          res.on('error', next)

          res.on('data', function (d) { hash.update(d) })

          var pipes = [stream]
          if (update.ungzip) pipes.push(gunzip())

          if (update.untar) pipes.push(tar.extract(saveTo, { fs: fs }))
          else pipes.push(fs.createWriteStream(saveTo))

          pump.apply(null, pipes.concat([ function (err) { next(err) } ]))
        })
      },
      checksum: function (next) {
        needle.get(update.checksumUrl || (update.url.split('?')[0] + '.sha256'), { follow_max: 3 }, function (err, resp, body) {
          if (err) return next(err)
          if (resp.statusCode !== 200) return next(new Error('checksum status code ' + resp.statusCode))
          next(null, body)
        })
      },
      verify: ['download', 'checksum', function (next, res) {
        // if ( ! verify.verify(options.publicKey, signature, 'base64') return next(new Error('signing verification failed'))
        if (res.checksum.toString() !== hash.digest('hex')) return next(new Error('checksum verification failed'))
        next()
      }]
    }, function (err) {
      cb(err, { saveTo: saveTo, updateUrl: update.url, update: update, isAsarUpdate: isAsarUpdate, version: version, current: options.version })
    })
  }
}
<|endoftext|>


<commit_before>/*
   Copyright 2012 Google Inc

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

var net = module.exports;
var events = require('events');
var util = require('util');
var Stream = require('stream');
var Buffer = require('buffer').Buffer;

var stringToArrayBuffer = function(str) {
  var buffer = new ArrayBuffer(str.length);
  var uint8Array = new Uint8Array(buffer);
  for(var i = 0; i < str.length; i++) {
    uint8Array[i] = str.charCodeAt(i);
  }
  return buffer;
};

var bufferToArrayBuffer = function(buffer) {
  return stringToArrayBuffer(buf.toString())
};

var arrayBufferToBuffer = function(arrayBuffer) {
  var buffer = new Buffer(arrayBuffer.byteLength);
  var uint8Array = new Uint8Array(arrayBuffer);
  for(var i = 0; i < uint8Array.length; i++) {
    buffer.writeUInt8(uint8Array[i], i);
  }
  return buffer;
};

net.createServer = function() {
  var options = {
  };
  var args = arguments;

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};

  if(typeof args[0] === 'object') {
    options = args[0];
  }

  var server = new net.Server(options);
  server.on("connection", cb);
  return server;
};

net.connect = net.createConnection = function() {
  var options = {};
  var args = arguments;
  if(typeof args[0] === 'object') {
    options.port = args[0].port;
    options.host = args[0].host || "127.0.0.1";
  }
  else if(typeof args[0] === 'number') {
    // there is a port
    options.port = args[0];
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
  }
  else if(typeof args[0] === 'string') {
    return; // can't do this.
  }

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};

  var socket = new net.Socket(options);
  socket.on("_created", function() {
    socket.connect(options, cb);
  });

  return socket;
};

net.Server = function() {
  var _maxConnections = 0;
  this.__defineGetter__("maxConnections", function() { return _maxConnections; });

  var _connections = 0;
  this.__defineGetter__("connections", function() { return _connections; });

  events.EventEmitter.call(this);
};

util.inherits(net.Server, events.EventEmitter);

net.Server.prototype.listen = function() {
  var self = this;
  var options = {};
  var args = arguments;

  if (typeof args[0] === 'number') {
    // assume port. and host.
    options.port = args[0];
    options.host = "127.0.0.1";
    options.backlog = 511;
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
    else if(typeof args[1] === 'number') {
      options.backlog = args[1];
    }

    if(typeof args[2] === 'number') {
      options.backlog = args[2];
    }
  }
  else {
    // throw.
  }

  this._serverSocket = new net.Socket(options);

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};

  self.on('listening', cb);

  self._serverSocket.on("_created", function() {
    // Socket created, now turn it into a server socket.
    chrome.socket.listen(self._serverSocket._socketInfo.socketId, options.host, options.port, options.backlog, function() {
      self.emit('listening');
      chrome.socket.accept(self._serverSocket._socketInfo.socketId, self._accept.bind(self))
    });
  });
};

net.Server.prototype._accept = function(acceptInfo) {
  // Create a new socket for the handle the response.
  var self = this;
  var socket = new net.Socket();

  socket._socketInfo = acceptInfo;
  self.emit("connection", socket);
  chrome.socket.accept(self._serverSocket._socketInfo.socketId, self._accept.bind(self))
};

net.Server.prototype.close = function(callback) {
  self.on("close", callback || function() {});
  self._serverSocket.destroy();
  self.emit("close");
};
net.Server.prototype.address = function() {};

net.Socket = function(options) {
  var self = this;
  options = options || {};
  this._fd = options.fd;
  this._type = options.type || "tcp";
  //assert(this._type === "tcp6", "Only tcp4 is allowed");
  //assert(this._type === "unix", "Only tcp4 is allowed");
  this._type = allowHalfOpen = options.allowHalfOpen || false;
  this._socketInfo = 0;
  this._encoding;

  chrome.socket.create("tcp", {}, function(createInfo) {
    self._socketInfo = createInfo;
    self.emit("_created"); // This event doesn't exist in the API, it is here because Chrome is async
    // start trying to read
    self._read();
  });
};

util.inherits(net.Socket, Stream);

/*
  Events:
    close
    connect
    data
    drain
    end
    error
    timeout
*/

/*
  Methods
*/

net.Socket.prototype.connect = function() {
  var self = this;
  var options = {};
  var args = arguments;

  if(typeof args[0] === 'object') {
    // we have an options object.
    options.port = args[0].port;
    options.host = args[0].host || "127.0.0.1";
  }
  else if (typeof args[0] === 'string') {
    // throw an error, we can't do named pipes.
  }
  else if (typeof args[0] === 'number') {
    // assume port. and host.
    options.port = args[0];
    options.host = "127.0.0.1";
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
  }

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};
  self.on('connect', cb);

  chrome.socket.connect(self._socketInfo.socketId, options.host, options.port, function(result) {
    if(result == 0) {
      self.emit('connect');
    }
    else {
      self.emit('error', new Error("Unable to connect"));
    }
  });
};

net.Socket.prototype.destroy = function() {
  chrome.socket.disconnect(this._socketInfo.socketId);
  chrome.socket.destroy(this._socketInfo.socketId);
};
net.Socket.prototype.destroySoon = function() {};
net.Socket.prototype.setEncoding = function(encoding) {
  this._encoding = encoding;
};

net.Socket.prototype.setNoDelay = function(noDelay) {
  noDelay = (noDelay === undefined) ? true : noDelay;
  chrome.socket.setNoDely(self._socketInfo.socketId, noDelay, function() {});
};

net.Socket.prototype.setKeepAlive = function(enable, delay) {
  enable = (enable === 'undefined') ? false : enable;
  delay = (delay === 'undefined') ? 0 : delay;
  chrome.socket.setKeepAlive(self._socketInfo.socketId, enable, initialDelay, function() {});
};

net.Socket.prototype._read = function() {
  var self = this;
  chrome.socket.read(self._socketInfo.socketId, function(readInfo) {
    if(readInfo.resultCode < 0) return;
    // ArrayBuffer to Buffer if no encoding.
    var buffer = arrayBufferToBuffer(readInfo.data);
    self.emit('data', buffer);
  });

  // enque another read soon. TODO: Is there are better way to controll speed.
  self._readTimer = setTimeout(self._read.bind(self), 100);
}

net.Socket.prototype.write = function(data, encoding, callback) {
  var buffer;
  var self = this;

  encoding = encoding || "UTF8";
  callback = callback || function() {};

  if(typeof data === 'string') {
    buffer = stringToArrayBuffer(data);
  }
  else if(data instanceof Buffer) {
    buffer = bufferToArrayBuffer(data);
  }
  else {
    // throw an error because we can't do anything.
  }

  self._resetTimeout();

  chrome.socket.write(self._socketInfo.socketId, buffer, function(writeInfo) {
    callback();
  });

  return true;
};

net.Socket.prototype._resetTimeout = function() {
  var self = this;
  if(!!self._timeout == false) clearTimeout(self._timeout);
  if(!!self._timeoutValue) self._timeout = setTimeout(function() { self.emit('timeout') }, self._timeoutValue);
};

net.Socket.prototype.setTimeout = function(timeout, callback) {
  this._timeoutValue = timeout;
  this._resetTimeout();
};

net.Socket.prototype.ref = function() {};
net.Socket.prototype.unref = function() {};
net.Socket.prototype.pause = function() {};
net.Socket.prototype.resume = function() {};
net.Socket.prototype.end = function() {

};

Object.defineProperty(net.Socket.prototype, 'readyState', {
  get: function() {}
});

Object.defineProperty(net.Socket.prototype, 'bufferSize', {
  get: function() {}
});
<commit_msg>Fixing a typo<commit_after>/*
   Copyright 2012 Google Inc

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

var net = module.exports;
var events = require('events');
var util = require('util');
var Stream = require('stream');
var Buffer = require('buffer').Buffer;

var stringToArrayBuffer = function(str) {
  var buffer = new ArrayBuffer(str.length);
  var uint8Array = new Uint8Array(buffer);
  for(var i = 0; i < str.length; i++) {
    uint8Array[i] = str.charCodeAt(i);
  }
  return buffer;
};

var bufferToArrayBuffer = function(buffer) {
  return stringToArrayBuffer(buffer.toString())
};

var arrayBufferToBuffer = function(arrayBuffer) {
  var buffer = new Buffer(arrayBuffer.byteLength);
  var uint8Array = new Uint8Array(arrayBuffer);
  for(var i = 0; i < uint8Array.length; i++) {
    buffer.writeUInt8(uint8Array[i], i);
  }
  return buffer;
};

net.createServer = function() {
  var options = {
  };
  var args = arguments;

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};

  if(typeof args[0] === 'object') {
    options = args[0];
  }

  var server = new net.Server(options);
  server.on("connection", cb);
  return server;
};

net.connect = net.createConnection = function() {
  var options = {};
  var args = arguments;
  if(typeof args[0] === 'object') {
    options.port = args[0].port;
    options.host = args[0].host || "127.0.0.1";
  }
  else if(typeof args[0] === 'number') {
    // there is a port
    options.port = args[0];
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
  }
  else if(typeof args[0] === 'string') {
    return; // can't do this.
  }

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};

  var socket = new net.Socket(options);
  socket.on("_created", function() {
    socket.connect(options, cb);
  });

  return socket;
};

net.Server = function() {
  var _maxConnections = 0;
  this.__defineGetter__("maxConnections", function() { return _maxConnections; });

  var _connections = 0;
  this.__defineGetter__("connections", function() { return _connections; });

  events.EventEmitter.call(this);
};

util.inherits(net.Server, events.EventEmitter);

net.Server.prototype.listen = function() {
  var self = this;
  var options = {};
  var args = arguments;

  if (typeof args[0] === 'number') {
    // assume port. and host.
    options.port = args[0];
    options.host = "127.0.0.1";
    options.backlog = 511;
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
    else if(typeof args[1] === 'number') {
      options.backlog = args[1];
    }

    if(typeof args[2] === 'number') {
      options.backlog = args[2];
    }
  }
  else {
    // throw.
  }

  this._serverSocket = new net.Socket(options);

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};

  self.on('listening', cb);

  self._serverSocket.on("_created", function() {
    // Socket created, now turn it into a server socket.
    chrome.socket.listen(self._serverSocket._socketInfo.socketId, options.host, options.port, options.backlog, function() {
      self.emit('listening');
      chrome.socket.accept(self._serverSocket._socketInfo.socketId, self._accept.bind(self))
    });
  });
};

net.Server.prototype._accept = function(acceptInfo) {
  // Create a new socket for the handle the response.
  var self = this;
  var socket = new net.Socket();

  socket._socketInfo = acceptInfo;
  self.emit("connection", socket);
  chrome.socket.accept(self._serverSocket._socketInfo.socketId, self._accept.bind(self))
};

net.Server.prototype.close = function(callback) {
  self.on("close", callback || function() {});
  self._serverSocket.destroy();
  self.emit("close");
};
net.Server.prototype.address = function() {};

net.Socket = function(options) {
  var self = this;
  options = options || {};
  this._fd = options.fd;
  this._type = options.type || "tcp";
  //assert(this._type === "tcp6", "Only tcp4 is allowed");
  //assert(this._type === "unix", "Only tcp4 is allowed");
  this._type = allowHalfOpen = options.allowHalfOpen || false;
  this._socketInfo = 0;
  this._encoding;

  chrome.socket.create("tcp", {}, function(createInfo) {
    self._socketInfo = createInfo;
    self.emit("_created"); // This event doesn't exist in the API, it is here because Chrome is async
    // start trying to read
    self._read();
  });
};

util.inherits(net.Socket, Stream);

/*
  Events:
    close
    connect
    data
    drain
    end
    error
    timeout
*/

/*
  Methods
*/

net.Socket.prototype.connect = function() {
  var self = this;
  var options = {};
  var args = arguments;

  if(typeof args[0] === 'object') {
    // we have an options object.
    options.port = args[0].port;
    options.host = args[0].host || "127.0.0.1";
  }
  else if (typeof args[0] === 'string') {
    // throw an error, we can't do named pipes.
  }
  else if (typeof args[0] === 'number') {
    // assume port. and host.
    options.port = args[0];
    options.host = "127.0.0.1";
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
  }

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};
  self.on('connect', cb);

  chrome.socket.connect(self._socketInfo.socketId, options.host, options.port, function(result) {
    if(result == 0) {
      self.emit('connect');
    }
    else {
      self.emit('error', new Error("Unable to connect"));
    }
  });
};

net.Socket.prototype.destroy = function() {
  chrome.socket.disconnect(this._socketInfo.socketId);
  chrome.socket.destroy(this._socketInfo.socketId);
};
net.Socket.prototype.destroySoon = function() {};
net.Socket.prototype.setEncoding = function(encoding) {
  this._encoding = encoding;
};

net.Socket.prototype.setNoDelay = function(noDelay) {
  noDelay = (noDelay === undefined) ? true : noDelay;
  chrome.socket.setNoDely(self._socketInfo.socketId, noDelay, function() {});
};

net.Socket.prototype.setKeepAlive = function(enable, delay) {
  enable = (enable === 'undefined') ? false : enable;
  delay = (delay === 'undefined') ? 0 : delay;
  chrome.socket.setKeepAlive(self._socketInfo.socketId, enable, initialDelay, function() {});
};

net.Socket.prototype._read = function() {
  var self = this;
  chrome.socket.read(self._socketInfo.socketId, function(readInfo) {
    if(readInfo.resultCode < 0) return;
    // ArrayBuffer to Buffer if no encoding.
    var buffer = arrayBufferToBuffer(readInfo.data);
    self.emit('data', buffer);
  });

  // enque another read soon. TODO: Is there are better way to controll speed.
  self._readTimer = setTimeout(self._read.bind(self), 100);
}

net.Socket.prototype.write = function(data, encoding, callback) {
  var buffer;
  var self = this;

  encoding = encoding || "UTF8";
  callback = callback || function() {};

  if(typeof data === 'string') {
    buffer = stringToArrayBuffer(data);
  }
  else if(data instanceof Buffer) {
    buffer = bufferToArrayBuffer(data);
  }
  else {
    // throw an error because we can't do anything.
  }

  self._resetTimeout();

  chrome.socket.write(self._socketInfo.socketId, buffer, function(writeInfo) {
    callback();
  });

  return true;
};

net.Socket.prototype._resetTimeout = function() {
  var self = this;
  if(!!self._timeout == false) clearTimeout(self._timeout);
  if(!!self._timeoutValue) self._timeout = setTimeout(function() { self.emit('timeout') }, self._timeoutValue);
};

net.Socket.prototype.setTimeout = function(timeout, callback) {
  this._timeoutValue = timeout;
  this._resetTimeout();
};

net.Socket.prototype.ref = function() {};
net.Socket.prototype.unref = function() {};
net.Socket.prototype.pause = function() {};
net.Socket.prototype.resume = function() {};
net.Socket.prototype.end = function() {

};

Object.defineProperty(net.Socket.prototype, 'readyState', {
  get: function() {}
});

Object.defineProperty(net.Socket.prototype, 'bufferSize', {
  get: function() {}
});
<|endoftext|>


<commit_before>"use strict"; // use strict mode

var keynav = {
  prefs : null,
  MailFolderKeyNavMenuItem : null,

  startup : function(e) {
  	var MailFolderKeyNav, GoMenuMailFolderKeyNavToggle;
    var keynavBundle = document.getElementById("keynav.keynav.strings"); // get the keynav stringbundle
  	// Get preference machinery for keynav
    this.prefs = Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefService)
    .getBranch("extensions.keynav.");
    // Add keynav prefs observer to keynav
    this.prefs.addObserver("", this, false);
    // Create the MailFolderKeynav menuitem
    const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; // xml namespace
    this.MailfolderKeyNavMenuItem = document.createElementNS(XULNS, "menuitem");
    this.MailfolderKeyNavMenuItem.setAttribute("id", "appmenu_goMailFolderKeyNavMenuItem");
    this.MailfolderKeyNavMenuItem.setAttribute("label",
      keynavBundle.getString("menu_EnableMailFolderKeyNav.label"));
    this.MailfolderKeyNavMenuItem.setAttribute("type", "checkbox");
    this.MailfolderKeyNavMenuItem.setAttribute("autocheck", "false");
    this.MailfolderKeyNavMenuItem.setAttribute("checked", "false");
    this.MailfolderKeyNavMenuItem.setAttribute("oncommand", "keynav.toggleMailFolderKeyNavOption()");
    // Get stored values of preferences
    MailFolderKeyNav = this.prefs.getBoolPref("MailFolderKeyNav");
    GoMenuMailFolderKeyNavToggle = this.prefs.getBoolPref("GoMenuMailFolderKeyNavToggle");
    // Add the MailFolderKeynav menuitem to the Go menu according to the GoMenuMailFolderKeyNavToggle option
    if (GoMenuMailFolderKeyNavToggle)
      document.getElementById("menu_GoPopup").appendChild(this.MailfolderKeyNavMenuItem);
    // Set the checked/unchecked state of the MailFolderKeynav Go menu item
    this.MailfolderKeyNavMenuItem.setAttribute("checked", MailFolderKeyNav.toString());
    // Set the key navigation state on the mail folder tree
    this.setMailFolderKeyNav(MailFolderKeyNav);
  },

  shutdown : function() {
  	// Remove the MailFolderKeyNav menu item from the Go menu if it is currently attached
    var val= this.prefs.getBoolPref("GoMenuMailFolderKeyNavToggle"); // get current preference value
    if (!val) {
      document.getElementById("menu_GoPopup").removeChild(this.MailfolderKeyNavMenuItem); // delete menu item from Go menu
    }
    this.MailFolderKeyNavMenuItem = null;
    // Remove the observer
    this.prefs.removeObserver("", this);
  },

  observe : function(subject, topic, data) {
  	var val;
  	// If the preference has not been changed, bail
    if (topic != "nsPref:changed") {return;}
    // Respond to change in preference
    switch (data) {
    	case "MailFolderKeyNav":
        val = this.prefs.getBoolPref("MailFolderKeyNav"); // get current preference value
        this.MailfolderKeyNavMenuItem.setAttribute("checked", val.toString());
        this.setMailFolderKeyNav(val);
    	  break;
    	case "GoMenuMailFolderKeyNavToggle":
        val= this.prefs.getBoolPref("GoMenuMailFolderKeyNavToggle"); // get current preference value
        if (val)
          document.getElementById("menu_GoPopup").appendChild(this.MailfolderKeyNavMenuItem); // add menu item to Go menu
        else
          document.getElementById("menu_GoPopup").removeChild(this.MailfolderKeyNavMenuItem); // delete menu item from Go menu
    	  break;
    }
  },

  setMailFolderKeyNav : function(val) {
    if (val) {
  	  document.getElementById("folderTree").removeAttribute("disableKeyNavigation"); // activate key navigation
	  } else {
  	  document.getElementById("folderTree").setAttribute("disableKeyNavigation", "true");  // deactivate key navigation
    }
  },

  toggleMailFolderKeyNavOption : function() {
    /* This function is called by the oncommand event when the user activates
  	the MailFolderKeyNav menuitem on the Go menu.  It is not necessary to
  	update the checked/unchecked state of the menuitem as this will be done
  	by the observer. */
    var val = this.prefs.getBoolPref("MailFolderKeyNav"); // get current value of MailFolderKeyNav
    this.prefs.setBoolPref("MailFolderKeyNav", !val); // flip it and write it back to preferences
  }
}; // keynav

// Set up event listeners for starting and stopping the extension

window.addEventListener("load",
  function(e) {
keynav.startup();
  })

  window.addEventListener("unload",
  function(e) {
keynav.shutdown();
  })

<commit_msg>Made adding/removing the Go menu quick toggle item more robust, hopefully.<commit_after>"use strict"; // use strict mode

var keynav = {
  prefs : null,
  MailFolderKeyNavMenuItem : null,

  startup : function(e) {
  	var MailFolderKeyNav, GoMenuMailFolderKeyNavToggle;
    var keynavBundle = document.getElementById("keynav.keynav.strings"); // get the keynav stringbundle
  	// Get preference machinery for keynav
    this.prefs = Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefService)
    .getBranch("extensions.keynav.");
    // Add keynav prefs observer to keynav
    this.prefs.addObserver("", this, false);
    // Create the MailFolderKeynav menuitem
    const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; // xml namespace
    this.MailFolderKeyNavMenuItem = document.createElementNS(XULNS, "menuitem");
    this.MailFolderKeyNavMenuItem.setAttribute("id", "appmenu_goMailFolderKeyNavMenuItem");
    this.MailFolderKeyNavMenuItem.setAttribute("label",
      keynavBundle.getString("menu_EnableMailFolderKeyNav.label"));
    this.MailFolderKeyNavMenuItem.setAttribute("type", "checkbox");
    this.MailFolderKeyNavMenuItem.setAttribute("accesskey", "k");
    this.MailFolderKeyNavMenuItem.setAttribute("autocheck", "false");
    this.MailFolderKeyNavMenuItem.setAttribute("checked", "false");
    this.MailFolderKeyNavMenuItem.setAttribute("oncommand", "keynav.toggleMailFolderKeyNavOption()");
    // Get stored values of preferences
    MailFolderKeyNav = this.prefs.getBoolPref("MailFolderKeyNav");
    GoMenuMailFolderKeyNavToggle = this.prefs.getBoolPref("GoMenuMailFolderKeyNavToggle");
    // Add the MailFolderKeynav menuitem to the Go menu according to the GoMenuMailFolderKeyNavToggle option
      this.displayGoMenuQuickToggle(GoMenuMailFolderKeyNavToggle);
/*    if (GoMenuMailFolderKeyNavToggle)
      document.getElementById("menu_GoPopup").appendChild(this.MailFolderKeyNavMenuItem);*/
    // Set the checked/unchecked state of the MailFolderKeynav Go menu item
    this.MailFolderKeyNavMenuItem.setAttribute("checked", MailFolderKeyNav.toString());
    // Set the key navigation state on the mail folder tree
    this.setMailFolderKeyNav(MailFolderKeyNav);
  },

  shutdown : function() {
  	// Remove the MailFolderKeyNav menu item from the Go menu if it is currently attached
  	  this.displayGoMenuQuickToggle(false);
/*    var val= this.prefs.getBoolPref("GoMenuMailFolderKeyNavToggle"); // get current preference value
    if (!val) {
      document.getElementById("menu_GoPopup").removeChild(this.MailFolderKeyNavMenuItem); // delete menu item from Go menu
    }*/
    this.MailFolderKeyNavMenuItem = null;
    // Remove the observer
    this.prefs.removeObserver("", this);
  },

  observe : function(subject, topic, data) {
  	var val;
  	// If the preference has not been changed, bail
    if (topic != "nsPref:changed") {return;}
    // Respond to change in preference
    switch (data) {
    	case "MailFolderKeyNav":
        val = this.prefs.getBoolPref("MailFolderKeyNav"); // get current preference value
        this.MailFolderKeyNavMenuItem.setAttribute("checked", val.toString());
        this.setMailFolderKeyNav(val);
    	  break;
    	case "GoMenuMailFolderKeyNavToggle":
        val= this.prefs.getBoolPref("GoMenuMailFolderKeyNavToggle"); // get current preference value
        this.displayGoMenuQuickToggle(val);
/*        if (val)
          document.getElementById("menu_GoPopup").appendChild(this.MailFolderKeyNavMenuItem); // add menu item to Go menu
        else
          document.getElementById("menu_GoPopup").removeChild(this.MailFolderKeyNavMenuItem); // delete menu item from Go menu */
    	  break;
    }
  },

  displayGoMenuQuickToggle : function(val) {
  	var goPopup = document.getElementById("menu_GoPopup");
    if (val && this.MailFolderKeyNavMenuItem.parentNode==null)
      goPopup.appendChild(this.MailFolderKeyNavMenuItem); // add menu item to Go menu
    else if (!val && this.MailFolderKeyNavMenuItem.parentNode==goPopup)
      goPopup.removeChild(this.MailFolderKeyNavMenuItem); // delete menu item from Go menu
  },

  setMailFolderKeyNav : function(val) {
    if (val) {
  	  document.getElementById("folderTree").removeAttribute("disableKeyNavigation"); // activate key navigation
	  } else {
  	  document.getElementById("folderTree").setAttribute("disableKeyNavigation", "true");  // deactivate key navigation
    }
  },

  toggleMailFolderKeyNavOption : function() {
    /* This function is called by the oncommand event when the user activates
  	the MailFolderKeyNav menuitem on the Go menu.  It is not necessary to
  	update the checked/unchecked state of the menuitem as this will be done
  	by the observer. */
    var val = this.prefs.getBoolPref("MailFolderKeyNav"); // get current value of MailFolderKeyNav
    this.prefs.setBoolPref("MailFolderKeyNav", !val); // flip it and write it back to preferences
  }
}; // keynav

// Set up event listeners for starting and stopping the extension

window.addEventListener("load",
  function(e) {
keynav.startup();
  })

  window.addEventListener("unload",
  function(e) {
keynav.shutdown();
  })

<|endoftext|>