"Fossies" - the Fresh Open Source Software Archive

Member "redis-6.0.8/src/server.h" (10 Sep 2020, 115286 Bytes) of package /linux/misc/redis-6.0.8.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.0.7_vs_6.0.8.

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