1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 * Copyright (C) 2006-2009 Brian Aker
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are
13 * * Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above
17 * copyright notice, this list of conditions and the following disclaimer
18 * in the documentation and/or other materials provided with the
21 * * The names of its contributors may not be used to endorse or
22 * promote products derived from this software without specific prior
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 #include <libmemcached/common.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
46 void initialize_binary_request(org::libmemcached::Instance
* server
, protocol_binary_request_header
& header
)
49 header
.request
.magic
= PROTOCOL_BINARY_REQ
;
50 header
.request
.opaque
= htons(server
->request_id
);
53 enum memc_read_or_write
{
59 * Try to fill the input buffer for a server with as much
62 * @param ptr the server to pack
64 static bool repack_input_buffer(org::libmemcached::Instance
* ptr
)
66 if (ptr
->read_ptr
!= ptr
->read_buffer
)
68 /* Move all of the data to the beginning of the buffer so
69 ** that we can fit more data into the buffer...
71 memmove(ptr
->read_buffer
, ptr
->read_ptr
, ptr
->read_buffer_length
);
72 ptr
->read_ptr
= ptr
->read_buffer
;
73 ptr
->read_data_length
= ptr
->read_buffer_length
;
76 /* There is room in the buffer, try to fill it! */
77 if (ptr
->read_buffer_length
!= MEMCACHED_MAX_BUFFER
)
80 /* Just try a single read to grab what's available */
82 if ((nr
= ::recv(ptr
->fd
,
83 ptr
->read_ptr
+ ptr
->read_data_length
,
84 MEMCACHED_MAX_BUFFER
- ptr
->read_data_length
,
89 memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
);
93 switch (get_socket_errno())
98 #if EWOULDBLOCK != EAGAIN
102 #ifdef TARGET_OS_LINUX
105 break; // No IO is fine, we can just move on
108 memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
114 else // We read data, append to our read buffer
116 ptr
->read_data_length
+= size_t(nr
);
117 ptr
->read_buffer_length
+= size_t(nr
);
128 * If the we have callbacks connected to this server structure
129 * we may start process the input queue and fire the callbacks
130 * for the incomming messages. This function is _only_ called
131 * when the input buffer is full, so that we _know_ that we have
132 * at least _one_ message to process.
134 * @param ptr the server to star processing iput messages for
135 * @return true if we processed anything, false otherwise
137 static bool process_input_buffer(org::libmemcached::Instance
* ptr
)
140 ** We might be able to process some of the response messages if we
141 ** have a callback set up
143 if (ptr
->root
->callbacks
!= NULL
)
146 * We might have responses... try to read them out and fire
149 memcached_callback_st cb
= *ptr
->root
->callbacks
;
151 memcached_set_processing_input((memcached_st
*)ptr
->root
, true);
153 char buffer
[MEMCACHED_DEFAULT_COMMAND_SIZE
];
154 memcached_st
*root
= (memcached_st
*)ptr
->root
;
155 memcached_return_t error
= memcached_response(ptr
, buffer
, sizeof(buffer
), &root
->result
);
157 memcached_set_processing_input(root
, false);
159 if (error
== MEMCACHED_SUCCESS
)
161 for (unsigned int x
= 0; x
< cb
.number_of_callback
; x
++)
163 error
= (*cb
.callback
[x
])(ptr
->root
, &root
->result
, cb
.context
);
164 if (error
!= MEMCACHED_SUCCESS
)
170 /* @todo what should I do with the error message??? */
172 /* @todo what should I do with other error messages?? */
179 static memcached_return_t
io_wait(org::libmemcached::Instance
* ptr
,
180 const memc_read_or_write read_or_write
)
183 ** We are going to block on write, but at least on Solaris we might block
184 ** on write if we haven't read anything from our input buffer..
185 ** Try to purge the input buffer if we don't do any flow control in the
186 ** application layer (just sending a lot of data etc)
187 ** The test is moved down in the purge function to avoid duplication of
190 if (read_or_write
== MEM_WRITE
)
192 if (memcached_purge(ptr
) == false)
194 return MEMCACHED_FAILURE
;
203 if (read_or_write
== MEM_WRITE
) /* write */
206 ptr
->io_wait_count
.write
++;
210 ptr
->io_wait_count
.read
++;
213 if (ptr
->root
->poll_timeout
== 0) // Mimic 0 causes timeout behavior (not all platforms do this)
215 ptr
->io_wait_count
.timeouts
++;
216 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
220 while (--loop_max
) // While loop is for ERESTART or EINTR
222 int active_fd
= poll(&fds
, 1, ptr
->root
->poll_timeout
);
226 assert_msg(active_fd
== 1 , "poll() returned an unexpected number of active file descriptors");
227 if (fds
.revents
& POLLIN
or fds
.revents
& POLLOUT
)
229 return MEMCACHED_SUCCESS
;
232 if (fds
.revents
& POLLHUP
)
234 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
235 memcached_literal_param("poll() detected hang up"));
238 if (fds
.revents
& POLLERR
)
240 int local_errno
= EINVAL
;
242 socklen_t len
= sizeof (err
);
243 if (getsockopt(ptr
->fd
, SOL_SOCKET
, SO_ERROR
, (char*)&err
, &len
) == 0)
245 if (err
== 0) // treat this as EINTR
251 memcached_quit_server(ptr
, true);
252 return memcached_set_errno(*ptr
, local_errno
, MEMCACHED_AT
,
253 memcached_literal_param("poll() returned POLLHUP"));
256 return memcached_set_error(*ptr
, MEMCACHED_FAILURE
, MEMCACHED_AT
, memcached_literal_param("poll() returned a value that was not dealt with"));
261 ptr
->io_wait_count
.timeouts
++;
262 return memcached_set_error(*ptr
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
);
265 // Only an error should result in this code being called.
266 int local_errno
= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
267 assert_msg(active_fd
== -1 , "poll() returned an unexpected value");
270 #ifdef TARGET_OS_LINUX
278 memcached_set_error(*ptr
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
);
281 memcached_set_error(*ptr
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
, memcached_literal_param("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid"));
284 memcached_set_errno(*ptr
, local_errno
, MEMCACHED_AT
, memcached_literal_param("poll"));
290 memcached_quit_server(ptr
, true);
292 if (memcached_has_error(ptr
))
294 return memcached_instance_error_return(ptr
);
297 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
298 memcached_literal_param("number of attempts to call io_wait() failed"));
301 static bool io_flush(org::libmemcached::Instance
* ptr
,
302 const bool with_flush
,
303 memcached_return_t
& error
)
306 ** We might want to purge the input buffer if we haven't consumed
307 ** any output yet... The test for the limits is the purge is inline
308 ** in the purge function to avoid duplicating the logic..
311 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
313 if (memcached_purge(ptr
) == false)
318 char *local_write_ptr
= ptr
->write_buffer
;
319 size_t write_length
= ptr
->write_buffer_offset
;
321 error
= MEMCACHED_SUCCESS
;
323 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
325 /* Looking for memory overflows */
327 if (write_length
== MEMCACHED_MAX_BUFFER
)
328 WATCHPOINT_ASSERT(ptr
->write_buffer
== local_write_ptr
);
329 WATCHPOINT_ASSERT((ptr
->write_buffer
+ MEMCACHED_MAX_BUFFER
) >= (local_write_ptr
+ write_length
));
334 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
335 WATCHPOINT_ASSERT(write_length
> 0);
344 flags
= MSG_NOSIGNAL
|MSG_MORE
;
347 ssize_t sent_length
= ::send(ptr
->fd
, local_write_ptr
, write_length
, flags
);
349 if (sent_length
== SOCKET_ERROR
)
351 #if 0 // @todo I should look at why we hit this bit of code hard frequently
352 WATCHPOINT_ERRNO(get_socket_errno());
353 WATCHPOINT_NUMBER(get_socket_errno());
355 switch (get_socket_errno())
360 #if EWOULDBLOCK != EAGAIN
366 * We may be blocked on write because the input buffer
367 * is full. Let's check if we have room in our input
368 * buffer for more data and retry the write before
371 if (repack_input_buffer(ptr
) or process_input_buffer(ptr
))
376 memcached_return_t rc
= io_wait(ptr
, MEM_WRITE
);
377 if (memcached_success(rc
))
381 else if (rc
== MEMCACHED_TIMEOUT
)
386 memcached_quit_server(ptr
, true);
387 error
= memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
393 memcached_quit_server(ptr
, true);
394 error
= memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
395 WATCHPOINT_ASSERT(ptr
->fd
== INVALID_SOCKET
);
400 ptr
->io_bytes_sent
+= uint32_t(sent_length
);
402 local_write_ptr
+= sent_length
;
403 write_length
-= uint32_t(sent_length
);
406 WATCHPOINT_ASSERT(write_length
== 0);
407 ptr
->write_buffer_offset
= 0;
412 memcached_return_t
memcached_io_wait_for_write(org::libmemcached::Instance
* ptr
)
414 return io_wait(ptr
, MEM_WRITE
);
417 static memcached_return_t
_io_fill(org::libmemcached::Instance
* ptr
)
422 data_read
= ::recv(ptr
->fd
, ptr
->read_buffer
, MEMCACHED_MAX_BUFFER
, MSG_NOSIGNAL
);
423 if (data_read
== SOCKET_ERROR
)
425 switch (get_socket_errno())
427 case EINTR
: // We just retry
430 case ETIMEDOUT
: // OSX
431 #if EWOULDBLOCK != EAGAIN
435 #ifdef TARGET_OS_LINUX
439 memcached_return_t io_wait_ret
;
440 if (memcached_success(io_wait_ret
= io_wait(ptr
, MEM_READ
)))
450 case ENOTCONN
: // Programmer Error
451 WATCHPOINT_ASSERT(0);
453 WATCHPOINT_ASSERT(0);
455 assert_msg(ptr
->fd
!= INVALID_SOCKET
, "Programmer error, invalid socket");
460 memcached_quit_server(ptr
, true);
461 memcached_set_errno(*ptr
, get_socket_errno(), MEMCACHED_AT
);
465 return memcached_instance_error_return(ptr
);
467 else if (data_read
== 0)
470 EOF. Any data received so far is incomplete
471 so discard it. This always reads by byte in case of TCP
472 and protocol enforcement happens at memcached_response()
473 looking for '\n'. We do not care for UDB which requests 8 bytes
474 at once. Generally, this means that connection went away. Since
475 for blocking I/O we do not return 0 and for non-blocking case
476 it will return EGAIN if data is not immediatly available.
478 memcached_quit_server(ptr
, true);
479 return memcached_set_error(*ptr
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
480 memcached_literal_param("::rec() returned zero, server has disconnected"));
482 ptr
->io_wait_count
._bytes_read
+= data_read
;
483 } while (data_read
<= 0);
485 ptr
->io_bytes_sent
= 0;
486 ptr
->read_data_length
= (size_t) data_read
;
487 ptr
->read_buffer_length
= (size_t) data_read
;
488 ptr
->read_ptr
= ptr
->read_buffer
;
490 return MEMCACHED_SUCCESS
;
493 memcached_return_t
memcached_io_read(org::libmemcached::Instance
* ptr
,
494 void *buffer
, size_t length
, ssize_t
& nread
)
496 assert(memcached_is_udp(ptr
->root
) == false);
497 assert_msg(ptr
, "Programmer error, memcached_io_read() recieved an invalid Instance"); // Programmer error
498 char *buffer_ptr
= static_cast<char *>(buffer
);
500 if (ptr
->fd
== INVALID_SOCKET
)
503 assert_msg(int(ptr
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Programmer error, invalid socket state");
505 return MEMCACHED_CONNECTION_FAILURE
;
510 if (ptr
->read_buffer_length
== 0)
512 memcached_return_t io_fill_ret
;
513 if (memcached_fatal(io_fill_ret
= _io_fill(ptr
)))
522 size_t difference
= (length
> ptr
->read_buffer_length
) ? ptr
->read_buffer_length
: length
;
524 memcpy(buffer_ptr
, ptr
->read_ptr
, difference
);
525 length
-= difference
;
526 ptr
->read_ptr
+= difference
;
527 ptr
->read_buffer_length
-= difference
;
528 buffer_ptr
+= difference
;
532 *buffer_ptr
= *ptr
->read_ptr
;
534 ptr
->read_buffer_length
--;
540 nread
= ssize_t(buffer_ptr
- (char*)buffer
);
542 return MEMCACHED_SUCCESS
;
545 memcached_return_t
memcached_io_slurp(org::libmemcached::Instance
* ptr
)
547 assert_msg(ptr
, "Programmer error, invalid Instance");
548 assert(memcached_is_udp(ptr
->root
) == false);
550 if (ptr
->fd
== INVALID_SOCKET
)
552 assert_msg(int(ptr
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Invalid socket state");
553 return MEMCACHED_CONNECTION_FAILURE
;
557 char buffer
[MEMCACHED_MAX_BUFFER
];
560 data_read
= ::recv(ptr
->fd
, ptr
->read_buffer
, sizeof(buffer
), MSG_NOSIGNAL
);
561 if (data_read
== SOCKET_ERROR
)
563 switch (get_socket_errno())
565 case EINTR
: // We just retry
568 case ETIMEDOUT
: // OSX
569 #if EWOULDBLOCK != EAGAIN
573 #ifdef TARGET_OS_LINUX
576 if (memcached_success(io_wait(ptr
, MEM_READ
)))
580 return MEMCACHED_IN_PROGRESS
;
584 case ENOTCONN
: // Programmer Error
589 assert_msg(ptr
->fd
!= INVALID_SOCKET
, "Invalid socket state");
594 return MEMCACHED_CONNECTION_FAILURE
; // We want this!
597 } while (data_read
> 0);
599 return MEMCACHED_CONNECTION_FAILURE
;
602 static bool _io_write(org::libmemcached::Instance
* ptr
,
603 const void *buffer
, size_t length
, bool with_flush
,
606 assert(ptr
->fd
!= INVALID_SOCKET
);
607 assert(memcached_is_udp(ptr
->root
) == false);
609 const char *buffer_ptr
= static_cast<const char *>(buffer
);
611 const size_t original_length
= length
;
616 size_t buffer_end
= MEMCACHED_MAX_BUFFER
;
617 size_t should_write
= buffer_end
-ptr
->write_buffer_offset
;
618 should_write
= (should_write
< length
) ? should_write
: length
;
620 write_ptr
= ptr
->write_buffer
+ ptr
->write_buffer_offset
;
621 memcpy(write_ptr
, buffer_ptr
, should_write
);
622 ptr
->write_buffer_offset
+= should_write
;
623 buffer_ptr
+= should_write
;
624 length
-= should_write
;
626 if (ptr
->write_buffer_offset
== buffer_end
)
628 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
630 memcached_return_t rc
;
631 if (io_flush(ptr
, with_flush
, rc
) == false)
633 written
= original_length
-length
;
641 memcached_return_t rc
;
642 WATCHPOINT_ASSERT(ptr
->fd
!= INVALID_SOCKET
);
643 if (io_flush(ptr
, with_flush
, rc
) == false)
645 written
= original_length
-length
;
650 written
= original_length
-length
;
655 bool memcached_io_write(org::libmemcached::Instance
* ptr
)
658 return _io_write(ptr
, NULL
, 0, true, written
);
661 ssize_t
memcached_io_write(org::libmemcached::Instance
* ptr
,
662 const void *buffer
, const size_t length
, const bool with_flush
)
666 if (_io_write(ptr
, buffer
, length
, with_flush
, written
) == false)
671 return ssize_t(written
);
674 bool memcached_io_writev(org::libmemcached::Instance
* ptr
,
675 libmemcached_io_vector_st vector
[],
676 const size_t number_of
, const bool with_flush
)
678 ssize_t complete_total
= 0;
681 for (size_t x
= 0; x
< number_of
; x
++, vector
++)
683 complete_total
+= vector
->length
;
687 if ((_io_write(ptr
, vector
->buffer
, vector
->length
, false, written
)) == false)
697 if (memcached_io_write(ptr
) == false)
703 return (complete_total
== total
);
707 void memcached_io_close(org::libmemcached::Instance
* ptr
)
709 if (ptr
->fd
== INVALID_SOCKET
)
714 /* in case of death shutdown to avoid blocking at close() */
715 if (shutdown(ptr
->fd
, SHUT_RDWR
) == SOCKET_ERROR
and get_socket_errno() != ENOTCONN
)
717 WATCHPOINT_NUMBER(ptr
->fd
);
718 WATCHPOINT_ERRNO(get_socket_errno());
719 WATCHPOINT_ASSERT(get_socket_errno());
722 if (closesocket(ptr
->fd
) == SOCKET_ERROR
)
724 WATCHPOINT_ERRNO(get_socket_errno());
726 ptr
->state
= MEMCACHED_SERVER_STATE_NEW
;
727 ptr
->fd
= INVALID_SOCKET
;
730 org::libmemcached::Instance
* memcached_io_get_readable_server(memcached_st
*memc
)
732 #define MAX_SERVERS_TO_POLL 100
733 struct pollfd fds
[MAX_SERVERS_TO_POLL
];
734 nfds_t host_index
= 0;
736 for (uint32_t x
= 0; x
< memcached_server_count(memc
) and host_index
< MAX_SERVERS_TO_POLL
; ++x
)
738 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, x
);
740 if (instance
->read_buffer_length
> 0) /* I have data in the buffer */
745 if (instance
->response_count() > 0)
747 fds
[host_index
].events
= POLLIN
;
748 fds
[host_index
].revents
= 0;
749 fds
[host_index
].fd
= instance
->fd
;
756 /* We have 0 or 1 server with pending events.. */
757 for (uint32_t x
= 0; x
< memcached_server_count(memc
); ++x
)
759 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, x
);
761 if (instance
->response_count() > 0)
770 int error
= poll(fds
, host_index
, memc
->poll_timeout
);
774 memcached_set_errno(*memc
, get_socket_errno(), MEMCACHED_AT
);
780 for (nfds_t x
= 0; x
< host_index
; ++x
)
782 if (fds
[x
].revents
& POLLIN
)
784 for (uint32_t y
= 0; y
< memcached_server_count(memc
); ++y
)
786 org::libmemcached::Instance
* instance
= memcached_instance_fetch(memc
, y
);
788 if (instance
->fd
== fds
[x
].fd
)
801 Eventually we will just kill off the server with the problem.
803 void memcached_io_reset(org::libmemcached::Instance
* ptr
)
805 memcached_quit_server(ptr
, true);
809 * Read a given number of bytes from the server and place it into a specific
810 * buffer. Reset the IO channel on this server if an error occurs.
812 memcached_return_t
memcached_safe_read(org::libmemcached::Instance
* ptr
,
817 char *data
= static_cast<char *>(dta
);
819 while (offset
< size
)
822 memcached_return_t rc
;
824 while (memcached_continue(rc
= memcached_io_read(ptr
, data
+ offset
, size
- offset
, nread
))) { };
826 if (memcached_failed(rc
))
831 offset
+= size_t(nread
);
834 return MEMCACHED_SUCCESS
;
837 memcached_return_t
memcached_io_readline(org::libmemcached::Instance
* ptr
,
843 bool line_complete
= false;
845 while (line_complete
== false)
847 if (ptr
->read_buffer_length
== 0)
850 * We don't have any data in the buffer, so let's fill the read
851 * buffer. Call the standard read function to avoid duplicating
855 memcached_return_t rc
= memcached_io_read(ptr
, buffer_ptr
, 1, nread
);
856 if (memcached_failed(rc
) and rc
== MEMCACHED_IN_PROGRESS
)
858 memcached_quit_server(ptr
, true);
859 return memcached_set_error(*ptr
, rc
, MEMCACHED_AT
);
861 else if (memcached_failed(rc
))
866 if (*buffer_ptr
== '\n')
875 /* Now let's look in the buffer and copy as we go! */
876 while (ptr
->read_buffer_length
and total_nr
< size
and line_complete
== false)
878 *buffer_ptr
= *ptr
->read_ptr
;
879 if (*buffer_ptr
== '\n')
881 line_complete
= true;
883 --ptr
->read_buffer_length
;
889 if (total_nr
== size
)
891 return MEMCACHED_PROTOCOL_ERROR
;
895 return MEMCACHED_SUCCESS
;