Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: d3dd0bb084
Fetching contributors…

Cannot retrieve contributors at this time

file 733 lines (649 sloc) 21.097 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/

/*
* Portions Copyright 2009 Matt Ingenthron
*/

#include "config.h"

#include "libmemc.h"

#ifdef HAVE_MEMCACHED_PROTOCOL_BINARY_H
#include <memcached/protocol_binary.h>
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <sys/uio.h>

struct Server {
   int sock;
   struct addrinfo *addrinfo;
   const char *errmsg;
   const char *peername;
   char *buffer;
   size_t buffersize;
};

enum StoreCommand {add, set, replace};

struct Memcache {
   struct Server** servers;
   enum Protocol protocol;
   int no_servers;
};

static struct Server* server_create(const char *name, in_port_t port);
static void server_destroy(struct Server *server);
static int textual_store(struct Server* server, enum StoreCommand cmd,
                        const struct Item *item);
static int textual_get(struct Server* server, struct Item* item);
static int binary_store(struct Server* server, enum StoreCommand cmd,
                        const struct Item *item);
static int binary_get(struct Server* server, struct Item* item);
static int libmemc_store(struct Memcache* handle, enum StoreCommand cmd, const struct Item *item);
static struct Server *get_server(struct Memcache *handle, const char *key);
static int server_connect(struct Server *server);


/**
* External interface
*/
struct Memcache* libmemc_create(enum Protocol protocol) {
   struct Memcache* ret = calloc(1, sizeof(struct Memcache));
   if (ret != NULL) {
      ret->protocol = protocol;
   }
   return ret;
}

void libmemc_destroy(struct Memcache* handle) {
   for (int ii = 0; ii < handle->no_servers; ++ii) {
      server_destroy(handle->servers[ii]);
   }
   free(handle);
}

int libmemc_add_server(struct Memcache *handle, const char *host, in_port_t port) {
   struct Server** servers = calloc(handle->no_servers + 1, sizeof(struct Server));
   struct Server** old = handle->servers;

   if (servers == 0) {
      return -1;
   }

   for (int ii = 0; ii < handle->no_servers; ++ii) {
      servers[ii] = handle->servers[ii];
   }

   handle->servers = servers;
   free(old);

   struct Server *server = server_create(host, port);
   if (server != NULL) {
      handle->servers[handle->no_servers++] = server;
   }

   return 0;
}

int libmemc_add(struct Memcache *handle, const struct Item *item) {
   return libmemc_store(handle, add, item);
}

int libmemc_set(struct Memcache *handle, const struct Item *item) {
   return libmemc_store(handle, set, item);
}

int libmemc_replace(struct Memcache *handle, const struct Item *item) {
   return libmemc_store(handle, replace, item);
}

int libmemc_get(struct Memcache *handle, struct Item *item) {
   struct Server* server = get_server(handle, item->key);
   if (server == NULL) {
      return -1;
   } else {
      if (server->sock == -1) {
         if (server_connect(server) == -1) {
            fprintf(stderr, "%s\n", server->errmsg);
            fflush(stderr);
            return -1;
         }
      }

      if (handle->protocol == Binary) {
         return binary_get(server, item);
      } else {
         return textual_get(server, item);
      }
   }
}

static struct addrinfo *lookuphost(const char *hostname, in_port_t port)
{
    struct addrinfo *ai = 0;
    struct addrinfo hints = {
        .ai_flags = AI_PASSIVE|AI_ADDRCONFIG,
        .ai_family = AF_UNSPEC,
        .ai_protocol = IPPROTO_TCP,
        .ai_socktype = SOCK_STREAM };
    char service[NI_MAXSERV];
    int error;

    (void)snprintf(service, NI_MAXSERV, "%d", port);
    if ((error = getaddrinfo(hostname, service, &hints, &ai)) != 0) {
       if (error != EAI_SYSTEM) {
          fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
       } else {
          perror("getaddrinfo()");
       }
    }

    return ai;
}

int libmemc_connect_server(const char *hostname, in_port_t port)
{
    struct addrinfo *ai = lookuphost(hostname, port);
    int sock = -1;
    if (ai != NULL) {
       if ((sock = socket(ai->ai_family, ai->ai_socktype,
                          ai->ai_protocol)) != -1) {
          if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
             fprintf(stderr, "Failed to connect socket: %s\n",
                     strerror(errno));
             close(sock);
             sock = -1;
          }
       } else {
          fprintf(stderr, "Failed to create socket: %s\n", strerror(errno));
       }

       freeaddrinfo(ai);
    }
    return sock;
}

/**
* Internal functions used by both protocols
*/
static uint32_t simplehash(const char *key) {
   if (key == 0) {
      return 0;
   }
   uint32_t ret = 0;
   for (ret = *key; *key != 0; ++key) {
      ret = (ret << 4) + *key;
   }
   return ret;
}

static struct Server *get_server(struct Memcache *handle, const char *key) {
   if (handle->no_servers == 1) {
      return handle->servers[0];
   } else if (handle->no_servers > 0) {
      int idx = simplehash(key) % handle->no_servers;
      return handle->servers[idx];
   } else {
      return NULL;
   }
}

static int libmemc_store(struct Memcache* handle, enum StoreCommand cmd,
                         const struct Item *item) {
   struct Server* server = get_server(handle, item->key);
   if (server == NULL) {
      return -1;
   } else {
      if (server->sock == -1) {
         if (server_connect(server) == -1) {
            return -1;
         }
      }

      if (handle->protocol == Binary) {
         return binary_store(server, cmd, item);
      } else {
         return textual_store(server, cmd, item);
      }
   }
}

static size_t server_receive(struct Server* server, char* data, size_t size, int line);
static int server_sendv(struct Server* server, struct iovec *iov, int iovcnt);
static void server_disconnect(struct Server *server);

void server_destroy(struct Server *server) {
   if (server != NULL) {
      if (server->sock != -1) {
         close(server->sock);
      }
      free(server->buffer);
      free(server);
   }
}

struct Server* server_create(const char *name, in_port_t port) {
   struct addrinfo* ai = lookuphost(name, port);
   struct Server* ret = NULL;
   if (ai != NULL) {
      ret = calloc(1, sizeof(struct Server));
      if (ret != 0) {
         char buffer[1024];
         ret->sock = -1;
         ret->errmsg = 0;
         ret->addrinfo = ai;
         sprintf(buffer, "%s:%d", name, port);
         ret->peername = strdup(buffer);
         ret->buffer = malloc(65 * 1024);
         ret->buffersize = 65 * 1024;
         server_connect(ret);
         if (ret->buffer == NULL) {
            server_destroy(ret);
            ret = 0;
         }
      }
   }

   return ret;
}

static void server_disconnect(struct Server *server) {
   if (server->sock != -1) {
      (void)close(server->sock);
      server->sock = -1;
   }
}

static int server_connect(struct Server *server)
{
   int flag = 1;

   if ((server->sock = socket(server->addrinfo->ai_family,
                              server->addrinfo->ai_socktype,
                              server->addrinfo->ai_protocol)) == -1) {
      char errmsg[1024];
      sprintf(errmsg, "Failed to create socket: %s", strerror(errno));
      server->errmsg = strdup(errmsg);
      return -1;
   }

   if (setsockopt(server->sock, IPPROTO_TCP, TCP_NODELAY,
                  &flag, sizeof(flag)) == -1) {
      perror("Failed to set TCP_NODELAY");
   }

   if (connect(server->sock, server->addrinfo->ai_addr,
               server->addrinfo->ai_addrlen) == -1) {
      char errmsg[1024];
      sprintf(errmsg, "Failed to connect socket: %s", strerror(errno));
      server->errmsg = strdup(errmsg);
      server_disconnect(server);
      return -1;
   }

   return 0;
}

static int server_sendv(struct Server* server, struct iovec *iov, int iovcnt) {
#ifdef WIN32
   // @todo I might have a scattered IO function on windows...
   for (int ii = 0; ii < iovcnt; ++ii) {
      if (send(server, iov[ii].iov_base, iov[ii].iov_len) != 0) {
         return -1;
      }
   }
#else
   // @todo Verify implementation if the writev returns with partitial
   // writes!
   size_t size = 0;
   for (int ii = 0; ii < iovcnt; ++ ii) {
      size += iov[ii].iov_len;
   }

   do {
      ssize_t sent = writev(server->sock, iov, iovcnt);
      if (sent == -1) {
         if (errno != EINTR) {
            char errmsg[1024];
            sprintf(errmsg, "Failed to send data to server: %s", strerror(errno));
            server->errmsg = strdup(errmsg);
            server_disconnect(server);
            return -1;
         }
      } else {
         if ((size_t)sent == size) {
            return 0;
         }

         for (int ii = 0; ii < iovcnt && sent > 0; ++ii) {
            if (iov[ii].iov_len < (size_t)sent) {
               size -= iov[ii].iov_len;
               sent -= iov[ii].iov_len;
               iov[ii].iov_len = 0;
            } else {
               iov[ii].iov_base = ((char*)iov[ii].iov_base) + sent;
               iov[ii].iov_len -= sent;
               size -= sent;
               break;
            }
         }
      }
   } while (size > 0);
#endif
   return 0;
}

static size_t server_receive(struct Server* server, char* data, size_t size, int line) {
   size_t offset = 0;
   int stop = 0;
   do {
      ssize_t nread = recv(server->sock, data + offset, size - offset, 0);
      if (nread == -1) {
         if (errno != EINTR) {
            char errmsg[1024];
            sprintf(errmsg, "Failed to receive data from server: %s", strerror(errno));
            server->errmsg = strdup(errmsg);
            server_disconnect(server);
            return -1;
         }
      } else {
         if (line) {
            if (strchr(data + offset, '\r') != 0) {
               stop = 1;
            }
         }
         offset += nread;
      }
   } while (offset < size && !stop);

   if (line && !stop) {
      server->errmsg = strdup("Protocol error");
      server_disconnect(server);
      return -1;
   }

   return offset;
}

#ifdef HAVE_MEMCACHED_PROTOCOL_BINARY_H
/* Byte swap a 64-bit number */
static int64_t swap64(int64_t in) {
#ifndef __sparc
    /* Little endian, flip the bytes around until someone makes a faster/better
* way to do this. */
    int64_t rv = 0;
    int i = 0;
     for(i = 0; i < 8; i++) {
        rv = (rv << 8) | (in & 0xff);
        in >>= 8;
     }
    return rv;
#else
    /* big-endian machines don't need byte swapping */
    return in;
#endif
}
#endif

/**
* Implementation of the Binary protocol
*/
static int binary_get(struct Server* server, struct Item* item)
{
#ifndef HAVE_MEMCACHED_PROTOCOL_BINARY_H
   (void)server;
   (void)item;
   return -1;
#else
   uint16_t keylen = item->keylen;
   uint32_t bodylen = keylen;

   protocol_binary_request_get request = { .bytes = {0} };
   request.message.header.request.magic = PROTOCOL_BINARY_REQ;
   request.message.header.request.opcode = PROTOCOL_BINARY_CMD_GET;
   request.message.header.request.keylen = htons(keylen);
   request.message.header.request.datatype = PROTOCOL_BINARY_RAW_BYTES;
   request.message.header.request.bodylen = htonl(bodylen);

   struct iovec iovec[2];
   iovec[0].iov_base = (void*)&request;
   iovec[0].iov_len = sizeof(request);
   iovec[1].iov_base = (void*)item->key;
   iovec[1].iov_len = keylen;

   server_sendv(server, iovec, 2);

   protocol_binary_response_set response;
   size_t nread = server_receive(server, (char*)response.bytes,
                                 sizeof(response.bytes), 0);
   if (nread != sizeof(response)) {
      server->errmsg = strdup("Protocol error");
      server_disconnect(server);
      return -1;
   }

   bodylen = ntohl(response.message.header.response.bodylen);
   if (response.message.header.response.status == 0) {
      if (item->data != NULL) {
         if ((bodylen-response.message.header.response.extlen) > item->size) {
            free(item->data);
            item->data = NULL;
         }
      }

      if (item->data == NULL) {
         item->size = bodylen - response.message.header.response.extlen;
         item->data = malloc(item->size);
         if (item->data == NULL) {
            server->errmsg = strdup("failed to allocate memory\n");
            server_disconnect(server);
            return -1;
         }
      }

      if (response.message.header.response.extlen != 0) {
         assert(response.message.header.response.extlen == 4);
         uint32_t flags;
         struct iovec iov[2];
         iov[0].iov_base = (void*)&flags;
         iov[0].iov_len = sizeof(flags);
         iov[1].iov_base = item->data;
         iov[1].iov_len = item->size;

         nread = readv(server->sock, iovec, 2);
         if (nread < bodylen) {
             // partial read.. read the rest!
             nread -= 4;
             size_t left = item->size - nread;
             if (server_receive(server, (char*)(item->data) + nread, left, 0) != left) {
                 abort();
             }
         }
      } else {
         nread = server_receive(server, item->data, item->size, 0);
         assert(nread == item->size);
      }

      item->cas_id = swap64(response.message.header.response.cas);
   } else {
      char *buffer = malloc(bodylen + 1);
      if (buffer == NULL) {
         server->errmsg = strdup("failed to allocate memory\n");
         server_disconnect(server);
         return -1;
      }
      buffer[bodylen] = '\0';
      server_receive(server, buffer, bodylen, 0);
      server->errmsg = buffer;

      return -1;
   }

   return 0;
#endif
}

static int binary_store(struct Server* server,
                         enum StoreCommand cmd,
                         const struct Item *item)
{
#ifndef HAVE_MEMCACHED_PROTOCOL_BINARY_H
   (void)server;
   (void)cmd;
   (void)item;
   return -1;
#else
   protocol_binary_request_set request = { .bytes = {0} };
   request.message.header.request.magic = PROTOCOL_BINARY_REQ;

   switch (cmd) {
   case add :
      request.message.header.request.opcode = PROTOCOL_BINARY_CMD_ADD; break;
   case set :
      request.message.header.request.opcode = PROTOCOL_BINARY_CMD_SET; break;
   case replace :
      request.message.header.request.opcode = PROTOCOL_BINARY_CMD_REPLACE; break;
   default:
      abort();
   }

   uint16_t keylen = item->keylen;
   request.message.header.request.keylen = htons(keylen);
   request.message.header.request.extlen = 8;
   request.message.header.request.datatype = 0;
   request.message.header.request.reserved = 0;
   request.message.header.request.bodylen = htonl(keylen + item->size + 8);
   request.message.header.request.opaque = 0;
   request.message.header.request.cas = swap64(item->cas_id);
   request.message.body.flags = 0;
   request.message.body.expiration = htonl(item->exptime);

   struct iovec iovec[3];
   iovec[0].iov_base = (void*)&request;
   iovec[0].iov_len = sizeof(request);
   iovec[1].iov_base = (void*)item->key;
   iovec[1].iov_len = keylen;
   iovec[2].iov_base = item->data;
   iovec[2].iov_len = item->size;

   server_sendv(server, iovec, 3);

   protocol_binary_response_set response;
   size_t nread = server_receive(server, (char*)response.bytes,
                                 sizeof(response.bytes), 0);
   if (nread != sizeof(response)) {
      server->errmsg = strdup("Protocol error");
      server_disconnect(server);
      return -1;
   }

   if (response.message.header.response.status == 0 &&
       response.message.header.response.bodylen != 0) {
      server->errmsg = strdup("Unexpected data returned\n");
      server_disconnect(server);
      return -1;
   } else if (response.message.header.response.bodylen != 0) {
      uint32_t len = ntohl(response.message.header.response.bodylen);
      char* buffer = malloc(len);
      if (buffer == 0) {
         server->errmsg = strdup("failed to allocate memory\n");
         server_disconnect(server);
         return -1;
      }

      nread = server_receive(server, buffer, len, 0);
      free(buffer);
   }

   return (response.message.header.response.status == 0) ? 0 : -1;
#endif
}

/**
* Implementation of the Textual protocol
*/
static int parse_value_line(char *header, uint32_t* flag, size_t* size, char** data) {
   char *end = strchr(header, ' ');
   if (end == 0) {
      return -1;
   }
   char *start = end + 1;
   *flag = (uint32_t)strtoul(start, &end, 10);
   if (start == end) {
      return -1;
   }
   start = end + 1;
   *size = (size_t)strtoul(start, &end, 10);
   if (start == end) {
      return -1;
   }
   if (strstr(end, "\r\n") != end) {
      return -1;
   }

   *data = end + 2;
   return 0;
}

static int textual_get(struct Server* server, struct Item* item) {
   uint32_t flag;

   struct iovec iovec[3];
   iovec[0].iov_base = (char*)"get ";
   iovec[0].iov_len = 4;
   iovec[1].iov_base = (char*)item->key;
   iovec[1].iov_len = item->keylen;
   iovec[2].iov_base = (char*)"\r\n";
   iovec[2].iov_len = 2;
   server_sendv(server, iovec, 3);

   size_t nread = server_receive(server, server->buffer,server->buffersize, 1);

   // Split the header line
   if (strstr(server->buffer, "VALUE ") == server->buffer) {
      size_t elemsize;
      char *ptr;

      if (parse_value_line(server->buffer + 6, &flag, &elemsize, &ptr) == -1){
         server->errmsg = strdup("Protocol error");
         server_disconnect(server);
         return -1;
      }
#ifndef __sun
      typedef size_t ptrdiff_t;
#endif
      ptrdiff_t headsize = ptr - server->buffer;
      size_t chunk = nread - headsize;

      if (chunk < (elemsize + 7)) {
         // I don't have all of the data.. keep on reading
         server_receive(server, server->buffer + nread,
                        (elemsize - chunk) + 7, 0);
      }

      void *result = ptr;
      if (elemsize > item->size) {
         if (item->data != 0) {
            free(item->data);
         }
         item->size = elemsize;
         item->data = malloc(item->size);
         if (item->data == 0) {
            item->size = 0;
            return -1;
         }
      }

      memcpy(item->data, result, item->size);
      return 0;
   } else if (strstr(server->buffer, "END") == server->buffer) {
      return -1;
   }

   abort();
}

static int textual_store(struct Server* server,
                         enum StoreCommand cmd,
                         const struct Item *item) {
   static const char* const commands[] = { "add ", "set ", "replace " };

   uint32_t flags = 0;
   const void *dta = item->data;
   size_t size = item->size;
   ssize_t len = sprintf(server->buffer, " %d %ld %ld\r\n",
           flags, (long)item->exptime, (long)item->size);

   struct iovec iovec[5];
   iovec[0].iov_base = (char*)commands[cmd];
   iovec[0].iov_len = strlen(commands[cmd]);
   iovec[1].iov_base = (char*)item->key;
   iovec[1].iov_len = item->keylen;
   iovec[2].iov_base = server->buffer;
   iovec[2].iov_len = len;
   iovec[3].iov_base = (char*)dta;
   iovec[3].iov_len = size;
   iovec[4].iov_base = (char*)"\r\n";
   iovec[4].iov_len = 2;
   server_sendv(server, iovec, 5);

   size_t offset = 0;
   do {
      len = recv(server->sock, (void*)(server->buffer + offset),
                 server->buffersize - offset, 0);
      if (len == -1) {
         if (errno != EINTR) {
            char errmsg[1024];
            sprintf(errmsg, "Failed to receive data from server: %s",
                    strerror(errno));
            server->errmsg = strdup(errmsg);
            server_disconnect(server);
            return -1;
         }
      } else if (len == 0) {
         server->errmsg = strdup("Lost contact with server");
         server_disconnect(server);
         return -1;
      } else {
         offset += len;
         if (strchr(server->buffer, '\r') != 0) {
            if (strstr(server->buffer, "STORED\r\n") == server->buffer) {
               return 0;
            } else if (strstr(server->buffer,
                              "NOT_STORED\r\n") == server->buffer) {
               server->errmsg = strdup("Item NOT stored");
               return -1;
            }
         }
      }
      if (offset == server->buffersize) {
         server->errmsg = strdup("Out of sync with server...");
         server_disconnect(server);
         return -1;
      }
   } while (1);
}
Something went wrong with that request. Please try again.