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