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