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