xref: /redis-3.2.3/src/config.c (revision f7d98273)
1 /* Configuration file parsing and CONFIG GET/SET commands implementation.
2  *
3  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  *   * Redistributions of source code must retain the above copyright notice,
10  *     this list of conditions and the following disclaimer.
11  *   * Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  *   * Neither the name of Redis nor the names of its contributors may be used
15  *     to endorse or promote products derived from this software without
16  *     specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include "redis.h"
32 #include "cluster.h"
33 
34 #include <fcntl.h>
35 #include <sys/stat.h>
36 
37 static struct {
38     const char     *name;
39     const int       value;
40 } validSyslogFacilities[] = {
41     {"user",    LOG_USER},
42     {"local0",  LOG_LOCAL0},
43     {"local1",  LOG_LOCAL1},
44     {"local2",  LOG_LOCAL2},
45     {"local3",  LOG_LOCAL3},
46     {"local4",  LOG_LOCAL4},
47     {"local5",  LOG_LOCAL5},
48     {"local6",  LOG_LOCAL6},
49     {"local7",  LOG_LOCAL7},
50     {NULL, 0}
51 };
52 
53 clientBufferLimitsConfig clientBufferLimitsDefaults[REDIS_CLIENT_TYPE_COUNT] = {
54     {0, 0, 0}, /* normal */
55     {1024*1024*256, 1024*1024*64, 60}, /* slave */
56     {1024*1024*32, 1024*1024*8, 60}  /* pubsub */
57 };
58 
59 /*-----------------------------------------------------------------------------
60  * Config file parsing
61  *----------------------------------------------------------------------------*/
62 
63 int yesnotoi(char *s) {
64     if (!strcasecmp(s,"yes")) return 1;
65     else if (!strcasecmp(s,"no")) return 0;
66     else return -1;
67 }
68 
69 void appendServerSaveParams(time_t seconds, int changes) {
70     server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
71     server.saveparams[server.saveparamslen].seconds = seconds;
72     server.saveparams[server.saveparamslen].changes = changes;
73     server.saveparamslen++;
74 }
75 
76 void resetServerSaveParams() {
77     zfree(server.saveparams);
78     server.saveparams = NULL;
79     server.saveparamslen = 0;
80 }
81 
82 void loadServerConfigFromString(char *config) {
83     char *err = NULL;
84     int linenum = 0, totlines, i;
85     int slaveof_linenum = 0;
86     sds *lines;
87 
88     lines = sdssplitlen(config,strlen(config),"\n",1,&totlines);
89 
90     for (i = 0; i < totlines; i++) {
91         sds *argv;
92         int argc;
93 
94         linenum = i+1;
95         lines[i] = sdstrim(lines[i]," \t\r\n");
96 
97         /* Skip comments and blank lines */
98         if (lines[i][0] == '#' || lines[i][0] == '\0') continue;
99 
100         /* Split into arguments */
101         argv = sdssplitargs(lines[i],&argc);
102         if (argv == NULL) {
103             err = "Unbalanced quotes in configuration line";
104             goto loaderr;
105         }
106 
107         /* Skip this line if the resulting command vector is empty. */
108         if (argc == 0) {
109             sdsfreesplitres(argv,argc);
110             continue;
111         }
112         sdstolower(argv[0]);
113 
114         /* Execute config directives */
115         if (!strcasecmp(argv[0],"timeout") && argc == 2) {
116             server.maxidletime = atoi(argv[1]);
117             if (server.maxidletime < 0) {
118                 err = "Invalid timeout value"; goto loaderr;
119             }
120         } else if (!strcasecmp(argv[0],"tcp-keepalive") && argc == 2) {
121             server.tcpkeepalive = atoi(argv[1]);
122             if (server.tcpkeepalive < 0) {
123                 err = "Invalid tcp-keepalive value"; goto loaderr;
124             }
125         } else if (!strcasecmp(argv[0],"port") && argc == 2) {
126             server.port = atoi(argv[1]);
127             if (server.port < 0 || server.port > 65535) {
128                 err = "Invalid port"; goto loaderr;
129             }
130         } else if (!strcasecmp(argv[0],"tcp-backlog") && argc == 2) {
131             server.tcp_backlog = atoi(argv[1]);
132             if (server.tcp_backlog < 0) {
133                 err = "Invalid backlog value"; goto loaderr;
134             }
135         } else if (!strcasecmp(argv[0],"bind") && argc >= 2) {
136             int j, addresses = argc-1;
137 
138             if (addresses > REDIS_BINDADDR_MAX) {
139                 err = "Too many bind addresses specified"; goto loaderr;
140             }
141             for (j = 0; j < addresses; j++)
142                 server.bindaddr[j] = zstrdup(argv[j+1]);
143             server.bindaddr_count = addresses;
144         } else if (!strcasecmp(argv[0],"unixsocket") && argc == 2) {
145             server.unixsocket = zstrdup(argv[1]);
146         } else if (!strcasecmp(argv[0],"unixsocketperm") && argc == 2) {
147             errno = 0;
148             server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8);
149             if (errno || server.unixsocketperm > 0777) {
150                 err = "Invalid socket file permissions"; goto loaderr;
151             }
152         } else if (!strcasecmp(argv[0],"save")) {
153             if (argc == 3) {
154                 int seconds = atoi(argv[1]);
155                 int changes = atoi(argv[2]);
156                 if (seconds < 1 || changes < 0) {
157                     err = "Invalid save parameters"; goto loaderr;
158                 }
159                 appendServerSaveParams(seconds,changes);
160             } else if (argc == 2 && !strcasecmp(argv[1],"")) {
161                 resetServerSaveParams();
162             }
163         } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
164             if (chdir(argv[1]) == -1) {
165                 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
166                     argv[1], strerror(errno));
167                 exit(1);
168             }
169         } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
170             if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
171             else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
172             else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
173             else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
174             else {
175                 err = "Invalid log level. Must be one of debug, notice, warning";
176                 goto loaderr;
177             }
178         } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
179             FILE *logfp;
180 
181             zfree(server.logfile);
182             server.logfile = zstrdup(argv[1]);
183             if (server.logfile[0] != '\0') {
184                 /* Test if we are able to open the file. The server will not
185                  * be able to abort just for this problem later... */
186                 logfp = fopen(server.logfile,"a");
187                 if (logfp == NULL) {
188                     err = sdscatprintf(sdsempty(),
189                         "Can't open the log file: %s", strerror(errno));
190                     goto loaderr;
191                 }
192                 fclose(logfp);
193             }
194         } else if (!strcasecmp(argv[0],"syslog-enabled") && argc == 2) {
195             if ((server.syslog_enabled = yesnotoi(argv[1])) == -1) {
196                 err = "argument must be 'yes' or 'no'"; goto loaderr;
197             }
198         } else if (!strcasecmp(argv[0],"syslog-ident") && argc == 2) {
199             if (server.syslog_ident) zfree(server.syslog_ident);
200             server.syslog_ident = zstrdup(argv[1]);
201         } else if (!strcasecmp(argv[0],"syslog-facility") && argc == 2) {
202             int i;
203 
204             for (i = 0; validSyslogFacilities[i].name; i++) {
205                 if (!strcasecmp(validSyslogFacilities[i].name, argv[1])) {
206                     server.syslog_facility = validSyslogFacilities[i].value;
207                     break;
208                 }
209             }
210 
211             if (!validSyslogFacilities[i].name) {
212                 err = "Invalid log facility. Must be one of USER or between LOCAL0-LOCAL7";
213                 goto loaderr;
214             }
215         } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
216             server.dbnum = atoi(argv[1]);
217             if (server.dbnum < 1) {
218                 err = "Invalid number of databases"; goto loaderr;
219             }
220         } else if (!strcasecmp(argv[0],"include") && argc == 2) {
221             loadServerConfig(argv[1],NULL);
222         } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
223             server.maxclients = atoi(argv[1]);
224             if (server.maxclients < 1) {
225                 err = "Invalid max clients limit"; goto loaderr;
226             }
227         } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
228             server.maxmemory = memtoll(argv[1],NULL);
229         } else if (!strcasecmp(argv[0],"maxmemory-policy") && argc == 2) {
230             if (!strcasecmp(argv[1],"volatile-lru")) {
231                 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
232             } else if (!strcasecmp(argv[1],"volatile-random")) {
233                 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_RANDOM;
234             } else if (!strcasecmp(argv[1],"volatile-ttl")) {
235                 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_TTL;
236             } else if (!strcasecmp(argv[1],"allkeys-lru")) {
237                 server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_LRU;
238             } else if (!strcasecmp(argv[1],"allkeys-random")) {
239                 server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_RANDOM;
240             } else if (!strcasecmp(argv[1],"noeviction")) {
241                 server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION;
242             } else {
243                 err = "Invalid maxmemory policy";
244                 goto loaderr;
245             }
246         } else if (!strcasecmp(argv[0],"maxmemory-samples") && argc == 2) {
247             server.maxmemory_samples = atoi(argv[1]);
248             if (server.maxmemory_samples <= 0) {
249                 err = "maxmemory-samples must be 1 or greater";
250                 goto loaderr;
251             }
252         } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
253             slaveof_linenum = linenum;
254             server.masterhost = sdsnew(argv[1]);
255             server.masterport = atoi(argv[2]);
256             server.repl_state = REDIS_REPL_CONNECT;
257         } else if (!strcasecmp(argv[0],"repl-ping-slave-period") && argc == 2) {
258             server.repl_ping_slave_period = atoi(argv[1]);
259             if (server.repl_ping_slave_period <= 0) {
260                 err = "repl-ping-slave-period must be 1 or greater";
261                 goto loaderr;
262             }
263         } else if (!strcasecmp(argv[0],"repl-timeout") && argc == 2) {
264             server.repl_timeout = atoi(argv[1]);
265             if (server.repl_timeout <= 0) {
266                 err = "repl-timeout must be 1 or greater";
267                 goto loaderr;
268             }
269         } else if (!strcasecmp(argv[0],"repl-disable-tcp-nodelay") && argc==2) {
270             if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) {
271                 err = "argument must be 'yes' or 'no'"; goto loaderr;
272             }
273         } else if (!strcasecmp(argv[0],"repl-backlog-size") && argc == 2) {
274             long long size = memtoll(argv[1],NULL);
275             if (size <= 0) {
276                 err = "repl-backlog-size must be 1 or greater.";
277                 goto loaderr;
278             }
279             resizeReplicationBacklog(size);
280         } else if (!strcasecmp(argv[0],"repl-backlog-ttl") && argc == 2) {
281             server.repl_backlog_time_limit = atoi(argv[1]);
282             if (server.repl_backlog_time_limit < 0) {
283                 err = "repl-backlog-ttl can't be negative ";
284                 goto loaderr;
285             }
286         } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
287         	server.masterauth = zstrdup(argv[1]);
288         } else if (!strcasecmp(argv[0],"slave-serve-stale-data") && argc == 2) {
289             if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) {
290                 err = "argument must be 'yes' or 'no'"; goto loaderr;
291             }
292         } else if (!strcasecmp(argv[0],"slave-read-only") && argc == 2) {
293             if ((server.repl_slave_ro = yesnotoi(argv[1])) == -1) {
294                 err = "argument must be 'yes' or 'no'"; goto loaderr;
295             }
296         } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
297             if ((server.rdb_compression = yesnotoi(argv[1])) == -1) {
298                 err = "argument must be 'yes' or 'no'"; goto loaderr;
299             }
300         } else if (!strcasecmp(argv[0],"rdbchecksum") && argc == 2) {
301             if ((server.rdb_checksum = yesnotoi(argv[1])) == -1) {
302                 err = "argument must be 'yes' or 'no'"; goto loaderr;
303             }
304         } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
305             if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
306                 err = "argument must be 'yes' or 'no'"; goto loaderr;
307             }
308         } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
309             if ((server.daemonize = yesnotoi(argv[1])) == -1) {
310                 err = "argument must be 'yes' or 'no'"; goto loaderr;
311             }
312         } else if (!strcasecmp(argv[0],"hz") && argc == 2) {
313             server.hz = atoi(argv[1]);
314             if (server.hz < REDIS_MIN_HZ) server.hz = REDIS_MIN_HZ;
315             if (server.hz > REDIS_MAX_HZ) server.hz = REDIS_MAX_HZ;
316         } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
317             int yes;
318 
319             if ((yes = yesnotoi(argv[1])) == -1) {
320                 err = "argument must be 'yes' or 'no'"; goto loaderr;
321             }
322             server.aof_state = yes ? REDIS_AOF_ON : REDIS_AOF_OFF;
323         } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
324             if (!pathIsBaseName(argv[1])) {
325                 err = "appendfilename can't be a path, just a filename";
326                 goto loaderr;
327             }
328             zfree(server.aof_filename);
329             server.aof_filename = zstrdup(argv[1]);
330         } else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite")
331                    && argc == 2) {
332             if ((server.aof_no_fsync_on_rewrite= yesnotoi(argv[1])) == -1) {
333                 err = "argument must be 'yes' or 'no'"; goto loaderr;
334             }
335         } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
336             if (!strcasecmp(argv[1],"no")) {
337                 server.aof_fsync = AOF_FSYNC_NO;
338             } else if (!strcasecmp(argv[1],"always")) {
339                 server.aof_fsync = AOF_FSYNC_ALWAYS;
340             } else if (!strcasecmp(argv[1],"everysec")) {
341                 server.aof_fsync = AOF_FSYNC_EVERYSEC;
342             } else {
343                 err = "argument must be 'no', 'always' or 'everysec'";
344                 goto loaderr;
345             }
346         } else if (!strcasecmp(argv[0],"auto-aof-rewrite-percentage") &&
347                    argc == 2)
348         {
349             server.aof_rewrite_perc = atoi(argv[1]);
350             if (server.aof_rewrite_perc < 0) {
351                 err = "Invalid negative percentage for AOF auto rewrite";
352                 goto loaderr;
353             }
354         } else if (!strcasecmp(argv[0],"auto-aof-rewrite-min-size") &&
355                    argc == 2)
356         {
357             server.aof_rewrite_min_size = memtoll(argv[1],NULL);
358         } else if (!strcasecmp(argv[0],"aof-rewrite-incremental-fsync") &&
359                    argc == 2)
360         {
361             if ((server.aof_rewrite_incremental_fsync = yesnotoi(argv[1])) == -1) {
362                 err = "argument must be 'yes' or 'no'"; goto loaderr;
363             }
364         } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
365             if (strlen(argv[1]) > REDIS_AUTHPASS_MAX_LEN) {
366                 err = "Password is longer than REDIS_AUTHPASS_MAX_LEN";
367                 goto loaderr;
368             }
369             server.requirepass = zstrdup(argv[1]);
370         } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
371             zfree(server.pidfile);
372             server.pidfile = zstrdup(argv[1]);
373         } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
374             if (!pathIsBaseName(argv[1])) {
375                 err = "dbfilename can't be a path, just a filename";
376                 goto loaderr;
377             }
378             zfree(server.rdb_filename);
379             server.rdb_filename = zstrdup(argv[1]);
380         } else if (!strcasecmp(argv[0],"hash-max-ziplist-entries") && argc == 2) {
381             server.hash_max_ziplist_entries = memtoll(argv[1], NULL);
382         } else if (!strcasecmp(argv[0],"hash-max-ziplist-value") && argc == 2) {
383             server.hash_max_ziplist_value = memtoll(argv[1], NULL);
384         } else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){
385             server.list_max_ziplist_entries = memtoll(argv[1], NULL);
386         } else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) {
387             server.list_max_ziplist_value = memtoll(argv[1], NULL);
388         } else if (!strcasecmp(argv[0],"set-max-intset-entries") && argc == 2) {
389             server.set_max_intset_entries = memtoll(argv[1], NULL);
390         } else if (!strcasecmp(argv[0],"zset-max-ziplist-entries") && argc == 2) {
391             server.zset_max_ziplist_entries = memtoll(argv[1], NULL);
392         } else if (!strcasecmp(argv[0],"zset-max-ziplist-value") && argc == 2) {
393             server.zset_max_ziplist_value = memtoll(argv[1], NULL);
394         } else if (!strcasecmp(argv[0],"hll-sparse-max-bytes") && argc == 2) {
395             server.hll_sparse_max_bytes = memtoll(argv[1], NULL);
396         } else if (!strcasecmp(argv[0],"rename-command") && argc == 3) {
397             struct redisCommand *cmd = lookupCommand(argv[1]);
398             int retval;
399 
400             if (!cmd) {
401                 err = "No such command in rename-command";
402                 goto loaderr;
403             }
404 
405             /* If the target command name is the empty string we just
406              * remove it from the command table. */
407             retval = dictDelete(server.commands, argv[1]);
408             redisAssert(retval == DICT_OK);
409 
410             /* Otherwise we re-add the command under a different name. */
411             if (sdslen(argv[2]) != 0) {
412                 sds copy = sdsdup(argv[2]);
413 
414                 retval = dictAdd(server.commands, copy, cmd);
415                 if (retval != DICT_OK) {
416                     sdsfree(copy);
417                     err = "Target command name already exists"; goto loaderr;
418                 }
419             }
420         } else if (!strcasecmp(argv[0],"cluster-enabled") && argc == 2) {
421             if ((server.cluster_enabled = yesnotoi(argv[1])) == -1) {
422                 err = "argument must be 'yes' or 'no'"; goto loaderr;
423             }
424         } else if (!strcasecmp(argv[0],"cluster-config-file") && argc == 2) {
425             zfree(server.cluster_configfile);
426             server.cluster_configfile = zstrdup(argv[1]);
427         } else if (!strcasecmp(argv[0],"cluster-node-timeout") && argc == 2) {
428             server.cluster_node_timeout = strtoll(argv[1],NULL,10);
429             if (server.cluster_node_timeout <= 0) {
430                 err = "cluster node timeout must be 1 or greater"; goto loaderr;
431             }
432         } else if (!strcasecmp(argv[0],"cluster-migration-barrier")
433                    && argc == 2)
434         {
435             server.cluster_migration_barrier = atoi(argv[1]);
436             if (server.cluster_migration_barrier < 0) {
437                 err = "cluster migration barrier must zero or positive";
438                 goto loaderr;
439             }
440         } else if (!strcasecmp(argv[0],"cluster-slave-validity-factor")
441                    && argc == 2)
442         {
443             server.cluster_slave_validity_factor = atoi(argv[1]);
444             if (server.cluster_slave_validity_factor < 0) {
445                 err = "cluster slave validity factor must be zero or positive";
446                 goto loaderr;
447             }
448         } else if (!strcasecmp(argv[0],"lua-time-limit") && argc == 2) {
449             server.lua_time_limit = strtoll(argv[1],NULL,10);
450         } else if (!strcasecmp(argv[0],"slowlog-log-slower-than") &&
451                    argc == 2)
452         {
453             server.slowlog_log_slower_than = strtoll(argv[1],NULL,10);
454         } else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) {
455             server.slowlog_max_len = strtoll(argv[1],NULL,10);
456         } else if (!strcasecmp(argv[0],"client-output-buffer-limit") &&
457                    argc == 5)
458         {
459             int class = getClientTypeByName(argv[1]);
460             unsigned long long hard, soft;
461             int soft_seconds;
462 
463             if (class == -1) {
464                 err = "Unrecognized client limit class";
465                 goto loaderr;
466             }
467             hard = memtoll(argv[2],NULL);
468             soft = memtoll(argv[3],NULL);
469             soft_seconds = atoi(argv[4]);
470             if (soft_seconds < 0) {
471                 err = "Negative number of seconds in soft limit is invalid";
472                 goto loaderr;
473             }
474             server.client_obuf_limits[class].hard_limit_bytes = hard;
475             server.client_obuf_limits[class].soft_limit_bytes = soft;
476             server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
477         } else if (!strcasecmp(argv[0],"stop-writes-on-bgsave-error") &&
478                    argc == 2) {
479             if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) {
480                 err = "argument must be 'yes' or 'no'"; goto loaderr;
481             }
482         } else if (!strcasecmp(argv[0],"slave-priority") && argc == 2) {
483             server.slave_priority = atoi(argv[1]);
484         } else if (!strcasecmp(argv[0],"min-slaves-to-write") && argc == 2) {
485             server.repl_min_slaves_to_write = atoi(argv[1]);
486             if (server.repl_min_slaves_to_write < 0) {
487                 err = "Invalid value for min-slaves-to-write."; goto loaderr;
488             }
489         } else if (!strcasecmp(argv[0],"min-slaves-max-lag") && argc == 2) {
490             server.repl_min_slaves_max_lag = atoi(argv[1]);
491             if (server.repl_min_slaves_max_lag < 0) {
492                 err = "Invalid value for min-slaves-max-lag."; goto loaderr;
493             }
494         } else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) {
495             int flags = keyspaceEventsStringToFlags(argv[1]);
496 
497             if (flags == -1) {
498                 err = "Invalid event class character. Use 'g$lshzxeA'.";
499                 goto loaderr;
500             }
501             server.notify_keyspace_events = flags;
502         } else if (!strcasecmp(argv[0],"sentinel")) {
503             /* argc == 1 is handled by main() as we need to enter the sentinel
504              * mode ASAP. */
505             if (argc != 1) {
506                 if (!server.sentinel_mode) {
507                     err = "sentinel directive while not in sentinel mode";
508                     goto loaderr;
509                 }
510                 err = sentinelHandleConfiguration(argv+1,argc-1);
511                 if (err) goto loaderr;
512             }
513         } else {
514             err = "Bad directive or wrong number of arguments"; goto loaderr;
515         }
516         sdsfreesplitres(argv,argc);
517     }
518 
519     /* Sanity checks. */
520     if (server.cluster_enabled && server.masterhost) {
521         linenum = slaveof_linenum;
522         i = linenum-1;
523         err = "slaveof directive not allowed in cluster mode";
524         goto loaderr;
525     }
526 
527     sdsfreesplitres(lines,totlines);
528     return;
529 
530 loaderr:
531     fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
532     fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
533     fprintf(stderr, ">>> '%s'\n", lines[i]);
534     fprintf(stderr, "%s\n", err);
535     exit(1);
536 }
537 
538 /* Load the server configuration from the specified filename.
539  * The function appends the additional configuration directives stored
540  * in the 'options' string to the config file before loading.
541  *
542  * Both filename and options can be NULL, in such a case are considered
543  * empty. This way loadServerConfig can be used to just load a file or
544  * just load a string. */
545 void loadServerConfig(char *filename, char *options) {
546     sds config = sdsempty();
547     char buf[REDIS_CONFIGLINE_MAX+1];
548 
549     /* Load the file content */
550     if (filename) {
551         FILE *fp;
552 
553         if (filename[0] == '-' && filename[1] == '\0') {
554             fp = stdin;
555         } else {
556             if ((fp = fopen(filename,"r")) == NULL) {
557                 redisLog(REDIS_WARNING,
558                     "Fatal error, can't open config file '%s'", filename);
559                 exit(1);
560             }
561         }
562         while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL)
563             config = sdscat(config,buf);
564         if (fp != stdin) fclose(fp);
565     }
566     /* Append the additional options */
567     if (options) {
568         config = sdscat(config,"\n");
569         config = sdscat(config,options);
570     }
571     loadServerConfigFromString(config);
572     sdsfree(config);
573 }
574 
575 /*-----------------------------------------------------------------------------
576  * CONFIG SET implementation
577  *----------------------------------------------------------------------------*/
578 
579 void configSetCommand(redisClient *c) {
580     robj *o;
581     long long ll;
582     redisAssertWithInfo(c,c->argv[2],sdsEncodedObject(c->argv[2]));
583     redisAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3]));
584     o = c->argv[3];
585 
586     if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
587         if (!pathIsBaseName(o->ptr)) {
588             addReplyError(c, "dbfilename can't be a path, just a filename");
589             return;
590         }
591         zfree(server.rdb_filename);
592         server.rdb_filename = zstrdup(o->ptr);
593     } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
594         if (sdslen(o->ptr) > REDIS_AUTHPASS_MAX_LEN) goto badfmt;
595         zfree(server.requirepass);
596         server.requirepass = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
597     } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
598         zfree(server.masterauth);
599         server.masterauth = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
600     } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
601         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
602             ll < 0) goto badfmt;
603         server.maxmemory = ll;
604         if (server.maxmemory) {
605             if (server.maxmemory < zmalloc_used_memory()) {
606                 redisLog(REDIS_WARNING,"WARNING: the new maxmemory value set via CONFIG SET is smaller than the current memory usage. This will result in keys eviction and/or inability to accept new write commands depending on the maxmemory-policy.");
607             }
608             freeMemoryIfNeeded();
609         }
610     } else if (!strcasecmp(c->argv[2]->ptr,"maxclients")) {
611         int orig_value = server.maxclients;
612 
613         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 1) goto badfmt;
614 
615         /* Try to check if the OS is capable of supporting so many FDs. */
616         server.maxclients = ll;
617         if (ll > orig_value) {
618             adjustOpenFilesLimit();
619             if (server.maxclients != ll) {
620                 addReplyErrorFormat(c,"The operating system is not able to handle the specified number of clients, try with %d", server.maxclients);
621                 server.maxclients = orig_value;
622                 return;
623             }
624             if (aeGetSetSize(server.el) <
625                 server.maxclients + REDIS_EVENTLOOP_FDSET_INCR)
626             {
627                 if (aeResizeSetSize(server.el,
628                     server.maxclients + REDIS_EVENTLOOP_FDSET_INCR) == AE_ERR)
629                 {
630                     addReplyError(c,"The event loop API used by Redis is not able to handle the specified number of clients");
631                     server.maxclients = orig_value;
632                     return;
633                 }
634             }
635         }
636     } else if (!strcasecmp(c->argv[2]->ptr,"hz")) {
637         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
638         server.hz = ll;
639         if (server.hz < REDIS_MIN_HZ) server.hz = REDIS_MIN_HZ;
640         if (server.hz > REDIS_MAX_HZ) server.hz = REDIS_MAX_HZ;
641     } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory-policy")) {
642         if (!strcasecmp(o->ptr,"volatile-lru")) {
643             server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
644         } else if (!strcasecmp(o->ptr,"volatile-random")) {
645             server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_RANDOM;
646         } else if (!strcasecmp(o->ptr,"volatile-ttl")) {
647             server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_TTL;
648         } else if (!strcasecmp(o->ptr,"allkeys-lru")) {
649             server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_LRU;
650         } else if (!strcasecmp(o->ptr,"allkeys-random")) {
651             server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_RANDOM;
652         } else if (!strcasecmp(o->ptr,"noeviction")) {
653             server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION;
654         } else {
655             goto badfmt;
656         }
657     } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory-samples")) {
658         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
659             ll <= 0) goto badfmt;
660         server.maxmemory_samples = ll;
661     } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
662         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
663             ll < 0 || ll > LONG_MAX) goto badfmt;
664         server.maxidletime = ll;
665     } else if (!strcasecmp(c->argv[2]->ptr,"tcp-keepalive")) {
666         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
667             ll < 0 || ll > INT_MAX) goto badfmt;
668         server.tcpkeepalive = ll;
669     } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
670         if (!strcasecmp(o->ptr,"no")) {
671             server.aof_fsync = AOF_FSYNC_NO;
672         } else if (!strcasecmp(o->ptr,"everysec")) {
673             server.aof_fsync = AOF_FSYNC_EVERYSEC;
674         } else if (!strcasecmp(o->ptr,"always")) {
675             server.aof_fsync = AOF_FSYNC_ALWAYS;
676         } else {
677             goto badfmt;
678         }
679     } else if (!strcasecmp(c->argv[2]->ptr,"no-appendfsync-on-rewrite")) {
680         int yn = yesnotoi(o->ptr);
681 
682         if (yn == -1) goto badfmt;
683         server.aof_no_fsync_on_rewrite = yn;
684     } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
685         int enable = yesnotoi(o->ptr);
686 
687         if (enable == -1) goto badfmt;
688         if (enable == 0 && server.aof_state != REDIS_AOF_OFF) {
689             stopAppendOnly();
690         } else if (enable && server.aof_state == REDIS_AOF_OFF) {
691             if (startAppendOnly() == REDIS_ERR) {
692                 addReplyError(c,
693                     "Unable to turn on AOF. Check server logs.");
694                 return;
695             }
696         }
697     } else if (!strcasecmp(c->argv[2]->ptr,"auto-aof-rewrite-percentage")) {
698         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
699         server.aof_rewrite_perc = ll;
700     } else if (!strcasecmp(c->argv[2]->ptr,"auto-aof-rewrite-min-size")) {
701         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
702         server.aof_rewrite_min_size = ll;
703     } else if (!strcasecmp(c->argv[2]->ptr,"aof-rewrite-incremental-fsync")) {
704         int yn = yesnotoi(o->ptr);
705 
706         if (yn == -1) goto badfmt;
707         server.aof_rewrite_incremental_fsync = yn;
708     } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
709         int vlen, j;
710         sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
711 
712         /* Perform sanity check before setting the new config:
713          * - Even number of args
714          * - Seconds >= 1, changes >= 0 */
715         if (vlen & 1) {
716             sdsfreesplitres(v,vlen);
717             goto badfmt;
718         }
719         for (j = 0; j < vlen; j++) {
720             char *eptr;
721             long val;
722 
723             val = strtoll(v[j], &eptr, 10);
724             if (eptr[0] != '\0' ||
725                 ((j & 1) == 0 && val < 1) ||
726                 ((j & 1) == 1 && val < 0)) {
727                 sdsfreesplitres(v,vlen);
728                 goto badfmt;
729             }
730         }
731         /* Finally set the new config */
732         resetServerSaveParams();
733         for (j = 0; j < vlen; j += 2) {
734             time_t seconds;
735             int changes;
736 
737             seconds = strtoll(v[j],NULL,10);
738             changes = strtoll(v[j+1],NULL,10);
739             appendServerSaveParams(seconds, changes);
740         }
741         sdsfreesplitres(v,vlen);
742     } else if (!strcasecmp(c->argv[2]->ptr,"slave-serve-stale-data")) {
743         int yn = yesnotoi(o->ptr);
744 
745         if (yn == -1) goto badfmt;
746         server.repl_serve_stale_data = yn;
747     } else if (!strcasecmp(c->argv[2]->ptr,"slave-read-only")) {
748         int yn = yesnotoi(o->ptr);
749 
750         if (yn == -1) goto badfmt;
751         server.repl_slave_ro = yn;
752     } else if (!strcasecmp(c->argv[2]->ptr,"dir")) {
753         if (chdir((char*)o->ptr) == -1) {
754             addReplyErrorFormat(c,"Changing directory: %s", strerror(errno));
755             return;
756         }
757     } else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-entries")) {
758         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
759         server.hash_max_ziplist_entries = ll;
760     } else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-value")) {
761         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
762         server.hash_max_ziplist_value = ll;
763     } else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-entries")) {
764         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
765         server.list_max_ziplist_entries = ll;
766     } else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-value")) {
767         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
768         server.list_max_ziplist_value = ll;
769     } else if (!strcasecmp(c->argv[2]->ptr,"set-max-intset-entries")) {
770         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
771         server.set_max_intset_entries = ll;
772     } else if (!strcasecmp(c->argv[2]->ptr,"zset-max-ziplist-entries")) {
773         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
774         server.zset_max_ziplist_entries = ll;
775     } else if (!strcasecmp(c->argv[2]->ptr,"zset-max-ziplist-value")) {
776         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
777         server.zset_max_ziplist_value = ll;
778     } else if (!strcasecmp(c->argv[2]->ptr,"hll-sparse-max-bytes")) {
779         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
780         server.hll_sparse_max_bytes = ll;
781     } else if (!strcasecmp(c->argv[2]->ptr,"lua-time-limit")) {
782         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
783         server.lua_time_limit = ll;
784     } else if (!strcasecmp(c->argv[2]->ptr,"slowlog-log-slower-than")) {
785         if (getLongLongFromObject(o,&ll) == REDIS_ERR) goto badfmt;
786         server.slowlog_log_slower_than = ll;
787     } else if (!strcasecmp(c->argv[2]->ptr,"slowlog-max-len")) {
788         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
789         server.slowlog_max_len = (unsigned)ll;
790     } else if (!strcasecmp(c->argv[2]->ptr,"loglevel")) {
791         if (!strcasecmp(o->ptr,"warning")) {
792             server.verbosity = REDIS_WARNING;
793         } else if (!strcasecmp(o->ptr,"notice")) {
794             server.verbosity = REDIS_NOTICE;
795         } else if (!strcasecmp(o->ptr,"verbose")) {
796             server.verbosity = REDIS_VERBOSE;
797         } else if (!strcasecmp(o->ptr,"debug")) {
798             server.verbosity = REDIS_DEBUG;
799         } else {
800             goto badfmt;
801         }
802     } else if (!strcasecmp(c->argv[2]->ptr,"client-output-buffer-limit")) {
803         int vlen, j;
804         sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
805 
806         /* We need a multiple of 4: <class> <hard> <soft> <soft_seconds> */
807         if (vlen % 4) {
808             sdsfreesplitres(v,vlen);
809             goto badfmt;
810         }
811 
812         /* Sanity check of single arguments, so that we either refuse the
813          * whole configuration string or accept it all, even if a single
814          * error in a single client class is present. */
815         for (j = 0; j < vlen; j++) {
816             char *eptr;
817             long val;
818 
819             if ((j % 4) == 0) {
820                 if (getClientTypeByName(v[j]) == -1) {
821                     sdsfreesplitres(v,vlen);
822                     goto badfmt;
823                 }
824             } else {
825                 val = strtoll(v[j], &eptr, 10);
826                 if (eptr[0] != '\0' || val < 0) {
827                     sdsfreesplitres(v,vlen);
828                     goto badfmt;
829                 }
830             }
831         }
832         /* Finally set the new config */
833         for (j = 0; j < vlen; j += 4) {
834             int class;
835             unsigned long long hard, soft;
836             int soft_seconds;
837 
838             class = getClientTypeByName(v[j]);
839             hard = strtoll(v[j+1],NULL,10);
840             soft = strtoll(v[j+2],NULL,10);
841             soft_seconds = strtoll(v[j+3],NULL,10);
842 
843             server.client_obuf_limits[class].hard_limit_bytes = hard;
844             server.client_obuf_limits[class].soft_limit_bytes = soft;
845             server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
846         }
847         sdsfreesplitres(v,vlen);
848     } else if (!strcasecmp(c->argv[2]->ptr,"stop-writes-on-bgsave-error")) {
849         int yn = yesnotoi(o->ptr);
850 
851         if (yn == -1) goto badfmt;
852         server.stop_writes_on_bgsave_err = yn;
853     } else if (!strcasecmp(c->argv[2]->ptr,"repl-ping-slave-period")) {
854         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
855         server.repl_ping_slave_period = ll;
856     } else if (!strcasecmp(c->argv[2]->ptr,"repl-timeout")) {
857         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
858         server.repl_timeout = ll;
859     } else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-size")) {
860         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
861         resizeReplicationBacklog(ll);
862     } else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-ttl")) {
863         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
864         server.repl_backlog_time_limit = ll;
865     } else if (!strcasecmp(c->argv[2]->ptr,"watchdog-period")) {
866         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
867         if (ll)
868             enableWatchdog(ll);
869         else
870             disableWatchdog();
871     } else if (!strcasecmp(c->argv[2]->ptr,"rdbcompression")) {
872         int yn = yesnotoi(o->ptr);
873 
874         if (yn == -1) goto badfmt;
875         server.rdb_compression = yn;
876     } else if (!strcasecmp(c->argv[2]->ptr,"notify-keyspace-events")) {
877         int flags = keyspaceEventsStringToFlags(o->ptr);
878 
879         if (flags == -1) goto badfmt;
880         server.notify_keyspace_events = flags;
881     } else if (!strcasecmp(c->argv[2]->ptr,"repl-disable-tcp-nodelay")) {
882         int yn = yesnotoi(o->ptr);
883 
884         if (yn == -1) goto badfmt;
885         server.repl_disable_tcp_nodelay = yn;
886     } else if (!strcasecmp(c->argv[2]->ptr,"slave-priority")) {
887         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
888             ll < 0) goto badfmt;
889         server.slave_priority = ll;
890     } else if (!strcasecmp(c->argv[2]->ptr,"min-slaves-to-write")) {
891         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
892             ll < 0) goto badfmt;
893         server.repl_min_slaves_to_write = ll;
894         refreshGoodSlavesCount();
895     } else if (!strcasecmp(c->argv[2]->ptr,"min-slaves-max-lag")) {
896         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
897             ll < 0) goto badfmt;
898         server.repl_min_slaves_max_lag = ll;
899         refreshGoodSlavesCount();
900     } else if (!strcasecmp(c->argv[2]->ptr,"cluster-node-timeout")) {
901         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
902             ll <= 0) goto badfmt;
903         server.cluster_node_timeout = ll;
904     } else if (!strcasecmp(c->argv[2]->ptr,"cluster-migration-barrier")) {
905         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
906             ll < 0) goto badfmt;
907         server.cluster_migration_barrier = ll;
908     } else if (!strcasecmp(c->argv[2]->ptr,"cluster-slave-validity-factor")) {
909         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
910             ll < 0) goto badfmt;
911         server.cluster_slave_validity_factor = ll;
912     } else {
913         addReplyErrorFormat(c,"Unsupported CONFIG parameter: %s",
914             (char*)c->argv[2]->ptr);
915         return;
916     }
917     addReply(c,shared.ok);
918     return;
919 
920 badfmt: /* Bad format errors */
921     addReplyErrorFormat(c,"Invalid argument '%s' for CONFIG SET '%s'",
922             (char*)o->ptr,
923             (char*)c->argv[2]->ptr);
924 }
925 
926 /*-----------------------------------------------------------------------------
927  * CONFIG GET implementation
928  *----------------------------------------------------------------------------*/
929 
930 #define config_get_string_field(_name,_var) do { \
931     if (stringmatch(pattern,_name,0)) { \
932         addReplyBulkCString(c,_name); \
933         addReplyBulkCString(c,_var ? _var : ""); \
934         matches++; \
935     } \
936 } while(0);
937 
938 #define config_get_bool_field(_name,_var) do { \
939     if (stringmatch(pattern,_name,0)) { \
940         addReplyBulkCString(c,_name); \
941         addReplyBulkCString(c,_var ? "yes" : "no"); \
942         matches++; \
943     } \
944 } while(0);
945 
946 #define config_get_numerical_field(_name,_var) do { \
947     if (stringmatch(pattern,_name,0)) { \
948         ll2string(buf,sizeof(buf),_var); \
949         addReplyBulkCString(c,_name); \
950         addReplyBulkCString(c,buf); \
951         matches++; \
952     } \
953 } while(0);
954 
955 void configGetCommand(redisClient *c) {
956     robj *o = c->argv[2];
957     void *replylen = addDeferredMultiBulkLength(c);
958     char *pattern = o->ptr;
959     char buf[128];
960     int matches = 0;
961     redisAssertWithInfo(c,o,sdsEncodedObject(o));
962 
963     /* String values */
964     config_get_string_field("dbfilename",server.rdb_filename);
965     config_get_string_field("requirepass",server.requirepass);
966     config_get_string_field("masterauth",server.masterauth);
967     config_get_string_field("unixsocket",server.unixsocket);
968     config_get_string_field("logfile",server.logfile);
969     config_get_string_field("pidfile",server.pidfile);
970 
971     /* Numerical values */
972     config_get_numerical_field("maxmemory",server.maxmemory);
973     config_get_numerical_field("maxmemory-samples",server.maxmemory_samples);
974     config_get_numerical_field("timeout",server.maxidletime);
975     config_get_numerical_field("tcp-keepalive",server.tcpkeepalive);
976     config_get_numerical_field("auto-aof-rewrite-percentage",
977             server.aof_rewrite_perc);
978     config_get_numerical_field("auto-aof-rewrite-min-size",
979             server.aof_rewrite_min_size);
980     config_get_numerical_field("hash-max-ziplist-entries",
981             server.hash_max_ziplist_entries);
982     config_get_numerical_field("hash-max-ziplist-value",
983             server.hash_max_ziplist_value);
984     config_get_numerical_field("list-max-ziplist-entries",
985             server.list_max_ziplist_entries);
986     config_get_numerical_field("list-max-ziplist-value",
987             server.list_max_ziplist_value);
988     config_get_numerical_field("set-max-intset-entries",
989             server.set_max_intset_entries);
990     config_get_numerical_field("zset-max-ziplist-entries",
991             server.zset_max_ziplist_entries);
992     config_get_numerical_field("zset-max-ziplist-value",
993             server.zset_max_ziplist_value);
994     config_get_numerical_field("hll-sparse-max-bytes",
995             server.hll_sparse_max_bytes);
996     config_get_numerical_field("lua-time-limit",server.lua_time_limit);
997     config_get_numerical_field("slowlog-log-slower-than",
998             server.slowlog_log_slower_than);
999     config_get_numerical_field("slowlog-max-len",
1000             server.slowlog_max_len);
1001     config_get_numerical_field("port",server.port);
1002     config_get_numerical_field("tcp-backlog",server.tcp_backlog);
1003     config_get_numerical_field("databases",server.dbnum);
1004     config_get_numerical_field("repl-ping-slave-period",server.repl_ping_slave_period);
1005     config_get_numerical_field("repl-timeout",server.repl_timeout);
1006     config_get_numerical_field("repl-backlog-size",server.repl_backlog_size);
1007     config_get_numerical_field("repl-backlog-ttl",server.repl_backlog_time_limit);
1008     config_get_numerical_field("maxclients",server.maxclients);
1009     config_get_numerical_field("watchdog-period",server.watchdog_period);
1010     config_get_numerical_field("slave-priority",server.slave_priority);
1011     config_get_numerical_field("min-slaves-to-write",server.repl_min_slaves_to_write);
1012     config_get_numerical_field("min-slaves-max-lag",server.repl_min_slaves_max_lag);
1013     config_get_numerical_field("hz",server.hz);
1014     config_get_numerical_field("cluster-node-timeout",server.cluster_node_timeout);
1015     config_get_numerical_field("cluster-migration-barrier",server.cluster_migration_barrier);
1016     config_get_numerical_field("cluster-slave-validity-factor",server.cluster_slave_validity_factor);
1017 
1018     /* Bool (yes/no) values */
1019     config_get_bool_field("no-appendfsync-on-rewrite",
1020             server.aof_no_fsync_on_rewrite);
1021     config_get_bool_field("slave-serve-stale-data",
1022             server.repl_serve_stale_data);
1023     config_get_bool_field("slave-read-only",
1024             server.repl_slave_ro);
1025     config_get_bool_field("stop-writes-on-bgsave-error",
1026             server.stop_writes_on_bgsave_err);
1027     config_get_bool_field("daemonize", server.daemonize);
1028     config_get_bool_field("rdbcompression", server.rdb_compression);
1029     config_get_bool_field("rdbchecksum", server.rdb_checksum);
1030     config_get_bool_field("activerehashing", server.activerehashing);
1031     config_get_bool_field("repl-disable-tcp-nodelay",
1032             server.repl_disable_tcp_nodelay);
1033     config_get_bool_field("aof-rewrite-incremental-fsync",
1034             server.aof_rewrite_incremental_fsync);
1035 
1036     /* Everything we can't handle with macros follows. */
1037 
1038     if (stringmatch(pattern,"appendonly",0)) {
1039         addReplyBulkCString(c,"appendonly");
1040         addReplyBulkCString(c,server.aof_state == REDIS_AOF_OFF ? "no" : "yes");
1041         matches++;
1042     }
1043     if (stringmatch(pattern,"dir",0)) {
1044         char buf[1024];
1045 
1046         if (getcwd(buf,sizeof(buf)) == NULL)
1047             buf[0] = '\0';
1048 
1049         addReplyBulkCString(c,"dir");
1050         addReplyBulkCString(c,buf);
1051         matches++;
1052     }
1053     if (stringmatch(pattern,"maxmemory-policy",0)) {
1054         char *s;
1055 
1056         switch(server.maxmemory_policy) {
1057         case REDIS_MAXMEMORY_VOLATILE_LRU: s = "volatile-lru"; break;
1058         case REDIS_MAXMEMORY_VOLATILE_TTL: s = "volatile-ttl"; break;
1059         case REDIS_MAXMEMORY_VOLATILE_RANDOM: s = "volatile-random"; break;
1060         case REDIS_MAXMEMORY_ALLKEYS_LRU: s = "allkeys-lru"; break;
1061         case REDIS_MAXMEMORY_ALLKEYS_RANDOM: s = "allkeys-random"; break;
1062         case REDIS_MAXMEMORY_NO_EVICTION: s = "noeviction"; break;
1063         default: s = "unknown"; break; /* too harmless to panic */
1064         }
1065         addReplyBulkCString(c,"maxmemory-policy");
1066         addReplyBulkCString(c,s);
1067         matches++;
1068     }
1069     if (stringmatch(pattern,"appendfsync",0)) {
1070         char *policy;
1071 
1072         switch(server.aof_fsync) {
1073         case AOF_FSYNC_NO: policy = "no"; break;
1074         case AOF_FSYNC_EVERYSEC: policy = "everysec"; break;
1075         case AOF_FSYNC_ALWAYS: policy = "always"; break;
1076         default: policy = "unknown"; break; /* too harmless to panic */
1077         }
1078         addReplyBulkCString(c,"appendfsync");
1079         addReplyBulkCString(c,policy);
1080         matches++;
1081     }
1082     if (stringmatch(pattern,"save",0)) {
1083         sds buf = sdsempty();
1084         int j;
1085 
1086         for (j = 0; j < server.saveparamslen; j++) {
1087             buf = sdscatprintf(buf,"%jd %d",
1088                     (intmax_t)server.saveparams[j].seconds,
1089                     server.saveparams[j].changes);
1090             if (j != server.saveparamslen-1)
1091                 buf = sdscatlen(buf," ",1);
1092         }
1093         addReplyBulkCString(c,"save");
1094         addReplyBulkCString(c,buf);
1095         sdsfree(buf);
1096         matches++;
1097     }
1098     if (stringmatch(pattern,"loglevel",0)) {
1099         char *s;
1100 
1101         switch(server.verbosity) {
1102         case REDIS_WARNING: s = "warning"; break;
1103         case REDIS_VERBOSE: s = "verbose"; break;
1104         case REDIS_NOTICE: s = "notice"; break;
1105         case REDIS_DEBUG: s = "debug"; break;
1106         default: s = "unknown"; break; /* too harmless to panic */
1107         }
1108         addReplyBulkCString(c,"loglevel");
1109         addReplyBulkCString(c,s);
1110         matches++;
1111     }
1112     if (stringmatch(pattern,"client-output-buffer-limit",0)) {
1113         sds buf = sdsempty();
1114         int j;
1115 
1116         for (j = 0; j < REDIS_CLIENT_TYPE_COUNT; j++) {
1117             buf = sdscatprintf(buf,"%s %llu %llu %ld",
1118                     getClientTypeName(j),
1119                     server.client_obuf_limits[j].hard_limit_bytes,
1120                     server.client_obuf_limits[j].soft_limit_bytes,
1121                     (long) server.client_obuf_limits[j].soft_limit_seconds);
1122             if (j != REDIS_CLIENT_TYPE_COUNT-1)
1123                 buf = sdscatlen(buf," ",1);
1124         }
1125         addReplyBulkCString(c,"client-output-buffer-limit");
1126         addReplyBulkCString(c,buf);
1127         sdsfree(buf);
1128         matches++;
1129     }
1130     if (stringmatch(pattern,"unixsocketperm",0)) {
1131         char buf[32];
1132         snprintf(buf,sizeof(buf),"%o",server.unixsocketperm);
1133         addReplyBulkCString(c,"unixsocketperm");
1134         addReplyBulkCString(c,buf);
1135         matches++;
1136     }
1137     if (stringmatch(pattern,"slaveof",0)) {
1138         char buf[256];
1139 
1140         addReplyBulkCString(c,"slaveof");
1141         if (server.masterhost)
1142             snprintf(buf,sizeof(buf),"%s %d",
1143                 server.masterhost, server.masterport);
1144         else
1145             buf[0] = '\0';
1146         addReplyBulkCString(c,buf);
1147         matches++;
1148     }
1149     if (stringmatch(pattern,"notify-keyspace-events",0)) {
1150         robj *flagsobj = createObject(REDIS_STRING,
1151             keyspaceEventsFlagsToString(server.notify_keyspace_events));
1152 
1153         addReplyBulkCString(c,"notify-keyspace-events");
1154         addReplyBulk(c,flagsobj);
1155         decrRefCount(flagsobj);
1156         matches++;
1157     }
1158     if (stringmatch(pattern,"bind",0)) {
1159         sds aux = sdsjoin(server.bindaddr,server.bindaddr_count," ");
1160 
1161         addReplyBulkCString(c,"bind");
1162         addReplyBulkCString(c,aux);
1163         sdsfree(aux);
1164         matches++;
1165     }
1166     setDeferredMultiBulkLength(c,replylen,matches*2);
1167 }
1168 
1169 /*-----------------------------------------------------------------------------
1170  * CONFIG REWRITE implementation
1171  *----------------------------------------------------------------------------*/
1172 
1173 #define REDIS_CONFIG_REWRITE_SIGNATURE "# Generated by CONFIG REWRITE"
1174 
1175 /* We use the following dictionary type to store where a configuration
1176  * option is mentioned in the old configuration file, so it's
1177  * like "maxmemory" -> list of line numbers (first line is zero). */
1178 unsigned int dictSdsCaseHash(const void *key);
1179 int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2);
1180 void dictSdsDestructor(void *privdata, void *val);
1181 void dictListDestructor(void *privdata, void *val);
1182 
1183 /* Sentinel config rewriting is implemented inside sentinel.c by
1184  * rewriteConfigSentinelOption(). */
1185 void rewriteConfigSentinelOption(struct rewriteConfigState *state);
1186 
1187 dictType optionToLineDictType = {
1188     dictSdsCaseHash,            /* hash function */
1189     NULL,                       /* key dup */
1190     NULL,                       /* val dup */
1191     dictSdsKeyCaseCompare,      /* key compare */
1192     dictSdsDestructor,          /* key destructor */
1193     dictListDestructor          /* val destructor */
1194 };
1195 
1196 dictType optionSetDictType = {
1197     dictSdsCaseHash,            /* hash function */
1198     NULL,                       /* key dup */
1199     NULL,                       /* val dup */
1200     dictSdsKeyCaseCompare,      /* key compare */
1201     dictSdsDestructor,          /* key destructor */
1202     NULL                        /* val destructor */
1203 };
1204 
1205 /* The config rewrite state. */
1206 struct rewriteConfigState {
1207     dict *option_to_line; /* Option -> list of config file lines map */
1208     dict *rewritten;      /* Dictionary of already processed options */
1209     int numlines;         /* Number of lines in current config */
1210     sds *lines;           /* Current lines as an array of sds strings */
1211     int has_tail;         /* True if we already added directives that were
1212                              not present in the original config file. */
1213 };
1214 
1215 /* Append the new line to the current configuration state. */
1216 void rewriteConfigAppendLine(struct rewriteConfigState *state, sds line) {
1217     state->lines = zrealloc(state->lines, sizeof(char*) * (state->numlines+1));
1218     state->lines[state->numlines++] = line;
1219 }
1220 
1221 /* Populate the option -> list of line numbers map. */
1222 void rewriteConfigAddLineNumberToOption(struct rewriteConfigState *state, sds option, int linenum) {
1223     list *l = dictFetchValue(state->option_to_line,option);
1224 
1225     if (l == NULL) {
1226         l = listCreate();
1227         dictAdd(state->option_to_line,sdsdup(option),l);
1228     }
1229     listAddNodeTail(l,(void*)(long)linenum);
1230 }
1231 
1232 /* Add the specified option to the set of processed options.
1233  * This is useful as only unused lines of processed options will be blanked
1234  * in the config file, while options the rewrite process does not understand
1235  * remain untouched. */
1236 void rewriteConfigMarkAsProcessed(struct rewriteConfigState *state, char *option) {
1237     sds opt = sdsnew(option);
1238 
1239     if (dictAdd(state->rewritten,opt,NULL) != DICT_OK) sdsfree(opt);
1240 }
1241 
1242 /* Read the old file, split it into lines to populate a newly created
1243  * config rewrite state, and return it to the caller.
1244  *
1245  * If it is impossible to read the old file, NULL is returned.
1246  * If the old file does not exist at all, an empty state is returned. */
1247 struct rewriteConfigState *rewriteConfigReadOldFile(char *path) {
1248     FILE *fp = fopen(path,"r");
1249     struct rewriteConfigState *state = zmalloc(sizeof(*state));
1250     char buf[REDIS_CONFIGLINE_MAX+1];
1251     int linenum = -1;
1252 
1253     if (fp == NULL && errno != ENOENT) return NULL;
1254 
1255     state->option_to_line = dictCreate(&optionToLineDictType,NULL);
1256     state->rewritten = dictCreate(&optionSetDictType,NULL);
1257     state->numlines = 0;
1258     state->lines = NULL;
1259     state->has_tail = 0;
1260     if (fp == NULL) return state;
1261 
1262     /* Read the old file line by line, populate the state. */
1263     while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1264         int argc;
1265         sds *argv;
1266         sds line = sdstrim(sdsnew(buf),"\r\n\t ");
1267 
1268         linenum++; /* Zero based, so we init at -1 */
1269 
1270         /* Handle comments and empty lines. */
1271         if (line[0] == '#' || line[0] == '\0') {
1272             if (!state->has_tail && !strcmp(line,REDIS_CONFIG_REWRITE_SIGNATURE))
1273                 state->has_tail = 1;
1274             rewriteConfigAppendLine(state,line);
1275             continue;
1276         }
1277 
1278         /* Not a comment, split into arguments. */
1279         argv = sdssplitargs(line,&argc);
1280         if (argv == NULL) {
1281             /* Apparently the line is unparsable for some reason, for
1282              * instance it may have unbalanced quotes. Load it as a
1283              * comment. */
1284             sds aux = sdsnew("# ??? ");
1285             aux = sdscatsds(aux,line);
1286             sdsfree(line);
1287             rewriteConfigAppendLine(state,aux);
1288             continue;
1289         }
1290 
1291         sdstolower(argv[0]); /* We only want lowercase config directives. */
1292 
1293         /* Now we populate the state according to the content of this line.
1294          * Append the line and populate the option -> line numbers map. */
1295         rewriteConfigAppendLine(state,line);
1296         rewriteConfigAddLineNumberToOption(state,argv[0],linenum);
1297 
1298         sdsfreesplitres(argv,argc);
1299     }
1300     fclose(fp);
1301     return state;
1302 }
1303 
1304 /* Rewrite the specified configuration option with the new "line".
1305  * It progressively uses lines of the file that were already used for the same
1306  * configuration option in the old version of the file, removing that line from
1307  * the map of options -> line numbers.
1308  *
1309  * If there are lines associated with a given configuration option and
1310  * "force" is non-zero, the line is appended to the configuration file.
1311  * Usually "force" is true when an option has not its default value, so it
1312  * must be rewritten even if not present previously.
1313  *
1314  * The first time a line is appended into a configuration file, a comment
1315  * is added to show that starting from that point the config file was generated
1316  * by CONFIG REWRITE.
1317  *
1318  * "line" is either used, or freed, so the caller does not need to free it
1319  * in any way. */
1320 void rewriteConfigRewriteLine(struct rewriteConfigState *state, char *option, sds line, int force) {
1321     sds o = sdsnew(option);
1322     list *l = dictFetchValue(state->option_to_line,o);
1323 
1324     rewriteConfigMarkAsProcessed(state,option);
1325 
1326     if (!l && !force) {
1327         /* Option not used previously, and we are not forced to use it. */
1328         sdsfree(line);
1329         sdsfree(o);
1330         return;
1331     }
1332 
1333     if (l) {
1334         listNode *ln = listFirst(l);
1335         int linenum = (long) ln->value;
1336 
1337         /* There are still lines in the old configuration file we can reuse
1338          * for this option. Replace the line with the new one. */
1339         listDelNode(l,ln);
1340         if (listLength(l) == 0) dictDelete(state->option_to_line,o);
1341         sdsfree(state->lines[linenum]);
1342         state->lines[linenum] = line;
1343     } else {
1344         /* Append a new line. */
1345         if (!state->has_tail) {
1346             rewriteConfigAppendLine(state,
1347                 sdsnew(REDIS_CONFIG_REWRITE_SIGNATURE));
1348             state->has_tail = 1;
1349         }
1350         rewriteConfigAppendLine(state,line);
1351     }
1352     sdsfree(o);
1353 }
1354 
1355 /* Write the long long 'bytes' value as a string in a way that is parsable
1356  * inside redis.conf. If possible uses the GB, MB, KB notation. */
1357 int rewriteConfigFormatMemory(char *buf, size_t len, long long bytes) {
1358     int gb = 1024*1024*1024;
1359     int mb = 1024*1024;
1360     int kb = 1024;
1361 
1362     if (bytes && (bytes % gb) == 0) {
1363         return snprintf(buf,len,"%lldgb",bytes/gb);
1364     } else if (bytes && (bytes % mb) == 0) {
1365         return snprintf(buf,len,"%lldmb",bytes/mb);
1366     } else if (bytes && (bytes % kb) == 0) {
1367         return snprintf(buf,len,"%lldkb",bytes/kb);
1368     } else {
1369         return snprintf(buf,len,"%lld",bytes);
1370     }
1371 }
1372 
1373 /* Rewrite a simple "option-name <bytes>" configuration option. */
1374 void rewriteConfigBytesOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) {
1375     char buf[64];
1376     int force = value != defvalue;
1377     sds line;
1378 
1379     rewriteConfigFormatMemory(buf,sizeof(buf),value);
1380     line = sdscatprintf(sdsempty(),"%s %s",option,buf);
1381     rewriteConfigRewriteLine(state,option,line,force);
1382 }
1383 
1384 /* Rewrite a yes/no option. */
1385 void rewriteConfigYesNoOption(struct rewriteConfigState *state, char *option, int value, int defvalue) {
1386     int force = value != defvalue;
1387     sds line = sdscatprintf(sdsempty(),"%s %s",option,
1388         value ? "yes" : "no");
1389 
1390     rewriteConfigRewriteLine(state,option,line,force);
1391 }
1392 
1393 /* Rewrite a string option. */
1394 void rewriteConfigStringOption(struct rewriteConfigState *state, char *option, char *value, char *defvalue) {
1395     int force = 1;
1396     sds line;
1397 
1398     /* String options set to NULL need to be not present at all in the
1399      * configuration file to be set to NULL again at the next reboot. */
1400     if (value == NULL) {
1401         rewriteConfigMarkAsProcessed(state,option);
1402         return;
1403     }
1404 
1405     /* Compare the strings as sds strings to have a binary safe comparison. */
1406     if (defvalue && strcmp(value,defvalue) == 0) force = 0;
1407 
1408     line = sdsnew(option);
1409     line = sdscatlen(line, " ", 1);
1410     line = sdscatrepr(line, value, strlen(value));
1411 
1412     rewriteConfigRewriteLine(state,option,line,force);
1413 }
1414 
1415 /* Rewrite a numerical (long long range) option. */
1416 void rewriteConfigNumericalOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) {
1417     int force = value != defvalue;
1418     sds line = sdscatprintf(sdsempty(),"%s %lld",option,value);
1419 
1420     rewriteConfigRewriteLine(state,option,line,force);
1421 }
1422 
1423 /* Rewrite a octal option. */
1424 void rewriteConfigOctalOption(struct rewriteConfigState *state, char *option, int value, int defvalue) {
1425     int force = value != defvalue;
1426     sds line = sdscatprintf(sdsempty(),"%s %o",option,value);
1427 
1428     rewriteConfigRewriteLine(state,option,line,force);
1429 }
1430 
1431 /* Rewrite an enumeration option, after the "value" every enum/value pair
1432  * is specified, terminated by NULL. After NULL the default value is
1433  * specified. See how the function is used for more information. */
1434 void rewriteConfigEnumOption(struct rewriteConfigState *state, char *option, int value, ...) {
1435     va_list ap;
1436     char *enum_name, *matching_name = NULL;
1437     int enum_val, def_val, force;
1438     sds line;
1439 
1440     va_start(ap, value);
1441     while(1) {
1442         enum_name = va_arg(ap,char*);
1443         enum_val = va_arg(ap,int);
1444         if (enum_name == NULL) {
1445             def_val = enum_val;
1446             break;
1447         }
1448         if (value == enum_val) matching_name = enum_name;
1449     }
1450     va_end(ap);
1451 
1452     force = value != def_val;
1453     line = sdscatprintf(sdsempty(),"%s %s",option,matching_name);
1454     rewriteConfigRewriteLine(state,option,line,force);
1455 }
1456 
1457 /* Rewrite the syslog-fability option. */
1458 void rewriteConfigSyslogfacilityOption(struct rewriteConfigState *state) {
1459     int value = server.syslog_facility, j;
1460     int force = value != LOG_LOCAL0;
1461     char *name = NULL, *option = "syslog-facility";
1462     sds line;
1463 
1464     for (j = 0; validSyslogFacilities[j].name; j++) {
1465         if (validSyslogFacilities[j].value == value) {
1466             name = (char*) validSyslogFacilities[j].name;
1467             break;
1468         }
1469     }
1470     line = sdscatprintf(sdsempty(),"%s %s",option,name);
1471     rewriteConfigRewriteLine(state,option,line,force);
1472 }
1473 
1474 /* Rewrite the save option. */
1475 void rewriteConfigSaveOption(struct rewriteConfigState *state) {
1476     int j;
1477     sds line;
1478 
1479     /* Note that if there are no save parameters at all, all the current
1480      * config line with "save" will be detected as orphaned and deleted,
1481      * resulting into no RDB persistence as expected. */
1482     for (j = 0; j < server.saveparamslen; j++) {
1483         line = sdscatprintf(sdsempty(),"save %ld %d",
1484             (long) server.saveparams[j].seconds, server.saveparams[j].changes);
1485         rewriteConfigRewriteLine(state,"save",line,1);
1486     }
1487     /* Mark "save" as processed in case server.saveparamslen is zero. */
1488     rewriteConfigMarkAsProcessed(state,"save");
1489 }
1490 
1491 /* Rewrite the dir option, always using absolute paths.*/
1492 void rewriteConfigDirOption(struct rewriteConfigState *state) {
1493     char cwd[1024];
1494 
1495     if (getcwd(cwd,sizeof(cwd)) == NULL) {
1496         rewriteConfigMarkAsProcessed(state,"dir");
1497         return; /* no rewrite on error. */
1498     }
1499     rewriteConfigStringOption(state,"dir",cwd,NULL);
1500 }
1501 
1502 /* Rewrite the slaveof option. */
1503 void rewriteConfigSlaveofOption(struct rewriteConfigState *state) {
1504     char *option = "slaveof";
1505     sds line;
1506 
1507     /* If this is a master, we want all the slaveof config options
1508      * in the file to be removed. Note that if this is a cluster instance
1509      * we don't want a slaveof directive inside redis.conf. */
1510     if (server.cluster_enabled || server.masterhost == NULL) {
1511         rewriteConfigMarkAsProcessed(state,"slaveof");
1512         return;
1513     }
1514     line = sdscatprintf(sdsempty(),"%s %s %d", option,
1515         server.masterhost, server.masterport);
1516     rewriteConfigRewriteLine(state,option,line,1);
1517 }
1518 
1519 /* Rewrite the notify-keyspace-events option. */
1520 void rewriteConfigNotifykeyspaceeventsOption(struct rewriteConfigState *state) {
1521     int force = server.notify_keyspace_events != 0;
1522     char *option = "notify-keyspace-events";
1523     sds line, flags;
1524 
1525     flags = keyspaceEventsFlagsToString(server.notify_keyspace_events);
1526     line = sdsnew(option);
1527     line = sdscatlen(line, " ", 1);
1528     line = sdscatrepr(line, flags, sdslen(flags));
1529     sdsfree(flags);
1530     rewriteConfigRewriteLine(state,option,line,force);
1531 }
1532 
1533 /* Rewrite the client-output-buffer-limit option. */
1534 void rewriteConfigClientoutputbufferlimitOption(struct rewriteConfigState *state) {
1535     int j;
1536     char *option = "client-output-buffer-limit";
1537 
1538     for (j = 0; j < REDIS_CLIENT_TYPE_COUNT; j++) {
1539         int force = (server.client_obuf_limits[j].hard_limit_bytes !=
1540                     clientBufferLimitsDefaults[j].hard_limit_bytes) ||
1541                     (server.client_obuf_limits[j].soft_limit_bytes !=
1542                     clientBufferLimitsDefaults[j].soft_limit_bytes) ||
1543                     (server.client_obuf_limits[j].soft_limit_seconds !=
1544                     clientBufferLimitsDefaults[j].soft_limit_seconds);
1545         sds line;
1546         char hard[64], soft[64];
1547 
1548         rewriteConfigFormatMemory(hard,sizeof(hard),
1549                 server.client_obuf_limits[j].hard_limit_bytes);
1550         rewriteConfigFormatMemory(soft,sizeof(soft),
1551                 server.client_obuf_limits[j].soft_limit_bytes);
1552 
1553         line = sdscatprintf(sdsempty(),"%s %s %s %s %ld",
1554                 option, getClientTypeName(j), hard, soft,
1555                 (long) server.client_obuf_limits[j].soft_limit_seconds);
1556         rewriteConfigRewriteLine(state,option,line,force);
1557     }
1558 }
1559 
1560 /* Rewrite the bind option. */
1561 void rewriteConfigBindOption(struct rewriteConfigState *state) {
1562     int force = 1;
1563     sds line, addresses;
1564     char *option = "bind";
1565 
1566     /* Nothing to rewrite if we don't have bind addresses. */
1567     if (server.bindaddr_count == 0) {
1568         rewriteConfigMarkAsProcessed(state,option);
1569         return;
1570     }
1571 
1572     /* Rewrite as bind <addr1> <addr2> ... <addrN> */
1573     addresses = sdsjoin(server.bindaddr,server.bindaddr_count," ");
1574     line = sdsnew(option);
1575     line = sdscatlen(line, " ", 1);
1576     line = sdscatsds(line, addresses);
1577     sdsfree(addresses);
1578 
1579     rewriteConfigRewriteLine(state,option,line,force);
1580 }
1581 
1582 /* Glue together the configuration lines in the current configuration
1583  * rewrite state into a single string, stripping multiple empty lines. */
1584 sds rewriteConfigGetContentFromState(struct rewriteConfigState *state) {
1585     sds content = sdsempty();
1586     int j, was_empty = 0;
1587 
1588     for (j = 0; j < state->numlines; j++) {
1589         /* Every cluster of empty lines is turned into a single empty line. */
1590         if (sdslen(state->lines[j]) == 0) {
1591             if (was_empty) continue;
1592             was_empty = 1;
1593         } else {
1594             was_empty = 0;
1595         }
1596         content = sdscatsds(content,state->lines[j]);
1597         content = sdscatlen(content,"\n",1);
1598     }
1599     return content;
1600 }
1601 
1602 /* Free the configuration rewrite state. */
1603 void rewriteConfigReleaseState(struct rewriteConfigState *state) {
1604     sdsfreesplitres(state->lines,state->numlines);
1605     dictRelease(state->option_to_line);
1606     dictRelease(state->rewritten);
1607     zfree(state);
1608 }
1609 
1610 /* At the end of the rewrite process the state contains the remaining
1611  * map between "option name" => "lines in the original config file".
1612  * Lines used by the rewrite process were removed by the function
1613  * rewriteConfigRewriteLine(), all the other lines are "orphaned" and
1614  * should be replaced by empty lines.
1615  *
1616  * This function does just this, iterating all the option names and
1617  * blanking all the lines still associated. */
1618 void rewriteConfigRemoveOrphaned(struct rewriteConfigState *state) {
1619     dictIterator *di = dictGetIterator(state->option_to_line);
1620     dictEntry *de;
1621 
1622     while((de = dictNext(di)) != NULL) {
1623         list *l = dictGetVal(de);
1624         sds option = dictGetKey(de);
1625 
1626         /* Don't blank lines about options the rewrite process
1627          * don't understand. */
1628         if (dictFind(state->rewritten,option) == NULL) {
1629             redisLog(REDIS_DEBUG,"Not rewritten option: %s", option);
1630             continue;
1631         }
1632 
1633         while(listLength(l)) {
1634             listNode *ln = listFirst(l);
1635             int linenum = (long) ln->value;
1636 
1637             sdsfree(state->lines[linenum]);
1638             state->lines[linenum] = sdsempty();
1639             listDelNode(l,ln);
1640         }
1641     }
1642     dictReleaseIterator(di);
1643 }
1644 
1645 /* This function overwrites the old configuration file with the new content.
1646  *
1647  * 1) The old file length is obtained.
1648  * 2) If the new content is smaller, padding is added.
1649  * 3) A single write(2) call is used to replace the content of the file.
1650  * 4) Later the file is truncated to the length of the new content.
1651  *
1652  * This way we are sure the file is left in a consistent state even if the
1653  * process is stopped between any of the four operations.
1654  *
1655  * The function returns 0 on success, otherwise -1 is returned and errno
1656  * set accordingly. */
1657 int rewriteConfigOverwriteFile(char *configfile, sds content) {
1658     int retval = 0;
1659     int fd = open(configfile,O_RDWR|O_CREAT,0644);
1660     int content_size = sdslen(content), padding = 0;
1661     struct stat sb;
1662     sds content_padded;
1663 
1664     /* 1) Open the old file (or create a new one if it does not
1665      *    exist), get the size. */
1666     if (fd == -1) return -1; /* errno set by open(). */
1667     if (fstat(fd,&sb) == -1) {
1668         close(fd);
1669         return -1; /* errno set by fstat(). */
1670     }
1671 
1672     /* 2) Pad the content at least match the old file size. */
1673     content_padded = sdsdup(content);
1674     if (content_size < sb.st_size) {
1675         /* If the old file was bigger, pad the content with
1676          * a newline plus as many "#" chars as required. */
1677         padding = sb.st_size - content_size;
1678         content_padded = sdsgrowzero(content_padded,sb.st_size);
1679         content_padded[content_size] = '\n';
1680         memset(content_padded+content_size+1,'#',padding-1);
1681     }
1682 
1683     /* 3) Write the new content using a single write(2). */
1684     if (write(fd,content_padded,strlen(content_padded)) == -1) {
1685         retval = -1;
1686         goto cleanup;
1687     }
1688 
1689     /* 4) Truncate the file to the right length if we used padding. */
1690     if (padding) {
1691         if (ftruncate(fd,content_size) == -1) {
1692             /* Non critical error... */
1693         }
1694     }
1695 
1696 cleanup:
1697     sdsfree(content_padded);
1698     close(fd);
1699     return retval;
1700 }
1701 
1702 /* Rewrite the configuration file at "path".
1703  * If the configuration file already exists, we try at best to retain comments
1704  * and overall structure.
1705  *
1706  * Configuration parameters that are at their default value, unless already
1707  * explicitly included in the old configuration file, are not rewritten.
1708  *
1709  * On error -1 is returned and errno is set accordingly, otherwise 0. */
1710 int rewriteConfig(char *path) {
1711     struct rewriteConfigState *state;
1712     sds newcontent;
1713     int retval;
1714 
1715     /* Step 1: read the old config into our rewrite state. */
1716     if ((state = rewriteConfigReadOldFile(path)) == NULL) return -1;
1717 
1718     /* Step 2: rewrite every single option, replacing or appending it inside
1719      * the rewrite state. */
1720 
1721     rewriteConfigYesNoOption(state,"daemonize",server.daemonize,0);
1722     rewriteConfigStringOption(state,"pidfile",server.pidfile,REDIS_DEFAULT_PID_FILE);
1723     rewriteConfigNumericalOption(state,"port",server.port,REDIS_SERVERPORT);
1724     rewriteConfigNumericalOption(state,"tcp-backlog",server.tcp_backlog,REDIS_TCP_BACKLOG);
1725     rewriteConfigBindOption(state);
1726     rewriteConfigStringOption(state,"unixsocket",server.unixsocket,NULL);
1727     rewriteConfigOctalOption(state,"unixsocketperm",server.unixsocketperm,REDIS_DEFAULT_UNIX_SOCKET_PERM);
1728     rewriteConfigNumericalOption(state,"timeout",server.maxidletime,REDIS_MAXIDLETIME);
1729     rewriteConfigNumericalOption(state,"tcp-keepalive",server.tcpkeepalive,REDIS_DEFAULT_TCP_KEEPALIVE);
1730     rewriteConfigEnumOption(state,"loglevel",server.verbosity,
1731         "debug", REDIS_DEBUG,
1732         "verbose", REDIS_VERBOSE,
1733         "notice", REDIS_NOTICE,
1734         "warning", REDIS_WARNING,
1735         NULL, REDIS_DEFAULT_VERBOSITY);
1736     rewriteConfigStringOption(state,"logfile",server.logfile,REDIS_DEFAULT_LOGFILE);
1737     rewriteConfigYesNoOption(state,"syslog-enabled",server.syslog_enabled,REDIS_DEFAULT_SYSLOG_ENABLED);
1738     rewriteConfigStringOption(state,"syslog-ident",server.syslog_ident,REDIS_DEFAULT_SYSLOG_IDENT);
1739     rewriteConfigSyslogfacilityOption(state);
1740     rewriteConfigSaveOption(state);
1741     rewriteConfigNumericalOption(state,"databases",server.dbnum,REDIS_DEFAULT_DBNUM);
1742     rewriteConfigYesNoOption(state,"stop-writes-on-bgsave-error",server.stop_writes_on_bgsave_err,REDIS_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR);
1743     rewriteConfigYesNoOption(state,"rdbcompression",server.rdb_compression,REDIS_DEFAULT_RDB_COMPRESSION);
1744     rewriteConfigYesNoOption(state,"rdbchecksum",server.rdb_checksum,REDIS_DEFAULT_RDB_CHECKSUM);
1745     rewriteConfigStringOption(state,"dbfilename",server.rdb_filename,REDIS_DEFAULT_RDB_FILENAME);
1746     rewriteConfigDirOption(state);
1747     rewriteConfigSlaveofOption(state);
1748     rewriteConfigStringOption(state,"masterauth",server.masterauth,NULL);
1749     rewriteConfigYesNoOption(state,"slave-serve-stale-data",server.repl_serve_stale_data,REDIS_DEFAULT_SLAVE_SERVE_STALE_DATA);
1750     rewriteConfigYesNoOption(state,"slave-read-only",server.repl_slave_ro,REDIS_DEFAULT_SLAVE_READ_ONLY);
1751     rewriteConfigNumericalOption(state,"repl-ping-slave-period",server.repl_ping_slave_period,REDIS_REPL_PING_SLAVE_PERIOD);
1752     rewriteConfigNumericalOption(state,"repl-timeout",server.repl_timeout,REDIS_REPL_TIMEOUT);
1753     rewriteConfigBytesOption(state,"repl-backlog-size",server.repl_backlog_size,REDIS_DEFAULT_REPL_BACKLOG_SIZE);
1754     rewriteConfigBytesOption(state,"repl-backlog-ttl",server.repl_backlog_time_limit,REDIS_DEFAULT_REPL_BACKLOG_TIME_LIMIT);
1755     rewriteConfigYesNoOption(state,"repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay,REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY);
1756     rewriteConfigNumericalOption(state,"slave-priority",server.slave_priority,REDIS_DEFAULT_SLAVE_PRIORITY);
1757     rewriteConfigNumericalOption(state,"min-slaves-to-write",server.repl_min_slaves_to_write,REDIS_DEFAULT_MIN_SLAVES_TO_WRITE);
1758     rewriteConfigNumericalOption(state,"min-slaves-max-lag",server.repl_min_slaves_max_lag,REDIS_DEFAULT_MIN_SLAVES_MAX_LAG);
1759     rewriteConfigStringOption(state,"requirepass",server.requirepass,NULL);
1760     rewriteConfigNumericalOption(state,"maxclients",server.maxclients,REDIS_MAX_CLIENTS);
1761     rewriteConfigBytesOption(state,"maxmemory",server.maxmemory,REDIS_DEFAULT_MAXMEMORY);
1762     rewriteConfigEnumOption(state,"maxmemory-policy",server.maxmemory_policy,
1763         "volatile-lru", REDIS_MAXMEMORY_VOLATILE_LRU,
1764         "allkeys-lru", REDIS_MAXMEMORY_ALLKEYS_LRU,
1765         "volatile-random", REDIS_MAXMEMORY_VOLATILE_RANDOM,
1766         "allkeys-random", REDIS_MAXMEMORY_ALLKEYS_RANDOM,
1767         "volatile-ttl", REDIS_MAXMEMORY_VOLATILE_TTL,
1768         "noeviction", REDIS_MAXMEMORY_NO_EVICTION,
1769         NULL, REDIS_DEFAULT_MAXMEMORY_POLICY);
1770     rewriteConfigNumericalOption(state,"maxmemory-samples",server.maxmemory_samples,REDIS_DEFAULT_MAXMEMORY_SAMPLES);
1771     rewriteConfigYesNoOption(state,"appendonly",server.aof_state != REDIS_AOF_OFF,0);
1772     rewriteConfigStringOption(state,"appendfilename",server.aof_filename,REDIS_DEFAULT_AOF_FILENAME);
1773     rewriteConfigEnumOption(state,"appendfsync",server.aof_fsync,
1774         "everysec", AOF_FSYNC_EVERYSEC,
1775         "always", AOF_FSYNC_ALWAYS,
1776         "no", AOF_FSYNC_NO,
1777         NULL, REDIS_DEFAULT_AOF_FSYNC);
1778     rewriteConfigYesNoOption(state,"no-appendfsync-on-rewrite",server.aof_no_fsync_on_rewrite,REDIS_DEFAULT_AOF_NO_FSYNC_ON_REWRITE);
1779     rewriteConfigNumericalOption(state,"auto-aof-rewrite-percentage",server.aof_rewrite_perc,REDIS_AOF_REWRITE_PERC);
1780     rewriteConfigBytesOption(state,"auto-aof-rewrite-min-size",server.aof_rewrite_min_size,REDIS_AOF_REWRITE_MIN_SIZE);
1781     rewriteConfigNumericalOption(state,"lua-time-limit",server.lua_time_limit,REDIS_LUA_TIME_LIMIT);
1782     rewriteConfigYesNoOption(state,"cluster-enabled",server.cluster_enabled,0);
1783     rewriteConfigStringOption(state,"cluster-config-file",server.cluster_configfile,REDIS_DEFAULT_CLUSTER_CONFIG_FILE);
1784     rewriteConfigNumericalOption(state,"cluster-node-timeout",server.cluster_node_timeout,REDIS_CLUSTER_DEFAULT_NODE_TIMEOUT);
1785     rewriteConfigNumericalOption(state,"cluster-migration-barrier",server.cluster_migration_barrier,REDIS_CLUSTER_DEFAULT_MIGRATION_BARRIER);
1786     rewriteConfigNumericalOption(state,"cluster-slave-validity-factor",server.cluster_slave_validity_factor,REDIS_CLUSTER_DEFAULT_SLAVE_VALIDITY);
1787     rewriteConfigNumericalOption(state,"slowlog-log-slower-than",server.slowlog_log_slower_than,REDIS_SLOWLOG_LOG_SLOWER_THAN);
1788     rewriteConfigNumericalOption(state,"slowlog-max-len",server.slowlog_max_len,REDIS_SLOWLOG_MAX_LEN);
1789     rewriteConfigNotifykeyspaceeventsOption(state);
1790     rewriteConfigNumericalOption(state,"hash-max-ziplist-entries",server.hash_max_ziplist_entries,REDIS_HASH_MAX_ZIPLIST_ENTRIES);
1791     rewriteConfigNumericalOption(state,"hash-max-ziplist-value",server.hash_max_ziplist_value,REDIS_HASH_MAX_ZIPLIST_VALUE);
1792     rewriteConfigNumericalOption(state,"list-max-ziplist-entries",server.list_max_ziplist_entries,REDIS_LIST_MAX_ZIPLIST_ENTRIES);
1793     rewriteConfigNumericalOption(state,"list-max-ziplist-value",server.list_max_ziplist_value,REDIS_LIST_MAX_ZIPLIST_VALUE);
1794     rewriteConfigNumericalOption(state,"set-max-intset-entries",server.set_max_intset_entries,REDIS_SET_MAX_INTSET_ENTRIES);
1795     rewriteConfigNumericalOption(state,"zset-max-ziplist-entries",server.zset_max_ziplist_entries,REDIS_ZSET_MAX_ZIPLIST_ENTRIES);
1796     rewriteConfigNumericalOption(state,"zset-max-ziplist-value",server.zset_max_ziplist_value,REDIS_ZSET_MAX_ZIPLIST_VALUE);
1797     rewriteConfigNumericalOption(state,"hll-sparse-max-bytes",server.hll_sparse_max_bytes,REDIS_DEFAULT_HLL_SPARSE_MAX_BYTES);
1798     rewriteConfigYesNoOption(state,"activerehashing",server.activerehashing,REDIS_DEFAULT_ACTIVE_REHASHING);
1799     rewriteConfigClientoutputbufferlimitOption(state);
1800     rewriteConfigNumericalOption(state,"hz",server.hz,REDIS_DEFAULT_HZ);
1801     rewriteConfigYesNoOption(state,"aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync,REDIS_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC);
1802     if (server.sentinel_mode) rewriteConfigSentinelOption(state);
1803 
1804     /* Step 3: remove all the orphaned lines in the old file, that is, lines
1805      * that were used by a config option and are no longer used, like in case
1806      * of multiple "save" options or duplicated options. */
1807     rewriteConfigRemoveOrphaned(state);
1808 
1809     /* Step 4: generate a new configuration file from the modified state
1810      * and write it into the original file. */
1811     newcontent = rewriteConfigGetContentFromState(state);
1812     retval = rewriteConfigOverwriteFile(server.configfile,newcontent);
1813 
1814     sdsfree(newcontent);
1815     rewriteConfigReleaseState(state);
1816     return retval;
1817 }
1818 
1819 /*-----------------------------------------------------------------------------
1820  * CONFIG command entry point
1821  *----------------------------------------------------------------------------*/
1822 
1823 void configCommand(redisClient *c) {
1824     if (!strcasecmp(c->argv[1]->ptr,"set")) {
1825         if (c->argc != 4) goto badarity;
1826         configSetCommand(c);
1827     } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
1828         if (c->argc != 3) goto badarity;
1829         configGetCommand(c);
1830     } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
1831         if (c->argc != 2) goto badarity;
1832         resetServerStats();
1833         resetCommandTableStats();
1834         addReply(c,shared.ok);
1835     } else if (!strcasecmp(c->argv[1]->ptr,"rewrite")) {
1836         if (c->argc != 2) goto badarity;
1837         if (server.configfile == NULL) {
1838             addReplyError(c,"The server is running without a config file");
1839             return;
1840         }
1841         if (rewriteConfig(server.configfile) == -1) {
1842             redisLog(REDIS_WARNING,"CONFIG REWRITE failed: %s", strerror(errno));
1843             addReplyErrorFormat(c,"Rewriting config file: %s", strerror(errno));
1844         } else {
1845             redisLog(REDIS_WARNING,"CONFIG REWRITE executed with success.");
1846             addReply(c,shared.ok);
1847         }
1848     } else {
1849         addReplyError(c,
1850             "CONFIG subcommand must be one of GET, SET, RESETSTAT, REWRITE");
1851     }
1852     return;
1853 
1854 badarity:
1855     addReplyErrorFormat(c,"Wrong number of arguments for CONFIG %s",
1856         (char*) c->argv[1]->ptr);
1857 }
1858