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