]> git.saurik.com Git - redis.git/blob - src/networking.c
make test depends on redis-check-aof as well.
[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 anetNonBlock(NULL,fd);
18 anetTcpNoDelay(NULL,fd);
19 if (aeCreateFileEvent(server.el,fd,AE_READABLE,
20 readQueryFromClient, c) == AE_ERR)
21 {
22 close(fd);
23 zfree(c);
24 return NULL;
25 }
26
27 selectDb(c,0);
28 c->fd = fd;
29 c->querybuf = sdsempty();
30 c->reqtype = 0;
31 c->argc = 0;
32 c->argv = NULL;
33 c->cmd = NULL;
34 c->multibulklen = 0;
35 c->bulklen = -1;
36 c->sentlen = 0;
37 c->flags = 0;
38 c->lastinteraction = time(NULL);
39 c->authenticated = 0;
40 c->replstate = REDIS_REPL_NONE;
41 c->reply = listCreate();
42 listSetFreeMethod(c->reply,decrRefCount);
43 listSetDupMethod(c->reply,dupClientReplyValue);
44 c->bpop.keys = NULL;
45 c->bpop.count = 0;
46 c->bpop.timeout = 0;
47 c->bpop.target = NULL;
48 c->io_keys = listCreate();
49 c->watched_keys = listCreate();
50 listSetFreeMethod(c->io_keys,decrRefCount);
51 c->pubsub_channels = dictCreate(&setDictType,NULL);
52 c->pubsub_patterns = listCreate();
53 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
54 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
55 listAddNodeTail(server.clients,c);
56 initClientMultiState(c);
57 return c;
58 }
59
60 /* Set the event loop to listen for write events on the client's socket.
61 * Typically gets called every time a reply is built. */
62 int _installWriteEvent(redisClient *c) {
63 if (c->fd <= 0) return REDIS_ERR;
64 if (c->bufpos == 0 && listLength(c->reply) == 0 &&
65 (c->replstate == REDIS_REPL_NONE ||
66 c->replstate == REDIS_REPL_ONLINE) &&
67 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
68 sendReplyToClient, c) == AE_ERR) return REDIS_ERR;
69 return REDIS_OK;
70 }
71
72 /* Create a duplicate of the last object in the reply list when
73 * it is not exclusively owned by the reply list. */
74 robj *dupLastObjectIfNeeded(list *reply) {
75 robj *new, *cur;
76 listNode *ln;
77 redisAssert(listLength(reply) > 0);
78 ln = listLast(reply);
79 cur = listNodeValue(ln);
80 if (cur->refcount > 1) {
81 new = dupStringObject(cur);
82 decrRefCount(cur);
83 listNodeValue(ln) = new;
84 }
85 return listNodeValue(ln);
86 }
87
88 /* -----------------------------------------------------------------------------
89 * Low level functions to add more data to output buffers.
90 * -------------------------------------------------------------------------- */
91
92 int _addReplyToBuffer(redisClient *c, char *s, size_t len) {
93 size_t available = sizeof(c->buf)-c->bufpos;
94
95 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return REDIS_OK;
96
97 /* If there already are entries in the reply list, we cannot
98 * add anything more to the static buffer. */
99 if (listLength(c->reply) > 0) return REDIS_ERR;
100
101 /* Check that the buffer has enough space available for this string. */
102 if (len > available) return REDIS_ERR;
103
104 memcpy(c->buf+c->bufpos,s,len);
105 c->bufpos+=len;
106 return REDIS_OK;
107 }
108
109 void _addReplyObjectToList(redisClient *c, robj *o) {
110 robj *tail;
111
112 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
113
114 if (listLength(c->reply) == 0) {
115 incrRefCount(o);
116 listAddNodeTail(c->reply,o);
117 } else {
118 tail = listNodeValue(listLast(c->reply));
119
120 /* Append to this object when possible. */
121 if (tail->ptr != NULL &&
122 sdslen(tail->ptr)+sdslen(o->ptr) <= REDIS_REPLY_CHUNK_BYTES)
123 {
124 tail = dupLastObjectIfNeeded(c->reply);
125 tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr));
126 } else {
127 incrRefCount(o);
128 listAddNodeTail(c->reply,o);
129 }
130 }
131 }
132
133 /* This method takes responsibility over the sds. When it is no longer
134 * needed it will be free'd, otherwise it ends up in a robj. */
135 void _addReplySdsToList(redisClient *c, sds s) {
136 robj *tail;
137
138 if (c->flags & REDIS_CLOSE_AFTER_REPLY) {
139 sdsfree(s);
140 return;
141 }
142
143 if (listLength(c->reply) == 0) {
144 listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
145 } else {
146 tail = listNodeValue(listLast(c->reply));
147
148 /* Append to this object when possible. */
149 if (tail->ptr != NULL &&
150 sdslen(tail->ptr)+sdslen(s) <= REDIS_REPLY_CHUNK_BYTES)
151 {
152 tail = dupLastObjectIfNeeded(c->reply);
153 tail->ptr = sdscatlen(tail->ptr,s,sdslen(s));
154 sdsfree(s);
155 } else {
156 listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
157 }
158 }
159 }
160
161 void _addReplyStringToList(redisClient *c, char *s, size_t len) {
162 robj *tail;
163
164 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
165
166 if (listLength(c->reply) == 0) {
167 listAddNodeTail(c->reply,createStringObject(s,len));
168 } else {
169 tail = listNodeValue(listLast(c->reply));
170
171 /* Append to this object when possible. */
172 if (tail->ptr != NULL &&
173 sdslen(tail->ptr)+len <= REDIS_REPLY_CHUNK_BYTES)
174 {
175 tail = dupLastObjectIfNeeded(c->reply);
176 tail->ptr = sdscatlen(tail->ptr,s,len);
177 } else {
178 listAddNodeTail(c->reply,createStringObject(s,len));
179 }
180 }
181 }
182
183 /* -----------------------------------------------------------------------------
184 * Higher level functions to queue data on the client output buffer.
185 * The following functions are the ones that commands implementations will call.
186 * -------------------------------------------------------------------------- */
187
188 void addReply(redisClient *c, robj *obj) {
189 if (_installWriteEvent(c) != REDIS_OK) return;
190
191 /* This is an important place where we can avoid copy-on-write
192 * when there is a saving child running, avoiding touching the
193 * refcount field of the object if it's not needed.
194 *
195 * If the encoding is RAW and there is room in the static buffer
196 * we'll be able to send the object to the client without
197 * messing with its page. */
198 if (obj->encoding == REDIS_ENCODING_RAW) {
199 if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
200 _addReplyObjectToList(c,obj);
201 } else {
202 /* FIXME: convert the long into string and use _addReplyToBuffer()
203 * instead of calling getDecodedObject. As this place in the
204 * code is too performance critical. */
205 obj = getDecodedObject(obj);
206 if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
207 _addReplyObjectToList(c,obj);
208 decrRefCount(obj);
209 }
210 }
211
212 void addReplySds(redisClient *c, sds s) {
213 if (_installWriteEvent(c) != REDIS_OK) {
214 /* The caller expects the sds to be free'd. */
215 sdsfree(s);
216 return;
217 }
218 if (_addReplyToBuffer(c,s,sdslen(s)) == REDIS_OK) {
219 sdsfree(s);
220 } else {
221 /* This method free's the sds when it is no longer needed. */
222 _addReplySdsToList(c,s);
223 }
224 }
225
226 void addReplyString(redisClient *c, char *s, size_t len) {
227 if (_installWriteEvent(c) != REDIS_OK) return;
228 if (_addReplyToBuffer(c,s,len) != REDIS_OK)
229 _addReplyStringToList(c,s,len);
230 }
231
232 void _addReplyError(redisClient *c, char *s, size_t len) {
233 addReplyString(c,"-ERR ",5);
234 addReplyString(c,s,len);
235 addReplyString(c,"\r\n",2);
236 }
237
238 void addReplyError(redisClient *c, char *err) {
239 _addReplyError(c,err,strlen(err));
240 }
241
242 void addReplyErrorFormat(redisClient *c, const char *fmt, ...) {
243 va_list ap;
244 va_start(ap,fmt);
245 sds s = sdscatvprintf(sdsempty(),fmt,ap);
246 va_end(ap);
247 _addReplyError(c,s,sdslen(s));
248 sdsfree(s);
249 }
250
251 void _addReplyStatus(redisClient *c, char *s, size_t len) {
252 addReplyString(c,"+",1);
253 addReplyString(c,s,len);
254 addReplyString(c,"\r\n",2);
255 }
256
257 void addReplyStatus(redisClient *c, char *status) {
258 _addReplyStatus(c,status,strlen(status));
259 }
260
261 void addReplyStatusFormat(redisClient *c, const char *fmt, ...) {
262 va_list ap;
263 va_start(ap,fmt);
264 sds s = sdscatvprintf(sdsempty(),fmt,ap);
265 va_end(ap);
266 _addReplyStatus(c,s,sdslen(s));
267 sdsfree(s);
268 }
269
270 /* Adds an empty object to the reply list that will contain the multi bulk
271 * length, which is not known when this function is called. */
272 void *addDeferredMultiBulkLength(redisClient *c) {
273 /* Note that we install the write event here even if the object is not
274 * ready to be sent, since we are sure that before returning to the
275 * event loop setDeferredMultiBulkLength() will be called. */
276 if (_installWriteEvent(c) != REDIS_OK) return NULL;
277 listAddNodeTail(c->reply,createObject(REDIS_STRING,NULL));
278 return listLast(c->reply);
279 }
280
281 /* Populate the length object and try glueing it to the next chunk. */
282 void setDeferredMultiBulkLength(redisClient *c, void *node, long length) {
283 listNode *ln = (listNode*)node;
284 robj *len, *next;
285
286 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
287 if (node == NULL) return;
288
289 len = listNodeValue(ln);
290 len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length);
291 if (ln->next != NULL) {
292 next = listNodeValue(ln->next);
293
294 /* Only glue when the next node is non-NULL (an sds in this case) */
295 if (next->ptr != NULL) {
296 len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr));
297 listDelNode(c->reply,ln->next);
298 }
299 }
300 }
301
302 /* Add a duble as a bulk reply */
303 void addReplyDouble(redisClient *c, double d) {
304 char dbuf[128], sbuf[128];
305 int dlen, slen;
306 dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d);
307 slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf);
308 addReplyString(c,sbuf,slen);
309 }
310
311 /* Add a long long as integer reply or bulk len / multi bulk count.
312 * Basically this is used to output <prefix><long long><crlf>. */
313 void _addReplyLongLong(redisClient *c, long long ll, char prefix) {
314 char buf[128];
315 int len;
316 buf[0] = prefix;
317 len = ll2string(buf+1,sizeof(buf)-1,ll);
318 buf[len+1] = '\r';
319 buf[len+2] = '\n';
320 addReplyString(c,buf,len+3);
321 }
322
323 void addReplyLongLong(redisClient *c, long long ll) {
324 if (ll == 0)
325 addReply(c,shared.czero);
326 else if (ll == 1)
327 addReply(c,shared.cone);
328 else
329 _addReplyLongLong(c,ll,':');
330 }
331
332 void addReplyMultiBulkLen(redisClient *c, long length) {
333 _addReplyLongLong(c,length,'*');
334 }
335
336 /* Create the length prefix of a bulk reply, example: $2234 */
337 void addReplyBulkLen(redisClient *c, robj *obj) {
338 size_t len;
339
340 if (obj->encoding == REDIS_ENCODING_RAW) {
341 len = sdslen(obj->ptr);
342 } else {
343 long n = (long)obj->ptr;
344
345 /* Compute how many bytes will take this integer as a radix 10 string */
346 len = 1;
347 if (n < 0) {
348 len++;
349 n = -n;
350 }
351 while((n = n/10) != 0) {
352 len++;
353 }
354 }
355 _addReplyLongLong(c,len,'$');
356 }
357
358 /* Add a Redis Object as a bulk reply */
359 void addReplyBulk(redisClient *c, robj *obj) {
360 addReplyBulkLen(c,obj);
361 addReply(c,obj);
362 addReply(c,shared.crlf);
363 }
364
365 /* Add a C buffer as bulk reply */
366 void addReplyBulkCBuffer(redisClient *c, void *p, size_t len) {
367 _addReplyLongLong(c,len,'$');
368 addReplyString(c,p,len);
369 addReply(c,shared.crlf);
370 }
371
372 /* Add a C nul term string as bulk reply */
373 void addReplyBulkCString(redisClient *c, char *s) {
374 if (s == NULL) {
375 addReply(c,shared.nullbulk);
376 } else {
377 addReplyBulkCBuffer(c,s,strlen(s));
378 }
379 }
380
381 /* Add a long long as a bulk reply */
382 void addReplyBulkLongLong(redisClient *c, long long ll) {
383 char buf[64];
384 int len;
385
386 len = ll2string(buf,64,ll);
387 addReplyBulkCBuffer(c,buf,len);
388 }
389
390 static void acceptCommonHandler(int fd) {
391 redisClient *c;
392 if ((c = createClient(fd)) == NULL) {
393 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
394 close(fd); /* May be already closed, just ingore errors */
395 return;
396 }
397 /* If maxclient directive is set and this is one client more... close the
398 * connection. Note that we create the client instead to check before
399 * for this condition, since now the socket is already set in nonblocking
400 * mode and we can send an error for free using the Kernel I/O */
401 if (server.maxclients && listLength(server.clients) > server.maxclients) {
402 char *err = "-ERR max number of clients reached\r\n";
403
404 /* That's a best effort error message, don't check write errors */
405 if (write(c->fd,err,strlen(err)) == -1) {
406 /* Nothing to do, Just to avoid the warning... */
407 }
408 freeClient(c);
409 return;
410 }
411 server.stat_numconnections++;
412 }
413
414 void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
415 int cport, cfd;
416 char cip[128];
417 REDIS_NOTUSED(el);
418 REDIS_NOTUSED(mask);
419 REDIS_NOTUSED(privdata);
420
421 cfd = anetTcpAccept(server.neterr, fd, cip, &cport);
422 if (cfd == AE_ERR) {
423 redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr);
424 return;
425 }
426 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
427 acceptCommonHandler(cfd);
428 }
429
430 void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
431 int cfd;
432 REDIS_NOTUSED(el);
433 REDIS_NOTUSED(mask);
434 REDIS_NOTUSED(privdata);
435
436 cfd = anetUnixAccept(server.neterr, fd);
437 if (cfd == AE_ERR) {
438 redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr);
439 return;
440 }
441 redisLog(REDIS_VERBOSE,"Accepted connection to %s", server.unixsocket);
442 acceptCommonHandler(cfd);
443 }
444
445
446 static void freeClientArgv(redisClient *c) {
447 int j;
448 for (j = 0; j < c->argc; j++)
449 decrRefCount(c->argv[j]);
450 c->argc = 0;
451 c->cmd = NULL;
452 }
453
454 void freeClient(redisClient *c) {
455 listNode *ln;
456
457 /* Note that if the client we are freeing is blocked into a blocking
458 * call, we have to set querybuf to NULL *before* to call
459 * unblockClientWaitingData() to avoid processInputBuffer() will get
460 * called. Also it is important to remove the file events after
461 * this, because this call adds the READABLE event. */
462 sdsfree(c->querybuf);
463 c->querybuf = NULL;
464 if (c->flags & REDIS_BLOCKED)
465 unblockClientWaitingData(c);
466
467 /* UNWATCH all the keys */
468 unwatchAllKeys(c);
469 listRelease(c->watched_keys);
470 /* Unsubscribe from all the pubsub channels */
471 pubsubUnsubscribeAllChannels(c,0);
472 pubsubUnsubscribeAllPatterns(c,0);
473 dictRelease(c->pubsub_channels);
474 listRelease(c->pubsub_patterns);
475 /* Obvious cleanup */
476 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
477 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
478 listRelease(c->reply);
479 freeClientArgv(c);
480 close(c->fd);
481 /* Remove from the list of clients */
482 ln = listSearchKey(server.clients,c);
483 redisAssert(ln != NULL);
484 listDelNode(server.clients,ln);
485 /* When client was just unblocked because of a blocking operation,
486 * remove it from the list with unblocked clients. */
487 if (c->flags & REDIS_UNBLOCKED) {
488 ln = listSearchKey(server.unblocked_clients,c);
489 redisAssert(ln != NULL);
490 listDelNode(server.unblocked_clients,ln);
491 }
492 listRelease(c->io_keys);
493 /* Master/slave cleanup.
494 * Case 1: we lost the connection with a slave. */
495 if (c->flags & REDIS_SLAVE) {
496 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
497 close(c->repldbfd);
498 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
499 ln = listSearchKey(l,c);
500 redisAssert(ln != NULL);
501 listDelNode(l,ln);
502 }
503
504 /* Case 2: we lost the connection with the master. */
505 if (c->flags & REDIS_MASTER) {
506 server.master = NULL;
507 server.replstate = REDIS_REPL_CONNECT;
508 server.repl_down_since = time(NULL);
509 /* Since we lost the connection with the master, we should also
510 * close the connection with all our slaves if we have any, so
511 * when we'll resync with the master the other slaves will sync again
512 * with us as well. Note that also when the slave is not connected
513 * to the master it will keep refusing connections by other slaves.
514 *
515 * We do this only if server.masterhost != NULL. If it is NULL this
516 * means the user called SLAVEOF NO ONE and we are freeing our
517 * link with the master, so no need to close link with slaves. */
518 if (server.masterhost != NULL) {
519 while (listLength(server.slaves)) {
520 ln = listFirst(server.slaves);
521 freeClient((redisClient*)ln->value);
522 }
523 }
524 }
525 /* Release memory */
526 zfree(c->argv);
527 freeClientMultiState(c);
528 zfree(c);
529 }
530
531 void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
532 redisClient *c = privdata;
533 int nwritten = 0, totwritten = 0, objlen;
534 robj *o;
535 REDIS_NOTUSED(el);
536 REDIS_NOTUSED(mask);
537
538 while(c->bufpos > 0 || listLength(c->reply)) {
539 if (c->bufpos > 0) {
540 if (c->flags & REDIS_MASTER) {
541 /* Don't reply to a master */
542 nwritten = c->bufpos - c->sentlen;
543 } else {
544 nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen);
545 if (nwritten <= 0) break;
546 }
547 c->sentlen += nwritten;
548 totwritten += nwritten;
549
550 /* If the buffer was sent, set bufpos to zero to continue with
551 * the remainder of the reply. */
552 if (c->sentlen == c->bufpos) {
553 c->bufpos = 0;
554 c->sentlen = 0;
555 }
556 } else {
557 o = listNodeValue(listFirst(c->reply));
558 objlen = sdslen(o->ptr);
559
560 if (objlen == 0) {
561 listDelNode(c->reply,listFirst(c->reply));
562 continue;
563 }
564
565 if (c->flags & REDIS_MASTER) {
566 /* Don't reply to a master */
567 nwritten = objlen - c->sentlen;
568 } else {
569 nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen);
570 if (nwritten <= 0) break;
571 }
572 c->sentlen += nwritten;
573 totwritten += nwritten;
574
575 /* If we fully sent the object on head go to the next one */
576 if (c->sentlen == objlen) {
577 listDelNode(c->reply,listFirst(c->reply));
578 c->sentlen = 0;
579 }
580 }
581 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
582 * bytes, in a single threaded server it's a good idea to serve
583 * other clients as well, even if a very large request comes from
584 * super fast link that is always able to accept data (in real world
585 * scenario think about 'KEYS *' against the loopback interfae) */
586 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
587 }
588 if (nwritten == -1) {
589 if (errno == EAGAIN) {
590 nwritten = 0;
591 } else {
592 redisLog(REDIS_VERBOSE,
593 "Error writing to client: %s", strerror(errno));
594 freeClient(c);
595 return;
596 }
597 }
598 if (totwritten > 0) c->lastinteraction = time(NULL);
599 if (listLength(c->reply) == 0) {
600 c->sentlen = 0;
601 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
602
603 /* Close connection after entire reply has been sent. */
604 if (c->flags & REDIS_CLOSE_AFTER_REPLY) freeClient(c);
605 }
606 }
607
608 /* resetClient prepare the client to process the next command */
609 void resetClient(redisClient *c) {
610 freeClientArgv(c);
611 c->reqtype = 0;
612 c->multibulklen = 0;
613 c->bulklen = -1;
614 }
615
616 void closeTimedoutClients(void) {
617 redisClient *c;
618 listNode *ln;
619 time_t now = time(NULL);
620 listIter li;
621
622 listRewind(server.clients,&li);
623 while ((ln = listNext(&li)) != NULL) {
624 c = listNodeValue(ln);
625 if (server.maxidletime &&
626 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
627 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
628 !(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */
629 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
630 listLength(c->pubsub_patterns) == 0 &&
631 (now - c->lastinteraction > server.maxidletime))
632 {
633 redisLog(REDIS_VERBOSE,"Closing idle client");
634 freeClient(c);
635 } else if (c->flags & REDIS_BLOCKED) {
636 if (c->bpop.timeout != 0 && c->bpop.timeout < now) {
637 addReply(c,shared.nullmultibulk);
638 unblockClientWaitingData(c);
639 }
640 }
641 }
642 }
643
644 int processInlineBuffer(redisClient *c) {
645 char *newline = strstr(c->querybuf,"\r\n");
646 int argc, j;
647 sds *argv;
648 size_t querylen;
649
650 /* Nothing to do without a \r\n */
651 if (newline == NULL)
652 return REDIS_ERR;
653
654 /* Split the input buffer up to the \r\n */
655 querylen = newline-(c->querybuf);
656 argv = sdssplitlen(c->querybuf,querylen," ",1,&argc);
657
658 /* Leave data after the first line of the query in the buffer */
659 c->querybuf = sdsrange(c->querybuf,querylen+2,-1);
660
661 /* Setup argv array on client structure */
662 if (c->argv) zfree(c->argv);
663 c->argv = zmalloc(sizeof(robj*)*argc);
664
665 /* Create redis objects for all arguments. */
666 for (c->argc = 0, j = 0; j < argc; j++) {
667 if (sdslen(argv[j])) {
668 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
669 c->argc++;
670 } else {
671 sdsfree(argv[j]);
672 }
673 }
674 zfree(argv);
675 return REDIS_OK;
676 }
677
678 /* Helper function. Trims query buffer to make the function that processes
679 * multi bulk requests idempotent. */
680 static void setProtocolError(redisClient *c, int pos) {
681 c->flags |= REDIS_CLOSE_AFTER_REPLY;
682 c->querybuf = sdsrange(c->querybuf,pos,-1);
683 }
684
685 int processMultibulkBuffer(redisClient *c) {
686 char *newline = NULL;
687 int pos = 0, ok;
688 long long ll;
689
690 if (c->multibulklen == 0) {
691 /* The client should have been reset */
692 redisAssert(c->argc == 0);
693
694 /* Multi bulk length cannot be read without a \r\n */
695 newline = strchr(c->querybuf,'\r');
696 if (newline == NULL)
697 return REDIS_ERR;
698
699 /* Buffer should also contain \n */
700 if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2))
701 return REDIS_ERR;
702
703 /* We know for sure there is a whole line since newline != NULL,
704 * so go ahead and find out the multi bulk length. */
705 redisAssert(c->querybuf[0] == '*');
706 ok = string2ll(c->querybuf+1,newline-(c->querybuf+1),&ll);
707 if (!ok || ll > 1024*1024) {
708 addReplyError(c,"Protocol error: invalid multibulk length");
709 setProtocolError(c,pos);
710 return REDIS_ERR;
711 }
712
713 pos = (newline-c->querybuf)+2;
714 if (ll <= 0) {
715 c->querybuf = sdsrange(c->querybuf,pos,-1);
716 return REDIS_OK;
717 }
718
719 c->multibulklen = ll;
720
721 /* Setup argv array on client structure */
722 if (c->argv) zfree(c->argv);
723 c->argv = zmalloc(sizeof(robj*)*c->multibulklen);
724 }
725
726 redisAssert(c->multibulklen > 0);
727 while(c->multibulklen) {
728 /* Read bulk length if unknown */
729 if (c->bulklen == -1) {
730 newline = strchr(c->querybuf+pos,'\r');
731 if (newline == NULL)
732 break;
733
734 /* Buffer should also contain \n */
735 if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2))
736 break;
737
738 if (c->querybuf[pos] != '$') {
739 addReplyErrorFormat(c,
740 "Protocol error: expected '$', got '%c'",
741 c->querybuf[pos]);
742 setProtocolError(c,pos);
743 return REDIS_ERR;
744 }
745
746 ok = string2ll(c->querybuf+pos+1,newline-(c->querybuf+pos+1),&ll);
747 if (!ok || ll < 0 || ll > 512*1024*1024) {
748 addReplyError(c,"Protocol error: invalid bulk length");
749 setProtocolError(c,pos);
750 return REDIS_ERR;
751 }
752
753 pos += newline-(c->querybuf+pos)+2;
754 c->bulklen = ll;
755 }
756
757 /* Read bulk argument */
758 if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) {
759 /* Not enough data (+2 == trailing \r\n) */
760 break;
761 } else {
762 c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen);
763 pos += c->bulklen+2;
764 c->bulklen = -1;
765 c->multibulklen--;
766 }
767 }
768
769 /* Trim to pos */
770 c->querybuf = sdsrange(c->querybuf,pos,-1);
771
772 /* We're done when c->multibulk == 0 */
773 if (c->multibulklen == 0) {
774 return REDIS_OK;
775 }
776 return REDIS_ERR;
777 }
778
779 void processInputBuffer(redisClient *c) {
780 /* Keep processing while there is something in the input buffer */
781 while(sdslen(c->querybuf)) {
782 /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
783 * written to the client. Make sure to not let the reply grow after
784 * this flag has been set (i.e. don't process more commands). */
785 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
786
787 /* Determine request type when unknown. */
788 if (!c->reqtype) {
789 if (c->querybuf[0] == '*') {
790 c->reqtype = REDIS_REQ_MULTIBULK;
791 } else {
792 c->reqtype = REDIS_REQ_INLINE;
793 }
794 }
795
796 if (c->reqtype == REDIS_REQ_INLINE) {
797 if (processInlineBuffer(c) != REDIS_OK) break;
798 } else if (c->reqtype == REDIS_REQ_MULTIBULK) {
799 if (processMultibulkBuffer(c) != REDIS_OK) break;
800 } else {
801 redisPanic("Unknown request type");
802 }
803
804 /* Multibulk processing could see a <= 0 length. */
805 if (c->argc == 0) {
806 resetClient(c);
807 } else {
808 /* Only reset the client when the command was executed. */
809 if (processCommand(c) == REDIS_OK)
810 resetClient(c);
811 }
812 }
813 }
814
815 void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
816 redisClient *c = (redisClient*) privdata;
817 char buf[REDIS_IOBUF_LEN];
818 int nread;
819 REDIS_NOTUSED(el);
820 REDIS_NOTUSED(mask);
821
822 nread = read(fd, buf, REDIS_IOBUF_LEN);
823 if (nread == -1) {
824 if (errno == EAGAIN) {
825 nread = 0;
826 } else {
827 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
828 freeClient(c);
829 return;
830 }
831 } else if (nread == 0) {
832 redisLog(REDIS_VERBOSE, "Client closed connection");
833 freeClient(c);
834 return;
835 }
836 if (nread) {
837 c->querybuf = sdscatlen(c->querybuf,buf,nread);
838 c->lastinteraction = time(NULL);
839 } else {
840 return;
841 }
842 processInputBuffer(c);
843 }
844
845 void getClientsMaxBuffers(unsigned long *longest_output_list,
846 unsigned long *biggest_input_buffer) {
847 redisClient *c;
848 listNode *ln;
849 listIter li;
850 unsigned long lol = 0, bib = 0;
851
852 listRewind(server.clients,&li);
853 while ((ln = listNext(&li)) != NULL) {
854 c = listNodeValue(ln);
855
856 if (listLength(c->reply) > lol) lol = listLength(c->reply);
857 if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf);
858 }
859 *longest_output_list = lol;
860 *biggest_input_buffer = bib;
861 }
862
863 void clientCommand(redisClient *c) {
864 listNode *ln;
865 listIter li;
866 redisClient *client;
867
868 if (!strcasecmp(c->argv[1]->ptr,"list") && c->argc == 2) {
869 sds o = sdsempty();
870 time_t now = time(NULL);
871
872 listRewind(server.clients,&li);
873 while ((ln = listNext(&li)) != NULL) {
874 char ip[32], flags[16], *p;
875 int port;
876
877 client = listNodeValue(ln);
878 if (anetPeerToString(client->fd,ip,&port) == -1) continue;
879 p = flags;
880 if (client->flags & REDIS_SLAVE) {
881 if (client->flags & REDIS_MONITOR)
882 *p++ = 'O';
883 else
884 *p++ = 'S';
885 }
886 if (client->flags & REDIS_MASTER) *p++ = 'M';
887 if (p == flags) *p++ = 'N';
888 if (client->flags & REDIS_MULTI) *p++ = 'x';
889 if (client->flags & REDIS_BLOCKED) *p++ = 'b';
890 if (client->flags & REDIS_DIRTY_CAS) *p++ = 'd';
891 if (client->flags & REDIS_CLOSE_AFTER_REPLY) *p++ = 'c';
892 if (client->flags & REDIS_UNBLOCKED) *p++ = 'u';
893 *p++ = '\0';
894 o = sdscatprintf(o,
895 "addr=%s:%d fd=%d idle=%ld flags=%s db=%d sub=%d psub=%d\n",
896 ip,port,client->fd,
897 (long)(now - client->lastinteraction),
898 flags,
899 client->db->id,
900 (int) dictSize(client->pubsub_channels),
901 (int) listLength(client->pubsub_patterns));
902 }
903 addReplyBulkCBuffer(c,o,sdslen(o));
904 sdsfree(o);
905 } else if (!strcasecmp(c->argv[1]->ptr,"kill") && c->argc == 3) {
906 listRewind(server.clients,&li);
907 while ((ln = listNext(&li)) != NULL) {
908 char ip[32], addr[64];
909 int port;
910
911 client = listNodeValue(ln);
912 if (anetPeerToString(client->fd,ip,&port) == -1) continue;
913 snprintf(addr,sizeof(addr),"%s:%d",ip,port);
914 if (strcmp(addr,c->argv[2]->ptr) == 0) {
915 addReply(c,shared.ok);
916 if (c == client) {
917 client->flags |= REDIS_CLOSE_AFTER_REPLY;
918 } else {
919 freeClient(client);
920 }
921 return;
922 }
923 }
924 addReplyError(c,"No such client");
925 } else {
926 addReplyError(c, "Syntax error, try CLIENT (LIST | KILL ip:port)");
927 }
928 }
929
930 void rewriteClientCommandVector(redisClient *c, int argc, ...) {
931 va_list ap;
932 int j;
933 robj **argv; /* The new argument vector */
934
935 argv = zmalloc(sizeof(robj*)*argc);
936 va_start(ap,argc);
937 for (j = 0; j < argc; j++) {
938 robj *a;
939
940 a = va_arg(ap, robj*);
941 argv[j] = a;
942 incrRefCount(a);
943 }
944 /* We free the objects in the original vector at the end, so we are
945 * sure that if the same objects are reused in the new vector the
946 * refcount gets incremented before it gets decremented. */
947 for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]);
948 zfree(c->argv);
949 /* Replace argv and argc with our new versions. */
950 c->argv = argv;
951 c->argc = argc;
952 c->cmd = lookupCommand(c->argv[0]->ptr);
953 redisAssert(c->cmd != NULL);
954 va_end(ap);
955 }