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