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