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