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