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 /* passing -1 as fd it is possible to create a non connected client.
18 * This is useful since all the Redis commands needs to be executed
19 * in the context of a client. When commands are executed in other
20 * contexts (for instance a Lua script) we need a non connected client. */
22 anetNonBlock(NULL
,fd
);
23 anetTcpNoDelay(NULL
,fd
);
24 if (aeCreateFileEvent(server
.el
,fd
,AE_READABLE
,
25 readQueryFromClient
, c
) == AE_ERR
)
35 c
->querybuf
= sdsempty();
43 c
->lastinteraction
= time(NULL
);
45 c
->replstate
= REDIS_REPL_NONE
;
46 c
->reply
= listCreate();
47 listSetFreeMethod(c
->reply
,decrRefCount
);
48 listSetDupMethod(c
->reply
,dupClientReplyValue
);
52 c
->bpop
.target
= NULL
;
53 c
->io_keys
= listCreate();
54 c
->watched_keys
= listCreate();
55 listSetFreeMethod(c
->io_keys
,decrRefCount
);
56 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
57 c
->pubsub_patterns
= listCreate();
58 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
59 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
60 listAddNodeTail(server
.clients
,c
);
61 initClientMultiState(c
);
65 /* Set the event loop to listen for write events on the client's socket.
66 * Typically gets called every time a reply is built. */
67 int _installWriteEvent(redisClient
*c
) {
68 if (c
->fd
<= 0) return REDIS_ERR
;
69 if (c
->bufpos
== 0 && listLength(c
->reply
) == 0 &&
70 (c
->replstate
== REDIS_REPL_NONE
||
71 c
->replstate
== REDIS_REPL_ONLINE
) &&
72 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
73 sendReplyToClient
, c
) == AE_ERR
) return REDIS_ERR
;
77 /* Create a duplicate of the last object in the reply list when
78 * it is not exclusively owned by the reply list. */
79 robj
*dupLastObjectIfNeeded(list
*reply
) {
82 redisAssert(listLength(reply
) > 0);
84 cur
= listNodeValue(ln
);
85 if (cur
->refcount
> 1) {
86 new = dupStringObject(cur
);
88 listNodeValue(ln
) = new;
90 return listNodeValue(ln
);
93 /* -----------------------------------------------------------------------------
94 * Low level functions to add more data to output buffers.
95 * -------------------------------------------------------------------------- */
97 int _addReplyToBuffer(redisClient
*c
, char *s
, size_t len
) {
98 size_t available
= sizeof(c
->buf
)-c
->bufpos
;
100 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return REDIS_OK
;
102 /* If there already are entries in the reply list, we cannot
103 * add anything more to the static buffer. */
104 if (listLength(c
->reply
) > 0) return REDIS_ERR
;
106 /* Check that the buffer has enough space available for this string. */
107 if (len
> available
) return REDIS_ERR
;
109 memcpy(c
->buf
+c
->bufpos
,s
,len
);
114 void _addReplyObjectToList(redisClient
*c
, robj
*o
) {
117 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
119 if (listLength(c
->reply
) == 0) {
121 listAddNodeTail(c
->reply
,o
);
123 tail
= listNodeValue(listLast(c
->reply
));
125 /* Append to this object when possible. */
126 if (tail
->ptr
!= NULL
&&
127 sdslen(tail
->ptr
)+sdslen(o
->ptr
) <= REDIS_REPLY_CHUNK_BYTES
)
129 tail
= dupLastObjectIfNeeded(c
->reply
);
130 tail
->ptr
= sdscatlen(tail
->ptr
,o
->ptr
,sdslen(o
->ptr
));
133 listAddNodeTail(c
->reply
,o
);
138 /* This method takes responsibility over the sds. When it is no longer
139 * needed it will be free'd, otherwise it ends up in a robj. */
140 void _addReplySdsToList(redisClient
*c
, sds s
) {
143 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) {
148 if (listLength(c
->reply
) == 0) {
149 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
151 tail
= listNodeValue(listLast(c
->reply
));
153 /* Append to this object when possible. */
154 if (tail
->ptr
!= NULL
&&
155 sdslen(tail
->ptr
)+sdslen(s
) <= REDIS_REPLY_CHUNK_BYTES
)
157 tail
= dupLastObjectIfNeeded(c
->reply
);
158 tail
->ptr
= sdscatlen(tail
->ptr
,s
,sdslen(s
));
161 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
));
166 void _addReplyStringToList(redisClient
*c
, char *s
, size_t len
) {
169 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
171 if (listLength(c
->reply
) == 0) {
172 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
174 tail
= listNodeValue(listLast(c
->reply
));
176 /* Append to this object when possible. */
177 if (tail
->ptr
!= NULL
&&
178 sdslen(tail
->ptr
)+len
<= REDIS_REPLY_CHUNK_BYTES
)
180 tail
= dupLastObjectIfNeeded(c
->reply
);
181 tail
->ptr
= sdscatlen(tail
->ptr
,s
,len
);
183 listAddNodeTail(c
->reply
,createStringObject(s
,len
));
188 /* -----------------------------------------------------------------------------
189 * Higher level functions to queue data on the client output buffer.
190 * The following functions are the ones that commands implementations will call.
191 * -------------------------------------------------------------------------- */
193 void addReply(redisClient
*c
, robj
*obj
) {
194 if (_installWriteEvent(c
) != REDIS_OK
) return;
196 /* This is an important place where we can avoid copy-on-write
197 * when there is a saving child running, avoiding touching the
198 * refcount field of the object if it's not needed.
200 * If the encoding is RAW and there is room in the static buffer
201 * we'll be able to send the object to the client without
202 * messing with its page. */
203 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
204 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
205 _addReplyObjectToList(c
,obj
);
207 /* FIXME: convert the long into string and use _addReplyToBuffer()
208 * instead of calling getDecodedObject. As this place in the
209 * code is too performance critical. */
210 obj
= getDecodedObject(obj
);
211 if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
)
212 _addReplyObjectToList(c
,obj
);
217 void addReplySds(redisClient
*c
, sds s
) {
218 if (_installWriteEvent(c
) != REDIS_OK
) {
219 /* The caller expects the sds to be free'd. */
223 if (_addReplyToBuffer(c
,s
,sdslen(s
)) == REDIS_OK
) {
226 /* This method free's the sds when it is no longer needed. */
227 _addReplySdsToList(c
,s
);
231 void addReplyString(redisClient
*c
, char *s
, size_t len
) {
232 if (_installWriteEvent(c
) != REDIS_OK
) return;
233 if (_addReplyToBuffer(c
,s
,len
) != REDIS_OK
)
234 _addReplyStringToList(c
,s
,len
);
237 void _addReplyError(redisClient
*c
, char *s
, size_t len
) {
238 addReplyString(c
,"-ERR ",5);
239 addReplyString(c
,s
,len
);
240 addReplyString(c
,"\r\n",2);
243 void addReplyError(redisClient
*c
, char *err
) {
244 _addReplyError(c
,err
,strlen(err
));
247 void addReplyErrorFormat(redisClient
*c
, const char *fmt
, ...) {
250 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
252 _addReplyError(c
,s
,sdslen(s
));
256 void _addReplyStatus(redisClient
*c
, char *s
, size_t len
) {
257 addReplyString(c
,"+",1);
258 addReplyString(c
,s
,len
);
259 addReplyString(c
,"\r\n",2);
262 void addReplyStatus(redisClient
*c
, char *status
) {
263 _addReplyStatus(c
,status
,strlen(status
));
266 void addReplyStatusFormat(redisClient
*c
, const char *fmt
, ...) {
269 sds s
= sdscatvprintf(sdsempty(),fmt
,ap
);
271 _addReplyStatus(c
,s
,sdslen(s
));
275 /* Adds an empty object to the reply list that will contain the multi bulk
276 * length, which is not known when this function is called. */
277 void *addDeferredMultiBulkLength(redisClient
*c
) {
278 /* Note that we install the write event here even if the object is not
279 * ready to be sent, since we are sure that before returning to the
280 * event loop setDeferredMultiBulkLength() will be called. */
281 if (_installWriteEvent(c
) != REDIS_OK
) return NULL
;
282 listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,NULL
));
283 return listLast(c
->reply
);
286 /* Populate the length object and try glueing it to the next chunk. */
287 void setDeferredMultiBulkLength(redisClient
*c
, void *node
, long length
) {
288 listNode
*ln
= (listNode
*)node
;
291 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
292 if (node
== NULL
) return;
294 len
= listNodeValue(ln
);
295 len
->ptr
= sdscatprintf(sdsempty(),"*%ld\r\n",length
);
296 if (ln
->next
!= NULL
) {
297 next
= listNodeValue(ln
->next
);
299 /* Only glue when the next node is non-NULL (an sds in this case) */
300 if (next
->ptr
!= NULL
) {
301 len
->ptr
= sdscatlen(len
->ptr
,next
->ptr
,sdslen(next
->ptr
));
302 listDelNode(c
->reply
,ln
->next
);
307 /* Add a duble as a bulk reply */
308 void addReplyDouble(redisClient
*c
, double d
) {
309 char dbuf
[128], sbuf
[128];
311 dlen
= snprintf(dbuf
,sizeof(dbuf
),"%.17g",d
);
312 slen
= snprintf(sbuf
,sizeof(sbuf
),"$%d\r\n%s\r\n",dlen
,dbuf
);
313 addReplyString(c
,sbuf
,slen
);
316 /* Add a long long as integer reply or bulk len / multi bulk count.
317 * Basically this is used to output <prefix><long long><crlf>. */
318 void _addReplyLongLong(redisClient
*c
, long long ll
, char prefix
) {
322 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
325 addReplyString(c
,buf
,len
+3);
328 void addReplyLongLong(redisClient
*c
, long long ll
) {
330 addReply(c
,shared
.czero
);
332 addReply(c
,shared
.cone
);
334 _addReplyLongLong(c
,ll
,':');
337 void addReplyMultiBulkLen(redisClient
*c
, long length
) {
338 _addReplyLongLong(c
,length
,'*');
341 /* Create the length prefix of a bulk reply, example: $2234 */
342 void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
345 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
346 len
= sdslen(obj
->ptr
);
348 long n
= (long)obj
->ptr
;
350 /* Compute how many bytes will take this integer as a radix 10 string */
356 while((n
= n
/10) != 0) {
360 _addReplyLongLong(c
,len
,'$');
363 /* Add a Redis Object as a bulk reply */
364 void addReplyBulk(redisClient
*c
, robj
*obj
) {
365 addReplyBulkLen(c
,obj
);
367 addReply(c
,shared
.crlf
);
370 /* Add a C buffer as bulk reply */
371 void addReplyBulkCBuffer(redisClient
*c
, void *p
, size_t len
) {
372 _addReplyLongLong(c
,len
,'$');
373 addReplyString(c
,p
,len
);
374 addReply(c
,shared
.crlf
);
377 /* Add a C nul term string as bulk reply */
378 void addReplyBulkCString(redisClient
*c
, char *s
) {
380 addReply(c
,shared
.nullbulk
);
382 addReplyBulkCBuffer(c
,s
,strlen(s
));
386 /* Add a long long as a bulk reply */
387 void addReplyBulkLongLong(redisClient
*c
, long long ll
) {
391 len
= ll2string(buf
,64,ll
);
392 addReplyBulkCBuffer(c
,buf
,len
);
395 static void acceptCommonHandler(int fd
) {
397 if ((c
= createClient(fd
)) == NULL
) {
398 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
399 close(fd
); /* May be already closed, just ingore errors */
402 /* If maxclient directive is set and this is one client more... close the
403 * connection. Note that we create the client instead to check before
404 * for this condition, since now the socket is already set in nonblocking
405 * mode and we can send an error for free using the Kernel I/O */
406 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
407 char *err
= "-ERR max number of clients reached\r\n";
409 /* That's a best effort error message, don't check write errors */
410 if (write(c
->fd
,err
,strlen(err
)) == -1) {
411 /* Nothing to do, Just to avoid the warning... */
416 server
.stat_numconnections
++;
419 void acceptTcpHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
424 REDIS_NOTUSED(privdata
);
426 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
428 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
431 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
432 acceptCommonHandler(cfd
);
435 void acceptUnixHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
439 REDIS_NOTUSED(privdata
);
441 cfd
= anetUnixAccept(server
.neterr
, fd
);
443 redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
);
446 redisLog(REDIS_VERBOSE
,"Accepted connection to %s", server
.unixsocket
);
447 acceptCommonHandler(cfd
);
451 static void freeClientArgv(redisClient
*c
) {
453 for (j
= 0; j
< c
->argc
; j
++)
454 decrRefCount(c
->argv
[j
]);
458 void freeClient(redisClient
*c
) {
461 /* Note that if the client we are freeing is blocked into a blocking
462 * call, we have to set querybuf to NULL *before* to call
463 * unblockClientWaitingData() to avoid processInputBuffer() will get
464 * called. Also it is important to remove the file events after
465 * this, because this call adds the READABLE event. */
466 sdsfree(c
->querybuf
);
468 if (c
->flags
& REDIS_BLOCKED
)
469 unblockClientWaitingData(c
);
471 /* UNWATCH all the keys */
473 listRelease(c
->watched_keys
);
474 /* Unsubscribe from all the pubsub channels */
475 pubsubUnsubscribeAllChannels(c
,0);
476 pubsubUnsubscribeAllPatterns(c
,0);
477 dictRelease(c
->pubsub_channels
);
478 listRelease(c
->pubsub_patterns
);
479 /* Obvious cleanup */
480 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
481 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
482 listRelease(c
->reply
);
485 /* Remove from the list of clients */
486 ln
= listSearchKey(server
.clients
,c
);
487 redisAssert(ln
!= NULL
);
488 listDelNode(server
.clients
,ln
);
489 /* When client was just unblocked because of a blocking operation,
490 * remove it from the list with unblocked clients. */
491 if (c
->flags
& REDIS_UNBLOCKED
) {
492 ln
= listSearchKey(server
.unblocked_clients
,c
);
493 redisAssert(ln
!= NULL
);
494 listDelNode(server
.unblocked_clients
,ln
);
496 /* Remove from the list of clients waiting for swapped keys, or ready
497 * to be restarted, but not yet woken up again. */
498 if (c
->flags
& REDIS_IO_WAIT
) {
499 redisAssert(server
.ds_enabled
);
500 if (listLength(c
->io_keys
) == 0) {
501 ln
= listSearchKey(server
.io_ready_clients
,c
);
503 /* When this client is waiting to be woken up (REDIS_IO_WAIT),
504 * it should be present in the list io_ready_clients */
505 redisAssert(ln
!= NULL
);
506 listDelNode(server
.io_ready_clients
,ln
);
508 while (listLength(c
->io_keys
)) {
509 ln
= listFirst(c
->io_keys
);
510 dontWaitForSwappedKey(c
,ln
->value
);
513 server
.cache_blocked_clients
--;
515 listRelease(c
->io_keys
);
516 /* Master/slave cleanup.
517 * Case 1: we lost the connection with a slave. */
518 if (c
->flags
& REDIS_SLAVE
) {
519 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
521 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
522 ln
= listSearchKey(l
,c
);
523 redisAssert(ln
!= NULL
);
527 /* Case 2: we lost the connection with the master. */
528 if (c
->flags
& REDIS_MASTER
) {
529 server
.master
= NULL
;
530 server
.replstate
= REDIS_REPL_CONNECT
;
531 /* Since we lost the connection with the master, we should also
532 * close the connection with all our slaves if we have any, so
533 * when we'll resync with the master the other slaves will sync again
534 * with us as well. Note that also when the slave is not connected
535 * to the master it will keep refusing connections by other slaves.
537 * We do this only if server.masterhost != NULL. If it is NULL this
538 * means the user called SLAVEOF NO ONE and we are freeing our
539 * link with the master, so no need to close link with slaves. */
540 if (server
.masterhost
!= NULL
) {
541 while (listLength(server
.slaves
)) {
542 ln
= listFirst(server
.slaves
);
543 freeClient((redisClient
*)ln
->value
);
549 freeClientMultiState(c
);
553 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
554 redisClient
*c
= privdata
;
555 int nwritten
= 0, totwritten
= 0, objlen
;
560 while(c
->bufpos
> 0 || listLength(c
->reply
)) {
562 if (c
->flags
& REDIS_MASTER
) {
563 /* Don't reply to a master */
564 nwritten
= c
->bufpos
- c
->sentlen
;
566 nwritten
= write(fd
,c
->buf
+c
->sentlen
,c
->bufpos
-c
->sentlen
);
567 if (nwritten
<= 0) break;
569 c
->sentlen
+= nwritten
;
570 totwritten
+= nwritten
;
572 /* If the buffer was sent, set bufpos to zero to continue with
573 * the remainder of the reply. */
574 if (c
->sentlen
== c
->bufpos
) {
579 o
= listNodeValue(listFirst(c
->reply
));
580 objlen
= sdslen(o
->ptr
);
583 listDelNode(c
->reply
,listFirst(c
->reply
));
587 if (c
->flags
& REDIS_MASTER
) {
588 /* Don't reply to a master */
589 nwritten
= objlen
- c
->sentlen
;
591 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
,objlen
-c
->sentlen
);
592 if (nwritten
<= 0) break;
594 c
->sentlen
+= nwritten
;
595 totwritten
+= nwritten
;
597 /* If we fully sent the object on head go to the next one */
598 if (c
->sentlen
== objlen
) {
599 listDelNode(c
->reply
,listFirst(c
->reply
));
603 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
604 * bytes, in a single threaded server it's a good idea to serve
605 * other clients as well, even if a very large request comes from
606 * super fast link that is always able to accept data (in real world
607 * scenario think about 'KEYS *' against the loopback interfae) */
608 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
610 if (nwritten
== -1) {
611 if (errno
== EAGAIN
) {
614 redisLog(REDIS_VERBOSE
,
615 "Error writing to client: %s", strerror(errno
));
620 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
621 if (listLength(c
->reply
) == 0) {
623 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
625 /* Close connection after entire reply has been sent. */
626 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) freeClient(c
);
630 /* resetClient prepare the client to process the next command */
631 void resetClient(redisClient
*c
) {
638 void closeTimedoutClients(void) {
641 time_t now
= time(NULL
);
644 listRewind(server
.clients
,&li
);
645 while ((ln
= listNext(&li
)) != NULL
) {
646 c
= listNodeValue(ln
);
647 if (server
.maxidletime
&&
648 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
649 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
650 !(c
->flags
& REDIS_BLOCKED
) && /* no timeout for BLPOP */
651 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
652 listLength(c
->pubsub_patterns
) == 0 &&
653 (now
- c
->lastinteraction
> server
.maxidletime
))
655 redisLog(REDIS_VERBOSE
,"Closing idle client");
657 } else if (c
->flags
& REDIS_BLOCKED
) {
658 if (c
->bpop
.timeout
!= 0 && c
->bpop
.timeout
< now
) {
659 addReply(c
,shared
.nullmultibulk
);
660 unblockClientWaitingData(c
);
666 int processInlineBuffer(redisClient
*c
) {
667 char *newline
= strstr(c
->querybuf
,"\r\n");
672 /* Nothing to do without a \r\n */
676 /* Split the input buffer up to the \r\n */
677 querylen
= newline
-(c
->querybuf
);
678 argv
= sdssplitlen(c
->querybuf
,querylen
," ",1,&argc
);
680 /* Leave data after the first line of the query in the buffer */
681 c
->querybuf
= sdsrange(c
->querybuf
,querylen
+2,-1);
683 /* Setup argv array on client structure */
684 if (c
->argv
) zfree(c
->argv
);
685 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
687 /* Create redis objects for all arguments. */
688 for (c
->argc
= 0, j
= 0; j
< argc
; j
++) {
689 if (sdslen(argv
[j
])) {
690 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
700 /* Helper function. Trims query buffer to make the function that processes
701 * multi bulk requests idempotent. */
702 static void setProtocolError(redisClient
*c
, int pos
) {
703 c
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
704 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
707 int processMultibulkBuffer(redisClient
*c
) {
708 char *newline
= NULL
;
712 if (c
->multibulklen
== 0) {
713 /* The client should have been reset */
714 redisAssert(c
->argc
== 0);
716 /* Multi bulk length cannot be read without a \r\n */
717 newline
= strchr(c
->querybuf
,'\r');
721 /* Buffer should also contain \n */
722 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
725 /* We know for sure there is a whole line since newline != NULL,
726 * so go ahead and find out the multi bulk length. */
727 redisAssert(c
->querybuf
[0] == '*');
728 ok
= string2ll(c
->querybuf
+1,newline
-(c
->querybuf
+1),&ll
);
729 if (!ok
|| ll
> 1024*1024) {
730 addReplyError(c
,"Protocol error: invalid multibulk length");
731 setProtocolError(c
,pos
);
735 pos
= (newline
-c
->querybuf
)+2;
737 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
741 c
->multibulklen
= ll
;
743 /* Setup argv array on client structure */
744 if (c
->argv
) zfree(c
->argv
);
745 c
->argv
= zmalloc(sizeof(robj
*)*c
->multibulklen
);
748 redisAssert(c
->multibulklen
> 0);
749 while(c
->multibulklen
) {
750 /* Read bulk length if unknown */
751 if (c
->bulklen
== -1) {
752 newline
= strchr(c
->querybuf
+pos
,'\r');
756 /* Buffer should also contain \n */
757 if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2))
760 if (c
->querybuf
[pos
] != '$') {
761 addReplyErrorFormat(c
,
762 "Protocol error: expected '$', got '%c'",
764 setProtocolError(c
,pos
);
768 ok
= string2ll(c
->querybuf
+pos
+1,newline
-(c
->querybuf
+pos
+1),&ll
);
769 if (!ok
|| ll
< 0 || ll
> 512*1024*1024) {
770 addReplyError(c
,"Protocol error: invalid bulk length");
771 setProtocolError(c
,pos
);
775 pos
+= newline
-(c
->querybuf
+pos
)+2;
779 /* Read bulk argument */
780 if (sdslen(c
->querybuf
)-pos
< (unsigned)(c
->bulklen
+2)) {
781 /* Not enough data (+2 == trailing \r\n) */
784 c
->argv
[c
->argc
++] = createStringObject(c
->querybuf
+pos
,c
->bulklen
);
792 c
->querybuf
= sdsrange(c
->querybuf
,pos
,-1);
794 /* We're done when c->multibulk == 0 */
795 if (c
->multibulklen
== 0) {
801 void processInputBuffer(redisClient
*c
) {
802 /* Keep processing while there is something in the input buffer */
803 while(sdslen(c
->querybuf
)) {
804 /* Immediately abort if the client is in the middle of something. */
805 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
807 /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
808 * written to the client. Make sure to not let the reply grow after
809 * this flag has been set (i.e. don't process more commands). */
810 if (c
->flags
& REDIS_CLOSE_AFTER_REPLY
) return;
812 /* Determine request type when unknown. */
814 if (c
->querybuf
[0] == '*') {
815 c
->reqtype
= REDIS_REQ_MULTIBULK
;
817 c
->reqtype
= REDIS_REQ_INLINE
;
821 if (c
->reqtype
== REDIS_REQ_INLINE
) {
822 if (processInlineBuffer(c
) != REDIS_OK
) break;
823 } else if (c
->reqtype
== REDIS_REQ_MULTIBULK
) {
824 if (processMultibulkBuffer(c
) != REDIS_OK
) break;
826 redisPanic("Unknown request type");
829 /* Multibulk processing could see a <= 0 length. */
833 /* Only reset the client when the command was executed. */
834 if (processCommand(c
) == REDIS_OK
)
840 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
841 redisClient
*c
= (redisClient
*) privdata
;
842 char buf
[REDIS_IOBUF_LEN
];
847 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
849 if (errno
== EAGAIN
) {
852 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
856 } else if (nread
== 0) {
857 redisLog(REDIS_VERBOSE
, "Client closed connection");
862 c
->querybuf
= sdscatlen(c
->querybuf
,buf
,nread
);
863 c
->lastinteraction
= time(NULL
);
867 processInputBuffer(c
);
870 void getClientsMaxBuffers(unsigned long *longest_output_list
,
871 unsigned long *biggest_input_buffer
) {
875 unsigned long lol
= 0, bib
= 0;
877 listRewind(server
.clients
,&li
);
878 while ((ln
= listNext(&li
)) != NULL
) {
879 c
= listNodeValue(ln
);
881 if (listLength(c
->reply
) > lol
) lol
= listLength(c
->reply
);
882 if (sdslen(c
->querybuf
) > bib
) bib
= sdslen(c
->querybuf
);
884 *longest_output_list
= lol
;
885 *biggest_input_buffer
= bib
;
888 void clientCommand(redisClient
*c
) {
893 if (!strcasecmp(c
->argv
[1]->ptr
,"list") && c
->argc
== 2) {
895 time_t now
= time(NULL
);
897 listRewind(server
.clients
,&li
);
898 while ((ln
= listNext(&li
)) != NULL
) {
899 char ip
[32], flags
[16], *p
;
902 client
= listNodeValue(ln
);
903 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue;
905 if (client
->flags
& REDIS_SLAVE
) {
906 if (client
->flags
& REDIS_MONITOR
)
911 if (client
->flags
& REDIS_MASTER
) *p
++ = 'M';
912 if (p
== flags
) *p
++ = 'N';
913 if (client
->flags
& REDIS_MULTI
) *p
++ = 'x';
914 if (client
->flags
& REDIS_BLOCKED
) *p
++ = 'b';
915 if (client
->flags
& REDIS_IO_WAIT
) *p
++ = 'i';
916 if (client
->flags
& REDIS_DIRTY_CAS
) *p
++ = 'd';
917 if (client
->flags
& REDIS_CLOSE_AFTER_REPLY
) *p
++ = 'c';
918 if (client
->flags
& REDIS_UNBLOCKED
) *p
++ = 'u';
921 "addr=%s:%d fd=%d idle=%ld flags=%s db=%d sub=%d psub=%d\n",
923 (long)(now
- client
->lastinteraction
),
926 (int) dictSize(client
->pubsub_channels
),
927 (int) listLength(client
->pubsub_patterns
));
929 addReplyBulkCBuffer(c
,o
,sdslen(o
));
931 } else if (!strcasecmp(c
->argv
[1]->ptr
,"kill") && c
->argc
== 3) {
932 listRewind(server
.clients
,&li
);
933 while ((ln
= listNext(&li
)) != NULL
) {
934 char ip
[32], addr
[64];
937 client
= listNodeValue(ln
);
938 if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue;
939 snprintf(addr
,sizeof(addr
),"%s:%d",ip
,port
);
940 if (strcmp(addr
,c
->argv
[2]->ptr
) == 0) {
941 addReply(c
,shared
.ok
);
943 client
->flags
|= REDIS_CLOSE_AFTER_REPLY
;
950 addReplyError(c
,"No such client");
952 addReplyError(c
, "Syntax error, try CLIENT (LIST | KILL ip:port)");