d2196f67d1e6524a0585f9999e2dca2facfb35e4
[awesomized/libmemcached] / libmemcached / io.cc
1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
2 *
3 * LibMemcached
4 *
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 * Copyright (C) 2006-2009 Brian Aker
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are
11 * met:
12 *
13 * * Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 *
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
19 * distribution.
20 *
21 * * The names of its contributors may not be used to endorse or
22 * promote products derived from this software without specific prior
23 * written permission.
24 *
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.
36 *
37 */
38
39
40 #include <libmemcached/common.h>
41
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif
45
46 void initialize_binary_request(memcached_instance_st* server, protocol_binary_request_header& header)
47 {
48 server->request_id++;
49 header.request.magic= PROTOCOL_BINARY_REQ;
50 header.request.opaque= htons(server->request_id);
51 }
52
53 enum memc_read_or_write {
54 MEM_READ,
55 MEM_WRITE
56 };
57
58 /**
59 * Try to fill the input buffer for a server with as much
60 * data as possible.
61 *
62 * @param instance the server to pack
63 */
64 static bool repack_input_buffer(memcached_instance_st* instance)
65 {
66 if (instance->read_ptr != instance->read_buffer)
67 {
68 /* Move all of the data to the beginning of the buffer so
69 ** that we can fit more data into the buffer...
70 */
71 memmove(instance->read_buffer, instance->read_ptr, instance->read_buffer_length);
72 instance->read_ptr= instance->read_buffer;
73 }
74
75 /* There is room in the buffer, try to fill it! */
76 if (instance->read_buffer_length != MEMCACHED_MAX_BUFFER)
77 {
78 do {
79 /* Just try a single read to grab what's available */
80 ssize_t nr;
81 if ((nr= ::recv(instance->fd,
82 instance->read_ptr + instance->read_buffer_length,
83 MEMCACHED_MAX_BUFFER - instance->read_buffer_length,
84 MSG_NOSIGNAL)) <= 0)
85 {
86 if (nr == 0)
87 {
88 memcached_set_error(*instance, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT);
89 }
90 else
91 {
92 switch (get_socket_errno())
93 {
94 case EINTR:
95 continue;
96
97 #if EWOULDBLOCK != EAGAIN
98 case EWOULDBLOCK:
99 #endif
100 case EAGAIN:
101 #ifdef __linux
102 case ERESTART:
103 #endif
104 break; // No IO is fine, we can just move on
105
106 default:
107 memcached_set_errno(*instance, get_socket_errno(), MEMCACHED_AT);
108 }
109 }
110
111 break;
112 }
113 else // We read data, append to our read buffer
114 {
115 instance->read_buffer_length+= size_t(nr);
116
117 return true;
118 }
119 } while (false);
120 }
121
122 return false;
123 }
124
125 /**
126 * If the we have callbacks connected to this server structure
127 * we may start process the input queue and fire the callbacks
128 * for the incomming messages. This function is _only_ called
129 * when the input buffer is full, so that we _know_ that we have
130 * at least _one_ message to process.
131 *
132 * @param instance the server to star processing iput messages for
133 * @return true if we processed anything, false otherwise
134 */
135 static bool process_input_buffer(memcached_instance_st* instance)
136 {
137 /*
138 ** We might be able to process some of the response messages if we
139 ** have a callback set up
140 */
141 if (instance->root->callbacks != NULL)
142 {
143 /*
144 * We might have responses... try to read them out and fire
145 * callbacks
146 */
147 memcached_callback_st cb= *instance->root->callbacks;
148
149 memcached_set_processing_input((Memcached *)instance->root, true);
150
151 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
152 Memcached *root= (Memcached *)instance->root;
153 memcached_return_t error= memcached_response(instance, buffer, sizeof(buffer), &root->result);
154
155 memcached_set_processing_input(root, false);
156
157 if (error == MEMCACHED_SUCCESS)
158 {
159 for (unsigned int x= 0; x < cb.number_of_callback; x++)
160 {
161 error= (*cb.callback[x])(instance->root, &root->result, cb.context);
162 if (error != MEMCACHED_SUCCESS)
163 {
164 break;
165 }
166 }
167
168 /* @todo what should I do with the error message??? */
169 }
170 /* @todo what should I do with other error messages?? */
171 return true;
172 }
173
174 return false;
175 }
176
177 static memcached_return_t io_wait(memcached_instance_st* instance,
178 const short events)
179 {
180 /*
181 ** We are going to block on write, but at least on Solaris we might block
182 ** on write if we haven't read anything from our input buffer..
183 ** Try to purge the input buffer if we don't do any flow control in the
184 ** application layer (just sending a lot of data etc)
185 ** The test is moved down in the purge function to avoid duplication of
186 ** the test.
187 */
188 if (events & POLLOUT)
189 {
190 if (memcached_purge(instance) == false)
191 {
192 return MEMCACHED_FAILURE;
193 }
194 }
195
196 struct pollfd fds;
197 fds.fd= instance->fd;
198 fds.events= events;
199 fds.revents= 0;
200
201 if (fds.events & POLLOUT) /* write */
202 {
203 instance->io_wait_count.write++;
204 }
205 else
206 {
207 instance->io_wait_count.read++;
208 }
209
210 if (instance->root->poll_timeout == 0) // Mimic 0 causes timeout behavior (not all platforms do this)
211 {
212 return memcached_set_error(*instance, MEMCACHED_TIMEOUT, MEMCACHED_AT, memcached_literal_param("poll_timeout() was set to zero"));
213 }
214
215 size_t loop_max= 5;
216 while (--loop_max) // While loop is for ERESTART or EINTR
217 {
218 int active_fd= poll(&fds, 1, instance->root->poll_timeout);
219
220 if (active_fd >= 1)
221 {
222 assert_msg(active_fd == 1 , "poll() returned an unexpected number of active file descriptors");
223 if (fds.revents & POLLIN or fds.revents & POLLOUT)
224 {
225 return MEMCACHED_SUCCESS;
226 }
227
228 if (fds.revents & POLLHUP)
229 {
230 return memcached_set_error(*instance, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT,
231 memcached_literal_param("poll() detected hang up"));
232 }
233
234 if (fds.revents & POLLERR)
235 {
236 int local_errno= EINVAL;
237 int err;
238 socklen_t len= sizeof (err);
239 if (getsockopt(instance->fd, SOL_SOCKET, SO_ERROR, (char*)&err, &len) == 0)
240 {
241 if (err == 0) // treat this as EINTR
242 {
243 continue;
244 }
245 local_errno= err;
246 }
247 memcached_quit_server(instance, true);
248 return memcached_set_errno(*instance, local_errno, MEMCACHED_AT,
249 memcached_literal_param("poll() returned POLLHUP"));
250 }
251
252 return memcached_set_error(*instance, MEMCACHED_FAILURE, MEMCACHED_AT, memcached_literal_param("poll() returned a value that was not dealt with"));
253 }
254
255 if (active_fd == 0)
256 {
257 return memcached_set_error(*instance, MEMCACHED_TIMEOUT, MEMCACHED_AT, memcached_literal_param("No active_fd were found"));
258 }
259
260 // Only an error should result in this code being called.
261 int local_errno= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
262 assert_msg(active_fd == -1 , "poll() returned an unexpected value");
263 switch (local_errno)
264 {
265 #ifdef __linux
266 case ERESTART:
267 #endif
268 case EINTR:
269 continue;
270
271 case EFAULT:
272 case ENOMEM:
273 memcached_set_error(*instance, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT);
274 break;
275
276 case EINVAL:
277 memcached_set_error(*instance, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT, memcached_literal_param("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid"));
278 break;
279
280 default:
281 memcached_set_errno(*instance, local_errno, MEMCACHED_AT, memcached_literal_param("poll"));
282 }
283
284 break;
285 }
286
287 memcached_quit_server(instance, true);
288
289 if (memcached_has_error(instance))
290 {
291 return memcached_instance_error_return(instance);
292 }
293
294 return memcached_set_error(*instance, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT,
295 memcached_literal_param("number of attempts to call io_wait() failed"));
296 }
297
298 static bool io_flush(memcached_instance_st* instance,
299 const bool with_flush,
300 memcached_return_t& error)
301 {
302 /*
303 ** We might want to purge the input buffer if we haven't consumed
304 ** any output yet... The test for the limits is the purge is inline
305 ** in the purge function to avoid duplicating the logic..
306 */
307 {
308 WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);
309
310 if (memcached_purge(instance) == false)
311 {
312 return false;
313 }
314 }
315 char *local_write_ptr= instance->write_buffer;
316 size_t write_length= instance->write_buffer_offset;
317
318 error= MEMCACHED_SUCCESS;
319
320 WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);
321
322 /* Looking for memory overflows */
323 #if defined(DEBUG)
324 if (write_length == MEMCACHED_MAX_BUFFER)
325 WATCHPOINT_ASSERT(instance->write_buffer == local_write_ptr);
326 WATCHPOINT_ASSERT((instance->write_buffer + MEMCACHED_MAX_BUFFER) >= (local_write_ptr + write_length));
327 #endif
328
329 while (write_length)
330 {
331 WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);
332 WATCHPOINT_ASSERT(write_length > 0);
333
334 int flags;
335 if (with_flush)
336 {
337 flags= MSG_NOSIGNAL;
338 }
339 else
340 {
341 flags= MSG_NOSIGNAL|MSG_MORE;
342 }
343
344 ssize_t sent_length= ::send(instance->fd, local_write_ptr, write_length, flags);
345 int local_errno= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
346
347 if (sent_length == SOCKET_ERROR)
348 {
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());
352 #endif
353 switch (get_socket_errno())
354 {
355 case ENOBUFS:
356 continue;
357
358 #if EWOULDBLOCK != EAGAIN
359 case EWOULDBLOCK:
360 #endif
361 case EAGAIN:
362 {
363 /*
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
367 * waiting..
368 */
369 if (repack_input_buffer(instance) or process_input_buffer(instance))
370 {
371 continue;
372 }
373
374 memcached_return_t rc= io_wait(instance, POLLOUT);
375 if (memcached_success(rc))
376 {
377 continue;
378 }
379 else if (rc == MEMCACHED_TIMEOUT)
380 {
381 return false;
382 }
383
384 memcached_quit_server(instance, true);
385 error= memcached_set_errno(*instance, local_errno, MEMCACHED_AT);
386 return false;
387 }
388 case ENOTCONN:
389 case EPIPE:
390 default:
391 memcached_quit_server(instance, true);
392 error= memcached_set_errno(*instance, local_errno, MEMCACHED_AT);
393 WATCHPOINT_ASSERT(instance->fd == INVALID_SOCKET);
394 return false;
395 }
396 }
397
398 instance->io_bytes_sent+= uint32_t(sent_length);
399
400 local_write_ptr+= sent_length;
401 write_length-= uint32_t(sent_length);
402 }
403
404 WATCHPOINT_ASSERT(write_length == 0);
405 instance->write_buffer_offset= 0;
406
407 return true;
408 }
409
410 memcached_return_t memcached_io_wait_for_write(memcached_instance_st* instance)
411 {
412 return io_wait(instance, POLLOUT);
413 }
414
415 memcached_return_t memcached_io_wait_for_read(memcached_instance_st* instance)
416 {
417 return io_wait(instance, POLLIN);
418 }
419
420 static memcached_return_t _io_fill(memcached_instance_st* instance)
421 {
422 ssize_t data_read;
423 do
424 {
425 data_read= ::recv(instance->fd, instance->read_buffer, MEMCACHED_MAX_BUFFER, MSG_NOSIGNAL);
426 int local_errno= get_socket_errno(); // We cache in case memcached_quit_server() modifies errno
427
428 if (data_read == SOCKET_ERROR)
429 {
430 switch (get_socket_errno())
431 {
432 case EINTR: // We just retry
433 continue;
434
435 case ETIMEDOUT: // OSX
436 #if EWOULDBLOCK != EAGAIN
437 case EWOULDBLOCK:
438 #endif
439 case EAGAIN:
440 #ifdef __linux
441 case ERESTART:
442 #endif
443 {
444 memcached_return_t io_wait_ret;
445 if (memcached_success(io_wait_ret= io_wait(instance, POLLIN)))
446 {
447 continue;
448 }
449
450 return io_wait_ret;
451 }
452
453 /* fall through */
454
455 case ENOTCONN: // Programmer Error
456 WATCHPOINT_ASSERT(0);
457 case ENOTSOCK:
458 WATCHPOINT_ASSERT(0);
459 case EBADF:
460 assert_msg(instance->fd != INVALID_SOCKET, "Programmer error, invalid socket");
461 /* fall through */
462 case EINVAL:
463 case EFAULT:
464 case ECONNREFUSED:
465 default:
466 memcached_quit_server(instance, true);
467 memcached_set_errno(*instance, local_errno, MEMCACHED_AT);
468 break;
469 }
470
471 return memcached_instance_error_return(instance);
472 }
473 else if (data_read == 0)
474 {
475 /*
476 EOF. Any data received so far is incomplete
477 so discard it. This always reads by byte in case of TCP
478 and protocol enforcement happens at memcached_response()
479 looking for '\n'. We do not care for UDB which requests 8 bytes
480 at once. Generally, this means that connection went away. Since
481 for blocking I/O we do not return 0 and for non-blocking case
482 it will return EGAIN if data is not immediatly available.
483 */
484 memcached_quit_server(instance, true);
485 return memcached_set_error(*instance, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT,
486 memcached_literal_param("::rec() returned zero, server has disconnected"));
487 }
488 instance->io_wait_count._bytes_read+= data_read;
489 } while (data_read <= 0);
490
491 instance->io_bytes_sent= 0;
492 instance->read_buffer_length= (size_t) data_read;
493 instance->read_ptr= instance->read_buffer;
494
495 return MEMCACHED_SUCCESS;
496 }
497
498 memcached_return_t memcached_io_read(memcached_instance_st* instance,
499 void *buffer, size_t length, ssize_t& nread)
500 {
501 assert(memcached_is_udp(instance->root) == false);
502 assert_msg(instance, "Programmer error, memcached_io_read() recieved an invalid Instance"); // Programmer error
503 char *buffer_ptr= static_cast<char *>(buffer);
504
505 if (instance->fd == INVALID_SOCKET)
506 {
507 #if 0
508 assert_msg(int(instance->state) <= int(MEMCACHED_SERVER_STATE_ADDRINFO), "Programmer error, invalid socket state");
509 #endif
510 return MEMCACHED_CONNECTION_FAILURE;
511 }
512
513 while (length)
514 {
515 if (instance->read_buffer_length == 0)
516 {
517 memcached_return_t io_fill_ret;
518 if (memcached_fatal(io_fill_ret= _io_fill(instance)))
519 {
520 nread= -1;
521 return io_fill_ret;
522 }
523 }
524
525 if (length > 1)
526 {
527 size_t difference= (length > instance->read_buffer_length) ? instance->read_buffer_length : length;
528
529 memcpy(buffer_ptr, instance->read_ptr, difference);
530 length -= difference;
531 instance->read_ptr+= difference;
532 instance->read_buffer_length-= difference;
533 buffer_ptr+= difference;
534 }
535 else
536 {
537 *buffer_ptr= *instance->read_ptr;
538 instance->read_ptr++;
539 instance->read_buffer_length--;
540 buffer_ptr++;
541 break;
542 }
543 }
544
545 nread= ssize_t(buffer_ptr - (char*)buffer);
546
547 return MEMCACHED_SUCCESS;
548 }
549
550 memcached_return_t memcached_io_slurp(memcached_instance_st* instance)
551 {
552 assert_msg(instance, "Programmer error, invalid Instance");
553 assert(memcached_is_udp(instance->root) == false);
554
555 if (instance->fd == INVALID_SOCKET)
556 {
557 assert_msg(int(instance->state) <= int(MEMCACHED_SERVER_STATE_ADDRINFO), "Invalid socket state");
558 return MEMCACHED_CONNECTION_FAILURE;
559 }
560
561 ssize_t data_read;
562 char buffer[MEMCACHED_MAX_BUFFER];
563 do
564 {
565 data_read= ::recv(instance->fd, instance->read_buffer, sizeof(buffer), MSG_NOSIGNAL);
566 if (data_read == SOCKET_ERROR)
567 {
568 switch (get_socket_errno())
569 {
570 case EINTR: // We just retry
571 continue;
572
573 case ETIMEDOUT: // OSX
574 #if EWOULDBLOCK != EAGAIN
575 case EWOULDBLOCK:
576 #endif
577 case EAGAIN:
578 #ifdef __linux
579 case ERESTART:
580 #endif
581 if (memcached_success(io_wait(instance, POLLIN)))
582 {
583 continue;
584 }
585 return MEMCACHED_IN_PROGRESS;
586
587 /* fall through */
588
589 case ENOTCONN: // Programmer Error
590 assert(0);
591 case ENOTSOCK:
592 assert(0);
593 case EBADF:
594 assert_msg(instance->fd != INVALID_SOCKET, "Invalid socket state");
595 /* fall through */
596 case EINVAL:
597 case EFAULT:
598 case ECONNREFUSED:
599 default:
600 return MEMCACHED_CONNECTION_FAILURE; // We want this!
601 }
602 }
603 } while (data_read > 0);
604
605 return MEMCACHED_CONNECTION_FAILURE;
606 }
607
608 static bool _io_write(memcached_instance_st* instance,
609 const void *buffer, size_t length, bool with_flush,
610 size_t& written)
611 {
612 assert(instance->fd != INVALID_SOCKET);
613 assert(memcached_is_udp(instance->root) == false);
614
615 const char *buffer_ptr= static_cast<const char *>(buffer);
616
617 const size_t original_length= length;
618
619 while (length)
620 {
621 char *write_ptr;
622 size_t buffer_end= MEMCACHED_MAX_BUFFER;
623 size_t should_write= buffer_end -instance->write_buffer_offset;
624 should_write= (should_write < length) ? should_write : length;
625
626 write_ptr= instance->write_buffer + instance->write_buffer_offset;
627 memcpy(write_ptr, buffer_ptr, should_write);
628 instance->write_buffer_offset+= should_write;
629 buffer_ptr+= should_write;
630 length-= should_write;
631
632 if (instance->write_buffer_offset == buffer_end)
633 {
634 WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);
635
636 memcached_return_t rc;
637 if (io_flush(instance, with_flush, rc) == false)
638 {
639 written= original_length -length;
640 return false;
641 }
642 }
643 }
644
645 if (with_flush)
646 {
647 memcached_return_t rc;
648 WATCHPOINT_ASSERT(instance->fd != INVALID_SOCKET);
649 if (io_flush(instance, with_flush, rc) == false)
650 {
651 written= original_length -length;
652 return false;
653 }
654 }
655
656 written= original_length -length;
657
658 return true;
659 }
660
661 bool memcached_io_write(memcached_instance_st* instance)
662 {
663 size_t written;
664 return _io_write(instance, NULL, 0, true, written);
665 }
666
667 ssize_t memcached_io_write(memcached_instance_st* instance,
668 const void *buffer, const size_t length, const bool with_flush)
669 {
670 size_t written;
671
672 if (_io_write(instance, buffer, length, with_flush, written) == false)
673 {
674 return -1;
675 }
676
677 return ssize_t(written);
678 }
679
680 bool memcached_io_writev(memcached_instance_st* instance,
681 libmemcached_io_vector_st vector[],
682 const size_t number_of, const bool with_flush)
683 {
684 ssize_t complete_total= 0;
685 ssize_t total= 0;
686
687 for (size_t x= 0; x < number_of; x++, vector++)
688 {
689 complete_total+= vector->length;
690 if (vector->length)
691 {
692 size_t written;
693 if ((_io_write(instance, vector->buffer, vector->length, false, written)) == false)
694 {
695 return false;
696 }
697 total+= written;
698 }
699 }
700
701 if (with_flush)
702 {
703 if (memcached_io_write(instance) == false)
704 {
705 return false;
706 }
707 }
708
709 return (complete_total == total);
710 }
711
712 void memcached_instance_st::start_close_socket()
713 {
714 if (fd != INVALID_SOCKET)
715 {
716 shutdown(fd, SHUT_WR);
717 options.is_shutting_down= true;
718 }
719 }
720
721 void memcached_instance_st::reset_socket()
722 {
723 if (fd != INVALID_SOCKET)
724 {
725 (void)closesocket(fd);
726 fd= INVALID_SOCKET;
727 }
728 }
729
730 void memcached_instance_st::close_socket()
731 {
732 if (fd != INVALID_SOCKET)
733 {
734 int shutdown_options= SHUT_RD;
735 if (options.is_shutting_down == false)
736 {
737 shutdown_options= SHUT_RDWR;
738 }
739
740 /* in case of death shutdown to avoid blocking at close() */
741 if (shutdown(fd, shutdown_options) == SOCKET_ERROR and get_socket_errno() != ENOTCONN)
742 {
743 WATCHPOINT_NUMBER(fd);
744 WATCHPOINT_ERRNO(get_socket_errno());
745 WATCHPOINT_ASSERT(get_socket_errno());
746 }
747
748 reset_socket();
749 state= MEMCACHED_SERVER_STATE_NEW;
750 }
751
752 state= MEMCACHED_SERVER_STATE_NEW;
753 cursor_active_= 0;
754 io_bytes_sent= 0;
755 write_buffer_offset= size_t(root and memcached_is_udp(root) ? UDP_DATAGRAM_HEADER_LENGTH : 0);
756 read_buffer_length= 0;
757 read_ptr= read_buffer;
758 options.is_shutting_down= false;
759 memcached_server_response_reset(this);
760
761 // We reset the version so that if we end up talking to a different server
762 // we don't have stale server version information.
763 major_version= minor_version= micro_version= UINT8_MAX;
764 }
765
766 memcached_instance_st* memcached_io_get_readable_server(Memcached *memc, memcached_return_t&)
767 {
768 #define MAX_SERVERS_TO_POLL 100
769 struct pollfd fds[MAX_SERVERS_TO_POLL];
770 nfds_t host_index= 0;
771
772 for (uint32_t x= 0; x < memcached_server_count(memc) and host_index < MAX_SERVERS_TO_POLL; ++x)
773 {
774 memcached_instance_st* instance= memcached_instance_fetch(memc, x);
775
776 if (instance->read_buffer_length > 0) /* I have data in the buffer */
777 {
778 return instance;
779 }
780
781 if (instance->response_count() > 0)
782 {
783 fds[host_index].events= POLLIN;
784 fds[host_index].revents= 0;
785 fds[host_index].fd= instance->fd;
786 ++host_index;
787 }
788 }
789
790 if (host_index < 2)
791 {
792 /* We have 0 or 1 server with pending events.. */
793 for (uint32_t x= 0; x< memcached_server_count(memc); ++x)
794 {
795 memcached_instance_st* instance= memcached_instance_fetch(memc, x);
796
797 if (instance->response_count() > 0)
798 {
799 return instance;
800 }
801 }
802
803 return NULL;
804 }
805
806 int error= poll(fds, host_index, memc->poll_timeout);
807 switch (error)
808 {
809 case -1:
810 memcached_set_errno(*memc, get_socket_errno(), MEMCACHED_AT);
811 /* FALLTHROUGH */
812 case 0:
813 break;
814
815 default:
816 for (nfds_t x= 0; x < host_index; ++x)
817 {
818 if (fds[x].revents & POLLIN)
819 {
820 for (uint32_t y= 0; y < memcached_server_count(memc); ++y)
821 {
822 memcached_instance_st* instance= memcached_instance_fetch(memc, y);
823
824 if (instance->fd == fds[x].fd)
825 {
826 return instance;
827 }
828 }
829 }
830 }
831 }
832
833 return NULL;
834 }
835
836 /*
837 Eventually we will just kill off the server with the problem.
838 */
839 void memcached_io_reset(memcached_instance_st* instance)
840 {
841 memcached_quit_server(instance, true);
842 }
843
844 /**
845 * Read a given number of bytes from the server and place it into a specific
846 * buffer. Reset the IO channel on this server if an error occurs.
847 */
848 memcached_return_t memcached_safe_read(memcached_instance_st* instance,
849 void *dta,
850 const size_t size)
851 {
852 size_t offset= 0;
853 char *data= static_cast<char *>(dta);
854
855 while (offset < size)
856 {
857 ssize_t nread;
858 memcached_return_t rc;
859
860 while (memcached_continue(rc= memcached_io_read(instance, data + offset, size - offset, nread))) { };
861
862 if (memcached_failed(rc))
863 {
864 return rc;
865 }
866
867 offset+= size_t(nread);
868 }
869
870 return MEMCACHED_SUCCESS;
871 }
872
873 memcached_return_t memcached_io_readline(memcached_instance_st* instance,
874 char *buffer_ptr,
875 size_t size,
876 size_t& total_nr)
877 {
878 total_nr= 0;
879 bool line_complete= false;
880
881 while (line_complete == false)
882 {
883 if (instance->read_buffer_length == 0)
884 {
885 /*
886 * We don't have any data in the buffer, so let's fill the read
887 * buffer. Call the standard read function to avoid duplicating
888 * the logic.
889 */
890 ssize_t nread;
891 memcached_return_t rc= memcached_io_read(instance, buffer_ptr, 1, nread);
892 if (memcached_failed(rc) and rc == MEMCACHED_IN_PROGRESS)
893 {
894 memcached_quit_server(instance, true);
895 return memcached_set_error(*instance, rc, MEMCACHED_AT);
896 }
897 else if (memcached_failed(rc))
898 {
899 return rc;
900 }
901
902 if (*buffer_ptr == '\n')
903 {
904 line_complete= true;
905 }
906
907 ++buffer_ptr;
908 ++total_nr;
909 }
910
911 /* Now let's look in the buffer and copy as we go! */
912 while (instance->read_buffer_length and total_nr < size and line_complete == false)
913 {
914 *buffer_ptr = *instance->read_ptr;
915 if (*buffer_ptr == '\n')
916 {
917 line_complete = true;
918 }
919 --instance->read_buffer_length;
920 ++instance->read_ptr;
921 ++total_nr;
922 ++buffer_ptr;
923 }
924
925 if (total_nr == size)
926 {
927 return MEMCACHED_PROTOCOL_ERROR;
928 }
929 }
930
931 return MEMCACHED_SUCCESS;
932 }