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