]> git.ipfire.org Git - thirdparty/chrony.git/commitdiff
util: add function for IP address hashing
authorMiroslav Lichvar <mlichvar@redhat.com>
Mon, 23 Nov 2015 14:24:33 +0000 (15:24 +0100)
committerMiroslav Lichvar <mlichvar@redhat.com>
Mon, 30 Nov 2015 16:34:50 +0000 (17:34 +0100)
Move the hashing function from find_slot() in ntp_sources to make it
available to clientlog and improve the hashing a bit.

ntp_sources.c
util.c
util.h

index eca681ccaeec7c632c54feb8ee1b01e24dc4ceb6..e6ac8b0b4b89116b2b54e994ada6c642e7174e28 100644 (file)
@@ -202,26 +202,16 @@ find_slot(NTP_Remote_Address *remote_addr, int *slot, int *found)
   uint32_t hash;
   unsigned int i, size;
   unsigned short port;
-  uint8_t *ip6;
 
   size = ARR_GetSize(records);
   
-  switch (remote_addr->ip_addr.family) {
-    case IPADDR_INET6:
-      ip6 = remote_addr->ip_addr.addr.in6;
-      hash = (ip6[0] ^ ip6[4] ^ ip6[8] ^ ip6[12]) |
-           (ip6[1] ^ ip6[5] ^ ip6[9] ^ ip6[13]) << 8 |
-           (ip6[2] ^ ip6[6] ^ ip6[10] ^ ip6[14]) << 16 |
-           (ip6[3] ^ ip6[7] ^ ip6[11] ^ ip6[15]) << 24;
-      break;
-    case IPADDR_INET4:
-      hash = remote_addr->ip_addr.addr.in4;
-      break;
-    default:
-      *found = *slot = 0;
-      return;
+  if (remote_addr->ip_addr.family != IPADDR_INET4 &&
+      remote_addr->ip_addr.family != IPADDR_INET6) {
+    *found = *slot = 0;
+    return;
   }
 
+  hash = UTI_IPToHash(&remote_addr->ip_addr);
   port = remote_addr->port;
 
   for (i = 0; i < size / 2; i++) {
diff --git a/util.c b/util.c
index fc3a81c30306ab650686303ce3d3be9cb0e4bfb6..da70f0bdf3154c34792012084959fab508dd2967 100644 (file)
--- a/util.c
+++ b/util.c
@@ -359,6 +359,34 @@ UTI_IPToRefid(IPAddr *ip)
 
 /* ================================================== */
 
+uint32_t
+UTI_IPToHash(IPAddr *ip)
+{
+  unsigned char *addr;
+  unsigned int i, len;
+  uint32_t hash;
+
+  switch (ip->family) {
+    case IPADDR_INET4:
+      addr = (unsigned char *)&ip->addr.in4;
+      len = sizeof (ip->addr.in4);
+      break;
+    case IPADDR_INET6:
+      addr = ip->addr.in6;
+      len = sizeof (ip->addr.in6);
+      break;
+    default:
+      return 0;
+  }
+
+  for (i = 0, hash = 0; i < len; i++)
+    hash = 71 * hash + addr[i];
+
+  return hash;
+}
+
+/* ================================================== */
+
 void
 UTI_IPHostToNetwork(IPAddr *src, IPAddr *dest)
 {
diff --git a/util.h b/util.h
index f0cb61058938c3337c694190ec7ac2f938389ce5..78b7d71af366400b5b511722c3732cd201b3297a 100644 (file)
--- a/util.h
+++ b/util.h
@@ -82,6 +82,7 @@ extern char *UTI_IPToString(IPAddr *ip);
 
 extern int UTI_StringToIP(const char *addr, IPAddr *ip);
 extern uint32_t UTI_IPToRefid(IPAddr *ip);
+extern uint32_t UTI_IPToHash(IPAddr *ip);
 extern void UTI_IPHostToNetwork(IPAddr *src, IPAddr *dest);
 extern void UTI_IPNetworkToHost(IPAddr *src, IPAddr *dest);
 extern int UTI_CompareIPs(IPAddr *a, IPAddr *b, IPAddr *mask);