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