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