]>
Commit | Line | Data |
---|---|---|
e2641e09 | 1 | #include "redis.h" |
e2641e09 | 2 | #include <sys/uio.h> |
3 | ||
4 | void *dupClientReplyValue(void *o) { | |
5 | incrRefCount((robj*)o); | |
6 | return o; | |
7 | } | |
8 | ||
9 | int listMatchObjects(void *a, void *b) { | |
10 | return equalStringObjects(a,b); | |
11 | } | |
12 | ||
13 | redisClient *createClient(int fd) { | |
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 | 67 | int _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. */ | |
80 | robj *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 | 98 | int _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 |
115 | void _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. */ | |
141 | void _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 | ||
167 | void _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 | 194 | void 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 | ||
218 | void 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 | 232 | void 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 |
238 | void _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 |
244 | void addReplyError(redisClient *c, char *err) { |
245 | _addReplyError(c,err,strlen(err)); | |
246 | } | |
e2641e09 | 247 | |
3ab20376 | 248 | void addReplyErrorFormat(redisClient *c, const char *fmt, ...) { |
3bb818df | 249 | size_t l, j; |
3ab20376 PN |
250 | va_list ap; |
251 | va_start(ap,fmt); | |
252 | sds s = sdscatvprintf(sdsempty(),fmt,ap); | |
253 | va_end(ap); | |
3bb818df | 254 | /* Make sure there are no newlines in the string, otherwise invalid protocol |
255 | * is emitted. */ | |
256 | l = sdslen(s); | |
257 | for (j = 0; j < l; j++) { | |
258 | if (s[j] == '\r' || s[j] == '\n') s[j] = ' '; | |
259 | } | |
3ab20376 PN |
260 | _addReplyError(c,s,sdslen(s)); |
261 | sdsfree(s); | |
262 | } | |
263 | ||
264 | void _addReplyStatus(redisClient *c, char *s, size_t len) { | |
265 | addReplyString(c,"+",1); | |
266 | addReplyString(c,s,len); | |
267 | addReplyString(c,"\r\n",2); | |
268 | } | |
269 | ||
270 | void addReplyStatus(redisClient *c, char *status) { | |
271 | _addReplyStatus(c,status,strlen(status)); | |
272 | } | |
273 | ||
274 | void addReplyStatusFormat(redisClient *c, const char *fmt, ...) { | |
275 | va_list ap; | |
276 | va_start(ap,fmt); | |
277 | sds s = sdscatvprintf(sdsempty(),fmt,ap); | |
278 | va_end(ap); | |
279 | _addReplyStatus(c,s,sdslen(s)); | |
280 | sdsfree(s); | |
281 | } | |
282 | ||
b301c1fc PN |
283 | /* Adds an empty object to the reply list that will contain the multi bulk |
284 | * length, which is not known when this function is called. */ | |
285 | void *addDeferredMultiBulkLength(redisClient *c) { | |
4c2e506a | 286 | /* Note that we install the write event here even if the object is not |
287 | * ready to be sent, since we are sure that before returning to the | |
288 | * event loop setDeferredMultiBulkLength() will be called. */ | |
289 | if (_installWriteEvent(c) != REDIS_OK) return NULL; | |
36c19d03 | 290 | listAddNodeTail(c->reply,createObject(REDIS_STRING,NULL)); |
b301c1fc PN |
291 | return listLast(c->reply); |
292 | } | |
293 | ||
294 | /* Populate the length object and try glueing it to the next chunk. */ | |
295 | void setDeferredMultiBulkLength(redisClient *c, void *node, long length) { | |
296 | listNode *ln = (listNode*)node; | |
297 | robj *len, *next; | |
298 | ||
299 | /* Abort when *node is NULL (see addDeferredMultiBulkLength). */ | |
300 | if (node == NULL) return; | |
301 | ||
302 | len = listNodeValue(ln); | |
303 | len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length); | |
304 | if (ln->next != NULL) { | |
305 | next = listNodeValue(ln->next); | |
36c19d03 | 306 | |
49128f0b | 307 | /* Only glue when the next node is non-NULL (an sds in this case) */ |
36c19d03 | 308 | if (next->ptr != NULL) { |
49128f0b | 309 | len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr)); |
b301c1fc PN |
310 | listDelNode(c->reply,ln->next); |
311 | } | |
e2641e09 | 312 | } |
b301c1fc PN |
313 | } |
314 | ||
d51ebef5 | 315 | /* Add a duble as a bulk reply */ |
834ef78e PN |
316 | void addReplyDouble(redisClient *c, double d) { |
317 | char dbuf[128], sbuf[128]; | |
318 | int dlen, slen; | |
319 | dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d); | |
320 | slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf); | |
321 | addReplyString(c,sbuf,slen); | |
e2641e09 | 322 | } |
323 | ||
d51ebef5 | 324 | /* Add a long long as integer reply or bulk len / multi bulk count. |
325 | * Basically this is used to output <prefix><long long><crlf>. */ | |
834ef78e | 326 | void _addReplyLongLong(redisClient *c, long long ll, char prefix) { |
e2641e09 | 327 | char buf[128]; |
834ef78e PN |
328 | int len; |
329 | buf[0] = prefix; | |
e2641e09 | 330 | len = ll2string(buf+1,sizeof(buf)-1,ll); |
331 | buf[len+1] = '\r'; | |
332 | buf[len+2] = '\n'; | |
834ef78e | 333 | addReplyString(c,buf,len+3); |
e2641e09 | 334 | } |
335 | ||
834ef78e | 336 | void addReplyLongLong(redisClient *c, long long ll) { |
009db676 | 337 | if (ll == 0) |
338 | addReply(c,shared.czero); | |
339 | else if (ll == 1) | |
340 | addReply(c,shared.cone); | |
341 | else | |
342 | _addReplyLongLong(c,ll,':'); | |
834ef78e | 343 | } |
e2641e09 | 344 | |
0537e7bf PN |
345 | void addReplyMultiBulkLen(redisClient *c, long length) { |
346 | _addReplyLongLong(c,length,'*'); | |
e2641e09 | 347 | } |
348 | ||
d51ebef5 | 349 | /* Create the length prefix of a bulk reply, example: $2234 */ |
e2641e09 | 350 | void addReplyBulkLen(redisClient *c, robj *obj) { |
834ef78e | 351 | size_t len; |
e2641e09 | 352 | |
353 | if (obj->encoding == REDIS_ENCODING_RAW) { | |
354 | len = sdslen(obj->ptr); | |
355 | } else { | |
356 | long n = (long)obj->ptr; | |
357 | ||
358 | /* Compute how many bytes will take this integer as a radix 10 string */ | |
359 | len = 1; | |
360 | if (n < 0) { | |
361 | len++; | |
362 | n = -n; | |
363 | } | |
364 | while((n = n/10) != 0) { | |
365 | len++; | |
366 | } | |
367 | } | |
834ef78e | 368 | _addReplyLongLong(c,len,'$'); |
e2641e09 | 369 | } |
370 | ||
d51ebef5 | 371 | /* Add a Redis Object as a bulk reply */ |
e2641e09 | 372 | void addReplyBulk(redisClient *c, robj *obj) { |
373 | addReplyBulkLen(c,obj); | |
374 | addReply(c,obj); | |
375 | addReply(c,shared.crlf); | |
376 | } | |
377 | ||
d51ebef5 | 378 | /* Add a C buffer as bulk reply */ |
379 | void addReplyBulkCBuffer(redisClient *c, void *p, size_t len) { | |
380 | _addReplyLongLong(c,len,'$'); | |
381 | addReplyString(c,p,len); | |
382 | addReply(c,shared.crlf); | |
383 | } | |
384 | ||
385 | /* Add a C nul term string as bulk reply */ | |
e2641e09 | 386 | void addReplyBulkCString(redisClient *c, char *s) { |
387 | if (s == NULL) { | |
388 | addReply(c,shared.nullbulk); | |
389 | } else { | |
d51ebef5 | 390 | addReplyBulkCBuffer(c,s,strlen(s)); |
e2641e09 | 391 | } |
392 | } | |
393 | ||
d51ebef5 | 394 | /* Add a long long as a bulk reply */ |
395 | void addReplyBulkLongLong(redisClient *c, long long ll) { | |
396 | char buf[64]; | |
397 | int len; | |
398 | ||
399 | len = ll2string(buf,64,ll); | |
400 | addReplyBulkCBuffer(c,buf,len); | |
401 | } | |
402 | ||
ab17b909 | 403 | static void acceptCommonHandler(int fd) { |
e2641e09 | 404 | redisClient *c; |
ab17b909 | 405 | if ((c = createClient(fd)) == NULL) { |
e2641e09 | 406 | redisLog(REDIS_WARNING,"Error allocating resoures for the client"); |
ab17b909 | 407 | close(fd); /* May be already closed, just ingore errors */ |
e2641e09 | 408 | return; |
409 | } | |
410 | /* If maxclient directive is set and this is one client more... close the | |
411 | * connection. Note that we create the client instead to check before | |
412 | * for this condition, since now the socket is already set in nonblocking | |
413 | * mode and we can send an error for free using the Kernel I/O */ | |
414 | if (server.maxclients && listLength(server.clients) > server.maxclients) { | |
415 | char *err = "-ERR max number of clients reached\r\n"; | |
416 | ||
417 | /* That's a best effort error message, don't check write errors */ | |
418 | if (write(c->fd,err,strlen(err)) == -1) { | |
419 | /* Nothing to do, Just to avoid the warning... */ | |
420 | } | |
421 | freeClient(c); | |
422 | return; | |
423 | } | |
424 | server.stat_numconnections++; | |
425 | } | |
426 | ||
ab17b909 PN |
427 | void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) { |
428 | int cport, cfd; | |
429 | char cip[128]; | |
430 | REDIS_NOTUSED(el); | |
431 | REDIS_NOTUSED(mask); | |
432 | REDIS_NOTUSED(privdata); | |
433 | ||
434 | cfd = anetTcpAccept(server.neterr, fd, cip, &cport); | |
435 | if (cfd == AE_ERR) { | |
df541bea | 436 | redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr); |
ab17b909 PN |
437 | return; |
438 | } | |
439 | redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport); | |
440 | acceptCommonHandler(cfd); | |
441 | } | |
442 | ||
443 | void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) { | |
444 | int cfd; | |
ab17b909 PN |
445 | REDIS_NOTUSED(el); |
446 | REDIS_NOTUSED(mask); | |
447 | REDIS_NOTUSED(privdata); | |
448 | ||
4fe83b55 | 449 | cfd = anetUnixAccept(server.neterr, fd); |
ab17b909 | 450 | if (cfd == AE_ERR) { |
df541bea | 451 | redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr); |
ab17b909 PN |
452 | return; |
453 | } | |
454 | redisLog(REDIS_VERBOSE,"Accepted connection to %s", server.unixsocket); | |
455 | acceptCommonHandler(cfd); | |
456 | } | |
457 | ||
458 | ||
e2641e09 | 459 | static void freeClientArgv(redisClient *c) { |
460 | int j; | |
e2641e09 | 461 | for (j = 0; j < c->argc; j++) |
462 | decrRefCount(c->argv[j]); | |
e2641e09 | 463 | c->argc = 0; |
e2641e09 | 464 | } |
465 | ||
466 | void freeClient(redisClient *c) { | |
467 | listNode *ln; | |
468 | ||
469 | /* Note that if the client we are freeing is blocked into a blocking | |
470 | * call, we have to set querybuf to NULL *before* to call | |
471 | * unblockClientWaitingData() to avoid processInputBuffer() will get | |
472 | * called. Also it is important to remove the file events after | |
473 | * this, because this call adds the READABLE event. */ | |
474 | sdsfree(c->querybuf); | |
475 | c->querybuf = NULL; | |
476 | if (c->flags & REDIS_BLOCKED) | |
477 | unblockClientWaitingData(c); | |
478 | ||
479 | /* UNWATCH all the keys */ | |
480 | unwatchAllKeys(c); | |
481 | listRelease(c->watched_keys); | |
482 | /* Unsubscribe from all the pubsub channels */ | |
483 | pubsubUnsubscribeAllChannels(c,0); | |
484 | pubsubUnsubscribeAllPatterns(c,0); | |
485 | dictRelease(c->pubsub_channels); | |
486 | listRelease(c->pubsub_patterns); | |
487 | /* Obvious cleanup */ | |
488 | aeDeleteFileEvent(server.el,c->fd,AE_READABLE); | |
489 | aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); | |
490 | listRelease(c->reply); | |
491 | freeClientArgv(c); | |
492 | close(c->fd); | |
493 | /* Remove from the list of clients */ | |
494 | ln = listSearchKey(server.clients,c); | |
495 | redisAssert(ln != NULL); | |
496 | listDelNode(server.clients,ln); | |
3bcffcbe PN |
497 | /* When client was just unblocked because of a blocking operation, |
498 | * remove it from the list with unblocked clients. */ | |
499 | if (c->flags & REDIS_UNBLOCKED) { | |
500 | ln = listSearchKey(server.unblocked_clients,c); | |
501 | redisAssert(ln != NULL); | |
502 | listDelNode(server.unblocked_clients,ln); | |
503 | } | |
1a71fb96 | 504 | /* Remove from the list of clients waiting for swapped keys, or ready |
505 | * to be restarted, but not yet woken up again. */ | |
506 | if (c->flags & REDIS_IO_WAIT) { | |
697af434 | 507 | redisAssert(server.ds_enabled); |
1a71fb96 | 508 | if (listLength(c->io_keys) == 0) { |
509 | ln = listSearchKey(server.io_ready_clients,c); | |
510 | ||
511 | /* When this client is waiting to be woken up (REDIS_IO_WAIT), | |
512 | * it should be present in the list io_ready_clients */ | |
513 | redisAssert(ln != NULL); | |
e2641e09 | 514 | listDelNode(server.io_ready_clients,ln); |
1a71fb96 | 515 | } else { |
516 | while (listLength(c->io_keys)) { | |
517 | ln = listFirst(c->io_keys); | |
518 | dontWaitForSwappedKey(c,ln->value); | |
519 | } | |
e2641e09 | 520 | } |
697af434 | 521 | server.cache_blocked_clients--; |
e2641e09 | 522 | } |
523 | listRelease(c->io_keys); | |
778b2210 | 524 | /* Master/slave cleanup. |
525 | * Case 1: we lost the connection with a slave. */ | |
e2641e09 | 526 | if (c->flags & REDIS_SLAVE) { |
527 | if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1) | |
528 | close(c->repldbfd); | |
529 | list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves; | |
530 | ln = listSearchKey(l,c); | |
531 | redisAssert(ln != NULL); | |
532 | listDelNode(l,ln); | |
533 | } | |
778b2210 | 534 | |
535 | /* Case 2: we lost the connection with the master. */ | |
e2641e09 | 536 | if (c->flags & REDIS_MASTER) { |
537 | server.master = NULL; | |
538 | server.replstate = REDIS_REPL_CONNECT; | |
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 | 561 | void 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); | |
629 | if (listLength(c->reply) == 0) { | |
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 */ |
639 | void resetClient(redisClient *c) { | |
640 | freeClientArgv(c); | |
cd8788f2 PN |
641 | c->reqtype = 0; |
642 | c->multibulklen = 0; | |
e2641e09 | 643 | c->bulklen = -1; |
e2641e09 | 644 | } |
645 | ||
646 | void closeTimedoutClients(void) { | |
647 | redisClient *c; | |
648 | listNode *ln; | |
649 | time_t now = time(NULL); | |
650 | listIter li; | |
651 | ||
652 | listRewind(server.clients,&li); | |
653 | while ((ln = listNext(&li)) != NULL) { | |
654 | c = listNodeValue(ln); | |
655 | if (server.maxidletime && | |
656 | !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */ | |
657 | !(c->flags & REDIS_MASTER) && /* no timeout for masters */ | |
e452436a | 658 | !(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */ |
e2641e09 | 659 | dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */ |
660 | listLength(c->pubsub_patterns) == 0 && | |
661 | (now - c->lastinteraction > server.maxidletime)) | |
662 | { | |
663 | redisLog(REDIS_VERBOSE,"Closing idle client"); | |
664 | freeClient(c); | |
665 | } else if (c->flags & REDIS_BLOCKED) { | |
e3c51c4b | 666 | if (c->bpop.timeout != 0 && c->bpop.timeout < now) { |
e2641e09 | 667 | addReply(c,shared.nullmultibulk); |
668 | unblockClientWaitingData(c); | |
669 | } | |
670 | } | |
671 | } | |
672 | } | |
673 | ||
cd8788f2 PN |
674 | int processInlineBuffer(redisClient *c) { |
675 | char *newline = strstr(c->querybuf,"\r\n"); | |
676 | int argc, j; | |
677 | sds *argv; | |
678 | size_t querylen; | |
679 | ||
680 | /* Nothing to do without a \r\n */ | |
681 | if (newline == NULL) | |
682 | return REDIS_ERR; | |
683 | ||
684 | /* Split the input buffer up to the \r\n */ | |
685 | querylen = newline-(c->querybuf); | |
686 | argv = sdssplitlen(c->querybuf,querylen," ",1,&argc); | |
687 | ||
688 | /* Leave data after the first line of the query in the buffer */ | |
689 | c->querybuf = sdsrange(c->querybuf,querylen+2,-1); | |
690 | ||
691 | /* Setup argv array on client structure */ | |
692 | if (c->argv) zfree(c->argv); | |
693 | c->argv = zmalloc(sizeof(robj*)*argc); | |
694 | ||
695 | /* Create redis objects for all arguments. */ | |
696 | for (c->argc = 0, j = 0; j < argc; j++) { | |
697 | if (sdslen(argv[j])) { | |
698 | c->argv[c->argc] = createObject(REDIS_STRING,argv[j]); | |
699 | c->argc++; | |
700 | } else { | |
701 | sdsfree(argv[j]); | |
702 | } | |
703 | } | |
704 | zfree(argv); | |
705 | return REDIS_OK; | |
706 | } | |
707 | ||
708 | /* Helper function. Trims query buffer to make the function that processes | |
709 | * multi bulk requests idempotent. */ | |
710 | static void setProtocolError(redisClient *c, int pos) { | |
711 | c->flags |= REDIS_CLOSE_AFTER_REPLY; | |
712 | c->querybuf = sdsrange(c->querybuf,pos,-1); | |
713 | } | |
714 | ||
715 | int processMultibulkBuffer(redisClient *c) { | |
716 | char *newline = NULL; | |
5af30201 PN |
717 | int pos = 0, ok; |
718 | long long ll; | |
cd8788f2 PN |
719 | |
720 | if (c->multibulklen == 0) { | |
721 | /* The client should have been reset */ | |
722 | redisAssert(c->argc == 0); | |
723 | ||
724 | /* Multi bulk length cannot be read without a \r\n */ | |
5af30201 | 725 | newline = strchr(c->querybuf,'\r'); |
cd8788f2 PN |
726 | if (newline == NULL) |
727 | return REDIS_ERR; | |
728 | ||
bf9fd5ff PN |
729 | /* Buffer should also contain \n */ |
730 | if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) | |
731 | return REDIS_ERR; | |
732 | ||
cd8788f2 PN |
733 | /* We know for sure there is a whole line since newline != NULL, |
734 | * so go ahead and find out the multi bulk length. */ | |
735 | redisAssert(c->querybuf[0] == '*'); | |
5af30201 PN |
736 | ok = string2ll(c->querybuf+1,newline-(c->querybuf+1),&ll); |
737 | if (!ok || ll > 1024*1024) { | |
b19c33d4 PN |
738 | addReplyError(c,"Protocol error: invalid multibulk length"); |
739 | setProtocolError(c,pos); | |
740 | return REDIS_ERR; | |
cd8788f2 | 741 | } |
af0e51f2 PN |
742 | |
743 | pos = (newline-c->querybuf)+2; | |
744 | if (ll <= 0) { | |
745 | c->querybuf = sdsrange(c->querybuf,pos,-1); | |
746 | return REDIS_OK; | |
747 | } | |
748 | ||
5af30201 | 749 | c->multibulklen = ll; |
cd8788f2 PN |
750 | |
751 | /* Setup argv array on client structure */ | |
752 | if (c->argv) zfree(c->argv); | |
753 | c->argv = zmalloc(sizeof(robj*)*c->multibulklen); | |
cd8788f2 PN |
754 | } |
755 | ||
756 | redisAssert(c->multibulklen > 0); | |
757 | while(c->multibulklen) { | |
758 | /* Read bulk length if unknown */ | |
759 | if (c->bulklen == -1) { | |
5af30201 | 760 | newline = strchr(c->querybuf+pos,'\r'); |
bf9fd5ff PN |
761 | if (newline == NULL) |
762 | break; | |
763 | ||
764 | /* Buffer should also contain \n */ | |
765 | if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) | |
cd8788f2 | 766 | break; |
bf9fd5ff PN |
767 | |
768 | if (c->querybuf[pos] != '$') { | |
769 | addReplyErrorFormat(c, | |
770 | "Protocol error: expected '$', got '%c'", | |
771 | c->querybuf[pos]); | |
772 | setProtocolError(c,pos); | |
773 | return REDIS_ERR; | |
e2641e09 | 774 | } |
bf9fd5ff PN |
775 | |
776 | ok = string2ll(c->querybuf+pos+1,newline-(c->querybuf+pos+1),&ll); | |
777 | if (!ok || ll < 0 || ll > 512*1024*1024) { | |
778 | addReplyError(c,"Protocol error: invalid bulk length"); | |
779 | setProtocolError(c,pos); | |
780 | return REDIS_ERR; | |
781 | } | |
782 | ||
783 | pos += newline-(c->querybuf+pos)+2; | |
784 | c->bulklen = ll; | |
cd8788f2 PN |
785 | } |
786 | ||
787 | /* Read bulk argument */ | |
788 | if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) { | |
789 | /* Not enough data (+2 == trailing \r\n) */ | |
790 | break; | |
791 | } else { | |
792 | c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen); | |
793 | pos += c->bulklen+2; | |
794 | c->bulklen = -1; | |
795 | c->multibulklen--; | |
796 | } | |
797 | } | |
798 | ||
799 | /* Trim to pos */ | |
800 | c->querybuf = sdsrange(c->querybuf,pos,-1); | |
801 | ||
802 | /* We're done when c->multibulk == 0 */ | |
803 | if (c->multibulklen == 0) { | |
804 | return REDIS_OK; | |
805 | } | |
806 | return REDIS_ERR; | |
807 | } | |
808 | ||
809 | void processInputBuffer(redisClient *c) { | |
810 | /* Keep processing while there is something in the input buffer */ | |
811 | while(sdslen(c->querybuf)) { | |
4794d88f | 812 | /* Immediately abort if the client is in the middle of something. */ |
cd8788f2 PN |
813 | if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return; |
814 | ||
5e78edb3 PN |
815 | /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is |
816 | * written to the client. Make sure to not let the reply grow after | |
817 | * this flag has been set (i.e. don't process more commands). */ | |
818 | if (c->flags & REDIS_CLOSE_AFTER_REPLY) return; | |
cd8788f2 PN |
819 | |
820 | /* Determine request type when unknown. */ | |
821 | if (!c->reqtype) { | |
822 | if (c->querybuf[0] == '*') { | |
823 | c->reqtype = REDIS_REQ_MULTIBULK; | |
e2641e09 | 824 | } else { |
cd8788f2 | 825 | c->reqtype = REDIS_REQ_INLINE; |
e2641e09 | 826 | } |
e2641e09 | 827 | } |
cd8788f2 PN |
828 | |
829 | if (c->reqtype == REDIS_REQ_INLINE) { | |
830 | if (processInlineBuffer(c) != REDIS_OK) break; | |
831 | } else if (c->reqtype == REDIS_REQ_MULTIBULK) { | |
832 | if (processMultibulkBuffer(c) != REDIS_OK) break; | |
833 | } else { | |
834 | redisPanic("Unknown request type"); | |
e2641e09 | 835 | } |
cd8788f2 PN |
836 | |
837 | /* Multibulk processing could see a <= 0 length. */ | |
9da6caac PN |
838 | if (c->argc == 0) { |
839 | resetClient(c); | |
840 | } else { | |
841 | /* Only reset the client when the command was executed. */ | |
842 | if (processCommand(c) == REDIS_OK) | |
843 | resetClient(c); | |
844 | } | |
e2641e09 | 845 | } |
846 | } | |
847 | ||
848 | void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) { | |
849 | redisClient *c = (redisClient*) privdata; | |
850 | char buf[REDIS_IOBUF_LEN]; | |
851 | int nread; | |
852 | REDIS_NOTUSED(el); | |
853 | REDIS_NOTUSED(mask); | |
854 | ||
855 | nread = read(fd, buf, REDIS_IOBUF_LEN); | |
856 | if (nread == -1) { | |
857 | if (errno == EAGAIN) { | |
858 | nread = 0; | |
859 | } else { | |
860 | redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno)); | |
861 | freeClient(c); | |
862 | return; | |
863 | } | |
864 | } else if (nread == 0) { | |
865 | redisLog(REDIS_VERBOSE, "Client closed connection"); | |
866 | freeClient(c); | |
867 | return; | |
868 | } | |
869 | if (nread) { | |
cd8788f2 | 870 | c->querybuf = sdscatlen(c->querybuf,buf,nread); |
e2641e09 | 871 | c->lastinteraction = time(NULL); |
872 | } else { | |
873 | return; | |
874 | } | |
875 | processInputBuffer(c); | |
876 | } | |
7a1fd61e | 877 | |
878 | void getClientsMaxBuffers(unsigned long *longest_output_list, | |
879 | unsigned long *biggest_input_buffer) { | |
880 | redisClient *c; | |
881 | listNode *ln; | |
882 | listIter li; | |
883 | unsigned long lol = 0, bib = 0; | |
884 | ||
885 | listRewind(server.clients,&li); | |
886 | while ((ln = listNext(&li)) != NULL) { | |
887 | c = listNodeValue(ln); | |
888 | ||
889 | if (listLength(c->reply) > lol) lol = listLength(c->reply); | |
890 | if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf); | |
891 | } | |
892 | *longest_output_list = lol; | |
893 | *biggest_input_buffer = bib; | |
894 | } | |
895 | ||
3cd12b56 | 896 | void clientCommand(redisClient *c) { |
b93fdb7b | 897 | listNode *ln; |
898 | listIter li; | |
899 | redisClient *client; | |
900 | ||
3cd12b56 | 901 | if (!strcasecmp(c->argv[1]->ptr,"list") && c->argc == 2) { |
3cd12b56 | 902 | sds o = sdsempty(); |
903 | time_t now = time(NULL); | |
904 | ||
905 | listRewind(server.clients,&li); | |
906 | while ((ln = listNext(&li)) != NULL) { | |
3cd12b56 | 907 | char ip[32], flags[16], *p; |
908 | int port; | |
909 | ||
910 | client = listNodeValue(ln); | |
911 | if (anetPeerToString(client->fd,ip,&port) == -1) continue; | |
912 | p = flags; | |
913 | if (client->flags & REDIS_SLAVE) { | |
914 | if (client->flags & REDIS_MONITOR) | |
915 | *p++ = 'O'; | |
916 | else | |
917 | *p++ = 'S'; | |
918 | } | |
919 | if (client->flags & REDIS_MASTER) *p++ = 'M'; | |
920 | if (p == flags) *p++ = 'N'; | |
921 | if (client->flags & REDIS_MULTI) *p++ = 'x'; | |
922 | if (client->flags & REDIS_BLOCKED) *p++ = 'b'; | |
923 | if (client->flags & REDIS_IO_WAIT) *p++ = 'i'; | |
924 | if (client->flags & REDIS_DIRTY_CAS) *p++ = 'd'; | |
925 | if (client->flags & REDIS_CLOSE_AFTER_REPLY) *p++ = 'c'; | |
926 | if (client->flags & REDIS_UNBLOCKED) *p++ = 'u'; | |
927 | *p++ = '\0'; | |
928 | o = sdscatprintf(o, | |
929 | "addr=%s:%d fd=%d idle=%ld flags=%s db=%d sub=%d psub=%d\n", | |
930 | ip,port,client->fd, | |
931 | (long)(now - client->lastinteraction), | |
932 | flags, | |
933 | client->db->id, | |
934 | (int) dictSize(client->pubsub_channels), | |
935 | (int) listLength(client->pubsub_patterns)); | |
936 | } | |
937 | addReplyBulkCBuffer(c,o,sdslen(o)); | |
938 | sdsfree(o); | |
b93fdb7b | 939 | } else if (!strcasecmp(c->argv[1]->ptr,"kill") && c->argc == 3) { |
940 | listRewind(server.clients,&li); | |
941 | while ((ln = listNext(&li)) != NULL) { | |
942 | char ip[32], addr[64]; | |
943 | int port; | |
944 | ||
945 | client = listNodeValue(ln); | |
946 | if (anetPeerToString(client->fd,ip,&port) == -1) continue; | |
947 | snprintf(addr,sizeof(addr),"%s:%d",ip,port); | |
948 | if (strcmp(addr,c->argv[2]->ptr) == 0) { | |
949 | addReply(c,shared.ok); | |
950 | if (c == client) { | |
951 | client->flags |= REDIS_CLOSE_AFTER_REPLY; | |
952 | } else { | |
953 | freeClient(client); | |
954 | } | |
955 | return; | |
956 | } | |
957 | } | |
958 | addReplyError(c,"No such client"); | |
3cd12b56 | 959 | } else { |
960 | addReplyError(c, "Syntax error, try CLIENT (LIST | KILL ip:port)"); | |
961 | } | |
962 | } |