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