forked from cheekyguy/memcached
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemcached.c
executable file
·3643 lines (3132 loc) · 114 KB
/
memcached.c
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* memcached - memory caching daemon
*
* http://www.danga.com/memcached/
*
* Copyright 2003 Danga Interactive, Inc. All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*
* Authors:
* Anatoly Vorobey <[email protected]>
* Brad Fitzpatrick <[email protected]>
*
* $Id$
*/
#include "generic.h"
#include <signal.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/signal.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <pwd.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#ifdef HAVE_MALLOC_H
/* OpenBSD has a malloc.h, but warns to use stdlib.h instead */
#ifndef __OpenBSD__
#include <malloc.h>
#endif
#endif
#include "assoc.h"
#include "binary_sm.h"
#include "items.h"
#include "memcached.h"
#include "stats.h"
#include "sigseg.h"
#include "conn_buffer.h"
#if defined(USE_SLAB_ALLOCATOR)
#include "slabs_items_support.h"
#endif /* #if defined(USE_SLAB_ALLOCATOR) */
#if defined(USE_FLAT_ALLOCATOR)
#include "flat_storage_support.h"
#endif /* #if defined(USE_FLAT_ALLOCATOR) */
#define LISTEN_DEPTH 4096
/*
* forward declarations
*/
static void drive_machine(conn* c);
static int new_socket(const bool is_udp);
static int server_socket(const int port, const bool is_udp);
static int try_read_command(conn *c);
static void maximize_socket_buffer(const int sfd, int optname);
/* defaults */
static void settings_init(void);
/* event handling, network IO */
static void event_handler(const int fd, const short which, void *arg);
static void conn_init(void);
static void complete_nread(conn* c);
static void process_command(conn* c, char *command);
static int ensure_iov_space(conn* c);
void pre_gdb(void);
static void conn_free(conn* c);
/** exported globals **/
settings_t settings;
int maps_fd = -1;
/** file scope variables **/
static item **todelete = NULL;
static int delcurr;
static int deltotal;
static conn* listen_conn;
static conn* listen_binary_conn;
struct event_base *main_base;
static int *buckets = 0; /* bucket->generation array for a managed instance */
#define REALTIME_MAXDELTA 60*60*24*30
/*
* given time value that's either unix time or delta from current unix time, return
* unix time. Use the fact that delta can't exceed one month (and real time value can't
* be that low).
*/
rel_time_t realtime(const time_t exptime) {
/* no. of seconds in 30 days - largest possible delta exptime */
if (exptime == 0) return 0; /* 0 means never expire */
if (exptime > REALTIME_MAXDELTA) {
/* if item expiration is at/before the server started, give it an
expiration time of 1 second after the server started.
(because 0 means don't expire). without this, we'd
underflow and wrap around to some large value way in the
future, effectively making items expiring in the past
really expiring never */
if (exptime <= started)
return (rel_time_t)1;
return (rel_time_t)(exptime - started);
} else {
return (rel_time_t)(exptime + current_time);
}
}
size_t append_to_buffer(char* const buffer_start,
const size_t buffer_size,
const size_t buffer_off,
const size_t reserved,
const char* fmt,
...) {
va_list ap;
ssize_t written;
size_t left = buffer_size - buffer_off - reserved;
va_start(ap, fmt);
written = vsnprintf(&buffer_start[buffer_off], left, fmt, ap);
va_end(ap);
if (written < 0) {
return buffer_off;
} else if (written >= left) {
buffer_start[buffer_off] = 0;
return buffer_off;
}
return buffer_off + written;
}
static void settings_init(void) {
settings.port = 0;
settings.udpport = 0;
settings.binary_port = 0;
settings.binary_udpport = 0;
settings.interf.s_addr = htonl(INADDR_ANY);
settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */
settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */
settings.verbose = 0;
settings.oldest_live = 0;
settings.evict_to_free = 1; /* push old items out of cache when memory runs out */
settings.socketpath = NULL; /* by default, not using a unix socket */
settings.managed = false;
settings.factor = 1.25;
settings.chunk_size = 48; /* space for a modest key and value */
settings.prefix_delimiter = ':';
settings.detail_enabled = 0;
settings.reqs_per_event = 1;
#ifdef HAVE__SC_NPROCESSORS_ONLN
/*
* If the system supports detecting the number of active processors
* use that to determine the number of worker threads + 1 dispatcher.
*/
settings.num_threads = sysconf(_SC_NPROCESSORS_ONLN) + 1;
#else
settings.num_threads = 4 + 1; /* N workers + 1 dispatcher */
#endif
}
/*
* Adds a message header to a connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
int add_msghdr(conn* c)
{
struct msghdr *msg;
assert(c != NULL);
if (c->msgsize == c->msgused) {
msg = pool_realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr),
c->msgsize * sizeof(struct msghdr), CONN_BUFFER_MSGLIST_POOL);
if (! msg)
return -1;
c->msglist = msg;
c->msgsize *= 2;
}
msg = c->msglist + c->msgused;
/* this wipes msg_iovlen, msg_control, msg_controllen, and
msg_flags, the last 3 of which aren't defined on solaris: */
memset(msg, 0, sizeof(struct msghdr));
if (ensure_iov_space(c) != 0) {
return -1;
}
msg->msg_iov = &c->iov[c->iovused];
msg->msg_name = &c->request_addr;
msg->msg_namelen = c->request_addr_size;
c->msgbytes = 0;
c->msgused++;
if (c->udp) {
/* Leave room for the UDP header, which we'll fill in later. */
return add_iov(c, NULL, UDP_HEADER_SIZE, false);
}
return 0;
}
/*
* Free list management for connections.
*/
static conn* *freeconns;
static int freetotal;
static int freecurr;
static void conn_init(void) {
freetotal = 200;
freecurr = 0;
if ((freeconns = (conn* *)pool_malloc(sizeof(conn*) * freetotal, CONN_POOL)) == NULL) {
perror("malloc()");
}
return;
}
/*
* Returns a connection from the freelist, if any. Should call this using
* conn_from_freelist() for thread safety.
*/
conn* do_conn_from_freelist() {
conn* c;
if (freecurr > 0) {
c = freeconns[--freecurr];
} else {
c = NULL;
}
return c;
}
/*
* Adds a connection to the freelist. 0 = success. Should call this using
* conn_add_to_freelist() for thread safety.
*/
bool do_conn_add_to_freelist(conn* c) {
if (freecurr < freetotal) {
freeconns[freecurr++] = c;
return false;
} else {
/* try to enlarge free connections array */
conn* *new_freeconns = pool_realloc(freeconns,
sizeof(conn*) * freetotal * 2,
sizeof(conn*) * freetotal,
CONN_POOL);
if (new_freeconns) {
freetotal *= 2;
freeconns = new_freeconns;
freeconns[freecurr++] = c;
return false;
}
}
return true;
}
#if defined(HAVE_UDP_REPLY_PORTS)
/* Allocate a port for udp reply transmission.
Starting from the port of the reciever socket, increment by one
until bind succeeds or we fail settings.num_threads times.
No locking is needed since each thread is racing to get a port
and the OS will only allow one thread to bind to any particular
port. */
static int allocate_udp_reply_port(int sfd, int tries) {
struct addrinfo hints, *res = NULL;
struct sockaddr addr;
socklen_t addr_len;
char port[6];
char host[100];
int error;
int xfd = -1;
/* Need the address to lookup the host:port pair */
addr_len = sizeof(addr);
if (getsockname(sfd, &addr, &addr_len) < 0) {
perror("getsockname");
return -1;
}
/* Lookup the host:port pair for the recieve socket. */
if (getnameinfo(&addr, addr_len, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST|NI_NUMERICSERV)) {
perror("getnameinfo");
return -1;
}
/* Already bound to the recieve port, so start the search
at the next one. */
sprintf(port, "%d", atoi(port) + 1);
for (; tries; tries--) {
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG | AI_NUMERICHOST;
if (res)
freeaddrinfo(res);
res = NULL;
error = getaddrinfo(host, port, &hints, &res);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
break;
}
xfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (xfd < 0) {
perror("socket");
break;
}
if (bind(xfd, res->ai_addr, res->ai_addrlen) < 0) {
close(xfd);
xfd = -1;
if (errno == EADDRINUSE) {
sprintf(port, "%d", atoi(port) + 1); /* next port */
continue;
}
perror("bind");
}
maximize_socket_buffer(xfd, SO_SNDBUF);
break; /* success or error, break out */
}
if (res)
freeaddrinfo(res);
return xfd;
}
#endif
conn *conn_new(const int sfd, const int init_state, const int event_flags,
conn_buffer_group_t* cbg, const bool is_udp, const bool is_binary,
const struct sockaddr* const addr, const socklen_t addrlen,
struct event_base *base) {
stats_t *stats = STATS_GET_TLS();
conn* c = conn_from_freelist();
if (NULL == c) {
if (!(c = (conn*)pool_calloc(1, sizeof(conn), CONN_POOL))) {
perror("malloc()");
return NULL;
}
c->rsize = 0;
c->wsize = DATA_BUFFER_SIZE;
c->isize = ITEM_LIST_INITIAL;
c->iovsize = 0;
c->msgsize = MSG_LIST_INITIAL;
c->hdrsize = 0;
c->riov_size = 0;
c->rbuf = NULL;
c->wbuf = (char *)pool_malloc((size_t)c->wsize, CONN_BUFFER_WBUF_POOL);
c->ilist = (item **)pool_malloc(sizeof(item *) * c->isize, CONN_BUFFER_ILIST_POOL);
c->iov = NULL;
c->msglist = (struct msghdr *)pool_malloc(sizeof(struct msghdr) * c->msgsize, CONN_BUFFER_MSGLIST_POOL);
c->hdrbuf = NULL;
c->riov = NULL;
if (is_binary) {
// because existing functions expects the key to be null-terminated,
// we must do so as well.
c->bp_key = (char*)pool_malloc(sizeof(char) * KEY_MAX_LENGTH + 1, CONN_BUFFER_BP_KEY_POOL);
c->bp_hdr_pool = bp_allocate_hdr_pool(NULL);
} else {
c->bp_key = NULL;
c->bp_hdr_pool = NULL;
}
if (c->wbuf == 0 ||
c->ilist == 0 ||
c->msglist == 0 ||
(is_binary && c->bp_key == 0)) {
if (c->wbuf != 0) pool_free(c->wbuf, c->wsize, CONN_BUFFER_WBUF_POOL);
if (c->ilist !=0) pool_free(c->ilist, sizeof(item*) * c->isize, CONN_BUFFER_ILIST_POOL);
if (c->msglist != 0) pool_free(c->msglist, sizeof(struct msghdr) * c->msgsize, CONN_BUFFER_MSGLIST_POOL);
if (c->bp_key != 0) pool_free(c->bp_key, sizeof(char) * KEY_MAX_LENGTH + 1, CONN_BUFFER_BP_KEY_POOL);
if (c->bp_hdr_pool != NULL) bp_release_hdr_pool(c);
pool_free(c, 1 * sizeof(conn), CONN_POOL);
perror("malloc()");
return NULL;
}
STATS_LOCK(stats);
stats->conn_structs++;
STATS_UNLOCK(stats);
}
memcpy(&c->request_addr, addr, addrlen);
if (settings.socketpath) {
c->request_addr_size = 0; /* for unix-domain sockets, don't store
* a request addr. */
} else {
c->request_addr_size = addrlen;
}
c->cbg = cbg;
if (settings.verbose > 1) {
if (init_state == conn_listening)
fprintf(stderr, "<%d server listening\n", sfd);
else if (is_udp)
fprintf(stderr, "<%d server listening (udp)\n", sfd);
else
fprintf(stderr, "<%d new client connection\n", sfd);
}
c->sfd = c->xfd = sfd;
#if defined(HAVE_UDP_REPLY_PORTS)
/* The linux UDP transmit path is heavily contended when more than one
thread is writing to the same socket. If configured to support
per-thread reply ports, allocate a per-thread udp socket and set the
udp fd accordingly, otherwise use the recieve socket. The transmit
fd is set in try_read_udp to validate that the client request
can handle the number of reply ports the server is configured for. */
if (is_udp) {
c->ufd = allocate_udp_reply_port(sfd, settings.num_threads - 1);
if (c->ufd == -1) {
fprintf(stderr, "unable to allocate all udp reply ports.\n");
exit(1);
}
}
#endif
c->udp = is_udp;
c->binary = is_binary;
c->state = init_state;
c->rbytes = c->wbytes = 0;
c->rcurr = c->rbuf;
c->wcurr = c->wbuf;
c->icurr = c->ilist;
c->ileft = 0;
c->iovused = 0;
c->msgcurr = 0;
c->msgused = 0;
c->riov_curr = 0;
c->riov_left = 0;
c->write_and_go = conn_read;
c->write_and_free = 0;
c->item = 0;
c->bucket = -1;
c->gen = 0;
event_set(&c->event, sfd, event_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = event_flags;
if (event_add(&c->event, 0) == -1) {
if (conn_add_to_freelist(c)) {
conn_free(c);
}
return NULL;
}
STATS_LOCK(stats);
stats->curr_conns++;
stats->total_conns++;
STATS_UNLOCK(stats);
return c;
}
void conn_cleanup(conn* c) {
assert(c != NULL);
if (c->item) {
item_deref(c->item);
c->item = 0;
}
if (c->ileft != 0) {
for (; c->ileft > 0; c->ileft--,c->icurr++) {
item_deref(*(c->icurr));
}
}
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
if (c->rbuf) {
free_conn_buffer(c->cbg, c->rbuf, 0); /* no idea how much was used... */
c->rbuf = NULL;
c->rsize = 0;
}
if (c->iov) {
free_conn_buffer(c->cbg, c->iov, 0); /* no idea how much was used... */
c->iov = NULL;
c->iovsize = 0;
}
if (c->riov) {
free_conn_buffer(c->cbg, c->riov, 0); /* no idea how much was used... */
c->riov = NULL;
c->riov_size = 0;
}
}
/*
* Frees a connection.
*/
void conn_free(conn* c) {
if (c) {
if (c->hdrbuf)
pool_free(c->hdrbuf, c->hdrsize * UDP_HEADER_SIZE, CONN_BUFFER_HDRBUF_POOL);
if (c->msglist)
pool_free(c->msglist, sizeof(struct msghdr) * c->msgsize, CONN_BUFFER_MSGLIST_POOL);
if (c->rbuf)
free_conn_buffer(c->cbg, c->rbuf, 0);
if (c->wbuf)
pool_free(c->wbuf, c->wsize, CONN_BUFFER_WBUF_POOL);
if (c->ilist)
pool_free(c->ilist, sizeof(item*) * c->isize, CONN_BUFFER_ILIST_POOL);
if (c->iov)
free_conn_buffer(c->cbg, c->iov, c->iovused * sizeof(struct iovec));
if (c->riov)
free_conn_buffer(c->cbg, c->riov, 0);
if (c->bp_key)
pool_free(c->bp_key, sizeof(char) * KEY_MAX_LENGTH + 1, CONN_BUFFER_BP_KEY_POOL);
if (c->bp_hdr_pool)
bp_release_hdr_pool(c);
pool_free(c, 1 * sizeof(conn), CONN_POOL);
}
}
void conn_close(conn* c) {
stats_t *stats = STATS_GET_TLS();
assert(c != NULL);
/* delete the event, the socket and the conn */
event_del(&c->event);
if (settings.verbose > 1)
fprintf(stderr, "<%d connection closed.\n", c->sfd);
close(c->sfd);
accept_new_conns(true, c->binary);
conn_cleanup(c);
/* if the connection has big buffers, just free it */
if (c->rsize > READ_BUFFER_HIGHWAT ||
c->wsize > WRITE_BUFFER_HIGHWAT ||
conn_add_to_freelist(c)) {
conn_free(c);
}
STATS_LOCK(stats);
stats->curr_conns--;
STATS_UNLOCK(stats);
return;
}
/*
* Shrinks a connection's buffers if they're too big. This prevents
* periodic large "get" requests from permanently chewing lots of server
* memory.
*
* This should only be called in between requests since it can wipe output
* buffers!
*/
void conn_shrink(conn* c) {
assert(c != NULL);
if (c->udp)
return;
if (c->rbytes == 0 && c->rbuf != NULL) {
/* drop the buffer since we have no bytes to preserve. */
free_conn_buffer(c->cbg, c->rbuf, 0);
c->rbuf = NULL;
c->rcurr = NULL;
c->rsize = 0;
} else {
memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
c->rcurr = c->rbuf;
}
if (c->wsize > WRITE_BUFFER_HIGHWAT) {
char *newbuf;
newbuf = (char*) pool_realloc((void*) c->wbuf, DATA_BUFFER_SIZE,
c->wsize, CONN_BUFFER_WBUF_POOL);
if (newbuf) {
c->wbuf = newbuf;
c->wsize = DATA_BUFFER_SIZE;
}
}
if (c->isize > ITEM_LIST_HIGHWAT) {
item **newbuf = (item**) pool_realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0]),
c->isize * sizeof(c->ilist[0]), CONN_BUFFER_ILIST_POOL);
if (newbuf) {
c->ilist = newbuf;
c->isize = ITEM_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->msgsize > MSG_LIST_HIGHWAT) {
struct msghdr *newbuf = (struct msghdr *) pool_realloc((void *)c->msglist,
MSG_LIST_INITIAL * sizeof(c->msglist[0]),
c->msgsize * sizeof(c->msglist[0]),
CONN_BUFFER_MSGLIST_POOL);
if (newbuf) {
c->msglist = newbuf;
c->msgsize = MSG_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->riov) {
free_conn_buffer(c->cbg, c->riov, 0);
c->riov = NULL;
c->riov_size = 0;
}
if (c->iov != NULL) {
free_conn_buffer(c->cbg, c->iov, 0);
c->iov = NULL;
c->iovsize = 0;
}
if (c->binary) {
bp_shrink_hdr_pool(c);
}
}
/*
* Sets a connection's current state in the state machine. Any special
* processing that needs to happen on certain state transitions can
* happen here.
*/
static void conn_set_state(conn* c, int state) {
assert(c != NULL);
if (state != c->state) {
if (state == conn_read) {
conn_shrink(c);
assoc_move_next_bucket();
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
}
c->state = state;
}
}
/*
* Ensures that there is room for another struct iovec in a connection's
* iov list.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int ensure_iov_space(conn* c) {
assert(c != NULL);
if (c->iovsize == 0) {
c->iov = (struct iovec *)alloc_conn_buffer(c->cbg, 0);
if (c->iov != NULL) {
c->iovsize = CONN_BUFFER_DATA_SZ / sizeof(struct iovec);
}
}
if (c->iovused >= c->iovsize) {
return -1;
}
report_max_rusage(c->cbg, c->iov, (c->iovused + 1) * sizeof(struct iovec));
return 0;
}
/*
* Adds data to the list of pending data that will be written out to a
* connection.
*
* is_start should be true if this data represents the start of a protocol
* response, e.g., a "VALUE" line.
*
* Returns 0 on success, -1 on out-of-memory.
*/
int add_iov(conn* c, const void *buf, int len, bool is_start) {
struct msghdr *m;
int leftover;
bool limit_to_mtu;
assert(c != NULL);
assert(c->msgused > 0);
do {
m = &c->msglist[c->msgused - 1];
/*
* Limit UDP packets, and the first payloads of TCP replies, to
* UDP_MAX_PAYLOAD_SIZE bytes.
*/
limit_to_mtu = c->udp || (1 == c->msgused);
/* We may need to start a new msghdr if this one is full. */
if (m->msg_iovlen == IOV_MAX ||
(limit_to_mtu && c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
/* If the fragment is too big to fit in the datagram, split it up */
if (limit_to_mtu && len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) {
leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE;
len -= leftover;
} else {
leftover = 0;
}
m = &c->msglist[c->msgused - 1];
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
/*
* If this is the start of a response (e.g., a "VALUE" line),
* and it's the first one so far in this message, mark it as
* such so we can put its offset in the UDP header.
*/
if (c->udp && is_start && ! m->msg_flags) {
m->msg_flags = 1;
m->msg_controllen = m->msg_iovlen;
}
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
buf = ((char *)buf) + len;
len = leftover;
is_start = false;
} while (leftover > 0);
return 0;
}
/*
* Constructs a set of UDP headers and attaches them to the outgoing messages.
*/
int build_udp_headers(conn* c) {
int i, j, offset;
unsigned char *hdr;
assert(c != NULL);
if (c->msgused > c->hdrsize) {
void *new_hdrbuf;
if (c->hdrbuf)
new_hdrbuf = pool_realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE,
c->hdrsize * UDP_HEADER_SIZE, CONN_BUFFER_HDRBUF_POOL);
else
new_hdrbuf = pool_malloc(c->msgused * 2 * UDP_HEADER_SIZE, CONN_BUFFER_HDRBUF_POOL);
if (! new_hdrbuf)
return -1;
c->hdrbuf = (unsigned char *)new_hdrbuf;
c->hdrsize = c->msgused * 2;
}
hdr = c->hdrbuf;
for (i = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov[0].iov_base = hdr;
c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE;
/* Find the offset of the first response line in the message, if any */
offset = 0;
if (c->msglist[i].msg_flags) {
for (j = 0; j < c->msglist[i].msg_controllen; j++) {
offset += c->msglist[i].msg_iov[j].iov_len;
}
c->msglist[i].msg_flags = 0;
c->msglist[i].msg_controllen = 0;
}
*hdr++ = c->request_id / 256;
*hdr++ = c->request_id % 256;
*hdr++ = i / 256;
*hdr++ = i % 256;
*hdr++ = c->msgused / 256;
*hdr++ = c->msgused % 256;
*hdr++ = offset / 256;
*hdr++ = offset % 256;
assert((void *) hdr == (void *)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE);
}
return 0;
}
static void out_string(conn* c, const char *str) {
size_t len;
assert(c != NULL);
assert(c->msgcurr == 0);
c->msgused = 0;
c->iovused = 0;
if (settings.verbose > 1)
fprintf(stderr, ">%d %s\n", c->sfd, str);
len = strlen(str);
if ((len + 2) > c->wsize) {
/* ought to be always enough. just fail for simplicity */
str = "SERVER_ERROR output line too long";
len = strlen(str);
}
memcpy(c->wbuf, str, len);
memcpy(c->wbuf + len, "\r\n", 2);
c->wbytes = len + 2;
c->wcurr = c->wbuf;
conn_set_state(c, conn_write);
c->write_and_go = conn_read;
return;
}
/*
* we get here after reading the value in set/add/replace commands. The command
* has been stored in c->item_comm, and the item is ready in c->item.
*/
static void complete_nread(conn* c) {
stats_t *stats = STATS_GET_TLS();
assert(c != NULL);
item *it = c->item;
int comm = c->item_comm;
STATS_LOCK(stats);
stats->set_cmds++;
STATS_UNLOCK(stats);
if (memcmp("\r\n", c->crlf, 2) != 0) {
out_string(c, "CLIENT_ERROR bad data chunk");
} else {
if (store_item(it, comm, c->update_key)) {
out_string(c, "STORED");
} else {
out_string(c, "NOT_STORED");
}
}
item_deref(c->item); /* release the c->item reference */
c->item = 0;
}
/*
* Stores an item in the cache according to the semantics of one of the set
* commands. In threaded mode, this is protected by the cache lock.
*
* Returns true if the item was stored.
*/
int do_store_item(item *it, int comm, const char* key) {
bool delete_locked = false;
item *old_it;
int stored = 0;
size_t nkey = ITEM_nkey(it);
old_it = do_item_get_notedeleted(key, nkey, &delete_locked);
if (old_it != NULL && comm == NREAD_ADD) {
/* add only adds a nonexistent item, but promote to head of LRU */
do_item_update(old_it);
} else if (!old_it && comm == NREAD_REPLACE) {
/* replace only replaces an existing value; don't store */
} else if (delete_locked && (comm == NREAD_REPLACE || comm == NREAD_ADD)) {
/* replace and add can't override delete locks; don't store */
} else {
/* "set" commands can override the delete lock
window... in which case we have to find the old hidden item
that's in the namespace/LRU but wasn't returned by
item_get.... because we need to replace it */
if (delete_locked) {
old_it = do_item_get_nocheck(key, nkey);
}
if (settings.detail_enabled) {
int prefix_stats_flags = PREFIX_INCR_ITEM_COUNT;
if (old_it != NULL) {
prefix_stats_flags |= PREFIX_IS_OVERWRITE;
}
stats_prefix_record_byte_total_change(key, nkey, ITEM_nkey(it) + ITEM_nbytes(it),
prefix_stats_flags);
}
stats_set(ITEM_nkey(it) + ITEM_nbytes(it),
(old_it == NULL) ? 0 : ITEM_nkey(old_it) + ITEM_nbytes(old_it));
if (old_it != NULL) {
do_item_replace(old_it, it, key);
} else {
do_item_link(it, key);
}
stored = 1;
}
if (old_it)
do_item_deref(old_it); /* release our reference */
return stored;
}
typedef struct token_s {
char *value;
size_t length;
} token_t;
#define COMMAND_TOKEN 0
#define SUBCOMMAND_TOKEN 1
#define KEY_TOKEN 1
#define MAX_TOKENS 6
/*
* Tokenize the command string by replacing whitespace with '\0' and update
* the token array tokens with pointer to start of each token and length.
* Returns total number of tokens. The last valid token is the terminal
* token (value points to the first unprocessed character of the string and
* length zero).
*
* Usage example:
*
* while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
* for(int ix = 0; tokens[ix].length != 0; ix++) {
* ...
* }
* ncommand = tokens[ix].value - command;
* command = tokens[ix].value;
* }
*/
static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) {
char *s, *e;
size_t ntokens = 0;
assert(command != NULL && tokens != NULL && max_tokens > 1);
for (s = e = command; ntokens < max_tokens - 1; ++e) {
if (*e == ' ') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
*e = '\0';
}
s = e + 1;
}
else if (*e == '\0') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
}