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