]> git.saurik.com Git - redis.git/blob - redis.c
Adds AUTH command.
[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 (server.requirepass && !c->authenticated && strcmp(c->argv[0]->ptr,"auth")) {
1103 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
1104 resetClient(c);
1105 return 1;
1106 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
1107 int bulklen = atoi(c->argv[c->argc-1]->ptr);
1108
1109 decrRefCount(c->argv[c->argc-1]);
1110 if (bulklen < 0 || bulklen > 1024*1024*1024) {
1111 c->argc--;
1112 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
1113 resetClient(c);
1114 return 1;
1115 }
1116 c->argc--;
1117 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
1118 /* It is possible that the bulk read is already in the
1119 * buffer. Check this condition and handle it accordingly */
1120 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
1121 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
1122 c->argc++;
1123 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
1124 } else {
1125 return 1;
1126 }
1127 }
1128 /* Let's try to share objects on the command arguments vector */
1129 if (server.shareobjects) {
1130 int j;
1131 for(j = 1; j < c->argc; j++)
1132 c->argv[j] = tryObjectSharing(c->argv[j]);
1133 }
1134 /* Exec the command */
1135 dirty = server.dirty;
1136 cmd->proc(c);
1137 if (server.dirty-dirty != 0 && listLength(server.slaves))
1138 replicationFeedSlaves(server.slaves,cmd,c->dictid,c->argv,c->argc);
1139 if (listLength(server.monitors))
1140 replicationFeedSlaves(server.monitors,cmd,c->dictid,c->argv,c->argc);
1141 server.stat_numcommands++;
1142
1143 /* Prepare the client for the next command */
1144 if (c->flags & REDIS_CLOSE) {
1145 freeClient(c);
1146 return 0;
1147 }
1148 resetClient(c);
1149 return 1;
1150 }
1151
1152 static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc) {
1153 listNode *ln = slaves->head;
1154 robj *outv[REDIS_MAX_ARGS*4]; /* enough room for args, spaces, newlines */
1155 int outc = 0, j;
1156
1157 for (j = 0; j < argc; j++) {
1158 if (j != 0) outv[outc++] = shared.space;
1159 if ((cmd->flags & REDIS_CMD_BULK) && j == argc-1) {
1160 robj *lenobj;
1161
1162 lenobj = createObject(REDIS_STRING,
1163 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv[j]->ptr)));
1164 lenobj->refcount = 0;
1165 outv[outc++] = lenobj;
1166 }
1167 outv[outc++] = argv[j];
1168 }
1169 outv[outc++] = shared.crlf;
1170
1171 while(ln) {
1172 redisClient *slave = ln->value;
1173 if (slave->slaveseldb != dictid) {
1174 robj *selectcmd;
1175
1176 switch(dictid) {
1177 case 0: selectcmd = shared.select0; break;
1178 case 1: selectcmd = shared.select1; break;
1179 case 2: selectcmd = shared.select2; break;
1180 case 3: selectcmd = shared.select3; break;
1181 case 4: selectcmd = shared.select4; break;
1182 case 5: selectcmd = shared.select5; break;
1183 case 6: selectcmd = shared.select6; break;
1184 case 7: selectcmd = shared.select7; break;
1185 case 8: selectcmd = shared.select8; break;
1186 case 9: selectcmd = shared.select9; break;
1187 default:
1188 selectcmd = createObject(REDIS_STRING,
1189 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
1190 selectcmd->refcount = 0;
1191 break;
1192 }
1193 addReply(slave,selectcmd);
1194 slave->slaveseldb = dictid;
1195 }
1196 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
1197 ln = ln->next;
1198 }
1199 }
1200
1201 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
1202 redisClient *c = (redisClient*) privdata;
1203 char buf[REDIS_QUERYBUF_LEN];
1204 int nread;
1205 REDIS_NOTUSED(el);
1206 REDIS_NOTUSED(mask);
1207
1208 nread = read(fd, buf, REDIS_QUERYBUF_LEN);
1209 if (nread == -1) {
1210 if (errno == EAGAIN) {
1211 nread = 0;
1212 } else {
1213 redisLog(REDIS_DEBUG, "Reading from client: %s",strerror(errno));
1214 freeClient(c);
1215 return;
1216 }
1217 } else if (nread == 0) {
1218 redisLog(REDIS_DEBUG, "Client closed connection");
1219 freeClient(c);
1220 return;
1221 }
1222 if (nread) {
1223 c->querybuf = sdscatlen(c->querybuf, buf, nread);
1224 c->lastinteraction = time(NULL);
1225 } else {
1226 return;
1227 }
1228
1229 again:
1230 if (c->bulklen == -1) {
1231 /* Read the first line of the query */
1232 char *p = strchr(c->querybuf,'\n');
1233 size_t querylen;
1234 if (p) {
1235 sds query, *argv;
1236 int argc, j;
1237
1238 query = c->querybuf;
1239 c->querybuf = sdsempty();
1240 querylen = 1+(p-(query));
1241 if (sdslen(query) > querylen) {
1242 /* leave data after the first line of the query in the buffer */
1243 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
1244 }
1245 *p = '\0'; /* remove "\n" */
1246 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
1247 sdsupdatelen(query);
1248
1249 /* Now we can split the query in arguments */
1250 if (sdslen(query) == 0) {
1251 /* Ignore empty query */
1252 sdsfree(query);
1253 return;
1254 }
1255 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
1256 sdsfree(query);
1257 if (argv == NULL) oom("sdssplitlen");
1258 for (j = 0; j < argc && j < REDIS_MAX_ARGS; j++) {
1259 if (sdslen(argv[j])) {
1260 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
1261 c->argc++;
1262 } else {
1263 sdsfree(argv[j]);
1264 }
1265 }
1266 zfree(argv);
1267 /* Execute the command. If the client is still valid
1268 * after processCommand() return and there is something
1269 * on the query buffer try to process the next command. */
1270 if (processCommand(c) && sdslen(c->querybuf)) goto again;
1271 return;
1272 } else if (sdslen(c->querybuf) >= 1024) {
1273 redisLog(REDIS_DEBUG, "Client protocol error");
1274 freeClient(c);
1275 return;
1276 }
1277 } else {
1278 /* Bulk read handling. Note that if we are at this point
1279 the client already sent a command terminated with a newline,
1280 we are reading the bulk data that is actually the last
1281 argument of the command. */
1282 int qbl = sdslen(c->querybuf);
1283
1284 if (c->bulklen <= qbl) {
1285 /* Copy everything but the final CRLF as final argument */
1286 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
1287 c->argc++;
1288 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
1289 processCommand(c);
1290 return;
1291 }
1292 }
1293 }
1294
1295 static int selectDb(redisClient *c, int id) {
1296 if (id < 0 || id >= server.dbnum)
1297 return REDIS_ERR;
1298 c->dict = server.dict[id];
1299 c->dictid = id;
1300 return REDIS_OK;
1301 }
1302
1303 static redisClient *createClient(int fd) {
1304 redisClient *c = zmalloc(sizeof(*c));
1305
1306 anetNonBlock(NULL,fd);
1307 anetTcpNoDelay(NULL,fd);
1308 if (!c) return NULL;
1309 selectDb(c,0);
1310 c->fd = fd;
1311 c->querybuf = sdsempty();
1312 c->argc = 0;
1313 c->bulklen = -1;
1314 c->sentlen = 0;
1315 c->flags = 0;
1316 c->lastinteraction = time(NULL);
1317 c->authenticated = 0;
1318 if ((c->reply = listCreate()) == NULL) oom("listCreate");
1319 listSetFreeMethod(c->reply,decrRefCount);
1320 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1321 readQueryFromClient, c, NULL) == AE_ERR) {
1322 freeClient(c);
1323 return NULL;
1324 }
1325 if (!listAddNodeTail(server.clients,c)) oom("listAddNodeTail");
1326 return c;
1327 }
1328
1329 static void addReply(redisClient *c, robj *obj) {
1330 if (listLength(c->reply) == 0 &&
1331 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
1332 sendReplyToClient, c, NULL) == AE_ERR) return;
1333 if (!listAddNodeTail(c->reply,obj)) oom("listAddNodeTail");
1334 incrRefCount(obj);
1335 }
1336
1337 static void addReplySds(redisClient *c, sds s) {
1338 robj *o = createObject(REDIS_STRING,s);
1339 addReply(c,o);
1340 decrRefCount(o);
1341 }
1342
1343 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
1344 int cport, cfd;
1345 char cip[128];
1346 REDIS_NOTUSED(el);
1347 REDIS_NOTUSED(mask);
1348 REDIS_NOTUSED(privdata);
1349
1350 cfd = anetAccept(server.neterr, fd, cip, &cport);
1351 if (cfd == AE_ERR) {
1352 redisLog(REDIS_DEBUG,"Accepting client connection: %s", server.neterr);
1353 return;
1354 }
1355 redisLog(REDIS_DEBUG,"Accepted %s:%d", cip, cport);
1356 if (createClient(cfd) == NULL) {
1357 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
1358 close(cfd); /* May be already closed, just ingore errors */
1359 return;
1360 }
1361 server.stat_numconnections++;
1362 }
1363
1364 /* ======================= Redis objects implementation ===================== */
1365
1366 static robj *createObject(int type, void *ptr) {
1367 robj *o;
1368
1369 if (listLength(server.objfreelist)) {
1370 listNode *head = listFirst(server.objfreelist);
1371 o = listNodeValue(head);
1372 listDelNode(server.objfreelist,head);
1373 } else {
1374 o = zmalloc(sizeof(*o));
1375 }
1376 if (!o) oom("createObject");
1377 o->type = type;
1378 o->ptr = ptr;
1379 o->refcount = 1;
1380 return o;
1381 }
1382
1383 static robj *createStringObject(char *ptr, size_t len) {
1384 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
1385 }
1386
1387 static robj *createListObject(void) {
1388 list *l = listCreate();
1389
1390 if (!l) oom("listCreate");
1391 listSetFreeMethod(l,decrRefCount);
1392 return createObject(REDIS_LIST,l);
1393 }
1394
1395 static robj *createSetObject(void) {
1396 dict *d = dictCreate(&setDictType,NULL);
1397 if (!d) oom("dictCreate");
1398 return createObject(REDIS_SET,d);
1399 }
1400
1401 #if 0
1402 static robj *createHashObject(void) {
1403 dict *d = dictCreate(&hashDictType,NULL);
1404 if (!d) oom("dictCreate");
1405 return createObject(REDIS_SET,d);
1406 }
1407 #endif
1408
1409 static void freeStringObject(robj *o) {
1410 sdsfree(o->ptr);
1411 }
1412
1413 static void freeListObject(robj *o) {
1414 listRelease((list*) o->ptr);
1415 }
1416
1417 static void freeSetObject(robj *o) {
1418 dictRelease((dict*) o->ptr);
1419 }
1420
1421 static void freeHashObject(robj *o) {
1422 dictRelease((dict*) o->ptr);
1423 }
1424
1425 static void incrRefCount(robj *o) {
1426 o->refcount++;
1427 }
1428
1429 static void decrRefCount(void *obj) {
1430 robj *o = obj;
1431 if (--(o->refcount) == 0) {
1432 switch(o->type) {
1433 case REDIS_STRING: freeStringObject(o); break;
1434 case REDIS_LIST: freeListObject(o); break;
1435 case REDIS_SET: freeSetObject(o); break;
1436 case REDIS_HASH: freeHashObject(o); break;
1437 default: assert(0 != 0); break;
1438 }
1439 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
1440 !listAddNodeHead(server.objfreelist,o))
1441 zfree(o);
1442 }
1443 }
1444
1445 /* Try to share an object against the shared objects pool */
1446 static robj *tryObjectSharing(robj *o) {
1447 struct dictEntry *de;
1448 unsigned long c;
1449
1450 if (server.shareobjects == 0) return o;
1451
1452 assert(o->type == REDIS_STRING);
1453 de = dictFind(server.sharingpool,o);
1454 if (de) {
1455 robj *shared = dictGetEntryKey(de);
1456
1457 c = ((unsigned long) dictGetEntryVal(de))+1;
1458 dictGetEntryVal(de) = (void*) c;
1459 incrRefCount(shared);
1460 decrRefCount(o);
1461 return shared;
1462 } else {
1463 /* Here we are using a stream algorihtm: Every time an object is
1464 * shared we increment its count, everytime there is a miss we
1465 * recrement the counter of a random object. If this object reaches
1466 * zero we remove the object and put the current object instead. */
1467 if (dictGetHashTableUsed(server.sharingpool) >=
1468 server.sharingpoolsize) {
1469 de = dictGetRandomKey(server.sharingpool);
1470 assert(de != NULL);
1471 c = ((unsigned long) dictGetEntryVal(de))-1;
1472 dictGetEntryVal(de) = (void*) c;
1473 if (c == 0) {
1474 dictDelete(server.sharingpool,de->key);
1475 }
1476 } else {
1477 c = 0; /* If the pool is empty we want to add this object */
1478 }
1479 if (c == 0) {
1480 int retval;
1481
1482 retval = dictAdd(server.sharingpool,o,(void*)1);
1483 assert(retval == DICT_OK);
1484 incrRefCount(o);
1485 }
1486 return o;
1487 }
1488 }
1489
1490 /*============================ DB saving/loading ============================ */
1491
1492 static int rdbSaveType(FILE *fp, unsigned char type) {
1493 if (fwrite(&type,1,1,fp) == 0) return -1;
1494 return 0;
1495 }
1496
1497 static int rdbSaveLen(FILE *fp, uint32_t len) {
1498 unsigned char buf[2];
1499
1500 if (len < (1<<6)) {
1501 /* Save a 6 bit len */
1502 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
1503 if (fwrite(buf,1,1,fp) == 0) return -1;
1504 } else if (len < (1<<14)) {
1505 /* Save a 14 bit len */
1506 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
1507 buf[1] = len&0xFF;
1508 if (fwrite(buf,4,1,fp) == 0) return -1;
1509 } else {
1510 /* Save a 32 bit len */
1511 buf[0] = (REDIS_RDB_32BITLEN<<6);
1512 if (fwrite(buf,1,1,fp) == 0) return -1;
1513 len = htonl(len);
1514 if (fwrite(&len,4,1,fp) == 0) return -1;
1515 }
1516 return 0;
1517 }
1518
1519 static int rdbSaveStringObject(FILE *fp, robj *obj) {
1520 size_t len = sdslen(obj->ptr);
1521
1522 if (rdbSaveLen(fp,len) == -1) return -1;
1523 if (len && fwrite(obj->ptr,len,1,fp) == 0) return -1;
1524 return 0;
1525 }
1526
1527 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
1528 static int rdbSave(char *filename) {
1529 dictIterator *di = NULL;
1530 dictEntry *de;
1531 FILE *fp;
1532 char tmpfile[256];
1533 int j;
1534
1535 snprintf(tmpfile,256,"temp-%d.%ld.rdb",(int)time(NULL),(long int)random());
1536 fp = fopen(tmpfile,"w");
1537 if (!fp) {
1538 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
1539 return REDIS_ERR;
1540 }
1541 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
1542 for (j = 0; j < server.dbnum; j++) {
1543 dict *d = server.dict[j];
1544 if (dictGetHashTableUsed(d) == 0) continue;
1545 di = dictGetIterator(d);
1546 if (!di) {
1547 fclose(fp);
1548 return REDIS_ERR;
1549 }
1550
1551 /* Write the SELECT DB opcode */
1552 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
1553 if (rdbSaveLen(fp,j) == -1) goto werr;
1554
1555 /* Iterate this DB writing every entry */
1556 while((de = dictNext(di)) != NULL) {
1557 robj *key = dictGetEntryKey(de);
1558 robj *o = dictGetEntryVal(de);
1559
1560 if (rdbSaveType(fp,o->type) == -1) goto werr;
1561 if (rdbSaveStringObject(fp,key) == -1) goto werr;
1562 if (o->type == REDIS_STRING) {
1563 /* Save a string value */
1564 if (rdbSaveStringObject(fp,o) == -1) goto werr;
1565 } else if (o->type == REDIS_LIST) {
1566 /* Save a list value */
1567 list *list = o->ptr;
1568 listNode *ln = list->head;
1569
1570 if (rdbSaveLen(fp,listLength(list)) == -1) goto werr;
1571 while(ln) {
1572 robj *eleobj = listNodeValue(ln);
1573
1574 if (rdbSaveStringObject(fp,eleobj) == -1) goto werr;
1575 ln = ln->next;
1576 }
1577 } else if (o->type == REDIS_SET) {
1578 /* Save a set value */
1579 dict *set = o->ptr;
1580 dictIterator *di = dictGetIterator(set);
1581 dictEntry *de;
1582
1583 if (!set) oom("dictGetIteraotr");
1584 if (rdbSaveLen(fp,dictGetHashTableUsed(set)) == -1) goto werr;
1585 while((de = dictNext(di)) != NULL) {
1586 robj *eleobj = dictGetEntryKey(de);
1587
1588 if (rdbSaveStringObject(fp,eleobj) == -1) goto werr;
1589 }
1590 dictReleaseIterator(di);
1591 } else {
1592 assert(0 != 0);
1593 }
1594 }
1595 dictReleaseIterator(di);
1596 }
1597 /* EOF opcode */
1598 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
1599
1600 /* Make sure data will not remain on the OS's output buffers */
1601 fflush(fp);
1602 fsync(fileno(fp));
1603 fclose(fp);
1604
1605 /* Use RENAME to make sure the DB file is changed atomically only
1606 * if the generate DB file is ok. */
1607 if (rename(tmpfile,filename) == -1) {
1608 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destionation: %s", strerror(errno));
1609 unlink(tmpfile);
1610 return REDIS_ERR;
1611 }
1612 redisLog(REDIS_NOTICE,"DB saved on disk");
1613 server.dirty = 0;
1614 server.lastsave = time(NULL);
1615 return REDIS_OK;
1616
1617 werr:
1618 fclose(fp);
1619 unlink(tmpfile);
1620 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
1621 if (di) dictReleaseIterator(di);
1622 return REDIS_ERR;
1623 }
1624
1625 static int rdbSaveBackground(char *filename) {
1626 pid_t childpid;
1627
1628 if (server.bgsaveinprogress) return REDIS_ERR;
1629 if ((childpid = fork()) == 0) {
1630 /* Child */
1631 close(server.fd);
1632 if (rdbSave(filename) == REDIS_OK) {
1633 exit(0);
1634 } else {
1635 exit(1);
1636 }
1637 } else {
1638 /* Parent */
1639 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
1640 server.bgsaveinprogress = 1;
1641 return REDIS_OK;
1642 }
1643 return REDIS_OK; /* unreached */
1644 }
1645
1646 static int rdbLoadType(FILE *fp) {
1647 unsigned char type;
1648 if (fread(&type,1,1,fp) == 0) return -1;
1649 return type;
1650 }
1651
1652 static uint32_t rdbLoadLen(FILE *fp, int rdbver) {
1653 unsigned char buf[2];
1654 uint32_t len;
1655
1656 if (rdbver == 0) {
1657 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
1658 return ntohl(len);
1659 } else {
1660 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
1661 if ((buf[0]&0xC0) == REDIS_RDB_6BITLEN) {
1662 /* Read a 6 bit len */
1663 return buf[0];
1664 } else if ((buf[0]&0xC0) == REDIS_RDB_14BITLEN) {
1665 /* Read a 14 bit len */
1666 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
1667 return ((buf[0]&0x3F)<<8)|buf[1];
1668 } else {
1669 /* Read a 32 bit len */
1670 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
1671 return ntohl(len);
1672 }
1673 }
1674 }
1675
1676 static robj *rdbLoadStringObject(FILE*fp,int rdbver) {
1677 uint32_t len = rdbLoadLen(fp,rdbver);
1678 sds val;
1679
1680 if (len == REDIS_RDB_LENERR) return NULL;
1681 val = sdsnewlen(NULL,len);
1682 if (len && fread(val,len,1,fp) == 0) {
1683 sdsfree(val);
1684 return NULL;
1685 }
1686 return tryObjectSharing(createObject(REDIS_STRING,val));
1687 }
1688
1689 static int rdbLoad(char *filename) {
1690 FILE *fp;
1691 robj *keyobj = NULL;
1692 uint32_t dbid;
1693 int type;
1694 int retval;
1695 dict *d = server.dict[0];
1696 char buf[1024];
1697 int rdbver;
1698 fp = fopen(filename,"r");
1699 if (!fp) return REDIS_ERR;
1700 if (fread(buf,9,1,fp) == 0) goto eoferr;
1701 buf[9] = '\0';
1702 if (memcmp(buf,"REDIS",5) != 0) {
1703 fclose(fp);
1704 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
1705 return REDIS_ERR;
1706 }
1707 rdbver = atoi(buf+5);
1708 if (rdbver > 1) {
1709 fclose(fp);
1710 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
1711 return REDIS_ERR;
1712 }
1713 while(1) {
1714 robj *o;
1715
1716 /* Read type. */
1717 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
1718 if (type == REDIS_EOF) break;
1719 /* Handle SELECT DB opcode as a special case */
1720 if (type == REDIS_SELECTDB) {
1721 if ((dbid = rdbLoadLen(fp,rdbver)) == REDIS_RDB_LENERR) goto eoferr;
1722 if (dbid >= (unsigned)server.dbnum) {
1723 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
1724 exit(1);
1725 }
1726 d = server.dict[dbid];
1727 continue;
1728 }
1729 /* Read key */
1730 if ((keyobj = rdbLoadStringObject(fp,rdbver)) == NULL) goto eoferr;
1731
1732 if (type == REDIS_STRING) {
1733 /* Read string value */
1734 if ((o = rdbLoadStringObject(fp,rdbver)) == NULL) goto eoferr;
1735 } else if (type == REDIS_LIST || type == REDIS_SET) {
1736 /* Read list/set value */
1737 uint32_t listlen;
1738
1739 if ((listlen = rdbLoadLen(fp,rdbver)) == REDIS_RDB_LENERR)
1740 goto eoferr;
1741 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
1742 /* Load every single element of the list/set */
1743 while(listlen--) {
1744 robj *ele;
1745
1746 if ((ele = rdbLoadStringObject(fp,rdbver)) == NULL) goto eoferr;
1747 if (type == REDIS_LIST) {
1748 if (!listAddNodeTail((list*)o->ptr,ele))
1749 oom("listAddNodeTail");
1750 } else {
1751 if (dictAdd((dict*)o->ptr,ele,NULL) == DICT_ERR)
1752 oom("dictAdd");
1753 }
1754 }
1755 } else {
1756 assert(0 != 0);
1757 }
1758 /* Add the new object in the hash table */
1759 retval = dictAdd(d,keyobj,o);
1760 if (retval == DICT_ERR) {
1761 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj->ptr);
1762 exit(1);
1763 }
1764 keyobj = o = NULL;
1765 }
1766 fclose(fp);
1767 return REDIS_OK;
1768
1769 eoferr: /* unexpected end of file is handled here with a fatal exit */
1770 decrRefCount(keyobj);
1771 redisLog(REDIS_WARNING,"Short read loading DB. Unrecoverable error, exiting now.");
1772 exit(1);
1773 return REDIS_ERR; /* Just to avoid warning */
1774 }
1775
1776 /*================================== Commands =============================== */
1777
1778 static void authCommand(redisClient *c) {
1779 if (!strcmp(c->argv[1]->ptr, server.requirepass)) {
1780 c->authenticated = 1;
1781 addReply(c,shared.ok);
1782 } else {
1783 c->authenticated = 0;
1784 addReply(c,shared.err);
1785 }
1786 }
1787
1788 static void pingCommand(redisClient *c) {
1789 addReply(c,shared.pong);
1790 }
1791
1792 static void echoCommand(redisClient *c) {
1793 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",
1794 (int)sdslen(c->argv[1]->ptr)));
1795 addReply(c,c->argv[1]);
1796 addReply(c,shared.crlf);
1797 }
1798
1799 /*=================================== Strings =============================== */
1800
1801 static void setGenericCommand(redisClient *c, int nx) {
1802 int retval;
1803
1804 retval = dictAdd(c->dict,c->argv[1],c->argv[2]);
1805 if (retval == DICT_ERR) {
1806 if (!nx) {
1807 dictReplace(c->dict,c->argv[1],c->argv[2]);
1808 incrRefCount(c->argv[2]);
1809 } else {
1810 addReply(c,shared.czero);
1811 return;
1812 }
1813 } else {
1814 incrRefCount(c->argv[1]);
1815 incrRefCount(c->argv[2]);
1816 }
1817 server.dirty++;
1818 addReply(c, nx ? shared.cone : shared.ok);
1819 }
1820
1821 static void setCommand(redisClient *c) {
1822 return setGenericCommand(c,0);
1823 }
1824
1825 static void setnxCommand(redisClient *c) {
1826 return setGenericCommand(c,1);
1827 }
1828
1829 static void getCommand(redisClient *c) {
1830 dictEntry *de;
1831
1832 de = dictFind(c->dict,c->argv[1]);
1833 if (de == NULL) {
1834 addReply(c,shared.nullbulk);
1835 } else {
1836 robj *o = dictGetEntryVal(de);
1837
1838 if (o->type != REDIS_STRING) {
1839 addReply(c,shared.wrongtypeerr);
1840 } else {
1841 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o->ptr)));
1842 addReply(c,o);
1843 addReply(c,shared.crlf);
1844 }
1845 }
1846 }
1847
1848 static void mgetCommand(redisClient *c) {
1849 dictEntry *de;
1850 int j;
1851
1852 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
1853 for (j = 1; j < c->argc; j++) {
1854 de = dictFind(c->dict,c->argv[j]);
1855 if (de == NULL) {
1856 addReply(c,shared.nullbulk);
1857 } else {
1858 robj *o = dictGetEntryVal(de);
1859
1860 if (o->type != REDIS_STRING) {
1861 addReply(c,shared.nullbulk);
1862 } else {
1863 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o->ptr)));
1864 addReply(c,o);
1865 addReply(c,shared.crlf);
1866 }
1867 }
1868 }
1869 }
1870
1871 static void incrDecrCommand(redisClient *c, int incr) {
1872 dictEntry *de;
1873 long long value;
1874 int retval;
1875 robj *o;
1876
1877 de = dictFind(c->dict,c->argv[1]);
1878 if (de == NULL) {
1879 value = 0;
1880 } else {
1881 robj *o = dictGetEntryVal(de);
1882
1883 if (o->type != REDIS_STRING) {
1884 value = 0;
1885 } else {
1886 char *eptr;
1887
1888 value = strtoll(o->ptr, &eptr, 10);
1889 }
1890 }
1891
1892 value += incr;
1893 o = createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",value));
1894 retval = dictAdd(c->dict,c->argv[1],o);
1895 if (retval == DICT_ERR) {
1896 dictReplace(c->dict,c->argv[1],o);
1897 } else {
1898 incrRefCount(c->argv[1]);
1899 }
1900 server.dirty++;
1901 addReply(c,shared.colon);
1902 addReply(c,o);
1903 addReply(c,shared.crlf);
1904 }
1905
1906 static void incrCommand(redisClient *c) {
1907 return incrDecrCommand(c,1);
1908 }
1909
1910 static void decrCommand(redisClient *c) {
1911 return incrDecrCommand(c,-1);
1912 }
1913
1914 static void incrbyCommand(redisClient *c) {
1915 int incr = atoi(c->argv[2]->ptr);
1916 return incrDecrCommand(c,incr);
1917 }
1918
1919 static void decrbyCommand(redisClient *c) {
1920 int incr = atoi(c->argv[2]->ptr);
1921 return incrDecrCommand(c,-incr);
1922 }
1923
1924 /* ========================= Type agnostic commands ========================= */
1925
1926 static void delCommand(redisClient *c) {
1927 if (dictDelete(c->dict,c->argv[1]) == DICT_OK) {
1928 server.dirty++;
1929 addReply(c,shared.cone);
1930 } else {
1931 addReply(c,shared.czero);
1932 }
1933 }
1934
1935 static void existsCommand(redisClient *c) {
1936 dictEntry *de;
1937
1938 de = dictFind(c->dict,c->argv[1]);
1939 if (de == NULL)
1940 addReply(c,shared.czero);
1941 else
1942 addReply(c,shared.cone);
1943 }
1944
1945 static void selectCommand(redisClient *c) {
1946 int id = atoi(c->argv[1]->ptr);
1947
1948 if (selectDb(c,id) == REDIS_ERR) {
1949 addReplySds(c,"-ERR invalid DB index\r\n");
1950 } else {
1951 addReply(c,shared.ok);
1952 }
1953 }
1954
1955 static void randomkeyCommand(redisClient *c) {
1956 dictEntry *de;
1957
1958 de = dictGetRandomKey(c->dict);
1959 if (de == NULL) {
1960 addReply(c,shared.crlf);
1961 } else {
1962 addReply(c,shared.plus);
1963 addReply(c,dictGetEntryKey(de));
1964 addReply(c,shared.crlf);
1965 }
1966 }
1967
1968 static void keysCommand(redisClient *c) {
1969 dictIterator *di;
1970 dictEntry *de;
1971 sds pattern = c->argv[1]->ptr;
1972 int plen = sdslen(pattern);
1973 int numkeys = 0, keyslen = 0;
1974 robj *lenobj = createObject(REDIS_STRING,NULL);
1975
1976 di = dictGetIterator(c->dict);
1977 if (!di) oom("dictGetIterator");
1978 addReply(c,lenobj);
1979 decrRefCount(lenobj);
1980 while((de = dictNext(di)) != NULL) {
1981 robj *keyobj = dictGetEntryKey(de);
1982 sds key = keyobj->ptr;
1983 if ((pattern[0] == '*' && pattern[1] == '\0') ||
1984 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
1985 if (numkeys != 0)
1986 addReply(c,shared.space);
1987 addReply(c,keyobj);
1988 numkeys++;
1989 keyslen += sdslen(key);
1990 }
1991 }
1992 dictReleaseIterator(di);
1993 lenobj->ptr = sdscatprintf(sdsempty(),"$%lu\r\n",keyslen+(numkeys ? (numkeys-1) : 0));
1994 addReply(c,shared.crlf);
1995 }
1996
1997 static void dbsizeCommand(redisClient *c) {
1998 addReplySds(c,
1999 sdscatprintf(sdsempty(),":%lu\r\n",dictGetHashTableUsed(c->dict)));
2000 }
2001
2002 static void lastsaveCommand(redisClient *c) {
2003 addReplySds(c,
2004 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
2005 }
2006
2007 static void typeCommand(redisClient *c) {
2008 dictEntry *de;
2009 char *type;
2010
2011 de = dictFind(c->dict,c->argv[1]);
2012 if (de == NULL) {
2013 type = "+none";
2014 } else {
2015 robj *o = dictGetEntryVal(de);
2016
2017 switch(o->type) {
2018 case REDIS_STRING: type = "+string"; break;
2019 case REDIS_LIST: type = "+list"; break;
2020 case REDIS_SET: type = "+set"; break;
2021 default: type = "unknown"; break;
2022 }
2023 }
2024 addReplySds(c,sdsnew(type));
2025 addReply(c,shared.crlf);
2026 }
2027
2028 static void saveCommand(redisClient *c) {
2029 if (rdbSave(server.dbfilename) == REDIS_OK) {
2030 addReply(c,shared.ok);
2031 } else {
2032 addReply(c,shared.err);
2033 }
2034 }
2035
2036 static void bgsaveCommand(redisClient *c) {
2037 if (server.bgsaveinprogress) {
2038 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
2039 return;
2040 }
2041 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
2042 addReply(c,shared.ok);
2043 } else {
2044 addReply(c,shared.err);
2045 }
2046 }
2047
2048 static void shutdownCommand(redisClient *c) {
2049 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
2050 if (rdbSave(server.dbfilename) == REDIS_OK) {
2051 if (server.daemonize) {
2052 unlink(server.pidfile);
2053 }
2054 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
2055 exit(1);
2056 } else {
2057 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
2058 addReplySds(c,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2059 }
2060 }
2061
2062 static void renameGenericCommand(redisClient *c, int nx) {
2063 dictEntry *de;
2064 robj *o;
2065
2066 /* To use the same key as src and dst is probably an error */
2067 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
2068 addReply(c,shared.sameobjecterr);
2069 return;
2070 }
2071
2072 de = dictFind(c->dict,c->argv[1]);
2073 if (de == NULL) {
2074 addReply(c,shared.nokeyerr);
2075 return;
2076 }
2077 o = dictGetEntryVal(de);
2078 incrRefCount(o);
2079 if (dictAdd(c->dict,c->argv[2],o) == DICT_ERR) {
2080 if (nx) {
2081 decrRefCount(o);
2082 addReply(c,shared.czero);
2083 return;
2084 }
2085 dictReplace(c->dict,c->argv[2],o);
2086 } else {
2087 incrRefCount(c->argv[2]);
2088 }
2089 dictDelete(c->dict,c->argv[1]);
2090 server.dirty++;
2091 addReply(c,nx ? shared.cone : shared.ok);
2092 }
2093
2094 static void renameCommand(redisClient *c) {
2095 renameGenericCommand(c,0);
2096 }
2097
2098 static void renamenxCommand(redisClient *c) {
2099 renameGenericCommand(c,1);
2100 }
2101
2102 static void moveCommand(redisClient *c) {
2103 dictEntry *de;
2104 robj *o, *key;
2105 dict *src, *dst;
2106 int srcid;
2107
2108 /* Obtain source and target DB pointers */
2109 src = c->dict;
2110 srcid = c->dictid;
2111 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
2112 addReply(c,shared.outofrangeerr);
2113 return;
2114 }
2115 dst = c->dict;
2116 c->dict = src;
2117 c->dictid = srcid;
2118
2119 /* If the user is moving using as target the same
2120 * DB as the source DB it is probably an error. */
2121 if (src == dst) {
2122 addReply(c,shared.sameobjecterr);
2123 return;
2124 }
2125
2126 /* Check if the element exists and get a reference */
2127 de = dictFind(c->dict,c->argv[1]);
2128 if (!de) {
2129 addReply(c,shared.czero);
2130 return;
2131 }
2132
2133 /* Try to add the element to the target DB */
2134 key = dictGetEntryKey(de);
2135 o = dictGetEntryVal(de);
2136 if (dictAdd(dst,key,o) == DICT_ERR) {
2137 addReply(c,shared.czero);
2138 return;
2139 }
2140 incrRefCount(key);
2141 incrRefCount(o);
2142
2143 /* OK! key moved, free the entry in the source DB */
2144 dictDelete(src,c->argv[1]);
2145 server.dirty++;
2146 addReply(c,shared.cone);
2147 }
2148
2149 /* =================================== Lists ================================ */
2150 static void pushGenericCommand(redisClient *c, int where) {
2151 robj *lobj;
2152 dictEntry *de;
2153 list *list;
2154
2155 de = dictFind(c->dict,c->argv[1]);
2156 if (de == NULL) {
2157 lobj = createListObject();
2158 list = lobj->ptr;
2159 if (where == REDIS_HEAD) {
2160 if (!listAddNodeHead(list,c->argv[2])) oom("listAddNodeHead");
2161 } else {
2162 if (!listAddNodeTail(list,c->argv[2])) oom("listAddNodeTail");
2163 }
2164 dictAdd(c->dict,c->argv[1],lobj);
2165 incrRefCount(c->argv[1]);
2166 incrRefCount(c->argv[2]);
2167 } else {
2168 lobj = dictGetEntryVal(de);
2169 if (lobj->type != REDIS_LIST) {
2170 addReply(c,shared.wrongtypeerr);
2171 return;
2172 }
2173 list = lobj->ptr;
2174 if (where == REDIS_HEAD) {
2175 if (!listAddNodeHead(list,c->argv[2])) oom("listAddNodeHead");
2176 } else {
2177 if (!listAddNodeTail(list,c->argv[2])) oom("listAddNodeTail");
2178 }
2179 incrRefCount(c->argv[2]);
2180 }
2181 server.dirty++;
2182 addReply(c,shared.ok);
2183 }
2184
2185 static void lpushCommand(redisClient *c) {
2186 pushGenericCommand(c,REDIS_HEAD);
2187 }
2188
2189 static void rpushCommand(redisClient *c) {
2190 pushGenericCommand(c,REDIS_TAIL);
2191 }
2192
2193 static void llenCommand(redisClient *c) {
2194 dictEntry *de;
2195 list *l;
2196
2197 de = dictFind(c->dict,c->argv[1]);
2198 if (de == NULL) {
2199 addReply(c,shared.czero);
2200 return;
2201 } else {
2202 robj *o = dictGetEntryVal(de);
2203 if (o->type != REDIS_LIST) {
2204 addReply(c,shared.wrongtypeerr);
2205 } else {
2206 l = o->ptr;
2207 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",listLength(l)));
2208 }
2209 }
2210 }
2211
2212 static void lindexCommand(redisClient *c) {
2213 dictEntry *de;
2214 int index = atoi(c->argv[2]->ptr);
2215
2216 de = dictFind(c->dict,c->argv[1]);
2217 if (de == NULL) {
2218 addReply(c,shared.nullbulk);
2219 } else {
2220 robj *o = dictGetEntryVal(de);
2221
2222 if (o->type != REDIS_LIST) {
2223 addReply(c,shared.wrongtypeerr);
2224 } else {
2225 list *list = o->ptr;
2226 listNode *ln;
2227
2228 ln = listIndex(list, index);
2229 if (ln == NULL) {
2230 addReply(c,shared.nullbulk);
2231 } else {
2232 robj *ele = listNodeValue(ln);
2233 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele->ptr)));
2234 addReply(c,ele);
2235 addReply(c,shared.crlf);
2236 }
2237 }
2238 }
2239 }
2240
2241 static void lsetCommand(redisClient *c) {
2242 dictEntry *de;
2243 int index = atoi(c->argv[2]->ptr);
2244
2245 de = dictFind(c->dict,c->argv[1]);
2246 if (de == NULL) {
2247 addReply(c,shared.nokeyerr);
2248 } else {
2249 robj *o = dictGetEntryVal(de);
2250
2251 if (o->type != REDIS_LIST) {
2252 addReply(c,shared.wrongtypeerr);
2253 } else {
2254 list *list = o->ptr;
2255 listNode *ln;
2256
2257 ln = listIndex(list, index);
2258 if (ln == NULL) {
2259 addReply(c,shared.outofrangeerr);
2260 } else {
2261 robj *ele = listNodeValue(ln);
2262
2263 decrRefCount(ele);
2264 listNodeValue(ln) = c->argv[3];
2265 incrRefCount(c->argv[3]);
2266 addReply(c,shared.ok);
2267 server.dirty++;
2268 }
2269 }
2270 }
2271 }
2272
2273 static void popGenericCommand(redisClient *c, int where) {
2274 dictEntry *de;
2275
2276 de = dictFind(c->dict,c->argv[1]);
2277 if (de == NULL) {
2278 addReply(c,shared.nullbulk);
2279 } else {
2280 robj *o = dictGetEntryVal(de);
2281
2282 if (o->type != REDIS_LIST) {
2283 addReply(c,shared.wrongtypeerr);
2284 } else {
2285 list *list = o->ptr;
2286 listNode *ln;
2287
2288 if (where == REDIS_HEAD)
2289 ln = listFirst(list);
2290 else
2291 ln = listLast(list);
2292
2293 if (ln == NULL) {
2294 addReply(c,shared.nullbulk);
2295 } else {
2296 robj *ele = listNodeValue(ln);
2297 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele->ptr)));
2298 addReply(c,ele);
2299 addReply(c,shared.crlf);
2300 listDelNode(list,ln);
2301 server.dirty++;
2302 }
2303 }
2304 }
2305 }
2306
2307 static void lpopCommand(redisClient *c) {
2308 popGenericCommand(c,REDIS_HEAD);
2309 }
2310
2311 static void rpopCommand(redisClient *c) {
2312 popGenericCommand(c,REDIS_TAIL);
2313 }
2314
2315 static void lrangeCommand(redisClient *c) {
2316 dictEntry *de;
2317 int start = atoi(c->argv[2]->ptr);
2318 int end = atoi(c->argv[3]->ptr);
2319
2320 de = dictFind(c->dict,c->argv[1]);
2321 if (de == NULL) {
2322 addReply(c,shared.nullmultibulk);
2323 } else {
2324 robj *o = dictGetEntryVal(de);
2325
2326 if (o->type != REDIS_LIST) {
2327 addReply(c,shared.wrongtypeerr);
2328 } else {
2329 list *list = o->ptr;
2330 listNode *ln;
2331 int llen = listLength(list);
2332 int rangelen, j;
2333 robj *ele;
2334
2335 /* convert negative indexes */
2336 if (start < 0) start = llen+start;
2337 if (end < 0) end = llen+end;
2338 if (start < 0) start = 0;
2339 if (end < 0) end = 0;
2340
2341 /* indexes sanity checks */
2342 if (start > end || start >= llen) {
2343 /* Out of range start or start > end result in empty list */
2344 addReply(c,shared.emptymultibulk);
2345 return;
2346 }
2347 if (end >= llen) end = llen-1;
2348 rangelen = (end-start)+1;
2349
2350 /* Return the result in form of a multi-bulk reply */
2351 ln = listIndex(list, start);
2352 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
2353 for (j = 0; j < rangelen; j++) {
2354 ele = listNodeValue(ln);
2355 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele->ptr)));
2356 addReply(c,ele);
2357 addReply(c,shared.crlf);
2358 ln = ln->next;
2359 }
2360 }
2361 }
2362 }
2363
2364 static void ltrimCommand(redisClient *c) {
2365 dictEntry *de;
2366 int start = atoi(c->argv[2]->ptr);
2367 int end = atoi(c->argv[3]->ptr);
2368
2369 de = dictFind(c->dict,c->argv[1]);
2370 if (de == NULL) {
2371 addReply(c,shared.nokeyerr);
2372 } else {
2373 robj *o = dictGetEntryVal(de);
2374
2375 if (o->type != REDIS_LIST) {
2376 addReply(c,shared.wrongtypeerr);
2377 } else {
2378 list *list = o->ptr;
2379 listNode *ln;
2380 int llen = listLength(list);
2381 int j, ltrim, rtrim;
2382
2383 /* convert negative indexes */
2384 if (start < 0) start = llen+start;
2385 if (end < 0) end = llen+end;
2386 if (start < 0) start = 0;
2387 if (end < 0) end = 0;
2388
2389 /* indexes sanity checks */
2390 if (start > end || start >= llen) {
2391 /* Out of range start or start > end result in empty list */
2392 ltrim = llen;
2393 rtrim = 0;
2394 } else {
2395 if (end >= llen) end = llen-1;
2396 ltrim = start;
2397 rtrim = llen-end-1;
2398 }
2399
2400 /* Remove list elements to perform the trim */
2401 for (j = 0; j < ltrim; j++) {
2402 ln = listFirst(list);
2403 listDelNode(list,ln);
2404 }
2405 for (j = 0; j < rtrim; j++) {
2406 ln = listLast(list);
2407 listDelNode(list,ln);
2408 }
2409 addReply(c,shared.ok);
2410 server.dirty++;
2411 }
2412 }
2413 }
2414
2415 static void lremCommand(redisClient *c) {
2416 dictEntry *de;
2417
2418 de = dictFind(c->dict,c->argv[1]);
2419 if (de == NULL) {
2420 addReply(c,shared.nokeyerr);
2421 } else {
2422 robj *o = dictGetEntryVal(de);
2423
2424 if (o->type != REDIS_LIST) {
2425 addReply(c,shared.wrongtypeerr);
2426 } else {
2427 list *list = o->ptr;
2428 listNode *ln, *next;
2429 int toremove = atoi(c->argv[2]->ptr);
2430 int removed = 0;
2431 int fromtail = 0;
2432
2433 if (toremove < 0) {
2434 toremove = -toremove;
2435 fromtail = 1;
2436 }
2437 ln = fromtail ? list->tail : list->head;
2438 while (ln) {
2439 next = fromtail ? ln->prev : ln->next;
2440 robj *ele = listNodeValue(ln);
2441 if (sdscmp(ele->ptr,c->argv[3]->ptr) == 0) {
2442 listDelNode(list,ln);
2443 server.dirty++;
2444 removed++;
2445 if (toremove && removed == toremove) break;
2446 }
2447 ln = next;
2448 }
2449 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
2450 }
2451 }
2452 }
2453
2454 /* ==================================== Sets ================================ */
2455
2456 static void saddCommand(redisClient *c) {
2457 dictEntry *de;
2458 robj *set;
2459
2460 de = dictFind(c->dict,c->argv[1]);
2461 if (de == NULL) {
2462 set = createSetObject();
2463 dictAdd(c->dict,c->argv[1],set);
2464 incrRefCount(c->argv[1]);
2465 } else {
2466 set = dictGetEntryVal(de);
2467 if (set->type != REDIS_SET) {
2468 addReply(c,shared.wrongtypeerr);
2469 return;
2470 }
2471 }
2472 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
2473 incrRefCount(c->argv[2]);
2474 server.dirty++;
2475 addReply(c,shared.cone);
2476 } else {
2477 addReply(c,shared.czero);
2478 }
2479 }
2480
2481 static void sremCommand(redisClient *c) {
2482 dictEntry *de;
2483
2484 de = dictFind(c->dict,c->argv[1]);
2485 if (de == NULL) {
2486 addReply(c,shared.czero);
2487 } else {
2488 robj *set;
2489
2490 set = dictGetEntryVal(de);
2491 if (set->type != REDIS_SET) {
2492 addReply(c,shared.wrongtypeerr);
2493 return;
2494 }
2495 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
2496 server.dirty++;
2497 addReply(c,shared.cone);
2498 } else {
2499 addReply(c,shared.czero);
2500 }
2501 }
2502 }
2503
2504 static void sismemberCommand(redisClient *c) {
2505 dictEntry *de;
2506
2507 de = dictFind(c->dict,c->argv[1]);
2508 if (de == NULL) {
2509 addReply(c,shared.czero);
2510 } else {
2511 robj *set;
2512
2513 set = dictGetEntryVal(de);
2514 if (set->type != REDIS_SET) {
2515 addReply(c,shared.wrongtypeerr);
2516 return;
2517 }
2518 if (dictFind(set->ptr,c->argv[2]))
2519 addReply(c,shared.cone);
2520 else
2521 addReply(c,shared.czero);
2522 }
2523 }
2524
2525 static void scardCommand(redisClient *c) {
2526 dictEntry *de;
2527 dict *s;
2528
2529 de = dictFind(c->dict,c->argv[1]);
2530 if (de == NULL) {
2531 addReply(c,shared.czero);
2532 return;
2533 } else {
2534 robj *o = dictGetEntryVal(de);
2535 if (o->type != REDIS_SET) {
2536 addReply(c,shared.wrongtypeerr);
2537 } else {
2538 s = o->ptr;
2539 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",
2540 dictGetHashTableUsed(s)));
2541 }
2542 }
2543 }
2544
2545 static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
2546 dict **d1 = (void*) s1, **d2 = (void*) s2;
2547
2548 return dictGetHashTableUsed(*d1)-dictGetHashTableUsed(*d2);
2549 }
2550
2551 static void sinterGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey) {
2552 dict **dv = zmalloc(sizeof(dict*)*setsnum);
2553 dictIterator *di;
2554 dictEntry *de;
2555 robj *lenobj = NULL, *dstset = NULL;
2556 int j, cardinality = 0;
2557
2558 if (!dv) oom("sinterCommand");
2559 for (j = 0; j < setsnum; j++) {
2560 robj *setobj;
2561 dictEntry *de;
2562
2563 de = dictFind(c->dict,setskeys[j]);
2564 if (!de) {
2565 zfree(dv);
2566 addReply(c,shared.nokeyerr);
2567 return;
2568 }
2569 setobj = dictGetEntryVal(de);
2570 if (setobj->type != REDIS_SET) {
2571 zfree(dv);
2572 addReply(c,shared.wrongtypeerr);
2573 return;
2574 }
2575 dv[j] = setobj->ptr;
2576 }
2577 /* Sort sets from the smallest to largest, this will improve our
2578 * algorithm's performace */
2579 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
2580
2581 /* The first thing we should output is the total number of elements...
2582 * since this is a multi-bulk write, but at this stage we don't know
2583 * the intersection set size, so we use a trick, append an empty object
2584 * to the output list and save the pointer to later modify it with the
2585 * right length */
2586 if (!dstkey) {
2587 lenobj = createObject(REDIS_STRING,NULL);
2588 addReply(c,lenobj);
2589 decrRefCount(lenobj);
2590 } else {
2591 /* If we have a target key where to store the resulting set
2592 * create this key with an empty set inside */
2593 dstset = createSetObject();
2594 dictDelete(c->dict,dstkey);
2595 dictAdd(c->dict,dstkey,dstset);
2596 incrRefCount(dstkey);
2597 }
2598
2599 /* Iterate all the elements of the first (smallest) set, and test
2600 * the element against all the other sets, if at least one set does
2601 * not include the element it is discarded */
2602 di = dictGetIterator(dv[0]);
2603 if (!di) oom("dictGetIterator");
2604
2605 while((de = dictNext(di)) != NULL) {
2606 robj *ele;
2607
2608 for (j = 1; j < setsnum; j++)
2609 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
2610 if (j != setsnum)
2611 continue; /* at least one set does not contain the member */
2612 ele = dictGetEntryKey(de);
2613 if (!dstkey) {
2614 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele->ptr)));
2615 addReply(c,ele);
2616 addReply(c,shared.crlf);
2617 cardinality++;
2618 } else {
2619 dictAdd(dstset->ptr,ele,NULL);
2620 incrRefCount(ele);
2621 }
2622 }
2623 dictReleaseIterator(di);
2624
2625 if (!dstkey)
2626 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",cardinality);
2627 else
2628 addReply(c,shared.ok);
2629 zfree(dv);
2630 }
2631
2632 static void sinterCommand(redisClient *c) {
2633 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
2634 }
2635
2636 static void sinterstoreCommand(redisClient *c) {
2637 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
2638 }
2639
2640 static void flushdbCommand(redisClient *c) {
2641 dictEmpty(c->dict);
2642 addReply(c,shared.ok);
2643 rdbSave(server.dbfilename);
2644 }
2645
2646 static void flushallCommand(redisClient *c) {
2647 emptyDb();
2648 addReply(c,shared.ok);
2649 rdbSave(server.dbfilename);
2650 }
2651
2652 redisSortOperation *createSortOperation(int type, robj *pattern) {
2653 redisSortOperation *so = zmalloc(sizeof(*so));
2654 if (!so) oom("createSortOperation");
2655 so->type = type;
2656 so->pattern = pattern;
2657 return so;
2658 }
2659
2660 /* Return the value associated to the key with a name obtained
2661 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2662 robj *lookupKeyByPattern(dict *dict, robj *pattern, robj *subst) {
2663 char *p;
2664 sds spat, ssub;
2665 robj keyobj;
2666 int prefixlen, sublen, postfixlen;
2667 dictEntry *de;
2668 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2669 struct {
2670 long len;
2671 long free;
2672 char buf[REDIS_SORTKEY_MAX+1];
2673 } keyname;
2674
2675
2676 spat = pattern->ptr;
2677 ssub = subst->ptr;
2678 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
2679 p = strchr(spat,'*');
2680 if (!p) return NULL;
2681
2682 prefixlen = p-spat;
2683 sublen = sdslen(ssub);
2684 postfixlen = sdslen(spat)-(prefixlen+1);
2685 memcpy(keyname.buf,spat,prefixlen);
2686 memcpy(keyname.buf+prefixlen,ssub,sublen);
2687 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
2688 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
2689 keyname.len = prefixlen+sublen+postfixlen;
2690
2691 keyobj.refcount = 1;
2692 keyobj.type = REDIS_STRING;
2693 keyobj.ptr = ((char*)&keyname)+(sizeof(long)*2);
2694
2695 de = dictFind(dict,&keyobj);
2696 // printf("lookup '%s' => %p\n", keyname.buf,de);
2697 if (!de) return NULL;
2698 return dictGetEntryVal(de);
2699 }
2700
2701 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2702 * the additional parameter is not standard but a BSD-specific we have to
2703 * pass sorting parameters via the global 'server' structure */
2704 static int sortCompare(const void *s1, const void *s2) {
2705 const redisSortObject *so1 = s1, *so2 = s2;
2706 int cmp;
2707
2708 if (!server.sort_alpha) {
2709 /* Numeric sorting. Here it's trivial as we precomputed scores */
2710 if (so1->u.score > so2->u.score) {
2711 cmp = 1;
2712 } else if (so1->u.score < so2->u.score) {
2713 cmp = -1;
2714 } else {
2715 cmp = 0;
2716 }
2717 } else {
2718 /* Alphanumeric sorting */
2719 if (server.sort_bypattern) {
2720 if (!so1->u.cmpobj || !so2->u.cmpobj) {
2721 /* At least one compare object is NULL */
2722 if (so1->u.cmpobj == so2->u.cmpobj)
2723 cmp = 0;
2724 else if (so1->u.cmpobj == NULL)
2725 cmp = -1;
2726 else
2727 cmp = 1;
2728 } else {
2729 /* We have both the objects, use strcoll */
2730 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
2731 }
2732 } else {
2733 /* Compare elements directly */
2734 cmp = strcoll(so1->obj->ptr,so2->obj->ptr);
2735 }
2736 }
2737 return server.sort_desc ? -cmp : cmp;
2738 }
2739
2740 /* The SORT command is the most complex command in Redis. Warning: this code
2741 * is optimized for speed and a bit less for readability */
2742 static void sortCommand(redisClient *c) {
2743 dictEntry *de;
2744 list *operations;
2745 int outputlen = 0;
2746 int desc = 0, alpha = 0;
2747 int limit_start = 0, limit_count = -1, start, end;
2748 int j, dontsort = 0, vectorlen;
2749 int getop = 0; /* GET operation counter */
2750 robj *sortval, *sortby = NULL;
2751 redisSortObject *vector; /* Resulting vector to sort */
2752
2753 /* Lookup the key to sort. It must be of the right types */
2754 de = dictFind(c->dict,c->argv[1]);
2755 if (de == NULL) {
2756 addReply(c,shared.nokeyerr);
2757 return;
2758 }
2759 sortval = dictGetEntryVal(de);
2760 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST) {
2761 addReply(c,shared.wrongtypeerr);
2762 return;
2763 }
2764
2765 /* Create a list of operations to perform for every sorted element.
2766 * Operations can be GET/DEL/INCR/DECR */
2767 operations = listCreate();
2768 listSetFreeMethod(operations,zfree);
2769 j = 2;
2770
2771 /* Now we need to protect sortval incrementing its count, in the future
2772 * SORT may have options able to overwrite/delete keys during the sorting
2773 * and the sorted key itself may get destroied */
2774 incrRefCount(sortval);
2775
2776 /* The SORT command has an SQL-alike syntax, parse it */
2777 while(j < c->argc) {
2778 int leftargs = c->argc-j-1;
2779 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
2780 desc = 0;
2781 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
2782 desc = 1;
2783 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
2784 alpha = 1;
2785 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
2786 limit_start = atoi(c->argv[j+1]->ptr);
2787 limit_count = atoi(c->argv[j+2]->ptr);
2788 j+=2;
2789 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
2790 sortby = c->argv[j+1];
2791 /* If the BY pattern does not contain '*', i.e. it is constant,
2792 * we don't need to sort nor to lookup the weight keys. */
2793 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
2794 j++;
2795 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
2796 listAddNodeTail(operations,createSortOperation(
2797 REDIS_SORT_GET,c->argv[j+1]));
2798 getop++;
2799 j++;
2800 } else if (!strcasecmp(c->argv[j]->ptr,"del") && leftargs >= 1) {
2801 listAddNodeTail(operations,createSortOperation(
2802 REDIS_SORT_DEL,c->argv[j+1]));
2803 j++;
2804 } else if (!strcasecmp(c->argv[j]->ptr,"incr") && leftargs >= 1) {
2805 listAddNodeTail(operations,createSortOperation(
2806 REDIS_SORT_INCR,c->argv[j+1]));
2807 j++;
2808 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
2809 listAddNodeTail(operations,createSortOperation(
2810 REDIS_SORT_DECR,c->argv[j+1]));
2811 j++;
2812 } else {
2813 decrRefCount(sortval);
2814 listRelease(operations);
2815 addReply(c,shared.syntaxerr);
2816 return;
2817 }
2818 j++;
2819 }
2820
2821 /* Load the sorting vector with all the objects to sort */
2822 vectorlen = (sortval->type == REDIS_LIST) ?
2823 listLength((list*)sortval->ptr) :
2824 dictGetHashTableUsed((dict*)sortval->ptr);
2825 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
2826 if (!vector) oom("allocating objects vector for SORT");
2827 j = 0;
2828 if (sortval->type == REDIS_LIST) {
2829 list *list = sortval->ptr;
2830 listNode *ln = list->head;
2831 while(ln) {
2832 robj *ele = ln->value;
2833 vector[j].obj = ele;
2834 vector[j].u.score = 0;
2835 vector[j].u.cmpobj = NULL;
2836 ln = ln->next;
2837 j++;
2838 }
2839 } else {
2840 dict *set = sortval->ptr;
2841 dictIterator *di;
2842 dictEntry *setele;
2843
2844 di = dictGetIterator(set);
2845 if (!di) oom("dictGetIterator");
2846 while((setele = dictNext(di)) != NULL) {
2847 vector[j].obj = dictGetEntryKey(setele);
2848 vector[j].u.score = 0;
2849 vector[j].u.cmpobj = NULL;
2850 j++;
2851 }
2852 dictReleaseIterator(di);
2853 }
2854 assert(j == vectorlen);
2855
2856 /* Now it's time to load the right scores in the sorting vector */
2857 if (dontsort == 0) {
2858 for (j = 0; j < vectorlen; j++) {
2859 if (sortby) {
2860 robj *byval;
2861
2862 byval = lookupKeyByPattern(c->dict,sortby,vector[j].obj);
2863 if (!byval || byval->type != REDIS_STRING) continue;
2864 if (alpha) {
2865 vector[j].u.cmpobj = byval;
2866 incrRefCount(byval);
2867 } else {
2868 vector[j].u.score = strtod(byval->ptr,NULL);
2869 }
2870 } else {
2871 if (!alpha) vector[j].u.score = strtod(vector[j].obj->ptr,NULL);
2872 }
2873 }
2874 }
2875
2876 /* We are ready to sort the vector... perform a bit of sanity check
2877 * on the LIMIT option too. We'll use a partial version of quicksort. */
2878 start = (limit_start < 0) ? 0 : limit_start;
2879 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
2880 if (start >= vectorlen) {
2881 start = vectorlen-1;
2882 end = vectorlen-2;
2883 }
2884 if (end >= vectorlen) end = vectorlen-1;
2885
2886 if (dontsort == 0) {
2887 server.sort_desc = desc;
2888 server.sort_alpha = alpha;
2889 server.sort_bypattern = sortby ? 1 : 0;
2890 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
2891 }
2892
2893 /* Send command output to the output buffer, performing the specified
2894 * GET/DEL/INCR/DECR operations if any. */
2895 outputlen = getop ? getop*(end-start+1) : end-start+1;
2896 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
2897 for (j = start; j <= end; j++) {
2898 listNode *ln = operations->head;
2899 if (!getop) {
2900 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",
2901 sdslen(vector[j].obj->ptr)));
2902 addReply(c,vector[j].obj);
2903 addReply(c,shared.crlf);
2904 }
2905 while(ln) {
2906 redisSortOperation *sop = ln->value;
2907 robj *val = lookupKeyByPattern(c->dict,sop->pattern,
2908 vector[j].obj);
2909
2910 if (sop->type == REDIS_SORT_GET) {
2911 if (!val || val->type != REDIS_STRING) {
2912 addReply(c,shared.nullbulk);
2913 } else {
2914 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",
2915 sdslen(val->ptr)));
2916 addReply(c,val);
2917 addReply(c,shared.crlf);
2918 }
2919 } else if (sop->type == REDIS_SORT_DEL) {
2920 /* TODO */
2921 }
2922 ln = ln->next;
2923 }
2924 }
2925
2926 /* Cleanup */
2927 decrRefCount(sortval);
2928 listRelease(operations);
2929 for (j = 0; j < vectorlen; j++) {
2930 if (sortby && alpha && vector[j].u.cmpobj)
2931 decrRefCount(vector[j].u.cmpobj);
2932 }
2933 zfree(vector);
2934 }
2935
2936 static void infoCommand(redisClient *c) {
2937 sds info;
2938 time_t uptime = time(NULL)-server.stat_starttime;
2939
2940 info = sdscatprintf(sdsempty(),
2941 "redis_version:%s\r\n"
2942 "connected_clients:%d\r\n"
2943 "connected_slaves:%d\r\n"
2944 "used_memory:%d\r\n"
2945 "changes_since_last_save:%lld\r\n"
2946 "last_save_time:%d\r\n"
2947 "total_connections_received:%lld\r\n"
2948 "total_commands_processed:%lld\r\n"
2949 "uptime_in_seconds:%d\r\n"
2950 "uptime_in_days:%d\r\n"
2951 ,REDIS_VERSION,
2952 listLength(server.clients)-listLength(server.slaves),
2953 listLength(server.slaves),
2954 server.usedmemory,
2955 server.dirty,
2956 server.lastsave,
2957 server.stat_numconnections,
2958 server.stat_numcommands,
2959 uptime,
2960 uptime/(3600*24)
2961 );
2962 addReplySds(c,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info)));
2963 addReplySds(c,info);
2964 addReply(c,shared.crlf);
2965 }
2966
2967 /* =============================== Replication ============================= */
2968
2969 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
2970 static int flushClientOutput(redisClient *c) {
2971 int retval;
2972 time_t start = time(NULL);
2973
2974 while(listLength(c->reply)) {
2975 if (time(NULL)-start > 5) return REDIS_ERR; /* 5 seconds timeout */
2976 retval = aeWait(c->fd,AE_WRITABLE,1000);
2977 if (retval == -1) {
2978 return REDIS_ERR;
2979 } else if (retval & AE_WRITABLE) {
2980 sendReplyToClient(NULL, c->fd, c, AE_WRITABLE);
2981 }
2982 }
2983 return REDIS_OK;
2984 }
2985
2986 static int syncWrite(int fd, void *ptr, ssize_t size, int timeout) {
2987 ssize_t nwritten, ret = size;
2988 time_t start = time(NULL);
2989
2990 timeout++;
2991 while(size) {
2992 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
2993 nwritten = write(fd,ptr,size);
2994 if (nwritten == -1) return -1;
2995 ptr += nwritten;
2996 size -= nwritten;
2997 }
2998 if ((time(NULL)-start) > timeout) {
2999 errno = ETIMEDOUT;
3000 return -1;
3001 }
3002 }
3003 return ret;
3004 }
3005
3006 static int syncRead(int fd, void *ptr, ssize_t size, int timeout) {
3007 ssize_t nread, totread = 0;
3008 time_t start = time(NULL);
3009
3010 timeout++;
3011 while(size) {
3012 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
3013 nread = read(fd,ptr,size);
3014 if (nread == -1) return -1;
3015 ptr += nread;
3016 size -= nread;
3017 totread += nread;
3018 }
3019 if ((time(NULL)-start) > timeout) {
3020 errno = ETIMEDOUT;
3021 return -1;
3022 }
3023 }
3024 return totread;
3025 }
3026
3027 static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
3028 ssize_t nread = 0;
3029
3030 size--;
3031 while(size) {
3032 char c;
3033
3034 if (syncRead(fd,&c,1,timeout) == -1) return -1;
3035 if (c == '\n') {
3036 *ptr = '\0';
3037 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
3038 return nread;
3039 } else {
3040 *ptr++ = c;
3041 *ptr = '\0';
3042 nread++;
3043 }
3044 }
3045 return nread;
3046 }
3047
3048 static void syncCommand(redisClient *c) {
3049 struct stat sb;
3050 int fd = -1, len;
3051 time_t start = time(NULL);
3052 char sizebuf[32];
3053
3054 /* ignore SYNC if aleady slave or in monitor mode */
3055 if (c->flags & REDIS_SLAVE) return;
3056
3057 redisLog(REDIS_NOTICE,"Slave ask for syncronization");
3058 if (flushClientOutput(c) == REDIS_ERR ||
3059 rdbSave(server.dbfilename) != REDIS_OK)
3060 goto closeconn;
3061
3062 fd = open(server.dbfilename, O_RDONLY);
3063 if (fd == -1 || fstat(fd,&sb) == -1) goto closeconn;
3064 len = sb.st_size;
3065
3066 snprintf(sizebuf,32,"$%d\r\n",len);
3067 if (syncWrite(c->fd,sizebuf,strlen(sizebuf),5) == -1) goto closeconn;
3068 while(len) {
3069 char buf[1024];
3070 int nread;
3071
3072 if (time(NULL)-start > REDIS_MAX_SYNC_TIME) goto closeconn;
3073 nread = read(fd,buf,1024);
3074 if (nread == -1) goto closeconn;
3075 len -= nread;
3076 if (syncWrite(c->fd,buf,nread,5) == -1) goto closeconn;
3077 }
3078 if (syncWrite(c->fd,"\r\n",2,5) == -1) goto closeconn;
3079 close(fd);
3080 c->flags |= REDIS_SLAVE;
3081 c->slaveseldb = 0;
3082 if (!listAddNodeTail(server.slaves,c)) oom("listAddNodeTail");
3083 redisLog(REDIS_NOTICE,"Syncronization with slave succeeded");
3084 return;
3085
3086 closeconn:
3087 if (fd != -1) close(fd);
3088 c->flags |= REDIS_CLOSE;
3089 redisLog(REDIS_WARNING,"Syncronization with slave failed");
3090 return;
3091 }
3092
3093 static int syncWithMaster(void) {
3094 char buf[1024], tmpfile[256];
3095 int dumpsize;
3096 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
3097 int dfd;
3098
3099 if (fd == -1) {
3100 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
3101 strerror(errno));
3102 return REDIS_ERR;
3103 }
3104 /* Issue the SYNC command */
3105 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
3106 close(fd);
3107 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
3108 strerror(errno));
3109 return REDIS_ERR;
3110 }
3111 /* Read the bulk write count */
3112 if (syncReadLine(fd,buf,1024,5) == -1) {
3113 close(fd);
3114 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
3115 strerror(errno));
3116 return REDIS_ERR;
3117 }
3118 dumpsize = atoi(buf+1);
3119 redisLog(REDIS_NOTICE,"Receiving %d bytes data dump from MASTER",dumpsize);
3120 /* Read the bulk write data on a temp file */
3121 snprintf(tmpfile,256,"temp-%d.%ld.rdb",(int)time(NULL),(long int)random());
3122 dfd = open(tmpfile,O_CREAT|O_WRONLY,0644);
3123 if (dfd == -1) {
3124 close(fd);
3125 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
3126 return REDIS_ERR;
3127 }
3128 while(dumpsize) {
3129 int nread, nwritten;
3130
3131 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
3132 if (nread == -1) {
3133 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
3134 strerror(errno));
3135 close(fd);
3136 close(dfd);
3137 return REDIS_ERR;
3138 }
3139 nwritten = write(dfd,buf,nread);
3140 if (nwritten == -1) {
3141 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
3142 close(fd);
3143 close(dfd);
3144 return REDIS_ERR;
3145 }
3146 dumpsize -= nread;
3147 }
3148 close(dfd);
3149 if (rename(tmpfile,server.dbfilename) == -1) {
3150 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
3151 unlink(tmpfile);
3152 close(fd);
3153 return REDIS_ERR;
3154 }
3155 emptyDb();
3156 if (rdbLoad(server.dbfilename) != REDIS_OK) {
3157 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
3158 close(fd);
3159 return REDIS_ERR;
3160 }
3161 server.master = createClient(fd);
3162 server.master->flags |= REDIS_MASTER;
3163 server.replstate = REDIS_REPL_CONNECTED;
3164 return REDIS_OK;
3165 }
3166
3167 static void monitorCommand(redisClient *c) {
3168 /* ignore MONITOR if aleady slave or in monitor mode */
3169 if (c->flags & REDIS_SLAVE) return;
3170
3171 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
3172 c->slaveseldb = 0;
3173 if (!listAddNodeTail(server.monitors,c)) oom("listAddNodeTail");
3174 addReply(c,shared.ok);
3175 }
3176
3177 /* =================================== Main! ================================ */
3178
3179 static void daemonize(void) {
3180 int fd;
3181 FILE *fp;
3182
3183 if (fork() != 0) exit(0); /* parent exits */
3184 setsid(); /* create a new session */
3185
3186 /* Every output goes to /dev/null. If Redis is daemonized but
3187 * the 'logfile' is set to 'stdout' in the configuration file
3188 * it will not log at all. */
3189 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
3190 dup2(fd, STDIN_FILENO);
3191 dup2(fd, STDOUT_FILENO);
3192 dup2(fd, STDERR_FILENO);
3193 if (fd > STDERR_FILENO) close(fd);
3194 }
3195 /* Try to write the pid file */
3196 fp = fopen(server.pidfile,"w");
3197 if (fp) {
3198 fprintf(fp,"%d\n",getpid());
3199 fclose(fp);
3200 }
3201 }
3202
3203 int main(int argc, char **argv) {
3204 initServerConfig();
3205 if (argc == 2) {
3206 ResetServerSaveParams();
3207 loadServerConfig(argv[1]);
3208 } else if (argc > 2) {
3209 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
3210 exit(1);
3211 }
3212 initServer();
3213 if (server.daemonize) daemonize();
3214 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
3215 if (rdbLoad(server.dbfilename) == REDIS_OK)
3216 redisLog(REDIS_NOTICE,"DB loaded from disk");
3217 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
3218 acceptHandler, NULL, NULL) == AE_ERR) oom("creating file event");
3219 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
3220 aeMain(server.el);
3221 aeDeleteEventLoop(server.el);
3222 return 0;
3223 }