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(memcached_instance_st
* 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 instance the server to pack
64 static bool repack_input_buffer(memcached_instance_st
* instance
)
66 if (instance
->read_ptr
!= instance
->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(instance
->read_buffer
, instance
->read_ptr
, instance
->read_buffer_length
);
72 instance
->read_ptr
= instance
->read_buffer
;
73 instance
->read_data_length
= instance
->read_buffer_length
;
76 /* There is room in the buffer, try to fill it! */
77 if (instance
->read_buffer_length
!= MEMCACHED_MAX_BUFFER
)
80 /* Just try a single read to grab what's available */
82 if ((nr
= ::recv(instance
->fd
,
83 instance
->read_ptr
+ instance
->read_data_length
,
84 MEMCACHED_MAX_BUFFER
- instance
->read_data_length
,
89 memcached_set_error(*instance
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
);
93 switch (get_socket_errno())
98 #if EWOULDBLOCK != EAGAIN
105 break; // No IO is fine, we can just move on
108 memcached_set_errno(*instance
, get_socket_errno(), MEMCACHED_AT
);
114 else // We read data, append to our read buffer
116 instance
->read_data_length
+= size_t(nr
);
117 instance
->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 instance the server to star processing iput messages for
135 * @return true if we processed anything, false otherwise
137 static bool process_input_buffer(memcached_instance_st
* instance
)
140 ** We might be able to process some of the response messages if we
141 ** have a callback set up
143 if (instance
->root
->callbacks
!= NULL
)
146 * We might have responses... try to read them out and fire
149 memcached_callback_st cb
= *instance
->root
->callbacks
;
151 memcached_set_processing_input((Memcached
*)instance
->root
, true);
153 char buffer
[MEMCACHED_DEFAULT_COMMAND_SIZE
];
154 Memcached
*root
= (Memcached
*)instance
->root
;
155 memcached_return_t error
= memcached_response(instance
, 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
])(instance
->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(memcached_instance_st
* instance
,
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(instance
) == false)
194 return MEMCACHED_FAILURE
;
199 fds
.fd
= instance
->fd
;
203 if (read_or_write
== MEM_WRITE
) /* write */
206 instance
->io_wait_count
.write
++;
210 instance
->io_wait_count
.read
++;
213 if (instance
->root
->poll_timeout
== 0) // Mimic 0 causes timeout behavior (not all platforms do this)
215 return memcached_set_error(*instance
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
, memcached_literal_param("poll_timeout() was set to zero"));
219 while (--loop_max
) // While loop is for ERESTART or EINTR
221 int active_fd
= poll(&fds
, 1, instance
->root
->poll_timeout
);
225 assert_msg(active_fd
== 1 , "poll() returned an unexpected number of active file descriptors");
226 if (fds
.revents
& POLLIN
or fds
.revents
& POLLOUT
)
228 return MEMCACHED_SUCCESS
;
231 if (fds
.revents
& POLLHUP
)
233 return memcached_set_error(*instance
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
234 memcached_literal_param("poll() detected hang up"));
237 if (fds
.revents
& POLLERR
)
239 int local_errno
= EINVAL
;
241 socklen_t len
= sizeof (err
);
242 if (getsockopt(instance
->fd
, SOL_SOCKET
, SO_ERROR
, (char*)&err
, &len
) == 0)
244 if (err
== 0) // treat this as EINTR
250 memcached_quit_server(instance
, true);
251 return memcached_set_errno(*instance
, local_errno
, MEMCACHED_AT
,
252 memcached_literal_param("poll() returned POLLHUP"));
255 return memcached_set_error(*instance
, MEMCACHED_FAILURE
, MEMCACHED_AT
, memcached_literal_param("poll() returned a value that was not dealt with"));
260 return memcached_set_error(*instance
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
, memcached_literal_param("No active_fd were found"));
263 // Only an error should result in this code being called.
264 int local_errno
= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
265 assert_msg(active_fd
== -1 , "poll() returned an unexpected value");
276 memcached_set_error(*instance
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
);
279 memcached_set_error(*instance
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
, memcached_literal_param("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid"));
282 memcached_set_errno(*instance
, local_errno
, MEMCACHED_AT
, memcached_literal_param("poll"));
288 memcached_quit_server(instance
, true);
290 if (memcached_has_error(instance
))
292 return memcached_instance_error_return(instance
);
295 return memcached_set_error(*instance
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
296 memcached_literal_param("number of attempts to call io_wait() failed"));
299 static bool io_flush(memcached_instance_st
* instance
,
300 const bool with_flush
,
301 memcached_return_t
& error
)
304 ** We might want to purge the input buffer if we haven't consumed
305 ** any output yet... The test for the limits is the purge is inline
306 ** in the purge function to avoid duplicating the logic..
309 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
311 if (memcached_purge(instance
) == false)
316 char *local_write_ptr
= instance
->write_buffer
;
317 size_t write_length
= instance
->write_buffer_offset
;
319 error
= MEMCACHED_SUCCESS
;
321 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
323 /* Looking for memory overflows */
325 if (write_length
== MEMCACHED_MAX_BUFFER
)
326 WATCHPOINT_ASSERT(instance
->write_buffer
== local_write_ptr
);
327 WATCHPOINT_ASSERT((instance
->write_buffer
+ MEMCACHED_MAX_BUFFER
) >= (local_write_ptr
+ write_length
));
332 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
333 WATCHPOINT_ASSERT(write_length
> 0);
342 flags
= MSG_NOSIGNAL
|MSG_MORE
;
345 ssize_t sent_length
= ::send(instance
->fd
, local_write_ptr
, write_length
, flags
);
347 if (sent_length
== SOCKET_ERROR
)
349 #if 0 // @todo I should look at why we hit this bit of code hard frequently
350 WATCHPOINT_ERRNO(get_socket_errno());
351 WATCHPOINT_NUMBER(get_socket_errno());
353 switch (get_socket_errno())
358 #if EWOULDBLOCK != EAGAIN
364 * We may be blocked on write because the input buffer
365 * is full. Let's check if we have room in our input
366 * buffer for more data and retry the write before
369 if (repack_input_buffer(instance
) or process_input_buffer(instance
))
374 memcached_return_t rc
= io_wait(instance
, MEM_WRITE
);
375 if (memcached_success(rc
))
379 else if (rc
== MEMCACHED_TIMEOUT
)
384 memcached_quit_server(instance
, true);
385 error
= memcached_set_errno(*instance
, get_socket_errno(), MEMCACHED_AT
);
391 memcached_quit_server(instance
, true);
392 error
= memcached_set_errno(*instance
, get_socket_errno(), MEMCACHED_AT
);
393 WATCHPOINT_ASSERT(instance
->fd
== INVALID_SOCKET
);
398 instance
->io_bytes_sent
+= uint32_t(sent_length
);
400 local_write_ptr
+= sent_length
;
401 write_length
-= uint32_t(sent_length
);
404 WATCHPOINT_ASSERT(write_length
== 0);
405 instance
->write_buffer_offset
= 0;
410 memcached_return_t
memcached_io_wait_for_write(memcached_instance_st
* instance
)
412 return io_wait(instance
, MEM_WRITE
);
415 memcached_return_t
memcached_io_wait_for_read(memcached_instance_st
* instance
)
417 return io_wait(instance
, MEM_READ
);
420 static memcached_return_t
_io_fill(memcached_instance_st
* instance
)
425 data_read
= ::recv(instance
->fd
, instance
->read_buffer
, MEMCACHED_MAX_BUFFER
, MSG_NOSIGNAL
);
426 if (data_read
== SOCKET_ERROR
)
428 switch (get_socket_errno())
430 case EINTR
: // We just retry
433 case ETIMEDOUT
: // OSX
434 #if EWOULDBLOCK != EAGAIN
442 memcached_return_t io_wait_ret
;
443 if (memcached_success(io_wait_ret
= io_wait(instance
, MEM_READ
)))
453 case ENOTCONN
: // Programmer Error
454 WATCHPOINT_ASSERT(0);
456 WATCHPOINT_ASSERT(0);
458 assert_msg(instance
->fd
!= INVALID_SOCKET
, "Programmer error, invalid socket");
463 memcached_quit_server(instance
, true);
464 memcached_set_errno(*instance
, get_socket_errno(), MEMCACHED_AT
);
468 return memcached_instance_error_return(instance
);
470 else if (data_read
== 0)
473 EOF. Any data received so far is incomplete
474 so discard it. This always reads by byte in case of TCP
475 and protocol enforcement happens at memcached_response()
476 looking for '\n'. We do not care for UDB which requests 8 bytes
477 at once. Generally, this means that connection went away. Since
478 for blocking I/O we do not return 0 and for non-blocking case
479 it will return EGAIN if data is not immediatly available.
481 memcached_quit_server(instance
, true);
482 return memcached_set_error(*instance
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
483 memcached_literal_param("::rec() returned zero, server has disconnected"));
485 instance
->io_wait_count
._bytes_read
+= data_read
;
486 } while (data_read
<= 0);
488 instance
->io_bytes_sent
= 0;
489 instance
->read_data_length
= (size_t) data_read
;
490 instance
->read_buffer_length
= (size_t) data_read
;
491 instance
->read_ptr
= instance
->read_buffer
;
493 return MEMCACHED_SUCCESS
;
496 memcached_return_t
memcached_io_read(memcached_instance_st
* instance
,
497 void *buffer
, size_t length
, ssize_t
& nread
)
499 assert(memcached_is_udp(instance
->root
) == false);
500 assert_msg(instance
, "Programmer error, memcached_io_read() recieved an invalid Instance"); // Programmer error
501 char *buffer_ptr
= static_cast<char *>(buffer
);
503 if (instance
->fd
== INVALID_SOCKET
)
506 assert_msg(int(instance
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Programmer error, invalid socket state");
508 return MEMCACHED_CONNECTION_FAILURE
;
513 if (instance
->read_buffer_length
== 0)
515 memcached_return_t io_fill_ret
;
516 if (memcached_fatal(io_fill_ret
= _io_fill(instance
)))
525 size_t difference
= (length
> instance
->read_buffer_length
) ? instance
->read_buffer_length
: length
;
527 memcpy(buffer_ptr
, instance
->read_ptr
, difference
);
528 length
-= difference
;
529 instance
->read_ptr
+= difference
;
530 instance
->read_buffer_length
-= difference
;
531 buffer_ptr
+= difference
;
535 *buffer_ptr
= *instance
->read_ptr
;
536 instance
->read_ptr
++;
537 instance
->read_buffer_length
--;
543 nread
= ssize_t(buffer_ptr
- (char*)buffer
);
545 return MEMCACHED_SUCCESS
;
548 memcached_return_t
memcached_io_slurp(memcached_instance_st
* instance
)
550 assert_msg(instance
, "Programmer error, invalid Instance");
551 assert(memcached_is_udp(instance
->root
) == false);
553 if (instance
->fd
== INVALID_SOCKET
)
555 assert_msg(int(instance
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Invalid socket state");
556 return MEMCACHED_CONNECTION_FAILURE
;
560 char buffer
[MEMCACHED_MAX_BUFFER
];
563 data_read
= ::recv(instance
->fd
, instance
->read_buffer
, sizeof(buffer
), MSG_NOSIGNAL
);
564 if (data_read
== SOCKET_ERROR
)
566 switch (get_socket_errno())
568 case EINTR
: // We just retry
571 case ETIMEDOUT
: // OSX
572 #if EWOULDBLOCK != EAGAIN
579 if (memcached_success(io_wait(instance
, MEM_READ
)))
583 return MEMCACHED_IN_PROGRESS
;
587 case ENOTCONN
: // Programmer Error
592 assert_msg(instance
->fd
!= INVALID_SOCKET
, "Invalid socket state");
597 return MEMCACHED_CONNECTION_FAILURE
; // We want this!
600 } while (data_read
> 0);
602 return MEMCACHED_CONNECTION_FAILURE
;
605 static bool _io_write(memcached_instance_st
* instance
,
606 const void *buffer
, size_t length
, bool with_flush
,
609 assert(instance
->fd
!= INVALID_SOCKET
);
610 assert(memcached_is_udp(instance
->root
) == false);
612 const char *buffer_ptr
= static_cast<const char *>(buffer
);
614 const size_t original_length
= length
;
619 size_t buffer_end
= MEMCACHED_MAX_BUFFER
;
620 size_t should_write
= buffer_end
-instance
->write_buffer_offset
;
621 should_write
= (should_write
< length
) ? should_write
: length
;
623 write_ptr
= instance
->write_buffer
+ instance
->write_buffer_offset
;
624 memcpy(write_ptr
, buffer_ptr
, should_write
);
625 instance
->write_buffer_offset
+= should_write
;
626 buffer_ptr
+= should_write
;
627 length
-= should_write
;
629 if (instance
->write_buffer_offset
== buffer_end
)
631 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
633 memcached_return_t rc
;
634 if (io_flush(instance
, with_flush
, rc
) == false)
636 written
= original_length
-length
;
644 memcached_return_t rc
;
645 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
646 if (io_flush(instance
, with_flush
, rc
) == false)
648 written
= original_length
-length
;
653 written
= original_length
-length
;
658 bool memcached_io_write(memcached_instance_st
* instance
)
661 return _io_write(instance
, NULL
, 0, true, written
);
664 ssize_t
memcached_io_write(memcached_instance_st
* instance
,
665 const void *buffer
, const size_t length
, const bool with_flush
)
669 if (_io_write(instance
, buffer
, length
, with_flush
, written
) == false)
674 return ssize_t(written
);
677 bool memcached_io_writev(memcached_instance_st
* instance
,
678 libmemcached_io_vector_st vector
[],
679 const size_t number_of
, const bool with_flush
)
681 ssize_t complete_total
= 0;
684 for (size_t x
= 0; x
< number_of
; x
++, vector
++)
686 complete_total
+= vector
->length
;
690 if ((_io_write(instance
, vector
->buffer
, vector
->length
, false, written
)) == false)
700 if (memcached_io_write(instance
) == false)
706 return (complete_total
== total
);
709 void memcached_instance_st::start_close_socket()
711 if (fd
!= INVALID_SOCKET
)
713 shutdown(fd
, SHUT_WR
);
714 options
.is_shutting_down
= true;
718 void memcached_instance_st::reset_socket()
720 if (fd
!= INVALID_SOCKET
)
722 (void)closesocket(fd
);
727 void memcached_instance_st::close_socket()
729 if (fd
!= INVALID_SOCKET
)
731 int shutdown_options
= SHUT_RD
;
732 if (options
.is_shutting_down
== false)
734 shutdown_options
= SHUT_RDWR
;
737 /* in case of death shutdown to avoid blocking at close() */
738 if (shutdown(fd
, shutdown_options
) == SOCKET_ERROR
and get_socket_errno() != ENOTCONN
)
740 WATCHPOINT_NUMBER(fd
);
741 WATCHPOINT_ERRNO(get_socket_errno());
742 WATCHPOINT_ASSERT(get_socket_errno());
746 state
= MEMCACHED_SERVER_STATE_NEW
;
749 state
= MEMCACHED_SERVER_STATE_NEW
;
752 write_buffer_offset
= size_t(root
and memcached_is_udp(root
) ? UDP_DATAGRAM_HEADER_LENGTH
: 0);
753 read_buffer_length
= 0;
754 read_ptr
= read_buffer
;
755 options
.is_shutting_down
= false;
756 memcached_server_response_reset(this);
758 // We reset the version so that if we end up talking to a different server
759 // we don't have stale server version information.
760 major_version
= minor_version
= micro_version
= UINT8_MAX
;
763 memcached_instance_st
* memcached_io_get_readable_server(Memcached
*memc
, memcached_return_t
&)
765 #define MAX_SERVERS_TO_POLL 100
766 struct pollfd fds
[MAX_SERVERS_TO_POLL
];
767 nfds_t host_index
= 0;
769 for (uint32_t x
= 0; x
< memcached_server_count(memc
) and host_index
< MAX_SERVERS_TO_POLL
; ++x
)
771 memcached_instance_st
* instance
= memcached_instance_fetch(memc
, x
);
773 if (instance
->read_buffer_length
> 0) /* I have data in the buffer */
778 if (instance
->response_count() > 0)
780 fds
[host_index
].events
= POLLIN
;
781 fds
[host_index
].revents
= 0;
782 fds
[host_index
].fd
= instance
->fd
;
789 /* We have 0 or 1 server with pending events.. */
790 for (uint32_t x
= 0; x
< memcached_server_count(memc
); ++x
)
792 memcached_instance_st
* instance
= memcached_instance_fetch(memc
, x
);
794 if (instance
->response_count() > 0)
803 int error
= poll(fds
, host_index
, memc
->poll_timeout
);
807 memcached_set_errno(*memc
, get_socket_errno(), MEMCACHED_AT
);
813 for (nfds_t x
= 0; x
< host_index
; ++x
)
815 if (fds
[x
].revents
& POLLIN
)
817 for (uint32_t y
= 0; y
< memcached_server_count(memc
); ++y
)
819 memcached_instance_st
* instance
= memcached_instance_fetch(memc
, y
);
821 if (instance
->fd
== fds
[x
].fd
)
834 Eventually we will just kill off the server with the problem.
836 void memcached_io_reset(memcached_instance_st
* instance
)
838 memcached_quit_server(instance
, true);
842 * Read a given number of bytes from the server and place it into a specific
843 * buffer. Reset the IO channel on this server if an error occurs.
845 memcached_return_t
memcached_safe_read(memcached_instance_st
* instance
,
850 char *data
= static_cast<char *>(dta
);
852 while (offset
< size
)
855 memcached_return_t rc
;
857 while (memcached_continue(rc
= memcached_io_read(instance
, data
+ offset
, size
- offset
, nread
))) { };
859 if (memcached_failed(rc
))
864 offset
+= size_t(nread
);
867 return MEMCACHED_SUCCESS
;
870 memcached_return_t
memcached_io_readline(memcached_instance_st
* instance
,
876 bool line_complete
= false;
878 while (line_complete
== false)
880 if (instance
->read_buffer_length
== 0)
883 * We don't have any data in the buffer, so let's fill the read
884 * buffer. Call the standard read function to avoid duplicating
888 memcached_return_t rc
= memcached_io_read(instance
, buffer_ptr
, 1, nread
);
889 if (memcached_failed(rc
) and rc
== MEMCACHED_IN_PROGRESS
)
891 memcached_quit_server(instance
, true);
892 return memcached_set_error(*instance
, rc
, MEMCACHED_AT
);
894 else if (memcached_failed(rc
))
899 if (*buffer_ptr
== '\n')
908 /* Now let's look in the buffer and copy as we go! */
909 while (instance
->read_buffer_length
and total_nr
< size
and line_complete
== false)
911 *buffer_ptr
= *instance
->read_ptr
;
912 if (*buffer_ptr
== '\n')
914 line_complete
= true;
916 --instance
->read_buffer_length
;
917 ++instance
->read_ptr
;
922 if (total_nr
== size
)
924 return MEMCACHED_PROTOCOL_ERROR
;
928 return MEMCACHED_SUCCESS
;