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 /* Set the event loop to listen for write events on the client's socket.
71 * Typically gets called every time a reply is built. */
72 int _installWriteEvent(redisClient
*c
) {
73 if (c
->flags
& REDIS_LUA_CLIENT
) return REDIS_OK
;
74 if (c
->fd
<= 0) return REDIS_ERR
;
75 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0 &&
76 (c
->replstate
== REDIS_REPL_NONE
||
77 c
->replstate
== REDIS_REPL_ONLINE
) &&
78 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
79 sendReplyToClient
, c
) == AE_ERR
) return REDIS_ERR
;
83 /* Create a duplicate of the last object in the reply list when
84 * it is not exclusively owned by the reply list. */
85 robj
*dupLastObjectIfNeeded(list
*reply
) {
88 redisAssert(listLength(reply
) > 0);
90 cur
= listNodeValue(ln
);
91 if (cur
->refcount
> 1) {
92 new = dupStringObject(cur
);
94 listNodeValue(ln
) = new;
96 return listNodeValue(ln
);
99 /* -----------------------------------------------------------------------------
100 * Low level functions to add more data to output buffers.
101 * -------------------------------------------------------------------------- */
103 int _addReplyToBuffer(redisClient
*c
, char *s
, size_t len
) {
104 size_t available
= sizeof(c
->buf
)-c
->bufpos
;
106 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return REDIS_OK
;
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
;
112 /* Check that the buffer has enough space available for this string. */
113 if (len
> available
) return REDIS_ERR
;
115 memcpy(c
->buf
+c
->bufpos
,s
,len
);
120 void _addReplyObjectToList(redisClient
*c
, robj
*o
) {
123 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
125 if (listLength(c
->reply
) == 0) {
127 listAddNodeTail(c
->reply
,o
);
129 tail
= listNodeValue(listLast(c
->reply
));
131 /* Append to this object when possible. */
132 if (tail
->ptr
!= NULL
&&
133 sdslen(tail
->ptr
)+sdslen(o
->ptr
) <= REDIS_REPLY_CHUNK_BYTES
)
135 tail
= dupLastObjectIfNeeded(c
->reply
);
136 tail
->ptr
= sdscatlen(tail
->ptr
,o
->ptr
,sdslen(o
->ptr
));
139 listAddNodeTail(c
->reply
,o
);
142 c
->reply_bytes
+= sdslen(o
->ptr
);
143 asyncCloseClientOnOutputBufferLimitReached(c
);
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. */
148 void _addReplySdsToList(redisClient
*c
, sds s
) {
151 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) {
156 c
->reply_bytes
+= sdslen(s
);
157 if (listLength(c
->reply
) == 0) {
158 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
160 tail
= listNodeValue(listLast(c
->reply
));
162 /* Append to this object when possible. */
163 if (tail
->ptr
!= NULL
&&
164 sdslen(tail
->ptr
)+sdslen(s
) <= REDIS_REPLY_CHUNK_BYTES
)
166 tail
= dupLastObjectIfNeeded(c
->reply
);
167 tail
->ptr
= sdscatlen(tail
->ptr
,s
,sdslen(s
));
170 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
173 asyncCloseClientOnOutputBufferLimitReached(c
);
176 void _addReplyStringToList(redisClient
*c
, char *s
, size_t len
) {
179 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
181 if (listLength(c
->reply
) == 0) {
182 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
184 tail
= listNodeValue(listLast(c
->reply
));
186 /* Append to this object when possible. */
187 if (tail
->ptr
!= NULL
&&
188 sdslen(tail
->ptr
)+len
<= REDIS_REPLY_CHUNK_BYTES
)
190 tail
= dupLastObjectIfNeeded(c
->reply
);
191 tail
->ptr
= sdscatlen(tail
->ptr
,s
,len
);
193 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
196 c
->reply_bytes
+= len
;
197 asyncCloseClientOnOutputBufferLimitReached(c
);
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 * -------------------------------------------------------------------------- */
205 void addReply(redisClient
*c
, robj
*obj
) {
206 if (_installWriteEvent(c
) != REDIS_OK
) return;
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.
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
);
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. */
222 obj
= getDecodedObject(obj
);
223 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
224 _addReplyObjectToList(c
,obj
);
229 void addReplySds(redisClient
*c
, sds s
) {
230 if (_installWriteEvent(c
) != REDIS_OK
) {
231 /* The caller expects the sds to be free'd. */
235 if (_addReplyToBuffer(c
,s
,sdslen(s
)) == REDIS_OK
) {
238 /* This method free's the sds when it is no longer needed. */
239 _addReplySdsToList(c
,s
);
243 void addReplyString(redisClient
*c
, char *s
, size_t len
) {
244 if (_installWriteEvent(c
) != REDIS_OK
) return;
245 if (_addReplyToBuffer(c
,s
,len
) != REDIS_OK
)
246 _addReplyStringToList(c
,s
,len
);
249 void _addReplyError(redisClient
*c
, char *s
, size_t len
) {
250 addReplyString(c
,"-ERR ",5);
251 addReplyString(c
,s
,len
);
252 addReplyString(c
,"\r\n",2);
255 void addReplyError(redisClient
*c
, char *err
) {
256 _addReplyError(c
,err
,strlen(err
));
259 void addReplyErrorFormat(redisClient
*c
, const char *fmt
, ...) {
263 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
265 /* Make sure there are no newlines in the string, otherwise invalid protocol
268 for (j
= 0; j
< l
; j
++) {
269 if (s
[j
] == '\r' || s
[j
] == '\n') s
[j
] = ' ';
271 _addReplyError(c
,s
,sdslen(s
));
275 void _addReplyStatus(redisClient
*c
, char *s
, size_t len
) {
276 addReplyString(c
,"+",1);
277 addReplyString(c
,s
,len
);
278 addReplyString(c
,"\r\n",2);
281 void addReplyStatus(redisClient
*c
, char *status
) {
282 _addReplyStatus(c
,status
,strlen(status
));
285 void addReplyStatusFormat(redisClient
*c
, const char *fmt
, ...) {
288 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
290 _addReplyStatus(c
,s
,sdslen(s
));
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. */
296 void *addDeferredMultiBulkLength(redisClient
*c
) {
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
;
301 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,NULL
));
302 return listLast(c
->reply
);
305 /* Populate the length object and try glueing it to the next chunk. */
306 void setDeferredMultiBulkLength(redisClient
*c
, void *node
, long length
) {
307 listNode
*ln
= (listNode
*)node
;
310 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
311 if (node
== NULL
) return;
313 len
= listNodeValue(ln
);
314 len
->ptr
= sdscatprintf(sdsempty(),"*%ld\r\n",length
);
315 c
->reply_bytes
+= sdslen(len
->ptr
);
316 if (ln
->next
!= NULL
) {
317 next
= listNodeValue(ln
->next
);
319 /* Only glue when the next node is non-NULL (an sds in this case) */
320 if (next
->ptr
!= NULL
) {
321 len
->ptr
= sdscatlen(len
->ptr
,next
->ptr
,sdslen(next
->ptr
));
322 listDelNode(c
->reply
,ln
->next
);
325 asyncCloseClientOnOutputBufferLimitReached(c
);
328 /* Add a duble as a bulk reply */
329 void addReplyDouble(redisClient
*c
, double d
) {
330 char dbuf
[128], sbuf
[128];
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
);
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>. */
339 void _addReplyLongLong(redisClient
*c
, long long ll
, char prefix
) {
343 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
346 addReplyString(c
,buf
,len
+3);
349 void addReplyLongLong(redisClient
*c
, long long ll
) {
351 addReply(c
,shared
.czero
);
353 addReply(c
,shared
.cone
);
355 _addReplyLongLong(c
,ll
,':');
358 void addReplyMultiBulkLen(redisClient
*c
, long length
) {
359 _addReplyLongLong(c
,length
,'*');
362 /* Create the length prefix of a bulk reply, example: $2234 */
363 void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
366 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
367 len
= sdslen(obj
->ptr
);
369 long n
= (long)obj
->ptr
;
371 /* Compute how many bytes will take this integer as a radix 10 string */
377 while((n
= n
/10) != 0) {
381 _addReplyLongLong(c
,len
,'$');
384 /* Add a Redis Object as a bulk reply */
385 void addReplyBulk(redisClient
*c
, robj
*obj
) {
386 addReplyBulkLen(c
,obj
);
388 addReply(c
,shared
.crlf
);
391 /* Add a C buffer as bulk reply */
392 void addReplyBulkCBuffer(redisClient
*c
, void *p
, size_t len
) {
393 _addReplyLongLong(c
,len
,'$');
394 addReplyString(c
,p
,len
);
395 addReply(c
,shared
.crlf
);
398 /* Add a C nul term string as bulk reply */
399 void addReplyBulkCString(redisClient
*c
, char *s
) {
401 addReply(c
,shared
.nullbulk
);
403 addReplyBulkCBuffer(c
,s
,strlen(s
));
407 /* Add a long long as a bulk reply */
408 void addReplyBulkLongLong(redisClient
*c
, long long ll
) {
412 len
= ll2string(buf
,64,ll
);
413 addReplyBulkCBuffer(c
,buf
,len
);
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. */
419 void 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
;
424 dst
->reply_bytes
= src
->reply_bytes
;
427 static void acceptCommonHandler(int fd
) {
429 if ((c
= createClient(fd
)) == NULL
) {
430 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
431 close(fd
); /* May be already closed, just ingore errors */
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 */
438 if (listLength(server
.clients
) > server
.maxclients
) {
439 char *err
= "-ERR max number of clients reached\r\n";
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... */
445 server
.stat_rejected_conn
++;
449 server
.stat_numconnections
++;
452 void acceptTcpHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
457 REDIS_NOTUSED(privdata
);
459 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
461 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
464 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
465 acceptCommonHandler(cfd
);
468 void acceptUnixHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
472 REDIS_NOTUSED(privdata
);
474 cfd
= anetUnixAccept(server
.neterr
, fd
);
476 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
479 redisLog(REDIS_VERBOSE
,"Accepted connection to %s", server
.unixsocket
);
480 acceptCommonHandler(cfd
);
484 static void freeClientArgv(redisClient
*c
) {
486 for (j
= 0; j
< c
->argc
; j
++)
487 decrRefCount(c
->argv
[j
]);
492 void freeClient(redisClient
*c
) {
495 /* If this is marked as current client unset it */
496 if (server
.current_client
== c
) server
.current_client
= NULL
;
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
);
505 if (c
->flags
& REDIS_BLOCKED
)
506 unblockClientWaitingData(c
);
508 /* UNWATCH all the keys */
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
);
522 /* Remove from the list of clients */
523 ln
= listSearchKey(server
.clients
,c
);
524 redisAssert(ln
!= NULL
);
525 listDelNode(server
.clients
,ln
);
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
);
533 listRelease(c
->io_keys
);
534 /* Master/slave cleanup.
535 * Case 1: we lost the connection with a slave. */
536 if (c
->flags
& REDIS_SLAVE
) {
537 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
539 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
540 ln
= listSearchKey(l
,c
);
541 redisAssert(ln
!= NULL
);
545 /* Case 2: we lost the connection with the master. */
546 if (c
->flags
& REDIS_MASTER
) {
547 server
.master
= NULL
;
548 server
.repl_state
= REDIS_REPL_CONNECT
;
549 server
.repl_down_since
= time(NULL
);
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
554 * to the master it will keep refusing connections by other slaves.
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
);
567 /* If this client was scheduled for async freeing we need to remove it
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
);
577 freeClientMultiState(c
);
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. */
585 void freeClientAsync(redisClient
*c
) {
586 if (c
->flags
& REDIS_CLOSE_ASAP
) return;
587 c
->flags
|= REDIS_CLOSE_ASAP
;
588 listAddNodeTail(server
.clients_to_close
,c
);
591 void freeClientsInAsyncFreeQueue(void) {
592 while (listLength(server
.clients_to_close
)) {
593 listNode
*ln
= listFirst(server
.clients_to_close
);
594 redisClient
*c
= listNodeValue(ln
);
596 c
->flags
&= ~REDIS_CLOSE_ASAP
;
598 listDelNode(server
.clients_to_close
,ln
);
602 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
603 redisClient
*c
= privdata
;
604 int nwritten
= 0, totwritten
= 0, objlen
;
609 while(c
->bufpos
> 0 || listLength(c
->reply
)) {
611 if (c
->flags
& REDIS_MASTER
) {
612 /* Don't reply to a master */
613 nwritten
= c
->bufpos
- c
->sentlen
;
615 nwritten
= write(fd
,c
->buf
+c
->sentlen
,c
->bufpos
-c
->sentlen
);
616 if (nwritten
<= 0) break;
618 c
->sentlen
+= nwritten
;
619 totwritten
+= nwritten
;
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
) {
628 o
= listNodeValue(listFirst(c
->reply
));
629 objlen
= sdslen(o
->ptr
);
632 listDelNode(c
->reply
,listFirst(c
->reply
));
636 if (c
->flags
& REDIS_MASTER
) {
637 /* Don't reply to a master */
638 nwritten
= objlen
- c
->sentlen
;
640 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
,objlen
-c
->sentlen
);
641 if (nwritten
<= 0) break;
643 c
->sentlen
+= nwritten
;
644 totwritten
+= nwritten
;
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
));
650 c
->reply_bytes
-= objlen
;
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;
660 if (nwritten
== -1) {
661 if (errno
== EAGAIN
) {
664 redisLog(REDIS_VERBOSE
,
665 "Error writing to client: %s", strerror(errno
));
670 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
671 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0) {
673 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
675 /* Close connection after entire reply has been sent. */
676 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) freeClient(c
);
680 /* resetClient prepare the client to process the next command */
681 void resetClient(redisClient
*c
) {
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
);
690 void closeTimedoutClients(void) {
693 time_t now
= time(NULL
);
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 */
702 !(c
->flags
& REDIS_BLOCKED
) && /* no timeout for BLPOP */
703 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
704 listLength(c
->pubsub_patterns
) == 0 &&
705 (now
- c
->lastinteraction
> server
.maxidletime
))
707 redisLog(REDIS_VERBOSE
,"Closing idle client");
709 } else if (c
->flags
& REDIS_BLOCKED
) {
710 if (c
->bpop
.timeout
!= 0 && c
->bpop
.timeout
< now
) {
711 addReply(c
,shared
.nullmultibulk
);
712 unblockClientWaitingData(c
);
718 int processInlineBuffer(redisClient
*c
) {
719 char *newline
= strstr(c
->querybuf
,"\r\n");
724 /* Nothing to do without a \r\n */
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);
733 /* Split the input buffer up to the \r\n */
734 querylen
= newline
-(c
->querybuf
);
735 argv
= sdssplitlen(c
->querybuf
,querylen
," ",1,&argc
);
737 /* Leave data after the first line of the query in the buffer */
738 c
->querybuf
= sdsrange(c
->querybuf
,querylen
+2,-1);
740 /* Setup argv array on client structure */
741 if (c
->argv
) zfree(c
->argv
);
742 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
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
]);
757 /* Helper function. Trims query buffer to make the function that processes
758 * multi bulk requests idempotent. */
759 static void setProtocolError(redisClient
*c
, int pos
) {
760 if (server
.verbosity
>= REDIS_VERBOSE
) {
761 sds client
= getClientInfoString(c
);
762 redisLog(REDIS_VERBOSE
,
763 "Protocol error from client: %s", client
);
766 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
767 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
770 int processMultibulkBuffer(redisClient
*c
) {
771 char *newline
= NULL
;
775 if (c
->multibulklen
== 0) {
776 /* The client should have been reset */
777 redisAssertWithInfo(c
,NULL
,c
->argc
== 0);
779 /* Multi bulk length cannot be read without a \r\n */
780 newline
= strchr(c
->querybuf
,'\r');
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);
789 /* Buffer should also contain \n */
790 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
793 /* We know for sure there is a whole line since newline != NULL,
794 * so go ahead and find out the multi bulk length. */
795 redisAssertWithInfo(c
,NULL
,c
->querybuf
[0] == '*');
796 ok
= string2ll(c
->querybuf
+1,newline
-(c
->querybuf
+1),&ll
);
797 if (!ok
|| ll
> 1024*1024) {
798 addReplyError(c
,"Protocol error: invalid multibulk length");
799 setProtocolError(c
,pos
);
803 pos
= (newline
-c
->querybuf
)+2;
805 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
809 c
->multibulklen
= ll
;
811 /* Setup argv array on client structure */
812 if (c
->argv
) zfree(c
->argv
);
813 c
->argv
= zmalloc(sizeof(robj
*)*c
->multibulklen
);
816 redisAssertWithInfo(c
,NULL
,c
->multibulklen
> 0);
817 while(c
->multibulklen
) {
818 /* Read bulk length if unknown */
819 if (c
->bulklen
== -1) {
820 newline
= strchr(c
->querybuf
+pos
,'\r');
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);
829 /* Buffer should also contain \n */
830 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
833 if (c
->querybuf
[pos
] != '$') {
834 addReplyErrorFormat(c
,
835 "Protocol error: expected '$', got '%c'",
837 setProtocolError(c
,pos
);
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
);
848 pos
+= newline
-(c
->querybuf
+pos
)+2;
849 if (ll
>= REDIS_MBULK_BIG_ARG
) {
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);
856 /* Hint the sds library about the amount of bytes this string is
857 * going to contain. */
858 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
,ll
+2);
863 /* Read bulk argument */
864 if (sdslen(c
->querybuf
)-pos
< (unsigned)(c
->bulklen
+2)) {
865 /* Not enough data (+2 == trailing \r\n) */
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. */
872 c
->bulklen
>= REDIS_MBULK_BIG_ARG
&&
873 (signed) sdslen(c
->querybuf
) == c
->bulklen
+2)
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
880 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
,c
->bulklen
+2);
884 createStringObject(c
->querybuf
+pos
,c
->bulklen
);
893 if (pos
) c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
895 /* We're done when c->multibulk == 0 */
896 if (c
->multibulklen
== 0) return REDIS_OK
;
898 /* Still not read to process the command */
902 void processInputBuffer(redisClient
*c
) {
903 /* Keep processing while there is something in the input buffer */
904 while(sdslen(c
->querybuf
)) {
905 /* Immediately abort if the client is in the middle of something. */
906 if (c
->flags
& REDIS_BLOCKED
) return;
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;
913 /* Determine request type when unknown. */
915 if (c
->querybuf
[0] == '*') {
916 c
->reqtype
= REDIS_REQ_MULTIBULK
;
918 c
->reqtype
= REDIS_REQ_INLINE
;
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;
927 redisPanic("Unknown request type");
930 /* Multibulk processing could see a <= 0 length. */
934 /* Only reset the client when the command was executed. */
935 if (processCommand(c
) == REDIS_OK
)
941 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
942 redisClient
*c
= (redisClient
*) privdata
;
948 server
.current_client
= c
;
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. */
956 if (c
->reqtype
== REDIS_REQ_MULTIBULK
&& c
->multibulklen
&& c
->bulklen
!= -1
957 && c
->bulklen
>= REDIS_MBULK_BIG_ARG
)
959 int remaining
= (unsigned)(c
->bulklen
+2)-sdslen(c
->querybuf
);
961 if (remaining
< readlen
) readlen
= remaining
;
964 qblen
= sdslen(c
->querybuf
);
965 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
, readlen
);
966 nread
= read(fd
, c
->querybuf
+qblen
, readlen
);
968 if (errno
== EAGAIN
) {
971 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
975 } else if (nread
== 0) {
976 redisLog(REDIS_VERBOSE
, "Client closed connection");
981 sdsIncrLen(c
->querybuf
,nread
);
982 c
->lastinteraction
= time(NULL
);
984 server
.current_client
= NULL
;
987 if (sdslen(c
->querybuf
) > server
.client_max_querybuf_len
) {
988 sds ci
= getClientInfoString(c
), bytes
= sdsempty();
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
);
997 processInputBuffer(c
);
998 server
.current_client
= NULL
;
1001 void getClientsMaxBuffers(unsigned long *longest_output_list
,
1002 unsigned long *biggest_input_buffer
) {
1006 unsigned long lol
= 0, bib
= 0;
1008 listRewind(server
.clients
,&li
);
1009 while ((ln
= listNext(&li
)) != NULL
) {
1010 c
= listNodeValue(ln
);
1012 if (listLength(c
->reply
) > lol
) lol
= listLength(c
->reply
);
1013 if (sdslen(c
->querybuf
) > bib
) bib
= sdslen(c
->querybuf
);
1015 *longest_output_list
= lol
;
1016 *biggest_input_buffer
= bib
;
1019 /* Turn a Redis client into an sds string representing its state. */
1020 sds
getClientInfoString(redisClient
*client
) {
1021 char ip
[32], flags
[16], events
[3], *p
;
1023 time_t now
= time(NULL
);
1026 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) {
1032 if (client
->flags
& REDIS_SLAVE
) {
1033 if (client
->flags
& REDIS_MONITOR
)
1038 if (client
->flags
& REDIS_MASTER
) *p
++ = 'M';
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';
1044 if (client
->flags
& REDIS_CLOSE_ASAP
) *p
++ = 'A';
1045 if (p
== flags
) *p
++ = 'N';
1048 emask
= client
->fd
== -1 ? 0 : aeGetFileEvents(server
.el
,client
->fd
);
1050 if (emask
& AE_READABLE
) *p
++ = 'r';
1051 if (emask
& AE_WRITABLE
) *p
++ = 'w';
1053 return sdscatprintf(sdsempty(),
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",
1056 (long)(now
- client
->lastinteraction
),
1059 (int) dictSize(client
->pubsub_channels
),
1060 (int) listLength(client
->pubsub_patterns
),
1061 (unsigned long) sdslen(client
->querybuf
),
1062 (unsigned long) client
->bufpos
,
1063 (unsigned long) listLength(client
->reply
),
1064 getClientOutputBufferMemoryUsage(client
),
1066 client
->lastcmd
? client
->lastcmd
->name
: "NULL");
1069 sds
getAllClientsInfoString(void) {
1072 redisClient
*client
;
1075 listRewind(server
.clients
,&li
);
1076 while ((ln
= listNext(&li
)) != NULL
) {
1079 client
= listNodeValue(ln
);
1080 cs
= getClientInfoString(client
);
1081 o
= sdscatsds(o
,cs
);
1083 o
= sdscatlen(o
,"\n",1);
1088 void clientCommand(redisClient
*c
) {
1091 redisClient
*client
;
1093 if (!strcasecmp(c
->argv
[1]->ptr
,"list") && c
->argc
== 2) {
1094 sds o
= getAllClientsInfoString();
1095 addReplyBulkCBuffer(c
,o
,sdslen(o
));
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];
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
);
1109 client
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1116 addReplyError(c
,"No such client");
1118 addReplyError(c
, "Syntax error, try CLIENT (LIST | KILL ip:port)");
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. */
1125 void rewriteClientCommandVector(redisClient
*c
, int argc
, ...) {
1128 robj
**argv
; /* The new argument vector */
1130 argv
= zmalloc(sizeof(robj
*)*argc
);
1132 for (j
= 0; j
< argc
; j
++) {
1135 a
= va_arg(ap
, robj
*);
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
]);
1144 /* Replace argv and argc with our new versions. */
1147 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1148 redisAssertWithInfo(c
,NULL
,c
->cmd
!= NULL
);
1152 /* Rewrite a single item in the command vector.
1153 * The new val ref count is incremented, and the old decremented. */
1154 void rewriteClientCommandArgument(redisClient
*c
, int i
, robj
*newval
) {
1157 redisAssertWithInfo(c
,NULL
,i
< c
->argc
);
1158 oldval
= c
->argv
[i
];
1159 c
->argv
[i
] = newval
;
1160 incrRefCount(newval
);
1161 decrRefCount(oldval
);
1163 /* If this is the command name make sure to fix c->cmd. */
1165 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1166 redisAssertWithInfo(c
,NULL
,c
->cmd
!= NULL
);
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.
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.
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. */
1183 unsigned long getClientOutputBufferMemoryUsage(redisClient
*c
) {
1184 unsigned long list_item_size
= sizeof(listNode
);
1186 return c
->reply_bytes
+ (list_item_size
*listLength(c
->reply
));
1189 /* Get the class of a client, used in order to envorce limits to different
1190 * classes of clients.
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
1197 int 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
;
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
1208 * Return value: non-zero if the client reached the soft or the hard limit.
1209 * Otherwise zero is returned. */
1210 int checkClientOutputBufferLimits(redisClient
*c
) {
1211 int soft
= 0, hard
= 0, class;
1212 unsigned long used_mem
= getClientOutputBufferMemoryUsage(c
);
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
)
1218 if (server
.client_obuf_limits
[class].soft_limit_bytes
&&
1219 used_mem
>= server
.client_obuf_limits
[class].soft_limit_bytes
)
1222 /* We need to check if the soft limit is reached continuously for the
1223 * specified amount of seconds. */
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 */
1229 time_t elapsed
= server
.unixtime
- c
->obuf_soft_limit_reached_time
;
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
1239 c
->obuf_soft_limit_reached_time
= 0;
1241 return soft
|| hard
;
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
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. */
1251 int asyncCloseClientOnOutputBufferLimitReached(redisClient
*c
) {
1252 if (checkClientOutputBufferLimits(c
)) {
1253 sds client
= getClientInfoString(c
);
1256 redisLog(REDIS_NOTICE
,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.");