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