1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 * Copyright (C) 2006-2010 Brian Aker All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
15 * * Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following disclaimer
17 * in the documentation and/or other materials provided with the
20 * * The names of its contributors may not be used to endorse or
21 * promote products derived from this software without specific prior
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 #include <libmemcached/common.h>
43 static memcached_return_t
connect_poll(memcached_server_st
*ptr
)
47 fds
[0].events
= POLLOUT
;
51 if (ptr
->root
->poll_timeout
== 0)
53 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
56 while (--loop_max
) // Should only loop on cases of ERESTART or EINTR
58 int error
= poll(fds
, 1, ptr
->root
->connect_timeout
);
64 socklen_t len
= sizeof (err
);
65 (void)getsockopt(ptr
->fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
);
67 // We check the value to see what happened wth the socket.
70 return MEMCACHED_SUCCESS
;
73 return memcached_set_errno(*ptr
, err
, MEMCACHED_AT
);
77 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
80 default: // A real error occurred and we need to completely bail
81 WATCHPOINT_ERRNO(get_socket_errno());
82 switch (get_socket_errno())
84 #ifdef TARGET_OS_LINUX
92 return memcached_set_error(*ptr
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
);
95 return memcached_set_error(*ptr
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
, memcached_literal_param("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid"));
97 default: // This should not happen
98 if (fds
[0].revents
& POLLERR
)
101 socklen_t len
= sizeof (err
);
102 (void)getsockopt(ptr
->fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
);
103 memcached_set_errno(*ptr
, (err
== 0) ? get_socket_errno() : err
, MEMCACHED_AT
);
107 memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
110 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
111 (void)closesocket(ptr
->fd
);
112 ptr
->fd
= INVALID_SOCKET
;
113 ptr
->state
= MEMCACHED_SERVER_STATE_NEW
;
115 return memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
120 // This should only be possible from ERESTART or EINTR;
121 return memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
124 static memcached_return_t
set_hostinfo(memcached_server_st
*server
)
126 WATCHPOINT_ASSERT(not server
->address_info
); // We cover the case where a programming mistake has been made.
127 if (server
->address_info
)
129 freeaddrinfo(server
->address_info
);
130 server
->address_info
= NULL
;
131 server
->address_info_next
= NULL
;
134 char str_port
[NI_MAXSERV
];
135 int length
= snprintf(str_port
, NI_MAXSERV
, "%u", (uint32_t)server
->port
);
136 if (length
>= NI_MAXSERV
|| length
< 0)
138 return MEMCACHED_FAILURE
;
141 struct addrinfo hints
;
142 memset(&hints
, 0, sizeof(struct addrinfo
));
145 hints
.ai_family
= AF_INET
;
147 if (server
->type
== MEMCACHED_CONNECTION_UDP
)
149 hints
.ai_protocol
= IPPROTO_UDP
;
150 hints
.ai_socktype
= SOCK_DGRAM
;
154 hints
.ai_socktype
= SOCK_STREAM
;
155 hints
.ai_protocol
= IPPROTO_TCP
;
159 switch(errcode
= getaddrinfo(server
->hostname
, str_port
, &hints
, &server
->address_info
))
165 return memcached_set_error(*server
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
, memcached_string_make_from_cstr(gai_strerror(errcode
)));
168 return memcached_set_errno(*server
, errno
, MEMCACHED_AT
, memcached_literal_param("getaddrinfo(EAI_SYSTEM)"));
171 return memcached_set_error(*server
, MEMCACHED_INVALID_ARGUMENTS
, MEMCACHED_AT
, memcached_literal_param("getaddrinfo(EAI_BADFLAGS)"));
174 return memcached_set_error(*server
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
, memcached_literal_param("getaddrinfo(EAI_MEMORY)"));
178 WATCHPOINT_STRING(server
->hostname
);
179 WATCHPOINT_STRING(gai_strerror(errcode
));
180 return memcached_set_error(*server
, MEMCACHED_HOST_LOOKUP_FAILURE
, MEMCACHED_AT
, memcached_string_make_from_cstr(gai_strerror(errcode
)));
183 server
->address_info_next
= server
->address_info
;
184 server
->state
= MEMCACHED_SERVER_STATE_ADDRINFO
;
186 return MEMCACHED_SUCCESS
;
189 static inline void set_socket_nonblocking(memcached_server_st
*ptr
)
193 if (ioctlsocket(ptr
->fd
, FIONBIO
, &arg
) == SOCKET_ERROR
)
195 memcached_set_errno(*ptr
, get_socket_errno(), NULL
);
202 flags
= fcntl(ptr
->fd
, F_GETFL
, 0);
203 } while (flags
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
207 memcached_set_errno(*ptr
, errno
, NULL
);
209 else if ((flags
& O_NONBLOCK
) == 0)
215 rval
= fcntl(ptr
->fd
, F_SETFL
, flags
| O_NONBLOCK
);
216 } while (rval
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
218 unlikely (rval
== -1)
220 memcached_set_errno(*ptr
, errno
, NULL
);
226 static void set_socket_options(memcached_server_st
*ptr
)
228 WATCHPOINT_ASSERT(ptr
->fd
!= -1);
230 if (ptr
->type
== MEMCACHED_CONNECTION_UDP
)
234 if (ptr
->root
->snd_timeout
)
237 struct timeval waittime
;
240 waittime
.tv_usec
= ptr
->root
->snd_timeout
;
242 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_SNDTIMEO
,
243 &waittime
, (socklen_t
)sizeof(struct timeval
));
244 WATCHPOINT_ASSERT(error
== 0);
249 if (ptr
->root
->rcv_timeout
)
252 struct timeval waittime
;
255 waittime
.tv_usec
= ptr
->root
->rcv_timeout
;
257 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_RCVTIMEO
,
258 &waittime
, (socklen_t
)sizeof(struct timeval
));
259 WATCHPOINT_ASSERT(error
== 0);
264 #if defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
267 int error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (void *)&set
, sizeof(int));
269 // This is not considered a fatal error
272 WATCHPOINT_ERRNO(get_socket_errno());
273 perror("setsockopt(SO_NOSIGPIPE)");
278 if (ptr
->root
->flags
.no_block
)
281 struct linger linger
;
284 linger
.l_linger
= 0; /* By default on close() just drop the socket */
285 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_LINGER
,
286 &linger
, (socklen_t
)sizeof(struct linger
));
287 WATCHPOINT_ASSERT(error
== 0);
290 if (ptr
->root
->flags
.tcp_nodelay
)
295 error
= setsockopt(ptr
->fd
, IPPROTO_TCP
, TCP_NODELAY
,
296 &flag
, (socklen_t
)sizeof(int));
297 WATCHPOINT_ASSERT(error
== 0);
300 if (ptr
->root
->flags
.tcp_keepalive
)
305 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_KEEPALIVE
,
306 &flag
, (socklen_t
)sizeof(int));
307 WATCHPOINT_ASSERT(error
== 0);
311 if (ptr
->root
->tcp_keepidle
> 0)
315 error
= setsockopt(ptr
->fd
, IPPROTO_TCP
, TCP_KEEPIDLE
,
316 &ptr
->root
->tcp_keepidle
, (socklen_t
)sizeof(int));
317 WATCHPOINT_ASSERT(error
== 0);
321 if (ptr
->root
->send_size
> 0)
325 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_SNDBUF
,
326 &ptr
->root
->send_size
, (socklen_t
)sizeof(int));
327 WATCHPOINT_ASSERT(error
== 0);
330 if (ptr
->root
->recv_size
> 0)
334 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_RCVBUF
,
335 &ptr
->root
->recv_size
, (socklen_t
)sizeof(int));
336 WATCHPOINT_ASSERT(error
== 0);
340 /* libmemcached will always use nonblocking IO to avoid write deadlocks */
341 set_socket_nonblocking(ptr
);
344 static memcached_return_t
unix_socket_connect(memcached_server_st
*ptr
)
347 WATCHPOINT_ASSERT(ptr
->fd
== -1);
349 if ((ptr
->fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) < 0)
351 memcached_set_errno(*ptr
, errno
, NULL
);
352 return MEMCACHED_CONNECTION_FAILURE
;
355 struct sockaddr_un servAddr
;
357 memset(&servAddr
, 0, sizeof (struct sockaddr_un
));
358 servAddr
.sun_family
= AF_UNIX
;
359 strncpy(servAddr
.sun_path
, ptr
->hostname
, sizeof(servAddr
.sun_path
)); /* Copy filename */
362 if (connect(ptr
->fd
, (struct sockaddr
*)&servAddr
, sizeof(servAddr
)) < 0)
371 case EISCONN
: /* We were spinning waiting on connect */
373 WATCHPOINT_ASSERT(0); // Programmer error
378 WATCHPOINT_ERRNO(errno
);
379 memcached_set_errno(*ptr
, errno
, MEMCACHED_AT
);
380 return MEMCACHED_CONNECTION_FAILURE
;
384 ptr
->state
= MEMCACHED_SERVER_STATE_CONNECTED
;
386 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
388 return MEMCACHED_SUCCESS
;
391 return MEMCACHED_NOT_SUPPORTED
;
395 static memcached_return_t
network_connect(memcached_server_st
*ptr
)
397 bool timeout_error_occured
= false;
399 WATCHPOINT_ASSERT(ptr
->fd
== INVALID_SOCKET
);
400 WATCHPOINT_ASSERT(ptr
->cursor_active
== 0);
402 if (not ptr
->address_info
)
404 WATCHPOINT_ASSERT(ptr
->state
== MEMCACHED_SERVER_STATE_NEW
);
405 memcached_return_t rc
;
409 if ((rc
= set_hostinfo(ptr
)) != MEMCACHED_TIMEOUT
)
413 struct timespec dream
, rem
;
418 nanosleep(&dream
, &rem
);
422 if (memcached_failed(rc
))
426 /* Create the socket */
427 while (ptr
->address_info_next
&& ptr
->fd
== INVALID_SOCKET
)
429 /* Memcache server does not support IPV6 in udp mode, so skip if not ipv4 */
430 if (ptr
->type
== MEMCACHED_CONNECTION_UDP
&& ptr
->address_info_next
->ai_family
!= AF_INET
)
432 ptr
->address_info_next
= ptr
->address_info_next
->ai_next
;
436 if ((ptr
->fd
= socket(ptr
->address_info_next
->ai_family
,
437 ptr
->address_info_next
->ai_socktype
,
438 ptr
->address_info_next
->ai_protocol
)) < 0)
440 return memcached_set_errno(*ptr
, get_socket_errno(), NULL
);
443 set_socket_options(ptr
);
445 /* connect to server */
446 if ((connect(ptr
->fd
, ptr
->address_info_next
->ai_addr
, ptr
->address_info_next
->ai_addrlen
) != SOCKET_ERROR
))
448 ptr
->state
= MEMCACHED_SERVER_STATE_CONNECTED
;
452 /* An error occurred */
453 switch (get_socket_errno())
456 timeout_error_occured
= true;
460 case EINPROGRESS
: // nonblocking mode - first return
461 case EALREADY
: // nonblocking mode - subsequent returns
463 ptr
->state
= MEMCACHED_SERVER_STATE_IN_PROGRESS
;
464 memcached_return_t rc
= connect_poll(ptr
);
466 if (memcached_success(rc
))
468 ptr
->state
= MEMCACHED_SERVER_STATE_CONNECTED
;
469 return MEMCACHED_SUCCESS
;
472 // A timeout here is treated as an error, we will not retry
473 if (rc
== MEMCACHED_TIMEOUT
)
475 timeout_error_occured
= true;
480 case EISCONN
: // we are connected :-)
481 WATCHPOINT_ASSERT(0); // This is a programmer's error
484 case EINTR
: // Special case, we retry ai_addr
485 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
486 (void)closesocket(ptr
->fd
);
487 ptr
->fd
= INVALID_SOCKET
;
494 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
495 (void)closesocket(ptr
->fd
);
496 ptr
->fd
= INVALID_SOCKET
;
497 ptr
->address_info_next
= ptr
->address_info_next
->ai_next
;
500 WATCHPOINT_ASSERT(ptr
->fd
== INVALID_SOCKET
);
502 if (timeout_error_occured
)
504 if (ptr
->fd
!= INVALID_SOCKET
)
506 (void)closesocket(ptr
->fd
);
507 ptr
->fd
= INVALID_SOCKET
;
511 WATCHPOINT_STRING("Never got a good file descriptor");
512 /* Failed to connect. schedule next retry */
513 if (ptr
->root
->retry_timeout
)
515 struct timeval next_time
;
517 if (gettimeofday(&next_time
, NULL
) == 0)
518 ptr
->next_retry
= next_time
.tv_sec
+ ptr
->root
->retry_timeout
;
521 if (timeout_error_occured
)
522 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
524 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
); /* The last error should be from connect() */
527 void set_last_disconnected_host(memcached_server_write_instance_st self
)
530 memcached_st
*root
= (memcached_st
*)self
->root
;
533 WATCHPOINT_STRING(self
->hostname
);
534 WATCHPOINT_NUMBER(self
->port
);
535 WATCHPOINT_ERRNO(self
->cached_errno
);
537 memcached_server_free(root
->last_disconnected_server
);
538 root
->last_disconnected_server
= memcached_server_clone(NULL
, self
);
541 memcached_return_t
memcached_connect(memcached_server_write_instance_st ptr
)
543 memcached_return_t rc
= MEMCACHED_NO_SERVERS
;
545 if (ptr
->fd
!= INVALID_SOCKET
)
547 return MEMCACHED_SUCCESS
;
550 LIBMEMCACHED_MEMCACHED_CONNECT_START();
552 /* both retry_timeout and server_failure_limit must be set in order to delay retrying a server on error. */
553 WATCHPOINT_ASSERT(ptr
->root
);
554 if (ptr
->root
->retry_timeout
&& ptr
->next_retry
)
556 struct timeval curr_time
;
558 gettimeofday(&curr_time
, NULL
);
560 // We should optimize this to remove the allocation if the server was
561 // the last server to die
562 if (ptr
->next_retry
> curr_time
.tv_sec
)
564 set_last_disconnected_host(ptr
);
566 return memcached_set_error(*ptr
, MEMCACHED_SERVER_MARKED_DEAD
, MEMCACHED_AT
);
570 // If we are over the counter failure, we just fail. Reject host only
571 // works if you have a set number of failures.
572 if (ptr
->root
->server_failure_limit
&& ptr
->server_failure_counter
>= ptr
->root
->server_failure_limit
)
574 set_last_disconnected_host(ptr
);
576 // @todo fix this by fixing behavior to no longer make use of
578 if (_is_auto_eject_host(ptr
->root
))
580 run_distribution((memcached_st
*)ptr
->root
);
583 return memcached_set_error(*ptr
, MEMCACHED_SERVER_MARKED_DEAD
, MEMCACHED_AT
);
586 /* We need to clean up the multi startup piece */
589 case MEMCACHED_CONNECTION_UNKNOWN
:
590 WATCHPOINT_ASSERT(0);
591 rc
= MEMCACHED_NOT_SUPPORTED
;
594 case MEMCACHED_CONNECTION_UDP
:
595 case MEMCACHED_CONNECTION_TCP
:
596 rc
= network_connect(ptr
);
597 #ifdef LIBMEMCACHED_WITH_SASL_SUPPORT
598 if (ptr
->fd
!= INVALID_SOCKET
and ptr
->root
->sasl
.callbacks
)
600 rc
= memcached_sasl_authenticate_connection(ptr
);
601 if (memcached_failed(rc
) and ptr
->fd
!= INVALID_SOCKET
)
603 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
604 (void)closesocket(ptr
->fd
);
605 ptr
->fd
= INVALID_SOCKET
;
611 case MEMCACHED_CONNECTION_UNIX_SOCKET
:
612 rc
= unix_socket_connect(ptr
);
615 case MEMCACHED_CONNECTION_MAX
:
617 WATCHPOINT_ASSERT(0);
620 if (memcached_success(rc
))
622 ptr
->server_failure_counter
= 0;
627 memcached_set_error(*ptr
, rc
, MEMCACHED_AT
);
628 ptr
->server_failure_counter
++;
629 set_last_disconnected_host(ptr
);
632 LIBMEMCACHED_MEMCACHED_CONNECT_END();