]>
Commit | Line | Data |
---|---|---|
1 | #include "redis.h" | |
2 | #include <sys/uio.h> | |
3 | ||
4 | static void setProtocolError(redisClient *c, int pos); | |
5 | ||
6 | void *dupClientReplyValue(void *o) { | |
7 | incrRefCount((robj*)o); | |
8 | return o; | |
9 | } | |
10 | ||
11 | int listMatchObjects(void *a, void *b) { | |
12 | return equalStringObjects(a,b); | |
13 | } | |
14 | ||
15 | redisClient *createClient(int fd) { | |
16 | redisClient *c = zmalloc(sizeof(redisClient)); | |
17 | c->bufpos = 0; | |
18 | ||
19 | /* passing -1 as fd it is possible to create a non connected client. | |
20 | * This is useful since all the Redis commands needs to be executed | |
21 | * in the context of a client. When commands are executed in other | |
22 | * contexts (for instance a Lua script) we need a non connected client. */ | |
23 | if (fd != -1) { | |
24 | anetNonBlock(NULL,fd); | |
25 | anetTcpNoDelay(NULL,fd); | |
26 | if (aeCreateFileEvent(server.el,fd,AE_READABLE, | |
27 | readQueryFromClient, c) == AE_ERR) | |
28 | { | |
29 | close(fd); | |
30 | zfree(c); | |
31 | return NULL; | |
32 | } | |
33 | } | |
34 | ||
35 | selectDb(c,0); | |
36 | c->fd = fd; | |
37 | c->querybuf = sdsempty(); | |
38 | c->reqtype = 0; | |
39 | c->argc = 0; | |
40 | c->argv = NULL; | |
41 | c->cmd = c->lastcmd = NULL; | |
42 | c->multibulklen = 0; | |
43 | c->bulklen = -1; | |
44 | c->sentlen = 0; | |
45 | c->flags = 0; | |
46 | c->lastinteraction = time(NULL); | |
47 | c->authenticated = 0; | |
48 | c->replstate = REDIS_REPL_NONE; | |
49 | c->reply = listCreate(); | |
50 | c->reply_bytes = 0; | |
51 | c->obuf_soft_limit_reached_time = 0; | |
52 | listSetFreeMethod(c->reply,decrRefCount); | |
53 | listSetDupMethod(c->reply,dupClientReplyValue); | |
54 | c->bpop.keys = NULL; | |
55 | c->bpop.count = 0; | |
56 | c->bpop.timeout = 0; | |
57 | c->bpop.target = NULL; | |
58 | c->io_keys = listCreate(); | |
59 | c->watched_keys = listCreate(); | |
60 | listSetFreeMethod(c->io_keys,decrRefCount); | |
61 | c->pubsub_channels = dictCreate(&setDictType,NULL); | |
62 | c->pubsub_patterns = listCreate(); | |
63 | listSetFreeMethod(c->pubsub_patterns,decrRefCount); | |
64 | listSetMatchMethod(c->pubsub_patterns,listMatchObjects); | |
65 | if (fd != -1) listAddNodeTail(server.clients,c); | |
66 | initClientMultiState(c); | |
67 | return c; | |
68 | } | |
69 | ||
70 | /* This function is called every time we are going to transmit new data | |
71 | * to the client. The behavior is the following: | |
72 | * | |
73 | * If the client should receive new data (normal clients will) the function | |
74 | * returns REDIS_OK, and make sure to install the write handler in our event | |
75 | * loop so that when the socket is writable new data gets written. | |
76 | * | |
77 | * If the client should not receive new data, because it is a fake client | |
78 | * or a slave, or because the setup of the write handler failed, the function | |
79 | * returns REDIS_ERR. | |
80 | * | |
81 | * Typically gets called every time a reply is built, before adding more | |
82 | * data to the clients output buffers. If the function returns REDIS_ERR no | |
83 | * data should be appended to the output buffers. */ | |
84 | int prepareClientToWrite(redisClient *c) { | |
85 | if (c->flags & REDIS_LUA_CLIENT) return REDIS_OK; | |
86 | if (c->fd <= 0) return REDIS_ERR; /* Fake client */ | |
87 | if (c->bufpos == 0 && listLength(c->reply) == 0 && | |
88 | (c->replstate == REDIS_REPL_NONE || | |
89 | c->replstate == REDIS_REPL_ONLINE) && | |
90 | aeCreateFileEvent(server.el, c->fd, AE_WRITABLE, | |
91 | sendReplyToClient, c) == AE_ERR) return REDIS_ERR; | |
92 | return REDIS_OK; | |
93 | } | |
94 | ||
95 | /* Create a duplicate of the last object in the reply list when | |
96 | * it is not exclusively owned by the reply list. */ | |
97 | robj *dupLastObjectIfNeeded(list *reply) { | |
98 | robj *new, *cur; | |
99 | listNode *ln; | |
100 | redisAssert(listLength(reply) > 0); | |
101 | ln = listLast(reply); | |
102 | cur = listNodeValue(ln); | |
103 | if (cur->refcount > 1) { | |
104 | new = dupStringObject(cur); | |
105 | decrRefCount(cur); | |
106 | listNodeValue(ln) = new; | |
107 | } | |
108 | return listNodeValue(ln); | |
109 | } | |
110 | ||
111 | /* ----------------------------------------------------------------------------- | |
112 | * Low level functions to add more data to output buffers. | |
113 | * -------------------------------------------------------------------------- */ | |
114 | ||
115 | int _addReplyToBuffer(redisClient *c, char *s, size_t len) { | |
116 | size_t available = sizeof(c->buf)-c->bufpos; | |
117 | ||
118 | if (c->flags & REDIS_CLOSE_AFTER_REPLY) return REDIS_OK; | |
119 | ||
120 | /* If there already are entries in the reply list, we cannot | |
121 | * add anything more to the static buffer. */ | |
122 | if (listLength(c->reply) > 0) return REDIS_ERR; | |
123 | ||
124 | /* Check that the buffer has enough space available for this string. */ | |
125 | if (len > available) return REDIS_ERR; | |
126 | ||
127 | memcpy(c->buf+c->bufpos,s,len); | |
128 | c->bufpos+=len; | |
129 | return REDIS_OK; | |
130 | } | |
131 | ||
132 | void _addReplyObjectToList(redisClient *c, robj *o) { | |
133 | robj *tail; | |
134 | ||
135 | if (c->flags & REDIS_CLOSE_AFTER_REPLY) return; | |
136 | ||
137 | if (listLength(c->reply) == 0) { | |
138 | incrRefCount(o); | |
139 | listAddNodeTail(c->reply,o); | |
140 | } else { | |
141 | tail = listNodeValue(listLast(c->reply)); | |
142 | ||
143 | /* Append to this object when possible. */ | |
144 | if (tail->ptr != NULL && | |
145 | sdslen(tail->ptr)+sdslen(o->ptr) <= REDIS_REPLY_CHUNK_BYTES) | |
146 | { | |
147 | tail = dupLastObjectIfNeeded(c->reply); | |
148 | tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr)); | |
149 | } else { | |
150 | incrRefCount(o); | |
151 | listAddNodeTail(c->reply,o); | |
152 | } | |
153 | } | |
154 | c->reply_bytes += zmalloc_size(o->ptr); | |
155 | asyncCloseClientOnOutputBufferLimitReached(c); | |
156 | } | |
157 | ||
158 | /* This method takes responsibility over the sds. When it is no longer | |
159 | * needed it will be free'd, otherwise it ends up in a robj. */ | |
160 | void _addReplySdsToList(redisClient *c, sds s) { | |
161 | robj *tail; | |
162 | ||
163 | if (c->flags & REDIS_CLOSE_AFTER_REPLY) { | |
164 | sdsfree(s); | |
165 | return; | |
166 | } | |
167 | ||
168 | c->reply_bytes += zmalloc_size(s); | |
169 | if (listLength(c->reply) == 0) { | |
170 | listAddNodeTail(c->reply,createObject(REDIS_STRING,s)); | |
171 | } else { | |
172 | tail = listNodeValue(listLast(c->reply)); | |
173 | ||
174 | /* Append to this object when possible. */ | |
175 | if (tail->ptr != NULL && | |
176 | sdslen(tail->ptr)+sdslen(s) <= REDIS_REPLY_CHUNK_BYTES) | |
177 | { | |
178 | tail = dupLastObjectIfNeeded(c->reply); | |
179 | tail->ptr = sdscatlen(tail->ptr,s,sdslen(s)); | |
180 | sdsfree(s); | |
181 | } else { | |
182 | listAddNodeTail(c->reply,createObject(REDIS_STRING,s)); | |
183 | } | |
184 | } | |
185 | asyncCloseClientOnOutputBufferLimitReached(c); | |
186 | } | |
187 | ||
188 | void _addReplyStringToList(redisClient *c, char *s, size_t len) { | |
189 | robj *tail; | |
190 | ||
191 | if (c->flags & REDIS_CLOSE_AFTER_REPLY) return; | |
192 | ||
193 | if (listLength(c->reply) == 0) { | |
194 | robj *o = createStringObject(s,len); | |
195 | ||
196 | listAddNodeTail(c->reply,o); | |
197 | c->reply_bytes += zmalloc_size(o->ptr); | |
198 | } else { | |
199 | tail = listNodeValue(listLast(c->reply)); | |
200 | ||
201 | /* Append to this object when possible. */ | |
202 | if (tail->ptr != NULL && | |
203 | sdslen(tail->ptr)+len <= REDIS_REPLY_CHUNK_BYTES) | |
204 | { | |
205 | c->reply_bytes -= zmalloc_size(tail->ptr); | |
206 | tail = dupLastObjectIfNeeded(c->reply); | |
207 | tail->ptr = sdscatlen(tail->ptr,s,len); | |
208 | c->reply_bytes += zmalloc_size(tail->ptr); | |
209 | } else { | |
210 | robj *o = createStringObject(s,len); | |
211 | ||
212 | listAddNodeTail(c->reply,o); | |
213 | c->reply_bytes += zmalloc_size(o->ptr); | |
214 | } | |
215 | } | |
216 | asyncCloseClientOnOutputBufferLimitReached(c); | |
217 | } | |
218 | ||
219 | /* ----------------------------------------------------------------------------- | |
220 | * Higher level functions to queue data on the client output buffer. | |
221 | * The following functions are the ones that commands implementations will call. | |
222 | * -------------------------------------------------------------------------- */ | |
223 | ||
224 | void addReply(redisClient *c, robj *obj) { | |
225 | if (prepareClientToWrite(c) != REDIS_OK) return; | |
226 | ||
227 | /* This is an important place where we can avoid copy-on-write | |
228 | * when there is a saving child running, avoiding touching the | |
229 | * refcount field of the object if it's not needed. | |
230 | * | |
231 | * If the encoding is RAW and there is room in the static buffer | |
232 | * we'll be able to send the object to the client without | |
233 | * messing with its page. */ | |
234 | if (obj->encoding == REDIS_ENCODING_RAW) { | |
235 | if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK) | |
236 | _addReplyObjectToList(c,obj); | |
237 | } else if (obj->encoding == REDIS_ENCODING_INT) { | |
238 | /* Optimization: if there is room in the static buffer for 32 bytes | |
239 | * (more than the max chars a 64 bit integer can take as string) we | |
240 | * avoid decoding the object and go for the lower level approach. */ | |
241 | if (listLength(c->reply) == 0 && (sizeof(c->buf) - c->bufpos) >= 32) { | |
242 | char buf[32]; | |
243 | int len; | |
244 | ||
245 | len = ll2string(buf,sizeof(buf),(long)obj->ptr); | |
246 | if (_addReplyToBuffer(c,buf,len) == REDIS_OK) | |
247 | return; | |
248 | /* else... continue with the normal code path, but should never | |
249 | * happen actually since we verified there is room. */ | |
250 | } | |
251 | obj = getDecodedObject(obj); | |
252 | if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK) | |
253 | _addReplyObjectToList(c,obj); | |
254 | decrRefCount(obj); | |
255 | } else { | |
256 | redisPanic("Wrong obj->encoding in addReply()"); | |
257 | } | |
258 | } | |
259 | ||
260 | void addReplySds(redisClient *c, sds s) { | |
261 | if (prepareClientToWrite(c) != REDIS_OK) { | |
262 | /* The caller expects the sds to be free'd. */ | |
263 | sdsfree(s); | |
264 | return; | |
265 | } | |
266 | if (_addReplyToBuffer(c,s,sdslen(s)) == REDIS_OK) { | |
267 | sdsfree(s); | |
268 | } else { | |
269 | /* This method free's the sds when it is no longer needed. */ | |
270 | _addReplySdsToList(c,s); | |
271 | } | |
272 | } | |
273 | ||
274 | void addReplyString(redisClient *c, char *s, size_t len) { | |
275 | if (prepareClientToWrite(c) != REDIS_OK) return; | |
276 | if (_addReplyToBuffer(c,s,len) != REDIS_OK) | |
277 | _addReplyStringToList(c,s,len); | |
278 | } | |
279 | ||
280 | void addReplyErrorLength(redisClient *c, char *s, size_t len) { | |
281 | addReplyString(c,"-ERR ",5); | |
282 | addReplyString(c,s,len); | |
283 | addReplyString(c,"\r\n",2); | |
284 | } | |
285 | ||
286 | void addReplyError(redisClient *c, char *err) { | |
287 | addReplyErrorLength(c,err,strlen(err)); | |
288 | } | |
289 | ||
290 | void addReplyErrorFormat(redisClient *c, const char *fmt, ...) { | |
291 | size_t l, j; | |
292 | va_list ap; | |
293 | va_start(ap,fmt); | |
294 | sds s = sdscatvprintf(sdsempty(),fmt,ap); | |
295 | va_end(ap); | |
296 | /* Make sure there are no newlines in the string, otherwise invalid protocol | |
297 | * is emitted. */ | |
298 | l = sdslen(s); | |
299 | for (j = 0; j < l; j++) { | |
300 | if (s[j] == '\r' || s[j] == '\n') s[j] = ' '; | |
301 | } | |
302 | addReplyErrorLength(c,s,sdslen(s)); | |
303 | sdsfree(s); | |
304 | } | |
305 | ||
306 | void addReplyStatusLength(redisClient *c, char *s, size_t len) { | |
307 | addReplyString(c,"+",1); | |
308 | addReplyString(c,s,len); | |
309 | addReplyString(c,"\r\n",2); | |
310 | } | |
311 | ||
312 | void addReplyStatus(redisClient *c, char *status) { | |
313 | addReplyStatusLength(c,status,strlen(status)); | |
314 | } | |
315 | ||
316 | void addReplyStatusFormat(redisClient *c, const char *fmt, ...) { | |
317 | va_list ap; | |
318 | va_start(ap,fmt); | |
319 | sds s = sdscatvprintf(sdsempty(),fmt,ap); | |
320 | va_end(ap); | |
321 | addReplyStatusLength(c,s,sdslen(s)); | |
322 | sdsfree(s); | |
323 | } | |
324 | ||
325 | /* Adds an empty object to the reply list that will contain the multi bulk | |
326 | * length, which is not known when this function is called. */ | |
327 | void *addDeferredMultiBulkLength(redisClient *c) { | |
328 | /* Note that we install the write event here even if the object is not | |
329 | * ready to be sent, since we are sure that before returning to the | |
330 | * event loop setDeferredMultiBulkLength() will be called. */ | |
331 | if (prepareClientToWrite(c) != REDIS_OK) return NULL; | |
332 | listAddNodeTail(c->reply,createObject(REDIS_STRING,NULL)); | |
333 | return listLast(c->reply); | |
334 | } | |
335 | ||
336 | /* Populate the length object and try glueing it to the next chunk. */ | |
337 | void setDeferredMultiBulkLength(redisClient *c, void *node, long length) { | |
338 | listNode *ln = (listNode*)node; | |
339 | robj *len, *next; | |
340 | ||
341 | /* Abort when *node is NULL (see addDeferredMultiBulkLength). */ | |
342 | if (node == NULL) return; | |
343 | ||
344 | len = listNodeValue(ln); | |
345 | len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length); | |
346 | c->reply_bytes += zmalloc_size(len->ptr); | |
347 | if (ln->next != NULL) { | |
348 | next = listNodeValue(ln->next); | |
349 | ||
350 | /* Only glue when the next node is non-NULL (an sds in this case) */ | |
351 | if (next->ptr != NULL) { | |
352 | len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr)); | |
353 | listDelNode(c->reply,ln->next); | |
354 | } | |
355 | } | |
356 | asyncCloseClientOnOutputBufferLimitReached(c); | |
357 | } | |
358 | ||
359 | /* Add a duble as a bulk reply */ | |
360 | void addReplyDouble(redisClient *c, double d) { | |
361 | char dbuf[128], sbuf[128]; | |
362 | int dlen, slen; | |
363 | dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d); | |
364 | slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf); | |
365 | addReplyString(c,sbuf,slen); | |
366 | } | |
367 | ||
368 | /* Add a long long as integer reply or bulk len / multi bulk count. | |
369 | * Basically this is used to output <prefix><long long><crlf>. */ | |
370 | void addReplyLongLongWithPrefix(redisClient *c, long long ll, char prefix) { | |
371 | char buf[128]; | |
372 | int len; | |
373 | ||
374 | /* Things like $3\r\n or *2\r\n are emitted very often by the protocol | |
375 | * so we have a few shared objects to use if the integer is small | |
376 | * like it is most of the times. */ | |
377 | if (prefix == '*' && ll < REDIS_SHARED_BULKHDR_LEN) { | |
378 | addReply(c,shared.mbulkhdr[ll]); | |
379 | return; | |
380 | } else if (prefix == '$' && ll < REDIS_SHARED_BULKHDR_LEN) { | |
381 | addReply(c,shared.bulkhdr[ll]); | |
382 | return; | |
383 | } | |
384 | ||
385 | buf[0] = prefix; | |
386 | len = ll2string(buf+1,sizeof(buf)-1,ll); | |
387 | buf[len+1] = '\r'; | |
388 | buf[len+2] = '\n'; | |
389 | addReplyString(c,buf,len+3); | |
390 | } | |
391 | ||
392 | void addReplyLongLong(redisClient *c, long long ll) { | |
393 | if (ll == 0) | |
394 | addReply(c,shared.czero); | |
395 | else if (ll == 1) | |
396 | addReply(c,shared.cone); | |
397 | else | |
398 | addReplyLongLongWithPrefix(c,ll,':'); | |
399 | } | |
400 | ||
401 | void addReplyMultiBulkLen(redisClient *c, long length) { | |
402 | addReplyLongLongWithPrefix(c,length,'*'); | |
403 | } | |
404 | ||
405 | /* Create the length prefix of a bulk reply, example: $2234 */ | |
406 | void addReplyBulkLen(redisClient *c, robj *obj) { | |
407 | size_t len; | |
408 | ||
409 | if (obj->encoding == REDIS_ENCODING_RAW) { | |
410 | len = sdslen(obj->ptr); | |
411 | } else { | |
412 | long n = (long)obj->ptr; | |
413 | ||
414 | /* Compute how many bytes will take this integer as a radix 10 string */ | |
415 | len = 1; | |
416 | if (n < 0) { | |
417 | len++; | |
418 | n = -n; | |
419 | } | |
420 | while((n = n/10) != 0) { | |
421 | len++; | |
422 | } | |
423 | } | |
424 | addReplyLongLongWithPrefix(c,len,'$'); | |
425 | } | |
426 | ||
427 | /* Add a Redis Object as a bulk reply */ | |
428 | void addReplyBulk(redisClient *c, robj *obj) { | |
429 | addReplyBulkLen(c,obj); | |
430 | addReply(c,obj); | |
431 | addReply(c,shared.crlf); | |
432 | } | |
433 | ||
434 | /* Add a C buffer as bulk reply */ | |
435 | void addReplyBulkCBuffer(redisClient *c, void *p, size_t len) { | |
436 | addReplyLongLongWithPrefix(c,len,'$'); | |
437 | addReplyString(c,p,len); | |
438 | addReply(c,shared.crlf); | |
439 | } | |
440 | ||
441 | /* Add a C nul term string as bulk reply */ | |
442 | void addReplyBulkCString(redisClient *c, char *s) { | |
443 | if (s == NULL) { | |
444 | addReply(c,shared.nullbulk); | |
445 | } else { | |
446 | addReplyBulkCBuffer(c,s,strlen(s)); | |
447 | } | |
448 | } | |
449 | ||
450 | /* Add a long long as a bulk reply */ | |
451 | void addReplyBulkLongLong(redisClient *c, long long ll) { | |
452 | char buf[64]; | |
453 | int len; | |
454 | ||
455 | len = ll2string(buf,64,ll); | |
456 | addReplyBulkCBuffer(c,buf,len); | |
457 | } | |
458 | ||
459 | /* Copy 'src' client output buffers into 'dst' client output buffers. | |
460 | * The function takes care of freeing the old output buffers of the | |
461 | * destination client. */ | |
462 | void copyClientOutputBuffer(redisClient *dst, redisClient *src) { | |
463 | listRelease(dst->reply); | |
464 | dst->reply = listDup(src->reply); | |
465 | memcpy(dst->buf,src->buf,src->bufpos); | |
466 | dst->bufpos = src->bufpos; | |
467 | dst->reply_bytes = src->reply_bytes; | |
468 | } | |
469 | ||
470 | static void acceptCommonHandler(int fd) { | |
471 | redisClient *c; | |
472 | if ((c = createClient(fd)) == NULL) { | |
473 | redisLog(REDIS_WARNING,"Error allocating resoures for the client"); | |
474 | close(fd); /* May be already closed, just ingore errors */ | |
475 | return; | |
476 | } | |
477 | /* If maxclient directive is set and this is one client more... close the | |
478 | * connection. Note that we create the client instead to check before | |
479 | * for this condition, since now the socket is already set in nonblocking | |
480 | * mode and we can send an error for free using the Kernel I/O */ | |
481 | if (listLength(server.clients) > server.maxclients) { | |
482 | char *err = "-ERR max number of clients reached\r\n"; | |
483 | ||
484 | /* That's a best effort error message, don't check write errors */ | |
485 | if (write(c->fd,err,strlen(err)) == -1) { | |
486 | /* Nothing to do, Just to avoid the warning... */ | |
487 | } | |
488 | server.stat_rejected_conn++; | |
489 | freeClient(c); | |
490 | return; | |
491 | } | |
492 | server.stat_numconnections++; | |
493 | } | |
494 | ||
495 | void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) { | |
496 | int cport, cfd; | |
497 | char cip[128]; | |
498 | REDIS_NOTUSED(el); | |
499 | REDIS_NOTUSED(mask); | |
500 | REDIS_NOTUSED(privdata); | |
501 | ||
502 | cfd = anetTcpAccept(server.neterr, fd, cip, &cport); | |
503 | if (cfd == AE_ERR) { | |
504 | redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr); | |
505 | return; | |
506 | } | |
507 | redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport); | |
508 | acceptCommonHandler(cfd); | |
509 | } | |
510 | ||
511 | void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) { | |
512 | int cfd; | |
513 | REDIS_NOTUSED(el); | |
514 | REDIS_NOTUSED(mask); | |
515 | REDIS_NOTUSED(privdata); | |
516 | ||
517 | cfd = anetUnixAccept(server.neterr, fd); | |
518 | if (cfd == AE_ERR) { | |
519 | redisLog(REDIS_WARNING,"Accepting client connection: %s", server.neterr); | |
520 | return; | |
521 | } | |
522 | redisLog(REDIS_VERBOSE,"Accepted connection to %s", server.unixsocket); | |
523 | acceptCommonHandler(cfd); | |
524 | } | |
525 | ||
526 | ||
527 | static void freeClientArgv(redisClient *c) { | |
528 | int j; | |
529 | for (j = 0; j < c->argc; j++) | |
530 | decrRefCount(c->argv[j]); | |
531 | c->argc = 0; | |
532 | c->cmd = NULL; | |
533 | } | |
534 | ||
535 | void freeClient(redisClient *c) { | |
536 | listNode *ln; | |
537 | ||
538 | /* If this is marked as current client unset it */ | |
539 | if (server.current_client == c) server.current_client = NULL; | |
540 | ||
541 | /* Note that if the client we are freeing is blocked into a blocking | |
542 | * call, we have to set querybuf to NULL *before* to call | |
543 | * unblockClientWaitingData() to avoid processInputBuffer() will get | |
544 | * called. Also it is important to remove the file events after | |
545 | * this, because this call adds the READABLE event. */ | |
546 | sdsfree(c->querybuf); | |
547 | c->querybuf = NULL; | |
548 | if (c->flags & REDIS_BLOCKED) | |
549 | unblockClientWaitingData(c); | |
550 | ||
551 | /* UNWATCH all the keys */ | |
552 | unwatchAllKeys(c); | |
553 | listRelease(c->watched_keys); | |
554 | /* Unsubscribe from all the pubsub channels */ | |
555 | pubsubUnsubscribeAllChannels(c,0); | |
556 | pubsubUnsubscribeAllPatterns(c,0); | |
557 | dictRelease(c->pubsub_channels); | |
558 | listRelease(c->pubsub_patterns); | |
559 | /* Obvious cleanup */ | |
560 | aeDeleteFileEvent(server.el,c->fd,AE_READABLE); | |
561 | aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); | |
562 | listRelease(c->reply); | |
563 | freeClientArgv(c); | |
564 | close(c->fd); | |
565 | /* Remove from the list of clients */ | |
566 | ln = listSearchKey(server.clients,c); | |
567 | redisAssert(ln != NULL); | |
568 | listDelNode(server.clients,ln); | |
569 | /* When client was just unblocked because of a blocking operation, | |
570 | * remove it from the list with unblocked clients. */ | |
571 | if (c->flags & REDIS_UNBLOCKED) { | |
572 | ln = listSearchKey(server.unblocked_clients,c); | |
573 | redisAssert(ln != NULL); | |
574 | listDelNode(server.unblocked_clients,ln); | |
575 | } | |
576 | listRelease(c->io_keys); | |
577 | /* Master/slave cleanup. | |
578 | * Case 1: we lost the connection with a slave. */ | |
579 | if (c->flags & REDIS_SLAVE) { | |
580 | if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1) | |
581 | close(c->repldbfd); | |
582 | list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves; | |
583 | ln = listSearchKey(l,c); | |
584 | redisAssert(ln != NULL); | |
585 | listDelNode(l,ln); | |
586 | } | |
587 | ||
588 | /* Case 2: we lost the connection with the master. */ | |
589 | if (c->flags & REDIS_MASTER) { | |
590 | server.master = NULL; | |
591 | server.repl_state = REDIS_REPL_CONNECT; | |
592 | server.repl_down_since = time(NULL); | |
593 | /* Since we lost the connection with the master, we should also | |
594 | * close the connection with all our slaves if we have any, so | |
595 | * when we'll resync with the master the other slaves will sync again | |
596 | * with us as well. Note that also when the slave is not connected | |
597 | * to the master it will keep refusing connections by other slaves. | |
598 | * | |
599 | * We do this only if server.masterhost != NULL. If it is NULL this | |
600 | * means the user called SLAVEOF NO ONE and we are freeing our | |
601 | * link with the master, so no need to close link with slaves. */ | |
602 | if (server.masterhost != NULL) { | |
603 | while (listLength(server.slaves)) { | |
604 | ln = listFirst(server.slaves); | |
605 | freeClient((redisClient*)ln->value); | |
606 | } | |
607 | } | |
608 | } | |
609 | ||
610 | /* If this client was scheduled for async freeing we need to remove it | |
611 | * from the queue. */ | |
612 | if (c->flags & REDIS_CLOSE_ASAP) { | |
613 | ln = listSearchKey(server.clients_to_close,c); | |
614 | redisAssert(ln != NULL); | |
615 | listDelNode(server.clients_to_close,ln); | |
616 | } | |
617 | ||
618 | /* Release memory */ | |
619 | zfree(c->argv); | |
620 | freeClientMultiState(c); | |
621 | zfree(c); | |
622 | } | |
623 | ||
624 | /* Schedule a client to free it at a safe time in the serverCron() function. | |
625 | * This function is useful when we need to terminate a client but we are in | |
626 | * a context where calling freeClient() is not possible, because the client | |
627 | * should be valid for the continuation of the flow of the program. */ | |
628 | void freeClientAsync(redisClient *c) { | |
629 | if (c->flags & REDIS_CLOSE_ASAP) return; | |
630 | c->flags |= REDIS_CLOSE_ASAP; | |
631 | listAddNodeTail(server.clients_to_close,c); | |
632 | } | |
633 | ||
634 | void freeClientsInAsyncFreeQueue(void) { | |
635 | while (listLength(server.clients_to_close)) { | |
636 | listNode *ln = listFirst(server.clients_to_close); | |
637 | redisClient *c = listNodeValue(ln); | |
638 | ||
639 | c->flags &= ~REDIS_CLOSE_ASAP; | |
640 | freeClient(c); | |
641 | listDelNode(server.clients_to_close,ln); | |
642 | } | |
643 | } | |
644 | ||
645 | void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) { | |
646 | redisClient *c = privdata; | |
647 | int nwritten = 0, totwritten = 0, objlen; | |
648 | size_t objmem; | |
649 | robj *o; | |
650 | REDIS_NOTUSED(el); | |
651 | REDIS_NOTUSED(mask); | |
652 | ||
653 | while(c->bufpos > 0 || listLength(c->reply)) { | |
654 | if (c->bufpos > 0) { | |
655 | if (c->flags & REDIS_MASTER) { | |
656 | /* Don't reply to a master */ | |
657 | nwritten = c->bufpos - c->sentlen; | |
658 | } else { | |
659 | nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen); | |
660 | if (nwritten <= 0) break; | |
661 | } | |
662 | c->sentlen += nwritten; | |
663 | totwritten += nwritten; | |
664 | ||
665 | /* If the buffer was sent, set bufpos to zero to continue with | |
666 | * the remainder of the reply. */ | |
667 | if (c->sentlen == c->bufpos) { | |
668 | c->bufpos = 0; | |
669 | c->sentlen = 0; | |
670 | } | |
671 | } else { | |
672 | o = listNodeValue(listFirst(c->reply)); | |
673 | objlen = sdslen(o->ptr); | |
674 | objmem = zmalloc_size(o->ptr); | |
675 | ||
676 | if (objlen == 0) { | |
677 | listDelNode(c->reply,listFirst(c->reply)); | |
678 | continue; | |
679 | } | |
680 | ||
681 | if (c->flags & REDIS_MASTER) { | |
682 | /* Don't reply to a master */ | |
683 | nwritten = objlen - c->sentlen; | |
684 | } else { | |
685 | nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen); | |
686 | if (nwritten <= 0) break; | |
687 | } | |
688 | c->sentlen += nwritten; | |
689 | totwritten += nwritten; | |
690 | ||
691 | /* If we fully sent the object on head go to the next one */ | |
692 | if (c->sentlen == objlen) { | |
693 | listDelNode(c->reply,listFirst(c->reply)); | |
694 | c->sentlen = 0; | |
695 | c->reply_bytes -= objmem; | |
696 | } | |
697 | } | |
698 | /* Note that we avoid to send more than REDIS_MAX_WRITE_PER_EVENT | |
699 | * bytes, in a single threaded server it's a good idea to serve | |
700 | * other clients as well, even if a very large request comes from | |
701 | * super fast link that is always able to accept data (in real world | |
702 | * scenario think about 'KEYS *' against the loopback interface). | |
703 | * | |
704 | * However if we are over the maxmemory limit we ignore that and | |
705 | * just deliver as much data as it is possible to deliver. */ | |
706 | if (totwritten > REDIS_MAX_WRITE_PER_EVENT && | |
707 | (server.maxmemory == 0 || | |
708 | zmalloc_used_memory() < server.maxmemory)) break; | |
709 | } | |
710 | if (nwritten == -1) { | |
711 | if (errno == EAGAIN) { | |
712 | nwritten = 0; | |
713 | } else { | |
714 | redisLog(REDIS_VERBOSE, | |
715 | "Error writing to client: %s", strerror(errno)); | |
716 | freeClient(c); | |
717 | return; | |
718 | } | |
719 | } | |
720 | if (totwritten > 0) c->lastinteraction = time(NULL); | |
721 | if (c->bufpos == 0 && listLength(c->reply) == 0) { | |
722 | c->sentlen = 0; | |
723 | aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); | |
724 | ||
725 | /* Close connection after entire reply has been sent. */ | |
726 | if (c->flags & REDIS_CLOSE_AFTER_REPLY) freeClient(c); | |
727 | } | |
728 | } | |
729 | ||
730 | /* resetClient prepare the client to process the next command */ | |
731 | void resetClient(redisClient *c) { | |
732 | freeClientArgv(c); | |
733 | c->reqtype = 0; | |
734 | c->multibulklen = 0; | |
735 | c->bulklen = -1; | |
736 | /* We clear the ASKING flag as well if we are not inside a MULTI. */ | |
737 | if (!(c->flags & REDIS_MULTI)) c->flags &= (~REDIS_ASKING); | |
738 | } | |
739 | ||
740 | void closeTimedoutClients(void) { | |
741 | redisClient *c; | |
742 | listNode *ln; | |
743 | time_t now = time(NULL); | |
744 | listIter li; | |
745 | ||
746 | listRewind(server.clients,&li); | |
747 | while ((ln = listNext(&li)) != NULL) { | |
748 | c = listNodeValue(ln); | |
749 | if (server.maxidletime && | |
750 | !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */ | |
751 | !(c->flags & REDIS_MASTER) && /* no timeout for masters */ | |
752 | !(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */ | |
753 | dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */ | |
754 | listLength(c->pubsub_patterns) == 0 && | |
755 | (now - c->lastinteraction > server.maxidletime)) | |
756 | { | |
757 | redisLog(REDIS_VERBOSE,"Closing idle client"); | |
758 | freeClient(c); | |
759 | } else if (c->flags & REDIS_BLOCKED) { | |
760 | if (c->bpop.timeout != 0 && c->bpop.timeout < now) { | |
761 | addReply(c,shared.nullmultibulk); | |
762 | unblockClientWaitingData(c); | |
763 | } | |
764 | } | |
765 | } | |
766 | } | |
767 | ||
768 | int processInlineBuffer(redisClient *c) { | |
769 | char *newline = strstr(c->querybuf,"\r\n"); | |
770 | int argc, j; | |
771 | sds *argv; | |
772 | size_t querylen; | |
773 | ||
774 | /* Nothing to do without a \r\n */ | |
775 | if (newline == NULL) { | |
776 | if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) { | |
777 | addReplyError(c,"Protocol error: too big inline request"); | |
778 | setProtocolError(c,0); | |
779 | } | |
780 | return REDIS_ERR; | |
781 | } | |
782 | ||
783 | /* Split the input buffer up to the \r\n */ | |
784 | querylen = newline-(c->querybuf); | |
785 | argv = sdssplitlen(c->querybuf,querylen," ",1,&argc); | |
786 | ||
787 | /* Leave data after the first line of the query in the buffer */ | |
788 | c->querybuf = sdsrange(c->querybuf,querylen+2,-1); | |
789 | ||
790 | /* Setup argv array on client structure */ | |
791 | if (c->argv) zfree(c->argv); | |
792 | c->argv = zmalloc(sizeof(robj*)*argc); | |
793 | ||
794 | /* Create redis objects for all arguments. */ | |
795 | for (c->argc = 0, j = 0; j < argc; j++) { | |
796 | if (sdslen(argv[j])) { | |
797 | c->argv[c->argc] = createObject(REDIS_STRING,argv[j]); | |
798 | c->argc++; | |
799 | } else { | |
800 | sdsfree(argv[j]); | |
801 | } | |
802 | } | |
803 | zfree(argv); | |
804 | return REDIS_OK; | |
805 | } | |
806 | ||
807 | /* Helper function. Trims query buffer to make the function that processes | |
808 | * multi bulk requests idempotent. */ | |
809 | static void setProtocolError(redisClient *c, int pos) { | |
810 | if (server.verbosity >= REDIS_VERBOSE) { | |
811 | sds client = getClientInfoString(c); | |
812 | redisLog(REDIS_VERBOSE, | |
813 | "Protocol error from client: %s", client); | |
814 | sdsfree(client); | |
815 | } | |
816 | c->flags |= REDIS_CLOSE_AFTER_REPLY; | |
817 | c->querybuf = sdsrange(c->querybuf,pos,-1); | |
818 | } | |
819 | ||
820 | int processMultibulkBuffer(redisClient *c) { | |
821 | char *newline = NULL; | |
822 | int pos = 0, ok; | |
823 | long long ll; | |
824 | ||
825 | if (c->multibulklen == 0) { | |
826 | /* The client should have been reset */ | |
827 | redisAssertWithInfo(c,NULL,c->argc == 0); | |
828 | ||
829 | /* Multi bulk length cannot be read without a \r\n */ | |
830 | newline = strchr(c->querybuf,'\r'); | |
831 | if (newline == NULL) { | |
832 | if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) { | |
833 | addReplyError(c,"Protocol error: too big mbulk count string"); | |
834 | setProtocolError(c,0); | |
835 | } | |
836 | return REDIS_ERR; | |
837 | } | |
838 | ||
839 | /* Buffer should also contain \n */ | |
840 | if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) | |
841 | return REDIS_ERR; | |
842 | ||
843 | /* We know for sure there is a whole line since newline != NULL, | |
844 | * so go ahead and find out the multi bulk length. */ | |
845 | redisAssertWithInfo(c,NULL,c->querybuf[0] == '*'); | |
846 | ok = string2ll(c->querybuf+1,newline-(c->querybuf+1),&ll); | |
847 | if (!ok || ll > 1024*1024) { | |
848 | addReplyError(c,"Protocol error: invalid multibulk length"); | |
849 | setProtocolError(c,pos); | |
850 | return REDIS_ERR; | |
851 | } | |
852 | ||
853 | pos = (newline-c->querybuf)+2; | |
854 | if (ll <= 0) { | |
855 | c->querybuf = sdsrange(c->querybuf,pos,-1); | |
856 | return REDIS_OK; | |
857 | } | |
858 | ||
859 | c->multibulklen = ll; | |
860 | ||
861 | /* Setup argv array on client structure */ | |
862 | if (c->argv) zfree(c->argv); | |
863 | c->argv = zmalloc(sizeof(robj*)*c->multibulklen); | |
864 | } | |
865 | ||
866 | redisAssertWithInfo(c,NULL,c->multibulklen > 0); | |
867 | while(c->multibulklen) { | |
868 | /* Read bulk length if unknown */ | |
869 | if (c->bulklen == -1) { | |
870 | newline = strchr(c->querybuf+pos,'\r'); | |
871 | if (newline == NULL) { | |
872 | if (sdslen(c->querybuf) > REDIS_INLINE_MAX_SIZE) { | |
873 | addReplyError(c,"Protocol error: too big bulk count string"); | |
874 | setProtocolError(c,0); | |
875 | } | |
876 | break; | |
877 | } | |
878 | ||
879 | /* Buffer should also contain \n */ | |
880 | if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) | |
881 | break; | |
882 | ||
883 | if (c->querybuf[pos] != '$') { | |
884 | addReplyErrorFormat(c, | |
885 | "Protocol error: expected '$', got '%c'", | |
886 | c->querybuf[pos]); | |
887 | setProtocolError(c,pos); | |
888 | return REDIS_ERR; | |
889 | } | |
890 | ||
891 | ok = string2ll(c->querybuf+pos+1,newline-(c->querybuf+pos+1),&ll); | |
892 | if (!ok || ll < 0 || ll > 512*1024*1024) { | |
893 | addReplyError(c,"Protocol error: invalid bulk length"); | |
894 | setProtocolError(c,pos); | |
895 | return REDIS_ERR; | |
896 | } | |
897 | ||
898 | pos += newline-(c->querybuf+pos)+2; | |
899 | if (ll >= REDIS_MBULK_BIG_ARG) { | |
900 | /* If we are going to read a large object from network | |
901 | * try to make it likely that it will start at c->querybuf | |
902 | * boundary so that we can optimized object creation | |
903 | * avoiding a large copy of data. */ | |
904 | c->querybuf = sdsrange(c->querybuf,pos,-1); | |
905 | pos = 0; | |
906 | /* Hint the sds library about the amount of bytes this string is | |
907 | * going to contain. */ | |
908 | c->querybuf = sdsMakeRoomFor(c->querybuf,ll+2); | |
909 | } | |
910 | c->bulklen = ll; | |
911 | } | |
912 | ||
913 | /* Read bulk argument */ | |
914 | if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) { | |
915 | /* Not enough data (+2 == trailing \r\n) */ | |
916 | break; | |
917 | } else { | |
918 | /* Optimization: if the buffer contanins JUST our bulk element | |
919 | * instead of creating a new object by *copying* the sds we | |
920 | * just use the current sds string. */ | |
921 | if (pos == 0 && | |
922 | c->bulklen >= REDIS_MBULK_BIG_ARG && | |
923 | (signed) sdslen(c->querybuf) == c->bulklen+2) | |
924 | { | |
925 | c->argv[c->argc++] = createObject(REDIS_STRING,c->querybuf); | |
926 | sdsIncrLen(c->querybuf,-2); /* remove CRLF */ | |
927 | c->querybuf = sdsempty(); | |
928 | /* Assume that if we saw a fat argument we'll see another one | |
929 | * likely... */ | |
930 | c->querybuf = sdsMakeRoomFor(c->querybuf,c->bulklen+2); | |
931 | pos = 0; | |
932 | } else { | |
933 | c->argv[c->argc++] = | |
934 | createStringObject(c->querybuf+pos,c->bulklen); | |
935 | pos += c->bulklen+2; | |
936 | } | |
937 | c->bulklen = -1; | |
938 | c->multibulklen--; | |
939 | } | |
940 | } | |
941 | ||
942 | /* Trim to pos */ | |
943 | if (pos) c->querybuf = sdsrange(c->querybuf,pos,-1); | |
944 | ||
945 | /* We're done when c->multibulk == 0 */ | |
946 | if (c->multibulklen == 0) return REDIS_OK; | |
947 | ||
948 | /* Still not read to process the command */ | |
949 | return REDIS_ERR; | |
950 | } | |
951 | ||
952 | void processInputBuffer(redisClient *c) { | |
953 | /* Keep processing while there is something in the input buffer */ | |
954 | while(sdslen(c->querybuf)) { | |
955 | /* Immediately abort if the client is in the middle of something. */ | |
956 | if (c->flags & REDIS_BLOCKED) return; | |
957 | ||
958 | /* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is | |
959 | * written to the client. Make sure to not let the reply grow after | |
960 | * this flag has been set (i.e. don't process more commands). */ | |
961 | if (c->flags & REDIS_CLOSE_AFTER_REPLY) return; | |
962 | ||
963 | /* Determine request type when unknown. */ | |
964 | if (!c->reqtype) { | |
965 | if (c->querybuf[0] == '*') { | |
966 | c->reqtype = REDIS_REQ_MULTIBULK; | |
967 | } else { | |
968 | c->reqtype = REDIS_REQ_INLINE; | |
969 | } | |
970 | } | |
971 | ||
972 | if (c->reqtype == REDIS_REQ_INLINE) { | |
973 | if (processInlineBuffer(c) != REDIS_OK) break; | |
974 | } else if (c->reqtype == REDIS_REQ_MULTIBULK) { | |
975 | if (processMultibulkBuffer(c) != REDIS_OK) break; | |
976 | } else { | |
977 | redisPanic("Unknown request type"); | |
978 | } | |
979 | ||
980 | /* Multibulk processing could see a <= 0 length. */ | |
981 | if (c->argc == 0) { | |
982 | resetClient(c); | |
983 | } else { | |
984 | /* Only reset the client when the command was executed. */ | |
985 | if (processCommand(c) == REDIS_OK) | |
986 | resetClient(c); | |
987 | } | |
988 | } | |
989 | } | |
990 | ||
991 | void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) { | |
992 | redisClient *c = (redisClient*) privdata; | |
993 | int nread, readlen; | |
994 | size_t qblen; | |
995 | REDIS_NOTUSED(el); | |
996 | REDIS_NOTUSED(mask); | |
997 | ||
998 | server.current_client = c; | |
999 | readlen = REDIS_IOBUF_LEN; | |
1000 | /* If this is a multi bulk request, and we are processing a bulk reply | |
1001 | * that is large enough, try to maximize the probabilty that the query | |
1002 | * buffer contains excatly the SDS string representing the object, even | |
1003 | * at the risk of requring more read(2) calls. This way the function | |
1004 | * processMultiBulkBuffer() can avoid copying buffers to create the | |
1005 | * Redis Object representing the argument. */ | |
1006 | if (c->reqtype == REDIS_REQ_MULTIBULK && c->multibulklen && c->bulklen != -1 | |
1007 | && c->bulklen >= REDIS_MBULK_BIG_ARG) | |
1008 | { | |
1009 | int remaining = (unsigned)(c->bulklen+2)-sdslen(c->querybuf); | |
1010 | ||
1011 | if (remaining < readlen) readlen = remaining; | |
1012 | } | |
1013 | ||
1014 | qblen = sdslen(c->querybuf); | |
1015 | c->querybuf = sdsMakeRoomFor(c->querybuf, readlen); | |
1016 | nread = read(fd, c->querybuf+qblen, readlen); | |
1017 | if (nread == -1) { | |
1018 | if (errno == EAGAIN) { | |
1019 | nread = 0; | |
1020 | } else { | |
1021 | redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno)); | |
1022 | freeClient(c); | |
1023 | return; | |
1024 | } | |
1025 | } else if (nread == 0) { | |
1026 | redisLog(REDIS_VERBOSE, "Client closed connection"); | |
1027 | freeClient(c); | |
1028 | return; | |
1029 | } | |
1030 | if (nread) { | |
1031 | sdsIncrLen(c->querybuf,nread); | |
1032 | c->lastinteraction = time(NULL); | |
1033 | } else { | |
1034 | server.current_client = NULL; | |
1035 | return; | |
1036 | } | |
1037 | if (sdslen(c->querybuf) > server.client_max_querybuf_len) { | |
1038 | sds ci = getClientInfoString(c), bytes = sdsempty(); | |
1039 | ||
1040 | bytes = sdscatrepr(bytes,c->querybuf,64); | |
1041 | redisLog(REDIS_WARNING,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci, bytes); | |
1042 | sdsfree(ci); | |
1043 | sdsfree(bytes); | |
1044 | freeClient(c); | |
1045 | return; | |
1046 | } | |
1047 | processInputBuffer(c); | |
1048 | server.current_client = NULL; | |
1049 | } | |
1050 | ||
1051 | void getClientsMaxBuffers(unsigned long *longest_output_list, | |
1052 | unsigned long *biggest_input_buffer) { | |
1053 | redisClient *c; | |
1054 | listNode *ln; | |
1055 | listIter li; | |
1056 | unsigned long lol = 0, bib = 0; | |
1057 | ||
1058 | listRewind(server.clients,&li); | |
1059 | while ((ln = listNext(&li)) != NULL) { | |
1060 | c = listNodeValue(ln); | |
1061 | ||
1062 | if (listLength(c->reply) > lol) lol = listLength(c->reply); | |
1063 | if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf); | |
1064 | } | |
1065 | *longest_output_list = lol; | |
1066 | *biggest_input_buffer = bib; | |
1067 | } | |
1068 | ||
1069 | /* Turn a Redis client into an sds string representing its state. */ | |
1070 | sds getClientInfoString(redisClient *client) { | |
1071 | char ip[32], flags[16], events[3], *p; | |
1072 | int port; | |
1073 | time_t now = time(NULL); | |
1074 | int emask; | |
1075 | ||
1076 | if (anetPeerToString(client->fd,ip,&port) == -1) { | |
1077 | ip[0] = '?'; | |
1078 | ip[1] = '\0'; | |
1079 | port = 0; | |
1080 | } | |
1081 | p = flags; | |
1082 | if (client->flags & REDIS_SLAVE) { | |
1083 | if (client->flags & REDIS_MONITOR) | |
1084 | *p++ = 'O'; | |
1085 | else | |
1086 | *p++ = 'S'; | |
1087 | } | |
1088 | if (client->flags & REDIS_MASTER) *p++ = 'M'; | |
1089 | if (client->flags & REDIS_MULTI) *p++ = 'x'; | |
1090 | if (client->flags & REDIS_BLOCKED) *p++ = 'b'; | |
1091 | if (client->flags & REDIS_DIRTY_CAS) *p++ = 'd'; | |
1092 | if (client->flags & REDIS_CLOSE_AFTER_REPLY) *p++ = 'c'; | |
1093 | if (client->flags & REDIS_UNBLOCKED) *p++ = 'u'; | |
1094 | if (client->flags & REDIS_CLOSE_ASAP) *p++ = 'A'; | |
1095 | if (p == flags) *p++ = 'N'; | |
1096 | *p++ = '\0'; | |
1097 | ||
1098 | emask = client->fd == -1 ? 0 : aeGetFileEvents(server.el,client->fd); | |
1099 | p = events; | |
1100 | if (emask & AE_READABLE) *p++ = 'r'; | |
1101 | if (emask & AE_WRITABLE) *p++ = 'w'; | |
1102 | *p = '\0'; | |
1103 | return sdscatprintf(sdsempty(), | |
1104 | "addr=%s:%d fd=%d idle=%ld flags=%s db=%d sub=%d psub=%d qbuf=%lu obl=%lu oll=%lu omem=%lu events=%s cmd=%s", | |
1105 | ip,port,client->fd, | |
1106 | (long)(now - client->lastinteraction), | |
1107 | flags, | |
1108 | client->db->id, | |
1109 | (int) dictSize(client->pubsub_channels), | |
1110 | (int) listLength(client->pubsub_patterns), | |
1111 | (unsigned long) sdslen(client->querybuf), | |
1112 | (unsigned long) client->bufpos, | |
1113 | (unsigned long) listLength(client->reply), | |
1114 | getClientOutputBufferMemoryUsage(client), | |
1115 | events, | |
1116 | client->lastcmd ? client->lastcmd->name : "NULL"); | |
1117 | } | |
1118 | ||
1119 | sds getAllClientsInfoString(void) { | |
1120 | listNode *ln; | |
1121 | listIter li; | |
1122 | redisClient *client; | |
1123 | sds o = sdsempty(); | |
1124 | ||
1125 | listRewind(server.clients,&li); | |
1126 | while ((ln = listNext(&li)) != NULL) { | |
1127 | sds cs; | |
1128 | ||
1129 | client = listNodeValue(ln); | |
1130 | cs = getClientInfoString(client); | |
1131 | o = sdscatsds(o,cs); | |
1132 | sdsfree(cs); | |
1133 | o = sdscatlen(o,"\n",1); | |
1134 | } | |
1135 | return o; | |
1136 | } | |
1137 | ||
1138 | void clientCommand(redisClient *c) { | |
1139 | listNode *ln; | |
1140 | listIter li; | |
1141 | redisClient *client; | |
1142 | ||
1143 | if (!strcasecmp(c->argv[1]->ptr,"list") && c->argc == 2) { | |
1144 | sds o = getAllClientsInfoString(); | |
1145 | addReplyBulkCBuffer(c,o,sdslen(o)); | |
1146 | sdsfree(o); | |
1147 | } else if (!strcasecmp(c->argv[1]->ptr,"kill") && c->argc == 3) { | |
1148 | listRewind(server.clients,&li); | |
1149 | while ((ln = listNext(&li)) != NULL) { | |
1150 | char ip[32], addr[64]; | |
1151 | int port; | |
1152 | ||
1153 | client = listNodeValue(ln); | |
1154 | if (anetPeerToString(client->fd,ip,&port) == -1) continue; | |
1155 | snprintf(addr,sizeof(addr),"%s:%d",ip,port); | |
1156 | if (strcmp(addr,c->argv[2]->ptr) == 0) { | |
1157 | addReply(c,shared.ok); | |
1158 | if (c == client) { | |
1159 | client->flags |= REDIS_CLOSE_AFTER_REPLY; | |
1160 | } else { | |
1161 | freeClient(client); | |
1162 | } | |
1163 | return; | |
1164 | } | |
1165 | } | |
1166 | addReplyError(c,"No such client"); | |
1167 | } else { | |
1168 | addReplyError(c, "Syntax error, try CLIENT (LIST | KILL ip:port)"); | |
1169 | } | |
1170 | } | |
1171 | ||
1172 | /* Rewrite the command vector of the client. All the new objects ref count | |
1173 | * is incremented. The old command vector is freed, and the old objects | |
1174 | * ref count is decremented. */ | |
1175 | void rewriteClientCommandVector(redisClient *c, int argc, ...) { | |
1176 | va_list ap; | |
1177 | int j; | |
1178 | robj **argv; /* The new argument vector */ | |
1179 | ||
1180 | argv = zmalloc(sizeof(robj*)*argc); | |
1181 | va_start(ap,argc); | |
1182 | for (j = 0; j < argc; j++) { | |
1183 | robj *a; | |
1184 | ||
1185 | a = va_arg(ap, robj*); | |
1186 | argv[j] = a; | |
1187 | incrRefCount(a); | |
1188 | } | |
1189 | /* We free the objects in the original vector at the end, so we are | |
1190 | * sure that if the same objects are reused in the new vector the | |
1191 | * refcount gets incremented before it gets decremented. */ | |
1192 | for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]); | |
1193 | zfree(c->argv); | |
1194 | /* Replace argv and argc with our new versions. */ | |
1195 | c->argv = argv; | |
1196 | c->argc = argc; | |
1197 | c->cmd = lookupCommand(c->argv[0]->ptr); | |
1198 | redisAssertWithInfo(c,NULL,c->cmd != NULL); | |
1199 | va_end(ap); | |
1200 | } | |
1201 | ||
1202 | /* Rewrite a single item in the command vector. | |
1203 | * The new val ref count is incremented, and the old decremented. */ | |
1204 | void rewriteClientCommandArgument(redisClient *c, int i, robj *newval) { | |
1205 | robj *oldval; | |
1206 | ||
1207 | redisAssertWithInfo(c,NULL,i < c->argc); | |
1208 | oldval = c->argv[i]; | |
1209 | c->argv[i] = newval; | |
1210 | incrRefCount(newval); | |
1211 | decrRefCount(oldval); | |
1212 | ||
1213 | /* If this is the command name make sure to fix c->cmd. */ | |
1214 | if (i == 0) { | |
1215 | c->cmd = lookupCommand(c->argv[0]->ptr); | |
1216 | redisAssertWithInfo(c,NULL,c->cmd != NULL); | |
1217 | } | |
1218 | } | |
1219 | ||
1220 | /* This function returns the number of bytes that Redis is virtually | |
1221 | * using to store the reply still not read by the client. | |
1222 | * It is "virtual" since the reply output list may contain objects that | |
1223 | * are shared and are not really using additional memory. | |
1224 | * | |
1225 | * The function returns the total sum of the length of all the objects | |
1226 | * stored in the output list, plus the memory used to allocate every | |
1227 | * list node. The static reply buffer is not taken into account since it | |
1228 | * is allocated anyway. | |
1229 | * | |
1230 | * Note: this function is very fast so can be called as many time as | |
1231 | * the caller wishes. The main usage of this function currently is | |
1232 | * enforcing the client output length limits. */ | |
1233 | unsigned long getClientOutputBufferMemoryUsage(redisClient *c) { | |
1234 | unsigned long list_item_size = sizeof(listNode)+sizeof(robj); | |
1235 | ||
1236 | return c->reply_bytes + (list_item_size*listLength(c->reply)); | |
1237 | } | |
1238 | ||
1239 | /* Get the class of a client, used in order to envorce limits to different | |
1240 | * classes of clients. | |
1241 | * | |
1242 | * The function will return one of the following: | |
1243 | * REDIS_CLIENT_LIMIT_CLASS_NORMAL -> Normal client | |
1244 | * REDIS_CLIENT_LIMIT_CLASS_SLAVE -> Slave or client executing MONITOR command | |
1245 | * REDIS_CLIENT_LIMIT_CLASS_PUBSUB -> Client subscribed to Pub/Sub channels | |
1246 | */ | |
1247 | int getClientLimitClass(redisClient *c) { | |
1248 | if (c->flags & REDIS_SLAVE) return REDIS_CLIENT_LIMIT_CLASS_SLAVE; | |
1249 | if (dictSize(c->pubsub_channels) || listLength(c->pubsub_patterns)) | |
1250 | return REDIS_CLIENT_LIMIT_CLASS_PUBSUB; | |
1251 | return REDIS_CLIENT_LIMIT_CLASS_NORMAL; | |
1252 | } | |
1253 | ||
1254 | int getClientLimitClassByName(char *name) { | |
1255 | if (!strcasecmp(name,"normal")) return REDIS_CLIENT_LIMIT_CLASS_NORMAL; | |
1256 | else if (!strcasecmp(name,"slave")) return REDIS_CLIENT_LIMIT_CLASS_SLAVE; | |
1257 | else if (!strcasecmp(name,"pubsub")) return REDIS_CLIENT_LIMIT_CLASS_PUBSUB; | |
1258 | else return -1; | |
1259 | } | |
1260 | ||
1261 | char *getClientLimitClassName(int class) { | |
1262 | switch(class) { | |
1263 | case REDIS_CLIENT_LIMIT_CLASS_NORMAL: return "normal"; | |
1264 | case REDIS_CLIENT_LIMIT_CLASS_SLAVE: return "slave"; | |
1265 | case REDIS_CLIENT_LIMIT_CLASS_PUBSUB: return "pubsub"; | |
1266 | default: return NULL; | |
1267 | } | |
1268 | } | |
1269 | ||
1270 | /* The function checks if the client reached output buffer soft or hard | |
1271 | * limit, and also update the state needed to check the soft limit as | |
1272 | * a side effect. | |
1273 | * | |
1274 | * Return value: non-zero if the client reached the soft or the hard limit. | |
1275 | * Otherwise zero is returned. */ | |
1276 | int checkClientOutputBufferLimits(redisClient *c) { | |
1277 | int soft = 0, hard = 0, class; | |
1278 | unsigned long used_mem = getClientOutputBufferMemoryUsage(c); | |
1279 | ||
1280 | class = getClientLimitClass(c); | |
1281 | if (server.client_obuf_limits[class].hard_limit_bytes && | |
1282 | used_mem >= server.client_obuf_limits[class].hard_limit_bytes) | |
1283 | hard = 1; | |
1284 | if (server.client_obuf_limits[class].soft_limit_bytes && | |
1285 | used_mem >= server.client_obuf_limits[class].soft_limit_bytes) | |
1286 | soft = 1; | |
1287 | ||
1288 | /* We need to check if the soft limit is reached continuously for the | |
1289 | * specified amount of seconds. */ | |
1290 | if (soft) { | |
1291 | if (c->obuf_soft_limit_reached_time == 0) { | |
1292 | c->obuf_soft_limit_reached_time = server.unixtime; | |
1293 | soft = 0; /* First time we see the soft limit reached */ | |
1294 | } else { | |
1295 | time_t elapsed = server.unixtime - c->obuf_soft_limit_reached_time; | |
1296 | ||
1297 | if (elapsed <= | |
1298 | server.client_obuf_limits[class].soft_limit_seconds) { | |
1299 | soft = 0; /* The client still did not reached the max number of | |
1300 | seconds for the soft limit to be considered | |
1301 | reached. */ | |
1302 | } | |
1303 | } | |
1304 | } else { | |
1305 | c->obuf_soft_limit_reached_time = 0; | |
1306 | } | |
1307 | return soft || hard; | |
1308 | } | |
1309 | ||
1310 | /* Asynchronously close a client if soft or hard limit is reached on the | |
1311 | * output buffer size. The caller can check if the client will be closed | |
1312 | * checking if the client REDIS_CLOSE_ASAP flag is set. | |
1313 | * | |
1314 | * Note: we need to close the client asynchronously because this function is | |
1315 | * called from contexts where the client can't be freed safely, i.e. from the | |
1316 | * lower level functions pushing data inside the client output buffers. */ | |
1317 | void asyncCloseClientOnOutputBufferLimitReached(redisClient *c) { | |
1318 | if (c->flags & REDIS_CLOSE_ASAP) return; | |
1319 | if (checkClientOutputBufferLimits(c)) { | |
1320 | sds client = getClientInfoString(c); | |
1321 | ||
1322 | freeClientAsync(c); | |
1323 | redisLog(REDIS_WARNING,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client); | |
1324 | sdsfree(client); | |
1325 | } | |
1326 | } | |
1327 | ||
1328 | /* Helper function used by freeMemoryIfNeeded() in order to flush slaves | |
1329 | * output buffers without returning control to the event loop. */ | |
1330 | void flushSlavesOutputBuffers(void) { | |
1331 | listIter li; | |
1332 | listNode *ln; | |
1333 | ||
1334 | listRewind(server.slaves,&li); | |
1335 | while((ln = listNext(&li))) { | |
1336 | redisClient *slave = listNodeValue(ln); | |
1337 | int events; | |
1338 | ||
1339 | events = aeGetFileEvents(server.el,slave->fd); | |
1340 | if (events & AE_WRITABLE && | |
1341 | slave->replstate == REDIS_REPL_ONLINE && | |
1342 | listLength(slave->reply)) | |
1343 | { | |
1344 | sendReplyToClient(server.el,slave->fd,slave,0); | |
1345 | } | |
1346 | } | |
1347 | } |