]> git.saurik.com Git - redis.git/blame - redis.c
replication slave timeout when receiving the initial bulk data set to 3600 seconds...
[redis.git] / redis.c
CommitLineData
ed9b544e 1/*
2 * Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
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.
16 *
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.
28 */
29
dec423d9 30#define REDIS_VERSION "0.100"
23d4709d 31
32#include "fmacros.h"
ed9b544e 33
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <time.h>
38#include <unistd.h>
39#include <signal.h>
40#include <sys/wait.h>
41#include <errno.h>
42#include <assert.h>
43#include <ctype.h>
44#include <stdarg.h>
45#include <inttypes.h>
46#include <arpa/inet.h>
47#include <sys/stat.h>
48#include <fcntl.h>
49#include <sys/time.h>
50#include <sys/resource.h>
f78fd11b 51#include <limits.h>
ed9b544e 52
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 */
5f5b9840 59#include "lzf.h" /* LZF compression library */
60#include "pqsort.h" /* Partial qsort for SORT+LIMIT */
ed9b544e 61
62/* Error codes */
63#define REDIS_OK 0
64#define REDIS_ERR -1
65
66/* Static server configuration */
67#define REDIS_SERVERPORT 6379 /* TCP port */
68#define REDIS_MAXIDLETIME (60*5) /* default client timeout */
6208b3a7 69#define REDIS_IOBUF_LEN 1024
ed9b544e 70#define REDIS_LOADBUF_LEN 1024
93ea3759 71#define REDIS_STATIC_ARGS 4
ed9b544e 72#define REDIS_DEFAULT_DBNUM 16
73#define REDIS_CONFIGLINE_MAX 1024
74#define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
75#define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
94754ccc 76#define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
ed9b544e 77
78/* Hash table parameters */
79#define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
80#define REDIS_HT_MINSLOTS 16384 /* Never resize the HT under this */
81
82/* Command flags */
83#define REDIS_CMD_BULK 1
84#define REDIS_CMD_INLINE 2
85
86/* Object types */
87#define REDIS_STRING 0
88#define REDIS_LIST 1
89#define REDIS_SET 2
90#define REDIS_HASH 3
f78fd11b 91
92/* Object types only used for dumping to disk */
bb32ede5 93#define REDIS_EXPIRETIME 253
ed9b544e 94#define REDIS_SELECTDB 254
95#define REDIS_EOF 255
96
f78fd11b 97/* Defines related to the dump file format. To store 32 bits lengths for short
98 * keys requires a lot of space, so we check the most significant 2 bits of
99 * the first byte to interpreter the length:
100 *
101 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
102 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
103 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
a4d1ba9a 104 * 11|000000 this means: specially encoded object will follow. The six bits
105 * number specify the kind of object that follows.
106 * See the REDIS_RDB_ENC_* defines.
f78fd11b 107 *
10c43610 108 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
109 * values, will fit inside. */
f78fd11b 110#define REDIS_RDB_6BITLEN 0
111#define REDIS_RDB_14BITLEN 1
112#define REDIS_RDB_32BITLEN 2
17be1a4a 113#define REDIS_RDB_ENCVAL 3
f78fd11b 114#define REDIS_RDB_LENERR UINT_MAX
115
a4d1ba9a 116/* When a length of a string object stored on disk has the first two bits
117 * set, the remaining two bits specify a special encoding for the object
118 * accordingly to the following defines: */
119#define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
120#define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
121#define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
774e3047 122#define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
a4d1ba9a 123
ed9b544e 124/* Client flags */
125#define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
126#define REDIS_SLAVE 2 /* This client is a slave server */
127#define REDIS_MASTER 4 /* This client is a master server */
87eca727 128#define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
ed9b544e 129
40d224a9 130/* Slave replication state - slave side */
ed9b544e 131#define REDIS_REPL_NONE 0 /* No active replication */
132#define REDIS_REPL_CONNECT 1 /* Must connect to master */
133#define REDIS_REPL_CONNECTED 2 /* Connected to master */
134
40d224a9 135/* Slave replication state - from the point of view of master
136 * Note that in SEND_BULK and ONLINE state the slave receives new updates
137 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
138 * to start the next background saving in order to send updates to it. */
139#define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
140#define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
141#define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
142#define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
143
ed9b544e 144/* List related stuff */
145#define REDIS_HEAD 0
146#define REDIS_TAIL 1
147
148/* Sort operations */
149#define REDIS_SORT_GET 0
150#define REDIS_SORT_DEL 1
151#define REDIS_SORT_INCR 2
152#define REDIS_SORT_DECR 3
153#define REDIS_SORT_ASC 4
154#define REDIS_SORT_DESC 5
155#define REDIS_SORTKEY_MAX 1024
156
157/* Log levels */
158#define REDIS_DEBUG 0
159#define REDIS_NOTICE 1
160#define REDIS_WARNING 2
161
162/* Anti-warning macro... */
163#define REDIS_NOTUSED(V) ((void) V)
164
165/*================================= Data types ============================== */
166
167/* A redis object, that is a type able to hold a string / list / set */
168typedef struct redisObject {
ed9b544e 169 void *ptr;
5a6e8b1d 170 int type;
ed9b544e 171 int refcount;
172} robj;
173
3305306f 174typedef struct redisDb {
175 dict *dict;
176 dict *expires;
177 int id;
178} redisDb;
179
ed9b544e 180/* With multiplexing we need to take per-clinet state.
181 * Clients are taken in a liked list. */
182typedef struct redisClient {
183 int fd;
3305306f 184 redisDb *db;
ed9b544e 185 int dictid;
186 sds querybuf;
93ea3759 187 robj **argv;
ed9b544e 188 int argc;
40d224a9 189 int bulklen; /* bulk read len. -1 if not in bulk read mode */
ed9b544e 190 list *reply;
191 int sentlen;
192 time_t lastinteraction; /* time of the last interaction, used for timeout */
40d224a9 193 int flags; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
194 int slaveseldb; /* slave selected db, if this client is a slave */
195 int authenticated; /* when requirepass is non-NULL */
196 int replstate; /* replication state if this is a slave */
197 int repldbfd; /* replication DB file descriptor */
6208b3a7 198 long repldboff; /* replication DB file offset */
40d224a9 199 off_t repldbsize; /* replication DB file size */
ed9b544e 200} redisClient;
201
202struct saveparam {
203 time_t seconds;
204 int changes;
205};
206
207/* Global server state structure */
208struct redisServer {
209 int port;
210 int fd;
3305306f 211 redisDb *db;
10c43610 212 dict *sharingpool;
213 unsigned int sharingpoolsize;
ed9b544e 214 long long dirty; /* changes to DB from the last save */
215 list *clients;
87eca727 216 list *slaves, *monitors;
ed9b544e 217 char neterr[ANET_ERR_LEN];
218 aeEventLoop *el;
219 int cronloops; /* number of times the cron function run */
220 list *objfreelist; /* A list of freed objects to avoid malloc() */
221 time_t lastsave; /* Unix time of last save succeeede */
5fba9f71 222 size_t usedmemory; /* Used memory in megabytes */
ed9b544e 223 /* Fields used only for stats */
224 time_t stat_starttime; /* server start time */
225 long long stat_numcommands; /* number of processed commands */
226 long long stat_numconnections; /* number of connections received */
227 /* Configuration */
228 int verbosity;
229 int glueoutputbuf;
230 int maxidletime;
231 int dbnum;
232 int daemonize;
ed329fcf 233 char *pidfile;
ed9b544e 234 int bgsaveinprogress;
235 struct saveparam *saveparams;
236 int saveparamslen;
237 char *logfile;
238 char *bindaddr;
239 char *dbfilename;
abcb223e 240 char *requirepass;
10c43610 241 int shareobjects;
ed9b544e 242 /* Replication related */
243 int isslave;
244 char *masterhost;
245 int masterport;
40d224a9 246 redisClient *master; /* client that is master for this slave */
ed9b544e 247 int replstate;
248 /* Sort parameters - qsort_r() is only available under BSD so we
249 * have to take this state global, in order to pass it to sortCompare() */
250 int sort_desc;
251 int sort_alpha;
252 int sort_bypattern;
253};
254
255typedef void redisCommandProc(redisClient *c);
256struct redisCommand {
257 char *name;
258 redisCommandProc *proc;
259 int arity;
260 int flags;
261};
262
263typedef struct _redisSortObject {
264 robj *obj;
265 union {
266 double score;
267 robj *cmpobj;
268 } u;
269} redisSortObject;
270
271typedef struct _redisSortOperation {
272 int type;
273 robj *pattern;
274} redisSortOperation;
275
276struct sharedObjectsStruct {
c937aa89 277 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
7b45bfb2 278 *colon, *nullbulk, *nullmultibulk,
c937aa89 279 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
280 *outofrangeerr, *plus,
ed9b544e 281 *select0, *select1, *select2, *select3, *select4,
282 *select5, *select6, *select7, *select8, *select9;
283} shared;
284
285/*================================ Prototypes =============================== */
286
287static void freeStringObject(robj *o);
288static void freeListObject(robj *o);
289static void freeSetObject(robj *o);
290static void decrRefCount(void *o);
291static robj *createObject(int type, void *ptr);
292static void freeClient(redisClient *c);
f78fd11b 293static int rdbLoad(char *filename);
ed9b544e 294static void addReply(redisClient *c, robj *obj);
295static void addReplySds(redisClient *c, sds s);
296static void incrRefCount(robj *o);
f78fd11b 297static int rdbSaveBackground(char *filename);
ed9b544e 298static robj *createStringObject(char *ptr, size_t len);
87eca727 299static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc);
ed9b544e 300static int syncWithMaster(void);
10c43610 301static robj *tryObjectSharing(robj *o);
3305306f 302static int removeExpire(redisDb *db, robj *key);
303static int expireIfNeeded(redisDb *db, robj *key);
304static int deleteIfVolatile(redisDb *db, robj *key);
94754ccc 305static int deleteKey(redisDb *db, robj *key);
bb32ede5 306static time_t getExpire(redisDb *db, robj *key);
307static int setExpire(redisDb *db, robj *key, time_t when);
6208b3a7 308static void updateSalvesWaitingBgsave(int bgsaveerr);
ed9b544e 309
abcb223e 310static void authCommand(redisClient *c);
ed9b544e 311static void pingCommand(redisClient *c);
312static void echoCommand(redisClient *c);
313static void setCommand(redisClient *c);
314static void setnxCommand(redisClient *c);
315static void getCommand(redisClient *c);
316static void delCommand(redisClient *c);
317static void existsCommand(redisClient *c);
318static void incrCommand(redisClient *c);
319static void decrCommand(redisClient *c);
320static void incrbyCommand(redisClient *c);
321static void decrbyCommand(redisClient *c);
322static void selectCommand(redisClient *c);
323static void randomkeyCommand(redisClient *c);
324static void keysCommand(redisClient *c);
325static void dbsizeCommand(redisClient *c);
326static void lastsaveCommand(redisClient *c);
327static void saveCommand(redisClient *c);
328static void bgsaveCommand(redisClient *c);
329static void shutdownCommand(redisClient *c);
330static void moveCommand(redisClient *c);
331static void renameCommand(redisClient *c);
332static void renamenxCommand(redisClient *c);
333static void lpushCommand(redisClient *c);
334static void rpushCommand(redisClient *c);
335static void lpopCommand(redisClient *c);
336static void rpopCommand(redisClient *c);
337static void llenCommand(redisClient *c);
338static void lindexCommand(redisClient *c);
339static void lrangeCommand(redisClient *c);
340static void ltrimCommand(redisClient *c);
341static void typeCommand(redisClient *c);
342static void lsetCommand(redisClient *c);
343static void saddCommand(redisClient *c);
344static void sremCommand(redisClient *c);
a4460ef4 345static void smoveCommand(redisClient *c);
ed9b544e 346static void sismemberCommand(redisClient *c);
347static void scardCommand(redisClient *c);
348static void sinterCommand(redisClient *c);
349static void sinterstoreCommand(redisClient *c);
40d224a9 350static void sunionCommand(redisClient *c);
351static void sunionstoreCommand(redisClient *c);
f4f56e1d 352static void sdiffCommand(redisClient *c);
353static void sdiffstoreCommand(redisClient *c);
ed9b544e 354static void syncCommand(redisClient *c);
355static void flushdbCommand(redisClient *c);
356static void flushallCommand(redisClient *c);
357static void sortCommand(redisClient *c);
358static void lremCommand(redisClient *c);
359static void infoCommand(redisClient *c);
70003d28 360static void mgetCommand(redisClient *c);
87eca727 361static void monitorCommand(redisClient *c);
3305306f 362static void expireCommand(redisClient *c);
a431eb74 363static void getSetCommand(redisClient *c);
fd88489a 364static void ttlCommand(redisClient *c);
ed9b544e 365
366/*================================= Globals ================================= */
367
368/* Global vars */
369static struct redisServer server; /* server global state */
370static struct redisCommand cmdTable[] = {
371 {"get",getCommand,2,REDIS_CMD_INLINE},
372 {"set",setCommand,3,REDIS_CMD_BULK},
373 {"setnx",setnxCommand,3,REDIS_CMD_BULK},
5109cdff 374 {"del",delCommand,-2,REDIS_CMD_INLINE},
ed9b544e 375 {"exists",existsCommand,2,REDIS_CMD_INLINE},
376 {"incr",incrCommand,2,REDIS_CMD_INLINE},
377 {"decr",decrCommand,2,REDIS_CMD_INLINE},
70003d28 378 {"mget",mgetCommand,-2,REDIS_CMD_INLINE},
ed9b544e 379 {"rpush",rpushCommand,3,REDIS_CMD_BULK},
380 {"lpush",lpushCommand,3,REDIS_CMD_BULK},
381 {"rpop",rpopCommand,2,REDIS_CMD_INLINE},
382 {"lpop",lpopCommand,2,REDIS_CMD_INLINE},
383 {"llen",llenCommand,2,REDIS_CMD_INLINE},
384 {"lindex",lindexCommand,3,REDIS_CMD_INLINE},
385 {"lset",lsetCommand,4,REDIS_CMD_BULK},
386 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE},
387 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE},
388 {"lrem",lremCommand,4,REDIS_CMD_BULK},
389 {"sadd",saddCommand,3,REDIS_CMD_BULK},
390 {"srem",sremCommand,3,REDIS_CMD_BULK},
a4460ef4 391 {"smove",smoveCommand,4,REDIS_CMD_BULK},
ed9b544e 392 {"sismember",sismemberCommand,3,REDIS_CMD_BULK},
393 {"scard",scardCommand,2,REDIS_CMD_INLINE},
394 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE},
395 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE},
40d224a9 396 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE},
397 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE},
f4f56e1d 398 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE},
399 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE},
ed9b544e 400 {"smembers",sinterCommand,2,REDIS_CMD_INLINE},
401 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE},
402 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE},
a431eb74 403 {"getset",getSetCommand,3,REDIS_CMD_BULK},
ed9b544e 404 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE},
405 {"select",selectCommand,2,REDIS_CMD_INLINE},
406 {"move",moveCommand,3,REDIS_CMD_INLINE},
407 {"rename",renameCommand,3,REDIS_CMD_INLINE},
408 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE},
409 {"keys",keysCommand,2,REDIS_CMD_INLINE},
410 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE},
abcb223e 411 {"auth",authCommand,2,REDIS_CMD_INLINE},
ed9b544e 412 {"ping",pingCommand,1,REDIS_CMD_INLINE},
413 {"echo",echoCommand,2,REDIS_CMD_BULK},
414 {"save",saveCommand,1,REDIS_CMD_INLINE},
415 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE},
416 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE},
417 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE},
418 {"type",typeCommand,2,REDIS_CMD_INLINE},
419 {"sync",syncCommand,1,REDIS_CMD_INLINE},
420 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE},
421 {"flushall",flushallCommand,1,REDIS_CMD_INLINE},
422 {"sort",sortCommand,-2,REDIS_CMD_INLINE},
423 {"info",infoCommand,1,REDIS_CMD_INLINE},
87eca727 424 {"monitor",monitorCommand,1,REDIS_CMD_INLINE},
3305306f 425 {"expire",expireCommand,3,REDIS_CMD_INLINE},
fd88489a 426 {"ttl",ttlCommand,2,REDIS_CMD_INLINE},
ed9b544e 427 {NULL,NULL,0,0}
428};
429
430/*============================ Utility functions ============================ */
431
432/* Glob-style pattern matching. */
433int stringmatchlen(const char *pattern, int patternLen,
434 const char *string, int stringLen, int nocase)
435{
436 while(patternLen) {
437 switch(pattern[0]) {
438 case '*':
439 while (pattern[1] == '*') {
440 pattern++;
441 patternLen--;
442 }
443 if (patternLen == 1)
444 return 1; /* match */
445 while(stringLen) {
446 if (stringmatchlen(pattern+1, patternLen-1,
447 string, stringLen, nocase))
448 return 1; /* match */
449 string++;
450 stringLen--;
451 }
452 return 0; /* no match */
453 break;
454 case '?':
455 if (stringLen == 0)
456 return 0; /* no match */
457 string++;
458 stringLen--;
459 break;
460 case '[':
461 {
462 int not, match;
463
464 pattern++;
465 patternLen--;
466 not = pattern[0] == '^';
467 if (not) {
468 pattern++;
469 patternLen--;
470 }
471 match = 0;
472 while(1) {
473 if (pattern[0] == '\\') {
474 pattern++;
475 patternLen--;
476 if (pattern[0] == string[0])
477 match = 1;
478 } else if (pattern[0] == ']') {
479 break;
480 } else if (patternLen == 0) {
481 pattern--;
482 patternLen++;
483 break;
484 } else if (pattern[1] == '-' && patternLen >= 3) {
485 int start = pattern[0];
486 int end = pattern[2];
487 int c = string[0];
488 if (start > end) {
489 int t = start;
490 start = end;
491 end = t;
492 }
493 if (nocase) {
494 start = tolower(start);
495 end = tolower(end);
496 c = tolower(c);
497 }
498 pattern += 2;
499 patternLen -= 2;
500 if (c >= start && c <= end)
501 match = 1;
502 } else {
503 if (!nocase) {
504 if (pattern[0] == string[0])
505 match = 1;
506 } else {
507 if (tolower((int)pattern[0]) == tolower((int)string[0]))
508 match = 1;
509 }
510 }
511 pattern++;
512 patternLen--;
513 }
514 if (not)
515 match = !match;
516 if (!match)
517 return 0; /* no match */
518 string++;
519 stringLen--;
520 break;
521 }
522 case '\\':
523 if (patternLen >= 2) {
524 pattern++;
525 patternLen--;
526 }
527 /* fall through */
528 default:
529 if (!nocase) {
530 if (pattern[0] != string[0])
531 return 0; /* no match */
532 } else {
533 if (tolower((int)pattern[0]) != tolower((int)string[0]))
534 return 0; /* no match */
535 }
536 string++;
537 stringLen--;
538 break;
539 }
540 pattern++;
541 patternLen--;
542 if (stringLen == 0) {
543 while(*pattern == '*') {
544 pattern++;
545 patternLen--;
546 }
547 break;
548 }
549 }
550 if (patternLen == 0 && stringLen == 0)
551 return 1;
552 return 0;
553}
554
555void redisLog(int level, const char *fmt, ...)
556{
557 va_list ap;
558 FILE *fp;
559
560 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
561 if (!fp) return;
562
563 va_start(ap, fmt);
564 if (level >= server.verbosity) {
565 char *c = ".-*";
1904ecc1 566 char buf[64];
567 time_t now;
568
569 now = time(NULL);
570 strftime(buf,64,"%d %b %H:%M:%S",gmtime(&now));
571 fprintf(fp,"%s %c ",buf,c[level]);
ed9b544e 572 vfprintf(fp, fmt, ap);
573 fprintf(fp,"\n");
574 fflush(fp);
575 }
576 va_end(ap);
577
578 if (server.logfile) fclose(fp);
579}
580
581/*====================== Hash table type implementation ==================== */
582
583/* This is an hash table type that uses the SDS dynamic strings libary as
584 * keys and radis objects as values (objects can hold SDS strings,
585 * lists, sets). */
586
587static int sdsDictKeyCompare(void *privdata, const void *key1,
588 const void *key2)
589{
590 int l1,l2;
591 DICT_NOTUSED(privdata);
592
593 l1 = sdslen((sds)key1);
594 l2 = sdslen((sds)key2);
595 if (l1 != l2) return 0;
596 return memcmp(key1, key2, l1) == 0;
597}
598
599static void dictRedisObjectDestructor(void *privdata, void *val)
600{
601 DICT_NOTUSED(privdata);
602
603 decrRefCount(val);
604}
605
606static int dictSdsKeyCompare(void *privdata, const void *key1,
607 const void *key2)
608{
609 const robj *o1 = key1, *o2 = key2;
610 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
611}
612
613static unsigned int dictSdsHash(const void *key) {
614 const robj *o = key;
615 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
616}
617
618static dictType setDictType = {
619 dictSdsHash, /* hash function */
620 NULL, /* key dup */
621 NULL, /* val dup */
622 dictSdsKeyCompare, /* key compare */
623 dictRedisObjectDestructor, /* key destructor */
624 NULL /* val destructor */
625};
626
627static dictType hashDictType = {
628 dictSdsHash, /* hash function */
629 NULL, /* key dup */
630 NULL, /* val dup */
631 dictSdsKeyCompare, /* key compare */
632 dictRedisObjectDestructor, /* key destructor */
633 dictRedisObjectDestructor /* val destructor */
634};
635
636/* ========================= Random utility functions ======================= */
637
638/* Redis generally does not try to recover from out of memory conditions
639 * when allocating objects or strings, it is not clear if it will be possible
640 * to report this condition to the client since the networking layer itself
641 * is based on heap allocation for send buffers, so we simply abort.
642 * At least the code will be simpler to read... */
643static void oom(const char *msg) {
644 fprintf(stderr, "%s: Out of memory\n",msg);
645 fflush(stderr);
646 sleep(1);
647 abort();
648}
649
650/* ====================== Redis server networking stuff ===================== */
651void closeTimedoutClients(void) {
652 redisClient *c;
ed9b544e 653 listNode *ln;
654 time_t now = time(NULL);
655
6208b3a7 656 listRewind(server.clients);
657 while ((ln = listYield(server.clients)) != NULL) {
ed9b544e 658 c = listNodeValue(ln);
659 if (!(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
660 (now - c->lastinteraction > server.maxidletime)) {
661 redisLog(REDIS_DEBUG,"Closing idle client");
662 freeClient(c);
663 }
664 }
ed9b544e 665}
666
0bc03378 667/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
668 * we resize the hash table to save memory */
669void tryResizeHashTables(void) {
670 int j;
671
672 for (j = 0; j < server.dbnum; j++) {
673 long long size, used;
674
675 size = dictSlots(server.db[j].dict);
676 used = dictSize(server.db[j].dict);
677 if (size && used && size > REDIS_HT_MINSLOTS &&
678 (used*100/size < REDIS_HT_MINFILL)) {
679 redisLog(REDIS_NOTICE,"The hash table %d is too sparse, resize it...",j);
680 dictResize(server.db[j].dict);
681 redisLog(REDIS_NOTICE,"Hash table %d resized.",j);
682 }
683 }
684}
685
ed9b544e 686int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
94754ccc 687 int j, loops = server.cronloops++;
ed9b544e 688 REDIS_NOTUSED(eventLoop);
689 REDIS_NOTUSED(id);
690 REDIS_NOTUSED(clientData);
691
692 /* Update the global state with the amount of used memory */
693 server.usedmemory = zmalloc_used_memory();
694
0bc03378 695 /* Show some info about non-empty databases */
ed9b544e 696 for (j = 0; j < server.dbnum; j++) {
dec423d9 697 long long size, used, vkeys;
94754ccc 698
3305306f 699 size = dictSlots(server.db[j].dict);
700 used = dictSize(server.db[j].dict);
94754ccc 701 vkeys = dictSize(server.db[j].expires);
ed9b544e 702 if (!(loops % 5) && used > 0) {
94754ccc 703 redisLog(REDIS_DEBUG,"DB %d: %d keys (%d volatile) in %d slots HT.",j,used,vkeys,size);
a4d1ba9a 704 /* dictPrintStats(server.dict); */
ed9b544e 705 }
ed9b544e 706 }
707
0bc03378 708 /* We don't want to resize the hash tables while a bacground saving
709 * is in progress: the saving child is created using fork() that is
710 * implemented with a copy-on-write semantic in most modern systems, so
711 * if we resize the HT while there is the saving child at work actually
712 * a lot of memory movements in the parent will cause a lot of pages
713 * copied. */
714 if (!server.bgsaveinprogress) tryResizeHashTables();
715
ed9b544e 716 /* Show information about connected clients */
717 if (!(loops % 5)) {
5fba9f71 718 redisLog(REDIS_DEBUG,"%d clients connected (%d slaves), %zu bytes in use",
ed9b544e 719 listLength(server.clients)-listLength(server.slaves),
720 listLength(server.slaves),
10c43610 721 server.usedmemory,
3305306f 722 dictSize(server.sharingpool));
ed9b544e 723 }
724
725 /* Close connections of timedout clients */
0150db36 726 if (server.maxidletime && !(loops % 10))
ed9b544e 727 closeTimedoutClients();
728
729 /* Check if a background saving in progress terminated */
730 if (server.bgsaveinprogress) {
731 int statloc;
6208b3a7 732 /* XXX: TODO handle the case of the saving child killed */
ed9b544e 733 if (wait4(-1,&statloc,WNOHANG,NULL)) {
734 int exitcode = WEXITSTATUS(statloc);
735 if (exitcode == 0) {
736 redisLog(REDIS_NOTICE,
737 "Background saving terminated with success");
738 server.dirty = 0;
739 server.lastsave = time(NULL);
740 } else {
741 redisLog(REDIS_WARNING,
742 "Background saving error");
743 }
744 server.bgsaveinprogress = 0;
6208b3a7 745 updateSalvesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
ed9b544e 746 }
747 } else {
748 /* If there is not a background saving in progress check if
749 * we have to save now */
750 time_t now = time(NULL);
751 for (j = 0; j < server.saveparamslen; j++) {
752 struct saveparam *sp = server.saveparams+j;
753
754 if (server.dirty >= sp->changes &&
755 now-server.lastsave > sp->seconds) {
756 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
757 sp->changes, sp->seconds);
f78fd11b 758 rdbSaveBackground(server.dbfilename);
ed9b544e 759 break;
760 }
761 }
762 }
94754ccc 763
764 /* Try to expire a few timed out keys */
765 for (j = 0; j < server.dbnum; j++) {
766 redisDb *db = server.db+j;
767 int num = dictSize(db->expires);
768
769 if (num) {
770 time_t now = time(NULL);
771
772 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
773 num = REDIS_EXPIRELOOKUPS_PER_CRON;
774 while (num--) {
775 dictEntry *de;
776 time_t t;
777
778 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
779 t = (time_t) dictGetEntryVal(de);
780 if (now > t) {
781 deleteKey(db,dictGetEntryKey(de));
782 }
783 }
784 }
785 }
786
ed9b544e 787 /* Check if we should connect to a MASTER */
788 if (server.replstate == REDIS_REPL_CONNECT) {
789 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
790 if (syncWithMaster() == REDIS_OK) {
791 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
792 }
793 }
794 return 1000;
795}
796
797static void createSharedObjects(void) {
798 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
799 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
800 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
c937aa89 801 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
802 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
803 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
804 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
805 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
806 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
ed9b544e 807 /* no such key */
ed9b544e 808 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
809 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
810 "-ERR Operation against a key holding the wrong kind of value\r\n"));
ed9b544e 811 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
812 "-ERR no such key\r\n"));
ed9b544e 813 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
814 "-ERR syntax error\r\n"));
c937aa89 815 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
816 "-ERR source and destination objects are the same\r\n"));
817 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
818 "-ERR index out of range\r\n"));
ed9b544e 819 shared.space = createObject(REDIS_STRING,sdsnew(" "));
c937aa89 820 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
821 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
ed9b544e 822 shared.select0 = createStringObject("select 0\r\n",10);
823 shared.select1 = createStringObject("select 1\r\n",10);
824 shared.select2 = createStringObject("select 2\r\n",10);
825 shared.select3 = createStringObject("select 3\r\n",10);
826 shared.select4 = createStringObject("select 4\r\n",10);
827 shared.select5 = createStringObject("select 5\r\n",10);
828 shared.select6 = createStringObject("select 6\r\n",10);
829 shared.select7 = createStringObject("select 7\r\n",10);
830 shared.select8 = createStringObject("select 8\r\n",10);
831 shared.select9 = createStringObject("select 9\r\n",10);
832}
833
834static void appendServerSaveParams(time_t seconds, int changes) {
835 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
836 if (server.saveparams == NULL) oom("appendServerSaveParams");
837 server.saveparams[server.saveparamslen].seconds = seconds;
838 server.saveparams[server.saveparamslen].changes = changes;
839 server.saveparamslen++;
840}
841
842static void ResetServerSaveParams() {
843 zfree(server.saveparams);
844 server.saveparams = NULL;
845 server.saveparamslen = 0;
846}
847
848static void initServerConfig() {
849 server.dbnum = REDIS_DEFAULT_DBNUM;
850 server.port = REDIS_SERVERPORT;
851 server.verbosity = REDIS_DEBUG;
852 server.maxidletime = REDIS_MAXIDLETIME;
853 server.saveparams = NULL;
854 server.logfile = NULL; /* NULL = log on standard output */
855 server.bindaddr = NULL;
856 server.glueoutputbuf = 1;
857 server.daemonize = 0;
ed329fcf 858 server.pidfile = "/var/run/redis.pid";
ed9b544e 859 server.dbfilename = "dump.rdb";
abcb223e 860 server.requirepass = NULL;
10c43610 861 server.shareobjects = 0;
ed9b544e 862 ResetServerSaveParams();
863
864 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
865 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
866 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
867 /* Replication related */
868 server.isslave = 0;
869 server.masterhost = NULL;
870 server.masterport = 6379;
871 server.master = NULL;
872 server.replstate = REDIS_REPL_NONE;
873}
874
875static void initServer() {
876 int j;
877
878 signal(SIGHUP, SIG_IGN);
879 signal(SIGPIPE, SIG_IGN);
880
881 server.clients = listCreate();
882 server.slaves = listCreate();
87eca727 883 server.monitors = listCreate();
ed9b544e 884 server.objfreelist = listCreate();
885 createSharedObjects();
886 server.el = aeCreateEventLoop();
3305306f 887 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
10c43610 888 server.sharingpool = dictCreate(&setDictType,NULL);
889 server.sharingpoolsize = 1024;
3305306f 890 if (!server.db || !server.clients || !server.slaves || !server.monitors || !server.el || !server.objfreelist)
ed9b544e 891 oom("server initialization"); /* Fatal OOM */
892 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
893 if (server.fd == -1) {
894 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
895 exit(1);
896 }
3305306f 897 for (j = 0; j < server.dbnum; j++) {
898 server.db[j].dict = dictCreate(&hashDictType,NULL);
899 server.db[j].expires = dictCreate(&setDictType,NULL);
900 server.db[j].id = j;
901 }
ed9b544e 902 server.cronloops = 0;
903 server.bgsaveinprogress = 0;
904 server.lastsave = time(NULL);
905 server.dirty = 0;
906 server.usedmemory = 0;
907 server.stat_numcommands = 0;
908 server.stat_numconnections = 0;
909 server.stat_starttime = time(NULL);
910 aeCreateTimeEvent(server.el, 1000, serverCron, NULL, NULL);
911}
912
913/* Empty the whole database */
ca37e9cd 914static long long emptyDb() {
ed9b544e 915 int j;
ca37e9cd 916 long long removed = 0;
ed9b544e 917
3305306f 918 for (j = 0; j < server.dbnum; j++) {
ca37e9cd 919 removed += dictSize(server.db[j].dict);
3305306f 920 dictEmpty(server.db[j].dict);
921 dictEmpty(server.db[j].expires);
922 }
ca37e9cd 923 return removed;
ed9b544e 924}
925
85dd2f3a 926static int yesnotoi(char *s) {
927 if (!strcasecmp(s,"yes")) return 1;
928 else if (!strcasecmp(s,"no")) return 0;
929 else return -1;
930}
931
ed9b544e 932/* I agree, this is a very rudimental way to load a configuration...
933 will improve later if the config gets more complex */
934static void loadServerConfig(char *filename) {
935 FILE *fp = fopen(filename,"r");
936 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
937 int linenum = 0;
938 sds line = NULL;
939
940 if (!fp) {
941 redisLog(REDIS_WARNING,"Fatal error, can't open config file");
942 exit(1);
943 }
944 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
945 sds *argv;
946 int argc, j;
947
948 linenum++;
949 line = sdsnew(buf);
950 line = sdstrim(line," \t\r\n");
951
952 /* Skip comments and blank lines*/
953 if (line[0] == '#' || line[0] == '\0') {
954 sdsfree(line);
955 continue;
956 }
957
958 /* Split into arguments */
959 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
960 sdstolower(argv[0]);
961
962 /* Execute config directives */
bb0b03a3 963 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
ed9b544e 964 server.maxidletime = atoi(argv[1]);
0150db36 965 if (server.maxidletime < 0) {
ed9b544e 966 err = "Invalid timeout value"; goto loaderr;
967 }
bb0b03a3 968 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
ed9b544e 969 server.port = atoi(argv[1]);
970 if (server.port < 1 || server.port > 65535) {
971 err = "Invalid port"; goto loaderr;
972 }
bb0b03a3 973 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
ed9b544e 974 server.bindaddr = zstrdup(argv[1]);
bb0b03a3 975 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
ed9b544e 976 int seconds = atoi(argv[1]);
977 int changes = atoi(argv[2]);
978 if (seconds < 1 || changes < 0) {
979 err = "Invalid save parameters"; goto loaderr;
980 }
981 appendServerSaveParams(seconds,changes);
bb0b03a3 982 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
ed9b544e 983 if (chdir(argv[1]) == -1) {
984 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
985 argv[1], strerror(errno));
986 exit(1);
987 }
bb0b03a3 988 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
989 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
990 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
991 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
ed9b544e 992 else {
993 err = "Invalid log level. Must be one of debug, notice, warning";
994 goto loaderr;
995 }
bb0b03a3 996 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
ed9b544e 997 FILE *fp;
998
999 server.logfile = zstrdup(argv[1]);
bb0b03a3 1000 if (!strcasecmp(server.logfile,"stdout")) {
ed9b544e 1001 zfree(server.logfile);
1002 server.logfile = NULL;
1003 }
1004 if (server.logfile) {
1005 /* Test if we are able to open the file. The server will not
1006 * be able to abort just for this problem later... */
1007 fp = fopen(server.logfile,"a");
1008 if (fp == NULL) {
1009 err = sdscatprintf(sdsempty(),
1010 "Can't open the log file: %s", strerror(errno));
1011 goto loaderr;
1012 }
1013 fclose(fp);
1014 }
bb0b03a3 1015 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
ed9b544e 1016 server.dbnum = atoi(argv[1]);
1017 if (server.dbnum < 1) {
1018 err = "Invalid number of databases"; goto loaderr;
1019 }
bb0b03a3 1020 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
ed9b544e 1021 server.masterhost = sdsnew(argv[1]);
1022 server.masterport = atoi(argv[2]);
1023 server.replstate = REDIS_REPL_CONNECT;
bb0b03a3 1024 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
85dd2f3a 1025 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
ed9b544e 1026 err = "argument must be 'yes' or 'no'"; goto loaderr;
1027 }
bb0b03a3 1028 } else if (!strcasecmp(argv[0],"shareobjects") && argc == 2) {
85dd2f3a 1029 if ((server.shareobjects = yesnotoi(argv[1])) == -1) {
10c43610 1030 err = "argument must be 'yes' or 'no'"; goto loaderr;
1031 }
bb0b03a3 1032 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
85dd2f3a 1033 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
ed9b544e 1034 err = "argument must be 'yes' or 'no'"; goto loaderr;
1035 }
bb0b03a3 1036 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
abcb223e 1037 server.requirepass = zstrdup(argv[1]);
bb0b03a3 1038 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
ed329fcf 1039 server.pidfile = zstrdup(argv[1]);
bb0b03a3 1040 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
b8b553c8 1041 server.dbfilename = zstrdup(argv[1]);
ed9b544e 1042 } else {
1043 err = "Bad directive or wrong number of arguments"; goto loaderr;
1044 }
1045 for (j = 0; j < argc; j++)
1046 sdsfree(argv[j]);
1047 zfree(argv);
1048 sdsfree(line);
1049 }
1050 fclose(fp);
1051 return;
1052
1053loaderr:
1054 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
1055 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
1056 fprintf(stderr, ">>> '%s'\n", line);
1057 fprintf(stderr, "%s\n", err);
1058 exit(1);
1059}
1060
1061static void freeClientArgv(redisClient *c) {
1062 int j;
1063
1064 for (j = 0; j < c->argc; j++)
1065 decrRefCount(c->argv[j]);
1066 c->argc = 0;
1067}
1068
1069static void freeClient(redisClient *c) {
1070 listNode *ln;
1071
1072 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
1073 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
1074 sdsfree(c->querybuf);
1075 listRelease(c->reply);
1076 freeClientArgv(c);
1077 close(c->fd);
1078 ln = listSearchKey(server.clients,c);
1079 assert(ln != NULL);
1080 listDelNode(server.clients,ln);
1081 if (c->flags & REDIS_SLAVE) {
6208b3a7 1082 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
1083 close(c->repldbfd);
87eca727 1084 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
1085 ln = listSearchKey(l,c);
ed9b544e 1086 assert(ln != NULL);
87eca727 1087 listDelNode(l,ln);
ed9b544e 1088 }
1089 if (c->flags & REDIS_MASTER) {
1090 server.master = NULL;
1091 server.replstate = REDIS_REPL_CONNECT;
1092 }
93ea3759 1093 zfree(c->argv);
ed9b544e 1094 zfree(c);
1095}
1096
1097static void glueReplyBuffersIfNeeded(redisClient *c) {
1098 int totlen = 0;
6208b3a7 1099 listNode *ln;
ed9b544e 1100 robj *o;
1101
6208b3a7 1102 listRewind(c->reply);
1103 while((ln = listYield(c->reply))) {
ed9b544e 1104 o = ln->value;
1105 totlen += sdslen(o->ptr);
ed9b544e 1106 /* This optimization makes more sense if we don't have to copy
1107 * too much data */
1108 if (totlen > 1024) return;
1109 }
1110 if (totlen > 0) {
1111 char buf[1024];
1112 int copylen = 0;
1113
6208b3a7 1114 listRewind(c->reply);
1115 while((ln = listYield(c->reply))) {
ed9b544e 1116 o = ln->value;
1117 memcpy(buf+copylen,o->ptr,sdslen(o->ptr));
1118 copylen += sdslen(o->ptr);
1119 listDelNode(c->reply,ln);
ed9b544e 1120 }
1121 /* Now the output buffer is empty, add the new single element */
6fdc78ac 1122 o = createObject(REDIS_STRING,sdsnewlen(buf,totlen));
1123 if (!listAddNodeTail(c->reply,o)) oom("listAddNodeTail");
ed9b544e 1124 }
1125}
1126
1127static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
1128 redisClient *c = privdata;
1129 int nwritten = 0, totwritten = 0, objlen;
1130 robj *o;
1131 REDIS_NOTUSED(el);
1132 REDIS_NOTUSED(mask);
1133
1134 if (server.glueoutputbuf && listLength(c->reply) > 1)
1135 glueReplyBuffersIfNeeded(c);
1136 while(listLength(c->reply)) {
1137 o = listNodeValue(listFirst(c->reply));
1138 objlen = sdslen(o->ptr);
1139
1140 if (objlen == 0) {
1141 listDelNode(c->reply,listFirst(c->reply));
1142 continue;
1143 }
1144
1145 if (c->flags & REDIS_MASTER) {
1146 nwritten = objlen - c->sentlen;
1147 } else {
a4d1ba9a 1148 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
ed9b544e 1149 if (nwritten <= 0) break;
1150 }
1151 c->sentlen += nwritten;
1152 totwritten += nwritten;
1153 /* If we fully sent the object on head go to the next one */
1154 if (c->sentlen == objlen) {
1155 listDelNode(c->reply,listFirst(c->reply));
1156 c->sentlen = 0;
1157 }
1158 }
1159 if (nwritten == -1) {
1160 if (errno == EAGAIN) {
1161 nwritten = 0;
1162 } else {
1163 redisLog(REDIS_DEBUG,
1164 "Error writing to client: %s", strerror(errno));
1165 freeClient(c);
1166 return;
1167 }
1168 }
1169 if (totwritten > 0) c->lastinteraction = time(NULL);
1170 if (listLength(c->reply) == 0) {
1171 c->sentlen = 0;
1172 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
1173 }
1174}
1175
1176static struct redisCommand *lookupCommand(char *name) {
1177 int j = 0;
1178 while(cmdTable[j].name != NULL) {
bb0b03a3 1179 if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
ed9b544e 1180 j++;
1181 }
1182 return NULL;
1183}
1184
1185/* resetClient prepare the client to process the next command */
1186static void resetClient(redisClient *c) {
1187 freeClientArgv(c);
1188 c->bulklen = -1;
1189}
1190
1191/* If this function gets called we already read a whole
1192 * command, argments are in the client argv/argc fields.
1193 * processCommand() execute the command or prepare the
1194 * server for a bulk read from the client.
1195 *
1196 * If 1 is returned the client is still alive and valid and
1197 * and other operations can be performed by the caller. Otherwise
1198 * if 0 is returned the client was destroied (i.e. after QUIT). */
1199static int processCommand(redisClient *c) {
1200 struct redisCommand *cmd;
1201 long long dirty;
1202
ed9b544e 1203 /* The QUIT command is handled as a special case. Normal command
1204 * procs are unable to close the client connection safely */
bb0b03a3 1205 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
ed9b544e 1206 freeClient(c);
1207 return 0;
1208 }
1209 cmd = lookupCommand(c->argv[0]->ptr);
1210 if (!cmd) {
1211 addReplySds(c,sdsnew("-ERR unknown command\r\n"));
1212 resetClient(c);
1213 return 1;
1214 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
1215 (c->argc < -cmd->arity)) {
1216 addReplySds(c,sdsnew("-ERR wrong number of arguments\r\n"));
1217 resetClient(c);
1218 return 1;
1219 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
1220 int bulklen = atoi(c->argv[c->argc-1]->ptr);
1221
1222 decrRefCount(c->argv[c->argc-1]);
1223 if (bulklen < 0 || bulklen > 1024*1024*1024) {
1224 c->argc--;
1225 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
1226 resetClient(c);
1227 return 1;
1228 }
1229 c->argc--;
1230 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
1231 /* It is possible that the bulk read is already in the
1232 * buffer. Check this condition and handle it accordingly */
1233 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
1234 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
1235 c->argc++;
1236 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
1237 } else {
1238 return 1;
1239 }
1240 }
10c43610 1241 /* Let's try to share objects on the command arguments vector */
1242 if (server.shareobjects) {
1243 int j;
1244 for(j = 1; j < c->argc; j++)
1245 c->argv[j] = tryObjectSharing(c->argv[j]);
1246 }
e63943a4 1247 /* Check if the user is authenticated */
1248 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
1249 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
1250 resetClient(c);
1251 return 1;
1252 }
1253
ed9b544e 1254 /* Exec the command */
1255 dirty = server.dirty;
1256 cmd->proc(c);
1257 if (server.dirty-dirty != 0 && listLength(server.slaves))
3305306f 1258 replicationFeedSlaves(server.slaves,cmd,c->db->id,c->argv,c->argc);
87eca727 1259 if (listLength(server.monitors))
3305306f 1260 replicationFeedSlaves(server.monitors,cmd,c->db->id,c->argv,c->argc);
ed9b544e 1261 server.stat_numcommands++;
1262
1263 /* Prepare the client for the next command */
1264 if (c->flags & REDIS_CLOSE) {
1265 freeClient(c);
1266 return 0;
1267 }
1268 resetClient(c);
1269 return 1;
1270}
1271
87eca727 1272static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc) {
6208b3a7 1273 listNode *ln;
ed9b544e 1274 int outc = 0, j;
93ea3759 1275 robj **outv;
1276 /* (args*2)+1 is enough room for args, spaces, newlines */
1277 robj *static_outv[REDIS_STATIC_ARGS*2+1];
1278
1279 if (argc <= REDIS_STATIC_ARGS) {
1280 outv = static_outv;
1281 } else {
1282 outv = zmalloc(sizeof(robj*)*(argc*2+1));
1283 if (!outv) oom("replicationFeedSlaves");
1284 }
ed9b544e 1285
1286 for (j = 0; j < argc; j++) {
1287 if (j != 0) outv[outc++] = shared.space;
1288 if ((cmd->flags & REDIS_CMD_BULK) && j == argc-1) {
1289 robj *lenobj;
1290
1291 lenobj = createObject(REDIS_STRING,
1292 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv[j]->ptr)));
1293 lenobj->refcount = 0;
1294 outv[outc++] = lenobj;
1295 }
1296 outv[outc++] = argv[j];
1297 }
1298 outv[outc++] = shared.crlf;
1299
40d224a9 1300 /* Increment all the refcounts at start and decrement at end in order to
1301 * be sure to free objects if there is no slave in a replication state
1302 * able to be feed with commands */
1303 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
6208b3a7 1304 listRewind(slaves);
1305 while((ln = listYield(slaves))) {
ed9b544e 1306 redisClient *slave = ln->value;
40d224a9 1307
1308 /* Don't feed slaves that are still waiting for BGSAVE to start */
6208b3a7 1309 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
40d224a9 1310
1311 /* Feed all the other slaves, MONITORs and so on */
ed9b544e 1312 if (slave->slaveseldb != dictid) {
1313 robj *selectcmd;
1314
1315 switch(dictid) {
1316 case 0: selectcmd = shared.select0; break;
1317 case 1: selectcmd = shared.select1; break;
1318 case 2: selectcmd = shared.select2; break;
1319 case 3: selectcmd = shared.select3; break;
1320 case 4: selectcmd = shared.select4; break;
1321 case 5: selectcmd = shared.select5; break;
1322 case 6: selectcmd = shared.select6; break;
1323 case 7: selectcmd = shared.select7; break;
1324 case 8: selectcmd = shared.select8; break;
1325 case 9: selectcmd = shared.select9; break;
1326 default:
1327 selectcmd = createObject(REDIS_STRING,
1328 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
1329 selectcmd->refcount = 0;
1330 break;
1331 }
1332 addReply(slave,selectcmd);
1333 slave->slaveseldb = dictid;
1334 }
1335 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
ed9b544e 1336 }
40d224a9 1337 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
93ea3759 1338 if (outv != static_outv) zfree(outv);
ed9b544e 1339}
1340
1341static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
1342 redisClient *c = (redisClient*) privdata;
6208b3a7 1343 char buf[REDIS_IOBUF_LEN];
ed9b544e 1344 int nread;
1345 REDIS_NOTUSED(el);
1346 REDIS_NOTUSED(mask);
1347
6208b3a7 1348 nread = read(fd, buf, REDIS_IOBUF_LEN);
ed9b544e 1349 if (nread == -1) {
1350 if (errno == EAGAIN) {
1351 nread = 0;
1352 } else {
1353 redisLog(REDIS_DEBUG, "Reading from client: %s",strerror(errno));
1354 freeClient(c);
1355 return;
1356 }
1357 } else if (nread == 0) {
1358 redisLog(REDIS_DEBUG, "Client closed connection");
1359 freeClient(c);
1360 return;
1361 }
1362 if (nread) {
1363 c->querybuf = sdscatlen(c->querybuf, buf, nread);
1364 c->lastinteraction = time(NULL);
1365 } else {
1366 return;
1367 }
1368
1369again:
1370 if (c->bulklen == -1) {
1371 /* Read the first line of the query */
1372 char *p = strchr(c->querybuf,'\n');
1373 size_t querylen;
1374 if (p) {
1375 sds query, *argv;
1376 int argc, j;
1377
1378 query = c->querybuf;
1379 c->querybuf = sdsempty();
1380 querylen = 1+(p-(query));
1381 if (sdslen(query) > querylen) {
1382 /* leave data after the first line of the query in the buffer */
1383 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
1384 }
1385 *p = '\0'; /* remove "\n" */
1386 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
1387 sdsupdatelen(query);
1388
1389 /* Now we can split the query in arguments */
1390 if (sdslen(query) == 0) {
1391 /* Ignore empty query */
1392 sdsfree(query);
1393 return;
1394 }
1395 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
ed9b544e 1396 if (argv == NULL) oom("sdssplitlen");
93ea3759 1397 sdsfree(query);
1398
1399 if (c->argv) zfree(c->argv);
1400 c->argv = zmalloc(sizeof(robj*)*argc);
1401 if (c->argv == NULL) oom("allocating arguments list for client");
1402
1403 for (j = 0; j < argc; j++) {
ed9b544e 1404 if (sdslen(argv[j])) {
1405 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
1406 c->argc++;
1407 } else {
1408 sdsfree(argv[j]);
1409 }
1410 }
1411 zfree(argv);
1412 /* Execute the command. If the client is still valid
1413 * after processCommand() return and there is something
1414 * on the query buffer try to process the next command. */
1415 if (processCommand(c) && sdslen(c->querybuf)) goto again;
1416 return;
1417 } else if (sdslen(c->querybuf) >= 1024) {
1418 redisLog(REDIS_DEBUG, "Client protocol error");
1419 freeClient(c);
1420 return;
1421 }
1422 } else {
1423 /* Bulk read handling. Note that if we are at this point
1424 the client already sent a command terminated with a newline,
1425 we are reading the bulk data that is actually the last
1426 argument of the command. */
1427 int qbl = sdslen(c->querybuf);
1428
1429 if (c->bulklen <= qbl) {
1430 /* Copy everything but the final CRLF as final argument */
1431 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
1432 c->argc++;
1433 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
1434 processCommand(c);
1435 return;
1436 }
1437 }
1438}
1439
1440static int selectDb(redisClient *c, int id) {
1441 if (id < 0 || id >= server.dbnum)
1442 return REDIS_ERR;
3305306f 1443 c->db = &server.db[id];
ed9b544e 1444 return REDIS_OK;
1445}
1446
40d224a9 1447static void *dupClientReplyValue(void *o) {
1448 incrRefCount((robj*)o);
1449 return 0;
1450}
1451
ed9b544e 1452static redisClient *createClient(int fd) {
1453 redisClient *c = zmalloc(sizeof(*c));
1454
1455 anetNonBlock(NULL,fd);
1456 anetTcpNoDelay(NULL,fd);
1457 if (!c) return NULL;
1458 selectDb(c,0);
1459 c->fd = fd;
1460 c->querybuf = sdsempty();
1461 c->argc = 0;
93ea3759 1462 c->argv = NULL;
ed9b544e 1463 c->bulklen = -1;
1464 c->sentlen = 0;
1465 c->flags = 0;
1466 c->lastinteraction = time(NULL);
abcb223e 1467 c->authenticated = 0;
40d224a9 1468 c->replstate = REDIS_REPL_NONE;
ed9b544e 1469 if ((c->reply = listCreate()) == NULL) oom("listCreate");
1470 listSetFreeMethod(c->reply,decrRefCount);
40d224a9 1471 listSetDupMethod(c->reply,dupClientReplyValue);
ed9b544e 1472 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1473 readQueryFromClient, c, NULL) == AE_ERR) {
1474 freeClient(c);
1475 return NULL;
1476 }
1477 if (!listAddNodeTail(server.clients,c)) oom("listAddNodeTail");
1478 return c;
1479}
1480
1481static void addReply(redisClient *c, robj *obj) {
1482 if (listLength(c->reply) == 0 &&
6208b3a7 1483 (c->replstate == REDIS_REPL_NONE ||
1484 c->replstate == REDIS_REPL_ONLINE) &&
ed9b544e 1485 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
1486 sendReplyToClient, c, NULL) == AE_ERR) return;
1487 if (!listAddNodeTail(c->reply,obj)) oom("listAddNodeTail");
1488 incrRefCount(obj);
1489}
1490
1491static void addReplySds(redisClient *c, sds s) {
1492 robj *o = createObject(REDIS_STRING,s);
1493 addReply(c,o);
1494 decrRefCount(o);
1495}
1496
1497static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
1498 int cport, cfd;
1499 char cip[128];
1500 REDIS_NOTUSED(el);
1501 REDIS_NOTUSED(mask);
1502 REDIS_NOTUSED(privdata);
1503
1504 cfd = anetAccept(server.neterr, fd, cip, &cport);
1505 if (cfd == AE_ERR) {
1506 redisLog(REDIS_DEBUG,"Accepting client connection: %s", server.neterr);
1507 return;
1508 }
1509 redisLog(REDIS_DEBUG,"Accepted %s:%d", cip, cport);
1510 if (createClient(cfd) == NULL) {
1511 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
1512 close(cfd); /* May be already closed, just ingore errors */
1513 return;
1514 }
1515 server.stat_numconnections++;
1516}
1517
1518/* ======================= Redis objects implementation ===================== */
1519
1520static robj *createObject(int type, void *ptr) {
1521 robj *o;
1522
1523 if (listLength(server.objfreelist)) {
1524 listNode *head = listFirst(server.objfreelist);
1525 o = listNodeValue(head);
1526 listDelNode(server.objfreelist,head);
1527 } else {
1528 o = zmalloc(sizeof(*o));
1529 }
1530 if (!o) oom("createObject");
1531 o->type = type;
1532 o->ptr = ptr;
1533 o->refcount = 1;
1534 return o;
1535}
1536
1537static robj *createStringObject(char *ptr, size_t len) {
1538 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
1539}
1540
1541static robj *createListObject(void) {
1542 list *l = listCreate();
1543
1544 if (!l) oom("listCreate");
1545 listSetFreeMethod(l,decrRefCount);
1546 return createObject(REDIS_LIST,l);
1547}
1548
1549static robj *createSetObject(void) {
1550 dict *d = dictCreate(&setDictType,NULL);
1551 if (!d) oom("dictCreate");
1552 return createObject(REDIS_SET,d);
1553}
1554
ed9b544e 1555static void freeStringObject(robj *o) {
1556 sdsfree(o->ptr);
1557}
1558
1559static void freeListObject(robj *o) {
1560 listRelease((list*) o->ptr);
1561}
1562
1563static void freeSetObject(robj *o) {
1564 dictRelease((dict*) o->ptr);
1565}
1566
1567static void freeHashObject(robj *o) {
1568 dictRelease((dict*) o->ptr);
1569}
1570
1571static void incrRefCount(robj *o) {
1572 o->refcount++;
94754ccc 1573#ifdef DEBUG_REFCOUNT
1574 if (o->type == REDIS_STRING)
1575 printf("Increment '%s'(%p), now is: %d\n",o->ptr,o,o->refcount);
1576#endif
ed9b544e 1577}
1578
1579static void decrRefCount(void *obj) {
1580 robj *o = obj;
94754ccc 1581
1582#ifdef DEBUG_REFCOUNT
1583 if (o->type == REDIS_STRING)
1584 printf("Decrement '%s'(%p), now is: %d\n",o->ptr,o,o->refcount-1);
1585#endif
ed9b544e 1586 if (--(o->refcount) == 0) {
1587 switch(o->type) {
1588 case REDIS_STRING: freeStringObject(o); break;
1589 case REDIS_LIST: freeListObject(o); break;
1590 case REDIS_SET: freeSetObject(o); break;
1591 case REDIS_HASH: freeHashObject(o); break;
1592 default: assert(0 != 0); break;
1593 }
1594 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
1595 !listAddNodeHead(server.objfreelist,o))
1596 zfree(o);
1597 }
1598}
1599
10c43610 1600/* Try to share an object against the shared objects pool */
1601static robj *tryObjectSharing(robj *o) {
1602 struct dictEntry *de;
1603 unsigned long c;
1604
3305306f 1605 if (o == NULL || server.shareobjects == 0) return o;
10c43610 1606
1607 assert(o->type == REDIS_STRING);
1608 de = dictFind(server.sharingpool,o);
1609 if (de) {
1610 robj *shared = dictGetEntryKey(de);
1611
1612 c = ((unsigned long) dictGetEntryVal(de))+1;
1613 dictGetEntryVal(de) = (void*) c;
1614 incrRefCount(shared);
1615 decrRefCount(o);
1616 return shared;
1617 } else {
1618 /* Here we are using a stream algorihtm: Every time an object is
1619 * shared we increment its count, everytime there is a miss we
1620 * recrement the counter of a random object. If this object reaches
1621 * zero we remove the object and put the current object instead. */
3305306f 1622 if (dictSize(server.sharingpool) >=
10c43610 1623 server.sharingpoolsize) {
1624 de = dictGetRandomKey(server.sharingpool);
1625 assert(de != NULL);
1626 c = ((unsigned long) dictGetEntryVal(de))-1;
1627 dictGetEntryVal(de) = (void*) c;
1628 if (c == 0) {
1629 dictDelete(server.sharingpool,de->key);
1630 }
1631 } else {
1632 c = 0; /* If the pool is empty we want to add this object */
1633 }
1634 if (c == 0) {
1635 int retval;
1636
1637 retval = dictAdd(server.sharingpool,o,(void*)1);
1638 assert(retval == DICT_OK);
1639 incrRefCount(o);
1640 }
1641 return o;
1642 }
1643}
1644
3305306f 1645static robj *lookupKey(redisDb *db, robj *key) {
1646 dictEntry *de = dictFind(db->dict,key);
1647 return de ? dictGetEntryVal(de) : NULL;
1648}
1649
1650static robj *lookupKeyRead(redisDb *db, robj *key) {
1651 expireIfNeeded(db,key);
1652 return lookupKey(db,key);
1653}
1654
1655static robj *lookupKeyWrite(redisDb *db, robj *key) {
1656 deleteIfVolatile(db,key);
1657 return lookupKey(db,key);
1658}
1659
1660static int deleteKey(redisDb *db, robj *key) {
94754ccc 1661 int retval;
1662
1663 /* We need to protect key from destruction: after the first dictDelete()
1664 * it may happen that 'key' is no longer valid if we don't increment
1665 * it's count. This may happen when we get the object reference directly
1666 * from the hash table with dictRandomKey() or dict iterators */
1667 incrRefCount(key);
3305306f 1668 if (dictSize(db->expires)) dictDelete(db->expires,key);
94754ccc 1669 retval = dictDelete(db->dict,key);
1670 decrRefCount(key);
1671
1672 return retval == DICT_OK;
3305306f 1673}
1674
ed9b544e 1675/*============================ DB saving/loading ============================ */
1676
f78fd11b 1677static int rdbSaveType(FILE *fp, unsigned char type) {
1678 if (fwrite(&type,1,1,fp) == 0) return -1;
1679 return 0;
1680}
1681
bb32ede5 1682static int rdbSaveTime(FILE *fp, time_t t) {
1683 int32_t t32 = (int32_t) t;
1684 if (fwrite(&t32,4,1,fp) == 0) return -1;
1685 return 0;
1686}
1687
e3566d4b 1688/* check rdbLoadLen() comments for more info */
f78fd11b 1689static int rdbSaveLen(FILE *fp, uint32_t len) {
1690 unsigned char buf[2];
1691
1692 if (len < (1<<6)) {
1693 /* Save a 6 bit len */
10c43610 1694 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
f78fd11b 1695 if (fwrite(buf,1,1,fp) == 0) return -1;
1696 } else if (len < (1<<14)) {
1697 /* Save a 14 bit len */
10c43610 1698 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
f78fd11b 1699 buf[1] = len&0xFF;
17be1a4a 1700 if (fwrite(buf,2,1,fp) == 0) return -1;
f78fd11b 1701 } else {
1702 /* Save a 32 bit len */
10c43610 1703 buf[0] = (REDIS_RDB_32BITLEN<<6);
f78fd11b 1704 if (fwrite(buf,1,1,fp) == 0) return -1;
1705 len = htonl(len);
1706 if (fwrite(&len,4,1,fp) == 0) return -1;
1707 }
1708 return 0;
1709}
1710
e3566d4b 1711/* String objects in the form "2391" "-100" without any space and with a
1712 * range of values that can fit in an 8, 16 or 32 bit signed value can be
1713 * encoded as integers to save space */
1714int rdbTryIntegerEncoding(sds s, unsigned char *enc) {
1715 long long value;
1716 char *endptr, buf[32];
1717
1718 /* Check if it's possible to encode this value as a number */
1719 value = strtoll(s, &endptr, 10);
1720 if (endptr[0] != '\0') return 0;
1721 snprintf(buf,32,"%lld",value);
1722
1723 /* If the number converted back into a string is not identical
1724 * then it's not possible to encode the string as integer */
1725 if (strlen(buf) != sdslen(s) || memcmp(buf,s,sdslen(s))) return 0;
1726
1727 /* Finally check if it fits in our ranges */
1728 if (value >= -(1<<7) && value <= (1<<7)-1) {
1729 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
1730 enc[1] = value&0xFF;
1731 return 2;
1732 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
1733 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
1734 enc[1] = value&0xFF;
1735 enc[2] = (value>>8)&0xFF;
1736 return 3;
1737 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
1738 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
1739 enc[1] = value&0xFF;
1740 enc[2] = (value>>8)&0xFF;
1741 enc[3] = (value>>16)&0xFF;
1742 enc[4] = (value>>24)&0xFF;
1743 return 5;
1744 } else {
1745 return 0;
1746 }
1747}
1748
774e3047 1749static int rdbSaveLzfStringObject(FILE *fp, robj *obj) {
1750 unsigned int comprlen, outlen;
1751 unsigned char byte;
1752 void *out;
1753
1754 /* We require at least four bytes compression for this to be worth it */
1755 outlen = sdslen(obj->ptr)-4;
1756 if (outlen <= 0) return 0;
3a2694c4 1757 if ((out = zmalloc(outlen+1)) == NULL) return 0;
774e3047 1758 comprlen = lzf_compress(obj->ptr, sdslen(obj->ptr), out, outlen);
1759 if (comprlen == 0) {
88e85998 1760 zfree(out);
774e3047 1761 return 0;
1762 }
1763 /* Data compressed! Let's save it on disk */
1764 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
1765 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
1766 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
1767 if (rdbSaveLen(fp,sdslen(obj->ptr)) == -1) goto writeerr;
1768 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
88e85998 1769 zfree(out);
774e3047 1770 return comprlen;
1771
1772writeerr:
88e85998 1773 zfree(out);
774e3047 1774 return -1;
1775}
1776
e3566d4b 1777/* Save a string objet as [len][data] on disk. If the object is a string
1778 * representation of an integer value we try to safe it in a special form */
10c43610 1779static int rdbSaveStringObject(FILE *fp, robj *obj) {
1780 size_t len = sdslen(obj->ptr);
e3566d4b 1781 int enclen;
10c43610 1782
774e3047 1783 /* Try integer encoding */
e3566d4b 1784 if (len <= 11) {
1785 unsigned char buf[5];
1786 if ((enclen = rdbTryIntegerEncoding(obj->ptr,buf)) > 0) {
1787 if (fwrite(buf,enclen,1,fp) == 0) return -1;
1788 return 0;
1789 }
1790 }
774e3047 1791
1792 /* Try LZF compression - under 20 bytes it's unable to compress even
88e85998 1793 * aaaaaaaaaaaaaaaaaa so skip it */
3a2694c4 1794 if (1 && len > 20) {
774e3047 1795 int retval;
1796
1797 retval = rdbSaveLzfStringObject(fp,obj);
1798 if (retval == -1) return -1;
1799 if (retval > 0) return 0;
1800 /* retval == 0 means data can't be compressed, save the old way */
1801 }
1802
1803 /* Store verbatim */
10c43610 1804 if (rdbSaveLen(fp,len) == -1) return -1;
1805 if (len && fwrite(obj->ptr,len,1,fp) == 0) return -1;
1806 return 0;
1807}
1808
ed9b544e 1809/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
f78fd11b 1810static int rdbSave(char *filename) {
ed9b544e 1811 dictIterator *di = NULL;
1812 dictEntry *de;
ed9b544e 1813 FILE *fp;
1814 char tmpfile[256];
1815 int j;
bb32ede5 1816 time_t now = time(NULL);
ed9b544e 1817
1818 snprintf(tmpfile,256,"temp-%d.%ld.rdb",(int)time(NULL),(long int)random());
1819 fp = fopen(tmpfile,"w");
1820 if (!fp) {
1821 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
1822 return REDIS_ERR;
1823 }
f78fd11b 1824 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
ed9b544e 1825 for (j = 0; j < server.dbnum; j++) {
bb32ede5 1826 redisDb *db = server.db+j;
1827 dict *d = db->dict;
3305306f 1828 if (dictSize(d) == 0) continue;
ed9b544e 1829 di = dictGetIterator(d);
1830 if (!di) {
1831 fclose(fp);
1832 return REDIS_ERR;
1833 }
1834
1835 /* Write the SELECT DB opcode */
f78fd11b 1836 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
1837 if (rdbSaveLen(fp,j) == -1) goto werr;
ed9b544e 1838
1839 /* Iterate this DB writing every entry */
1840 while((de = dictNext(di)) != NULL) {
1841 robj *key = dictGetEntryKey(de);
1842 robj *o = dictGetEntryVal(de);
bb32ede5 1843 time_t expiretime = getExpire(db,key);
1844
1845 /* Save the expire time */
1846 if (expiretime != -1) {
1847 /* If this key is already expired skip it */
1848 if (expiretime < now) continue;
1849 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
1850 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
1851 }
1852 /* Save the key and associated value */
f78fd11b 1853 if (rdbSaveType(fp,o->type) == -1) goto werr;
10c43610 1854 if (rdbSaveStringObject(fp,key) == -1) goto werr;
f78fd11b 1855 if (o->type == REDIS_STRING) {
ed9b544e 1856 /* Save a string value */
10c43610 1857 if (rdbSaveStringObject(fp,o) == -1) goto werr;
f78fd11b 1858 } else if (o->type == REDIS_LIST) {
ed9b544e 1859 /* Save a list value */
1860 list *list = o->ptr;
6208b3a7 1861 listNode *ln;
ed9b544e 1862
6208b3a7 1863 listRewind(list);
f78fd11b 1864 if (rdbSaveLen(fp,listLength(list)) == -1) goto werr;
6208b3a7 1865 while((ln = listYield(list))) {
ed9b544e 1866 robj *eleobj = listNodeValue(ln);
f78fd11b 1867
10c43610 1868 if (rdbSaveStringObject(fp,eleobj) == -1) goto werr;
ed9b544e 1869 }
f78fd11b 1870 } else if (o->type == REDIS_SET) {
ed9b544e 1871 /* Save a set value */
1872 dict *set = o->ptr;
1873 dictIterator *di = dictGetIterator(set);
1874 dictEntry *de;
1875
1876 if (!set) oom("dictGetIteraotr");
3305306f 1877 if (rdbSaveLen(fp,dictSize(set)) == -1) goto werr;
ed9b544e 1878 while((de = dictNext(di)) != NULL) {
10c43610 1879 robj *eleobj = dictGetEntryKey(de);
ed9b544e 1880
10c43610 1881 if (rdbSaveStringObject(fp,eleobj) == -1) goto werr;
ed9b544e 1882 }
1883 dictReleaseIterator(di);
1884 } else {
1885 assert(0 != 0);
1886 }
1887 }
1888 dictReleaseIterator(di);
1889 }
1890 /* EOF opcode */
f78fd11b 1891 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
1892
1893 /* Make sure data will not remain on the OS's output buffers */
ed9b544e 1894 fflush(fp);
1895 fsync(fileno(fp));
1896 fclose(fp);
1897
1898 /* Use RENAME to make sure the DB file is changed atomically only
1899 * if the generate DB file is ok. */
1900 if (rename(tmpfile,filename) == -1) {
1901 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destionation: %s", strerror(errno));
1902 unlink(tmpfile);
1903 return REDIS_ERR;
1904 }
1905 redisLog(REDIS_NOTICE,"DB saved on disk");
1906 server.dirty = 0;
1907 server.lastsave = time(NULL);
1908 return REDIS_OK;
1909
1910werr:
1911 fclose(fp);
1912 unlink(tmpfile);
1913 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
1914 if (di) dictReleaseIterator(di);
1915 return REDIS_ERR;
1916}
1917
f78fd11b 1918static int rdbSaveBackground(char *filename) {
ed9b544e 1919 pid_t childpid;
1920
1921 if (server.bgsaveinprogress) return REDIS_ERR;
1922 if ((childpid = fork()) == 0) {
1923 /* Child */
1924 close(server.fd);
f78fd11b 1925 if (rdbSave(filename) == REDIS_OK) {
ed9b544e 1926 exit(0);
1927 } else {
1928 exit(1);
1929 }
1930 } else {
1931 /* Parent */
5a7c647e 1932 if (childpid == -1) {
1933 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
1934 strerror(errno));
1935 return REDIS_ERR;
1936 }
ed9b544e 1937 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
1938 server.bgsaveinprogress = 1;
1939 return REDIS_OK;
1940 }
1941 return REDIS_OK; /* unreached */
1942}
1943
f78fd11b 1944static int rdbLoadType(FILE *fp) {
1945 unsigned char type;
7b45bfb2 1946 if (fread(&type,1,1,fp) == 0) return -1;
1947 return type;
1948}
1949
bb32ede5 1950static time_t rdbLoadTime(FILE *fp) {
1951 int32_t t32;
1952 if (fread(&t32,4,1,fp) == 0) return -1;
1953 return (time_t) t32;
1954}
1955
e3566d4b 1956/* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
1957 * of this file for a description of how this are stored on disk.
1958 *
1959 * isencoded is set to 1 if the readed length is not actually a length but
1960 * an "encoding type", check the above comments for more info */
1961static uint32_t rdbLoadLen(FILE *fp, int rdbver, int *isencoded) {
f78fd11b 1962 unsigned char buf[2];
1963 uint32_t len;
1964
e3566d4b 1965 if (isencoded) *isencoded = 0;
f78fd11b 1966 if (rdbver == 0) {
1967 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
1968 return ntohl(len);
1969 } else {
17be1a4a 1970 int type;
1971
f78fd11b 1972 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
17be1a4a 1973 type = (buf[0]&0xC0)>>6;
1974 if (type == REDIS_RDB_6BITLEN) {
f78fd11b 1975 /* Read a 6 bit len */
e3566d4b 1976 return buf[0]&0x3F;
1977 } else if (type == REDIS_RDB_ENCVAL) {
1978 /* Read a 6 bit len encoding type */
1979 if (isencoded) *isencoded = 1;
1980 return buf[0]&0x3F;
17be1a4a 1981 } else if (type == REDIS_RDB_14BITLEN) {
f78fd11b 1982 /* Read a 14 bit len */
1983 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
1984 return ((buf[0]&0x3F)<<8)|buf[1];
1985 } else {
1986 /* Read a 32 bit len */
1987 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
1988 return ntohl(len);
1989 }
1990 }
f78fd11b 1991}
1992
e3566d4b 1993static robj *rdbLoadIntegerObject(FILE *fp, int enctype) {
1994 unsigned char enc[4];
1995 long long val;
1996
1997 if (enctype == REDIS_RDB_ENC_INT8) {
1998 if (fread(enc,1,1,fp) == 0) return NULL;
1999 val = (signed char)enc[0];
2000 } else if (enctype == REDIS_RDB_ENC_INT16) {
2001 uint16_t v;
2002 if (fread(enc,2,1,fp) == 0) return NULL;
2003 v = enc[0]|(enc[1]<<8);
2004 val = (int16_t)v;
2005 } else if (enctype == REDIS_RDB_ENC_INT32) {
2006 uint32_t v;
2007 if (fread(enc,4,1,fp) == 0) return NULL;
2008 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
2009 val = (int32_t)v;
2010 } else {
2011 val = 0; /* anti-warning */
2012 assert(0!=0);
2013 }
2014 return createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",val));
2015}
2016
88e85998 2017static robj *rdbLoadLzfStringObject(FILE*fp, int rdbver) {
2018 unsigned int len, clen;
2019 unsigned char *c = NULL;
2020 sds val = NULL;
2021
2022 if ((clen = rdbLoadLen(fp,rdbver,NULL)) == REDIS_RDB_LENERR) return NULL;
2023 if ((len = rdbLoadLen(fp,rdbver,NULL)) == REDIS_RDB_LENERR) return NULL;
2024 if ((c = zmalloc(clen)) == NULL) goto err;
2025 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
2026 if (fread(c,clen,1,fp) == 0) goto err;
2027 if (lzf_decompress(c,clen,val,len) == 0) goto err;
5109cdff 2028 zfree(c);
88e85998 2029 return createObject(REDIS_STRING,val);
2030err:
2031 zfree(c);
2032 sdsfree(val);
2033 return NULL;
2034}
2035
e3566d4b 2036static robj *rdbLoadStringObject(FILE*fp, int rdbver) {
2037 int isencoded;
2038 uint32_t len;
f78fd11b 2039 sds val;
2040
e3566d4b 2041 len = rdbLoadLen(fp,rdbver,&isencoded);
2042 if (isencoded) {
2043 switch(len) {
2044 case REDIS_RDB_ENC_INT8:
2045 case REDIS_RDB_ENC_INT16:
2046 case REDIS_RDB_ENC_INT32:
3305306f 2047 return tryObjectSharing(rdbLoadIntegerObject(fp,len));
88e85998 2048 case REDIS_RDB_ENC_LZF:
2049 return tryObjectSharing(rdbLoadLzfStringObject(fp,rdbver));
e3566d4b 2050 default:
2051 assert(0!=0);
2052 }
2053 }
2054
f78fd11b 2055 if (len == REDIS_RDB_LENERR) return NULL;
2056 val = sdsnewlen(NULL,len);
2057 if (len && fread(val,len,1,fp) == 0) {
2058 sdsfree(val);
2059 return NULL;
2060 }
10c43610 2061 return tryObjectSharing(createObject(REDIS_STRING,val));
f78fd11b 2062}
2063
2064static int rdbLoad(char *filename) {
ed9b544e 2065 FILE *fp;
f78fd11b 2066 robj *keyobj = NULL;
2067 uint32_t dbid;
bb32ede5 2068 int type, retval, rdbver;
3305306f 2069 dict *d = server.db[0].dict;
bb32ede5 2070 redisDb *db = server.db+0;
f78fd11b 2071 char buf[1024];
bb32ede5 2072 time_t expiretime = -1, now = time(NULL);
2073
ed9b544e 2074 fp = fopen(filename,"r");
2075 if (!fp) return REDIS_ERR;
2076 if (fread(buf,9,1,fp) == 0) goto eoferr;
f78fd11b 2077 buf[9] = '\0';
2078 if (memcmp(buf,"REDIS",5) != 0) {
ed9b544e 2079 fclose(fp);
2080 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
2081 return REDIS_ERR;
2082 }
f78fd11b 2083 rdbver = atoi(buf+5);
2084 if (rdbver > 1) {
2085 fclose(fp);
2086 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
2087 return REDIS_ERR;
2088 }
ed9b544e 2089 while(1) {
2090 robj *o;
2091
2092 /* Read type. */
f78fd11b 2093 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
bb32ede5 2094 if (type == REDIS_EXPIRETIME) {
2095 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
2096 /* We read the time so we need to read the object type again */
2097 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
2098 }
ed9b544e 2099 if (type == REDIS_EOF) break;
2100 /* Handle SELECT DB opcode as a special case */
2101 if (type == REDIS_SELECTDB) {
e3566d4b 2102 if ((dbid = rdbLoadLen(fp,rdbver,NULL)) == REDIS_RDB_LENERR)
2103 goto eoferr;
ed9b544e 2104 if (dbid >= (unsigned)server.dbnum) {
f78fd11b 2105 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
ed9b544e 2106 exit(1);
2107 }
bb32ede5 2108 db = server.db+dbid;
2109 d = db->dict;
ed9b544e 2110 continue;
2111 }
2112 /* Read key */
f78fd11b 2113 if ((keyobj = rdbLoadStringObject(fp,rdbver)) == NULL) goto eoferr;
ed9b544e 2114
2115 if (type == REDIS_STRING) {
2116 /* Read string value */
f78fd11b 2117 if ((o = rdbLoadStringObject(fp,rdbver)) == NULL) goto eoferr;
ed9b544e 2118 } else if (type == REDIS_LIST || type == REDIS_SET) {
2119 /* Read list/set value */
2120 uint32_t listlen;
f78fd11b 2121
e3566d4b 2122 if ((listlen = rdbLoadLen(fp,rdbver,NULL)) == REDIS_RDB_LENERR)
f78fd11b 2123 goto eoferr;
ed9b544e 2124 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
2125 /* Load every single element of the list/set */
2126 while(listlen--) {
2127 robj *ele;
2128
f78fd11b 2129 if ((ele = rdbLoadStringObject(fp,rdbver)) == NULL) goto eoferr;
ed9b544e 2130 if (type == REDIS_LIST) {
2131 if (!listAddNodeTail((list*)o->ptr,ele))
2132 oom("listAddNodeTail");
2133 } else {
2134 if (dictAdd((dict*)o->ptr,ele,NULL) == DICT_ERR)
2135 oom("dictAdd");
2136 }
ed9b544e 2137 }
2138 } else {
2139 assert(0 != 0);
2140 }
2141 /* Add the new object in the hash table */
f78fd11b 2142 retval = dictAdd(d,keyobj,o);
ed9b544e 2143 if (retval == DICT_ERR) {
f78fd11b 2144 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj->ptr);
ed9b544e 2145 exit(1);
2146 }
bb32ede5 2147 /* Set the expire time if needed */
2148 if (expiretime != -1) {
2149 setExpire(db,keyobj,expiretime);
2150 /* Delete this key if already expired */
2151 if (expiretime < now) deleteKey(db,keyobj);
2152 expiretime = -1;
2153 }
f78fd11b 2154 keyobj = o = NULL;
ed9b544e 2155 }
2156 fclose(fp);
2157 return REDIS_OK;
2158
2159eoferr: /* unexpected end of file is handled here with a fatal exit */
e3566d4b 2160 if (keyobj) decrRefCount(keyobj);
2161 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, exiting now.");
ed9b544e 2162 exit(1);
2163 return REDIS_ERR; /* Just to avoid warning */
2164}
2165
2166/*================================== Commands =============================== */
2167
abcb223e 2168static void authCommand(redisClient *c) {
2e77c2ee 2169 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
abcb223e
BH
2170 c->authenticated = 1;
2171 addReply(c,shared.ok);
2172 } else {
2173 c->authenticated = 0;
2174 addReply(c,shared.err);
2175 }
2176}
2177
ed9b544e 2178static void pingCommand(redisClient *c) {
2179 addReply(c,shared.pong);
2180}
2181
2182static void echoCommand(redisClient *c) {
c937aa89 2183 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",
ed9b544e 2184 (int)sdslen(c->argv[1]->ptr)));
2185 addReply(c,c->argv[1]);
2186 addReply(c,shared.crlf);
2187}
2188
2189/*=================================== Strings =============================== */
2190
2191static void setGenericCommand(redisClient *c, int nx) {
2192 int retval;
2193
3305306f 2194 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
ed9b544e 2195 if (retval == DICT_ERR) {
2196 if (!nx) {
3305306f 2197 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
ed9b544e 2198 incrRefCount(c->argv[2]);
2199 } else {
c937aa89 2200 addReply(c,shared.czero);
ed9b544e 2201 return;
2202 }
2203 } else {
2204 incrRefCount(c->argv[1]);
2205 incrRefCount(c->argv[2]);
2206 }
2207 server.dirty++;
3305306f 2208 removeExpire(c->db,c->argv[1]);
c937aa89 2209 addReply(c, nx ? shared.cone : shared.ok);
ed9b544e 2210}
2211
2212static void setCommand(redisClient *c) {
a4d1ba9a 2213 setGenericCommand(c,0);
ed9b544e 2214}
2215
2216static void setnxCommand(redisClient *c) {
a4d1ba9a 2217 setGenericCommand(c,1);
ed9b544e 2218}
2219
2220static void getCommand(redisClient *c) {
3305306f 2221 robj *o = lookupKeyRead(c->db,c->argv[1]);
2222
2223 if (o == NULL) {
c937aa89 2224 addReply(c,shared.nullbulk);
ed9b544e 2225 } else {
ed9b544e 2226 if (o->type != REDIS_STRING) {
c937aa89 2227 addReply(c,shared.wrongtypeerr);
ed9b544e 2228 } else {
c937aa89 2229 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o->ptr)));
ed9b544e 2230 addReply(c,o);
2231 addReply(c,shared.crlf);
2232 }
2233 }
2234}
2235
a431eb74 2236static void getSetCommand(redisClient *c) {
2237 getCommand(c);
2238 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
2239 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
2240 } else {
2241 incrRefCount(c->argv[1]);
2242 }
2243 incrRefCount(c->argv[2]);
2244 server.dirty++;
2245 removeExpire(c->db,c->argv[1]);
2246}
2247
70003d28 2248static void mgetCommand(redisClient *c) {
70003d28 2249 int j;
2250
c937aa89 2251 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
70003d28 2252 for (j = 1; j < c->argc; j++) {
3305306f 2253 robj *o = lookupKeyRead(c->db,c->argv[j]);
2254 if (o == NULL) {
c937aa89 2255 addReply(c,shared.nullbulk);
70003d28 2256 } else {
70003d28 2257 if (o->type != REDIS_STRING) {
c937aa89 2258 addReply(c,shared.nullbulk);
70003d28 2259 } else {
c937aa89 2260 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o->ptr)));
70003d28 2261 addReply(c,o);
2262 addReply(c,shared.crlf);
2263 }
2264 }
2265 }
2266}
2267
d68ed120 2268static void incrDecrCommand(redisClient *c, long long incr) {
ed9b544e 2269 long long value;
2270 int retval;
2271 robj *o;
2272
3305306f 2273 o = lookupKeyWrite(c->db,c->argv[1]);
2274 if (o == NULL) {
ed9b544e 2275 value = 0;
2276 } else {
ed9b544e 2277 if (o->type != REDIS_STRING) {
2278 value = 0;
2279 } else {
2280 char *eptr;
2281
2282 value = strtoll(o->ptr, &eptr, 10);
2283 }
2284 }
2285
2286 value += incr;
2287 o = createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",value));
3305306f 2288 retval = dictAdd(c->db->dict,c->argv[1],o);
ed9b544e 2289 if (retval == DICT_ERR) {
3305306f 2290 dictReplace(c->db->dict,c->argv[1],o);
2291 removeExpire(c->db,c->argv[1]);
ed9b544e 2292 } else {
2293 incrRefCount(c->argv[1]);
2294 }
2295 server.dirty++;
c937aa89 2296 addReply(c,shared.colon);
ed9b544e 2297 addReply(c,o);
2298 addReply(c,shared.crlf);
2299}
2300
2301static void incrCommand(redisClient *c) {
a4d1ba9a 2302 incrDecrCommand(c,1);
ed9b544e 2303}
2304
2305static void decrCommand(redisClient *c) {
a4d1ba9a 2306 incrDecrCommand(c,-1);
ed9b544e 2307}
2308
2309static void incrbyCommand(redisClient *c) {
d68ed120 2310 long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
a4d1ba9a 2311 incrDecrCommand(c,incr);
ed9b544e 2312}
2313
2314static void decrbyCommand(redisClient *c) {
d68ed120 2315 long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
a4d1ba9a 2316 incrDecrCommand(c,-incr);
ed9b544e 2317}
2318
2319/* ========================= Type agnostic commands ========================= */
2320
2321static void delCommand(redisClient *c) {
5109cdff 2322 int deleted = 0, j;
2323
2324 for (j = 1; j < c->argc; j++) {
2325 if (deleteKey(c->db,c->argv[j])) {
2326 server.dirty++;
2327 deleted++;
2328 }
2329 }
2330 switch(deleted) {
2331 case 0:
c937aa89 2332 addReply(c,shared.czero);
5109cdff 2333 break;
2334 case 1:
2335 addReply(c,shared.cone);
2336 break;
2337 default:
2338 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",deleted));
2339 break;
ed9b544e 2340 }
2341}
2342
2343static void existsCommand(redisClient *c) {
3305306f 2344 addReply(c,lookupKeyRead(c->db,c->argv[1]) ? shared.cone : shared.czero);
ed9b544e 2345}
2346
2347static void selectCommand(redisClient *c) {
2348 int id = atoi(c->argv[1]->ptr);
2349
2350 if (selectDb(c,id) == REDIS_ERR) {
774e3047 2351 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
ed9b544e 2352 } else {
2353 addReply(c,shared.ok);
2354 }
2355}
2356
2357static void randomkeyCommand(redisClient *c) {
2358 dictEntry *de;
3305306f 2359
2360 while(1) {
2361 de = dictGetRandomKey(c->db->dict);
ce7bef07 2362 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
3305306f 2363 }
ed9b544e 2364 if (de == NULL) {
ce7bef07 2365 addReply(c,shared.plus);
ed9b544e 2366 addReply(c,shared.crlf);
2367 } else {
c937aa89 2368 addReply(c,shared.plus);
ed9b544e 2369 addReply(c,dictGetEntryKey(de));
2370 addReply(c,shared.crlf);
2371 }
2372}
2373
2374static void keysCommand(redisClient *c) {
2375 dictIterator *di;
2376 dictEntry *de;
2377 sds pattern = c->argv[1]->ptr;
2378 int plen = sdslen(pattern);
2379 int numkeys = 0, keyslen = 0;
2380 robj *lenobj = createObject(REDIS_STRING,NULL);
2381
3305306f 2382 di = dictGetIterator(c->db->dict);
ed9b544e 2383 if (!di) oom("dictGetIterator");
2384 addReply(c,lenobj);
2385 decrRefCount(lenobj);
2386 while((de = dictNext(di)) != NULL) {
2387 robj *keyobj = dictGetEntryKey(de);
3305306f 2388
ed9b544e 2389 sds key = keyobj->ptr;
2390 if ((pattern[0] == '*' && pattern[1] == '\0') ||
2391 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
3305306f 2392 if (expireIfNeeded(c->db,keyobj) == 0) {
2393 if (numkeys != 0)
2394 addReply(c,shared.space);
2395 addReply(c,keyobj);
2396 numkeys++;
2397 keyslen += sdslen(key);
2398 }
ed9b544e 2399 }
2400 }
2401 dictReleaseIterator(di);
c937aa89 2402 lenobj->ptr = sdscatprintf(sdsempty(),"$%lu\r\n",keyslen+(numkeys ? (numkeys-1) : 0));
ed9b544e 2403 addReply(c,shared.crlf);
2404}
2405
2406static void dbsizeCommand(redisClient *c) {
2407 addReplySds(c,
3305306f 2408 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
ed9b544e 2409}
2410
2411static void lastsaveCommand(redisClient *c) {
2412 addReplySds(c,
c937aa89 2413 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
ed9b544e 2414}
2415
2416static void typeCommand(redisClient *c) {
3305306f 2417 robj *o;
ed9b544e 2418 char *type;
3305306f 2419
2420 o = lookupKeyRead(c->db,c->argv[1]);
2421 if (o == NULL) {
c937aa89 2422 type = "+none";
ed9b544e 2423 } else {
ed9b544e 2424 switch(o->type) {
c937aa89 2425 case REDIS_STRING: type = "+string"; break;
2426 case REDIS_LIST: type = "+list"; break;
2427 case REDIS_SET: type = "+set"; break;
ed9b544e 2428 default: type = "unknown"; break;
2429 }
2430 }
2431 addReplySds(c,sdsnew(type));
2432 addReply(c,shared.crlf);
2433}
2434
2435static void saveCommand(redisClient *c) {
05557f6d 2436 if (server.bgsaveinprogress) {
2437 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
2438 return;
2439 }
f78fd11b 2440 if (rdbSave(server.dbfilename) == REDIS_OK) {
ed9b544e 2441 addReply(c,shared.ok);
2442 } else {
2443 addReply(c,shared.err);
2444 }
2445}
2446
2447static void bgsaveCommand(redisClient *c) {
2448 if (server.bgsaveinprogress) {
2449 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
2450 return;
2451 }
f78fd11b 2452 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
ed9b544e 2453 addReply(c,shared.ok);
2454 } else {
2455 addReply(c,shared.err);
2456 }
2457}
2458
2459static void shutdownCommand(redisClient *c) {
2460 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
6208b3a7 2461 /* XXX: TODO kill the child if there is a bgsave in progress */
f78fd11b 2462 if (rdbSave(server.dbfilename) == REDIS_OK) {
ed329fcf 2463 if (server.daemonize) {
b284af55 2464 unlink(server.pidfile);
ed329fcf 2465 }
b284af55 2466 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
ed9b544e 2467 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
2468 exit(1);
2469 } else {
2470 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
2471 addReplySds(c,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2472 }
2473}
2474
2475static void renameGenericCommand(redisClient *c, int nx) {
ed9b544e 2476 robj *o;
2477
2478 /* To use the same key as src and dst is probably an error */
2479 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
c937aa89 2480 addReply(c,shared.sameobjecterr);
ed9b544e 2481 return;
2482 }
2483
3305306f 2484 o = lookupKeyWrite(c->db,c->argv[1]);
2485 if (o == NULL) {
c937aa89 2486 addReply(c,shared.nokeyerr);
ed9b544e 2487 return;
2488 }
ed9b544e 2489 incrRefCount(o);
3305306f 2490 deleteIfVolatile(c->db,c->argv[2]);
2491 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
ed9b544e 2492 if (nx) {
2493 decrRefCount(o);
c937aa89 2494 addReply(c,shared.czero);
ed9b544e 2495 return;
2496 }
3305306f 2497 dictReplace(c->db->dict,c->argv[2],o);
ed9b544e 2498 } else {
2499 incrRefCount(c->argv[2]);
2500 }
3305306f 2501 deleteKey(c->db,c->argv[1]);
ed9b544e 2502 server.dirty++;
c937aa89 2503 addReply(c,nx ? shared.cone : shared.ok);
ed9b544e 2504}
2505
2506static void renameCommand(redisClient *c) {
2507 renameGenericCommand(c,0);
2508}
2509
2510static void renamenxCommand(redisClient *c) {
2511 renameGenericCommand(c,1);
2512}
2513
2514static void moveCommand(redisClient *c) {
3305306f 2515 robj *o;
2516 redisDb *src, *dst;
ed9b544e 2517 int srcid;
2518
2519 /* Obtain source and target DB pointers */
3305306f 2520 src = c->db;
2521 srcid = c->db->id;
ed9b544e 2522 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
c937aa89 2523 addReply(c,shared.outofrangeerr);
ed9b544e 2524 return;
2525 }
3305306f 2526 dst = c->db;
2527 selectDb(c,srcid); /* Back to the source DB */
ed9b544e 2528
2529 /* If the user is moving using as target the same
2530 * DB as the source DB it is probably an error. */
2531 if (src == dst) {
c937aa89 2532 addReply(c,shared.sameobjecterr);
ed9b544e 2533 return;
2534 }
2535
2536 /* Check if the element exists and get a reference */
3305306f 2537 o = lookupKeyWrite(c->db,c->argv[1]);
2538 if (!o) {
c937aa89 2539 addReply(c,shared.czero);
ed9b544e 2540 return;
2541 }
2542
2543 /* Try to add the element to the target DB */
3305306f 2544 deleteIfVolatile(dst,c->argv[1]);
2545 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
c937aa89 2546 addReply(c,shared.czero);
ed9b544e 2547 return;
2548 }
3305306f 2549 incrRefCount(c->argv[1]);
ed9b544e 2550 incrRefCount(o);
2551
2552 /* OK! key moved, free the entry in the source DB */
3305306f 2553 deleteKey(src,c->argv[1]);
ed9b544e 2554 server.dirty++;
c937aa89 2555 addReply(c,shared.cone);
ed9b544e 2556}
2557
2558/* =================================== Lists ================================ */
2559static void pushGenericCommand(redisClient *c, int where) {
2560 robj *lobj;
ed9b544e 2561 list *list;
3305306f 2562
2563 lobj = lookupKeyWrite(c->db,c->argv[1]);
2564 if (lobj == NULL) {
ed9b544e 2565 lobj = createListObject();
2566 list = lobj->ptr;
2567 if (where == REDIS_HEAD) {
2568 if (!listAddNodeHead(list,c->argv[2])) oom("listAddNodeHead");
2569 } else {
2570 if (!listAddNodeTail(list,c->argv[2])) oom("listAddNodeTail");
2571 }
3305306f 2572 dictAdd(c->db->dict,c->argv[1],lobj);
ed9b544e 2573 incrRefCount(c->argv[1]);
2574 incrRefCount(c->argv[2]);
2575 } else {
ed9b544e 2576 if (lobj->type != REDIS_LIST) {
2577 addReply(c,shared.wrongtypeerr);
2578 return;
2579 }
2580 list = lobj->ptr;
2581 if (where == REDIS_HEAD) {
2582 if (!listAddNodeHead(list,c->argv[2])) oom("listAddNodeHead");
2583 } else {
2584 if (!listAddNodeTail(list,c->argv[2])) oom("listAddNodeTail");
2585 }
2586 incrRefCount(c->argv[2]);
2587 }
2588 server.dirty++;
2589 addReply(c,shared.ok);
2590}
2591
2592static void lpushCommand(redisClient *c) {
2593 pushGenericCommand(c,REDIS_HEAD);
2594}
2595
2596static void rpushCommand(redisClient *c) {
2597 pushGenericCommand(c,REDIS_TAIL);
2598}
2599
2600static void llenCommand(redisClient *c) {
3305306f 2601 robj *o;
ed9b544e 2602 list *l;
2603
3305306f 2604 o = lookupKeyRead(c->db,c->argv[1]);
2605 if (o == NULL) {
c937aa89 2606 addReply(c,shared.czero);
ed9b544e 2607 return;
2608 } else {
ed9b544e 2609 if (o->type != REDIS_LIST) {
c937aa89 2610 addReply(c,shared.wrongtypeerr);
ed9b544e 2611 } else {
2612 l = o->ptr;
c937aa89 2613 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",listLength(l)));
ed9b544e 2614 }
2615 }
2616}
2617
2618static void lindexCommand(redisClient *c) {
3305306f 2619 robj *o;
ed9b544e 2620 int index = atoi(c->argv[2]->ptr);
2621
3305306f 2622 o = lookupKeyRead(c->db,c->argv[1]);
2623 if (o == NULL) {
c937aa89 2624 addReply(c,shared.nullbulk);
ed9b544e 2625 } else {
ed9b544e 2626 if (o->type != REDIS_LIST) {
c937aa89 2627 addReply(c,shared.wrongtypeerr);
ed9b544e 2628 } else {
2629 list *list = o->ptr;
2630 listNode *ln;
2631
2632 ln = listIndex(list, index);
2633 if (ln == NULL) {
c937aa89 2634 addReply(c,shared.nullbulk);
ed9b544e 2635 } else {
2636 robj *ele = listNodeValue(ln);
c937aa89 2637 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele->ptr)));
ed9b544e 2638 addReply(c,ele);
2639 addReply(c,shared.crlf);
2640 }
2641 }
2642 }
2643}
2644
2645static void lsetCommand(redisClient *c) {
3305306f 2646 robj *o;
ed9b544e 2647 int index = atoi(c->argv[2]->ptr);
2648
3305306f 2649 o = lookupKeyWrite(c->db,c->argv[1]);
2650 if (o == NULL) {
ed9b544e 2651 addReply(c,shared.nokeyerr);
2652 } else {
ed9b544e 2653 if (o->type != REDIS_LIST) {
2654 addReply(c,shared.wrongtypeerr);
2655 } else {
2656 list *list = o->ptr;
2657 listNode *ln;
2658
2659 ln = listIndex(list, index);
2660 if (ln == NULL) {
c937aa89 2661 addReply(c,shared.outofrangeerr);
ed9b544e 2662 } else {
2663 robj *ele = listNodeValue(ln);
2664
2665 decrRefCount(ele);
2666 listNodeValue(ln) = c->argv[3];
2667 incrRefCount(c->argv[3]);
2668 addReply(c,shared.ok);
2669 server.dirty++;
2670 }
2671 }
2672 }
2673}
2674
2675static void popGenericCommand(redisClient *c, int where) {
3305306f 2676 robj *o;
2677
2678 o = lookupKeyWrite(c->db,c->argv[1]);
2679 if (o == NULL) {
c937aa89 2680 addReply(c,shared.nullbulk);
ed9b544e 2681 } else {
ed9b544e 2682 if (o->type != REDIS_LIST) {
c937aa89 2683 addReply(c,shared.wrongtypeerr);
ed9b544e 2684 } else {
2685 list *list = o->ptr;
2686 listNode *ln;
2687
2688 if (where == REDIS_HEAD)
2689 ln = listFirst(list);
2690 else
2691 ln = listLast(list);
2692
2693 if (ln == NULL) {
c937aa89 2694 addReply(c,shared.nullbulk);
ed9b544e 2695 } else {
2696 robj *ele = listNodeValue(ln);
c937aa89 2697 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele->ptr)));
ed9b544e 2698 addReply(c,ele);
2699 addReply(c,shared.crlf);
2700 listDelNode(list,ln);
2701 server.dirty++;
2702 }
2703 }
2704 }
2705}
2706
2707static void lpopCommand(redisClient *c) {
2708 popGenericCommand(c,REDIS_HEAD);
2709}
2710
2711static void rpopCommand(redisClient *c) {
2712 popGenericCommand(c,REDIS_TAIL);
2713}
2714
2715static void lrangeCommand(redisClient *c) {
3305306f 2716 robj *o;
ed9b544e 2717 int start = atoi(c->argv[2]->ptr);
2718 int end = atoi(c->argv[3]->ptr);
3305306f 2719
2720 o = lookupKeyRead(c->db,c->argv[1]);
2721 if (o == NULL) {
c937aa89 2722 addReply(c,shared.nullmultibulk);
ed9b544e 2723 } else {
ed9b544e 2724 if (o->type != REDIS_LIST) {
c937aa89 2725 addReply(c,shared.wrongtypeerr);
ed9b544e 2726 } else {
2727 list *list = o->ptr;
2728 listNode *ln;
2729 int llen = listLength(list);
2730 int rangelen, j;
2731 robj *ele;
2732
2733 /* convert negative indexes */
2734 if (start < 0) start = llen+start;
2735 if (end < 0) end = llen+end;
2736 if (start < 0) start = 0;
2737 if (end < 0) end = 0;
2738
2739 /* indexes sanity checks */
2740 if (start > end || start >= llen) {
2741 /* Out of range start or start > end result in empty list */
c937aa89 2742 addReply(c,shared.emptymultibulk);
ed9b544e 2743 return;
2744 }
2745 if (end >= llen) end = llen-1;
2746 rangelen = (end-start)+1;
2747
2748 /* Return the result in form of a multi-bulk reply */
2749 ln = listIndex(list, start);
c937aa89 2750 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
ed9b544e 2751 for (j = 0; j < rangelen; j++) {
2752 ele = listNodeValue(ln);
c937aa89 2753 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele->ptr)));
ed9b544e 2754 addReply(c,ele);
2755 addReply(c,shared.crlf);
2756 ln = ln->next;
2757 }
2758 }
2759 }
2760}
2761
2762static void ltrimCommand(redisClient *c) {
3305306f 2763 robj *o;
ed9b544e 2764 int start = atoi(c->argv[2]->ptr);
2765 int end = atoi(c->argv[3]->ptr);
2766
3305306f 2767 o = lookupKeyWrite(c->db,c->argv[1]);
2768 if (o == NULL) {
ed9b544e 2769 addReply(c,shared.nokeyerr);
2770 } else {
ed9b544e 2771 if (o->type != REDIS_LIST) {
2772 addReply(c,shared.wrongtypeerr);
2773 } else {
2774 list *list = o->ptr;
2775 listNode *ln;
2776 int llen = listLength(list);
2777 int j, ltrim, rtrim;
2778
2779 /* convert negative indexes */
2780 if (start < 0) start = llen+start;
2781 if (end < 0) end = llen+end;
2782 if (start < 0) start = 0;
2783 if (end < 0) end = 0;
2784
2785 /* indexes sanity checks */
2786 if (start > end || start >= llen) {
2787 /* Out of range start or start > end result in empty list */
2788 ltrim = llen;
2789 rtrim = 0;
2790 } else {
2791 if (end >= llen) end = llen-1;
2792 ltrim = start;
2793 rtrim = llen-end-1;
2794 }
2795
2796 /* Remove list elements to perform the trim */
2797 for (j = 0; j < ltrim; j++) {
2798 ln = listFirst(list);
2799 listDelNode(list,ln);
2800 }
2801 for (j = 0; j < rtrim; j++) {
2802 ln = listLast(list);
2803 listDelNode(list,ln);
2804 }
2805 addReply(c,shared.ok);
2806 server.dirty++;
2807 }
2808 }
2809}
2810
2811static void lremCommand(redisClient *c) {
3305306f 2812 robj *o;
ed9b544e 2813
3305306f 2814 o = lookupKeyWrite(c->db,c->argv[1]);
2815 if (o == NULL) {
7b45bfb2 2816 addReply(c,shared.nokeyerr);
ed9b544e 2817 } else {
ed9b544e 2818 if (o->type != REDIS_LIST) {
c937aa89 2819 addReply(c,shared.wrongtypeerr);
ed9b544e 2820 } else {
2821 list *list = o->ptr;
2822 listNode *ln, *next;
2823 int toremove = atoi(c->argv[2]->ptr);
2824 int removed = 0;
2825 int fromtail = 0;
2826
2827 if (toremove < 0) {
2828 toremove = -toremove;
2829 fromtail = 1;
2830 }
2831 ln = fromtail ? list->tail : list->head;
2832 while (ln) {
ed9b544e 2833 robj *ele = listNodeValue(ln);
a4d1ba9a 2834
2835 next = fromtail ? ln->prev : ln->next;
ed9b544e 2836 if (sdscmp(ele->ptr,c->argv[3]->ptr) == 0) {
2837 listDelNode(list,ln);
2838 server.dirty++;
2839 removed++;
2840 if (toremove && removed == toremove) break;
2841 }
2842 ln = next;
2843 }
c937aa89 2844 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
ed9b544e 2845 }
2846 }
2847}
2848
2849/* ==================================== Sets ================================ */
2850
2851static void saddCommand(redisClient *c) {
ed9b544e 2852 robj *set;
2853
3305306f 2854 set = lookupKeyWrite(c->db,c->argv[1]);
2855 if (set == NULL) {
ed9b544e 2856 set = createSetObject();
3305306f 2857 dictAdd(c->db->dict,c->argv[1],set);
ed9b544e 2858 incrRefCount(c->argv[1]);
2859 } else {
ed9b544e 2860 if (set->type != REDIS_SET) {
c937aa89 2861 addReply(c,shared.wrongtypeerr);
ed9b544e 2862 return;
2863 }
2864 }
2865 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
2866 incrRefCount(c->argv[2]);
2867 server.dirty++;
c937aa89 2868 addReply(c,shared.cone);
ed9b544e 2869 } else {
c937aa89 2870 addReply(c,shared.czero);
ed9b544e 2871 }
2872}
2873
2874static void sremCommand(redisClient *c) {
3305306f 2875 robj *set;
ed9b544e 2876
3305306f 2877 set = lookupKeyWrite(c->db,c->argv[1]);
2878 if (set == NULL) {
c937aa89 2879 addReply(c,shared.czero);
ed9b544e 2880 } else {
ed9b544e 2881 if (set->type != REDIS_SET) {
c937aa89 2882 addReply(c,shared.wrongtypeerr);
ed9b544e 2883 return;
2884 }
2885 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
2886 server.dirty++;
c937aa89 2887 addReply(c,shared.cone);
ed9b544e 2888 } else {
c937aa89 2889 addReply(c,shared.czero);
ed9b544e 2890 }
2891 }
2892}
2893
a4460ef4 2894static void smoveCommand(redisClient *c) {
2895 robj *srcset, *dstset;
2896
2897 srcset = lookupKeyWrite(c->db,c->argv[1]);
2898 dstset = lookupKeyWrite(c->db,c->argv[2]);
2899
2900 /* If the source key does not exist return 0, if it's of the wrong type
2901 * raise an error */
2902 if (srcset == NULL || srcset->type != REDIS_SET) {
2903 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
2904 return;
2905 }
2906 /* Error if the destination key is not a set as well */
2907 if (dstset && dstset->type != REDIS_SET) {
2908 addReply(c,shared.wrongtypeerr);
2909 return;
2910 }
2911 /* Remove the element from the source set */
2912 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
2913 /* Key not found in the src set! return zero */
2914 addReply(c,shared.czero);
2915 return;
2916 }
2917 server.dirty++;
2918 /* Add the element to the destination set */
2919 if (!dstset) {
2920 dstset = createSetObject();
2921 dictAdd(c->db->dict,c->argv[2],dstset);
2922 incrRefCount(c->argv[2]);
2923 }
2924 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
2925 incrRefCount(c->argv[3]);
2926 addReply(c,shared.cone);
2927}
2928
ed9b544e 2929static void sismemberCommand(redisClient *c) {
3305306f 2930 robj *set;
ed9b544e 2931
3305306f 2932 set = lookupKeyRead(c->db,c->argv[1]);
2933 if (set == NULL) {
c937aa89 2934 addReply(c,shared.czero);
ed9b544e 2935 } else {
ed9b544e 2936 if (set->type != REDIS_SET) {
c937aa89 2937 addReply(c,shared.wrongtypeerr);
ed9b544e 2938 return;
2939 }
2940 if (dictFind(set->ptr,c->argv[2]))
c937aa89 2941 addReply(c,shared.cone);
ed9b544e 2942 else
c937aa89 2943 addReply(c,shared.czero);
ed9b544e 2944 }
2945}
2946
2947static void scardCommand(redisClient *c) {
3305306f 2948 robj *o;
ed9b544e 2949 dict *s;
2950
3305306f 2951 o = lookupKeyRead(c->db,c->argv[1]);
2952 if (o == NULL) {
c937aa89 2953 addReply(c,shared.czero);
ed9b544e 2954 return;
2955 } else {
ed9b544e 2956 if (o->type != REDIS_SET) {
c937aa89 2957 addReply(c,shared.wrongtypeerr);
ed9b544e 2958 } else {
2959 s = o->ptr;
c937aa89 2960 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",
3305306f 2961 dictSize(s)));
ed9b544e 2962 }
2963 }
2964}
2965
2966static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
2967 dict **d1 = (void*) s1, **d2 = (void*) s2;
2968
3305306f 2969 return dictSize(*d1)-dictSize(*d2);
ed9b544e 2970}
2971
2972static void sinterGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey) {
2973 dict **dv = zmalloc(sizeof(dict*)*setsnum);
2974 dictIterator *di;
2975 dictEntry *de;
2976 robj *lenobj = NULL, *dstset = NULL;
2977 int j, cardinality = 0;
2978
3ba37089 2979 if (!dv) oom("sinterGenericCommand");
ed9b544e 2980 for (j = 0; j < setsnum; j++) {
2981 robj *setobj;
3305306f 2982
2983 setobj = dstkey ?
2984 lookupKeyWrite(c->db,setskeys[j]) :
2985 lookupKeyRead(c->db,setskeys[j]);
2986 if (!setobj) {
ed9b544e 2987 zfree(dv);
5faa6025 2988 if (dstkey) {
2989 deleteKey(c->db,dstkey);
2990 addReply(c,shared.ok);
2991 } else {
2992 addReply(c,shared.nullmultibulk);
2993 }
ed9b544e 2994 return;
2995 }
ed9b544e 2996 if (setobj->type != REDIS_SET) {
2997 zfree(dv);
c937aa89 2998 addReply(c,shared.wrongtypeerr);
ed9b544e 2999 return;
3000 }
3001 dv[j] = setobj->ptr;
3002 }
3003 /* Sort sets from the smallest to largest, this will improve our
3004 * algorithm's performace */
3005 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
3006
3007 /* The first thing we should output is the total number of elements...
3008 * since this is a multi-bulk write, but at this stage we don't know
3009 * the intersection set size, so we use a trick, append an empty object
3010 * to the output list and save the pointer to later modify it with the
3011 * right length */
3012 if (!dstkey) {
3013 lenobj = createObject(REDIS_STRING,NULL);
3014 addReply(c,lenobj);
3015 decrRefCount(lenobj);
3016 } else {
3017 /* If we have a target key where to store the resulting set
3018 * create this key with an empty set inside */
3019 dstset = createSetObject();
ed9b544e 3020 }
3021
3022 /* Iterate all the elements of the first (smallest) set, and test
3023 * the element against all the other sets, if at least one set does
3024 * not include the element it is discarded */
3025 di = dictGetIterator(dv[0]);
3026 if (!di) oom("dictGetIterator");
3027
3028 while((de = dictNext(di)) != NULL) {
3029 robj *ele;
3030
3031 for (j = 1; j < setsnum; j++)
3032 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
3033 if (j != setsnum)
3034 continue; /* at least one set does not contain the member */
3035 ele = dictGetEntryKey(de);
3036 if (!dstkey) {
c937aa89 3037 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele->ptr)));
ed9b544e 3038 addReply(c,ele);
3039 addReply(c,shared.crlf);
3040 cardinality++;
3041 } else {
3042 dictAdd(dstset->ptr,ele,NULL);
3043 incrRefCount(ele);
3044 }
3045 }
3046 dictReleaseIterator(di);
3047
83cdfe18
AG
3048 if (dstkey) {
3049 /* Store the resulting set into the target */
3050 deleteKey(c->db,dstkey);
3051 dictAdd(c->db->dict,dstkey,dstset);
3052 incrRefCount(dstkey);
3053 }
3054
40d224a9 3055 if (!dstkey) {
c937aa89 3056 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",cardinality);
40d224a9 3057 } else {
03fd01c7 3058 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",
3059 dictSize((dict*)dstset->ptr)));
40d224a9 3060 server.dirty++;
3061 }
ed9b544e 3062 zfree(dv);
3063}
3064
3065static void sinterCommand(redisClient *c) {
3066 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
3067}
3068
3069static void sinterstoreCommand(redisClient *c) {
3070 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
3071}
3072
f4f56e1d 3073#define REDIS_OP_UNION 0
3074#define REDIS_OP_DIFF 1
3075
3076static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
40d224a9 3077 dict **dv = zmalloc(sizeof(dict*)*setsnum);
3078 dictIterator *di;
3079 dictEntry *de;
f4f56e1d 3080 robj *dstset = NULL;
40d224a9 3081 int j, cardinality = 0;
3082
f4f56e1d 3083 if (!dv) oom("sunionDiffGenericCommand");
40d224a9 3084 for (j = 0; j < setsnum; j++) {
3085 robj *setobj;
3086
3087 setobj = dstkey ?
3088 lookupKeyWrite(c->db,setskeys[j]) :
3089 lookupKeyRead(c->db,setskeys[j]);
3090 if (!setobj) {
3091 dv[j] = NULL;
3092 continue;
3093 }
3094 if (setobj->type != REDIS_SET) {
3095 zfree(dv);
3096 addReply(c,shared.wrongtypeerr);
3097 return;
3098 }
3099 dv[j] = setobj->ptr;
3100 }
3101
3102 /* We need a temp set object to store our union. If the dstkey
3103 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
3104 * this set object will be the resulting object to set into the target key*/
3105 dstset = createSetObject();
3106
40d224a9 3107 /* Iterate all the elements of all the sets, add every element a single
3108 * time to the result set */
3109 for (j = 0; j < setsnum; j++) {
51829ed3 3110 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
40d224a9 3111 if (!dv[j]) continue; /* non existing keys are like empty sets */
3112
3113 di = dictGetIterator(dv[j]);
3114 if (!di) oom("dictGetIterator");
3115
3116 while((de = dictNext(di)) != NULL) {
3117 robj *ele;
3118
3119 /* dictAdd will not add the same element multiple times */
3120 ele = dictGetEntryKey(de);
f4f56e1d 3121 if (op == REDIS_OP_UNION || j == 0) {
3122 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
3123 incrRefCount(ele);
40d224a9 3124 cardinality++;
3125 }
f4f56e1d 3126 } else if (op == REDIS_OP_DIFF) {
3127 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
3128 cardinality--;
3129 }
40d224a9 3130 }
3131 }
3132 dictReleaseIterator(di);
51829ed3
AG
3133
3134 if (op == REDIS_OP_DIFF && cardinality == 0) break; /* result set is empty */
40d224a9 3135 }
3136
f4f56e1d 3137 /* Output the content of the resulting set, if not in STORE mode */
3138 if (!dstkey) {
3139 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
3140 di = dictGetIterator(dstset->ptr);
3141 if (!di) oom("dictGetIterator");
3142 while((de = dictNext(di)) != NULL) {
3143 robj *ele;
3144
3145 ele = dictGetEntryKey(de);
3146 addReplySds(c,sdscatprintf(sdsempty(),
3147 "$%d\r\n",sdslen(ele->ptr)));
3148 addReply(c,ele);
3149 addReply(c,shared.crlf);
3150 }
3151 dictReleaseIterator(di);
83cdfe18
AG
3152 } else {
3153 /* If we have a target key where to store the resulting set
3154 * create this key with the result set inside */
3155 deleteKey(c->db,dstkey);
3156 dictAdd(c->db->dict,dstkey,dstset);
3157 incrRefCount(dstkey);
f4f56e1d 3158 }
3159
3160 /* Cleanup */
40d224a9 3161 if (!dstkey) {
40d224a9 3162 decrRefCount(dstset);
3163 } else {
03fd01c7 3164 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",
3165 dictSize((dict*)dstset->ptr)));
40d224a9 3166 server.dirty++;
3167 }
3168 zfree(dv);
3169}
3170
3171static void sunionCommand(redisClient *c) {
f4f56e1d 3172 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
40d224a9 3173}
3174
3175static void sunionstoreCommand(redisClient *c) {
f4f56e1d 3176 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
3177}
3178
3179static void sdiffCommand(redisClient *c) {
3180 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
3181}
3182
3183static void sdiffstoreCommand(redisClient *c) {
3184 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
40d224a9 3185}
3186
ed9b544e 3187static void flushdbCommand(redisClient *c) {
ca37e9cd 3188 server.dirty += dictSize(c->db->dict);
3305306f 3189 dictEmpty(c->db->dict);
3190 dictEmpty(c->db->expires);
ed9b544e 3191 addReply(c,shared.ok);
ed9b544e 3192}
3193
3194static void flushallCommand(redisClient *c) {
ca37e9cd 3195 server.dirty += emptyDb();
ed9b544e 3196 addReply(c,shared.ok);
f78fd11b 3197 rdbSave(server.dbfilename);
ca37e9cd 3198 server.dirty++;
ed9b544e 3199}
3200
3201redisSortOperation *createSortOperation(int type, robj *pattern) {
3202 redisSortOperation *so = zmalloc(sizeof(*so));
3203 if (!so) oom("createSortOperation");
3204 so->type = type;
3205 so->pattern = pattern;
3206 return so;
3207}
3208
3209/* Return the value associated to the key with a name obtained
3210 * substituting the first occurence of '*' in 'pattern' with 'subst' */
3305306f 3211robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
ed9b544e 3212 char *p;
3213 sds spat, ssub;
3214 robj keyobj;
3215 int prefixlen, sublen, postfixlen;
ed9b544e 3216 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
3217 struct {
3218 long len;
3219 long free;
3220 char buf[REDIS_SORTKEY_MAX+1];
3221 } keyname;
3222
ed9b544e 3223 spat = pattern->ptr;
3224 ssub = subst->ptr;
3225 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
3226 p = strchr(spat,'*');
3227 if (!p) return NULL;
3228
3229 prefixlen = p-spat;
3230 sublen = sdslen(ssub);
3231 postfixlen = sdslen(spat)-(prefixlen+1);
3232 memcpy(keyname.buf,spat,prefixlen);
3233 memcpy(keyname.buf+prefixlen,ssub,sublen);
3234 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
3235 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
3236 keyname.len = prefixlen+sublen+postfixlen;
3237
3238 keyobj.refcount = 1;
3239 keyobj.type = REDIS_STRING;
3240 keyobj.ptr = ((char*)&keyname)+(sizeof(long)*2);
3241
a4d1ba9a 3242 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
3305306f 3243 return lookupKeyRead(db,&keyobj);
ed9b544e 3244}
3245
3246/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
3247 * the additional parameter is not standard but a BSD-specific we have to
3248 * pass sorting parameters via the global 'server' structure */
3249static int sortCompare(const void *s1, const void *s2) {
3250 const redisSortObject *so1 = s1, *so2 = s2;
3251 int cmp;
3252
3253 if (!server.sort_alpha) {
3254 /* Numeric sorting. Here it's trivial as we precomputed scores */
3255 if (so1->u.score > so2->u.score) {
3256 cmp = 1;
3257 } else if (so1->u.score < so2->u.score) {
3258 cmp = -1;
3259 } else {
3260 cmp = 0;
3261 }
3262 } else {
3263 /* Alphanumeric sorting */
3264 if (server.sort_bypattern) {
3265 if (!so1->u.cmpobj || !so2->u.cmpobj) {
3266 /* At least one compare object is NULL */
3267 if (so1->u.cmpobj == so2->u.cmpobj)
3268 cmp = 0;
3269 else if (so1->u.cmpobj == NULL)
3270 cmp = -1;
3271 else
3272 cmp = 1;
3273 } else {
3274 /* We have both the objects, use strcoll */
3275 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
3276 }
3277 } else {
3278 /* Compare elements directly */
3279 cmp = strcoll(so1->obj->ptr,so2->obj->ptr);
3280 }
3281 }
3282 return server.sort_desc ? -cmp : cmp;
3283}
3284
3285/* The SORT command is the most complex command in Redis. Warning: this code
3286 * is optimized for speed and a bit less for readability */
3287static void sortCommand(redisClient *c) {
ed9b544e 3288 list *operations;
3289 int outputlen = 0;
3290 int desc = 0, alpha = 0;
3291 int limit_start = 0, limit_count = -1, start, end;
3292 int j, dontsort = 0, vectorlen;
3293 int getop = 0; /* GET operation counter */
3294 robj *sortval, *sortby = NULL;
3295 redisSortObject *vector; /* Resulting vector to sort */
3296
3297 /* Lookup the key to sort. It must be of the right types */
3305306f 3298 sortval = lookupKeyRead(c->db,c->argv[1]);
3299 if (sortval == NULL) {
c937aa89 3300 addReply(c,shared.nokeyerr);
ed9b544e 3301 return;
3302 }
ed9b544e 3303 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST) {
c937aa89 3304 addReply(c,shared.wrongtypeerr);
ed9b544e 3305 return;
3306 }
3307
3308 /* Create a list of operations to perform for every sorted element.
3309 * Operations can be GET/DEL/INCR/DECR */
3310 operations = listCreate();
092dac2a 3311 listSetFreeMethod(operations,zfree);
ed9b544e 3312 j = 2;
3313
3314 /* Now we need to protect sortval incrementing its count, in the future
3315 * SORT may have options able to overwrite/delete keys during the sorting
3316 * and the sorted key itself may get destroied */
3317 incrRefCount(sortval);
3318
3319 /* The SORT command has an SQL-alike syntax, parse it */
3320 while(j < c->argc) {
3321 int leftargs = c->argc-j-1;
3322 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
3323 desc = 0;
3324 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
3325 desc = 1;
3326 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
3327 alpha = 1;
3328 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
3329 limit_start = atoi(c->argv[j+1]->ptr);
3330 limit_count = atoi(c->argv[j+2]->ptr);
3331 j+=2;
3332 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
3333 sortby = c->argv[j+1];
3334 /* If the BY pattern does not contain '*', i.e. it is constant,
3335 * we don't need to sort nor to lookup the weight keys. */
3336 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
3337 j++;
3338 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
3339 listAddNodeTail(operations,createSortOperation(
3340 REDIS_SORT_GET,c->argv[j+1]));
3341 getop++;
3342 j++;
3343 } else if (!strcasecmp(c->argv[j]->ptr,"del") && leftargs >= 1) {
3344 listAddNodeTail(operations,createSortOperation(
3345 REDIS_SORT_DEL,c->argv[j+1]));
3346 j++;
3347 } else if (!strcasecmp(c->argv[j]->ptr,"incr") && leftargs >= 1) {
3348 listAddNodeTail(operations,createSortOperation(
3349 REDIS_SORT_INCR,c->argv[j+1]));
3350 j++;
3351 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
3352 listAddNodeTail(operations,createSortOperation(
3353 REDIS_SORT_DECR,c->argv[j+1]));
3354 j++;
3355 } else {
3356 decrRefCount(sortval);
3357 listRelease(operations);
c937aa89 3358 addReply(c,shared.syntaxerr);
ed9b544e 3359 return;
3360 }
3361 j++;
3362 }
3363
3364 /* Load the sorting vector with all the objects to sort */
3365 vectorlen = (sortval->type == REDIS_LIST) ?
3366 listLength((list*)sortval->ptr) :
3305306f 3367 dictSize((dict*)sortval->ptr);
ed9b544e 3368 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
3369 if (!vector) oom("allocating objects vector for SORT");
3370 j = 0;
3371 if (sortval->type == REDIS_LIST) {
3372 list *list = sortval->ptr;
6208b3a7 3373 listNode *ln;
3374
3375 listRewind(list);
3376 while((ln = listYield(list))) {
ed9b544e 3377 robj *ele = ln->value;
3378 vector[j].obj = ele;
3379 vector[j].u.score = 0;
3380 vector[j].u.cmpobj = NULL;
ed9b544e 3381 j++;
3382 }
3383 } else {
3384 dict *set = sortval->ptr;
3385 dictIterator *di;
3386 dictEntry *setele;
3387
3388 di = dictGetIterator(set);
3389 if (!di) oom("dictGetIterator");
3390 while((setele = dictNext(di)) != NULL) {
3391 vector[j].obj = dictGetEntryKey(setele);
3392 vector[j].u.score = 0;
3393 vector[j].u.cmpobj = NULL;
3394 j++;
3395 }
3396 dictReleaseIterator(di);
3397 }
3398 assert(j == vectorlen);
3399
3400 /* Now it's time to load the right scores in the sorting vector */
3401 if (dontsort == 0) {
3402 for (j = 0; j < vectorlen; j++) {
3403 if (sortby) {
3404 robj *byval;
3405
3305306f 3406 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
ed9b544e 3407 if (!byval || byval->type != REDIS_STRING) continue;
3408 if (alpha) {
3409 vector[j].u.cmpobj = byval;
3410 incrRefCount(byval);
3411 } else {
3412 vector[j].u.score = strtod(byval->ptr,NULL);
3413 }
3414 } else {
3415 if (!alpha) vector[j].u.score = strtod(vector[j].obj->ptr,NULL);
3416 }
3417 }
3418 }
3419
3420 /* We are ready to sort the vector... perform a bit of sanity check
3421 * on the LIMIT option too. We'll use a partial version of quicksort. */
3422 start = (limit_start < 0) ? 0 : limit_start;
3423 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
3424 if (start >= vectorlen) {
3425 start = vectorlen-1;
3426 end = vectorlen-2;
3427 }
3428 if (end >= vectorlen) end = vectorlen-1;
3429
3430 if (dontsort == 0) {
3431 server.sort_desc = desc;
3432 server.sort_alpha = alpha;
3433 server.sort_bypattern = sortby ? 1 : 0;
5f5b9840 3434 if (sortby && (start != 0 || end != vectorlen-1))
3435 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
3436 else
3437 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
ed9b544e 3438 }
3439
3440 /* Send command output to the output buffer, performing the specified
3441 * GET/DEL/INCR/DECR operations if any. */
3442 outputlen = getop ? getop*(end-start+1) : end-start+1;
c937aa89 3443 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
ed9b544e 3444 for (j = start; j <= end; j++) {
6208b3a7 3445 listNode *ln;
ed9b544e 3446 if (!getop) {
c937aa89 3447 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",
ed9b544e 3448 sdslen(vector[j].obj->ptr)));
3449 addReply(c,vector[j].obj);
3450 addReply(c,shared.crlf);
3451 }
6208b3a7 3452 listRewind(operations);
3453 while((ln = listYield(operations))) {
ed9b544e 3454 redisSortOperation *sop = ln->value;
3305306f 3455 robj *val = lookupKeyByPattern(c->db,sop->pattern,
ed9b544e 3456 vector[j].obj);
3457
3458 if (sop->type == REDIS_SORT_GET) {
3459 if (!val || val->type != REDIS_STRING) {
9eb00f21 3460 addReply(c,shared.nullbulk);
ed9b544e 3461 } else {
c937aa89 3462 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",
ed9b544e 3463 sdslen(val->ptr)));
3464 addReply(c,val);
3465 addReply(c,shared.crlf);
3466 }
3467 } else if (sop->type == REDIS_SORT_DEL) {
3468 /* TODO */
3469 }
ed9b544e 3470 }
3471 }
3472
3473 /* Cleanup */
3474 decrRefCount(sortval);
3475 listRelease(operations);
3476 for (j = 0; j < vectorlen; j++) {
3477 if (sortby && alpha && vector[j].u.cmpobj)
3478 decrRefCount(vector[j].u.cmpobj);
3479 }
3480 zfree(vector);
3481}
3482
3483static void infoCommand(redisClient *c) {
3484 sds info;
3485 time_t uptime = time(NULL)-server.stat_starttime;
3486
3487 info = sdscatprintf(sdsempty(),
3488 "redis_version:%s\r\n"
3489 "connected_clients:%d\r\n"
3490 "connected_slaves:%d\r\n"
5fba9f71 3491 "used_memory:%zu\r\n"
ed9b544e 3492 "changes_since_last_save:%lld\r\n"
be2bb6b0 3493 "bgsave_in_progress:%d\r\n"
ed9b544e 3494 "last_save_time:%d\r\n"
3495 "total_connections_received:%lld\r\n"
3496 "total_commands_processed:%lld\r\n"
3497 "uptime_in_seconds:%d\r\n"
3498 "uptime_in_days:%d\r\n"
3499 ,REDIS_VERSION,
3500 listLength(server.clients)-listLength(server.slaves),
3501 listLength(server.slaves),
3502 server.usedmemory,
3503 server.dirty,
be2bb6b0 3504 server.bgsaveinprogress,
ed9b544e 3505 server.lastsave,
3506 server.stat_numconnections,
3507 server.stat_numcommands,
3508 uptime,
3509 uptime/(3600*24)
3510 );
c937aa89 3511 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info)));
ed9b544e 3512 addReplySds(c,info);
70003d28 3513 addReply(c,shared.crlf);
ed9b544e 3514}
3515
3305306f 3516static void monitorCommand(redisClient *c) {
3517 /* ignore MONITOR if aleady slave or in monitor mode */
3518 if (c->flags & REDIS_SLAVE) return;
3519
3520 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
3521 c->slaveseldb = 0;
3522 if (!listAddNodeTail(server.monitors,c)) oom("listAddNodeTail");
3523 addReply(c,shared.ok);
3524}
3525
3526/* ================================= Expire ================================= */
3527static int removeExpire(redisDb *db, robj *key) {
3528 if (dictDelete(db->expires,key) == DICT_OK) {
3529 return 1;
3530 } else {
3531 return 0;
3532 }
3533}
3534
3535static int setExpire(redisDb *db, robj *key, time_t when) {
3536 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
3537 return 0;
3538 } else {
3539 incrRefCount(key);
3540 return 1;
3541 }
3542}
3543
bb32ede5 3544/* Return the expire time of the specified key, or -1 if no expire
3545 * is associated with this key (i.e. the key is non volatile) */
3546static time_t getExpire(redisDb *db, robj *key) {
3547 dictEntry *de;
3548
3549 /* No expire? return ASAP */
3550 if (dictSize(db->expires) == 0 ||
3551 (de = dictFind(db->expires,key)) == NULL) return -1;
3552
3553 return (time_t) dictGetEntryVal(de);
3554}
3555
3305306f 3556static int expireIfNeeded(redisDb *db, robj *key) {
3557 time_t when;
3558 dictEntry *de;
3559
3560 /* No expire? return ASAP */
3561 if (dictSize(db->expires) == 0 ||
3562 (de = dictFind(db->expires,key)) == NULL) return 0;
3563
3564 /* Lookup the expire */
3565 when = (time_t) dictGetEntryVal(de);
3566 if (time(NULL) <= when) return 0;
3567
3568 /* Delete the key */
3569 dictDelete(db->expires,key);
3570 return dictDelete(db->dict,key) == DICT_OK;
3571}
3572
3573static int deleteIfVolatile(redisDb *db, robj *key) {
3574 dictEntry *de;
3575
3576 /* No expire? return ASAP */
3577 if (dictSize(db->expires) == 0 ||
3578 (de = dictFind(db->expires,key)) == NULL) return 0;
3579
3580 /* Delete the key */
0c66a471 3581 server.dirty++;
3305306f 3582 dictDelete(db->expires,key);
3583 return dictDelete(db->dict,key) == DICT_OK;
3584}
3585
3586static void expireCommand(redisClient *c) {
3587 dictEntry *de;
3588 int seconds = atoi(c->argv[2]->ptr);
3589
3590 de = dictFind(c->db->dict,c->argv[1]);
3591 if (de == NULL) {
3592 addReply(c,shared.czero);
3593 return;
3594 }
3595 if (seconds <= 0) {
3596 addReply(c, shared.czero);
3597 return;
3598 } else {
3599 time_t when = time(NULL)+seconds;
3600 if (setExpire(c->db,c->argv[1],when))
3601 addReply(c,shared.cone);
3602 else
3603 addReply(c,shared.czero);
3604 return;
3605 }
3606}
3607
fd88489a 3608static void ttlCommand(redisClient *c) {
3609 time_t expire;
3610 int ttl = -1;
3611
3612 expire = getExpire(c->db,c->argv[1]);
3613 if (expire != -1) {
3614 ttl = (int) (expire-time(NULL));
3615 if (ttl < 0) ttl = -1;
3616 }
3617 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
3618}
3619
ed9b544e 3620/* =============================== Replication ============================= */
3621
a4d1ba9a 3622static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 3623 ssize_t nwritten, ret = size;
3624 time_t start = time(NULL);
3625
3626 timeout++;
3627 while(size) {
3628 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
3629 nwritten = write(fd,ptr,size);
3630 if (nwritten == -1) return -1;
3631 ptr += nwritten;
3632 size -= nwritten;
3633 }
3634 if ((time(NULL)-start) > timeout) {
3635 errno = ETIMEDOUT;
3636 return -1;
3637 }
3638 }
3639 return ret;
3640}
3641
a4d1ba9a 3642static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 3643 ssize_t nread, totread = 0;
3644 time_t start = time(NULL);
3645
3646 timeout++;
3647 while(size) {
3648 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
3649 nread = read(fd,ptr,size);
3650 if (nread == -1) return -1;
3651 ptr += nread;
3652 size -= nread;
3653 totread += nread;
3654 }
3655 if ((time(NULL)-start) > timeout) {
3656 errno = ETIMEDOUT;
3657 return -1;
3658 }
3659 }
3660 return totread;
3661}
3662
3663static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
3664 ssize_t nread = 0;
3665
3666 size--;
3667 while(size) {
3668 char c;
3669
3670 if (syncRead(fd,&c,1,timeout) == -1) return -1;
3671 if (c == '\n') {
3672 *ptr = '\0';
3673 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
3674 return nread;
3675 } else {
3676 *ptr++ = c;
3677 *ptr = '\0';
3678 nread++;
3679 }
3680 }
3681 return nread;
3682}
3683
3684static void syncCommand(redisClient *c) {
40d224a9 3685 /* ignore SYNC if aleady slave or in monitor mode */
3686 if (c->flags & REDIS_SLAVE) return;
3687
3688 /* SYNC can't be issued when the server has pending data to send to
3689 * the client about already issued commands. We need a fresh reply
3690 * buffer registering the differences between the BGSAVE and the current
3691 * dataset, so that we can copy to other slaves if needed. */
3692 if (listLength(c->reply) != 0) {
3693 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
3694 return;
3695 }
3696
3697 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
3698 /* Here we need to check if there is a background saving operation
3699 * in progress, or if it is required to start one */
3700 if (server.bgsaveinprogress) {
3701 /* Ok a background save is in progress. Let's check if it is a good
3702 * one for replication, i.e. if there is another slave that is
3703 * registering differences since the server forked to save */
3704 redisClient *slave;
3705 listNode *ln;
3706
6208b3a7 3707 listRewind(server.slaves);
3708 while((ln = listYield(server.slaves))) {
40d224a9 3709 slave = ln->value;
3710 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
40d224a9 3711 }
3712 if (ln) {
3713 /* Perfect, the server is already registering differences for
3714 * another slave. Set the right state, and copy the buffer. */
3715 listRelease(c->reply);
3716 c->reply = listDup(slave->reply);
3717 if (!c->reply) oom("listDup copying slave reply list");
3718 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
3719 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
3720 } else {
3721 /* No way, we need to wait for the next BGSAVE in order to
3722 * register differences */
3723 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
3724 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
3725 }
3726 } else {
3727 /* Ok we don't have a BGSAVE in progress, let's start one */
3728 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
3729 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
3730 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
3731 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
3732 return;
3733 }
3734 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
3735 }
6208b3a7 3736 c->repldbfd = -1;
40d224a9 3737 c->flags |= REDIS_SLAVE;
3738 c->slaveseldb = 0;
3739 if (!listAddNodeTail(server.slaves,c)) oom("listAddNodeTail");
40d224a9 3740 return;
3741}
3742
6208b3a7 3743static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
3744 redisClient *slave = privdata;
3745 REDIS_NOTUSED(el);
3746 REDIS_NOTUSED(mask);
3747 char buf[REDIS_IOBUF_LEN];
3748 ssize_t nwritten, buflen;
3749
3750 if (slave->repldboff == 0) {
3751 /* Write the bulk write count before to transfer the DB. In theory here
3752 * we don't know how much room there is in the output buffer of the
3753 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
3754 * operations) will never be smaller than the few bytes we need. */
3755 sds bulkcount;
3756
3757 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
3758 slave->repldbsize);
3759 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
3760 {
3761 sdsfree(bulkcount);
3762 freeClient(slave);
3763 return;
3764 }
3765 sdsfree(bulkcount);
3766 }
3767 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
3768 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
3769 if (buflen <= 0) {
3770 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
3771 (buflen == 0) ? "premature EOF" : strerror(errno));
3772 freeClient(slave);
3773 return;
3774 }
3775 if ((nwritten = write(fd,buf,buflen)) == -1) {
3776 redisLog(REDIS_DEBUG,"Write error sending DB to slave: %s",
3777 strerror(errno));
3778 freeClient(slave);
3779 return;
3780 }
3781 slave->repldboff += nwritten;
3782 if (slave->repldboff == slave->repldbsize) {
3783 close(slave->repldbfd);
3784 slave->repldbfd = -1;
3785 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
3786 slave->replstate = REDIS_REPL_ONLINE;
3787 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
3788 sendReplyToClient, slave, NULL) == AE_ERR) {
3789 freeClient(slave);
3790 return;
3791 }
3792 addReplySds(slave,sdsempty());
3793 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
3794 }
3795}
ed9b544e 3796
6208b3a7 3797static void updateSalvesWaitingBgsave(int bgsaveerr) {
3798 listNode *ln;
3799 int startbgsave = 0;
ed9b544e 3800
6208b3a7 3801 listRewind(server.slaves);
3802 while((ln = listYield(server.slaves))) {
3803 redisClient *slave = ln->value;
ed9b544e 3804
6208b3a7 3805 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
3806 startbgsave = 1;
3807 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
3808 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
3809 struct stat buf;
3810
3811 if (bgsaveerr != REDIS_OK) {
3812 freeClient(slave);
3813 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
3814 continue;
3815 }
3816 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
3817 fstat(slave->repldbfd,&buf) == -1) {
3818 freeClient(slave);
3819 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
3820 continue;
3821 }
3822 slave->repldboff = 0;
3823 slave->repldbsize = buf.st_size;
3824 slave->replstate = REDIS_REPL_SEND_BULK;
3825 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
3826 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave, NULL) == AE_ERR) {
3827 freeClient(slave);
3828 continue;
3829 }
3830 }
ed9b544e 3831 }
6208b3a7 3832 if (startbgsave) {
3833 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
3834 listRewind(server.slaves);
3835 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
3836 while((ln = listYield(server.slaves))) {
3837 redisClient *slave = ln->value;
ed9b544e 3838
6208b3a7 3839 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
3840 freeClient(slave);
3841 }
3842 }
3843 }
ed9b544e 3844}
3845
3846static int syncWithMaster(void) {
3847 char buf[1024], tmpfile[256];
3848 int dumpsize;
3849 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
3850 int dfd;
3851
3852 if (fd == -1) {
3853 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
3854 strerror(errno));
3855 return REDIS_ERR;
3856 }
3857 /* Issue the SYNC command */
3858 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
3859 close(fd);
3860 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
3861 strerror(errno));
3862 return REDIS_ERR;
3863 }
3864 /* Read the bulk write count */
8c4d91fc 3865 if (syncReadLine(fd,buf,1024,3600) == -1) {
ed9b544e 3866 close(fd);
3867 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
3868 strerror(errno));
3869 return REDIS_ERR;
3870 }
c937aa89 3871 dumpsize = atoi(buf+1);
ed9b544e 3872 redisLog(REDIS_NOTICE,"Receiving %d bytes data dump from MASTER",dumpsize);
3873 /* Read the bulk write data on a temp file */
3874 snprintf(tmpfile,256,"temp-%d.%ld.rdb",(int)time(NULL),(long int)random());
3875 dfd = open(tmpfile,O_CREAT|O_WRONLY,0644);
3876 if (dfd == -1) {
3877 close(fd);
3878 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
3879 return REDIS_ERR;
3880 }
3881 while(dumpsize) {
3882 int nread, nwritten;
3883
3884 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
3885 if (nread == -1) {
3886 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
3887 strerror(errno));
3888 close(fd);
3889 close(dfd);
3890 return REDIS_ERR;
3891 }
3892 nwritten = write(dfd,buf,nread);
3893 if (nwritten == -1) {
3894 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
3895 close(fd);
3896 close(dfd);
3897 return REDIS_ERR;
3898 }
3899 dumpsize -= nread;
3900 }
3901 close(dfd);
3902 if (rename(tmpfile,server.dbfilename) == -1) {
3903 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
3904 unlink(tmpfile);
3905 close(fd);
3906 return REDIS_ERR;
3907 }
3908 emptyDb();
f78fd11b 3909 if (rdbLoad(server.dbfilename) != REDIS_OK) {
ed9b544e 3910 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
3911 close(fd);
3912 return REDIS_ERR;
3913 }
3914 server.master = createClient(fd);
3915 server.master->flags |= REDIS_MASTER;
3916 server.replstate = REDIS_REPL_CONNECTED;
3917 return REDIS_OK;
3918}
3919
3920/* =================================== Main! ================================ */
3921
0bc03378 3922#ifdef __linux__
3923int linuxOvercommitMemoryValue(void) {
3924 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
3925 char buf[64];
3926
3927 if (!fp) return -1;
3928 if (fgets(buf,64,fp) == NULL) {
3929 fclose(fp);
3930 return -1;
3931 }
3932 fclose(fp);
3933
3934 return atoi(buf);
3935}
3936
3937void linuxOvercommitMemoryWarning(void) {
3938 if (linuxOvercommitMemoryValue() == 0) {
3939 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.");
3940 }
3941}
3942#endif /* __linux__ */
3943
ed9b544e 3944static void daemonize(void) {
3945 int fd;
3946 FILE *fp;
3947
3948 if (fork() != 0) exit(0); /* parent exits */
3949 setsid(); /* create a new session */
3950
3951 /* Every output goes to /dev/null. If Redis is daemonized but
3952 * the 'logfile' is set to 'stdout' in the configuration file
3953 * it will not log at all. */
3954 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
3955 dup2(fd, STDIN_FILENO);
3956 dup2(fd, STDOUT_FILENO);
3957 dup2(fd, STDERR_FILENO);
3958 if (fd > STDERR_FILENO) close(fd);
3959 }
3960 /* Try to write the pid file */
ed329fcf 3961 fp = fopen(server.pidfile,"w");
ed9b544e 3962 if (fp) {
3963 fprintf(fp,"%d\n",getpid());
3964 fclose(fp);
3965 }
3966}
3967
3968int main(int argc, char **argv) {
0bc03378 3969#ifdef __linux__
3970 linuxOvercommitMemoryWarning();
3971#endif
3972
ed9b544e 3973 initServerConfig();
3974 if (argc == 2) {
3975 ResetServerSaveParams();
3976 loadServerConfig(argv[1]);
3977 } else if (argc > 2) {
3978 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
3979 exit(1);
3980 }
3981 initServer();
3982 if (server.daemonize) daemonize();
3983 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
f78fd11b 3984 if (rdbLoad(server.dbfilename) == REDIS_OK)
ed9b544e 3985 redisLog(REDIS_NOTICE,"DB loaded from disk");
3986 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
3987 acceptHandler, NULL, NULL) == AE_ERR) oom("creating file event");
46713f83 3988 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
ed9b544e 3989 aeMain(server.el);
3990 aeDeleteEventLoop(server.el);
3991 return 0;
3992}