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