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