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