2  * Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com> 
   5  * Redistribution and use in source and binary forms, with or without 
   6  * modification, are permitted provided that the following conditions are met: 
   8  *   * Redistributions of source code must retain the above copyright notice, 
   9  *     this list of conditions and the following disclaimer. 
  10  *   * Redistributions in binary form must reproduce the above copyright 
  11  *     notice, this list of conditions and the following disclaimer in the 
  12  *     documentation and/or other materials provided with the distribution. 
  13  *   * Neither the name of Redis nor the names of its contributors may be used 
  14  *     to endorse or promote products derived from this software without 
  15  *     specific prior written permission. 
  17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
  19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
  20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
  21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
  24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
  25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
  26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  27  * POSSIBILITY OF SUCH DAMAGE. 
  30 #define REDIS_VERSION "0.100" 
  46 #include <arpa/inet.h> 
  50 #include <sys/resource.h> 
  53 #include "ae.h"     /* Event driven programming library */ 
  54 #include "sds.h"    /* Dynamic safe strings */ 
  55 #include "anet.h"   /* Networking the easy way */ 
  56 #include "dict.h"   /* Hash tables */ 
  57 #include "adlist.h" /* Linked lists */ 
  58 #include "zmalloc.h" /* total memory usage aware version of malloc/free */ 
  65 /* Static server configuration */ 
  66 #define REDIS_SERVERPORT        6379    /* TCP port */ 
  67 #define REDIS_MAXIDLETIME       (60*5)  /* default client timeout */ 
  68 #define REDIS_IOBUF_LEN         1024 
  69 #define REDIS_LOADBUF_LEN       1024 
  70 #define REDIS_STATIC_ARGS       4 
  71 #define REDIS_DEFAULT_DBNUM     16 
  72 #define REDIS_CONFIGLINE_MAX    1024 
  73 #define REDIS_OBJFREELIST_MAX   1000000 /* Max number of objects to cache */ 
  74 #define REDIS_MAX_SYNC_TIME     60      /* Slave can't take more to sync */ 
  75 #define REDIS_EXPIRELOOKUPS_PER_CRON    100 /* try to expire 100 keys/second */ 
  77 /* Hash table parameters */ 
  78 #define REDIS_HT_MINFILL        10      /* Minimal hash table fill 10% */ 
  79 #define REDIS_HT_MINSLOTS       16384   /* Never resize the HT under this */ 
  82 #define REDIS_CMD_BULK          1 
  83 #define REDIS_CMD_INLINE        2 
  86 #define REDIS_STRING 0 
  91 /* Object types only used for dumping to disk */ 
  92 #define REDIS_EXPIRETIME 253 
  93 #define REDIS_SELECTDB 254 
  96 /* Defines related to the dump file format. To store 32 bits lengths for short 
  97  * keys requires a lot of space, so we check the most significant 2 bits of 
  98  * the first byte to interpreter the length: 
 100  * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte 
 101  * 01|000000 00000000 =>  01, the len is 14 byes, 6 bits + 8 bits of next byte 
 102  * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow 
 103  * 11|000000 this means: specially encoded object will follow. The six bits 
 104  *           number specify the kind of object that follows. 
 105  *           See the REDIS_RDB_ENC_* defines. 
 107  * Lenghts up to 63 are stored using a single byte, most DB keys, and may 
 108  * values, will fit inside. */ 
 109 #define REDIS_RDB_6BITLEN 0 
 110 #define REDIS_RDB_14BITLEN 1 
 111 #define REDIS_RDB_32BITLEN 2 
 112 #define REDIS_RDB_ENCVAL 3 
 113 #define REDIS_RDB_LENERR UINT_MAX 
 115 /* When a length of a string object stored on disk has the first two bits 
 116  * set, the remaining two bits specify a special encoding for the object 
 117  * accordingly to the following defines: */ 
 118 #define REDIS_RDB_ENC_INT8 0        /* 8 bit signed integer */ 
 119 #define REDIS_RDB_ENC_INT16 1       /* 16 bit signed integer */ 
 120 #define REDIS_RDB_ENC_INT32 2       /* 32 bit signed integer */ 
 121 #define REDIS_RDB_ENC_LZF 3         /* string compressed with FASTLZ */ 
 124 #define REDIS_CLOSE 1       /* This client connection should be closed ASAP */ 
 125 #define REDIS_SLAVE 2       /* This client is a slave server */ 
 126 #define REDIS_MASTER 4      /* This client is a master server */ 
 127 #define REDIS_MONITOR 8      /* This client is a slave monitor, see MONITOR */ 
 129 /* Slave replication state - slave side */ 
 130 #define REDIS_REPL_NONE 0   /* No active replication */ 
 131 #define REDIS_REPL_CONNECT 1    /* Must connect to master */ 
 132 #define REDIS_REPL_CONNECTED 2  /* Connected to master */ 
 134 /* Slave replication state - from the point of view of master 
 135  * Note that in SEND_BULK and ONLINE state the slave receives new updates 
 136  * in its output queue. In the WAIT_BGSAVE state instead the server is waiting 
 137  * to start the next background saving in order to send updates to it. */ 
 138 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */ 
 139 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */ 
 140 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */ 
 141 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */ 
 143 /* List related stuff */ 
 147 /* Sort operations */ 
 148 #define REDIS_SORT_GET 0 
 149 #define REDIS_SORT_DEL 1 
 150 #define REDIS_SORT_INCR 2 
 151 #define REDIS_SORT_DECR 3 
 152 #define REDIS_SORT_ASC 4 
 153 #define REDIS_SORT_DESC 5 
 154 #define REDIS_SORTKEY_MAX 1024 
 157 #define REDIS_DEBUG 0 
 158 #define REDIS_NOTICE 1 
 159 #define REDIS_WARNING 2 
 161 /* Anti-warning macro... */ 
 162 #define REDIS_NOTUSED(V) ((void) V) 
 164 /*================================= Data types ============================== */ 
 166 /* A redis object, that is a type able to hold a string / list / set */ 
 167 typedef struct redisObject 
{ 
 173 typedef struct redisDb 
{ 
 179 /* With multiplexing we need to take per-clinet state. 
 180  * Clients are taken in a liked list. */ 
 181 typedef struct redisClient 
{ 
 188     int bulklen
;            /* bulk read len. -1 if not in bulk read mode */ 
 191     time_t lastinteraction
; /* time of the last interaction, used for timeout */ 
 192     int flags
;              /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */ 
 193     int slaveseldb
;         /* slave selected db, if this client is a slave */ 
 194     int authenticated
;      /* when requirepass is non-NULL */ 
 195     int replstate
;          /* replication state if this is a slave */ 
 196     int repldbfd
;           /* replication DB file descriptor */ 
 197     long repldboff
;          /* replication DB file offset */ 
 198     off_t repldbsize
;       /* replication DB file size */ 
 206 /* Global server state structure */ 
 212     unsigned int sharingpoolsize
; 
 213     long long dirty
;            /* changes to DB from the last save */ 
 215     list 
*slaves
, *monitors
; 
 216     char neterr
[ANET_ERR_LEN
]; 
 218     int cronloops
;              /* number of times the cron function run */ 
 219     list 
*objfreelist
;          /* A list of freed objects to avoid malloc() */ 
 220     time_t lastsave
;            /* Unix time of last save succeeede */ 
 221     size_t usedmemory
;             /* Used memory in megabytes */ 
 222     /* Fields used only for stats */ 
 223     time_t stat_starttime
;         /* server start time */ 
 224     long long stat_numcommands
;    /* number of processed commands */ 
 225     long long stat_numconnections
; /* number of connections received */ 
 233     int bgsaveinprogress
; 
 234     struct saveparam 
*saveparams
; 
 241     /* Replication related */ 
 245     redisClient 
*master
;    /* client that is master for this slave */ 
 247     /* Sort parameters - qsort_r() is only available under BSD so we 
 248      * have to take this state global, in order to pass it to sortCompare() */ 
 254 typedef void redisCommandProc(redisClient 
*c
); 
 255 struct redisCommand 
{ 
 257     redisCommandProc 
*proc
; 
 262 typedef struct _redisSortObject 
{ 
 270 typedef struct _redisSortOperation 
{ 
 273 } redisSortOperation
; 
 275 struct sharedObjectsStruct 
{ 
 276     robj 
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
, 
 277     *colon
, *nullbulk
, *nullmultibulk
, 
 278     *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
, 
 279     *outofrangeerr
, *plus
, 
 280     *select0
, *select1
, *select2
, *select3
, *select4
, 
 281     *select5
, *select6
, *select7
, *select8
, *select9
; 
 284 /*================================ Prototypes =============================== */ 
 286 static void freeStringObject(robj 
*o
); 
 287 static void freeListObject(robj 
*o
); 
 288 static void freeSetObject(robj 
*o
); 
 289 static void decrRefCount(void *o
); 
 290 static robj 
*createObject(int type
, void *ptr
); 
 291 static void freeClient(redisClient 
*c
); 
 292 static int rdbLoad(char *filename
); 
 293 static void addReply(redisClient 
*c
, robj 
*obj
); 
 294 static void addReplySds(redisClient 
*c
, sds s
); 
 295 static void incrRefCount(robj 
*o
); 
 296 static int rdbSaveBackground(char *filename
); 
 297 static robj 
*createStringObject(char *ptr
, size_t len
); 
 298 static void replicationFeedSlaves(list 
*slaves
, struct redisCommand 
*cmd
, int dictid
, robj 
**argv
, int argc
); 
 299 static int syncWithMaster(void); 
 300 static robj 
*tryObjectSharing(robj 
*o
); 
 301 static int removeExpire(redisDb 
*db
, robj 
*key
); 
 302 static int expireIfNeeded(redisDb 
*db
, robj 
*key
); 
 303 static int deleteIfVolatile(redisDb 
*db
, robj 
*key
); 
 304 static int deleteKey(redisDb 
*db
, robj 
*key
); 
 305 static time_t getExpire(redisDb 
*db
, robj 
*key
); 
 306 static int setExpire(redisDb 
*db
, robj 
*key
, time_t when
); 
 307 static void updateSalvesWaitingBgsave(int bgsaveerr
); 
 309 static void authCommand(redisClient 
*c
); 
 310 static void pingCommand(redisClient 
*c
); 
 311 static void echoCommand(redisClient 
*c
); 
 312 static void setCommand(redisClient 
*c
); 
 313 static void setnxCommand(redisClient 
*c
); 
 314 static void getCommand(redisClient 
*c
); 
 315 static void delCommand(redisClient 
*c
); 
 316 static void existsCommand(redisClient 
*c
); 
 317 static void incrCommand(redisClient 
*c
); 
 318 static void decrCommand(redisClient 
*c
); 
 319 static void incrbyCommand(redisClient 
*c
); 
 320 static void decrbyCommand(redisClient 
*c
); 
 321 static void selectCommand(redisClient 
*c
); 
 322 static void randomkeyCommand(redisClient 
*c
); 
 323 static void keysCommand(redisClient 
*c
); 
 324 static void dbsizeCommand(redisClient 
*c
); 
 325 static void lastsaveCommand(redisClient 
*c
); 
 326 static void saveCommand(redisClient 
*c
); 
 327 static void bgsaveCommand(redisClient 
*c
); 
 328 static void shutdownCommand(redisClient 
*c
); 
 329 static void moveCommand(redisClient 
*c
); 
 330 static void renameCommand(redisClient 
*c
); 
 331 static void renamenxCommand(redisClient 
*c
); 
 332 static void lpushCommand(redisClient 
*c
); 
 333 static void rpushCommand(redisClient 
*c
); 
 334 static void lpopCommand(redisClient 
*c
); 
 335 static void rpopCommand(redisClient 
*c
); 
 336 static void llenCommand(redisClient 
*c
); 
 337 static void lindexCommand(redisClient 
*c
); 
 338 static void lrangeCommand(redisClient 
*c
); 
 339 static void ltrimCommand(redisClient 
*c
); 
 340 static void typeCommand(redisClient 
*c
); 
 341 static void lsetCommand(redisClient 
*c
); 
 342 static void saddCommand(redisClient 
*c
); 
 343 static void sremCommand(redisClient 
*c
); 
 344 static void smoveCommand(redisClient 
*c
); 
 345 static void sismemberCommand(redisClient 
*c
); 
 346 static void scardCommand(redisClient 
*c
); 
 347 static void sinterCommand(redisClient 
*c
); 
 348 static void sinterstoreCommand(redisClient 
*c
); 
 349 static void sunionCommand(redisClient 
*c
); 
 350 static void sunionstoreCommand(redisClient 
*c
); 
 351 static void sdiffCommand(redisClient 
*c
); 
 352 static void sdiffstoreCommand(redisClient 
*c
); 
 353 static void syncCommand(redisClient 
*c
); 
 354 static void flushdbCommand(redisClient 
*c
); 
 355 static void flushallCommand(redisClient 
*c
); 
 356 static void sortCommand(redisClient 
*c
); 
 357 static void lremCommand(redisClient 
*c
); 
 358 static void infoCommand(redisClient 
*c
); 
 359 static void mgetCommand(redisClient 
*c
); 
 360 static void monitorCommand(redisClient 
*c
); 
 361 static void expireCommand(redisClient 
*c
); 
 362 static void getSetCommand(redisClient 
*c
); 
 364 /*================================= Globals ================================= */ 
 367 static struct redisServer server
; /* server global state */ 
 368 static struct redisCommand cmdTable
[] = { 
 369     {"get",getCommand
,2,REDIS_CMD_INLINE
}, 
 370     {"set",setCommand
,3,REDIS_CMD_BULK
}, 
 371     {"setnx",setnxCommand
,3,REDIS_CMD_BULK
}, 
 372     {"del",delCommand
,-2,REDIS_CMD_INLINE
}, 
 373     {"exists",existsCommand
,2,REDIS_CMD_INLINE
}, 
 374     {"incr",incrCommand
,2,REDIS_CMD_INLINE
}, 
 375     {"decr",decrCommand
,2,REDIS_CMD_INLINE
}, 
 376     {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
}, 
 377     {"rpush",rpushCommand
,3,REDIS_CMD_BULK
}, 
 378     {"lpush",lpushCommand
,3,REDIS_CMD_BULK
}, 
 379     {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
}, 
 380     {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
}, 
 381     {"llen",llenCommand
,2,REDIS_CMD_INLINE
}, 
 382     {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
}, 
 383     {"lset",lsetCommand
,4,REDIS_CMD_BULK
}, 
 384     {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
}, 
 385     {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
}, 
 386     {"lrem",lremCommand
,4,REDIS_CMD_BULK
}, 
 387     {"sadd",saddCommand
,3,REDIS_CMD_BULK
}, 
 388     {"srem",sremCommand
,3,REDIS_CMD_BULK
}, 
 389     {"smove",smoveCommand
,4,REDIS_CMD_BULK
}, 
 390     {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
}, 
 391     {"scard",scardCommand
,2,REDIS_CMD_INLINE
}, 
 392     {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
}, 
 393     {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
}, 
 394     {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
}, 
 395     {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
}, 
 396     {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
}, 
 397     {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
}, 
 398     {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
}, 
 399     {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
}, 
 400     {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
}, 
 401     {"getset",getSetCommand
,3,REDIS_CMD_BULK
}, 
 402     {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
}, 
 403     {"select",selectCommand
,2,REDIS_CMD_INLINE
}, 
 404     {"move",moveCommand
,3,REDIS_CMD_INLINE
}, 
 405     {"rename",renameCommand
,3,REDIS_CMD_INLINE
}, 
 406     {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
}, 
 407     {"keys",keysCommand
,2,REDIS_CMD_INLINE
}, 
 408     {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
}, 
 409     {"auth",authCommand
,2,REDIS_CMD_INLINE
}, 
 410     {"ping",pingCommand
,1,REDIS_CMD_INLINE
}, 
 411     {"echo",echoCommand
,2,REDIS_CMD_BULK
}, 
 412     {"save",saveCommand
,1,REDIS_CMD_INLINE
}, 
 413     {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
}, 
 414     {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
}, 
 415     {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
}, 
 416     {"type",typeCommand
,2,REDIS_CMD_INLINE
}, 
 417     {"sync",syncCommand
,1,REDIS_CMD_INLINE
}, 
 418     {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
}, 
 419     {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
}, 
 420     {"sort",sortCommand
,-2,REDIS_CMD_INLINE
}, 
 421     {"info",infoCommand
,1,REDIS_CMD_INLINE
}, 
 422     {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
}, 
 423     {"expire",expireCommand
,3,REDIS_CMD_INLINE
}, 
 427 /*============================ Utility functions ============================ */ 
 429 /* Glob-style pattern matching. */ 
 430 int stringmatchlen(const char *pattern
, int patternLen
, 
 431         const char *string
, int stringLen
, int nocase
) 
 436             while (pattern
[1] == '*') { 
 441                 return 1; /* match */ 
 443                 if (stringmatchlen(pattern
+1, patternLen
-1, 
 444                             string
, stringLen
, nocase
)) 
 445                     return 1; /* match */ 
 449             return 0; /* no match */ 
 453                 return 0; /* no match */ 
 463             not = pattern
[0] == '^'; 
 470                 if (pattern
[0] == '\\') { 
 473                     if (pattern
[0] == string
[0]) 
 475                 } else if (pattern
[0] == ']') { 
 477                 } else if (patternLen 
== 0) { 
 481                 } else if (pattern
[1] == '-' && patternLen 
>= 3) { 
 482                     int start 
= pattern
[0]; 
 483                     int end 
= pattern
[2]; 
 491                         start 
= tolower(start
); 
 497                     if (c 
>= start 
&& c 
<= end
) 
 501                         if (pattern
[0] == string
[0]) 
 504                         if (tolower((int)pattern
[0]) == tolower((int)string
[0])) 
 514                 return 0; /* no match */ 
 520             if (patternLen 
>= 2) { 
 527                 if (pattern
[0] != string
[0]) 
 528                     return 0; /* no match */ 
 530                 if (tolower((int)pattern
[0]) != tolower((int)string
[0])) 
 531                     return 0; /* no match */ 
 539         if (stringLen 
== 0) { 
 540             while(*pattern 
== '*') { 
 547     if (patternLen 
== 0 && stringLen 
== 0) 
 552 void redisLog(int level
, const char *fmt
, ...) 
 557     fp 
= (server
.logfile 
== NULL
) ? stdout 
: fopen(server
.logfile
,"a"); 
 561     if (level 
>= server
.verbosity
) { 
 567         strftime(buf
,64,"%d %b %H:%M:%S",gmtime(&now
)); 
 568         fprintf(fp
,"%s %c ",buf
,c
[level
]); 
 569         vfprintf(fp
, fmt
, ap
); 
 575     if (server
.logfile
) fclose(fp
); 
 578 /*====================== Hash table type implementation  ==================== */ 
 580 /* This is an hash table type that uses the SDS dynamic strings libary as 
 581  * keys and radis objects as values (objects can hold SDS strings, 
 584 static int sdsDictKeyCompare(void *privdata
, const void *key1
, 
 588     DICT_NOTUSED(privdata
); 
 590     l1 
= sdslen((sds
)key1
); 
 591     l2 
= sdslen((sds
)key2
); 
 592     if (l1 
!= l2
) return 0; 
 593     return memcmp(key1
, key2
, l1
) == 0; 
 596 static void dictRedisObjectDestructor(void *privdata
, void *val
) 
 598     DICT_NOTUSED(privdata
); 
 603 static int dictSdsKeyCompare(void *privdata
, const void *key1
, 
 606     const robj 
*o1 
= key1
, *o2 
= key2
; 
 607     return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
); 
 610 static unsigned int dictSdsHash(const void *key
) { 
 612     return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
)); 
 615 static dictType setDictType 
= { 
 616     dictSdsHash
,               /* hash function */ 
 619     dictSdsKeyCompare
,         /* key compare */ 
 620     dictRedisObjectDestructor
, /* key destructor */ 
 621     NULL                       
/* val destructor */ 
 624 static dictType hashDictType 
= { 
 625     dictSdsHash
,                /* hash function */ 
 628     dictSdsKeyCompare
,          /* key compare */ 
 629     dictRedisObjectDestructor
,  /* key destructor */ 
 630     dictRedisObjectDestructor   
/* val destructor */ 
 633 /* ========================= Random utility functions ======================= */ 
 635 /* Redis generally does not try to recover from out of memory conditions 
 636  * when allocating objects or strings, it is not clear if it will be possible 
 637  * to report this condition to the client since the networking layer itself 
 638  * is based on heap allocation for send buffers, so we simply abort. 
 639  * At least the code will be simpler to read... */ 
 640 static void oom(const char *msg
) { 
 641     fprintf(stderr
, "%s: Out of memory\n",msg
); 
 647 /* ====================== Redis server networking stuff ===================== */ 
 648 void closeTimedoutClients(void) { 
 651     time_t now 
= time(NULL
); 
 653     listRewind(server
.clients
); 
 654     while ((ln 
= listYield(server
.clients
)) != NULL
) { 
 655         c 
= listNodeValue(ln
); 
 656         if (!(c
->flags 
& REDIS_SLAVE
) &&    /* no timeout for slaves */ 
 657              (now 
- c
->lastinteraction 
> server
.maxidletime
)) { 
 658             redisLog(REDIS_DEBUG
,"Closing idle client"); 
 664 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL 
 665  * we resize the hash table to save memory */ 
 666 void tryResizeHashTables(void) { 
 669     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 670         long long size
, used
; 
 672         size 
= dictSlots(server
.db
[j
].dict
); 
 673         used 
= dictSize(server
.db
[j
].dict
); 
 674         if (size 
&& used 
&& size 
> REDIS_HT_MINSLOTS 
&& 
 675             (used
*100/size 
< REDIS_HT_MINFILL
)) { 
 676             redisLog(REDIS_NOTICE
,"The hash table %d is too sparse, resize it...",j
); 
 677             dictResize(server
.db
[j
].dict
); 
 678             redisLog(REDIS_NOTICE
,"Hash table %d resized.",j
); 
 683 int serverCron(struct aeEventLoop 
*eventLoop
, long long id
, void *clientData
) { 
 684     int j
, loops 
= server
.cronloops
++; 
 685     REDIS_NOTUSED(eventLoop
); 
 687     REDIS_NOTUSED(clientData
); 
 689     /* Update the global state with the amount of used memory */ 
 690     server
.usedmemory 
= zmalloc_used_memory(); 
 692     /* Show some info about non-empty databases */ 
 693     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 694         long long size
, used
, vkeys
; 
 696         size 
= dictSlots(server
.db
[j
].dict
); 
 697         used 
= dictSize(server
.db
[j
].dict
); 
 698         vkeys 
= dictSize(server
.db
[j
].expires
); 
 699         if (!(loops 
% 5) && used 
> 0) { 
 700             redisLog(REDIS_DEBUG
,"DB %d: %d keys (%d volatile) in %d slots HT.",j
,used
,vkeys
,size
); 
 701             /* dictPrintStats(server.dict); */ 
 705     /* We don't want to resize the hash tables while a bacground saving 
 706      * is in progress: the saving child is created using fork() that is 
 707      * implemented with a copy-on-write semantic in most modern systems, so 
 708      * if we resize the HT while there is the saving child at work actually 
 709      * a lot of memory movements in the parent will cause a lot of pages 
 711     if (!server
.bgsaveinprogress
) tryResizeHashTables(); 
 713     /* Show information about connected clients */ 
 715         redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %zu bytes in use", 
 716             listLength(server
.clients
)-listLength(server
.slaves
), 
 717             listLength(server
.slaves
), 
 719             dictSize(server
.sharingpool
)); 
 722     /* Close connections of timedout clients */ 
 724         closeTimedoutClients(); 
 726     /* Check if a background saving in progress terminated */ 
 727     if (server
.bgsaveinprogress
) { 
 729         /* XXX: TODO handle the case of the saving child killed */ 
 730         if (wait4(-1,&statloc
,WNOHANG
,NULL
)) { 
 731             int exitcode 
= WEXITSTATUS(statloc
); 
 733                 redisLog(REDIS_NOTICE
, 
 734                     "Background saving terminated with success"); 
 736                 server
.lastsave 
= time(NULL
); 
 738                 redisLog(REDIS_WARNING
, 
 739                     "Background saving error"); 
 741             server
.bgsaveinprogress 
= 0; 
 742             updateSalvesWaitingBgsave(exitcode 
== 0 ? REDIS_OK 
: REDIS_ERR
); 
 745         /* If there is not a background saving in progress check if 
 746          * we have to save now */ 
 747          time_t now 
= time(NULL
); 
 748          for (j 
= 0; j 
< server
.saveparamslen
; j
++) { 
 749             struct saveparam 
*sp 
= server
.saveparams
+j
; 
 751             if (server
.dirty 
>= sp
->changes 
&& 
 752                 now
-server
.lastsave 
> sp
->seconds
) { 
 753                 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...", 
 754                     sp
->changes
, sp
->seconds
); 
 755                 rdbSaveBackground(server
.dbfilename
); 
 761     /* Try to expire a few timed out keys */ 
 762     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 763         redisDb 
*db 
= server
.db
+j
; 
 764         int num 
= dictSize(db
->expires
); 
 767             time_t now 
= time(NULL
); 
 769             if (num 
> REDIS_EXPIRELOOKUPS_PER_CRON
) 
 770                 num 
= REDIS_EXPIRELOOKUPS_PER_CRON
; 
 775                 if ((de 
= dictGetRandomKey(db
->expires
)) == NULL
) break; 
 776                 t 
= (time_t) dictGetEntryVal(de
); 
 778                     deleteKey(db
,dictGetEntryKey(de
)); 
 784     /* Check if we should connect to a MASTER */ 
 785     if (server
.replstate 
== REDIS_REPL_CONNECT
) { 
 786         redisLog(REDIS_NOTICE
,"Connecting to MASTER..."); 
 787         if (syncWithMaster() == REDIS_OK
) { 
 788             redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded"); 
 794 static void createSharedObjects(void) { 
 795     shared
.crlf 
= createObject(REDIS_STRING
,sdsnew("\r\n")); 
 796     shared
.ok 
= createObject(REDIS_STRING
,sdsnew("+OK\r\n")); 
 797     shared
.err 
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n")); 
 798     shared
.emptybulk 
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n")); 
 799     shared
.czero 
= createObject(REDIS_STRING
,sdsnew(":0\r\n")); 
 800     shared
.cone 
= createObject(REDIS_STRING
,sdsnew(":1\r\n")); 
 801     shared
.nullbulk 
= createObject(REDIS_STRING
,sdsnew("$-1\r\n")); 
 802     shared
.nullmultibulk 
= createObject(REDIS_STRING
,sdsnew("*-1\r\n")); 
 803     shared
.emptymultibulk 
= createObject(REDIS_STRING
,sdsnew("*0\r\n")); 
 805     shared
.pong 
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n")); 
 806     shared
.wrongtypeerr 
= createObject(REDIS_STRING
,sdsnew( 
 807         "-ERR Operation against a key holding the wrong kind of value\r\n")); 
 808     shared
.nokeyerr 
= createObject(REDIS_STRING
,sdsnew( 
 809         "-ERR no such key\r\n")); 
 810     shared
.syntaxerr 
= createObject(REDIS_STRING
,sdsnew( 
 811         "-ERR syntax error\r\n")); 
 812     shared
.sameobjecterr 
= createObject(REDIS_STRING
,sdsnew( 
 813         "-ERR source and destination objects are the same\r\n")); 
 814     shared
.outofrangeerr 
= createObject(REDIS_STRING
,sdsnew( 
 815         "-ERR index out of range\r\n")); 
 816     shared
.space 
= createObject(REDIS_STRING
,sdsnew(" ")); 
 817     shared
.colon 
= createObject(REDIS_STRING
,sdsnew(":")); 
 818     shared
.plus 
= createObject(REDIS_STRING
,sdsnew("+")); 
 819     shared
.select0 
= createStringObject("select 0\r\n",10); 
 820     shared
.select1 
= createStringObject("select 1\r\n",10); 
 821     shared
.select2 
= createStringObject("select 2\r\n",10); 
 822     shared
.select3 
= createStringObject("select 3\r\n",10); 
 823     shared
.select4 
= createStringObject("select 4\r\n",10); 
 824     shared
.select5 
= createStringObject("select 5\r\n",10); 
 825     shared
.select6 
= createStringObject("select 6\r\n",10); 
 826     shared
.select7 
= createStringObject("select 7\r\n",10); 
 827     shared
.select8 
= createStringObject("select 8\r\n",10); 
 828     shared
.select9 
= createStringObject("select 9\r\n",10); 
 831 static void appendServerSaveParams(time_t seconds
, int changes
) { 
 832     server
.saveparams 
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1)); 
 833     if (server
.saveparams 
== NULL
) oom("appendServerSaveParams"); 
 834     server
.saveparams
[server
.saveparamslen
].seconds 
= seconds
; 
 835     server
.saveparams
[server
.saveparamslen
].changes 
= changes
; 
 836     server
.saveparamslen
++; 
 839 static void ResetServerSaveParams() { 
 840     zfree(server
.saveparams
); 
 841     server
.saveparams 
= NULL
; 
 842     server
.saveparamslen 
= 0; 
 845 static void initServerConfig() { 
 846     server
.dbnum 
= REDIS_DEFAULT_DBNUM
; 
 847     server
.port 
= REDIS_SERVERPORT
; 
 848     server
.verbosity 
= REDIS_DEBUG
; 
 849     server
.maxidletime 
= REDIS_MAXIDLETIME
; 
 850     server
.saveparams 
= NULL
; 
 851     server
.logfile 
= NULL
; /* NULL = log on standard output */ 
 852     server
.bindaddr 
= NULL
; 
 853     server
.glueoutputbuf 
= 1; 
 854     server
.daemonize 
= 0; 
 855     server
.pidfile 
= "/var/run/redis.pid"; 
 856     server
.dbfilename 
= "dump.rdb"; 
 857     server
.requirepass 
= NULL
; 
 858     server
.shareobjects 
= 0; 
 859     ResetServerSaveParams(); 
 861     appendServerSaveParams(60*60,1);  /* save after 1 hour and 1 change */ 
 862     appendServerSaveParams(300,100);  /* save after 5 minutes and 100 changes */ 
 863     appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ 
 864     /* Replication related */ 
 866     server
.masterhost 
= NULL
; 
 867     server
.masterport 
= 6379; 
 868     server
.master 
= NULL
; 
 869     server
.replstate 
= REDIS_REPL_NONE
; 
 872 static void initServer() { 
 875     signal(SIGHUP
, SIG_IGN
); 
 876     signal(SIGPIPE
, SIG_IGN
); 
 878     server
.clients 
= listCreate(); 
 879     server
.slaves 
= listCreate(); 
 880     server
.monitors 
= listCreate(); 
 881     server
.objfreelist 
= listCreate(); 
 882     createSharedObjects(); 
 883     server
.el 
= aeCreateEventLoop(); 
 884     server
.db 
= zmalloc(sizeof(redisDb
)*server
.dbnum
); 
 885     server
.sharingpool 
= dictCreate(&setDictType
,NULL
); 
 886     server
.sharingpoolsize 
= 1024; 
 887     if (!server
.db 
|| !server
.clients 
|| !server
.slaves 
|| !server
.monitors 
|| !server
.el 
|| !server
.objfreelist
) 
 888         oom("server initialization"); /* Fatal OOM */ 
 889     server
.fd 
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
); 
 890     if (server
.fd 
== -1) { 
 891         redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
); 
 894     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 895         server
.db
[j
].dict 
= dictCreate(&hashDictType
,NULL
); 
 896         server
.db
[j
].expires 
= dictCreate(&setDictType
,NULL
); 
 899     server
.cronloops 
= 0; 
 900     server
.bgsaveinprogress 
= 0; 
 901     server
.lastsave 
= time(NULL
); 
 903     server
.usedmemory 
= 0; 
 904     server
.stat_numcommands 
= 0; 
 905     server
.stat_numconnections 
= 0; 
 906     server
.stat_starttime 
= time(NULL
); 
 907     aeCreateTimeEvent(server
.el
, 1000, serverCron
, NULL
, NULL
); 
 910 /* Empty the whole database */ 
 911 static long long emptyDb() { 
 913     long long removed 
= 0; 
 915     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 916         removed 
+= dictSize(server
.db
[j
].dict
); 
 917         dictEmpty(server
.db
[j
].dict
); 
 918         dictEmpty(server
.db
[j
].expires
); 
 923 static int yesnotoi(char *s
) { 
 924     if (!strcasecmp(s
,"yes")) return 1; 
 925     else if (!strcasecmp(s
,"no")) return 0; 
 929 /* I agree, this is a very rudimental way to load a configuration... 
 930    will improve later if the config gets more complex */ 
 931 static void loadServerConfig(char *filename
) { 
 932     FILE *fp 
= fopen(filename
,"r"); 
 933     char buf
[REDIS_CONFIGLINE_MAX
+1], *err 
= NULL
; 
 938         redisLog(REDIS_WARNING
,"Fatal error, can't open config file"); 
 941     while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) { 
 947         line 
= sdstrim(line
," \t\r\n"); 
 949         /* Skip comments and blank lines*/ 
 950         if (line
[0] == '#' || line
[0] == '\0') { 
 955         /* Split into arguments */ 
 956         argv 
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
); 
 959         /* Execute config directives */ 
 960         if (!strcasecmp(argv
[0],"timeout") && argc 
== 2) { 
 961             server
.maxidletime 
= atoi(argv
[1]); 
 962             if (server
.maxidletime 
< 1) { 
 963                 err 
= "Invalid timeout value"; goto loaderr
; 
 965         } else if (!strcasecmp(argv
[0],"port") && argc 
== 2) { 
 966             server
.port 
= atoi(argv
[1]); 
 967             if (server
.port 
< 1 || server
.port 
> 65535) { 
 968                 err 
= "Invalid port"; goto loaderr
; 
 970         } else if (!strcasecmp(argv
[0],"bind") && argc 
== 2) { 
 971             server
.bindaddr 
= zstrdup(argv
[1]); 
 972         } else if (!strcasecmp(argv
[0],"save") && argc 
== 3) { 
 973             int seconds 
= atoi(argv
[1]); 
 974             int changes 
= atoi(argv
[2]); 
 975             if (seconds 
< 1 || changes 
< 0) { 
 976                 err 
= "Invalid save parameters"; goto loaderr
; 
 978             appendServerSaveParams(seconds
,changes
); 
 979         } else if (!strcasecmp(argv
[0],"dir") && argc 
== 2) { 
 980             if (chdir(argv
[1]) == -1) { 
 981                 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s", 
 982                     argv
[1], strerror(errno
)); 
 985         } else if (!strcasecmp(argv
[0],"loglevel") && argc 
== 2) { 
 986             if (!strcasecmp(argv
[1],"debug")) server
.verbosity 
= REDIS_DEBUG
; 
 987             else if (!strcasecmp(argv
[1],"notice")) server
.verbosity 
= REDIS_NOTICE
; 
 988             else if (!strcasecmp(argv
[1],"warning")) server
.verbosity 
= REDIS_WARNING
; 
 990                 err 
= "Invalid log level. Must be one of debug, notice, warning"; 
 993         } else if (!strcasecmp(argv
[0],"logfile") && argc 
== 2) { 
 996             server
.logfile 
= zstrdup(argv
[1]); 
 997             if (!strcasecmp(server
.logfile
,"stdout")) { 
 998                 zfree(server
.logfile
); 
 999                 server
.logfile 
= NULL
; 
1001             if (server
.logfile
) { 
1002                 /* Test if we are able to open the file. The server will not 
1003                  * be able to abort just for this problem later... */ 
1004                 fp 
= fopen(server
.logfile
,"a"); 
1006                     err 
= sdscatprintf(sdsempty(), 
1007                         "Can't open the log file: %s", strerror(errno
)); 
1012         } else if (!strcasecmp(argv
[0],"databases") && argc 
== 2) { 
1013             server
.dbnum 
= atoi(argv
[1]); 
1014             if (server
.dbnum 
< 1) { 
1015                 err 
= "Invalid number of databases"; goto loaderr
; 
1017         } else if (!strcasecmp(argv
[0],"slaveof") && argc 
== 3) { 
1018             server
.masterhost 
= sdsnew(argv
[1]); 
1019             server
.masterport 
= atoi(argv
[2]); 
1020             server
.replstate 
= REDIS_REPL_CONNECT
; 
1021         } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc 
== 2) { 
1022             if ((server
.glueoutputbuf 
= yesnotoi(argv
[1])) == -1) { 
1023                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1025         } else if (!strcasecmp(argv
[0],"shareobjects") && argc 
== 2) { 
1026             if ((server
.shareobjects 
= yesnotoi(argv
[1])) == -1) { 
1027                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1029         } else if (!strcasecmp(argv
[0],"daemonize") && argc 
== 2) { 
1030             if ((server
.daemonize 
= yesnotoi(argv
[1])) == -1) { 
1031                 err 
= "argument must be 'yes' or 'no'"; goto loaderr
; 
1033         } else if (!strcasecmp(argv
[0],"requirepass") && argc 
== 2) { 
1034           server
.requirepass 
= zstrdup(argv
[1]); 
1035         } else if (!strcasecmp(argv
[0],"pidfile") && argc 
== 2) { 
1036           server
.pidfile 
= zstrdup(argv
[1]); 
1037         } else if (!strcasecmp(argv
[0],"dbfilename") && argc 
== 2) { 
1038           server
.dbfilename 
= zstrdup(argv
[1]); 
1040             err 
= "Bad directive or wrong number of arguments"; goto loaderr
; 
1042         for (j 
= 0; j 
< argc
; j
++) 
1051     fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n"); 
1052     fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
); 
1053     fprintf(stderr
, ">>> '%s'\n", line
); 
1054     fprintf(stderr
, "%s\n", err
); 
1058 static void freeClientArgv(redisClient 
*c
) { 
1061     for (j 
= 0; j 
< c
->argc
; j
++) 
1062         decrRefCount(c
->argv
[j
]); 
1066 static void freeClient(redisClient 
*c
) { 
1069     aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
); 
1070     aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
); 
1071     sdsfree(c
->querybuf
); 
1072     listRelease(c
->reply
); 
1075     ln 
= listSearchKey(server
.clients
,c
); 
1077     listDelNode(server
.clients
,ln
); 
1078     if (c
->flags 
& REDIS_SLAVE
) { 
1079         if (c
->replstate 
== REDIS_REPL_SEND_BULK 
&& c
->repldbfd 
!= -1) 
1081         list 
*l 
= (c
->flags 
& REDIS_MONITOR
) ? server
.monitors 
: server
.slaves
; 
1082         ln 
= listSearchKey(l
,c
); 
1086     if (c
->flags 
& REDIS_MASTER
) { 
1087         server
.master 
= NULL
; 
1088         server
.replstate 
= REDIS_REPL_CONNECT
; 
1094 static void glueReplyBuffersIfNeeded(redisClient 
*c
) { 
1099     listRewind(c
->reply
); 
1100     while((ln 
= listYield(c
->reply
))) { 
1102         totlen 
+= sdslen(o
->ptr
); 
1103         /* This optimization makes more sense if we don't have to copy 
1105         if (totlen 
> 1024) return; 
1111         listRewind(c
->reply
); 
1112         while((ln 
= listYield(c
->reply
))) { 
1114             memcpy(buf
+copylen
,o
->ptr
,sdslen(o
->ptr
)); 
1115             copylen 
+= sdslen(o
->ptr
); 
1116             listDelNode(c
->reply
,ln
); 
1118         /* Now the output buffer is empty, add the new single element */ 
1119         addReplySds(c
,sdsnewlen(buf
,totlen
)); 
1123 static void sendReplyToClient(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
1124     redisClient 
*c 
= privdata
; 
1125     int nwritten 
= 0, totwritten 
= 0, objlen
; 
1128     REDIS_NOTUSED(mask
); 
1130     if (server
.glueoutputbuf 
&& listLength(c
->reply
) > 1) 
1131         glueReplyBuffersIfNeeded(c
); 
1132     while(listLength(c
->reply
)) { 
1133         o 
= listNodeValue(listFirst(c
->reply
)); 
1134         objlen 
= sdslen(o
->ptr
); 
1137             listDelNode(c
->reply
,listFirst(c
->reply
)); 
1141         if (c
->flags 
& REDIS_MASTER
) { 
1142             nwritten 
= objlen 
- c
->sentlen
; 
1144             nwritten 
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen 
- c
->sentlen
); 
1145             if (nwritten 
<= 0) break; 
1147         c
->sentlen 
+= nwritten
; 
1148         totwritten 
+= nwritten
; 
1149         /* If we fully sent the object on head go to the next one */ 
1150         if (c
->sentlen 
== objlen
) { 
1151             listDelNode(c
->reply
,listFirst(c
->reply
)); 
1155     if (nwritten 
== -1) { 
1156         if (errno 
== EAGAIN
) { 
1159             redisLog(REDIS_DEBUG
, 
1160                 "Error writing to client: %s", strerror(errno
)); 
1165     if (totwritten 
> 0) c
->lastinteraction 
= time(NULL
); 
1166     if (listLength(c
->reply
) == 0) { 
1168         aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
); 
1172 static struct redisCommand 
*lookupCommand(char *name
) { 
1174     while(cmdTable
[j
].name 
!= NULL
) { 
1175         if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
]; 
1181 /* resetClient prepare the client to process the next command */ 
1182 static void resetClient(redisClient 
*c
) { 
1187 /* If this function gets called we already read a whole 
1188  * command, argments are in the client argv/argc fields. 
1189  * processCommand() execute the command or prepare the 
1190  * server for a bulk read from the client. 
1192  * If 1 is returned the client is still alive and valid and 
1193  * and other operations can be performed by the caller. Otherwise 
1194  * if 0 is returned the client was destroied (i.e. after QUIT). */ 
1195 static int processCommand(redisClient 
*c
) { 
1196     struct redisCommand 
*cmd
; 
1199     /* The QUIT command is handled as a special case. Normal command 
1200      * procs are unable to close the client connection safely */ 
1201     if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) { 
1205     cmd 
= lookupCommand(c
->argv
[0]->ptr
); 
1207         addReplySds(c
,sdsnew("-ERR unknown command\r\n")); 
1210     } else if ((cmd
->arity 
> 0 && cmd
->arity 
!= c
->argc
) || 
1211                (c
->argc 
< -cmd
->arity
)) { 
1212         addReplySds(c
,sdsnew("-ERR wrong number of arguments\r\n")); 
1215     } else if (cmd
->flags 
& REDIS_CMD_BULK 
&& c
->bulklen 
== -1) { 
1216         int bulklen 
= atoi(c
->argv
[c
->argc
-1]->ptr
); 
1218         decrRefCount(c
->argv
[c
->argc
-1]); 
1219         if (bulklen 
< 0 || bulklen 
> 1024*1024*1024) { 
1221             addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n")); 
1226         c
->bulklen 
= bulklen
+2; /* add two bytes for CR+LF */ 
1227         /* It is possible that the bulk read is already in the 
1228          * buffer. Check this condition and handle it accordingly */ 
1229         if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) { 
1230             c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2); 
1232             c
->querybuf 
= sdsrange(c
->querybuf
,c
->bulklen
,-1); 
1237     /* Let's try to share objects on the command arguments vector */ 
1238     if (server
.shareobjects
) { 
1240         for(j 
= 1; j 
< c
->argc
; j
++) 
1241             c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]); 
1243     /* Check if the user is authenticated */ 
1244     if (server
.requirepass 
&& !c
->authenticated 
&& cmd
->proc 
!= authCommand
) { 
1245         addReplySds(c
,sdsnew("-ERR operation not permitted\r\n")); 
1250     /* Exec the command */ 
1251     dirty 
= server
.dirty
; 
1253     if (server
.dirty
-dirty 
!= 0 && listLength(server
.slaves
)) 
1254         replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
); 
1255     if (listLength(server
.monitors
)) 
1256         replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
); 
1257     server
.stat_numcommands
++; 
1259     /* Prepare the client for the next command */ 
1260     if (c
->flags 
& REDIS_CLOSE
) { 
1268 static void replicationFeedSlaves(list 
*slaves
, struct redisCommand 
*cmd
, int dictid
, robj 
**argv
, int argc
) { 
1272     /* (args*2)+1 is enough room for args, spaces, newlines */ 
1273     robj 
*static_outv
[REDIS_STATIC_ARGS
*2+1]; 
1275     if (argc 
<= REDIS_STATIC_ARGS
) { 
1278         outv 
= zmalloc(sizeof(robj
*)*(argc
*2+1)); 
1279         if (!outv
) oom("replicationFeedSlaves"); 
1282     for (j 
= 0; j 
< argc
; j
++) { 
1283         if (j 
!= 0) outv
[outc
++] = shared
.space
; 
1284         if ((cmd
->flags 
& REDIS_CMD_BULK
) && j 
== argc
-1) { 
1287             lenobj 
= createObject(REDIS_STRING
, 
1288                 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv
[j
]->ptr
))); 
1289             lenobj
->refcount 
= 0; 
1290             outv
[outc
++] = lenobj
; 
1292         outv
[outc
++] = argv
[j
]; 
1294     outv
[outc
++] = shared
.crlf
; 
1296     /* Increment all the refcounts at start and decrement at end in order to 
1297      * be sure to free objects if there is no slave in a replication state 
1298      * able to be feed with commands */ 
1299     for (j 
= 0; j 
< outc
; j
++) incrRefCount(outv
[j
]); 
1301     while((ln 
= listYield(slaves
))) { 
1302         redisClient 
*slave 
= ln
->value
; 
1304         /* Don't feed slaves that are still waiting for BGSAVE to start */ 
1305         if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_START
) continue; 
1307         /* Feed all the other slaves, MONITORs and so on */ 
1308         if (slave
->slaveseldb 
!= dictid
) { 
1312             case 0: selectcmd 
= shared
.select0
; break; 
1313             case 1: selectcmd 
= shared
.select1
; break; 
1314             case 2: selectcmd 
= shared
.select2
; break; 
1315             case 3: selectcmd 
= shared
.select3
; break; 
1316             case 4: selectcmd 
= shared
.select4
; break; 
1317             case 5: selectcmd 
= shared
.select5
; break; 
1318             case 6: selectcmd 
= shared
.select6
; break; 
1319             case 7: selectcmd 
= shared
.select7
; break; 
1320             case 8: selectcmd 
= shared
.select8
; break; 
1321             case 9: selectcmd 
= shared
.select9
; break; 
1323                 selectcmd 
= createObject(REDIS_STRING
, 
1324                     sdscatprintf(sdsempty(),"select %d\r\n",dictid
)); 
1325                 selectcmd
->refcount 
= 0; 
1328             addReply(slave
,selectcmd
); 
1329             slave
->slaveseldb 
= dictid
; 
1331         for (j 
= 0; j 
< outc
; j
++) addReply(slave
,outv
[j
]); 
1333     for (j 
= 0; j 
< outc
; j
++) decrRefCount(outv
[j
]); 
1334     if (outv 
!= static_outv
) zfree(outv
); 
1337 static void readQueryFromClient(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
1338     redisClient 
*c 
= (redisClient
*) privdata
; 
1339     char buf
[REDIS_IOBUF_LEN
]; 
1342     REDIS_NOTUSED(mask
); 
1344     nread 
= read(fd
, buf
, REDIS_IOBUF_LEN
); 
1346         if (errno 
== EAGAIN
) { 
1349             redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
)); 
1353     } else if (nread 
== 0) { 
1354         redisLog(REDIS_DEBUG
, "Client closed connection"); 
1359         c
->querybuf 
= sdscatlen(c
->querybuf
, buf
, nread
); 
1360         c
->lastinteraction 
= time(NULL
); 
1366     if (c
->bulklen 
== -1) { 
1367         /* Read the first line of the query */ 
1368         char *p 
= strchr(c
->querybuf
,'\n'); 
1374             query 
= c
->querybuf
; 
1375             c
->querybuf 
= sdsempty(); 
1376             querylen 
= 1+(p
-(query
)); 
1377             if (sdslen(query
) > querylen
) { 
1378                 /* leave data after the first line of the query in the buffer */ 
1379                 c
->querybuf 
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
); 
1381             *p 
= '\0'; /* remove "\n" */ 
1382             if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */ 
1383             sdsupdatelen(query
); 
1385             /* Now we can split the query in arguments */ 
1386             if (sdslen(query
) == 0) { 
1387                 /* Ignore empty query */ 
1391             argv 
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
); 
1392             if (argv 
== NULL
) oom("sdssplitlen"); 
1395             if (c
->argv
) zfree(c
->argv
); 
1396             c
->argv 
= zmalloc(sizeof(robj
*)*argc
); 
1397             if (c
->argv 
== NULL
) oom("allocating arguments list for client"); 
1399             for (j 
= 0; j 
< argc
; j
++) { 
1400                 if (sdslen(argv
[j
])) { 
1401                     c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]); 
1408             /* Execute the command. If the client is still valid 
1409              * after processCommand() return and there is something 
1410              * on the query buffer try to process the next command. */ 
1411             if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
; 
1413         } else if (sdslen(c
->querybuf
) >= 1024) { 
1414             redisLog(REDIS_DEBUG
, "Client protocol error"); 
1419         /* Bulk read handling. Note that if we are at this point 
1420            the client already sent a command terminated with a newline, 
1421            we are reading the bulk data that is actually the last 
1422            argument of the command. */ 
1423         int qbl 
= sdslen(c
->querybuf
); 
1425         if (c
->bulklen 
<= qbl
) { 
1426             /* Copy everything but the final CRLF as final argument */ 
1427             c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2); 
1429             c
->querybuf 
= sdsrange(c
->querybuf
,c
->bulklen
,-1); 
1436 static int selectDb(redisClient 
*c
, int id
) { 
1437     if (id 
< 0 || id 
>= server
.dbnum
) 
1439     c
->db 
= &server
.db
[id
]; 
1443 static void *dupClientReplyValue(void *o
) { 
1444     incrRefCount((robj
*)o
); 
1448 static redisClient 
*createClient(int fd
) { 
1449     redisClient 
*c 
= zmalloc(sizeof(*c
)); 
1451     anetNonBlock(NULL
,fd
); 
1452     anetTcpNoDelay(NULL
,fd
); 
1453     if (!c
) return NULL
; 
1456     c
->querybuf 
= sdsempty(); 
1462     c
->lastinteraction 
= time(NULL
); 
1463     c
->authenticated 
= 0; 
1464     c
->replstate 
= REDIS_REPL_NONE
; 
1465     if ((c
->reply 
= listCreate()) == NULL
) oom("listCreate"); 
1466     listSetFreeMethod(c
->reply
,decrRefCount
); 
1467     listSetDupMethod(c
->reply
,dupClientReplyValue
); 
1468     if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, 
1469         readQueryFromClient
, c
, NULL
) == AE_ERR
) { 
1473     if (!listAddNodeTail(server
.clients
,c
)) oom("listAddNodeTail"); 
1477 static void addReply(redisClient 
*c
, robj 
*obj
) { 
1478     if (listLength(c
->reply
) == 0 && 
1479         (c
->replstate 
== REDIS_REPL_NONE 
|| 
1480          c
->replstate 
== REDIS_REPL_ONLINE
) && 
1481         aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
, 
1482         sendReplyToClient
, c
, NULL
) == AE_ERR
) return; 
1483     if (!listAddNodeTail(c
->reply
,obj
)) oom("listAddNodeTail"); 
1487 static void addReplySds(redisClient 
*c
, sds s
) { 
1488     robj 
*o 
= createObject(REDIS_STRING
,s
); 
1493 static void acceptHandler(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
1497     REDIS_NOTUSED(mask
); 
1498     REDIS_NOTUSED(privdata
); 
1500     cfd 
= anetAccept(server
.neterr
, fd
, cip
, &cport
); 
1501     if (cfd 
== AE_ERR
) { 
1502         redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
); 
1505     redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
); 
1506     if (createClient(cfd
) == NULL
) { 
1507         redisLog(REDIS_WARNING
,"Error allocating resoures for the client"); 
1508         close(cfd
); /* May be already closed, just ingore errors */ 
1511     server
.stat_numconnections
++; 
1514 /* ======================= Redis objects implementation ===================== */ 
1516 static robj 
*createObject(int type
, void *ptr
) { 
1519     if (listLength(server
.objfreelist
)) { 
1520         listNode 
*head 
= listFirst(server
.objfreelist
); 
1521         o 
= listNodeValue(head
); 
1522         listDelNode(server
.objfreelist
,head
); 
1524         o 
= zmalloc(sizeof(*o
)); 
1526     if (!o
) oom("createObject"); 
1533 static robj 
*createStringObject(char *ptr
, size_t len
) { 
1534     return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
)); 
1537 static robj 
*createListObject(void) { 
1538     list 
*l 
= listCreate(); 
1540     if (!l
) oom("listCreate"); 
1541     listSetFreeMethod(l
,decrRefCount
); 
1542     return createObject(REDIS_LIST
,l
); 
1545 static robj 
*createSetObject(void) { 
1546     dict 
*d 
= dictCreate(&setDictType
,NULL
); 
1547     if (!d
) oom("dictCreate"); 
1548     return createObject(REDIS_SET
,d
); 
1551 static void freeStringObject(robj 
*o
) { 
1555 static void freeListObject(robj 
*o
) { 
1556     listRelease((list
*) o
->ptr
); 
1559 static void freeSetObject(robj 
*o
) { 
1560     dictRelease((dict
*) o
->ptr
); 
1563 static void freeHashObject(robj 
*o
) { 
1564     dictRelease((dict
*) o
->ptr
); 
1567 static void incrRefCount(robj 
*o
) { 
1569 #ifdef DEBUG_REFCOUNT 
1570     if (o
->type 
== REDIS_STRING
) 
1571         printf("Increment '%s'(%p), now is: %d\n",o
->ptr
,o
,o
->refcount
); 
1575 static void decrRefCount(void *obj
) { 
1578 #ifdef DEBUG_REFCOUNT 
1579     if (o
->type 
== REDIS_STRING
) 
1580         printf("Decrement '%s'(%p), now is: %d\n",o
->ptr
,o
,o
->refcount
-1); 
1582     if (--(o
->refcount
) == 0) { 
1584         case REDIS_STRING
: freeStringObject(o
); break; 
1585         case REDIS_LIST
: freeListObject(o
); break; 
1586         case REDIS_SET
: freeSetObject(o
); break; 
1587         case REDIS_HASH
: freeHashObject(o
); break; 
1588         default: assert(0 != 0); break; 
1590         if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX 
|| 
1591             !listAddNodeHead(server
.objfreelist
,o
)) 
1596 /* Try to share an object against the shared objects pool */ 
1597 static robj 
*tryObjectSharing(robj 
*o
) { 
1598     struct dictEntry 
*de
; 
1601     if (o 
== NULL 
|| server
.shareobjects 
== 0) return o
; 
1603     assert(o
->type 
== REDIS_STRING
); 
1604     de 
= dictFind(server
.sharingpool
,o
); 
1606         robj 
*shared 
= dictGetEntryKey(de
); 
1608         c 
= ((unsigned long) dictGetEntryVal(de
))+1; 
1609         dictGetEntryVal(de
) = (void*) c
; 
1610         incrRefCount(shared
); 
1614         /* Here we are using a stream algorihtm: Every time an object is 
1615          * shared we increment its count, everytime there is a miss we 
1616          * recrement the counter of a random object. If this object reaches 
1617          * zero we remove the object and put the current object instead. */ 
1618         if (dictSize(server
.sharingpool
) >= 
1619                 server
.sharingpoolsize
) { 
1620             de 
= dictGetRandomKey(server
.sharingpool
); 
1622             c 
= ((unsigned long) dictGetEntryVal(de
))-1; 
1623             dictGetEntryVal(de
) = (void*) c
; 
1625                 dictDelete(server
.sharingpool
,de
->key
); 
1628             c 
= 0; /* If the pool is empty we want to add this object */ 
1633             retval 
= dictAdd(server
.sharingpool
,o
,(void*)1); 
1634             assert(retval 
== DICT_OK
); 
1641 static robj 
*lookupKey(redisDb 
*db
, robj 
*key
) { 
1642     dictEntry 
*de 
= dictFind(db
->dict
,key
); 
1643     return de 
? dictGetEntryVal(de
) : NULL
; 
1646 static robj 
*lookupKeyRead(redisDb 
*db
, robj 
*key
) { 
1647     expireIfNeeded(db
,key
); 
1648     return lookupKey(db
,key
); 
1651 static robj 
*lookupKeyWrite(redisDb 
*db
, robj 
*key
) { 
1652     deleteIfVolatile(db
,key
); 
1653     return lookupKey(db
,key
); 
1656 static int deleteKey(redisDb 
*db
, robj 
*key
) { 
1659     /* We need to protect key from destruction: after the first dictDelete() 
1660      * it may happen that 'key' is no longer valid if we don't increment 
1661      * it's count. This may happen when we get the object reference directly 
1662      * from the hash table with dictRandomKey() or dict iterators */ 
1664     if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
); 
1665     retval 
= dictDelete(db
->dict
,key
); 
1668     return retval 
== DICT_OK
; 
1671 /*============================ DB saving/loading ============================ */ 
1673 static int rdbSaveType(FILE *fp
, unsigned char type
) { 
1674     if (fwrite(&type
,1,1,fp
) == 0) return -1; 
1678 static int rdbSaveTime(FILE *fp
, time_t t
) { 
1679     int32_t t32 
= (int32_t) t
; 
1680     if (fwrite(&t32
,4,1,fp
) == 0) return -1; 
1684 /* check rdbLoadLen() comments for more info */ 
1685 static int rdbSaveLen(FILE *fp
, uint32_t len
) { 
1686     unsigned char buf
[2]; 
1689         /* Save a 6 bit len */ 
1690         buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6); 
1691         if (fwrite(buf
,1,1,fp
) == 0) return -1; 
1692     } else if (len 
< (1<<14)) { 
1693         /* Save a 14 bit len */ 
1694         buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6); 
1696         if (fwrite(buf
,2,1,fp
) == 0) return -1; 
1698         /* Save a 32 bit len */ 
1699         buf
[0] = (REDIS_RDB_32BITLEN
<<6); 
1700         if (fwrite(buf
,1,1,fp
) == 0) return -1; 
1702         if (fwrite(&len
,4,1,fp
) == 0) return -1; 
1707 /* String objects in the form "2391" "-100" without any space and with a 
1708  * range of values that can fit in an 8, 16 or 32 bit signed value can be 
1709  * encoded as integers to save space */ 
1710 int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) { 
1712     char *endptr
, buf
[32]; 
1714     /* Check if it's possible to encode this value as a number */ 
1715     value 
= strtoll(s
, &endptr
, 10); 
1716     if (endptr
[0] != '\0') return 0; 
1717     snprintf(buf
,32,"%lld",value
); 
1719     /* If the number converted back into a string is not identical 
1720      * then it's not possible to encode the string as integer */ 
1721     if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0; 
1723     /* Finally check if it fits in our ranges */ 
1724     if (value 
>= -(1<<7) && value 
<= (1<<7)-1) { 
1725         enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
; 
1726         enc
[1] = value
&0xFF; 
1728     } else if (value 
>= -(1<<15) && value 
<= (1<<15)-1) { 
1729         enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
; 
1730         enc
[1] = value
&0xFF; 
1731         enc
[2] = (value
>>8)&0xFF; 
1733     } else if (value 
>= -((long long)1<<31) && value 
<= ((long long)1<<31)-1) { 
1734         enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
; 
1735         enc
[1] = value
&0xFF; 
1736         enc
[2] = (value
>>8)&0xFF; 
1737         enc
[3] = (value
>>16)&0xFF; 
1738         enc
[4] = (value
>>24)&0xFF; 
1745 static int rdbSaveLzfStringObject(FILE *fp
, robj 
*obj
) { 
1746     unsigned int comprlen
, outlen
; 
1750     /* We require at least four bytes compression for this to be worth it */ 
1751     outlen 
= sdslen(obj
->ptr
)-4; 
1752     if (outlen 
<= 0) return 0; 
1753     if ((out 
= zmalloc(outlen
+1)) == NULL
) return 0; 
1754     comprlen 
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
); 
1755     if (comprlen 
== 0) { 
1759     /* Data compressed! Let's save it on disk */ 
1760     byte 
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
; 
1761     if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
; 
1762     if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
; 
1763     if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
; 
1764     if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
; 
1773 /* Save a string objet as [len][data] on disk. If the object is a string 
1774  * representation of an integer value we try to safe it in a special form */ 
1775 static int rdbSaveStringObject(FILE *fp
, robj 
*obj
) { 
1776     size_t len 
= sdslen(obj
->ptr
); 
1779     /* Try integer encoding */ 
1781         unsigned char buf
[5]; 
1782         if ((enclen 
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) { 
1783             if (fwrite(buf
,enclen
,1,fp
) == 0) return -1; 
1788     /* Try LZF compression - under 20 bytes it's unable to compress even 
1789      * aaaaaaaaaaaaaaaaaa so skip it */ 
1790     if (1 && len 
> 20) { 
1793         retval 
= rdbSaveLzfStringObject(fp
,obj
); 
1794         if (retval 
== -1) return -1; 
1795         if (retval 
> 0) return 0; 
1796         /* retval == 0 means data can't be compressed, save the old way */ 
1799     /* Store verbatim */ 
1800     if (rdbSaveLen(fp
,len
) == -1) return -1; 
1801     if (len 
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1; 
1805 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */ 
1806 static int rdbSave(char *filename
) { 
1807     dictIterator 
*di 
= NULL
; 
1812     time_t now 
= time(NULL
); 
1814     snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random()); 
1815     fp 
= fopen(tmpfile
,"w"); 
1817         redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
)); 
1820     if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
; 
1821     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
1822         redisDb 
*db 
= server
.db
+j
; 
1824         if (dictSize(d
) == 0) continue; 
1825         di 
= dictGetIterator(d
); 
1831         /* Write the SELECT DB opcode */ 
1832         if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
; 
1833         if (rdbSaveLen(fp
,j
) == -1) goto werr
; 
1835         /* Iterate this DB writing every entry */ 
1836         while((de 
= dictNext(di
)) != NULL
) { 
1837             robj 
*key 
= dictGetEntryKey(de
); 
1838             robj 
*o 
= dictGetEntryVal(de
); 
1839             time_t expiretime 
= getExpire(db
,key
); 
1841             /* Save the expire time */ 
1842             if (expiretime 
!= -1) { 
1843                 /* If this key is already expired skip it */ 
1844                 if (expiretime 
< now
) continue; 
1845                 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
; 
1846                 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
; 
1848             /* Save the key and associated value */ 
1849             if (rdbSaveType(fp
,o
->type
) == -1) goto werr
; 
1850             if (rdbSaveStringObject(fp
,key
) == -1) goto werr
; 
1851             if (o
->type 
== REDIS_STRING
) { 
1852                 /* Save a string value */ 
1853                 if (rdbSaveStringObject(fp
,o
) == -1) goto werr
; 
1854             } else if (o
->type 
== REDIS_LIST
) { 
1855                 /* Save a list value */ 
1856                 list 
*list 
= o
->ptr
; 
1860                 if (rdbSaveLen(fp
,listLength(list
)) == -1) goto werr
; 
1861                 while((ln 
= listYield(list
))) { 
1862                     robj 
*eleobj 
= listNodeValue(ln
); 
1864                     if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
; 
1866             } else if (o
->type 
== REDIS_SET
) { 
1867                 /* Save a set value */ 
1869                 dictIterator 
*di 
= dictGetIterator(set
); 
1872                 if (!set
) oom("dictGetIteraotr"); 
1873                 if (rdbSaveLen(fp
,dictSize(set
)) == -1) goto werr
; 
1874                 while((de 
= dictNext(di
)) != NULL
) { 
1875                     robj 
*eleobj 
= dictGetEntryKey(de
); 
1877                     if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
; 
1879                 dictReleaseIterator(di
); 
1884         dictReleaseIterator(di
); 
1887     if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
; 
1889     /* Make sure data will not remain on the OS's output buffers */ 
1894     /* Use RENAME to make sure the DB file is changed atomically only 
1895      * if the generate DB file is ok. */ 
1896     if (rename(tmpfile
,filename
) == -1) { 
1897         redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destionation: %s", strerror(errno
)); 
1901     redisLog(REDIS_NOTICE
,"DB saved on disk"); 
1903     server
.lastsave 
= time(NULL
); 
1909     redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
)); 
1910     if (di
) dictReleaseIterator(di
); 
1914 static int rdbSaveBackground(char *filename
) { 
1917     if (server
.bgsaveinprogress
) return REDIS_ERR
; 
1918     if ((childpid 
= fork()) == 0) { 
1921         if (rdbSave(filename
) == REDIS_OK
) { 
1928         if (childpid 
== -1) { 
1929             redisLog(REDIS_WARNING
,"Can't save in background: fork: %s", 
1933         redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
); 
1934         server
.bgsaveinprogress 
= 1; 
1937     return REDIS_OK
; /* unreached */ 
1940 static int rdbLoadType(FILE *fp
) { 
1942     if (fread(&type
,1,1,fp
) == 0) return -1; 
1946 static time_t rdbLoadTime(FILE *fp
) { 
1948     if (fread(&t32
,4,1,fp
) == 0) return -1; 
1949     return (time_t) t32
; 
1952 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top 
1953  * of this file for a description of how this are stored on disk. 
1955  * isencoded is set to 1 if the readed length is not actually a length but 
1956  * an "encoding type", check the above comments for more info */ 
1957 static uint32_t rdbLoadLen(FILE *fp
, int rdbver
, int *isencoded
) { 
1958     unsigned char buf
[2]; 
1961     if (isencoded
) *isencoded 
= 0; 
1963         if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
; 
1968         if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
; 
1969         type 
= (buf
[0]&0xC0)>>6; 
1970         if (type 
== REDIS_RDB_6BITLEN
) { 
1971             /* Read a 6 bit len */ 
1973         } else if (type 
== REDIS_RDB_ENCVAL
) { 
1974             /* Read a 6 bit len encoding type */ 
1975             if (isencoded
) *isencoded 
= 1; 
1977         } else if (type 
== REDIS_RDB_14BITLEN
) { 
1978             /* Read a 14 bit len */ 
1979             if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
; 
1980             return ((buf
[0]&0x3F)<<8)|buf
[1]; 
1982             /* Read a 32 bit len */ 
1983             if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
; 
1989 static robj 
*rdbLoadIntegerObject(FILE *fp
, int enctype
) { 
1990     unsigned char enc
[4]; 
1993     if (enctype 
== REDIS_RDB_ENC_INT8
) { 
1994         if (fread(enc
,1,1,fp
) == 0) return NULL
; 
1995         val 
= (signed char)enc
[0]; 
1996     } else if (enctype 
== REDIS_RDB_ENC_INT16
) { 
1998         if (fread(enc
,2,1,fp
) == 0) return NULL
; 
1999         v 
= enc
[0]|(enc
[1]<<8); 
2001     } else if (enctype 
== REDIS_RDB_ENC_INT32
) { 
2003         if (fread(enc
,4,1,fp
) == 0) return NULL
; 
2004         v 
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24); 
2007         val 
= 0; /* anti-warning */ 
2010     return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
)); 
2013 static robj 
*rdbLoadLzfStringObject(FILE*fp
, int rdbver
) { 
2014     unsigned int len
, clen
; 
2015     unsigned char *c 
= NULL
; 
2018     if ((clen 
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
) return NULL
; 
2019     if ((len 
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
) return NULL
; 
2020     if ((c 
= zmalloc(clen
)) == NULL
) goto err
; 
2021     if ((val 
= sdsnewlen(NULL
,len
)) == NULL
) goto err
; 
2022     if (fread(c
,clen
,1,fp
) == 0) goto err
; 
2023     if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
; 
2025     return createObject(REDIS_STRING
,val
); 
2032 static robj 
*rdbLoadStringObject(FILE*fp
, int rdbver
) { 
2037     len 
= rdbLoadLen(fp
,rdbver
,&isencoded
); 
2040         case REDIS_RDB_ENC_INT8
: 
2041         case REDIS_RDB_ENC_INT16
: 
2042         case REDIS_RDB_ENC_INT32
: 
2043             return tryObjectSharing(rdbLoadIntegerObject(fp
,len
)); 
2044         case REDIS_RDB_ENC_LZF
: 
2045             return tryObjectSharing(rdbLoadLzfStringObject(fp
,rdbver
)); 
2051     if (len 
== REDIS_RDB_LENERR
) return NULL
; 
2052     val 
= sdsnewlen(NULL
,len
); 
2053     if (len 
&& fread(val
,len
,1,fp
) == 0) { 
2057     return tryObjectSharing(createObject(REDIS_STRING
,val
)); 
2060 static int rdbLoad(char *filename
) { 
2062     robj 
*keyobj 
= NULL
; 
2064     int type
, retval
, rdbver
; 
2065     dict 
*d 
= server
.db
[0].dict
; 
2066     redisDb 
*db 
= server
.db
+0; 
2068     time_t expiretime 
= -1, now 
= time(NULL
); 
2070     fp 
= fopen(filename
,"r"); 
2071     if (!fp
) return REDIS_ERR
; 
2072     if (fread(buf
,9,1,fp
) == 0) goto eoferr
; 
2074     if (memcmp(buf
,"REDIS",5) != 0) { 
2076         redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file"); 
2079     rdbver 
= atoi(buf
+5); 
2082         redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
); 
2089         if ((type 
= rdbLoadType(fp
)) == -1) goto eoferr
; 
2090         if (type 
== REDIS_EXPIRETIME
) { 
2091             if ((expiretime 
= rdbLoadTime(fp
)) == -1) goto eoferr
; 
2092             /* We read the time so we need to read the object type again */ 
2093             if ((type 
= rdbLoadType(fp
)) == -1) goto eoferr
; 
2095         if (type 
== REDIS_EOF
) break; 
2096         /* Handle SELECT DB opcode as a special case */ 
2097         if (type 
== REDIS_SELECTDB
) { 
2098             if ((dbid 
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
) 
2100             if (dbid 
>= (unsigned)server
.dbnum
) { 
2101                 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
); 
2104             db 
= server
.db
+dbid
; 
2109         if ((keyobj 
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
; 
2111         if (type 
== REDIS_STRING
) { 
2112             /* Read string value */ 
2113             if ((o 
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
; 
2114         } else if (type 
== REDIS_LIST 
|| type 
== REDIS_SET
) { 
2115             /* Read list/set value */ 
2118             if ((listlen 
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
) 
2120             o 
= (type 
== REDIS_LIST
) ? createListObject() : createSetObject(); 
2121             /* Load every single element of the list/set */ 
2125                 if ((ele 
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
; 
2126                 if (type 
== REDIS_LIST
) { 
2127                     if (!listAddNodeTail((list
*)o
->ptr
,ele
)) 
2128                         oom("listAddNodeTail"); 
2130                     if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
) 
2137         /* Add the new object in the hash table */ 
2138         retval 
= dictAdd(d
,keyobj
,o
); 
2139         if (retval 
== DICT_ERR
) { 
2140             redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
); 
2143         /* Set the expire time if needed */ 
2144         if (expiretime 
!= -1) { 
2145             setExpire(db
,keyobj
,expiretime
); 
2146             /* Delete this key if already expired */ 
2147             if (expiretime 
< now
) deleteKey(db
,keyobj
); 
2155 eoferr
: /* unexpected end of file is handled here with a fatal exit */ 
2156     if (keyobj
) decrRefCount(keyobj
); 
2157     redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, exiting now."); 
2159     return REDIS_ERR
; /* Just to avoid warning */ 
2162 /*================================== Commands =============================== */ 
2164 static void authCommand(redisClient 
*c
) { 
2165     if (!server
.requirepass 
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) { 
2166       c
->authenticated 
= 1; 
2167       addReply(c
,shared
.ok
); 
2169       c
->authenticated 
= 0; 
2170       addReply(c
,shared
.err
); 
2174 static void pingCommand(redisClient 
*c
) { 
2175     addReply(c
,shared
.pong
); 
2178 static void echoCommand(redisClient 
*c
) { 
2179     addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n", 
2180         (int)sdslen(c
->argv
[1]->ptr
))); 
2181     addReply(c
,c
->argv
[1]); 
2182     addReply(c
,shared
.crlf
); 
2185 /*=================================== Strings =============================== */ 
2187 static void setGenericCommand(redisClient 
*c
, int nx
) { 
2190     retval 
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]); 
2191     if (retval 
== DICT_ERR
) { 
2193             dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]); 
2194             incrRefCount(c
->argv
[2]); 
2196             addReply(c
,shared
.czero
); 
2200         incrRefCount(c
->argv
[1]); 
2201         incrRefCount(c
->argv
[2]); 
2204     removeExpire(c
->db
,c
->argv
[1]); 
2205     addReply(c
, nx 
? shared
.cone 
: shared
.ok
); 
2208 static void setCommand(redisClient 
*c
) { 
2209     setGenericCommand(c
,0); 
2212 static void setnxCommand(redisClient 
*c
) { 
2213     setGenericCommand(c
,1); 
2216 static void getCommand(redisClient 
*c
) { 
2217     robj 
*o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
2220         addReply(c
,shared
.nullbulk
); 
2222         if (o
->type 
!= REDIS_STRING
) { 
2223             addReply(c
,shared
.wrongtypeerr
); 
2225             addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
))); 
2227             addReply(c
,shared
.crlf
); 
2232 static void getSetCommand(redisClient 
*c
) { 
2234     if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) { 
2235         dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]); 
2237         incrRefCount(c
->argv
[1]); 
2239     incrRefCount(c
->argv
[2]); 
2241     removeExpire(c
->db
,c
->argv
[1]); 
2244 static void mgetCommand(redisClient 
*c
) { 
2247     addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1)); 
2248     for (j 
= 1; j 
< c
->argc
; j
++) { 
2249         robj 
*o 
= lookupKeyRead(c
->db
,c
->argv
[j
]); 
2251             addReply(c
,shared
.nullbulk
); 
2253             if (o
->type 
!= REDIS_STRING
) { 
2254                 addReply(c
,shared
.nullbulk
); 
2256                 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
))); 
2258                 addReply(c
,shared
.crlf
); 
2264 static void incrDecrCommand(redisClient 
*c
, long long incr
) { 
2269     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2273         if (o
->type 
!= REDIS_STRING
) { 
2278             value 
= strtoll(o
->ptr
, &eptr
, 10); 
2283     o 
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
)); 
2284     retval 
= dictAdd(c
->db
->dict
,c
->argv
[1],o
); 
2285     if (retval 
== DICT_ERR
) { 
2286         dictReplace(c
->db
->dict
,c
->argv
[1],o
); 
2287         removeExpire(c
->db
,c
->argv
[1]); 
2289         incrRefCount(c
->argv
[1]); 
2292     addReply(c
,shared
.colon
); 
2294     addReply(c
,shared
.crlf
); 
2297 static void incrCommand(redisClient 
*c
) { 
2298     incrDecrCommand(c
,1); 
2301 static void decrCommand(redisClient 
*c
) { 
2302     incrDecrCommand(c
,-1); 
2305 static void incrbyCommand(redisClient 
*c
) { 
2306     long long incr 
= strtoll(c
->argv
[2]->ptr
, NULL
, 10); 
2307     incrDecrCommand(c
,incr
); 
2310 static void decrbyCommand(redisClient 
*c
) { 
2311     long long incr 
= strtoll(c
->argv
[2]->ptr
, NULL
, 10); 
2312     incrDecrCommand(c
,-incr
); 
2315 /* ========================= Type agnostic commands ========================= */ 
2317 static void delCommand(redisClient 
*c
) { 
2320     for (j 
= 1; j 
< c
->argc
; j
++) { 
2321         if (deleteKey(c
->db
,c
->argv
[j
])) { 
2328         addReply(c
,shared
.czero
); 
2331         addReply(c
,shared
.cone
); 
2334         addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
)); 
2339 static void existsCommand(redisClient 
*c
) { 
2340     addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone 
: shared
.czero
); 
2343 static void selectCommand(redisClient 
*c
) { 
2344     int id 
= atoi(c
->argv
[1]->ptr
); 
2346     if (selectDb(c
,id
) == REDIS_ERR
) { 
2347         addReplySds(c
,sdsnew("-ERR invalid DB index\r\n")); 
2349         addReply(c
,shared
.ok
); 
2353 static void randomkeyCommand(redisClient 
*c
) { 
2357         de 
= dictGetRandomKey(c
->db
->dict
); 
2358         if (!de 
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break; 
2361         addReply(c
,shared
.plus
); 
2362         addReply(c
,shared
.crlf
); 
2364         addReply(c
,shared
.plus
); 
2365         addReply(c
,dictGetEntryKey(de
)); 
2366         addReply(c
,shared
.crlf
); 
2370 static void keysCommand(redisClient 
*c
) { 
2373     sds pattern 
= c
->argv
[1]->ptr
; 
2374     int plen 
= sdslen(pattern
); 
2375     int numkeys 
= 0, keyslen 
= 0; 
2376     robj 
*lenobj 
= createObject(REDIS_STRING
,NULL
); 
2378     di 
= dictGetIterator(c
->db
->dict
); 
2379     if (!di
) oom("dictGetIterator"); 
2381     decrRefCount(lenobj
); 
2382     while((de 
= dictNext(di
)) != NULL
) { 
2383         robj 
*keyobj 
= dictGetEntryKey(de
); 
2385         sds key 
= keyobj
->ptr
; 
2386         if ((pattern
[0] == '*' && pattern
[1] == '\0') || 
2387             stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) { 
2388             if (expireIfNeeded(c
->db
,keyobj
) == 0) { 
2390                     addReply(c
,shared
.space
); 
2393                 keyslen 
+= sdslen(key
); 
2397     dictReleaseIterator(di
); 
2398     lenobj
->ptr 
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys 
? (numkeys
-1) : 0)); 
2399     addReply(c
,shared
.crlf
); 
2402 static void dbsizeCommand(redisClient 
*c
) { 
2404         sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
))); 
2407 static void lastsaveCommand(redisClient 
*c
) { 
2409         sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
)); 
2412 static void typeCommand(redisClient 
*c
) { 
2416     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
2421         case REDIS_STRING
: type 
= "+string"; break; 
2422         case REDIS_LIST
: type 
= "+list"; break; 
2423         case REDIS_SET
: type 
= "+set"; break; 
2424         default: type 
= "unknown"; break; 
2427     addReplySds(c
,sdsnew(type
)); 
2428     addReply(c
,shared
.crlf
); 
2431 static void saveCommand(redisClient 
*c
) { 
2432     if (server
.bgsaveinprogress
) { 
2433         addReplySds(c
,sdsnew("-ERR background save in progress\r\n")); 
2436     if (rdbSave(server
.dbfilename
) == REDIS_OK
) { 
2437         addReply(c
,shared
.ok
); 
2439         addReply(c
,shared
.err
); 
2443 static void bgsaveCommand(redisClient 
*c
) { 
2444     if (server
.bgsaveinprogress
) { 
2445         addReplySds(c
,sdsnew("-ERR background save already in progress\r\n")); 
2448     if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) { 
2449         addReply(c
,shared
.ok
); 
2451         addReply(c
,shared
.err
); 
2455 static void shutdownCommand(redisClient 
*c
) { 
2456     redisLog(REDIS_WARNING
,"User requested shutdown, saving DB..."); 
2457     /* XXX: TODO kill the child if there is a bgsave in progress */ 
2458     if (rdbSave(server
.dbfilename
) == REDIS_OK
) { 
2459         if (server
.daemonize
) { 
2460             unlink(server
.pidfile
); 
2462         redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory()); 
2463         redisLog(REDIS_WARNING
,"Server exit now, bye bye..."); 
2466         redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");  
2467         addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n")); 
2471 static void renameGenericCommand(redisClient 
*c
, int nx
) { 
2474     /* To use the same key as src and dst is probably an error */ 
2475     if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) { 
2476         addReply(c
,shared
.sameobjecterr
); 
2480     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2482         addReply(c
,shared
.nokeyerr
); 
2486     deleteIfVolatile(c
->db
,c
->argv
[2]); 
2487     if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) { 
2490             addReply(c
,shared
.czero
); 
2493         dictReplace(c
->db
->dict
,c
->argv
[2],o
); 
2495         incrRefCount(c
->argv
[2]); 
2497     deleteKey(c
->db
,c
->argv
[1]); 
2499     addReply(c
,nx 
? shared
.cone 
: shared
.ok
); 
2502 static void renameCommand(redisClient 
*c
) { 
2503     renameGenericCommand(c
,0); 
2506 static void renamenxCommand(redisClient 
*c
) { 
2507     renameGenericCommand(c
,1); 
2510 static void moveCommand(redisClient 
*c
) { 
2515     /* Obtain source and target DB pointers */ 
2518     if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) { 
2519         addReply(c
,shared
.outofrangeerr
); 
2523     selectDb(c
,srcid
); /* Back to the source DB */ 
2525     /* If the user is moving using as target the same 
2526      * DB as the source DB it is probably an error. */ 
2528         addReply(c
,shared
.sameobjecterr
); 
2532     /* Check if the element exists and get a reference */ 
2533     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2535         addReply(c
,shared
.czero
); 
2539     /* Try to add the element to the target DB */ 
2540     deleteIfVolatile(dst
,c
->argv
[1]); 
2541     if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) { 
2542         addReply(c
,shared
.czero
); 
2545     incrRefCount(c
->argv
[1]); 
2548     /* OK! key moved, free the entry in the source DB */ 
2549     deleteKey(src
,c
->argv
[1]); 
2551     addReply(c
,shared
.cone
); 
2554 /* =================================== Lists ================================ */ 
2555 static void pushGenericCommand(redisClient 
*c
, int where
) { 
2559     lobj 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2561         lobj 
= createListObject(); 
2563         if (where 
== REDIS_HEAD
) { 
2564             if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead"); 
2566             if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail"); 
2568         dictAdd(c
->db
->dict
,c
->argv
[1],lobj
); 
2569         incrRefCount(c
->argv
[1]); 
2570         incrRefCount(c
->argv
[2]); 
2572         if (lobj
->type 
!= REDIS_LIST
) { 
2573             addReply(c
,shared
.wrongtypeerr
); 
2577         if (where 
== REDIS_HEAD
) { 
2578             if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead"); 
2580             if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail"); 
2582         incrRefCount(c
->argv
[2]); 
2585     addReply(c
,shared
.ok
); 
2588 static void lpushCommand(redisClient 
*c
) { 
2589     pushGenericCommand(c
,REDIS_HEAD
); 
2592 static void rpushCommand(redisClient 
*c
) { 
2593     pushGenericCommand(c
,REDIS_TAIL
); 
2596 static void llenCommand(redisClient 
*c
) { 
2600     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
2602         addReply(c
,shared
.czero
); 
2605         if (o
->type 
!= REDIS_LIST
) { 
2606             addReply(c
,shared
.wrongtypeerr
); 
2609             addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
))); 
2614 static void lindexCommand(redisClient 
*c
) { 
2616     int index 
= atoi(c
->argv
[2]->ptr
); 
2618     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
2620         addReply(c
,shared
.nullbulk
); 
2622         if (o
->type 
!= REDIS_LIST
) { 
2623             addReply(c
,shared
.wrongtypeerr
); 
2625             list 
*list 
= o
->ptr
; 
2628             ln 
= listIndex(list
, index
); 
2630                 addReply(c
,shared
.nullbulk
); 
2632                 robj 
*ele 
= listNodeValue(ln
); 
2633                 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
))); 
2635                 addReply(c
,shared
.crlf
); 
2641 static void lsetCommand(redisClient 
*c
) { 
2643     int index 
= atoi(c
->argv
[2]->ptr
); 
2645     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2647         addReply(c
,shared
.nokeyerr
); 
2649         if (o
->type 
!= REDIS_LIST
) { 
2650             addReply(c
,shared
.wrongtypeerr
); 
2652             list 
*list 
= o
->ptr
; 
2655             ln 
= listIndex(list
, index
); 
2657                 addReply(c
,shared
.outofrangeerr
); 
2659                 robj 
*ele 
= listNodeValue(ln
); 
2662                 listNodeValue(ln
) = c
->argv
[3]; 
2663                 incrRefCount(c
->argv
[3]); 
2664                 addReply(c
,shared
.ok
); 
2671 static void popGenericCommand(redisClient 
*c
, int where
) { 
2674     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2676         addReply(c
,shared
.nullbulk
); 
2678         if (o
->type 
!= REDIS_LIST
) { 
2679             addReply(c
,shared
.wrongtypeerr
); 
2681             list 
*list 
= o
->ptr
; 
2684             if (where 
== REDIS_HEAD
) 
2685                 ln 
= listFirst(list
); 
2687                 ln 
= listLast(list
); 
2690                 addReply(c
,shared
.nullbulk
); 
2692                 robj 
*ele 
= listNodeValue(ln
); 
2693                 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
))); 
2695                 addReply(c
,shared
.crlf
); 
2696                 listDelNode(list
,ln
); 
2703 static void lpopCommand(redisClient 
*c
) { 
2704     popGenericCommand(c
,REDIS_HEAD
); 
2707 static void rpopCommand(redisClient 
*c
) { 
2708     popGenericCommand(c
,REDIS_TAIL
); 
2711 static void lrangeCommand(redisClient 
*c
) { 
2713     int start 
= atoi(c
->argv
[2]->ptr
); 
2714     int end 
= atoi(c
->argv
[3]->ptr
); 
2716     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
2718         addReply(c
,shared
.nullmultibulk
); 
2720         if (o
->type 
!= REDIS_LIST
) { 
2721             addReply(c
,shared
.wrongtypeerr
); 
2723             list 
*list 
= o
->ptr
; 
2725             int llen 
= listLength(list
); 
2729             /* convert negative indexes */ 
2730             if (start 
< 0) start 
= llen
+start
; 
2731             if (end 
< 0) end 
= llen
+end
; 
2732             if (start 
< 0) start 
= 0; 
2733             if (end 
< 0) end 
= 0; 
2735             /* indexes sanity checks */ 
2736             if (start 
> end 
|| start 
>= llen
) { 
2737                 /* Out of range start or start > end result in empty list */ 
2738                 addReply(c
,shared
.emptymultibulk
); 
2741             if (end 
>= llen
) end 
= llen
-1; 
2742             rangelen 
= (end
-start
)+1; 
2744             /* Return the result in form of a multi-bulk reply */ 
2745             ln 
= listIndex(list
, start
); 
2746             addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
)); 
2747             for (j 
= 0; j 
< rangelen
; j
++) { 
2748                 ele 
= listNodeValue(ln
); 
2749                 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
))); 
2751                 addReply(c
,shared
.crlf
); 
2758 static void ltrimCommand(redisClient 
*c
) { 
2760     int start 
= atoi(c
->argv
[2]->ptr
); 
2761     int end 
= atoi(c
->argv
[3]->ptr
); 
2763     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2765         addReply(c
,shared
.nokeyerr
); 
2767         if (o
->type 
!= REDIS_LIST
) { 
2768             addReply(c
,shared
.wrongtypeerr
); 
2770             list 
*list 
= o
->ptr
; 
2772             int llen 
= listLength(list
); 
2773             int j
, ltrim
, rtrim
; 
2775             /* convert negative indexes */ 
2776             if (start 
< 0) start 
= llen
+start
; 
2777             if (end 
< 0) end 
= llen
+end
; 
2778             if (start 
< 0) start 
= 0; 
2779             if (end 
< 0) end 
= 0; 
2781             /* indexes sanity checks */ 
2782             if (start 
> end 
|| start 
>= llen
) { 
2783                 /* Out of range start or start > end result in empty list */ 
2787                 if (end 
>= llen
) end 
= llen
-1; 
2792             /* Remove list elements to perform the trim */ 
2793             for (j 
= 0; j 
< ltrim
; j
++) { 
2794                 ln 
= listFirst(list
); 
2795                 listDelNode(list
,ln
); 
2797             for (j 
= 0; j 
< rtrim
; j
++) { 
2798                 ln 
= listLast(list
); 
2799                 listDelNode(list
,ln
); 
2801             addReply(c
,shared
.ok
); 
2807 static void lremCommand(redisClient 
*c
) { 
2810     o 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2812         addReply(c
,shared
.nokeyerr
); 
2814         if (o
->type 
!= REDIS_LIST
) { 
2815             addReply(c
,shared
.wrongtypeerr
); 
2817             list 
*list 
= o
->ptr
; 
2818             listNode 
*ln
, *next
; 
2819             int toremove 
= atoi(c
->argv
[2]->ptr
); 
2824                 toremove 
= -toremove
; 
2827             ln 
= fromtail 
? list
->tail 
: list
->head
; 
2829                 robj 
*ele 
= listNodeValue(ln
); 
2831                 next 
= fromtail 
? ln
->prev 
: ln
->next
; 
2832                 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) { 
2833                     listDelNode(list
,ln
); 
2836                     if (toremove 
&& removed 
== toremove
) break; 
2840             addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
)); 
2845 /* ==================================== Sets ================================ */ 
2847 static void saddCommand(redisClient 
*c
) { 
2850     set 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2852         set 
= createSetObject(); 
2853         dictAdd(c
->db
->dict
,c
->argv
[1],set
); 
2854         incrRefCount(c
->argv
[1]); 
2856         if (set
->type 
!= REDIS_SET
) { 
2857             addReply(c
,shared
.wrongtypeerr
); 
2861     if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) { 
2862         incrRefCount(c
->argv
[2]); 
2864         addReply(c
,shared
.cone
); 
2866         addReply(c
,shared
.czero
); 
2870 static void sremCommand(redisClient 
*c
) { 
2873     set 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2875         addReply(c
,shared
.czero
); 
2877         if (set
->type 
!= REDIS_SET
) { 
2878             addReply(c
,shared
.wrongtypeerr
); 
2881         if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) { 
2883             addReply(c
,shared
.cone
); 
2885             addReply(c
,shared
.czero
); 
2890 static void smoveCommand(redisClient 
*c
) { 
2891     robj 
*srcset
, *dstset
; 
2893     srcset 
= lookupKeyWrite(c
->db
,c
->argv
[1]); 
2894     dstset 
= lookupKeyWrite(c
->db
,c
->argv
[2]); 
2896     /* If the source key does not exist return 0, if it's of the wrong type 
2898     if (srcset 
== NULL 
|| srcset
->type 
!= REDIS_SET
) { 
2899         addReply(c
, srcset 
? shared
.wrongtypeerr 
: shared
.czero
); 
2902     /* Error if the destination key is not a set as well */ 
2903     if (dstset 
&& dstset
->type 
!= REDIS_SET
) { 
2904         addReply(c
,shared
.wrongtypeerr
); 
2907     /* Remove the element from the source set */ 
2908     if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) { 
2909         /* Key not found in the src set! return zero */ 
2910         addReply(c
,shared
.czero
); 
2914     /* Add the element to the destination set */ 
2916         dstset 
= createSetObject(); 
2917         dictAdd(c
->db
->dict
,c
->argv
[2],dstset
); 
2918         incrRefCount(c
->argv
[2]); 
2920     if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
) 
2921         incrRefCount(c
->argv
[3]); 
2922     addReply(c
,shared
.cone
); 
2925 static void sismemberCommand(redisClient 
*c
) { 
2928     set 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
2930         addReply(c
,shared
.czero
); 
2932         if (set
->type 
!= REDIS_SET
) { 
2933             addReply(c
,shared
.wrongtypeerr
); 
2936         if (dictFind(set
->ptr
,c
->argv
[2])) 
2937             addReply(c
,shared
.cone
); 
2939             addReply(c
,shared
.czero
); 
2943 static void scardCommand(redisClient 
*c
) { 
2947     o 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
2949         addReply(c
,shared
.czero
); 
2952         if (o
->type 
!= REDIS_SET
) { 
2953             addReply(c
,shared
.wrongtypeerr
); 
2956             addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n", 
2962 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) { 
2963     dict 
**d1 
= (void*) s1
, **d2 
= (void*) s2
; 
2965     return dictSize(*d1
)-dictSize(*d2
); 
2968 static void sinterGenericCommand(redisClient 
*c
, robj 
**setskeys
, int setsnum
, robj 
*dstkey
) { 
2969     dict 
**dv 
= zmalloc(sizeof(dict
*)*setsnum
); 
2972     robj 
*lenobj 
= NULL
, *dstset 
= NULL
; 
2973     int j
, cardinality 
= 0; 
2975     if (!dv
) oom("sinterCommand"); 
2976     for (j 
= 0; j 
< setsnum
; j
++) { 
2980                     lookupKeyWrite(c
->db
,setskeys
[j
]) : 
2981                     lookupKeyRead(c
->db
,setskeys
[j
]); 
2985                 deleteKey(c
->db
,dstkey
); 
2986                 addReply(c
,shared
.ok
); 
2988                 addReply(c
,shared
.nullmultibulk
); 
2992         if (setobj
->type 
!= REDIS_SET
) { 
2994             addReply(c
,shared
.wrongtypeerr
); 
2997         dv
[j
] = setobj
->ptr
; 
2999     /* Sort sets from the smallest to largest, this will improve our 
3000      * algorithm's performace */ 
3001     qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
); 
3003     /* The first thing we should output is the total number of elements... 
3004      * since this is a multi-bulk write, but at this stage we don't know 
3005      * the intersection set size, so we use a trick, append an empty object 
3006      * to the output list and save the pointer to later modify it with the 
3009         lenobj 
= createObject(REDIS_STRING
,NULL
); 
3011         decrRefCount(lenobj
); 
3013         /* If we have a target key where to store the resulting set 
3014          * create this key with an empty set inside */ 
3015         dstset 
= createSetObject(); 
3016         deleteKey(c
->db
,dstkey
); 
3017         dictAdd(c
->db
->dict
,dstkey
,dstset
); 
3018         incrRefCount(dstkey
); 
3021     /* Iterate all the elements of the first (smallest) set, and test 
3022      * the element against all the other sets, if at least one set does 
3023      * not include the element it is discarded */ 
3024     di 
= dictGetIterator(dv
[0]); 
3025     if (!di
) oom("dictGetIterator"); 
3027     while((de 
= dictNext(di
)) != NULL
) { 
3030         for (j 
= 1; j 
< setsnum
; j
++) 
3031             if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break; 
3033             continue; /* at least one set does not contain the member */ 
3034         ele 
= dictGetEntryKey(de
); 
3036             addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
))); 
3038             addReply(c
,shared
.crlf
); 
3041             dictAdd(dstset
->ptr
,ele
,NULL
); 
3045     dictReleaseIterator(di
); 
3048         lenobj
->ptr 
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
); 
3050         addReply(c
,shared
.ok
); 
3056 static void sinterCommand(redisClient 
*c
) { 
3057     sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
); 
3060 static void sinterstoreCommand(redisClient 
*c
) { 
3061     sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]); 
3064 #define REDIS_OP_UNION 0 
3065 #define REDIS_OP_DIFF 1 
3067 static void sunionDiffGenericCommand(redisClient 
*c
, robj 
**setskeys
, int setsnum
, robj 
*dstkey
, int op
) { 
3068     dict 
**dv 
= zmalloc(sizeof(dict
*)*setsnum
); 
3071     robj 
*dstset 
= NULL
; 
3072     int j
, cardinality 
= 0; 
3074     if (!dv
) oom("sunionDiffGenericCommand"); 
3075     for (j 
= 0; j 
< setsnum
; j
++) { 
3079                     lookupKeyWrite(c
->db
,setskeys
[j
]) : 
3080                     lookupKeyRead(c
->db
,setskeys
[j
]); 
3085         if (setobj
->type 
!= REDIS_SET
) { 
3087             addReply(c
,shared
.wrongtypeerr
); 
3090         dv
[j
] = setobj
->ptr
; 
3093     /* We need a temp set object to store our union. If the dstkey 
3094      * is not NULL (that is, we are inside an SUNIONSTORE operation) then 
3095      * this set object will be the resulting object to set into the target key*/ 
3096     dstset 
= createSetObject(); 
3098     /* The first thing we should output is the total number of elements... 
3099      * since this is a multi-bulk write, but at this stage we don't know 
3100      * the intersection set size, so we use a trick, append an empty object 
3101      * to the output list and save the pointer to later modify it with the 
3104         /* If we have a target key where to store the resulting set 
3105          * create this key with an empty set inside */ 
3106         deleteKey(c
->db
,dstkey
); 
3107         dictAdd(c
->db
->dict
,dstkey
,dstset
); 
3108         incrRefCount(dstkey
); 
3112     /* Iterate all the elements of all the sets, add every element a single 
3113      * time to the result set */ 
3114     for (j 
= 0; j 
< setsnum
; j
++) { 
3115         if (op 
== REDIS_OP_DIFF 
&& j 
== 0 && !dv
[j
]) break; /* result set is empty */ 
3116         if (!dv
[j
]) continue; /* non existing keys are like empty sets */ 
3118         di 
= dictGetIterator(dv
[j
]); 
3119         if (!di
) oom("dictGetIterator"); 
3121         while((de 
= dictNext(di
)) != NULL
) { 
3124             /* dictAdd will not add the same element multiple times */ 
3125             ele 
= dictGetEntryKey(de
); 
3126             if (op 
== REDIS_OP_UNION 
|| j 
== 0) { 
3127                 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) { 
3131             } else if (op 
== REDIS_OP_DIFF
) { 
3132                 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) { 
3137         dictReleaseIterator(di
); 
3139         if (op 
== REDIS_OP_DIFF 
&& cardinality 
== 0) break; /* result set is empty */ 
3142     /* Output the content of the resulting set, if not in STORE mode */ 
3144         addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
)); 
3145         di 
= dictGetIterator(dstset
->ptr
); 
3146         if (!di
) oom("dictGetIterator"); 
3147         while((de 
= dictNext(di
)) != NULL
) { 
3150             ele 
= dictGetEntryKey(de
); 
3151             addReplySds(c
,sdscatprintf(sdsempty(), 
3152                     "$%d\r\n",sdslen(ele
->ptr
))); 
3154             addReply(c
,shared
.crlf
); 
3156         dictReleaseIterator(di
); 
3161         decrRefCount(dstset
); 
3163         addReply(c
,shared
.ok
); 
3169 static void sunionCommand(redisClient 
*c
) { 
3170     sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
); 
3173 static void sunionstoreCommand(redisClient 
*c
) { 
3174     sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
); 
3177 static void sdiffCommand(redisClient 
*c
) { 
3178     sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
); 
3181 static void sdiffstoreCommand(redisClient 
*c
) { 
3182     sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
); 
3185 static void flushdbCommand(redisClient 
*c
) { 
3186     server
.dirty 
+= dictSize(c
->db
->dict
); 
3187     dictEmpty(c
->db
->dict
); 
3188     dictEmpty(c
->db
->expires
); 
3189     addReply(c
,shared
.ok
); 
3192 static void flushallCommand(redisClient 
*c
) { 
3193     server
.dirty 
+= emptyDb(); 
3194     addReply(c
,shared
.ok
); 
3195     rdbSave(server
.dbfilename
); 
3199 redisSortOperation 
*createSortOperation(int type
, robj 
*pattern
) { 
3200     redisSortOperation 
*so 
= zmalloc(sizeof(*so
)); 
3201     if (!so
) oom("createSortOperation"); 
3203     so
->pattern 
= pattern
; 
3207 /* Return the value associated to the key with a name obtained 
3208  * substituting the first occurence of '*' in 'pattern' with 'subst' */ 
3209 robj 
*lookupKeyByPattern(redisDb 
*db
, robj 
*pattern
, robj 
*subst
) { 
3213     int prefixlen
, sublen
, postfixlen
; 
3214     /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */ 
3218         char buf
[REDIS_SORTKEY_MAX
+1]; 
3221     spat 
= pattern
->ptr
; 
3223     if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
; 
3224     p 
= strchr(spat
,'*'); 
3225     if (!p
) return NULL
; 
3228     sublen 
= sdslen(ssub
); 
3229     postfixlen 
= sdslen(spat
)-(prefixlen
+1); 
3230     memcpy(keyname
.buf
,spat
,prefixlen
); 
3231     memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
); 
3232     memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
); 
3233     keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0'; 
3234     keyname
.len 
= prefixlen
+sublen
+postfixlen
; 
3236     keyobj
.refcount 
= 1; 
3237     keyobj
.type 
= REDIS_STRING
; 
3238     keyobj
.ptr 
= ((char*)&keyname
)+(sizeof(long)*2); 
3240     /* printf("lookup '%s' => %p\n", keyname.buf,de); */ 
3241     return lookupKeyRead(db
,&keyobj
); 
3244 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with 
3245  * the additional parameter is not standard but a BSD-specific we have to 
3246  * pass sorting parameters via the global 'server' structure */ 
3247 static int sortCompare(const void *s1
, const void *s2
) { 
3248     const redisSortObject 
*so1 
= s1
, *so2 
= s2
; 
3251     if (!server
.sort_alpha
) { 
3252         /* Numeric sorting. Here it's trivial as we precomputed scores */ 
3253         if (so1
->u
.score 
> so2
->u
.score
) { 
3255         } else if (so1
->u
.score 
< so2
->u
.score
) { 
3261         /* Alphanumeric sorting */ 
3262         if (server
.sort_bypattern
) { 
3263             if (!so1
->u
.cmpobj 
|| !so2
->u
.cmpobj
) { 
3264                 /* At least one compare object is NULL */ 
3265                 if (so1
->u
.cmpobj 
== so2
->u
.cmpobj
) 
3267                 else if (so1
->u
.cmpobj 
== NULL
) 
3272                 /* We have both the objects, use strcoll */ 
3273                 cmp 
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
); 
3276             /* Compare elements directly */ 
3277             cmp 
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
); 
3280     return server
.sort_desc 
? -cmp 
: cmp
; 
3283 /* The SORT command is the most complex command in Redis. Warning: this code 
3284  * is optimized for speed and a bit less for readability */ 
3285 static void sortCommand(redisClient 
*c
) { 
3288     int desc 
= 0, alpha 
= 0; 
3289     int limit_start 
= 0, limit_count 
= -1, start
, end
; 
3290     int j
, dontsort 
= 0, vectorlen
; 
3291     int getop 
= 0; /* GET operation counter */ 
3292     robj 
*sortval
, *sortby 
= NULL
; 
3293     redisSortObject 
*vector
; /* Resulting vector to sort */ 
3295     /* Lookup the key to sort. It must be of the right types */ 
3296     sortval 
= lookupKeyRead(c
->db
,c
->argv
[1]); 
3297     if (sortval 
== NULL
) { 
3298         addReply(c
,shared
.nokeyerr
); 
3301     if (sortval
->type 
!= REDIS_SET 
&& sortval
->type 
!= REDIS_LIST
) { 
3302         addReply(c
,shared
.wrongtypeerr
); 
3306     /* Create a list of operations to perform for every sorted element. 
3307      * Operations can be GET/DEL/INCR/DECR */ 
3308     operations 
= listCreate(); 
3309     listSetFreeMethod(operations
,zfree
); 
3312     /* Now we need to protect sortval incrementing its count, in the future 
3313      * SORT may have options able to overwrite/delete keys during the sorting 
3314      * and the sorted key itself may get destroied */ 
3315     incrRefCount(sortval
); 
3317     /* The SORT command has an SQL-alike syntax, parse it */ 
3318     while(j 
< c
->argc
) { 
3319         int leftargs 
= c
->argc
-j
-1; 
3320         if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) { 
3322         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) { 
3324         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) { 
3326         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs 
>= 2) { 
3327             limit_start 
= atoi(c
->argv
[j
+1]->ptr
); 
3328             limit_count 
= atoi(c
->argv
[j
+2]->ptr
); 
3330         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs 
>= 1) { 
3331             sortby 
= c
->argv
[j
+1]; 
3332             /* If the BY pattern does not contain '*', i.e. it is constant, 
3333              * we don't need to sort nor to lookup the weight keys. */ 
3334             if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort 
= 1; 
3336         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs 
>= 1) { 
3337             listAddNodeTail(operations
,createSortOperation( 
3338                 REDIS_SORT_GET
,c
->argv
[j
+1])); 
3341         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs 
>= 1) { 
3342             listAddNodeTail(operations
,createSortOperation( 
3343                 REDIS_SORT_DEL
,c
->argv
[j
+1])); 
3345         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs 
>= 1) { 
3346             listAddNodeTail(operations
,createSortOperation( 
3347                 REDIS_SORT_INCR
,c
->argv
[j
+1])); 
3349         } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs 
>= 1) { 
3350             listAddNodeTail(operations
,createSortOperation( 
3351                 REDIS_SORT_DECR
,c
->argv
[j
+1])); 
3354             decrRefCount(sortval
); 
3355             listRelease(operations
); 
3356             addReply(c
,shared
.syntaxerr
); 
3362     /* Load the sorting vector with all the objects to sort */ 
3363     vectorlen 
= (sortval
->type 
== REDIS_LIST
) ? 
3364         listLength((list
*)sortval
->ptr
) : 
3365         dictSize((dict
*)sortval
->ptr
); 
3366     vector 
= zmalloc(sizeof(redisSortObject
)*vectorlen
); 
3367     if (!vector
) oom("allocating objects vector for SORT"); 
3369     if (sortval
->type 
== REDIS_LIST
) { 
3370         list 
*list 
= sortval
->ptr
; 
3374         while((ln 
= listYield(list
))) { 
3375             robj 
*ele 
= ln
->value
; 
3376             vector
[j
].obj 
= ele
; 
3377             vector
[j
].u
.score 
= 0; 
3378             vector
[j
].u
.cmpobj 
= NULL
; 
3382         dict 
*set 
= sortval
->ptr
; 
3386         di 
= dictGetIterator(set
); 
3387         if (!di
) oom("dictGetIterator"); 
3388         while((setele 
= dictNext(di
)) != NULL
) { 
3389             vector
[j
].obj 
= dictGetEntryKey(setele
); 
3390             vector
[j
].u
.score 
= 0; 
3391             vector
[j
].u
.cmpobj 
= NULL
; 
3394         dictReleaseIterator(di
); 
3396     assert(j 
== vectorlen
); 
3398     /* Now it's time to load the right scores in the sorting vector */ 
3399     if (dontsort 
== 0) { 
3400         for (j 
= 0; j 
< vectorlen
; j
++) { 
3404                 byval 
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
); 
3405                 if (!byval 
|| byval
->type 
!= REDIS_STRING
) continue; 
3407                     vector
[j
].u
.cmpobj 
= byval
; 
3408                     incrRefCount(byval
); 
3410                     vector
[j
].u
.score 
= strtod(byval
->ptr
,NULL
); 
3413                 if (!alpha
) vector
[j
].u
.score 
= strtod(vector
[j
].obj
->ptr
,NULL
); 
3418     /* We are ready to sort the vector... perform a bit of sanity check 
3419      * on the LIMIT option too. We'll use a partial version of quicksort. */ 
3420     start 
= (limit_start 
< 0) ? 0 : limit_start
; 
3421     end 
= (limit_count 
< 0) ? vectorlen
-1 : start
+limit_count
-1; 
3422     if (start 
>= vectorlen
) { 
3423         start 
= vectorlen
-1; 
3426     if (end 
>= vectorlen
) end 
= vectorlen
-1; 
3428     if (dontsort 
== 0) { 
3429         server
.sort_desc 
= desc
; 
3430         server
.sort_alpha 
= alpha
; 
3431         server
.sort_bypattern 
= sortby 
? 1 : 0; 
3432         qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
); 
3435     /* Send command output to the output buffer, performing the specified 
3436      * GET/DEL/INCR/DECR operations if any. */ 
3437     outputlen 
= getop 
? getop
*(end
-start
+1) : end
-start
+1; 
3438     addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
)); 
3439     for (j 
= start
; j 
<= end
; j
++) { 
3442             addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n", 
3443                 sdslen(vector
[j
].obj
->ptr
))); 
3444             addReply(c
,vector
[j
].obj
); 
3445             addReply(c
,shared
.crlf
); 
3447         listRewind(operations
); 
3448         while((ln 
= listYield(operations
))) { 
3449             redisSortOperation 
*sop 
= ln
->value
; 
3450             robj 
*val 
= lookupKeyByPattern(c
->db
,sop
->pattern
, 
3453             if (sop
->type 
== REDIS_SORT_GET
) { 
3454                 if (!val 
|| val
->type 
!= REDIS_STRING
) { 
3455                     addReply(c
,shared
.nullbulk
); 
3457                     addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n", 
3460                     addReply(c
,shared
.crlf
); 
3462             } else if (sop
->type 
== REDIS_SORT_DEL
) { 
3469     decrRefCount(sortval
); 
3470     listRelease(operations
); 
3471     for (j 
= 0; j 
< vectorlen
; j
++) { 
3472         if (sortby 
&& alpha 
&& vector
[j
].u
.cmpobj
) 
3473             decrRefCount(vector
[j
].u
.cmpobj
); 
3478 static void infoCommand(redisClient 
*c
) { 
3480     time_t uptime 
= time(NULL
)-server
.stat_starttime
; 
3482     info 
= sdscatprintf(sdsempty(), 
3483         "redis_version:%s\r\n" 
3484         "connected_clients:%d\r\n" 
3485         "connected_slaves:%d\r\n" 
3486         "used_memory:%zu\r\n" 
3487         "changes_since_last_save:%lld\r\n" 
3488         "bgsave_in_progress:%d\r\n" 
3489         "last_save_time:%d\r\n" 
3490         "total_connections_received:%lld\r\n" 
3491         "total_commands_processed:%lld\r\n" 
3492         "uptime_in_seconds:%d\r\n" 
3493         "uptime_in_days:%d\r\n" 
3495         listLength(server
.clients
)-listLength(server
.slaves
), 
3496         listLength(server
.slaves
), 
3499         server
.bgsaveinprogress
, 
3501         server
.stat_numconnections
, 
3502         server
.stat_numcommands
, 
3506     addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
))); 
3507     addReplySds(c
,info
); 
3508     addReply(c
,shared
.crlf
); 
3511 static void monitorCommand(redisClient 
*c
) { 
3512     /* ignore MONITOR if aleady slave or in monitor mode */ 
3513     if (c
->flags 
& REDIS_SLAVE
) return; 
3515     c
->flags 
|= (REDIS_SLAVE
|REDIS_MONITOR
); 
3517     if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail"); 
3518     addReply(c
,shared
.ok
); 
3521 /* ================================= Expire ================================= */ 
3522 static int removeExpire(redisDb 
*db
, robj 
*key
) { 
3523     if (dictDelete(db
->expires
,key
) == DICT_OK
) { 
3530 static int setExpire(redisDb 
*db
, robj 
*key
, time_t when
) { 
3531     if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) { 
3539 /* Return the expire time of the specified key, or -1 if no expire 
3540  * is associated with this key (i.e. the key is non volatile) */ 
3541 static time_t getExpire(redisDb 
*db
, robj 
*key
) { 
3544     /* No expire? return ASAP */ 
3545     if (dictSize(db
->expires
) == 0 || 
3546        (de 
= dictFind(db
->expires
,key
)) == NULL
) return -1; 
3548     return (time_t) dictGetEntryVal(de
); 
3551 static int expireIfNeeded(redisDb 
*db
, robj 
*key
) { 
3555     /* No expire? return ASAP */ 
3556     if (dictSize(db
->expires
) == 0 || 
3557        (de 
= dictFind(db
->expires
,key
)) == NULL
) return 0; 
3559     /* Lookup the expire */ 
3560     when 
= (time_t) dictGetEntryVal(de
); 
3561     if (time(NULL
) <= when
) return 0; 
3563     /* Delete the key */ 
3564     dictDelete(db
->expires
,key
); 
3565     return dictDelete(db
->dict
,key
) == DICT_OK
; 
3568 static int deleteIfVolatile(redisDb 
*db
, robj 
*key
) { 
3571     /* No expire? return ASAP */ 
3572     if (dictSize(db
->expires
) == 0 || 
3573        (de 
= dictFind(db
->expires
,key
)) == NULL
) return 0; 
3575     /* Delete the key */ 
3577     dictDelete(db
->expires
,key
); 
3578     return dictDelete(db
->dict
,key
) == DICT_OK
; 
3581 static void expireCommand(redisClient 
*c
) { 
3583     int seconds 
= atoi(c
->argv
[2]->ptr
); 
3585     de 
= dictFind(c
->db
->dict
,c
->argv
[1]); 
3587         addReply(c
,shared
.czero
); 
3591         addReply(c
, shared
.czero
); 
3594         time_t when 
= time(NULL
)+seconds
; 
3595         if (setExpire(c
->db
,c
->argv
[1],when
)) 
3596             addReply(c
,shared
.cone
); 
3598             addReply(c
,shared
.czero
); 
3603 /* =============================== Replication  ============================= */ 
3605 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) { 
3606     ssize_t nwritten
, ret 
= size
; 
3607     time_t start 
= time(NULL
); 
3611         if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) { 
3612             nwritten 
= write(fd
,ptr
,size
); 
3613             if (nwritten 
== -1) return -1; 
3617         if ((time(NULL
)-start
) > timeout
) { 
3625 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) { 
3626     ssize_t nread
, totread 
= 0; 
3627     time_t start 
= time(NULL
); 
3631         if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) { 
3632             nread 
= read(fd
,ptr
,size
); 
3633             if (nread 
== -1) return -1; 
3638         if ((time(NULL
)-start
) > timeout
) { 
3646 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) { 
3653         if (syncRead(fd
,&c
,1,timeout
) == -1) return -1; 
3656             if (nread 
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0'; 
3667 static void syncCommand(redisClient 
*c
) { 
3668     /* ignore SYNC if aleady slave or in monitor mode */ 
3669     if (c
->flags 
& REDIS_SLAVE
) return; 
3671     /* SYNC can't be issued when the server has pending data to send to 
3672      * the client about already issued commands. We need a fresh reply 
3673      * buffer registering the differences between the BGSAVE and the current 
3674      * dataset, so that we can copy to other slaves if needed. */ 
3675     if (listLength(c
->reply
) != 0) { 
3676         addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n")); 
3680     redisLog(REDIS_NOTICE
,"Slave ask for synchronization"); 
3681     /* Here we need to check if there is a background saving operation 
3682      * in progress, or if it is required to start one */ 
3683     if (server
.bgsaveinprogress
) { 
3684         /* Ok a background save is in progress. Let's check if it is a good 
3685          * one for replication, i.e. if there is another slave that is 
3686          * registering differences since the server forked to save */ 
3690         listRewind(server
.slaves
); 
3691         while((ln 
= listYield(server
.slaves
))) { 
3693             if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_END
) break; 
3696             /* Perfect, the server is already registering differences for 
3697              * another slave. Set the right state, and copy the buffer. */ 
3698             listRelease(c
->reply
); 
3699             c
->reply 
= listDup(slave
->reply
); 
3700             if (!c
->reply
) oom("listDup copying slave reply list"); 
3701             c
->replstate 
= REDIS_REPL_WAIT_BGSAVE_END
; 
3702             redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC"); 
3704             /* No way, we need to wait for the next BGSAVE in order to 
3705              * register differences */ 
3706             c
->replstate 
= REDIS_REPL_WAIT_BGSAVE_START
; 
3707             redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC"); 
3710         /* Ok we don't have a BGSAVE in progress, let's start one */ 
3711         redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC"); 
3712         if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) { 
3713             redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE"); 
3714             addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n")); 
3717         c
->replstate 
= REDIS_REPL_WAIT_BGSAVE_END
; 
3720     c
->flags 
|= REDIS_SLAVE
; 
3722     if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail"); 
3726 static void sendBulkToSlave(aeEventLoop 
*el
, int fd
, void *privdata
, int mask
) { 
3727     redisClient 
*slave 
= privdata
; 
3729     REDIS_NOTUSED(mask
); 
3730     char buf
[REDIS_IOBUF_LEN
]; 
3731     ssize_t nwritten
, buflen
; 
3733     if (slave
->repldboff 
== 0) { 
3734         /* Write the bulk write count before to transfer the DB. In theory here 
3735          * we don't know how much room there is in the output buffer of the 
3736          * socket, but in pratice SO_SNDLOWAT (the minimum count for output 
3737          * operations) will never be smaller than the few bytes we need. */ 
3740         bulkcount 
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long) 
3742         if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
)) 
3750     lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
); 
3751     buflen 
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
); 
3753         redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s", 
3754             (buflen 
== 0) ? "premature EOF" : strerror(errno
)); 
3758     if ((nwritten 
= write(fd
,buf
,buflen
)) == -1) { 
3759         redisLog(REDIS_DEBUG
,"Write error sending DB to slave: %s", 
3764     slave
->repldboff 
+= nwritten
; 
3765     if (slave
->repldboff 
== slave
->repldbsize
) { 
3766         close(slave
->repldbfd
); 
3767         slave
->repldbfd 
= -1; 
3768         aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
); 
3769         slave
->replstate 
= REDIS_REPL_ONLINE
; 
3770         if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, 
3771             sendReplyToClient
, slave
, NULL
) == AE_ERR
) { 
3775         addReplySds(slave
,sdsempty()); 
3776         redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded"); 
3780 static void updateSalvesWaitingBgsave(int bgsaveerr
) { 
3782     int startbgsave 
= 0; 
3784     listRewind(server
.slaves
); 
3785     while((ln 
= listYield(server
.slaves
))) { 
3786         redisClient 
*slave 
= ln
->value
; 
3788         if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_START
) { 
3790             slave
->replstate 
= REDIS_REPL_WAIT_BGSAVE_END
; 
3791         } else if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_END
) { 
3794             if (bgsaveerr 
!= REDIS_OK
) { 
3796                 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error"); 
3799             if ((slave
->repldbfd 
= open(server
.dbfilename
,O_RDONLY
)) == -1 || 
3800                 fstat(slave
->repldbfd
,&buf
) == -1) { 
3802                 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
)); 
3805             slave
->repldboff 
= 0; 
3806             slave
->repldbsize 
= buf
.st_size
; 
3807             slave
->replstate 
= REDIS_REPL_SEND_BULK
; 
3808             aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
); 
3809             if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
, NULL
) == AE_ERR
) { 
3816         if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) { 
3817             listRewind(server
.slaves
); 
3818             redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed"); 
3819             while((ln 
= listYield(server
.slaves
))) { 
3820                 redisClient 
*slave 
= ln
->value
; 
3822                 if (slave
->replstate 
== REDIS_REPL_WAIT_BGSAVE_START
) 
3829 static int syncWithMaster(void) { 
3830     char buf
[1024], tmpfile
[256]; 
3832     int fd 
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
); 
3836         redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s", 
3840     /* Issue the SYNC command */ 
3841     if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) { 
3843         redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s", 
3847     /* Read the bulk write count */ 
3848     if (syncReadLine(fd
,buf
,1024,5) == -1) { 
3850         redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s", 
3854     dumpsize 
= atoi(buf
+1); 
3855     redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
); 
3856     /* Read the bulk write data on a temp file */ 
3857     snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random()); 
3858     dfd 
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644); 
3861         redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
)); 
3865         int nread
, nwritten
; 
3867         nread 
= read(fd
,buf
,(dumpsize 
< 1024)?dumpsize
:1024); 
3869             redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s", 
3875         nwritten 
= write(dfd
,buf
,nread
); 
3876         if (nwritten 
== -1) { 
3877             redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
)); 
3885     if (rename(tmpfile
,server
.dbfilename
) == -1) { 
3886         redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
)); 
3892     if (rdbLoad(server
.dbfilename
) != REDIS_OK
) { 
3893         redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk"); 
3897     server
.master 
= createClient(fd
); 
3898     server
.master
->flags 
|= REDIS_MASTER
; 
3899     server
.replstate 
= REDIS_REPL_CONNECTED
; 
3903 /* =================================== Main! ================================ */ 
3906 int linuxOvercommitMemoryValue(void) { 
3907     FILE *fp 
= fopen("/proc/sys/vm/overcommit_memory","r"); 
3911     if (fgets(buf
,64,fp
) == NULL
) { 
3920 void linuxOvercommitMemoryWarning(void) { 
3921     if (linuxOvercommitMemoryValue() == 0) { 
3922         redisLog(REDIS_WARNING
,"WARNING overcommit_memory is set to 0! Background save may fail under low condition memory. To fix this issue add 'echo 1 > /proc/sys/vm/overcommit_memory' in your init scripts."); 
3925 #endif /* __linux__ */ 
3927 static void daemonize(void) { 
3931     if (fork() != 0) exit(0); /* parent exits */ 
3932     setsid(); /* create a new session */ 
3934     /* Every output goes to /dev/null. If Redis is daemonized but 
3935      * the 'logfile' is set to 'stdout' in the configuration file 
3936      * it will not log at all. */ 
3937     if ((fd 
= open("/dev/null", O_RDWR
, 0)) != -1) { 
3938         dup2(fd
, STDIN_FILENO
); 
3939         dup2(fd
, STDOUT_FILENO
); 
3940         dup2(fd
, STDERR_FILENO
); 
3941         if (fd 
> STDERR_FILENO
) close(fd
); 
3943     /* Try to write the pid file */ 
3944     fp 
= fopen(server
.pidfile
,"w"); 
3946         fprintf(fp
,"%d\n",getpid()); 
3951 int main(int argc
, char **argv
) { 
3953     linuxOvercommitMemoryWarning(); 
3958         ResetServerSaveParams(); 
3959         loadServerConfig(argv
[1]); 
3960     } else if (argc 
> 2) { 
3961         fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n"); 
3965     if (server
.daemonize
) daemonize(); 
3966     redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
); 
3967     if (rdbLoad(server
.dbfilename
) == REDIS_OK
) 
3968         redisLog(REDIS_NOTICE
,"DB loaded from disk"); 
3969     if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
, 
3970         acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event"); 
3971     redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
); 
3973     aeDeleteEventLoop(server
.el
);