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