Fixed thread issue on Linux with gethostbyname_r().
[m6w6/libmemcached] / lib / memcached_connect.c
index 0c256b71e07c6b9853798135fa6f4688ecb42fcf..1a7cde1676dc2e536607fe5547f9d8637f0db6ab 100644 (file)
 static memcached_return set_hostinfo(memcached_server_st *server)
 {
   struct hostent *h;
-
+#ifdef HAVE_GETHOSTBYNAME_R
+  struct hostent h_static;
+  char buffer[SMALL_STRING_LEN];
+  int tmp_error;
+
+  if (gethostbyname_r(server->hostname,
+                      &h_static, buffer, SMALL_STRING_LEN, 
+                      &h, &tmp_error))
+  {
+    WATCHPOINT_STRING(server->hostname);
+    WATCHPOINT_STRING(hstrerror(tmp_error));
+    return MEMCACHED_HOST_LOOKUP_FAILURE;
+  }
+#else
   if ((h= gethostbyname(server->hostname)) == NULL)
   {
-    return MEMCACHED_HOST_LOCKUP_FAILURE;
+    WATCHPOINT_STRING(server->hostname);
+    WATCHPOINT_STRING(hstrerror(h_errno));
+    return MEMCACHED_HOST_LOOKUP_FAILURE;
   }
+#endif
 
   server->servAddr.sin_family= h->h_addrtype;
   memcpy((char *) &server->servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
+
   server->servAddr.sin_port = htons(server->port);
 
   return MEMCACHED_SUCCESS;
@@ -72,7 +89,12 @@ static memcached_return udp_connect(memcached_st *ptr, unsigned int server_key)
     /* Old connection junk still is in the structure */
     WATCHPOINT_ASSERT(ptr->hosts[server_key].stack_responses == 0);
 
-    if (ptr->hosts[server_key].sockaddr_inited == MEMCACHED_NOT_ALLOCATED)
+    /*
+      If we have not allocated the hosts object.
+      Or if the cache has not been set.
+    */
+    if (ptr->hosts[server_key].sockaddr_inited == MEMCACHED_NOT_ALLOCATED || 
+        (!(ptr->flags & MEM_USE_CACHE_LOOKUPS)))
     {
       memcached_return rc;
 
@@ -205,6 +227,9 @@ memcached_return memcached_connect(memcached_st *ptr, unsigned int server_key)
       rc= unix_socket_connect(ptr, server_key);
       break;
     }
+
+    if (rc != MEMCACHED_SUCCESS)
+      WATCHPOINT_ERROR(rc);
   }
   else
   {
@@ -235,7 +260,10 @@ memcached_return memcached_connect(memcached_st *ptr, unsigned int server_key)
       rc= MEMCACHED_SUCCESS;
 
       if (possible_rc != MEMCACHED_SUCCESS)
+      {
+        WATCHPOINT_ERROR(possible_rc);
         rc= MEMCACHED_SOME_ERRORS;
+      }
     }
   }
   LIBMEMCACHED_MEMCACHED_CONNECT_END();