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     if (fd 
!= -1) 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
->flags 
& REDIS_LUA_CLIENT
) return REDIS_OK
; 
  69     if (c
->fd 
<= 0) return REDIS_ERR
; 
  70     if (c
->bufpos 
== 0 && listLength(c
->reply
) == 0 && 
  71         (c
->replstate 
== REDIS_REPL_NONE 
|| 
  72          c
->replstate 
== REDIS_REPL_ONLINE
) && 
  73         aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
, 
  74         sendReplyToClient
, c
) == AE_ERR
) return REDIS_ERR
; 
  78 /* Create a duplicate of the last object in the reply list when 
  79  * it is not exclusively owned by the reply list. */ 
  80 robj 
*dupLastObjectIfNeeded(list 
*reply
) { 
  83     redisAssert(listLength(reply
) > 0); 
  85     cur 
= listNodeValue(ln
); 
  86     if (cur
->refcount 
> 1) { 
  87         new = dupStringObject(cur
); 
  89         listNodeValue(ln
) = new; 
  91     return listNodeValue(ln
); 
  94 /* ----------------------------------------------------------------------------- 
  95  * Low level functions to add more data to output buffers. 
  96  * -------------------------------------------------------------------------- */ 
  98 int _addReplyToBuffer(redisClient 
*c
, char *s
, size_t len
) { 
  99     size_t available 
= sizeof(c
->buf
)-c
->bufpos
; 
 101     if (c
->flags 
& REDIS_CLOSE_AFTER_REPLY
) return REDIS_OK
; 
 103     /* If there already are entries in the reply list, we cannot 
 104      * add anything more to the static buffer. */ 
 105     if (listLength(c
->reply
) > 0) return REDIS_ERR
; 
 107     /* Check that the buffer has enough space available for this string. */ 
 108     if (len 
> available
) return REDIS_ERR
; 
 110     memcpy(c
->buf
+c
->bufpos
,s
,len
); 
 115 void _addReplyObjectToList(redisClient 
*c
, robj 
*o
) { 
 118     if (c
->flags 
& REDIS_CLOSE_AFTER_REPLY
) return; 
 120     if (listLength(c
->reply
) == 0) { 
 122         listAddNodeTail(c
->reply
,o
); 
 124         tail 
= listNodeValue(listLast(c
->reply
)); 
 126         /* Append to this object when possible. */ 
 127         if (tail
->ptr 
!= NULL 
&& 
 128             sdslen(tail
->ptr
)+sdslen(o
->ptr
) <= REDIS_REPLY_CHUNK_BYTES
) 
 130             tail 
= dupLastObjectIfNeeded(c
->reply
); 
 131             tail
->ptr 
= sdscatlen(tail
->ptr
,o
->ptr
,sdslen(o
->ptr
)); 
 134             listAddNodeTail(c
->reply
,o
); 
 139 /* This method takes responsibility over the sds. When it is no longer 
 140  * needed it will be free'd, otherwise it ends up in a robj. */ 
 141 void _addReplySdsToList(redisClient 
*c
, sds s
) { 
 144     if (c
->flags 
& REDIS_CLOSE_AFTER_REPLY
) { 
 149     if (listLength(c
->reply
) == 0) { 
 150         listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
)); 
 152         tail 
= listNodeValue(listLast(c
->reply
)); 
 154         /* Append to this object when possible. */ 
 155         if (tail
->ptr 
!= NULL 
&& 
 156             sdslen(tail
->ptr
)+sdslen(s
) <= REDIS_REPLY_CHUNK_BYTES
) 
 158             tail 
= dupLastObjectIfNeeded(c
->reply
); 
 159             tail
->ptr 
= sdscatlen(tail
->ptr
,s
,sdslen(s
)); 
 162             listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,s
)); 
 167 void _addReplyStringToList(redisClient 
*c
, char *s
, size_t len
) { 
 170     if (c
->flags 
& REDIS_CLOSE_AFTER_REPLY
) return; 
 172     if (listLength(c
->reply
) == 0) { 
 173         listAddNodeTail(c
->reply
,createStringObject(s
,len
)); 
 175         tail 
= listNodeValue(listLast(c
->reply
)); 
 177         /* Append to this object when possible. */ 
 178         if (tail
->ptr 
!= NULL 
&& 
 179             sdslen(tail
->ptr
)+len 
<= REDIS_REPLY_CHUNK_BYTES
) 
 181             tail 
= dupLastObjectIfNeeded(c
->reply
); 
 182             tail
->ptr 
= sdscatlen(tail
->ptr
,s
,len
); 
 184             listAddNodeTail(c
->reply
,createStringObject(s
,len
)); 
 189 /* ----------------------------------------------------------------------------- 
 190  * Higher level functions to queue data on the client output buffer. 
 191  * The following functions are the ones that commands implementations will call. 
 192  * -------------------------------------------------------------------------- */ 
 194 void addReply(redisClient 
*c
, robj 
*obj
) { 
 195     if (_installWriteEvent(c
) != REDIS_OK
) return; 
 197     /* This is an important place where we can avoid copy-on-write 
 198      * when there is a saving child running, avoiding touching the 
 199      * refcount field of the object if it's not needed. 
 201      * If the encoding is RAW and there is room in the static buffer 
 202      * we'll be able to send the object to the client without 
 203      * messing with its page. */ 
 204     if (obj
->encoding 
== REDIS_ENCODING_RAW
) { 
 205         if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
) 
 206             _addReplyObjectToList(c
,obj
); 
 208         /* FIXME: convert the long into string and use _addReplyToBuffer() 
 209          * instead of calling getDecodedObject. As this place in the 
 210          * code is too performance critical. */ 
 211         obj 
= getDecodedObject(obj
); 
 212         if (_addReplyToBuffer(c
,obj
->ptr
,sdslen(obj
->ptr
)) != REDIS_OK
) 
 213             _addReplyObjectToList(c
,obj
); 
 218 void addReplySds(redisClient 
*c
, sds s
) { 
 219     if (_installWriteEvent(c
) != REDIS_OK
) { 
 220         /* The caller expects the sds to be free'd. */ 
 224     if (_addReplyToBuffer(c
,s
,sdslen(s
)) == REDIS_OK
) { 
 227         /* This method free's the sds when it is no longer needed. */ 
 228         _addReplySdsToList(c
,s
); 
 232 void addReplyString(redisClient 
*c
, char *s
, size_t len
) { 
 233     if (_installWriteEvent(c
) != REDIS_OK
) return; 
 234     if (_addReplyToBuffer(c
,s
,len
) != REDIS_OK
) 
 235         _addReplyStringToList(c
,s
,len
); 
 238 void _addReplyError(redisClient 
*c
, char *s
, size_t len
) { 
 239     addReplyString(c
,"-ERR ",5); 
 240     addReplyString(c
,s
,len
); 
 241     addReplyString(c
,"\r\n",2); 
 244 void addReplyError(redisClient 
*c
, char *err
) { 
 245     _addReplyError(c
,err
,strlen(err
)); 
 248 void addReplyErrorFormat(redisClient 
*c
, const char *fmt
, ...) { 
 252     sds s 
= sdscatvprintf(sdsempty(),fmt
,ap
); 
 254     /* Make sure there are no newlines in the string, otherwise invalid protocol 
 257     for (j 
= 0; j 
< l
; j
++) { 
 258         if (s
[j
] == '\r' || s
[j
] == '\n') s
[j
] = ' '; 
 260     _addReplyError(c
,s
,sdslen(s
)); 
 264 void _addReplyStatus(redisClient 
*c
, char *s
, size_t len
) { 
 265     addReplyString(c
,"+",1); 
 266     addReplyString(c
,s
,len
); 
 267     addReplyString(c
,"\r\n",2); 
 270 void addReplyStatus(redisClient 
*c
, char *status
) { 
 271     _addReplyStatus(c
,status
,strlen(status
)); 
 274 void addReplyStatusFormat(redisClient 
*c
, const char *fmt
, ...) { 
 277     sds s 
= sdscatvprintf(sdsempty(),fmt
,ap
); 
 279     _addReplyStatus(c
,s
,sdslen(s
)); 
 283 /* Adds an empty object to the reply list that will contain the multi bulk 
 284  * length, which is not known when this function is called. */ 
 285 void *addDeferredMultiBulkLength(redisClient 
*c
) { 
 286     /* Note that we install the write event here even if the object is not 
 287      * ready to be sent, since we are sure that before returning to the 
 288      * event loop setDeferredMultiBulkLength() will be called. */ 
 289     if (_installWriteEvent(c
) != REDIS_OK
) return NULL
; 
 290     listAddNodeTail(c
->reply
,createObject(REDIS_STRING
,NULL
)); 
 291     return listLast(c
->reply
); 
 294 /* Populate the length object and try glueing it to the next chunk. */ 
 295 void setDeferredMultiBulkLength(redisClient 
*c
, void *node
, long length
) { 
 296     listNode 
*ln 
= (listNode
*)node
; 
 299     /* Abort when *node is NULL (see addDeferredMultiBulkLength). */ 
 300     if (node 
== NULL
) return; 
 302     len 
= listNodeValue(ln
); 
 303     len
->ptr 
= sdscatprintf(sdsempty(),"*%ld\r\n",length
); 
 304     if (ln
->next 
!= NULL
) { 
 305         next 
= listNodeValue(ln
->next
); 
 307         /* Only glue when the next node is non-NULL (an sds in this case) */ 
 308         if (next
->ptr 
!= NULL
) { 
 309             len
->ptr 
= sdscatlen(len
->ptr
,next
->ptr
,sdslen(next
->ptr
)); 
 310             listDelNode(c
->reply
,ln
->next
); 
 315 /* Add a duble as a bulk reply */ 
 316 void addReplyDouble(redisClient 
*c
, double d
) { 
 317     char dbuf
[128], sbuf
[128]; 
 319     dlen 
= snprintf(dbuf
,sizeof(dbuf
),"%.17g",d
); 
 320     slen 
= snprintf(sbuf
,sizeof(sbuf
),"$%d\r\n%s\r\n",dlen
,dbuf
); 
 321     addReplyString(c
,sbuf
,slen
); 
 324 /* Add a long long as integer reply or bulk len / multi bulk count. 
 325  * Basically this is used to output <prefix><long long><crlf>. */ 
 326 void _addReplyLongLong(redisClient 
*c
, long long ll
, char prefix
) { 
 330     len 
= ll2string(buf
+1,sizeof(buf
)-1,ll
); 
 333     addReplyString(c
,buf
,len
+3); 
 336 void addReplyLongLong(redisClient 
*c
, long long ll
) { 
 338         addReply(c
,shared
.czero
); 
 340         addReply(c
,shared
.cone
); 
 342         _addReplyLongLong(c
,ll
,':'); 
 345 void addReplyMultiBulkLen(redisClient 
*c
, long length
) { 
 346     _addReplyLongLong(c
,length
,'*'); 
 349 /* Create the length prefix of a bulk reply, example: $2234 */ 
 350 void addReplyBulkLen(redisClient 
*c
, robj 
*obj
) { 
 353     if (obj
->encoding 
== REDIS_ENCODING_RAW
) { 
 354         len 
= sdslen(obj
->ptr
); 
 356         long n 
= (long)obj
->ptr
; 
 358         /* Compute how many bytes will take this integer as a radix 10 string */ 
 364         while((n 
= n
/10) != 0) { 
 368     _addReplyLongLong(c
,len
,'$'); 
 371 /* Add a Redis Object as a bulk reply */ 
 372 void addReplyBulk(redisClient 
*c
, robj 
*obj
) { 
 373     addReplyBulkLen(c
,obj
); 
 375     addReply(c
,shared
.crlf
); 
 378 /* Add a C buffer as bulk reply */ 
 379 void addReplyBulkCBuffer(redisClient 
*c
, void *p
, size_t len
) { 
 380     _addReplyLongLong(c
,len
,'$'); 
 381     addReplyString(c
,p
,len
); 
 382     addReply(c
,shared
.crlf
); 
 385 /* Add a C nul term string as bulk reply */ 
 386 void addReplyBulkCString(redisClient 
*c
, char *s
) { 
 388         addReply(c
,shared
.nullbulk
); 
 390         addReplyBulkCBuffer(c
,s
,strlen(s
)); 
 394 /* Add a long long as a bulk reply */ 
 395 void addReplyBulkLongLong(redisClient 
*c
, long long ll
) { 
 399     len 
= ll2string(buf
,64,ll
); 
 400     addReplyBulkCBuffer(c
,buf
,len
); 
 403 static void acceptCommonHandler(int fd
) { 
 405     if ((c 
= createClient(fd
)) == NULL
) { 
 406         redisLog(REDIS_WARNING
,"Error allocating resoures for the client"); 
 407         close(fd
); /* May be already closed, just ingore errors */ 
 410     /* If maxclient directive is set and this is one client more... close the 
 411      * connection. Note that we create the client instead to check before 
 412      * for this condition, since now the socket is already set in nonblocking 
 413      * mode and we can send an error for free using the Kernel I/O */ 
 414     if (server
.maxclients 
&& listLength(server
.clients
) > server
.maxclients
) { 
 415         char *err 
= "-ERR max number of clients reached\r\n"; 
 417         /* That's a best effort error message, don't check write errors */ 
 418         if (write(c
->fd
,err
,strlen(err
)) == -1) { 
 419             /* Nothing to do, Just to avoid the warning... */ 
 424     server
.stat_numconnections
++; 
 427 void acceptTcpHandler(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
 432     REDIS_NOTUSED(privdata
); 
 434     cfd 
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
); 
 436         redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
); 
 439     redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
); 
 440     acceptCommonHandler(cfd
); 
 443 void acceptUnixHandler(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
 447     REDIS_NOTUSED(privdata
); 
 449     cfd 
= anetUnixAccept(server
.neterr
, fd
); 
 451         redisLog(REDIS_WARNING
,"Accepting client connection: %s", server
.neterr
); 
 454     redisLog(REDIS_VERBOSE
,"Accepted connection to %s", server
.unixsocket
); 
 455     acceptCommonHandler(cfd
); 
 459 static void freeClientArgv(redisClient 
*c
) { 
 461     for (j 
= 0; j 
< c
->argc
; j
++) 
 462         decrRefCount(c
->argv
[j
]); 
 466 void freeClient(redisClient 
*c
) { 
 469     /* Note that if the client we are freeing is blocked into a blocking 
 470      * call, we have to set querybuf to NULL *before* to call 
 471      * unblockClientWaitingData() to avoid processInputBuffer() will get 
 472      * called. Also it is important to remove the file events after 
 473      * this, because this call adds the READABLE event. */ 
 474     sdsfree(c
->querybuf
); 
 476     if (c
->flags 
& REDIS_BLOCKED
) 
 477         unblockClientWaitingData(c
); 
 479     /* UNWATCH all the keys */ 
 481     listRelease(c
->watched_keys
); 
 482     /* Unsubscribe from all the pubsub channels */ 
 483     pubsubUnsubscribeAllChannels(c
,0); 
 484     pubsubUnsubscribeAllPatterns(c
,0); 
 485     dictRelease(c
->pubsub_channels
); 
 486     listRelease(c
->pubsub_patterns
); 
 487     /* Obvious cleanup */ 
 488     aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
); 
 489     aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
); 
 490     listRelease(c
->reply
); 
 493     /* Remove from the list of clients */ 
 494     ln 
= listSearchKey(server
.clients
,c
); 
 495     redisAssert(ln 
!= NULL
); 
 496     listDelNode(server
.clients
,ln
); 
 497     /* When client was just unblocked because of a blocking operation, 
 498      * remove it from the list with unblocked clients. */ 
 499     if (c
->flags 
& REDIS_UNBLOCKED
) { 
 500         ln 
= listSearchKey(server
.unblocked_clients
,c
); 
 501         redisAssert(ln 
!= NULL
); 
 502         listDelNode(server
.unblocked_clients
,ln
); 
 504     listRelease(c
->io_keys
); 
 505     /* Master/slave cleanup. 
 506      * Case 1: we lost the connection with a slave. */ 
 507     if (c
->flags 
& REDIS_SLAVE
) { 
 508         if (c
->replstate 
== REDIS_REPL_SEND_BULK 
&& c
->repldbfd 
!= -1) 
 510         list 
*l 
= (c
->flags 
& REDIS_MONITOR
) ? server
.monitors 
: server
.slaves
; 
 511         ln 
= listSearchKey(l
,c
); 
 512         redisAssert(ln 
!= NULL
); 
 516     /* Case 2: we lost the connection with the master. */ 
 517     if (c
->flags 
& REDIS_MASTER
) { 
 518         server
.master 
= NULL
; 
 519         server
.replstate 
= REDIS_REPL_CONNECT
; 
 520         server
.repl_down_since 
= time(NULL
); 
 521         /* Since we lost the connection with the master, we should also 
 522          * close the connection with all our slaves if we have any, so 
 523          * when we'll resync with the master the other slaves will sync again 
 524          * with us as well. Note that also when the slave is not connected 
 525          * to the master it will keep refusing connections by other slaves. 
 527          * We do this only if server.masterhost != NULL. If it is NULL this 
 528          * means the user called SLAVEOF NO ONE and we are freeing our 
 529          * link with the master, so no need to close link with slaves. */ 
 530         if (server
.masterhost 
!= NULL
) { 
 531             while (listLength(server
.slaves
)) { 
 532                 ln 
= listFirst(server
.slaves
); 
 533                 freeClient((redisClient
*)ln
->value
); 
 539     freeClientMultiState(c
); 
 543 void sendReplyToClient(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
 544     redisClient 
*c 
= privdata
; 
 545     int nwritten 
= 0, totwritten 
= 0, objlen
; 
 550     while(c
->bufpos 
> 0 || listLength(c
->reply
)) { 
 552             if (c
->flags 
& REDIS_MASTER
) { 
 553                 /* Don't reply to a master */ 
 554                 nwritten 
= c
->bufpos 
- c
->sentlen
; 
 556                 nwritten 
= write(fd
,c
->buf
+c
->sentlen
,c
->bufpos
-c
->sentlen
); 
 557                 if (nwritten 
<= 0) break; 
 559             c
->sentlen 
+= nwritten
; 
 560             totwritten 
+= nwritten
; 
 562             /* If the buffer was sent, set bufpos to zero to continue with 
 563              * the remainder of the reply. */ 
 564             if (c
->sentlen 
== c
->bufpos
) { 
 569             o 
= listNodeValue(listFirst(c
->reply
)); 
 570             objlen 
= sdslen(o
->ptr
); 
 573                 listDelNode(c
->reply
,listFirst(c
->reply
)); 
 577             if (c
->flags 
& REDIS_MASTER
) { 
 578                 /* Don't reply to a master */ 
 579                 nwritten 
= objlen 
- c
->sentlen
; 
 581                 nwritten 
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
,objlen
-c
->sentlen
); 
 582                 if (nwritten 
<= 0) break; 
 584             c
->sentlen 
+= nwritten
; 
 585             totwritten 
+= nwritten
; 
 587             /* If we fully sent the object on head go to the next one */ 
 588             if (c
->sentlen 
== objlen
) { 
 589                 listDelNode(c
->reply
,listFirst(c
->reply
)); 
 593         /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT 
 594          * bytes, in a single threaded server it's a good idea to serve 
 595          * other clients as well, even if a very large request comes from 
 596          * super fast link that is always able to accept data (in real world 
 597          * scenario think about 'KEYS *' against the loopback interfae) */ 
 598         if (totwritten 
> REDIS_MAX_WRITE_PER_EVENT
) break; 
 600     if (nwritten 
== -1) { 
 601         if (errno 
== EAGAIN
) { 
 604             redisLog(REDIS_VERBOSE
, 
 605                 "Error writing to client: %s", strerror(errno
)); 
 610     if (totwritten 
> 0) c
->lastinteraction 
= time(NULL
); 
 611     if (listLength(c
->reply
) == 0) { 
 613         aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
); 
 615         /* Close connection after entire reply has been sent. */ 
 616         if (c
->flags 
& REDIS_CLOSE_AFTER_REPLY
) freeClient(c
); 
 620 /* resetClient prepare the client to process the next command */ 
 621 void resetClient(redisClient 
*c
) { 
 628 void closeTimedoutClients(void) { 
 631     time_t now 
= time(NULL
); 
 634     listRewind(server
.clients
,&li
); 
 635     while ((ln 
= listNext(&li
)) != NULL
) { 
 636         c 
= listNodeValue(ln
); 
 637         if (server
.maxidletime 
&& 
 638             !(c
->flags 
& REDIS_SLAVE
) &&    /* no timeout for slaves */ 
 639             !(c
->flags 
& REDIS_MASTER
) &&   /* no timeout for masters */ 
 640             !(c
->flags 
& REDIS_BLOCKED
) &&  /* no timeout for BLPOP */ 
 641             dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */ 
 642             listLength(c
->pubsub_patterns
) == 0 && 
 643             (now 
- c
->lastinteraction 
> server
.maxidletime
)) 
 645             redisLog(REDIS_VERBOSE
,"Closing idle client"); 
 647         } else if (c
->flags 
& REDIS_BLOCKED
) { 
 648             if (c
->bpop
.timeout 
!= 0 && c
->bpop
.timeout 
< now
) { 
 649                 addReply(c
,shared
.nullmultibulk
); 
 650                 unblockClientWaitingData(c
); 
 656 int processInlineBuffer(redisClient 
*c
) { 
 657     char *newline 
= strstr(c
->querybuf
,"\r\n"); 
 662     /* Nothing to do without a \r\n */ 
 666     /* Split the input buffer up to the \r\n */ 
 667     querylen 
= newline
-(c
->querybuf
); 
 668     argv 
= sdssplitlen(c
->querybuf
,querylen
," ",1,&argc
); 
 670     /* Leave data after the first line of the query in the buffer */ 
 671     c
->querybuf 
= sdsrange(c
->querybuf
,querylen
+2,-1); 
 673     /* Setup argv array on client structure */ 
 674     if (c
->argv
) zfree(c
->argv
); 
 675     c
->argv 
= zmalloc(sizeof(robj
*)*argc
); 
 677     /* Create redis objects for all arguments. */ 
 678     for (c
->argc 
= 0, j 
= 0; j 
< argc
; j
++) { 
 679         if (sdslen(argv
[j
])) { 
 680             c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]); 
 690 /* Helper function. Trims query buffer to make the function that processes 
 691  * multi bulk requests idempotent. */ 
 692 static void setProtocolError(redisClient 
*c
, int pos
) { 
 693     c
->flags 
|= REDIS_CLOSE_AFTER_REPLY
; 
 694     c
->querybuf 
= sdsrange(c
->querybuf
,pos
,-1); 
 697 int processMultibulkBuffer(redisClient 
*c
) { 
 698     char *newline 
= NULL
; 
 702     if (c
->multibulklen 
== 0) { 
 703         /* The client should have been reset */ 
 704         redisAssert(c
->argc 
== 0); 
 706         /* Multi bulk length cannot be read without a \r\n */ 
 707         newline 
= strchr(c
->querybuf
,'\r'); 
 711         /* Buffer should also contain \n */ 
 712         if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2)) 
 715         /* We know for sure there is a whole line since newline != NULL, 
 716          * so go ahead and find out the multi bulk length. */ 
 717         redisAssert(c
->querybuf
[0] == '*'); 
 718         ok 
= string2ll(c
->querybuf
+1,newline
-(c
->querybuf
+1),&ll
); 
 719         if (!ok 
|| ll 
> 1024*1024) { 
 720             addReplyError(c
,"Protocol error: invalid multibulk length"); 
 721             setProtocolError(c
,pos
); 
 725         pos 
= (newline
-c
->querybuf
)+2; 
 727             c
->querybuf 
= sdsrange(c
->querybuf
,pos
,-1); 
 731         c
->multibulklen 
= ll
; 
 733         /* Setup argv array on client structure */ 
 734         if (c
->argv
) zfree(c
->argv
); 
 735         c
->argv 
= zmalloc(sizeof(robj
*)*c
->multibulklen
); 
 738     redisAssert(c
->multibulklen 
> 0); 
 739     while(c
->multibulklen
) { 
 740         /* Read bulk length if unknown */ 
 741         if (c
->bulklen 
== -1) { 
 742             newline 
= strchr(c
->querybuf
+pos
,'\r'); 
 746             /* Buffer should also contain \n */ 
 747             if (newline
-(c
->querybuf
) > ((signed)sdslen(c
->querybuf
)-2)) 
 750             if (c
->querybuf
[pos
] != '$') { 
 751                 addReplyErrorFormat(c
, 
 752                     "Protocol error: expected '$', got '%c'", 
 754                 setProtocolError(c
,pos
); 
 758             ok 
= string2ll(c
->querybuf
+pos
+1,newline
-(c
->querybuf
+pos
+1),&ll
); 
 759             if (!ok 
|| ll 
< 0 || ll 
> 512*1024*1024) { 
 760                 addReplyError(c
,"Protocol error: invalid bulk length"); 
 761                 setProtocolError(c
,pos
); 
 765             pos 
+= newline
-(c
->querybuf
+pos
)+2; 
 769         /* Read bulk argument */ 
 770         if (sdslen(c
->querybuf
)-pos 
< (unsigned)(c
->bulklen
+2)) { 
 771             /* Not enough data (+2 == trailing \r\n) */ 
 774             c
->argv
[c
->argc
++] = createStringObject(c
->querybuf
+pos
,c
->bulklen
); 
 782     c
->querybuf 
= sdsrange(c
->querybuf
,pos
,-1); 
 784     /* We're done when c->multibulk == 0 */ 
 785     if (c
->multibulklen 
== 0) { 
 791 void processInputBuffer(redisClient 
*c
) { 
 792     /* Keep processing while there is something in the input buffer */ 
 793     while(sdslen(c
->querybuf
)) { 
 794         /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is 
 795          * written to the client. Make sure to not let the reply grow after 
 796          * this flag has been set (i.e. don't process more commands). */ 
 797         if (c
->flags 
& REDIS_CLOSE_AFTER_REPLY
) return; 
 799         /* Determine request type when unknown. */ 
 801             if (c
->querybuf
[0] == '*') { 
 802                 c
->reqtype 
= REDIS_REQ_MULTIBULK
; 
 804                 c
->reqtype 
= REDIS_REQ_INLINE
; 
 808         if (c
->reqtype 
== REDIS_REQ_INLINE
) { 
 809             if (processInlineBuffer(c
) != REDIS_OK
) break; 
 810         } else if (c
->reqtype 
== REDIS_REQ_MULTIBULK
) { 
 811             if (processMultibulkBuffer(c
) != REDIS_OK
) break; 
 813             redisPanic("Unknown request type"); 
 816         /* Multibulk processing could see a <= 0 length. */ 
 820             /* Only reset the client when the command was executed. */ 
 821             if (processCommand(c
) == REDIS_OK
) 
 827 void readQueryFromClient(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
 828     redisClient 
*c 
= (redisClient
*) privdata
; 
 829     char buf
[REDIS_IOBUF_LEN
]; 
 834     nread 
= read(fd
, buf
, REDIS_IOBUF_LEN
); 
 836         if (errno 
== EAGAIN
) { 
 839             redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
)); 
 843     } else if (nread 
== 0) { 
 844         redisLog(REDIS_VERBOSE
, "Client closed connection"); 
 849         c
->querybuf 
= sdscatlen(c
->querybuf
,buf
,nread
); 
 850         c
->lastinteraction 
= time(NULL
); 
 854     processInputBuffer(c
); 
 857 void getClientsMaxBuffers(unsigned long *longest_output_list
, 
 858                           unsigned long *biggest_input_buffer
) { 
 862     unsigned long lol 
= 0, bib 
= 0; 
 864     listRewind(server
.clients
,&li
); 
 865     while ((ln 
= listNext(&li
)) != NULL
) { 
 866         c 
= listNodeValue(ln
); 
 868         if (listLength(c
->reply
) > lol
) lol 
= listLength(c
->reply
); 
 869         if (sdslen(c
->querybuf
) > bib
) bib 
= sdslen(c
->querybuf
); 
 871     *longest_output_list 
= lol
; 
 872     *biggest_input_buffer 
= bib
; 
 875 void clientCommand(redisClient 
*c
) { 
 880     if (!strcasecmp(c
->argv
[1]->ptr
,"list") && c
->argc 
== 2) { 
 882         time_t now 
= time(NULL
); 
 884         listRewind(server
.clients
,&li
); 
 885         while ((ln 
= listNext(&li
)) != NULL
) { 
 886             char ip
[32], flags
[16], *p
; 
 889             client 
= listNodeValue(ln
); 
 890             if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue; 
 892             if (client
->flags 
& REDIS_SLAVE
) { 
 893                 if (client
->flags 
& REDIS_MONITOR
) 
 898             if (client
->flags 
& REDIS_MASTER
) *p
++ = 'M'; 
 899             if (p 
== flags
) *p
++ = 'N'; 
 900             if (client
->flags 
& REDIS_MULTI
) *p
++ = 'x'; 
 901             if (client
->flags 
& REDIS_BLOCKED
) *p
++ = 'b'; 
 902             if (client
->flags 
& REDIS_DIRTY_CAS
) *p
++ = 'd'; 
 903             if (client
->flags 
& REDIS_CLOSE_AFTER_REPLY
) *p
++ = 'c'; 
 904             if (client
->flags 
& REDIS_UNBLOCKED
) *p
++ = 'u'; 
 907                 "addr=%s:%d fd=%d idle=%ld flags=%s db=%d sub=%d psub=%d\n", 
 909                 (long)(now 
- client
->lastinteraction
), 
 912                 (int) dictSize(client
->pubsub_channels
), 
 913                 (int) listLength(client
->pubsub_patterns
)); 
 915         addReplyBulkCBuffer(c
,o
,sdslen(o
)); 
 917     } else if (!strcasecmp(c
->argv
[1]->ptr
,"kill") && c
->argc 
== 3) { 
 918         listRewind(server
.clients
,&li
); 
 919         while ((ln 
= listNext(&li
)) != NULL
) { 
 920             char ip
[32], addr
[64]; 
 923             client 
= listNodeValue(ln
); 
 924             if (anetPeerToString(client
->fd
,ip
,&port
) == -1) continue; 
 925             snprintf(addr
,sizeof(addr
),"%s:%d",ip
,port
); 
 926             if (strcmp(addr
,c
->argv
[2]->ptr
) == 0) { 
 927                 addReply(c
,shared
.ok
); 
 929                     client
->flags 
|= REDIS_CLOSE_AFTER_REPLY
; 
 936         addReplyError(c
,"No such client"); 
 938         addReplyError(c
, "Syntax error, try CLIENT (LIST | KILL ip:port)"); 
 942 void rewriteClientCommandVector(redisClient 
*c
, int argc
, ...) { 
 945     robj 
**argv
; /* The new argument vector */ 
 947     argv 
= zmalloc(sizeof(robj
*)*argc
); 
 949     for (j 
= 0; j 
< argc
; j
++) { 
 952         a 
= va_arg(ap
, robj
*); 
 956     /* We free the objects in the original vector at the end, so we are 
 957      * sure that if the same objects are reused in the new vector the 
 958      * refcount gets incremented before it gets decremented. */ 
 959     for (j 
= 0; j 
< c
->argc
; j
++) decrRefCount(c
->argv
[j
]); 
 961     /* Replace argv and argc with our new versions. */