4 void *dupClientReplyValue(void *o
) {
5 incrRefCount((robj
*)o
);
9 int listMatchObjects(void *a
, void *b
) {
10 return equalStringObjects(a
,b
);
13 redisClient
*createClient(int fd
) {
16 /* Allocate more space to hold a static write buffer. */
17 c
= zmalloc(sizeof(redisClient
)+REDIS_REPLY_CHUNK_BYTES
);
18 c
->buflen
= REDIS_REPLY_CHUNK_BYTES
;
21 anetNonBlock(NULL
,fd
);
22 anetTcpNoDelay(NULL
,fd
);
26 c
->querybuf
= sdsempty();
35 c
->lastinteraction
= time(NULL
);
37 c
->replstate
= REDIS_REPL_NONE
;
38 c
->reply
= listCreate();
39 listSetFreeMethod(c
->reply
,decrRefCount
);
40 listSetDupMethod(c
->reply
,dupClientReplyValue
);
41 c
->blocking_keys
= NULL
;
42 c
->blocking_keys_num
= 0;
43 c
->io_keys
= listCreate();
44 c
->watched_keys
= listCreate();
45 listSetFreeMethod(c
->io_keys
,decrRefCount
);
46 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
47 c
->pubsub_patterns
= listCreate();
48 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
49 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
50 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
51 readQueryFromClient
, c
) == AE_ERR
) {
55 listAddNodeTail(server
.clients
,c
);
56 initClientMultiState(c
);
60 int _ensureFileEvent(redisClient
*c
) {
61 if (c
->fd
<= 0) return REDIS_ERR
;
62 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0 &&
63 (c
->replstate
== REDIS_REPL_NONE
||
64 c
->replstate
== REDIS_REPL_ONLINE
) &&
65 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
66 sendReplyToClient
, c
) == AE_ERR
) return REDIS_ERR
;
70 /* Create a duplicate of the last object in the reply list when
71 * it is not exclusively owned by the reply list. */
72 robj
*dupLastObjectIfNeeded(list
*reply
) {
75 redisAssert(listLength(reply
) > 0);
77 cur
= listNodeValue(ln
);
78 if (cur
->refcount
> 1) {
79 new = dupStringObject(cur
);
81 listNodeValue(ln
) = new;
83 return listNodeValue(ln
);
86 int _addReplyToBuffer(redisClient
*c
, char *s
, size_t len
) {
87 size_t available
= c
->buflen
-c
->bufpos
;
89 /* If there already are entries in the reply list, we cannot
90 * add anything more to the static buffer. */
91 if (listLength(c
->reply
) > 0) return REDIS_ERR
;
93 /* Check that the buffer has enough space available for this string. */
94 if (len
> available
) return REDIS_ERR
;
96 memcpy(c
->buf
+c
->bufpos
,s
,len
);
101 void _addReplyObjectToList(redisClient
*c
, robj
*o
) {
103 if (listLength(c
->reply
) == 0) {
105 listAddNodeTail(c
->reply
,o
);
107 tail
= listNodeValue(listLast(c
->reply
));
109 /* Append to this object when possible. */
110 if (tail
->ptr
!= NULL
&&
111 sdslen(tail
->ptr
)+sdslen(o
->ptr
) <= REDIS_REPLY_CHUNK_BYTES
)
113 tail
= dupLastObjectIfNeeded(c
->reply
);
114 tail
->ptr
= sdscatlen(tail
->ptr
,o
->ptr
,sdslen(o
->ptr
));
117 listAddNodeTail(c
->reply
,o
);
122 /* This method takes responsibility over the sds. When it is no longer
123 * needed it will be free'd, otherwise it ends up in a robj. */
124 void _addReplySdsToList(redisClient
*c
, sds s
) {
126 if (listLength(c
->reply
) == 0) {
127 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
129 tail
= listNodeValue(listLast(c
->reply
));
131 /* Append to this object when possible. */
132 if (tail
->ptr
!= NULL
&&
133 sdslen(tail
->ptr
)+sdslen(s
) <= REDIS_REPLY_CHUNK_BYTES
)
135 tail
= dupLastObjectIfNeeded(c
->reply
);
136 tail
->ptr
= sdscatlen(tail
->ptr
,s
,sdslen(s
));
139 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
144 void _addReplyStringToList(redisClient
*c
, char *s
, size_t len
) {
146 if (listLength(c
->reply
) == 0) {
147 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
149 tail
= listNodeValue(listLast(c
->reply
));
151 /* Append to this object when possible. */
152 if (tail
->ptr
!= NULL
&&
153 sdslen(tail
->ptr
)+len
<= REDIS_REPLY_CHUNK_BYTES
)
155 tail
= dupLastObjectIfNeeded(c
->reply
);
156 tail
->ptr
= sdscatlen(tail
->ptr
,s
,len
);
158 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
163 void addReply(redisClient
*c
, robj
*obj
) {
164 if (_ensureFileEvent(c
) != REDIS_OK
) return;
165 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
166 /* Returns a new object with refcount 1 */
167 obj
= dupStringObject(obj
);
169 /* This increments the refcount. */
170 obj
= getDecodedObject(obj
);
172 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
173 _addReplyObjectToList(c
,obj
);
177 void addReplySds(redisClient
*c
, sds s
) {
178 if (_ensureFileEvent(c
) != REDIS_OK
) {
179 /* The caller expects the sds to be free'd. */
183 if (_addReplyToBuffer(c
,s
,sdslen(s
)) == REDIS_OK
) {
186 /* This method free's the sds when it is no longer needed. */
187 _addReplySdsToList(c
,s
);
191 void addReplyString(redisClient
*c
, char *s
, size_t len
) {
192 if (_ensureFileEvent(c
) != REDIS_OK
) return;
193 if (_addReplyToBuffer(c
,s
,len
) != REDIS_OK
)
194 _addReplyStringToList(c
,s
,len
);
197 /* Adds an empty object to the reply list that will contain the multi bulk
198 * length, which is not known when this function is called. */
199 void *addDeferredMultiBulkLength(redisClient
*c
) {
200 if (_ensureFileEvent(c
) != REDIS_OK
) return NULL
;
201 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,NULL
));
202 return listLast(c
->reply
);
205 /* Populate the length object and try glueing it to the next chunk. */
206 void setDeferredMultiBulkLength(redisClient
*c
, void *node
, long length
) {
207 listNode
*ln
= (listNode
*)node
;
210 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
211 if (node
== NULL
) return;
213 len
= listNodeValue(ln
);
214 len
->ptr
= sdscatprintf(sdsempty(),"*%ld\r\n",length
);
215 if (ln
->next
!= NULL
) {
216 next
= listNodeValue(ln
->next
);
218 /* Only glue when the next node is an sds */
219 if (next
->ptr
!= NULL
) {
220 len
->ptr
= sdscat(len
->ptr
,next
->ptr
);
221 listDelNode(c
->reply
,ln
->next
);
226 void addReplyDouble(redisClient
*c
, double d
) {
227 char dbuf
[128], sbuf
[128];
229 dlen
= snprintf(dbuf
,sizeof(dbuf
),"%.17g",d
);
230 slen
= snprintf(sbuf
,sizeof(sbuf
),"$%d\r\n%s\r\n",dlen
,dbuf
);
231 addReplyString(c
,sbuf
,slen
);
234 void _addReplyLongLong(redisClient
*c
, long long ll
, char prefix
) {
238 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
241 addReplyString(c
,buf
,len
+3);
244 void addReplyLongLong(redisClient
*c
, long long ll
) {
245 _addReplyLongLong(c
,ll
,':');
248 void addReplyMultiBulkLen(redisClient
*c
, long length
) {
249 _addReplyLongLong(c
,length
,'*');
252 void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
255 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
256 len
= sdslen(obj
->ptr
);
258 long n
= (long)obj
->ptr
;
260 /* Compute how many bytes will take this integer as a radix 10 string */
266 while((n
= n
/10) != 0) {
270 _addReplyLongLong(c
,len
,'$');
273 void addReplyBulk(redisClient
*c
, robj
*obj
) {
274 addReplyBulkLen(c
,obj
);
276 addReply(c
,shared
.crlf
);
279 /* In the CONFIG command we need to add vanilla C string as bulk replies */
280 void addReplyBulkCString(redisClient
*c
, char *s
) {
282 addReply(c
,shared
.nullbulk
);
284 robj
*o
= createStringObject(s
,strlen(s
));
290 void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
296 REDIS_NOTUSED(privdata
);
298 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
300 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
303 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
304 if ((c
= createClient(cfd
)) == NULL
) {
305 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
306 close(cfd
); /* May be already closed, just ingore errors */
309 /* If maxclient directive is set and this is one client more... close the
310 * connection. Note that we create the client instead to check before
311 * for this condition, since now the socket is already set in nonblocking
312 * mode and we can send an error for free using the Kernel I/O */
313 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
314 char *err
= "-ERR max number of clients reached\r\n";
316 /* That's a best effort error message, don't check write errors */
317 if (write(c
->fd
,err
,strlen(err
)) == -1) {
318 /* Nothing to do, Just to avoid the warning... */
323 server
.stat_numconnections
++;
326 static void freeClientArgv(redisClient
*c
) {
329 for (j
= 0; j
< c
->argc
; j
++)
330 decrRefCount(c
->argv
[j
]);
331 for (j
= 0; j
< c
->mbargc
; j
++)
332 decrRefCount(c
->mbargv
[j
]);
337 void freeClient(redisClient
*c
) {
340 /* Note that if the client we are freeing is blocked into a blocking
341 * call, we have to set querybuf to NULL *before* to call
342 * unblockClientWaitingData() to avoid processInputBuffer() will get
343 * called. Also it is important to remove the file events after
344 * this, because this call adds the READABLE event. */
345 sdsfree(c
->querybuf
);
347 if (c
->flags
& REDIS_BLOCKED
)
348 unblockClientWaitingData(c
);
350 /* UNWATCH all the keys */
352 listRelease(c
->watched_keys
);
353 /* Unsubscribe from all the pubsub channels */
354 pubsubUnsubscribeAllChannels(c
,0);
355 pubsubUnsubscribeAllPatterns(c
,0);
356 dictRelease(c
->pubsub_channels
);
357 listRelease(c
->pubsub_patterns
);
358 /* Obvious cleanup */
359 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
360 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
361 listRelease(c
->reply
);
364 /* Remove from the list of clients */
365 ln
= listSearchKey(server
.clients
,c
);
366 redisAssert(ln
!= NULL
);
367 listDelNode(server
.clients
,ln
);
368 /* Remove from the list of clients waiting for swapped keys, or ready
369 * to be restarted, but not yet woken up again. */
370 if (c
->flags
& REDIS_IO_WAIT
) {
371 redisAssert(server
.vm_enabled
);
372 if (listLength(c
->io_keys
) == 0) {
373 ln
= listSearchKey(server
.io_ready_clients
,c
);
375 /* When this client is waiting to be woken up (REDIS_IO_WAIT),
376 * it should be present in the list io_ready_clients */
377 redisAssert(ln
!= NULL
);
378 listDelNode(server
.io_ready_clients
,ln
);
380 while (listLength(c
->io_keys
)) {
381 ln
= listFirst(c
->io_keys
);
382 dontWaitForSwappedKey(c
,ln
->value
);
385 server
.vm_blocked_clients
--;
387 listRelease(c
->io_keys
);
388 /* Master/slave cleanup.
389 * Case 1: we lost the connection with a slave. */
390 if (c
->flags
& REDIS_SLAVE
) {
391 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
393 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
394 ln
= listSearchKey(l
,c
);
395 redisAssert(ln
!= NULL
);
399 /* Case 2: we lost the connection with the master. */
400 if (c
->flags
& REDIS_MASTER
) {
401 server
.master
= NULL
;
402 server
.replstate
= REDIS_REPL_CONNECT
;
403 /* Since we lost the connection with the master, we should also
404 * close the connection with all our slaves if we have any, so
405 * when we'll resync with the master the other slaves will sync again
406 * with us as well. Note that also when the slave is not connected
407 * to the master it will keep refusing connections by other slaves. */
408 while (listLength(server
.slaves
)) {
409 ln
= listFirst(server
.slaves
);
410 freeClient((redisClient
*)ln
->value
);
416 freeClientMultiState(c
);
420 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
421 redisClient
*c
= privdata
;
422 int nwritten
= 0, totwritten
= 0, objlen
;
427 /* Use writev() if we have enough buffers to send */
428 if (!server
.glueoutputbuf
&&
429 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
430 !(c
->flags
& REDIS_MASTER
))
432 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
436 while(c
->bufpos
> 0 || listLength(c
->reply
)) {
438 if (c
->flags
& REDIS_MASTER
) {
439 /* Don't reply to a master */
440 nwritten
= c
->bufpos
- c
->sentlen
;
442 nwritten
= write(fd
,c
->buf
+c
->sentlen
,c
->bufpos
-c
->sentlen
);
443 if (nwritten
<= 0) break;
445 c
->sentlen
+= nwritten
;
446 totwritten
+= nwritten
;
448 /* If the buffer was sent, set bufpos to zero to continue with
449 * the remainder of the reply. */
450 if (c
->sentlen
== c
->bufpos
) {
455 o
= listNodeValue(listFirst(c
->reply
));
456 objlen
= sdslen(o
->ptr
);
459 listDelNode(c
->reply
,listFirst(c
->reply
));
463 if (c
->flags
& REDIS_MASTER
) {
464 /* Don't reply to a master */
465 nwritten
= objlen
- c
->sentlen
;
467 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
,objlen
-c
->sentlen
);
468 if (nwritten
<= 0) break;
470 c
->sentlen
+= nwritten
;
471 totwritten
+= nwritten
;
473 /* If we fully sent the object on head go to the next one */
474 if (c
->sentlen
== objlen
) {
475 listDelNode(c
->reply
,listFirst(c
->reply
));
479 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
480 * bytes, in a single threaded server it's a good idea to serve
481 * other clients as well, even if a very large request comes from
482 * super fast link that is always able to accept data (in real world
483 * scenario think about 'KEYS *' against the loopback interfae) */
484 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
486 if (nwritten
== -1) {
487 if (errno
== EAGAIN
) {
490 redisLog(REDIS_VERBOSE
,
491 "Error writing to client: %s", strerror(errno
));
496 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
497 if (listLength(c
->reply
) == 0) {
499 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
503 void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
505 redisClient
*c
= privdata
;
506 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
508 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
514 while (listLength(c
->reply
)) {
519 /* fill-in the iov[] array */
520 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
521 o
= listNodeValue(node
);
522 objlen
= sdslen(o
->ptr
);
524 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
527 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
528 break; /* no more iovecs */
530 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
531 iov
[ion
].iov_len
= objlen
- offset
;
532 willwrite
+= objlen
- offset
;
533 offset
= 0; /* just for the first item */
540 /* write all collected blocks at once */
541 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
542 if (errno
!= EAGAIN
) {
543 redisLog(REDIS_VERBOSE
,
544 "Error writing to client: %s", strerror(errno
));
551 totwritten
+= nwritten
;
554 /* remove written robjs from c->reply */
555 while (nwritten
&& listLength(c
->reply
)) {
556 o
= listNodeValue(listFirst(c
->reply
));
557 objlen
= sdslen(o
->ptr
);
559 if(nwritten
>= objlen
- offset
) {
560 listDelNode(c
->reply
, listFirst(c
->reply
));
561 nwritten
-= objlen
- offset
;
565 c
->sentlen
+= nwritten
;
573 c
->lastinteraction
= time(NULL
);
575 if (listLength(c
->reply
) == 0) {
577 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
581 /* resetClient prepare the client to process the next command */
582 void resetClient(redisClient
*c
) {
588 void closeTimedoutClients(void) {
591 time_t now
= time(NULL
);
594 listRewind(server
.clients
,&li
);
595 while ((ln
= listNext(&li
)) != NULL
) {
596 c
= listNodeValue(ln
);
597 if (server
.maxidletime
&&
598 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
599 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
600 !(c
->flags
& REDIS_BLOCKED
) && /* no timeout for BLPOP */
601 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
602 listLength(c
->pubsub_patterns
) == 0 &&
603 (now
- c
->lastinteraction
> server
.maxidletime
))
605 redisLog(REDIS_VERBOSE
,"Closing idle client");
607 } else if (c
->flags
& REDIS_BLOCKED
) {
608 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
609 addReply(c
,shared
.nullmultibulk
);
610 unblockClientWaitingData(c
);
616 void processInputBuffer(redisClient
*c
) {
618 /* Before to process the input buffer, make sure the client is not
619 * waitig for a blocking operation such as BLPOP. Note that the first
620 * iteration the client is never blocked, otherwise the processInputBuffer
621 * would not be called at all, but after the execution of the first commands
622 * in the input buffer the client may be blocked, and the "goto again"
623 * will try to reiterate. The following line will make it return asap. */
624 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
625 if (c
->bulklen
== -1) {
626 /* Read the first line of the query */
627 char *p
= strchr(c
->querybuf
,'\n');
635 c
->querybuf
= sdsempty();
636 querylen
= 1+(p
-(query
));
637 if (sdslen(query
) > querylen
) {
638 /* leave data after the first line of the query in the buffer */
639 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
641 *p
= '\0'; /* remove "\n" */
642 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
645 /* Now we can split the query in arguments */
646 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
649 if (c
->argv
) zfree(c
->argv
);
650 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
652 for (j
= 0; j
< argc
; j
++) {
653 if (sdslen(argv
[j
])) {
654 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
662 /* Execute the command. If the client is still valid
663 * after processCommand() return and there is something
664 * on the query buffer try to process the next command. */
665 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
667 /* Nothing to process, argc == 0. Just process the query
668 * buffer if it's not empty or return to the caller */
669 if (sdslen(c
->querybuf
)) goto again
;
672 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
673 redisLog(REDIS_VERBOSE
, "Client protocol error");
678 /* Bulk read handling. Note that if we are at this point
679 the client already sent a command terminated with a newline,
680 we are reading the bulk data that is actually the last
681 argument of the command. */
682 int qbl
= sdslen(c
->querybuf
);
684 if (c
->bulklen
<= qbl
) {
685 /* Copy everything but the final CRLF as final argument */
686 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
688 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
689 /* Process the command. If the client is still valid after
690 * the processing and there is more data in the buffer
691 * try to parse it. */
692 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
698 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
699 redisClient
*c
= (redisClient
*) privdata
;
700 char buf
[REDIS_IOBUF_LEN
];
705 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
707 if (errno
== EAGAIN
) {
710 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
714 } else if (nread
== 0) {
715 redisLog(REDIS_VERBOSE
, "Client closed connection");
720 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
721 c
->lastinteraction
= time(NULL
);
725 processInputBuffer(c
);