]> git.saurik.com Git - redis.git/blob - src/networking.c
b26c20595decfad39d3f88938d74ebcee3b32b85
[redis.git] / src / networking.c
1 #include "redis.h"
2 #include <sys/uio.h>
3
4 void *dupClientReplyValue(void *o) {
5 incrRefCount((robj*)o);
6 return o;
7 }
8
9 int listMatchObjects(void *a, void *b) {
10 return equalStringObjects(a,b);
11 }
12
13 redisClient *createClient(int fd) {
14 redisClient *c = zmalloc(sizeof(redisClient));
15 c->bufpos = 0;
16
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. */
21 if (fd != -1) {
22 anetNonBlock(NULL,fd);
23 anetTcpNoDelay(NULL,fd);
24 if (aeCreateFileEvent(server.el,fd,AE_READABLE,
25 readQueryFromClient, c) == AE_ERR)
26 {
27 close(fd);
28 zfree(c);
29 return NULL;
30 }
31 }
32
33 selectDb(c,0);
34 c->fd = fd;
35 c->querybuf = sdsempty();
36 c->reqtype = 0;
37 c->argc = 0;
38 c->argv = NULL;
39 c->multibulklen = 0;
40 c->bulklen = -1;
41 c->sentlen = 0;
42 c->flags = 0;
43 c->lastinteraction = time(NULL);
44 c->authenticated = 0;
45 c->replstate = REDIS_REPL_NONE;
46 c->reply = listCreate();
47 listSetFreeMethod(c->reply,decrRefCount);
48 listSetDupMethod(c->reply,dupClientReplyValue);
49 c->bpop.keys = NULL;
50 c->bpop.count = 0;
51 c->bpop.timeout = 0;
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);
62 return c;
63 }
64
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;
74 return REDIS_OK;
75 }
76
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) {
80 robj *new, *cur;
81 listNode *ln;
82 redisAssert(listLength(reply) > 0);
83 ln = listLast(reply);
84 cur = listNodeValue(ln);
85 if (cur->refcount > 1) {
86 new = dupStringObject(cur);
87 decrRefCount(cur);
88 listNodeValue(ln) = new;
89 }
90 return listNodeValue(ln);
91 }
92
93 /* -----------------------------------------------------------------------------
94 * Low level functions to add more data to output buffers.
95 * -------------------------------------------------------------------------- */
96
97 int _addReplyToBuffer(redisClient *c, char *s, size_t len) {
98 size_t available = sizeof(c->buf)-c->bufpos;
99
100 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return REDIS_OK;
101
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;
105
106 /* Check that the buffer has enough space available for this string. */
107 if (len > available) return REDIS_ERR;
108
109 memcpy(c->buf+c->bufpos,s,len);
110 c->bufpos+=len;
111 return REDIS_OK;
112 }
113
114 void _addReplyObjectToList(redisClient *c, robj *o) {
115 robj *tail;
116
117 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
118
119 if (listLength(c->reply) == 0) {
120 incrRefCount(o);
121 listAddNodeTail(c->reply,o);
122 } else {
123 tail = listNodeValue(listLast(c->reply));
124
125 /* Append to this object when possible. */
126 if (tail->ptr != NULL &&
127 sdslen(tail->ptr)+sdslen(o->ptr) <= REDIS_REPLY_CHUNK_BYTES)
128 {
129 tail = dupLastObjectIfNeeded(c->reply);
130 tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr));
131 } else {
132 incrRefCount(o);
133 listAddNodeTail(c->reply,o);
134 }
135 }
136 }
137
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) {
141 robj *tail;
142
143 if (c->flags & REDIS_CLOSE_AFTER_REPLY) {
144 sdsfree(s);
145 return;
146 }
147
148 if (listLength(c->reply) == 0) {
149 listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
150 } else {
151 tail = listNodeValue(listLast(c->reply));
152
153 /* Append to this object when possible. */
154 if (tail->ptr != NULL &&
155 sdslen(tail->ptr)+sdslen(s) <= REDIS_REPLY_CHUNK_BYTES)
156 {
157 tail = dupLastObjectIfNeeded(c->reply);
158 tail->ptr = sdscatlen(tail->ptr,s,sdslen(s));
159 sdsfree(s);
160 } else {
161 listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
162 }
163 }
164 }
165
166 void _addReplyStringToList(redisClient *c, char *s, size_t len) {
167 robj *tail;
168
169 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
170
171 if (listLength(c->reply) == 0) {
172 listAddNodeTail(c->reply,createStringObject(s,len));
173 } else {
174 tail = listNodeValue(listLast(c->reply));
175
176 /* Append to this object when possible. */
177 if (tail->ptr != NULL &&
178 sdslen(tail->ptr)+len <= REDIS_REPLY_CHUNK_BYTES)
179 {
180 tail = dupLastObjectIfNeeded(c->reply);
181 tail->ptr = sdscatlen(tail->ptr,s,len);
182 } else {
183 listAddNodeTail(c->reply,createStringObject(s,len));
184 }
185 }
186 }
187
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 * -------------------------------------------------------------------------- */
192
193 void addReply(redisClient *c, robj *obj) {
194 if (_installWriteEvent(c) != REDIS_OK) return;
195
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.
199 *
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);
206 } else {
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);
213 decrRefCount(obj);
214 }
215 }
216
217 void addReplySds(redisClient *c, sds s) {
218 if (_installWriteEvent(c) != REDIS_OK) {
219 /* The caller expects the sds to be free'd. */
220 sdsfree(s);
221 return;
222 }
223 if (_addReplyToBuffer(c,s,sdslen(s)) == REDIS_OK) {
224 sdsfree(s);
225 } else {
226 /* This method free's the sds when it is no longer needed. */
227 _addReplySdsToList(c,s);
228 }
229 }
230
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);
235 }
236
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);
241 }
242
243 void addReplyError(redisClient *c, char *err) {
244 _addReplyError(c,err,strlen(err));
245 }
246
247 void addReplyErrorFormat(redisClient *c, const char *fmt, ...) {
248 va_list ap;
249 va_start(ap,fmt);
250 sds s = sdscatvprintf(sdsempty(),fmt,ap);
251 va_end(ap);
252 _addReplyError(c,s,sdslen(s));
253 sdsfree(s);
254 }
255
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);
260 }
261
262 void addReplyStatus(redisClient *c, char *status) {
263 _addReplyStatus(c,status,strlen(status));
264 }
265
266 void addReplyStatusFormat(redisClient *c, const char *fmt, ...) {
267 va_list ap;
268 va_start(ap,fmt);
269 sds s = sdscatvprintf(sdsempty(),fmt,ap);
270 va_end(ap);
271 _addReplyStatus(c,s,sdslen(s));
272 sdsfree(s);
273 }
274
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);
284 }
285
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;
289 robj *len, *next;
290
291 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
292 if (node == NULL) return;
293
294 len = listNodeValue(ln);
295 len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length);
296 if (ln->next != NULL) {
297 next = listNodeValue(ln->next);
298
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);
303 }
304 }
305 }
306
307 /* Add a duble as a bulk reply */
308 void addReplyDouble(redisClient *c, double d) {
309 char dbuf[128], sbuf[128];
310 int dlen, slen;
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);
314 }
315
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) {
319 char buf[128];
320 int len;
321 buf[0] = prefix;
322 len = ll2string(buf+1,sizeof(buf)-1,ll);
323 buf[len+1] = '\r';
324 buf[len+2] = '\n';
325 addReplyString(c,buf,len+3);
326 }
327
328 void addReplyLongLong(redisClient *c, long long ll) {
329 if (ll == 0)
330 addReply(c,shared.czero);
331 else if (ll == 1)
332 addReply(c,shared.cone);
333 else
334 _addReplyLongLong(c,ll,':');
335 }
336
337 void addReplyMultiBulkLen(redisClient *c, long length) {
338 _addReplyLongLong(c,length,'*');
339 }
340
341 /* Create the length prefix of a bulk reply, example: $2234 */
342 void addReplyBulkLen(redisClient *c, robj *obj) {
343 size_t len;
344
345 if (obj->encoding == REDIS_ENCODING_RAW) {
346 len = sdslen(obj->ptr);
347 } else {
348 long n = (long)obj->ptr;
349
350 /* Compute how many bytes will take this integer as a radix 10 string */
351 len = 1;
352 if (n < 0) {
353 len++;
354 n = -n;
355 }
356 while((n = n/10) != 0) {
357 len++;
358 }
359 }
360 _addReplyLongLong(c,len,'$');
361 }
362
363 /* Add a Redis Object as a bulk reply */
364 void addReplyBulk(redisClient *c, robj *obj) {
365 addReplyBulkLen(c,obj);
366 addReply(c,obj);
367 addReply(c,shared.crlf);
368 }
369
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);
375 }
376
377 /* Add a C nul term string as bulk reply */
378 void addReplyBulkCString(redisClient *c, char *s) {
379 if (s == NULL) {
380 addReply(c,shared.nullbulk);
381 } else {
382 addReplyBulkCBuffer(c,s,strlen(s));
383 }
384 }
385
386 /* Add a long long as a bulk reply */
387 void addReplyBulkLongLong(redisClient *c, long long ll) {
388 char buf[64];
389 int len;
390
391 len = ll2string(buf,64,ll);
392 addReplyBulkCBuffer(c,buf,len);
393 }
394
395 static void acceptCommonHandler(int fd) {
396 redisClient *c;
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 */
400 return;
401 }
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";
408
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... */
412 }
413 freeClient(c);
414 return;
415 }
416 server.stat_numconnections++;
417 }
418
419 void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
420 int cport, cfd;
421 char cip[128];
422 REDIS_NOTUSED(el);
423 REDIS_NOTUSED(mask);
424 REDIS_NOTUSED(privdata);
425
426 cfd = anetTcpAccept(server.neterr, fd, cip, &cport);
427 if (cfd == AE_ERR) {
428 redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr);
429 return;
430 }
431 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
432 acceptCommonHandler(cfd);
433 }
434
435 void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
436 int cfd;
437 REDIS_NOTUSED(el);
438 REDIS_NOTUSED(mask);
439 REDIS_NOTUSED(privdata);
440
441 cfd = anetUnixAccept(server.neterr, fd);
442 if (cfd == AE_ERR) {
443 redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr);
444 return;
445 }
446 redisLog(REDIS_VERBOSE,"Accepted connection to %s", server.unixsocket);
447 acceptCommonHandler(cfd);
448 }
449
450
451 static void freeClientArgv(redisClient *c) {
452 int j;
453 for (j = 0; j < c->argc; j++)
454 decrRefCount(c->argv[j]);
455 c->argc = 0;
456 }
457
458 void freeClient(redisClient *c) {
459 listNode *ln;
460
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);
467 c->querybuf = NULL;
468 if (c->flags & REDIS_BLOCKED)
469 unblockClientWaitingData(c);
470
471 /* UNWATCH all the keys */
472 unwatchAllKeys(c);
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);
483 freeClientArgv(c);
484 close(c->fd);
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);
495 }
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);
502
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);
507 } else {
508 while (listLength(c->io_keys)) {
509 ln = listFirst(c->io_keys);
510 dontWaitForSwappedKey(c,ln->value);
511 }
512 }
513 server.cache_blocked_clients--;
514 }
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)
520 close(c->repldbfd);
521 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
522 ln = listSearchKey(l,c);
523 redisAssert(ln != NULL);
524 listDelNode(l,ln);
525 }
526
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.
536 *
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);
544 }
545 }
546 }
547 /* Release memory */
548 zfree(c->argv);
549 freeClientMultiState(c);
550 zfree(c);
551 }
552
553 void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
554 redisClient *c = privdata;
555 int nwritten = 0, totwritten = 0, objlen;
556 robj *o;
557 REDIS_NOTUSED(el);
558 REDIS_NOTUSED(mask);
559
560 while(c->bufpos > 0 || listLength(c->reply)) {
561 if (c->bufpos > 0) {
562 if (c->flags & REDIS_MASTER) {
563 /* Don't reply to a master */
564 nwritten = c->bufpos - c->sentlen;
565 } else {
566 nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen);
567 if (nwritten <= 0) break;
568 }
569 c->sentlen += nwritten;
570 totwritten += nwritten;
571
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) {
575 c->bufpos = 0;
576 c->sentlen = 0;
577 }
578 } else {
579 o = listNodeValue(listFirst(c->reply));
580 objlen = sdslen(o->ptr);
581
582 if (objlen == 0) {
583 listDelNode(c->reply,listFirst(c->reply));
584 continue;
585 }
586
587 if (c->flags & REDIS_MASTER) {
588 /* Don't reply to a master */
589 nwritten = objlen - c->sentlen;
590 } else {
591 nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen);
592 if (nwritten <= 0) break;
593 }
594 c->sentlen += nwritten;
595 totwritten += nwritten;
596
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));
600 c->sentlen = 0;
601 }
602 }
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;
609 }
610 if (nwritten == -1) {
611 if (errno == EAGAIN) {
612 nwritten = 0;
613 } else {
614 redisLog(REDIS_VERBOSE,
615 "Error writing to client: %s", strerror(errno));
616 freeClient(c);
617 return;
618 }
619 }
620 if (totwritten > 0) c->lastinteraction = time(NULL);
621 if (listLength(c->reply) == 0) {
622 c->sentlen = 0;
623 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
624
625 /* Close connection after entire reply has been sent. */
626 if (c->flags & REDIS_CLOSE_AFTER_REPLY) freeClient(c);
627 }
628 }
629
630 /* resetClient prepare the client to process the next command */
631 void resetClient(redisClient *c) {
632 freeClientArgv(c);
633 c->reqtype = 0;
634 c->multibulklen = 0;
635 c->bulklen = -1;
636 }
637
638 void closeTimedoutClients(void) {
639 redisClient *c;
640 listNode *ln;
641 time_t now = time(NULL);
642 listIter li;
643
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))
654 {
655 redisLog(REDIS_VERBOSE,"Closing idle client");
656 freeClient(c);
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);
661 }
662 }
663 }
664 }
665
666 int processInlineBuffer(redisClient *c) {
667 char *newline = strstr(c->querybuf,"\r\n");
668 int argc, j;
669 sds *argv;
670 size_t querylen;
671
672 /* Nothing to do without a \r\n */
673 if (newline == NULL)
674 return REDIS_ERR;
675
676 /* Split the input buffer up to the \r\n */
677 querylen = newline-(c->querybuf);
678 argv = sdssplitlen(c->querybuf,querylen," ",1,&argc);
679
680 /* Leave data after the first line of the query in the buffer */
681 c->querybuf = sdsrange(c->querybuf,querylen+2,-1);
682
683 /* Setup argv array on client structure */
684 if (c->argv) zfree(c->argv);
685 c->argv = zmalloc(sizeof(robj*)*argc);
686
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]);
691 c->argc++;
692 } else {
693 sdsfree(argv[j]);
694 }
695 }
696 zfree(argv);
697 return REDIS_OK;
698 }
699
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);
705 }
706
707 int processMultibulkBuffer(redisClient *c) {
708 char *newline = NULL;
709 int pos = 0, ok;
710 long long ll;
711
712 if (c->multibulklen == 0) {
713 /* The client should have been reset */
714 redisAssert(c->argc == 0);
715
716 /* Multi bulk length cannot be read without a \r\n */
717 newline = strchr(c->querybuf,'\r');
718 if (newline == NULL)
719 return REDIS_ERR;
720
721 /* Buffer should also contain \n */
722 if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2))
723 return REDIS_ERR;
724
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);
732 return REDIS_ERR;
733 }
734
735 pos = (newline-c->querybuf)+2;
736 if (ll <= 0) {
737 c->querybuf = sdsrange(c->querybuf,pos,-1);
738 return REDIS_OK;
739 }
740
741 c->multibulklen = ll;
742
743 /* Setup argv array on client structure */
744 if (c->argv) zfree(c->argv);
745 c->argv = zmalloc(sizeof(robj*)*c->multibulklen);
746 }
747
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');
753 if (newline == NULL)
754 break;
755
756 /* Buffer should also contain \n */
757 if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2))
758 break;
759
760 if (c->querybuf[pos] != '$') {
761 addReplyErrorFormat(c,
762 "Protocol error: expected '$', got '%c'",
763 c->querybuf[pos]);
764 setProtocolError(c,pos);
765 return REDIS_ERR;
766 }
767
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);
772 return REDIS_ERR;
773 }
774
775 pos += newline-(c->querybuf+pos)+2;
776 c->bulklen = ll;
777 }
778
779 /* Read bulk argument */
780 if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) {
781 /* Not enough data (+2 == trailing \r\n) */
782 break;
783 } else {
784 c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen);
785 pos += c->bulklen+2;
786 c->bulklen = -1;
787 c->multibulklen--;
788 }
789 }
790
791 /* Trim to pos */
792 c->querybuf = sdsrange(c->querybuf,pos,-1);
793
794 /* We're done when c->multibulk == 0 */
795 if (c->multibulklen == 0) {
796 return REDIS_OK;
797 }
798 return REDIS_ERR;
799 }
800
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;
806
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;
811
812 /* Determine request type when unknown. */
813 if (!c->reqtype) {
814 if (c->querybuf[0] == '*') {
815 c->reqtype = REDIS_REQ_MULTIBULK;
816 } else {
817 c->reqtype = REDIS_REQ_INLINE;
818 }
819 }
820
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;
825 } else {
826 redisPanic("Unknown request type");
827 }
828
829 /* Multibulk processing could see a <= 0 length. */
830 if (c->argc == 0) {
831 resetClient(c);
832 } else {
833 /* Only reset the client when the command was executed. */
834 if (processCommand(c) == REDIS_OK)
835 resetClient(c);
836 }
837 }
838 }
839
840 void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
841 redisClient *c = (redisClient*) privdata;
842 char buf[REDIS_IOBUF_LEN];
843 int nread;
844 REDIS_NOTUSED(el);
845 REDIS_NOTUSED(mask);
846
847 nread = read(fd, buf, REDIS_IOBUF_LEN);
848 if (nread == -1) {
849 if (errno == EAGAIN) {
850 nread = 0;
851 } else {
852 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
853 freeClient(c);
854 return;
855 }
856 } else if (nread == 0) {
857 redisLog(REDIS_VERBOSE, "Client closed connection");
858 freeClient(c);
859 return;
860 }
861 if (nread) {
862 c->querybuf = sdscatlen(c->querybuf,buf,nread);
863 c->lastinteraction = time(NULL);
864 } else {
865 return;
866 }
867 processInputBuffer(c);
868 }
869
870 void getClientsMaxBuffers(unsigned long *longest_output_list,
871 unsigned long *biggest_input_buffer) {
872 redisClient *c;
873 listNode *ln;
874 listIter li;
875 unsigned long lol = 0, bib = 0;
876
877 listRewind(server.clients,&li);
878 while ((ln = listNext(&li)) != NULL) {
879 c = listNodeValue(ln);
880
881 if (listLength(c->reply) > lol) lol = listLength(c->reply);
882 if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf);
883 }
884 *longest_output_list = lol;
885 *biggest_input_buffer = bib;
886 }
887
888 void clientCommand(redisClient *c) {
889 listNode *ln;
890 listIter li;
891 redisClient *client;
892
893 if (!strcasecmp(c->argv[1]->ptr,"list") && c->argc == 2) {
894 sds o = sdsempty();
895 time_t now = time(NULL);
896
897 listRewind(server.clients,&li);
898 while ((ln = listNext(&li)) != NULL) {
899 char ip[32], flags[16], *p;
900 int port;
901
902 client = listNodeValue(ln);
903 if (anetPeerToString(client->fd,ip,&port) == -1) continue;
904 p = flags;
905 if (client->flags & REDIS_SLAVE) {
906 if (client->flags & REDIS_MONITOR)
907 *p++ = 'O';
908 else
909 *p++ = 'S';
910 }
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';
919 *p++ = '\0';
920 o = sdscatprintf(o,
921 "addr=%s:%d fd=%d idle=%ld flags=%s db=%d sub=%d psub=%d\n",
922 ip,port,client->fd,
923 (long)(now - client->lastinteraction),
924 flags,
925 client->db->id,
926 (int) dictSize(client->pubsub_channels),
927 (int) listLength(client->pubsub_patterns));
928 }
929 addReplyBulkCBuffer(c,o,sdslen(o));
930 sdsfree(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];
935 int port;
936
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);
942 if (c == client) {
943 client->flags |= REDIS_CLOSE_AFTER_REPLY;
944 } else {
945 freeClient(client);
946 }
947 return;
948 }
949 }
950 addReplyError(c,"No such client");
951 } else {
952 addReplyError(c, "Syntax error, try CLIENT (LIST | KILL ip:port)");
953 }
954 }