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