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>
44 static memcached_return_t
connect_poll(memcached_server_st
*ptr
)
48 fds
[0].events
= POLLOUT
;
52 while (--loop_max
) // Should only loop on cases of ERESTART or EINTR
55 if (ptr
->root
->poll_timeout
)
57 error
= poll(fds
, 1, ptr
->root
->connect_timeout
);
69 socklen_t len
= sizeof (err
);
70 (void)getsockopt(ptr
->fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
);
72 // We check the value to see what happened wth the socket.
75 return MEMCACHED_SUCCESS
;
78 return memcached_set_errno(*ptr
, err
, MEMCACHED_AT
);
82 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
85 default: // A real error occurred and we need to completely bail
86 WATCHPOINT_ERRNO(get_socket_errno());
87 switch (get_socket_errno())
89 #ifdef TARGET_OS_LINUX
97 return memcached_set_error(*ptr
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
);
100 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"));
102 default: // This should not happen
103 if (fds
[0].revents
& POLLERR
)
106 socklen_t len
= sizeof (err
);
107 (void)getsockopt(ptr
->fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
);
108 ptr
->cached_errno
= (err
== 0) ? get_socket_errno() : err
;
112 ptr
->cached_errno
= get_socket_errno();
115 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
116 (void)closesocket(ptr
->fd
);
117 ptr
->fd
= INVALID_SOCKET
;
118 ptr
->state
= MEMCACHED_SERVER_STATE_NEW
;
120 return memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
125 // This should only be possible from ERESTART or EINTR;
126 return memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
129 static memcached_return_t
set_hostinfo(memcached_server_st
*server
)
131 WATCHPOINT_ASSERT(not server
->address_info
); // We cover the case where a programming mistake has been made.
132 if (server
->address_info
)
134 freeaddrinfo(server
->address_info
);
135 server
->address_info
= NULL
;
136 server
->address_info_next
= NULL
;
139 char str_port
[NI_MAXSERV
];
140 int length
= snprintf(str_port
, NI_MAXSERV
, "%u", (uint32_t)server
->port
);
141 if (length
>= NI_MAXSERV
|| length
< 0)
142 return MEMCACHED_FAILURE
;
144 struct addrinfo hints
;
145 memset(&hints
, 0, sizeof(struct addrinfo
));
148 hints
.ai_family
= AF_INET
;
150 if (server
->type
== MEMCACHED_CONNECTION_UDP
)
152 hints
.ai_protocol
= IPPROTO_UDP
;
153 hints
.ai_socktype
= SOCK_DGRAM
;
157 hints
.ai_socktype
= SOCK_STREAM
;
158 hints
.ai_protocol
= IPPROTO_TCP
;
162 switch(errcode
= getaddrinfo(server
->hostname
, str_port
, &hints
, &server
->address_info
))
168 return memcached_set_error(*server
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
, memcached_string_make_from_cstr(gai_strerror(errcode
)));
171 return memcached_set_errno(*server
, errno
, MEMCACHED_AT
, memcached_literal_param("getaddrinfo(EAI_SYSTEM)"));
174 return memcached_set_error(*server
, MEMCACHED_INVALID_ARGUMENTS
, MEMCACHED_AT
, memcached_literal_param("getaddrinfo(EAI_BADFLAGS)"));
177 return memcached_set_error(*server
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
, memcached_literal_param("getaddrinfo(EAI_MEMORY)"));
181 WATCHPOINT_STRING(server
->hostname
);
182 WATCHPOINT_STRING(gai_strerror(errcode
));
183 return memcached_set_error(*server
, MEMCACHED_HOST_LOOKUP_FAILURE
, MEMCACHED_AT
, memcached_string_make_from_cstr(gai_strerror(errcode
)));
186 server
->address_info_next
= server
->address_info
;
187 server
->state
= MEMCACHED_SERVER_STATE_ADDRINFO
;
189 return MEMCACHED_SUCCESS
;
192 static inline void set_socket_nonblocking(memcached_server_st
*ptr
)
196 if (ioctlsocket(ptr
->fd
, FIONBIO
, &arg
) == SOCKET_ERROR
)
198 memcached_set_errno(*ptr
, get_socket_errno(), NULL
);
205 flags
= fcntl(ptr
->fd
, F_GETFL
, 0);
206 } while (flags
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
210 memcached_set_errno(*ptr
, errno
, NULL
);
212 else if ((flags
& O_NONBLOCK
) == 0)
218 rval
= fcntl(ptr
->fd
, F_SETFL
, flags
| O_NONBLOCK
);
219 } while (rval
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
221 unlikely (rval
== -1)
223 memcached_set_errno(*ptr
, errno
, NULL
);
229 static void set_socket_options(memcached_server_st
*ptr
)
231 WATCHPOINT_ASSERT(ptr
->fd
!= -1);
233 if (ptr
->type
== MEMCACHED_CONNECTION_UDP
)
237 if (ptr
->root
->snd_timeout
)
240 struct timeval waittime
;
243 waittime
.tv_usec
= ptr
->root
->snd_timeout
;
245 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_SNDTIMEO
,
246 &waittime
, (socklen_t
)sizeof(struct timeval
));
247 WATCHPOINT_ASSERT(error
== 0);
252 if (ptr
->root
->rcv_timeout
)
255 struct timeval waittime
;
258 waittime
.tv_usec
= ptr
->root
->rcv_timeout
;
260 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_RCVTIMEO
,
261 &waittime
, (socklen_t
)sizeof(struct timeval
));
262 WATCHPOINT_ASSERT(error
== 0);
267 #if defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
270 int error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (void *)&set
, sizeof(int));
272 // This is not considered a fatal error
275 WATCHPOINT_ERRNO(get_socket_errno());
276 perror("setsockopt(SO_NOSIGPIPE)");
281 if (ptr
->root
->flags
.no_block
)
284 struct linger linger
;
287 linger
.l_linger
= 0; /* By default on close() just drop the socket */
288 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_LINGER
,
289 &linger
, (socklen_t
)sizeof(struct linger
));
290 WATCHPOINT_ASSERT(error
== 0);
293 if (ptr
->root
->flags
.tcp_nodelay
)
298 error
= setsockopt(ptr
->fd
, IPPROTO_TCP
, TCP_NODELAY
,
299 &flag
, (socklen_t
)sizeof(int));
300 WATCHPOINT_ASSERT(error
== 0);
303 if (ptr
->root
->flags
.tcp_keepalive
)
308 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_KEEPALIVE
,
309 &flag
, (socklen_t
)sizeof(int));
310 WATCHPOINT_ASSERT(error
== 0);
314 if (ptr
->root
->tcp_keepidle
> 0)
318 error
= setsockopt(ptr
->fd
, IPPROTO_TCP
, TCP_KEEPIDLE
,
319 &ptr
->root
->tcp_keepidle
, (socklen_t
)sizeof(int));
320 WATCHPOINT_ASSERT(error
== 0);
324 if (ptr
->root
->send_size
> 0)
328 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_SNDBUF
,
329 &ptr
->root
->send_size
, (socklen_t
)sizeof(int));
330 WATCHPOINT_ASSERT(error
== 0);
333 if (ptr
->root
->recv_size
> 0)
337 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_RCVBUF
,
338 &ptr
->root
->recv_size
, (socklen_t
)sizeof(int));
339 WATCHPOINT_ASSERT(error
== 0);
343 /* libmemcached will always use nonblocking IO to avoid write deadlocks */
344 set_socket_nonblocking(ptr
);
347 static memcached_return_t
unix_socket_connect(memcached_server_st
*ptr
)
350 WATCHPOINT_ASSERT(ptr
->fd
== -1);
352 if ((ptr
->fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) < 0)
354 return memcached_set_errno(*ptr
, errno
, NULL
);
357 struct sockaddr_un servAddr
;
359 memset(&servAddr
, 0, sizeof (struct sockaddr_un
));
360 servAddr
.sun_family
= AF_UNIX
;
361 strncpy(servAddr
.sun_path
, ptr
->hostname
, sizeof(servAddr
.sun_path
)); /* Copy filename */
364 if (connect(ptr
->fd
, (struct sockaddr
*)&servAddr
, sizeof(servAddr
)) < 0)
373 case EISCONN
: /* We were spinning waiting on connect */
375 WATCHPOINT_ASSERT(0); // Programmer error
380 WATCHPOINT_ERRNO(errno
);
381 return memcached_set_errno(*ptr
, errno
, MEMCACHED_AT
);
385 ptr
->state
= MEMCACHED_SERVER_STATE_CONNECTED
;
387 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
389 return MEMCACHED_SUCCESS
;
392 return MEMCACHED_NOT_SUPPORTED
;
396 static memcached_return_t
network_connect(memcached_server_st
*ptr
)
398 bool timeout_error_occured
= false;
400 WATCHPOINT_ASSERT(ptr
->fd
== INVALID_SOCKET
);
401 WATCHPOINT_ASSERT(ptr
->cursor_active
== 0);
403 if (not ptr
->address_info
)
405 WATCHPOINT_ASSERT(ptr
->state
== MEMCACHED_SERVER_STATE_NEW
);
406 memcached_return_t rc
;
410 if ((rc
= set_hostinfo(ptr
)) != MEMCACHED_TIMEOUT
)
414 struct timespec dream
, rem
;
419 nanosleep(&dream
, &rem
);
423 if (memcached_failed(rc
))
427 /* Create the socket */
428 while (ptr
->address_info_next
&& ptr
->fd
== INVALID_SOCKET
)
430 /* Memcache server does not support IPV6 in udp mode, so skip if not ipv4 */
431 if (ptr
->type
== MEMCACHED_CONNECTION_UDP
&& ptr
->address_info_next
->ai_family
!= AF_INET
)
433 ptr
->address_info_next
= ptr
->address_info_next
->ai_next
;
437 if ((ptr
->fd
= socket(ptr
->address_info_next
->ai_family
,
438 ptr
->address_info_next
->ai_socktype
,
439 ptr
->address_info_next
->ai_protocol
)) < 0)
441 return memcached_set_errno(*ptr
, get_socket_errno(), NULL
);
444 set_socket_options(ptr
);
446 /* connect to server */
447 if ((connect(ptr
->fd
, ptr
->address_info_next
->ai_addr
, ptr
->address_info_next
->ai_addrlen
) != SOCKET_ERROR
))
449 ptr
->state
= MEMCACHED_SERVER_STATE_CONNECTED
;
453 /* An error occurred */
454 switch (get_socket_errno())
457 timeout_error_occured
= true;
461 case EINPROGRESS
: // nonblocking mode - first return
462 case EALREADY
: // nonblocking mode - subsequent returns
464 ptr
->state
= MEMCACHED_SERVER_STATE_IN_PROGRESS
;
465 memcached_return_t rc
= connect_poll(ptr
);
467 if (memcached_success(rc
))
469 ptr
->state
= MEMCACHED_SERVER_STATE_CONNECTED
;
470 return MEMCACHED_SUCCESS
;
473 // A timeout here is treated as an error, we will not retry
474 if (rc
== MEMCACHED_TIMEOUT
)
476 timeout_error_occured
= true;
481 case EISCONN
: // we are connected :-)
482 WATCHPOINT_ASSERT(0); // This is a programmer's error
485 case EINTR
: // Special case, we retry ai_addr
486 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
487 (void)closesocket(ptr
->fd
);
488 ptr
->fd
= INVALID_SOCKET
;
495 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
496 (void)closesocket(ptr
->fd
);
497 ptr
->fd
= INVALID_SOCKET
;
498 ptr
->address_info_next
= ptr
->address_info_next
->ai_next
;
501 WATCHPOINT_ASSERT(ptr
->fd
== INVALID_SOCKET
);
503 if (timeout_error_occured
)
505 if (ptr
->fd
!= INVALID_SOCKET
)
507 (void)closesocket(ptr
->fd
);
508 ptr
->fd
= INVALID_SOCKET
;
512 WATCHPOINT_STRING("Never got a good file descriptor");
513 /* Failed to connect. schedule next retry */
514 if (ptr
->root
->retry_timeout
)
516 struct timeval next_time
;
518 if (gettimeofday(&next_time
, NULL
) == 0)
519 ptr
->next_retry
= next_time
.tv_sec
+ ptr
->root
->retry_timeout
;
522 if (timeout_error_occured
)
523 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
525 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
); /* The last error should be from connect() */
528 void set_last_disconnected_host(memcached_server_write_instance_st self
)
531 memcached_st
*root
= (memcached_st
*)self
->root
;
534 WATCHPOINT_STRING(self
->hostname
);
535 WATCHPOINT_NUMBER(self
->port
);
536 WATCHPOINT_ERRNO(self
->cached_errno
);
538 memcached_server_free(root
->last_disconnected_server
);
539 root
->last_disconnected_server
= memcached_server_clone(NULL
, self
);
542 memcached_return_t
memcached_connect(memcached_server_write_instance_st ptr
)
544 memcached_return_t rc
= MEMCACHED_NO_SERVERS
;
546 if (ptr
->fd
!= INVALID_SOCKET
)
547 return MEMCACHED_SUCCESS
;
549 LIBMEMCACHED_MEMCACHED_CONNECT_START();
551 /* both retry_timeout and server_failure_limit must be set in order to delay retrying a server on error. */
552 WATCHPOINT_ASSERT(ptr
->root
);
553 if (ptr
->root
->retry_timeout
&& ptr
->next_retry
)
555 struct timeval curr_time
;
557 gettimeofday(&curr_time
, NULL
);
559 // We should optimize this to remove the allocation if the server was
560 // the last server to die
561 if (ptr
->next_retry
> curr_time
.tv_sec
)
563 set_last_disconnected_host(ptr
);
565 return memcached_set_error(*ptr
, MEMCACHED_SERVER_MARKED_DEAD
, MEMCACHED_AT
);
569 // If we are over the counter failure, we just fail. Reject host only
570 // works if you have a set number of failures.
571 if (ptr
->root
->server_failure_limit
&& ptr
->server_failure_counter
>= ptr
->root
->server_failure_limit
)
573 set_last_disconnected_host(ptr
);
575 // @todo fix this by fixing behavior to no longer make use of
577 if (_is_auto_eject_host(ptr
->root
))
579 run_distribution((memcached_st
*)ptr
->root
);
582 return memcached_set_error(*ptr
, MEMCACHED_SERVER_MARKED_DEAD
, MEMCACHED_AT
);
585 /* We need to clean up the multi startup piece */
588 case MEMCACHED_CONNECTION_UNKNOWN
:
589 WATCHPOINT_ASSERT(0);
590 rc
= MEMCACHED_NOT_SUPPORTED
;
593 case MEMCACHED_CONNECTION_UDP
:
594 case MEMCACHED_CONNECTION_TCP
:
595 rc
= network_connect(ptr
);
596 #ifdef LIBMEMCACHED_WITH_SASL_SUPPORT
597 if (ptr
->fd
!= INVALID_SOCKET
and ptr
->root
->sasl
.callbacks
)
599 rc
= memcached_sasl_authenticate_connection(ptr
);
600 if (memcached_failed(rc
) and ptr
->fd
!= INVALID_SOCKET
)
602 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
603 (void)closesocket(ptr
->fd
);
604 ptr
->fd
= INVALID_SOCKET
;
610 case MEMCACHED_CONNECTION_UNIX_SOCKET
:
611 rc
= unix_socket_connect(ptr
);
614 case MEMCACHED_CONNECTION_MAX
:
616 WATCHPOINT_ASSERT(0);
619 if (memcached_success(rc
))
621 ptr
->server_failure_counter
= 0;
626 memcached_set_error(*ptr
, rc
, MEMCACHED_AT
);
627 ptr
->server_failure_counter
++;
628 set_last_disconnected_host(ptr
);
631 LIBMEMCACHED_MEMCACHED_CONNECT_END();