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