]> git.saurik.com Git - redis.git/blame_incremental - src/networking.c
Fixed issue #503. MONITOR + QUIT could crash the server, there are actually other...
[redis.git] / src / networking.c
... / ...
CommitLineData
1#include "redis.h"
2#include <sys/uio.h>
3
4void *dupClientReplyValue(void *o) {
5 incrRefCount((robj*)o);
6 return o;
7}
8
9int listMatchObjects(void *a, void *b) {
10 return equalStringObjects(a,b);
11}
12
13redisClient *createClient(int fd) {
14 redisClient *c = zmalloc(sizeof(redisClient));
15 c->bufpos = 0;
16
17 anetNonBlock(NULL,fd);
18 anetTcpNoDelay(NULL,fd);
19 if (!c) return NULL;
20 if (aeCreateFileEvent(server.el,fd,AE_READABLE,
21 readQueryFromClient, c) == AE_ERR)
22 {
23 close(fd);
24 zfree(c);
25 return NULL;
26 }
27
28 selectDb(c,0);
29 c->fd = fd;
30 c->querybuf = sdsempty();
31 c->reqtype = 0;
32 c->argc = 0;
33 c->argv = 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. */
62int _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. */
74robj *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
92int _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
109void _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. */
135void _addReplySdsToList(redisClient *c, sds s) {
136 robj *tail;
137
138 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
139
140 if (listLength(c->reply) == 0) {
141 listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
142 } else {
143 tail = listNodeValue(listLast(c->reply));
144
145 /* Append to this object when possible. */
146 if (tail->ptr != NULL &&
147 sdslen(tail->ptr)+sdslen(s) <= REDIS_REPLY_CHUNK_BYTES)
148 {
149 tail = dupLastObjectIfNeeded(c->reply);
150 tail->ptr = sdscatlen(tail->ptr,s,sdslen(s));
151 sdsfree(s);
152 } else {
153 listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
154 }
155 }
156}
157
158void _addReplyStringToList(redisClient *c, char *s, size_t len) {
159 robj *tail;
160
161 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
162
163 if (listLength(c->reply) == 0) {
164 listAddNodeTail(c->reply,createStringObject(s,len));
165 } else {
166 tail = listNodeValue(listLast(c->reply));
167
168 /* Append to this object when possible. */
169 if (tail->ptr != NULL &&
170 sdslen(tail->ptr)+len <= REDIS_REPLY_CHUNK_BYTES)
171 {
172 tail = dupLastObjectIfNeeded(c->reply);
173 tail->ptr = sdscatlen(tail->ptr,s,len);
174 } else {
175 listAddNodeTail(c->reply,createStringObject(s,len));
176 }
177 }
178}
179
180/* -----------------------------------------------------------------------------
181 * Higher level functions to queue data on the client output buffer.
182 * The following functions are the ones that commands implementations will call.
183 * -------------------------------------------------------------------------- */
184
185void addReply(redisClient *c, robj *obj) {
186 if (_installWriteEvent(c) != REDIS_OK) return;
187
188 /* This is an important place where we can avoid copy-on-write
189 * when there is a saving child running, avoiding touching the
190 * refcount field of the object if it's not needed.
191 *
192 * If the encoding is RAW and there is room in the static buffer
193 * we'll be able to send the object to the client without
194 * messing with its page. */
195 if (obj->encoding == REDIS_ENCODING_RAW) {
196 if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
197 _addReplyObjectToList(c,obj);
198 } else {
199 /* FIXME: convert the long into string and use _addReplyToBuffer()
200 * instead of calling getDecodedObject. As this place in the
201 * code is too performance critical. */
202 obj = getDecodedObject(obj);
203 if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
204 _addReplyObjectToList(c,obj);
205 decrRefCount(obj);
206 }
207}
208
209void addReplySds(redisClient *c, sds s) {
210 if (_installWriteEvent(c) != REDIS_OK) {
211 /* The caller expects the sds to be free'd. */
212 sdsfree(s);
213 return;
214 }
215 if (_addReplyToBuffer(c,s,sdslen(s)) == REDIS_OK) {
216 sdsfree(s);
217 } else {
218 /* This method free's the sds when it is no longer needed. */
219 _addReplySdsToList(c,s);
220 }
221}
222
223void addReplyString(redisClient *c, char *s, size_t len) {
224 if (_installWriteEvent(c) != REDIS_OK) return;
225 if (_addReplyToBuffer(c,s,len) != REDIS_OK)
226 _addReplyStringToList(c,s,len);
227}
228
229void _addReplyError(redisClient *c, char *s, size_t len) {
230 addReplyString(c,"-ERR ",5);
231 addReplyString(c,s,len);
232 addReplyString(c,"\r\n",2);
233}
234
235void addReplyError(redisClient *c, char *err) {
236 _addReplyError(c,err,strlen(err));
237}
238
239void addReplyErrorFormat(redisClient *c, const char *fmt, ...) {
240 va_list ap;
241 va_start(ap,fmt);
242 sds s = sdscatvprintf(sdsempty(),fmt,ap);
243 va_end(ap);
244 _addReplyError(c,s,sdslen(s));
245 sdsfree(s);
246}
247
248void _addReplyStatus(redisClient *c, char *s, size_t len) {
249 addReplyString(c,"+",1);
250 addReplyString(c,s,len);
251 addReplyString(c,"\r\n",2);
252}
253
254void addReplyStatus(redisClient *c, char *status) {
255 _addReplyStatus(c,status,strlen(status));
256}
257
258void addReplyStatusFormat(redisClient *c, const char *fmt, ...) {
259 va_list ap;
260 va_start(ap,fmt);
261 sds s = sdscatvprintf(sdsempty(),fmt,ap);
262 va_end(ap);
263 _addReplyStatus(c,s,sdslen(s));
264 sdsfree(s);
265}
266
267/* Adds an empty object to the reply list that will contain the multi bulk
268 * length, which is not known when this function is called. */
269void *addDeferredMultiBulkLength(redisClient *c) {
270 /* Note that we install the write event here even if the object is not
271 * ready to be sent, since we are sure that before returning to the
272 * event loop setDeferredMultiBulkLength() will be called. */
273 if (_installWriteEvent(c) != REDIS_OK) return NULL;
274 listAddNodeTail(c->reply,createObject(REDIS_STRING,NULL));
275 return listLast(c->reply);
276}
277
278/* Populate the length object and try glueing it to the next chunk. */
279void setDeferredMultiBulkLength(redisClient *c, void *node, long length) {
280 listNode *ln = (listNode*)node;
281 robj *len, *next;
282
283 /* Abort when *node is NULL (see addDeferredMultiBulkLength). */
284 if (node == NULL) return;
285
286 len = listNodeValue(ln);
287 len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length);
288 if (ln->next != NULL) {
289 next = listNodeValue(ln->next);
290
291 /* Only glue when the next node is non-NULL (an sds in this case) */
292 if (next->ptr != NULL) {
293 len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr));
294 listDelNode(c->reply,ln->next);
295 }
296 }
297}
298
299/* Add a duble as a bulk reply */
300void addReplyDouble(redisClient *c, double d) {
301 char dbuf[128], sbuf[128];
302 int dlen, slen;
303 dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d);
304 slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf);
305 addReplyString(c,sbuf,slen);
306}
307
308/* Add a long long as integer reply or bulk len / multi bulk count.
309 * Basically this is used to output <prefix><long long><crlf>. */
310void _addReplyLongLong(redisClient *c, long long ll, char prefix) {
311 char buf[128];
312 int len;
313 buf[0] = prefix;
314 len = ll2string(buf+1,sizeof(buf)-1,ll);
315 buf[len+1] = '\r';
316 buf[len+2] = '\n';
317 addReplyString(c,buf,len+3);
318}
319
320void addReplyLongLong(redisClient *c, long long ll) {
321 _addReplyLongLong(c,ll,':');
322}
323
324void addReplyMultiBulkLen(redisClient *c, long length) {
325 _addReplyLongLong(c,length,'*');
326}
327
328/* Create the length prefix of a bulk reply, example: $2234 */
329void addReplyBulkLen(redisClient *c, robj *obj) {
330 size_t len;
331
332 if (obj->encoding == REDIS_ENCODING_RAW) {
333 len = sdslen(obj->ptr);
334 } else {
335 long n = (long)obj->ptr;
336
337 /* Compute how many bytes will take this integer as a radix 10 string */
338 len = 1;
339 if (n < 0) {
340 len++;
341 n = -n;
342 }
343 while((n = n/10) != 0) {
344 len++;
345 }
346 }
347 _addReplyLongLong(c,len,'$');
348}
349
350/* Add a Redis Object as a bulk reply */
351void addReplyBulk(redisClient *c, robj *obj) {
352 addReplyBulkLen(c,obj);
353 addReply(c,obj);
354 addReply(c,shared.crlf);
355}
356
357/* Add a C buffer as bulk reply */
358void addReplyBulkCBuffer(redisClient *c, void *p, size_t len) {
359 _addReplyLongLong(c,len,'$');
360 addReplyString(c,p,len);
361 addReply(c,shared.crlf);
362}
363
364/* Add a C nul term string as bulk reply */
365void addReplyBulkCString(redisClient *c, char *s) {
366 if (s == NULL) {
367 addReply(c,shared.nullbulk);
368 } else {
369 addReplyBulkCBuffer(c,s,strlen(s));
370 }
371}
372
373/* Add a long long as a bulk reply */
374void addReplyBulkLongLong(redisClient *c, long long ll) {
375 char buf[64];
376 int len;
377
378 len = ll2string(buf,64,ll);
379 addReplyBulkCBuffer(c,buf,len);
380}
381
382static void acceptCommonHandler(int fd) {
383 redisClient *c;
384 if ((c = createClient(fd)) == NULL) {
385 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
386 close(fd); /* May be already closed, just ingore errors */
387 return;
388 }
389 /* If maxclient directive is set and this is one client more... close the
390 * connection. Note that we create the client instead to check before
391 * for this condition, since now the socket is already set in nonblocking
392 * mode and we can send an error for free using the Kernel I/O */
393 if (server.maxclients && listLength(server.clients) > server.maxclients) {
394 char *err = "-ERR max number of clients reached\r\n";
395
396 /* That's a best effort error message, don't check write errors */
397 if (write(c->fd,err,strlen(err)) == -1) {
398 /* Nothing to do, Just to avoid the warning... */
399 }
400 freeClient(c);
401 return;
402 }
403 server.stat_numconnections++;
404}
405
406void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
407 int cport, cfd;
408 char cip[128];
409 REDIS_NOTUSED(el);
410 REDIS_NOTUSED(mask);
411 REDIS_NOTUSED(privdata);
412
413 cfd = anetTcpAccept(server.neterr, fd, cip, &cport);
414 if (cfd == AE_ERR) {
415 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
416 return;
417 }
418 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
419 acceptCommonHandler(cfd);
420}
421
422void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
423 int cfd;
424 REDIS_NOTUSED(el);
425 REDIS_NOTUSED(mask);
426 REDIS_NOTUSED(privdata);
427
428 cfd = anetUnixAccept(server.neterr, fd);
429 if (cfd == AE_ERR) {
430 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
431 return;
432 }
433 redisLog(REDIS_VERBOSE,"Accepted connection to %s", server.unixsocket);
434 acceptCommonHandler(cfd);
435}
436
437
438static void freeClientArgv(redisClient *c) {
439 int j;
440 for (j = 0; j < c->argc; j++)
441 decrRefCount(c->argv[j]);
442 c->argc = 0;
443}
444
445void freeClient(redisClient *c) {
446 listNode *ln;
447
448 /* Note that if the client we are freeing is blocked into a blocking
449 * call, we have to set querybuf to NULL *before* to call
450 * unblockClientWaitingData() to avoid processInputBuffer() will get
451 * called. Also it is important to remove the file events after
452 * this, because this call adds the READABLE event. */
453 sdsfree(c->querybuf);
454 c->querybuf = NULL;
455 if (c->flags & REDIS_BLOCKED)
456 unblockClientWaitingData(c);
457
458 /* UNWATCH all the keys */
459 unwatchAllKeys(c);
460 listRelease(c->watched_keys);
461 /* Unsubscribe from all the pubsub channels */
462 pubsubUnsubscribeAllChannels(c,0);
463 pubsubUnsubscribeAllPatterns(c,0);
464 dictRelease(c->pubsub_channels);
465 listRelease(c->pubsub_patterns);
466 /* Obvious cleanup */
467 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
468 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
469 listRelease(c->reply);
470 freeClientArgv(c);
471 close(c->fd);
472 /* Remove from the list of clients */
473 ln = listSearchKey(server.clients,c);
474 redisAssert(ln != NULL);
475 listDelNode(server.clients,ln);
476 /* When client was just unblocked because of a blocking operation,
477 * remove it from the list with unblocked clients. */
478 if (c->flags & REDIS_UNBLOCKED) {
479 ln = listSearchKey(server.unblocked_clients,c);
480 redisAssert(ln != NULL);
481 listDelNode(server.unblocked_clients,ln);
482 }
483 /* Remove from the list of clients waiting for swapped keys, or ready
484 * to be restarted, but not yet woken up again. */
485 if (c->flags & REDIS_IO_WAIT) {
486 redisAssert(server.ds_enabled);
487 if (listLength(c->io_keys) == 0) {
488 ln = listSearchKey(server.io_ready_clients,c);
489
490 /* When this client is waiting to be woken up (REDIS_IO_WAIT),
491 * it should be present in the list io_ready_clients */
492 redisAssert(ln != NULL);
493 listDelNode(server.io_ready_clients,ln);
494 } else {
495 while (listLength(c->io_keys)) {
496 ln = listFirst(c->io_keys);
497 dontWaitForSwappedKey(c,ln->value);
498 }
499 }
500 server.cache_blocked_clients--;
501 }
502 listRelease(c->io_keys);
503 /* Master/slave cleanup.
504 * Case 1: we lost the connection with a slave. */
505 if (c->flags & REDIS_SLAVE) {
506 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
507 close(c->repldbfd);
508 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
509 ln = listSearchKey(l,c);
510 redisAssert(ln != NULL);
511 listDelNode(l,ln);
512 }
513
514 /* Case 2: we lost the connection with the master. */
515 if (c->flags & REDIS_MASTER) {
516 server.master = NULL;
517 server.replstate = REDIS_REPL_CONNECT;
518 /* Since we lost the connection with the master, we should also
519 * close the connection with all our slaves if we have any, so
520 * when we'll resync with the master the other slaves will sync again
521 * with us as well. Note that also when the slave is not connected
522 * to the master it will keep refusing connections by other slaves. */
523 while (listLength(server.slaves)) {
524 ln = listFirst(server.slaves);
525 freeClient((redisClient*)ln->value);
526 }
527 }
528 /* Release memory */
529 zfree(c->argv);
530 freeClientMultiState(c);
531 zfree(c);
532}
533
534void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
535 redisClient *c = privdata;
536 int nwritten = 0, totwritten = 0, objlen;
537 robj *o;
538 REDIS_NOTUSED(el);
539 REDIS_NOTUSED(mask);
540
541 while(c->bufpos > 0 || listLength(c->reply)) {
542 if (c->bufpos > 0) {
543 if (c->flags & REDIS_MASTER) {
544 /* Don't reply to a master */
545 nwritten = c->bufpos - c->sentlen;
546 } else {
547 nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen);
548 if (nwritten <= 0) break;
549 }
550 c->sentlen += nwritten;
551 totwritten += nwritten;
552
553 /* If the buffer was sent, set bufpos to zero to continue with
554 * the remainder of the reply. */
555 if (c->sentlen == c->bufpos) {
556 c->bufpos = 0;
557 c->sentlen = 0;
558 }
559 } else {
560 o = listNodeValue(listFirst(c->reply));
561 objlen = sdslen(o->ptr);
562
563 if (objlen == 0) {
564 listDelNode(c->reply,listFirst(c->reply));
565 continue;
566 }
567
568 if (c->flags & REDIS_MASTER) {
569 /* Don't reply to a master */
570 nwritten = objlen - c->sentlen;
571 } else {
572 nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen);
573 if (nwritten <= 0) break;
574 }
575 c->sentlen += nwritten;
576 totwritten += nwritten;
577
578 /* If we fully sent the object on head go to the next one */
579 if (c->sentlen == objlen) {
580 listDelNode(c->reply,listFirst(c->reply));
581 c->sentlen = 0;
582 }
583 }
584 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
585 * bytes, in a single threaded server it's a good idea to serve
586 * other clients as well, even if a very large request comes from
587 * super fast link that is always able to accept data (in real world
588 * scenario think about 'KEYS *' against the loopback interfae) */
589 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
590 }
591 if (nwritten == -1) {
592 if (errno == EAGAIN) {
593 nwritten = 0;
594 } else {
595 redisLog(REDIS_VERBOSE,
596 "Error writing to client: %s", strerror(errno));
597 freeClient(c);
598 return;
599 }
600 }
601 if (totwritten > 0) c->lastinteraction = time(NULL);
602 if (listLength(c->reply) == 0) {
603 c->sentlen = 0;
604 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
605
606 /* Close connection after entire reply has been sent. */
607 if (c->flags & REDIS_CLOSE_AFTER_REPLY) freeClient(c);
608 }
609}
610
611/* resetClient prepare the client to process the next command */
612void resetClient(redisClient *c) {
613 freeClientArgv(c);
614 c->reqtype = 0;
615 c->multibulklen = 0;
616 c->bulklen = -1;
617}
618
619void closeTimedoutClients(void) {
620 redisClient *c;
621 listNode *ln;
622 time_t now = time(NULL);
623 listIter li;
624
625 listRewind(server.clients,&li);
626 while ((ln = listNext(&li)) != NULL) {
627 c = listNodeValue(ln);
628 if (server.maxidletime &&
629 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
630 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
631 !(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */
632 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
633 listLength(c->pubsub_patterns) == 0 &&
634 (now - c->lastinteraction > server.maxidletime))
635 {
636 redisLog(REDIS_VERBOSE,"Closing idle client");
637 freeClient(c);
638 } else if (c->flags & REDIS_BLOCKED) {
639 if (c->bpop.timeout != 0 && c->bpop.timeout < now) {
640 addReply(c,shared.nullmultibulk);
641 unblockClientWaitingData(c);
642 }
643 }
644 }
645}
646
647int processInlineBuffer(redisClient *c) {
648 char *newline = strstr(c->querybuf,"\r\n");
649 int argc, j;
650 sds *argv;
651 size_t querylen;
652
653 /* Nothing to do without a \r\n */
654 if (newline == NULL)
655 return REDIS_ERR;
656
657 /* Split the input buffer up to the \r\n */
658 querylen = newline-(c->querybuf);
659 argv = sdssplitlen(c->querybuf,querylen," ",1,&argc);
660
661 /* Leave data after the first line of the query in the buffer */
662 c->querybuf = sdsrange(c->querybuf,querylen+2,-1);
663
664 /* Setup argv array on client structure */
665 if (c->argv) zfree(c->argv);
666 c->argv = zmalloc(sizeof(robj*)*argc);
667
668 /* Create redis objects for all arguments. */
669 for (c->argc = 0, j = 0; j < argc; j++) {
670 if (sdslen(argv[j])) {
671 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
672 c->argc++;
673 } else {
674 sdsfree(argv[j]);
675 }
676 }
677 zfree(argv);
678 return REDIS_OK;
679}
680
681/* Helper function. Trims query buffer to make the function that processes
682 * multi bulk requests idempotent. */
683static void setProtocolError(redisClient *c, int pos) {
684 c->flags |= REDIS_CLOSE_AFTER_REPLY;
685 c->querybuf = sdsrange(c->querybuf,pos,-1);
686}
687
688int processMultibulkBuffer(redisClient *c) {
689 char *newline = NULL;
690 char *eptr;
691 int pos = 0, tolerr;
692 long bulklen;
693
694 if (c->multibulklen == 0) {
695 /* The client should have been reset */
696 redisAssert(c->argc == 0);
697
698 /* Multi bulk length cannot be read without a \r\n */
699 newline = strstr(c->querybuf,"\r\n");
700 if (newline == NULL)
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 c->multibulklen = strtol(c->querybuf+1,&eptr,10);
707 pos = (newline-c->querybuf)+2;
708 if (c->multibulklen <= 0) {
709 c->querybuf = sdsrange(c->querybuf,pos,-1);
710 return REDIS_OK;
711 } else if (c->multibulklen > 1024*1024) {
712 addReplyError(c,"Protocol error: invalid multibulk length");
713 setProtocolError(c,pos);
714 return REDIS_ERR;
715 }
716
717 /* Setup argv array on client structure */
718 if (c->argv) zfree(c->argv);
719 c->argv = zmalloc(sizeof(robj*)*c->multibulklen);
720
721 /* Search new newline */
722 newline = strstr(c->querybuf+pos,"\r\n");
723 }
724
725 redisAssert(c->multibulklen > 0);
726 while(c->multibulklen) {
727 /* Read bulk length if unknown */
728 if (c->bulklen == -1) {
729 newline = strstr(c->querybuf+pos,"\r\n");
730 if (newline != NULL) {
731 if (c->querybuf[pos] != '$') {
732 addReplyErrorFormat(c,
733 "Protocol error: expected '$', got '%c'",
734 c->querybuf[pos]);
735 setProtocolError(c,pos);
736 return REDIS_ERR;
737 }
738
739 bulklen = strtol(c->querybuf+pos+1,&eptr,10);
740 tolerr = (eptr[0] != '\r');
741 if (tolerr || bulklen == LONG_MIN || bulklen == LONG_MAX ||
742 bulklen < 0 || bulklen > 512*1024*1024)
743 {
744 addReplyError(c,"Protocol error: invalid bulk length");
745 setProtocolError(c,pos);
746 return REDIS_ERR;
747 }
748 pos += eptr-(c->querybuf+pos)+2;
749 c->bulklen = bulklen;
750 } else {
751 /* No newline in current buffer, so wait for more data */
752 break;
753 }
754 }
755
756 /* Read bulk argument */
757 if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) {
758 /* Not enough data (+2 == trailing \r\n) */
759 break;
760 } else {
761 c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen);
762 pos += c->bulklen+2;
763 c->bulklen = -1;
764 c->multibulklen--;
765 }
766 }
767
768 /* Trim to pos */
769 c->querybuf = sdsrange(c->querybuf,pos,-1);
770
771 /* We're done when c->multibulk == 0 */
772 if (c->multibulklen == 0) {
773 return REDIS_OK;
774 }
775 return REDIS_ERR;
776}
777
778void processInputBuffer(redisClient *c) {
779 /* Keep processing while there is something in the input buffer */
780 while(sdslen(c->querybuf)) {
781 /* Immediately abort if the client is in the middle of something. */
782 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
783
784 /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
785 * written to the client. Make sure to not let the reply grow after
786 * this flag has been set (i.e. don't process more commands). */
787 if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
788
789 /* Determine request type when unknown. */
790 if (!c->reqtype) {
791 if (c->querybuf[0] == '*') {
792 c->reqtype = REDIS_REQ_MULTIBULK;
793 } else {
794 c->reqtype = REDIS_REQ_INLINE;
795 }
796 }
797
798 if (c->reqtype == REDIS_REQ_INLINE) {
799 if (processInlineBuffer(c) != REDIS_OK) break;
800 } else if (c->reqtype == REDIS_REQ_MULTIBULK) {
801 if (processMultibulkBuffer(c) != REDIS_OK) break;
802 } else {
803 redisPanic("Unknown request type");
804 }
805
806 /* Multibulk processing could see a <= 0 length. */
807 if (c->argc == 0) {
808 resetClient(c);
809 } else {
810 /* Only reset the client when the command was executed. */
811 if (processCommand(c) == REDIS_OK)
812 resetClient(c);
813 }
814 }
815}
816
817void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
818 redisClient *c = (redisClient*) privdata;
819 char buf[REDIS_IOBUF_LEN];
820 int nread;
821 REDIS_NOTUSED(el);
822 REDIS_NOTUSED(mask);
823
824 nread = read(fd, buf, REDIS_IOBUF_LEN);
825 if (nread == -1) {
826 if (errno == EAGAIN) {
827 nread = 0;
828 } else {
829 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
830 freeClient(c);
831 return;
832 }
833 } else if (nread == 0) {
834 redisLog(REDIS_VERBOSE, "Client closed connection");
835 freeClient(c);
836 return;
837 }
838 if (nread) {
839 c->querybuf = sdscatlen(c->querybuf,buf,nread);
840 c->lastinteraction = time(NULL);
841 } else {
842 return;
843 }
844 processInputBuffer(c);
845}
846
847void getClientsMaxBuffers(unsigned long *longest_output_list,
848 unsigned long *biggest_input_buffer) {
849 redisClient *c;
850 listNode *ln;
851 listIter li;
852 unsigned long lol = 0, bib = 0;
853
854 listRewind(server.clients,&li);
855 while ((ln = listNext(&li)) != NULL) {
856 c = listNodeValue(ln);
857
858 if (listLength(c->reply) > lol) lol = listLength(c->reply);
859 if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf);
860 }
861 *longest_output_list = lol;
862 *biggest_input_buffer = bib;
863}
864