f95b8e7d752f3115298cf85310b63c1d93a9bb69
[awesomized/libmemcached] / lib / memcached_connect.c
1 #include "common.h"
2
3 #include <fcntl.h>
4 #include <sys/types.h>
5 #include <sys/socket.h>
6 #include <netinet/tcp.h>
7
8 memcached_return memcached_real_connect(memcached_st *ptr, unsigned int server_key)
9 {
10 struct sockaddr_in localAddr, servAddr;
11 struct hostent *h;
12
13 if (ptr->hosts[server_key].fd == -1)
14 {
15 if ((h= gethostbyname(ptr->hosts[server_key].hostname)) == NULL)
16 return MEMCACHED_HOST_LOCKUP_FAILURE;
17
18 servAddr.sin_family= h->h_addrtype;
19 memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
20 servAddr.sin_port = htons(ptr->hosts[server_key].port);
21
22 /* Create the socket */
23 if ((ptr->hosts[server_key].fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
24 {
25 ptr->my_errno= errno;
26 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE;
27 }
28
29
30 /* bind any port number */
31 localAddr.sin_family = AF_INET;
32 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
33 localAddr.sin_port = htons(0);
34
35 /* For the moment, not getting a nonblocking mode will note be fatal */
36 if (ptr->flags & MEM_NO_BLOCK)
37 {
38 int flags;
39
40 flags= fcntl(ptr->hosts[server_key].fd, F_GETFL, 0);
41 if (flags != -1)
42 (void)fcntl(ptr->hosts[server_key].fd, F_SETFL, flags | O_NONBLOCK);
43 }
44
45 if (ptr->flags & MEM_TCP_NODELAY)
46 {
47 int flag= 1;
48
49 setsockopt(ptr->hosts[server_key].fd, IPPROTO_TCP, TCP_NODELAY,
50 &flag, (socklen_t)sizeof(int));
51 }
52
53 /* connect to server */
54 test_connect:
55 if (connect(ptr->hosts[server_key].fd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
56 {
57 switch (errno) {
58 /* We are spinning waiting on connect */
59 case EINPROGRESS:
60 case EINTR:
61 goto test_connect;
62 case EISCONN: /* We were spinning waiting on connect */
63 break;
64 default:
65 ptr->my_errno= errno;
66 return MEMCACHED_HOST_LOCKUP_FAILURE;
67 }
68 ptr->connected++;
69 }
70 }
71
72 return MEMCACHED_SUCCESS;
73 }
74
75
76 memcached_return memcached_connect(memcached_st *ptr, unsigned int server_key)
77 {
78 memcached_return rc;
79 LIBMEMCACHED_MEMCACHED_CONNECT_START();
80
81 if (ptr->connected == ptr->number_of_hosts)
82 return MEMCACHED_SUCCESS;
83
84 if (!ptr->hosts)
85 return MEMCACHED_NO_SERVERS;
86
87 /* We need to clean up the multi startup piece */
88 if (server_key)
89 rc= memcached_real_connect(ptr, server_key);
90 else
91 {
92 unsigned int x;
93
94 for (x= 0; x < ptr->number_of_hosts; x++)
95 rc= memcached_real_connect(ptr, x);
96 }
97 LIBMEMCACHED_MEMCACHED_CONNECT_END();
98
99 return rc;
100 }