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
+= sdslen(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
+= sdslen(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 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
196 tail
= listNodeValue(listLast(c
->reply
));
198 /* Append to this object when possible. */
199 if (tail
->ptr
!= NULL
&&
200 sdslen(tail
->ptr
)+len
<= REDIS_REPLY_CHUNK_BYTES
)
202 tail
= dupLastObjectIfNeeded(c
->reply
);
203 tail
->ptr
= sdscatlen(tail
->ptr
,s
,len
);
205 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
208 c
->reply_bytes
+= len
;
209 asyncCloseClientOnOutputBufferLimitReached(c
);
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 * -------------------------------------------------------------------------- */
217 void addReply(redisClient
*c
, robj
*obj
) {
218 if (prepareClientToWrite(c
) != REDIS_OK
) return;
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.
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) {
238 len
= ll2string(buf
,sizeof(buf
),(long)obj
->ptr
);
239 if (_addReplyToBuffer(c
,buf
,len
) == REDIS_OK
)
241 /* else... continue with the normal code path, but should never
242 * happen actually since we verified there is room. */
244 obj
= getDecodedObject(obj
);
245 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
246 _addReplyObjectToList(c
,obj
);
249 redisPanic("Wrong obj->encoding in addReply()");
253 void addReplySds(redisClient
*c
, sds s
) {
254 if (prepareClientToWrite(c
) != REDIS_OK
) {
255 /* The caller expects the sds to be free'd. */
259 if (_addReplyToBuffer(c
,s
,sdslen(s
)) == REDIS_OK
) {
262 /* This method free's the sds when it is no longer needed. */
263 _addReplySdsToList(c
,s
);
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
);
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);
279 void addReplyError(redisClient
*c
, char *err
) {
280 addReplyErrorLength(c
,err
,strlen(err
));
283 void addReplyErrorFormat(redisClient
*c
, const char *fmt
, ...) {
287 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
289 /* Make sure there are no newlines in the string, otherwise invalid protocol
292 for (j
= 0; j
< l
; j
++) {
293 if (s
[j
] == '\r' || s
[j
] == '\n') s
[j
] = ' ';
295 addReplyErrorLength(c
,s
,sdslen(s
));
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);
305 void addReplyStatus(redisClient
*c
, char *status
) {
306 addReplyStatusLength(c
,status
,strlen(status
));
309 void addReplyStatusFormat(redisClient
*c
, const char *fmt
, ...) {
312 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
314 addReplyStatusLength(c
,s
,sdslen(s
));
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
);
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
;
334 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
335 if (node
== NULL
) return;
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
);
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
);
349 asyncCloseClientOnOutputBufferLimitReached(c
);
352 /* Add a duble as a bulk reply */
353 void addReplyDouble(redisClient
*c
, double d
) {
354 char dbuf
[128], sbuf
[128];
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
);
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
) {
367 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
370 addReplyString(c
,buf
,len
+3);
373 void addReplyLongLong(redisClient
*c
, long long ll
) {
375 addReply(c
,shared
.czero
);
377 addReply(c
,shared
.cone
);
379 addReplyLongLongWithPrefix(c
,ll
,':');
382 void addReplyMultiBulkLen(redisClient
*c
, long length
) {
383 addReplyLongLongWithPrefix(c
,length
,'*');
386 /* Create the length prefix of a bulk reply, example: $2234 */
387 void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
390 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
391 len
= sdslen(obj
->ptr
);
393 long n
= (long)obj
->ptr
;
395 /* Compute how many bytes will take this integer as a radix 10 string */
401 while((n
= n
/10) != 0) {
405 addReplyLongLongWithPrefix(c
,len
,'$');
408 /* Add a Redis Object as a bulk reply */
409 void addReplyBulk(redisClient
*c
, robj
*obj
) {
410 addReplyBulkLen(c
,obj
);
412 addReply(c
,shared
.crlf
);
415 /* Add a C buffer as bulk reply */
416 void addReplyBulkCBuffer(redisClient
*c
, void *p
, size_t len
) {
417 addReplyLongLongWithPrefix(c
,len
,'$');
418 addReplyString(c
,p
,len
);
419 addReply(c
,shared
.crlf
);
422 /* Add a C nul term string as bulk reply */
423 void addReplyBulkCString(redisClient
*c
, char *s
) {
425 addReply(c
,shared
.nullbulk
);
427 addReplyBulkCBuffer(c
,s
,strlen(s
));
431 /* Add a long long as a bulk reply */
432 void addReplyBulkLongLong(redisClient
*c
, long long ll
) {
436 len
= ll2string(buf
,64,ll
);
437 addReplyBulkCBuffer(c
,buf
,len
);
440 /* Copy 'src' client output buffers into 'dst' client output buffers.
441 * The function takes care of freeing the old output buffers of the
442 * destination client. */
443 void copyClientOutputBuffer(redisClient
*dst
, redisClient
*src
) {
444 listRelease(dst
->reply
);
445 dst
->reply
= listDup(src
->reply
);
446 memcpy(dst
->buf
,src
->buf
,src
->bufpos
);
447 dst
->bufpos
= src
->bufpos
;
448 dst
->reply_bytes
= src
->reply_bytes
;
451 static void acceptCommonHandler(int fd
) {
453 if ((c
= createClient(fd
)) == NULL
) {
454 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
455 close(fd
); /* May be already closed, just ingore errors */
458 /* If maxclient directive is set and this is one client more... close the
459 * connection. Note that we create the client instead to check before
460 * for this condition, since now the socket is already set in nonblocking
461 * mode and we can send an error for free using the Kernel I/O */
462 if (listLength(server
.clients
) > server
.maxclients
) {
463 char *err
= "-ERR max number of clients reached\r\n";
465 /* That's a best effort error message, don't check write errors */
466 if (write(c
->fd
,err
,strlen(err
)) == -1) {
467 /* Nothing to do, Just to avoid the warning... */
469 server
.stat_rejected_conn
++;
473 server
.stat_numconnections
++;
476 void acceptTcpHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
481 REDIS_NOTUSED(privdata
);
483 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
485 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
488 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
489 acceptCommonHandler(cfd
);
492 void acceptUnixHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
496 REDIS_NOTUSED(privdata
);
498 cfd
= anetUnixAccept(server
.neterr
, fd
);
500 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
503 redisLog(REDIS_VERBOSE
,"Accepted connection to %s", server
.unixsocket
);
504 acceptCommonHandler(cfd
);
508 static void freeClientArgv(redisClient
*c
) {
510 for (j
= 0; j
< c
->argc
; j
++)
511 decrRefCount(c
->argv
[j
]);
516 void freeClient(redisClient
*c
) {
519 /* If this is marked as current client unset it */
520 if (server
.current_client
== c
) server
.current_client
= NULL
;
522 /* Note that if the client we are freeing is blocked into a blocking
523 * call, we have to set querybuf to NULL *before* to call
524 * unblockClientWaitingData() to avoid processInputBuffer() will get
525 * called. Also it is important to remove the file events after
526 * this, because this call adds the READABLE event. */
527 sdsfree(c
->querybuf
);
529 if (c
->flags
& REDIS_BLOCKED
)
530 unblockClientWaitingData(c
);
532 /* UNWATCH all the keys */
534 listRelease(c
->watched_keys
);
535 /* Unsubscribe from all the pubsub channels */
536 pubsubUnsubscribeAllChannels(c
,0);
537 pubsubUnsubscribeAllPatterns(c
,0);
538 dictRelease(c
->pubsub_channels
);
539 listRelease(c
->pubsub_patterns
);
540 /* Obvious cleanup */
541 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
542 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
543 listRelease(c
->reply
);
546 /* Remove from the list of clients */
547 ln
= listSearchKey(server
.clients
,c
);
548 redisAssert(ln
!= NULL
);
549 listDelNode(server
.clients
,ln
);
550 /* When client was just unblocked because of a blocking operation,
551 * remove it from the list with unblocked clients. */
552 if (c
->flags
& REDIS_UNBLOCKED
) {
553 ln
= listSearchKey(server
.unblocked_clients
,c
);
554 redisAssert(ln
!= NULL
);
555 listDelNode(server
.unblocked_clients
,ln
);
557 listRelease(c
->io_keys
);
558 /* Master/slave cleanup.
559 * Case 1: we lost the connection with a slave. */
560 if (c
->flags
& REDIS_SLAVE
) {
561 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
563 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
564 ln
= listSearchKey(l
,c
);
565 redisAssert(ln
!= NULL
);
569 /* Case 2: we lost the connection with the master. */
570 if (c
->flags
& REDIS_MASTER
) {
571 server
.master
= NULL
;
572 server
.repl_state
= REDIS_REPL_CONNECT
;
573 server
.repl_down_since
= time(NULL
);
574 /* Since we lost the connection with the master, we should also
575 * close the connection with all our slaves if we have any, so
576 * when we'll resync with the master the other slaves will sync again
577 * with us as well. Note that also when the slave is not connected
578 * to the master it will keep refusing connections by other slaves.
580 * We do this only if server.masterhost != NULL. If it is NULL this
581 * means the user called SLAVEOF NO ONE and we are freeing our
582 * link with the master, so no need to close link with slaves. */
583 if (server
.masterhost
!= NULL
) {
584 while (listLength(server
.slaves
)) {
585 ln
= listFirst(server
.slaves
);
586 freeClient((redisClient
*)ln
->value
);
591 /* If this client was scheduled for async freeing we need to remove it
593 if (c
->flags
& REDIS_CLOSE_ASAP
) {
594 ln
= listSearchKey(server
.clients_to_close
,c
);
595 redisAssert(ln
!= NULL
);
596 listDelNode(server
.clients_to_close
,ln
);
601 freeClientMultiState(c
);
605 /* Schedule a client to free it at a safe time in the serverCron() function.
606 * This function is useful when we need to terminate a client but we are in
607 * a context where calling freeClient() is not possible, because the client
608 * should be valid for the continuation of the flow of the program. */
609 void freeClientAsync(redisClient
*c
) {
610 if (c
->flags
& REDIS_CLOSE_ASAP
) return;
611 c
->flags
|= REDIS_CLOSE_ASAP
;
612 listAddNodeTail(server
.clients_to_close
,c
);
615 void freeClientsInAsyncFreeQueue(void) {
616 while (listLength(server
.clients_to_close
)) {
617 listNode
*ln
= listFirst(server
.clients_to_close
);
618 redisClient
*c
= listNodeValue(ln
);
620 c
->flags
&= ~REDIS_CLOSE_ASAP
;
622 listDelNode(server
.clients_to_close
,ln
);
626 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
627 redisClient
*c
= privdata
;
628 int nwritten
= 0, totwritten
= 0, objlen
;
633 while(c
->bufpos
> 0 || listLength(c
->reply
)) {
635 if (c
->flags
& REDIS_MASTER
) {
636 /* Don't reply to a master */
637 nwritten
= c
->bufpos
- c
->sentlen
;
639 nwritten
= write(fd
,c
->buf
+c
->sentlen
,c
->bufpos
-c
->sentlen
);
640 if (nwritten
<= 0) break;
642 c
->sentlen
+= nwritten
;
643 totwritten
+= nwritten
;
645 /* If the buffer was sent, set bufpos to zero to continue with
646 * the remainder of the reply. */
647 if (c
->sentlen
== c
->bufpos
) {
652 o
= listNodeValue(listFirst(c
->reply
));
653 objlen
= sdslen(o
->ptr
);
656 listDelNode(c
->reply
,listFirst(c
->reply
));
660 if (c
->flags
& REDIS_MASTER
) {
661 /* Don't reply to a master */
662 nwritten
= objlen
- c
->sentlen
;
664 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
,objlen
-c
->sentlen
);
665 if (nwritten
<= 0) break;
667 c
->sentlen
+= nwritten
;
668 totwritten
+= nwritten
;
670 /* If we fully sent the object on head go to the next one */
671 if (c
->sentlen
== objlen
) {
672 listDelNode(c
->reply
,listFirst(c
->reply
));
674 c
->reply_bytes
-= objlen
;
677 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
678 * bytes, in a single threaded server it's a good idea to serve
679 * other clients as well, even if a very large request comes from
680 * super fast link that is always able to accept data (in real world
681 * scenario think about 'KEYS *' against the loopback interfae) */
682 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
684 if (nwritten
== -1) {
685 if (errno
== EAGAIN
) {
688 redisLog(REDIS_VERBOSE
,
689 "Error writing to client: %s", strerror(errno
));
694 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
695 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0) {
697 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
699 /* Close connection after entire reply has been sent. */
700 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) freeClient(c
);
704 /* resetClient prepare the client to process the next command */
705 void resetClient(redisClient
*c
) {
710 /* We clear the ASKING flag as well if we are not inside a MULTI. */
711 if (!(c
->flags
& REDIS_MULTI
)) c
->flags
&= (~REDIS_ASKING
);
714 void closeTimedoutClients(void) {
717 time_t now
= time(NULL
);
720 listRewind(server
.clients
,&li
);
721 while ((ln
= listNext(&li
)) != NULL
) {
722 c
= listNodeValue(ln
);
723 if (server
.maxidletime
&&
724 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
725 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
726 !(c
->flags
& REDIS_BLOCKED
) && /* no timeout for BLPOP */
727 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
728 listLength(c
->pubsub_patterns
) == 0 &&
729 (now
- c
->lastinteraction
> server
.maxidletime
))
731 redisLog(REDIS_VERBOSE
,"Closing idle client");
733 } else if (c
->flags
& REDIS_BLOCKED
) {
734 if (c
->bpop
.timeout
!= 0 && c
->bpop
.timeout
< now
) {
735 addReply(c
,shared
.nullmultibulk
);
736 unblockClientWaitingData(c
);
742 int processInlineBuffer(redisClient
*c
) {
743 char *newline
= strstr(c
->querybuf
,"\r\n");
748 /* Nothing to do without a \r\n */
749 if (newline
== NULL
) {
750 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
751 addReplyError(c
,"Protocol error: too big inline request");
752 setProtocolError(c
,0);
757 /* Split the input buffer up to the \r\n */
758 querylen
= newline
-(c
->querybuf
);
759 argv
= sdssplitlen(c
->querybuf
,querylen
," ",1,&argc
);
761 /* Leave data after the first line of the query in the buffer */
762 c
->querybuf
= sdsrange(c
->querybuf
,querylen
+2,-1);
764 /* Setup argv array on client structure */
765 if (c
->argv
) zfree(c
->argv
);
766 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
768 /* Create redis objects for all arguments. */
769 for (c
->argc
= 0, j
= 0; j
< argc
; j
++) {
770 if (sdslen(argv
[j
])) {
771 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
781 /* Helper function. Trims query buffer to make the function that processes
782 * multi bulk requests idempotent. */
783 static void setProtocolError(redisClient
*c
, int pos
) {
784 if (server
.verbosity
>= REDIS_VERBOSE
) {
785 sds client
= getClientInfoString(c
);
786 redisLog(REDIS_VERBOSE
,
787 "Protocol error from client: %s", client
);
790 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
791 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
794 int processMultibulkBuffer(redisClient
*c
) {
795 char *newline
= NULL
;
799 if (c
->multibulklen
== 0) {
800 /* The client should have been reset */
801 redisAssertWithInfo(c
,NULL
,c
->argc
== 0);
803 /* Multi bulk length cannot be read without a \r\n */
804 newline
= strchr(c
->querybuf
,'\r');
805 if (newline
== NULL
) {
806 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
807 addReplyError(c
,"Protocol error: too big mbulk count string");
808 setProtocolError(c
,0);
813 /* Buffer should also contain \n */
814 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
817 /* We know for sure there is a whole line since newline != NULL,
818 * so go ahead and find out the multi bulk length. */
819 redisAssertWithInfo(c
,NULL
,c
->querybuf
[0] == '*');
820 ok
= string2ll(c
->querybuf
+1,newline
-(c
->querybuf
+1),&ll
);
821 if (!ok
|| ll
> 1024*1024) {
822 addReplyError(c
,"Protocol error: invalid multibulk length");
823 setProtocolError(c
,pos
);
827 pos
= (newline
-c
->querybuf
)+2;
829 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
833 c
->multibulklen
= ll
;
835 /* Setup argv array on client structure */
836 if (c
->argv
) zfree(c
->argv
);
837 c
->argv
= zmalloc(sizeof(robj
*)*c
->multibulklen
);
840 redisAssertWithInfo(c
,NULL
,c
->multibulklen
> 0);
841 while(c
->multibulklen
) {
842 /* Read bulk length if unknown */
843 if (c
->bulklen
== -1) {
844 newline
= strchr(c
->querybuf
+pos
,'\r');
845 if (newline
== NULL
) {
846 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
847 addReplyError(c
,"Protocol error: too big bulk count string");
848 setProtocolError(c
,0);
853 /* Buffer should also contain \n */
854 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
857 if (c
->querybuf
[pos
] != '$') {
858 addReplyErrorFormat(c
,
859 "Protocol error: expected '$', got '%c'",
861 setProtocolError(c
,pos
);
865 ok
= string2ll(c
->querybuf
+pos
+1,newline
-(c
->querybuf
+pos
+1),&ll
);
866 if (!ok
|| ll
< 0 || ll
> 512*1024*1024) {
867 addReplyError(c
,"Protocol error: invalid bulk length");
868 setProtocolError(c
,pos
);
872 pos
+= newline
-(c
->querybuf
+pos
)+2;
873 if (ll
>= REDIS_MBULK_BIG_ARG
) {
874 /* If we are going to read a large object from network
875 * try to make it likely that it will start at c->querybuf
876 * boundary so that we can optimized object creation
877 * avoiding a large copy of data. */
878 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
880 /* Hint the sds library about the amount of bytes this string is
881 * going to contain. */
882 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
,ll
+2);
887 /* Read bulk argument */
888 if (sdslen(c
->querybuf
)-pos
< (unsigned)(c
->bulklen
+2)) {
889 /* Not enough data (+2 == trailing \r\n) */
892 /* Optimization: if the buffer contanins JUST our bulk element
893 * instead of creating a new object by *copying* the sds we
894 * just use the current sds string. */
896 c
->bulklen
>= REDIS_MBULK_BIG_ARG
&&
897 (signed) sdslen(c
->querybuf
) == c
->bulklen
+2)
899 c
->argv
[c
->argc
++] = createObject(REDIS_STRING
,c
->querybuf
);
900 sdsIncrLen(c
->querybuf
,-2); /* remove CRLF */
901 c
->querybuf
= sdsempty();
902 /* Assume that if we saw a fat argument we'll see another one
904 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
,c
->bulklen
+2);
908 createStringObject(c
->querybuf
+pos
,c
->bulklen
);
917 if (pos
) c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
919 /* We're done when c->multibulk == 0 */
920 if (c
->multibulklen
== 0) return REDIS_OK
;
922 /* Still not read to process the command */
926 void processInputBuffer(redisClient
*c
) {
927 /* Keep processing while there is something in the input buffer */
928 while(sdslen(c
->querybuf
)) {
929 /* Immediately abort if the client is in the middle of something. */
930 if (c
->flags
& REDIS_BLOCKED
) return;
932 /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
933 * written to the client. Make sure to not let the reply grow after
934 * this flag has been set (i.e. don't process more commands). */
935 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
937 /* Determine request type when unknown. */
939 if (c
->querybuf
[0] == '*') {
940 c
->reqtype
= REDIS_REQ_MULTIBULK
;
942 c
->reqtype
= REDIS_REQ_INLINE
;
946 if (c
->reqtype
== REDIS_REQ_INLINE
) {
947 if (processInlineBuffer(c
) != REDIS_OK
) break;
948 } else if (c
->reqtype
== REDIS_REQ_MULTIBULK
) {
949 if (processMultibulkBuffer(c
) != REDIS_OK
) break;
951 redisPanic("Unknown request type");
954 /* Multibulk processing could see a <= 0 length. */
958 /* Only reset the client when the command was executed. */
959 if (processCommand(c
) == REDIS_OK
)
965 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
966 redisClient
*c
= (redisClient
*) privdata
;
972 server
.current_client
= c
;
973 readlen
= REDIS_IOBUF_LEN
;
974 /* If this is a multi bulk request, and we are processing a bulk reply
975 * that is large enough, try to maximize the probabilty that the query
976 * buffer contains excatly the SDS string representing the object, even
977 * at the risk of requring more read(2) calls. This way the function
978 * processMultiBulkBuffer() can avoid copying buffers to create the
979 * Redis Object representing the argument. */
980 if (c
->reqtype
== REDIS_REQ_MULTIBULK
&& c
->multibulklen
&& c
->bulklen
!= -1
981 && c
->bulklen
>= REDIS_MBULK_BIG_ARG
)
983 int remaining
= (unsigned)(c
->bulklen
+2)-sdslen(c
->querybuf
);
985 if (remaining
< readlen
) readlen
= remaining
;
988 qblen
= sdslen(c
->querybuf
);
989 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
, readlen
);
990 nread
= read(fd
, c
->querybuf
+qblen
, readlen
);
992 if (errno
== EAGAIN
) {
995 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
999 } else if (nread
== 0) {
1000 redisLog(REDIS_VERBOSE
, "Client closed connection");
1005 sdsIncrLen(c
->querybuf
,nread
);
1006 c
->lastinteraction
= time(NULL
);
1008 server
.current_client
= NULL
;
1011 if (sdslen(c
->querybuf
) > server
.client_max_querybuf_len
) {
1012 sds ci
= getClientInfoString(c
), bytes
= sdsempty();
1014 bytes
= sdscatrepr(bytes
,c
->querybuf
,64);
1015 redisLog(REDIS_WARNING
,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci
, bytes
);
1021 processInputBuffer(c
);
1022 server
.current_client
= NULL
;
1025 void getClientsMaxBuffers(unsigned long *longest_output_list
,
1026 unsigned long *biggest_input_buffer
) {
1030 unsigned long lol
= 0, bib
= 0;
1032 listRewind(server
.clients
,&li
);
1033 while ((ln
= listNext(&li
)) != NULL
) {
1034 c
= listNodeValue(ln
);
1036 if (listLength(c
->reply
) > lol
) lol
= listLength(c
->reply
);
1037 if (sdslen(c
->querybuf
) > bib
) bib
= sdslen(c
->querybuf
);
1039 *longest_output_list
= lol
;
1040 *biggest_input_buffer
= bib
;
1043 /* Turn a Redis client into an sds string representing its state. */
1044 sds
getClientInfoString(redisClient
*client
) {
1045 char ip
[32], flags
[16], events
[3], *p
;
1047 time_t now
= time(NULL
);
1050 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) {
1056 if (client
->flags
& REDIS_SLAVE
) {
1057 if (client
->flags
& REDIS_MONITOR
)
1062 if (client
->flags
& REDIS_MASTER
) *p
++ = 'M';
1063 if (client
->flags
& REDIS_MULTI
) *p
++ = 'x';
1064 if (client
->flags
& REDIS_BLOCKED
) *p
++ = 'b';
1065 if (client
->flags
& REDIS_DIRTY_CAS
) *p
++ = 'd';
1066 if (client
->flags
& REDIS_CLOSE_AFTER_REPLY
) *p
++ = 'c';
1067 if (client
->flags
& REDIS_UNBLOCKED
) *p
++ = 'u';
1068 if (client
->flags
& REDIS_CLOSE_ASAP
) *p
++ = 'A';
1069 if (p
== flags
) *p
++ = 'N';
1072 emask
= client
->fd
== -1 ? 0 : aeGetFileEvents(server
.el
,client
->fd
);
1074 if (emask
& AE_READABLE
) *p
++ = 'r';
1075 if (emask
& AE_WRITABLE
) *p
++ = 'w';
1077 return sdscatprintf(sdsempty(),
1078 "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",
1080 (long)(now
- client
->lastinteraction
),
1083 (int) dictSize(client
->pubsub_channels
),
1084 (int) listLength(client
->pubsub_patterns
),
1085 (unsigned long) sdslen(client
->querybuf
),
1086 (unsigned long) client
->bufpos
,
1087 (unsigned long) listLength(client
->reply
),
1088 getClientOutputBufferMemoryUsage(client
),
1090 client
->lastcmd
? client
->lastcmd
->name
: "NULL");
1093 sds
getAllClientsInfoString(void) {
1096 redisClient
*client
;
1099 listRewind(server
.clients
,&li
);
1100 while ((ln
= listNext(&li
)) != NULL
) {
1103 client
= listNodeValue(ln
);
1104 cs
= getClientInfoString(client
);
1105 o
= sdscatsds(o
,cs
);
1107 o
= sdscatlen(o
,"\n",1);
1112 void clientCommand(redisClient
*c
) {
1115 redisClient
*client
;
1117 if (!strcasecmp(c
->argv
[1]->ptr
,"list") && c
->argc
== 2) {
1118 sds o
= getAllClientsInfoString();
1119 addReplyBulkCBuffer(c
,o
,sdslen(o
));
1121 } else if (!strcasecmp(c
->argv
[1]->ptr
,"kill") && c
->argc
== 3) {
1122 listRewind(server
.clients
,&li
);
1123 while ((ln
= listNext(&li
)) != NULL
) {
1124 char ip
[32], addr
[64];
1127 client
= listNodeValue(ln
);
1128 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue;
1129 snprintf(addr
,sizeof(addr
),"%s:%d",ip
,port
);
1130 if (strcmp(addr
,c
->argv
[2]->ptr
) == 0) {
1131 addReply(c
,shared
.ok
);
1133 client
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1140 addReplyError(c
,"No such client");
1142 addReplyError(c
, "Syntax error, try CLIENT (LIST | KILL ip:port)");
1146 /* Rewrite the command vector of the client. All the new objects ref count
1147 * is incremented. The old command vector is freed, and the old objects
1148 * ref count is decremented. */
1149 void rewriteClientCommandVector(redisClient
*c
, int argc
, ...) {
1152 robj
**argv
; /* The new argument vector */
1154 argv
= zmalloc(sizeof(robj
*)*argc
);
1156 for (j
= 0; j
< argc
; j
++) {
1159 a
= va_arg(ap
, robj
*);
1163 /* We free the objects in the original vector at the end, so we are
1164 * sure that if the same objects are reused in the new vector the
1165 * refcount gets incremented before it gets decremented. */
1166 for (j
= 0; j
< c
->argc
; j
++) decrRefCount(c
->argv
[j
]);
1168 /* Replace argv and argc with our new versions. */
1171 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1172 redisAssertWithInfo(c
,NULL
,c
->cmd
!= NULL
);
1176 /* Rewrite a single item in the command vector.
1177 * The new val ref count is incremented, and the old decremented. */
1178 void rewriteClientCommandArgument(redisClient
*c
, int i
, robj
*newval
) {
1181 redisAssertWithInfo(c
,NULL
,i
< c
->argc
);
1182 oldval
= c
->argv
[i
];
1183 c
->argv
[i
] = newval
;
1184 incrRefCount(newval
);
1185 decrRefCount(oldval
);
1187 /* If this is the command name make sure to fix c->cmd. */
1189 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1190 redisAssertWithInfo(c
,NULL
,c
->cmd
!= NULL
);
1194 /* This function returns the number of bytes that Redis is virtually
1195 * using to store the reply still not read by the client.
1196 * It is "virtual" since the reply output list may contain objects that
1197 * are shared and are not really using additional memory.
1199 * The function returns the total sum of the length of all the objects
1200 * stored in the output list, plus the memory used to allocate every
1201 * list node. The static reply buffer is not taken into account since it
1202 * is allocated anyway.
1204 * Note: this function is very fast so can be called as many time as
1205 * the caller wishes. The main usage of this function currently is
1206 * enforcing the client output length limits. */
1207 unsigned long getClientOutputBufferMemoryUsage(redisClient
*c
) {
1208 unsigned long list_item_size
= sizeof(listNode
);
1210 return c
->reply_bytes
+ (list_item_size
*listLength(c
->reply
));
1213 /* Get the class of a client, used in order to envorce limits to different
1214 * classes of clients.
1216 * The function will return one of the following:
1217 * REDIS_CLIENT_LIMIT_CLASS_NORMAL -> Normal client
1218 * REDIS_CLIENT_LIMIT_CLASS_SLAVE -> Slave or client executing MONITOR command
1219 * REDIS_CLIENT_LIMIT_CLASS_PUBSUB -> Client subscribed to Pub/Sub channels
1221 int getClientLimitClass(redisClient
*c
) {
1222 if (c
->flags
& REDIS_SLAVE
) return REDIS_CLIENT_LIMIT_CLASS_SLAVE
;
1223 if (dictSize(c
->pubsub_channels
) || listLength(c
->pubsub_patterns
))
1224 return REDIS_CLIENT_LIMIT_CLASS_PUBSUB
;
1225 return REDIS_CLIENT_LIMIT_CLASS_NORMAL
;
1228 int getClientLimitClassByName(char *name
) {
1229 if (!strcasecmp(name
,"normal")) return REDIS_CLIENT_LIMIT_CLASS_NORMAL
;
1230 else if (!strcasecmp(name
,"slave")) return REDIS_CLIENT_LIMIT_CLASS_SLAVE
;
1231 else if (!strcasecmp(name
,"pubsub")) return REDIS_CLIENT_LIMIT_CLASS_SLAVE
;
1235 char *getClientLimitClassName(int class) {
1237 case REDIS_CLIENT_LIMIT_CLASS_NORMAL
: return "normal";
1238 case REDIS_CLIENT_LIMIT_CLASS_SLAVE
: return "slave";
1239 case REDIS_CLIENT_LIMIT_CLASS_PUBSUB
: return "pubsub";
1240 default: return NULL
;
1244 /* The function checks if the client reached output buffer soft or hard
1245 * limit, and also update the state needed to check the soft limit as
1248 * Return value: non-zero if the client reached the soft or the hard limit.
1249 * Otherwise zero is returned. */
1250 int checkClientOutputBufferLimits(redisClient
*c
) {
1251 int soft
= 0, hard
= 0, class;
1252 unsigned long used_mem
= getClientOutputBufferMemoryUsage(c
);
1254 class = getClientLimitClass(c
);
1255 if (server
.client_obuf_limits
[class].hard_limit_bytes
&&
1256 used_mem
>= server
.client_obuf_limits
[class].hard_limit_bytes
)
1258 if (server
.client_obuf_limits
[class].soft_limit_bytes
&&
1259 used_mem
>= server
.client_obuf_limits
[class].soft_limit_bytes
)
1262 /* We need to check if the soft limit is reached continuously for the
1263 * specified amount of seconds. */
1265 if (c
->obuf_soft_limit_reached_time
== 0) {
1266 c
->obuf_soft_limit_reached_time
= server
.unixtime
;
1267 soft
= 0; /* First time we see the soft limit reached */
1269 time_t elapsed
= server
.unixtime
- c
->obuf_soft_limit_reached_time
;
1272 server
.client_obuf_limits
[class].soft_limit_seconds
) {
1273 soft
= 0; /* The client still did not reached the max number of
1274 seconds for the soft limit to be considered
1279 c
->obuf_soft_limit_reached_time
= 0;
1281 return soft
|| hard
;
1284 /* Asynchronously close a client if soft or hard limit is reached on the
1285 * output buffer size. The caller can check if the client will be closed
1286 * checking if the client REDIS_CLOSE_ASAP flag is set.
1288 * Note: we need to close the client asynchronously because this function is
1289 * called from contexts where the client can't be freed safely, i.e. from the
1290 * lower level functions pushing data inside the client output buffers. */
1291 void asyncCloseClientOnOutputBufferLimitReached(redisClient
*c
) {
1292 if (c
->flags
& REDIS_CLOSE_ASAP
) return;
1293 if (checkClientOutputBufferLimits(c
)) {
1294 sds client
= getClientInfoString(c
);
1297 redisLog(REDIS_WARNING
,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client
);