Small cleanup in string.h and converted result_st macro to inline.
[awesomized/libmemcached] / libmemcached / io.c
1 /* LibMemcached
2 * Copyright (C) 2006-2009 Brian Aker
3 * All rights reserved.
4 *
5 * Use and distribution licensed under the BSD license. See
6 * the COPYING file in the parent directory for full text.
7 *
8 * Summary: Server IO, Not public!
9 *
10 */
11
12
13 #include "common.h"
14 #include <sys/select.h>
15 #include <poll.h>
16
17 typedef enum {
18 MEM_READ,
19 MEM_WRITE
20 } memc_read_or_write;
21
22 static ssize_t io_flush(memcached_server_instance_st *ptr, memcached_return_t *error);
23 static void increment_udp_message_id(memcached_server_instance_st *ptr);
24
25 static memcached_return_t io_wait(memcached_server_instance_st *ptr,
26 memc_read_or_write read_or_write)
27 {
28 struct pollfd fds= {
29 .fd= ptr->fd,
30 .events = POLLIN
31 };
32 int error;
33
34 unlikely (read_or_write == MEM_WRITE) /* write */
35 fds.events= POLLOUT;
36
37 /*
38 ** We are going to block on write, but at least on Solaris we might block
39 ** on write if we haven't read anything from our input buffer..
40 ** Try to purge the input buffer if we don't do any flow control in the
41 ** application layer (just sending a lot of data etc)
42 ** The test is moved down in the purge function to avoid duplication of
43 ** the test.
44 */
45 if (read_or_write == MEM_WRITE)
46 {
47 memcached_return_t rc= memcached_purge(ptr);
48 if (rc != MEMCACHED_SUCCESS && rc != MEMCACHED_STORED)
49 return MEMCACHED_FAILURE;
50 }
51
52 int timeout= ptr->root->poll_timeout;
53 if (ptr->root->flags.no_block == false)
54 timeout= -1;
55
56 error= poll(&fds, 1, timeout);
57
58 if (error == 1)
59 return MEMCACHED_SUCCESS;
60 else if (error == 0)
61 return MEMCACHED_TIMEOUT;
62
63 /* Imposssible for anything other then -1 */
64 WATCHPOINT_ASSERT(error == -1);
65 memcached_quit_server(ptr, 1);
66
67 return MEMCACHED_FAILURE;
68 }
69
70 /**
71 * Try to fill the input buffer for a server with as much
72 * data as possible.
73 *
74 * @param ptr the server to pack
75 */
76 static bool repack_input_buffer(memcached_server_instance_st *ptr)
77 {
78 if (ptr->read_ptr != ptr->read_buffer)
79 {
80 /* Move all of the data to the beginning of the buffer so
81 ** that we can fit more data into the buffer...
82 */
83 memmove(ptr->read_buffer, ptr->read_ptr, ptr->read_buffer_length);
84 ptr->read_ptr= ptr->read_buffer;
85 ptr->read_data_length= ptr->read_buffer_length;
86 }
87
88 /* There is room in the buffer, try to fill it! */
89 if (ptr->read_buffer_length != MEMCACHED_MAX_BUFFER)
90 {
91 /* Just try a single read to grab what's available */
92 ssize_t nr= read(ptr->fd,
93 ptr->read_ptr + ptr->read_data_length,
94 MEMCACHED_MAX_BUFFER - ptr->read_data_length);
95
96 if (nr > 0)
97 {
98 ptr->read_data_length+= (size_t)nr;
99 ptr->read_buffer_length+= (size_t)nr;
100 return true;
101 }
102 }
103 return false;
104 }
105
106 /**
107 * If the we have callbacks connected to this server structure
108 * we may start process the input queue and fire the callbacks
109 * for the incomming messages. This function is _only_ called
110 * when the input buffer is full, so that we _know_ that we have
111 * at least _one_ message to process.
112 *
113 * @param ptr the server to star processing iput messages for
114 * @return true if we processed anything, false otherwise
115 */
116 static bool process_input_buffer(memcached_server_instance_st *ptr)
117 {
118 /*
119 ** We might be able to process some of the response messages if we
120 ** have a callback set up
121 */
122 if (ptr->root->callbacks != NULL && ptr->root->flags.use_udp == false)
123 {
124 /*
125 * We might have responses... try to read them out and fire
126 * callbacks
127 */
128 memcached_callback_st cb= *ptr->root->callbacks;
129
130 memcached_set_processing_input(ptr->root, true);
131
132 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
133 memcached_return_t error;
134 error= memcached_response(ptr, buffer, sizeof(buffer),
135 &ptr->root->result);
136
137 memcached_set_processing_input(ptr->root, false);
138
139 if (error == MEMCACHED_SUCCESS)
140 {
141 for (unsigned int x= 0; x < cb.number_of_callback; x++)
142 {
143 error= (*cb.callback[x])(ptr->root, &ptr->root->result, cb.context);
144 if (error != MEMCACHED_SUCCESS)
145 break;
146 }
147
148 /* @todo what should I do with the error message??? */
149 }
150 /* @todo what should I do with other error messages?? */
151 return true;
152 }
153
154 return false;
155 }
156
157 static inline void memcached_io_cork_push(memcached_server_st *ptr)
158 {
159 #ifdef CORK
160 if (ptr->root->flags.cork == false || ptr->state.is_corked)
161 return;
162
163 int enable= 1;
164 int err= setsockopt(ptr->fd, IPPROTO_TCP, CORK,
165 &enable, (socklen_t)sizeof(int));
166 if (! err)
167 ptr->state.is_corked= true;
168
169 WATCHPOINT_ASSERT(ptr->state.is_corked == true);
170 #else
171 (void)ptr;
172 #endif
173 }
174
175 static inline void memcached_io_cork_pop(memcached_server_st *ptr)
176 {
177 #ifdef CORK
178 if (ptr->root->flags.cork == false || ptr->state.is_corked == false)
179 return;
180
181 int enable= 0;
182 int err= setsockopt(ptr->fd, IPPROTO_TCP, CORK,
183 &enable, (socklen_t)sizeof(int));
184 if (! err)
185 ptr->state.is_corked= false;
186
187 WATCHPOINT_ASSERT(ptr->state.is_corked == false);
188 #else
189 (void)ptr;
190 #endif
191 }
192
193 #ifdef UNUSED
194 void memcached_io_preread(memcached_st *ptr)
195 {
196 unsigned int x;
197
198 return;
199
200 for (x= 0; x < memcached_server_count(ptr); x++)
201 {
202 if (memcached_server_response_count(ptr, x) &&
203 ptr->hosts[x].read_data_length < MEMCACHED_MAX_BUFFER )
204 {
205 size_t data_read;
206
207 data_read= read(ptr->hosts[x].fd,
208 ptr->hosts[x].read_ptr + ptr->hosts[x].read_data_length,
209 MEMCACHED_MAX_BUFFER - ptr->hosts[x].read_data_length);
210 if (data_read == -1)
211 continue;
212
213 ptr->hosts[x].read_buffer_length+= data_read;
214 ptr->hosts[x].read_data_length+= data_read;
215 }
216 }
217 }
218 #endif
219
220 memcached_return_t memcached_io_read(memcached_server_instance_st *ptr,
221 void *buffer, size_t length, ssize_t *nread)
222 {
223 char *buffer_ptr;
224
225 buffer_ptr= buffer;
226
227 while (length)
228 {
229 if (!ptr->read_buffer_length)
230 {
231 ssize_t data_read;
232
233 while (1)
234 {
235 data_read= read(ptr->fd, ptr->read_buffer, MEMCACHED_MAX_BUFFER);
236 if (data_read > 0)
237 break;
238 else if (data_read == -1)
239 {
240 ptr->cached_errno= errno;
241 memcached_return_t rc= MEMCACHED_UNKNOWN_READ_FAILURE;
242 switch (errno)
243 {
244 case EAGAIN:
245 case EINTR:
246 if ((rc= io_wait(ptr, MEM_READ)) == MEMCACHED_SUCCESS)
247 continue;
248 /* fall through */
249
250 default:
251 {
252 memcached_quit_server(ptr, 1);
253 *nread= -1;
254 return rc;
255 }
256 }
257 }
258 else
259 {
260 /*
261 EOF. Any data received so far is incomplete
262 so discard it. This always reads by byte in case of TCP
263 and protocol enforcement happens at memcached_response()
264 looking for '\n'. We do not care for UDB which requests 8 bytes
265 at once. Generally, this means that connection went away. Since
266 for blocking I/O we do not return 0 and for non-blocking case
267 it will return EGAIN if data is not immediatly available.
268 */
269 memcached_quit_server(ptr, 1);
270 *nread= -1;
271 return MEMCACHED_UNKNOWN_READ_FAILURE;
272 }
273 }
274
275 ptr->io_bytes_sent = 0;
276 ptr->read_data_length= (size_t) data_read;
277 ptr->read_buffer_length= (size_t) data_read;
278 ptr->read_ptr= ptr->read_buffer;
279 }
280
281 if (length > 1)
282 {
283 size_t difference;
284
285 difference= (length > ptr->read_buffer_length) ? ptr->read_buffer_length : length;
286
287 memcpy(buffer_ptr, ptr->read_ptr, difference);
288 length -= difference;
289 ptr->read_ptr+= difference;
290 ptr->read_buffer_length-= difference;
291 buffer_ptr+= difference;
292 }
293 else
294 {
295 *buffer_ptr= *ptr->read_ptr;
296 ptr->read_ptr++;
297 ptr->read_buffer_length--;
298 buffer_ptr++;
299 break;
300 }
301 }
302
303 ptr->server_failure_counter= 0;
304 *nread = (ssize_t)(buffer_ptr - (char*)buffer);
305 return MEMCACHED_SUCCESS;
306 }
307
308 ssize_t memcached_io_write(memcached_server_instance_st *ptr,
309 const void *buffer, size_t length, char with_flush)
310 {
311 size_t original_length;
312 const char* buffer_ptr;
313
314 WATCHPOINT_ASSERT(ptr->fd != -1);
315
316 original_length= length;
317 buffer_ptr= buffer;
318
319 /* more writable data is coming if a flush isn't required, so delay send */
320 if (! with_flush)
321 {
322 memcached_io_cork_push(ptr);
323 }
324
325 while (length)
326 {
327 char *write_ptr;
328 size_t should_write;
329 size_t buffer_end;
330
331 if (ptr->type == MEMCACHED_CONNECTION_UDP)
332 {
333 //UDP does not support partial writes
334 buffer_end= MAX_UDP_DATAGRAM_LENGTH;
335 should_write= length;
336 if (ptr->write_buffer_offset + should_write > buffer_end)
337 return -1;
338 }
339 else
340 {
341 buffer_end= MEMCACHED_MAX_BUFFER;
342 should_write= buffer_end - ptr->write_buffer_offset;
343 should_write= (should_write < length) ? should_write : length;
344 }
345
346 write_ptr= ptr->write_buffer + ptr->write_buffer_offset;
347 memcpy(write_ptr, buffer_ptr, should_write);
348 ptr->write_buffer_offset+= should_write;
349 buffer_ptr+= should_write;
350 length-= should_write;
351
352 if (ptr->write_buffer_offset == buffer_end && ptr->type != MEMCACHED_CONNECTION_UDP)
353 {
354 memcached_return_t rc;
355 ssize_t sent_length;
356
357 WATCHPOINT_ASSERT(ptr->fd != -1);
358 sent_length= io_flush(ptr, &rc);
359 if (sent_length == -1)
360 return -1;
361
362 /* If io_flush calls memcached_purge, sent_length may be 0 */
363 unlikely (sent_length != 0)
364 {
365 WATCHPOINT_ASSERT(sent_length == (ssize_t)buffer_end);
366 }
367 }
368 }
369
370 if (with_flush)
371 {
372 memcached_return_t rc;
373 WATCHPOINT_ASSERT(ptr->fd != -1);
374 if (io_flush(ptr, &rc) == -1)
375 {
376 return -1;
377 }
378
379 memcached_io_cork_pop(ptr);
380 }
381
382 return (ssize_t) original_length;
383 }
384
385 memcached_return_t memcached_io_close(memcached_server_instance_st *ptr)
386 {
387 if (ptr->fd == -1)
388 {
389 return MEMCACHED_SUCCESS;
390 }
391
392 /* in case of death shutdown to avoid blocking at close() */
393 if (shutdown(ptr->fd, SHUT_RDWR) == -1 && errno != ENOTCONN)
394 {
395 WATCHPOINT_NUMBER(ptr->fd);
396 WATCHPOINT_ERRNO(errno);
397 WATCHPOINT_ASSERT(errno);
398 }
399
400 if (close(ptr->fd) == -1)
401 {
402 WATCHPOINT_ERRNO(errno);
403 }
404
405 return MEMCACHED_SUCCESS;
406 }
407
408 memcached_server_instance_st *memcached_io_get_readable_server(memcached_st *memc)
409 {
410 #define MAX_SERVERS_TO_POLL 100
411 struct pollfd fds[MAX_SERVERS_TO_POLL];
412 unsigned int host_index= 0;
413
414 for (uint32_t x= 0;
415 x< memcached_server_count(memc) && host_index < MAX_SERVERS_TO_POLL;
416 ++x)
417 {
418 memcached_server_instance_st *instance=
419 memcached_server_instance_fetch(memc, x);
420
421 if (instance->read_buffer_length > 0) /* I have data in the buffer */
422 return instance;
423
424 if (memcached_server_response_count(instance) > 0)
425 {
426 fds[host_index].events = POLLIN;
427 fds[host_index].revents = 0;
428 fds[host_index].fd = instance->fd;
429 ++host_index;
430 }
431 }
432
433 if (host_index < 2)
434 {
435 /* We have 0 or 1 server with pending events.. */
436 for (uint32_t x= 0; x< memcached_server_count(memc); ++x)
437 {
438 memcached_server_instance_st *instance=
439 memcached_server_instance_fetch(memc, x);
440
441 if (memcached_server_response_count(instance) > 0)
442 {
443 return instance;
444 }
445 }
446
447 return NULL;
448 }
449
450 int err= poll(fds, host_index, memc->poll_timeout);
451 switch (err) {
452 case -1:
453 memc->cached_errno = errno;
454 /* FALLTHROUGH */
455 case 0:
456 break;
457 default:
458 for (size_t x= 0; x < host_index; ++x)
459 {
460 if (fds[x].revents & POLLIN)
461 {
462 for (uint32_t y= 0; y < memcached_server_count(memc); ++y)
463 {
464 memcached_server_instance_st *instance=
465 memcached_server_instance_fetch(memc, y);
466
467 if (instance->fd == fds[x].fd)
468 return instance;
469 }
470 }
471 }
472 }
473
474 return NULL;
475 }
476
477 static ssize_t io_flush(memcached_server_instance_st *ptr,
478 memcached_return_t *error)
479 {
480 /*
481 ** We might want to purge the input buffer if we haven't consumed
482 ** any output yet... The test for the limits is the purge is inline
483 ** in the purge function to avoid duplicating the logic..
484 */
485 {
486 memcached_return_t rc;
487 WATCHPOINT_ASSERT(ptr->fd != -1);
488 rc= memcached_purge(ptr);
489
490 if (rc != MEMCACHED_SUCCESS && rc != MEMCACHED_STORED)
491 return -1;
492 }
493 ssize_t sent_length;
494 size_t return_length;
495 char *local_write_ptr= ptr->write_buffer;
496 size_t write_length= ptr->write_buffer_offset;
497
498 *error= MEMCACHED_SUCCESS;
499
500 WATCHPOINT_ASSERT(ptr->fd != -1);
501
502 // UDP Sanity check, make sure that we are not sending somthing too big
503 if (ptr->type == MEMCACHED_CONNECTION_UDP && write_length > MAX_UDP_DATAGRAM_LENGTH)
504 return -1;
505
506 if (ptr->write_buffer_offset == 0 || (ptr->type == MEMCACHED_CONNECTION_UDP
507 && ptr->write_buffer_offset == UDP_DATAGRAM_HEADER_LENGTH))
508 return 0;
509
510 /* Looking for memory overflows */
511 #if defined(DEBUG)
512 if (write_length == MEMCACHED_MAX_BUFFER)
513 WATCHPOINT_ASSERT(ptr->write_buffer == local_write_ptr);
514 WATCHPOINT_ASSERT((ptr->write_buffer + MEMCACHED_MAX_BUFFER) >= (local_write_ptr + write_length));
515 #endif
516
517 return_length= 0;
518 while (write_length)
519 {
520 WATCHPOINT_ASSERT(ptr->fd != -1);
521 WATCHPOINT_ASSERT(write_length > 0);
522 sent_length= 0;
523 if (ptr->type == MEMCACHED_CONNECTION_UDP)
524 increment_udp_message_id(ptr);
525 sent_length= write(ptr->fd, local_write_ptr, write_length);
526
527 if (sent_length == -1)
528 {
529 ptr->cached_errno= errno;
530 switch (errno)
531 {
532 case ENOBUFS:
533 continue;
534 case EAGAIN:
535 {
536 /*
537 * We may be blocked on write because the input buffer
538 * is full. Let's check if we have room in our input
539 * buffer for more data and retry the write before
540 * waiting..
541 */
542 if (repack_input_buffer(ptr) ||
543 process_input_buffer(ptr))
544 continue;
545
546 memcached_return_t rc;
547 rc= io_wait(ptr, MEM_WRITE);
548
549 if (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_TIMEOUT)
550 continue;
551
552 memcached_quit_server(ptr, 1);
553 return -1;
554 }
555 default:
556 memcached_quit_server(ptr, 1);
557 *error= MEMCACHED_ERRNO;
558 return -1;
559 }
560 }
561
562 if (ptr->type == MEMCACHED_CONNECTION_UDP &&
563 (size_t)sent_length != write_length)
564 {
565 memcached_quit_server(ptr, 1);
566 return -1;
567 }
568
569 ptr->io_bytes_sent += (uint32_t) sent_length;
570
571 local_write_ptr+= sent_length;
572 write_length-= (uint32_t) sent_length;
573 return_length+= (uint32_t) sent_length;
574 }
575
576 WATCHPOINT_ASSERT(write_length == 0);
577 // Need to study this assert() WATCHPOINT_ASSERT(return_length ==
578 // ptr->write_buffer_offset);
579
580 // if we are a udp server, the begining of the buffer is reserverd for
581 // the upd frame header
582 if (ptr->type == MEMCACHED_CONNECTION_UDP)
583 ptr->write_buffer_offset= UDP_DATAGRAM_HEADER_LENGTH;
584 else
585 ptr->write_buffer_offset= 0;
586
587 return (ssize_t) return_length;
588 }
589
590 /*
591 Eventually we will just kill off the server with the problem.
592 */
593 void memcached_io_reset(memcached_server_instance_st *ptr)
594 {
595 memcached_quit_server(ptr, 1);
596 }
597
598 /**
599 * Read a given number of bytes from the server and place it into a specific
600 * buffer. Reset the IO channel on this server if an error occurs.
601 */
602 memcached_return_t memcached_safe_read(memcached_server_instance_st *ptr,
603 void *dta,
604 size_t size)
605 {
606 size_t offset= 0;
607 char *data= dta;
608
609 while (offset < size)
610 {
611 ssize_t nread;
612 memcached_return_t rc= memcached_io_read(ptr, data + offset, size - offset,
613 &nread);
614 if (rc != MEMCACHED_SUCCESS)
615 return rc;
616
617 offset+= (size_t) nread;
618 }
619
620 return MEMCACHED_SUCCESS;
621 }
622
623 memcached_return_t memcached_io_readline(memcached_server_instance_st *ptr,
624 char *buffer_ptr,
625 size_t size)
626 {
627 bool line_complete= false;
628 size_t total_nr= 0;
629
630 while (!line_complete)
631 {
632 if (ptr->read_buffer_length == 0)
633 {
634 /*
635 * We don't have any data in the buffer, so let's fill the read
636 * buffer. Call the standard read function to avoid duplicating
637 * the logic.
638 */
639 ssize_t nread;
640 memcached_return_t rc= memcached_io_read(ptr, buffer_ptr, 1, &nread);
641 if (rc != MEMCACHED_SUCCESS)
642 return rc;
643
644 if (*buffer_ptr == '\n')
645 line_complete= true;
646
647 ++buffer_ptr;
648 ++total_nr;
649 }
650
651 /* Now let's look in the buffer and copy as we go! */
652 while (ptr->read_buffer_length && total_nr < size && !line_complete)
653 {
654 *buffer_ptr = *ptr->read_ptr;
655 if (*buffer_ptr == '\n')
656 line_complete = true;
657 --ptr->read_buffer_length;
658 ++ptr->read_ptr;
659 ++total_nr;
660 ++buffer_ptr;
661 }
662
663 if (total_nr == size)
664 return MEMCACHED_PROTOCOL_ERROR;
665 }
666
667 return MEMCACHED_SUCCESS;
668 }
669
670 /*
671 * The udp request id consists of two seperate sections
672 * 1) The thread id
673 * 2) The message number
674 * The thread id should only be set when the memcached_st struct is created
675 * and should not be changed.
676 *
677 * The message num is incremented for each new message we send, this function
678 * extracts the message number from message_id, increments it and then
679 * writes the new value back into the header
680 */
681 static void increment_udp_message_id(memcached_server_instance_st *ptr)
682 {
683 struct udp_datagram_header_st *header= (struct udp_datagram_header_st *)ptr->write_buffer;
684 uint16_t cur_req= get_udp_datagram_request_id(header);
685 int msg_num= get_msg_num_from_request_id(cur_req);
686 int thread_id= get_thread_id_from_request_id(cur_req);
687
688 if (((++msg_num) & UDP_REQUEST_ID_THREAD_MASK) != 0)
689 msg_num= 0;
690
691 header->request_id= htons((uint16_t) (thread_id | msg_num));
692 }
693
694 memcached_return_t memcached_io_init_udp_header(memcached_server_instance_st *ptr, uint16_t thread_id)
695 {
696 if (thread_id > UDP_REQUEST_ID_MAX_THREAD_ID)
697 return MEMCACHED_FAILURE;
698
699 struct udp_datagram_header_st *header= (struct udp_datagram_header_st *)ptr->write_buffer;
700 header->request_id= htons((uint16_t) (generate_udp_request_thread_id(thread_id)));
701 header->num_datagrams= htons(1);
702 header->sequence_number= htons(0);
703
704 return MEMCACHED_SUCCESS;
705 }