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