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