d4599f77c793e15095c3b2cf08f47a9f3d66e6fc
[m6w6/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(org::libmemcached::Instance* 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 ptr the server to pack
63 */
64 static bool repack_input_buffer(org::libmemcached::Instance* ptr)
65 {
66 if (ptr->read_ptr != ptr->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(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;
74 }
75
76 /* There is room in the buffer, try to fill it! */
77 if (ptr->read_buffer_length != MEMCACHED_MAX_BUFFER)
78 {
79 do {
80 /* Just try a single read to grab what's available */
81 ssize_t nr;
82 if ((nr= ::recv(ptr->fd,
83 ptr->read_ptr + ptr->read_data_length,
84 MEMCACHED_MAX_BUFFER - ptr->read_data_length,
85 MSG_NOSIGNAL)) <= 0)
86 {
87 if (nr == 0)
88 {
89 memcached_set_error(*ptr, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT);
90 }
91 else
92 {
93 switch (get_socket_errno())
94 {
95 case EINTR:
96 continue;
97
98 #if EWOULDBLOCK != EAGAIN
99 case EWOULDBLOCK:
100 #endif
101 case EAGAIN:
102 #ifdef TARGET_OS_LINUX
103 case ERESTART:
104 #endif
105 break; // No IO is fine, we can just move on
106
107 default:
108 memcached_set_errno(*ptr, get_socket_errno(), MEMCACHED_AT);
109 }
110 }
111
112 break;
113 }
114 else // We read data, append to our read buffer
115 {
116 ptr->read_data_length+= size_t(nr);
117 ptr->read_buffer_length+= size_t(nr);
118
119 return true;
120 }
121 } while (false);
122 }
123
124 return false;
125 }
126
127 /**
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.
133 *
134 * @param ptr the server to star processing iput messages for
135 * @return true if we processed anything, false otherwise
136 */
137 static bool process_input_buffer(org::libmemcached::Instance* ptr)
138 {
139 /*
140 ** We might be able to process some of the response messages if we
141 ** have a callback set up
142 */
143 if (ptr->root->callbacks != NULL)
144 {
145 /*
146 * We might have responses... try to read them out and fire
147 * callbacks
148 */
149 memcached_callback_st cb= *ptr->root->callbacks;
150
151 memcached_set_processing_input((memcached_st *)ptr->root, true);
152
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);
156
157 memcached_set_processing_input(root, false);
158
159 if (error == MEMCACHED_SUCCESS)
160 {
161 for (unsigned int x= 0; x < cb.number_of_callback; x++)
162 {
163 error= (*cb.callback[x])(ptr->root, &root->result, cb.context);
164 if (error != MEMCACHED_SUCCESS)
165 {
166 break;
167 }
168 }
169
170 /* @todo what should I do with the error message??? */
171 }
172 /* @todo what should I do with other error messages?? */
173 return true;
174 }
175
176 return false;
177 }
178
179 static memcached_return_t io_wait(org::libmemcached::Instance* ptr,
180 const memc_read_or_write read_or_write)
181 {
182 /*
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
188 ** the test.
189 */
190 if (read_or_write == MEM_WRITE)
191 {
192 if (memcached_purge(ptr) == false)
193 {
194 return MEMCACHED_FAILURE;
195 }
196 }
197
198 struct pollfd fds;
199 fds.fd= ptr->fd;
200 fds.events= POLLIN;
201 fds.revents= 0;
202
203 if (read_or_write == MEM_WRITE) /* write */
204 {
205 fds.events= POLLOUT;
206 ptr->io_wait_count.write++;
207 }
208 else
209 {
210 ptr->io_wait_count.read++;
211 }
212
213 if (ptr->root->poll_timeout == 0) // Mimic 0 causes timeout behavior (not all platforms do this)
214 {
215 ptr->io_wait_count.timeouts++;
216 return memcached_set_error(*ptr, MEMCACHED_TIMEOUT, MEMCACHED_AT);
217 }
218
219 size_t loop_max= 5;
220 while (--loop_max) // While loop is for ERESTART or EINTR
221 {
222 int active_fd= poll(&fds, 1, ptr->root->poll_timeout);
223
224 if (active_fd >= 1)
225 {
226 assert_msg(active_fd == 1 , "poll() returned an unexpected number of active file descriptors");
227 if (fds.revents & POLLIN or fds.revents & POLLOUT)
228 {
229 return MEMCACHED_SUCCESS;
230 }
231
232 if (fds.revents & POLLHUP)
233 {
234 return memcached_set_error(*ptr, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT,
235 memcached_literal_param("poll() detected hang up"));
236 }
237
238 if (fds.revents & POLLERR)
239 {
240 int local_errno= EINVAL;
241 int err;
242 socklen_t len= sizeof (err);
243 if (getsockopt(ptr->fd, SOL_SOCKET, SO_ERROR, (char*)&err, &len) == 0)
244 {
245 if (err == 0) // treat this as EINTR
246 {
247 continue;
248 }
249 local_errno= err;
250 }
251 memcached_quit_server(ptr, true);
252 return memcached_set_errno(*ptr, local_errno, MEMCACHED_AT,
253 memcached_literal_param("poll() returned POLLHUP"));
254 }
255
256 return memcached_set_error(*ptr, MEMCACHED_FAILURE, MEMCACHED_AT, memcached_literal_param("poll() returned a value that was not dealt with"));
257 }
258
259 if (active_fd == 0)
260 {
261 ptr->io_wait_count.timeouts++;
262 return memcached_set_error(*ptr, MEMCACHED_TIMEOUT, MEMCACHED_AT);
263 }
264
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");
268 switch (local_errno)
269 {
270 #ifdef TARGET_OS_LINUX
271 case ERESTART:
272 #endif
273 case EINTR:
274 continue;
275
276 case EFAULT:
277 case ENOMEM:
278 memcached_set_error(*ptr, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT);
279
280 case EINVAL:
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"));
282
283 default:
284 memcached_set_errno(*ptr, local_errno, MEMCACHED_AT, memcached_literal_param("poll"));
285 }
286
287 break;
288 }
289
290 memcached_quit_server(ptr, true);
291
292 if (memcached_has_error(ptr))
293 {
294 return memcached_instance_error_return(ptr);
295 }
296
297 return memcached_set_error(*ptr, MEMCACHED_CONNECTION_FAILURE, MEMCACHED_AT,
298 memcached_literal_param("number of attempts to call io_wait() failed"));
299 }
300
301 static bool io_flush(org::libmemcached::Instance* ptr,
302 const bool with_flush,
303 memcached_return_t& error)
304 {
305 /*
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..
309 */
310 {
311 WATCHPOINT_ASSERT(ptr->fd != INVALID_SOCKET);
312
313 if (memcached_purge(ptr) == false)
314 {
315 return false;
316 }
317 }
318 char *local_write_ptr= ptr->write_buffer;
319 size_t write_length= ptr->write_buffer_offset;
320
321 error= MEMCACHED_SUCCESS;
322
323 WATCHPOINT_ASSERT(ptr->fd != INVALID_SOCKET);
324
325 /* Looking for memory overflows */
326 #if defined(DEBUG)
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));
330 #endif
331
332 while (write_length)
333 {
334 WATCHPOINT_ASSERT(ptr->fd != INVALID_SOCKET);
335 WATCHPOINT_ASSERT(write_length > 0);
336
337 int flags;
338 if (with_flush)
339 {
340 flags= MSG_NOSIGNAL;
341 }
342 else
343 {
344 flags= MSG_NOSIGNAL|MSG_MORE;
345 }
346
347 ssize_t sent_length= ::send(ptr->fd, local_write_ptr, write_length, flags);
348
349 if (sent_length == SOCKET_ERROR)
350 {
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());
354 #endif
355 switch (get_socket_errno())
356 {
357 case ENOBUFS:
358 continue;
359
360 #if EWOULDBLOCK != EAGAIN
361 case EWOULDBLOCK:
362 #endif
363 case EAGAIN:
364 {
365 /*
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
369 * waiting..
370 */
371 if (repack_input_buffer(ptr) or process_input_buffer(ptr))
372 {
373 continue;
374 }
375
376 memcached_return_t rc= io_wait(ptr, MEM_WRITE);
377 if (memcached_success(rc))
378 {
379 continue;
380 }
381 else if (rc == MEMCACHED_TIMEOUT)
382 {
383 return false;
384 }
385
386 memcached_quit_server(ptr, true);
387 error= memcached_set_errno(*ptr, get_socket_errno(), MEMCACHED_AT);
388 return false;
389 }
390 case ENOTCONN:
391 case EPIPE:
392 default:
393 memcached_quit_server(ptr, true);
394 error= memcached_set_errno(*ptr, get_socket_errno(), MEMCACHED_AT);
395 WATCHPOINT_ASSERT(ptr->fd == INVALID_SOCKET);
396 return false;
397 }
398 }
399
400 ptr->io_bytes_sent+= uint32_t(sent_length);
401
402 local_write_ptr+= sent_length;
403 write_length-= uint32_t(sent_length);
404 }
405
406 WATCHPOINT_ASSERT(write_length == 0);
407 ptr->write_buffer_offset= 0;
408
409 return true;
410 }
411
412 memcached_return_t memcached_io_wait_for_write(org::libmemcached::Instance* ptr)
413 {
414 return io_wait(ptr, MEM_WRITE);
415 }
416
417 static memcached_return_t _io_fill(org::libmemcached::Instance* ptr)
418 {
419 ssize_t data_read;
420 do
421 {
422 data_read= ::recv(ptr->fd, ptr->read_buffer, MEMCACHED_MAX_BUFFER, MSG_NOSIGNAL);
423 if (data_read == SOCKET_ERROR)
424 {
425 switch (get_socket_errno())
426 {
427 case EINTR: // We just retry
428 continue;
429
430 case ETIMEDOUT: // OSX
431 #if EWOULDBLOCK != EAGAIN
432 case EWOULDBLOCK:
433 #endif
434 case EAGAIN:
435 #ifdef TARGET_OS_LINUX
436 case ERESTART:
437 #endif
438 {
439 memcached_return_t io_wait_ret;
440 if (memcached_success(io_wait_ret= io_wait(ptr, MEM_READ)))
441 {
442 continue;
443 }
444
445 return io_wait_ret;
446 }
447
448 /* fall through */
449
450 case ENOTCONN: // Programmer Error
451 WATCHPOINT_ASSERT(0);
452 case ENOTSOCK:
453 WATCHPOINT_ASSERT(0);
454 case EBADF:
455 assert_msg(ptr->fd != INVALID_SOCKET, "Programmer error, invalid socket");
456 case EINVAL:
457 case EFAULT:
458 case ECONNREFUSED:
459 default:
460 memcached_quit_server(ptr, true);
461 memcached_set_errno(*ptr, get_socket_errno(), MEMCACHED_AT);
462 break;
463 }
464
465 return memcached_instance_error_return(ptr);
466 }
467 else if (data_read == 0)
468 {
469 /*
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.
477 */
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"));
481 }
482 ptr->io_wait_count._bytes_read+= data_read;
483 } while (data_read <= 0);
484
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;
489
490 return MEMCACHED_SUCCESS;
491 }
492
493 memcached_return_t memcached_io_read(org::libmemcached::Instance* ptr,
494 void *buffer, size_t length, ssize_t& nread)
495 {
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);
499
500 if (ptr->fd == INVALID_SOCKET)
501 {
502 #if 0
503 assert_msg(int(ptr->state) <= int(MEMCACHED_SERVER_STATE_ADDRINFO), "Programmer error, invalid socket state");
504 #endif
505 return MEMCACHED_CONNECTION_FAILURE;
506 }
507
508 while (length)
509 {
510 if (ptr->read_buffer_length == 0)
511 {
512 memcached_return_t io_fill_ret;
513 if (memcached_fatal(io_fill_ret= _io_fill(ptr)))
514 {
515 nread= -1;
516 return io_fill_ret;
517 }
518 }
519
520 if (length > 1)
521 {
522 size_t difference= (length > ptr->read_buffer_length) ? ptr->read_buffer_length : length;
523
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;
529 }
530 else
531 {
532 *buffer_ptr= *ptr->read_ptr;
533 ptr->read_ptr++;
534 ptr->read_buffer_length--;
535 buffer_ptr++;
536 break;
537 }
538 }
539
540 nread= ssize_t(buffer_ptr - (char*)buffer);
541
542 return MEMCACHED_SUCCESS;
543 }
544
545 memcached_return_t memcached_io_slurp(org::libmemcached::Instance* ptr)
546 {
547 assert_msg(ptr, "Programmer error, invalid Instance");
548 assert(memcached_is_udp(ptr->root) == false);
549
550 if (ptr->fd == INVALID_SOCKET)
551 {
552 assert_msg(int(ptr->state) <= int(MEMCACHED_SERVER_STATE_ADDRINFO), "Invalid socket state");
553 return MEMCACHED_CONNECTION_FAILURE;
554 }
555
556 ssize_t data_read;
557 char buffer[MEMCACHED_MAX_BUFFER];
558 do
559 {
560 data_read= ::recv(ptr->fd, ptr->read_buffer, sizeof(buffer), MSG_NOSIGNAL);
561 if (data_read == SOCKET_ERROR)
562 {
563 switch (get_socket_errno())
564 {
565 case EINTR: // We just retry
566 continue;
567
568 case ETIMEDOUT: // OSX
569 #if EWOULDBLOCK != EAGAIN
570 case EWOULDBLOCK:
571 #endif
572 case EAGAIN:
573 #ifdef TARGET_OS_LINUX
574 case ERESTART:
575 #endif
576 if (memcached_success(io_wait(ptr, MEM_READ)))
577 {
578 continue;
579 }
580 return MEMCACHED_IN_PROGRESS;
581
582 /* fall through */
583
584 case ENOTCONN: // Programmer Error
585 assert(0);
586 case ENOTSOCK:
587 assert(0);
588 case EBADF:
589 assert_msg(ptr->fd != INVALID_SOCKET, "Invalid socket state");
590 case EINVAL:
591 case EFAULT:
592 case ECONNREFUSED:
593 default:
594 return MEMCACHED_CONNECTION_FAILURE; // We want this!
595 }
596 }
597 } while (data_read > 0);
598
599 return MEMCACHED_CONNECTION_FAILURE;
600 }
601
602 static bool _io_write(org::libmemcached::Instance* ptr,
603 const void *buffer, size_t length, bool with_flush,
604 size_t& written)
605 {
606 assert(ptr->fd != INVALID_SOCKET);
607 assert(memcached_is_udp(ptr->root) == false);
608
609 const char *buffer_ptr= static_cast<const char *>(buffer);
610
611 const size_t original_length= length;
612
613 while (length)
614 {
615 char *write_ptr;
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;
619
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;
625
626 if (ptr->write_buffer_offset == buffer_end)
627 {
628 WATCHPOINT_ASSERT(ptr->fd != INVALID_SOCKET);
629
630 memcached_return_t rc;
631 if (io_flush(ptr, with_flush, rc) == false)
632 {
633 written= original_length -length;
634 return false;
635 }
636 }
637 }
638
639 if (with_flush)
640 {
641 memcached_return_t rc;
642 WATCHPOINT_ASSERT(ptr->fd != INVALID_SOCKET);
643 if (io_flush(ptr, with_flush, rc) == false)
644 {
645 written= original_length -length;
646 return false;
647 }
648 }
649
650 written= original_length -length;
651
652 return true;
653 }
654
655 bool memcached_io_write(org::libmemcached::Instance* ptr)
656 {
657 size_t written;
658 return _io_write(ptr, NULL, 0, true, written);
659 }
660
661 ssize_t memcached_io_write(org::libmemcached::Instance* ptr,
662 const void *buffer, const size_t length, const bool with_flush)
663 {
664 size_t written;
665
666 if (_io_write(ptr, buffer, length, with_flush, written) == false)
667 {
668 return -1;
669 }
670
671 return ssize_t(written);
672 }
673
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)
677 {
678 ssize_t complete_total= 0;
679 ssize_t total= 0;
680
681 for (size_t x= 0; x < number_of; x++, vector++)
682 {
683 complete_total+= vector->length;
684 if (vector->length)
685 {
686 size_t written;
687 if ((_io_write(ptr, vector->buffer, vector->length, false, written)) == false)
688 {
689 return false;
690 }
691 total+= written;
692 }
693 }
694
695 if (with_flush)
696 {
697 if (memcached_io_write(ptr) == false)
698 {
699 return false;
700 }
701 }
702
703 return (complete_total == total);
704 }
705
706
707 void memcached_io_close(org::libmemcached::Instance* ptr)
708 {
709 if (ptr->fd == INVALID_SOCKET)
710 {
711 return;
712 }
713
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)
716 {
717 WATCHPOINT_NUMBER(ptr->fd);
718 WATCHPOINT_ERRNO(get_socket_errno());
719 WATCHPOINT_ASSERT(get_socket_errno());
720 }
721
722 if (closesocket(ptr->fd) == SOCKET_ERROR)
723 {
724 WATCHPOINT_ERRNO(get_socket_errno());
725 }
726 ptr->state= MEMCACHED_SERVER_STATE_NEW;
727 ptr->fd= INVALID_SOCKET;
728 }
729
730 org::libmemcached::Instance* memcached_io_get_readable_server(memcached_st *memc)
731 {
732 #define MAX_SERVERS_TO_POLL 100
733 struct pollfd fds[MAX_SERVERS_TO_POLL];
734 nfds_t host_index= 0;
735
736 for (uint32_t x= 0; x < memcached_server_count(memc) and host_index < MAX_SERVERS_TO_POLL; ++x)
737 {
738 org::libmemcached::Instance* instance= memcached_instance_fetch(memc, x);
739
740 if (instance->read_buffer_length > 0) /* I have data in the buffer */
741 {
742 return instance;
743 }
744
745 if (instance->response_count() > 0)
746 {
747 fds[host_index].events= POLLIN;
748 fds[host_index].revents= 0;
749 fds[host_index].fd= instance->fd;
750 ++host_index;
751 }
752 }
753
754 if (host_index < 2)
755 {
756 /* We have 0 or 1 server with pending events.. */
757 for (uint32_t x= 0; x< memcached_server_count(memc); ++x)
758 {
759 org::libmemcached::Instance* instance= memcached_instance_fetch(memc, x);
760
761 if (instance->response_count() > 0)
762 {
763 return instance;
764 }
765 }
766
767 return NULL;
768 }
769
770 int error= poll(fds, host_index, memc->poll_timeout);
771 switch (error)
772 {
773 case -1:
774 memcached_set_errno(*memc, get_socket_errno(), MEMCACHED_AT);
775 /* FALLTHROUGH */
776 case 0:
777 break;
778
779 default:
780 for (nfds_t x= 0; x < host_index; ++x)
781 {
782 if (fds[x].revents & POLLIN)
783 {
784 for (uint32_t y= 0; y < memcached_server_count(memc); ++y)
785 {
786 org::libmemcached::Instance* instance= memcached_instance_fetch(memc, y);
787
788 if (instance->fd == fds[x].fd)
789 {
790 return instance;
791 }
792 }
793 }
794 }
795 }
796
797 return NULL;
798 }
799
800 /*
801 Eventually we will just kill off the server with the problem.
802 */
803 void memcached_io_reset(org::libmemcached::Instance* ptr)
804 {
805 memcached_quit_server(ptr, true);
806 }
807
808 /**
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.
811 */
812 memcached_return_t memcached_safe_read(org::libmemcached::Instance* ptr,
813 void *dta,
814 const size_t size)
815 {
816 size_t offset= 0;
817 char *data= static_cast<char *>(dta);
818
819 while (offset < size)
820 {
821 ssize_t nread;
822 memcached_return_t rc;
823
824 while (memcached_continue(rc= memcached_io_read(ptr, data + offset, size - offset, nread))) { };
825
826 if (memcached_failed(rc))
827 {
828 return rc;
829 }
830
831 offset+= size_t(nread);
832 }
833
834 return MEMCACHED_SUCCESS;
835 }
836
837 memcached_return_t memcached_io_readline(org::libmemcached::Instance* ptr,
838 char *buffer_ptr,
839 size_t size,
840 size_t& total_nr)
841 {
842 total_nr= 0;
843 bool line_complete= false;
844
845 while (line_complete == false)
846 {
847 if (ptr->read_buffer_length == 0)
848 {
849 /*
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
852 * the logic.
853 */
854 ssize_t nread;
855 memcached_return_t rc= memcached_io_read(ptr, buffer_ptr, 1, nread);
856 if (memcached_failed(rc) and rc == MEMCACHED_IN_PROGRESS)
857 {
858 memcached_quit_server(ptr, true);
859 return memcached_set_error(*ptr, rc, MEMCACHED_AT);
860 }
861 else if (memcached_failed(rc))
862 {
863 return rc;
864 }
865
866 if (*buffer_ptr == '\n')
867 {
868 line_complete= true;
869 }
870
871 ++buffer_ptr;
872 ++total_nr;
873 }
874
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)
877 {
878 *buffer_ptr = *ptr->read_ptr;
879 if (*buffer_ptr == '\n')
880 {
881 line_complete = true;
882 }
883 --ptr->read_buffer_length;
884 ++ptr->read_ptr;
885 ++total_nr;
886 ++buffer_ptr;
887 }
888
889 if (total_nr == size)
890 {
891 return MEMCACHED_PROTOCOL_ERROR;
892 }
893 }
894
895 return MEMCACHED_SUCCESS;
896 }