From d59126c90928be27a87f155e77bce074eb99bca3 Mon Sep 17 00:00:00 2001 From: Dana NicCaluim Date: Fri, 21 Aug 2015 11:28:58 -0700 Subject: [PATCH] work around IPv6 addresses in Trace#fromRequest --- lib/trace.js | 29 ++++++++++++++++++++++++++++- tests/test_trace.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/lib/trace.js b/lib/trace.js index 381b8d6..d9b3b59 100644 --- a/lib/trace.js +++ b/lib/trace.js @@ -15,7 +15,7 @@ (function () { var tracers, formatters, zipkinCore_types; var Trace, Annotation, Endpoint, Int64; - var forEach, has, getUniqueId, getNowMicros, getHex64; + var forEach, has, getUniqueId, getNowMicros, getHex64, isIPv4; forEach = function(obj, f){ Array.prototype.forEach.call(obj, f); @@ -54,6 +54,28 @@ return Date.now() * 1000; }; + /** + * Returns true if an IP address is v4 dotted decimal + * @param {String} address + * @returns {Boolean} + */ + isIPv4 = function(address) { + var octets = address.split('.'); + + if (octets.length !== 4) { + return false; + } + + forEach(octets, function(octet) { + var n = parseInt(octet) + if (isNaN(n) || n < 0 || n > 255) { + return false; + } + }); + + return true; + } + /** * A Trace encapsulates information about the current span of this trace * and provides a mechanism for creating new child spans and recording @@ -237,6 +259,11 @@ var host = (request.socket && request.socket.address ? request.socket.address() : {address: '127.0.0.1', port: 80}); + if (host.address === '::1') { + host.address = '127.0.0.1' + } else if (!isIPv4(host.address)) { + host.address = '0.0.0.0'; + } if (serviceName === undefined || serviceName === null) { serviceName = 'http'; diff --git a/tests/test_trace.js b/tests/test_trace.js index fe6a3e3..d4647b0 100644 --- a/tests/test_trace.js +++ b/tests/test_trace.js @@ -223,6 +223,34 @@ module.exports = { {method: 'GET', headers: {}}, 'this_is_a_service'); test.equal(t.endpoint.serviceName, "this_is_a_service"); test.done(); + }, + test_fromRequest_endpoint_with_ipv6_localhost: function(test) { + var t = new trace.Trace.fromRequest({ + method: 'GET', + headers: {}, + socket: { + address: function() { + return {family: 2, port: 8888, address: '::1'}; + } + } + }); + test.equal(t.endpoint.ipv4, '127.0.0.1'); + test.equal(t.endpoint.port, 8888); + test.done(); + }, + test_fromRequest_endpoint_with_other_ipv6: function(test) { + var t = new trace.Trace.fromRequest({ + method: 'GET', + headers: {}, + socket: { + address: function() { + return {family: 2, port: 8888, address: '2001:db8::ff00:42:8329'}; + } + } + }); + test.equal(t.endpoint.ipv4, '0.0.0.0'); + test.equal(t.endpoint.port, 8888); + test.done(); } }, annotationTests: {