forked from memcached/memcached
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcached.c
6323 lines (5811 loc) · 224 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
*
* https://www.memcached.org/
*
* 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]>
*/
#include "memcached.h"
#include "storage.h"
#include "authfile.h"
#include "restart.h"
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <ctype.h>
#include <stdarg.h>
/* some POSIX systems need the following definition
* to get mlockall flags out of sys/mman.h. */
#ifndef _P1003_1B_VISIBLE
#define _P1003_1B_VISIBLE
#endif
#include <pwd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <sysexits.h>
#include <stddef.h>
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#endif
#ifdef TLS
#include "tls.h"
#endif
#include "proto_text.h"
#include "proto_bin.h"
#include "proto_proxy.h"
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#endif
/*
* forward declarations
*/
static void drive_machine(conn *c);
static int new_socket(struct addrinfo *ai);
static ssize_t tcp_read(conn *arg, void *buf, size_t count);
static ssize_t tcp_sendmsg(conn *arg, struct msghdr *msg, int flags);
static ssize_t tcp_write(conn *arg, void *buf, size_t count);
enum try_read_result {
READ_DATA_RECEIVED,
READ_NO_DATA_RECEIVED,
READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */
READ_MEMORY_ERROR /** failed to allocate more memory */
};
static int try_read_command_negotiate(conn *c);
static int try_read_command_udp(conn *c);
static enum try_read_result try_read_network(conn *c);
static enum try_read_result try_read_udp(conn *c);
static int start_conn_timeout_thread(void);
/* stats */
static void stats_init(void);
static void conn_to_str(const conn *c, char *addr, char *svr_addr);
/* defaults */
static void settings_init(void);
/* event handling, network IO */
static void event_handler(const evutil_socket_t fd, const short which, void *arg);
static void conn_close(conn *c);
static void conn_init(void);
static bool update_event(conn *c, const int new_flags);
static void complete_nread(conn *c);
static void conn_free(conn *c);
/** exported globals **/
struct stats stats;
struct stats_state stats_state;
struct settings settings;
time_t process_started; /* when the process was started */
conn **conns;
struct slab_rebalance slab_rebal;
volatile int slab_rebalance_signal;
#ifdef EXTSTORE
/* hoping this is temporary; I'd prefer to cut globals, but will complete this
* battle another day.
*/
void *ext_storage = NULL;
#endif
/** file scope variables **/
static conn *listen_conn = NULL;
static int max_fds;
static struct event_base *main_base;
enum transmit_result {
TRANSMIT_COMPLETE, /** All done writing. */
TRANSMIT_INCOMPLETE, /** More data remaining to write. */
TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */
TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */
};
/* Default methods to read from/ write to a socket */
ssize_t tcp_read(conn *c, void *buf, size_t count) {
assert (c != NULL);
return read(c->sfd, buf, count);
}
ssize_t tcp_sendmsg(conn *c, struct msghdr *msg, int flags) {
assert (c != NULL);
return sendmsg(c->sfd, msg, flags);
}
ssize_t tcp_write(conn *c, void *buf, size_t count) {
assert (c != NULL);
return write(c->sfd, buf, count);
}
static enum transmit_result transmit(conn *c);
/* This reduces the latency without adding lots of extra wiring to be able to
* notify the listener thread of when to listen again.
* Also, the clock timer could be broken out into its own thread and we
* can block the listener via a condition.
*/
static volatile bool allow_new_conns = true;
static int stop_main_loop = NOT_STOP;
static struct event maxconnsevent;
static void maxconns_handler(const evutil_socket_t fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 0, .tv_usec = 10000};
if (fd == -42 || allow_new_conns == false) {
/* reschedule in 10ms if we need to keep polling */
evtimer_set(&maxconnsevent, maxconns_handler, 0);
event_base_set(main_base, &maxconnsevent);
evtimer_add(&maxconnsevent, &t);
} else {
evtimer_del(&maxconnsevent);
accept_new_conns(true);
}
}
/*
* 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 <= process_started)
return (rel_time_t)1;
return (rel_time_t)(exptime - process_started);
} else {
return (rel_time_t)(exptime + current_time);
}
}
static void stats_init(void) {
memset(&stats, 0, sizeof(struct stats));
memset(&stats_state, 0, sizeof(struct stats_state));
stats_state.accepting_conns = true; /* assuming we start in this state. */
/* make the time we started always be 2 seconds before we really
did, so time(0) - time.started is never zero. if so, things
like 'settings.oldest_live' which act as booleans as well as
values are now false in boolean context... */
process_started = time(0) - ITEM_UPDATE_INTERVAL - 2;
stats_prefix_init(settings.prefix_delimiter);
}
void stats_reset(void) {
STATS_LOCK();
memset(&stats, 0, sizeof(struct stats));
stats_prefix_clear();
STATS_UNLOCK();
threadlocal_stats_reset();
item_stats_reset();
}
static void settings_init(void) {
settings.use_cas = true;
settings.access = 0700;
settings.port = 11211;
settings.udpport = 0;
#ifdef TLS
settings.ssl_enabled = false;
settings.ssl_ctx = NULL;
settings.ssl_chain_cert = NULL;
settings.ssl_key = NULL;
settings.ssl_verify_mode = SSL_VERIFY_NONE;
settings.ssl_keyformat = SSL_FILETYPE_PEM;
settings.ssl_ciphers = NULL;
settings.ssl_ca_cert = NULL;
settings.ssl_last_cert_refresh_time = current_time;
settings.ssl_wbuf_size = 16 * 1024; // default is 16KB (SSL max frame size is 17KB)
settings.ssl_session_cache = false;
settings.ssl_kernel_tls = false;
settings.ssl_min_version = TLS1_2_VERSION;
#endif
/* By default this string should be NULL for getaddrinfo() */
settings.inter = NULL;
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.oldest_cas = 0; /* supplements accuracy of oldest_live */
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.auth_file = NULL; /* by default, not using ASCII authentication tokens */
settings.factor = 1.25;
settings.chunk_size = 48; /* space for a modest key and value */
settings.num_threads = 4; /* N workers */
settings.num_threads_per_udp = 0;
settings.prefix_delimiter = ':';
settings.detail_enabled = 0;
settings.reqs_per_event = 20;
settings.backlog = 1024;
settings.binding_protocol = negotiating_prot;
settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */
settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */
settings.slab_chunk_size_max = settings.slab_page_size / 2;
settings.sasl = false;
settings.maxconns_fast = true;
settings.lru_crawler = false;
settings.lru_crawler_sleep = 100;
settings.lru_crawler_tocrawl = 0;
settings.lru_maintainer_thread = false;
settings.lru_segmented = true;
settings.hot_lru_pct = 20;
settings.warm_lru_pct = 40;
settings.hot_max_factor = 0.2;
settings.warm_max_factor = 2.0;
settings.temp_lru = false;
settings.temporary_ttl = 61;
settings.idle_timeout = 0; /* disabled */
settings.hashpower_init = 0;
settings.slab_reassign = true;
settings.slab_automove = 1;
settings.slab_automove_ratio = 0.8;
settings.slab_automove_window = 30;
settings.shutdown_command = false;
settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT;
settings.flush_enabled = true;
settings.dump_enabled = true;
settings.crawls_persleep = 1000;
settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE;
settings.logger_buf_size = LOGGER_BUF_SIZE;
settings.drop_privileges = false;
settings.watch_enabled = true;
settings.read_buf_mem_limit = 0;
#ifdef MEMCACHED_DEBUG
settings.relaxed_privileges = false;
#endif
settings.num_napi_ids = 0;
settings.memory_file = NULL;
#ifdef SOCK_COOKIE_ID
settings.sock_cookie_id = 0;
#endif
}
extern pthread_mutex_t conn_lock;
/* Connection timeout thread bits */
static pthread_t conn_timeout_tid;
static int do_run_conn_timeout_thread;
static pthread_cond_t conn_timeout_cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t conn_timeout_lock = PTHREAD_MUTEX_INITIALIZER;
#define CONNS_PER_SLICE 100
static void *conn_timeout_thread(void *arg) {
int i;
conn *c;
rel_time_t oldest_last_cmd;
int sleep_time;
int sleep_slice = max_fds / CONNS_PER_SLICE;
if (sleep_slice == 0)
sleep_slice = CONNS_PER_SLICE;
useconds_t timeslice = 1000000 / sleep_slice;
mutex_lock(&conn_timeout_lock);
while(do_run_conn_timeout_thread) {
if (settings.verbose > 2)
fprintf(stderr, "idle timeout thread at top of connection list\n");
oldest_last_cmd = current_time;
for (i = 0; i < max_fds; i++) {
if ((i % CONNS_PER_SLICE) == 0) {
if (settings.verbose > 2)
fprintf(stderr, "idle timeout thread sleeping for %ulus\n",
(unsigned int)timeslice);
usleep(timeslice);
}
if (!conns[i])
continue;
c = conns[i];
if (!IS_TCP(c->transport))
continue;
if (c->state != conn_new_cmd && c->state != conn_read)
continue;
if ((current_time - c->last_cmd_time) > settings.idle_timeout) {
timeout_conn(c);
} else {
if (c->last_cmd_time < oldest_last_cmd)
oldest_last_cmd = c->last_cmd_time;
}
}
/* This is the soonest we could have another connection time out */
sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1;
if (sleep_time <= 0)
sleep_time = 1;
if (settings.verbose > 2)
fprintf(stderr,
"idle timeout thread finished pass, sleeping for %ds\n",
sleep_time);
struct timeval now;
struct timespec to_sleep;
gettimeofday(&now, NULL);
to_sleep.tv_sec = now.tv_sec + sleep_time;
to_sleep.tv_nsec = 0;
pthread_cond_timedwait(&conn_timeout_cond, &conn_timeout_lock, &to_sleep);
}
mutex_unlock(&conn_timeout_lock);
return NULL;
}
static int start_conn_timeout_thread(void) {
int ret;
if (settings.idle_timeout == 0)
return -1;
do_run_conn_timeout_thread = 1;
if ((ret = pthread_create(&conn_timeout_tid, NULL,
conn_timeout_thread, NULL)) != 0) {
fprintf(stderr, "Can't create idle connection timeout thread: %s\n",
strerror(ret));
return -1;
}
thread_setname(conn_timeout_tid, "mc-idletimeout");
return 0;
}
int stop_conn_timeout_thread(void) {
if (!do_run_conn_timeout_thread)
return -1;
mutex_lock(&conn_timeout_lock);
do_run_conn_timeout_thread = 0;
pthread_cond_signal(&conn_timeout_cond);
mutex_unlock(&conn_timeout_lock);
pthread_join(conn_timeout_tid, NULL);
return 0;
}
/*
* read buffer cache helper functions
*/
static void rbuf_release(conn *c) {
if (c->rbuf != NULL && c->rbytes == 0 && !IS_UDP(c->transport)) {
if (c->rbuf_malloced) {
free(c->rbuf);
c->rbuf_malloced = false;
} else {
do_cache_free(c->thread->rbuf_cache, c->rbuf);
}
c->rsize = 0;
c->rbuf = NULL;
c->rcurr = NULL;
}
}
static bool rbuf_alloc(conn *c) {
if (c->rbuf == NULL) {
c->rbuf = do_cache_alloc(c->thread->rbuf_cache);
if (!c->rbuf) {
THR_STATS_LOCK(c->thread);
c->thread->stats.read_buf_oom++;
THR_STATS_UNLOCK(c->thread);
return false;
}
c->rsize = READ_BUFFER_SIZE;
c->rcurr = c->rbuf;
}
return true;
}
// Just for handling huge ASCII multigets.
// The previous system was essentially the same; realloc'ing until big enough,
// then realloc'ing back down after the request finished.
bool rbuf_switch_to_malloc(conn *c) {
// Might as well start with x2 and work from there.
size_t size = c->rsize * 2;
char *tmp = malloc(size);
if (!tmp)
return false;
memcpy(tmp, c->rcurr, c->rbytes);
do_cache_free(c->thread->rbuf_cache, c->rbuf);
c->rcurr = c->rbuf = tmp;
c->rsize = size;
c->rbuf_malloced = true;
return true;
}
/*
* Initializes the connections array. We don't actually allocate connection
* structures until they're needed, so as to avoid wasting memory when the
* maximum connection count is much higher than the actual number of
* connections.
*
* This does end up wasting a few pointers' worth of memory for FDs that are
* used for things other than connections, but that's worth it in exchange for
* being able to directly index the conns array by FD.
*/
static void conn_init(void) {
/* We're unlikely to see an FD much higher than maxconns. */
int next_fd = dup(1);
if (next_fd < 0) {
perror("Failed to duplicate file descriptor\n");
exit(1);
}
int headroom = 10; /* account for extra unexpected open FDs */
struct rlimit rl;
max_fds = settings.maxconns + headroom + next_fd;
/* But if possible, get the actual highest FD we can possibly ever see. */
if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
max_fds = rl.rlim_max;
} else {
fprintf(stderr, "Failed to query maximum file descriptor; "
"falling back to maxconns\n");
}
close(next_fd);
if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) {
fprintf(stderr, "Failed to allocate connection structures\n");
/* This is unrecoverable so bail out early. */
exit(1);
}
}
static const char *prot_text(enum protocol prot) {
char *rv = "unknown";
switch(prot) {
case ascii_prot:
rv = "ascii";
break;
case binary_prot:
rv = "binary";
break;
case negotiating_prot:
rv = "auto-negotiate";
break;
#ifdef PROXY
case proxy_prot:
rv = "proxy";
break;
#endif
}
return rv;
}
void conn_close_idle(conn *c) {
if (settings.idle_timeout > 0 &&
(current_time - c->last_cmd_time) > settings.idle_timeout) {
if (c->state != conn_new_cmd && c->state != conn_read) {
if (settings.verbose > 1)
fprintf(stderr,
"fd %d wants to timeout, but isn't in read state", c->sfd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, "Closing idle fd %d\n", c->sfd);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.idle_kicks++;
pthread_mutex_unlock(&c->thread->stats.mutex);
c->close_reason = IDLE_TIMEOUT_CLOSE;
conn_set_state(c, conn_closing);
drive_machine(c);
}
}
static void _conn_event_readd(conn *c) {
c->ev_flags = EV_READ | EV_PERSIST;
event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c);
event_base_set(c->thread->base, &c->event);
// TODO: call conn_cleanup/fail/etc
if (event_add(&c->event, 0) == -1) {
perror("event_add");
}
}
/* bring conn back from a sidethread. could have had its event base moved. */
void conn_worker_readd(conn *c) {
if (c->io_queues_submitted) { // TODO: ensure this is safe?
c->io_queues_submitted--;
// If we're still waiting for other queues to return, don't re-add the
// connection yet.
if (c->io_queues_submitted != 0) {
return;
}
}
switch (c->state) {
case conn_closing:
// might be fixable: only need to do this because we can't do
// event_del() without the event being armed.
_conn_event_readd(c);
drive_machine(c);
break;
case conn_io_pending:
// The event listener was removed as more data showed up while
// waiting for the async response.
_conn_event_readd(c);
// Explicit fall-through.
case conn_io_queue:
conn_set_state(c, conn_io_resume);
// machine will know how to return based on secondary state.
drive_machine(c);
break;
default:
_conn_event_readd(c);
conn_set_state(c, conn_new_cmd);
}
}
void thread_io_queue_add(LIBEVENT_THREAD *t, int type, void *ctx, io_queue_stack_cb cb) {
io_queue_cb_t *q = t->io_queues;
while (q->type != IO_QUEUE_NONE) {
q++;
}
q->type = type;
q->ctx = ctx;
q->submit_cb = cb;
return;
}
void conn_io_queue_setup(conn *c) {
io_queue_cb_t *qcb = c->thread->io_queues;
io_queue_t *q = c->io_queues;
while (qcb->type != IO_QUEUE_NONE) {
q->type = qcb->type;
q->ctx = qcb->ctx;
q->stack_ctx = NULL;
q->count = 0;
qcb++;
q++;
}
}
// To be called from conn_release_items to ensure the stack ptrs are reset.
static void conn_io_queue_reset(conn *c) {
for (io_queue_t *q = c->io_queues; q->type != IO_QUEUE_NONE; q++) {
assert(q->count == 0);
q->stack_ctx = NULL;
}
}
io_queue_cb_t *thread_io_queue_get(LIBEVENT_THREAD *t, int type) {
io_queue_cb_t *q = t->io_queues;
while (q->type != IO_QUEUE_NONE) {
if (q->type == type) {
return q;
}
q++;
}
return NULL;
}
io_queue_t *conn_io_queue_get(conn *c, int type) {
io_queue_t *q = c->io_queues;
while (q->type != IO_QUEUE_NONE) {
if (q->type == type) {
return q;
}
q++;
}
return NULL;
}
// called to return a single IO object to the original worker thread.
void conn_io_queue_return(io_pending_t *io) {
io->return_cb(io);
}
conn *conn_new(const int sfd, enum conn_states init_state,
const int event_flags,
const int read_buffer_size, enum network_transport transport,
struct event_base *base, void *ssl, uint64_t conntag,
enum protocol bproto) {
conn *c;
assert(sfd >= 0 && sfd < max_fds);
c = conns[sfd];
if (NULL == c) {
if (!(c = (conn *)calloc(1, sizeof(conn)))) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
fprintf(stderr, "Failed to allocate connection object\n");
return NULL;
}
MEMCACHED_CONN_CREATE(c);
c->read = NULL;
c->sendmsg = NULL;
c->write = NULL;
c->rbuf = NULL;
c->rsize = read_buffer_size;
// UDP connections use a persistent static buffer.
if (c->rsize) {
c->rbuf = (char *)malloc((size_t)c->rsize);
}
if (c->rsize && c->rbuf == NULL) {
conn_free(c);
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
fprintf(stderr, "Failed to allocate buffers for connection\n");
return NULL;
}
STATS_LOCK();
stats_state.conn_structs++;
STATS_UNLOCK();
c->sfd = sfd;
conns[sfd] = c;
}
c->transport = transport;
c->protocol = bproto;
c->tag = conntag;
/* unix socket mode doesn't need this, so zeroed out. but why
* is this done for every command? presumably for UDP
* mode. */
if (!settings.socketpath) {
c->request_addr_size = sizeof(c->request_addr);
} else {
c->request_addr_size = 0;
}
if (transport == tcp_transport && init_state == conn_new_cmd) {
if (getpeername(sfd, (struct sockaddr *) &c->request_addr,
&c->request_addr_size)) {
perror("getpeername");
memset(&c->request_addr, 0, sizeof(c->request_addr));
}
}
if (init_state == conn_new_cmd) {
LOGGER_LOG(NULL, LOG_CONNEVENTS, LOGGER_CONNECTION_NEW, NULL,
&c->request_addr, c->request_addr_size, c->transport, 0, sfd);
}
if (settings.verbose > 1) {
if (init_state == conn_listening) {
fprintf(stderr, "<%d server listening (%s)\n", sfd,
prot_text(c->protocol));
} else if (IS_UDP(transport)) {
fprintf(stderr, "<%d server listening (udp)\n", sfd);
} else if (c->protocol == negotiating_prot) {
fprintf(stderr, "<%d new auto-negotiating client connection\n",
sfd);
} else if (c->protocol == ascii_prot) {
fprintf(stderr, "<%d new ascii client connection.\n", sfd);
} else if (c->protocol == binary_prot) {
fprintf(stderr, "<%d new binary client connection.\n", sfd);
#ifdef PROXY
} else if (c->protocol == proxy_prot) {
fprintf(stderr, "<%d new proxy client connection.\n", sfd);
#endif
} else {
fprintf(stderr, "<%d new unknown (%d) client connection\n",
sfd, c->protocol);
assert(false);
}
}
#ifdef TLS
c->ssl = NULL;
c->ssl_wbuf = NULL;
c->ssl_enabled = false;
#endif
c->state = init_state;
c->rlbytes = 0;
c->cmd = -1;
c->rbytes = 0;
c->rcurr = c->rbuf;
c->ritem = 0;
c->rbuf_malloced = false;
c->item_malloced = false;
c->sasl_started = false;
c->set_stale = false;
c->mset_res = false;
c->close_after_write = false;
c->last_cmd_time = current_time; /* initialize for idle kicker */
// wipe all queues.
memset(c->io_queues, 0, sizeof(c->io_queues));
c->io_queues_submitted = 0;
c->item = 0;
c->noreply = false;
#ifdef TLS
if (ssl) {
c->ssl = (SSL*)ssl;
c->read = ssl_read;
c->sendmsg = ssl_sendmsg;
c->write = ssl_write;
c->ssl_enabled = true;
SSL_set_info_callback(c->ssl, ssl_callback);
} else
#else
// This must be NULL if TLS is not enabled.
assert(ssl == NULL);
#endif
{
c->read = tcp_read;
c->sendmsg = tcp_sendmsg;
c->write = tcp_write;
}
if (IS_UDP(transport)) {
c->try_read_command = try_read_command_udp;
} else {
switch (c->protocol) {
case ascii_prot:
if (settings.auth_file == NULL) {
c->authenticated = true;
c->try_read_command = try_read_command_ascii;
} else {
c->authenticated = false;
c->try_read_command = try_read_command_asciiauth;
}
break;
case binary_prot:
// binprot handles its own authentication via SASL parsing.
c->authenticated = false;
c->try_read_command = try_read_command_binary;
break;
case negotiating_prot:
c->try_read_command = try_read_command_negotiate;
break;
#ifdef PROXY
case proxy_prot:
c->try_read_command = try_read_command_proxy;
break;
#endif
}
}
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) {
perror("event_add");
return NULL;
}
STATS_LOCK();
stats_state.curr_conns++;
stats.total_conns++;
STATS_UNLOCK();
MEMCACHED_CONN_ALLOCATE(c->sfd);
return c;
}
void conn_release_items(conn *c) {
assert(c != NULL);
if (c->item) {
if (c->item_malloced) {
free(c->item);
c->item_malloced = false;
} else {
item_remove(c->item);
}
c->item = 0;
}
// Cull any unsent responses.
if (c->resp_head) {
mc_resp *resp = c->resp_head;
// r_f() handles the chain maintenance.
while (resp) {
// temporary by default. hide behind a debug flag in the future:
// double free detection. Transmit loops can drop out early, but
// here we could infinite loop.
if (resp->free) {
fprintf(stderr, "ERROR: double free detected during conn_release_items(): [%d] [%s]\n",
c->sfd, c->protocol == binary_prot ? "binary" : "ascii");
// Since this is a critical failure, just leak the memory.
// If these errors are seen, an abort() can be used instead.
c->resp_head = NULL;
c->resp = NULL;
break;
}
resp = resp_finish(c, resp);
}
conn_io_queue_reset(c);
}
}
static void conn_cleanup(conn *c) {
assert(c != NULL);
conn_release_items(c);
#ifdef PROXY
if (c->proxy_rctx) {
proxy_cleanup_conn(c);
}
#endif
if (c->sasl_conn) {
assert(settings.sasl);
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
}
if (IS_UDP(c->transport)) {
conn_set_state(c, conn_read);
}
}
/*
* Frees a connection.
*/
void conn_free(conn *c) {
if (c) {
assert(c != NULL);
assert(c->sfd >= 0 && c->sfd < max_fds);
MEMCACHED_CONN_DESTROY(c);
conns[c->sfd] = NULL;
if (c->rbuf)
free(c->rbuf);
#ifdef TLS
if (c->ssl_wbuf)
c->ssl_wbuf = NULL;
#endif
free(c);
}
}
static void conn_close(conn *c) {
assert(c != NULL);
if (c->thread) {
LOGGER_LOG(c->thread->l, LOG_CONNEVENTS, LOGGER_CONNECTION_CLOSE, NULL,
&c->request_addr, c->request_addr_size, c->transport,
c->close_reason, c->sfd);
}
/* delete the event, the socket and the conn */
event_del(&c->event);
if (settings.verbose > 1)
fprintf(stderr, "<%d connection closed.\n", c->sfd);
conn_cleanup(c);
// force release of read buffer.
if (c->thread) {
c->rbytes = 0;
rbuf_release(c);
}
MEMCACHED_CONN_RELEASE(c->sfd);
conn_set_state(c, conn_closed);
#ifdef TLS
if (c->ssl) {
SSL_shutdown(c->ssl);
SSL_free(c->ssl);
}
#endif
close(c->sfd);
c->close_reason = 0;
pthread_mutex_lock(&conn_lock);
allow_new_conns = true;
pthread_mutex_unlock(&conn_lock);
STATS_LOCK();
stats_state.curr_conns--;
STATS_UNLOCK();
return;
}
// Since some connections might be off on side threads and some are managed as
// listeners we need to walk through them all from a central point.
// Must be called with all worker threads hung or in the process of closing.
void conn_close_all(void) {
int i;
for (i = 0; i < max_fds; i++) {
if (conns[i] && conns[i]->state != conn_closed) {
conn_close(conns[i]);
}
}
}
/**
* Convert a state name to a human readable form.
*/
static const char *state_text(enum conn_states state) {
const char* const statenames[] = { "conn_listening",
"conn_new_cmd",
"conn_waiting",
"conn_read",
"conn_parse_cmd",
"conn_write",
"conn_nread",
"conn_swallow",
"conn_closing",
"conn_mwrite",
"conn_closed",
"conn_watch",
"conn_io_queue",
"conn_io_resume",
"conn_io_pending" };
return statenames[state];
}
/*
* Sets a connection's current state in the state machine. Any special
* processing that needs to happen on certain state transitions can
* happen here.
*/
void conn_set_state(conn *c, enum conn_states state) {
assert(c != NULL);
assert(state >= conn_listening && state < conn_max_state);