xref: /redis-3.2.3/src/config.c (revision 897adc1c)
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_LIMIT_NUM_CLASSES] = {
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 be positive";
438                 goto loaderr;
439             }
440         } else if (!strcasecmp(argv[0],"lua-time-limit") && argc == 2) {
441             server.lua_time_limit = strtoll(argv[1],NULL,10);
442         } else if (!strcasecmp(argv[0],"slowlog-log-slower-than") &&
443                    argc == 2)
444         {
445             server.slowlog_log_slower_than = strtoll(argv[1],NULL,10);
446         } else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) {
447             server.slowlog_max_len = strtoll(argv[1],NULL,10);
448         } else if (!strcasecmp(argv[0],"client-output-buffer-limit") &&
449                    argc == 5)
450         {
451             int class = getClientLimitClassByName(argv[1]);
452             unsigned long long hard, soft;
453             int soft_seconds;
454 
455             if (class == -1) {
456                 err = "Unrecognized client limit class";
457                 goto loaderr;
458             }
459             hard = memtoll(argv[2],NULL);
460             soft = memtoll(argv[3],NULL);
461             soft_seconds = atoi(argv[4]);
462             if (soft_seconds < 0) {
463                 err = "Negative number of seconds in soft limit is invalid";
464                 goto loaderr;
465             }
466             server.client_obuf_limits[class].hard_limit_bytes = hard;
467             server.client_obuf_limits[class].soft_limit_bytes = soft;
468             server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
469         } else if (!strcasecmp(argv[0],"stop-writes-on-bgsave-error") &&
470                    argc == 2) {
471             if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) {
472                 err = "argument must be 'yes' or 'no'"; goto loaderr;
473             }
474         } else if (!strcasecmp(argv[0],"slave-priority") && argc == 2) {
475             server.slave_priority = atoi(argv[1]);
476         } else if (!strcasecmp(argv[0],"min-slaves-to-write") && argc == 2) {
477             server.repl_min_slaves_to_write = atoi(argv[1]);
478             if (server.repl_min_slaves_to_write < 0) {
479                 err = "Invalid value for min-slaves-to-write."; goto loaderr;
480             }
481         } else if (!strcasecmp(argv[0],"min-slaves-max-lag") && argc == 2) {
482             server.repl_min_slaves_max_lag = atoi(argv[1]);
483             if (server.repl_min_slaves_max_lag < 0) {
484                 err = "Invalid value for min-slaves-max-lag."; goto loaderr;
485             }
486         } else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) {
487             int flags = keyspaceEventsStringToFlags(argv[1]);
488 
489             if (flags == -1) {
490                 err = "Invalid event class character. Use 'g$lshzxeA'.";
491                 goto loaderr;
492             }
493             server.notify_keyspace_events = flags;
494         } else if (!strcasecmp(argv[0],"sentinel")) {
495             /* argc == 1 is handled by main() as we need to enter the sentinel
496              * mode ASAP. */
497             if (argc != 1) {
498                 if (!server.sentinel_mode) {
499                     err = "sentinel directive while not in sentinel mode";
500                     goto loaderr;
501                 }
502                 err = sentinelHandleConfiguration(argv+1,argc-1);
503                 if (err) goto loaderr;
504             }
505         } else {
506             err = "Bad directive or wrong number of arguments"; goto loaderr;
507         }
508         sdsfreesplitres(argv,argc);
509     }
510 
511     /* Sanity checks. */
512     if (server.cluster_enabled && server.masterhost) {
513         linenum = slaveof_linenum;
514         i = linenum-1;
515         err = "slaveof directive not allowed in cluster mode";
516         goto loaderr;
517     }
518 
519     sdsfreesplitres(lines,totlines);
520     return;
521 
522 loaderr:
523     fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
524     fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
525     fprintf(stderr, ">>> '%s'\n", lines[i]);
526     fprintf(stderr, "%s\n", err);
527     exit(1);
528 }
529 
530 /* Load the server configuration from the specified filename.
531  * The function appends the additional configuration directives stored
532  * in the 'options' string to the config file before loading.
533  *
534  * Both filename and options can be NULL, in such a case are considered
535  * empty. This way loadServerConfig can be used to just load a file or
536  * just load a string. */
537 void loadServerConfig(char *filename, char *options) {
538     sds config = sdsempty();
539     char buf[REDIS_CONFIGLINE_MAX+1];
540 
541     /* Load the file content */
542     if (filename) {
543         FILE *fp;
544 
545         if (filename[0] == '-' && filename[1] == '\0') {
546             fp = stdin;
547         } else {
548             if ((fp = fopen(filename,"r")) == NULL) {
549                 redisLog(REDIS_WARNING,
550                     "Fatal error, can't open config file '%s'", filename);
551                 exit(1);
552             }
553         }
554         while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL)
555             config = sdscat(config,buf);
556         if (fp != stdin) fclose(fp);
557     }
558     /* Append the additional options */
559     if (options) {
560         config = sdscat(config,"\n");
561         config = sdscat(config,options);
562     }
563     loadServerConfigFromString(config);
564     sdsfree(config);
565 }
566 
567 /*-----------------------------------------------------------------------------
568  * CONFIG SET implementation
569  *----------------------------------------------------------------------------*/
570 
571 void configSetCommand(redisClient *c) {
572     robj *o;
573     long long ll;
574     redisAssertWithInfo(c,c->argv[2],sdsEncodedObject(c->argv[2]));
575     redisAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3]));
576     o = c->argv[3];
577 
578     if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
579         if (!pathIsBaseName(o->ptr)) {
580             addReplyError(c, "dbfilename can't be a path, just a filename");
581             return;
582         }
583         zfree(server.rdb_filename);
584         server.rdb_filename = zstrdup(o->ptr);
585     } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
586         if (sdslen(o->ptr) > REDIS_AUTHPASS_MAX_LEN) goto badfmt;
587         zfree(server.requirepass);
588         server.requirepass = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
589     } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
590         zfree(server.masterauth);
591         server.masterauth = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
592     } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
593         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
594             ll < 0) goto badfmt;
595         server.maxmemory = ll;
596         if (server.maxmemory) {
597             if (server.maxmemory < zmalloc_used_memory()) {
598                 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.");
599             }
600             freeMemoryIfNeeded();
601         }
602     } else if (!strcasecmp(c->argv[2]->ptr,"maxclients")) {
603         int orig_value = server.maxclients;
604 
605         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 1) goto badfmt;
606 
607         /* Try to check if the OS is capable of supporting so many FDs. */
608         server.maxclients = ll;
609         if (ll > orig_value) {
610             adjustOpenFilesLimit();
611             if (server.maxclients != ll) {
612                 addReplyErrorFormat(c,"The operating system is not able to handle the specified number of clients, try with %d", server.maxclients);
613                 server.maxclients = orig_value;
614                 return;
615             }
616             if (aeGetSetSize(server.el) <
617                 server.maxclients + REDIS_EVENTLOOP_FDSET_INCR)
618             {
619                 if (aeResizeSetSize(server.el,
620                     server.maxclients + REDIS_EVENTLOOP_FDSET_INCR) == AE_ERR)
621                 {
622                     addReplyError(c,"The event loop API used by Redis is not able to handle the specified number of clients");
623                     server.maxclients = orig_value;
624                     return;
625                 }
626             }
627         }
628     } else if (!strcasecmp(c->argv[2]->ptr,"hz")) {
629         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
630         server.hz = ll;
631         if (server.hz < REDIS_MIN_HZ) server.hz = REDIS_MIN_HZ;
632         if (server.hz > REDIS_MAX_HZ) server.hz = REDIS_MAX_HZ;
633     } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory-policy")) {
634         if (!strcasecmp(o->ptr,"volatile-lru")) {
635             server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
636         } else if (!strcasecmp(o->ptr,"volatile-random")) {
637             server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_RANDOM;
638         } else if (!strcasecmp(o->ptr,"volatile-ttl")) {
639             server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_TTL;
640         } else if (!strcasecmp(o->ptr,"allkeys-lru")) {
641             server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_LRU;
642         } else if (!strcasecmp(o->ptr,"allkeys-random")) {
643             server.maxmemory_policy = REDIS_MAXMEMORY_ALLKEYS_RANDOM;
644         } else if (!strcasecmp(o->ptr,"noeviction")) {
645             server.maxmemory_policy = REDIS_MAXMEMORY_NO_EVICTION;
646         } else {
647             goto badfmt;
648         }
649     } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory-samples")) {
650         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
651             ll <= 0) goto badfmt;
652         server.maxmemory_samples = ll;
653     } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
654         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
655             ll < 0 || ll > LONG_MAX) goto badfmt;
656         server.maxidletime = ll;
657     } else if (!strcasecmp(c->argv[2]->ptr,"tcp-keepalive")) {
658         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
659             ll < 0 || ll > INT_MAX) goto badfmt;
660         server.tcpkeepalive = ll;
661     } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
662         if (!strcasecmp(o->ptr,"no")) {
663             server.aof_fsync = AOF_FSYNC_NO;
664         } else if (!strcasecmp(o->ptr,"everysec")) {
665             server.aof_fsync = AOF_FSYNC_EVERYSEC;
666         } else if (!strcasecmp(o->ptr,"always")) {
667             server.aof_fsync = AOF_FSYNC_ALWAYS;
668         } else {
669             goto badfmt;
670         }
671     } else if (!strcasecmp(c->argv[2]->ptr,"no-appendfsync-on-rewrite")) {
672         int yn = yesnotoi(o->ptr);
673 
674         if (yn == -1) goto badfmt;
675         server.aof_no_fsync_on_rewrite = yn;
676     } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
677         int enable = yesnotoi(o->ptr);
678 
679         if (enable == -1) goto badfmt;
680         if (enable == 0 && server.aof_state != REDIS_AOF_OFF) {
681             stopAppendOnly();
682         } else if (enable && server.aof_state == REDIS_AOF_OFF) {
683             if (startAppendOnly() == REDIS_ERR) {
684                 addReplyError(c,
685                     "Unable to turn on AOF. Check server logs.");
686                 return;
687             }
688         }
689     } else if (!strcasecmp(c->argv[2]->ptr,"auto-aof-rewrite-percentage")) {
690         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
691         server.aof_rewrite_perc = ll;
692     } else if (!strcasecmp(c->argv[2]->ptr,"auto-aof-rewrite-min-size")) {
693         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
694         server.aof_rewrite_min_size = ll;
695     } else if (!strcasecmp(c->argv[2]->ptr,"aof-rewrite-incremental-fsync")) {
696         int yn = yesnotoi(o->ptr);
697 
698         if (yn == -1) goto badfmt;
699         server.aof_rewrite_incremental_fsync = yn;
700     } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
701         int vlen, j;
702         sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
703 
704         /* Perform sanity check before setting the new config:
705          * - Even number of args
706          * - Seconds >= 1, changes >= 0 */
707         if (vlen & 1) {
708             sdsfreesplitres(v,vlen);
709             goto badfmt;
710         }
711         for (j = 0; j < vlen; j++) {
712             char *eptr;
713             long val;
714 
715             val = strtoll(v[j], &eptr, 10);
716             if (eptr[0] != '\0' ||
717                 ((j & 1) == 0 && val < 1) ||
718                 ((j & 1) == 1 && val < 0)) {
719                 sdsfreesplitres(v,vlen);
720                 goto badfmt;
721             }
722         }
723         /* Finally set the new config */
724         resetServerSaveParams();
725         for (j = 0; j < vlen; j += 2) {
726             time_t seconds;
727             int changes;
728 
729             seconds = strtoll(v[j],NULL,10);
730             changes = strtoll(v[j+1],NULL,10);
731             appendServerSaveParams(seconds, changes);
732         }
733         sdsfreesplitres(v,vlen);
734     } else if (!strcasecmp(c->argv[2]->ptr,"slave-serve-stale-data")) {
735         int yn = yesnotoi(o->ptr);
736 
737         if (yn == -1) goto badfmt;
738         server.repl_serve_stale_data = yn;
739     } else if (!strcasecmp(c->argv[2]->ptr,"slave-read-only")) {
740         int yn = yesnotoi(o->ptr);
741 
742         if (yn == -1) goto badfmt;
743         server.repl_slave_ro = yn;
744     } else if (!strcasecmp(c->argv[2]->ptr,"dir")) {
745         if (chdir((char*)o->ptr) == -1) {
746             addReplyErrorFormat(c,"Changing directory: %s", strerror(errno));
747             return;
748         }
749     } else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-entries")) {
750         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
751         server.hash_max_ziplist_entries = ll;
752     } else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-value")) {
753         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
754         server.hash_max_ziplist_value = ll;
755     } else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-entries")) {
756         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
757         server.list_max_ziplist_entries = ll;
758     } else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-value")) {
759         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
760         server.list_max_ziplist_value = ll;
761     } else if (!strcasecmp(c->argv[2]->ptr,"set-max-intset-entries")) {
762         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
763         server.set_max_intset_entries = ll;
764     } else if (!strcasecmp(c->argv[2]->ptr,"zset-max-ziplist-entries")) {
765         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
766         server.zset_max_ziplist_entries = ll;
767     } else if (!strcasecmp(c->argv[2]->ptr,"zset-max-ziplist-value")) {
768         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
769         server.zset_max_ziplist_value = ll;
770     } else if (!strcasecmp(c->argv[2]->ptr,"hll-sparse-max-bytes")) {
771         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
772         server.hll_sparse_max_bytes = ll;
773     } else if (!strcasecmp(c->argv[2]->ptr,"lua-time-limit")) {
774         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
775         server.lua_time_limit = ll;
776     } else if (!strcasecmp(c->argv[2]->ptr,"slowlog-log-slower-than")) {
777         if (getLongLongFromObject(o,&ll) == REDIS_ERR) goto badfmt;
778         server.slowlog_log_slower_than = ll;
779     } else if (!strcasecmp(c->argv[2]->ptr,"slowlog-max-len")) {
780         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
781         server.slowlog_max_len = (unsigned)ll;
782     } else if (!strcasecmp(c->argv[2]->ptr,"loglevel")) {
783         if (!strcasecmp(o->ptr,"warning")) {
784             server.verbosity = REDIS_WARNING;
785         } else if (!strcasecmp(o->ptr,"notice")) {
786             server.verbosity = REDIS_NOTICE;
787         } else if (!strcasecmp(o->ptr,"verbose")) {
788             server.verbosity = REDIS_VERBOSE;
789         } else if (!strcasecmp(o->ptr,"debug")) {
790             server.verbosity = REDIS_DEBUG;
791         } else {
792             goto badfmt;
793         }
794     } else if (!strcasecmp(c->argv[2]->ptr,"client-output-buffer-limit")) {
795         int vlen, j;
796         sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
797 
798         /* We need a multiple of 4: <class> <hard> <soft> <soft_seconds> */
799         if (vlen % 4) {
800             sdsfreesplitres(v,vlen);
801             goto badfmt;
802         }
803 
804         /* Sanity check of single arguments, so that we either refuse the
805          * whole configuration string or accept it all, even if a single
806          * error in a single client class is present. */
807         for (j = 0; j < vlen; j++) {
808             char *eptr;
809             long val;
810 
811             if ((j % 4) == 0) {
812                 if (getClientLimitClassByName(v[j]) == -1) {
813                     sdsfreesplitres(v,vlen);
814                     goto badfmt;
815                 }
816             } else {
817                 val = strtoll(v[j], &eptr, 10);
818                 if (eptr[0] != '\0' || val < 0) {
819                     sdsfreesplitres(v,vlen);
820                     goto badfmt;
821                 }
822             }
823         }
824         /* Finally set the new config */
825         for (j = 0; j < vlen; j += 4) {
826             int class;
827             unsigned long long hard, soft;
828             int soft_seconds;
829 
830             class = getClientLimitClassByName(v[j]);
831             hard = strtoll(v[j+1],NULL,10);
832             soft = strtoll(v[j+2],NULL,10);
833             soft_seconds = strtoll(v[j+3],NULL,10);
834 
835             server.client_obuf_limits[class].hard_limit_bytes = hard;
836             server.client_obuf_limits[class].soft_limit_bytes = soft;
837             server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
838         }
839         sdsfreesplitres(v,vlen);
840     } else if (!strcasecmp(c->argv[2]->ptr,"stop-writes-on-bgsave-error")) {
841         int yn = yesnotoi(o->ptr);
842 
843         if (yn == -1) goto badfmt;
844         server.stop_writes_on_bgsave_err = yn;
845     } else if (!strcasecmp(c->argv[2]->ptr,"repl-ping-slave-period")) {
846         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
847         server.repl_ping_slave_period = ll;
848     } else if (!strcasecmp(c->argv[2]->ptr,"repl-timeout")) {
849         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
850         server.repl_timeout = ll;
851     } else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-size")) {
852         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
853         resizeReplicationBacklog(ll);
854     } else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-ttl")) {
855         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
856         server.repl_backlog_time_limit = ll;
857     } else if (!strcasecmp(c->argv[2]->ptr,"watchdog-period")) {
858         if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
859         if (ll)
860             enableWatchdog(ll);
861         else
862             disableWatchdog();
863     } else if (!strcasecmp(c->argv[2]->ptr,"rdbcompression")) {
864         int yn = yesnotoi(o->ptr);
865 
866         if (yn == -1) goto badfmt;
867         server.rdb_compression = yn;
868     } else if (!strcasecmp(c->argv[2]->ptr,"notify-keyspace-events")) {
869         int flags = keyspaceEventsStringToFlags(o->ptr);
870 
871         if (flags == -1) goto badfmt;
872         server.notify_keyspace_events = flags;
873     } else if (!strcasecmp(c->argv[2]->ptr,"repl-disable-tcp-nodelay")) {
874         int yn = yesnotoi(o->ptr);
875 
876         if (yn == -1) goto badfmt;
877         server.repl_disable_tcp_nodelay = yn;
878     } else if (!strcasecmp(c->argv[2]->ptr,"slave-priority")) {
879         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
880             ll < 0) goto badfmt;
881         server.slave_priority = ll;
882     } else if (!strcasecmp(c->argv[2]->ptr,"min-slaves-to-write")) {
883         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
884             ll < 0) goto badfmt;
885         server.repl_min_slaves_to_write = ll;
886         refreshGoodSlavesCount();
887     } else if (!strcasecmp(c->argv[2]->ptr,"min-slaves-max-lag")) {
888         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
889             ll < 0) goto badfmt;
890         server.repl_min_slaves_max_lag = ll;
891         refreshGoodSlavesCount();
892     } else if (!strcasecmp(c->argv[2]->ptr,"cluster-node-timeout")) {
893         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
894             ll <= 0) goto badfmt;
895         server.cluster_node_timeout = ll;
896     } else if (!strcasecmp(c->argv[2]->ptr,"cluster-migration-barrier")) {
897         if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
898             ll < 0) goto badfmt;
899         server.cluster_migration_barrier = ll;
900     } else {
901         addReplyErrorFormat(c,"Unsupported CONFIG parameter: %s",
902             (char*)c->argv[2]->ptr);
903         return;
904     }
905     addReply(c,shared.ok);
906     return;
907 
908 badfmt: /* Bad format errors */
909     addReplyErrorFormat(c,"Invalid argument '%s' for CONFIG SET '%s'",
910             (char*)o->ptr,
911             (char*)c->argv[2]->ptr);
912 }
913 
914 /*-----------------------------------------------------------------------------
915  * CONFIG GET implementation
916  *----------------------------------------------------------------------------*/
917 
918 #define config_get_string_field(_name,_var) do { \
919     if (stringmatch(pattern,_name,0)) { \
920         addReplyBulkCString(c,_name); \
921         addReplyBulkCString(c,_var ? _var : ""); \
922         matches++; \
923     } \
924 } while(0);
925 
926 #define config_get_bool_field(_name,_var) do { \
927     if (stringmatch(pattern,_name,0)) { \
928         addReplyBulkCString(c,_name); \
929         addReplyBulkCString(c,_var ? "yes" : "no"); \
930         matches++; \
931     } \
932 } while(0);
933 
934 #define config_get_numerical_field(_name,_var) do { \
935     if (stringmatch(pattern,_name,0)) { \
936         ll2string(buf,sizeof(buf),_var); \
937         addReplyBulkCString(c,_name); \
938         addReplyBulkCString(c,buf); \
939         matches++; \
940     } \
941 } while(0);
942 
943 void configGetCommand(redisClient *c) {
944     robj *o = c->argv[2];
945     void *replylen = addDeferredMultiBulkLength(c);
946     char *pattern = o->ptr;
947     char buf[128];
948     int matches = 0;
949     redisAssertWithInfo(c,o,sdsEncodedObject(o));
950 
951     /* String values */
952     config_get_string_field("dbfilename",server.rdb_filename);
953     config_get_string_field("requirepass",server.requirepass);
954     config_get_string_field("masterauth",server.masterauth);
955     config_get_string_field("unixsocket",server.unixsocket);
956     config_get_string_field("logfile",server.logfile);
957     config_get_string_field("pidfile",server.pidfile);
958 
959     /* Numerical values */
960     config_get_numerical_field("maxmemory",server.maxmemory);
961     config_get_numerical_field("maxmemory-samples",server.maxmemory_samples);
962     config_get_numerical_field("timeout",server.maxidletime);
963     config_get_numerical_field("tcp-keepalive",server.tcpkeepalive);
964     config_get_numerical_field("auto-aof-rewrite-percentage",
965             server.aof_rewrite_perc);
966     config_get_numerical_field("auto-aof-rewrite-min-size",
967             server.aof_rewrite_min_size);
968     config_get_numerical_field("hash-max-ziplist-entries",
969             server.hash_max_ziplist_entries);
970     config_get_numerical_field("hash-max-ziplist-value",
971             server.hash_max_ziplist_value);
972     config_get_numerical_field("list-max-ziplist-entries",
973             server.list_max_ziplist_entries);
974     config_get_numerical_field("list-max-ziplist-value",
975             server.list_max_ziplist_value);
976     config_get_numerical_field("set-max-intset-entries",
977             server.set_max_intset_entries);
978     config_get_numerical_field("zset-max-ziplist-entries",
979             server.zset_max_ziplist_entries);
980     config_get_numerical_field("zset-max-ziplist-value",
981             server.zset_max_ziplist_value);
982     config_get_numerical_field("hll-sparse-max-bytes",
983             server.hll_sparse_max_bytes);
984     config_get_numerical_field("lua-time-limit",server.lua_time_limit);
985     config_get_numerical_field("slowlog-log-slower-than",
986             server.slowlog_log_slower_than);
987     config_get_numerical_field("slowlog-max-len",
988             server.slowlog_max_len);
989     config_get_numerical_field("port",server.port);
990     config_get_numerical_field("tcp-backlog",server.tcp_backlog);
991     config_get_numerical_field("databases",server.dbnum);
992     config_get_numerical_field("repl-ping-slave-period",server.repl_ping_slave_period);
993     config_get_numerical_field("repl-timeout",server.repl_timeout);
994     config_get_numerical_field("repl-backlog-size",server.repl_backlog_size);
995     config_get_numerical_field("repl-backlog-ttl",server.repl_backlog_time_limit);
996     config_get_numerical_field("maxclients",server.maxclients);
997     config_get_numerical_field("watchdog-period",server.watchdog_period);
998     config_get_numerical_field("slave-priority",server.slave_priority);
999     config_get_numerical_field("min-slaves-to-write",server.repl_min_slaves_to_write);
1000     config_get_numerical_field("min-slaves-max-lag",server.repl_min_slaves_max_lag);
1001     config_get_numerical_field("hz",server.hz);
1002     config_get_numerical_field("cluster-node-timeout",server.cluster_node_timeout);
1003     config_get_numerical_field("cluster-migration-barrier",server.cluster_migration_barrier);
1004 
1005     /* Bool (yes/no) values */
1006     config_get_bool_field("no-appendfsync-on-rewrite",
1007             server.aof_no_fsync_on_rewrite);
1008     config_get_bool_field("slave-serve-stale-data",
1009             server.repl_serve_stale_data);
1010     config_get_bool_field("slave-read-only",
1011             server.repl_slave_ro);
1012     config_get_bool_field("stop-writes-on-bgsave-error",
1013             server.stop_writes_on_bgsave_err);
1014     config_get_bool_field("daemonize", server.daemonize);
1015     config_get_bool_field("rdbcompression", server.rdb_compression);
1016     config_get_bool_field("rdbchecksum", server.rdb_checksum);
1017     config_get_bool_field("activerehashing", server.activerehashing);
1018     config_get_bool_field("repl-disable-tcp-nodelay",
1019             server.repl_disable_tcp_nodelay);
1020     config_get_bool_field("aof-rewrite-incremental-fsync",
1021             server.aof_rewrite_incremental_fsync);
1022 
1023     /* Everything we can't handle with macros follows. */
1024 
1025     if (stringmatch(pattern,"appendonly",0)) {
1026         addReplyBulkCString(c,"appendonly");
1027         addReplyBulkCString(c,server.aof_state == REDIS_AOF_OFF ? "no" : "yes");
1028         matches++;
1029     }
1030     if (stringmatch(pattern,"dir",0)) {
1031         char buf[1024];
1032 
1033         if (getcwd(buf,sizeof(buf)) == NULL)
1034             buf[0] = '\0';
1035 
1036         addReplyBulkCString(c,"dir");
1037         addReplyBulkCString(c,buf);
1038         matches++;
1039     }
1040     if (stringmatch(pattern,"maxmemory-policy",0)) {
1041         char *s;
1042 
1043         switch(server.maxmemory_policy) {
1044         case REDIS_MAXMEMORY_VOLATILE_LRU: s = "volatile-lru"; break;
1045         case REDIS_MAXMEMORY_VOLATILE_TTL: s = "volatile-ttl"; break;
1046         case REDIS_MAXMEMORY_VOLATILE_RANDOM: s = "volatile-random"; break;
1047         case REDIS_MAXMEMORY_ALLKEYS_LRU: s = "allkeys-lru"; break;
1048         case REDIS_MAXMEMORY_ALLKEYS_RANDOM: s = "allkeys-random"; break;
1049         case REDIS_MAXMEMORY_NO_EVICTION: s = "noeviction"; break;
1050         default: s = "unknown"; break; /* too harmless to panic */
1051         }
1052         addReplyBulkCString(c,"maxmemory-policy");
1053         addReplyBulkCString(c,s);
1054         matches++;
1055     }
1056     if (stringmatch(pattern,"appendfsync",0)) {
1057         char *policy;
1058 
1059         switch(server.aof_fsync) {
1060         case AOF_FSYNC_NO: policy = "no"; break;
1061         case AOF_FSYNC_EVERYSEC: policy = "everysec"; break;
1062         case AOF_FSYNC_ALWAYS: policy = "always"; break;
1063         default: policy = "unknown"; break; /* too harmless to panic */
1064         }
1065         addReplyBulkCString(c,"appendfsync");
1066         addReplyBulkCString(c,policy);
1067         matches++;
1068     }
1069     if (stringmatch(pattern,"save",0)) {
1070         sds buf = sdsempty();
1071         int j;
1072 
1073         for (j = 0; j < server.saveparamslen; j++) {
1074             buf = sdscatprintf(buf,"%jd %d",
1075                     (intmax_t)server.saveparams[j].seconds,
1076                     server.saveparams[j].changes);
1077             if (j != server.saveparamslen-1)
1078                 buf = sdscatlen(buf," ",1);
1079         }
1080         addReplyBulkCString(c,"save");
1081         addReplyBulkCString(c,buf);
1082         sdsfree(buf);
1083         matches++;
1084     }
1085     if (stringmatch(pattern,"loglevel",0)) {
1086         char *s;
1087 
1088         switch(server.verbosity) {
1089         case REDIS_WARNING: s = "warning"; break;
1090         case REDIS_VERBOSE: s = "verbose"; break;
1091         case REDIS_NOTICE: s = "notice"; break;
1092         case REDIS_DEBUG: s = "debug"; break;
1093         default: s = "unknown"; break; /* too harmless to panic */
1094         }
1095         addReplyBulkCString(c,"loglevel");
1096         addReplyBulkCString(c,s);
1097         matches++;
1098     }
1099     if (stringmatch(pattern,"client-output-buffer-limit",0)) {
1100         sds buf = sdsempty();
1101         int j;
1102 
1103         for (j = 0; j < REDIS_CLIENT_LIMIT_NUM_CLASSES; j++) {
1104             buf = sdscatprintf(buf,"%s %llu %llu %ld",
1105                     getClientLimitClassName(j),
1106                     server.client_obuf_limits[j].hard_limit_bytes,
1107                     server.client_obuf_limits[j].soft_limit_bytes,
1108                     (long) server.client_obuf_limits[j].soft_limit_seconds);
1109             if (j != REDIS_CLIENT_LIMIT_NUM_CLASSES-1)
1110                 buf = sdscatlen(buf," ",1);
1111         }
1112         addReplyBulkCString(c,"client-output-buffer-limit");
1113         addReplyBulkCString(c,buf);
1114         sdsfree(buf);
1115         matches++;
1116     }
1117     if (stringmatch(pattern,"unixsocketperm",0)) {
1118         char buf[32];
1119         snprintf(buf,sizeof(buf),"%o",server.unixsocketperm);
1120         addReplyBulkCString(c,"unixsocketperm");
1121         addReplyBulkCString(c,buf);
1122         matches++;
1123     }
1124     if (stringmatch(pattern,"slaveof",0)) {
1125         char buf[256];
1126 
1127         addReplyBulkCString(c,"slaveof");
1128         if (server.masterhost)
1129             snprintf(buf,sizeof(buf),"%s %d",
1130                 server.masterhost, server.masterport);
1131         else
1132             buf[0] = '\0';
1133         addReplyBulkCString(c,buf);
1134         matches++;
1135     }
1136     if (stringmatch(pattern,"notify-keyspace-events",0)) {
1137         robj *flagsobj = createObject(REDIS_STRING,
1138             keyspaceEventsFlagsToString(server.notify_keyspace_events));
1139 
1140         addReplyBulkCString(c,"notify-keyspace-events");
1141         addReplyBulk(c,flagsobj);
1142         decrRefCount(flagsobj);
1143         matches++;
1144     }
1145     if (stringmatch(pattern,"bind",0)) {
1146         sds aux = sdsjoin(server.bindaddr,server.bindaddr_count," ");
1147 
1148         addReplyBulkCString(c,"bind");
1149         addReplyBulkCString(c,aux);
1150         sdsfree(aux);
1151         matches++;
1152     }
1153     setDeferredMultiBulkLength(c,replylen,matches*2);
1154 }
1155 
1156 /*-----------------------------------------------------------------------------
1157  * CONFIG REWRITE implementation
1158  *----------------------------------------------------------------------------*/
1159 
1160 #define REDIS_CONFIG_REWRITE_SIGNATURE "# Generated by CONFIG REWRITE"
1161 
1162 /* We use the following dictionary type to store where a configuration
1163  * option is mentioned in the old configuration file, so it's
1164  * like "maxmemory" -> list of line numbers (first line is zero). */
1165 unsigned int dictSdsCaseHash(const void *key);
1166 int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2);
1167 void dictSdsDestructor(void *privdata, void *val);
1168 void dictListDestructor(void *privdata, void *val);
1169 
1170 /* Sentinel config rewriting is implemented inside sentinel.c by
1171  * rewriteConfigSentinelOption(). */
1172 void rewriteConfigSentinelOption(struct rewriteConfigState *state);
1173 
1174 dictType optionToLineDictType = {
1175     dictSdsCaseHash,            /* hash function */
1176     NULL,                       /* key dup */
1177     NULL,                       /* val dup */
1178     dictSdsKeyCaseCompare,      /* key compare */
1179     dictSdsDestructor,          /* key destructor */
1180     dictListDestructor          /* val destructor */
1181 };
1182 
1183 dictType optionSetDictType = {
1184     dictSdsCaseHash,            /* hash function */
1185     NULL,                       /* key dup */
1186     NULL,                       /* val dup */
1187     dictSdsKeyCaseCompare,      /* key compare */
1188     dictSdsDestructor,          /* key destructor */
1189     NULL                        /* val destructor */
1190 };
1191 
1192 /* The config rewrite state. */
1193 struct rewriteConfigState {
1194     dict *option_to_line; /* Option -> list of config file lines map */
1195     dict *rewritten;      /* Dictionary of already processed options */
1196     int numlines;         /* Number of lines in current config */
1197     sds *lines;           /* Current lines as an array of sds strings */
1198     int has_tail;         /* True if we already added directives that were
1199                              not present in the original config file. */
1200 };
1201 
1202 /* Append the new line to the current configuration state. */
1203 void rewriteConfigAppendLine(struct rewriteConfigState *state, sds line) {
1204     state->lines = zrealloc(state->lines, sizeof(char*) * (state->numlines+1));
1205     state->lines[state->numlines++] = line;
1206 }
1207 
1208 /* Populate the option -> list of line numbers map. */
1209 void rewriteConfigAddLineNumberToOption(struct rewriteConfigState *state, sds option, int linenum) {
1210     list *l = dictFetchValue(state->option_to_line,option);
1211 
1212     if (l == NULL) {
1213         l = listCreate();
1214         dictAdd(state->option_to_line,sdsdup(option),l);
1215     }
1216     listAddNodeTail(l,(void*)(long)linenum);
1217 }
1218 
1219 /* Add the specified option to the set of processed options.
1220  * This is useful as only unused lines of processed options will be blanked
1221  * in the config file, while options the rewrite process does not understand
1222  * remain untouched. */
1223 void rewriteConfigMarkAsProcessed(struct rewriteConfigState *state, char *option) {
1224     sds opt = sdsnew(option);
1225 
1226     if (dictAdd(state->rewritten,opt,NULL) != DICT_OK) sdsfree(opt);
1227 }
1228 
1229 /* Read the old file, split it into lines to populate a newly created
1230  * config rewrite state, and return it to the caller.
1231  *
1232  * If it is impossible to read the old file, NULL is returned.
1233  * If the old file does not exist at all, an empty state is returned. */
1234 struct rewriteConfigState *rewriteConfigReadOldFile(char *path) {
1235     FILE *fp = fopen(path,"r");
1236     struct rewriteConfigState *state = zmalloc(sizeof(*state));
1237     char buf[REDIS_CONFIGLINE_MAX+1];
1238     int linenum = -1;
1239 
1240     if (fp == NULL && errno != ENOENT) return NULL;
1241 
1242     state->option_to_line = dictCreate(&optionToLineDictType,NULL);
1243     state->rewritten = dictCreate(&optionSetDictType,NULL);
1244     state->numlines = 0;
1245     state->lines = NULL;
1246     state->has_tail = 0;
1247     if (fp == NULL) return state;
1248 
1249     /* Read the old file line by line, populate the state. */
1250     while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1251         int argc;
1252         sds *argv;
1253         sds line = sdstrim(sdsnew(buf),"\r\n\t ");
1254 
1255         linenum++; /* Zero based, so we init at -1 */
1256 
1257         /* Handle comments and empty lines. */
1258         if (line[0] == '#' || line[0] == '\0') {
1259             if (!state->has_tail && !strcmp(line,REDIS_CONFIG_REWRITE_SIGNATURE))
1260                 state->has_tail = 1;
1261             rewriteConfigAppendLine(state,line);
1262             continue;
1263         }
1264 
1265         /* Not a comment, split into arguments. */
1266         argv = sdssplitargs(line,&argc);
1267         if (argv == NULL) {
1268             /* Apparently the line is unparsable for some reason, for
1269              * instance it may have unbalanced quotes. Load it as a
1270              * comment. */
1271             sds aux = sdsnew("# ??? ");
1272             aux = sdscatsds(aux,line);
1273             sdsfree(line);
1274             rewriteConfigAppendLine(state,aux);
1275             continue;
1276         }
1277 
1278         sdstolower(argv[0]); /* We only want lowercase config directives. */
1279 
1280         /* Now we populate the state according to the content of this line.
1281          * Append the line and populate the option -> line numbers map. */
1282         rewriteConfigAppendLine(state,line);
1283         rewriteConfigAddLineNumberToOption(state,argv[0],linenum);
1284 
1285         sdsfreesplitres(argv,argc);
1286     }
1287     fclose(fp);
1288     return state;
1289 }
1290 
1291 /* Rewrite the specified configuration option with the new "line".
1292  * It progressively uses lines of the file that were already used for the same
1293  * configuration option in the old version of the file, removing that line from
1294  * the map of options -> line numbers.
1295  *
1296  * If there are lines associated with a given configuration option and
1297  * "force" is non-zero, the line is appended to the configuration file.
1298  * Usually "force" is true when an option has not its default value, so it
1299  * must be rewritten even if not present previously.
1300  *
1301  * The first time a line is appended into a configuration file, a comment
1302  * is added to show that starting from that point the config file was generated
1303  * by CONFIG REWRITE.
1304  *
1305  * "line" is either used, or freed, so the caller does not need to free it
1306  * in any way. */
1307 void rewriteConfigRewriteLine(struct rewriteConfigState *state, char *option, sds line, int force) {
1308     sds o = sdsnew(option);
1309     list *l = dictFetchValue(state->option_to_line,o);
1310 
1311     rewriteConfigMarkAsProcessed(state,option);
1312 
1313     if (!l && !force) {
1314         /* Option not used previously, and we are not forced to use it. */
1315         sdsfree(line);
1316         sdsfree(o);
1317         return;
1318     }
1319 
1320     if (l) {
1321         listNode *ln = listFirst(l);
1322         int linenum = (long) ln->value;
1323 
1324         /* There are still lines in the old configuration file we can reuse
1325          * for this option. Replace the line with the new one. */
1326         listDelNode(l,ln);
1327         if (listLength(l) == 0) dictDelete(state->option_to_line,o);
1328         sdsfree(state->lines[linenum]);
1329         state->lines[linenum] = line;
1330     } else {
1331         /* Append a new line. */
1332         if (!state->has_tail) {
1333             rewriteConfigAppendLine(state,
1334                 sdsnew(REDIS_CONFIG_REWRITE_SIGNATURE));
1335             state->has_tail = 1;
1336         }
1337         rewriteConfigAppendLine(state,line);
1338     }
1339     sdsfree(o);
1340 }
1341 
1342 /* Write the long long 'bytes' value as a string in a way that is parsable
1343  * inside redis.conf. If possible uses the GB, MB, KB notation. */
1344 int rewriteConfigFormatMemory(char *buf, size_t len, long long bytes) {
1345     int gb = 1024*1024*1024;
1346     int mb = 1024*1024;
1347     int kb = 1024;
1348 
1349     if (bytes && (bytes % gb) == 0) {
1350         return snprintf(buf,len,"%lldgb",bytes/gb);
1351     } else if (bytes && (bytes % mb) == 0) {
1352         return snprintf(buf,len,"%lldmb",bytes/mb);
1353     } else if (bytes && (bytes % kb) == 0) {
1354         return snprintf(buf,len,"%lldkb",bytes/kb);
1355     } else {
1356         return snprintf(buf,len,"%lld",bytes);
1357     }
1358 }
1359 
1360 /* Rewrite a simple "option-name <bytes>" configuration option. */
1361 void rewriteConfigBytesOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) {
1362     char buf[64];
1363     int force = value != defvalue;
1364     sds line;
1365 
1366     rewriteConfigFormatMemory(buf,sizeof(buf),value);
1367     line = sdscatprintf(sdsempty(),"%s %s",option,buf);
1368     rewriteConfigRewriteLine(state,option,line,force);
1369 }
1370 
1371 /* Rewrite a yes/no option. */
1372 void rewriteConfigYesNoOption(struct rewriteConfigState *state, char *option, int value, int defvalue) {
1373     int force = value != defvalue;
1374     sds line = sdscatprintf(sdsempty(),"%s %s",option,
1375         value ? "yes" : "no");
1376 
1377     rewriteConfigRewriteLine(state,option,line,force);
1378 }
1379 
1380 /* Rewrite a string option. */
1381 void rewriteConfigStringOption(struct rewriteConfigState *state, char *option, char *value, char *defvalue) {
1382     int force = 1;
1383     sds line;
1384 
1385     /* String options set to NULL need to be not present at all in the
1386      * configuration file to be set to NULL again at the next reboot. */
1387     if (value == NULL) {
1388         rewriteConfigMarkAsProcessed(state,option);
1389         return;
1390     }
1391 
1392     /* Compare the strings as sds strings to have a binary safe comparison. */
1393     if (defvalue && strcmp(value,defvalue) == 0) force = 0;
1394 
1395     line = sdsnew(option);
1396     line = sdscatlen(line, " ", 1);
1397     line = sdscatrepr(line, value, strlen(value));
1398 
1399     rewriteConfigRewriteLine(state,option,line,force);
1400 }
1401 
1402 /* Rewrite a numerical (long long range) option. */
1403 void rewriteConfigNumericalOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) {
1404     int force = value != defvalue;
1405     sds line = sdscatprintf(sdsempty(),"%s %lld",option,value);
1406 
1407     rewriteConfigRewriteLine(state,option,line,force);
1408 }
1409 
1410 /* Rewrite a octal option. */
1411 void rewriteConfigOctalOption(struct rewriteConfigState *state, char *option, int value, int defvalue) {
1412     int force = value != defvalue;
1413     sds line = sdscatprintf(sdsempty(),"%s %o",option,value);
1414 
1415     rewriteConfigRewriteLine(state,option,line,force);
1416 }
1417 
1418 /* Rewrite an enumeration option, after the "value" every enum/value pair
1419  * is specified, terminated by NULL. After NULL the default value is
1420  * specified. See how the function is used for more information. */
1421 void rewriteConfigEnumOption(struct rewriteConfigState *state, char *option, int value, ...) {
1422     va_list ap;
1423     char *enum_name, *matching_name = NULL;
1424     int enum_val, def_val, force;
1425     sds line;
1426 
1427     va_start(ap, value);
1428     while(1) {
1429         enum_name = va_arg(ap,char*);
1430         enum_val = va_arg(ap,int);
1431         if (enum_name == NULL) {
1432             def_val = enum_val;
1433             break;
1434         }
1435         if (value == enum_val) matching_name = enum_name;
1436     }
1437     va_end(ap);
1438 
1439     force = value != def_val;
1440     line = sdscatprintf(sdsempty(),"%s %s",option,matching_name);
1441     rewriteConfigRewriteLine(state,option,line,force);
1442 }
1443 
1444 /* Rewrite the syslog-fability option. */
1445 void rewriteConfigSyslogfacilityOption(struct rewriteConfigState *state) {
1446     int value = server.syslog_facility, j;
1447     int force = value != LOG_LOCAL0;
1448     char *name = NULL, *option = "syslog-facility";
1449     sds line;
1450 
1451     for (j = 0; validSyslogFacilities[j].name; j++) {
1452         if (validSyslogFacilities[j].value == value) {
1453             name = (char*) validSyslogFacilities[j].name;
1454             break;
1455         }
1456     }
1457     line = sdscatprintf(sdsempty(),"%s %s",option,name);
1458     rewriteConfigRewriteLine(state,option,line,force);
1459 }
1460 
1461 /* Rewrite the save option. */
1462 void rewriteConfigSaveOption(struct rewriteConfigState *state) {
1463     int j;
1464     sds line;
1465 
1466     /* Note that if there are no save parameters at all, all the current
1467      * config line with "save" will be detected as orphaned and deleted,
1468      * resulting into no RDB persistence as expected. */
1469     for (j = 0; j < server.saveparamslen; j++) {
1470         line = sdscatprintf(sdsempty(),"save %ld %d",
1471             (long) server.saveparams[j].seconds, server.saveparams[j].changes);
1472         rewriteConfigRewriteLine(state,"save",line,1);
1473     }
1474     /* Mark "save" as processed in case server.saveparamslen is zero. */
1475     rewriteConfigMarkAsProcessed(state,"save");
1476 }
1477 
1478 /* Rewrite the dir option, always using absolute paths.*/
1479 void rewriteConfigDirOption(struct rewriteConfigState *state) {
1480     char cwd[1024];
1481 
1482     if (getcwd(cwd,sizeof(cwd)) == NULL) {
1483         rewriteConfigMarkAsProcessed(state,"dir");
1484         return; /* no rewrite on error. */
1485     }
1486     rewriteConfigStringOption(state,"dir",cwd,NULL);
1487 }
1488 
1489 /* Rewrite the slaveof option. */
1490 void rewriteConfigSlaveofOption(struct rewriteConfigState *state) {
1491     char *option = "slaveof";
1492     sds line;
1493 
1494     /* If this is a master, we want all the slaveof config options
1495      * in the file to be removed. Note that if this is a cluster instance
1496      * we don't want a slaveof directive inside redis.conf. */
1497     if (server.cluster_enabled || server.masterhost == NULL) {
1498         rewriteConfigMarkAsProcessed(state,"slaveof");
1499         return;
1500     }
1501     line = sdscatprintf(sdsempty(),"%s %s %d", option,
1502         server.masterhost, server.masterport);
1503     rewriteConfigRewriteLine(state,option,line,1);
1504 }
1505 
1506 /* Rewrite the notify-keyspace-events option. */
1507 void rewriteConfigNotifykeyspaceeventsOption(struct rewriteConfigState *state) {
1508     int force = server.notify_keyspace_events != 0;
1509     char *option = "notify-keyspace-events";
1510     sds line, flags;
1511 
1512     flags = keyspaceEventsFlagsToString(server.notify_keyspace_events);
1513     line = sdsnew(option);
1514     line = sdscatlen(line, " ", 1);
1515     line = sdscatrepr(line, flags, sdslen(flags));
1516     sdsfree(flags);
1517     rewriteConfigRewriteLine(state,option,line,force);
1518 }
1519 
1520 /* Rewrite the client-output-buffer-limit option. */
1521 void rewriteConfigClientoutputbufferlimitOption(struct rewriteConfigState *state) {
1522     int j;
1523     char *option = "client-output-buffer-limit";
1524 
1525     for (j = 0; j < REDIS_CLIENT_LIMIT_NUM_CLASSES; j++) {
1526         int force = (server.client_obuf_limits[j].hard_limit_bytes !=
1527                     clientBufferLimitsDefaults[j].hard_limit_bytes) ||
1528                     (server.client_obuf_limits[j].soft_limit_bytes !=
1529                     clientBufferLimitsDefaults[j].soft_limit_bytes) ||
1530                     (server.client_obuf_limits[j].soft_limit_seconds !=
1531                     clientBufferLimitsDefaults[j].soft_limit_seconds);
1532         sds line;
1533         char hard[64], soft[64];
1534 
1535         rewriteConfigFormatMemory(hard,sizeof(hard),
1536                 server.client_obuf_limits[j].hard_limit_bytes);
1537         rewriteConfigFormatMemory(soft,sizeof(soft),
1538                 server.client_obuf_limits[j].soft_limit_bytes);
1539 
1540         line = sdscatprintf(sdsempty(),"%s %s %s %s %ld",
1541                 option, getClientLimitClassName(j), hard, soft,
1542                 (long) server.client_obuf_limits[j].soft_limit_seconds);
1543         rewriteConfigRewriteLine(state,option,line,force);
1544     }
1545 }
1546 
1547 /* Rewrite the bind option. */
1548 void rewriteConfigBindOption(struct rewriteConfigState *state) {
1549     int force = 1;
1550     sds line, addresses;
1551     char *option = "bind";
1552 
1553     /* Nothing to rewrite if we don't have bind addresses. */
1554     if (server.bindaddr_count == 0) {
1555         rewriteConfigMarkAsProcessed(state,option);
1556         return;
1557     }
1558 
1559     /* Rewrite as bind <addr1> <addr2> ... <addrN> */
1560     addresses = sdsjoin(server.bindaddr,server.bindaddr_count," ");
1561     line = sdsnew(option);
1562     line = sdscatlen(line, " ", 1);
1563     line = sdscatsds(line, addresses);
1564     sdsfree(addresses);
1565 
1566     rewriteConfigRewriteLine(state,option,line,force);
1567 }
1568 
1569 /* Glue together the configuration lines in the current configuration
1570  * rewrite state into a single string, stripping multiple empty lines. */
1571 sds rewriteConfigGetContentFromState(struct rewriteConfigState *state) {
1572     sds content = sdsempty();
1573     int j, was_empty = 0;
1574 
1575     for (j = 0; j < state->numlines; j++) {
1576         /* Every cluster of empty lines is turned into a single empty line. */
1577         if (sdslen(state->lines[j]) == 0) {
1578             if (was_empty) continue;
1579             was_empty = 1;
1580         } else {
1581             was_empty = 0;
1582         }
1583         content = sdscatsds(content,state->lines[j]);
1584         content = sdscatlen(content,"\n",1);
1585     }
1586     return content;
1587 }
1588 
1589 /* Free the configuration rewrite state. */
1590 void rewriteConfigReleaseState(struct rewriteConfigState *state) {
1591     sdsfreesplitres(state->lines,state->numlines);
1592     dictRelease(state->option_to_line);
1593     dictRelease(state->rewritten);
1594     zfree(state);
1595 }
1596 
1597 /* At the end of the rewrite process the state contains the remaining
1598  * map between "option name" => "lines in the original config file".
1599  * Lines used by the rewrite process were removed by the function
1600  * rewriteConfigRewriteLine(), all the other lines are "orphaned" and
1601  * should be replaced by empty lines.
1602  *
1603  * This function does just this, iterating all the option names and
1604  * blanking all the lines still associated. */
1605 void rewriteConfigRemoveOrphaned(struct rewriteConfigState *state) {
1606     dictIterator *di = dictGetIterator(state->option_to_line);
1607     dictEntry *de;
1608 
1609     while((de = dictNext(di)) != NULL) {
1610         list *l = dictGetVal(de);
1611         sds option = dictGetKey(de);
1612 
1613         /* Don't blank lines about options the rewrite process
1614          * don't understand. */
1615         if (dictFind(state->rewritten,option) == NULL) {
1616             redisLog(REDIS_DEBUG,"Not rewritten option: %s", option);
1617             continue;
1618         }
1619 
1620         while(listLength(l)) {
1621             listNode *ln = listFirst(l);
1622             int linenum = (long) ln->value;
1623 
1624             sdsfree(state->lines[linenum]);
1625             state->lines[linenum] = sdsempty();
1626             listDelNode(l,ln);
1627         }
1628     }
1629     dictReleaseIterator(di);
1630 }
1631 
1632 /* This function overwrites the old configuration file with the new content.
1633  *
1634  * 1) The old file length is obtained.
1635  * 2) If the new content is smaller, padding is added.
1636  * 3) A single write(2) call is used to replace the content of the file.
1637  * 4) Later the file is truncated to the length of the new content.
1638  *
1639  * This way we are sure the file is left in a consistent state even if the
1640  * process is stopped between any of the four operations.
1641  *
1642  * The function returns 0 on success, otherwise -1 is returned and errno
1643  * set accordingly. */
1644 int rewriteConfigOverwriteFile(char *configfile, sds content) {
1645     int retval = 0;
1646     int fd = open(configfile,O_RDWR|O_CREAT,0644);
1647     int content_size = sdslen(content), padding = 0;
1648     struct stat sb;
1649     sds content_padded;
1650 
1651     /* 1) Open the old file (or create a new one if it does not
1652      *    exist), get the size. */
1653     if (fd == -1) return -1; /* errno set by open(). */
1654     if (fstat(fd,&sb) == -1) {
1655         close(fd);
1656         return -1; /* errno set by fstat(). */
1657     }
1658 
1659     /* 2) Pad the content at least match the old file size. */
1660     content_padded = sdsdup(content);
1661     if (content_size < sb.st_size) {
1662         /* If the old file was bigger, pad the content with
1663          * a newline plus as many "#" chars as required. */
1664         padding = sb.st_size - content_size;
1665         content_padded = sdsgrowzero(content_padded,sb.st_size);
1666         content_padded[content_size] = '\n';
1667         memset(content_padded+content_size+1,'#',padding-1);
1668     }
1669 
1670     /* 3) Write the new content using a single write(2). */
1671     if (write(fd,content_padded,strlen(content_padded)) == -1) {
1672         retval = -1;
1673         goto cleanup;
1674     }
1675 
1676     /* 4) Truncate the file to the right length if we used padding. */
1677     if (padding) {
1678         if (ftruncate(fd,content_size) == -1) {
1679             /* Non critical error... */
1680         }
1681     }
1682 
1683 cleanup:
1684     sdsfree(content_padded);
1685     close(fd);
1686     return retval;
1687 }
1688 
1689 /* Rewrite the configuration file at "path".
1690  * If the configuration file already exists, we try at best to retain comments
1691  * and overall structure.
1692  *
1693  * Configuration parameters that are at their default value, unless already
1694  * explicitly included in the old configuration file, are not rewritten.
1695  *
1696  * On error -1 is returned and errno is set accordingly, otherwise 0. */
1697 int rewriteConfig(char *path) {
1698     struct rewriteConfigState *state;
1699     sds newcontent;
1700     int retval;
1701 
1702     /* Step 1: read the old config into our rewrite state. */
1703     if ((state = rewriteConfigReadOldFile(path)) == NULL) return -1;
1704 
1705     /* Step 2: rewrite every single option, replacing or appending it inside
1706      * the rewrite state. */
1707 
1708     rewriteConfigYesNoOption(state,"daemonize",server.daemonize,0);
1709     rewriteConfigStringOption(state,"pidfile",server.pidfile,REDIS_DEFAULT_PID_FILE);
1710     rewriteConfigNumericalOption(state,"port",server.port,REDIS_SERVERPORT);
1711     rewriteConfigNumericalOption(state,"tcp-backlog",server.tcp_backlog,REDIS_TCP_BACKLOG);
1712     rewriteConfigBindOption(state);
1713     rewriteConfigStringOption(state,"unixsocket",server.unixsocket,NULL);
1714     rewriteConfigOctalOption(state,"unixsocketperm",server.unixsocketperm,REDIS_DEFAULT_UNIX_SOCKET_PERM);
1715     rewriteConfigNumericalOption(state,"timeout",server.maxidletime,REDIS_MAXIDLETIME);
1716     rewriteConfigNumericalOption(state,"tcp-keepalive",server.tcpkeepalive,REDIS_DEFAULT_TCP_KEEPALIVE);
1717     rewriteConfigEnumOption(state,"loglevel",server.verbosity,
1718         "debug", REDIS_DEBUG,
1719         "verbose", REDIS_VERBOSE,
1720         "notice", REDIS_NOTICE,
1721         "warning", REDIS_WARNING,
1722         NULL, REDIS_DEFAULT_VERBOSITY);
1723     rewriteConfigStringOption(state,"logfile",server.logfile,REDIS_DEFAULT_LOGFILE);
1724     rewriteConfigYesNoOption(state,"syslog-enabled",server.syslog_enabled,REDIS_DEFAULT_SYSLOG_ENABLED);
1725     rewriteConfigStringOption(state,"syslog-ident",server.syslog_ident,REDIS_DEFAULT_SYSLOG_IDENT);
1726     rewriteConfigSyslogfacilityOption(state);
1727     rewriteConfigSaveOption(state);
1728     rewriteConfigNumericalOption(state,"databases",server.dbnum,REDIS_DEFAULT_DBNUM);
1729     rewriteConfigYesNoOption(state,"stop-writes-on-bgsave-error",server.stop_writes_on_bgsave_err,REDIS_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR);
1730     rewriteConfigYesNoOption(state,"rdbcompression",server.rdb_compression,REDIS_DEFAULT_RDB_COMPRESSION);
1731     rewriteConfigYesNoOption(state,"rdbchecksum",server.rdb_checksum,REDIS_DEFAULT_RDB_CHECKSUM);
1732     rewriteConfigStringOption(state,"dbfilename",server.rdb_filename,REDIS_DEFAULT_RDB_FILENAME);
1733     rewriteConfigDirOption(state);
1734     rewriteConfigSlaveofOption(state);
1735     rewriteConfigStringOption(state,"masterauth",server.masterauth,NULL);
1736     rewriteConfigYesNoOption(state,"slave-serve-stale-data",server.repl_serve_stale_data,REDIS_DEFAULT_SLAVE_SERVE_STALE_DATA);
1737     rewriteConfigYesNoOption(state,"slave-read-only",server.repl_slave_ro,REDIS_DEFAULT_SLAVE_READ_ONLY);
1738     rewriteConfigNumericalOption(state,"repl-ping-slave-period",server.repl_ping_slave_period,REDIS_REPL_PING_SLAVE_PERIOD);
1739     rewriteConfigNumericalOption(state,"repl-timeout",server.repl_timeout,REDIS_REPL_TIMEOUT);
1740     rewriteConfigBytesOption(state,"repl-backlog-size",server.repl_backlog_size,REDIS_DEFAULT_REPL_BACKLOG_SIZE);
1741     rewriteConfigBytesOption(state,"repl-backlog-ttl",server.repl_backlog_time_limit,REDIS_DEFAULT_REPL_BACKLOG_TIME_LIMIT);
1742     rewriteConfigYesNoOption(state,"repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay,REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY);
1743     rewriteConfigNumericalOption(state,"slave-priority",server.slave_priority,REDIS_DEFAULT_SLAVE_PRIORITY);
1744     rewriteConfigNumericalOption(state,"min-slaves-to-write",server.repl_min_slaves_to_write,REDIS_DEFAULT_MIN_SLAVES_TO_WRITE);
1745     rewriteConfigNumericalOption(state,"min-slaves-max-lag",server.repl_min_slaves_max_lag,REDIS_DEFAULT_MIN_SLAVES_MAX_LAG);
1746     rewriteConfigStringOption(state,"requirepass",server.requirepass,NULL);
1747     rewriteConfigNumericalOption(state,"maxclients",server.maxclients,REDIS_MAX_CLIENTS);
1748     rewriteConfigBytesOption(state,"maxmemory",server.maxmemory,REDIS_DEFAULT_MAXMEMORY);
1749     rewriteConfigEnumOption(state,"maxmemory-policy",server.maxmemory_policy,
1750         "volatile-lru", REDIS_MAXMEMORY_VOLATILE_LRU,
1751         "allkeys-lru", REDIS_MAXMEMORY_ALLKEYS_LRU,
1752         "volatile-random", REDIS_MAXMEMORY_VOLATILE_RANDOM,
1753         "allkeys-random", REDIS_MAXMEMORY_ALLKEYS_RANDOM,
1754         "volatile-ttl", REDIS_MAXMEMORY_VOLATILE_TTL,
1755         "noeviction", REDIS_MAXMEMORY_NO_EVICTION,
1756         NULL, REDIS_DEFAULT_MAXMEMORY_POLICY);
1757     rewriteConfigNumericalOption(state,"maxmemory-samples",server.maxmemory_samples,REDIS_DEFAULT_MAXMEMORY_SAMPLES);
1758     rewriteConfigYesNoOption(state,"appendonly",server.aof_state != REDIS_AOF_OFF,0);
1759     rewriteConfigStringOption(state,"appendfilename",server.aof_filename,REDIS_DEFAULT_AOF_FILENAME);
1760     rewriteConfigEnumOption(state,"appendfsync",server.aof_fsync,
1761         "everysec", AOF_FSYNC_EVERYSEC,
1762         "always", AOF_FSYNC_ALWAYS,
1763         "no", AOF_FSYNC_NO,
1764         NULL, REDIS_DEFAULT_AOF_FSYNC);
1765     rewriteConfigYesNoOption(state,"no-appendfsync-on-rewrite",server.aof_no_fsync_on_rewrite,REDIS_DEFAULT_AOF_NO_FSYNC_ON_REWRITE);
1766     rewriteConfigNumericalOption(state,"auto-aof-rewrite-percentage",server.aof_rewrite_perc,REDIS_AOF_REWRITE_PERC);
1767     rewriteConfigBytesOption(state,"auto-aof-rewrite-min-size",server.aof_rewrite_min_size,REDIS_AOF_REWRITE_MIN_SIZE);
1768     rewriteConfigNumericalOption(state,"lua-time-limit",server.lua_time_limit,REDIS_LUA_TIME_LIMIT);
1769     rewriteConfigYesNoOption(state,"cluster-enabled",server.cluster_enabled,0);
1770     rewriteConfigStringOption(state,"cluster-config-file",server.cluster_configfile,REDIS_DEFAULT_CLUSTER_CONFIG_FILE);
1771     rewriteConfigNumericalOption(state,"cluster-node-timeout",server.cluster_node_timeout,REDIS_CLUSTER_DEFAULT_NODE_TIMEOUT);
1772     rewriteConfigNumericalOption(state,"cluster-migration-barrier",server.cluster_migration_barrier,REDIS_CLUSTER_DEFAULT_MIGRATION_BARRIER);
1773     rewriteConfigNumericalOption(state,"slowlog-log-slower-than",server.slowlog_log_slower_than,REDIS_SLOWLOG_LOG_SLOWER_THAN);
1774     rewriteConfigNumericalOption(state,"slowlog-max-len",server.slowlog_max_len,REDIS_SLOWLOG_MAX_LEN);
1775     rewriteConfigNotifykeyspaceeventsOption(state);
1776     rewriteConfigNumericalOption(state,"hash-max-ziplist-entries",server.hash_max_ziplist_entries,REDIS_HASH_MAX_ZIPLIST_ENTRIES);
1777     rewriteConfigNumericalOption(state,"hash-max-ziplist-value",server.hash_max_ziplist_value,REDIS_HASH_MAX_ZIPLIST_VALUE);
1778     rewriteConfigNumericalOption(state,"list-max-ziplist-entries",server.list_max_ziplist_entries,REDIS_LIST_MAX_ZIPLIST_ENTRIES);
1779     rewriteConfigNumericalOption(state,"list-max-ziplist-value",server.list_max_ziplist_value,REDIS_LIST_MAX_ZIPLIST_VALUE);
1780     rewriteConfigNumericalOption(state,"set-max-intset-entries",server.set_max_intset_entries,REDIS_SET_MAX_INTSET_ENTRIES);
1781     rewriteConfigNumericalOption(state,"zset-max-ziplist-entries",server.zset_max_ziplist_entries,REDIS_ZSET_MAX_ZIPLIST_ENTRIES);
1782     rewriteConfigNumericalOption(state,"zset-max-ziplist-value",server.zset_max_ziplist_value,REDIS_ZSET_MAX_ZIPLIST_VALUE);
1783     rewriteConfigNumericalOption(state,"hll-sparse-max-bytes",server.hll_sparse_max_bytes,REDIS_DEFAULT_HLL_SPARSE_MAX_BYTES);
1784     rewriteConfigYesNoOption(state,"activerehashing",server.activerehashing,REDIS_DEFAULT_ACTIVE_REHASHING);
1785     rewriteConfigClientoutputbufferlimitOption(state);
1786     rewriteConfigNumericalOption(state,"hz",server.hz,REDIS_DEFAULT_HZ);
1787     rewriteConfigYesNoOption(state,"aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync,REDIS_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC);
1788     if (server.sentinel_mode) rewriteConfigSentinelOption(state);
1789 
1790     /* Step 3: remove all the orphaned lines in the old file, that is, lines
1791      * that were used by a config option and are no longer used, like in case
1792      * of multiple "save" options or duplicated options. */
1793     rewriteConfigRemoveOrphaned(state);
1794 
1795     /* Step 4: generate a new configuration file from the modified state
1796      * and write it into the original file. */
1797     newcontent = rewriteConfigGetContentFromState(state);
1798     retval = rewriteConfigOverwriteFile(server.configfile,newcontent);
1799 
1800     sdsfree(newcontent);
1801     rewriteConfigReleaseState(state);
1802     return retval;
1803 }
1804 
1805 /*-----------------------------------------------------------------------------
1806  * CONFIG command entry point
1807  *----------------------------------------------------------------------------*/
1808 
1809 void configCommand(redisClient *c) {
1810     if (!strcasecmp(c->argv[1]->ptr,"set")) {
1811         if (c->argc != 4) goto badarity;
1812         configSetCommand(c);
1813     } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
1814         if (c->argc != 3) goto badarity;
1815         configGetCommand(c);
1816     } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
1817         if (c->argc != 2) goto badarity;
1818         resetServerStats();
1819         resetCommandTableStats();
1820         addReply(c,shared.ok);
1821     } else if (!strcasecmp(c->argv[1]->ptr,"rewrite")) {
1822         if (c->argc != 2) goto badarity;
1823         if (server.configfile == NULL) {
1824             addReplyError(c,"The server is running without a config file");
1825             return;
1826         }
1827         if (rewriteConfig(server.configfile) == -1) {
1828             redisLog(REDIS_WARNING,"CONFIG REWRITE failed: %s", strerror(errno));
1829             addReplyErrorFormat(c,"Rewriting config file: %s", strerror(errno));
1830         } else {
1831             redisLog(REDIS_WARNING,"CONFIG REWRITE executed with success.");
1832             addReply(c,shared.ok);
1833         }
1834     } else {
1835         addReplyError(c,
1836             "CONFIG subcommand must be one of GET, SET, RESETSTAT, REWRITE");
1837     }
1838     return;
1839 
1840 badarity:
1841     addReplyErrorFormat(c,"Wrong number of arguments for CONFIG %s",
1842         (char*) c->argv[1]->ptr);
1843 }
1844