4 static void setProtocolError(redisClient
*c
, int pos
);
6 void *dupClientReplyValue(void *o
) {
7 incrRefCount((robj
*)o
);
11 int listMatchObjects(void *a
, void *b
) {
12 return equalStringObjects(a
,b
);
15 redisClient
*createClient(int fd
) {
16 redisClient
*c
= zmalloc(sizeof(redisClient
));
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. */
24 anetNonBlock(NULL
,fd
);
25 anetTcpNoDelay(NULL
,fd
);
26 if (aeCreateFileEvent(server
.el
,fd
,AE_READABLE
,
27 readQueryFromClient
, c
) == AE_ERR
)
37 c
->querybuf
= sdsempty();
41 c
->cmd
= c
->lastcmd
= NULL
;
46 c
->lastinteraction
= time(NULL
);
48 c
->replstate
= REDIS_REPL_NONE
;
49 c
->reply
= listCreate();
51 c
->obuf_soft_limit_reached_time
= 0;
52 listSetFreeMethod(c
->reply
,decrRefCount
);
53 listSetDupMethod(c
->reply
,dupClientReplyValue
);
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
);
70 /* This function is called every time we are going to transmit new data
71 * to the client. The behavior is the following:
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.
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
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
;
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
) {
100 redisAssert(listLength(reply
) > 0);
101 ln
= listLast(reply
);
102 cur
= listNodeValue(ln
);
103 if (cur
->refcount
> 1) {
104 new = dupStringObject(cur
);
106 listNodeValue(ln
) = new;
108 return listNodeValue(ln
);
111 /* -----------------------------------------------------------------------------
112 * Low level functions to add more data to output buffers.
113 * -------------------------------------------------------------------------- */
115 int _addReplyToBuffer(redisClient
*c
, char *s
, size_t len
) {
116 size_t available
= sizeof(c
->buf
)-c
->bufpos
;
118 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return REDIS_OK
;
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
;
124 /* Check that the buffer has enough space available for this string. */
125 if (len
> available
) return REDIS_ERR
;
127 memcpy(c
->buf
+c
->bufpos
,s
,len
);
132 void _addReplyObjectToList(redisClient
*c
, robj
*o
) {
135 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
137 if (listLength(c
->reply
) == 0) {
139 listAddNodeTail(c
->reply
,o
);
141 tail
= listNodeValue(listLast(c
->reply
));
143 /* Append to this object when possible. */
144 if (tail
->ptr
!= NULL
&&
145 sdslen(tail
->ptr
)+sdslen(o
->ptr
) <= REDIS_REPLY_CHUNK_BYTES
)
147 tail
= dupLastObjectIfNeeded(c
->reply
);
148 tail
->ptr
= sdscatlen(tail
->ptr
,o
->ptr
,sdslen(o
->ptr
));
151 listAddNodeTail(c
->reply
,o
);
154 c
->reply_bytes
+= zmalloc_size(o
->ptr
);
155 asyncCloseClientOnOutputBufferLimitReached(c
);
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
) {
163 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) {
168 c
->reply_bytes
+= zmalloc_size(s
);
169 if (listLength(c
->reply
) == 0) {
170 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
172 tail
= listNodeValue(listLast(c
->reply
));
174 /* Append to this object when possible. */
175 if (tail
->ptr
!= NULL
&&
176 sdslen(tail
->ptr
)+sdslen(s
) <= REDIS_REPLY_CHUNK_BYTES
)
178 tail
= dupLastObjectIfNeeded(c
->reply
);
179 tail
->ptr
= sdscatlen(tail
->ptr
,s
,sdslen(s
));
182 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
185 asyncCloseClientOnOutputBufferLimitReached(c
);
188 void _addReplyStringToList(redisClient
*c
, char *s
, size_t len
) {
191 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
193 if (listLength(c
->reply
) == 0) {
194 robj
*o
= createStringObject(s
,len
);
196 listAddNodeTail(c
->reply
,o
);
197 c
->reply_bytes
+= zmalloc_size(o
->ptr
);
199 tail
= listNodeValue(listLast(c
->reply
));
201 /* Append to this object when possible. */
202 if (tail
->ptr
!= NULL
&&
203 sdslen(tail
->ptr
)+len
<= REDIS_REPLY_CHUNK_BYTES
)
205 c
->reply_bytes
-= zmalloc_size(tail
->ptr
);
206 tail
= dupLastObjectIfNeeded(c
->reply
);
207 tail
->ptr
= sdscatlen(tail
->ptr
,s
,len
);
208 c
->reply_bytes
+= zmalloc_size(tail
->ptr
);
210 robj
*o
= createStringObject(s
,len
);
212 listAddNodeTail(c
->reply
,o
);
213 c
->reply_bytes
+= zmalloc_size(o
->ptr
);
216 asyncCloseClientOnOutputBufferLimitReached(c
);
219 /* -----------------------------------------------------------------------------
220 * Higher level functions to queue data on the client output buffer.
221 * The following functions are the ones that commands implementations will call.
222 * -------------------------------------------------------------------------- */
224 void addReply(redisClient
*c
, robj
*obj
) {
225 if (prepareClientToWrite(c
) != REDIS_OK
) return;
227 /* This is an important place where we can avoid copy-on-write
228 * when there is a saving child running, avoiding touching the
229 * refcount field of the object if it's not needed.
231 * If the encoding is RAW and there is room in the static buffer
232 * we'll be able to send the object to the client without
233 * messing with its page. */
234 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
235 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
236 _addReplyObjectToList(c
,obj
);
237 } else if (obj
->encoding
== REDIS_ENCODING_INT
) {
238 /* Optimization: if there is room in the static buffer for 32 bytes
239 * (more than the max chars a 64 bit integer can take as string) we
240 * avoid decoding the object and go for the lower level approach. */
241 if (listLength(c
->reply
) == 0 && (sizeof(c
->buf
) - c
->bufpos
) >= 32) {
245 len
= ll2string(buf
,sizeof(buf
),(long)obj
->ptr
);
246 if (_addReplyToBuffer(c
,buf
,len
) == REDIS_OK
)
248 /* else... continue with the normal code path, but should never
249 * happen actually since we verified there is room. */
251 obj
= getDecodedObject(obj
);
252 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
253 _addReplyObjectToList(c
,obj
);
256 redisPanic("Wrong obj->encoding in addReply()");
260 void addReplySds(redisClient
*c
, sds s
) {
261 if (prepareClientToWrite(c
) != REDIS_OK
) {
262 /* The caller expects the sds to be free'd. */
266 if (_addReplyToBuffer(c
,s
,sdslen(s
)) == REDIS_OK
) {
269 /* This method free's the sds when it is no longer needed. */
270 _addReplySdsToList(c
,s
);
274 void addReplyString(redisClient
*c
, char *s
, size_t len
) {
275 if (prepareClientToWrite(c
) != REDIS_OK
) return;
276 if (_addReplyToBuffer(c
,s
,len
) != REDIS_OK
)
277 _addReplyStringToList(c
,s
,len
);
280 void addReplyErrorLength(redisClient
*c
, char *s
, size_t len
) {
281 addReplyString(c
,"-ERR ",5);
282 addReplyString(c
,s
,len
);
283 addReplyString(c
,"\r\n",2);
286 void addReplyError(redisClient
*c
, char *err
) {
287 addReplyErrorLength(c
,err
,strlen(err
));
290 void addReplyErrorFormat(redisClient
*c
, const char *fmt
, ...) {
294 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
296 /* Make sure there are no newlines in the string, otherwise invalid protocol
299 for (j
= 0; j
< l
; j
++) {
300 if (s
[j
] == '\r' || s
[j
] == '\n') s
[j
] = ' ';
302 addReplyErrorLength(c
,s
,sdslen(s
));
306 void addReplyStatusLength(redisClient
*c
, char *s
, size_t len
) {
307 addReplyString(c
,"+",1);
308 addReplyString(c
,s
,len
);
309 addReplyString(c
,"\r\n",2);
312 void addReplyStatus(redisClient
*c
, char *status
) {
313 addReplyStatusLength(c
,status
,strlen(status
));
316 void addReplyStatusFormat(redisClient
*c
, const char *fmt
, ...) {
319 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
321 addReplyStatusLength(c
,s
,sdslen(s
));
325 /* Adds an empty object to the reply list that will contain the multi bulk
326 * length, which is not known when this function is called. */
327 void *addDeferredMultiBulkLength(redisClient
*c
) {
328 /* Note that we install the write event here even if the object is not
329 * ready to be sent, since we are sure that before returning to the
330 * event loop setDeferredMultiBulkLength() will be called. */
331 if (prepareClientToWrite(c
) != REDIS_OK
) return NULL
;
332 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,NULL
));
333 return listLast(c
->reply
);
336 /* Populate the length object and try glueing it to the next chunk. */
337 void setDeferredMultiBulkLength(redisClient
*c
, void *node
, long length
) {
338 listNode
*ln
= (listNode
*)node
;
341 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
342 if (node
== NULL
) return;
344 len
= listNodeValue(ln
);
345 len
->ptr
= sdscatprintf(sdsempty(),"*%ld\r\n",length
);
346 c
->reply_bytes
+= zmalloc_size(len
->ptr
);
347 if (ln
->next
!= NULL
) {
348 next
= listNodeValue(ln
->next
);
350 /* Only glue when the next node is non-NULL (an sds in this case) */
351 if (next
->ptr
!= NULL
) {
352 len
->ptr
= sdscatlen(len
->ptr
,next
->ptr
,sdslen(next
->ptr
));
353 listDelNode(c
->reply
,ln
->next
);
356 asyncCloseClientOnOutputBufferLimitReached(c
);
359 /* Add a duble as a bulk reply */
360 void addReplyDouble(redisClient
*c
, double d
) {
361 char dbuf
[128], sbuf
[128];
363 dlen
= snprintf(dbuf
,sizeof(dbuf
),"%.17g",d
);
364 slen
= snprintf(sbuf
,sizeof(sbuf
),"$%d\r\n%s\r\n",dlen
,dbuf
);
365 addReplyString(c
,sbuf
,slen
);
368 /* Add a long long as integer reply or bulk len / multi bulk count.
369 * Basically this is used to output <prefix><long long><crlf>. */
370 void addReplyLongLongWithPrefix(redisClient
*c
, long long ll
, char prefix
) {
374 /* Things like $3\r\n or *2\r\n are emitted very often by the protocol
375 * so we have a few shared objects to use if the integer is small
376 * like it is most of the times. */
377 if (prefix
== '*' && ll
< REDIS_SHARED_BULKHDR_LEN
) {
378 addReply(c
,shared
.mbulkhdr
[ll
]);
380 } else if (prefix
== '$' && ll
< REDIS_SHARED_BULKHDR_LEN
) {
381 addReply(c
,shared
.bulkhdr
[ll
]);
386 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
389 addReplyString(c
,buf
,len
+3);
392 void addReplyLongLong(redisClient
*c
, long long ll
) {
394 addReply(c
,shared
.czero
);
396 addReply(c
,shared
.cone
);
398 addReplyLongLongWithPrefix(c
,ll
,':');
401 void addReplyMultiBulkLen(redisClient
*c
, long length
) {
402 addReplyLongLongWithPrefix(c
,length
,'*');
405 /* Create the length prefix of a bulk reply, example: $2234 */
406 void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
409 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
410 len
= sdslen(obj
->ptr
);
412 long n
= (long)obj
->ptr
;
414 /* Compute how many bytes will take this integer as a radix 10 string */
420 while((n
= n
/10) != 0) {
424 addReplyLongLongWithPrefix(c
,len
,'$');
427 /* Add a Redis Object as a bulk reply */
428 void addReplyBulk(redisClient
*c
, robj
*obj
) {
429 addReplyBulkLen(c
,obj
);
431 addReply(c
,shared
.crlf
);
434 /* Add a C buffer as bulk reply */
435 void addReplyBulkCBuffer(redisClient
*c
, void *p
, size_t len
) {
436 addReplyLongLongWithPrefix(c
,len
,'$');
437 addReplyString(c
,p
,len
);
438 addReply(c
,shared
.crlf
);
441 /* Add a C nul term string as bulk reply */
442 void addReplyBulkCString(redisClient
*c
, char *s
) {
444 addReply(c
,shared
.nullbulk
);
446 addReplyBulkCBuffer(c
,s
,strlen(s
));
450 /* Add a long long as a bulk reply */
451 void addReplyBulkLongLong(redisClient
*c
, long long ll
) {
455 len
= ll2string(buf
,64,ll
);
456 addReplyBulkCBuffer(c
,buf
,len
);
459 /* Copy 'src' client output buffers into 'dst' client output buffers.
460 * The function takes care of freeing the old output buffers of the
461 * destination client. */
462 void copyClientOutputBuffer(redisClient
*dst
, redisClient
*src
) {
463 listRelease(dst
->reply
);
464 dst
->reply
= listDup(src
->reply
);
465 memcpy(dst
->buf
,src
->buf
,src
->bufpos
);
466 dst
->bufpos
= src
->bufpos
;
467 dst
->reply_bytes
= src
->reply_bytes
;
470 static void acceptCommonHandler(int fd
) {
472 if ((c
= createClient(fd
)) == NULL
) {
473 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
474 close(fd
); /* May be already closed, just ingore errors */
477 /* If maxclient directive is set and this is one client more... close the
478 * connection. Note that we create the client instead to check before
479 * for this condition, since now the socket is already set in nonblocking
480 * mode and we can send an error for free using the Kernel I/O */
481 if (listLength(server
.clients
) > server
.maxclients
) {
482 char *err
= "-ERR max number of clients reached\r\n";
484 /* That's a best effort error message, don't check write errors */
485 if (write(c
->fd
,err
,strlen(err
)) == -1) {
486 /* Nothing to do, Just to avoid the warning... */
488 server
.stat_rejected_conn
++;
492 server
.stat_numconnections
++;
495 void acceptTcpHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
500 REDIS_NOTUSED(privdata
);
502 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
504 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
507 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
508 acceptCommonHandler(cfd
);
511 void acceptUnixHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
515 REDIS_NOTUSED(privdata
);
517 cfd
= anetUnixAccept(server
.neterr
, fd
);
519 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
522 redisLog(REDIS_VERBOSE
,"Accepted connection to %s", server
.unixsocket
);
523 acceptCommonHandler(cfd
);
527 static void freeClientArgv(redisClient
*c
) {
529 for (j
= 0; j
< c
->argc
; j
++)
530 decrRefCount(c
->argv
[j
]);
535 void freeClient(redisClient
*c
) {
538 /* If this is marked as current client unset it */
539 if (server
.current_client
== c
) server
.current_client
= NULL
;
541 /* Note that if the client we are freeing is blocked into a blocking
542 * call, we have to set querybuf to NULL *before* to call
543 * unblockClientWaitingData() to avoid processInputBuffer() will get
544 * called. Also it is important to remove the file events after
545 * this, because this call adds the READABLE event. */
546 sdsfree(c
->querybuf
);
548 if (c
->flags
& REDIS_BLOCKED
)
549 unblockClientWaitingData(c
);
551 /* UNWATCH all the keys */
553 listRelease(c
->watched_keys
);
554 /* Unsubscribe from all the pubsub channels */
555 pubsubUnsubscribeAllChannels(c
,0);
556 pubsubUnsubscribeAllPatterns(c
,0);
557 dictRelease(c
->pubsub_channels
);
558 listRelease(c
->pubsub_patterns
);
559 /* Obvious cleanup */
560 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
561 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
562 listRelease(c
->reply
);
565 /* Remove from the list of clients */
566 ln
= listSearchKey(server
.clients
,c
);
567 redisAssert(ln
!= NULL
);
568 listDelNode(server
.clients
,ln
);
569 /* When client was just unblocked because of a blocking operation,
570 * remove it from the list with unblocked clients. */
571 if (c
->flags
& REDIS_UNBLOCKED
) {
572 ln
= listSearchKey(server
.unblocked_clients
,c
);
573 redisAssert(ln
!= NULL
);
574 listDelNode(server
.unblocked_clients
,ln
);
576 listRelease(c
->io_keys
);
577 /* Master/slave cleanup.
578 * Case 1: we lost the connection with a slave. */
579 if (c
->flags
& REDIS_SLAVE
) {
580 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
582 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
583 ln
= listSearchKey(l
,c
);
584 redisAssert(ln
!= NULL
);
588 /* Case 2: we lost the connection with the master. */
589 if (c
->flags
& REDIS_MASTER
) {
590 server
.master
= NULL
;
591 server
.repl_state
= REDIS_REPL_CONNECT
;
592 server
.repl_down_since
= time(NULL
);
593 /* Since we lost the connection with the master, we should also
594 * close the connection with all our slaves if we have any, so
595 * when we'll resync with the master the other slaves will sync again
596 * with us as well. Note that also when the slave is not connected
597 * to the master it will keep refusing connections by other slaves.
599 * We do this only if server.masterhost != NULL. If it is NULL this
600 * means the user called SLAVEOF NO ONE and we are freeing our
601 * link with the master, so no need to close link with slaves. */
602 if (server
.masterhost
!= NULL
) {
603 while (listLength(server
.slaves
)) {
604 ln
= listFirst(server
.slaves
);
605 freeClient((redisClient
*)ln
->value
);
610 /* If this client was scheduled for async freeing we need to remove it
612 if (c
->flags
& REDIS_CLOSE_ASAP
) {
613 ln
= listSearchKey(server
.clients_to_close
,c
);
614 redisAssert(ln
!= NULL
);
615 listDelNode(server
.clients_to_close
,ln
);
620 freeClientMultiState(c
);
624 /* Schedule a client to free it at a safe time in the serverCron() function.
625 * This function is useful when we need to terminate a client but we are in
626 * a context where calling freeClient() is not possible, because the client
627 * should be valid for the continuation of the flow of the program. */
628 void freeClientAsync(redisClient
*c
) {
629 if (c
->flags
& REDIS_CLOSE_ASAP
) return;
630 c
->flags
|= REDIS_CLOSE_ASAP
;
631 listAddNodeTail(server
.clients_to_close
,c
);
634 void freeClientsInAsyncFreeQueue(void) {
635 while (listLength(server
.clients_to_close
)) {
636 listNode
*ln
= listFirst(server
.clients_to_close
);
637 redisClient
*c
= listNodeValue(ln
);
639 c
->flags
&= ~REDIS_CLOSE_ASAP
;
641 listDelNode(server
.clients_to_close
,ln
);
645 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
646 redisClient
*c
= privdata
;
647 int nwritten
= 0, totwritten
= 0, objlen
;
653 while(c
->bufpos
> 0 || listLength(c
->reply
)) {
655 if (c
->flags
& REDIS_MASTER
) {
656 /* Don't reply to a master */
657 nwritten
= c
->bufpos
- c
->sentlen
;
659 nwritten
= write(fd
,c
->buf
+c
->sentlen
,c
->bufpos
-c
->sentlen
);
660 if (nwritten
<= 0) break;
662 c
->sentlen
+= nwritten
;
663 totwritten
+= nwritten
;
665 /* If the buffer was sent, set bufpos to zero to continue with
666 * the remainder of the reply. */
667 if (c
->sentlen
== c
->bufpos
) {
672 o
= listNodeValue(listFirst(c
->reply
));
673 objlen
= sdslen(o
->ptr
);
674 objmem
= zmalloc_size(o
->ptr
);
677 listDelNode(c
->reply
,listFirst(c
->reply
));
681 if (c
->flags
& REDIS_MASTER
) {
682 /* Don't reply to a master */
683 nwritten
= objlen
- c
->sentlen
;
685 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
,objlen
-c
->sentlen
);
686 if (nwritten
<= 0) break;
688 c
->sentlen
+= nwritten
;
689 totwritten
+= nwritten
;
691 /* If we fully sent the object on head go to the next one */
692 if (c
->sentlen
== objlen
) {
693 listDelNode(c
->reply
,listFirst(c
->reply
));
695 c
->reply_bytes
-= objmem
;
698 /* Note that we avoid to send more than REDIS_MAX_WRITE_PER_EVENT
699 * bytes, in a single threaded server it's a good idea to serve
700 * other clients as well, even if a very large request comes from
701 * super fast link that is always able to accept data (in real world
702 * scenario think about 'KEYS *' against the loopback interface).
704 * However if we are over the maxmemory limit we ignore that and
705 * just deliver as much data as it is possible to deliver. */
706 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
&&
707 (server
.maxmemory
== 0 ||
708 zmalloc_used_memory() < server
.maxmemory
)) break;
710 if (nwritten
== -1) {
711 if (errno
== EAGAIN
) {
714 redisLog(REDIS_VERBOSE
,
715 "Error writing to client: %s", strerror(errno
));
720 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
721 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0) {
723 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
725 /* Close connection after entire reply has been sent. */
726 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) freeClient(c
);
730 /* resetClient prepare the client to process the next command */
731 void resetClient(redisClient
*c
) {
736 /* We clear the ASKING flag as well if we are not inside a MULTI. */
737 if (!(c
->flags
& REDIS_MULTI
)) c
->flags
&= (~REDIS_ASKING
);
740 void closeTimedoutClients(void) {
743 time_t now
= time(NULL
);
746 listRewind(server
.clients
,&li
);
747 while ((ln
= listNext(&li
)) != NULL
) {
748 c
= listNodeValue(ln
);
749 if (server
.maxidletime
&&
750 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
751 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
752 !(c
->flags
& REDIS_BLOCKED
) && /* no timeout for BLPOP */
753 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
754 listLength(c
->pubsub_patterns
) == 0 &&
755 (now
- c
->lastinteraction
> server
.maxidletime
))
757 redisLog(REDIS_VERBOSE
,"Closing idle client");
759 } else if (c
->flags
& REDIS_BLOCKED
) {
760 if (c
->bpop
.timeout
!= 0 && c
->bpop
.timeout
< now
) {
761 addReply(c
,shared
.nullmultibulk
);
762 unblockClientWaitingData(c
);
768 int processInlineBuffer(redisClient
*c
) {
769 char *newline
= strstr(c
->querybuf
,"\r\n");
774 /* Nothing to do without a \r\n */
775 if (newline
== NULL
) {
776 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
777 addReplyError(c
,"Protocol error: too big inline request");
778 setProtocolError(c
,0);
783 /* Split the input buffer up to the \r\n */
784 querylen
= newline
-(c
->querybuf
);
785 argv
= sdssplitlen(c
->querybuf
,querylen
," ",1,&argc
);
787 /* Leave data after the first line of the query in the buffer */
788 c
->querybuf
= sdsrange(c
->querybuf
,querylen
+2,-1);
790 /* Setup argv array on client structure */
791 if (c
->argv
) zfree(c
->argv
);
792 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
794 /* Create redis objects for all arguments. */
795 for (c
->argc
= 0, j
= 0; j
< argc
; j
++) {
796 if (sdslen(argv
[j
])) {
797 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
807 /* Helper function. Trims query buffer to make the function that processes
808 * multi bulk requests idempotent. */
809 static void setProtocolError(redisClient
*c
, int pos
) {
810 if (server
.verbosity
>= REDIS_VERBOSE
) {
811 sds client
= getClientInfoString(c
);
812 redisLog(REDIS_VERBOSE
,
813 "Protocol error from client: %s", client
);
816 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
817 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
820 int processMultibulkBuffer(redisClient
*c
) {
821 char *newline
= NULL
;
825 if (c
->multibulklen
== 0) {
826 /* The client should have been reset */
827 redisAssertWithInfo(c
,NULL
,c
->argc
== 0);
829 /* Multi bulk length cannot be read without a \r\n */
830 newline
= strchr(c
->querybuf
,'\r');
831 if (newline
== NULL
) {
832 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
833 addReplyError(c
,"Protocol error: too big mbulk count string");
834 setProtocolError(c
,0);
839 /* Buffer should also contain \n */
840 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
843 /* We know for sure there is a whole line since newline != NULL,
844 * so go ahead and find out the multi bulk length. */
845 redisAssertWithInfo(c
,NULL
,c
->querybuf
[0] == '*');
846 ok
= string2ll(c
->querybuf
+1,newline
-(c
->querybuf
+1),&ll
);
847 if (!ok
|| ll
> 1024*1024) {
848 addReplyError(c
,"Protocol error: invalid multibulk length");
849 setProtocolError(c
,pos
);
853 pos
= (newline
-c
->querybuf
)+2;
855 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
859 c
->multibulklen
= ll
;
861 /* Setup argv array on client structure */
862 if (c
->argv
) zfree(c
->argv
);
863 c
->argv
= zmalloc(sizeof(robj
*)*c
->multibulklen
);
866 redisAssertWithInfo(c
,NULL
,c
->multibulklen
> 0);
867 while(c
->multibulklen
) {
868 /* Read bulk length if unknown */
869 if (c
->bulklen
== -1) {
870 newline
= strchr(c
->querybuf
+pos
,'\r');
871 if (newline
== NULL
) {
872 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
873 addReplyError(c
,"Protocol error: too big bulk count string");
874 setProtocolError(c
,0);
879 /* Buffer should also contain \n */
880 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
883 if (c
->querybuf
[pos
] != '$') {
884 addReplyErrorFormat(c
,
885 "Protocol error: expected '$', got '%c'",
887 setProtocolError(c
,pos
);
891 ok
= string2ll(c
->querybuf
+pos
+1,newline
-(c
->querybuf
+pos
+1),&ll
);
892 if (!ok
|| ll
< 0 || ll
> 512*1024*1024) {
893 addReplyError(c
,"Protocol error: invalid bulk length");
894 setProtocolError(c
,pos
);
898 pos
+= newline
-(c
->querybuf
+pos
)+2;
899 if (ll
>= REDIS_MBULK_BIG_ARG
) {
900 /* If we are going to read a large object from network
901 * try to make it likely that it will start at c->querybuf
902 * boundary so that we can optimized object creation
903 * avoiding a large copy of data. */
904 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
906 /* Hint the sds library about the amount of bytes this string is
907 * going to contain. */
908 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
,ll
+2);
913 /* Read bulk argument */
914 if (sdslen(c
->querybuf
)-pos
< (unsigned)(c
->bulklen
+2)) {
915 /* Not enough data (+2 == trailing \r\n) */
918 /* Optimization: if the buffer contanins JUST our bulk element
919 * instead of creating a new object by *copying* the sds we
920 * just use the current sds string. */
922 c
->bulklen
>= REDIS_MBULK_BIG_ARG
&&
923 (signed) sdslen(c
->querybuf
) == c
->bulklen
+2)
925 c
->argv
[c
->argc
++] = createObject(REDIS_STRING
,c
->querybuf
);
926 sdsIncrLen(c
->querybuf
,-2); /* remove CRLF */
927 c
->querybuf
= sdsempty();
928 /* Assume that if we saw a fat argument we'll see another one
930 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
,c
->bulklen
+2);
934 createStringObject(c
->querybuf
+pos
,c
->bulklen
);
943 if (pos
) c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
945 /* We're done when c->multibulk == 0 */
946 if (c
->multibulklen
== 0) return REDIS_OK
;
948 /* Still not read to process the command */
952 void processInputBuffer(redisClient
*c
) {
953 /* Keep processing while there is something in the input buffer */
954 while(sdslen(c
->querybuf
)) {
955 /* Immediately abort if the client is in the middle of something. */
956 if (c
->flags
& REDIS_BLOCKED
) return;
958 /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
959 * written to the client. Make sure to not let the reply grow after
960 * this flag has been set (i.e. don't process more commands). */
961 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
963 /* Determine request type when unknown. */
965 if (c
->querybuf
[0] == '*') {
966 c
->reqtype
= REDIS_REQ_MULTIBULK
;
968 c
->reqtype
= REDIS_REQ_INLINE
;
972 if (c
->reqtype
== REDIS_REQ_INLINE
) {
973 if (processInlineBuffer(c
) != REDIS_OK
) break;
974 } else if (c
->reqtype
== REDIS_REQ_MULTIBULK
) {
975 if (processMultibulkBuffer(c
) != REDIS_OK
) break;
977 redisPanic("Unknown request type");
980 /* Multibulk processing could see a <= 0 length. */
984 /* Only reset the client when the command was executed. */
985 if (processCommand(c
) == REDIS_OK
)
991 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
992 redisClient
*c
= (redisClient
*) privdata
;
998 server
.current_client
= c
;
999 readlen
= REDIS_IOBUF_LEN
;
1000 /* If this is a multi bulk request, and we are processing a bulk reply
1001 * that is large enough, try to maximize the probabilty that the query
1002 * buffer contains excatly the SDS string representing the object, even
1003 * at the risk of requring more read(2) calls. This way the function
1004 * processMultiBulkBuffer() can avoid copying buffers to create the
1005 * Redis Object representing the argument. */
1006 if (c
->reqtype
== REDIS_REQ_MULTIBULK
&& c
->multibulklen
&& c
->bulklen
!= -1
1007 && c
->bulklen
>= REDIS_MBULK_BIG_ARG
)
1009 int remaining
= (unsigned)(c
->bulklen
+2)-sdslen(c
->querybuf
);
1011 if (remaining
< readlen
) readlen
= remaining
;
1014 qblen
= sdslen(c
->querybuf
);
1015 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
, readlen
);
1016 nread
= read(fd
, c
->querybuf
+qblen
, readlen
);
1018 if (errno
== EAGAIN
) {
1021 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
1025 } else if (nread
== 0) {
1026 redisLog(REDIS_VERBOSE
, "Client closed connection");
1031 sdsIncrLen(c
->querybuf
,nread
);
1032 c
->lastinteraction
= time(NULL
);
1034 server
.current_client
= NULL
;
1037 if (sdslen(c
->querybuf
) > server
.client_max_querybuf_len
) {
1038 sds ci
= getClientInfoString(c
), bytes
= sdsempty();
1040 bytes
= sdscatrepr(bytes
,c
->querybuf
,64);
1041 redisLog(REDIS_WARNING
,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci
, bytes
);
1047 processInputBuffer(c
);
1048 server
.current_client
= NULL
;
1051 void getClientsMaxBuffers(unsigned long *longest_output_list
,
1052 unsigned long *biggest_input_buffer
) {
1056 unsigned long lol
= 0, bib
= 0;
1058 listRewind(server
.clients
,&li
);
1059 while ((ln
= listNext(&li
)) != NULL
) {
1060 c
= listNodeValue(ln
);
1062 if (listLength(c
->reply
) > lol
) lol
= listLength(c
->reply
);
1063 if (sdslen(c
->querybuf
) > bib
) bib
= sdslen(c
->querybuf
);
1065 *longest_output_list
= lol
;
1066 *biggest_input_buffer
= bib
;
1069 /* Turn a Redis client into an sds string representing its state. */
1070 sds
getClientInfoString(redisClient
*client
) {
1071 char ip
[32], flags
[16], events
[3], *p
;
1073 time_t now
= time(NULL
);
1076 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) {
1082 if (client
->flags
& REDIS_SLAVE
) {
1083 if (client
->flags
& REDIS_MONITOR
)
1088 if (client
->flags
& REDIS_MASTER
) *p
++ = 'M';
1089 if (client
->flags
& REDIS_MULTI
) *p
++ = 'x';
1090 if (client
->flags
& REDIS_BLOCKED
) *p
++ = 'b';
1091 if (client
->flags
& REDIS_DIRTY_CAS
) *p
++ = 'd';
1092 if (client
->flags
& REDIS_CLOSE_AFTER_REPLY
) *p
++ = 'c';
1093 if (client
->flags
& REDIS_UNBLOCKED
) *p
++ = 'u';
1094 if (client
->flags
& REDIS_CLOSE_ASAP
) *p
++ = 'A';
1095 if (p
== flags
) *p
++ = 'N';
1098 emask
= client
->fd
== -1 ? 0 : aeGetFileEvents(server
.el
,client
->fd
);
1100 if (emask
& AE_READABLE
) *p
++ = 'r';
1101 if (emask
& AE_WRITABLE
) *p
++ = 'w';
1103 return sdscatprintf(sdsempty(),
1104 "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",
1106 (long)(now
- client
->lastinteraction
),
1109 (int) dictSize(client
->pubsub_channels
),
1110 (int) listLength(client
->pubsub_patterns
),
1111 (unsigned long) sdslen(client
->querybuf
),
1112 (unsigned long) client
->bufpos
,
1113 (unsigned long) listLength(client
->reply
),
1114 getClientOutputBufferMemoryUsage(client
),
1116 client
->lastcmd
? client
->lastcmd
->name
: "NULL");
1119 sds
getAllClientsInfoString(void) {
1122 redisClient
*client
;
1125 listRewind(server
.clients
,&li
);
1126 while ((ln
= listNext(&li
)) != NULL
) {
1129 client
= listNodeValue(ln
);
1130 cs
= getClientInfoString(client
);
1131 o
= sdscatsds(o
,cs
);
1133 o
= sdscatlen(o
,"\n",1);
1138 void clientCommand(redisClient
*c
) {
1141 redisClient
*client
;
1143 if (!strcasecmp(c
->argv
[1]->ptr
,"list") && c
->argc
== 2) {
1144 sds o
= getAllClientsInfoString();
1145 addReplyBulkCBuffer(c
,o
,sdslen(o
));
1147 } else if (!strcasecmp(c
->argv
[1]->ptr
,"kill") && c
->argc
== 3) {
1148 listRewind(server
.clients
,&li
);
1149 while ((ln
= listNext(&li
)) != NULL
) {
1150 char ip
[32], addr
[64];
1153 client
= listNodeValue(ln
);
1154 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue;
1155 snprintf(addr
,sizeof(addr
),"%s:%d",ip
,port
);
1156 if (strcmp(addr
,c
->argv
[2]->ptr
) == 0) {
1157 addReply(c
,shared
.ok
);
1159 client
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1166 addReplyError(c
,"No such client");
1168 addReplyError(c
, "Syntax error, try CLIENT (LIST | KILL ip:port)");
1172 /* Rewrite the command vector of the client. All the new objects ref count
1173 * is incremented. The old command vector is freed, and the old objects
1174 * ref count is decremented. */
1175 void rewriteClientCommandVector(redisClient
*c
, int argc
, ...) {
1178 robj
**argv
; /* The new argument vector */
1180 argv
= zmalloc(sizeof(robj
*)*argc
);
1182 for (j
= 0; j
< argc
; j
++) {
1185 a
= va_arg(ap
, robj
*);
1189 /* We free the objects in the original vector at the end, so we are
1190 * sure that if the same objects are reused in the new vector the
1191 * refcount gets incremented before it gets decremented. */
1192 for (j
= 0; j
< c
->argc
; j
++) decrRefCount(c
->argv
[j
]);
1194 /* Replace argv and argc with our new versions. */
1197 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1198 redisAssertWithInfo(c
,NULL
,c
->cmd
!= NULL
);
1202 /* Rewrite a single item in the command vector.
1203 * The new val ref count is incremented, and the old decremented. */
1204 void rewriteClientCommandArgument(redisClient
*c
, int i
, robj
*newval
) {
1207 redisAssertWithInfo(c
,NULL
,i
< c
->argc
);
1208 oldval
= c
->argv
[i
];
1209 c
->argv
[i
] = newval
;
1210 incrRefCount(newval
);
1211 decrRefCount(oldval
);
1213 /* If this is the command name make sure to fix c->cmd. */
1215 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1216 redisAssertWithInfo(c
,NULL
,c
->cmd
!= NULL
);
1220 /* This function returns the number of bytes that Redis is virtually
1221 * using to store the reply still not read by the client.
1222 * It is "virtual" since the reply output list may contain objects that
1223 * are shared and are not really using additional memory.
1225 * The function returns the total sum of the length of all the objects
1226 * stored in the output list, plus the memory used to allocate every
1227 * list node. The static reply buffer is not taken into account since it
1228 * is allocated anyway.
1230 * Note: this function is very fast so can be called as many time as
1231 * the caller wishes. The main usage of this function currently is
1232 * enforcing the client output length limits. */
1233 unsigned long getClientOutputBufferMemoryUsage(redisClient
*c
) {
1234 unsigned long list_item_size
= sizeof(listNode
)+sizeof(robj
);
1236 return c
->reply_bytes
+ (list_item_size
*listLength(c
->reply
));
1239 /* Get the class of a client, used in order to envorce limits to different
1240 * classes of clients.
1242 * The function will return one of the following:
1243 * REDIS_CLIENT_LIMIT_CLASS_NORMAL -> Normal client
1244 * REDIS_CLIENT_LIMIT_CLASS_SLAVE -> Slave or client executing MONITOR command
1245 * REDIS_CLIENT_LIMIT_CLASS_PUBSUB -> Client subscribed to Pub/Sub channels
1247 int getClientLimitClass(redisClient
*c
) {
1248 if (c
->flags
& REDIS_SLAVE
) return REDIS_CLIENT_LIMIT_CLASS_SLAVE
;
1249 if (dictSize(c
->pubsub_channels
) || listLength(c
->pubsub_patterns
))
1250 return REDIS_CLIENT_LIMIT_CLASS_PUBSUB
;
1251 return REDIS_CLIENT_LIMIT_CLASS_NORMAL
;
1254 int getClientLimitClassByName(char *name
) {
1255 if (!strcasecmp(name
,"normal")) return REDIS_CLIENT_LIMIT_CLASS_NORMAL
;
1256 else if (!strcasecmp(name
,"slave")) return REDIS_CLIENT_LIMIT_CLASS_SLAVE
;
1257 else if (!strcasecmp(name
,"pubsub")) return REDIS_CLIENT_LIMIT_CLASS_PUBSUB
;
1261 char *getClientLimitClassName(int class) {
1263 case REDIS_CLIENT_LIMIT_CLASS_NORMAL
: return "normal";
1264 case REDIS_CLIENT_LIMIT_CLASS_SLAVE
: return "slave";
1265 case REDIS_CLIENT_LIMIT_CLASS_PUBSUB
: return "pubsub";
1266 default: return NULL
;
1270 /* The function checks if the client reached output buffer soft or hard
1271 * limit, and also update the state needed to check the soft limit as
1274 * Return value: non-zero if the client reached the soft or the hard limit.
1275 * Otherwise zero is returned. */
1276 int checkClientOutputBufferLimits(redisClient
*c
) {
1277 int soft
= 0, hard
= 0, class;
1278 unsigned long used_mem
= getClientOutputBufferMemoryUsage(c
);
1280 class = getClientLimitClass(c
);
1281 if (server
.client_obuf_limits
[class].hard_limit_bytes
&&
1282 used_mem
>= server
.client_obuf_limits
[class].hard_limit_bytes
)
1284 if (server
.client_obuf_limits
[class].soft_limit_bytes
&&
1285 used_mem
>= server
.client_obuf_limits
[class].soft_limit_bytes
)
1288 /* We need to check if the soft limit is reached continuously for the
1289 * specified amount of seconds. */
1291 if (c
->obuf_soft_limit_reached_time
== 0) {
1292 c
->obuf_soft_limit_reached_time
= server
.unixtime
;
1293 soft
= 0; /* First time we see the soft limit reached */
1295 time_t elapsed
= server
.unixtime
- c
->obuf_soft_limit_reached_time
;
1298 server
.client_obuf_limits
[class].soft_limit_seconds
) {
1299 soft
= 0; /* The client still did not reached the max number of
1300 seconds for the soft limit to be considered
1305 c
->obuf_soft_limit_reached_time
= 0;
1307 return soft
|| hard
;
1310 /* Asynchronously close a client if soft or hard limit is reached on the
1311 * output buffer size. The caller can check if the client will be closed
1312 * checking if the client REDIS_CLOSE_ASAP flag is set.
1314 * Note: we need to close the client asynchronously because this function is
1315 * called from contexts where the client can't be freed safely, i.e. from the
1316 * lower level functions pushing data inside the client output buffers. */
1317 void asyncCloseClientOnOutputBufferLimitReached(redisClient
*c
) {
1318 if (c
->flags
& REDIS_CLOSE_ASAP
) return;
1319 if (checkClientOutputBufferLimits(c
)) {
1320 sds client
= getClientInfoString(c
);
1323 redisLog(REDIS_WARNING
,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client
);
1328 /* Helper function used by freeMemoryIfNeeded() in order to flush slaves
1329 * output buffers without returning control to the event loop. */
1330 void flushSlavesOutputBuffers(void) {
1334 listRewind(server
.slaves
,&li
);
1335 while((ln
= listNext(&li
))) {
1336 redisClient
*slave
= listNodeValue(ln
);
1339 events
= aeGetFileEvents(server
.el
,slave
->fd
);
1340 if (events
& AE_WRITABLE
&&
1341 slave
->replstate
== REDIS_REPL_ONLINE
&&
1342 listLength(slave
->reply
))
1344 sendReplyToClient(server
.el
,slave
->fd
,slave
,0);