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