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