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
;
53 while (--loop_max
) // Should only loop on cases of ERESTART or EINTR
55 error
= poll(fds
, 1, ptr
->root
->connect_timeout
);
62 socklen_t len
= sizeof (err
);
63 (void)getsockopt(ptr
->fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
);
65 // We check the value to see what happened wth the socket.
68 return MEMCACHED_SUCCESS
;
72 ptr
->cached_errno
= errno
;
74 return MEMCACHED_ERRNO
;
78 return MEMCACHED_TIMEOUT
;
79 default: // A real error occurred and we need to completely bail
80 WATCHPOINT_ERRNO(get_socket_errno());
81 switch (get_socket_errno())
83 #ifdef TARGET_OS_LINUX
89 if (fds
[0].revents
& POLLERR
)
92 socklen_t len
= sizeof (err
);
93 (void)getsockopt(ptr
->fd
, SOL_SOCKET
, SO_ERROR
, &err
, &len
);
94 ptr
->cached_errno
= (err
== 0) ? get_socket_errno() : err
;
98 ptr
->cached_errno
= get_socket_errno();
101 (void)closesocket(ptr
->fd
);
102 ptr
->fd
= INVALID_SOCKET
;
104 return MEMCACHED_ERRNO
;
109 // This should only be possible from ERESTART or EINTR;
110 ptr
->cached_errno
= get_socket_errno();
112 return MEMCACHED_ERRNO
;
115 static memcached_return_t
set_hostinfo(memcached_server_st
*server
)
117 char str_port
[NI_MAXSERV
];
119 assert(! server
->address_info
); // We cover the case where a programming mistake has been made.
120 if (server
->address_info
)
122 freeaddrinfo(server
->address_info
);
123 server
->address_info
= NULL
;
124 server
->address_info_next
= NULL
;
127 int length
= snprintf(str_port
, NI_MAXSERV
, "%u", (uint32_t)server
->port
);
128 if (length
>= NI_MAXSERV
|| length
< 0)
129 return MEMCACHED_FAILURE
;
131 struct addrinfo hints
;
132 memset(&hints
, 0, sizeof(struct addrinfo
));
135 hints
.ai_family
= AF_INET
;
137 if (server
->type
== MEMCACHED_CONNECTION_UDP
)
139 hints
.ai_protocol
= IPPROTO_UDP
;
140 hints
.ai_socktype
= SOCK_DGRAM
;
144 hints
.ai_socktype
= SOCK_STREAM
;
145 hints
.ai_protocol
= IPPROTO_TCP
;
152 switch(errcode
= getaddrinfo(server
->hostname
, str_port
, &hints
, &server
->address_info
))
160 struct timespec dream
, rem
;
165 nanosleep(&dream
, &rem
);
171 return memcached_set_error_string(*server
, MEMCACHED_HOST_LOOKUP_FAILURE
, gai_strerror(errcode
), strlen(gai_strerror(errcode
)));
176 static memcached_string_t mesg
= { memcached_string_make("getaddrinfo") };
177 return memcached_set_errno(*server
, errno
, &mesg
);
180 return memcached_set_error_string(*server
, MEMCACHED_HOST_LOOKUP_FAILURE
, memcached_literal_param("getaddrinfo(EAI_BADFLAGS)"));
183 return memcached_set_error_string(*server
, MEMCACHED_ERRNO
, memcached_literal_param("getaddrinfo(EAI_MEMORY)"));
187 WATCHPOINT_STRING(server
->hostname
);
188 WATCHPOINT_STRING(gai_strerror(e
));
189 return memcached_set_error_string(*server
, MEMCACHED_HOST_LOOKUP_FAILURE
, gai_strerror(errcode
), strlen(gai_strerror(errcode
)));
194 server
->address_info_next
= server
->address_info
;
196 return MEMCACHED_SUCCESS
;
199 static inline memcached_return_t
set_socket_nonblocking(memcached_server_st
*ptr
)
203 if (ioctlsocket(ptr
->fd
, FIONBIO
, &arg
) == SOCKET_ERROR
)
205 return memcached_set_errno(*ptr
, get_socket_errno(), NULL
);
212 flags
= fcntl(ptr
->fd
, F_GETFL
, 0);
214 while (flags
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
216 unlikely (flags
== -1)
218 return memcached_set_errno(*ptr
, errno
, NULL
);
220 else if ((flags
& O_NONBLOCK
) == 0)
226 rval
= fcntl(ptr
->fd
, F_SETFL
, flags
| O_NONBLOCK
);
228 while (rval
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
230 unlikely (rval
== -1)
232 return memcached_set_errno(*ptr
, errno
, NULL
);
236 return MEMCACHED_SUCCESS
;
239 static memcached_return_t
set_socket_options(memcached_server_st
*ptr
)
241 WATCHPOINT_ASSERT(ptr
->fd
!= -1);
243 if (ptr
->type
== MEMCACHED_CONNECTION_UDP
)
244 return MEMCACHED_SUCCESS
;
247 if (ptr
->root
->snd_timeout
)
250 struct timeval waittime
;
253 waittime
.tv_usec
= ptr
->root
->snd_timeout
;
255 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_SNDTIMEO
,
256 &waittime
, (socklen_t
)sizeof(struct timeval
));
257 WATCHPOINT_ASSERT(error
== 0);
259 return MEMCACHED_FAILURE
;
264 if (ptr
->root
->rcv_timeout
)
267 struct timeval waittime
;
270 waittime
.tv_usec
= ptr
->root
->rcv_timeout
;
272 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_RCVTIMEO
,
273 &waittime
, (socklen_t
)sizeof(struct timeval
));
274 WATCHPOINT_ASSERT(error
== 0);
276 return MEMCACHED_FAILURE
;
281 #if defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
284 int error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (void *)&set
, sizeof(int));
286 // This is not considered a fatal error
289 WATCHPOINT_ERRNO(get_socket_errno());
290 perror("setsockopt(SO_NOSIGPIPE)");
295 if (ptr
->root
->flags
.no_block
)
298 struct linger linger
;
301 linger
.l_linger
= 0; /* By default on close() just drop the socket */
302 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_LINGER
,
303 &linger
, (socklen_t
)sizeof(struct linger
));
304 WATCHPOINT_ASSERT(error
== 0);
306 return MEMCACHED_FAILURE
;
309 if (ptr
->root
->flags
.tcp_nodelay
)
314 error
= setsockopt(ptr
->fd
, IPPROTO_TCP
, TCP_NODELAY
,
315 &flag
, (socklen_t
)sizeof(int));
316 WATCHPOINT_ASSERT(error
== 0);
318 return MEMCACHED_FAILURE
;
321 if (ptr
->root
->flags
.tcp_keepalive
)
326 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_KEEPALIVE
,
327 &flag
, (socklen_t
)sizeof(int));
328 WATCHPOINT_ASSERT(error
== 0);
330 return MEMCACHED_FAILURE
;
334 if (ptr
->root
->tcp_keepidle
> 0)
338 error
= setsockopt(ptr
->fd
, IPPROTO_TCP
, TCP_KEEPIDLE
,
339 &ptr
->root
->tcp_keepidle
, (socklen_t
)sizeof(int));
340 WATCHPOINT_ASSERT(error
== 0);
342 return MEMCACHED_FAILURE
;
346 if (ptr
->root
->send_size
> 0)
350 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_SNDBUF
,
351 &ptr
->root
->send_size
, (socklen_t
)sizeof(int));
352 WATCHPOINT_ASSERT(error
== 0);
354 return MEMCACHED_FAILURE
;
357 if (ptr
->root
->recv_size
> 0)
361 error
= setsockopt(ptr
->fd
, SOL_SOCKET
, SO_RCVBUF
,
362 &ptr
->root
->recv_size
, (socklen_t
)sizeof(int));
363 WATCHPOINT_ASSERT(error
== 0);
365 return MEMCACHED_FAILURE
;
369 /* libmemcached will always use nonblocking IO to avoid write deadlocks */
370 return set_socket_nonblocking(ptr
);
373 static memcached_return_t
unix_socket_connect(memcached_server_st
*ptr
)
376 WATCHPOINT_ASSERT(ptr
->fd
== -1);
378 if ((ptr
->fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) < 0)
380 ptr
->cached_errno
= errno
;
381 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE
;
384 struct sockaddr_un servAddr
;
386 memset(&servAddr
, 0, sizeof (struct sockaddr_un
));
387 servAddr
.sun_family
= AF_UNIX
;
388 strncpy(servAddr
.sun_path
, ptr
->hostname
, sizeof(servAddr
.sun_path
)); /* Copy filename */
392 (struct sockaddr
*)&servAddr
,
393 sizeof(servAddr
)) < 0)
401 case EISCONN
: /* We were spinning waiting on connect */
404 WATCHPOINT_ERRNO(errno
);
405 ptr
->cached_errno
= errno
;
406 return MEMCACHED_ERRNO
;
410 WATCHPOINT_ASSERT(ptr
->fd
!= -1);
412 return MEMCACHED_SUCCESS
;
415 return MEMCACHED_NOT_SUPPORTED
;
419 static memcached_return_t
network_connect(memcached_server_st
*ptr
)
421 bool timeout_error_occured
= false;
423 WATCHPOINT_ASSERT(ptr
->fd
== INVALID_SOCKET
);
424 WATCHPOINT_ASSERT(ptr
->cursor_active
== 0);
426 if (! ptr
->address_info
)
428 memcached_return_t rc
= set_hostinfo(ptr
);
429 if (rc
!= MEMCACHED_SUCCESS
)
433 /* Create the socket */
434 while (ptr
->address_info_next
&& ptr
->fd
== INVALID_SOCKET
)
436 /* Memcache server does not support IPV6 in udp mode, so skip if not ipv4 */
437 if (ptr
->type
== MEMCACHED_CONNECTION_UDP
&& ptr
->address_info_next
->ai_family
!= AF_INET
)
439 ptr
->address_info_next
= ptr
->address_info_next
->ai_next
;
443 if ((ptr
->fd
= socket(ptr
->address_info_next
->ai_family
,
444 ptr
->address_info_next
->ai_socktype
,
445 ptr
->address_info_next
->ai_protocol
)) < 0)
447 ptr
->cached_errno
= get_socket_errno();
448 WATCHPOINT_ERRNO(get_socket_errno());
449 return MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE
;
452 (void)set_socket_options(ptr
);
454 /* connect to server */
455 if ((connect(ptr
->fd
, ptr
->address_info_next
->ai_addr
, ptr
->address_info_next
->ai_addrlen
) != SOCKET_ERROR
))
460 /* An error occurred */
461 ptr
->cached_errno
= get_socket_errno();
462 switch (ptr
->cached_errno
)
465 case EINPROGRESS
: // nonblocking mode - first return
466 case EALREADY
: // nonblocking mode - subsequent returns
468 memcached_return_t rc
;
469 rc
= connect_poll(ptr
);
471 if (rc
== MEMCACHED_TIMEOUT
)
472 timeout_error_occured
= true;
474 if (rc
== MEMCACHED_SUCCESS
)
478 case EISCONN
: // we are connected :-)
481 case EINTR
: // Special case, we retry ai_addr
482 (void)closesocket(ptr
->fd
);
483 ptr
->fd
= INVALID_SOCKET
;
487 (void)closesocket(ptr
->fd
);
488 ptr
->fd
= INVALID_SOCKET
;
489 ptr
->address_info_next
= ptr
->address_info_next
->ai_next
;
494 if (ptr
->fd
== INVALID_SOCKET
)
496 WATCHPOINT_STRING("Never got a good file descriptor");
498 /* Failed to connect. schedule next retry */
499 if (ptr
->root
->retry_timeout
)
501 struct timeval next_time
;
503 if (gettimeofday(&next_time
, NULL
) == 0)
504 ptr
->next_retry
= next_time
.tv_sec
+ ptr
->root
->retry_timeout
;
507 if (timeout_error_occured
)
508 return MEMCACHED_TIMEOUT
;
510 return MEMCACHED_ERRNO
; /* The last error should be from connect() */
513 return MEMCACHED_SUCCESS
; /* The last error should be from connect() */
516 void set_last_disconnected_host(memcached_server_write_instance_st ptr
)
519 memcached_st
*root
= (memcached_st
*)ptr
->root
;
522 WATCHPOINT_STRING(ptr
->hostname
);
523 WATCHPOINT_NUMBER(ptr
->port
);
524 WATCHPOINT_ERRNO(ptr
->cached_errno
);
526 if (root
->last_disconnected_server
)
527 memcached_server_free(root
->last_disconnected_server
);
528 root
->last_disconnected_server
= memcached_server_clone(NULL
, ptr
);
531 memcached_return_t
memcached_connect(memcached_server_write_instance_st ptr
)
533 memcached_return_t rc
= MEMCACHED_NO_SERVERS
;
535 if (ptr
->fd
!= INVALID_SOCKET
)
536 return MEMCACHED_SUCCESS
;
538 LIBMEMCACHED_MEMCACHED_CONNECT_START();
540 /* both retry_timeout and server_failure_limit must be set in order to delay retrying a server on error. */
541 WATCHPOINT_ASSERT(ptr
->root
);
542 if (ptr
->root
->retry_timeout
&& ptr
->next_retry
)
544 struct timeval curr_time
;
546 gettimeofday(&curr_time
, NULL
);
548 // We should optimize this to remove the allocation if the server was
549 // the last server to die
550 if (ptr
->next_retry
> curr_time
.tv_sec
)
552 set_last_disconnected_host(ptr
);
554 return MEMCACHED_SERVER_MARKED_DEAD
;
558 // If we are over the counter failure, we just fail. Reject host only
559 // works if you have a set number of failures.
560 if (ptr
->root
->server_failure_limit
&& ptr
->server_failure_counter
>= ptr
->root
->server_failure_limit
)
562 set_last_disconnected_host(ptr
);
564 // @todo fix this by fixing behavior to no longer make use of
566 if (_is_auto_eject_host(ptr
->root
))
568 run_distribution((memcached_st
*)ptr
->root
);
571 return MEMCACHED_SERVER_MARKED_DEAD
;
574 /* We need to clean up the multi startup piece */
577 case MEMCACHED_CONNECTION_UNKNOWN
:
578 WATCHPOINT_ASSERT(0);
579 rc
= MEMCACHED_NOT_SUPPORTED
;
581 case MEMCACHED_CONNECTION_UDP
:
582 case MEMCACHED_CONNECTION_TCP
:
583 rc
= network_connect(ptr
);
584 #ifdef LIBMEMCACHED_WITH_SASL_SUPPORT
585 if (ptr
->fd
!= INVALID_SOCKET
&& ptr
->root
->sasl
.callbacks
)
587 rc
= memcached_sasl_authenticate_connection(ptr
);
588 if (rc
!= MEMCACHED_SUCCESS
)
590 (void)closesocket(ptr
->fd
);
591 ptr
->fd
= INVALID_SOCKET
;
596 case MEMCACHED_CONNECTION_UNIX_SOCKET
:
597 rc
= unix_socket_connect(ptr
);
599 case MEMCACHED_CONNECTION_MAX
:
601 WATCHPOINT_ASSERT(0);
604 if (rc
== MEMCACHED_SUCCESS
)
606 ptr
->server_failure_counter
= 0;
611 ptr
->server_failure_counter
++;
613 set_last_disconnected_host(ptr
);
616 LIBMEMCACHED_MEMCACHED_CONNECT_END();