5 void *dupClientReplyValue(void *o
) {
6 incrRefCount((robj
*)o
);
10 int listMatchObjects(void *a
, void *b
) {
11 return equalStringObjects(a
,b
);
14 redisClient
*createClient(int fd
) {
15 redisClient
*c
= zmalloc(sizeof(*c
));
17 anetNonBlock(NULL
,fd
);
18 anetTcpNoDelay(NULL
,fd
);
22 c
->querybuf
= sdsempty();
31 c
->lastinteraction
= time(NULL
);
33 c
->replstate
= REDIS_REPL_NONE
;
34 c
->reply
= listCreate();
35 listSetFreeMethod(c
->reply
,decrRefCount
);
36 listSetDupMethod(c
->reply
,dupClientReplyValue
);
37 c
->blocking_keys
= NULL
;
38 c
->blocking_keys_num
= 0;
39 c
->io_keys
= listCreate();
40 c
->watched_keys
= listCreate();
41 listSetFreeMethod(c
->io_keys
,decrRefCount
);
42 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
43 c
->pubsub_patterns
= listCreate();
44 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
45 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
46 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
47 readQueryFromClient
, c
) == AE_ERR
) {
51 listAddNodeTail(server
.clients
,c
);
52 initClientMultiState(c
);
56 void addReply(redisClient
*c
, robj
*obj
) {
57 if (listLength(c
->reply
) == 0 &&
58 (c
->replstate
== REDIS_REPL_NONE
||
59 c
->replstate
== REDIS_REPL_ONLINE
) &&
60 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
61 sendReplyToClient
, c
) == AE_ERR
) return;
63 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
64 obj
= dupStringObject(obj
);
65 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
67 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
70 void addReplySds(redisClient
*c
, sds s
) {
71 robj
*o
= createObject(REDIS_STRING
,s
);
76 void addReplyDouble(redisClient
*c
, double d
) {
79 snprintf(buf
,sizeof(buf
),"%.17g",d
);
80 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
81 (unsigned long) strlen(buf
),buf
));
84 void addReplyLongLong(redisClient
*c
, long long ll
) {
89 addReply(c
,shared
.czero
);
92 addReply(c
,shared
.cone
);
96 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
99 addReplySds(c
,sdsnewlen(buf
,len
+3));
102 void addReplyUlong(redisClient
*c
, unsigned long ul
) {
107 addReply(c
,shared
.czero
);
109 } else if (ul
== 1) {
110 addReply(c
,shared
.cone
);
113 len
= snprintf(buf
,sizeof(buf
),":%lu\r\n",ul
);
114 addReplySds(c
,sdsnewlen(buf
,len
));
117 void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
121 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
122 len
= sdslen(obj
->ptr
);
124 long n
= (long)obj
->ptr
;
126 /* Compute how many bytes will take this integer as a radix 10 string */
132 while((n
= n
/10) != 0) {
137 intlen
= ll2string(buf
+1,sizeof(buf
)-1,(long long)len
);
138 buf
[intlen
+1] = '\r';
139 buf
[intlen
+2] = '\n';
140 addReplySds(c
,sdsnewlen(buf
,intlen
+3));
143 void addReplyBulk(redisClient
*c
, robj
*obj
) {
144 addReplyBulkLen(c
,obj
);
146 addReply(c
,shared
.crlf
);
149 /* In the CONFIG command we need to add vanilla C string as bulk replies */
150 void addReplyBulkCString(redisClient
*c
, char *s
) {
152 addReply(c
,shared
.nullbulk
);
154 robj
*o
= createStringObject(s
,strlen(s
));
160 void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
166 REDIS_NOTUSED(privdata
);
168 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
170 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
173 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
174 if ((c
= createClient(cfd
)) == NULL
) {
175 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
176 close(cfd
); /* May be already closed, just ingore errors */
179 /* If maxclient directive is set and this is one client more... close the
180 * connection. Note that we create the client instead to check before
181 * for this condition, since now the socket is already set in nonblocking
182 * mode and we can send an error for free using the Kernel I/O */
183 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
184 char *err
= "-ERR max number of clients reached\r\n";
186 /* That's a best effort error message, don't check write errors */
187 if (write(c
->fd
,err
,strlen(err
)) == -1) {
188 /* Nothing to do, Just to avoid the warning... */
193 server
.stat_numconnections
++;
196 static void freeClientArgv(redisClient
*c
) {
199 for (j
= 0; j
< c
->argc
; j
++)
200 decrRefCount(c
->argv
[j
]);
201 for (j
= 0; j
< c
->mbargc
; j
++)
202 decrRefCount(c
->mbargv
[j
]);
207 void freeClient(redisClient
*c
) {
210 /* Note that if the client we are freeing is blocked into a blocking
211 * call, we have to set querybuf to NULL *before* to call
212 * unblockClientWaitingData() to avoid processInputBuffer() will get
213 * called. Also it is important to remove the file events after
214 * this, because this call adds the READABLE event. */
215 sdsfree(c
->querybuf
);
217 if (c
->flags
& REDIS_BLOCKED
)
218 unblockClientWaitingData(c
);
220 /* UNWATCH all the keys */
222 listRelease(c
->watched_keys
);
223 /* Unsubscribe from all the pubsub channels */
224 pubsubUnsubscribeAllChannels(c
,0);
225 pubsubUnsubscribeAllPatterns(c
,0);
226 dictRelease(c
->pubsub_channels
);
227 listRelease(c
->pubsub_patterns
);
228 /* Obvious cleanup */
229 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
230 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
231 listRelease(c
->reply
);
234 /* Remove from the list of clients */
235 ln
= listSearchKey(server
.clients
,c
);
236 redisAssert(ln
!= NULL
);
237 listDelNode(server
.clients
,ln
);
238 /* Remove from the list of clients that are now ready to be restarted
239 * after waiting for swapped keys */
240 if (c
->flags
& REDIS_IO_WAIT
&& listLength(c
->io_keys
) == 0) {
241 ln
= listSearchKey(server
.io_ready_clients
,c
);
243 listDelNode(server
.io_ready_clients
,ln
);
244 server
.vm_blocked_clients
--;
247 /* Remove from the list of clients waiting for swapped keys */
248 while (server
.vm_enabled
&& listLength(c
->io_keys
)) {
249 ln
= listFirst(c
->io_keys
);
250 dontWaitForSwappedKey(c
,ln
->value
);
252 listRelease(c
->io_keys
);
253 /* Master/slave cleanup */
254 if (c
->flags
& REDIS_SLAVE
) {
255 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
257 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
258 ln
= listSearchKey(l
,c
);
259 redisAssert(ln
!= NULL
);
262 if (c
->flags
& REDIS_MASTER
) {
263 server
.master
= NULL
;
264 server
.replstate
= REDIS_REPL_CONNECT
;
269 freeClientMultiState(c
);
273 #define GLUEREPLY_UP_TO (1024)
274 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
276 char buf
[GLUEREPLY_UP_TO
];
281 listRewind(c
->reply
,&li
);
282 while((ln
= listNext(&li
))) {
286 objlen
= sdslen(o
->ptr
);
287 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
288 memcpy(buf
+copylen
,o
->ptr
,objlen
);
290 listDelNode(c
->reply
,ln
);
292 if (copylen
== 0) return;
296 /* Now the output buffer is empty, add the new single element */
297 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
298 listAddNodeHead(c
->reply
,o
);
301 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
302 redisClient
*c
= privdata
;
303 int nwritten
= 0, totwritten
= 0, objlen
;
308 /* Use writev() if we have enough buffers to send */
309 if (!server
.glueoutputbuf
&&
310 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
311 !(c
->flags
& REDIS_MASTER
))
313 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
317 while(listLength(c
->reply
)) {
318 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
319 glueReplyBuffersIfNeeded(c
);
321 o
= listNodeValue(listFirst(c
->reply
));
322 objlen
= sdslen(o
->ptr
);
325 listDelNode(c
->reply
,listFirst(c
->reply
));
329 if (c
->flags
& REDIS_MASTER
) {
330 /* Don't reply to a master */
331 nwritten
= objlen
- c
->sentlen
;
333 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
334 if (nwritten
<= 0) break;
336 c
->sentlen
+= nwritten
;
337 totwritten
+= nwritten
;
338 /* If we fully sent the object on head go to the next one */
339 if (c
->sentlen
== objlen
) {
340 listDelNode(c
->reply
,listFirst(c
->reply
));
343 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
344 * bytes, in a single threaded server it's a good idea to serve
345 * other clients as well, even if a very large request comes from
346 * super fast link that is always able to accept data (in real world
347 * scenario think about 'KEYS *' against the loopback interfae) */
348 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
350 if (nwritten
== -1) {
351 if (errno
== EAGAIN
) {
354 redisLog(REDIS_VERBOSE
,
355 "Error writing to client: %s", strerror(errno
));
360 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
361 if (listLength(c
->reply
) == 0) {
363 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
367 void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
369 redisClient
*c
= privdata
;
370 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
372 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
378 while (listLength(c
->reply
)) {
383 /* fill-in the iov[] array */
384 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
385 o
= listNodeValue(node
);
386 objlen
= sdslen(o
->ptr
);
388 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
391 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
392 break; /* no more iovecs */
394 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
395 iov
[ion
].iov_len
= objlen
- offset
;
396 willwrite
+= objlen
- offset
;
397 offset
= 0; /* just for the first item */
404 /* write all collected blocks at once */
405 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
406 if (errno
!= EAGAIN
) {
407 redisLog(REDIS_VERBOSE
,
408 "Error writing to client: %s", strerror(errno
));
415 totwritten
+= nwritten
;
418 /* remove written robjs from c->reply */
419 while (nwritten
&& listLength(c
->reply
)) {
420 o
= listNodeValue(listFirst(c
->reply
));
421 objlen
= sdslen(o
->ptr
);
423 if(nwritten
>= objlen
- offset
) {
424 listDelNode(c
->reply
, listFirst(c
->reply
));
425 nwritten
-= objlen
- offset
;
429 c
->sentlen
+= nwritten
;
437 c
->lastinteraction
= time(NULL
);
439 if (listLength(c
->reply
) == 0) {
441 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
445 /* resetClient prepare the client to process the next command */
446 void resetClient(redisClient
*c
) {
452 void closeTimedoutClients(void) {
455 time_t now
= time(NULL
);
458 listRewind(server
.clients
,&li
);
459 while ((ln
= listNext(&li
)) != NULL
) {
460 c
= listNodeValue(ln
);
461 if (server
.maxidletime
&&
462 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
463 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
464 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
465 listLength(c
->pubsub_patterns
) == 0 &&
466 (now
- c
->lastinteraction
> server
.maxidletime
))
468 redisLog(REDIS_VERBOSE
,"Closing idle client");
470 } else if (c
->flags
& REDIS_BLOCKED
) {
471 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
472 addReply(c
,shared
.nullmultibulk
);
473 unblockClientWaitingData(c
);
479 void processInputBuffer(redisClient
*c
) {
481 /* Before to process the input buffer, make sure the client is not
482 * waitig for a blocking operation such as BLPOP. Note that the first
483 * iteration the client is never blocked, otherwise the processInputBuffer
484 * would not be called at all, but after the execution of the first commands
485 * in the input buffer the client may be blocked, and the "goto again"
486 * will try to reiterate. The following line will make it return asap. */
487 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
488 if (c
->bulklen
== -1) {
489 /* Read the first line of the query */
490 char *p
= strchr(c
->querybuf
,'\n');
498 c
->querybuf
= sdsempty();
499 querylen
= 1+(p
-(query
));
500 if (sdslen(query
) > querylen
) {
501 /* leave data after the first line of the query in the buffer */
502 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
504 *p
= '\0'; /* remove "\n" */
505 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
508 /* Now we can split the query in arguments */
509 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
512 if (c
->argv
) zfree(c
->argv
);
513 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
515 for (j
= 0; j
< argc
; j
++) {
516 if (sdslen(argv
[j
])) {
517 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
525 /* Execute the command. If the client is still valid
526 * after processCommand() return and there is something
527 * on the query buffer try to process the next command. */
528 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
530 /* Nothing to process, argc == 0. Just process the query
531 * buffer if it's not empty or return to the caller */
532 if (sdslen(c
->querybuf
)) goto again
;
535 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
536 redisLog(REDIS_VERBOSE
, "Client protocol error");
541 /* Bulk read handling. Note that if we are at this point
542 the client already sent a command terminated with a newline,
543 we are reading the bulk data that is actually the last
544 argument of the command. */
545 int qbl
= sdslen(c
->querybuf
);
547 if (c
->bulklen
<= qbl
) {
548 /* Copy everything but the final CRLF as final argument */
549 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
551 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
552 /* Process the command. If the client is still valid after
553 * the processing and there is more data in the buffer
554 * try to parse it. */
555 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
561 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
562 redisClient
*c
= (redisClient
*) privdata
;
563 char buf
[REDIS_IOBUF_LEN
];
568 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
570 if (errno
== EAGAIN
) {
573 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
577 } else if (nread
== 0) {
578 redisLog(REDIS_VERBOSE
, "Client closed connection");
583 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
584 c
->lastinteraction
= time(NULL
);
588 processInputBuffer(c
);