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