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 static void acceptCommonHandler(int fd
) {
162 if ((c
= createClient(fd
)) == NULL
) {
163 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
164 close(fd
); /* May be already closed, just ingore errors */
167 /* If maxclient directive is set and this is one client more... close the
168 * connection. Note that we create the client instead to check before
169 * for this condition, since now the socket is already set in nonblocking
170 * mode and we can send an error for free using the Kernel I/O */
171 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
172 char *err
= "-ERR max number of clients reached\r\n";
174 /* That's a best effort error message, don't check write errors */
175 if (write(c
->fd
,err
,strlen(err
)) == -1) {
176 /* Nothing to do, Just to avoid the warning... */
181 server
.stat_numconnections
++;
184 void acceptTcpHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
189 REDIS_NOTUSED(privdata
);
191 cfd
= anetTcpAccept(server
.neterr
, fd
, cip
, &cport
);
193 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
196 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
197 acceptCommonHandler(cfd
);
200 void acceptUnixHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
205 REDIS_NOTUSED(privdata
);
207 cfd
= anetUnixAccept(server
.neterr
, fd
, cpath
, sizeof(cpath
));
209 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
212 redisLog(REDIS_VERBOSE
,"Accepted connection to %s", server
.unixsocket
);
213 acceptCommonHandler(cfd
);
217 static void freeClientArgv(redisClient
*c
) {
220 for (j
= 0; j
< c
->argc
; j
++)
221 decrRefCount(c
->argv
[j
]);
222 for (j
= 0; j
< c
->mbargc
; j
++)
223 decrRefCount(c
->mbargv
[j
]);
228 void freeClient(redisClient
*c
) {
231 /* Note that if the client we are freeing is blocked into a blocking
232 * call, we have to set querybuf to NULL *before* to call
233 * unblockClientWaitingData() to avoid processInputBuffer() will get
234 * called. Also it is important to remove the file events after
235 * this, because this call adds the READABLE event. */
236 sdsfree(c
->querybuf
);
238 if (c
->flags
& REDIS_BLOCKED
)
239 unblockClientWaitingData(c
);
241 /* UNWATCH all the keys */
243 listRelease(c
->watched_keys
);
244 /* Unsubscribe from all the pubsub channels */
245 pubsubUnsubscribeAllChannels(c
,0);
246 pubsubUnsubscribeAllPatterns(c
,0);
247 dictRelease(c
->pubsub_channels
);
248 listRelease(c
->pubsub_patterns
);
249 /* Obvious cleanup */
250 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
251 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
252 listRelease(c
->reply
);
255 /* Remove from the list of clients */
256 ln
= listSearchKey(server
.clients
,c
);
257 redisAssert(ln
!= NULL
);
258 listDelNode(server
.clients
,ln
);
259 /* Remove from the list of clients waiting for swapped keys, or ready
260 * to be restarted, but not yet woken up again. */
261 if (c
->flags
& REDIS_IO_WAIT
) {
262 redisAssert(server
.vm_enabled
);
263 if (listLength(c
->io_keys
) == 0) {
264 ln
= listSearchKey(server
.io_ready_clients
,c
);
266 /* When this client is waiting to be woken up (REDIS_IO_WAIT),
267 * it should be present in the list io_ready_clients */
268 redisAssert(ln
!= NULL
);
269 listDelNode(server
.io_ready_clients
,ln
);
271 while (listLength(c
->io_keys
)) {
272 ln
= listFirst(c
->io_keys
);
273 dontWaitForSwappedKey(c
,ln
->value
);
276 server
.vm_blocked_clients
--;
278 listRelease(c
->io_keys
);
279 /* Master/slave cleanup */
280 if (c
->flags
& REDIS_SLAVE
) {
281 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
283 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
284 ln
= listSearchKey(l
,c
);
285 redisAssert(ln
!= NULL
);
288 if (c
->flags
& REDIS_MASTER
) {
289 server
.master
= NULL
;
290 server
.replstate
= REDIS_REPL_CONNECT
;
295 freeClientMultiState(c
);
299 #define GLUEREPLY_UP_TO (1024)
300 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
302 char buf
[GLUEREPLY_UP_TO
];
307 listRewind(c
->reply
,&li
);
308 while((ln
= listNext(&li
))) {
312 objlen
= sdslen(o
->ptr
);
313 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
314 memcpy(buf
+copylen
,o
->ptr
,objlen
);
316 listDelNode(c
->reply
,ln
);
318 if (copylen
== 0) return;
322 /* Now the output buffer is empty, add the new single element */
323 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
324 listAddNodeHead(c
->reply
,o
);
327 void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
328 redisClient
*c
= privdata
;
329 int nwritten
= 0, totwritten
= 0, objlen
;
334 /* Use writev() if we have enough buffers to send */
335 if (!server
.glueoutputbuf
&&
336 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
337 !(c
->flags
& REDIS_MASTER
))
339 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
343 while(listLength(c
->reply
)) {
344 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
345 glueReplyBuffersIfNeeded(c
);
347 o
= listNodeValue(listFirst(c
->reply
));
348 objlen
= sdslen(o
->ptr
);
351 listDelNode(c
->reply
,listFirst(c
->reply
));
355 if (c
->flags
& REDIS_MASTER
) {
356 /* Don't reply to a master */
357 nwritten
= objlen
- c
->sentlen
;
359 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
360 if (nwritten
<= 0) break;
362 c
->sentlen
+= nwritten
;
363 totwritten
+= nwritten
;
364 /* If we fully sent the object on head go to the next one */
365 if (c
->sentlen
== objlen
) {
366 listDelNode(c
->reply
,listFirst(c
->reply
));
369 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
370 * bytes, in a single threaded server it's a good idea to serve
371 * other clients as well, even if a very large request comes from
372 * super fast link that is always able to accept data (in real world
373 * scenario think about 'KEYS *' against the loopback interfae) */
374 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
376 if (nwritten
== -1) {
377 if (errno
== EAGAIN
) {
380 redisLog(REDIS_VERBOSE
,
381 "Error writing to client: %s", strerror(errno
));
386 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
387 if (listLength(c
->reply
) == 0) {
389 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
393 void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
395 redisClient
*c
= privdata
;
396 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
398 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
404 while (listLength(c
->reply
)) {
409 /* fill-in the iov[] array */
410 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
411 o
= listNodeValue(node
);
412 objlen
= sdslen(o
->ptr
);
414 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
417 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
418 break; /* no more iovecs */
420 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
421 iov
[ion
].iov_len
= objlen
- offset
;
422 willwrite
+= objlen
- offset
;
423 offset
= 0; /* just for the first item */
430 /* write all collected blocks at once */
431 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
432 if (errno
!= EAGAIN
) {
433 redisLog(REDIS_VERBOSE
,
434 "Error writing to client: %s", strerror(errno
));
441 totwritten
+= nwritten
;
444 /* remove written robjs from c->reply */
445 while (nwritten
&& listLength(c
->reply
)) {
446 o
= listNodeValue(listFirst(c
->reply
));
447 objlen
= sdslen(o
->ptr
);
449 if(nwritten
>= objlen
- offset
) {
450 listDelNode(c
->reply
, listFirst(c
->reply
));
451 nwritten
-= objlen
- offset
;
455 c
->sentlen
+= nwritten
;
463 c
->lastinteraction
= time(NULL
);
465 if (listLength(c
->reply
) == 0) {
467 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
471 /* resetClient prepare the client to process the next command */
472 void resetClient(redisClient
*c
) {
478 void closeTimedoutClients(void) {
481 time_t now
= time(NULL
);
484 listRewind(server
.clients
,&li
);
485 while ((ln
= listNext(&li
)) != NULL
) {
486 c
= listNodeValue(ln
);
487 if (server
.maxidletime
&&
488 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
489 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
490 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
491 listLength(c
->pubsub_patterns
) == 0 &&
492 (now
- c
->lastinteraction
> server
.maxidletime
))
494 redisLog(REDIS_VERBOSE
,"Closing idle client");
496 } else if (c
->flags
& REDIS_BLOCKED
) {
497 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
498 addReply(c
,shared
.nullmultibulk
);
499 unblockClientWaitingData(c
);
505 void processInputBuffer(redisClient
*c
) {
507 /* Before to process the input buffer, make sure the client is not
508 * waitig for a blocking operation such as BLPOP. Note that the first
509 * iteration the client is never blocked, otherwise the processInputBuffer
510 * would not be called at all, but after the execution of the first commands
511 * in the input buffer the client may be blocked, and the "goto again"
512 * will try to reiterate. The following line will make it return asap. */
513 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
514 if (c
->bulklen
== -1) {
515 /* Read the first line of the query */
516 char *p
= strchr(c
->querybuf
,'\n');
524 c
->querybuf
= sdsempty();
525 querylen
= 1+(p
-(query
));
526 if (sdslen(query
) > querylen
) {
527 /* leave data after the first line of the query in the buffer */
528 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
530 *p
= '\0'; /* remove "\n" */
531 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
534 /* Now we can split the query in arguments */
535 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
538 if (c
->argv
) zfree(c
->argv
);
539 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
541 for (j
= 0; j
< argc
; j
++) {
542 if (sdslen(argv
[j
])) {
543 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
551 /* Execute the command. If the client is still valid
552 * after processCommand() return and there is something
553 * on the query buffer try to process the next command. */
554 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
556 /* Nothing to process, argc == 0. Just process the query
557 * buffer if it's not empty or return to the caller */
558 if (sdslen(c
->querybuf
)) goto again
;
561 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
562 redisLog(REDIS_VERBOSE
, "Client protocol error");
567 /* Bulk read handling. Note that if we are at this point
568 the client already sent a command terminated with a newline,
569 we are reading the bulk data that is actually the last
570 argument of the command. */
571 int qbl
= sdslen(c
->querybuf
);
573 if (c
->bulklen
<= qbl
) {
574 /* Copy everything but the final CRLF as final argument */
575 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
577 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
578 /* Process the command. If the client is still valid after
579 * the processing and there is more data in the buffer
580 * try to parse it. */
581 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
587 void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
588 redisClient
*c
= (redisClient
*) privdata
;
589 char buf
[REDIS_IOBUF_LEN
];
594 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
596 if (errno
== EAGAIN
) {
599 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
603 } else if (nread
== 0) {
604 redisLog(REDIS_VERBOSE
, "Client closed connection");
609 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
610 c
->lastinteraction
= time(NULL
);
614 processInputBuffer(c
);