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