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