4 static void setProtocolError(redisClient
*c
, int pos
);
6 /* To evaluate the output buffer size of a client we need to get size of
7 * allocated objects, however we can't used zmalloc_size() directly on sds
8 * strings because of the trick they use to work (the header is before the
9 * returned pointer), so we use this helper function. */
10 size_t zmalloc_size_sds(sds s
) {
11 return zmalloc_size(s
-sizeof(struct sdshdr
));
14 void *dupClientReplyValue(void *o
) {
15 incrRefCount((robj
*)o
);
19 int listMatchObjects(void *a
, void *b
) {
20 return equalStringObjects(a
,b
);
23 redisClient
*createClient(int fd
) {
24 redisClient
*c
= zmalloc(sizeof(redisClient
));
26 /* passing -1 as fd it is possible to create a non connected client.
27 * This is useful since all the Redis commands needs to be executed
28 * in the context of a client. When commands are executed in other
29 * contexts (for instance a Lua script) we need a non connected client. */
31 anetNonBlock(NULL
,fd
);
32 anetTcpNoDelay(NULL
,fd
);
33 if (aeCreateFileEvent(server
.el
,fd
,AE_READABLE
,
34 readQueryFromClient
, c
) == AE_ERR
)
45 c
->querybuf
= sdsempty();
50 c
->cmd
= c
->lastcmd
= NULL
;
55 c
->ctime
= c
->lastinteraction
= server
.unixtime
;
57 c
->replstate
= REDIS_REPL_NONE
;
58 c
->slave_listening_port
= 0;
59 c
->reply
= listCreate();
61 c
->obuf_soft_limit_reached_time
= 0;
62 listSetFreeMethod(c
->reply
,decrRefCount
);
63 listSetDupMethod(c
->reply
,dupClientReplyValue
);
67 c
->bpop
.target
= NULL
;
68 c
->io_keys
= listCreate();
69 c
->watched_keys
= listCreate();
70 listSetFreeMethod(c
->io_keys
,decrRefCount
);
71 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
72 c
->pubsub_patterns
= listCreate();
73 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
74 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
75 if (fd
!= -1) listAddNodeTail(server
.clients
,c
);
76 initClientMultiState(c
);
80 /* This function is called every time we are going to transmit new data
81 * to the client. The behavior is the following:
83 * If the client should receive new data (normal clients will) the function
84 * returns REDIS_OK, and make sure to install the write handler in our event
85 * loop so that when the socket is writable new data gets written.
87 * If the client should not receive new data, because it is a fake client
88 * or a slave, or because the setup of the write handler failed, the function
91 * Typically gets called every time a reply is built, before adding more
92 * data to the clients output buffers. If the function returns REDIS_ERR no
93 * data should be appended to the output buffers. */
94 int prepareClientToWrite(redisClient
*c
) {
95 if (c
->flags
& REDIS_LUA_CLIENT
) return REDIS_OK
;
96 if (c
->fd
<= 0) return REDIS_ERR
; /* Fake client */
97 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0 &&
98 (c
->replstate
== REDIS_REPL_NONE
||
99 c
->replstate
== REDIS_REPL_ONLINE
) &&
100 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
101 sendReplyToClient
, c
) == AE_ERR
) return REDIS_ERR
;
105 /* Create a duplicate of the last object in the reply list when
106 * it is not exclusively owned by the reply list. */
107 robj
*dupLastObjectIfNeeded(list
*reply
) {
110 redisAssert(listLength(reply
) > 0);
111 ln
= listLast(reply
);
112 cur
= listNodeValue(ln
);
113 if (cur
->refcount
> 1) {
114 new = dupStringObject(cur
);
116 listNodeValue(ln
) = new;
118 return listNodeValue(ln
);
121 /* -----------------------------------------------------------------------------
122 * Low level functions to add more data to output buffers.
123 * -------------------------------------------------------------------------- */
125 int _addReplyToBuffer(redisClient
*c
, char *s
, size_t len
) {
126 size_t available
= sizeof(c
->buf
)-c
->bufpos
;
128 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return REDIS_OK
;
130 /* If there already are entries in the reply list, we cannot
131 * add anything more to the static buffer. */
132 if (listLength(c
->reply
) > 0) return REDIS_ERR
;
134 /* Check that the buffer has enough space available for this string. */
135 if (len
> available
) return REDIS_ERR
;
137 memcpy(c
->buf
+c
->bufpos
,s
,len
);
142 void _addReplyObjectToList(redisClient
*c
, robj
*o
) {
145 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
147 if (listLength(c
->reply
) == 0) {
149 listAddNodeTail(c
->reply
,o
);
150 c
->reply_bytes
+= zmalloc_size_sds(o
->ptr
);
152 tail
= listNodeValue(listLast(c
->reply
));
154 /* Append to this object when possible. */
155 if (tail
->ptr
!= NULL
&&
156 sdslen(tail
->ptr
)+sdslen(o
->ptr
) <= REDIS_REPLY_CHUNK_BYTES
)
158 c
->reply_bytes
-= zmalloc_size_sds(tail
->ptr
);
159 tail
= dupLastObjectIfNeeded(c
->reply
);
160 tail
->ptr
= sdscatlen(tail
->ptr
,o
->ptr
,sdslen(o
->ptr
));
161 c
->reply_bytes
+= zmalloc_size_sds(tail
->ptr
);
164 listAddNodeTail(c
->reply
,o
);
165 c
->reply_bytes
+= zmalloc_size_sds(o
->ptr
);
168 asyncCloseClientOnOutputBufferLimitReached(c
);
171 /* This method takes responsibility over the sds. When it is no longer
172 * needed it will be free'd, otherwise it ends up in a robj. */
173 void _addReplySdsToList(redisClient
*c
, sds s
) {
176 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) {
181 if (listLength(c
->reply
) == 0) {
182 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
183 c
->reply_bytes
+= zmalloc_size_sds(s
);
185 tail
= listNodeValue(listLast(c
->reply
));
187 /* Append to this object when possible. */
188 if (tail
->ptr
!= NULL
&&
189 sdslen(tail
->ptr
)+sdslen(s
) <= REDIS_REPLY_CHUNK_BYTES
)
191 c
->reply_bytes
-= zmalloc_size_sds(tail
->ptr
);
192 tail
= dupLastObjectIfNeeded(c
->reply
);
193 tail
->ptr
= sdscatlen(tail
->ptr
,s
,sdslen(s
));
194 c
->reply_bytes
+= zmalloc_size_sds(tail
->ptr
);
197 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
198 c
->reply_bytes
+= zmalloc_size_sds(s
);
201 asyncCloseClientOnOutputBufferLimitReached(c
);
204 void _addReplyStringToList(redisClient
*c
, char *s
, size_t len
) {
207 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
209 if (listLength(c
->reply
) == 0) {
210 robj
*o
= createStringObject(s
,len
);
212 listAddNodeTail(c
->reply
,o
);
213 c
->reply_bytes
+= zmalloc_size_sds(o
->ptr
);
215 tail
= listNodeValue(listLast(c
->reply
));
217 /* Append to this object when possible. */
218 if (tail
->ptr
!= NULL
&&
219 sdslen(tail
->ptr
)+len
<= REDIS_REPLY_CHUNK_BYTES
)
221 c
->reply_bytes
-= zmalloc_size_sds(tail
->ptr
);
222 tail
= dupLastObjectIfNeeded(c
->reply
);
223 tail
->ptr
= sdscatlen(tail
->ptr
,s
,len
);
224 c
->reply_bytes
+= zmalloc_size_sds(tail
->ptr
);
226 robj
*o
= createStringObject(s
,len
);
228 listAddNodeTail(c
->reply
,o
);
229 c
->reply_bytes
+= zmalloc_size_sds(o
->ptr
);
232 asyncCloseClientOnOutputBufferLimitReached(c
);
235 /* -----------------------------------------------------------------------------
236 * Higher level functions to queue data on the client output buffer.
237 * The following functions are the ones that commands implementations will call.
238 * -------------------------------------------------------------------------- */
240 void addReply(redisClient
*c
, robj
*obj
) {
241 if (prepareClientToWrite(c
) != REDIS_OK
) return;
243 /* This is an important place where we can avoid copy-on-write
244 * when there is a saving child running, avoiding touching the
245 * refcount field of the object if it's not needed.
247 * If the encoding is RAW and there is room in the static buffer
248 * we'll be able to send the object to the client without
249 * messing with its page. */
250 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
251 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
252 _addReplyObjectToList(c
,obj
);
253 } else if (obj
->encoding
== REDIS_ENCODING_INT
) {
254 /* Optimization: if there is room in the static buffer for 32 bytes
255 * (more than the max chars a 64 bit integer can take as string) we
256 * avoid decoding the object and go for the lower level approach. */
257 if (listLength(c
->reply
) == 0 && (sizeof(c
->buf
) - c
->bufpos
) >= 32) {
261 len
= ll2string(buf
,sizeof(buf
),(long)obj
->ptr
);
262 if (_addReplyToBuffer(c
,buf
,len
) == REDIS_OK
)
264 /* else... continue with the normal code path, but should never
265 * happen actually since we verified there is room. */
267 obj
= getDecodedObject(obj
);
268 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
269 _addReplyObjectToList(c
,obj
);
272 redisPanic("Wrong obj->encoding in addReply()");
276 void addReplySds(redisClient
*c
, sds s
) {
277 if (prepareClientToWrite(c
) != REDIS_OK
) {
278 /* The caller expects the sds to be free'd. */
282 if (_addReplyToBuffer(c
,s
,sdslen(s
)) == REDIS_OK
) {
285 /* This method free's the sds when it is no longer needed. */
286 _addReplySdsToList(c
,s
);
290 void addReplyString(redisClient
*c
, char *s
, size_t len
) {
291 if (prepareClientToWrite(c
) != REDIS_OK
) return;
292 if (_addReplyToBuffer(c
,s
,len
) != REDIS_OK
)
293 _addReplyStringToList(c
,s
,len
);
296 void addReplyErrorLength(redisClient
*c
, char *s
, size_t len
) {
297 addReplyString(c
,"-ERR ",5);
298 addReplyString(c
,s
,len
);
299 addReplyString(c
,"\r\n",2);
302 void addReplyError(redisClient
*c
, char *err
) {
303 addReplyErrorLength(c
,err
,strlen(err
));
306 void addReplyErrorFormat(redisClient
*c
, const char *fmt
, ...) {
310 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
312 /* Make sure there are no newlines in the string, otherwise invalid protocol
315 for (j
= 0; j
< l
; j
++) {
316 if (s
[j
] == '\r' || s
[j
] == '\n') s
[j
] = ' ';
318 addReplyErrorLength(c
,s
,sdslen(s
));
322 void addReplyStatusLength(redisClient
*c
, char *s
, size_t len
) {
323 addReplyString(c
,"+",1);
324 addReplyString(c
,s
,len
);
325 addReplyString(c
,"\r\n",2);
328 void addReplyStatus(redisClient
*c
, char *status
) {
329 addReplyStatusLength(c
,status
,strlen(status
));
332 void addReplyStatusFormat(redisClient
*c
, const char *fmt
, ...) {
335 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
337 addReplyStatusLength(c
,s
,sdslen(s
));
341 /* Adds an empty object to the reply list that will contain the multi bulk
342 * length, which is not known when this function is called. */
343 void *addDeferredMultiBulkLength(redisClient
*c
) {
344 /* Note that we install the write event here even if the object is not
345 * ready to be sent, since we are sure that before returning to the
346 * event loop setDeferredMultiBulkLength() will be called. */
347 if (prepareClientToWrite(c
) != REDIS_OK
) return NULL
;
348 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,NULL
));
349 return listLast(c
->reply
);
352 /* Populate the length object and try glueing it to the next chunk. */
353 void setDeferredMultiBulkLength(redisClient
*c
, void *node
, long length
) {
354 listNode
*ln
= (listNode
*)node
;
357 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
358 if (node
== NULL
) return;
360 len
= listNodeValue(ln
);
361 len
->ptr
= sdscatprintf(sdsempty(),"*%ld\r\n",length
);
362 c
->reply_bytes
+= zmalloc_size_sds(len
->ptr
);
363 if (ln
->next
!= NULL
) {
364 next
= listNodeValue(ln
->next
);
366 /* Only glue when the next node is non-NULL (an sds in this case) */
367 if (next
->ptr
!= NULL
) {
368 c
->reply_bytes
-= zmalloc_size_sds(len
->ptr
);
369 c
->reply_bytes
-= zmalloc_size_sds(next
->ptr
);
370 len
->ptr
= sdscatlen(len
->ptr
,next
->ptr
,sdslen(next
->ptr
));
371 c
->reply_bytes
+= zmalloc_size_sds(len
->ptr
);
372 listDelNode(c
->reply
,ln
->next
);
375 asyncCloseClientOnOutputBufferLimitReached(c
);
378 /* Add a duble as a bulk reply */
379 void addReplyDouble(redisClient
*c
, double d
) {
380 char dbuf
[128], sbuf
[128];
382 dlen
= snprintf(dbuf
,sizeof(dbuf
),"%.17g",d
);
383 slen
= snprintf(sbuf
,sizeof(sbuf
),"$%d\r\n%s\r\n",dlen
,dbuf
);
384 addReplyString(c
,sbuf
,slen
);
387 /* Add a long long as integer reply or bulk len / multi bulk count.
388 * Basically this is used to output <prefix><long long><crlf>. */
389 void addReplyLongLongWithPrefix(redisClient
*c
, long long ll
, char prefix
) {
393 /* Things like $3\r\n or *2\r\n are emitted very often by the protocol
394 * so we have a few shared objects to use if the integer is small
395 * like it is most of the times. */
396 if (prefix
== '*' && ll
< REDIS_SHARED_BULKHDR_LEN
) {
397 addReply(c
,shared
.mbulkhdr
[ll
]);
399 } else if (prefix
== '$' && ll
< REDIS_SHARED_BULKHDR_LEN
) {
400 addReply(c
,shared
.bulkhdr
[ll
]);
405 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
408 addReplyString(c
,buf
,len
+3);
411 void addReplyLongLong(redisClient
*c
, long long ll
) {
413 addReply(c
,shared
.czero
);
415 addReply(c
,shared
.cone
);
417 addReplyLongLongWithPrefix(c
,ll
,':');
420 void addReplyMultiBulkLen(redisClient
*c
, long length
) {
421 addReplyLongLongWithPrefix(c
,length
,'*');
424 /* Create the length prefix of a bulk reply, example: $2234 */
425 void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
428 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
429 len
= sdslen(obj
->ptr
);
431 long n
= (long)obj
->ptr
;
433 /* Compute how many bytes will take this integer as a radix 10 string */
439 while((n
= n
/10) != 0) {
443 addReplyLongLongWithPrefix(c
,len
,'$');
446 /* Add a Redis Object as a bulk reply */
447 void addReplyBulk(redisClient
*c
, robj
*obj
) {
448 addReplyBulkLen(c
,obj
);
450 addReply(c
,shared
.crlf
);
453 /* Add a C buffer as bulk reply */
454 void addReplyBulkCBuffer(redisClient
*c
, void *p
, size_t len
) {
455 addReplyLongLongWithPrefix(c
,len
,'$');
456 addReplyString(c
,p
,len
);
457 addReply(c
,shared
.crlf
);
460 /* Add a C nul term string as bulk reply */
461 void addReplyBulkCString(redisClient
*c
, char *s
) {
463 addReply(c
,shared
.nullbulk
);
465 addReplyBulkCBuffer(c
,s
,strlen(s
));
469 /* Add a long long as a bulk reply */
470 void addReplyBulkLongLong(redisClient
*c
, long long ll
) {
474 len
= ll2string(buf
,64,ll
);
475 addReplyBulkCBuffer(c
,buf
,len
);
478 /* Copy 'src' client output buffers into 'dst' client output buffers.
479 * The function takes care of freeing the old output buffers of the
480 * destination client. */
481 void copyClientOutputBuffer(redisClient
*dst
, redisClient
*src
) {
482 listRelease(dst
->reply
);
483 dst
->reply
= listDup(src
->reply
);
484 memcpy(dst
->buf
,src
->buf
,src
->bufpos
);
485 dst
->bufpos
= src
->bufpos
;
486 dst
->reply_bytes
= src
->reply_bytes
;
489 static void acceptCommonHandler(int fd
) {
491 if ((c
= createClient(fd
)) == NULL
) {
492 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
493 close(fd
); /* May be already closed, just ingore errors */
496 /* If maxclient directive is set and this is one client more... close the
497 * connection. Note that we create the client instead to check before
498 * for this condition, since now the socket is already set in nonblocking
499 * mode and we can send an error for free using the Kernel I/O */
500 if (listLength(server
.clients
) > server
.maxclients
) {
501 char *err
= "-ERR max number of clients reached\r\n";
503 /* That's a best effort error message, don't check write errors */
504 if (write(c
->fd
,err
,strlen(err
)) == -1) {
505 /* Nothing to do, Just to avoid the warning... */
507 server
.stat_rejected_conn
++;
511 server
.stat_numconnections
++;
514 void acceptTcpHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
519 REDIS_NOTUSED(privdata
);
521 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
523 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
526 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
527 acceptCommonHandler(cfd
);
530 void acceptUnixHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
534 REDIS_NOTUSED(privdata
);
536 cfd
= anetUnixAccept(server
.neterr
, fd
);
538 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
541 redisLog(REDIS_VERBOSE
,"Accepted connection to %s", server
.unixsocket
);
542 acceptCommonHandler(cfd
);
546 static void freeClientArgv(redisClient
*c
) {
548 for (j
= 0; j
< c
->argc
; j
++)
549 decrRefCount(c
->argv
[j
]);
554 /* Close all the slaves connections. This is useful in chained replication
555 * when we resync with our own master and want to force all our slaves to
556 * resync with us as well. */
557 void disconnectSlaves(void) {
558 while (listLength(server
.slaves
)) {
559 listNode
*ln
= listFirst(server
.slaves
);
560 freeClient((redisClient
*)ln
->value
);
564 void freeClient(redisClient
*c
) {
567 /* If this is marked as current client unset it */
568 if (server
.current_client
== c
) server
.current_client
= NULL
;
570 /* Note that if the client we are freeing is blocked into a blocking
571 * call, we have to set querybuf to NULL *before* to call
572 * unblockClientWaitingData() to avoid processInputBuffer() will get
573 * called. Also it is important to remove the file events after
574 * this, because this call adds the READABLE event. */
575 sdsfree(c
->querybuf
);
577 if (c
->flags
& REDIS_BLOCKED
)
578 unblockClientWaitingData(c
);
580 /* UNWATCH all the keys */
582 listRelease(c
->watched_keys
);
583 /* Unsubscribe from all the pubsub channels */
584 pubsubUnsubscribeAllChannels(c
,0);
585 pubsubUnsubscribeAllPatterns(c
,0);
586 dictRelease(c
->pubsub_channels
);
587 listRelease(c
->pubsub_patterns
);
588 /* Obvious cleanup */
589 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
590 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
591 listRelease(c
->reply
);
594 /* Remove from the list of clients */
595 ln
= listSearchKey(server
.clients
,c
);
596 redisAssert(ln
!= NULL
);
597 listDelNode(server
.clients
,ln
);
598 /* When client was just unblocked because of a blocking operation,
599 * remove it from the list with unblocked clients. */
600 if (c
->flags
& REDIS_UNBLOCKED
) {
601 ln
= listSearchKey(server
.unblocked_clients
,c
);
602 redisAssert(ln
!= NULL
);
603 listDelNode(server
.unblocked_clients
,ln
);
605 listRelease(c
->io_keys
);
606 /* Master/slave cleanup.
607 * Case 1: we lost the connection with a slave. */
608 if (c
->flags
& REDIS_SLAVE
) {
609 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
611 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
612 ln
= listSearchKey(l
,c
);
613 redisAssert(ln
!= NULL
);
617 /* Case 2: we lost the connection with the master. */
618 if (c
->flags
& REDIS_MASTER
) {
619 server
.master
= NULL
;
620 server
.repl_state
= REDIS_REPL_CONNECT
;
621 server
.repl_down_since
= server
.unixtime
;
622 /* We lost connection with our master, force our slaves to resync
623 * with us as well to load the new data set.
625 * If server.masterhost is NULL the user called SLAVEOF NO ONE so
626 * slave resync is not needed. */
627 if (server
.masterhost
!= NULL
) disconnectSlaves();
630 /* If this client was scheduled for async freeing we need to remove it
632 if (c
->flags
& REDIS_CLOSE_ASAP
) {
633 ln
= listSearchKey(server
.clients_to_close
,c
);
634 redisAssert(ln
!= NULL
);
635 listDelNode(server
.clients_to_close
,ln
);
640 freeClientMultiState(c
);
644 /* Schedule a client to free it at a safe time in the serverCron() function.
645 * This function is useful when we need to terminate a client but we are in
646 * a context where calling freeClient() is not possible, because the client
647 * should be valid for the continuation of the flow of the program. */
648 void freeClientAsync(redisClient
*c
) {
649 if (c
->flags
& REDIS_CLOSE_ASAP
) return;
650 c
->flags
|= REDIS_CLOSE_ASAP
;
651 listAddNodeTail(server
.clients_to_close
,c
);
654 void freeClientsInAsyncFreeQueue(void) {
655 while (listLength(server
.clients_to_close
)) {
656 listNode
*ln
= listFirst(server
.clients_to_close
);
657 redisClient
*c
= listNodeValue(ln
);
659 c
->flags
&= ~REDIS_CLOSE_ASAP
;
661 listDelNode(server
.clients_to_close
,ln
);
665 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
666 redisClient
*c
= privdata
;
667 int nwritten
= 0, totwritten
= 0, objlen
;
673 while(c
->bufpos
> 0 || listLength(c
->reply
)) {
675 if (c
->flags
& REDIS_MASTER
) {
676 /* Don't reply to a master */
677 nwritten
= c
->bufpos
- c
->sentlen
;
679 nwritten
= write(fd
,c
->buf
+c
->sentlen
,c
->bufpos
-c
->sentlen
);
680 if (nwritten
<= 0) break;
682 c
->sentlen
+= nwritten
;
683 totwritten
+= nwritten
;
685 /* If the buffer was sent, set bufpos to zero to continue with
686 * the remainder of the reply. */
687 if (c
->sentlen
== c
->bufpos
) {
692 o
= listNodeValue(listFirst(c
->reply
));
693 objlen
= sdslen(o
->ptr
);
694 objmem
= zmalloc_size_sds(o
->ptr
);
697 listDelNode(c
->reply
,listFirst(c
->reply
));
701 if (c
->flags
& REDIS_MASTER
) {
702 /* Don't reply to a master */
703 nwritten
= objlen
- c
->sentlen
;
705 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
,objlen
-c
->sentlen
);
706 if (nwritten
<= 0) break;
708 c
->sentlen
+= nwritten
;
709 totwritten
+= nwritten
;
711 /* If we fully sent the object on head go to the next one */
712 if (c
->sentlen
== objlen
) {
713 listDelNode(c
->reply
,listFirst(c
->reply
));
715 c
->reply_bytes
-= objmem
;
718 /* Note that we avoid to send more than REDIS_MAX_WRITE_PER_EVENT
719 * bytes, in a single threaded server it's a good idea to serve
720 * other clients as well, even if a very large request comes from
721 * super fast link that is always able to accept data (in real world
722 * scenario think about 'KEYS *' against the loopback interface).
724 * However if we are over the maxmemory limit we ignore that and
725 * just deliver as much data as it is possible to deliver. */
726 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
&&
727 (server
.maxmemory
== 0 ||
728 zmalloc_used_memory() < server
.maxmemory
)) break;
730 if (nwritten
== -1) {
731 if (errno
== EAGAIN
) {
734 redisLog(REDIS_VERBOSE
,
735 "Error writing to client: %s", strerror(errno
));
740 if (totwritten
> 0) c
->lastinteraction
= server
.unixtime
;
741 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0) {
743 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
745 /* Close connection after entire reply has been sent. */
746 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) freeClient(c
);
750 /* resetClient prepare the client to process the next command */
751 void resetClient(redisClient
*c
) {
756 /* We clear the ASKING flag as well if we are not inside a MULTI. */
757 if (!(c
->flags
& REDIS_MULTI
)) c
->flags
&= (~REDIS_ASKING
);
760 int processInlineBuffer(redisClient
*c
) {
761 char *newline
= strstr(c
->querybuf
,"\r\n");
766 /* Nothing to do without a \r\n */
767 if (newline
== NULL
) {
768 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
769 addReplyError(c
,"Protocol error: too big inline request");
770 setProtocolError(c
,0);
775 /* Split the input buffer up to the \r\n */
776 querylen
= newline
-(c
->querybuf
);
777 argv
= sdssplitlen(c
->querybuf
,querylen
," ",1,&argc
);
779 /* Leave data after the first line of the query in the buffer */
780 c
->querybuf
= sdsrange(c
->querybuf
,querylen
+2,-1);
782 /* Setup argv array on client structure */
783 if (c
->argv
) zfree(c
->argv
);
784 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
786 /* Create redis objects for all arguments. */
787 for (c
->argc
= 0, j
= 0; j
< argc
; j
++) {
788 if (sdslen(argv
[j
])) {
789 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
799 /* Helper function. Trims query buffer to make the function that processes
800 * multi bulk requests idempotent. */
801 static void setProtocolError(redisClient
*c
, int pos
) {
802 if (server
.verbosity
>= REDIS_VERBOSE
) {
803 sds client
= getClientInfoString(c
);
804 redisLog(REDIS_VERBOSE
,
805 "Protocol error from client: %s", client
);
808 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
809 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
812 int processMultibulkBuffer(redisClient
*c
) {
813 char *newline
= NULL
;
817 if (c
->multibulklen
== 0) {
818 /* The client should have been reset */
819 redisAssertWithInfo(c
,NULL
,c
->argc
== 0);
821 /* Multi bulk length cannot be read without a \r\n */
822 newline
= strchr(c
->querybuf
,'\r');
823 if (newline
== NULL
) {
824 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
825 addReplyError(c
,"Protocol error: too big mbulk count string");
826 setProtocolError(c
,0);
831 /* Buffer should also contain \n */
832 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
835 /* We know for sure there is a whole line since newline != NULL,
836 * so go ahead and find out the multi bulk length. */
837 redisAssertWithInfo(c
,NULL
,c
->querybuf
[0] == '*');
838 ok
= string2ll(c
->querybuf
+1,newline
-(c
->querybuf
+1),&ll
);
839 if (!ok
|| ll
> 1024*1024) {
840 addReplyError(c
,"Protocol error: invalid multibulk length");
841 setProtocolError(c
,pos
);
845 pos
= (newline
-c
->querybuf
)+2;
847 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
851 c
->multibulklen
= ll
;
853 /* Setup argv array on client structure */
854 if (c
->argv
) zfree(c
->argv
);
855 c
->argv
= zmalloc(sizeof(robj
*)*c
->multibulklen
);
858 redisAssertWithInfo(c
,NULL
,c
->multibulklen
> 0);
859 while(c
->multibulklen
) {
860 /* Read bulk length if unknown */
861 if (c
->bulklen
== -1) {
862 newline
= strchr(c
->querybuf
+pos
,'\r');
863 if (newline
== NULL
) {
864 if (sdslen(c
->querybuf
) > REDIS_INLINE_MAX_SIZE
) {
865 addReplyError(c
,"Protocol error: too big bulk count string");
866 setProtocolError(c
,0);
871 /* Buffer should also contain \n */
872 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
875 if (c
->querybuf
[pos
] != '$') {
876 addReplyErrorFormat(c
,
877 "Protocol error: expected '$', got '%c'",
879 setProtocolError(c
,pos
);
883 ok
= string2ll(c
->querybuf
+pos
+1,newline
-(c
->querybuf
+pos
+1),&ll
);
884 if (!ok
|| ll
< 0 || ll
> 512*1024*1024) {
885 addReplyError(c
,"Protocol error: invalid bulk length");
886 setProtocolError(c
,pos
);
890 pos
+= newline
-(c
->querybuf
+pos
)+2;
891 if (ll
>= REDIS_MBULK_BIG_ARG
) {
892 /* If we are going to read a large object from network
893 * try to make it likely that it will start at c->querybuf
894 * boundary so that we can optimized object creation
895 * avoiding a large copy of data. */
896 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
898 /* Hint the sds library about the amount of bytes this string is
899 * going to contain. */
900 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
,ll
+2);
905 /* Read bulk argument */
906 if (sdslen(c
->querybuf
)-pos
< (unsigned)(c
->bulklen
+2)) {
907 /* Not enough data (+2 == trailing \r\n) */
910 /* Optimization: if the buffer contanins JUST our bulk element
911 * instead of creating a new object by *copying* the sds we
912 * just use the current sds string. */
914 c
->bulklen
>= REDIS_MBULK_BIG_ARG
&&
915 (signed) sdslen(c
->querybuf
) == c
->bulklen
+2)
917 c
->argv
[c
->argc
++] = createObject(REDIS_STRING
,c
->querybuf
);
918 sdsIncrLen(c
->querybuf
,-2); /* remove CRLF */
919 c
->querybuf
= sdsempty();
920 /* Assume that if we saw a fat argument we'll see another one
922 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
,c
->bulklen
+2);
926 createStringObject(c
->querybuf
+pos
,c
->bulklen
);
935 if (pos
) c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
937 /* We're done when c->multibulk == 0 */
938 if (c
->multibulklen
== 0) return REDIS_OK
;
940 /* Still not read to process the command */
944 void processInputBuffer(redisClient
*c
) {
945 /* Keep processing while there is something in the input buffer */
946 while(sdslen(c
->querybuf
)) {
947 /* Immediately abort if the client is in the middle of something. */
948 if (c
->flags
& REDIS_BLOCKED
) return;
950 /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
951 * written to the client. Make sure to not let the reply grow after
952 * this flag has been set (i.e. don't process more commands). */
953 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
955 /* Determine request type when unknown. */
957 if (c
->querybuf
[0] == '*') {
958 c
->reqtype
= REDIS_REQ_MULTIBULK
;
960 c
->reqtype
= REDIS_REQ_INLINE
;
964 if (c
->reqtype
== REDIS_REQ_INLINE
) {
965 if (processInlineBuffer(c
) != REDIS_OK
) break;
966 } else if (c
->reqtype
== REDIS_REQ_MULTIBULK
) {
967 if (processMultibulkBuffer(c
) != REDIS_OK
) break;
969 redisPanic("Unknown request type");
972 /* Multibulk processing could see a <= 0 length. */
976 /* Only reset the client when the command was executed. */
977 if (processCommand(c
) == REDIS_OK
)
983 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
984 redisClient
*c
= (redisClient
*) privdata
;
990 server
.current_client
= c
;
991 readlen
= REDIS_IOBUF_LEN
;
992 /* If this is a multi bulk request, and we are processing a bulk reply
993 * that is large enough, try to maximize the probabilty that the query
994 * buffer contains excatly the SDS string representing the object, even
995 * at the risk of requring more read(2) calls. This way the function
996 * processMultiBulkBuffer() can avoid copying buffers to create the
997 * Redis Object representing the argument. */
998 if (c
->reqtype
== REDIS_REQ_MULTIBULK
&& c
->multibulklen
&& c
->bulklen
!= -1
999 && c
->bulklen
>= REDIS_MBULK_BIG_ARG
)
1001 int remaining
= (unsigned)(c
->bulklen
+2)-sdslen(c
->querybuf
);
1003 if (remaining
< readlen
) readlen
= remaining
;
1006 qblen
= sdslen(c
->querybuf
);
1007 if (c
->querybuf_peak
< qblen
) c
->querybuf_peak
= qblen
;
1008 c
->querybuf
= sdsMakeRoomFor(c
->querybuf
, readlen
);
1009 nread
= read(fd
, c
->querybuf
+qblen
, readlen
);
1011 if (errno
== EAGAIN
) {
1014 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
1018 } else if (nread
== 0) {
1019 redisLog(REDIS_VERBOSE
, "Client closed connection");
1024 sdsIncrLen(c
->querybuf
,nread
);
1025 c
->lastinteraction
= server
.unixtime
;
1027 server
.current_client
= NULL
;
1030 if (sdslen(c
->querybuf
) > server
.client_max_querybuf_len
) {
1031 sds ci
= getClientInfoString(c
), bytes
= sdsempty();
1033 bytes
= sdscatrepr(bytes
,c
->querybuf
,64);
1034 redisLog(REDIS_WARNING
,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci
, bytes
);
1040 processInputBuffer(c
);
1041 server
.current_client
= NULL
;
1044 void getClientsMaxBuffers(unsigned long *longest_output_list
,
1045 unsigned long *biggest_input_buffer
) {
1049 unsigned long lol
= 0, bib
= 0;
1051 listRewind(server
.clients
,&li
);
1052 while ((ln
= listNext(&li
)) != NULL
) {
1053 c
= listNodeValue(ln
);
1055 if (listLength(c
->reply
) > lol
) lol
= listLength(c
->reply
);
1056 if (sdslen(c
->querybuf
) > bib
) bib
= sdslen(c
->querybuf
);
1058 *longest_output_list
= lol
;
1059 *biggest_input_buffer
= bib
;
1062 /* Turn a Redis client into an sds string representing its state. */
1063 sds
getClientInfoString(redisClient
*client
) {
1064 char ip
[32], flags
[16], events
[3], *p
;
1068 anetPeerToString(client
->fd
,ip
,&port
);
1070 if (client
->flags
& REDIS_SLAVE
) {
1071 if (client
->flags
& REDIS_MONITOR
)
1076 if (client
->flags
& REDIS_MASTER
) *p
++ = 'M';
1077 if (client
->flags
& REDIS_MULTI
) *p
++ = 'x';
1078 if (client
->flags
& REDIS_BLOCKED
) *p
++ = 'b';
1079 if (client
->flags
& REDIS_DIRTY_CAS
) *p
++ = 'd';
1080 if (client
->flags
& REDIS_CLOSE_AFTER_REPLY
) *p
++ = 'c';
1081 if (client
->flags
& REDIS_UNBLOCKED
) *p
++ = 'u';
1082 if (client
->flags
& REDIS_CLOSE_ASAP
) *p
++ = 'A';
1083 if (p
== flags
) *p
++ = 'N';
1086 emask
= client
->fd
== -1 ? 0 : aeGetFileEvents(server
.el
,client
->fd
);
1088 if (emask
& AE_READABLE
) *p
++ = 'r';
1089 if (emask
& AE_WRITABLE
) *p
++ = 'w';
1091 return sdscatprintf(sdsempty(),
1092 "addr=%s:%d fd=%d age=%ld idle=%ld flags=%s db=%d sub=%d psub=%d multi=%d qbuf=%lu qbuf-free=%lu obl=%lu oll=%lu omem=%lu events=%s cmd=%s",
1094 (long)(server
.unixtime
- client
->ctime
),
1095 (long)(server
.unixtime
- client
->lastinteraction
),
1098 (int) dictSize(client
->pubsub_channels
),
1099 (int) listLength(client
->pubsub_patterns
),
1100 (client
->flags
& REDIS_MULTI
) ? client
->mstate
.count
: -1,
1101 (unsigned long) sdslen(client
->querybuf
),
1102 (unsigned long) sdsavail(client
->querybuf
),
1103 (unsigned long) client
->bufpos
,
1104 (unsigned long) listLength(client
->reply
),
1105 getClientOutputBufferMemoryUsage(client
),
1107 client
->lastcmd
? client
->lastcmd
->name
: "NULL");
1110 sds
getAllClientsInfoString(void) {
1113 redisClient
*client
;
1116 listRewind(server
.clients
,&li
);
1117 while ((ln
= listNext(&li
)) != NULL
) {
1120 client
= listNodeValue(ln
);
1121 cs
= getClientInfoString(client
);
1122 o
= sdscatsds(o
,cs
);
1124 o
= sdscatlen(o
,"\n",1);
1129 void clientCommand(redisClient
*c
) {
1132 redisClient
*client
;
1134 if (!strcasecmp(c
->argv
[1]->ptr
,"list") && c
->argc
== 2) {
1135 sds o
= getAllClientsInfoString();
1136 addReplyBulkCBuffer(c
,o
,sdslen(o
));
1138 } else if (!strcasecmp(c
->argv
[1]->ptr
,"kill") && c
->argc
== 3) {
1139 listRewind(server
.clients
,&li
);
1140 while ((ln
= listNext(&li
)) != NULL
) {
1141 char ip
[32], addr
[64];
1144 client
= listNodeValue(ln
);
1145 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue;
1146 snprintf(addr
,sizeof(addr
),"%s:%d",ip
,port
);
1147 if (strcmp(addr
,c
->argv
[2]->ptr
) == 0) {
1148 addReply(c
,shared
.ok
);
1150 client
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
1157 addReplyError(c
,"No such client");
1159 addReplyError(c
, "Syntax error, try CLIENT (LIST | KILL ip:port)");
1163 /* Rewrite the command vector of the client. All the new objects ref count
1164 * is incremented. The old command vector is freed, and the old objects
1165 * ref count is decremented. */
1166 void rewriteClientCommandVector(redisClient
*c
, int argc
, ...) {
1169 robj
**argv
; /* The new argument vector */
1171 argv
= zmalloc(sizeof(robj
*)*argc
);
1173 for (j
= 0; j
< argc
; j
++) {
1176 a
= va_arg(ap
, robj
*);
1180 /* We free the objects in the original vector at the end, so we are
1181 * sure that if the same objects are reused in the new vector the
1182 * refcount gets incremented before it gets decremented. */
1183 for (j
= 0; j
< c
->argc
; j
++) decrRefCount(c
->argv
[j
]);
1185 /* Replace argv and argc with our new versions. */
1188 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1189 redisAssertWithInfo(c
,NULL
,c
->cmd
!= NULL
);
1193 /* Rewrite a single item in the command vector.
1194 * The new val ref count is incremented, and the old decremented. */
1195 void rewriteClientCommandArgument(redisClient
*c
, int i
, robj
*newval
) {
1198 redisAssertWithInfo(c
,NULL
,i
< c
->argc
);
1199 oldval
= c
->argv
[i
];
1200 c
->argv
[i
] = newval
;
1201 incrRefCount(newval
);
1202 decrRefCount(oldval
);
1204 /* If this is the command name make sure to fix c->cmd. */
1206 c
->cmd
= lookupCommand(c
->argv
[0]->ptr
);
1207 redisAssertWithInfo(c
,NULL
,c
->cmd
!= NULL
);
1211 /* This function returns the number of bytes that Redis is virtually
1212 * using to store the reply still not read by the client.
1213 * It is "virtual" since the reply output list may contain objects that
1214 * are shared and are not really using additional memory.
1216 * The function returns the total sum of the length of all the objects
1217 * stored in the output list, plus the memory used to allocate every
1218 * list node. The static reply buffer is not taken into account since it
1219 * is allocated anyway.
1221 * Note: this function is very fast so can be called as many time as
1222 * the caller wishes. The main usage of this function currently is
1223 * enforcing the client output length limits. */
1224 unsigned long getClientOutputBufferMemoryUsage(redisClient
*c
) {
1225 unsigned long list_item_size
= sizeof(listNode
)+sizeof(robj
);
1227 return c
->reply_bytes
+ (list_item_size
*listLength(c
->reply
));
1230 /* Get the class of a client, used in order to envorce limits to different
1231 * classes of clients.
1233 * The function will return one of the following:
1234 * REDIS_CLIENT_LIMIT_CLASS_NORMAL -> Normal client
1235 * REDIS_CLIENT_LIMIT_CLASS_SLAVE -> Slave or client executing MONITOR command
1236 * REDIS_CLIENT_LIMIT_CLASS_PUBSUB -> Client subscribed to Pub/Sub channels
1238 int getClientLimitClass(redisClient
*c
) {
1239 if (c
->flags
& REDIS_SLAVE
) return REDIS_CLIENT_LIMIT_CLASS_SLAVE
;
1240 if (dictSize(c
->pubsub_channels
) || listLength(c
->pubsub_patterns
))
1241 return REDIS_CLIENT_LIMIT_CLASS_PUBSUB
;
1242 return REDIS_CLIENT_LIMIT_CLASS_NORMAL
;
1245 int getClientLimitClassByName(char *name
) {
1246 if (!strcasecmp(name
,"normal")) return REDIS_CLIENT_LIMIT_CLASS_NORMAL
;
1247 else if (!strcasecmp(name
,"slave")) return REDIS_CLIENT_LIMIT_CLASS_SLAVE
;
1248 else if (!strcasecmp(name
,"pubsub")) return REDIS_CLIENT_LIMIT_CLASS_PUBSUB
;
1252 char *getClientLimitClassName(int class) {
1254 case REDIS_CLIENT_LIMIT_CLASS_NORMAL
: return "normal";
1255 case REDIS_CLIENT_LIMIT_CLASS_SLAVE
: return "slave";
1256 case REDIS_CLIENT_LIMIT_CLASS_PUBSUB
: return "pubsub";
1257 default: return NULL
;
1261 /* The function checks if the client reached output buffer soft or hard
1262 * limit, and also update the state needed to check the soft limit as
1265 * Return value: non-zero if the client reached the soft or the hard limit.
1266 * Otherwise zero is returned. */
1267 int checkClientOutputBufferLimits(redisClient
*c
) {
1268 int soft
= 0, hard
= 0, class;
1269 unsigned long used_mem
= getClientOutputBufferMemoryUsage(c
);
1271 class = getClientLimitClass(c
);
1272 if (server
.client_obuf_limits
[class].hard_limit_bytes
&&
1273 used_mem
>= server
.client_obuf_limits
[class].hard_limit_bytes
)
1275 if (server
.client_obuf_limits
[class].soft_limit_bytes
&&
1276 used_mem
>= server
.client_obuf_limits
[class].soft_limit_bytes
)
1279 /* We need to check if the soft limit is reached continuously for the
1280 * specified amount of seconds. */
1282 if (c
->obuf_soft_limit_reached_time
== 0) {
1283 c
->obuf_soft_limit_reached_time
= server
.unixtime
;
1284 soft
= 0; /* First time we see the soft limit reached */
1286 time_t elapsed
= server
.unixtime
- c
->obuf_soft_limit_reached_time
;
1289 server
.client_obuf_limits
[class].soft_limit_seconds
) {
1290 soft
= 0; /* The client still did not reached the max number of
1291 seconds for the soft limit to be considered
1296 c
->obuf_soft_limit_reached_time
= 0;
1298 return soft
|| hard
;
1301 /* Asynchronously close a client if soft or hard limit is reached on the
1302 * output buffer size. The caller can check if the client will be closed
1303 * checking if the client REDIS_CLOSE_ASAP flag is set.
1305 * Note: we need to close the client asynchronously because this function is
1306 * called from contexts where the client can't be freed safely, i.e. from the
1307 * lower level functions pushing data inside the client output buffers. */
1308 void asyncCloseClientOnOutputBufferLimitReached(redisClient
*c
) {
1309 redisAssert(c
->reply_bytes
< ULONG_MAX
-(1024*64));
1310 if (c
->reply_bytes
== 0 || c
->flags
& REDIS_CLOSE_ASAP
) return;
1311 if (checkClientOutputBufferLimits(c
)) {
1312 sds client
= getClientInfoString(c
);
1315 redisLog(REDIS_WARNING
,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client
);
1320 /* Helper function used by freeMemoryIfNeeded() in order to flush slaves
1321 * output buffers without returning control to the event loop. */
1322 void flushSlavesOutputBuffers(void) {
1326 listRewind(server
.slaves
,&li
);
1327 while((ln
= listNext(&li
))) {
1328 redisClient
*slave
= listNodeValue(ln
);
1331 events
= aeGetFileEvents(server
.el
,slave
->fd
);
1332 if (events
& AE_WRITABLE
&&
1333 slave
->replstate
== REDIS_REPL_ONLINE
&&
1334 listLength(slave
->reply
))
1336 sendReplyToClient(server
.el
,slave
->fd
,slave
,0);