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
) {
14 redisClient
*c
= zmalloc(sizeof(redisClient
));
17 anetNonBlock(NULL
,fd
);
18 anetTcpNoDelay(NULL
,fd
);
19 if (aeCreateFileEvent(server
.el
,fd
,AE_READABLE
,
20 readQueryFromClient
, c
) == AE_ERR
)
29 c
->querybuf
= sdsempty();
37 c
->lastinteraction
= time(NULL
);
39 c
->replstate
= REDIS_REPL_NONE
;
40 c
->reply
= listCreate();
41 listSetFreeMethod(c
->reply
,decrRefCount
);
42 listSetDupMethod(c
->reply
,dupClientReplyValue
);
46 c
->bpop
.target
= NULL
;
47 c
->io_keys
= listCreate();
48 c
->watched_keys
= listCreate();
49 listSetFreeMethod(c
->io_keys
,decrRefCount
);
50 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
51 c
->pubsub_patterns
= listCreate();
52 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
53 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
54 listAddNodeTail(server
.clients
,c
);
55 initClientMultiState(c
);
59 /* Set the event loop to listen for write events on the client's socket.
60 * Typically gets called every time a reply is built. */
61 int _installWriteEvent(redisClient
*c
) {
62 if (c
->fd
<= 0) return REDIS_ERR
;
63 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0 &&
64 (c
->replstate
== REDIS_REPL_NONE
||
65 c
->replstate
== REDIS_REPL_ONLINE
) &&
66 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
67 sendReplyToClient
, c
) == AE_ERR
) return REDIS_ERR
;
71 /* Create a duplicate of the last object in the reply list when
72 * it is not exclusively owned by the reply list. */
73 robj
*dupLastObjectIfNeeded(list
*reply
) {
76 redisAssert(listLength(reply
) > 0);
78 cur
= listNodeValue(ln
);
79 if (cur
->refcount
> 1) {
80 new = dupStringObject(cur
);
82 listNodeValue(ln
) = new;
84 return listNodeValue(ln
);
87 /* -----------------------------------------------------------------------------
88 * Low level functions to add more data to output buffers.
89 * -------------------------------------------------------------------------- */
91 int _addReplyToBuffer(redisClient
*c
, char *s
, size_t len
) {
92 size_t available
= sizeof(c
->buf
)-c
->bufpos
;
94 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return REDIS_OK
;
96 /* If there already are entries in the reply list, we cannot
97 * add anything more to the static buffer. */
98 if (listLength(c
->reply
) > 0) return REDIS_ERR
;
100 /* Check that the buffer has enough space available for this string. */
101 if (len
> available
) return REDIS_ERR
;
103 memcpy(c
->buf
+c
->bufpos
,s
,len
);
108 void _addReplyObjectToList(redisClient
*c
, robj
*o
) {
111 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
113 if (listLength(c
->reply
) == 0) {
115 listAddNodeTail(c
->reply
,o
);
117 tail
= listNodeValue(listLast(c
->reply
));
119 /* Append to this object when possible. */
120 if (tail
->ptr
!= NULL
&&
121 sdslen(tail
->ptr
)+sdslen(o
->ptr
) <= REDIS_REPLY_CHUNK_BYTES
)
123 tail
= dupLastObjectIfNeeded(c
->reply
);
124 tail
->ptr
= sdscatlen(tail
->ptr
,o
->ptr
,sdslen(o
->ptr
));
127 listAddNodeTail(c
->reply
,o
);
132 /* This method takes responsibility over the sds. When it is no longer
133 * needed it will be free'd, otherwise it ends up in a robj. */
134 void _addReplySdsToList(redisClient
*c
, sds s
) {
137 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) {
142 if (listLength(c
->reply
) == 0) {
143 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
145 tail
= listNodeValue(listLast(c
->reply
));
147 /* Append to this object when possible. */
148 if (tail
->ptr
!= NULL
&&
149 sdslen(tail
->ptr
)+sdslen(s
) <= REDIS_REPLY_CHUNK_BYTES
)
151 tail
= dupLastObjectIfNeeded(c
->reply
);
152 tail
->ptr
= sdscatlen(tail
->ptr
,s
,sdslen(s
));
155 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
160 void _addReplyStringToList(redisClient
*c
, char *s
, size_t len
) {
163 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
165 if (listLength(c
->reply
) == 0) {
166 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
168 tail
= listNodeValue(listLast(c
->reply
));
170 /* Append to this object when possible. */
171 if (tail
->ptr
!= NULL
&&
172 sdslen(tail
->ptr
)+len
<= REDIS_REPLY_CHUNK_BYTES
)
174 tail
= dupLastObjectIfNeeded(c
->reply
);
175 tail
->ptr
= sdscatlen(tail
->ptr
,s
,len
);
177 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
182 /* -----------------------------------------------------------------------------
183 * Higher level functions to queue data on the client output buffer.
184 * The following functions are the ones that commands implementations will call.
185 * -------------------------------------------------------------------------- */
187 void addReply(redisClient
*c
, robj
*obj
) {
188 if (_installWriteEvent(c
) != REDIS_OK
) return;
190 /* This is an important place where we can avoid copy-on-write
191 * when there is a saving child running, avoiding touching the
192 * refcount field of the object if it's not needed.
194 * If the encoding is RAW and there is room in the static buffer
195 * we'll be able to send the object to the client without
196 * messing with its page. */
197 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
198 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
199 _addReplyObjectToList(c
,obj
);
201 /* FIXME: convert the long into string and use _addReplyToBuffer()
202 * instead of calling getDecodedObject. As this place in the
203 * code is too performance critical. */
204 obj
= getDecodedObject(obj
);
205 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
206 _addReplyObjectToList(c
,obj
);
211 void addReplySds(redisClient
*c
, sds s
) {
212 if (_installWriteEvent(c
) != REDIS_OK
) {
213 /* The caller expects the sds to be free'd. */
217 if (_addReplyToBuffer(c
,s
,sdslen(s
)) == REDIS_OK
) {
220 /* This method free's the sds when it is no longer needed. */
221 _addReplySdsToList(c
,s
);
225 void addReplyString(redisClient
*c
, char *s
, size_t len
) {
226 if (_installWriteEvent(c
) != REDIS_OK
) return;
227 if (_addReplyToBuffer(c
,s
,len
) != REDIS_OK
)
228 _addReplyStringToList(c
,s
,len
);
231 void _addReplyError(redisClient
*c
, char *s
, size_t len
) {
232 addReplyString(c
,"-ERR ",5);
233 addReplyString(c
,s
,len
);
234 addReplyString(c
,"\r\n",2);
237 void addReplyError(redisClient
*c
, char *err
) {
238 _addReplyError(c
,err
,strlen(err
));
241 void addReplyErrorFormat(redisClient
*c
, const char *fmt
, ...) {
244 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
246 _addReplyError(c
,s
,sdslen(s
));
250 void _addReplyStatus(redisClient
*c
, char *s
, size_t len
) {
251 addReplyString(c
,"+",1);
252 addReplyString(c
,s
,len
);
253 addReplyString(c
,"\r\n",2);
256 void addReplyStatus(redisClient
*c
, char *status
) {
257 _addReplyStatus(c
,status
,strlen(status
));
260 void addReplyStatusFormat(redisClient
*c
, const char *fmt
, ...) {
263 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
265 _addReplyStatus(c
,s
,sdslen(s
));
269 /* Adds an empty object to the reply list that will contain the multi bulk
270 * length, which is not known when this function is called. */
271 void *addDeferredMultiBulkLength(redisClient
*c
) {
272 /* Note that we install the write event here even if the object is not
273 * ready to be sent, since we are sure that before returning to the
274 * event loop setDeferredMultiBulkLength() will be called. */
275 if (_installWriteEvent(c
) != REDIS_OK
) return NULL
;
276 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,NULL
));
277 return listLast(c
->reply
);
280 /* Populate the length object and try glueing it to the next chunk. */
281 void setDeferredMultiBulkLength(redisClient
*c
, void *node
, long length
) {
282 listNode
*ln
= (listNode
*)node
;
285 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
286 if (node
== NULL
) return;
288 len
= listNodeValue(ln
);
289 len
->ptr
= sdscatprintf(sdsempty(),"*%ld\r\n",length
);
290 if (ln
->next
!= NULL
) {
291 next
= listNodeValue(ln
->next
);
293 /* Only glue when the next node is non-NULL (an sds in this case) */
294 if (next
->ptr
!= NULL
) {
295 len
->ptr
= sdscatlen(len
->ptr
,next
->ptr
,sdslen(next
->ptr
));
296 listDelNode(c
->reply
,ln
->next
);
301 /* Add a duble as a bulk reply */
302 void addReplyDouble(redisClient
*c
, double d
) {
303 char dbuf
[128], sbuf
[128];
305 dlen
= snprintf(dbuf
,sizeof(dbuf
),"%.17g",d
);
306 slen
= snprintf(sbuf
,sizeof(sbuf
),"$%d\r\n%s\r\n",dlen
,dbuf
);
307 addReplyString(c
,sbuf
,slen
);
310 /* Add a long long as integer reply or bulk len / multi bulk count.
311 * Basically this is used to output <prefix><long long><crlf>. */
312 void _addReplyLongLong(redisClient
*c
, long long ll
, char prefix
) {
316 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
319 addReplyString(c
,buf
,len
+3);
322 void addReplyLongLong(redisClient
*c
, long long ll
) {
324 addReply(c
,shared
.czero
);
326 addReply(c
,shared
.cone
);
328 _addReplyLongLong(c
,ll
,':');
331 void addReplyMultiBulkLen(redisClient
*c
, long length
) {
332 _addReplyLongLong(c
,length
,'*');
335 /* Create the length prefix of a bulk reply, example: $2234 */
336 void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
339 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
340 len
= sdslen(obj
->ptr
);
342 long n
= (long)obj
->ptr
;
344 /* Compute how many bytes will take this integer as a radix 10 string */
350 while((n
= n
/10) != 0) {
354 _addReplyLongLong(c
,len
,'$');
357 /* Add a Redis Object as a bulk reply */
358 void addReplyBulk(redisClient
*c
, robj
*obj
) {
359 addReplyBulkLen(c
,obj
);
361 addReply(c
,shared
.crlf
);
364 /* Add a C buffer as bulk reply */
365 void addReplyBulkCBuffer(redisClient
*c
, void *p
, size_t len
) {
366 _addReplyLongLong(c
,len
,'$');
367 addReplyString(c
,p
,len
);
368 addReply(c
,shared
.crlf
);
371 /* Add a C nul term string as bulk reply */
372 void addReplyBulkCString(redisClient
*c
, char *s
) {
374 addReply(c
,shared
.nullbulk
);
376 addReplyBulkCBuffer(c
,s
,strlen(s
));
380 /* Add a long long as a bulk reply */
381 void addReplyBulkLongLong(redisClient
*c
, long long ll
) {
385 len
= ll2string(buf
,64,ll
);
386 addReplyBulkCBuffer(c
,buf
,len
);
389 static void acceptCommonHandler(int fd
) {
391 if ((c
= createClient(fd
)) == NULL
) {
392 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
393 close(fd
); /* May be already closed, just ingore errors */
396 /* If maxclient directive is set and this is one client more... close the
397 * connection. Note that we create the client instead to check before
398 * for this condition, since now the socket is already set in nonblocking
399 * mode and we can send an error for free using the Kernel I/O */
400 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
401 char *err
= "-ERR max number of clients reached\r\n";
403 /* That's a best effort error message, don't check write errors */
404 if (write(c
->fd
,err
,strlen(err
)) == -1) {
405 /* Nothing to do, Just to avoid the warning... */
410 server
.stat_numconnections
++;
413 void acceptTcpHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
418 REDIS_NOTUSED(privdata
);
420 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
422 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
425 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
426 acceptCommonHandler(cfd
);
429 void acceptUnixHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
433 REDIS_NOTUSED(privdata
);
435 cfd
= anetUnixAccept(server
.neterr
, fd
);
437 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
440 redisLog(REDIS_VERBOSE
,"Accepted connection to %s", server
.unixsocket
);
441 acceptCommonHandler(cfd
);
445 static void freeClientArgv(redisClient
*c
) {
447 for (j
= 0; j
< c
->argc
; j
++)
448 decrRefCount(c
->argv
[j
]);
452 void freeClient(redisClient
*c
) {
455 /* Note that if the client we are freeing is blocked into a blocking
456 * call, we have to set querybuf to NULL *before* to call
457 * unblockClientWaitingData() to avoid processInputBuffer() will get
458 * called. Also it is important to remove the file events after
459 * this, because this call adds the READABLE event. */
460 sdsfree(c
->querybuf
);
462 if (c
->flags
& REDIS_BLOCKED
)
463 unblockClientWaitingData(c
);
465 /* UNWATCH all the keys */
467 listRelease(c
->watched_keys
);
468 /* Unsubscribe from all the pubsub channels */
469 pubsubUnsubscribeAllChannels(c
,0);
470 pubsubUnsubscribeAllPatterns(c
,0);
471 dictRelease(c
->pubsub_channels
);
472 listRelease(c
->pubsub_patterns
);
473 /* Obvious cleanup */
474 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
475 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
476 listRelease(c
->reply
);
479 /* Remove from the list of clients */
480 ln
= listSearchKey(server
.clients
,c
);
481 redisAssert(ln
!= NULL
);
482 listDelNode(server
.clients
,ln
);
483 /* When client was just unblocked because of a blocking operation,
484 * remove it from the list with unblocked clients. */
485 if (c
->flags
& REDIS_UNBLOCKED
) {
486 ln
= listSearchKey(server
.unblocked_clients
,c
);
487 redisAssert(ln
!= NULL
);
488 listDelNode(server
.unblocked_clients
,ln
);
490 /* Remove from the list of clients waiting for swapped keys, or ready
491 * to be restarted, but not yet woken up again. */
492 if (c
->flags
& REDIS_IO_WAIT
) {
493 redisAssert(server
.ds_enabled
);
494 if (listLength(c
->io_keys
) == 0) {
495 ln
= listSearchKey(server
.io_ready_clients
,c
);
497 /* When this client is waiting to be woken up (REDIS_IO_WAIT),
498 * it should be present in the list io_ready_clients */
499 redisAssert(ln
!= NULL
);
500 listDelNode(server
.io_ready_clients
,ln
);
502 while (listLength(c
->io_keys
)) {
503 ln
= listFirst(c
->io_keys
);
504 dontWaitForSwappedKey(c
,ln
->value
);
507 server
.cache_blocked_clients
--;
509 listRelease(c
->io_keys
);
510 /* Master/slave cleanup.
511 * Case 1: we lost the connection with a slave. */
512 if (c
->flags
& REDIS_SLAVE
) {
513 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
515 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
516 ln
= listSearchKey(l
,c
);
517 redisAssert(ln
!= NULL
);
521 /* Case 2: we lost the connection with the master. */
522 if (c
->flags
& REDIS_MASTER
) {
523 server
.master
= NULL
;
524 server
.replstate
= REDIS_REPL_CONNECT
;
525 /* Since we lost the connection with the master, we should also
526 * close the connection with all our slaves if we have any, so
527 * when we'll resync with the master the other slaves will sync again
528 * with us as well. Note that also when the slave is not connected
529 * to the master it will keep refusing connections by other slaves. */
530 while (listLength(server
.slaves
)) {
531 ln
= listFirst(server
.slaves
);
532 freeClient((redisClient
*)ln
->value
);
537 freeClientMultiState(c
);
541 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
542 redisClient
*c
= privdata
;
543 int nwritten
= 0, totwritten
= 0, objlen
;
548 while(c
->bufpos
> 0 || listLength(c
->reply
)) {
550 if (c
->flags
& REDIS_MASTER
) {
551 /* Don't reply to a master */
552 nwritten
= c
->bufpos
- c
->sentlen
;
554 nwritten
= write(fd
,c
->buf
+c
->sentlen
,c
->bufpos
-c
->sentlen
);
555 if (nwritten
<= 0) break;
557 c
->sentlen
+= nwritten
;
558 totwritten
+= nwritten
;
560 /* If the buffer was sent, set bufpos to zero to continue with
561 * the remainder of the reply. */
562 if (c
->sentlen
== c
->bufpos
) {
567 o
= listNodeValue(listFirst(c
->reply
));
568 objlen
= sdslen(o
->ptr
);
571 listDelNode(c
->reply
,listFirst(c
->reply
));
575 if (c
->flags
& REDIS_MASTER
) {
576 /* Don't reply to a master */
577 nwritten
= objlen
- c
->sentlen
;
579 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
,objlen
-c
->sentlen
);
580 if (nwritten
<= 0) break;
582 c
->sentlen
+= nwritten
;
583 totwritten
+= nwritten
;
585 /* If we fully sent the object on head go to the next one */
586 if (c
->sentlen
== objlen
) {
587 listDelNode(c
->reply
,listFirst(c
->reply
));
591 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
592 * bytes, in a single threaded server it's a good idea to serve
593 * other clients as well, even if a very large request comes from
594 * super fast link that is always able to accept data (in real world
595 * scenario think about 'KEYS *' against the loopback interfae) */
596 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
598 if (nwritten
== -1) {
599 if (errno
== EAGAIN
) {
602 redisLog(REDIS_VERBOSE
,
603 "Error writing to client: %s", strerror(errno
));
608 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
609 if (listLength(c
->reply
) == 0) {
611 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
613 /* Close connection after entire reply has been sent. */
614 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) freeClient(c
);
618 /* resetClient prepare the client to process the next command */
619 void resetClient(redisClient
*c
) {
626 void closeTimedoutClients(void) {
629 time_t now
= time(NULL
);
632 listRewind(server
.clients
,&li
);
633 while ((ln
= listNext(&li
)) != NULL
) {
634 c
= listNodeValue(ln
);
635 if (server
.maxidletime
&&
636 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
637 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
638 !(c
->flags
& REDIS_BLOCKED
) && /* no timeout for BLPOP */
639 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
640 listLength(c
->pubsub_patterns
) == 0 &&
641 (now
- c
->lastinteraction
> server
.maxidletime
))
643 redisLog(REDIS_VERBOSE
,"Closing idle client");
645 } else if (c
->flags
& REDIS_BLOCKED
) {
646 if (c
->bpop
.timeout
!= 0 && c
->bpop
.timeout
< now
) {
647 addReply(c
,shared
.nullmultibulk
);
648 unblockClientWaitingData(c
);
654 int processInlineBuffer(redisClient
*c
) {
655 char *newline
= strstr(c
->querybuf
,"\r\n");
660 /* Nothing to do without a \r\n */
664 /* Split the input buffer up to the \r\n */
665 querylen
= newline
-(c
->querybuf
);
666 argv
= sdssplitlen(c
->querybuf
,querylen
," ",1,&argc
);
668 /* Leave data after the first line of the query in the buffer */
669 c
->querybuf
= sdsrange(c
->querybuf
,querylen
+2,-1);
671 /* Setup argv array on client structure */
672 if (c
->argv
) zfree(c
->argv
);
673 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
675 /* Create redis objects for all arguments. */
676 for (c
->argc
= 0, j
= 0; j
< argc
; j
++) {
677 if (sdslen(argv
[j
])) {
678 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
688 /* Helper function. Trims query buffer to make the function that processes
689 * multi bulk requests idempotent. */
690 static void setProtocolError(redisClient
*c
, int pos
) {
691 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
692 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
695 int processMultibulkBuffer(redisClient
*c
) {
696 char *newline
= NULL
;
701 if (c
->multibulklen
== 0) {
702 /* The client should have been reset */
703 redisAssert(c
->argc
== 0);
705 /* Multi bulk length cannot be read without a \r\n */
706 newline
= strstr(c
->querybuf
,"\r\n");
710 /* We know for sure there is a whole line since newline != NULL,
711 * so go ahead and find out the multi bulk length. */
712 redisAssert(c
->querybuf
[0] == '*');
713 c
->multibulklen
= strtol(c
->querybuf
+1,&eptr
,10);
714 pos
= (newline
-c
->querybuf
)+2;
715 if (c
->multibulklen
<= 0) {
716 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
718 } else if (c
->multibulklen
> 1024*1024) {
719 addReplyError(c
,"Protocol error: invalid multibulk length");
720 setProtocolError(c
,pos
);
724 /* Setup argv array on client structure */
725 if (c
->argv
) zfree(c
->argv
);
726 c
->argv
= zmalloc(sizeof(robj
*)*c
->multibulklen
);
728 /* Search new newline */
729 newline
= strstr(c
->querybuf
+pos
,"\r\n");
732 redisAssert(c
->multibulklen
> 0);
733 while(c
->multibulklen
) {
734 /* Read bulk length if unknown */
735 if (c
->bulklen
== -1) {
736 newline
= strstr(c
->querybuf
+pos
,"\r\n");
737 if (newline
!= NULL
) {
738 if (c
->querybuf
[pos
] != '$') {
739 addReplyErrorFormat(c
,
740 "Protocol error: expected '$', got '%c'",
742 setProtocolError(c
,pos
);
746 bulklen
= strtol(c
->querybuf
+pos
+1,&eptr
,10);
747 tolerr
= (eptr
[0] != '\r');
748 if (tolerr
|| bulklen
== LONG_MIN
|| bulklen
== LONG_MAX
||
749 bulklen
< 0 || bulklen
> 512*1024*1024)
751 addReplyError(c
,"Protocol error: invalid bulk length");
752 setProtocolError(c
,pos
);
755 pos
+= eptr
-(c
->querybuf
+pos
)+2;
756 c
->bulklen
= bulklen
;
758 /* No newline in current buffer, so wait for more data */
763 /* Read bulk argument */
764 if (sdslen(c
->querybuf
)-pos
< (unsigned)(c
->bulklen
+2)) {
765 /* Not enough data (+2 == trailing \r\n) */
768 c
->argv
[c
->argc
++] = createStringObject(c
->querybuf
+pos
,c
->bulklen
);
776 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
778 /* We're done when c->multibulk == 0 */
779 if (c
->multibulklen
== 0) {
785 void processInputBuffer(redisClient
*c
) {
786 /* Keep processing while there is something in the input buffer */
787 while(sdslen(c
->querybuf
)) {
788 /* Immediately abort if the client is in the middle of something. */
789 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
791 /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
792 * written to the client. Make sure to not let the reply grow after
793 * this flag has been set (i.e. don't process more commands). */
794 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
796 /* Determine request type when unknown. */
798 if (c
->querybuf
[0] == '*') {
799 c
->reqtype
= REDIS_REQ_MULTIBULK
;
801 c
->reqtype
= REDIS_REQ_INLINE
;
805 if (c
->reqtype
== REDIS_REQ_INLINE
) {
806 if (processInlineBuffer(c
) != REDIS_OK
) break;
807 } else if (c
->reqtype
== REDIS_REQ_MULTIBULK
) {
808 if (processMultibulkBuffer(c
) != REDIS_OK
) break;
810 redisPanic("Unknown request type");
813 /* Multibulk processing could see a <= 0 length. */
817 /* Only reset the client when the command was executed. */
818 if (processCommand(c
) == REDIS_OK
)
824 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
825 redisClient
*c
= (redisClient
*) privdata
;
826 char buf
[REDIS_IOBUF_LEN
];
831 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
833 if (errno
== EAGAIN
) {
836 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
840 } else if (nread
== 0) {
841 redisLog(REDIS_VERBOSE
, "Client closed connection");
846 c
->querybuf
= sdscatlen(c
->querybuf
,buf
,nread
);
847 c
->lastinteraction
= time(NULL
);
851 processInputBuffer(c
);
854 void getClientsMaxBuffers(unsigned long *longest_output_list
,
855 unsigned long *biggest_input_buffer
) {
859 unsigned long lol
= 0, bib
= 0;
861 listRewind(server
.clients
,&li
);
862 while ((ln
= listNext(&li
)) != NULL
) {
863 c
= listNodeValue(ln
);
865 if (listLength(c
->reply
) > lol
) lol
= listLength(c
->reply
);
866 if (sdslen(c
->querybuf
) > bib
) bib
= sdslen(c
->querybuf
);
868 *longest_output_list
= lol
;
869 *biggest_input_buffer
= bib
;
872 void clientCommand(redisClient
*c
) {
877 if (!strcasecmp(c
->argv
[1]->ptr
,"list") && c
->argc
== 2) {
879 time_t now
= time(NULL
);
881 listRewind(server
.clients
,&li
);
882 while ((ln
= listNext(&li
)) != NULL
) {
883 char ip
[32], flags
[16], *p
;
886 client
= listNodeValue(ln
);
887 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue;
889 if (client
->flags
& REDIS_SLAVE
) {
890 if (client
->flags
& REDIS_MONITOR
)
895 if (client
->flags
& REDIS_MASTER
) *p
++ = 'M';
896 if (p
== flags
) *p
++ = 'N';
897 if (client
->flags
& REDIS_MULTI
) *p
++ = 'x';
898 if (client
->flags
& REDIS_BLOCKED
) *p
++ = 'b';
899 if (client
->flags
& REDIS_IO_WAIT
) *p
++ = 'i';
900 if (client
->flags
& REDIS_DIRTY_CAS
) *p
++ = 'd';
901 if (client
->flags
& REDIS_CLOSE_AFTER_REPLY
) *p
++ = 'c';
902 if (client
->flags
& REDIS_UNBLOCKED
) *p
++ = 'u';
905 "addr=%s:%d fd=%d idle=%ld flags=%s db=%d sub=%d psub=%d\n",
907 (long)(now
- client
->lastinteraction
),
910 (int) dictSize(client
->pubsub_channels
),
911 (int) listLength(client
->pubsub_patterns
));
913 addReplyBulkCBuffer(c
,o
,sdslen(o
));
915 } else if (!strcasecmp(c
->argv
[1]->ptr
,"kill") && c
->argc
== 3) {
916 listRewind(server
.clients
,&li
);
917 while ((ln
= listNext(&li
)) != NULL
) {
918 char ip
[32], addr
[64];
921 client
= listNodeValue(ln
);
922 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue;
923 snprintf(addr
,sizeof(addr
),"%s:%d",ip
,port
);
924 if (strcmp(addr
,c
->argv
[2]->ptr
) == 0) {
925 addReply(c
,shared
.ok
);
927 client
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
934 addReplyError(c
,"No such client");
936 addReplyError(c
, "Syntax error, try CLIENT (LIST | KILL ip:port)");