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