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