2 +--------------------------------------------------------------------+
3 | libmemcached-awesome - C/C++ Client Library for memcached |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted under the terms of the BSD license. |
7 | You should have received a copy of the license in a bundled file |
8 | named LICENSE; in case you did not receive a copy you can review |
9 | the terms online at: https://opensource.org/licenses/BSD-3-Clause |
10 +--------------------------------------------------------------------+
11 | Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ |
12 | Copyright (c) 2020-2021 Michael Wallner https://awesome.co/ |
13 +--------------------------------------------------------------------+
16 #include "libmemcached/common.h"
17 #include "p9y/poll.hpp"
18 #include "p9y/clock_gettime.hpp"
20 void initialize_binary_request(memcached_instance_st
*server
,
21 protocol_binary_request_header
&header
) {
23 header
.request
.magic
= PROTOCOL_BINARY_REQ
;
24 header
.request
.opaque
= htons(server
->request_id
);
27 enum memc_read_or_write
{ MEM_READ
, MEM_WRITE
};
30 * Try to fill the input buffer for a server with as much
33 * @param instance the server to pack
35 static bool repack_input_buffer(memcached_instance_st
*instance
) {
36 if (instance
->read_ptr
!= instance
->read_buffer
) {
37 /* Move all of the data to the beginning of the buffer so
38 ** that we can fit more data into the buffer...
40 memmove(instance
->read_buffer
, instance
->read_ptr
, instance
->read_buffer_length
);
41 instance
->read_ptr
= instance
->read_buffer
;
44 /* There is room in the buffer, try to fill it! */
45 if (instance
->read_buffer_length
!= MEMCACHED_MAX_BUFFER
) {
47 /* Just try a single read to grab what's available */
49 if ((nr
= ::recv(instance
->fd
, instance
->read_ptr
+ instance
->read_buffer_length
,
50 MEMCACHED_MAX_BUFFER
- instance
->read_buffer_length
, MSG_NOSIGNAL
))
54 memcached_set_error(*instance
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
);
56 switch (get_socket_errno()) {
60 #if EWOULDBLOCK != EAGAIN
67 break; // No IO is fine, we can just move on
70 memcached_set_errno(*instance
, get_socket_errno(), MEMCACHED_AT
);
75 } else // We read data, append to our read buffer
77 instance
->read_buffer_length
+= size_t(nr
);
88 * If the we have callbacks connected to this server structure
89 * we may start process the input queue and fire the callbacks
90 * for the incomming messages. This function is _only_ called
91 * when the input buffer is full, so that we _know_ that we have
92 * at least _one_ message to process.
94 * @param instance the server to star processing iput messages for
95 * @return true if we processed anything, false otherwise
97 static bool process_input_buffer(memcached_instance_st
*instance
) {
99 ** We might be able to process some of the response messages if we
100 ** have a callback set up
102 if (instance
->root
->callbacks
) {
104 * We might have responses... try to read them out and fire
107 memcached_callback_st cb
= *instance
->root
->callbacks
;
109 memcached_set_processing_input((Memcached
*) instance
->root
, true);
111 char buffer
[MEMCACHED_DEFAULT_COMMAND_SIZE
];
112 Memcached
*root
= (Memcached
*) instance
->root
;
113 memcached_return_t error
= memcached_response(instance
, buffer
, sizeof(buffer
), &root
->result
);
115 memcached_set_processing_input(root
, false);
117 if (error
== MEMCACHED_SUCCESS
) {
118 for (unsigned int x
= 0; x
< cb
.number_of_callback
; x
++) {
119 error
= (*cb
.callback
[x
])(instance
->root
, &root
->result
, cb
.context
);
120 if (error
!= MEMCACHED_SUCCESS
) {
125 /* @todo what should I do with the error message??? */
127 /* @todo what should I do with other error messages?? */
134 static memcached_return_t
io_sock_err(memcached_instance_st
*inst
,
135 const char *reason_str
, size_t reason_len
) {
137 socklen_t len
= sizeof(err
);
139 if (getsockopt(inst
->fd
, SOL_SOCKET
, SO_ERROR
, (char *) &err
, &len
) == -1) {
140 return memcached_set_errno(*inst
, errno
, MEMCACHED_AT
,
141 memcached_literal_param("getsockopt()"));
145 return memcached_set_errno(*inst
, err
, MEMCACHED_AT
, reason_str
, reason_len
);
147 return MEMCACHED_SUCCESS
;
150 memcached_return_t
memcached_io_poll(memcached_instance_st
*inst
, int16_t events
, int prev_errno
) {
154 pfd
.events
= events
? events
: inst
->events();
157 timeout
= inst
->root
->poll_timeout
;
159 timeout
= inst
->root
->connect_timeout
;
163 return memcached_set_error(*inst
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
,
164 memcached_literal_param("timeout was set to zero"));
167 timespec tspec
{}; // for clock_gettime()
168 int64_t start
, elapsed
; // ns
169 int32_t poll_timeout
= timeout
; // ms
171 if (clock_gettime(CLOCK_MONOTONIC
, &tspec
)) {
172 return memcached_set_errno(*inst
, errno
, MEMCACHED_AT
,
173 memcached_literal_param("clock_gettime()"));
175 start
= tspec
.tv_sec
* 1000000000 + tspec
.tv_nsec
;
177 int active
= poll(&pfd
, 1, poll_timeout
);
179 if (active
== SOCKET_ERROR
) {
180 int local_errno
= get_socket_errno();
182 switch (local_errno
) {
187 clock_gettime(CLOCK_MONOTONIC
, &tspec
);
188 elapsed
= tspec
.tv_sec
* 1000000000 + tspec
.tv_nsec
- start
;
189 if (elapsed
/ 1000000 >= timeout
|| !start
/* safety if clock_gettime is broken */) {
190 return memcached_set_error(*inst
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
,
191 memcached_literal_param("timeout on interrupt or restart"));
193 poll_timeout
-= elapsed
/ 1000000;
198 return memcached_set_error(*inst
, MEMCACHED_MEMORY_ALLOCATION_FAILURE
, MEMCACHED_AT
);
201 return memcached_set_error(*inst
, MEMCACHED_INVALID_ARGUMENTS
, MEMCACHED_AT
,
202 memcached_literal_param("RLIMIT_NOFILE exceeded, or invalid timeout"));
204 if (events
== IO_POLL_CONNECT
) {
205 inst
->reset_socket();
206 inst
->state
= MEMCACHED_SERVER_STATE_NEW
;
208 return memcached_set_errno(*inst
, local_errno
, MEMCACHED_AT
, memcached_literal_param("poll()"));
213 /* do not test SO_ERROR on EALREADY */
214 if (prev_errno
!= EALREADY
) {
215 memcached_return_t rc
= io_sock_err(inst
, memcached_literal_param("getsockopt() after poll() timed out"));
216 if (MEMCACHED_SUCCESS
!= rc
) {
220 return memcached_set_error(*inst
, MEMCACHED_TIMEOUT
, MEMCACHED_AT
,
221 memcached_literal_param("time out"));
224 assert_msg(active
== 1, "poll() returned an unexpected number of active file descriptors");
226 if (pfd
.revents
& (POLLERR
|POLLHUP
|POLLNVAL
)) {
227 memcached_return_t rc
= io_sock_err(inst
, memcached_literal_param("poll(POLLERR|POLLHUP|POLLNVAL)"));
228 if (MEMCACHED_SUCCESS
!= rc
) {
229 if (events
!= IO_POLL_CONNECT
) {
230 memcached_quit_server(inst
, true);
235 if (pfd
.revents
& events
|| (events
== IO_POLL_CONNECT
&& pfd
.revents
& POLLOUT
)) {
236 return MEMCACHED_SUCCESS
;
239 dprintf(STDERR_FILENO
, "io_poll() looped!\n");
244 static memcached_return_t
io_wait(memcached_instance_st
*instance
, const short events
) {
245 if (events
& POLLOUT
) {
247 ** We are going to block on write, but at least on Solaris we might block
248 ** on write if we haven't read anything from our input buffer..
249 ** Try to purge the input buffer if we don't do any flow control in the
250 ** application layer (just sending a lot of data etc)
251 ** The test is moved down in the purge function to avoid duplication of
254 if (memcached_purge(instance
) == false) {
255 return MEMCACHED_FAILURE
;
257 instance
->io_wait_count
.write
++;
259 instance
->io_wait_count
.read
++;
262 return memcached_io_poll(instance
, events
);
265 static bool io_flush(memcached_instance_st
*instance
, const bool with_flush
,
266 memcached_return_t
&error
) {
268 ** We might want to purge the input buffer if we haven't consumed
269 ** any output yet... The test for the limits is the purge is inline
270 ** in the purge function to avoid duplicating the logic..
273 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
275 if (memcached_purge(instance
) == false) {
279 char *local_write_ptr
= instance
->write_buffer
;
280 size_t write_length
= instance
->write_buffer_offset
;
282 error
= MEMCACHED_SUCCESS
;
284 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
286 /* Looking for memory overflows */
288 if (write_length
== MEMCACHED_MAX_BUFFER
)
289 WATCHPOINT_ASSERT(instance
->write_buffer
== local_write_ptr
);
290 WATCHPOINT_ASSERT((instance
->write_buffer
+ MEMCACHED_MAX_BUFFER
)
291 >= (local_write_ptr
+ write_length
));
294 while (write_length
) {
295 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
296 WATCHPOINT_ASSERT(write_length
> 0);
300 flags
= MSG_NOSIGNAL
;
302 flags
= MSG_NOSIGNAL
| MSG_MORE
;
305 ssize_t sent_length
= ::send(instance
->fd
, local_write_ptr
, write_length
, flags
);
306 int local_errno
= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
308 if (sent_length
== SOCKET_ERROR
) {
309 #if 0 // @todo I should look at why we hit this bit of code hard frequently
310 WATCHPOINT_ERRNO(get_socket_errno());
311 WATCHPOINT_NUMBER(get_socket_errno());
313 switch (get_socket_errno()) {
317 #if EWOULDBLOCK != EAGAIN
322 * We may be blocked on write because the input buffer
323 * is full. Let's check if we have room in our input
324 * buffer for more data and retry the write before
327 if (repack_input_buffer(instance
) or process_input_buffer(instance
)) {
331 memcached_return_t rc
= io_wait(instance
, POLLOUT
);
332 if (memcached_success(rc
)) {
334 } else if (rc
== MEMCACHED_TIMEOUT
) {
338 memcached_quit_server(instance
, true);
339 error
= memcached_set_errno(*instance
, local_errno
, MEMCACHED_AT
);
345 memcached_quit_server(instance
, true);
346 error
= memcached_set_errno(*instance
, local_errno
, MEMCACHED_AT
);
347 WATCHPOINT_ASSERT(instance
->fd
== INVALID_SOCKET
);
352 instance
->io_bytes_sent
+= uint32_t(sent_length
);
354 local_write_ptr
+= sent_length
;
355 write_length
-= uint32_t(sent_length
);
358 WATCHPOINT_ASSERT(write_length
== 0);
359 instance
->write_buffer_offset
= 0;
364 memcached_return_t
memcached_io_wait_for_write(memcached_instance_st
*instance
) {
365 return io_wait(instance
, POLLOUT
);
368 memcached_return_t
memcached_io_wait_for_read(memcached_instance_st
*instance
) {
369 return io_wait(instance
, POLLIN
);
372 static memcached_return_t
_io_fill(memcached_instance_st
*instance
) {
375 data_read
= ::recv(instance
->fd
, instance
->read_buffer
, MEMCACHED_MAX_BUFFER
, MSG_NOSIGNAL
);
376 int local_errno
= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
378 if (data_read
== SOCKET_ERROR
) {
379 switch (get_socket_errno()) {
380 case EINTR
: // We just retry
383 case ETIMEDOUT
: // OSX
384 #if EWOULDBLOCK != EAGAIN
392 memcached_return_t io_wait_ret
;
393 if (memcached_success(io_wait_ret
= io_wait(instance
, POLLIN
))) {
402 case ENOTCONN
: // Programmer Error
403 WATCHPOINT_ASSERT(0);
406 WATCHPOINT_ASSERT(0);
409 assert_msg(instance
->fd
!= INVALID_SOCKET
, "Programmer error, invalid socket");
415 memcached_quit_server(instance
, true);
416 memcached_set_errno(*instance
, local_errno
, MEMCACHED_AT
);
420 return memcached_instance_error_return(instance
);
421 } else if (data_read
== 0) {
423 EOF. Any data received so far is incomplete
424 so discard it. This always reads by byte in case of TCP
425 and protocol enforcement happens at memcached_response()
426 looking for '\n'. We do not care for UDB which requests 8 bytes
427 at once. Generally, this means that connection went away. Since
428 for blocking I/O we do not return 0 and for non-blocking case
429 it will return EGAIN if data is not immediatly available.
431 memcached_quit_server(instance
, true);
432 return memcached_set_error(
433 *instance
, MEMCACHED_CONNECTION_FAILURE
, MEMCACHED_AT
,
434 memcached_literal_param("::rec() returned zero, server has disconnected"));
436 instance
->io_wait_count
._bytes_read
+= data_read
;
437 } while (data_read
<= 0);
439 instance
->io_bytes_sent
= 0;
440 instance
->read_buffer_length
= (size_t) data_read
;
441 instance
->read_ptr
= instance
->read_buffer
;
443 return MEMCACHED_SUCCESS
;
446 memcached_return_t
memcached_io_read(memcached_instance_st
*instance
, void *buffer
, size_t length
,
448 assert(memcached_is_udp(instance
->root
) == false);
451 "Programmer error, memcached_io_read() recieved an invalid Instance"); // Programmer error
452 char *buffer_ptr
= static_cast<char *>(buffer
);
454 if (instance
->fd
== INVALID_SOCKET
) {
456 assert_msg(int(instance
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
), "Programmer error, invalid socket state");
458 return MEMCACHED_CONNECTION_FAILURE
;
462 if (instance
->read_buffer_length
== 0) {
463 memcached_return_t io_fill_ret
;
464 if (memcached_fatal(io_fill_ret
= _io_fill(instance
))) {
472 (length
> instance
->read_buffer_length
) ? instance
->read_buffer_length
: length
;
474 memcpy(buffer_ptr
, instance
->read_ptr
, difference
);
475 length
-= difference
;
476 instance
->read_ptr
+= difference
;
477 instance
->read_buffer_length
-= difference
;
478 buffer_ptr
+= difference
;
480 *buffer_ptr
= *instance
->read_ptr
;
481 instance
->read_ptr
++;
482 instance
->read_buffer_length
--;
488 nread
= ssize_t(buffer_ptr
- (char *) buffer
);
490 return MEMCACHED_SUCCESS
;
493 memcached_return_t
memcached_io_slurp(memcached_instance_st
*instance
) {
494 assert_msg(instance
, "Programmer error, invalid Instance");
495 assert(memcached_is_udp(instance
->root
) == false);
497 if (instance
->fd
== INVALID_SOCKET
) {
498 assert_msg(int(instance
->state
) <= int(MEMCACHED_SERVER_STATE_ADDRINFO
),
499 "Invalid socket state");
500 return MEMCACHED_CONNECTION_FAILURE
;
504 char buffer
[MEMCACHED_MAX_BUFFER
];
506 data_read
= ::recv(instance
->fd
, instance
->read_buffer
, sizeof(buffer
), MSG_NOSIGNAL
);
507 if (data_read
== SOCKET_ERROR
) {
508 switch (get_socket_errno()) {
509 case EINTR
: // We just retry
512 case ETIMEDOUT
: // OSX
513 #if EWOULDBLOCK != EAGAIN
520 if (memcached_success(io_wait(instance
, POLLIN
))) {
523 return MEMCACHED_IN_PROGRESS
;
527 case ENOTCONN
: // Programmer Error
532 assert_msg(instance
->fd
!= INVALID_SOCKET
, "Invalid socket state");
538 return MEMCACHED_CONNECTION_FAILURE
; // We want this!
541 } while (data_read
> 0);
543 return MEMCACHED_CONNECTION_FAILURE
;
546 static bool _io_write(memcached_instance_st
*instance
, const void *buffer
, size_t length
,
547 bool with_flush
, size_t &written
) {
548 assert(instance
->fd
!= INVALID_SOCKET
);
549 assert(memcached_is_udp(instance
->root
) == false);
551 const char *buffer_ptr
= static_cast<const char *>(buffer
);
553 const size_t original_length
= length
;
557 size_t buffer_end
= MEMCACHED_MAX_BUFFER
;
558 size_t should_write
= buffer_end
- instance
->write_buffer_offset
;
559 should_write
= (should_write
< length
) ? should_write
: length
;
561 write_ptr
= instance
->write_buffer
+ instance
->write_buffer_offset
;
562 memcpy(write_ptr
, buffer_ptr
, should_write
);
563 instance
->write_buffer_offset
+= should_write
;
564 buffer_ptr
+= should_write
;
565 length
-= should_write
;
567 if (instance
->write_buffer_offset
== buffer_end
) {
568 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
570 memcached_return_t rc
;
571 if (io_flush(instance
, with_flush
, rc
) == false) {
572 written
= original_length
- length
;
579 memcached_return_t rc
;
580 WATCHPOINT_ASSERT(instance
->fd
!= INVALID_SOCKET
);
581 if (io_flush(instance
, with_flush
, rc
) == false) {
582 written
= original_length
- length
;
587 written
= original_length
- length
;
592 bool memcached_io_write(memcached_instance_st
*instance
) {
594 return _io_write(instance
, NULL
, 0, true, written
);
597 ssize_t
memcached_io_write(memcached_instance_st
*instance
, const void *buffer
, const size_t length
,
598 const bool with_flush
) {
601 if (_io_write(instance
, buffer
, length
, with_flush
, written
) == false) {
605 return ssize_t(written
);
608 bool memcached_io_writev(memcached_instance_st
*instance
, libmemcached_io_vector_st vector
[],
609 const size_t number_of
, const bool with_flush
) {
610 ssize_t complete_total
= 0;
613 for (size_t x
= 0; x
< number_of
; x
++, vector
++) {
614 complete_total
+= vector
->length
;
615 if (vector
->length
) {
617 if ((_io_write(instance
, vector
->buffer
, vector
->length
, false, written
)) == false) {
625 if (memcached_io_write(instance
) == false) {
630 return (complete_total
== total
);
633 void memcached_instance_st::start_close_socket() {
634 if (fd
!= INVALID_SOCKET
) {
635 shutdown(fd
, SHUT_WR
);
636 options
.is_shutting_down
= true;
640 void memcached_instance_st::reset_socket() {
641 if (fd
!= INVALID_SOCKET
) {
642 (void) closesocket(fd
);
647 void memcached_instance_st::close_socket() {
648 if (fd
!= INVALID_SOCKET
) {
649 int shutdown_options
= SHUT_RD
;
650 if (options
.is_shutting_down
== false) {
651 shutdown_options
= SHUT_RDWR
;
654 /* in case of death shutdown to avoid blocking at close() */
655 if (shutdown(fd
, shutdown_options
) == SOCKET_ERROR
and get_socket_errno() != ENOTCONN
) {
656 WATCHPOINT_NUMBER(fd
);
657 WATCHPOINT_ERRNO(get_socket_errno());
658 WATCHPOINT_ASSERT(get_socket_errno());
662 state
= MEMCACHED_SERVER_STATE_NEW
;
665 state
= MEMCACHED_SERVER_STATE_NEW
;
668 write_buffer_offset
= size_t(root
and memcached_is_udp(root
) ? UDP_DATAGRAM_HEADER_LENGTH
: 0);
669 read_buffer_length
= 0;
670 read_ptr
= read_buffer
;
671 options
.is_shutting_down
= false;
672 memcached_server_response_reset(this);
674 // We reset the version so that if we end up talking to a different server
675 // we don't have stale server version information.
676 major_version
= minor_version
= micro_version
= UINT8_MAX
;
679 memcached_instance_st
*memcached_io_get_readable_server(Memcached
*memc
, memcached_return_t
&) {
680 #define MAX_SERVERS_TO_POLL 100
681 struct pollfd fds
[MAX_SERVERS_TO_POLL
];
682 nfds_t host_index
= 0;
684 for (uint32_t x
= 0; x
< memcached_server_count(memc
) and host_index
< MAX_SERVERS_TO_POLL
; ++x
) {
685 memcached_instance_st
*instance
= memcached_instance_fetch(memc
, x
);
687 if (instance
->read_buffer_length
> 0) /* I have data in the buffer */ {
691 if (instance
->response_count() > 0) {
692 fds
[host_index
].events
= POLLIN
;
693 fds
[host_index
].revents
= 0;
694 fds
[host_index
].fd
= instance
->fd
;
699 if (host_index
< 2) {
700 /* We have 0 or 1 server with pending events.. */
701 for (uint32_t x
= 0; x
< memcached_server_count(memc
); ++x
) {
702 memcached_instance_st
*instance
= memcached_instance_fetch(memc
, x
);
704 if (instance
->response_count() > 0) {
712 int error
= poll(fds
, host_index
, memc
->poll_timeout
);
715 memcached_set_errno(*memc
, get_socket_errno(), MEMCACHED_AT
);
721 for (nfds_t x
= 0; x
< host_index
; ++x
) {
722 if (fds
[x
].revents
& POLLIN
) {
723 for (uint32_t y
= 0; y
< memcached_server_count(memc
); ++y
) {
724 memcached_instance_st
*instance
= memcached_instance_fetch(memc
, y
);
726 if (instance
->fd
== fds
[x
].fd
) {
738 Eventually we will just kill off the server with the problem.
740 void memcached_io_reset(memcached_instance_st
*instance
) {
741 memcached_quit_server(instance
, true);
745 * Read a given number of bytes from the server and place it into a specific
746 * buffer. Reset the IO channel on this server if an error occurs.
748 memcached_return_t
memcached_safe_read(memcached_instance_st
*instance
, void *dta
,
751 char *data
= static_cast<char *>(dta
);
753 while (offset
< size
) {
755 memcached_return_t rc
;
758 memcached_continue(rc
= memcached_io_read(instance
, data
+ offset
, size
- offset
, nread
))) {
761 if (memcached_failed(rc
)) {
765 offset
+= size_t(nread
);
768 return MEMCACHED_SUCCESS
;
771 memcached_return_t
memcached_io_readline(memcached_instance_st
*instance
, char *buffer_ptr
,
772 size_t size
, size_t &total_nr
) {
774 bool line_complete
= false;
776 while (line_complete
== false) {
777 if (instance
->read_buffer_length
== 0) {
779 * We don't have any data in the buffer, so let's fill the read
780 * buffer. Call the standard read function to avoid duplicating
784 memcached_return_t rc
= memcached_io_read(instance
, buffer_ptr
, 1, nread
);
785 if (memcached_failed(rc
) and rc
== MEMCACHED_IN_PROGRESS
) {
786 memcached_quit_server(instance
, true);
787 return memcached_set_error(*instance
, rc
, MEMCACHED_AT
);
788 } else if (memcached_failed(rc
)) {
792 if (*buffer_ptr
== '\n') {
793 line_complete
= true;
800 /* Now let's look in the buffer and copy as we go! */
801 while (instance
->read_buffer_length
and total_nr
< size
and line_complete
== false) {
802 *buffer_ptr
= *instance
->read_ptr
;
803 if (*buffer_ptr
== '\n') {
804 line_complete
= true;
806 --instance
->read_buffer_length
;
807 ++instance
->read_ptr
;
812 if (total_nr
== size
) {
813 return MEMCACHED_PROTOCOL_ERROR
;
817 return MEMCACHED_SUCCESS
;