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