]> git.saurik.com Git - redis.git/blame - src/networking.c
Blocking POP: use a dictionary to store keys clinet side.
[redis.git] / src / networking.c
CommitLineData
d288ee65 1/*
2 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 */
29
e2641e09 30#include "redis.h"
e2641e09 31#include <sys/uio.h>
32
11e0c4c5 33static void setProtocolError(redisClient *c, int pos);
34
609baba8 35/* To evaluate the output buffer size of a client we need to get size of
36 * allocated objects, however we can't used zmalloc_size() directly on sds
37 * strings because of the trick they use to work (the header is before the
38 * returned pointer), so we use this helper function. */
39size_t zmalloc_size_sds(sds s) {
40 return zmalloc_size(s-sizeof(struct sdshdr));
41}
42
e2641e09 43void *dupClientReplyValue(void *o) {
44 incrRefCount((robj*)o);
45 return o;
46}
47
48int listMatchObjects(void *a, void *b) {
49 return equalStringObjects(a,b);
50}
51
52redisClient *createClient(int fd) {
f3357792 53 redisClient *c = zmalloc(sizeof(redisClient));
e2641e09 54
0f1d64ca 55 /* passing -1 as fd it is possible to create a non connected client.
56 * This is useful since all the Redis commands needs to be executed
57 * in the context of a client. When commands are executed in other
58 * contexts (for instance a Lua script) we need a non connected client. */
59 if (fd != -1) {
60 anetNonBlock(NULL,fd);
61 anetTcpNoDelay(NULL,fd);
62 if (aeCreateFileEvent(server.el,fd,AE_READABLE,
63 readQueryFromClient, c) == AE_ERR)
64 {
65 close(fd);
66 zfree(c);
67 return NULL;
68 }
106bd87a
PN
69 }
70
e2641e09 71 selectDb(c,0);
72 c->fd = fd;
56de4964 73 c->bufpos = 0;
e2641e09 74 c->querybuf = sdsempty();
9fa9ccb0 75 c->querybuf_peak = 0;
cd8788f2 76 c->reqtype = 0;
e2641e09 77 c->argc = 0;
78 c->argv = NULL;
2c74a9f9 79 c->cmd = c->lastcmd = NULL;
cd8788f2 80 c->multibulklen = 0;
e2641e09 81 c->bulklen = -1;
e2641e09 82 c->sentlen = 0;
83 c->flags = 0;
56ff70f8 84 c->ctime = c->lastinteraction = server.unixtime;
e2641e09 85 c->authenticated = 0;
86 c->replstate = REDIS_REPL_NONE;
dbd8c753 87 c->slave_listening_port = 0;
e2641e09 88 c->reply = listCreate();
3853c168 89 c->reply_bytes = 0;
7eac2a75 90 c->obuf_soft_limit_reached_time = 0;
e2641e09 91 listSetFreeMethod(c->reply,decrRefCount);
92 listSetDupMethod(c->reply,dupClientReplyValue);
54b08c86 93 c->bpop.keys = dictCreate(&setDictType,NULL);
e3c51c4b
DJMM
94 c->bpop.timeout = 0;
95 c->bpop.target = NULL;
e2641e09 96 c->io_keys = listCreate();
97 c->watched_keys = listCreate();
98 listSetFreeMethod(c->io_keys,decrRefCount);
99 c->pubsub_channels = dictCreate(&setDictType,NULL);
100 c->pubsub_patterns = listCreate();
101 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
102 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
7b722727 103 if (fd != -1) listAddNodeTail(server.clients,c);
e2641e09 104 initClientMultiState(c);
105 return c;
106}
107
51669c5a 108/* This function is called every time we are going to transmit new data
109 * to the client. The behavior is the following:
110 *
111 * If the client should receive new data (normal clients will) the function
112 * returns REDIS_OK, and make sure to install the write handler in our event
113 * loop so that when the socket is writable new data gets written.
114 *
115 * If the client should not receive new data, because it is a fake client
116 * or a slave, or because the setup of the write handler failed, the function
117 * returns REDIS_ERR.
118 *
119 * Typically gets called every time a reply is built, before adding more
120 * data to the clients output buffers. If the function returns REDIS_ERR no
121 * data should be appended to the output buffers. */
122int prepareClientToWrite(redisClient *c) {
7156f43c 123 if (c->flags & REDIS_LUA_CLIENT) return REDIS_OK;
51669c5a 124 if (c->fd <= 0) return REDIS_ERR; /* Fake client */
834ef78e 125 if (c->bufpos == 0 && listLength(c->reply) == 0 &&
e2641e09 126 (c->replstate == REDIS_REPL_NONE ||
127 c->replstate == REDIS_REPL_ONLINE) &&
128 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
834ef78e
PN
129 sendReplyToClient, c) == AE_ERR) return REDIS_ERR;
130 return REDIS_OK;
131}
132
36c19d03
PN
133/* Create a duplicate of the last object in the reply list when
134 * it is not exclusively owned by the reply list. */
135robj *dupLastObjectIfNeeded(list *reply) {
136 robj *new, *cur;
137 listNode *ln;
138 redisAssert(listLength(reply) > 0);
139 ln = listLast(reply);
140 cur = listNodeValue(ln);
141 if (cur->refcount > 1) {
142 new = dupStringObject(cur);
143 decrRefCount(cur);
144 listNodeValue(ln) = new;
145 }
146 return listNodeValue(ln);
834ef78e
PN
147}
148
25ef3192 149/* -----------------------------------------------------------------------------
150 * Low level functions to add more data to output buffers.
151 * -------------------------------------------------------------------------- */
152
36c19d03 153int _addReplyToBuffer(redisClient *c, char *s, size_t len) {
f3357792 154 size_t available = sizeof(c->buf)-c->bufpos;
36c19d03 155
25ef3192 156 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return REDIS_OK;
157
36c19d03
PN
158 /* If there already are entries in the reply list, we cannot
159 * add anything more to the static buffer. */
160 if (listLength(c->reply) > 0) return REDIS_ERR;
161
162 /* Check that the buffer has enough space available for this string. */
163 if (len > available) return REDIS_ERR;
e2641e09 164
36c19d03
PN
165 memcpy(c->buf+c->bufpos,s,len);
166 c->bufpos+=len;
167 return REDIS_OK;
834ef78e
PN
168}
169
36c19d03
PN
170void _addReplyObjectToList(redisClient *c, robj *o) {
171 robj *tail;
25ef3192 172
173 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
174
36c19d03
PN
175 if (listLength(c->reply) == 0) {
176 incrRefCount(o);
177 listAddNodeTail(c->reply,o);
609baba8 178 c->reply_bytes += zmalloc_size_sds(o->ptr);
36c19d03
PN
179 } else {
180 tail = listNodeValue(listLast(c->reply));
181
182 /* Append to this object when possible. */
183 if (tail->ptr != NULL &&
184 sdslen(tail->ptr)+sdslen(o->ptr) <= REDIS_REPLY_CHUNK_BYTES)
185 {
609baba8 186 c->reply_bytes -= zmalloc_size_sds(tail->ptr);
36c19d03
PN
187 tail = dupLastObjectIfNeeded(c->reply);
188 tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr));
609baba8 189 c->reply_bytes += zmalloc_size_sds(tail->ptr);
36c19d03
PN
190 } else {
191 incrRefCount(o);
192 listAddNodeTail(c->reply,o);
609baba8 193 c->reply_bytes += zmalloc_size_sds(o->ptr);
36c19d03
PN
194 }
195 }
7eac2a75 196 asyncCloseClientOnOutputBufferLimitReached(c);
36c19d03 197}
834ef78e 198
36c19d03
PN
199/* This method takes responsibility over the sds. When it is no longer
200 * needed it will be free'd, otherwise it ends up in a robj. */
201void _addReplySdsToList(redisClient *c, sds s) {
202 robj *tail;
25ef3192 203
5b94b8ac 204 if (c->flags & REDIS_CLOSE_AFTER_REPLY) {
205 sdsfree(s);
206 return;
207 }
25ef3192 208
36c19d03
PN
209 if (listLength(c->reply) == 0) {
210 listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
609baba8 211 c->reply_bytes += zmalloc_size_sds(s);
36c19d03
PN
212 } else {
213 tail = listNodeValue(listLast(c->reply));
214
215 /* Append to this object when possible. */
216 if (tail->ptr != NULL &&
217 sdslen(tail->ptr)+sdslen(s) <= REDIS_REPLY_CHUNK_BYTES)
218 {
609baba8 219 c->reply_bytes -= zmalloc_size_sds(tail->ptr);
36c19d03
PN
220 tail = dupLastObjectIfNeeded(c->reply);
221 tail->ptr = sdscatlen(tail->ptr,s,sdslen(s));
609baba8 222 c->reply_bytes += zmalloc_size_sds(tail->ptr);
36c19d03 223 sdsfree(s);
834ef78e 224 } else {
36c19d03 225 listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
609baba8 226 c->reply_bytes += zmalloc_size_sds(s);
834ef78e 227 }
36c19d03 228 }
7eac2a75 229 asyncCloseClientOnOutputBufferLimitReached(c);
36c19d03
PN
230}
231
232void _addReplyStringToList(redisClient *c, char *s, size_t len) {
233 robj *tail;
25ef3192 234
235 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
236
36c19d03 237 if (listLength(c->reply) == 0) {
442246dd 238 robj *o = createStringObject(s,len);
239
240 listAddNodeTail(c->reply,o);
609baba8 241 c->reply_bytes += zmalloc_size_sds(o->ptr);
834ef78e 242 } else {
36c19d03
PN
243 tail = listNodeValue(listLast(c->reply));
244
245 /* Append to this object when possible. */
246 if (tail->ptr != NULL &&
247 sdslen(tail->ptr)+len <= REDIS_REPLY_CHUNK_BYTES)
248 {
609baba8 249 c->reply_bytes -= zmalloc_size_sds(tail->ptr);
36c19d03
PN
250 tail = dupLastObjectIfNeeded(c->reply);
251 tail->ptr = sdscatlen(tail->ptr,s,len);
609baba8 252 c->reply_bytes += zmalloc_size_sds(tail->ptr);
834ef78e 253 } else {
442246dd 254 robj *o = createStringObject(s,len);
255
256 listAddNodeTail(c->reply,o);
609baba8 257 c->reply_bytes += zmalloc_size_sds(o->ptr);
834ef78e
PN
258 }
259 }
7eac2a75 260 asyncCloseClientOnOutputBufferLimitReached(c);
834ef78e 261}
e2641e09 262
25ef3192 263/* -----------------------------------------------------------------------------
264 * Higher level functions to queue data on the client output buffer.
265 * The following functions are the ones that commands implementations will call.
266 * -------------------------------------------------------------------------- */
267
834ef78e 268void addReply(redisClient *c, robj *obj) {
51669c5a 269 if (prepareClientToWrite(c) != REDIS_OK) return;
4c2e506a 270
271 /* This is an important place where we can avoid copy-on-write
272 * when there is a saving child running, avoiding touching the
273 * refcount field of the object if it's not needed.
274 *
275 * If the encoding is RAW and there is room in the static buffer
276 * we'll be able to send the object to the client without
277 * messing with its page. */
278 if (obj->encoding == REDIS_ENCODING_RAW) {
279 if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
280 _addReplyObjectToList(c,obj);
51669c5a 281 } else if (obj->encoding == REDIS_ENCODING_INT) {
282 /* Optimization: if there is room in the static buffer for 32 bytes
283 * (more than the max chars a 64 bit integer can take as string) we
284 * avoid decoding the object and go for the lower level approach. */
285 if (listLength(c->reply) == 0 && (sizeof(c->buf) - c->bufpos) >= 32) {
286 char buf[32];
287 int len;
288
289 len = ll2string(buf,sizeof(buf),(long)obj->ptr);
290 if (_addReplyToBuffer(c,buf,len) == REDIS_OK)
291 return;
292 /* else... continue with the normal code path, but should never
293 * happen actually since we verified there is room. */
294 }
834ef78e 295 obj = getDecodedObject(obj);
4c2e506a 296 if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
297 _addReplyObjectToList(c,obj);
298 decrRefCount(obj);
51669c5a 299 } else {
300 redisPanic("Wrong obj->encoding in addReply()");
e2641e09 301 }
e2641e09 302}
303
304void addReplySds(redisClient *c, sds s) {
51669c5a 305 if (prepareClientToWrite(c) != REDIS_OK) {
cd76bb65
PN
306 /* The caller expects the sds to be free'd. */
307 sdsfree(s);
308 return;
309 }
36c19d03 310 if (_addReplyToBuffer(c,s,sdslen(s)) == REDIS_OK) {
834ef78e
PN
311 sdsfree(s);
312 } else {
36c19d03
PN
313 /* This method free's the sds when it is no longer needed. */
314 _addReplySdsToList(c,s);
834ef78e 315 }
e2641e09 316}
317
834ef78e 318void addReplyString(redisClient *c, char *s, size_t len) {
51669c5a 319 if (prepareClientToWrite(c) != REDIS_OK) return;
36c19d03
PN
320 if (_addReplyToBuffer(c,s,len) != REDIS_OK)
321 _addReplyStringToList(c,s,len);
834ef78e 322}
e2641e09 323
51669c5a 324void addReplyErrorLength(redisClient *c, char *s, size_t len) {
3ab20376
PN
325 addReplyString(c,"-ERR ",5);
326 addReplyString(c,s,len);
327 addReplyString(c,"\r\n",2);
e2641e09 328}
329
3ab20376 330void addReplyError(redisClient *c, char *err) {
51669c5a 331 addReplyErrorLength(c,err,strlen(err));
3ab20376 332}
e2641e09 333
3ab20376 334void addReplyErrorFormat(redisClient *c, const char *fmt, ...) {
3bb818df 335 size_t l, j;
3ab20376
PN
336 va_list ap;
337 va_start(ap,fmt);
338 sds s = sdscatvprintf(sdsempty(),fmt,ap);
339 va_end(ap);
3bb818df 340 /* Make sure there are no newlines in the string, otherwise invalid protocol
341 * is emitted. */
342 l = sdslen(s);
343 for (j = 0; j < l; j++) {
344 if (s[j] == '\r' || s[j] == '\n') s[j] = ' ';
345 }
51669c5a 346 addReplyErrorLength(c,s,sdslen(s));
3ab20376
PN
347 sdsfree(s);
348}
349
51669c5a 350void addReplyStatusLength(redisClient *c, char *s, size_t len) {
3ab20376
PN
351 addReplyString(c,"+",1);
352 addReplyString(c,s,len);
353 addReplyString(c,"\r\n",2);
354}
355
356void addReplyStatus(redisClient *c, char *status) {
51669c5a 357 addReplyStatusLength(c,status,strlen(status));
3ab20376
PN
358}
359
360void addReplyStatusFormat(redisClient *c, const char *fmt, ...) {
361 va_list ap;
362 va_start(ap,fmt);
363 sds s = sdscatvprintf(sdsempty(),fmt,ap);
364 va_end(ap);
51669c5a 365 addReplyStatusLength(c,s,sdslen(s));
3ab20376
PN
366 sdsfree(s);
367}
368
b301c1fc
PN
369/* Adds an empty object to the reply list that will contain the multi bulk
370 * length, which is not known when this function is called. */
371void *addDeferredMultiBulkLength(redisClient *c) {
4c2e506a 372 /* Note that we install the write event here even if the object is not
373 * ready to be sent, since we are sure that before returning to the
374 * event loop setDeferredMultiBulkLength() will be called. */
51669c5a 375 if (prepareClientToWrite(c) != REDIS_OK) return NULL;
36c19d03 376 listAddNodeTail(c->reply,createObject(REDIS_STRING,NULL));
b301c1fc
PN
377 return listLast(c->reply);
378}
379
380/* Populate the length object and try glueing it to the next chunk. */
381void setDeferredMultiBulkLength(redisClient *c, void *node, long length) {
382 listNode *ln = (listNode*)node;
383 robj *len, *next;
384
385 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
386 if (node == NULL) return;
387
388 len = listNodeValue(ln);
389 len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length);
609baba8 390 c->reply_bytes += zmalloc_size_sds(len->ptr);
b301c1fc
PN
391 if (ln->next != NULL) {
392 next = listNodeValue(ln->next);
36c19d03 393
49128f0b 394 /* Only glue when the next node is non-NULL (an sds in this case) */
36c19d03 395 if (next->ptr != NULL) {
6fe9c402 396 c->reply_bytes -= zmalloc_size_sds(len->ptr);
397 c->reply_bytes -= zmalloc_size_sds(next->ptr);
49128f0b 398 len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr));
6fe9c402 399 c->reply_bytes += zmalloc_size_sds(len->ptr);
b301c1fc
PN
400 listDelNode(c->reply,ln->next);
401 }
e2641e09 402 }
7eac2a75 403 asyncCloseClientOnOutputBufferLimitReached(c);
b301c1fc
PN
404}
405
d51ebef5 406/* Add a duble as a bulk reply */
834ef78e
PN
407void addReplyDouble(redisClient *c, double d) {
408 char dbuf[128], sbuf[128];
409 int dlen, slen;
410 dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d);
411 slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf);
412 addReplyString(c,sbuf,slen);
e2641e09 413}
414
d51ebef5 415/* Add a long long as integer reply or bulk len / multi bulk count.
416 * Basically this is used to output <prefix><long long><crlf>. */
51669c5a 417void addReplyLongLongWithPrefix(redisClient *c, long long ll, char prefix) {
e2641e09 418 char buf[128];
834ef78e 419 int len;
355f8591 420
421 /* Things like $3\r\n or *2\r\n are emitted very often by the protocol
422 * so we have a few shared objects to use if the integer is small
423 * like it is most of the times. */
424 if (prefix == '*' && ll < REDIS_SHARED_BULKHDR_LEN) {
425 addReply(c,shared.mbulkhdr[ll]);
426 return;
427 } else if (prefix == '$' && ll < REDIS_SHARED_BULKHDR_LEN) {
428 addReply(c,shared.bulkhdr[ll]);
429 return;
430 }
431
834ef78e 432 buf[0] = prefix;
e2641e09 433 len = ll2string(buf+1,sizeof(buf)-1,ll);
434 buf[len+1] = '\r';
435 buf[len+2] = '\n';
834ef78e 436 addReplyString(c,buf,len+3);
e2641e09 437}
438
834ef78e 439void addReplyLongLong(redisClient *c, long long ll) {
009db676 440 if (ll == 0)
441 addReply(c,shared.czero);
442 else if (ll == 1)
443 addReply(c,shared.cone);
444 else
51669c5a 445 addReplyLongLongWithPrefix(c,ll,':');
834ef78e 446}
e2641e09 447
0537e7bf 448void addReplyMultiBulkLen(redisClient *c, long length) {
51669c5a 449 addReplyLongLongWithPrefix(c,length,'*');
e2641e09 450}
451
d51ebef5 452/* Create the length prefix of a bulk reply, example: $2234 */
e2641e09 453void addReplyBulkLen(redisClient *c, robj *obj) {
834ef78e 454 size_t len;
e2641e09 455
456 if (obj->encoding == REDIS_ENCODING_RAW) {
457 len = sdslen(obj->ptr);
458 } else {
459 long n = (long)obj->ptr;
460
461 /* Compute how many bytes will take this integer as a radix 10 string */
462 len = 1;
463 if (n < 0) {
464 len++;
465 n = -n;
466 }
467 while((n = n/10) != 0) {
468 len++;
469 }
470 }
51669c5a 471 addReplyLongLongWithPrefix(c,len,'$');
e2641e09 472}
473
d51ebef5 474/* Add a Redis Object as a bulk reply */
e2641e09 475void addReplyBulk(redisClient *c, robj *obj) {
476 addReplyBulkLen(c,obj);
477 addReply(c,obj);
478 addReply(c,shared.crlf);
479}
480
d51ebef5 481/* Add a C buffer as bulk reply */
482void addReplyBulkCBuffer(redisClient *c, void *p, size_t len) {
51669c5a 483 addReplyLongLongWithPrefix(c,len,'$');
d51ebef5 484 addReplyString(c,p,len);
485 addReply(c,shared.crlf);
486}
487
488/* Add a C nul term string as bulk reply */
e2641e09 489void addReplyBulkCString(redisClient *c, char *s) {
490 if (s == NULL) {
491 addReply(c,shared.nullbulk);
492 } else {
d51ebef5 493 addReplyBulkCBuffer(c,s,strlen(s));
e2641e09 494 }
495}
496
d51ebef5 497/* Add a long long as a bulk reply */
498void addReplyBulkLongLong(redisClient *c, long long ll) {
499 char buf[64];
500 int len;
501
502 len = ll2string(buf,64,ll);
503 addReplyBulkCBuffer(c,buf,len);
504}
505
1824e3a3 506/* Copy 'src' client output buffers into 'dst' client output buffers.
507 * The function takes care of freeing the old output buffers of the
508 * destination client. */
509void copyClientOutputBuffer(redisClient *dst, redisClient *src) {
510 listRelease(dst->reply);
511 dst->reply = listDup(src->reply);
512 memcpy(dst->buf,src->buf,src->bufpos);
513 dst->bufpos = src->bufpos;
3853c168 514 dst->reply_bytes = src->reply_bytes;
1824e3a3 515}
516
b6ffa85f 517static void acceptCommonHandler(int fd, int flags) {
e2641e09 518 redisClient *c;
ab17b909 519 if ((c = createClient(fd)) == NULL) {
ed44a74e
YF
520 redisLog(REDIS_WARNING,"Error allocating resources for the client");
521 close(fd); /* May be already closed, just ignore errors */
e2641e09 522 return;
523 }
524 /* If maxclient directive is set and this is one client more... close the
525 * connection. Note that we create the client instead to check before
526 * for this condition, since now the socket is already set in nonblocking
527 * mode and we can send an error for free using the Kernel I/O */
58732c23 528 if (listLength(server.clients) > server.maxclients) {
e2641e09 529 char *err = "-ERR max number of clients reached\r\n";
530
531 /* That's a best effort error message, don't check write errors */
532 if (write(c->fd,err,strlen(err)) == -1) {
533 /* Nothing to do, Just to avoid the warning... */
534 }
3c95e721 535 server.stat_rejected_conn++;
e2641e09 536 freeClient(c);
537 return;
538 }
539 server.stat_numconnections++;
b6ffa85f 540 c->flags |= flags;
e2641e09 541}
542
ab17b909
PN
543void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
544 int cport, cfd;
545 char cip[128];
546 REDIS_NOTUSED(el);
547 REDIS_NOTUSED(mask);
548 REDIS_NOTUSED(privdata);
549
550 cfd = anetTcpAccept(server.neterr, fd, cip, &cport);
551 if (cfd == AE_ERR) {
df541bea 552 redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr);
ab17b909
PN
553 return;
554 }
555 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
b6ffa85f 556 acceptCommonHandler(cfd,0);
ab17b909
PN
557}
558
559void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
560 int cfd;
ab17b909
PN
561 REDIS_NOTUSED(el);
562 REDIS_NOTUSED(mask);
563 REDIS_NOTUSED(privdata);
564
4fe83b55 565 cfd = anetUnixAccept(server.neterr, fd);
ab17b909 566 if (cfd == AE_ERR) {
df541bea 567 redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr);
ab17b909
PN
568 return;
569 }
570 redisLog(REDIS_VERBOSE,"Accepted connection to %s", server.unixsocket);
b6ffa85f 571 acceptCommonHandler(cfd,REDIS_UNIX_SOCKET);
ab17b909
PN
572}
573
574
e2641e09 575static void freeClientArgv(redisClient *c) {
576 int j;
e2641e09 577 for (j = 0; j < c->argc; j++)
578 decrRefCount(c->argv[j]);
e2641e09 579 c->argc = 0;
09e2d9ee 580 c->cmd = NULL;
e2641e09 581}
582
ed4d4f11 583/* Close all the slaves connections. This is useful in chained replication
584 * when we resync with our own master and want to force all our slaves to
585 * resync with us as well. */
586void disconnectSlaves(void) {
587 while (listLength(server.slaves)) {
588 listNode *ln = listFirst(server.slaves);
589 freeClient((redisClient*)ln->value);
590 }
591}
592
e2641e09 593void freeClient(redisClient *c) {
594 listNode *ln;
595
00010fa9 596 /* If this is marked as current client unset it */
597 if (server.current_client == c) server.current_client = NULL;
598
e2641e09 599 /* Note that if the client we are freeing is blocked into a blocking
600 * call, we have to set querybuf to NULL *before* to call
601 * unblockClientWaitingData() to avoid processInputBuffer() will get
602 * called. Also it is important to remove the file events after
603 * this, because this call adds the READABLE event. */
604 sdsfree(c->querybuf);
605 c->querybuf = NULL;
606 if (c->flags & REDIS_BLOCKED)
607 unblockClientWaitingData(c);
608
609 /* UNWATCH all the keys */
610 unwatchAllKeys(c);
611 listRelease(c->watched_keys);
612 /* Unsubscribe from all the pubsub channels */
613 pubsubUnsubscribeAllChannels(c,0);
614 pubsubUnsubscribeAllPatterns(c,0);
615 dictRelease(c->pubsub_channels);
616 listRelease(c->pubsub_patterns);
617 /* Obvious cleanup */
618 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
619 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
620 listRelease(c->reply);
621 freeClientArgv(c);
622 close(c->fd);
623 /* Remove from the list of clients */
624 ln = listSearchKey(server.clients,c);
625 redisAssert(ln != NULL);
626 listDelNode(server.clients,ln);
3bcffcbe
PN
627 /* When client was just unblocked because of a blocking operation,
628 * remove it from the list with unblocked clients. */
629 if (c->flags & REDIS_UNBLOCKED) {
630 ln = listSearchKey(server.unblocked_clients,c);
631 redisAssert(ln != NULL);
632 listDelNode(server.unblocked_clients,ln);
633 }
e2641e09 634 listRelease(c->io_keys);
778b2210 635 /* Master/slave cleanup.
636 * Case 1: we lost the connection with a slave. */
e2641e09 637 if (c->flags & REDIS_SLAVE) {
638 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
639 close(c->repldbfd);
640 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
641 ln = listSearchKey(l,c);
642 redisAssert(ln != NULL);
643 listDelNode(l,ln);
644 }
778b2210 645
646 /* Case 2: we lost the connection with the master. */
e2641e09 647 if (c->flags & REDIS_MASTER) {
648 server.master = NULL;
1844f990 649 server.repl_state = REDIS_REPL_CONNECT;
56ff70f8 650 server.repl_down_since = server.unixtime;
ed4d4f11 651 /* We lost connection with our master, force our slaves to resync
652 * with us as well to load the new data set.
d37299e3 653 *
f1e38b35 654 * If server.masterhost is NULL the user called SLAVEOF NO ONE so
ed4d4f11 655 * slave resync is not needed. */
656 if (server.masterhost != NULL) disconnectSlaves();
e2641e09 657 }
7eac2a75 658
659 /* If this client was scheduled for async freeing we need to remove it
660 * from the queue. */
661 if (c->flags & REDIS_CLOSE_ASAP) {
662 ln = listSearchKey(server.clients_to_close,c);
663 redisAssert(ln != NULL);
664 listDelNode(server.clients_to_close,ln);
665 }
666
e2641e09 667 /* Release memory */
668 zfree(c->argv);
e2641e09 669 freeClientMultiState(c);
670 zfree(c);
671}
672
7eac2a75 673/* Schedule a client to free it at a safe time in the serverCron() function.
674 * This function is useful when we need to terminate a client but we are in
675 * a context where calling freeClient() is not possible, because the client
676 * should be valid for the continuation of the flow of the program. */
677void freeClientAsync(redisClient *c) {
678 if (c->flags & REDIS_CLOSE_ASAP) return;
679 c->flags |= REDIS_CLOSE_ASAP;
680 listAddNodeTail(server.clients_to_close,c);
681}
682
683void freeClientsInAsyncFreeQueue(void) {
684 while (listLength(server.clients_to_close)) {
685 listNode *ln = listFirst(server.clients_to_close);
686 redisClient *c = listNodeValue(ln);
687
688 c->flags &= ~REDIS_CLOSE_ASAP;
689 freeClient(c);
690 listDelNode(server.clients_to_close,ln);
691 }
692}
693
e2641e09 694void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
695 redisClient *c = privdata;
696 int nwritten = 0, totwritten = 0, objlen;
442246dd 697 size_t objmem;
e2641e09 698 robj *o;
699 REDIS_NOTUSED(el);
700 REDIS_NOTUSED(mask);
701
834ef78e
PN
702 while(c->bufpos > 0 || listLength(c->reply)) {
703 if (c->bufpos > 0) {
704 if (c->flags & REDIS_MASTER) {
705 /* Don't reply to a master */
706 nwritten = c->bufpos - c->sentlen;
707 } else {
708 nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen);
709 if (nwritten <= 0) break;
710 }
711 c->sentlen += nwritten;
712 totwritten += nwritten;
713
714 /* If the buffer was sent, set bufpos to zero to continue with
715 * the remainder of the reply. */
716 if (c->sentlen == c->bufpos) {
717 c->bufpos = 0;
718 c->sentlen = 0;
719 }
720 } else {
721 o = listNodeValue(listFirst(c->reply));
722 objlen = sdslen(o->ptr);
609baba8 723 objmem = zmalloc_size_sds(o->ptr);
e2641e09 724
834ef78e
PN
725 if (objlen == 0) {
726 listDelNode(c->reply,listFirst(c->reply));
727 continue;
728 }
e2641e09 729
834ef78e
PN
730 if (c->flags & REDIS_MASTER) {
731 /* Don't reply to a master */
732 nwritten = objlen - c->sentlen;
733 } else {
734 nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen);
735 if (nwritten <= 0) break;
736 }
737 c->sentlen += nwritten;
738 totwritten += nwritten;
e2641e09 739
834ef78e
PN
740 /* If we fully sent the object on head go to the next one */
741 if (c->sentlen == objlen) {
742 listDelNode(c->reply,listFirst(c->reply));
743 c->sentlen = 0;
442246dd 744 c->reply_bytes -= objmem;
834ef78e 745 }
e2641e09 746 }
f6b32c14 747 /* Note that we avoid to send more than REDIS_MAX_WRITE_PER_EVENT
e2641e09 748 * bytes, in a single threaded server it's a good idea to serve
749 * other clients as well, even if a very large request comes from
750 * super fast link that is always able to accept data (in real world
f6b32c14 751 * scenario think about 'KEYS *' against the loopback interface).
752 *
753 * However if we are over the maxmemory limit we ignore that and
754 * just deliver as much data as it is possible to deliver. */
755 if (totwritten > REDIS_MAX_WRITE_PER_EVENT &&
756 (server.maxmemory == 0 ||
757 zmalloc_used_memory() < server.maxmemory)) break;
e2641e09 758 }
759 if (nwritten == -1) {
760 if (errno == EAGAIN) {
761 nwritten = 0;
762 } else {
763 redisLog(REDIS_VERBOSE,
764 "Error writing to client: %s", strerror(errno));
765 freeClient(c);
766 return;
767 }
768 }
56ff70f8 769 if (totwritten > 0) c->lastinteraction = server.unixtime;
3bc89500 770 if (c->bufpos == 0 && listLength(c->reply) == 0) {
e2641e09 771 c->sentlen = 0;
772 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
941c9fa2
PN
773
774 /* Close connection after entire reply has been sent. */
cd8788f2 775 if (c->flags & REDIS_CLOSE_AFTER_REPLY) freeClient(c);
e2641e09 776 }
777}
778
e2641e09 779/* resetClient prepare the client to process the next command */
780void resetClient(redisClient *c) {
781 freeClientArgv(c);
cd8788f2
PN
782 c->reqtype = 0;
783 c->multibulklen = 0;
e2641e09 784 c->bulklen = -1;
6856c7b4 785 /* We clear the ASKING flag as well if we are not inside a MULTI. */
786 if (!(c->flags & REDIS_MULTI)) c->flags &= (~REDIS_ASKING);
e2641e09 787}
788
cd8788f2
PN
789int processInlineBuffer(redisClient *c) {
790 char *newline = strstr(c->querybuf,"\r\n");
791 int argc, j;
792 sds *argv;
793 size_t querylen;
794
795 /* Nothing to do without a \r\n */
11e0c4c5 796 if (newline == NULL) {
797 if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) {
798 addReplyError(c,"Protocol error: too big inline request");
799 setProtocolError(c,0);
800 }
cd8788f2 801 return REDIS_ERR;
11e0c4c5 802 }
cd8788f2
PN
803
804 /* Split the input buffer up to the \r\n */
805 querylen = newline-(c->querybuf);
806 argv = sdssplitlen(c->querybuf,querylen," ",1,&argc);
807
808 /* Leave data after the first line of the query in the buffer */
809 c->querybuf = sdsrange(c->querybuf,querylen+2,-1);
810
811 /* Setup argv array on client structure */
812 if (c->argv) zfree(c->argv);
813 c->argv = zmalloc(sizeof(robj*)*argc);
814
815 /* Create redis objects for all arguments. */
816 for (c->argc = 0, j = 0; j < argc; j++) {
817 if (sdslen(argv[j])) {
818 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
819 c->argc++;
820 } else {
821 sdsfree(argv[j]);
822 }
823 }
824 zfree(argv);
825 return REDIS_OK;
826}
827
828/* Helper function. Trims query buffer to make the function that processes
829 * multi bulk requests idempotent. */
830static void setProtocolError(redisClient *c, int pos) {
3e0a975e 831 if (server.verbosity >= REDIS_VERBOSE) {
832 sds client = getClientInfoString(c);
833 redisLog(REDIS_VERBOSE,
834 "Protocol error from client: %s", client);
835 sdsfree(client);
836 }
cd8788f2
PN
837 c->flags |= REDIS_CLOSE_AFTER_REPLY;
838 c->querybuf = sdsrange(c->querybuf,pos,-1);
839}
840
841int processMultibulkBuffer(redisClient *c) {
842 char *newline = NULL;
5af30201
PN
843 int pos = 0, ok;
844 long long ll;
cd8788f2
PN
845
846 if (c->multibulklen == 0) {
847 /* The client should have been reset */
eab0e26e 848 redisAssertWithInfo(c,NULL,c->argc == 0);
cd8788f2
PN
849
850 /* Multi bulk length cannot be read without a \r\n */
5af30201 851 newline = strchr(c->querybuf,'\r');
11e0c4c5 852 if (newline == NULL) {
853 if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) {
854 addReplyError(c,"Protocol error: too big mbulk count string");
855 setProtocolError(c,0);
856 }
cd8788f2 857 return REDIS_ERR;
11e0c4c5 858 }
cd8788f2 859
bf9fd5ff
PN
860 /* Buffer should also contain \n */
861 if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2))
862 return REDIS_ERR;
863
cd8788f2
PN
864 /* We know for sure there is a whole line since newline != NULL,
865 * so go ahead and find out the multi bulk length. */
eab0e26e 866 redisAssertWithInfo(c,NULL,c->querybuf[0] == '*');
5af30201
PN
867 ok = string2ll(c->querybuf+1,newline-(c->querybuf+1),&ll);
868 if (!ok || ll > 1024*1024) {
b19c33d4
PN
869 addReplyError(c,"Protocol error: invalid multibulk length");
870 setProtocolError(c,pos);
871 return REDIS_ERR;
cd8788f2 872 }
af0e51f2
PN
873
874 pos = (newline-c->querybuf)+2;
875 if (ll <= 0) {
876 c->querybuf = sdsrange(c->querybuf,pos,-1);
877 return REDIS_OK;
878 }
879
5af30201 880 c->multibulklen = ll;
cd8788f2
PN
881
882 /* Setup argv array on client structure */
883 if (c->argv) zfree(c->argv);
884 c->argv = zmalloc(sizeof(robj*)*c->multibulklen);
cd8788f2
PN
885 }
886
eab0e26e 887 redisAssertWithInfo(c,NULL,c->multibulklen > 0);
cd8788f2
PN
888 while(c->multibulklen) {
889 /* Read bulk length if unknown */
890 if (c->bulklen == -1) {
5af30201 891 newline = strchr(c->querybuf+pos,'\r');
11e0c4c5 892 if (newline == NULL) {
893 if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) {
894 addReplyError(c,"Protocol error: too big bulk count string");
895 setProtocolError(c,0);
896 }
bf9fd5ff 897 break;
11e0c4c5 898 }
bf9fd5ff
PN
899
900 /* Buffer should also contain \n */
901 if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2))
cd8788f2 902 break;
bf9fd5ff
PN
903
904 if (c->querybuf[pos] != '$') {
905 addReplyErrorFormat(c,
906 "Protocol error: expected '$', got '%c'",
907 c->querybuf[pos]);
908 setProtocolError(c,pos);
909 return REDIS_ERR;
e2641e09 910 }
bf9fd5ff
PN
911
912 ok = string2ll(c->querybuf+pos+1,newline-(c->querybuf+pos+1),&ll);
913 if (!ok || ll < 0 || ll > 512*1024*1024) {
914 addReplyError(c,"Protocol error: invalid bulk length");
915 setProtocolError(c,pos);
916 return REDIS_ERR;
917 }
918
919 pos += newline-(c->querybuf+pos)+2;
94d490b9 920 if (ll >= REDIS_MBULK_BIG_ARG) {
826b5beb 921 /* If we are going to read a large object from network
922 * try to make it likely that it will start at c->querybuf
923 * boundary so that we can optimized object creation
924 * avoiding a large copy of data. */
925 c->querybuf = sdsrange(c->querybuf,pos,-1);
926 pos = 0;
b9031458 927 /* Hint the sds library about the amount of bytes this string is
928 * going to contain. */
94d490b9 929 c->querybuf = sdsMakeRoomFor(c->querybuf,ll+2);
b9031458 930 }
bf9fd5ff 931 c->bulklen = ll;
cd8788f2
PN
932 }
933
934 /* Read bulk argument */
935 if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) {
936 /* Not enough data (+2 == trailing \r\n) */
937 break;
938 } else {
92170955 939 /* Optimization: if the buffer contanins JUST our bulk element
940 * instead of creating a new object by *copying* the sds we
941 * just use the current sds string. */
942 if (pos == 0 &&
94d490b9 943 c->bulklen >= REDIS_MBULK_BIG_ARG &&
92170955 944 (signed) sdslen(c->querybuf) == c->bulklen+2)
945 {
946 c->argv[c->argc++] = createObject(REDIS_STRING,c->querybuf);
947 sdsIncrLen(c->querybuf,-2); /* remove CRLF */
948 c->querybuf = sdsempty();
949 /* Assume that if we saw a fat argument we'll see another one
950 * likely... */
951 c->querybuf = sdsMakeRoomFor(c->querybuf,c->bulklen+2);
952 pos = 0;
953 } else {
954 c->argv[c->argc++] =
955 createStringObject(c->querybuf+pos,c->bulklen);
956 pos += c->bulklen+2;
957 }
cd8788f2
PN
958 c->bulklen = -1;
959 c->multibulklen--;
960 }
961 }
962
963 /* Trim to pos */
92170955 964 if (pos) c->querybuf = sdsrange(c->querybuf,pos,-1);
cd8788f2
PN
965
966 /* We're done when c->multibulk == 0 */
11e0c4c5 967 if (c->multibulklen == 0) return REDIS_OK;
968
969 /* Still not read to process the command */
cd8788f2
PN
970 return REDIS_ERR;
971}
972
973void processInputBuffer(redisClient *c) {
974 /* Keep processing while there is something in the input buffer */
975 while(sdslen(c->querybuf)) {
64f201c2
HW
976 /* Immediately abort if the client is in the middle of something. */
977 if (c->flags & REDIS_BLOCKED) return;
978
5e78edb3
PN
979 /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
980 * written to the client. Make sure to not let the reply grow after
981 * this flag has been set (i.e. don't process more commands). */
982 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
cd8788f2
PN
983
984 /* Determine request type when unknown. */
985 if (!c->reqtype) {
986 if (c->querybuf[0] == '*') {
987 c->reqtype = REDIS_REQ_MULTIBULK;
e2641e09 988 } else {
cd8788f2 989 c->reqtype = REDIS_REQ_INLINE;
e2641e09 990 }
e2641e09 991 }
cd8788f2
PN
992
993 if (c->reqtype == REDIS_REQ_INLINE) {
994 if (processInlineBuffer(c) != REDIS_OK) break;
995 } else if (c->reqtype == REDIS_REQ_MULTIBULK) {
996 if (processMultibulkBuffer(c) != REDIS_OK) break;
997 } else {
998 redisPanic("Unknown request type");
e2641e09 999 }
cd8788f2
PN
1000
1001 /* Multibulk processing could see a <= 0 length. */
9da6caac
PN
1002 if (c->argc == 0) {
1003 resetClient(c);
1004 } else {
1005 /* Only reset the client when the command was executed. */
1006 if (processCommand(c) == REDIS_OK)
1007 resetClient(c);
1008 }
e2641e09 1009 }
1010}
1011
1012void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
1013 redisClient *c = (redisClient*) privdata;
826b5beb 1014 int nread, readlen;
b8d743e1 1015 size_t qblen;
e2641e09 1016 REDIS_NOTUSED(el);
1017 REDIS_NOTUSED(mask);
1018
00010fa9 1019 server.current_client = c;
826b5beb 1020 readlen = REDIS_IOBUF_LEN;
1021 /* If this is a multi bulk request, and we are processing a bulk reply
ed44a74e
YF
1022 * that is large enough, try to maximize the probability that the query
1023 * buffer contains exactly the SDS string representing the object, even
1024 * at the risk of requiring more read(2) calls. This way the function
826b5beb 1025 * processMultiBulkBuffer() can avoid copying buffers to create the
1026 * Redis Object representing the argument. */
826b5beb 1027 if (c->reqtype == REDIS_REQ_MULTIBULK && c->multibulklen && c->bulklen != -1
94d490b9 1028 && c->bulklen >= REDIS_MBULK_BIG_ARG)
826b5beb 1029 {
1030 int remaining = (unsigned)(c->bulklen+2)-sdslen(c->querybuf);
1031
1032 if (remaining < readlen) readlen = remaining;
1033 }
826b5beb 1034
b8d743e1 1035 qblen = sdslen(c->querybuf);
9fa9ccb0 1036 if (c->querybuf_peak < qblen) c->querybuf_peak = qblen;
826b5beb 1037 c->querybuf = sdsMakeRoomFor(c->querybuf, readlen);
1038 nread = read(fd, c->querybuf+qblen, readlen);
e2641e09 1039 if (nread == -1) {
1040 if (errno == EAGAIN) {
1041 nread = 0;
1042 } else {
1043 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
1044 freeClient(c);
1045 return;
1046 }
1047 } else if (nread == 0) {
1048 redisLog(REDIS_VERBOSE, "Client closed connection");
1049 freeClient(c);
1050 return;
1051 }
1052 if (nread) {
b8d743e1 1053 sdsIncrLen(c->querybuf,nread);
56ff70f8 1054 c->lastinteraction = server.unixtime;
e2641e09 1055 } else {
00010fa9 1056 server.current_client = NULL;
e2641e09 1057 return;
1058 }
becf5fdb 1059 if (sdslen(c->querybuf) > server.client_max_querybuf_len) {
63fd1399 1060 sds ci = getClientInfoString(c), bytes = sdsempty();
1061
1062 bytes = sdscatrepr(bytes,c->querybuf,64);
1063 redisLog(REDIS_WARNING,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci, bytes);
becf5fdb 1064 sdsfree(ci);
63fd1399 1065 sdsfree(bytes);
becf5fdb 1066 freeClient(c);
1067 return;
1068 }
e2641e09 1069 processInputBuffer(c);
00010fa9 1070 server.current_client = NULL;
e2641e09 1071}
7a1fd61e 1072
1073void getClientsMaxBuffers(unsigned long *longest_output_list,
1074 unsigned long *biggest_input_buffer) {
1075 redisClient *c;
1076 listNode *ln;
1077 listIter li;
1078 unsigned long lol = 0, bib = 0;
1079
1080 listRewind(server.clients,&li);
1081 while ((ln = listNext(&li)) != NULL) {
1082 c = listNodeValue(ln);
1083
1084 if (listLength(c->reply) > lol) lol = listLength(c->reply);
1085 if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf);
1086 }
1087 *longest_output_list = lol;
1088 *biggest_input_buffer = bib;
1089}
1090
17d25a33 1091/* Turn a Redis client into an sds string representing its state. */
1092sds getClientInfoString(redisClient *client) {
6621b8ff 1093 char ip[32], flags[16], events[3], *p;
b6ffa85f 1094 int port = 0; /* initialized to zero for the unix socket case. */
6621b8ff 1095 int emask;
17d25a33 1096
b6ffa85f 1097 if (!(client->flags & REDIS_UNIX_SOCKET))
1098 anetPeerToString(client->fd,ip,&port);
17d25a33 1099 p = flags;
1100 if (client->flags & REDIS_SLAVE) {
1101 if (client->flags & REDIS_MONITOR)
1102 *p++ = 'O';
1103 else
1104 *p++ = 'S';
1105 }
1106 if (client->flags & REDIS_MASTER) *p++ = 'M';
17d25a33 1107 if (client->flags & REDIS_MULTI) *p++ = 'x';
1108 if (client->flags & REDIS_BLOCKED) *p++ = 'b';
1109 if (client->flags & REDIS_DIRTY_CAS) *p++ = 'd';
1110 if (client->flags & REDIS_CLOSE_AFTER_REPLY) *p++ = 'c';
1111 if (client->flags & REDIS_UNBLOCKED) *p++ = 'u';
7eac2a75 1112 if (client->flags & REDIS_CLOSE_ASAP) *p++ = 'A';
b6ffa85f 1113 if (client->flags & REDIS_UNIX_SOCKET) *p++ = 'U';
afd0f06b 1114 if (p == flags) *p++ = 'N';
17d25a33 1115 *p++ = '\0';
6621b8ff 1116
1117 emask = client->fd == -1 ? 0 : aeGetFileEvents(server.el,client->fd);
1118 p = events;
1119 if (emask & AE_READABLE) *p++ = 'r';
1120 if (emask & AE_WRITABLE) *p++ = 'w';
1121 *p = '\0';
17d25a33 1122 return sdscatprintf(sdsempty(),
b162e6f1 1123 "addr=%s:%d fd=%d age=%ld idle=%ld flags=%s db=%d sub=%d psub=%d multi=%d qbuf=%lu qbuf-free=%lu obl=%lu oll=%lu omem=%lu events=%s cmd=%s",
b6ffa85f 1124 (client->flags & REDIS_UNIX_SOCKET) ? server.unixsocket : ip,
1125 port,client->fd,
56ff70f8
PH
1126 (long)(server.unixtime - client->ctime),
1127 (long)(server.unixtime - client->lastinteraction),
17d25a33 1128 flags,
1129 client->db->id,
1130 (int) dictSize(client->pubsub_channels),
491c1c4e 1131 (int) listLength(client->pubsub_patterns),
b162e6f1 1132 (client->flags & REDIS_MULTI) ? client->mstate.count : -1,
491c1c4e 1133 (unsigned long) sdslen(client->querybuf),
57a5e54d 1134 (unsigned long) sdsavail(client->querybuf),
491c1c4e 1135 (unsigned long) client->bufpos,
6621b8ff 1136 (unsigned long) listLength(client->reply),
3853c168 1137 getClientOutputBufferMemoryUsage(client),
2c74a9f9 1138 events,
1139 client->lastcmd ? client->lastcmd->name : "NULL");
17d25a33 1140}
1141
45e7a1ce 1142sds getAllClientsInfoString(void) {
1143 listNode *ln;
1144 listIter li;
1145 redisClient *client;
1146 sds o = sdsempty();
1147
1148 listRewind(server.clients,&li);
1149 while ((ln = listNext(&li)) != NULL) {
0a466a75 1150 sds cs;
1151
45e7a1ce 1152 client = listNodeValue(ln);
0a466a75 1153 cs = getClientInfoString(client);
1154 o = sdscatsds(o,cs);
1155 sdsfree(cs);
45e7a1ce 1156 o = sdscatlen(o,"\n",1);
1157 }
1158 return o;
1159}
1160
3cd12b56 1161void clientCommand(redisClient *c) {
b93fdb7b 1162 listNode *ln;
1163 listIter li;
1164 redisClient *client;
1165
3cd12b56 1166 if (!strcasecmp(c->argv[1]->ptr,"list") && c->argc == 2) {
45e7a1ce 1167 sds o = getAllClientsInfoString();
3cd12b56 1168 addReplyBulkCBuffer(c,o,sdslen(o));
1169 sdsfree(o);
b93fdb7b 1170 } else if (!strcasecmp(c->argv[1]->ptr,"kill") && c->argc == 3) {
1171 listRewind(server.clients,&li);
1172 while ((ln = listNext(&li)) != NULL) {
1173 char ip[32], addr[64];
1174 int port;
1175
1176 client = listNodeValue(ln);
1177 if (anetPeerToString(client->fd,ip,&port) == -1) continue;
1178 snprintf(addr,sizeof(addr),"%s:%d",ip,port);
1179 if (strcmp(addr,c->argv[2]->ptr) == 0) {
1180 addReply(c,shared.ok);
1181 if (c == client) {
1182 client->flags |= REDIS_CLOSE_AFTER_REPLY;
1183 } else {
1184 freeClient(client);
1185 }
1186 return;
1187 }
1188 }
1189 addReplyError(c,"No such client");
3cd12b56 1190 } else {
1191 addReplyError(c, "Syntax error, try CLIENT (LIST | KILL ip:port)");
1192 }
1193}
c1c9d551 1194
4dd444bb 1195/* Rewrite the command vector of the client. All the new objects ref count
1196 * is incremented. The old command vector is freed, and the old objects
1197 * ref count is decremented. */
c1c9d551 1198void rewriteClientCommandVector(redisClient *c, int argc, ...) {
1199 va_list ap;
1200 int j;
1201 robj **argv; /* The new argument vector */
1202
1203 argv = zmalloc(sizeof(robj*)*argc);
1204 va_start(ap,argc);
1205 for (j = 0; j < argc; j++) {
1206 robj *a;
1207
1208 a = va_arg(ap, robj*);
1209 argv[j] = a;
1210 incrRefCount(a);
1211 }
1212 /* We free the objects in the original vector at the end, so we are
1213 * sure that if the same objects are reused in the new vector the
1214 * refcount gets incremented before it gets decremented. */
1215 for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]);
1216 zfree(c->argv);
1217 /* Replace argv and argc with our new versions. */
1218 c->argv = argv;
1219 c->argc = argc;
09e2d9ee 1220 c->cmd = lookupCommand(c->argv[0]->ptr);
eab0e26e 1221 redisAssertWithInfo(c,NULL,c->cmd != NULL);
c1c9d551 1222 va_end(ap);
1223}
4dd444bb 1224
1225/* Rewrite a single item in the command vector.
1226 * The new val ref count is incremented, and the old decremented. */
1227void rewriteClientCommandArgument(redisClient *c, int i, robj *newval) {
1228 robj *oldval;
1229
eab0e26e 1230 redisAssertWithInfo(c,NULL,i < c->argc);
4dd444bb 1231 oldval = c->argv[i];
1232 c->argv[i] = newval;
1233 incrRefCount(newval);
1234 decrRefCount(oldval);
1235
1236 /* If this is the command name make sure to fix c->cmd. */
1237 if (i == 0) {
1238 c->cmd = lookupCommand(c->argv[0]->ptr);
eab0e26e 1239 redisAssertWithInfo(c,NULL,c->cmd != NULL);
4dd444bb 1240 }
1241}
3853c168 1242
1243/* This function returns the number of bytes that Redis is virtually
1244 * using to store the reply still not read by the client.
1245 * It is "virtual" since the reply output list may contain objects that
1246 * are shared and are not really using additional memory.
1247 *
1248 * The function returns the total sum of the length of all the objects
1249 * stored in the output list, plus the memory used to allocate every
1250 * list node. The static reply buffer is not taken into account since it
1251 * is allocated anyway.
1252 *
1253 * Note: this function is very fast so can be called as many time as
1254 * the caller wishes. The main usage of this function currently is
2f0f0d95 1255 * enforcing the client output length limits. */
3853c168 1256unsigned long getClientOutputBufferMemoryUsage(redisClient *c) {
442246dd 1257 unsigned long list_item_size = sizeof(listNode)+sizeof(robj);
3853c168 1258
1259 return c->reply_bytes + (list_item_size*listLength(c->reply));
1260}
498dc555 1261
ed44a74e 1262/* Get the class of a client, used in order to enforce limits to different
498dc555 1263 * classes of clients.
1264 *
1265 * The function will return one of the following:
1266 * REDIS_CLIENT_LIMIT_CLASS_NORMAL -> Normal client
1267 * REDIS_CLIENT_LIMIT_CLASS_SLAVE -> Slave or client executing MONITOR command
1268 * REDIS_CLIENT_LIMIT_CLASS_PUBSUB -> Client subscribed to Pub/Sub channels
1269 */
1270int getClientLimitClass(redisClient *c) {
1271 if (c->flags & REDIS_SLAVE) return REDIS_CLIENT_LIMIT_CLASS_SLAVE;
1272 if (dictSize(c->pubsub_channels) || listLength(c->pubsub_patterns))
1273 return REDIS_CLIENT_LIMIT_CLASS_PUBSUB;
1274 return REDIS_CLIENT_LIMIT_CLASS_NORMAL;
1275}
7eac2a75 1276
7fe8d49a 1277int getClientLimitClassByName(char *name) {
1278 if (!strcasecmp(name,"normal")) return REDIS_CLIENT_LIMIT_CLASS_NORMAL;
1279 else if (!strcasecmp(name,"slave")) return REDIS_CLIENT_LIMIT_CLASS_SLAVE;
c715c9b8 1280 else if (!strcasecmp(name,"pubsub")) return REDIS_CLIENT_LIMIT_CLASS_PUBSUB;
7fe8d49a 1281 else return -1;
1282}
1283
1284char *getClientLimitClassName(int class) {
1285 switch(class) {
1286 case REDIS_CLIENT_LIMIT_CLASS_NORMAL: return "normal";
1287 case REDIS_CLIENT_LIMIT_CLASS_SLAVE: return "slave";
1288 case REDIS_CLIENT_LIMIT_CLASS_PUBSUB: return "pubsub";
1289 default: return NULL;
1290 }
1291}
1292
7eac2a75 1293/* The function checks if the client reached output buffer soft or hard
1294 * limit, and also update the state needed to check the soft limit as
1295 * a side effect.
1296 *
1297 * Return value: non-zero if the client reached the soft or the hard limit.
1298 * Otherwise zero is returned. */
1299int checkClientOutputBufferLimits(redisClient *c) {
1300 int soft = 0, hard = 0, class;
1301 unsigned long used_mem = getClientOutputBufferMemoryUsage(c);
1302
1303 class = getClientLimitClass(c);
1304 if (server.client_obuf_limits[class].hard_limit_bytes &&
1305 used_mem >= server.client_obuf_limits[class].hard_limit_bytes)
1306 hard = 1;
1307 if (server.client_obuf_limits[class].soft_limit_bytes &&
1308 used_mem >= server.client_obuf_limits[class].soft_limit_bytes)
1309 soft = 1;
1310
1311 /* We need to check if the soft limit is reached continuously for the
1312 * specified amount of seconds. */
1313 if (soft) {
1314 if (c->obuf_soft_limit_reached_time == 0) {
1315 c->obuf_soft_limit_reached_time = server.unixtime;
1316 soft = 0; /* First time we see the soft limit reached */
1317 } else {
1318 time_t elapsed = server.unixtime - c->obuf_soft_limit_reached_time;
1319
1320 if (elapsed <=
1321 server.client_obuf_limits[class].soft_limit_seconds) {
1322 soft = 0; /* The client still did not reached the max number of
1323 seconds for the soft limit to be considered
1324 reached. */
1325 }
1326 }
1327 } else {
1328 c->obuf_soft_limit_reached_time = 0;
1329 }
1330 return soft || hard;
1331}
1332
1333/* Asynchronously close a client if soft or hard limit is reached on the
06b3dced 1334 * output buffer size. The caller can check if the client will be closed
1335 * checking if the client REDIS_CLOSE_ASAP flag is set.
7eac2a75 1336 *
1337 * Note: we need to close the client asynchronously because this function is
1338 * called from contexts where the client can't be freed safely, i.e. from the
1339 * lower level functions pushing data inside the client output buffers. */
06b3dced 1340void asyncCloseClientOnOutputBufferLimitReached(redisClient *c) {
6fe9c402 1341 redisAssert(c->reply_bytes < ULONG_MAX-(1024*64));
6e09ad1c 1342 if (c->reply_bytes == 0 || c->flags & REDIS_CLOSE_ASAP) return;
7eac2a75 1343 if (checkClientOutputBufferLimits(c)) {
1344 sds client = getClientInfoString(c);
1345
1346 freeClientAsync(c);
7957c676 1347 redisLog(REDIS_WARNING,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client);
7eac2a75 1348 sdsfree(client);
7eac2a75 1349 }
1350}
8b7c3455 1351
1352/* Helper function used by freeMemoryIfNeeded() in order to flush slaves
1353 * output buffers without returning control to the event loop. */
1354void flushSlavesOutputBuffers(void) {
1355 listIter li;
1356 listNode *ln;
1357
1358 listRewind(server.slaves,&li);
1359 while((ln = listNext(&li))) {
1360 redisClient *slave = listNodeValue(ln);
1361 int events;
1362
1363 events = aeGetFileEvents(server.el,slave->fd);
1364 if (events & AE_WRITABLE &&
1365 slave->replstate == REDIS_REPL_ONLINE &&
1366 listLength(slave->reply))
1367 {
1368 sendReplyToClient(server.el,slave->fd,slave,0);
1369 }
1370 }
1371}