"Fossies" - the Fresh Open Source Software Archive

Member "redis-6.2.5/src/server.h" (21 Jul 2021, 130470 Bytes) of package /linux/misc/redis-6.2.5.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "server.h" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 6.2.4_vs_6.2.5.

    1 /*
    2  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
    3  * All rights reserved.
    4  *
    5  * Redistribution and use in source and binary forms, with or without
    6  * modification, are permitted provided that the following conditions are met:
    7  *
    8  *   * Redistributions of source code must retain the above copyright notice,
    9  *     this list of conditions and the following disclaimer.
   10  *   * Redistributions in binary form must reproduce the above copyright
   11  *     notice, this list of conditions and the following disclaimer in the
   12  *     documentation and/or other materials provided with the distribution.
   13  *   * Neither the name of Redis nor the names of its contributors may be used
   14  *     to endorse or promote products derived from this software without
   15  *     specific prior written permission.
   16  *
   17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   27  * POSSIBILITY OF SUCH DAMAGE.
   28  */
   29 
   30 #ifndef __REDIS_H
   31 #define __REDIS_H
   32 
   33 #include "fmacros.h"
   34 #include "config.h"
   35 #include "solarisfixes.h"
   36 #include "rio.h"
   37 #include "atomicvar.h"
   38 
   39 #include <stdio.h>
   40 #include <stdlib.h>
   41 #include <string.h>
   42 #include <time.h>
   43 #include <limits.h>
   44 #include <unistd.h>
   45 #include <errno.h>
   46 #include <inttypes.h>
   47 #include <pthread.h>
   48 #include <syslog.h>
   49 #include <netinet/in.h>
   50 #include <sys/socket.h>
   51 #include <lua.h>
   52 #include <signal.h>
   53 
   54 #ifdef HAVE_LIBSYSTEMD
   55 #include <systemd/sd-daemon.h>
   56 #endif
   57 
   58 typedef long long mstime_t; /* millisecond time type. */
   59 typedef long long ustime_t; /* microsecond time type. */
   60 
   61 #include "ae.h"      /* Event driven programming library */
   62 #include "sds.h"     /* Dynamic safe strings */
   63 #include "dict.h"    /* Hash tables */
   64 #include "adlist.h"  /* Linked lists */
   65 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
   66 #include "anet.h"    /* Networking the easy way */
   67 #include "ziplist.h" /* Compact list data structure */
   68 #include "intset.h"  /* Compact integer set structure */
   69 #include "version.h" /* Version macro */
   70 #include "util.h"    /* Misc functions useful in many places */
   71 #include "latency.h" /* Latency monitor API */
   72 #include "sparkline.h" /* ASCII graphs API */
   73 #include "quicklist.h"  /* Lists are encoded as linked lists of
   74                            N-elements flat arrays */
   75 #include "rax.h"     /* Radix tree */
   76 #include "connection.h" /* Connection abstraction */
   77 
   78 #define REDISMODULE_CORE 1
   79 #include "redismodule.h"    /* Redis modules API defines. */
   80 
   81 /* Following includes allow test functions to be called from Redis main() */
   82 #include "zipmap.h"
   83 #include "sha1.h"
   84 #include "endianconv.h"
   85 #include "crc64.h"
   86 
   87 /* Error codes */
   88 #define C_OK                    0
   89 #define C_ERR                   -1
   90 
   91 /* Static server configuration */
   92 #define CONFIG_DEFAULT_HZ        10             /* Time interrupt calls/sec. */
   93 #define CONFIG_MIN_HZ            1
   94 #define CONFIG_MAX_HZ            500
   95 #define MAX_CLIENTS_PER_CLOCK_TICK 200          /* HZ is adapted based on that. */
   96 #define CONFIG_MAX_LINE    1024
   97 #define CRON_DBS_PER_CALL 16
   98 #define NET_MAX_WRITES_PER_EVENT (1024*64)
   99 #define PROTO_SHARED_SELECT_CMDS 10
  100 #define OBJ_SHARED_INTEGERS 10000
  101 #define OBJ_SHARED_BULKHDR_LEN 32
  102 #define LOG_MAX_LEN    1024 /* Default maximum length of syslog messages.*/
  103 #define AOF_REWRITE_ITEMS_PER_CMD 64
  104 #define AOF_READ_DIFF_INTERVAL_BYTES (1024*10)
  105 #define CONFIG_AUTHPASS_MAX_LEN 512
  106 #define CONFIG_RUN_ID_SIZE 40
  107 #define RDB_EOF_MARK_SIZE 40
  108 #define CONFIG_REPL_BACKLOG_MIN_SIZE (1024*16)          /* 16k */
  109 #define CONFIG_BGSAVE_RETRY_DELAY 5 /* Wait a few secs before trying again. */
  110 #define CONFIG_DEFAULT_PID_FILE "/var/run/redis.pid"
  111 #define CONFIG_DEFAULT_CLUSTER_CONFIG_FILE "nodes.conf"
  112 #define CONFIG_DEFAULT_UNIX_SOCKET_PERM 0
  113 #define CONFIG_DEFAULT_LOGFILE ""
  114 #define NET_HOST_STR_LEN 256 /* Longest valid hostname */
  115 #define NET_IP_STR_LEN 46 /* INET6_ADDRSTRLEN is 46, but we need to be sure */
  116 #define NET_ADDR_STR_LEN (NET_IP_STR_LEN+32) /* Must be enough for ip:port */
  117 #define NET_HOST_PORT_STR_LEN (NET_HOST_STR_LEN+32) /* Must be enough for hostname:port */
  118 #define CONFIG_BINDADDR_MAX 16
  119 #define CONFIG_MIN_RESERVED_FDS 32
  120 #define CONFIG_DEFAULT_PROC_TITLE_TEMPLATE "{title} {listen-addr} {server-mode}"
  121 
  122 #define ACTIVE_EXPIRE_CYCLE_SLOW 0
  123 #define ACTIVE_EXPIRE_CYCLE_FAST 1
  124 
  125 /* Children process will exit with this status code to signal that the
  126  * process terminated without an error: this is useful in order to kill
  127  * a saving child (RDB or AOF one), without triggering in the parent the
  128  * write protection that is normally turned on on write errors.
  129  * Usually children that are terminated with SIGUSR1 will exit with this
  130  * special code. */
  131 #define SERVER_CHILD_NOERROR_RETVAL    255
  132 
  133 /* Reading copy-on-write info is sometimes expensive and may slow down child
  134  * processes that report it continuously. We measure the cost of obtaining it
  135  * and hold back additional reading based on this factor. */
  136 #define CHILD_COW_DUTY_CYCLE           100
  137 
  138 /* Instantaneous metrics tracking. */
  139 #define STATS_METRIC_SAMPLES 16     /* Number of samples per metric. */
  140 #define STATS_METRIC_COMMAND 0      /* Number of commands executed. */
  141 #define STATS_METRIC_NET_INPUT 1    /* Bytes read to network .*/
  142 #define STATS_METRIC_NET_OUTPUT 2   /* Bytes written to network. */
  143 #define STATS_METRIC_COUNT 3
  144 
  145 /* Protocol and I/O related defines */
  146 #define PROTO_IOBUF_LEN         (1024*16)  /* Generic I/O buffer size */
  147 #define PROTO_REPLY_CHUNK_BYTES (16*1024) /* 16k output buffer */
  148 #define PROTO_INLINE_MAX_SIZE   (1024*64) /* Max size of inline reads */
  149 #define PROTO_MBULK_BIG_ARG     (1024*32)
  150 #define LONG_STR_SIZE      21          /* Bytes needed for long -> str + '\0' */
  151 #define REDIS_AUTOSYNC_BYTES (1024*1024*32) /* fdatasync every 32MB */
  152 
  153 #define LIMIT_PENDING_QUERYBUF (4*1024*1024) /* 4mb */
  154 
  155 /* When configuring the server eventloop, we setup it so that the total number
  156  * of file descriptors we can handle are server.maxclients + RESERVED_FDS +
  157  * a few more to stay safe. Since RESERVED_FDS defaults to 32, we add 96
  158  * in order to make sure of not over provisioning more than 128 fds. */
  159 #define CONFIG_FDSET_INCR (CONFIG_MIN_RESERVED_FDS+96)
  160 
  161 /* OOM Score Adjustment classes. */
  162 #define CONFIG_OOM_MASTER 0
  163 #define CONFIG_OOM_REPLICA 1
  164 #define CONFIG_OOM_BGCHILD 2
  165 #define CONFIG_OOM_COUNT 3
  166 
  167 extern int configOOMScoreAdjValuesDefaults[CONFIG_OOM_COUNT];
  168 
  169 /* Hash table parameters */
  170 #define HASHTABLE_MIN_FILL        10      /* Minimal hash table fill 10% */
  171 #define HASHTABLE_MAX_LOAD_FACTOR 1.618   /* Maximum hash table load factor. */
  172 
  173 /* Command flags. Please check the command table defined in the server.c file
  174  * for more information about the meaning of every flag. */
  175 #define CMD_WRITE (1ULL<<0)            /* "write" flag */
  176 #define CMD_READONLY (1ULL<<1)         /* "read-only" flag */
  177 #define CMD_DENYOOM (1ULL<<2)          /* "use-memory" flag */
  178 #define CMD_MODULE (1ULL<<3)           /* Command exported by module. */
  179 #define CMD_ADMIN (1ULL<<4)            /* "admin" flag */
  180 #define CMD_PUBSUB (1ULL<<5)           /* "pub-sub" flag */
  181 #define CMD_NOSCRIPT (1ULL<<6)         /* "no-script" flag */
  182 #define CMD_RANDOM (1ULL<<7)           /* "random" flag */
  183 #define CMD_SORT_FOR_SCRIPT (1ULL<<8)  /* "to-sort" flag */
  184 #define CMD_LOADING (1ULL<<9)          /* "ok-loading" flag */
  185 #define CMD_STALE (1ULL<<10)           /* "ok-stale" flag */
  186 #define CMD_SKIP_MONITOR (1ULL<<11)    /* "no-monitor" flag */
  187 #define CMD_SKIP_SLOWLOG (1ULL<<12)    /* "no-slowlog" flag */
  188 #define CMD_ASKING (1ULL<<13)          /* "cluster-asking" flag */
  189 #define CMD_FAST (1ULL<<14)            /* "fast" flag */
  190 #define CMD_NO_AUTH (1ULL<<15)         /* "no-auth" flag */
  191 #define CMD_MAY_REPLICATE (1ULL<<16)   /* "may-replicate" flag */
  192 
  193 /* Command flags used by the module system. */
  194 #define CMD_MODULE_GETKEYS (1ULL<<17)  /* Use the modules getkeys interface. */
  195 #define CMD_MODULE_NO_CLUSTER (1ULL<<18) /* Deny on Redis Cluster. */
  196 
  197 /* Command flags that describe ACLs categories. */
  198 #define CMD_CATEGORY_KEYSPACE (1ULL<<19)
  199 #define CMD_CATEGORY_READ (1ULL<<20)
  200 #define CMD_CATEGORY_WRITE (1ULL<<21)
  201 #define CMD_CATEGORY_SET (1ULL<<22)
  202 #define CMD_CATEGORY_SORTEDSET (1ULL<<23)
  203 #define CMD_CATEGORY_LIST (1ULL<<24)
  204 #define CMD_CATEGORY_HASH (1ULL<<25)
  205 #define CMD_CATEGORY_STRING (1ULL<<26)
  206 #define CMD_CATEGORY_BITMAP (1ULL<<27)
  207 #define CMD_CATEGORY_HYPERLOGLOG (1ULL<<28)
  208 #define CMD_CATEGORY_GEO (1ULL<<29)
  209 #define CMD_CATEGORY_STREAM (1ULL<<30)
  210 #define CMD_CATEGORY_PUBSUB (1ULL<<31)
  211 #define CMD_CATEGORY_ADMIN (1ULL<<32)
  212 #define CMD_CATEGORY_FAST (1ULL<<33)
  213 #define CMD_CATEGORY_SLOW (1ULL<<34)
  214 #define CMD_CATEGORY_BLOCKING (1ULL<<35)
  215 #define CMD_CATEGORY_DANGEROUS (1ULL<<36)
  216 #define CMD_CATEGORY_CONNECTION (1ULL<<37)
  217 #define CMD_CATEGORY_TRANSACTION (1ULL<<38)
  218 #define CMD_CATEGORY_SCRIPTING (1ULL<<39)
  219 
  220 /* AOF states */
  221 #define AOF_OFF 0             /* AOF is off */
  222 #define AOF_ON 1              /* AOF is on */
  223 #define AOF_WAIT_REWRITE 2    /* AOF waits rewrite to start appending */
  224 
  225 /* Client flags */
  226 #define CLIENT_SLAVE (1<<0)   /* This client is a replica */
  227 #define CLIENT_MASTER (1<<1)  /* This client is a master */
  228 #define CLIENT_MONITOR (1<<2) /* This client is a slave monitor, see MONITOR */
  229 #define CLIENT_MULTI (1<<3)   /* This client is in a MULTI context */
  230 #define CLIENT_BLOCKED (1<<4) /* The client is waiting in a blocking operation */
  231 #define CLIENT_DIRTY_CAS (1<<5) /* Watched keys modified. EXEC will fail. */
  232 #define CLIENT_CLOSE_AFTER_REPLY (1<<6) /* Close after writing entire reply. */
  233 #define CLIENT_UNBLOCKED (1<<7) /* This client was unblocked and is stored in
  234                                   server.unblocked_clients */
  235 #define CLIENT_LUA (1<<8) /* This is a non connected client used by Lua */
  236 #define CLIENT_ASKING (1<<9)     /* Client issued the ASKING command */
  237 #define CLIENT_CLOSE_ASAP (1<<10)/* Close this client ASAP */
  238 #define CLIENT_UNIX_SOCKET (1<<11) /* Client connected via Unix domain socket */
  239 #define CLIENT_DIRTY_EXEC (1<<12)  /* EXEC will fail for errors while queueing */
  240 #define CLIENT_MASTER_FORCE_REPLY (1<<13)  /* Queue replies even if is master */
  241 #define CLIENT_FORCE_AOF (1<<14)   /* Force AOF propagation of current cmd. */
  242 #define CLIENT_FORCE_REPL (1<<15)  /* Force replication of current cmd. */
  243 #define CLIENT_PRE_PSYNC (1<<16)   /* Instance don't understand PSYNC. */
  244 #define CLIENT_READONLY (1<<17)    /* Cluster client is in read-only state. */
  245 #define CLIENT_PUBSUB (1<<18)      /* Client is in Pub/Sub mode. */
  246 #define CLIENT_PREVENT_AOF_PROP (1<<19)  /* Don't propagate to AOF. */
  247 #define CLIENT_PREVENT_REPL_PROP (1<<20)  /* Don't propagate to slaves. */
  248 #define CLIENT_PREVENT_PROP (CLIENT_PREVENT_AOF_PROP|CLIENT_PREVENT_REPL_PROP)
  249 #define CLIENT_PENDING_WRITE (1<<21) /* Client has output to send but a write
  250                                         handler is yet not installed. */
  251 #define CLIENT_REPLY_OFF (1<<22)   /* Don't send replies to client. */
  252 #define CLIENT_REPLY_SKIP_NEXT (1<<23)  /* Set CLIENT_REPLY_SKIP for next cmd */
  253 #define CLIENT_REPLY_SKIP (1<<24)  /* Don't send just this reply. */
  254 #define CLIENT_LUA_DEBUG (1<<25)  /* Run EVAL in debug mode. */
  255 #define CLIENT_LUA_DEBUG_SYNC (1<<26)  /* EVAL debugging without fork() */
  256 #define CLIENT_MODULE (1<<27) /* Non connected client used by some module. */
  257 #define CLIENT_PROTECTED (1<<28) /* Client should not be freed for now. */
  258 #define CLIENT_PENDING_READ (1<<29) /* The client has pending reads and was put
  259                                        in the list of clients we can read
  260                                        from. */
  261 #define CLIENT_PENDING_COMMAND (1<<30) /* Indicates the client has a fully
  262                                         * parsed command ready for execution. */
  263 #define CLIENT_TRACKING (1ULL<<31) /* Client enabled keys tracking in order to
  264                                    perform client side caching. */
  265 #define CLIENT_TRACKING_BROKEN_REDIR (1ULL<<32) /* Target client is invalid. */
  266 #define CLIENT_TRACKING_BCAST (1ULL<<33) /* Tracking in BCAST mode. */
  267 #define CLIENT_TRACKING_OPTIN (1ULL<<34)  /* Tracking in opt-in mode. */
  268 #define CLIENT_TRACKING_OPTOUT (1ULL<<35) /* Tracking in opt-out mode. */
  269 #define CLIENT_TRACKING_CACHING (1ULL<<36) /* CACHING yes/no was given,
  270                                               depending on optin/optout mode. */
  271 #define CLIENT_TRACKING_NOLOOP (1ULL<<37) /* Don't send invalidation messages
  272                                              about writes performed by myself.*/
  273 #define CLIENT_IN_TO_TABLE (1ULL<<38) /* This client is in the timeout table. */
  274 #define CLIENT_PROTOCOL_ERROR (1ULL<<39) /* Protocol error chatting with it. */
  275 #define CLIENT_CLOSE_AFTER_COMMAND (1ULL<<40) /* Close after executing commands
  276                                                * and writing entire reply. */
  277 #define CLIENT_DENY_BLOCKING (1ULL<<41) /* Indicate that the client should not be blocked.
  278                                            currently, turned on inside MULTI, Lua, RM_Call,
  279                                            and AOF client */
  280 #define CLIENT_REPL_RDBONLY (1ULL<<42) /* This client is a replica that only wants
  281                                           RDB without replication buffer. */
  282 
  283 /* Client block type (btype field in client structure)
  284  * if CLIENT_BLOCKED flag is set. */
  285 #define BLOCKED_NONE 0    /* Not blocked, no CLIENT_BLOCKED flag set. */
  286 #define BLOCKED_LIST 1    /* BLPOP & co. */
  287 #define BLOCKED_WAIT 2    /* WAIT for synchronous replication. */
  288 #define BLOCKED_MODULE 3  /* Blocked by a loadable module. */
  289 #define BLOCKED_STREAM 4  /* XREAD. */
  290 #define BLOCKED_ZSET 5    /* BZPOP et al. */
  291 #define BLOCKED_PAUSE 6   /* Blocked by CLIENT PAUSE */
  292 #define BLOCKED_NUM 7     /* Number of blocked states. */
  293 
  294 /* Client request types */
  295 #define PROTO_REQ_INLINE 1
  296 #define PROTO_REQ_MULTIBULK 2
  297 
  298 /* Client classes for client limits, currently used only for
  299  * the max-client-output-buffer limit implementation. */
  300 #define CLIENT_TYPE_NORMAL 0 /* Normal req-reply clients + MONITORs */
  301 #define CLIENT_TYPE_SLAVE 1  /* Slaves. */
  302 #define CLIENT_TYPE_PUBSUB 2 /* Clients subscribed to PubSub channels. */
  303 #define CLIENT_TYPE_MASTER 3 /* Master. */
  304 #define CLIENT_TYPE_COUNT 4  /* Total number of client types. */
  305 #define CLIENT_TYPE_OBUF_COUNT 3 /* Number of clients to expose to output
  306                                     buffer configuration. Just the first
  307                                     three: normal, slave, pubsub. */
  308 
  309 /* Slave replication state. Used in server.repl_state for slaves to remember
  310  * what to do next. */
  311 typedef enum {
  312     REPL_STATE_NONE = 0,            /* No active replication */
  313     REPL_STATE_CONNECT,             /* Must connect to master */
  314     REPL_STATE_CONNECTING,          /* Connecting to master */
  315     /* --- Handshake states, must be ordered --- */
  316     REPL_STATE_RECEIVE_PING_REPLY,  /* Wait for PING reply */
  317     REPL_STATE_SEND_HANDSHAKE,      /* Send handshake sequance to master */
  318     REPL_STATE_RECEIVE_AUTH_REPLY,  /* Wait for AUTH reply */
  319     REPL_STATE_RECEIVE_PORT_REPLY,  /* Wait for REPLCONF reply */
  320     REPL_STATE_RECEIVE_IP_REPLY,    /* Wait for REPLCONF reply */
  321     REPL_STATE_RECEIVE_CAPA_REPLY,  /* Wait for REPLCONF reply */
  322     REPL_STATE_SEND_PSYNC,          /* Send PSYNC */
  323     REPL_STATE_RECEIVE_PSYNC_REPLY, /* Wait for PSYNC reply */
  324     /* --- End of handshake states --- */
  325     REPL_STATE_TRANSFER,        /* Receiving .rdb from master */
  326     REPL_STATE_CONNECTED,       /* Connected to master */
  327 } repl_state;
  328 
  329 /* The state of an in progress coordinated failover */
  330 typedef enum {
  331     NO_FAILOVER = 0,        /* No failover in progress */
  332     FAILOVER_WAIT_FOR_SYNC, /* Waiting for target replica to catch up */
  333     FAILOVER_IN_PROGRESS    /* Waiting for target replica to accept
  334                              * PSYNC FAILOVER request. */
  335 } failover_state;
  336 
  337 /* State of slaves from the POV of the master. Used in client->replstate.
  338  * In SEND_BULK and ONLINE state the slave receives new updates
  339  * in its output queue. In the WAIT_BGSAVE states instead the server is waiting
  340  * to start the next background saving in order to send updates to it. */
  341 #define SLAVE_STATE_WAIT_BGSAVE_START 6 /* We need to produce a new RDB file. */
  342 #define SLAVE_STATE_WAIT_BGSAVE_END 7 /* Waiting RDB file creation to finish. */
  343 #define SLAVE_STATE_SEND_BULK 8 /* Sending RDB file to slave. */
  344 #define SLAVE_STATE_ONLINE 9 /* RDB file transmitted, sending just updates. */
  345 
  346 /* Slave capabilities. */
  347 #define SLAVE_CAPA_NONE 0
  348 #define SLAVE_CAPA_EOF (1<<0)    /* Can parse the RDB EOF streaming format. */
  349 #define SLAVE_CAPA_PSYNC2 (1<<1) /* Supports PSYNC2 protocol. */
  350 
  351 /* Synchronous read timeout - slave side */
  352 #define CONFIG_REPL_SYNCIO_TIMEOUT 5
  353 
  354 /* List related stuff */
  355 #define LIST_HEAD 0
  356 #define LIST_TAIL 1
  357 #define ZSET_MIN 0
  358 #define ZSET_MAX 1
  359 
  360 /* Sort operations */
  361 #define SORT_OP_GET 0
  362 
  363 /* Log levels */
  364 #define LL_DEBUG 0
  365 #define LL_VERBOSE 1
  366 #define LL_NOTICE 2
  367 #define LL_WARNING 3
  368 #define LL_RAW (1<<10) /* Modifier to log without timestamp */
  369 
  370 /* Supervision options */
  371 #define SUPERVISED_NONE 0
  372 #define SUPERVISED_AUTODETECT 1
  373 #define SUPERVISED_SYSTEMD 2
  374 #define SUPERVISED_UPSTART 3
  375 
  376 /* Anti-warning macro... */
  377 #define UNUSED(V) ((void) V)
  378 
  379 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^64 elements */
  380 #define ZSKIPLIST_P 0.25      /* Skiplist P = 1/4 */
  381 
  382 /* Append only defines */
  383 #define AOF_FSYNC_NO 0
  384 #define AOF_FSYNC_ALWAYS 1
  385 #define AOF_FSYNC_EVERYSEC 2
  386 
  387 /* Replication diskless load defines */
  388 #define REPL_DISKLESS_LOAD_DISABLED 0
  389 #define REPL_DISKLESS_LOAD_WHEN_DB_EMPTY 1
  390 #define REPL_DISKLESS_LOAD_SWAPDB 2
  391 
  392 /* TLS Client Authentication */
  393 #define TLS_CLIENT_AUTH_NO 0
  394 #define TLS_CLIENT_AUTH_YES 1
  395 #define TLS_CLIENT_AUTH_OPTIONAL 2
  396 
  397 /* Sanitize dump payload */
  398 #define SANITIZE_DUMP_NO 0
  399 #define SANITIZE_DUMP_YES 1
  400 #define SANITIZE_DUMP_CLIENTS 2
  401 
  402 /* Sets operations codes */
  403 #define SET_OP_UNION 0
  404 #define SET_OP_DIFF 1
  405 #define SET_OP_INTER 2
  406 
  407 /* oom-score-adj defines */
  408 #define OOM_SCORE_ADJ_NO 0
  409 #define OOM_SCORE_RELATIVE 1
  410 #define OOM_SCORE_ADJ_ABSOLUTE 2
  411 
  412 /* Redis maxmemory strategies. Instead of using just incremental number
  413  * for this defines, we use a set of flags so that testing for certain
  414  * properties common to multiple policies is faster. */
  415 #define MAXMEMORY_FLAG_LRU (1<<0)
  416 #define MAXMEMORY_FLAG_LFU (1<<1)
  417 #define MAXMEMORY_FLAG_ALLKEYS (1<<2)
  418 #define MAXMEMORY_FLAG_NO_SHARED_INTEGERS \
  419     (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU)
  420 
  421 #define MAXMEMORY_VOLATILE_LRU ((0<<8)|MAXMEMORY_FLAG_LRU)
  422 #define MAXMEMORY_VOLATILE_LFU ((1<<8)|MAXMEMORY_FLAG_LFU)
  423 #define MAXMEMORY_VOLATILE_TTL (2<<8)
  424 #define MAXMEMORY_VOLATILE_RANDOM (3<<8)
  425 #define MAXMEMORY_ALLKEYS_LRU ((4<<8)|MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_ALLKEYS)
  426 #define MAXMEMORY_ALLKEYS_LFU ((5<<8)|MAXMEMORY_FLAG_LFU|MAXMEMORY_FLAG_ALLKEYS)
  427 #define MAXMEMORY_ALLKEYS_RANDOM ((6<<8)|MAXMEMORY_FLAG_ALLKEYS)
  428 #define MAXMEMORY_NO_EVICTION (7<<8)
  429 
  430 /* Units */
  431 #define UNIT_SECONDS 0
  432 #define UNIT_MILLISECONDS 1
  433 
  434 /* SHUTDOWN flags */
  435 #define SHUTDOWN_NOFLAGS 0      /* No flags. */
  436 #define SHUTDOWN_SAVE 1         /* Force SAVE on SHUTDOWN even if no save
  437                                    points are configured. */
  438 #define SHUTDOWN_NOSAVE 2       /* Don't SAVE on SHUTDOWN. */
  439 
  440 /* Command call flags, see call() function */
  441 #define CMD_CALL_NONE 0
  442 #define CMD_CALL_SLOWLOG (1<<0)
  443 #define CMD_CALL_STATS (1<<1)
  444 #define CMD_CALL_PROPAGATE_AOF (1<<2)
  445 #define CMD_CALL_PROPAGATE_REPL (1<<3)
  446 #define CMD_CALL_PROPAGATE (CMD_CALL_PROPAGATE_AOF|CMD_CALL_PROPAGATE_REPL)
  447 #define CMD_CALL_FULL (CMD_CALL_SLOWLOG | CMD_CALL_STATS | CMD_CALL_PROPAGATE)
  448 #define CMD_CALL_NOWRAP (1<<4)  /* Don't wrap also propagate array into
  449                                    MULTI/EXEC: the caller will handle it.  */
  450 
  451 /* Command propagation flags, see propagate() function */
  452 #define PROPAGATE_NONE 0
  453 #define PROPAGATE_AOF 1
  454 #define PROPAGATE_REPL 2
  455 
  456 /* Client pause types, larger types are more restrictive
  457  * pause types than smaller pause types. */
  458 typedef enum {
  459     CLIENT_PAUSE_OFF = 0, /* Pause no commands */
  460     CLIENT_PAUSE_WRITE,   /* Pause write commands */
  461     CLIENT_PAUSE_ALL      /* Pause all commands */
  462 } pause_type;
  463 
  464 /* RDB active child save type. */
  465 #define RDB_CHILD_TYPE_NONE 0
  466 #define RDB_CHILD_TYPE_DISK 1     /* RDB is written to disk. */
  467 #define RDB_CHILD_TYPE_SOCKET 2   /* RDB is written to slave socket. */
  468 
  469 /* Keyspace changes notification classes. Every class is associated with a
  470  * character for configuration purposes. */
  471 #define NOTIFY_KEYSPACE (1<<0)    /* K */
  472 #define NOTIFY_KEYEVENT (1<<1)    /* E */
  473 #define NOTIFY_GENERIC (1<<2)     /* g */
  474 #define NOTIFY_STRING (1<<3)      /* $ */
  475 #define NOTIFY_LIST (1<<4)        /* l */
  476 #define NOTIFY_SET (1<<5)         /* s */
  477 #define NOTIFY_HASH (1<<6)        /* h */
  478 #define NOTIFY_ZSET (1<<7)        /* z */
  479 #define NOTIFY_EXPIRED (1<<8)     /* x */
  480 #define NOTIFY_EVICTED (1<<9)     /* e */
  481 #define NOTIFY_STREAM (1<<10)     /* t */
  482 #define NOTIFY_KEY_MISS (1<<11)   /* m (Note: This one is excluded from NOTIFY_ALL on purpose) */
  483 #define NOTIFY_LOADED (1<<12)     /* module only key space notification, indicate a key loaded from rdb */
  484 #define NOTIFY_MODULE (1<<13)     /* d, module key space notification */
  485 #define NOTIFY_ALL (NOTIFY_GENERIC | NOTIFY_STRING | NOTIFY_LIST | NOTIFY_SET | NOTIFY_HASH | NOTIFY_ZSET | NOTIFY_EXPIRED | NOTIFY_EVICTED | NOTIFY_STREAM | NOTIFY_MODULE) /* A flag */
  486 
  487 /* Get the first bind addr or NULL */
  488 #define NET_FIRST_BIND_ADDR (server.bindaddr_count ? server.bindaddr[0] : NULL)
  489 
  490 /* Using the following macro you can run code inside serverCron() with the
  491  * specified period, specified in milliseconds.
  492  * The actual resolution depends on server.hz. */
  493 #define run_with_period(_ms_) if ((_ms_ <= 1000/server.hz) || !(server.cronloops%((_ms_)/(1000/server.hz))))
  494 
  495 /* We can print the stacktrace, so our assert is defined this way: */
  496 #define serverAssertWithInfo(_c,_o,_e) ((_e)?(void)0 : (_serverAssertWithInfo(_c,_o,#_e,__FILE__,__LINE__),redis_unreachable()))
  497 #define serverAssert(_e) ((_e)?(void)0 : (_serverAssert(#_e,__FILE__,__LINE__),redis_unreachable()))
  498 #define serverPanic(...) _serverPanic(__FILE__,__LINE__,__VA_ARGS__),redis_unreachable()
  499 
  500 /*-----------------------------------------------------------------------------
  501  * Data types
  502  *----------------------------------------------------------------------------*/
  503 
  504 /* A redis object, that is a type able to hold a string / list / set */
  505 
  506 /* The actual Redis Object */
  507 #define OBJ_STRING 0    /* String object. */
  508 #define OBJ_LIST 1      /* List object. */
  509 #define OBJ_SET 2       /* Set object. */
  510 #define OBJ_ZSET 3      /* Sorted set object. */
  511 #define OBJ_HASH 4      /* Hash object. */
  512 
  513 /* The "module" object type is a special one that signals that the object
  514  * is one directly managed by a Redis module. In this case the value points
  515  * to a moduleValue struct, which contains the object value (which is only
  516  * handled by the module itself) and the RedisModuleType struct which lists
  517  * function pointers in order to serialize, deserialize, AOF-rewrite and
  518  * free the object.
  519  *
  520  * Inside the RDB file, module types are encoded as OBJ_MODULE followed
  521  * by a 64 bit module type ID, which has a 54 bits module-specific signature
  522  * in order to dispatch the loading to the right module, plus a 10 bits
  523  * encoding version. */
  524 #define OBJ_MODULE 5    /* Module object. */
  525 #define OBJ_STREAM 6    /* Stream object. */
  526 
  527 /* Extract encver / signature from a module type ID. */
  528 #define REDISMODULE_TYPE_ENCVER_BITS 10
  529 #define REDISMODULE_TYPE_ENCVER_MASK ((1<<REDISMODULE_TYPE_ENCVER_BITS)-1)
  530 #define REDISMODULE_TYPE_ENCVER(id) (id & REDISMODULE_TYPE_ENCVER_MASK)
  531 #define REDISMODULE_TYPE_SIGN(id) ((id & ~((uint64_t)REDISMODULE_TYPE_ENCVER_MASK)) >>REDISMODULE_TYPE_ENCVER_BITS)
  532 
  533 /* Bit flags for moduleTypeAuxSaveFunc */
  534 #define REDISMODULE_AUX_BEFORE_RDB (1<<0)
  535 #define REDISMODULE_AUX_AFTER_RDB (1<<1)
  536 
  537 struct RedisModule;
  538 struct RedisModuleIO;
  539 struct RedisModuleDigest;
  540 struct RedisModuleCtx;
  541 struct redisObject;
  542 struct RedisModuleDefragCtx;
  543 
  544 /* Each module type implementation should export a set of methods in order
  545  * to serialize and deserialize the value in the RDB file, rewrite the AOF
  546  * log, create the digest for "DEBUG DIGEST", and free the value when a key
  547  * is deleted. */
  548 typedef void *(*moduleTypeLoadFunc)(struct RedisModuleIO *io, int encver);
  549 typedef void (*moduleTypeSaveFunc)(struct RedisModuleIO *io, void *value);
  550 typedef int (*moduleTypeAuxLoadFunc)(struct RedisModuleIO *rdb, int encver, int when);
  551 typedef void (*moduleTypeAuxSaveFunc)(struct RedisModuleIO *rdb, int when);
  552 typedef void (*moduleTypeRewriteFunc)(struct RedisModuleIO *io, struct redisObject *key, void *value);
  553 typedef void (*moduleTypeDigestFunc)(struct RedisModuleDigest *digest, void *value);
  554 typedef size_t (*moduleTypeMemUsageFunc)(const void *value);
  555 typedef void (*moduleTypeFreeFunc)(void *value);
  556 typedef size_t (*moduleTypeFreeEffortFunc)(struct redisObject *key, const void *value);
  557 typedef void (*moduleTypeUnlinkFunc)(struct redisObject *key, void *value);
  558 typedef void *(*moduleTypeCopyFunc)(struct redisObject *fromkey, struct redisObject *tokey, const void *value);
  559 typedef int (*moduleTypeDefragFunc)(struct RedisModuleDefragCtx *ctx, struct redisObject *key, void **value);
  560 
  561 /* This callback type is called by moduleNotifyUserChanged() every time
  562  * a user authenticated via the module API is associated with a different
  563  * user or gets disconnected. This needs to be exposed since you can't cast
  564  * a function pointer to (void *). */
  565 typedef void (*RedisModuleUserChangedFunc) (uint64_t client_id, void *privdata);
  566 
  567 
  568 /* The module type, which is referenced in each value of a given type, defines
  569  * the methods and links to the module exporting the type. */
  570 typedef struct RedisModuleType {
  571     uint64_t id; /* Higher 54 bits of type ID + 10 lower bits of encoding ver. */
  572     struct RedisModule *module;
  573     moduleTypeLoadFunc rdb_load;
  574     moduleTypeSaveFunc rdb_save;
  575     moduleTypeRewriteFunc aof_rewrite;
  576     moduleTypeMemUsageFunc mem_usage;
  577     moduleTypeDigestFunc digest;
  578     moduleTypeFreeFunc free;
  579     moduleTypeFreeEffortFunc free_effort;
  580     moduleTypeUnlinkFunc unlink;
  581     moduleTypeCopyFunc copy;
  582     moduleTypeDefragFunc defrag;
  583     moduleTypeAuxLoadFunc aux_load;
  584     moduleTypeAuxSaveFunc aux_save;
  585     int aux_save_triggers;
  586     char name[10]; /* 9 bytes name + null term. Charset: A-Z a-z 0-9 _- */
  587 } moduleType;
  588 
  589 /* In Redis objects 'robj' structures of type OBJ_MODULE, the value pointer
  590  * is set to the following structure, referencing the moduleType structure
  591  * in order to work with the value, and at the same time providing a raw
  592  * pointer to the value, as created by the module commands operating with
  593  * the module type.
  594  *
  595  * So for example in order to free such a value, it is possible to use
  596  * the following code:
  597  *
  598  *  if (robj->type == OBJ_MODULE) {
  599  *      moduleValue *mt = robj->ptr;
  600  *      mt->type->free(mt->value);
  601  *      zfree(mt); // We need to release this in-the-middle struct as well.
  602  *  }
  603  */
  604 typedef struct moduleValue {
  605     moduleType *type;
  606     void *value;
  607 } moduleValue;
  608 
  609 /* This is a wrapper for the 'rio' streams used inside rdb.c in Redis, so that
  610  * the user does not have to take the total count of the written bytes nor
  611  * to care about error conditions. */
  612 typedef struct RedisModuleIO {
  613     size_t bytes;       /* Bytes read / written so far. */
  614     rio *rio;           /* Rio stream. */
  615     moduleType *type;   /* Module type doing the operation. */
  616     int error;          /* True if error condition happened. */
  617     int ver;            /* Module serialization version: 1 (old),
  618                          * 2 (current version with opcodes annotation). */
  619     struct RedisModuleCtx *ctx; /* Optional context, see RM_GetContextFromIO()*/
  620     struct redisObject *key;    /* Optional name of key processed */
  621 } RedisModuleIO;
  622 
  623 /* Macro to initialize an IO context. Note that the 'ver' field is populated
  624  * inside rdb.c according to the version of the value to load. */
  625 #define moduleInitIOContext(iovar,mtype,rioptr,keyptr) do { \
  626     iovar.rio = rioptr; \
  627     iovar.type = mtype; \
  628     iovar.bytes = 0; \
  629     iovar.error = 0; \
  630     iovar.ver = 0; \
  631     iovar.key = keyptr; \
  632     iovar.ctx = NULL; \
  633 } while(0)
  634 
  635 /* This is a structure used to export DEBUG DIGEST capabilities to Redis
  636  * modules. We want to capture both the ordered and unordered elements of
  637  * a data structure, so that a digest can be created in a way that correctly
  638  * reflects the values. See the DEBUG DIGEST command implementation for more
  639  * background. */
  640 typedef struct RedisModuleDigest {
  641     unsigned char o[20];    /* Ordered elements. */
  642     unsigned char x[20];    /* Xored elements. */
  643 } RedisModuleDigest;
  644 
  645 /* Just start with a digest composed of all zero bytes. */
  646 #define moduleInitDigestContext(mdvar) do { \
  647     memset(mdvar.o,0,sizeof(mdvar.o)); \
  648     memset(mdvar.x,0,sizeof(mdvar.x)); \
  649 } while(0)
  650 
  651 /* Objects encoding. Some kind of objects like Strings and Hashes can be
  652  * internally represented in multiple ways. The 'encoding' field of the object
  653  * is set to one of this fields for this object. */
  654 #define OBJ_ENCODING_RAW 0     /* Raw representation */
  655 #define OBJ_ENCODING_INT 1     /* Encoded as integer */
  656 #define OBJ_ENCODING_HT 2      /* Encoded as hash table */
  657 #define OBJ_ENCODING_ZIPMAP 3  /* Encoded as zipmap */
  658 #define OBJ_ENCODING_LINKEDLIST 4 /* No longer used: old list encoding. */
  659 #define OBJ_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
  660 #define OBJ_ENCODING_INTSET 6  /* Encoded as intset */
  661 #define OBJ_ENCODING_SKIPLIST 7  /* Encoded as skiplist */
  662 #define OBJ_ENCODING_EMBSTR 8  /* Embedded sds string encoding */
  663 #define OBJ_ENCODING_QUICKLIST 9 /* Encoded as linked list of ziplists */
  664 #define OBJ_ENCODING_STREAM 10 /* Encoded as a radix tree of listpacks */
  665 
  666 #define LRU_BITS 24
  667 #define LRU_CLOCK_MAX ((1<<LRU_BITS)-1) /* Max value of obj->lru */
  668 #define LRU_CLOCK_RESOLUTION 1000 /* LRU clock resolution in ms */
  669 
  670 #define OBJ_SHARED_REFCOUNT INT_MAX     /* Global object never destroyed. */
  671 #define OBJ_STATIC_REFCOUNT (INT_MAX-1) /* Object allocated in the stack. */
  672 #define OBJ_FIRST_SPECIAL_REFCOUNT OBJ_STATIC_REFCOUNT
  673 typedef struct redisObject {
  674     unsigned type:4;
  675     unsigned encoding:4;
  676     unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
  677                             * LFU data (least significant 8 bits frequency
  678                             * and most significant 16 bits access time). */
  679     int refcount;
  680     void *ptr;
  681 } robj;
  682 
  683 /* The a string name for an object's type as listed above
  684  * Native types are checked against the OBJ_STRING, OBJ_LIST, OBJ_* defines,
  685  * and Module types have their registered name returned. */
  686 char *getObjectTypeName(robj*);
  687 
  688 /* Macro used to initialize a Redis object allocated on the stack.
  689  * Note that this macro is taken near the structure definition to make sure
  690  * we'll update it when the structure is changed, to avoid bugs like
  691  * bug #85 introduced exactly in this way. */
  692 #define initStaticStringObject(_var,_ptr) do { \
  693     _var.refcount = OBJ_STATIC_REFCOUNT; \
  694     _var.type = OBJ_STRING; \
  695     _var.encoding = OBJ_ENCODING_RAW; \
  696     _var.ptr = _ptr; \
  697 } while(0)
  698 
  699 struct evictionPoolEntry; /* Defined in evict.c */
  700 
  701 /* This structure is used in order to represent the output buffer of a client,
  702  * which is actually a linked list of blocks like that, that is: client->reply. */
  703 typedef struct clientReplyBlock {
  704     size_t size, used;
  705     char buf[];
  706 } clientReplyBlock;
  707 
  708 /* Redis database representation. There are multiple databases identified
  709  * by integers from 0 (the default database) up to the max configured
  710  * database. The database number is the 'id' field in the structure. */
  711 typedef struct redisDb {
  712     dict *dict;                 /* The keyspace for this DB */
  713     dict *expires;              /* Timeout of keys with a timeout set */
  714     dict *blocking_keys;        /* Keys with clients waiting for data (BLPOP)*/
  715     dict *ready_keys;           /* Blocked keys that received a PUSH */
  716     dict *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS */
  717     int id;                     /* Database ID */
  718     long long avg_ttl;          /* Average TTL, just for stats */
  719     unsigned long expires_cursor; /* Cursor of the active expire cycle. */
  720     list *defrag_later;         /* List of key names to attempt to defrag one by one, gradually. */
  721 } redisDb;
  722 
  723 /* Declare database backup that include redis main DBs and slots to keys map.
  724  * Definition is in db.c. We can't define it here since we define CLUSTER_SLOTS
  725  * in cluster.h. */
  726 typedef struct dbBackup dbBackup;
  727 
  728 /* Client MULTI/EXEC state */
  729 typedef struct multiCmd {
  730     robj **argv;
  731     int argc;
  732     struct redisCommand *cmd;
  733 } multiCmd;
  734 
  735 typedef struct multiState {
  736     multiCmd *commands;     /* Array of MULTI commands */
  737     int count;              /* Total number of MULTI commands */
  738     int cmd_flags;          /* The accumulated command flags OR-ed together.
  739                                So if at least a command has a given flag, it
  740                                will be set in this field. */
  741     int cmd_inv_flags;      /* Same as cmd_flags, OR-ing the ~flags. so that it
  742                                is possible to know if all the commands have a
  743                                certain flag. */
  744 } multiState;
  745 
  746 /* This structure holds the blocking operation state for a client.
  747  * The fields used depend on client->btype. */
  748 typedef struct blockingState {
  749     /* Generic fields. */
  750     mstime_t timeout;       /* Blocking operation timeout. If UNIX current time
  751                              * is > timeout then the operation timed out. */
  752 
  753     /* BLOCKED_LIST, BLOCKED_ZSET and BLOCKED_STREAM */
  754     dict *keys;             /* The keys we are waiting to terminate a blocking
  755                              * operation such as BLPOP or XREAD. Or NULL. */
  756     robj *target;           /* The key that should receive the element,
  757                              * for BLMOVE. */
  758     struct listPos {
  759         int wherefrom;      /* Where to pop from */
  760         int whereto;        /* Where to push to */
  761     } listpos;              /* The positions in the src/dst lists
  762                              * where we want to pop/push an element
  763                              * for BLPOP, BRPOP and BLMOVE. */
  764 
  765     /* BLOCK_STREAM */
  766     size_t xread_count;     /* XREAD COUNT option. */
  767     robj *xread_group;      /* XREADGROUP group name. */
  768     robj *xread_consumer;   /* XREADGROUP consumer name. */
  769     int xread_group_noack;
  770 
  771     /* BLOCKED_WAIT */
  772     int numreplicas;        /* Number of replicas we are waiting for ACK. */
  773     long long reploffset;   /* Replication offset to reach. */
  774 
  775     /* BLOCKED_MODULE */
  776     void *module_blocked_handle; /* RedisModuleBlockedClient structure.
  777                                     which is opaque for the Redis core, only
  778                                     handled in module.c. */
  779 } blockingState;
  780 
  781 /* The following structure represents a node in the server.ready_keys list,
  782  * where we accumulate all the keys that had clients blocked with a blocking
  783  * operation such as B[LR]POP, but received new data in the context of the
  784  * last executed command.
  785  *
  786  * After the execution of every command or script, we run this list to check
  787  * if as a result we should serve data to clients blocked, unblocking them.
  788  * Note that server.ready_keys will not have duplicates as there dictionary
  789  * also called ready_keys in every structure representing a Redis database,
  790  * where we make sure to remember if a given key was already added in the
  791  * server.ready_keys list. */
  792 typedef struct readyList {
  793     redisDb *db;
  794     robj *key;
  795 } readyList;
  796 
  797 /* This structure represents a Redis user. This is useful for ACLs, the
  798  * user is associated to the connection after the connection is authenticated.
  799  * If there is no associated user, the connection uses the default user. */
  800 #define USER_COMMAND_BITS_COUNT 1024    /* The total number of command bits
  801                                            in the user structure. The last valid
  802                                            command ID we can set in the user
  803                                            is USER_COMMAND_BITS_COUNT-1. */
  804 #define USER_FLAG_ENABLED (1<<0)        /* The user is active. */
  805 #define USER_FLAG_DISABLED (1<<1)       /* The user is disabled. */
  806 #define USER_FLAG_ALLKEYS (1<<2)        /* The user can mention any key. */
  807 #define USER_FLAG_ALLCOMMANDS (1<<3)    /* The user can run all commands. */
  808 #define USER_FLAG_NOPASS      (1<<4)    /* The user requires no password, any
  809                                            provided password will work. For the
  810                                            default user, this also means that
  811                                            no AUTH is needed, and every
  812                                            connection is immediately
  813                                            authenticated. */
  814 #define USER_FLAG_ALLCHANNELS (1<<5)    /* The user can mention any Pub/Sub
  815                                            channel. */
  816 #define USER_FLAG_SANITIZE_PAYLOAD (1<<6)       /* The user require a deep RESTORE
  817                                                  * payload sanitization. */
  818 #define USER_FLAG_SANITIZE_PAYLOAD_SKIP (1<<7)  /* The user should skip the
  819                                                  * deep sanitization of RESTORE
  820                                                  * payload. */
  821 
  822 typedef struct {
  823     sds name;       /* The username as an SDS string. */
  824     uint64_t flags; /* See USER_FLAG_* */
  825 
  826     /* The bit in allowed_commands is set if this user has the right to
  827      * execute this command. In commands having subcommands, if this bit is
  828      * set, then all the subcommands are also available.
  829      *
  830      * If the bit for a given command is NOT set and the command has
  831      * subcommands, Redis will also check allowed_subcommands in order to
  832      * understand if the command can be executed. */
  833     uint64_t allowed_commands[USER_COMMAND_BITS_COUNT/64];
  834 
  835     /* This array points, for each command ID (corresponding to the command
  836      * bit set in allowed_commands), to an array of SDS strings, terminated by
  837      * a NULL pointer, with all the sub commands that can be executed for
  838      * this command. When no subcommands matching is used, the field is just
  839      * set to NULL to avoid allocating USER_COMMAND_BITS_COUNT pointers. */
  840     sds **allowed_subcommands;
  841     list *passwords; /* A list of SDS valid passwords for this user. */
  842     list *patterns;  /* A list of allowed key patterns. If this field is NULL
  843                         the user cannot mention any key in a command, unless
  844                         the flag ALLKEYS is set in the user. */
  845     list *channels;  /* A list of allowed Pub/Sub channel patterns. If this
  846                         field is NULL the user cannot mention any channel in a
  847                         `PUBLISH` or [P][UNSUBSCRIBE] command, unless the flag
  848                         ALLCHANNELS is set in the user. */
  849 } user;
  850 
  851 /* With multiplexing we need to take per-client state.
  852  * Clients are taken in a linked list. */
  853 
  854 #define CLIENT_ID_AOF (UINT64_MAX) /* Reserved ID for the AOF client. If you
  855                                       need more reserved IDs use UINT64_MAX-1,
  856                                       -2, ... and so forth. */
  857 
  858 typedef struct client {
  859     uint64_t id;            /* Client incremental unique ID. */
  860     connection *conn;
  861     int resp;               /* RESP protocol version. Can be 2 or 3. */
  862     redisDb *db;            /* Pointer to currently SELECTed DB. */
  863     robj *name;             /* As set by CLIENT SETNAME. */
  864     sds querybuf;           /* Buffer we use to accumulate client queries. */
  865     size_t qb_pos;          /* The position we have read in querybuf. */
  866     sds pending_querybuf;   /* If this client is flagged as master, this buffer
  867                                represents the yet not applied portion of the
  868                                replication stream that we are receiving from
  869                                the master. */
  870     size_t querybuf_peak;   /* Recent (100ms or more) peak of querybuf size. */
  871     int argc;               /* Num of arguments of current command. */
  872     robj **argv;            /* Arguments of current command. */
  873     int original_argc;      /* Num of arguments of original command if arguments were rewritten. */
  874     robj **original_argv;   /* Arguments of original command if arguments were rewritten. */
  875     size_t argv_len_sum;    /* Sum of lengths of objects in argv list. */
  876     struct redisCommand *cmd, *lastcmd;  /* Last command executed. */
  877     user *user;             /* User associated with this connection. If the
  878                                user is set to NULL the connection can do
  879                                anything (admin). */
  880     int reqtype;            /* Request protocol type: PROTO_REQ_* */
  881     int multibulklen;       /* Number of multi bulk arguments left to read. */
  882     long bulklen;           /* Length of bulk argument in multi bulk request. */
  883     list *reply;            /* List of reply objects to send to the client. */
  884     unsigned long long reply_bytes; /* Tot bytes of objects in reply list. */
  885     size_t sentlen;         /* Amount of bytes already sent in the current
  886                                buffer or object being sent. */
  887     time_t ctime;           /* Client creation time. */
  888     long duration;          /* Current command duration. Used for measuring latency of blocking/non-blocking cmds */
  889     time_t lastinteraction; /* Time of the last interaction, used for timeout */
  890     time_t obuf_soft_limit_reached_time;
  891     uint64_t flags;         /* Client flags: CLIENT_* macros. */
  892     int authenticated;      /* Needed when the default user requires auth. */
  893     int replstate;          /* Replication state if this is a slave. */
  894     int repl_put_online_on_ack; /* Install slave write handler on first ACK. */
  895     int repldbfd;           /* Replication DB file descriptor. */
  896     off_t repldboff;        /* Replication DB file offset. */
  897     off_t repldbsize;       /* Replication DB file size. */
  898     sds replpreamble;       /* Replication DB preamble. */
  899     long long read_reploff; /* Read replication offset if this is a master. */
  900     long long reploff;      /* Applied replication offset if this is a master. */
  901     long long repl_ack_off; /* Replication ack offset, if this is a slave. */
  902     long long repl_ack_time;/* Replication ack time, if this is a slave. */
  903     long long repl_last_partial_write; /* The last time the server did a partial write from the RDB child pipe to this replica  */
  904     long long psync_initial_offset; /* FULLRESYNC reply offset other slaves
  905                                        copying this slave output buffer
  906                                        should use. */
  907     char replid[CONFIG_RUN_ID_SIZE+1]; /* Master replication ID (if master). */
  908     int slave_listening_port; /* As configured with: REPLCONF listening-port */
  909     char *slave_addr;       /* Optionally given by REPLCONF ip-address */
  910     int slave_capa;         /* Slave capabilities: SLAVE_CAPA_* bitwise OR. */
  911     multiState mstate;      /* MULTI/EXEC state */
  912     int btype;              /* Type of blocking op if CLIENT_BLOCKED. */
  913     blockingState bpop;     /* blocking state */
  914     long long woff;         /* Last write global replication offset. */
  915     list *watched_keys;     /* Keys WATCHED for MULTI/EXEC CAS */
  916     dict *pubsub_channels;  /* channels a client is interested in (SUBSCRIBE) */
  917     list *pubsub_patterns;  /* patterns a client is interested in (SUBSCRIBE) */
  918     sds peerid;             /* Cached peer ID. */
  919     sds sockname;           /* Cached connection target address. */
  920     listNode *client_list_node; /* list node in client list */
  921     listNode *paused_list_node; /* list node within the pause list */
  922     RedisModuleUserChangedFunc auth_callback; /* Module callback to execute
  923                                                * when the authenticated user
  924                                                * changes. */
  925     void *auth_callback_privdata; /* Private data that is passed when the auth
  926                                    * changed callback is executed. Opaque for
  927                                    * Redis Core. */
  928     void *auth_module;      /* The module that owns the callback, which is used
  929                              * to disconnect the client if the module is
  930                              * unloaded for cleanup. Opaque for Redis Core.*/
  931 
  932     /* If this client is in tracking mode and this field is non zero,
  933      * invalidation messages for keys fetched by this client will be send to
  934      * the specified client ID. */
  935     uint64_t client_tracking_redirection;
  936     rax *client_tracking_prefixes; /* A dictionary of prefixes we are already
  937                                       subscribed to in BCAST mode, in the
  938                                       context of client side caching. */
  939     /* In clientsCronTrackClientsMemUsage() we track the memory usage of
  940      * each client and add it to the sum of all the clients of a given type,
  941      * however we need to remember what was the old contribution of each
  942      * client, and in which categoty the client was, in order to remove it
  943      * before adding it the new value. */
  944     uint64_t client_cron_last_memory_usage;
  945     int      client_cron_last_memory_type;
  946     /* Response buffer */
  947     int bufpos;
  948     char buf[PROTO_REPLY_CHUNK_BYTES];
  949 } client;
  950 
  951 struct saveparam {
  952     time_t seconds;
  953     int changes;
  954 };
  955 
  956 struct moduleLoadQueueEntry {
  957     sds path;
  958     int argc;
  959     robj **argv;
  960 };
  961 
  962 struct sentinelLoadQueueEntry {
  963     int argc;
  964     sds *argv;
  965     int linenum;
  966     sds line;
  967 };
  968 
  969 struct sentinelConfig {
  970     list *pre_monitor_cfg;
  971     list *monitor_cfg;
  972     list *post_monitor_cfg;
  973 };
  974 
  975 struct sharedObjectsStruct {
  976     robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
  977     *colon, *queued, *null[4], *nullarray[4], *emptymap[4], *emptyset[4],
  978     *emptyarray, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
  979     *outofrangeerr, *noscripterr, *loadingerr, *slowscripterr, *bgsaveerr,
  980     *masterdownerr, *roslaveerr, *execaborterr, *noautherr, *noreplicaserr,
  981     *busykeyerr, *oomerr, *plus, *messagebulk, *pmessagebulk, *subscribebulk,
  982     *unsubscribebulk, *psubscribebulk, *punsubscribebulk, *del, *unlink,
  983     *rpop, *lpop, *lpush, *rpoplpush, *lmove, *blmove, *zpopmin, *zpopmax,
  984     *emptyscan, *multi, *exec, *left, *right, *hset, *srem, *xgroup, *xclaim,  
  985     *script, *replconf, *eval, *persist, *set, *pexpireat, *pexpire, 
  986     *time, *pxat, *px, *retrycount, *force, *justid, 
  987     *lastid, *ping, *setid, *keepttl, *load, *createconsumer,
  988     *getack, *special_asterick, *special_equals, *default_username, *redacted,
  989     *select[PROTO_SHARED_SELECT_CMDS],
  990     *integers[OBJ_SHARED_INTEGERS],
  991     *mbulkhdr[OBJ_SHARED_BULKHDR_LEN], /* "*<value>\r\n" */
  992     *bulkhdr[OBJ_SHARED_BULKHDR_LEN];  /* "$<value>\r\n" */
  993     sds minstring, maxstring;
  994 };
  995 
  996 /* ZSETs use a specialized version of Skiplists */
  997 typedef struct zskiplistNode {
  998     sds ele;
  999     double score;
 1000     struct zskiplistNode *backward;
 1001     struct zskiplistLevel {
 1002         struct zskiplistNode *forward;
 1003         unsigned long span;
 1004     } level[];
 1005 } zskiplistNode;
 1006 
 1007 typedef struct zskiplist {
 1008     struct zskiplistNode *header, *tail;
 1009     unsigned long length;
 1010     int level;
 1011 } zskiplist;
 1012 
 1013 typedef struct zset {
 1014     dict *dict;
 1015     zskiplist *zsl;
 1016 } zset;
 1017 
 1018 typedef struct clientBufferLimitsConfig {
 1019     unsigned long long hard_limit_bytes;
 1020     unsigned long long soft_limit_bytes;
 1021     time_t soft_limit_seconds;
 1022 } clientBufferLimitsConfig;
 1023 
 1024 extern clientBufferLimitsConfig clientBufferLimitsDefaults[CLIENT_TYPE_OBUF_COUNT];
 1025 
 1026 /* The redisOp structure defines a Redis Operation, that is an instance of
 1027  * a command with an argument vector, database ID, propagation target
 1028  * (PROPAGATE_*), and command pointer.
 1029  *
 1030  * Currently only used to additionally propagate more commands to AOF/Replication
 1031  * after the propagation of the executed command. */
 1032 typedef struct redisOp {
 1033     robj **argv;
 1034     int argc, dbid, target;
 1035     struct redisCommand *cmd;
 1036 } redisOp;
 1037 
 1038 /* Defines an array of Redis operations. There is an API to add to this
 1039  * structure in an easy way.
 1040  *
 1041  * redisOpArrayInit();
 1042  * redisOpArrayAppend();
 1043  * redisOpArrayFree();
 1044  */
 1045 typedef struct redisOpArray {
 1046     redisOp *ops;
 1047     int numops;
 1048 } redisOpArray;
 1049 
 1050 /* This structure is returned by the getMemoryOverheadData() function in
 1051  * order to return memory overhead information. */
 1052 struct redisMemOverhead {
 1053     size_t peak_allocated;
 1054     size_t total_allocated;
 1055     size_t startup_allocated;
 1056     size_t repl_backlog;
 1057     size_t clients_slaves;
 1058     size_t clients_normal;
 1059     size_t aof_buffer;
 1060     size_t lua_caches;
 1061     size_t overhead_total;
 1062     size_t dataset;
 1063     size_t total_keys;
 1064     size_t bytes_per_key;
 1065     float dataset_perc;
 1066     float peak_perc;
 1067     float total_frag;
 1068     ssize_t total_frag_bytes;
 1069     float allocator_frag;
 1070     ssize_t allocator_frag_bytes;
 1071     float allocator_rss;
 1072     ssize_t allocator_rss_bytes;
 1073     float rss_extra;
 1074     size_t rss_extra_bytes;
 1075     size_t num_dbs;
 1076     struct {
 1077         size_t dbid;
 1078         size_t overhead_ht_main;
 1079         size_t overhead_ht_expires;
 1080     } *db;
 1081 };
 1082 
 1083 /* This structure can be optionally passed to RDB save/load functions in
 1084  * order to implement additional functionalities, by storing and loading
 1085  * metadata to the RDB file.
 1086  *
 1087  * Currently the only use is to select a DB at load time, useful in
 1088  * replication in order to make sure that chained slaves (slaves of slaves)
 1089  * select the correct DB and are able to accept the stream coming from the
 1090  * top-level master. */
 1091 typedef struct rdbSaveInfo {
 1092     /* Used saving and loading. */
 1093     int repl_stream_db;  /* DB to select in server.master client. */
 1094 
 1095     /* Used only loading. */
 1096     int repl_id_is_set;  /* True if repl_id field is set. */
 1097     char repl_id[CONFIG_RUN_ID_SIZE+1];     /* Replication ID. */
 1098     long long repl_offset;                  /* Replication offset. */
 1099 } rdbSaveInfo;
 1100 
 1101 #define RDB_SAVE_INFO_INIT {-1,0,"0000000000000000000000000000000000000000",-1}
 1102 
 1103 struct malloc_stats {
 1104     size_t zmalloc_used;
 1105     size_t process_rss;
 1106     size_t allocator_allocated;
 1107     size_t allocator_active;
 1108     size_t allocator_resident;
 1109 };
 1110 
 1111 typedef struct socketFds {
 1112     int fd[CONFIG_BINDADDR_MAX];
 1113     int count;
 1114 } socketFds;
 1115 
 1116 /*-----------------------------------------------------------------------------
 1117  * TLS Context Configuration
 1118  *----------------------------------------------------------------------------*/
 1119 
 1120 typedef struct redisTLSContextConfig {
 1121     char *cert_file;                /* Server side and optionally client side cert file name */
 1122     char *key_file;                 /* Private key filename for cert_file */
 1123     char *key_file_pass;            /* Optional password for key_file */
 1124     char *client_cert_file;         /* Certificate to use as a client; if none, use cert_file */
 1125     char *client_key_file;          /* Private key filename for client_cert_file */
 1126     char *client_key_file_pass;     /* Optional password for client_key_file */
 1127     char *dh_params_file;
 1128     char *ca_cert_file;
 1129     char *ca_cert_dir;
 1130     char *protocols;
 1131     char *ciphers;
 1132     char *ciphersuites;
 1133     int prefer_server_ciphers;
 1134     int session_caching;
 1135     int session_cache_size;
 1136     int session_cache_timeout;
 1137 } redisTLSContextConfig;
 1138 
 1139 /*-----------------------------------------------------------------------------
 1140  * Global server state
 1141  *----------------------------------------------------------------------------*/
 1142 
 1143 struct clusterState;
 1144 
 1145 /* AIX defines hz to __hz, we don't use this define and in order to allow
 1146  * Redis build on AIX we need to undef it. */
 1147 #ifdef _AIX
 1148 #undef hz
 1149 #endif
 1150 
 1151 #define CHILD_TYPE_NONE 0
 1152 #define CHILD_TYPE_RDB 1
 1153 #define CHILD_TYPE_AOF 2
 1154 #define CHILD_TYPE_LDB 3
 1155 #define CHILD_TYPE_MODULE 4
 1156 
 1157 typedef enum childInfoType {
 1158     CHILD_INFO_TYPE_CURRENT_INFO,
 1159     CHILD_INFO_TYPE_AOF_COW_SIZE,
 1160     CHILD_INFO_TYPE_RDB_COW_SIZE,
 1161     CHILD_INFO_TYPE_MODULE_COW_SIZE
 1162 } childInfoType;
 1163 
 1164 struct redisServer {
 1165     /* General */
 1166     pid_t pid;                  /* Main process pid. */
 1167     pthread_t main_thread_id;         /* Main thread id */
 1168     char *configfile;           /* Absolute config file path, or NULL */
 1169     char *executable;           /* Absolute executable file path. */
 1170     char **exec_argv;           /* Executable argv vector (copy). */
 1171     int dynamic_hz;             /* Change hz value depending on # of clients. */
 1172     int config_hz;              /* Configured HZ value. May be different than
 1173                                    the actual 'hz' field value if dynamic-hz
 1174                                    is enabled. */
 1175     mode_t umask;               /* The umask value of the process on startup */
 1176     int hz;                     /* serverCron() calls frequency in hertz */
 1177     int in_fork_child;          /* indication that this is a fork child */
 1178     redisDb *db;
 1179     dict *commands;             /* Command table */
 1180     dict *orig_commands;        /* Command table before command renaming. */
 1181     aeEventLoop *el;
 1182     rax *errors;                /* Errors table */
 1183     redisAtomic unsigned int lruclock; /* Clock for LRU eviction */
 1184     volatile sig_atomic_t shutdown_asap; /* SHUTDOWN needed ASAP */
 1185     int activerehashing;        /* Incremental rehash in serverCron() */
 1186     int active_defrag_running;  /* Active defragmentation running (holds current scan aggressiveness) */
 1187     char *pidfile;              /* PID file path */
 1188     int arch_bits;              /* 32 or 64 depending on sizeof(long) */
 1189     int cronloops;              /* Number of times the cron function run */
 1190     char runid[CONFIG_RUN_ID_SIZE+1];  /* ID always different at every exec. */
 1191     int sentinel_mode;          /* True if this instance is a Sentinel. */
 1192     size_t initial_memory_usage; /* Bytes used after initialization. */
 1193     int always_show_logo;       /* Show logo even for non-stdout logging. */
 1194     int in_eval;                /* Are we inside EVAL? */
 1195     int in_exec;                /* Are we inside EXEC? */
 1196     int propagate_in_transaction;  /* Make sure we don't propagate nested MULTI/EXEC */
 1197     char *ignore_warnings;      /* Config: warnings that should be ignored. */
 1198     int client_pause_in_transaction; /* Was a client pause executed during this Exec? */
 1199     /* Modules */
 1200     dict *moduleapi;            /* Exported core APIs dictionary for modules. */
 1201     dict *sharedapi;            /* Like moduleapi but containing the APIs that
 1202                                    modules share with each other. */
 1203     list *loadmodule_queue;     /* List of modules to load at startup. */
 1204     int module_blocked_pipe[2]; /* Pipe used to awake the event loop if a
 1205                                    client blocked on a module command needs
 1206                                    to be processed. */
 1207     pid_t child_pid;            /* PID of current child */
 1208     int child_type;             /* Type of current child */
 1209     client *module_client;      /* "Fake" client to call Redis from modules */
 1210     /* Networking */
 1211     int port;                   /* TCP listening port */
 1212     int tls_port;               /* TLS listening port */
 1213     int tcp_backlog;            /* TCP listen() backlog */
 1214     char *bindaddr[CONFIG_BINDADDR_MAX]; /* Addresses we should bind to */
 1215     int bindaddr_count;         /* Number of addresses in server.bindaddr[] */
 1216     char *unixsocket;           /* UNIX socket path */
 1217     mode_t unixsocketperm;      /* UNIX socket permission */
 1218     socketFds ipfd;             /* TCP socket file descriptors */
 1219     socketFds tlsfd;            /* TLS socket file descriptors */
 1220     int sofd;                   /* Unix socket file descriptor */
 1221     socketFds cfd;              /* Cluster bus listening socket */
 1222     list *clients;              /* List of active clients */
 1223     list *clients_to_close;     /* Clients to close asynchronously */
 1224     list *clients_pending_write; /* There is to write or install handler. */
 1225     list *clients_pending_read;  /* Client has pending read socket buffers. */
 1226     list *slaves, *monitors;    /* List of slaves and MONITORs */
 1227     client *current_client;     /* Current client executing the command. */
 1228     rax *clients_timeout_table; /* Radix tree for blocked clients timeouts. */
 1229     long fixed_time_expire;     /* If > 0, expire keys against server.mstime. */
 1230     rax *clients_index;         /* Active clients dictionary by client ID. */
 1231     pause_type client_pause_type;      /* True if clients are currently paused */
 1232     list *paused_clients;       /* List of pause clients */
 1233     mstime_t client_pause_end_time;    /* Time when we undo clients_paused */
 1234     char neterr[ANET_ERR_LEN];   /* Error buffer for anet.c */
 1235     dict *migrate_cached_sockets;/* MIGRATE cached sockets */
 1236     redisAtomic uint64_t next_client_id; /* Next client unique ID. Incremental. */
 1237     int protected_mode;         /* Don't accept external connections. */
 1238     int gopher_enabled;         /* If true the server will reply to gopher
 1239                                    queries. Will still serve RESP2 queries. */
 1240     int io_threads_num;         /* Number of IO threads to use. */
 1241     int io_threads_do_reads;    /* Read and parse from IO threads? */
 1242     int io_threads_active;      /* Is IO threads currently active? */
 1243     long long events_processed_while_blocked; /* processEventsWhileBlocked() */
 1244 
 1245     /* RDB / AOF loading information */
 1246     volatile sig_atomic_t loading; /* We are loading data from disk if true */
 1247     off_t loading_total_bytes;
 1248     off_t loading_rdb_used_mem;
 1249     off_t loading_loaded_bytes;
 1250     time_t loading_start_time;
 1251     off_t loading_process_events_interval_bytes;
 1252     /* Fast pointers to often looked up command */
 1253     struct redisCommand *delCommand, *multiCommand, *lpushCommand,
 1254                         *lpopCommand, *rpopCommand, *zpopminCommand,
 1255                         *zpopmaxCommand, *sremCommand, *execCommand,
 1256                         *expireCommand, *pexpireCommand, *xclaimCommand,
 1257                         *xgroupCommand, *rpoplpushCommand, *lmoveCommand;
 1258     /* Fields used only for stats */
 1259     time_t stat_starttime;          /* Server start time */
 1260     long long stat_numcommands;     /* Number of processed commands */
 1261     long long stat_numconnections;  /* Number of connections received */
 1262     long long stat_expiredkeys;     /* Number of expired keys */
 1263     double stat_expired_stale_perc; /* Percentage of keys probably expired */
 1264     long long stat_expired_time_cap_reached_count; /* Early expire cylce stops.*/
 1265     long long stat_expire_cycle_time_used; /* Cumulative microseconds used. */
 1266     long long stat_evictedkeys;     /* Number of evicted keys (maxmemory) */
 1267     long long stat_keyspace_hits;   /* Number of successful lookups of keys */
 1268     long long stat_keyspace_misses; /* Number of failed lookups of keys */
 1269     long long stat_active_defrag_hits;      /* number of allocations moved */
 1270     long long stat_active_defrag_misses;    /* number of allocations scanned but not moved */
 1271     long long stat_active_defrag_key_hits;  /* number of keys with moved allocations */
 1272     long long stat_active_defrag_key_misses;/* number of keys scanned and not moved */
 1273     long long stat_active_defrag_scanned;   /* number of dictEntries scanned */
 1274     size_t stat_peak_memory;        /* Max used memory record */
 1275     long long stat_fork_time;       /* Time needed to perform latest fork() */
 1276     double stat_fork_rate;          /* Fork rate in GB/sec. */
 1277     long long stat_total_forks;     /* Total count of fork. */
 1278     long long stat_rejected_conn;   /* Clients rejected because of maxclients */
 1279     long long stat_sync_full;       /* Number of full resyncs with slaves. */
 1280     long long stat_sync_partial_ok; /* Number of accepted PSYNC requests. */
 1281     long long stat_sync_partial_err;/* Number of unaccepted PSYNC requests. */
 1282     list *slowlog;                  /* SLOWLOG list of commands */
 1283     long long slowlog_entry_id;     /* SLOWLOG current entry ID */
 1284     long long slowlog_log_slower_than; /* SLOWLOG time limit (to get logged) */
 1285     unsigned long slowlog_max_len;     /* SLOWLOG max number of items logged */
 1286     struct malloc_stats cron_malloc_stats; /* sampled in serverCron(). */
 1287     redisAtomic long long stat_net_input_bytes; /* Bytes read from network. */
 1288     redisAtomic long long stat_net_output_bytes; /* Bytes written to network. */
 1289     size_t stat_current_cow_bytes;  /* Copy on write bytes while child is active. */
 1290     monotime stat_current_cow_updated;  /* Last update time of stat_current_cow_bytes */
 1291     size_t stat_current_save_keys_processed;  /* Processed keys while child is active. */
 1292     size_t stat_current_save_keys_total;  /* Number of keys when child started. */
 1293     size_t stat_rdb_cow_bytes;      /* Copy on write bytes during RDB saving. */
 1294     size_t stat_aof_cow_bytes;      /* Copy on write bytes during AOF rewrite. */
 1295     size_t stat_module_cow_bytes;   /* Copy on write bytes during module fork. */
 1296     double stat_module_progress;   /* Module save progress. */
 1297     uint64_t stat_clients_type_memory[CLIENT_TYPE_COUNT];/* Mem usage by type */
 1298     long long stat_unexpected_error_replies; /* Number of unexpected (aof-loading, replica to master, etc.) error replies */
 1299     long long stat_total_error_replies; /* Total number of issued error replies ( command + rejected errors ) */
 1300     long long stat_dump_payload_sanitizations; /* Number deep dump payloads integrity validations. */
 1301     long long stat_io_reads_processed; /* Number of read events processed by IO / Main threads */
 1302     long long stat_io_writes_processed; /* Number of write events processed by IO / Main threads */
 1303     redisAtomic long long stat_total_reads_processed; /* Total number of read events processed */
 1304     redisAtomic long long stat_total_writes_processed; /* Total number of write events processed */
 1305     /* The following two are used to track instantaneous metrics, like
 1306      * number of operations per second, network traffic. */
 1307     struct {
 1308         long long last_sample_time; /* Timestamp of last sample in ms */
 1309         long long last_sample_count;/* Count in last sample */
 1310         long long samples[STATS_METRIC_SAMPLES];
 1311         int idx;
 1312     } inst_metric[STATS_METRIC_COUNT];
 1313     /* Configuration */
 1314     int verbosity;                  /* Loglevel in redis.conf */
 1315     int maxidletime;                /* Client timeout in seconds */
 1316     int tcpkeepalive;               /* Set SO_KEEPALIVE if non-zero. */
 1317     int active_expire_enabled;      /* Can be disabled for testing purposes. */
 1318     int active_expire_effort;       /* From 1 (default) to 10, active effort. */
 1319     int active_defrag_enabled;
 1320     int sanitize_dump_payload;      /* Enables deep sanitization for ziplist and listpack in RDB and RESTORE. */
 1321     int skip_checksum_validation;   /* Disables checksum validateion for RDB and RESTORE payload. */
 1322     int jemalloc_bg_thread;         /* Enable jemalloc background thread */
 1323     size_t active_defrag_ignore_bytes; /* minimum amount of fragmentation waste to start active defrag */
 1324     int active_defrag_threshold_lower; /* minimum percentage of fragmentation to start active defrag */
 1325     int active_defrag_threshold_upper; /* maximum percentage of fragmentation at which we use maximum effort */
 1326     int active_defrag_cycle_min;       /* minimal effort for defrag in CPU percentage */
 1327     int active_defrag_cycle_max;       /* maximal effort for defrag in CPU percentage */
 1328     unsigned long active_defrag_max_scan_fields; /* maximum number of fields of set/hash/zset/list to process from within the main dict scan */
 1329     size_t client_max_querybuf_len; /* Limit for client query buffer length */
 1330     int dbnum;                      /* Total number of configured DBs */
 1331     int supervised;                 /* 1 if supervised, 0 otherwise. */
 1332     int supervised_mode;            /* See SUPERVISED_* */
 1333     int daemonize;                  /* True if running as a daemon */
 1334     int set_proc_title;             /* True if change proc title */
 1335     char *proc_title_template;      /* Process title template format */
 1336     clientBufferLimitsConfig client_obuf_limits[CLIENT_TYPE_OBUF_COUNT];
 1337     /* AOF persistence */
 1338     int aof_enabled;                /* AOF configuration */
 1339     int aof_state;                  /* AOF_(ON|OFF|WAIT_REWRITE) */
 1340     int aof_fsync;                  /* Kind of fsync() policy */
 1341     char *aof_filename;             /* Name of the AOF file */
 1342     int aof_no_fsync_on_rewrite;    /* Don't fsync if a rewrite is in prog. */
 1343     int aof_rewrite_perc;           /* Rewrite AOF if % growth is > M and... */
 1344     off_t aof_rewrite_min_size;     /* the AOF file is at least N bytes. */
 1345     off_t aof_rewrite_base_size;    /* AOF size on latest startup or rewrite. */
 1346     off_t aof_current_size;         /* AOF current size. */
 1347     off_t aof_fsync_offset;         /* AOF offset which is already synced to disk. */
 1348     int aof_flush_sleep;            /* Micros to sleep before flush. (used by tests) */
 1349     int aof_rewrite_scheduled;      /* Rewrite once BGSAVE terminates. */
 1350     list *aof_rewrite_buf_blocks;   /* Hold changes during an AOF rewrite. */
 1351     sds aof_buf;      /* AOF buffer, written before entering the event loop */
 1352     int aof_fd;       /* File descriptor of currently selected AOF file */
 1353     int aof_selected_db; /* Currently selected DB in AOF */
 1354     time_t aof_flush_postponed_start; /* UNIX time of postponed AOF flush */
 1355     time_t aof_last_fsync;            /* UNIX time of last fsync() */
 1356     time_t aof_rewrite_time_last;   /* Time used by last AOF rewrite run. */
 1357     time_t aof_rewrite_time_start;  /* Current AOF rewrite start time. */
 1358     int aof_lastbgrewrite_status;   /* C_OK or C_ERR */
 1359     unsigned long aof_delayed_fsync;  /* delayed AOF fsync() counter */
 1360     int aof_rewrite_incremental_fsync;/* fsync incrementally while aof rewriting? */
 1361     int rdb_save_incremental_fsync;   /* fsync incrementally while rdb saving? */
 1362     int aof_last_write_status;      /* C_OK or C_ERR */
 1363     int aof_last_write_errno;       /* Valid if aof write/fsync status is ERR */
 1364     int aof_load_truncated;         /* Don't stop on unexpected AOF EOF. */
 1365     int aof_use_rdb_preamble;       /* Use RDB preamble on AOF rewrites. */
 1366     redisAtomic int aof_bio_fsync_status; /* Status of AOF fsync in bio job. */
 1367     redisAtomic int aof_bio_fsync_errno;  /* Errno of AOF fsync in bio job. */
 1368     /* AOF pipes used to communicate between parent and child during rewrite. */
 1369     int aof_pipe_write_data_to_child;
 1370     int aof_pipe_read_data_from_parent;
 1371     int aof_pipe_write_ack_to_parent;
 1372     int aof_pipe_read_ack_from_child;
 1373     int aof_pipe_write_ack_to_child;
 1374     int aof_pipe_read_ack_from_parent;
 1375     int aof_stop_sending_diff;     /* If true stop sending accumulated diffs
 1376                                       to child process. */
 1377     sds aof_child_diff;             /* AOF diff accumulator child side. */
 1378     /* RDB persistence */
 1379     long long dirty;                /* Changes to DB from the last save */
 1380     long long dirty_before_bgsave;  /* Used to restore dirty on failed BGSAVE */
 1381     struct saveparam *saveparams;   /* Save points array for RDB */
 1382     int saveparamslen;              /* Number of saving points */
 1383     char *rdb_filename;             /* Name of RDB file */
 1384     int rdb_compression;            /* Use compression in RDB? */
 1385     int rdb_checksum;               /* Use RDB checksum? */
 1386     int rdb_del_sync_files;         /* Remove RDB files used only for SYNC if
 1387                                        the instance does not use persistence. */
 1388     time_t lastsave;                /* Unix time of last successful save */
 1389     time_t lastbgsave_try;          /* Unix time of last attempted bgsave */
 1390     time_t rdb_save_time_last;      /* Time used by last RDB save run. */
 1391     time_t rdb_save_time_start;     /* Current RDB save start time. */
 1392     int rdb_bgsave_scheduled;       /* BGSAVE when possible if true. */
 1393     int rdb_child_type;             /* Type of save by active child. */
 1394     int lastbgsave_status;          /* C_OK or C_ERR */
 1395     int stop_writes_on_bgsave_err;  /* Don't allow writes if can't BGSAVE */
 1396     int rdb_pipe_read;              /* RDB pipe used to transfer the rdb data */
 1397                                     /* to the parent process in diskless repl. */
 1398     int rdb_child_exit_pipe;        /* Used by the diskless parent allow child exit. */
 1399     connection **rdb_pipe_conns;    /* Connections which are currently the */
 1400     int rdb_pipe_numconns;          /* target of diskless rdb fork child. */
 1401     int rdb_pipe_numconns_writing;  /* Number of rdb conns with pending writes. */
 1402     char *rdb_pipe_buff;            /* In diskless replication, this buffer holds data */
 1403     int rdb_pipe_bufflen;           /* that was read from the the rdb pipe. */
 1404     int rdb_key_save_delay;         /* Delay in microseconds between keys while
 1405                                      * writing the RDB. (for testings). negative
 1406                                      * value means fractions of microsecons (on average). */
 1407     int key_load_delay;             /* Delay in microseconds between keys while
 1408                                      * loading aof or rdb. (for testings). negative
 1409                                      * value means fractions of microsecons (on average). */
 1410     /* Pipe and data structures for child -> parent info sharing. */
 1411     int child_info_pipe[2];         /* Pipe used to write the child_info_data. */
 1412     int child_info_nread;           /* Num of bytes of the last read from pipe */
 1413     /* Propagation of commands in AOF / replication */
 1414     redisOpArray also_propagate;    /* Additional command to propagate. */
 1415     int replication_allowed;        /* Are we allowed to replicate? */
 1416     /* Logging */
 1417     char *logfile;                  /* Path of log file */
 1418     int syslog_enabled;             /* Is syslog enabled? */
 1419     char *syslog_ident;             /* Syslog ident */
 1420     int syslog_facility;            /* Syslog facility */
 1421     int crashlog_enabled;           /* Enable signal handler for crashlog.
 1422                                      * disable for clean core dumps. */
 1423     int memcheck_enabled;           /* Enable memory check on crash. */
 1424     int use_exit_on_panic;          /* Use exit() on panic and assert rather than
 1425                                      * abort(). useful for Valgrind. */
 1426     /* Replication (master) */
 1427     char replid[CONFIG_RUN_ID_SIZE+1];  /* My current replication ID. */
 1428     char replid2[CONFIG_RUN_ID_SIZE+1]; /* replid inherited from master*/
 1429     long long master_repl_offset;   /* My current replication offset */
 1430     long long second_replid_offset; /* Accept offsets up to this for replid2. */
 1431     int slaveseldb;                 /* Last SELECTed DB in replication output */
 1432     int repl_ping_slave_period;     /* Master pings the slave every N seconds */
 1433     char *repl_backlog;             /* Replication backlog for partial syncs */
 1434     long long repl_backlog_size;    /* Backlog circular buffer size */
 1435     long long repl_backlog_histlen; /* Backlog actual data length */
 1436     long long repl_backlog_idx;     /* Backlog circular buffer current offset,
 1437                                        that is the next byte will'll write to.*/
 1438     long long repl_backlog_off;     /* Replication "master offset" of first
 1439                                        byte in the replication backlog buffer.*/
 1440     time_t repl_backlog_time_limit; /* Time without slaves after the backlog
 1441                                        gets released. */
 1442     time_t repl_no_slaves_since;    /* We have no slaves since that time.
 1443                                        Only valid if server.slaves len is 0. */
 1444     int repl_min_slaves_to_write;   /* Min number of slaves to write. */
 1445     int repl_min_slaves_max_lag;    /* Max lag of <count> slaves to write. */
 1446     int repl_good_slaves_count;     /* Number of slaves with lag <= max_lag. */
 1447     int repl_diskless_sync;         /* Master send RDB to slaves sockets directly. */
 1448     int repl_diskless_load;         /* Slave parse RDB directly from the socket.
 1449                                      * see REPL_DISKLESS_LOAD_* enum */
 1450     int repl_diskless_sync_delay;   /* Delay to start a diskless repl BGSAVE. */
 1451     /* Replication (slave) */
 1452     char *masteruser;               /* AUTH with this user and masterauth with master */
 1453     sds masterauth;                 /* AUTH with this password with master */
 1454     char *masterhost;               /* Hostname of master */
 1455     int masterport;                 /* Port of master */
 1456     int repl_timeout;               /* Timeout after N seconds of master idle */
 1457     client *master;     /* Client that is master for this slave */
 1458     client *cached_master; /* Cached master to be reused for PSYNC. */
 1459     int repl_syncio_timeout; /* Timeout for synchronous I/O calls */
 1460     int repl_state;          /* Replication status if the instance is a slave */
 1461     off_t repl_transfer_size; /* Size of RDB to read from master during sync. */
 1462     off_t repl_transfer_read; /* Amount of RDB read from master during sync. */
 1463     off_t repl_transfer_last_fsync_off; /* Offset when we fsync-ed last time. */
 1464     connection *repl_transfer_s;     /* Slave -> Master SYNC connection */
 1465     int repl_transfer_fd;    /* Slave -> Master SYNC temp file descriptor */
 1466     char *repl_transfer_tmpfile; /* Slave-> master SYNC temp file name */
 1467     time_t repl_transfer_lastio; /* Unix time of the latest read, for timeout */
 1468     int repl_serve_stale_data; /* Serve stale data when link is down? */
 1469     int repl_slave_ro;          /* Slave is read only? */
 1470     int repl_slave_ignore_maxmemory;    /* If true slaves do not evict. */
 1471     time_t repl_down_since; /* Unix time at which link with master went down */
 1472     int repl_disable_tcp_nodelay;   /* Disable TCP_NODELAY after SYNC? */
 1473     int slave_priority;             /* Reported in INFO and used by Sentinel. */
 1474     int replica_announced;          /* If true, replica is announced by Sentinel */
 1475     int slave_announce_port;        /* Give the master this listening port. */
 1476     char *slave_announce_ip;        /* Give the master this ip address. */
 1477     /* The following two fields is where we store master PSYNC replid/offset
 1478      * while the PSYNC is in progress. At the end we'll copy the fields into
 1479      * the server->master client structure. */
 1480     char master_replid[CONFIG_RUN_ID_SIZE+1];  /* Master PSYNC runid. */
 1481     long long master_initial_offset;           /* Master PSYNC offset. */
 1482     int repl_slave_lazy_flush;          /* Lazy FLUSHALL before loading DB? */
 1483     /* Replication script cache. */
 1484     dict *repl_scriptcache_dict;        /* SHA1 all slaves are aware of. */
 1485     list *repl_scriptcache_fifo;        /* First in, first out LRU eviction. */
 1486     unsigned int repl_scriptcache_size; /* Max number of elements. */
 1487     /* Synchronous replication. */
 1488     list *clients_waiting_acks;         /* Clients waiting in WAIT command. */
 1489     int get_ack_from_slaves;            /* If true we send REPLCONF GETACK. */
 1490     /* Limits */
 1491     unsigned int maxclients;            /* Max number of simultaneous clients */
 1492     unsigned long long maxmemory;   /* Max number of memory bytes to use */
 1493     int maxmemory_policy;           /* Policy for key eviction */
 1494     int maxmemory_samples;          /* Precision of random sampling */
 1495     int maxmemory_eviction_tenacity;/* Aggressiveness of eviction processing */
 1496     int lfu_log_factor;             /* LFU logarithmic counter factor. */
 1497     int lfu_decay_time;             /* LFU counter decay factor. */
 1498     long long proto_max_bulk_len;   /* Protocol bulk length maximum size. */
 1499     int oom_score_adj_base;         /* Base oom_score_adj value, as observed on startup */
 1500     int oom_score_adj_values[CONFIG_OOM_COUNT];   /* Linux oom_score_adj configuration */
 1501     int oom_score_adj;                            /* If true, oom_score_adj is managed */
 1502     int disable_thp;                              /* If true, disable THP by syscall */
 1503     /* Blocked clients */
 1504     unsigned int blocked_clients;   /* # of clients executing a blocking cmd.*/
 1505     unsigned int blocked_clients_by_type[BLOCKED_NUM];
 1506     list *unblocked_clients; /* list of clients to unblock before next loop */
 1507     list *ready_keys;        /* List of readyList structures for BLPOP & co */
 1508     /* Client side caching. */
 1509     unsigned int tracking_clients;  /* # of clients with tracking enabled.*/
 1510     size_t tracking_table_max_keys; /* Max number of keys in tracking table. */
 1511     /* Sort parameters - qsort_r() is only available under BSD so we
 1512      * have to take this state global, in order to pass it to sortCompare() */
 1513     int sort_desc;
 1514     int sort_alpha;
 1515     int sort_bypattern;
 1516     int sort_store;
 1517     /* Zip structure config, see redis.conf for more information  */
 1518     size_t hash_max_ziplist_entries;
 1519     size_t hash_max_ziplist_value;
 1520     size_t set_max_intset_entries;
 1521     size_t zset_max_ziplist_entries;
 1522     size_t zset_max_ziplist_value;
 1523     size_t hll_sparse_max_bytes;
 1524     size_t stream_node_max_bytes;
 1525     long long stream_node_max_entries;
 1526     /* List parameters */
 1527     int list_max_ziplist_size;
 1528     int list_compress_depth;
 1529     /* time cache */
 1530     redisAtomic time_t unixtime; /* Unix time sampled every cron cycle. */
 1531     time_t timezone;            /* Cached timezone. As set by tzset(). */
 1532     int daylight_active;        /* Currently in daylight saving time. */
 1533     mstime_t mstime;            /* 'unixtime' in milliseconds. */
 1534     ustime_t ustime;            /* 'unixtime' in microseconds. */
 1535     size_t blocking_op_nesting; /* Nesting level of blocking operation, used to reset blocked_last_cron. */
 1536     long long blocked_last_cron; /* Indicate the mstime of the last time we did cron jobs from a blocking operation */
 1537     /* Pubsub */
 1538     dict *pubsub_channels;  /* Map channels to list of subscribed clients */
 1539     dict *pubsub_patterns;  /* A dict of pubsub_patterns */
 1540     int notify_keyspace_events; /* Events to propagate via Pub/Sub. This is an
 1541                                    xor of NOTIFY_... flags. */
 1542     /* Cluster */
 1543     int cluster_enabled;      /* Is cluster enabled? */
 1544     mstime_t cluster_node_timeout; /* Cluster node timeout. */
 1545     char *cluster_configfile; /* Cluster auto-generated config file name. */
 1546     struct clusterState *cluster;  /* State of the cluster */
 1547     int cluster_migration_barrier; /* Cluster replicas migration barrier. */
 1548     int cluster_allow_replica_migration; /* Automatic replica migrations to orphaned masters and from empty masters */
 1549     int cluster_slave_validity_factor; /* Slave max data age for failover. */
 1550     int cluster_require_full_coverage; /* If true, put the cluster down if
 1551                                           there is at least an uncovered slot.*/
 1552     int cluster_slave_no_failover;  /* Prevent slave from starting a failover
 1553                                        if the master is in failure state. */
 1554     char *cluster_announce_ip;  /* IP address to announce on cluster bus. */
 1555     int cluster_announce_port;     /* base port to announce on cluster bus. */
 1556     int cluster_announce_tls_port; /* TLS port to announce on cluster bus. */
 1557     int cluster_announce_bus_port; /* bus port to announce on cluster bus. */
 1558     int cluster_module_flags;      /* Set of flags that Redis modules are able
 1559                                       to set in order to suppress certain
 1560                                       native Redis Cluster features. Check the
 1561                                       REDISMODULE_CLUSTER_FLAG_*. */
 1562     int cluster_allow_reads_when_down; /* Are reads allowed when the cluster
 1563                                         is down? */
 1564     int cluster_config_file_lock_fd;   /* cluster config fd, will be flock */
 1565     /* Scripting */
 1566     lua_State *lua; /* The Lua interpreter. We use just one for all clients */
 1567     client *lua_client;   /* The "fake client" to query Redis from Lua */
 1568     client *lua_caller;   /* The client running EVAL right now, or NULL */
 1569     char* lua_cur_script; /* SHA1 of the script currently running, or NULL */
 1570     dict *lua_scripts;         /* A dictionary of SHA1 -> Lua scripts */
 1571     unsigned long long lua_scripts_mem;  /* Cached scripts' memory + oh */
 1572     mstime_t lua_time_limit;  /* Script timeout in milliseconds */
 1573     monotime lua_time_start;  /* monotonic timer to detect timed-out script */
 1574     mstime_t lua_time_snapshot; /* Snapshot of mstime when script is started */
 1575     int lua_write_dirty;  /* True if a write command was called during the
 1576                              execution of the current script. */
 1577     int lua_random_dirty; /* True if a random command was called during the
 1578                              execution of the current script. */
 1579     int lua_replicate_commands; /* True if we are doing single commands repl. */
 1580     int lua_multi_emitted;/* True if we already propagated MULTI. */
 1581     int lua_repl;         /* Script replication flags for redis.set_repl(). */
 1582     int lua_timedout;     /* True if we reached the time limit for script
 1583                              execution. */
 1584     int lua_kill;         /* Kill the script if true. */
 1585     int lua_always_replicate_commands; /* Default replication type. */
 1586     int lua_oom;          /* OOM detected when script start? */
 1587     /* Lazy free */
 1588     int lazyfree_lazy_eviction;
 1589     int lazyfree_lazy_expire;
 1590     int lazyfree_lazy_server_del;
 1591     int lazyfree_lazy_user_del;
 1592     int lazyfree_lazy_user_flush;
 1593     /* Latency monitor */
 1594     long long latency_monitor_threshold;
 1595     dict *latency_events;
 1596     /* ACLs */
 1597     char *acl_filename;           /* ACL Users file. NULL if not configured. */
 1598     unsigned long acllog_max_len; /* Maximum length of the ACL LOG list. */
 1599     sds requirepass;              /* Remember the cleartext password set with
 1600                                      the old "requirepass" directive for
 1601                                      backward compatibility with Redis <= 5. */
 1602     int acl_pubsub_default;      /* Default ACL pub/sub channels flag */
 1603     /* Assert & bug reporting */
 1604     int watchdog_period;  /* Software watchdog period in ms. 0 = off */
 1605     /* System hardware info */
 1606     size_t system_memory_size;  /* Total memory in system as reported by OS */
 1607     /* TLS Configuration */
 1608     int tls_cluster;
 1609     int tls_replication;
 1610     int tls_auth_clients;
 1611     redisTLSContextConfig tls_ctx_config;
 1612     /* cpu affinity */
 1613     char *server_cpulist; /* cpu affinity list of redis server main/io thread. */
 1614     char *bio_cpulist; /* cpu affinity list of bio thread. */
 1615     char *aof_rewrite_cpulist; /* cpu affinity list of aof rewrite process. */
 1616     char *bgsave_cpulist; /* cpu affinity list of bgsave process. */
 1617     /* Sentinel config */
 1618     struct sentinelConfig *sentinel_config; /* sentinel config to load at startup time. */
 1619     /* Coordinate failover info */
 1620     mstime_t failover_end_time; /* Deadline for failover command. */
 1621     int force_failover; /* If true then failover will be foreced at the
 1622                          * deadline, otherwise failover is aborted. */
 1623     char *target_replica_host; /* Failover target host. If null during a
 1624                                 * failover then any replica can be used. */
 1625     int target_replica_port; /* Failover target port */
 1626     int failover_state; /* Failover state */
 1627 };
 1628 
 1629 #define MAX_KEYS_BUFFER 256
 1630 
 1631 /* A result structure for the various getkeys function calls. It lists the
 1632  * keys as indices to the provided argv.
 1633  */
 1634 typedef struct {
 1635     int keysbuf[MAX_KEYS_BUFFER];       /* Pre-allocated buffer, to save heap allocations */
 1636     int *keys;                          /* Key indices array, points to keysbuf or heap */
 1637     int numkeys;                        /* Number of key indices return */
 1638     int size;                           /* Available array size */
 1639 } getKeysResult;
 1640 #define GETKEYS_RESULT_INIT { {0}, NULL, 0, MAX_KEYS_BUFFER }
 1641 
 1642 typedef void redisCommandProc(client *c);
 1643 typedef int redisGetKeysProc(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 1644 struct redisCommand {
 1645     char *name;
 1646     redisCommandProc *proc;
 1647     int arity;
 1648     char *sflags;   /* Flags as string representation, one char per flag. */
 1649     uint64_t flags; /* The actual flags, obtained from the 'sflags' field. */
 1650     /* Use a function to determine keys arguments in a command line.
 1651      * Used for Redis Cluster redirect. */
 1652     redisGetKeysProc *getkeys_proc;
 1653     /* What keys should be loaded in background when calling this command? */
 1654     int firstkey; /* The first argument that's a key (0 = no keys) */
 1655     int lastkey;  /* The last argument that's a key */
 1656     int keystep;  /* The step between first and last key */
 1657     long long microseconds, calls, rejected_calls, failed_calls;
 1658     int id;     /* Command ID. This is a progressive ID starting from 0 that
 1659                    is assigned at runtime, and is used in order to check
 1660                    ACLs. A connection is able to execute a given command if
 1661                    the user associated to the connection has this command
 1662                    bit set in the bitmap of allowed commands. */
 1663 };
 1664 
 1665 struct redisError {
 1666     long long count;
 1667 };
 1668 
 1669 struct redisFunctionSym {
 1670     char *name;
 1671     unsigned long pointer;
 1672 };
 1673 
 1674 typedef struct _redisSortObject {
 1675     robj *obj;
 1676     union {
 1677         double score;
 1678         robj *cmpobj;
 1679     } u;
 1680 } redisSortObject;
 1681 
 1682 typedef struct _redisSortOperation {
 1683     int type;
 1684     robj *pattern;
 1685 } redisSortOperation;
 1686 
 1687 /* Structure to hold list iteration abstraction. */
 1688 typedef struct {
 1689     robj *subject;
 1690     unsigned char encoding;
 1691     unsigned char direction; /* Iteration direction */
 1692     quicklistIter *iter;
 1693 } listTypeIterator;
 1694 
 1695 /* Structure for an entry while iterating over a list. */
 1696 typedef struct {
 1697     listTypeIterator *li;
 1698     quicklistEntry entry; /* Entry in quicklist */
 1699 } listTypeEntry;
 1700 
 1701 /* Structure to hold set iteration abstraction. */
 1702 typedef struct {
 1703     robj *subject;
 1704     int encoding;
 1705     int ii; /* intset iterator */
 1706     dictIterator *di;
 1707 } setTypeIterator;
 1708 
 1709 /* Structure to hold hash iteration abstraction. Note that iteration over
 1710  * hashes involves both fields and values. Because it is possible that
 1711  * not both are required, store pointers in the iterator to avoid
 1712  * unnecessary memory allocation for fields/values. */
 1713 typedef struct {
 1714     robj *subject;
 1715     int encoding;
 1716 
 1717     unsigned char *fptr, *vptr;
 1718 
 1719     dictIterator *di;
 1720     dictEntry *de;
 1721 } hashTypeIterator;
 1722 
 1723 #include "stream.h"  /* Stream data type header file. */
 1724 
 1725 #define OBJ_HASH_KEY 1
 1726 #define OBJ_HASH_VALUE 2
 1727 
 1728 /*-----------------------------------------------------------------------------
 1729  * Extern declarations
 1730  *----------------------------------------------------------------------------*/
 1731 
 1732 extern struct redisServer server;
 1733 extern struct sharedObjectsStruct shared;
 1734 extern dictType objectKeyPointerValueDictType;
 1735 extern dictType objectKeyHeapPointerValueDictType;
 1736 extern dictType setDictType;
 1737 extern dictType zsetDictType;
 1738 extern dictType clusterNodesDictType;
 1739 extern dictType clusterNodesBlackListDictType;
 1740 extern dictType dbDictType;
 1741 extern dictType shaScriptObjectDictType;
 1742 extern double R_Zero, R_PosInf, R_NegInf, R_Nan;
 1743 extern dictType hashDictType;
 1744 extern dictType replScriptCacheDictType;
 1745 extern dictType dbExpiresDictType;
 1746 extern dictType modulesDictType;
 1747 extern dictType sdsReplyDictType;
 1748 
 1749 /*-----------------------------------------------------------------------------
 1750  * Functions prototypes
 1751  *----------------------------------------------------------------------------*/
 1752 
 1753 /* Modules */
 1754 void moduleInitModulesSystem(void);
 1755 void moduleInitModulesSystemLast(void);
 1756 int moduleLoad(const char *path, void **argv, int argc);
 1757 void moduleLoadFromQueue(void);
 1758 int moduleGetCommandKeysViaAPI(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 1759 moduleType *moduleTypeLookupModuleByID(uint64_t id);
 1760 void moduleTypeNameByID(char *name, uint64_t moduleid);
 1761 const char *moduleTypeModuleName(moduleType *mt);
 1762 void moduleFreeContext(struct RedisModuleCtx *ctx);
 1763 void unblockClientFromModule(client *c);
 1764 void moduleHandleBlockedClients(void);
 1765 void moduleBlockedClientTimedOut(client *c);
 1766 void moduleBlockedClientPipeReadable(aeEventLoop *el, int fd, void *privdata, int mask);
 1767 size_t moduleCount(void);
 1768 void moduleAcquireGIL(void);
 1769 int moduleTryAcquireGIL(void);
 1770 void moduleReleaseGIL(void);
 1771 void moduleNotifyKeyspaceEvent(int type, const char *event, robj *key, int dbid);
 1772 void moduleCallCommandFilters(client *c);
 1773 void ModuleForkDoneHandler(int exitcode, int bysignal);
 1774 int TerminateModuleForkChild(int child_pid, int wait);
 1775 ssize_t rdbSaveModulesAux(rio *rdb, int when);
 1776 int moduleAllDatatypesHandleErrors();
 1777 sds modulesCollectInfo(sds info, const char *section, int for_crash_report, int sections);
 1778 void moduleFireServerEvent(uint64_t eid, int subid, void *data);
 1779 void processModuleLoadingProgressEvent(int is_aof);
 1780 int moduleTryServeClientBlockedOnKey(client *c, robj *key);
 1781 void moduleUnblockClient(client *c);
 1782 int moduleBlockedClientMayTimeout(client *c);
 1783 int moduleClientIsBlockedOnKeys(client *c);
 1784 void moduleNotifyUserChanged(client *c);
 1785 void moduleNotifyKeyUnlink(robj *key, robj *val);
 1786 robj *moduleTypeDupOrReply(client *c, robj *fromkey, robj *tokey, robj *value);
 1787 int moduleDefragValue(robj *key, robj *obj, long *defragged);
 1788 int moduleLateDefrag(robj *key, robj *value, unsigned long *cursor, long long endtime, long long *defragged);
 1789 long moduleDefragGlobals(void);
 1790 
 1791 /* Utils */
 1792 long long ustime(void);
 1793 long long mstime(void);
 1794 void getRandomHexChars(char *p, size_t len);
 1795 void getRandomBytes(unsigned char *p, size_t len);
 1796 uint64_t crc64(uint64_t crc, const unsigned char *s, uint64_t l);
 1797 void exitFromChild(int retcode);
 1798 long long redisPopcount(void *s, long count);
 1799 int redisSetProcTitle(char *title);
 1800 int validateProcTitleTemplate(const char *template);
 1801 int redisCommunicateSystemd(const char *sd_notify_msg);
 1802 void redisSetCpuAffinity(const char *cpulist);
 1803 
 1804 /* networking.c -- Networking and Client related operations */
 1805 client *createClient(connection *conn);
 1806 void closeTimedoutClients(void);
 1807 void freeClient(client *c);
 1808 void freeClientAsync(client *c);
 1809 void resetClient(client *c);
 1810 void freeClientOriginalArgv(client *c);
 1811 void sendReplyToClient(connection *conn);
 1812 void *addReplyDeferredLen(client *c);
 1813 void setDeferredArrayLen(client *c, void *node, long length);
 1814 void setDeferredMapLen(client *c, void *node, long length);
 1815 void setDeferredSetLen(client *c, void *node, long length);
 1816 void setDeferredAttributeLen(client *c, void *node, long length);
 1817 void setDeferredPushLen(client *c, void *node, long length);
 1818 void processInputBuffer(client *c);
 1819 void processGopherRequest(client *c);
 1820 void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
 1821 void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask);
 1822 void acceptTLSHandler(aeEventLoop *el, int fd, void *privdata, int mask);
 1823 void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask);
 1824 void readQueryFromClient(connection *conn);
 1825 void addReplyNull(client *c);
 1826 void addReplyNullArray(client *c);
 1827 void addReplyBool(client *c, int b);
 1828 void addReplyVerbatim(client *c, const char *s, size_t len, const char *ext);
 1829 void addReplyProto(client *c, const char *s, size_t len);
 1830 void AddReplyFromClient(client *c, client *src);
 1831 void addReplyBulk(client *c, robj *obj);
 1832 void addReplyBulkCString(client *c, const char *s);
 1833 void addReplyBulkCBuffer(client *c, const void *p, size_t len);
 1834 void addReplyBulkLongLong(client *c, long long ll);
 1835 void addReply(client *c, robj *obj);
 1836 void addReplySds(client *c, sds s);
 1837 void addReplyBulkSds(client *c, sds s);
 1838 void setDeferredReplyBulkSds(client *c, void *node, sds s);
 1839 void addReplyErrorObject(client *c, robj *err);
 1840 void addReplyErrorSds(client *c, sds err);
 1841 void addReplyError(client *c, const char *err);
 1842 void addReplyStatus(client *c, const char *status);
 1843 void addReplyDouble(client *c, double d);
 1844 void addReplyBigNum(client *c, const char* num, size_t len);
 1845 void addReplyHumanLongDouble(client *c, long double d);
 1846 void addReplyLongLong(client *c, long long ll);
 1847 void addReplyArrayLen(client *c, long length);
 1848 void addReplyMapLen(client *c, long length);
 1849 void addReplySetLen(client *c, long length);
 1850 void addReplyAttributeLen(client *c, long length);
 1851 void addReplyPushLen(client *c, long length);
 1852 void addReplyHelp(client *c, const char **help);
 1853 void addReplySubcommandSyntaxError(client *c);
 1854 void addReplyLoadedModules(client *c);
 1855 void copyClientOutputBuffer(client *dst, client *src);
 1856 size_t sdsZmallocSize(sds s);
 1857 size_t getStringObjectSdsUsedMemory(robj *o);
 1858 void freeClientReplyValue(void *o);
 1859 void *dupClientReplyValue(void *o);
 1860 void getClientsMaxBuffers(unsigned long *longest_output_list,
 1861                           unsigned long *biggest_input_buffer);
 1862 char *getClientPeerId(client *client);
 1863 char *getClientSockName(client *client);
 1864 sds catClientInfoString(sds s, client *client);
 1865 sds getAllClientsInfoString(int type);
 1866 void rewriteClientCommandVector(client *c, int argc, ...);
 1867 void rewriteClientCommandArgument(client *c, int i, robj *newval);
 1868 void replaceClientCommandVector(client *c, int argc, robj **argv);
 1869 void redactClientCommandArgument(client *c, int argc);
 1870 unsigned long getClientOutputBufferMemoryUsage(client *c);
 1871 int freeClientsInAsyncFreeQueue(void);
 1872 int closeClientOnOutputBufferLimitReached(client *c, int async);
 1873 int getClientType(client *c);
 1874 int getClientTypeByName(char *name);
 1875 char *getClientTypeName(int class);
 1876 void flushSlavesOutputBuffers(void);
 1877 void disconnectSlaves(void);
 1878 int listenToPort(int port, socketFds *fds);
 1879 void pauseClients(mstime_t duration, pause_type type);
 1880 void unpauseClients(void);
 1881 int areClientsPaused(void);
 1882 int checkClientPauseTimeoutAndReturnIfPaused(void);
 1883 void processEventsWhileBlocked(void);
 1884 void loadingCron(void);
 1885 void whileBlockedCron();
 1886 void blockingOperationStarts();
 1887 void blockingOperationEnds();
 1888 int handleClientsWithPendingWrites(void);
 1889 int handleClientsWithPendingWritesUsingThreads(void);
 1890 int handleClientsWithPendingReadsUsingThreads(void);
 1891 int stopThreadedIOIfNeeded(void);
 1892 int clientHasPendingReplies(client *c);
 1893 void unlinkClient(client *c);
 1894 int writeToClient(client *c, int handler_installed);
 1895 void linkClient(client *c);
 1896 void protectClient(client *c);
 1897 void unprotectClient(client *c);
 1898 void initThreadedIO(void);
 1899 client *lookupClientByID(uint64_t id);
 1900 
 1901 #ifdef __GNUC__
 1902 void addReplyErrorFormat(client *c, const char *fmt, ...)
 1903     __attribute__((format(printf, 2, 3)));
 1904 void addReplyStatusFormat(client *c, const char *fmt, ...)
 1905     __attribute__((format(printf, 2, 3)));
 1906 #else
 1907 void addReplyErrorFormat(client *c, const char *fmt, ...);
 1908 void addReplyStatusFormat(client *c, const char *fmt, ...);
 1909 #endif
 1910 
 1911 /* Client side caching (tracking mode) */
 1912 void enableTracking(client *c, uint64_t redirect_to, uint64_t options, robj **prefix, size_t numprefix);
 1913 void disableTracking(client *c);
 1914 void trackingRememberKeys(client *c);
 1915 void trackingInvalidateKey(client *c, robj *keyobj);
 1916 void trackingInvalidateKeysOnFlush(int async);
 1917 void freeTrackingRadixTree(rax *rt);
 1918 void freeTrackingRadixTreeAsync(rax *rt);
 1919 void trackingLimitUsedSlots(void);
 1920 uint64_t trackingGetTotalItems(void);
 1921 uint64_t trackingGetTotalKeys(void);
 1922 uint64_t trackingGetTotalPrefixes(void);
 1923 void trackingBroadcastInvalidationMessages(void);
 1924 int checkPrefixCollisionsOrReply(client *c, robj **prefix, size_t numprefix);
 1925 
 1926 /* List data type */
 1927 void listTypeTryConversion(robj *subject, robj *value);
 1928 void listTypePush(robj *subject, robj *value, int where);
 1929 robj *listTypePop(robj *subject, int where);
 1930 unsigned long listTypeLength(const robj *subject);
 1931 listTypeIterator *listTypeInitIterator(robj *subject, long index, unsigned char direction);
 1932 void listTypeReleaseIterator(listTypeIterator *li);
 1933 int listTypeNext(listTypeIterator *li, listTypeEntry *entry);
 1934 robj *listTypeGet(listTypeEntry *entry);
 1935 void listTypeInsert(listTypeEntry *entry, robj *value, int where);
 1936 int listTypeEqual(listTypeEntry *entry, robj *o);
 1937 void listTypeDelete(listTypeIterator *iter, listTypeEntry *entry);
 1938 void listTypeConvert(robj *subject, int enc);
 1939 robj *listTypeDup(robj *o);
 1940 void unblockClientWaitingData(client *c);
 1941 void popGenericCommand(client *c, int where);
 1942 void listElementsRemoved(client *c, robj *key, int where, robj *o, long count);
 1943 
 1944 /* MULTI/EXEC/WATCH... */
 1945 void unwatchAllKeys(client *c);
 1946 void initClientMultiState(client *c);
 1947 void freeClientMultiState(client *c);
 1948 void queueMultiCommand(client *c);
 1949 void touchWatchedKey(redisDb *db, robj *key);
 1950 int isWatchedKeyExpired(client *c);
 1951 void touchAllWatchedKeysInDb(redisDb *emptied, redisDb *replaced_with);
 1952 void discardTransaction(client *c);
 1953 void flagTransaction(client *c);
 1954 void execCommandAbort(client *c, sds error);
 1955 void execCommandPropagateMulti(int dbid);
 1956 void execCommandPropagateExec(int dbid);
 1957 void beforePropagateMulti();
 1958 void afterPropagateExec();
 1959 
 1960 /* Redis object implementation */
 1961 void decrRefCount(robj *o);
 1962 void decrRefCountVoid(void *o);
 1963 void incrRefCount(robj *o);
 1964 robj *makeObjectShared(robj *o);
 1965 robj *resetRefCount(robj *obj);
 1966 void freeStringObject(robj *o);
 1967 void freeListObject(robj *o);
 1968 void freeSetObject(robj *o);
 1969 void freeZsetObject(robj *o);
 1970 void freeHashObject(robj *o);
 1971 robj *createObject(int type, void *ptr);
 1972 robj *createStringObject(const char *ptr, size_t len);
 1973 robj *createRawStringObject(const char *ptr, size_t len);
 1974 robj *createEmbeddedStringObject(const char *ptr, size_t len);
 1975 robj *dupStringObject(const robj *o);
 1976 int isSdsRepresentableAsLongLong(sds s, long long *llval);
 1977 int isObjectRepresentableAsLongLong(robj *o, long long *llongval);
 1978 robj *tryObjectEncoding(robj *o);
 1979 robj *getDecodedObject(robj *o);
 1980 size_t stringObjectLen(robj *o);
 1981 robj *createStringObjectFromLongLong(long long value);
 1982 robj *createStringObjectFromLongLongForValue(long long value);
 1983 robj *createStringObjectFromLongDouble(long double value, int humanfriendly);
 1984 robj *createQuicklistObject(void);
 1985 robj *createZiplistObject(void);
 1986 robj *createSetObject(void);
 1987 robj *createIntsetObject(void);
 1988 robj *createHashObject(void);
 1989 robj *createZsetObject(void);
 1990 robj *createZsetZiplistObject(void);
 1991 robj *createStreamObject(void);
 1992 robj *createModuleObject(moduleType *mt, void *value);
 1993 int getLongFromObjectOrReply(client *c, robj *o, long *target, const char *msg);
 1994 int getPositiveLongFromObjectOrReply(client *c, robj *o, long *target, const char *msg);
 1995 int getRangeLongFromObjectOrReply(client *c, robj *o, long min, long max, long *target, const char *msg);
 1996 int checkType(client *c, robj *o, int type);
 1997 int getLongLongFromObjectOrReply(client *c, robj *o, long long *target, const char *msg);
 1998 int getDoubleFromObjectOrReply(client *c, robj *o, double *target, const char *msg);
 1999 int getDoubleFromObject(const robj *o, double *target);
 2000 int getLongLongFromObject(robj *o, long long *target);
 2001 int getLongDoubleFromObject(robj *o, long double *target);
 2002 int getLongDoubleFromObjectOrReply(client *c, robj *o, long double *target, const char *msg);
 2003 int getIntFromObjectOrReply(client *c, robj *o, int *target, const char *msg);
 2004 char *strEncoding(int encoding);
 2005 int compareStringObjects(robj *a, robj *b);
 2006 int collateStringObjects(robj *a, robj *b);
 2007 int equalStringObjects(robj *a, robj *b);
 2008 unsigned long long estimateObjectIdleTime(robj *o);
 2009 void trimStringObjectIfNeeded(robj *o);
 2010 #define sdsEncodedObject(objptr) (objptr->encoding == OBJ_ENCODING_RAW || objptr->encoding == OBJ_ENCODING_EMBSTR)
 2011 
 2012 /* Synchronous I/O with timeout */
 2013 ssize_t syncWrite(int fd, char *ptr, ssize_t size, long long timeout);
 2014 ssize_t syncRead(int fd, char *ptr, ssize_t size, long long timeout);
 2015 ssize_t syncReadLine(int fd, char *ptr, ssize_t size, long long timeout);
 2016 
 2017 /* Replication */
 2018 void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
 2019 void replicationFeedSlavesFromMasterStream(list *slaves, char *buf, size_t buflen);
 2020 void replicationFeedMonitors(client *c, list *monitors, int dictid, robj **argv, int argc);
 2021 void updateSlavesWaitingBgsave(int bgsaveerr, int type);
 2022 void replicationCron(void);
 2023 void replicationStartPendingFork(void);
 2024 void replicationHandleMasterDisconnection(void);
 2025 void replicationCacheMaster(client *c);
 2026 void resizeReplicationBacklog(long long newsize);
 2027 void replicationSetMaster(char *ip, int port);
 2028 void replicationUnsetMaster(void);
 2029 void refreshGoodSlavesCount(void);
 2030 void replicationScriptCacheInit(void);
 2031 void replicationScriptCacheFlush(void);
 2032 void replicationScriptCacheAdd(sds sha1);
 2033 int replicationScriptCacheExists(sds sha1);
 2034 void processClientsWaitingReplicas(void);
 2035 void unblockClientWaitingReplicas(client *c);
 2036 int replicationCountAcksByOffset(long long offset);
 2037 void replicationSendNewlineToMaster(void);
 2038 long long replicationGetSlaveOffset(void);
 2039 char *replicationGetSlaveName(client *c);
 2040 long long getPsyncInitialOffset(void);
 2041 int replicationSetupSlaveForFullResync(client *slave, long long offset);
 2042 void changeReplicationId(void);
 2043 void clearReplicationId2(void);
 2044 void chopReplicationBacklog(void);
 2045 void replicationCacheMasterUsingMyself(void);
 2046 void feedReplicationBacklog(void *ptr, size_t len);
 2047 void showLatestBacklog(void);
 2048 void rdbPipeReadHandler(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask);
 2049 void rdbPipeWriteHandlerConnRemoved(struct connection *conn);
 2050 void clearFailoverState(void);
 2051 void updateFailoverStatus(void);
 2052 void abortFailover(const char *err);
 2053 const char *getFailoverStateString();
 2054 
 2055 /* Generic persistence functions */
 2056 void startLoadingFile(FILE* fp, char* filename, int rdbflags);
 2057 void startLoading(size_t size, int rdbflags);
 2058 void loadingProgress(off_t pos);
 2059 void stopLoading(int success);
 2060 void startSaving(int rdbflags);
 2061 void stopSaving(int success);
 2062 int allPersistenceDisabled(void);
 2063 
 2064 #define DISK_ERROR_TYPE_AOF 1       /* Don't accept writes: AOF errors. */
 2065 #define DISK_ERROR_TYPE_RDB 2       /* Don't accept writes: RDB errors. */
 2066 #define DISK_ERROR_TYPE_NONE 0      /* No problems, we can accept writes. */
 2067 int writeCommandsDeniedByDiskError(void);
 2068 
 2069 /* RDB persistence */
 2070 #include "rdb.h"
 2071 void killRDBChild(void);
 2072 int bg_unlink(const char *filename);
 2073 
 2074 /* AOF persistence */
 2075 void flushAppendOnlyFile(int force);
 2076 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
 2077 void aofRemoveTempFile(pid_t childpid);
 2078 int rewriteAppendOnlyFileBackground(void);
 2079 int loadAppendOnlyFile(char *filename);
 2080 void stopAppendOnly(void);
 2081 int startAppendOnly(void);
 2082 void backgroundRewriteDoneHandler(int exitcode, int bysignal);
 2083 void aofRewriteBufferReset(void);
 2084 unsigned long aofRewriteBufferSize(void);
 2085 ssize_t aofReadDiffFromParent(void);
 2086 void killAppendOnlyChild(void);
 2087 void restartAOFAfterSYNC();
 2088 
 2089 /* Child info */
 2090 void openChildInfoPipe(void);
 2091 void closeChildInfoPipe(void);
 2092 void sendChildInfoGeneric(childInfoType info_type, size_t keys, double progress, char *pname);
 2093 void sendChildCowInfo(childInfoType info_type, char *pname);
 2094 void sendChildInfo(childInfoType info_type, size_t keys, char *pname);
 2095 void receiveChildInfo(void);
 2096 
 2097 /* Fork helpers */
 2098 int redisFork(int type);
 2099 int hasActiveChildProcess();
 2100 void resetChildState();
 2101 int isMutuallyExclusiveChildType(int type);
 2102 
 2103 /* acl.c -- Authentication related prototypes. */
 2104 extern rax *Users;
 2105 extern user *DefaultUser;
 2106 void ACLInit(void);
 2107 /* Return values for ACLCheckAllPerm(). */
 2108 #define ACL_OK 0
 2109 #define ACL_DENIED_CMD 1
 2110 #define ACL_DENIED_KEY 2
 2111 #define ACL_DENIED_AUTH 3 /* Only used for ACL LOG entries. */
 2112 #define ACL_DENIED_CHANNEL 4 /* Only used for pub/sub commands */
 2113 int ACLCheckUserCredentials(robj *username, robj *password);
 2114 int ACLAuthenticateUser(client *c, robj *username, robj *password);
 2115 unsigned long ACLGetCommandID(const char *cmdname);
 2116 void ACLClearCommandID(void);
 2117 user *ACLGetUserByName(const char *name, size_t namelen);
 2118 int ACLCheckAllPerm(client *c, int *idxptr);
 2119 int ACLSetUser(user *u, const char *op, ssize_t oplen);
 2120 sds ACLDefaultUserFirstPassword(void);
 2121 uint64_t ACLGetCommandCategoryFlagByName(const char *name);
 2122 int ACLAppendUserForLoading(sds *argv, int argc, int *argc_err);
 2123 const char *ACLSetUserStringError(void);
 2124 int ACLLoadConfiguredUsers(void);
 2125 sds ACLDescribeUser(user *u);
 2126 void ACLLoadUsersAtStartup(void);
 2127 void addReplyCommandCategories(client *c, struct redisCommand *cmd);
 2128 user *ACLCreateUnlinkedUser();
 2129 void ACLFreeUserAndKillClients(user *u);
 2130 void addACLLogEntry(client *c, int reason, int keypos, sds username);
 2131 void ACLUpdateDefaultUserPassword(sds password);
 2132 
 2133 /* Sorted sets data type */
 2134 
 2135 /* Input flags. */
 2136 #define ZADD_IN_NONE 0
 2137 #define ZADD_IN_INCR (1<<0)    /* Increment the score instead of setting it. */
 2138 #define ZADD_IN_NX (1<<1)      /* Don't touch elements not already existing. */
 2139 #define ZADD_IN_XX (1<<2)      /* Only touch elements already existing. */
 2140 #define ZADD_IN_GT (1<<3)      /* Only update existing when new scores are higher. */
 2141 #define ZADD_IN_LT (1<<4)      /* Only update existing when new scores are lower. */
 2142 
 2143 /* Output flags. */
 2144 #define ZADD_OUT_NOP (1<<0)     /* Operation not performed because of conditionals.*/
 2145 #define ZADD_OUT_NAN (1<<1)     /* Only touch elements already existing. */
 2146 #define ZADD_OUT_ADDED (1<<2)   /* The element was new and was added. */
 2147 #define ZADD_OUT_UPDATED (1<<3) /* The element already existed, score updated. */
 2148 
 2149 /* Struct to hold an inclusive/exclusive range spec by score comparison. */
 2150 typedef struct {
 2151     double min, max;
 2152     int minex, maxex; /* are min or max exclusive? */
 2153 } zrangespec;
 2154 
 2155 /* Struct to hold an inclusive/exclusive range spec by lexicographic comparison. */
 2156 typedef struct {
 2157     sds min, max;     /* May be set to shared.(minstring|maxstring) */
 2158     int minex, maxex; /* are min or max exclusive? */
 2159 } zlexrangespec;
 2160 
 2161 zskiplist *zslCreate(void);
 2162 void zslFree(zskiplist *zsl);
 2163 zskiplistNode *zslInsert(zskiplist *zsl, double score, sds ele);
 2164 unsigned char *zzlInsert(unsigned char *zl, sds ele, double score);
 2165 int zslDelete(zskiplist *zsl, double score, sds ele, zskiplistNode **node);
 2166 zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range);
 2167 zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range);
 2168 double zzlGetScore(unsigned char *sptr);
 2169 void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
 2170 void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
 2171 unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec *range);
 2172 unsigned char *zzlLastInRange(unsigned char *zl, zrangespec *range);
 2173 unsigned long zsetLength(const robj *zobj);
 2174 void zsetConvert(robj *zobj, int encoding);
 2175 void zsetConvertToZiplistIfNeeded(robj *zobj, size_t maxelelen);
 2176 int zsetScore(robj *zobj, sds member, double *score);
 2177 unsigned long zslGetRank(zskiplist *zsl, double score, sds o);
 2178 int zsetAdd(robj *zobj, double score, sds ele, int in_flags, int *out_flags, double *newscore);
 2179 long zsetRank(robj *zobj, sds ele, int reverse);
 2180 int zsetDel(robj *zobj, sds ele);
 2181 robj *zsetDup(robj *o);
 2182 int zsetZiplistValidateIntegrity(unsigned char *zl, size_t size, int deep);
 2183 void genericZpopCommand(client *c, robj **keyv, int keyc, int where, int emitkey, robj *countarg);
 2184 sds ziplistGetObject(unsigned char *sptr);
 2185 int zslValueGteMin(double value, zrangespec *spec);
 2186 int zslValueLteMax(double value, zrangespec *spec);
 2187 void zslFreeLexRange(zlexrangespec *spec);
 2188 int zslParseLexRange(robj *min, robj *max, zlexrangespec *spec);
 2189 unsigned char *zzlFirstInLexRange(unsigned char *zl, zlexrangespec *range);
 2190 unsigned char *zzlLastInLexRange(unsigned char *zl, zlexrangespec *range);
 2191 zskiplistNode *zslFirstInLexRange(zskiplist *zsl, zlexrangespec *range);
 2192 zskiplistNode *zslLastInLexRange(zskiplist *zsl, zlexrangespec *range);
 2193 int zzlLexValueGteMin(unsigned char *p, zlexrangespec *spec);
 2194 int zzlLexValueLteMax(unsigned char *p, zlexrangespec *spec);
 2195 int zslLexValueGteMin(sds value, zlexrangespec *spec);
 2196 int zslLexValueLteMax(sds value, zlexrangespec *spec);
 2197 
 2198 /* Core functions */
 2199 int getMaxmemoryState(size_t *total, size_t *logical, size_t *tofree, float *level);
 2200 size_t freeMemoryGetNotCountedMemory();
 2201 int overMaxmemoryAfterAlloc(size_t moremem);
 2202 int processCommand(client *c);
 2203 int processPendingCommandsAndResetClient(client *c);
 2204 void setupSignalHandlers(void);
 2205 void removeSignalHandlers(void);
 2206 int createSocketAcceptHandler(socketFds *sfd, aeFileProc *accept_handler);
 2207 int changeListenPort(int port, socketFds *sfd, aeFileProc *accept_handler);
 2208 int changeBindAddr(sds *addrlist, int addrlist_len);
 2209 struct redisCommand *lookupCommand(sds name);
 2210 struct redisCommand *lookupCommandByCString(const char *s);
 2211 struct redisCommand *lookupCommandOrOriginal(sds name);
 2212 void call(client *c, int flags);
 2213 void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags);
 2214 void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target);
 2215 void redisOpArrayInit(redisOpArray *oa);
 2216 void redisOpArrayFree(redisOpArray *oa);
 2217 void forceCommandPropagation(client *c, int flags);
 2218 void preventCommandPropagation(client *c);
 2219 void preventCommandAOF(client *c);
 2220 void preventCommandReplication(client *c);
 2221 void slowlogPushCurrentCommand(client *c, struct redisCommand *cmd, ustime_t duration);
 2222 int prepareForShutdown(int flags);
 2223 #ifdef __GNUC__
 2224 void _serverLog(int level, const char *fmt, ...)
 2225     __attribute__((format(printf, 2, 3)));
 2226 #else
 2227 void _serverLog(int level, const char *fmt, ...);
 2228 #endif
 2229 void serverLogRaw(int level, const char *msg);
 2230 void serverLogFromHandler(int level, const char *msg);
 2231 void usage(void);
 2232 void updateDictResizePolicy(void);
 2233 int htNeedsResize(dict *dict);
 2234 void populateCommandTable(void);
 2235 void resetCommandTableStats(void);
 2236 void resetErrorTableStats(void);
 2237 void adjustOpenFilesLimit(void);
 2238 void incrementErrorCount(const char *fullerr, size_t namelen);
 2239 void closeListeningSockets(int unlink_unix_socket);
 2240 void updateCachedTime(int update_daylight_info);
 2241 void resetServerStats(void);
 2242 void activeDefragCycle(void);
 2243 unsigned int getLRUClock(void);
 2244 unsigned int LRU_CLOCK(void);
 2245 const char *evictPolicyToString(void);
 2246 struct redisMemOverhead *getMemoryOverheadData(void);
 2247 void freeMemoryOverheadData(struct redisMemOverhead *mh);
 2248 void checkChildrenDone(void);
 2249 int setOOMScoreAdj(int process_class);
 2250 void rejectCommandFormat(client *c, const char *fmt, ...);
 2251 void *activeDefragAlloc(void *ptr);
 2252 robj *activeDefragStringOb(robj* ob, long *defragged);
 2253 
 2254 #define RESTART_SERVER_NONE 0
 2255 #define RESTART_SERVER_GRACEFULLY (1<<0)     /* Do proper shutdown. */
 2256 #define RESTART_SERVER_CONFIG_REWRITE (1<<1) /* CONFIG REWRITE before restart.*/
 2257 int restartServer(int flags, mstime_t delay);
 2258 
 2259 /* Set data type */
 2260 robj *setTypeCreate(sds value);
 2261 int setTypeAdd(robj *subject, sds value);
 2262 int setTypeRemove(robj *subject, sds value);
 2263 int setTypeIsMember(robj *subject, sds value);
 2264 setTypeIterator *setTypeInitIterator(robj *subject);
 2265 void setTypeReleaseIterator(setTypeIterator *si);
 2266 int setTypeNext(setTypeIterator *si, sds *sdsele, int64_t *llele);
 2267 sds setTypeNextObject(setTypeIterator *si);
 2268 int setTypeRandomElement(robj *setobj, sds *sdsele, int64_t *llele);
 2269 unsigned long setTypeRandomElements(robj *set, unsigned long count, robj *aux_set);
 2270 unsigned long setTypeSize(const robj *subject);
 2271 void setTypeConvert(robj *subject, int enc);
 2272 robj *setTypeDup(robj *o);
 2273 
 2274 /* Hash data type */
 2275 #define HASH_SET_TAKE_FIELD (1<<0)
 2276 #define HASH_SET_TAKE_VALUE (1<<1)
 2277 #define HASH_SET_COPY 0
 2278 
 2279 void hashTypeConvert(robj *o, int enc);
 2280 void hashTypeTryConversion(robj *subject, robj **argv, int start, int end);
 2281 int hashTypeExists(robj *o, sds key);
 2282 int hashTypeDelete(robj *o, sds key);
 2283 unsigned long hashTypeLength(const robj *o);
 2284 hashTypeIterator *hashTypeInitIterator(robj *subject);
 2285 void hashTypeReleaseIterator(hashTypeIterator *hi);
 2286 int hashTypeNext(hashTypeIterator *hi);
 2287 void hashTypeCurrentFromZiplist(hashTypeIterator *hi, int what,
 2288                                 unsigned char **vstr,
 2289                                 unsigned int *vlen,
 2290                                 long long *vll);
 2291 sds hashTypeCurrentFromHashTable(hashTypeIterator *hi, int what);
 2292 void hashTypeCurrentObject(hashTypeIterator *hi, int what, unsigned char **vstr, unsigned int *vlen, long long *vll);
 2293 sds hashTypeCurrentObjectNewSds(hashTypeIterator *hi, int what);
 2294 robj *hashTypeLookupWriteOrCreate(client *c, robj *key);
 2295 robj *hashTypeGetValueObject(robj *o, sds field);
 2296 int hashTypeSet(robj *o, sds field, sds value, int flags);
 2297 robj *hashTypeDup(robj *o);
 2298 int hashZiplistValidateIntegrity(unsigned char *zl, size_t size, int deep);
 2299 
 2300 /* Pub / Sub */
 2301 int pubsubUnsubscribeAllChannels(client *c, int notify);
 2302 int pubsubUnsubscribeAllPatterns(client *c, int notify);
 2303 int pubsubPublishMessage(robj *channel, robj *message);
 2304 void addReplyPubsubMessage(client *c, robj *channel, robj *msg);
 2305 
 2306 /* Keyspace events notification */
 2307 void notifyKeyspaceEvent(int type, char *event, robj *key, int dbid);
 2308 int keyspaceEventsStringToFlags(char *classes);
 2309 sds keyspaceEventsFlagsToString(int flags);
 2310 
 2311 /* Configuration */
 2312 void loadServerConfig(char *filename, char config_from_stdin, char *options);
 2313 void appendServerSaveParams(time_t seconds, int changes);
 2314 void resetServerSaveParams(void);
 2315 struct rewriteConfigState; /* Forward declaration to export API. */
 2316 void rewriteConfigRewriteLine(struct rewriteConfigState *state, const char *option, sds line, int force);
 2317 void rewriteConfigMarkAsProcessed(struct rewriteConfigState *state, const char *option);
 2318 int rewriteConfig(char *path, int force_all);
 2319 void initConfigValues();
 2320 
 2321 /* db.c -- Keyspace access API */
 2322 int removeExpire(redisDb *db, robj *key);
 2323 void propagateExpire(redisDb *db, robj *key, int lazy);
 2324 int keyIsExpired(redisDb *db, robj *key);
 2325 int expireIfNeeded(redisDb *db, robj *key);
 2326 long long getExpire(redisDb *db, robj *key);
 2327 void setExpire(client *c, redisDb *db, robj *key, long long when);
 2328 int checkAlreadyExpired(long long when);
 2329 robj *lookupKey(redisDb *db, robj *key, int flags);
 2330 robj *lookupKeyRead(redisDb *db, robj *key);
 2331 robj *lookupKeyWrite(redisDb *db, robj *key);
 2332 robj *lookupKeyReadOrReply(client *c, robj *key, robj *reply);
 2333 robj *lookupKeyWriteOrReply(client *c, robj *key, robj *reply);
 2334 robj *lookupKeyReadWithFlags(redisDb *db, robj *key, int flags);
 2335 robj *lookupKeyWriteWithFlags(redisDb *db, robj *key, int flags);
 2336 robj *objectCommandLookup(client *c, robj *key);
 2337 robj *objectCommandLookupOrReply(client *c, robj *key, robj *reply);
 2338 int objectSetLRUOrLFU(robj *val, long long lfu_freq, long long lru_idle,
 2339                        long long lru_clock, int lru_multiplier);
 2340 #define LOOKUP_NONE 0
 2341 #define LOOKUP_NOTOUCH (1<<0)
 2342 #define LOOKUP_NONOTIFY (1<<1)
 2343 void dbAdd(redisDb *db, robj *key, robj *val);
 2344 int dbAddRDBLoad(redisDb *db, sds key, robj *val);
 2345 void dbOverwrite(redisDb *db, robj *key, robj *val);
 2346 void genericSetKey(client *c, redisDb *db, robj *key, robj *val, int keepttl, int signal);
 2347 void setKey(client *c, redisDb *db, robj *key, robj *val);
 2348 robj *dbRandomKey(redisDb *db);
 2349 int dbSyncDelete(redisDb *db, robj *key);
 2350 int dbDelete(redisDb *db, robj *key);
 2351 robj *dbUnshareStringValue(redisDb *db, robj *key, robj *o);
 2352 
 2353 #define EMPTYDB_NO_FLAGS 0      /* No flags. */
 2354 #define EMPTYDB_ASYNC (1<<0)    /* Reclaim memory in another thread. */
 2355 long long emptyDb(int dbnum, int flags, void(callback)(void*));
 2356 long long emptyDbStructure(redisDb *dbarray, int dbnum, int async, void(callback)(void*));
 2357 void flushAllDataAndResetRDB(int flags);
 2358 long long dbTotalServerKeyCount();
 2359 dbBackup *backupDb(void);
 2360 void restoreDbBackup(dbBackup *buckup);
 2361 void discardDbBackup(dbBackup *buckup, int flags, void(callback)(void*));
 2362 
 2363 
 2364 int selectDb(client *c, int id);
 2365 void signalModifiedKey(client *c, redisDb *db, robj *key);
 2366 void signalFlushedDb(int dbid, int async);
 2367 unsigned int getKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count);
 2368 unsigned int countKeysInSlot(unsigned int hashslot);
 2369 unsigned int delKeysInSlot(unsigned int hashslot);
 2370 int verifyClusterConfigWithData(void);
 2371 void scanGenericCommand(client *c, robj *o, unsigned long cursor);
 2372 int parseScanCursorOrReply(client *c, robj *o, unsigned long *cursor);
 2373 void slotToKeyAdd(sds key);
 2374 void slotToKeyDel(sds key);
 2375 int dbAsyncDelete(redisDb *db, robj *key);
 2376 void emptyDbAsync(redisDb *db);
 2377 void slotToKeyFlush(int async);
 2378 size_t lazyfreeGetPendingObjectsCount(void);
 2379 size_t lazyfreeGetFreedObjectsCount(void);
 2380 void freeObjAsync(robj *key, robj *obj);
 2381 void freeSlotsToKeysMapAsync(rax *rt);
 2382 void freeSlotsToKeysMap(rax *rt, int async);
 2383 
 2384 
 2385 /* API to get key arguments from commands */
 2386 int *getKeysPrepareResult(getKeysResult *result, int numkeys);
 2387 int getKeysFromCommand(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 2388 void getKeysFreeResult(getKeysResult *result);
 2389 int zunionInterDiffGetKeys(struct redisCommand *cmd,robj **argv, int argc, getKeysResult *result);
 2390 int zunionInterDiffStoreGetKeys(struct redisCommand *cmd,robj **argv, int argc, getKeysResult *result);
 2391 int evalGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 2392 int sortGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 2393 int migrateGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 2394 int georadiusGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 2395 int xreadGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 2396 int memoryGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 2397 int lcsGetKeys(struct redisCommand *cmd, robj **argv, int argc, getKeysResult *result);
 2398 
 2399 /* Cluster */
 2400 void clusterInit(void);
 2401 unsigned short crc16(const char *buf, int len);
 2402 unsigned int keyHashSlot(char *key, int keylen);
 2403 void clusterCron(void);
 2404 void clusterPropagatePublish(robj *channel, robj *message);
 2405 void migrateCloseTimedoutSockets(void);
 2406 void clusterBeforeSleep(void);
 2407 int clusterSendModuleMessageToTarget(const char *target, uint64_t module_id, uint8_t type, unsigned char *payload, uint32_t len);
 2408 
 2409 /* Sentinel */
 2410 void initSentinelConfig(void);
 2411 void initSentinel(void);
 2412 void sentinelTimer(void);
 2413 const char *sentinelHandleConfiguration(char **argv, int argc);
 2414 void queueSentinelConfig(sds *argv, int argc, int linenum, sds line);
 2415 void loadSentinelConfigFromQueue(void);
 2416 void sentinelIsRunning(void);
 2417 void sentinelCheckConfigFile(void);
 2418 
 2419 /* redis-check-rdb & aof */
 2420 int redis_check_rdb(char *rdbfilename, FILE *fp);
 2421 int redis_check_rdb_main(int argc, char **argv, FILE *fp);
 2422 int redis_check_aof_main(int argc, char **argv);
 2423 
 2424 /* Scripting */
 2425 void scriptingInit(int setup);
 2426 int ldbRemoveChild(pid_t pid);
 2427 void ldbKillForkedSessions(void);
 2428 int ldbPendingChildren(void);
 2429 sds luaCreateFunction(client *c, lua_State *lua, robj *body);
 2430 void freeLuaScriptsAsync(dict *lua_scripts);
 2431 
 2432 /* Blocked clients */
 2433 void processUnblockedClients(void);
 2434 void blockClient(client *c, int btype);
 2435 void unblockClient(client *c);
 2436 void queueClientForReprocessing(client *c);
 2437 void replyToBlockedClientTimedOut(client *c);
 2438 int getTimeoutFromObjectOrReply(client *c, robj *object, mstime_t *timeout, int unit);
 2439 void disconnectAllBlockedClients(void);
 2440 void handleClientsBlockedOnKeys(void);
 2441 void signalKeyAsReady(redisDb *db, robj *key, int type);
 2442 void blockForKeys(client *c, int btype, robj **keys, int numkeys, mstime_t timeout, robj *target, struct listPos *listpos, streamID *ids);
 2443 void updateStatsOnUnblock(client *c, long blocked_us, long reply_us);
 2444 
 2445 /* timeout.c -- Blocked clients timeout and connections timeout. */
 2446 void addClientToTimeoutTable(client *c);
 2447 void removeClientFromTimeoutTable(client *c);
 2448 void handleBlockedClientsTimeout(void);
 2449 int clientsCronHandleTimeout(client *c, mstime_t now_ms);
 2450 
 2451 /* expire.c -- Handling of expired keys */
 2452 void activeExpireCycle(int type);
 2453 void expireSlaveKeys(void);
 2454 void rememberSlaveKeyWithExpire(redisDb *db, robj *key);
 2455 void flushSlaveKeysWithExpireList(void);
 2456 size_t getSlaveKeyWithExpireCount(void);
 2457 
 2458 /* evict.c -- maxmemory handling and LRU eviction. */
 2459 void evictionPoolAlloc(void);
 2460 #define LFU_INIT_VAL 5
 2461 unsigned long LFUGetTimeInMinutes(void);
 2462 uint8_t LFULogIncr(uint8_t value);
 2463 unsigned long LFUDecrAndReturn(robj *o);
 2464 #define EVICT_OK 0
 2465 #define EVICT_RUNNING 1
 2466 #define EVICT_FAIL 2
 2467 int performEvictions(void);
 2468 
 2469 
 2470 /* Keys hashing / comparison functions for dict.c hash tables. */
 2471 uint64_t dictSdsHash(const void *key);
 2472 int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2);
 2473 void dictSdsDestructor(void *privdata, void *val);
 2474 
 2475 /* Git SHA1 */
 2476 char *redisGitSHA1(void);
 2477 char *redisGitDirty(void);
 2478 uint64_t redisBuildId(void);
 2479 char *redisBuildIdString(void);
 2480 
 2481 /* Commands prototypes */
 2482 void authCommand(client *c);
 2483 void pingCommand(client *c);
 2484 void echoCommand(client *c);
 2485 void commandCommand(client *c);
 2486 void setCommand(client *c);
 2487 void setnxCommand(client *c);
 2488 void setexCommand(client *c);
 2489 void psetexCommand(client *c);
 2490 void getCommand(client *c);
 2491 void getexCommand(client *c);
 2492 void getdelCommand(client *c);
 2493 void delCommand(client *c);
 2494 void unlinkCommand(client *c);
 2495 void existsCommand(client *c);
 2496 void setbitCommand(client *c);
 2497 void getbitCommand(client *c);
 2498 void bitfieldCommand(client *c);
 2499 void bitfieldroCommand(client *c);
 2500 void setrangeCommand(client *c);
 2501 void getrangeCommand(client *c);
 2502 void incrCommand(client *c);
 2503 void decrCommand(client *c);
 2504 void incrbyCommand(client *c);
 2505 void decrbyCommand(client *c);
 2506 void incrbyfloatCommand(client *c);
 2507 void selectCommand(client *c);
 2508 void swapdbCommand(client *c);
 2509 void randomkeyCommand(client *c);
 2510 void keysCommand(client *c);
 2511 void scanCommand(client *c);
 2512 void dbsizeCommand(client *c);
 2513 void lastsaveCommand(client *c);
 2514 void saveCommand(client *c);
 2515 void bgsaveCommand(client *c);
 2516 void bgrewriteaofCommand(client *c);
 2517 void shutdownCommand(client *c);
 2518 void moveCommand(client *c);
 2519 void copyCommand(client *c);
 2520 void renameCommand(client *c);
 2521 void renamenxCommand(client *c);
 2522 void lpushCommand(client *c);
 2523 void rpushCommand(client *c);
 2524 void lpushxCommand(client *c);
 2525 void rpushxCommand(client *c);
 2526 void linsertCommand(client *c);
 2527 void lpopCommand(client *c);
 2528 void rpopCommand(client *c);
 2529 void llenCommand(client *c);
 2530 void lindexCommand(client *c);
 2531 void lrangeCommand(client *c);
 2532 void ltrimCommand(client *c);
 2533 void typeCommand(client *c);
 2534 void lsetCommand(client *c);
 2535 void saddCommand(client *c);
 2536 void sremCommand(client *c);
 2537 void smoveCommand(client *c);
 2538 void sismemberCommand(client *c);
 2539 void smismemberCommand(client *c);
 2540 void scardCommand(client *c);
 2541 void spopCommand(client *c);
 2542 void srandmemberCommand(client *c);
 2543 void sinterCommand(client *c);
 2544 void sinterstoreCommand(client *c);
 2545 void sunionCommand(client *c);
 2546 void sunionstoreCommand(client *c);
 2547 void sdiffCommand(client *c);
 2548 void sdiffstoreCommand(client *c);
 2549 void sscanCommand(client *c);
 2550 void syncCommand(client *c);
 2551 void flushdbCommand(client *c);
 2552 void flushallCommand(client *c);
 2553 void sortCommand(client *c);
 2554 void lremCommand(client *c);
 2555 void lposCommand(client *c);
 2556 void rpoplpushCommand(client *c);
 2557 void lmoveCommand(client *c);
 2558 void infoCommand(client *c);
 2559 void mgetCommand(client *c);
 2560 void monitorCommand(client *c);
 2561 void expireCommand(client *c);
 2562 void expireatCommand(client *c);
 2563 void pexpireCommand(client *c);
 2564 void pexpireatCommand(client *c);
 2565 void getsetCommand(client *c);
 2566 void ttlCommand(client *c);
 2567 void touchCommand(client *c);
 2568 void pttlCommand(client *c);
 2569 void persistCommand(client *c);
 2570 void replicaofCommand(client *c);
 2571 void roleCommand(client *c);
 2572 void debugCommand(client *c);
 2573 void msetCommand(client *c);
 2574 void msetnxCommand(client *c);
 2575 void zaddCommand(client *c);
 2576 void zincrbyCommand(client *c);
 2577 void zrangeCommand(client *c);
 2578 void zrangebyscoreCommand(client *c);
 2579 void zrevrangebyscoreCommand(client *c);
 2580 void zrangebylexCommand(client *c);
 2581 void zrevrangebylexCommand(client *c);
 2582 void zcountCommand(client *c);
 2583 void zlexcountCommand(client *c);
 2584 void zrevrangeCommand(client *c);
 2585 void zcardCommand(client *c);
 2586 void zremCommand(client *c);
 2587 void zscoreCommand(client *c);
 2588 void zmscoreCommand(client *c);
 2589 void zremrangebyscoreCommand(client *c);
 2590 void zremrangebylexCommand(client *c);
 2591 void zpopminCommand(client *c);
 2592 void zpopmaxCommand(client *c);
 2593 void bzpopminCommand(client *c);
 2594 void bzpopmaxCommand(client *c);
 2595 void zrandmemberCommand(client *c);
 2596 void multiCommand(client *c);
 2597 void execCommand(client *c);
 2598 void discardCommand(client *c);
 2599 void blpopCommand(client *c);
 2600 void brpopCommand(client *c);
 2601 void brpoplpushCommand(client *c);
 2602 void blmoveCommand(client *c);
 2603 void appendCommand(client *c);
 2604 void strlenCommand(client *c);
 2605 void zrankCommand(client *c);
 2606 void zrevrankCommand(client *c);
 2607 void hsetCommand(client *c);
 2608 void hsetnxCommand(client *c);
 2609 void hgetCommand(client *c);
 2610 void hmsetCommand(client *c);
 2611 void hmgetCommand(client *c);
 2612 void hdelCommand(client *c);
 2613 void hlenCommand(client *c);
 2614 void hstrlenCommand(client *c);
 2615 void zremrangebyrankCommand(client *c);
 2616 void zunionstoreCommand(client *c);
 2617 void zinterstoreCommand(client *c);
 2618 void zdiffstoreCommand(client *c);
 2619 void zunionCommand(client *c);
 2620 void zinterCommand(client *c);
 2621 void zrangestoreCommand(client *c);
 2622 void zdiffCommand(client *c);
 2623 void zscanCommand(client *c);
 2624 void hkeysCommand(client *c);
 2625 void hvalsCommand(client *c);
 2626 void hgetallCommand(client *c);
 2627 void hexistsCommand(client *c);
 2628 void hscanCommand(client *c);
 2629 void hrandfieldCommand(client *c);
 2630 void configCommand(client *c);
 2631 void hincrbyCommand(client *c);
 2632 void hincrbyfloatCommand(client *c);
 2633 void subscribeCommand(client *c);
 2634 void unsubscribeCommand(client *c);
 2635 void psubscribeCommand(client *c);
 2636 void punsubscribeCommand(client *c);
 2637 void publishCommand(client *c);
 2638 void pubsubCommand(client *c);
 2639 void watchCommand(client *c);
 2640 void unwatchCommand(client *c);
 2641 void clusterCommand(client *c);
 2642 void restoreCommand(client *c);
 2643 void migrateCommand(client *c);
 2644 void askingCommand(client *c);
 2645 void readonlyCommand(client *c);
 2646 void readwriteCommand(client *c);
 2647 void dumpCommand(client *c);
 2648 void objectCommand(client *c);
 2649 void memoryCommand(client *c);
 2650 void clientCommand(client *c);
 2651 void helloCommand(client *c);
 2652 void evalCommand(client *c);
 2653 void evalShaCommand(client *c);
 2654 void scriptCommand(client *c);
 2655 void timeCommand(client *c);
 2656 void bitopCommand(client *c);
 2657 void bitcountCommand(client *c);
 2658 void bitposCommand(client *c);
 2659 void replconfCommand(client *c);
 2660 void waitCommand(client *c);
 2661 void geoencodeCommand(client *c);
 2662 void geodecodeCommand(client *c);
 2663 void georadiusbymemberCommand(client *c);
 2664 void georadiusbymemberroCommand(client *c);
 2665 void georadiusCommand(client *c);
 2666 void georadiusroCommand(client *c);
 2667 void geoaddCommand(client *c);
 2668 void geohashCommand(client *c);
 2669 void geoposCommand(client *c);
 2670 void geodistCommand(client *c);
 2671 void geosearchCommand(client *c);
 2672 void geosearchstoreCommand(client *c);
 2673 void pfselftestCommand(client *c);
 2674 void pfaddCommand(client *c);
 2675 void pfcountCommand(client *c);
 2676 void pfmergeCommand(client *c);
 2677 void pfdebugCommand(client *c);
 2678 void latencyCommand(client *c);
 2679 void moduleCommand(client *c);
 2680 void securityWarningCommand(client *c);
 2681 void xaddCommand(client *c);
 2682 void xrangeCommand(client *c);
 2683 void xrevrangeCommand(client *c);
 2684 void xlenCommand(client *c);
 2685 void xreadCommand(client *c);
 2686 void xgroupCommand(client *c);
 2687 void xsetidCommand(client *c);
 2688 void xackCommand(client *c);
 2689 void xpendingCommand(client *c);
 2690 void xclaimCommand(client *c);
 2691 void xautoclaimCommand(client *c);
 2692 void xinfoCommand(client *c);
 2693 void xdelCommand(client *c);
 2694 void xtrimCommand(client *c);
 2695 void lolwutCommand(client *c);
 2696 void aclCommand(client *c);
 2697 void stralgoCommand(client *c);
 2698 void resetCommand(client *c);
 2699 void failoverCommand(client *c);
 2700 
 2701 #if defined(__GNUC__)
 2702 void *calloc(size_t count, size_t size) __attribute__ ((deprecated));
 2703 void free(void *ptr) __attribute__ ((deprecated));
 2704 void *malloc(size_t size) __attribute__ ((deprecated));
 2705 void *realloc(void *ptr, size_t size) __attribute__ ((deprecated));
 2706 #endif
 2707 
 2708 /* Debugging stuff */
 2709 void _serverAssertWithInfo(const client *c, const robj *o, const char *estr, const char *file, int line);
 2710 void _serverAssert(const char *estr, const char *file, int line);
 2711 #ifdef __GNUC__
 2712 void _serverPanic(const char *file, int line, const char *msg, ...)
 2713     __attribute__ ((format (printf, 3, 4)));
 2714 #else
 2715 void _serverPanic(const char *file, int line, const char *msg, ...);
 2716 #endif
 2717 void serverLogObjectDebugInfo(const robj *o);
 2718 void sigsegvHandler(int sig, siginfo_t *info, void *secret);
 2719 const char *getSafeInfoString(const char *s, size_t len, char **tmp);
 2720 sds genRedisInfoString(const char *section);
 2721 sds genModulesInfoString(sds info);
 2722 void enableWatchdog(int period);
 2723 void disableWatchdog(void);
 2724 void watchdogScheduleSignal(int period);
 2725 void serverLogHexDump(int level, char *descr, void *value, size_t len);
 2726 int memtest_preserving_test(unsigned long *m, size_t bytes, int passes);
 2727 void mixDigest(unsigned char *digest, void *ptr, size_t len);
 2728 void xorDigest(unsigned char *digest, void *ptr, size_t len);
 2729 int populateCommandTableParseFlags(struct redisCommand *c, char *strflags);
 2730 void debugDelay(int usec);
 2731 void killIOThreads(void);
 2732 void killThreads(void);
 2733 void makeThreadKillable(void);
 2734 
 2735 /* Use macro for checking log level to avoid evaluating arguments in cases log
 2736  * should be ignored due to low level. */
 2737 #define serverLog(level, ...) do {\
 2738         if (((level)&0xff) < server.verbosity) break;\
 2739         _serverLog(level, __VA_ARGS__);\
 2740     } while(0)
 2741 
 2742 /* TLS stuff */
 2743 void tlsInit(void);
 2744 void tlsCleanup(void);
 2745 int tlsConfigure(redisTLSContextConfig *ctx_config);
 2746 
 2747 #define redisDebug(fmt, ...) \
 2748     printf("DEBUG %s:%d > " fmt "\n", __FILE__, __LINE__, __VA_ARGS__)
 2749 #define redisDebugMark() \
 2750     printf("-- MARK %s:%d --\n", __FILE__, __LINE__)
 2751 
 2752 int iAmMaster(void);
 2753 
 2754 #endif