├── redis ├── CMakeLists.txt ├── modules │ ├── .gitignore │ ├── gendoc.rb │ ├── Makefile │ ├── hellotimer.c │ ├── hellohook.c │ ├── hellocluster.c │ └── hellodict.c ├── version.h ├── .gitignore ├── redis-cli ├── redis-sentinel ├── redis-server ├── redis-benchmark ├── redis-check-aof ├── redis-check-rdb ├── release.h ├── test.c ├── crc64.h ├── valgrind.sup ├── geo.h ├── sha1.h ├── mkreleasehdr.sh ├── sha256.h ├── rand.h ├── pqsort.h ├── rax_malloc.h ├── listpack_malloc.h ├── sdsalloc.h ├── bio.h ├── fmacros.h ├── solarisfixes.h ├── debugmacro.h ├── intset.h ├── sparkline.h ├── slowlog.h ├── redisassert.h ├── testhelp.h ├── lolwut.h ├── zipmap.h ├── release.c ├── asciilogo.h ├── listpack.h ├── crcspeed.h ├── ziplist.h ├── endianconv.h ├── util.h ├── geohash_helper.h ├── connhelpers.h ├── adlist.h ├── anet.h ├── rand.c ├── redis-trib.rb ├── latency.h ├── ae_select.c ├── endianconv.c ├── childinfo.c ├── zmalloc.h ├── setcpuaffinity.c ├── geohash.h ├── crc16.c ├── lzf.h ├── gopher.c ├── ae_kqueue.c ├── ae_epoll.c ├── atomicvar.h ├── sha256.c ├── localtime.c ├── syncio.c ├── ae.h ├── pqsort.c ├── notify.c ├── stream.h └── lzfP.h └── README.md /redis/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /redis/modules/.gitignore: -------------------------------------------------------------------------------- 1 | *.so 2 | *.xo 3 | -------------------------------------------------------------------------------- /redis/version.h: -------------------------------------------------------------------------------- 1 | #define REDIS_VERSION "6.0.7" 2 | -------------------------------------------------------------------------------- /redis/.gitignore: -------------------------------------------------------------------------------- 1 | *.gcda 2 | *.gcno 3 | *.gcov 4 | redis.info 5 | lcov-html 6 | -------------------------------------------------------------------------------- /redis/redis-cli: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pengyujia1234/redis-explain/HEAD/redis/redis-cli -------------------------------------------------------------------------------- /redis/redis-sentinel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pengyujia1234/redis-explain/HEAD/redis/redis-sentinel -------------------------------------------------------------------------------- /redis/redis-server: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pengyujia1234/redis-explain/HEAD/redis/redis-server -------------------------------------------------------------------------------- /redis/redis-benchmark: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pengyujia1234/redis-explain/HEAD/redis/redis-benchmark -------------------------------------------------------------------------------- /redis/redis-check-aof: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pengyujia1234/redis-explain/HEAD/redis/redis-check-aof -------------------------------------------------------------------------------- /redis/redis-check-rdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pengyujia1234/redis-explain/HEAD/redis/redis-check-rdb -------------------------------------------------------------------------------- /redis/release.h: -------------------------------------------------------------------------------- 1 | #define REDIS_GIT_SHA1 "00000000" 2 | #define REDIS_GIT_DIRTY " 0" 3 | #define REDIS_BUILD_ID "CN0014006322M.local-1599621792" 4 | -------------------------------------------------------------------------------- /redis/test.c: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Peng Yujia on 9/23/20. 3 | // 4 | int main(void) { 5 | printf("e9c6d914c4b8d9ca == %016llx\n"); 6 | return 0; 7 | } 8 | -------------------------------------------------------------------------------- /redis/crc64.h: -------------------------------------------------------------------------------- 1 | #ifndef CRC64_H 2 | #define CRC64_H 3 | 4 | #include 5 | 6 | void crc64_init(void); 7 | uint64_t crc64(uint64_t crc, const unsigned char *s, uint64_t l); 8 | 9 | #ifdef REDIS_TEST 10 | int crc64Test(int argc, char *argv[]); 11 | #endif 12 | 13 | #endif 14 | -------------------------------------------------------------------------------- /redis/valgrind.sup: -------------------------------------------------------------------------------- 1 | { 2 | 3 | Memcheck:Cond 4 | fun:lzf_compress 5 | } 6 | 7 | { 8 | 9 | Memcheck:Value4 10 | fun:lzf_compress 11 | } 12 | 13 | { 14 | 15 | Memcheck:Value8 16 | fun:lzf_compress 17 | } 18 | -------------------------------------------------------------------------------- /redis/geo.h: -------------------------------------------------------------------------------- 1 | #ifndef __GEO_H__ 2 | #define __GEO_H__ 3 | 4 | #include "server.h" 5 | 6 | /* Structures used inside geo.c in order to represent points and array of 7 | * points on the earth. */ 8 | typedef struct geoPoint { 9 | double longitude; 10 | double latitude; 11 | double dist; 12 | double score; 13 | char *member; 14 | } geoPoint; 15 | 16 | typedef struct geoArray { 17 | struct geoPoint *array; 18 | size_t buckets; 19 | size_t used; 20 | } geoArray; 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /redis/sha1.h: -------------------------------------------------------------------------------- 1 | #ifndef SHA1_H 2 | #define SHA1_H 3 | /* ================ sha1.h ================ */ 4 | /* 5 | SHA-1 in C 6 | By Steve Reid 7 | 100% Public Domain 8 | */ 9 | 10 | typedef struct { 11 | uint32_t state[5]; 12 | uint32_t count[2]; 13 | unsigned char buffer[64]; 14 | } SHA1_CTX; 15 | 16 | void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]); 17 | void SHA1Init(SHA1_CTX* context); 18 | void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len); 19 | void SHA1Final(unsigned char digest[20], SHA1_CTX* context); 20 | 21 | #ifdef REDIS_TEST 22 | int sha1Test(int argc, char **argv); 23 | #endif 24 | #endif 25 | -------------------------------------------------------------------------------- /redis/mkreleasehdr.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | GIT_SHA1=`(git show-ref --head --hash=8 2> /dev/null || echo 00000000) | head -n1` 3 | GIT_DIRTY=`git diff --no-ext-diff 2> /dev/null | wc -l` 4 | BUILD_ID=`uname -n`"-"`date +%s` 5 | if [ -n "$SOURCE_DATE_EPOCH" ]; then 6 | BUILD_ID=$(date -u -d "@$SOURCE_DATE_EPOCH" +%s 2>/dev/null || date -u -r "$SOURCE_DATE_EPOCH" +%s 2>/dev/null || date -u +%s) 7 | fi 8 | test -f release.h || touch release.h 9 | (cat release.h | grep SHA1 | grep $GIT_SHA1) && \ 10 | (cat release.h | grep DIRTY | grep $GIT_DIRTY) && exit 0 # Already up-to-date 11 | echo "#define REDIS_GIT_SHA1 \"$GIT_SHA1\"" > release.h 12 | echo "#define REDIS_GIT_DIRTY \"$GIT_DIRTY\"" >> release.h 13 | echo "#define REDIS_BUILD_ID \"$BUILD_ID\"" >> release.h 14 | touch release.c # Force recompile of release.c 15 | -------------------------------------------------------------------------------- /redis/sha256.h: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * Filename: sha256.h 3 | * Author: Brad Conte (brad AT bradconte.com) 4 | * Copyright: 5 | * Disclaimer: This code is presented "as is" without any guarantees. 6 | * Details: Defines the API for the corresponding SHA1 implementation. 7 | *********************************************************************/ 8 | 9 | #ifndef SHA256_H 10 | #define SHA256_H 11 | 12 | /*************************** HEADER FILES ***************************/ 13 | #include 14 | #include 15 | 16 | /****************************** MACROS ******************************/ 17 | #define SHA256_BLOCK_SIZE 32 // SHA256 outputs a 32 byte digest 18 | 19 | /**************************** DATA TYPES ****************************/ 20 | typedef uint8_t BYTE; // 8-bit byte 21 | typedef uint32_t WORD; // 32-bit word 22 | 23 | typedef struct { 24 | BYTE data[64]; 25 | WORD datalen; 26 | unsigned long long bitlen; 27 | WORD state[8]; 28 | } SHA256_CTX; 29 | 30 | /*********************** FUNCTION DECLARATIONS **********************/ 31 | void sha256_init(SHA256_CTX *ctx); 32 | void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len); 33 | void sha256_final(SHA256_CTX *ctx, BYTE hash[]); 34 | 35 | #endif // SHA256_H 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # redis-explain 2 | redis 相关博文和带有注释的代码,本文是以redis-6.0.7为蓝本,只做学习来用 3 | 4 | # 关于这个代码仓库 5 | 目前暂时用于redis代码的学习,后面可能会放入其它源码讲解。 6 | 如果觉得作者博文写得很好,请给本仓库一个小星星 7 | 代码注释也会持续更新 8 | # 关于如何阅读源码 9 | 推荐使用vscode 直接导入本工程即可。 10 | 11 | # redis 博文系列 12 | 1. [ziplist vs 普通数组,以及redis hash 在ziplist的实现](https://blog.csdn.net/qq_33361976/article/details/108432016) 13 | 14 | 2. [redis系列,键过期的知识你要知道的全在这里(一)](https://blog.csdn.net/qq_33361976/article/details/108529264) 15 | 16 | 3. [redis系列,键过期的知识你要知道的全在这里完结篇(二)](https://blog.csdn.net/qq_33361976/article/details/108685615) 17 | 18 | 4. [redis系列,redis的异步删除我该怎么用?](https://blog.csdn.net/qq_33361976/article/details/108714766) 19 | 20 | 5. [redis系列,redis6.0多线程解密!](https://blog.csdn.net/qq_33361976/article/details/108815683) 21 | 22 | 6. [redis系列,redis网络,你得知道的一些事](https://blog.csdn.net/qq_33361976/article/details/108911499) 23 | 24 | 7. [redis 系列,要懂redis,首先得看懂sds(全网最细节的sds讲解)](https://blog.csdn.net/qq_33361976/article/details/109014012) 25 | 26 | 8. [redis系列,redis是如何执行命令(一)](https://blog.csdn.net/qq_33361976/article/details/109014012) 27 | 28 | 9. [redis系列,给你看最完整的字典讲解](https://blog.csdn.net/qq_33361976/article/details/109265009) 29 | 30 | 10. [redis系列,你真的了解scan命令吗](https://blog.csdn.net/qq_33361976/article/details/109285073) 31 | 32 | 11. [redis系列,bitmap 命令全解析以及源码赏析](https://blog.csdn.net/qq_33361976/article/details/109546651) 33 | 34 | 12. [redis系列,zset到底是个什么鬼(一)!深度源码剖析](https://blog.csdn.net/qq_33361976/article/details/109711907) 35 | 36 | 13. [redis系列,rdb为什么要这么做?深度剖析](https://blog.csdn.net/qq_33361976/article/details/110230296) 37 | 38 | ## 后续文章持续更新中 39 | -------------------------------------------------------------------------------- /redis/modules/gendoc.rb: -------------------------------------------------------------------------------- 1 | # gendoc.rb -- Converts the top-comments inside module.c to modules API 2 | # reference documentation in markdown format. 3 | 4 | # Convert the C comment to markdown 5 | def markdown(s) 6 | s = s.gsub(/\*\/$/,"") 7 | s = s.gsub(/^ \* {0,1}/,"") 8 | s = s.gsub(/^\/\* /,"") 9 | s.chop! while s[-1] == "\n" || s[-1] == " " 10 | lines = s.split("\n") 11 | newlines = [] 12 | lines.each{|l| 13 | if l[0] != ' ' 14 | l = l.gsub(/RM_[A-z()]+/){|x| "`#{x}`"} 15 | l = l.gsub(/RedisModule_[A-z()]+/){|x| "`#{x}`"} 16 | l = l.gsub(/REDISMODULE_[A-z]+/){|x| "`#{x}`"} 17 | end 18 | newlines << l 19 | } 20 | return newlines.join("\n") 21 | end 22 | 23 | # Given the source code array and the index at which an exported symbol was 24 | # detected, extracts and outputs the documentation. 25 | def docufy(src,i) 26 | m = /RM_[A-z0-9]+/.match(src[i]) 27 | name = m[0] 28 | name = name.sub("RM_","RedisModule_") 29 | proto = src[i].sub("{","").strip+";\n" 30 | proto = proto.sub("RM_","RedisModule_") 31 | puts "## `#{name}`\n\n" 32 | puts " #{proto}\n" 33 | comment = "" 34 | while true 35 | i = i-1 36 | comment = src[i]+comment 37 | break if src[i] =~ /\/\*/ 38 | end 39 | comment = markdown(comment) 40 | puts comment+"\n\n" 41 | end 42 | 43 | puts "# Modules API reference\n\n" 44 | src = File.open("../module.c").to_a 45 | src.each_with_index{|line,i| 46 | if line =~ /RM_/ && line[0] != ' ' && line[0] != '#' && line[0] != '/' 47 | if src[i-1] =~ /\*\// 48 | docufy(src,i) 49 | end 50 | end 51 | } 52 | -------------------------------------------------------------------------------- /redis/modules/Makefile: -------------------------------------------------------------------------------- 1 | 2 | # find the OS 3 | uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') 4 | 5 | # Compile flags for linux / osx 6 | ifeq ($(uname_S),Linux) 7 | SHOBJ_CFLAGS ?= -W -Wall -fno-common -g -ggdb -std=c99 -O2 8 | SHOBJ_LDFLAGS ?= -shared 9 | else 10 | SHOBJ_CFLAGS ?= -W -Wall -dynamic -fno-common -g -ggdb -std=c99 -O2 11 | SHOBJ_LDFLAGS ?= -bundle -undefined dynamic_lookup 12 | endif 13 | 14 | .SUFFIXES: .c .so .xo .o 15 | 16 | all: helloworld.so hellotype.so helloblock.so testmodule.so hellocluster.so hellotimer.so hellodict.so hellohook.so helloacl.so 17 | 18 | .c.xo: 19 | $(CC) -I. $(CFLAGS) $(SHOBJ_CFLAGS) -fPIC -c $< -o $@ 20 | 21 | helloworld.xo: ../redismodule.h 22 | 23 | helloworld.so: helloworld.xo 24 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc 25 | 26 | hellotype.xo: ../redismodule.h 27 | 28 | hellotype.so: hellotype.xo 29 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc 30 | 31 | helloblock.xo: ../redismodule.h 32 | 33 | helloblock.so: helloblock.xo 34 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lpthread -lc 35 | 36 | hellocluster.xo: ../redismodule.h 37 | 38 | hellocluster.so: hellocluster.xo 39 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc 40 | 41 | hellotimer.xo: ../redismodule.h 42 | 43 | hellotimer.so: hellotimer.xo 44 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc 45 | 46 | hellodict.xo: ../redismodule.h 47 | 48 | hellodict.so: hellodict.xo 49 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc 50 | 51 | hellohook.xo: ../redismodule.h 52 | 53 | hellohook.so: hellohook.xo 54 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc 55 | 56 | helloacl.xo: ../redismodule.h 57 | 58 | helloacl.so: helloacl.xo 59 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc 60 | 61 | testmodule.xo: ../redismodule.h 62 | 63 | testmodule.so: testmodule.xo 64 | $(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc 65 | 66 | clean: 67 | rm -rf *.xo *.so 68 | -------------------------------------------------------------------------------- /redis/rand.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 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_RANDOM_H 31 | #define REDIS_RANDOM_H 32 | 33 | int32_t redisLrand48(); 34 | void redisSrand48(int32_t seedval); 35 | 36 | #define REDIS_LRAND48_MAX INT32_MAX 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /redis/pqsort.h: -------------------------------------------------------------------------------- 1 | /* The following is the NetBSD libc qsort implementation modified in order to 2 | * support partial sorting of ranges for Redis. 3 | * 4 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * 10 | * * Redistributions of source code must retain the above copyright notice, 11 | * this list of conditions and the following disclaimer. 12 | * * Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * * Neither the name of Redis nor the names of its contributors may be used 16 | * to endorse or promote products derived from this software without 17 | * specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | * POSSIBILITY OF SUCH DAMAGE. 30 | * 31 | * See the pqsort.c file for the original copyright notice. */ 32 | 33 | #ifndef __PQSORT_H 34 | #define __PQSORT_H 35 | 36 | void 37 | pqsort(void *a, size_t n, size_t es, 38 | int (*cmp) (const void *, const void *), size_t lrange, size_t rrange); 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /redis/rax_malloc.h: -------------------------------------------------------------------------------- 1 | /* Rax -- A radix tree implementation. 2 | * 3 | * Copyright (c) 2017, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | /* Allocator selection. 32 | * 33 | * This file is used in order to change the Rax allocator at compile time. 34 | * Just define the following defines to what you want to use. Also add 35 | * the include of your alternate allocator if needed (not needed in order 36 | * to use the default libc allocator). */ 37 | 38 | #ifndef RAX_ALLOC_H 39 | #define RAX_ALLOC_H 40 | #include "zmalloc.h" 41 | #define rax_malloc zmalloc 42 | #define rax_realloc zrealloc 43 | #define rax_free zfree 44 | #endif 45 | -------------------------------------------------------------------------------- /redis/listpack_malloc.h: -------------------------------------------------------------------------------- 1 | /* Listpack -- A lists of strings serialization format 2 | * https://github.com/antirez/listpack 3 | * 4 | * Copyright (c) 2017, Salvatore Sanfilippo 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * 10 | * * Redistributions of source code must retain the above copyright notice, 11 | * this list of conditions and the following disclaimer. 12 | * * Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * * Neither the name of Redis nor the names of its contributors may be used 16 | * to endorse or promote products derived from this software without 17 | * specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | * POSSIBILITY OF SUCH DAMAGE. 30 | */ 31 | 32 | /* Allocator selection. 33 | * 34 | * This file is used in order to change the Rax allocator at compile time. 35 | * Just define the following defines to what you want to use. Also add 36 | * the include of your alternate allocator if needed (not needed in order 37 | * to use the default libc allocator). */ 38 | 39 | #ifndef LISTPACK_ALLOC_H 40 | #define LISTPACK_ALLOC_H 41 | #include "zmalloc.h" 42 | #define lp_malloc zmalloc 43 | #define lp_realloc zrealloc 44 | #define lp_free zfree 45 | #endif 46 | -------------------------------------------------------------------------------- /redis/sdsalloc.h: -------------------------------------------------------------------------------- 1 | /* SDSLib 2.0 -- A C dynamic strings library 2 | * 3 | * Copyright (c) 2006-2015, Salvatore Sanfilippo 4 | * Copyright (c) 2015, Redis Labs, Inc 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * 10 | * * Redistributions of source code must retain the above copyright notice, 11 | * this list of conditions and the following disclaimer. 12 | * * Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * * Neither the name of Redis nor the names of its contributors may be used 16 | * to endorse or promote products derived from this software without 17 | * specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | * POSSIBILITY OF SUCH DAMAGE. 30 | */ 31 | 32 | /* SDS allocator selection. 33 | * 34 | * This file is used in order to change the SDS allocator at compile time. 35 | * Just define the following defines to what you want to use. Also add 36 | * the include of your alternate allocator if needed (not needed in order 37 | * to use the default libc allocator). */ 38 | 39 | #ifndef __SDS_ALLOC_H__ 40 | #define __SDS_ALLOC_H__ 41 | 42 | #include "zmalloc.h" 43 | #define s_malloc zmalloc 44 | #define s_realloc zrealloc 45 | #define s_free zfree 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /redis/bio.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 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 __BIO_H 31 | #define __BIO_H 32 | 33 | /* Exported API */ 34 | void bioInit(void); 35 | void bioCreateBackgroundJob(int type, void *arg1, void *arg2, void *arg3); 36 | unsigned long long bioPendingJobsOfType(int type); 37 | unsigned long long bioWaitStepOfType(int type); 38 | time_t bioOlderJobOfType(int type); 39 | void bioKillThreads(void); 40 | 41 | /* Background job opcodes */ 42 | #define BIO_CLOSE_FILE 0 /* Deferred close(2) syscall. */ 43 | #define BIO_AOF_FSYNC 1 /* Deferred AOF fsync. */ 44 | #define BIO_LAZY_FREE 2 /* Deferred objects freeing. */ 45 | #define BIO_NUM_OPS 3 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /redis/fmacros.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 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_FMACRO_H 31 | #define _REDIS_FMACRO_H 32 | 33 | #define _BSD_SOURCE 34 | 35 | #if defined(__linux__) 36 | #define _GNU_SOURCE 37 | #define _DEFAULT_SOURCE 38 | #endif 39 | 40 | #if defined(_AIX) 41 | #define _ALL_SOURCE 42 | #endif 43 | 44 | #if defined(__linux__) || defined(__OpenBSD__) 45 | #define _XOPEN_SOURCE 700 46 | /* 47 | * On NetBSD, _XOPEN_SOURCE undefines _NETBSD_SOURCE and 48 | * thus hides inet_aton etc. 49 | */ 50 | #elif !defined(__NetBSD__) 51 | #define _XOPEN_SOURCE 52 | #endif 53 | 54 | #if defined(__sun) 55 | #define _POSIX_C_SOURCE 199506L 56 | #endif 57 | 58 | #define _LARGEFILE_SOURCE 59 | #define _FILE_OFFSET_BITS 64 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /redis/solarisfixes.h: -------------------------------------------------------------------------------- 1 | /* Solaris specific fixes. 2 | * 3 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #if defined(__sun) 32 | 33 | #if defined(__GNUC__) 34 | #include 35 | #undef isnan 36 | #define isnan(x) \ 37 | __extension__({ __typeof (x) __x_a = (x); \ 38 | __builtin_expect(__x_a != __x_a, 0); }) 39 | 40 | #undef isfinite 41 | #define isfinite(x) \ 42 | __extension__ ({ __typeof (x) __x_f = (x); \ 43 | __builtin_expect(!isnan(__x_f - __x_f), 1); }) 44 | 45 | #undef isinf 46 | #define isinf(x) \ 47 | __extension__ ({ __typeof (x) __x_i = (x); \ 48 | __builtin_expect(!isnan(__x_i) && !isfinite(__x_i), 0); }) 49 | 50 | #define u_int uint 51 | #define u_int32_t uint32_t 52 | #endif /* __GNUC__ */ 53 | 54 | #endif /* __sun */ 55 | -------------------------------------------------------------------------------- /redis/debugmacro.h: -------------------------------------------------------------------------------- 1 | /* This file contains debugging macros to be used when investigating issues. 2 | * 3 | * ----------------------------------------------------------------------------- 4 | * 5 | * Copyright (c) 2016, Salvatore Sanfilippo 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are met: 10 | * 11 | * * Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * * Neither the name of Redis nor the names of its contributors may be used 17 | * to endorse or promote products derived from this software without 18 | * specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #include 34 | #define D(...) \ 35 | do { \ 36 | FILE *fp = fopen("/tmp/log.txt","a"); \ 37 | fprintf(fp,"%s:%s:%d:\t", __FILE__, __func__, __LINE__); \ 38 | fprintf(fp,__VA_ARGS__); \ 39 | fprintf(fp,"\n"); \ 40 | fclose(fp); \ 41 | } while (0); 42 | -------------------------------------------------------------------------------- /redis/intset.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Pieter Noordhuis 3 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #ifndef __INTSET_H 32 | #define __INTSET_H 33 | #include 34 | 35 | typedef struct intset { 36 | uint32_t encoding; 37 | uint32_t length; 38 | int8_t contents[]; 39 | } intset; 40 | 41 | intset *intsetNew(void); 42 | intset *intsetAdd(intset *is, int64_t value, uint8_t *success); 43 | intset *intsetRemove(intset *is, int64_t value, int *success); 44 | uint8_t intsetFind(intset *is, int64_t value); 45 | int64_t intsetRandom(intset *is); 46 | uint8_t intsetGet(intset *is, uint32_t pos, int64_t *value); 47 | uint32_t intsetLen(const intset *is); 48 | size_t intsetBlobLen(intset *is); 49 | 50 | #ifdef REDIS_TEST 51 | int intsetTest(int argc, char *argv[]); 52 | #endif 53 | 54 | #endif // __INTSET_H 55 | -------------------------------------------------------------------------------- /redis/sparkline.h: -------------------------------------------------------------------------------- 1 | /* sparkline.h -- ASCII Sparklines header file 2 | * 3 | * --------------------------------------------------------------------------- 4 | * 5 | * Copyright(C) 2011-2014 Salvatore Sanfilippo 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are met: 10 | * 11 | * * Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 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 __SPARKLINE_H 31 | #define __SPARKLINE_H 32 | 33 | /* A sequence is represented of many "samples" */ 34 | struct sample { 35 | double value; 36 | char *label; 37 | }; 38 | 39 | struct sequence { 40 | int length; 41 | int labels; 42 | struct sample *samples; 43 | double min, max; 44 | }; 45 | 46 | #define SPARKLINE_NO_FLAGS 0 47 | #define SPARKLINE_FILL 1 /* Fill the area under the curve. */ 48 | #define SPARKLINE_LOG_SCALE 2 /* Use logarithmic scale. */ 49 | 50 | struct sequence *createSparklineSequence(void); 51 | void sparklineSequenceAddSample(struct sequence *seq, double value, char *label); 52 | void freeSparklineSequence(struct sequence *seq); 53 | sds sparklineRenderRange(sds output, struct sequence *seq, int rows, int offset, int len, int flags); 54 | sds sparklineRender(sds output, struct sequence *seq, int columns, int rows, int flags); 55 | 56 | #endif /* __SPARKLINE_H */ 57 | -------------------------------------------------------------------------------- /redis/slowlog.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 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 __SLOWLOG_H__ 31 | #define __SLOWLOG_H__ 32 | 33 | #define SLOWLOG_ENTRY_MAX_ARGC 32 34 | #define SLOWLOG_ENTRY_MAX_STRING 128 35 | 36 | /* This structure defines an entry inside the slow log list */ 37 | typedef struct slowlogEntry { 38 | robj **argv; 39 | int argc; 40 | long long id; /* Unique entry identifier. */ 41 | long long duration; /* Time spent by the query, in microseconds. */ 42 | time_t time; /* Unix time at which the query was executed. */ 43 | sds cname; /* Client name. */ 44 | sds peerid; /* Client network address. */ 45 | } slowlogEntry; 46 | 47 | /* Exported API */ 48 | void slowlogInit(void); 49 | void slowlogPushEntryIfNeeded(client *c, robj **argv, int argc, long long duration); 50 | 51 | /* Exported commands */ 52 | void slowlogCommand(client *c); 53 | 54 | #endif /* __SLOWLOG_H__ */ 55 | -------------------------------------------------------------------------------- /redis/redisassert.h: -------------------------------------------------------------------------------- 1 | /* redisassert.h -- Drop in replacements assert.h that prints the stack trace 2 | * in the Redis logs. 3 | * 4 | * This file should be included instead of "assert.h" inside libraries used by 5 | * Redis that are using assertions, so instead of Redis disappearing with 6 | * SIGABORT, we get the details and stack trace inside the log file. 7 | * 8 | * ---------------------------------------------------------------------------- 9 | * 10 | * Copyright (c) 2006-2012, Salvatore Sanfilippo 11 | * All rights reserved. 12 | * 13 | * Redistribution and use in source and binary forms, with or without 14 | * modification, are permitted provided that the following conditions are met: 15 | * 16 | * * Redistributions of source code must retain the above copyright notice, 17 | * this list of conditions and the following disclaimer. 18 | * * Redistributions in binary form must reproduce the above copyright 19 | * notice, this list of conditions and the following disclaimer in the 20 | * documentation and/or other materials provided with the distribution. 21 | * * Neither the name of Redis nor the names of its contributors may be used 22 | * to endorse or promote products derived from this software without 23 | * specific prior written permission. 24 | * 25 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 26 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 27 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 28 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 29 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 30 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 31 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 32 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 33 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 34 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 35 | * POSSIBILITY OF SUCH DAMAGE. 36 | */ 37 | 38 | #ifndef __REDIS_ASSERT_H__ 39 | #define __REDIS_ASSERT_H__ 40 | 41 | #include /* for _exit() */ 42 | 43 | #define assert(_e) ((_e)?(void)0 : (_serverAssert(#_e,__FILE__,__LINE__),_exit(1))) 44 | #define panic(...) _serverPanic(__FILE__,__LINE__,__VA_ARGS__),_exit(1) 45 | 46 | void _serverAssert(char *estr, char *file, int line); 47 | void _serverPanic(const char *file, int line, const char *msg, ...); 48 | 49 | #endif 50 | -------------------------------------------------------------------------------- /redis/testhelp.h: -------------------------------------------------------------------------------- 1 | /* This is a really minimal testing framework for C. 2 | * 3 | * Example: 4 | * 5 | * test_cond("Check if 1 == 1", 1==1) 6 | * test_cond("Check if 5 > 10", 5 > 10) 7 | * test_report() 8 | * 9 | * ---------------------------------------------------------------------------- 10 | * 11 | * Copyright (c) 2010-2012, Salvatore Sanfilippo 12 | * All rights reserved. 13 | * 14 | * Redistribution and use in source and binary forms, with or without 15 | * modification, are permitted provided that the following conditions are met: 16 | * 17 | * * Redistributions of source code must retain the above copyright notice, 18 | * this list of conditions and the following disclaimer. 19 | * * Redistributions in binary form must reproduce the above copyright 20 | * notice, this list of conditions and the following disclaimer in the 21 | * documentation and/or other materials provided with the distribution. 22 | * * Neither the name of Redis nor the names of its contributors may be used 23 | * to endorse or promote products derived from this software without 24 | * specific prior written permission. 25 | * 26 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 27 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 30 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 31 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 32 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 33 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 34 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 35 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 36 | * POSSIBILITY OF SUCH DAMAGE. 37 | */ 38 | 39 | #ifndef __TESTHELP_H 40 | #define __TESTHELP_H 41 | 42 | int __failed_tests = 0; 43 | int __test_num = 0; 44 | #define test_cond(descr,_c) do { \ 45 | __test_num++; printf("%d - %s: ", __test_num, descr); \ 46 | if(_c) printf("PASSED\n"); else {printf("FAILED\n"); __failed_tests++;} \ 47 | } while(0); 48 | #define test_report() do { \ 49 | printf("%d tests, %d passed, %d failed\n", __test_num, \ 50 | __test_num-__failed_tests, __failed_tests); \ 51 | if (__failed_tests) { \ 52 | printf("=== WARNING === We have failed tests here...\n"); \ 53 | exit(1); \ 54 | } \ 55 | } while(0); 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /redis/lolwut.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018-2019, Salvatore Sanfilippo 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 | /* This structure represents our canvas. Drawing functions will take a pointer 31 | * to a canvas to write to it. Later the canvas can be rendered to a string 32 | * suitable to be printed on the screen, using unicode Braille characters. */ 33 | 34 | /* This represents a very simple generic canvas in order to draw stuff. 35 | * It's up to each LOLWUT versions to translate what they draw to the 36 | * screen, depending on the result to accomplish. */ 37 | 38 | #ifndef __LOLWUT_H 39 | #define __LOLWUT_H 40 | 41 | typedef struct lwCanvas { 42 | int width; 43 | int height; 44 | char *pixels; 45 | } lwCanvas; 46 | 47 | /* Drawing functions implemented inside lolwut.c. */ 48 | lwCanvas *lwCreateCanvas(int width, int height, int bgcolor); 49 | void lwFreeCanvas(lwCanvas *canvas); 50 | void lwDrawPixel(lwCanvas *canvas, int x, int y, int color); 51 | int lwGetPixel(lwCanvas *canvas, int x, int y); 52 | void lwDrawLine(lwCanvas *canvas, int x1, int y1, int x2, int y2, int color); 53 | void lwDrawSquare(lwCanvas *canvas, int x, int y, float size, float angle, int color); 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /redis/zipmap.h: -------------------------------------------------------------------------------- 1 | /* String -> String Map data structure optimized for size. 2 | * 3 | * See zipmap.c for more info. 4 | * 5 | * -------------------------------------------------------------------------- 6 | * 7 | * Copyright (c) 2009-2010, Salvatore Sanfilippo 8 | * All rights reserved. 9 | * 10 | * Redistribution and use in source and binary forms, with or without 11 | * modification, are permitted provided that the following conditions are met: 12 | * 13 | * * Redistributions of source code must retain the above copyright notice, 14 | * this list of conditions and the following disclaimer. 15 | * * Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in the 17 | * documentation and/or other materials provided with the distribution. 18 | * * Neither the name of Redis nor the names of its contributors may be used 19 | * to endorse or promote products derived from this software without 20 | * specific prior written permission. 21 | * 22 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 23 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 26 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 27 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 28 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 29 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 30 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 31 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 32 | * POSSIBILITY OF SUCH DAMAGE. 33 | */ 34 | 35 | #ifndef _ZIPMAP_H 36 | #define _ZIPMAP_H 37 | 38 | unsigned char *zipmapNew(void); 39 | unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update); 40 | unsigned char *zipmapDel(unsigned char *zm, unsigned char *key, unsigned int klen, int *deleted); 41 | unsigned char *zipmapRewind(unsigned char *zm); 42 | unsigned char *zipmapNext(unsigned char *zm, unsigned char **key, unsigned int *klen, unsigned char **value, unsigned int *vlen); 43 | int zipmapGet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char **value, unsigned int *vlen); 44 | int zipmapExists(unsigned char *zm, unsigned char *key, unsigned int klen); 45 | unsigned int zipmapLen(unsigned char *zm); 46 | size_t zipmapBlobLen(unsigned char *zm); 47 | void zipmapRepr(unsigned char *p); 48 | 49 | #ifdef REDIS_TEST 50 | int zipmapTest(int argc, char *argv[]); 51 | #endif 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /redis/release.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 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 | /* Every time the Redis Git SHA1 or Dirty status changes only this small 31 | * file is recompiled, as we access this information in all the other 32 | * files using this functions. */ 33 | 34 | #include 35 | #include 36 | 37 | #include "release.h" 38 | #include "version.h" 39 | #include "crc64.h" 40 | 41 | char *redisGitSHA1(void) { 42 | return REDIS_GIT_SHA1; 43 | } 44 | 45 | char *redisGitDirty(void) { 46 | return REDIS_GIT_DIRTY; 47 | } 48 | 49 | uint64_t redisBuildId(void) { 50 | char *buildid = REDIS_VERSION REDIS_BUILD_ID REDIS_GIT_DIRTY REDIS_GIT_SHA1; 51 | 52 | return crc64(0,(unsigned char*)buildid,strlen(buildid)); 53 | } 54 | 55 | /* Return a cached value of the build string in order to avoid recomputing 56 | * and converting it in hex every time: this string is shown in the INFO 57 | * output that should be fast. */ 58 | char *redisBuildIdString(void) { 59 | static char buf[32]; 60 | static int cached = 0; 61 | if (!cached) { 62 | snprintf(buf,sizeof(buf),"%llx",(unsigned long long) redisBuildId()); 63 | cached = 1; 64 | } 65 | return buf; 66 | } 67 | -------------------------------------------------------------------------------- /redis/asciilogo.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 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 | const char *ascii_logo = 31 | " _._ \n" 32 | " _.-``__ ''-._ \n" 33 | " _.-`` `. `_. ''-._ Redis %s (%s/%d) %s bit\n" 34 | " .-`` .-```. ```\\/ _.,_ ''-._ \n" 35 | " ( ' , .-` | `, ) Running in %s mode\n" 36 | " |`-._`-...-` __...-.``-._|'` _.-'| Port: %d\n" 37 | " | `-._ `._ / _.-' | PID: %ld\n" 38 | " `-._ `-._ `-./ _.-' _.-' \n" 39 | " |`-._`-._ `-.__.-' _.-'_.-'| \n" 40 | " | `-._`-._ _.-'_.-' | http://redis.io \n" 41 | " `-._ `-._`-.__.-'_.-' _.-' \n" 42 | " |`-._`-._ `-.__.-' _.-'_.-'| \n" 43 | " | `-._`-._ _.-'_.-' | \n" 44 | " `-._ `-._`-.__.-'_.-' _.-' \n" 45 | " `-._ `-.__.-' _.-' \n" 46 | " `-._ _.-' \n" 47 | " `-.__.-' \n\n"; 48 | -------------------------------------------------------------------------------- /redis/listpack.h: -------------------------------------------------------------------------------- 1 | /* Listpack -- A lists of strings serialization format 2 | * 3 | * This file implements the specification you can find at: 4 | * 5 | * https://github.com/antirez/listpack 6 | * 7 | * Copyright (c) 2017, Salvatore Sanfilippo 8 | * All rights reserved. 9 | * 10 | * Redistribution and use in source and binary forms, with or without 11 | * modification, are permitted provided that the following conditions are met: 12 | * 13 | * * Redistributions of source code must retain the above copyright notice, 14 | * this list of conditions and the following disclaimer. 15 | * * Redistributions in binary form must reproduce the above copyright 16 | * notice, this list of conditions and the following disclaimer in the 17 | * documentation and/or other materials provided with the distribution. 18 | * * Neither the name of Redis nor the names of its contributors may be used 19 | * to endorse or promote products derived from this software without 20 | * specific prior written permission. 21 | * 22 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 23 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 26 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 27 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 28 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 29 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 30 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 31 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 32 | * POSSIBILITY OF SUCH DAMAGE. 33 | */ 34 | 35 | #ifndef __LISTPACK_H 36 | #define __LISTPACK_H 37 | 38 | #include 39 | 40 | #define LP_INTBUF_SIZE 21 /* 20 digits of -2^63 + 1 null term = 21. */ 41 | 42 | /* lpInsert() where argument possible values: */ 43 | #define LP_BEFORE 0 44 | #define LP_AFTER 1 45 | #define LP_REPLACE 2 46 | 47 | unsigned char *lpNew(void); 48 | void lpFree(unsigned char *lp); 49 | unsigned char *lpInsert(unsigned char *lp, unsigned char *ele, uint32_t size, unsigned char *p, int where, unsigned char **newp); 50 | unsigned char *lpAppend(unsigned char *lp, unsigned char *ele, uint32_t size); 51 | unsigned char *lpDelete(unsigned char *lp, unsigned char *p, unsigned char **newp); 52 | uint32_t lpLength(unsigned char *lp); 53 | unsigned char *lpGet(unsigned char *p, int64_t *count, unsigned char *intbuf); 54 | unsigned char *lpFirst(unsigned char *lp); 55 | unsigned char *lpLast(unsigned char *lp); 56 | unsigned char *lpNext(unsigned char *lp, unsigned char *p); 57 | unsigned char *lpPrev(unsigned char *lp, unsigned char *p); 58 | uint32_t lpBytes(unsigned char *lp); 59 | unsigned char *lpSeek(unsigned char *lp, long index); 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /redis/crcspeed.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2014, Matt Stancliff 2 | * All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * 7 | * * Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * * Redistributions in binary form must reproduce the above copyright 10 | * notice, this list of conditions and the following disclaimer in the 11 | * documentation and/or other materials provided with the distribution. 12 | * * Neither the name of Redis nor the names of its contributors may be used 13 | * to endorse or promote products derived from this software without 14 | * specific prior written permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. */ 27 | 28 | #ifndef CRCSPEED_H 29 | #define CRCSPEED_H 30 | 31 | #include 32 | #include 33 | 34 | typedef uint64_t (*crcfn64)(uint64_t, const void *, const uint64_t); 35 | typedef uint16_t (*crcfn16)(uint16_t, const void *, const uint64_t); 36 | 37 | /* CRC-64 */ 38 | void crcspeed64little_init(crcfn64 fn, uint64_t table[8][256]); 39 | void crcspeed64big_init(crcfn64 fn, uint64_t table[8][256]); 40 | void crcspeed64native_init(crcfn64 fn, uint64_t table[8][256]); 41 | 42 | uint64_t crcspeed64little(uint64_t table[8][256], uint64_t crc, void *buf, 43 | size_t len); 44 | uint64_t crcspeed64big(uint64_t table[8][256], uint64_t crc, void *buf, 45 | size_t len); 46 | uint64_t crcspeed64native(uint64_t table[8][256], uint64_t crc, void *buf, 47 | size_t len); 48 | 49 | /* CRC-16 */ 50 | void crcspeed16little_init(crcfn16 fn, uint16_t table[8][256]); 51 | void crcspeed16big_init(crcfn16 fn, uint16_t table[8][256]); 52 | void crcspeed16native_init(crcfn16 fn, uint16_t table[8][256]); 53 | 54 | uint16_t crcspeed16little(uint16_t table[8][256], uint16_t crc, void *buf, 55 | size_t len); 56 | uint16_t crcspeed16big(uint16_t table[8][256], uint16_t crc, void *buf, 57 | size_t len); 58 | uint16_t crcspeed16native(uint16_t table[8][256], uint16_t crc, void *buf, 59 | size_t len); 60 | #endif 61 | -------------------------------------------------------------------------------- /redis/ziplist.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Pieter Noordhuis 3 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #ifndef _ZIPLIST_H 32 | #define _ZIPLIST_H 33 | 34 | #define ZIPLIST_HEAD 0 35 | #define ZIPLIST_TAIL 1 36 | 37 | unsigned char *ziplistNew(void); 38 | unsigned char *ziplistMerge(unsigned char **first, unsigned char **second); 39 | unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where); 40 | unsigned char *ziplistIndex(unsigned char *zl, int index); 41 | unsigned char *ziplistNext(unsigned char *zl, unsigned char *p); 42 | unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p); 43 | unsigned int ziplistGet(unsigned char *p, unsigned char **sval, unsigned int *slen, long long *lval); 44 | unsigned char *ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen); 45 | unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p); 46 | unsigned char *ziplistDeleteRange(unsigned char *zl, int index, unsigned int num); 47 | unsigned int ziplistCompare(unsigned char *p, unsigned char *s, unsigned int slen); 48 | unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int vlen, unsigned int skip); 49 | unsigned int ziplistLen(unsigned char *zl); 50 | size_t ziplistBlobLen(unsigned char *zl); 51 | void ziplistRepr(unsigned char *zl); 52 | 53 | #ifdef REDIS_TEST 54 | int ziplistTest(int argc, char *argv[]); 55 | #endif 56 | 57 | #endif /* _ZIPLIST_H */ 58 | -------------------------------------------------------------------------------- /redis/endianconv.h: -------------------------------------------------------------------------------- 1 | /* See endianconv.c top comments for more information 2 | * 3 | * ---------------------------------------------------------------------------- 4 | * 5 | * Copyright (c) 2011-2012, Salvatore Sanfilippo 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are met: 10 | * 11 | * * Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * * Neither the name of Redis nor the names of its contributors may be used 17 | * to endorse or promote products derived from this software without 18 | * specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #ifndef __ENDIANCONV_H 34 | #define __ENDIANCONV_H 35 | 36 | #include "config.h" 37 | #include 38 | 39 | void memrev16(void *p); 40 | void memrev32(void *p); 41 | void memrev64(void *p); 42 | uint16_t intrev16(uint16_t v); 43 | uint32_t intrev32(uint32_t v); 44 | uint64_t intrev64(uint64_t v); 45 | 46 | /* variants of the function doing the actual conversion only if the target 47 | * host is big endian */ 48 | #if (BYTE_ORDER == LITTLE_ENDIAN) 49 | #define memrev16ifbe(p) ((void)(0)) 50 | #define memrev32ifbe(p) ((void)(0)) 51 | #define memrev64ifbe(p) ((void)(0)) 52 | #define intrev16ifbe(v) (v) 53 | #define intrev32ifbe(v) (v) 54 | #define intrev64ifbe(v) (v) 55 | #else 56 | #define memrev16ifbe(p) memrev16(p) 57 | #define memrev32ifbe(p) memrev32(p) 58 | #define memrev64ifbe(p) memrev64(p) 59 | #define intrev16ifbe(v) intrev16(v) 60 | #define intrev32ifbe(v) intrev32(v) 61 | #define intrev64ifbe(v) intrev64(v) 62 | #endif 63 | 64 | /* The functions htonu64() and ntohu64() convert the specified value to 65 | * network byte ordering and back. In big endian systems they are no-ops. */ 66 | #if (BYTE_ORDER == BIG_ENDIAN) 67 | #define htonu64(v) (v) 68 | #define ntohu64(v) (v) 69 | #else 70 | #define htonu64(v) intrev64(v) 71 | #define ntohu64(v) intrev64(v) 72 | #endif 73 | 74 | #ifdef REDIS_TEST 75 | int endianconvTest(int argc, char *argv[]); 76 | #endif 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /redis/util.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 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_UTIL_H 31 | #define __REDIS_UTIL_H 32 | 33 | #include 34 | #include "sds.h" 35 | 36 | /* The maximum number of characters needed to represent a long double 37 | * as a string (long double has a huge range). 38 | * This should be the size of the buffer given to ld2string */ 39 | #define MAX_LONG_DOUBLE_CHARS 5*1024 40 | 41 | /* long double to string convertion options */ 42 | typedef enum { 43 | LD_STR_AUTO, /* %.17Lg */ 44 | LD_STR_HUMAN, /* %.17Lf + Trimming of trailing zeros */ 45 | LD_STR_HEX /* %La */ 46 | } ld2string_mode; 47 | 48 | int stringmatchlen(const char *p, int plen, const char *s, int slen, int nocase); 49 | int stringmatch(const char *p, const char *s, int nocase); 50 | int stringmatchlen_fuzz_test(void); 51 | long long memtoll(const char *p, int *err); 52 | uint32_t digits10(uint64_t v); 53 | uint32_t sdigits10(int64_t v); 54 | int ll2string(char *s, size_t len, long long value); 55 | int string2ll(const char *s, size_t slen, long long *value); 56 | int string2ull(const char *s, unsigned long long *value); 57 | int string2l(const char *s, size_t slen, long *value); 58 | int string2ld(const char *s, size_t slen, long double *dp); 59 | int string2d(const char *s, size_t slen, double *dp); 60 | int d2string(char *buf, size_t len, double value); 61 | int ld2string(char *buf, size_t len, long double value, ld2string_mode mode); 62 | sds getAbsolutePath(char *filename); 63 | unsigned long getTimeZone(void); 64 | int pathIsBaseName(char *path); 65 | 66 | #ifdef REDIS_TEST 67 | int utilTest(int argc, char **argv); 68 | #endif 69 | 70 | #endif 71 | -------------------------------------------------------------------------------- /redis/modules/hellotimer.c: -------------------------------------------------------------------------------- 1 | /* Timer API example -- Register and handle timer events 2 | * 3 | * ----------------------------------------------------------------------------- 4 | * 5 | * Copyright (c) 2018, Salvatore Sanfilippo 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are met: 10 | * 11 | * * Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * * Neither the name of Redis nor the names of its contributors may be used 17 | * to endorse or promote products derived from this software without 18 | * specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #define REDISMODULE_EXPERIMENTAL_API 34 | #include "../redismodule.h" 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | /* Timer callback. */ 41 | void timerHandler(RedisModuleCtx *ctx, void *data) { 42 | REDISMODULE_NOT_USED(ctx); 43 | printf("Fired %s!\n", (char *)data); 44 | RedisModule_Free(data); 45 | } 46 | 47 | /* HELLOTIMER.TIMER*/ 48 | int TimerCommand_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 49 | REDISMODULE_NOT_USED(argv); 50 | REDISMODULE_NOT_USED(argc); 51 | 52 | for (int j = 0; j < 10; j++) { 53 | int delay = rand() % 5000; 54 | char *buf = RedisModule_Alloc(256); 55 | snprintf(buf,256,"After %d", delay); 56 | RedisModuleTimerID tid = RedisModule_CreateTimer(ctx,delay,timerHandler,buf); 57 | REDISMODULE_NOT_USED(tid); 58 | } 59 | return RedisModule_ReplyWithSimpleString(ctx, "OK"); 60 | } 61 | 62 | /* This function must be present on each Redis module. It is used in order to 63 | * register the commands into the Redis server. */ 64 | int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 65 | REDISMODULE_NOT_USED(argv); 66 | REDISMODULE_NOT_USED(argc); 67 | 68 | if (RedisModule_Init(ctx,"hellotimer",1,REDISMODULE_APIVER_1) 69 | == REDISMODULE_ERR) return REDISMODULE_ERR; 70 | 71 | if (RedisModule_CreateCommand(ctx,"hellotimer.timer", 72 | TimerCommand_RedisCommand,"readonly",0,0,0) == REDISMODULE_ERR) 73 | return REDISMODULE_ERR; 74 | 75 | return REDISMODULE_OK; 76 | } 77 | -------------------------------------------------------------------------------- /redis/geohash_helper.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2014, yinqiwen 3 | * Copyright (c) 2014, Matt Stancliff . 4 | * Copyright (c) 2015, Salvatore Sanfilippo . 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * 10 | * * Redistributions of source code must retain the above copyright notice, 11 | * this list of conditions and the following disclaimer. 12 | * * Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * * Neither the name of Redis nor the names of its contributors may be used 16 | * to endorse or promote products derived from this software without 17 | * specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 23 | * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 29 | * THE POSSIBILITY OF SUCH DAMAGE. 30 | */ 31 | 32 | #ifndef GEOHASH_HELPER_HPP_ 33 | #define GEOHASH_HELPER_HPP_ 34 | 35 | #include "geohash.h" 36 | 37 | #define GZERO(s) s.bits = s.step = 0; 38 | #define GISZERO(s) (!s.bits && !s.step) 39 | #define GISNOTZERO(s) (s.bits || s.step) 40 | 41 | typedef uint64_t GeoHashFix52Bits; 42 | typedef uint64_t GeoHashVarBits; 43 | 44 | typedef struct { 45 | GeoHashBits hash; 46 | GeoHashArea area; 47 | GeoHashNeighbors neighbors; 48 | } GeoHashRadius; 49 | 50 | int GeoHashBitsComparator(const GeoHashBits *a, const GeoHashBits *b); 51 | uint8_t geohashEstimateStepsByRadius(double range_meters, double lat); 52 | int geohashBoundingBox(double longitude, double latitude, double radius_meters, 53 | double *bounds); 54 | GeoHashRadius geohashGetAreasByRadius(double longitude, 55 | double latitude, double radius_meters); 56 | GeoHashRadius geohashGetAreasByRadiusWGS84(double longitude, double latitude, 57 | double radius_meters); 58 | GeoHashRadius geohashGetAreasByRadiusMercator(double longitude, double latitude, 59 | double radius_meters); 60 | GeoHashFix52Bits geohashAlign52Bits(const GeoHashBits hash); 61 | double geohashGetDistance(double lon1d, double lat1d, 62 | double lon2d, double lat2d); 63 | int geohashGetDistanceIfInRadius(double x1, double y1, 64 | double x2, double y2, double radius, 65 | double *distance); 66 | int geohashGetDistanceIfInRadiusWGS84(double x1, double y1, double x2, 67 | double y2, double radius, 68 | double *distance); 69 | 70 | #endif /* GEOHASH_HELPER_HPP_ */ 71 | -------------------------------------------------------------------------------- /redis/connhelpers.h: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright (c) 2019, Redis Labs 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #ifndef __REDIS_CONNHELPERS_H 32 | #define __REDIS_CONNHELPERS_H 33 | 34 | #include "connection.h" 35 | 36 | /* These are helper functions that are common to different connection 37 | * implementations (currently sockets in connection.c and TLS in tls.c). 38 | * 39 | * Currently helpers implement the mechanisms for invoking connection 40 | * handlers and tracking connection references, to allow safe destruction 41 | * of connections from within a handler. 42 | */ 43 | 44 | /* Incremenet connection references. 45 | * 46 | * Inside a connection handler, we guarantee refs >= 1 so it is always 47 | * safe to connClose(). 48 | * 49 | * In other cases where we don't want to prematurely lose the connection, 50 | * it can go beyond 1 as well; currently it is only done by connAccept(). 51 | */ 52 | static inline void connIncrRefs(connection *conn) { 53 | conn->refs++; 54 | } 55 | 56 | /* Decrement connection references. 57 | * 58 | * Note that this is not intended to provide any automatic free logic! 59 | * callHandler() takes care of that for the common flows, and anywhere an 60 | * explicit connIncrRefs() is used, the caller is expected to take care of 61 | * that. 62 | */ 63 | 64 | static inline void connDecrRefs(connection *conn) { 65 | conn->refs--; 66 | } 67 | 68 | static inline int connHasRefs(connection *conn) { 69 | return conn->refs; 70 | } 71 | 72 | /* Helper for connection implementations to call handlers: 73 | * 1. Increment refs to protect the connection. 74 | * 2. Execute the handler (if set). 75 | * 3. Decrement refs and perform deferred close, if refs==0. 76 | */ 77 | static inline int callHandler(connection *conn, ConnectionCallbackFunc handler) { 78 | connIncrRefs(conn); 79 | if (handler) handler(conn); 80 | connDecrRefs(conn); 81 | if (conn->flags & CONN_FLAG_CLOSE_SCHEDULED) { 82 | if (!connHasRefs(conn)) connClose(conn); 83 | return 0; 84 | } 85 | return 1; 86 | } 87 | 88 | #endif /* __REDIS_CONNHELPERS_H */ 89 | -------------------------------------------------------------------------------- /redis/adlist.h: -------------------------------------------------------------------------------- 1 | /* adlist.h - A generic doubly linked list implementation 2 | * 3 | * Copyright (c) 2006-2012, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #ifndef __ADLIST_H__ 32 | #define __ADLIST_H__ 33 | 34 | /* Node, List, and Iterator are the only data structures used currently. */ 35 | 36 | typedef struct listNode { 37 | struct listNode *prev; 38 | struct listNode *next; 39 | void *value; 40 | } listNode; 41 | 42 | typedef struct listIter { 43 | listNode *next; 44 | int direction; 45 | } listIter; 46 | 47 | typedef struct list { 48 | //头节点 49 | listNode *head; 50 | listNode *tail; 51 | void *(*dup)(void *ptr); 52 | void (*free)(void *ptr); 53 | int (*match)(void *ptr, void *key); 54 | unsigned long len; 55 | } list; 56 | 57 | /* Functions implemented as macros */ 58 | #define listLength(l) ((l)->len) 59 | #define listFirst(l) ((l)->head) 60 | #define listLast(l) ((l)->tail) 61 | #define listPrevNode(n) ((n)->prev) 62 | #define listNextNode(n) ((n)->next) 63 | #define listNodeValue(n) ((n)->value) 64 | 65 | #define listSetDupMethod(l,m) ((l)->dup = (m)) 66 | #define listSetFreeMethod(l,m) ((l)->free = (m)) 67 | #define listSetMatchMethod(l,m) ((l)->match = (m)) 68 | 69 | #define listGetDupMethod(l) ((l)->dup) 70 | #define listGetFreeMethod(l) ((l)->free) 71 | #define listGetMatchMethod(l) ((l)->match) 72 | 73 | /* Prototypes */ 74 | list *listCreate(void); 75 | void listRelease(list *list); 76 | void listEmpty(list *list); 77 | list *listAddNodeHead(list *list, void *value); 78 | list *listAddNodeTail(list *list, void *value); 79 | list *listInsertNode(list *list, listNode *old_node, void *value, int after); 80 | void listDelNode(list *list, listNode *node); 81 | listIter *listGetIterator(list *list, int direction); 82 | listNode *listNext(listIter *iter); 83 | void listReleaseIterator(listIter *iter); 84 | list *listDup(list *orig); 85 | listNode *listSearchKey(list *list, void *key); 86 | listNode *listIndex(list *list, long index); 87 | void listRewind(list *list, listIter *li); 88 | void listRewindTail(list *list, listIter *li); 89 | void listRotateTailToHead(list *list); 90 | void listRotateHeadToTail(list *list); 91 | void listJoin(list *l, list *o); 92 | 93 | /* Directions for iterators */ 94 | #define AL_START_HEAD 0 95 | #define AL_START_TAIL 1 96 | 97 | #endif /* __ADLIST_H__ */ 98 | -------------------------------------------------------------------------------- /redis/anet.h: -------------------------------------------------------------------------------- 1 | /* anet.c -- Basic TCP socket stuff made a bit less boring 2 | * 3 | * Copyright (c) 2006-2012, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #ifndef ANET_H 32 | #define ANET_H 33 | 34 | #include 35 | 36 | #define ANET_OK 0 37 | #define ANET_ERR -1 38 | #define ANET_ERR_LEN 256 39 | 40 | /* Flags used with certain functions. */ 41 | #define ANET_NONE 0 42 | #define ANET_IP_ONLY (1<<0) 43 | 44 | #if defined(__sun) || defined(_AIX) 45 | #define AF_LOCAL AF_UNIX 46 | #endif 47 | 48 | #ifdef _AIX 49 | #undef ip_len 50 | #endif 51 | 52 | int anetTcpConnect(char *err, const char *addr, int port); 53 | int anetTcpNonBlockConnect(char *err, const char *addr, int port); 54 | int anetTcpNonBlockBindConnect(char *err, const char *addr, int port, const char *source_addr); 55 | int anetTcpNonBlockBestEffortBindConnect(char *err, const char *addr, int port, const char *source_addr); 56 | int anetUnixConnect(char *err, const char *path); 57 | int anetUnixNonBlockConnect(char *err, const char *path); 58 | int anetRead(int fd, char *buf, int count); 59 | int anetResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len); 60 | int anetResolveIP(char *err, char *host, char *ipbuf, size_t ipbuf_len); 61 | int anetTcpServer(char *err, int port, char *bindaddr, int backlog); 62 | int anetTcp6Server(char *err, int port, char *bindaddr, int backlog); 63 | int anetUnixServer(char *err, char *path, mode_t perm, int backlog); 64 | int anetTcpAccept(char *err, int serversock, char *ip, size_t ip_len, int *port); 65 | int anetUnixAccept(char *err, int serversock); 66 | int anetWrite(int fd, char *buf, int count); 67 | int anetNonBlock(char *err, int fd); 68 | int anetBlock(char *err, int fd); 69 | int anetEnableTcpNoDelay(char *err, int fd); 70 | int anetDisableTcpNoDelay(char *err, int fd); 71 | int anetTcpKeepAlive(char *err, int fd); 72 | int anetSendTimeout(char *err, int fd, long long ms); 73 | int anetRecvTimeout(char *err, int fd, long long ms); 74 | int anetPeerToString(int fd, char *ip, size_t ip_len, int *port); 75 | int anetKeepAlive(char *err, int fd, int interval); 76 | int anetSockName(int fd, char *ip, size_t ip_len, int *port); 77 | int anetFormatAddr(char *fmt, size_t fmt_len, char *ip, int port); 78 | int anetFormatPeer(int fd, char *fmt, size_t fmt_len); 79 | int anetFormatSock(int fd, char *fmt, size_t fmt_len); 80 | 81 | #endif 82 | -------------------------------------------------------------------------------- /redis/modules/hellohook.c: -------------------------------------------------------------------------------- 1 | /* Server hooks API example 2 | * 3 | * ----------------------------------------------------------------------------- 4 | * 5 | * Copyright (c) 2019, Salvatore Sanfilippo 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are met: 10 | * 11 | * * Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * * Neither the name of Redis nor the names of its contributors may be used 17 | * to endorse or promote products derived from this software without 18 | * specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #define REDISMODULE_EXPERIMENTAL_API 34 | #include "../redismodule.h" 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | /* Client state change callback. */ 41 | void clientChangeCallback(RedisModuleCtx *ctx, RedisModuleEvent e, uint64_t sub, void *data) 42 | { 43 | REDISMODULE_NOT_USED(ctx); 44 | REDISMODULE_NOT_USED(e); 45 | 46 | RedisModuleClientInfo *ci = data; 47 | printf("Client %s event for client #%llu %s:%d\n", 48 | (sub == REDISMODULE_SUBEVENT_CLIENT_CHANGE_CONNECTED) ? 49 | "connection" : "disconnection", 50 | ci->id,ci->addr,ci->port); 51 | } 52 | 53 | void flushdbCallback(RedisModuleCtx *ctx, RedisModuleEvent e, uint64_t sub, void *data) 54 | { 55 | REDISMODULE_NOT_USED(ctx); 56 | REDISMODULE_NOT_USED(e); 57 | 58 | RedisModuleFlushInfo *fi = data; 59 | if (sub == REDISMODULE_SUBEVENT_FLUSHDB_START) { 60 | if (fi->dbnum != -1) { 61 | RedisModuleCallReply *reply; 62 | reply = RedisModule_Call(ctx,"DBSIZE",""); 63 | long long numkeys = RedisModule_CallReplyInteger(reply); 64 | printf("FLUSHDB event of database %d started (%lld keys in DB)\n", 65 | fi->dbnum, numkeys); 66 | RedisModule_FreeCallReply(reply); 67 | } else { 68 | printf("FLUSHALL event started\n"); 69 | } 70 | } else { 71 | if (fi->dbnum != -1) { 72 | printf("FLUSHDB event of database %d ended\n",fi->dbnum); 73 | } else { 74 | printf("FLUSHALL event ended\n"); 75 | } 76 | } 77 | } 78 | 79 | /* This function must be present on each Redis module. It is used in order to 80 | * register the commands into the Redis server. */ 81 | int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 82 | REDISMODULE_NOT_USED(argv); 83 | REDISMODULE_NOT_USED(argc); 84 | 85 | if (RedisModule_Init(ctx,"hellohook",1,REDISMODULE_APIVER_1) 86 | == REDISMODULE_ERR) return REDISMODULE_ERR; 87 | 88 | RedisModule_SubscribeToServerEvent(ctx, 89 | RedisModuleEvent_ClientChange, clientChangeCallback); 90 | RedisModule_SubscribeToServerEvent(ctx, 91 | RedisModuleEvent_FlushDB, flushdbCallback); 92 | return REDISMODULE_OK; 93 | } 94 | -------------------------------------------------------------------------------- /redis/rand.c: -------------------------------------------------------------------------------- 1 | /* Pseudo random number generation functions derived from the drand48() 2 | * function obtained from pysam source code. 3 | * 4 | * This functions are used in order to replace the default math.random() 5 | * Lua implementation with something having exactly the same behavior 6 | * across different systems (by default Lua uses libc's rand() that is not 7 | * required to implement a specific PRNG generating the same sequence 8 | * in different systems if seeded with the same integer). 9 | * 10 | * The original code appears to be under the public domain. 11 | * I modified it removing the non needed functions and all the 12 | * 1960-style C coding stuff... 13 | * 14 | * ---------------------------------------------------------------------------- 15 | * 16 | * Copyright (c) 2010-2012, Salvatore Sanfilippo 17 | * All rights reserved. 18 | * 19 | * Redistribution and use in source and binary forms, with or without 20 | * modification, are permitted provided that the following conditions are met: 21 | * 22 | * * Redistributions of source code must retain the above copyright notice, 23 | * this list of conditions and the following disclaimer. 24 | * * Redistributions in binary form must reproduce the above copyright 25 | * notice, this list of conditions and the following disclaimer in the 26 | * documentation and/or other materials provided with the distribution. 27 | * * Neither the name of Redis nor the names of its contributors may be used 28 | * to endorse or promote products derived from this software without 29 | * specific prior written permission. 30 | * 31 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 32 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 33 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 34 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 35 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 36 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 37 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 38 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 39 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 40 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 41 | * POSSIBILITY OF SUCH DAMAGE. 42 | */ 43 | 44 | #include 45 | 46 | #define N 16 47 | #define MASK ((1 << (N - 1)) + (1 << (N - 1)) - 1) 48 | #define LOW(x) ((unsigned)(x) & MASK) 49 | #define HIGH(x) LOW((x) >> N) 50 | #define MUL(x, y, z) { int32_t l = (long)(x) * (long)(y); \ 51 | (z)[0] = LOW(l); (z)[1] = HIGH(l); } 52 | #define CARRY(x, y) ((int32_t)(x) + (long)(y) > MASK) 53 | #define ADDEQU(x, y, z) (z = CARRY(x, (y)), x = LOW(x + (y))) 54 | #define X0 0x330E 55 | #define X1 0xABCD 56 | #define X2 0x1234 57 | #define A0 0xE66D 58 | #define A1 0xDEEC 59 | #define A2 0x5 60 | #define C 0xB 61 | #define SET3(x, x0, x1, x2) ((x)[0] = (x0), (x)[1] = (x1), (x)[2] = (x2)) 62 | #define SETLOW(x, y, n) SET3(x, LOW((y)[n]), LOW((y)[(n)+1]), LOW((y)[(n)+2])) 63 | #define SEED(x0, x1, x2) (SET3(x, x0, x1, x2), SET3(a, A0, A1, A2), c = C) 64 | #define REST(v) for (i = 0; i < 3; i++) { xsubi[i] = x[i]; x[i] = temp[i]; } \ 65 | return (v); 66 | #define HI_BIT (1L << (2 * N - 1)) 67 | 68 | static uint32_t x[3] = { X0, X1, X2 }, a[3] = { A0, A1, A2 }, c = C; 69 | static void next(void); 70 | 71 | int32_t redisLrand48() { 72 | next(); 73 | return (((int32_t)x[2] << (N - 1)) + (x[1] >> 1)); 74 | } 75 | 76 | void redisSrand48(int32_t seedval) { 77 | SEED(X0, LOW(seedval), HIGH(seedval)); 78 | } 79 | 80 | static void next(void) { 81 | uint32_t p[2], q[2], r[2], carry0, carry1; 82 | 83 | MUL(a[0], x[0], p); 84 | ADDEQU(p[0], c, carry0); 85 | ADDEQU(p[1], carry0, carry1); 86 | MUL(a[0], x[1], q); 87 | ADDEQU(p[1], q[0], carry0); 88 | MUL(a[1], x[0], r); 89 | x[2] = LOW(carry0 + carry1 + CARRY(p[1], r[0]) + q[1] + r[1] + 90 | a[0] * x[2] + a[1] * x[1] + a[2] * x[0]); 91 | x[1] = LOW(p[1] + r[0]); 92 | x[0] = LOW(p[0]); 93 | } 94 | -------------------------------------------------------------------------------- /redis/redis-trib.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | def colorized(str, color) 4 | return str if !(ENV['TERM'] || '')["xterm"] 5 | color_code = { 6 | white: 29, 7 | bold: '29;1', 8 | black: 30, 9 | red: 31, 10 | green: 32, 11 | yellow: 33, 12 | blue: 34, 13 | magenta: 35, 14 | cyan: 36, 15 | gray: 37 16 | }[color] 17 | return str if !color_code 18 | "\033[#{color_code}m#{str}\033[0m" 19 | end 20 | 21 | class String 22 | 23 | %w(white bold black red green yellow blue magenta cyan gray).each{|color| 24 | color = :"#{color}" 25 | define_method(color){ 26 | colorized(self, color) 27 | } 28 | } 29 | 30 | end 31 | 32 | COMMANDS = %w(create check info fix reshard rebalance add-node 33 | del-node set-timeout call import help) 34 | 35 | ALLOWED_OPTIONS={ 36 | "create" => {"replicas" => true}, 37 | "add-node" => {"slave" => false, "master-id" => true}, 38 | "import" => {"from" => :required, "copy" => false, "replace" => false}, 39 | "reshard" => {"from" => true, "to" => true, "slots" => true, "yes" => false, "timeout" => true, "pipeline" => true}, 40 | "rebalance" => {"weight" => [], "auto-weights" => false, "use-empty-masters" => false, "timeout" => true, "simulate" => false, "pipeline" => true, "threshold" => true}, 41 | "fix" => {"timeout" => 0}, 42 | } 43 | 44 | def parse_options(cmd) 45 | cmd = cmd.downcase 46 | idx = 0 47 | options = {} 48 | args = [] 49 | while (arg = ARGV.shift) 50 | if arg[0..1] == "--" 51 | option = arg[2..-1] 52 | 53 | # --verbose is a global option 54 | if option == "--verbose" 55 | options['verbose'] = true 56 | next 57 | end 58 | if ALLOWED_OPTIONS[cmd] == nil || 59 | ALLOWED_OPTIONS[cmd][option] == nil 60 | next 61 | end 62 | if ALLOWED_OPTIONS[cmd][option] != false 63 | value = ARGV.shift 64 | next if !value 65 | else 66 | value = true 67 | end 68 | 69 | # If the option is set to [], it's a multiple arguments 70 | # option. We just queue every new value into an array. 71 | if ALLOWED_OPTIONS[cmd][option] == [] 72 | options[option] = [] if !options[option] 73 | options[option] << value 74 | else 75 | options[option] = value 76 | end 77 | else 78 | next if arg[0,1] == '-' 79 | args << arg 80 | end 81 | end 82 | 83 | return options,args 84 | end 85 | 86 | def command_example(cmd, args, opts) 87 | cmd = "redis-cli --cluster #{cmd}" 88 | args.each{|a| 89 | a = a.to_s 90 | a = a.inspect if a[' '] 91 | cmd << " #{a}" 92 | } 93 | opts.each{|opt, val| 94 | opt = " --cluster-#{opt.downcase}" 95 | if val != true 96 | val = val.join(' ') if val.is_a? Array 97 | opt << " #{val}" 98 | end 99 | cmd << opt 100 | } 101 | cmd 102 | end 103 | 104 | $command = ARGV.shift 105 | $opts, $args = parse_options($command) if $command 106 | 107 | puts "WARNING: redis-trib.rb is not longer available!".yellow 108 | puts "You should use #{'redis-cli'.bold} instead." 109 | puts '' 110 | puts "All commands and features belonging to redis-trib.rb "+ 111 | "have been moved\nto redis-cli." 112 | puts "In order to use them you should call redis-cli with the #{'--cluster'.bold}" 113 | puts "option followed by the subcommand name, arguments and options." 114 | puts '' 115 | puts "Use the following syntax:" 116 | puts "redis-cli --cluster SUBCOMMAND [ARGUMENTS] [OPTIONS]".bold 117 | puts '' 118 | puts "Example:" 119 | if $command 120 | example = command_example $command, $args, $opts 121 | else 122 | example = "redis-cli --cluster info 127.0.0.1:7000" 123 | end 124 | puts example.bold 125 | puts '' 126 | puts "To get help about all subcommands, type:" 127 | puts "redis-cli --cluster help".bold 128 | puts '' 129 | exit 1 130 | -------------------------------------------------------------------------------- /redis/latency.h: -------------------------------------------------------------------------------- 1 | /* latency.h -- latency monitor API header file 2 | * See latency.c for more information. 3 | * 4 | * ---------------------------------------------------------------------------- 5 | * 6 | * Copyright (c) 2014, Salvatore Sanfilippo 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without 10 | * modification, are permitted provided that the following conditions are met: 11 | * 12 | * * Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * * Redistributions in binary form must reproduce the above copyright 15 | * notice, this list of conditions and the following disclaimer in the 16 | * documentation and/or other materials provided with the distribution. 17 | * * Neither the name of Redis nor the names of its contributors may be used 18 | * to endorse or promote products derived from this software without 19 | * specific prior written permission. 20 | * 21 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 22 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 25 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 26 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 27 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 28 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 29 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 30 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 31 | * POSSIBILITY OF SUCH DAMAGE. 32 | */ 33 | 34 | #ifndef __LATENCY_H 35 | #define __LATENCY_H 36 | 37 | #define LATENCY_TS_LEN 160 /* History length for every monitored event. */ 38 | 39 | /* Representation of a latency sample: the sampling time and the latency 40 | * observed in milliseconds. */ 41 | struct latencySample { 42 | int32_t time; /* We don't use time_t to force 4 bytes usage everywhere. */ 43 | uint32_t latency; /* Latency in milliseconds. */ 44 | }; 45 | 46 | /* The latency time series for a given event. */ 47 | struct latencyTimeSeries { 48 | int idx; /* Index of the next sample to store. */ 49 | uint32_t max; /* Max latency observed for this event. */ 50 | struct latencySample samples[LATENCY_TS_LEN]; /* Latest history. */ 51 | }; 52 | 53 | /* Latency statistics structure. */ 54 | struct latencyStats { 55 | uint32_t all_time_high; /* Absolute max observed since latest reset. */ 56 | uint32_t avg; /* Average of current samples. */ 57 | uint32_t min; /* Min of current samples. */ 58 | uint32_t max; /* Max of current samples. */ 59 | uint32_t mad; /* Mean absolute deviation. */ 60 | uint32_t samples; /* Number of non-zero samples. */ 61 | time_t period; /* Number of seconds since first event and now. */ 62 | }; 63 | 64 | void latencyMonitorInit(void); 65 | void latencyAddSample(const char *event, mstime_t latency); 66 | int THPIsEnabled(void); 67 | 68 | /* Latency monitoring macros. */ 69 | 70 | /* Start monitoring an event. We just set the current time. */ 71 | #define latencyStartMonitor(var) if (server.latency_monitor_threshold) { \ 72 | var = mstime(); \ 73 | } else { \ 74 | var = 0; \ 75 | } 76 | 77 | /* End monitoring an event, compute the difference with the current time 78 | * to check the amount of time elapsed. */ 79 | #define latencyEndMonitor(var) if (server.latency_monitor_threshold) { \ 80 | var = mstime() - var; \ 81 | } 82 | 83 | /* Add the sample only if the elapsed time is >= to the configured threshold. */ 84 | #define latencyAddSampleIfNeeded(event,var) \ 85 | if (server.latency_monitor_threshold && \ 86 | (var) >= server.latency_monitor_threshold) \ 87 | latencyAddSample((event),(var)); 88 | 89 | /* Remove time from a nested event. */ 90 | #define latencyRemoveNestedEvent(event_var,nested_var) \ 91 | event_var += nested_var; 92 | 93 | #endif /* __LATENCY_H */ 94 | -------------------------------------------------------------------------------- /redis/ae_select.c: -------------------------------------------------------------------------------- 1 | /* Select()-based ae.c module. 2 | * 3 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | 32 | #include 33 | #include 34 | 35 | typedef struct aeApiState { 36 | fd_set rfds, wfds; 37 | /* We need to have a copy of the fd sets as it's not safe to reuse 38 | * FD sets after select(). */ 39 | fd_set _rfds, _wfds; 40 | } aeApiState; 41 | 42 | static int aeApiCreate(aeEventLoop *eventLoop) { 43 | aeApiState *state = zmalloc(sizeof(aeApiState)); 44 | 45 | if (!state) return -1; 46 | FD_ZERO(&state->rfds); 47 | FD_ZERO(&state->wfds); 48 | eventLoop->apidata = state; 49 | return 0; 50 | } 51 | 52 | static int aeApiResize(aeEventLoop *eventLoop, int setsize) { 53 | /* Just ensure we have enough room in the fd_set type. */ 54 | if (setsize >= FD_SETSIZE) return -1; 55 | return 0; 56 | } 57 | 58 | static void aeApiFree(aeEventLoop *eventLoop) { 59 | zfree(eventLoop->apidata); 60 | } 61 | 62 | static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { 63 | aeApiState *state = eventLoop->apidata; 64 | 65 | if (mask & AE_READABLE) FD_SET(fd,&state->rfds); 66 | if (mask & AE_WRITABLE) FD_SET(fd,&state->wfds); 67 | return 0; 68 | } 69 | 70 | static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) { 71 | aeApiState *state = eventLoop->apidata; 72 | 73 | if (mask & AE_READABLE) FD_CLR(fd,&state->rfds); 74 | if (mask & AE_WRITABLE) FD_CLR(fd,&state->wfds); 75 | } 76 | 77 | static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { 78 | aeApiState *state = eventLoop->apidata; 79 | int retval, j, numevents = 0; 80 | 81 | memcpy(&state->_rfds,&state->rfds,sizeof(fd_set)); 82 | memcpy(&state->_wfds,&state->wfds,sizeof(fd_set)); 83 | 84 | retval = select(eventLoop->maxfd+1, 85 | &state->_rfds,&state->_wfds,NULL,tvp); 86 | if (retval > 0) { 87 | for (j = 0; j <= eventLoop->maxfd; j++) { 88 | int mask = 0; 89 | aeFileEvent *fe = &eventLoop->events[j]; 90 | 91 | if (fe->mask == AE_NONE) continue; 92 | if (fe->mask & AE_READABLE && FD_ISSET(j,&state->_rfds)) 93 | mask |= AE_READABLE; 94 | if (fe->mask & AE_WRITABLE && FD_ISSET(j,&state->_wfds)) 95 | mask |= AE_WRITABLE; 96 | eventLoop->fired[numevents].fd = j; 97 | eventLoop->fired[numevents].mask = mask; 98 | numevents++; 99 | } 100 | } 101 | return numevents; 102 | } 103 | 104 | static char *aeApiName(void) { 105 | return "select"; 106 | } 107 | -------------------------------------------------------------------------------- /redis/endianconv.c: -------------------------------------------------------------------------------- 1 | /* endinconv.c -- Endian conversions utilities. 2 | * 3 | * This functions are never called directly, but always using the macros 4 | * defined into endianconv.h, this way we define everything is a non-operation 5 | * if the arch is already little endian. 6 | * 7 | * Redis tries to encode everything as little endian (but a few things that need 8 | * to be backward compatible are still in big endian) because most of the 9 | * production environments are little endian, and we have a lot of conversions 10 | * in a few places because ziplists, intsets, zipmaps, need to be endian-neutral 11 | * even in memory, since they are serialied on RDB files directly with a single 12 | * write(2) without other additional steps. 13 | * 14 | * ---------------------------------------------------------------------------- 15 | * 16 | * Copyright (c) 2011-2012, Salvatore Sanfilippo 17 | * All rights reserved. 18 | * 19 | * Redistribution and use in source and binary forms, with or without 20 | * modification, are permitted provided that the following conditions are met: 21 | * 22 | * * Redistributions of source code must retain the above copyright notice, 23 | * this list of conditions and the following disclaimer. 24 | * * Redistributions in binary form must reproduce the above copyright 25 | * notice, this list of conditions and the following disclaimer in the 26 | * documentation and/or other materials provided with the distribution. 27 | * * Neither the name of Redis nor the names of its contributors may be used 28 | * to endorse or promote products derived from this software without 29 | * specific prior written permission. 30 | * 31 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 32 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 33 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 34 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 35 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 36 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 37 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 38 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 39 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 40 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 41 | * POSSIBILITY OF SUCH DAMAGE. 42 | */ 43 | 44 | 45 | #include 46 | 47 | /* Toggle the 16 bit unsigned integer pointed by *p from little endian to 48 | * big endian */ 49 | void memrev16(void *p) { 50 | unsigned char *x = p, t; 51 | 52 | t = x[0]; 53 | x[0] = x[1]; 54 | x[1] = t; 55 | } 56 | 57 | /* Toggle the 32 bit unsigned integer pointed by *p from little endian to 58 | * big endian */ 59 | void memrev32(void *p) { 60 | unsigned char *x = p, t; 61 | 62 | t = x[0]; 63 | x[0] = x[3]; 64 | x[3] = t; 65 | t = x[1]; 66 | x[1] = x[2]; 67 | x[2] = t; 68 | } 69 | 70 | /* Toggle the 64 bit unsigned integer pointed by *p from little endian to 71 | * big endian */ 72 | void memrev64(void *p) { 73 | unsigned char *x = p, t; 74 | 75 | t = x[0]; 76 | x[0] = x[7]; 77 | x[7] = t; 78 | t = x[1]; 79 | x[1] = x[6]; 80 | x[6] = t; 81 | t = x[2]; 82 | x[2] = x[5]; 83 | x[5] = t; 84 | t = x[3]; 85 | x[3] = x[4]; 86 | x[4] = t; 87 | } 88 | 89 | uint16_t intrev16(uint16_t v) { 90 | memrev16(&v); 91 | return v; 92 | } 93 | 94 | uint32_t intrev32(uint32_t v) { 95 | memrev32(&v); 96 | return v; 97 | } 98 | 99 | uint64_t intrev64(uint64_t v) { 100 | memrev64(&v); 101 | return v; 102 | } 103 | 104 | #ifdef REDIS_TEST 105 | #include 106 | 107 | #define UNUSED(x) (void)(x) 108 | int endianconvTest(int argc, char *argv[]) { 109 | char buf[32]; 110 | 111 | UNUSED(argc); 112 | UNUSED(argv); 113 | 114 | sprintf(buf,"ciaoroma"); 115 | memrev16(buf); 116 | printf("%s\n", buf); 117 | 118 | sprintf(buf,"ciaoroma"); 119 | memrev32(buf); 120 | printf("%s\n", buf); 121 | 122 | sprintf(buf,"ciaoroma"); 123 | memrev64(buf); 124 | printf("%s\n", buf); 125 | 126 | return 0; 127 | } 128 | #endif 129 | -------------------------------------------------------------------------------- /redis/childinfo.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016, Salvatore Sanfilippo 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 | #include "server.h" 31 | #include 32 | 33 | /* Open a child-parent channel used in order to move information about the 34 | * RDB / AOF saving process from the child to the parent (for instance 35 | * the amount of copy on write memory used) */ 36 | void openChildInfoPipe(void) { 37 | //建立通道一个负责写,一个负责读,常用于父子或者兄弟线程通信 38 | if (pipe(server.child_info_pipe) == -1) { 39 | /* On error our two file descriptors should be still set to -1, 40 | * but we call anyway cloesChildInfoPipe() since can't hurt. */ 41 | closeChildInfoPipe(); 42 | } 43 | //设置非阻塞通道 44 | else if (anetNonBlock(NULL,server.child_info_pipe[0]) != ANET_OK) { 45 | closeChildInfoPipe(); 46 | } else { 47 | //初始化全部set0; 48 | memset(&server.child_info_data,0,sizeof(server.child_info_data)); 49 | } 50 | } 51 | 52 | /* Close the pipes opened with openChildInfoPipe(). */ 53 | void closeChildInfoPipe(void) { 54 | if (server.child_info_pipe[0] != -1 || 55 | server.child_info_pipe[1] != -1) 56 | { 57 | close(server.child_info_pipe[0]); 58 | close(server.child_info_pipe[1]); 59 | server.child_info_pipe[0] = -1; 60 | server.child_info_pipe[1] = -1; 61 | } 62 | } 63 | 64 | /* Send COW data to parent. The child should call this function after populating 65 | * the corresponding fields it want to sent (according to the process type). */ 66 | void sendChildInfo(int ptype) { 67 | if (server.child_info_pipe[1] == -1) return; 68 | //客户端魔术 69 | server.child_info_data.magic = CHILD_INFO_MAGIC; 70 | server.child_info_data.process_type = ptype; 71 | ssize_t wlen = sizeof(server.child_info_data); 72 | //通知到parent 端 73 | if (write(server.child_info_pipe[1],&server.child_info_data,wlen) != wlen) { 74 | /* Nothing to do on error, this will be detected by the other side. */ 75 | } 76 | } 77 | 78 | /* Receive COW data from parent. */ 79 | void receiveChildInfo(void) { 80 | if (server.child_info_pipe[0] == -1) return; 81 | ssize_t wlen = sizeof(server.child_info_data); 82 | if (read(server.child_info_pipe[0],&server.child_info_data,wlen) == wlen && 83 | server.child_info_data.magic == CHILD_INFO_MAGIC) 84 | { 85 | if (server.child_info_data.process_type == CHILD_INFO_TYPE_RDB) { 86 | //rdb 87 | server.stat_rdb_cow_bytes = server.child_info_data.cow_size; 88 | } else if (server.child_info_data.process_type == CHILD_INFO_TYPE_AOF) { 89 | //aof 90 | server.stat_aof_cow_bytes = server.child_info_data.cow_size; 91 | } else if (server.child_info_data.process_type == CHILD_INFO_TYPE_MODULE) { 92 | //其它module 逻辑 93 | server.stat_module_cow_bytes = server.child_info_data.cow_size; 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /redis/zmalloc.h: -------------------------------------------------------------------------------- 1 | /* zmalloc - total amount of allocated memory aware version of malloc() 2 | * 3 | * Copyright (c) 2009-2010, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #ifndef __ZMALLOC_H 32 | #define __ZMALLOC_H 33 | 34 | /* Double expansion needed for stringification of macro values. */ 35 | #define __xstr(s) __str(s) 36 | #define __str(s) #s 37 | 38 | #if defined(USE_TCMALLOC) 39 | #define ZMALLOC_LIB ("tcmalloc-" __xstr(TC_VERSION_MAJOR) "." __xstr(TC_VERSION_MINOR)) 40 | #include 41 | #if (TC_VERSION_MAJOR == 1 && TC_VERSION_MINOR >= 6) || (TC_VERSION_MAJOR > 1) 42 | #define HAVE_MALLOC_SIZE 1 43 | #define zmalloc_size(p) tc_malloc_size(p) 44 | #else 45 | #error "Newer version of tcmalloc required" 46 | #endif 47 | 48 | #elif defined(USE_JEMALLOC) 49 | #define ZMALLOC_LIB ("jemalloc-" __xstr(JEMALLOC_VERSION_MAJOR) "." __xstr(JEMALLOC_VERSION_MINOR) "." __xstr(JEMALLOC_VERSION_BUGFIX)) 50 | #include 51 | #if (JEMALLOC_VERSION_MAJOR == 2 && JEMALLOC_VERSION_MINOR >= 1) || (JEMALLOC_VERSION_MAJOR > 2) 52 | #define HAVE_MALLOC_SIZE 1 53 | #define zmalloc_size(p) je_malloc_usable_size(p) 54 | #else 55 | #error "Newer version of jemalloc required" 56 | #endif 57 | 58 | #elif defined(__APPLE__) 59 | #include 60 | #define HAVE_MALLOC_SIZE 1 61 | #define zmalloc_size(p) malloc_size(p) 62 | #endif 63 | 64 | #ifndef ZMALLOC_LIB 65 | #define ZMALLOC_LIB "libc" 66 | #ifdef __GLIBC__ 67 | #include 68 | #define HAVE_MALLOC_SIZE 1 69 | #define zmalloc_size(p) malloc_usable_size(p) 70 | #endif 71 | #endif 72 | 73 | /* We can enable the Redis defrag capabilities only if we are using Jemalloc 74 | * and the version used is our special version modified for Redis having 75 | * the ability to return per-allocation fragmentation hints. */ 76 | #if defined(USE_JEMALLOC) && defined(JEMALLOC_FRAG_HINT) 77 | #define HAVE_DEFRAG 78 | #endif 79 | 80 | void *zmalloc(size_t size); 81 | void *zcalloc(size_t size); 82 | void *zrealloc(void *ptr, size_t size); 83 | void zfree(void *ptr); 84 | char *zstrdup(const char *s); 85 | size_t zmalloc_used_memory(void); 86 | void zmalloc_set_oom_handler(void (*oom_handler)(size_t)); 87 | size_t zmalloc_get_rss(void); 88 | int zmalloc_get_allocator_info(size_t *allocated, size_t *active, size_t *resident); 89 | void set_jemalloc_bg_thread(int enable); 90 | int jemalloc_purge(); 91 | size_t zmalloc_get_private_dirty(long pid); 92 | size_t zmalloc_get_smap_bytes_by_field(char *field, long pid); 93 | size_t zmalloc_get_memory_size(void); 94 | void zlibc_free(void *ptr); 95 | 96 | #ifdef HAVE_DEFRAG 97 | void zfree_no_tcache(void *ptr); 98 | void *zmalloc_no_tcache(size_t size); 99 | #endif 100 | 101 | #ifndef HAVE_MALLOC_SIZE 102 | size_t zmalloc_size(void *ptr); 103 | size_t zmalloc_usable(void *ptr); 104 | #else 105 | #define zmalloc_usable(p) zmalloc_size(p) 106 | #endif 107 | 108 | #ifdef REDIS_TEST 109 | int zmalloc_test(int argc, char **argv); 110 | #endif 111 | 112 | #endif /* __ZMALLOC_H */ 113 | -------------------------------------------------------------------------------- /redis/setcpuaffinity.c: -------------------------------------------------------------------------------- 1 | /* ========================================================================== 2 | * setcpuaffinity.c - Linux/BSD setcpuaffinity. 3 | * -------------------------------------------------------------------------- 4 | * Copyright (C) 2020 zhenwei pi 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a 7 | * copy of this software and associated documentation files (the 8 | * "Software"), to deal in the Software without restriction, including 9 | * without limitation the rights to use, copy, modify, merge, publish, 10 | * distribute, sublicense, and/or sell copies of the Software, and to permit 11 | * persons to whom the Software is furnished to do so, subject to the 12 | * following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included 15 | * in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 20 | * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 21 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 22 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 23 | * USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | * ========================================================================== 25 | */ 26 | #ifndef _GNU_SOURCE 27 | #define _GNU_SOURCE 28 | #endif 29 | #include 30 | #include 31 | #include 32 | #ifdef __linux__ 33 | #include 34 | #endif 35 | #ifdef __FreeBSD__ 36 | #include 37 | #include 38 | #endif 39 | #ifdef __NetBSD__ 40 | #include 41 | #include 42 | #endif 43 | #include "config.h" 44 | 45 | #ifdef USE_SETCPUAFFINITY 46 | static const char *next_token(const char *q, int sep) { 47 | if (q) 48 | q = strchr(q, sep); 49 | if (q) 50 | q++; 51 | 52 | return q; 53 | } 54 | 55 | static int next_num(const char *str, char **end, int *result) { 56 | if (!str || *str == '\0' || !isdigit(*str)) 57 | return -1; 58 | 59 | *result = strtoul(str, end, 10); 60 | if (str == *end) 61 | return -1; 62 | 63 | return 0; 64 | } 65 | 66 | /* set current thread cpu affinity to cpu list, this function works like 67 | * taskset command (actually cpulist parsing logic reference to util-linux). 68 | * example of this function: "0,2,3", "0,2-3", "0-20:2". */ 69 | void setcpuaffinity(const char *cpulist) { 70 | const char *p, *q; 71 | char *end = NULL; 72 | #ifdef __linux__ 73 | cpu_set_t cpuset; 74 | #endif 75 | #ifdef __FreeBSD__ 76 | cpuset_t cpuset; 77 | #endif 78 | #ifdef __NetBSD__ 79 | cpuset_t *cpuset; 80 | #endif 81 | 82 | if (!cpulist) 83 | return; 84 | 85 | #ifndef __NetBSD__ 86 | CPU_ZERO(&cpuset); 87 | #else 88 | cpuset = cpuset_create(); 89 | #endif 90 | 91 | q = cpulist; 92 | while (p = q, q = next_token(q, ','), p) { 93 | int a, b, s; 94 | const char *c1, *c2; 95 | 96 | if (next_num(p, &end, &a) != 0) 97 | return; 98 | 99 | b = a; 100 | s = 1; 101 | p = end; 102 | 103 | c1 = next_token(p, '-'); 104 | c2 = next_token(p, ','); 105 | 106 | if (c1 != NULL && (c2 == NULL || c1 < c2)) { 107 | if (next_num(c1, &end, &b) != 0) 108 | return; 109 | 110 | c1 = end && *end ? next_token(end, ':') : NULL; 111 | if (c1 != NULL && (c2 == NULL || c1 < c2)) { 112 | if (next_num(c1, &end, &s) != 0) 113 | return; 114 | 115 | if (s == 0) 116 | return; 117 | } 118 | } 119 | 120 | if ((a > b)) 121 | return; 122 | 123 | while (a <= b) { 124 | #ifndef __NetBSD__ 125 | CPU_SET(a, &cpuset); 126 | #else 127 | cpuset_set(a, cpuset); 128 | #endif 129 | a += s; 130 | } 131 | } 132 | 133 | if (end && *end) 134 | return; 135 | 136 | #ifdef __linux__ 137 | sched_setaffinity(0, sizeof(cpuset), &cpuset); 138 | #endif 139 | #ifdef __FreeBSD__ 140 | cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(cpuset), &cpuset); 141 | #endif 142 | #ifdef __NetBSD__ 143 | pthread_setaffinity_np(pthread_self(), cpuset_size(cpuset), cpuset); 144 | cpuset_destroy(cpuset); 145 | #endif 146 | } 147 | 148 | #endif /* USE_SETCPUAFFINITY */ 149 | -------------------------------------------------------------------------------- /redis/geohash.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013-2014, yinqiwen 3 | * Copyright (c) 2014, Matt Stancliff . 4 | * Copyright (c) 2015, Salvatore Sanfilippo . 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * 10 | * * Redistributions of source code must retain the above copyright notice, 11 | * this list of conditions and the following disclaimer. 12 | * * Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * * Neither the name of Redis nor the names of its contributors may be used 16 | * to endorse or promote products derived from this software without 17 | * specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 23 | * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 29 | * THE POSSIBILITY OF SUCH DAMAGE. 30 | */ 31 | 32 | #ifndef GEOHASH_H_ 33 | #define GEOHASH_H_ 34 | 35 | #include 36 | #include 37 | #include 38 | 39 | #if defined(__cplusplus) 40 | extern "C" { 41 | #endif 42 | 43 | #define HASHISZERO(r) (!(r).bits && !(r).step) 44 | #define RANGEISZERO(r) (!(r).max && !(r).min) 45 | #define RANGEPISZERO(r) (r == NULL || RANGEISZERO(*r)) 46 | 47 | #define GEO_STEP_MAX 26 /* 26*2 = 52 bits. */ 48 | 49 | /* Limits from EPSG:900913 / EPSG:3785 / OSGEO:41001 */ 50 | #define GEO_LAT_MIN -85.05112878 51 | #define GEO_LAT_MAX 85.05112878 52 | #define GEO_LONG_MIN -180 53 | #define GEO_LONG_MAX 180 54 | 55 | typedef enum { 56 | GEOHASH_NORTH = 0, 57 | GEOHASH_EAST, 58 | GEOHASH_WEST, 59 | GEOHASH_SOUTH, 60 | GEOHASH_SOUTH_WEST, 61 | GEOHASH_SOUTH_EAST, 62 | GEOHASH_NORT_WEST, 63 | GEOHASH_NORT_EAST 64 | } GeoDirection; 65 | 66 | typedef struct { 67 | uint64_t bits; 68 | uint8_t step; 69 | } GeoHashBits; 70 | 71 | typedef struct { 72 | double min; 73 | double max; 74 | } GeoHashRange; 75 | 76 | typedef struct { 77 | GeoHashBits hash; 78 | GeoHashRange longitude; 79 | GeoHashRange latitude; 80 | } GeoHashArea; 81 | 82 | typedef struct { 83 | GeoHashBits north; 84 | GeoHashBits east; 85 | GeoHashBits west; 86 | GeoHashBits south; 87 | GeoHashBits north_east; 88 | GeoHashBits south_east; 89 | GeoHashBits north_west; 90 | GeoHashBits south_west; 91 | } GeoHashNeighbors; 92 | 93 | /* 94 | * 0:success 95 | * -1:failed 96 | */ 97 | void geohashGetCoordRange(GeoHashRange *long_range, GeoHashRange *lat_range); 98 | int geohashEncode(const GeoHashRange *long_range, const GeoHashRange *lat_range, 99 | double longitude, double latitude, uint8_t step, 100 | GeoHashBits *hash); 101 | int geohashEncodeType(double longitude, double latitude, 102 | uint8_t step, GeoHashBits *hash); 103 | int geohashEncodeWGS84(double longitude, double latitude, uint8_t step, 104 | GeoHashBits *hash); 105 | int geohashDecode(const GeoHashRange long_range, const GeoHashRange lat_range, 106 | const GeoHashBits hash, GeoHashArea *area); 107 | int geohashDecodeType(const GeoHashBits hash, GeoHashArea *area); 108 | int geohashDecodeWGS84(const GeoHashBits hash, GeoHashArea *area); 109 | int geohashDecodeAreaToLongLat(const GeoHashArea *area, double *xy); 110 | int geohashDecodeToLongLatType(const GeoHashBits hash, double *xy); 111 | int geohashDecodeToLongLatWGS84(const GeoHashBits hash, double *xy); 112 | int geohashDecodeToLongLatMercator(const GeoHashBits hash, double *xy); 113 | void geohashNeighbors(const GeoHashBits *hash, GeoHashNeighbors *neighbors); 114 | 115 | #if defined(__cplusplus) 116 | } 117 | #endif 118 | #endif /* GEOHASH_H_ */ 119 | -------------------------------------------------------------------------------- /redis/crc16.c: -------------------------------------------------------------------------------- 1 | #include "server.h" 2 | 3 | /* 4 | * Copyright 2001-2010 Georges Menie (www.menie.org) 5 | * Copyright 2010-2012 Salvatore Sanfilippo (adapted to Redis coding style) 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are met: 10 | * 11 | * * Redistributions of source code must retain the above copyright 12 | * notice, this list of conditions and the following disclaimer. 13 | * * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * * Neither the name of the University of California, Berkeley nor the 17 | * names of its contributors may be used to endorse or promote products 18 | * derived from this software without specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY 21 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 22 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY 24 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 25 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 26 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 27 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 29 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | */ 31 | 32 | /* CRC16 implementation according to CCITT standards. 33 | * 34 | * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the 35 | * following parameters: 36 | * 37 | * Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN" 38 | * Width : 16 bit 39 | * Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1) 40 | * Initialization : 0000 41 | * Reflect Input byte : False 42 | * Reflect Output CRC : False 43 | * Xor constant to output CRC : 0000 44 | * Output for "123456789" : 31C3 45 | */ 46 | 47 | static const uint16_t crc16tab[256]= { 48 | 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7, 49 | 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef, 50 | 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6, 51 | 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de, 52 | 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485, 53 | 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d, 54 | 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4, 55 | 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc, 56 | 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823, 57 | 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b, 58 | 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12, 59 | 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a, 60 | 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41, 61 | 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49, 62 | 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70, 63 | 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78, 64 | 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f, 65 | 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067, 66 | 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e, 67 | 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256, 68 | 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d, 69 | 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405, 70 | 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c, 71 | 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634, 72 | 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab, 73 | 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3, 74 | 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a, 75 | 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92, 76 | 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9, 77 | 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1, 78 | 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8, 79 | 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0 80 | }; 81 | 82 | uint16_t crc16(const char *buf, int len) { 83 | int counter; 84 | uint16_t crc = 0; 85 | for (counter = 0; counter < len; counter++) 86 | crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *buf++)&0x00FF]; 87 | return crc; 88 | } 89 | -------------------------------------------------------------------------------- /redis/lzf.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2000-2008 Marc Alexander Lehmann 3 | * 4 | * Redistribution and use in source and binary forms, with or without modifica- 5 | * tion, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * 10 | * 2. 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 | * 14 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 15 | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- 16 | * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 17 | * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- 18 | * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 19 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 20 | * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 21 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- 22 | * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 23 | * OF THE POSSIBILITY OF SUCH DAMAGE. 24 | * 25 | * Alternatively, the contents of this file may be used under the terms of 26 | * the GNU General Public License ("GPL") version 2 or any later version, 27 | * in which case the provisions of the GPL are applicable instead of 28 | * the above. If you wish to allow the use of your version of this file 29 | * only under the terms of the GPL and not to allow others to use your 30 | * version of this file under the BSD license, indicate your decision 31 | * by deleting the provisions above and replace them with the notice 32 | * and other provisions required by the GPL. If you do not delete the 33 | * provisions above, a recipient may use your version of this file under 34 | * either the BSD or the GPL. 35 | */ 36 | 37 | #ifndef LZF_H 38 | #define LZF_H 39 | 40 | /*********************************************************************** 41 | ** 42 | ** lzf -- an extremely fast/free compression/decompression-method 43 | ** http://liblzf.plan9.de/ 44 | ** 45 | ** This algorithm is believed to be patent-free. 46 | ** 47 | ***********************************************************************/ 48 | 49 | #define LZF_VERSION 0x0105 /* 1.5, API version */ 50 | 51 | /* 52 | * Compress in_len bytes stored at the memory block starting at 53 | * in_data and write the result to out_data, up to a maximum length 54 | * of out_len bytes. 55 | * 56 | * If the output buffer is not large enough or any error occurs return 0, 57 | * otherwise return the number of bytes used, which might be considerably 58 | * more than in_len (but less than 104% of the original size), so it 59 | * makes sense to always use out_len == in_len - 1), to ensure _some_ 60 | * compression, and store the data uncompressed otherwise (with a flag, of 61 | * course. 62 | * 63 | * lzf_compress might use different algorithms on different systems and 64 | * even different runs, thus might result in different compressed strings 65 | * depending on the phase of the moon or similar factors. However, all 66 | * these strings are architecture-independent and will result in the 67 | * original data when decompressed using lzf_decompress. 68 | * 69 | * The buffers must not be overlapping. 70 | * 71 | * If the option LZF_STATE_ARG is enabled, an extra argument must be 72 | * supplied which is not reflected in this header file. Refer to lzfP.h 73 | * and lzf_c.c. 74 | * 75 | */ 76 | unsigned int 77 | lzf_compress (const void *const in_data, unsigned int in_len, 78 | void *out_data, unsigned int out_len); 79 | 80 | /* 81 | * Decompress data compressed with some version of the lzf_compress 82 | * function and stored at location in_data and length in_len. The result 83 | * will be stored at out_data up to a maximum of out_len characters. 84 | * 85 | * If the output buffer is not large enough to hold the decompressed 86 | * data, a 0 is returned and errno is set to E2BIG. Otherwise the number 87 | * of decompressed bytes (i.e. the original length of the data) is 88 | * returned. 89 | * 90 | * If an error in the compressed data is detected, a zero is returned and 91 | * errno is set to EINVAL. 92 | * 93 | * This function is very fast, about as fast as a copying loop. 94 | */ 95 | unsigned int 96 | lzf_decompress (const void *const in_data, unsigned int in_len, 97 | void *out_data, unsigned int out_len); 98 | 99 | #endif 100 | 101 | -------------------------------------------------------------------------------- /redis/gopher.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, Salvatore Sanfilippo 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 | #include "server.h" 31 | 32 | /* Emit an item in Gopher directory listing format: 33 | * 34 | * If descr or selector are NULL, then the "(NULL)" string is used instead. */ 35 | void addReplyGopherItem(client *c, const char *type, const char *descr, 36 | const char *selector, const char *hostname, int port) 37 | { 38 | sds item = sdscatfmt(sdsempty(),"%s%s\t%s\t%s\t%i\r\n", 39 | type, descr, 40 | selector ? selector : "(NULL)", 41 | hostname ? hostname : "(NULL)", 42 | port); 43 | addReplyProto(c,item,sdslen(item)); 44 | sdsfree(item); 45 | } 46 | 47 | /* This is called by processInputBuffer() when an inline request is processed 48 | * with Gopher mode enabled, and the request happens to have zero or just one 49 | * argument. In such case we get the relevant key and reply using the Gopher 50 | * protocol. */ 51 | void processGopherRequest(client *c) { 52 | robj *keyname = c->argc == 0 ? createStringObject("/",1) : c->argv[0]; 53 | robj *o = lookupKeyRead(c->db,keyname); 54 | 55 | /* If there is no such key, return with a Gopher error. */ 56 | if (o == NULL || o->type != OBJ_STRING) { 57 | char *errstr; 58 | if (o == NULL) 59 | errstr = "Error: no content at the specified key"; 60 | else 61 | errstr = "Error: selected key type is invalid " 62 | "for Gopher output"; 63 | addReplyGopherItem(c,"i",errstr,NULL,NULL,0); 64 | addReplyGopherItem(c,"i","Redis Gopher server",NULL,NULL,0); 65 | } else { 66 | addReply(c,o); 67 | } 68 | 69 | /* Cleanup, also make sure to emit the final ".CRLF" line. Note that 70 | * the connection will be closed immediately after this because the client 71 | * will be flagged with CLIENT_CLOSE_AFTER_REPLY, in accordance with the 72 | * Gopher protocol. */ 73 | if (c->argc == 0) decrRefCount(keyname); 74 | 75 | /* Note that in theory we should terminate the Gopher request with 76 | * "." (called Lastline in the RFC) like that: 77 | * 78 | * addReplyProto(c,".\r\n",3); 79 | * 80 | * However after examining the current clients landscape, it's probably 81 | * going to do more harm than good for several reasons: 82 | * 83 | * 1. Clients should not have any issue with missing . as for 84 | * specification, and in the real world indeed certain servers 85 | * implementations never used to send the terminator. 86 | * 87 | * 2. Redis does not know if it's serving a text file or a binary file: 88 | * at the same time clients will not remove the "." bytes at 89 | * tne end when downloading a binary file from the server, so adding 90 | * the "Lastline" terminator without knowing the content is just 91 | * dangerous. 92 | * 93 | * 3. The utility gopher2redis.rb that we provide for Redis, and any 94 | * other similar tool you may use as Gopher authoring system for 95 | * Redis, can just add the "Lastline" when needed. 96 | */ 97 | } 98 | -------------------------------------------------------------------------------- /redis/ae_kqueue.c: -------------------------------------------------------------------------------- 1 | /* Kqueue(2)-based ae.c module 2 | * 3 | * Copyright (C) 2009 Harish Mallipeddi - harish.mallipeddi@gmail.com 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | typedef struct aeApiState { 37 | int kqfd; 38 | struct kevent *events; 39 | } aeApiState; 40 | 41 | static int aeApiCreate(aeEventLoop *eventLoop) { 42 | aeApiState *state = zmalloc(sizeof(aeApiState)); 43 | 44 | if (!state) return -1; 45 | state->events = zmalloc(sizeof(struct kevent)*eventLoop->setsize); 46 | if (!state->events) { 47 | zfree(state); 48 | return -1; 49 | } 50 | state->kqfd = kqueue(); 51 | if (state->kqfd == -1) { 52 | zfree(state->events); 53 | zfree(state); 54 | return -1; 55 | } 56 | eventLoop->apidata = state; 57 | return 0; 58 | } 59 | 60 | static int aeApiResize(aeEventLoop *eventLoop, int setsize) { 61 | aeApiState *state = eventLoop->apidata; 62 | 63 | state->events = zrealloc(state->events, sizeof(struct kevent)*setsize); 64 | return 0; 65 | } 66 | 67 | static void aeApiFree(aeEventLoop *eventLoop) { 68 | aeApiState *state = eventLoop->apidata; 69 | 70 | close(state->kqfd); 71 | zfree(state->events); 72 | zfree(state); 73 | } 74 | 75 | static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { 76 | aeApiState *state = eventLoop->apidata; 77 | struct kevent ke; 78 | 79 | if (mask & AE_READABLE) { 80 | EV_SET(&ke, fd, EVFILT_READ, EV_ADD, 0, 0, NULL); 81 | if (kevent(state->kqfd, &ke, 1, NULL, 0, NULL) == -1) return -1; 82 | } 83 | if (mask & AE_WRITABLE) { 84 | EV_SET(&ke, fd, EVFILT_WRITE, EV_ADD, 0, 0, NULL); 85 | if (kevent(state->kqfd, &ke, 1, NULL, 0, NULL) == -1) return -1; 86 | } 87 | return 0; 88 | } 89 | 90 | static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) { 91 | aeApiState *state = eventLoop->apidata; 92 | struct kevent ke; 93 | 94 | if (mask & AE_READABLE) { 95 | EV_SET(&ke, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); 96 | kevent(state->kqfd, &ke, 1, NULL, 0, NULL); 97 | } 98 | if (mask & AE_WRITABLE) { 99 | EV_SET(&ke, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); 100 | kevent(state->kqfd, &ke, 1, NULL, 0, NULL); 101 | } 102 | } 103 | 104 | static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { 105 | aeApiState *state = eventLoop->apidata; 106 | int retval, numevents = 0; 107 | 108 | if (tvp != NULL) { 109 | struct timespec timeout; 110 | timeout.tv_sec = tvp->tv_sec; 111 | timeout.tv_nsec = tvp->tv_usec * 1000; 112 | retval = kevent(state->kqfd, NULL, 0, state->events, eventLoop->setsize, 113 | &timeout); 114 | } else { 115 | retval = kevent(state->kqfd, NULL, 0, state->events, eventLoop->setsize, 116 | NULL); 117 | } 118 | 119 | if (retval > 0) { 120 | int j; 121 | 122 | numevents = retval; 123 | for(j = 0; j < numevents; j++) { 124 | int mask = 0; 125 | struct kevent *e = state->events+j; 126 | 127 | if (e->filter == EVFILT_READ) mask |= AE_READABLE; 128 | if (e->filter == EVFILT_WRITE) mask |= AE_WRITABLE; 129 | eventLoop->fired[j].fd = e->ident; 130 | eventLoop->fired[j].mask = mask; 131 | } 132 | } 133 | return numevents; 134 | } 135 | 136 | static char *aeApiName(void) { 137 | return "kqueue"; 138 | } 139 | -------------------------------------------------------------------------------- /redis/ae_epoll.c: -------------------------------------------------------------------------------- 1 | /* Linux epoll(2) based ae.c module 2 | * 3 | * Copyright (c) 2009-2012, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | 32 | #include 33 | 34 | typedef struct aeApiState { 35 | int epfd; 36 | struct epoll_event *events; 37 | } aeApiState; 38 | 39 | static int aeApiCreate(aeEventLoop *eventLoop) { 40 | aeApiState *state = zmalloc(sizeof(aeApiState)); 41 | 42 | if (!state) return -1; 43 | state->events = zmalloc(sizeof(struct epoll_event)*eventLoop->setsize); 44 | if (!state->events) { 45 | zfree(state); 46 | return -1; 47 | } 48 | state->epfd = epoll_create(1024); /* 1024 is just a hint for the kernel */ 49 | if (state->epfd == -1) { 50 | zfree(state->events); 51 | zfree(state); 52 | return -1; 53 | } 54 | eventLoop->apidata = state; 55 | return 0; 56 | } 57 | 58 | static int aeApiResize(aeEventLoop *eventLoop, int setsize) { 59 | aeApiState *state = eventLoop->apidata; 60 | 61 | state->events = zrealloc(state->events, sizeof(struct epoll_event)*setsize); 62 | return 0; 63 | } 64 | 65 | static void aeApiFree(aeEventLoop *eventLoop) { 66 | aeApiState *state = eventLoop->apidata; 67 | 68 | close(state->epfd); 69 | zfree(state->events); 70 | zfree(state); 71 | } 72 | 73 | static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { 74 | aeApiState *state = eventLoop->apidata; 75 | struct epoll_event ee = {0}; /* avoid valgrind warning */ 76 | /* If the fd was already monitored for some event, we need a MOD 77 | * operation. Otherwise we need an ADD operation. */ 78 | //判断当前文件描述符 是否已经被创建 79 | int op = eventLoop->events[fd].mask == AE_NONE ? 80 | EPOLL_CTL_ADD : EPOLL_CTL_MOD; 81 | 82 | ee.events = 0; 83 | mask |= eventLoop->events[fd].mask; /* Merge old events */ 84 | if (mask & AE_READABLE) ee.events |= EPOLLIN; 85 | if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; 86 | ee.data.fd = fd; 87 | //为这个fd 注册 epollin 或者 epollout 状态 88 | if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1; 89 | return 0; 90 | } 91 | 92 | static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int delmask) { 93 | aeApiState *state = eventLoop->apidata; 94 | struct epoll_event ee = {0}; /* avoid valgrind warning */ 95 | int mask = eventLoop->events[fd].mask & (~delmask); 96 | 97 | ee.events = 0; 98 | if (mask & AE_READABLE) ee.events |= EPOLLIN; 99 | if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; 100 | ee.data.fd = fd; 101 | if (mask != AE_NONE) { 102 | epoll_ctl(state->epfd,EPOLL_CTL_MOD,fd,&ee); 103 | } else { 104 | /* Note, Kernel < 2.6.9 requires a non null event pointer even for 105 | * EPOLL_CTL_DEL. */ 106 | epoll_ctl(state->epfd,EPOLL_CTL_DEL,fd,&ee); 107 | } 108 | } 109 | 110 | //通过epoll wait 拉到对应的可被读写的fd 111 | static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { 112 | aeApiState *state = eventLoop->apidata; 113 | int retval, numevents = 0; 114 | //通过这个方法拉取到可读可写的fd 115 | retval = epoll_wait(state->epfd,state->events,eventLoop->setsize, 116 | tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1); 117 | if (retval > 0) { 118 | int j; 119 | 120 | numevents = retval; 121 | for (j = 0; j < numevents; j++) { 122 | int mask = 0; 123 | struct epoll_event *e = state->events+j; 124 | //可以看到c语言常用位数来表示状态,这样的话多状态就可以表现出来了。 125 | if (e->events & EPOLLIN) mask |= AE_READABLE; 126 | if (e->events & EPOLLOUT) mask |= AE_WRITABLE; 127 | if (e->events & EPOLLERR) mask |= AE_WRITABLE|AE_READABLE; 128 | if (e->events & EPOLLHUP) mask |= AE_WRITABLE|AE_READABLE; 129 | eventLoop->fired[j].fd = e->data.fd; 130 | eventLoop->fired[j].mask = mask; 131 | } 132 | } 133 | return numevents; 134 | } 135 | 136 | static char *aeApiName(void) { 137 | return "epoll"; 138 | } 139 | -------------------------------------------------------------------------------- /redis/modules/hellocluster.c: -------------------------------------------------------------------------------- 1 | /* Helloworld cluster -- A ping/pong cluster API example. 2 | * 3 | * ----------------------------------------------------------------------------- 4 | * 5 | * Copyright (c) 2018, Salvatore Sanfilippo 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are met: 10 | * 11 | * * Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * * Neither the name of Redis nor the names of its contributors may be used 17 | * to endorse or promote products derived from this software without 18 | * specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #define REDISMODULE_EXPERIMENTAL_API 34 | #include "../redismodule.h" 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | #define MSGTYPE_PING 1 41 | #define MSGTYPE_PONG 2 42 | 43 | /* HELLOCLUSTER.PINGALL */ 44 | int PingallCommand_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 45 | REDISMODULE_NOT_USED(argv); 46 | REDISMODULE_NOT_USED(argc); 47 | 48 | RedisModule_SendClusterMessage(ctx,NULL,MSGTYPE_PING,(unsigned char*)"Hey",3); 49 | return RedisModule_ReplyWithSimpleString(ctx, "OK"); 50 | } 51 | 52 | /* HELLOCLUSTER.LIST */ 53 | int ListCommand_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 54 | REDISMODULE_NOT_USED(argv); 55 | REDISMODULE_NOT_USED(argc); 56 | 57 | size_t numnodes; 58 | char **ids = RedisModule_GetClusterNodesList(ctx,&numnodes); 59 | if (ids == NULL) { 60 | return RedisModule_ReplyWithError(ctx,"Cluster not enabled"); 61 | } 62 | 63 | RedisModule_ReplyWithArray(ctx,numnodes); 64 | for (size_t j = 0; j < numnodes; j++) { 65 | int port; 66 | RedisModule_GetClusterNodeInfo(ctx,ids[j],NULL,NULL,&port,NULL); 67 | RedisModule_ReplyWithArray(ctx,2); 68 | RedisModule_ReplyWithStringBuffer(ctx,ids[j],REDISMODULE_NODE_ID_LEN); 69 | RedisModule_ReplyWithLongLong(ctx,port); 70 | } 71 | RedisModule_FreeClusterNodesList(ids); 72 | return REDISMODULE_OK; 73 | } 74 | 75 | /* Callback for message MSGTYPE_PING */ 76 | void PingReceiver(RedisModuleCtx *ctx, const char *sender_id, uint8_t type, const unsigned char *payload, uint32_t len) { 77 | RedisModule_Log(ctx,"notice","PING (type %d) RECEIVED from %.*s: '%.*s'", 78 | type,REDISMODULE_NODE_ID_LEN,sender_id,(int)len, payload); 79 | RedisModule_SendClusterMessage(ctx,NULL,MSGTYPE_PONG,(unsigned char*)"Ohi!",4); 80 | RedisModule_Call(ctx, "INCR", "c", "pings_received"); 81 | } 82 | 83 | /* Callback for message MSGTYPE_PONG. */ 84 | void PongReceiver(RedisModuleCtx *ctx, const char *sender_id, uint8_t type, const unsigned char *payload, uint32_t len) { 85 | RedisModule_Log(ctx,"notice","PONG (type %d) RECEIVED from %.*s: '%.*s'", 86 | type,REDISMODULE_NODE_ID_LEN,sender_id,(int)len, payload); 87 | } 88 | 89 | /* This function must be present on each Redis module. It is used in order to 90 | * register the commands into the Redis server. */ 91 | int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 92 | REDISMODULE_NOT_USED(argv); 93 | REDISMODULE_NOT_USED(argc); 94 | 95 | if (RedisModule_Init(ctx,"hellocluster",1,REDISMODULE_APIVER_1) 96 | == REDISMODULE_ERR) return REDISMODULE_ERR; 97 | 98 | if (RedisModule_CreateCommand(ctx,"hellocluster.pingall", 99 | PingallCommand_RedisCommand,"readonly",0,0,0) == REDISMODULE_ERR) 100 | return REDISMODULE_ERR; 101 | 102 | if (RedisModule_CreateCommand(ctx,"hellocluster.list", 103 | ListCommand_RedisCommand,"readonly",0,0,0) == REDISMODULE_ERR) 104 | return REDISMODULE_ERR; 105 | 106 | /* Disable Redis Cluster sharding and redirections. This way every node 107 | * will be able to access every possible key, regardless of the hash slot. 108 | * This way the PING message handler will be able to increment a specific 109 | * variable. Normally you do that in order for the distributed system 110 | * you create as a module to have total freedom in the keyspace 111 | * manipulation. */ 112 | RedisModule_SetClusterFlags(ctx,REDISMODULE_CLUSTER_FLAG_NO_REDIRECTION); 113 | 114 | /* Register our handlers for different message types. */ 115 | RedisModule_RegisterClusterMessageReceiver(ctx,MSGTYPE_PING,PingReceiver); 116 | RedisModule_RegisterClusterMessageReceiver(ctx,MSGTYPE_PONG,PongReceiver); 117 | return REDISMODULE_OK; 118 | } 119 | -------------------------------------------------------------------------------- /redis/modules/hellodict.c: -------------------------------------------------------------------------------- 1 | /* Hellodict -- An example of modules dictionary API 2 | * 3 | * This module implements a volatile key-value store on top of the 4 | * dictionary exported by the Redis modules API. 5 | * 6 | * ----------------------------------------------------------------------------- 7 | * 8 | * Copyright (c) 2018, Salvatore Sanfilippo 9 | * All rights reserved. 10 | * 11 | * Redistribution and use in source and binary forms, with or without 12 | * modification, are permitted provided that the following conditions are met: 13 | * 14 | * * Redistributions of source code must retain the above copyright notice, 15 | * this list of conditions and the following disclaimer. 16 | * * Redistributions in binary form must reproduce the above copyright 17 | * notice, this list of conditions and the following disclaimer in the 18 | * documentation and/or other materials provided with the distribution. 19 | * * Neither the name of Redis nor the names of its contributors may be used 20 | * to endorse or promote products derived from this software without 21 | * specific prior written permission. 22 | * 23 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 24 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 25 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 26 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 27 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 28 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 29 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 30 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 31 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 32 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 33 | * POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | 36 | #define REDISMODULE_EXPERIMENTAL_API 37 | #include "../redismodule.h" 38 | #include 39 | #include 40 | #include 41 | #include 42 | 43 | static RedisModuleDict *Keyspace; 44 | 45 | /* HELLODICT.SET 46 | * 47 | * Set the specified key to the specified value. */ 48 | int cmd_SET(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 49 | if (argc != 3) return RedisModule_WrongArity(ctx); 50 | RedisModule_DictSet(Keyspace,argv[1],argv[2]); 51 | /* We need to keep a reference to the value stored at the key, otherwise 52 | * it would be freed when this callback returns. */ 53 | RedisModule_RetainString(NULL,argv[2]); 54 | return RedisModule_ReplyWithSimpleString(ctx, "OK"); 55 | } 56 | 57 | /* HELLODICT.GET 58 | * 59 | * Return the value of the specified key, or a null reply if the key 60 | * is not defined. */ 61 | int cmd_GET(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 62 | if (argc != 2) return RedisModule_WrongArity(ctx); 63 | RedisModuleString *val = RedisModule_DictGet(Keyspace,argv[1],NULL); 64 | if (val == NULL) { 65 | return RedisModule_ReplyWithNull(ctx); 66 | } else { 67 | return RedisModule_ReplyWithString(ctx, val); 68 | } 69 | } 70 | 71 | /* HELLODICT.KEYRANGE 72 | * 73 | * Return a list of matching keys, lexicographically between startkey 74 | * and endkey. No more than 'count' items are emitted. */ 75 | int cmd_KEYRANGE(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 76 | if (argc != 4) return RedisModule_WrongArity(ctx); 77 | 78 | /* Parse the count argument. */ 79 | long long count; 80 | if (RedisModule_StringToLongLong(argv[3],&count) != REDISMODULE_OK) { 81 | return RedisModule_ReplyWithError(ctx,"ERR invalid count"); 82 | } 83 | 84 | /* Seek the iterator. */ 85 | RedisModuleDictIter *iter = RedisModule_DictIteratorStart( 86 | Keyspace, ">=", argv[1]); 87 | 88 | /* Reply with the matching items. */ 89 | char *key; 90 | size_t keylen; 91 | long long replylen = 0; /* Keep track of the amitted array len. */ 92 | RedisModule_ReplyWithArray(ctx,REDISMODULE_POSTPONED_ARRAY_LEN); 93 | while((key = RedisModule_DictNextC(iter,&keylen,NULL)) != NULL) { 94 | if (replylen >= count) break; 95 | if (RedisModule_DictCompare(iter,"<=",argv[2]) == REDISMODULE_ERR) 96 | break; 97 | RedisModule_ReplyWithStringBuffer(ctx,key,keylen); 98 | replylen++; 99 | } 100 | RedisModule_ReplySetArrayLength(ctx,replylen); 101 | 102 | /* Cleanup. */ 103 | RedisModule_DictIteratorStop(iter); 104 | return REDISMODULE_OK; 105 | } 106 | 107 | /* This function must be present on each Redis module. It is used in order to 108 | * register the commands into the Redis server. */ 109 | int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { 110 | REDISMODULE_NOT_USED(argv); 111 | REDISMODULE_NOT_USED(argc); 112 | 113 | if (RedisModule_Init(ctx,"hellodict",1,REDISMODULE_APIVER_1) 114 | == REDISMODULE_ERR) return REDISMODULE_ERR; 115 | 116 | if (RedisModule_CreateCommand(ctx,"hellodict.set", 117 | cmd_SET,"write deny-oom",1,1,0) == REDISMODULE_ERR) 118 | return REDISMODULE_ERR; 119 | 120 | if (RedisModule_CreateCommand(ctx,"hellodict.get", 121 | cmd_GET,"readonly",1,1,0) == REDISMODULE_ERR) 122 | return REDISMODULE_ERR; 123 | 124 | if (RedisModule_CreateCommand(ctx,"hellodict.keyrange", 125 | cmd_KEYRANGE,"readonly",1,1,0) == REDISMODULE_ERR) 126 | return REDISMODULE_ERR; 127 | 128 | /* Create our global dictionray. Here we'll set our keys and values. */ 129 | Keyspace = RedisModule_CreateDict(NULL); 130 | 131 | return REDISMODULE_OK; 132 | } 133 | -------------------------------------------------------------------------------- /redis/atomicvar.h: -------------------------------------------------------------------------------- 1 | /* This file implements atomic counters using __atomic or __sync macros if 2 | * available, otherwise synchronizing different threads using a mutex. 3 | * 4 | * The exported interface is composed of three macros: 5 | * 6 | * atomicIncr(var,count) -- Increment the atomic counter 7 | * atomicGetIncr(var,oldvalue_var,count) -- Get and increment the atomic counter 8 | * atomicDecr(var,count) -- Decrement the atomic counter 9 | * atomicGet(var,dstvar) -- Fetch the atomic counter value 10 | * atomicSet(var,value) -- Set the atomic counter value 11 | * 12 | * The variable 'var' should also have a declared mutex with the same 13 | * name and the "_mutex" postfix, for instance: 14 | * 15 | * long myvar; 16 | * pthread_mutex_t myvar_mutex; 17 | * atomicSet(myvar,12345); 18 | * 19 | * If atomic primitives are available (tested in config.h) the mutex 20 | * is not used. 21 | * 22 | * Never use return value from the macros, instead use the AtomicGetIncr() 23 | * if you need to get the current value and increment it atomically, like 24 | * in the followign example: 25 | * 26 | * long oldvalue; 27 | * atomicGetIncr(myvar,oldvalue,1); 28 | * doSomethingWith(oldvalue); 29 | * 30 | * ---------------------------------------------------------------------------- 31 | * 32 | * Copyright (c) 2015, Salvatore Sanfilippo 33 | * All rights reserved. 34 | * 35 | * Redistribution and use in source and binary forms, with or without 36 | * modification, are permitted provided that the following conditions are met: 37 | * 38 | * * Redistributions of source code must retain the above copyright notice, 39 | * this list of conditions and the following disclaimer. 40 | * * Redistributions in binary form must reproduce the above copyright 41 | * notice, this list of conditions and the following disclaimer in the 42 | * documentation and/or other materials provided with the distribution. 43 | * * Neither the name of Redis nor the names of its contributors may be used 44 | * to endorse or promote products derived from this software without 45 | * specific prior written permission. 46 | * 47 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 48 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 49 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 50 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 51 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 52 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 53 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 54 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 55 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 56 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 57 | * POSSIBILITY OF SUCH DAMAGE. 58 | */ 59 | 60 | #include 61 | 62 | #ifndef __ATOMIC_VAR_H 63 | #define __ATOMIC_VAR_H 64 | 65 | /* To test Redis with Helgrind (a Valgrind tool) it is useful to define 66 | * the following macro, so that __sync macros are used: those can be detected 67 | * by Helgrind (even if they are less efficient) so that no false positive 68 | * is reported. */ 69 | // #define __ATOMIC_VAR_FORCE_SYNC_MACROS 70 | 71 | #if !defined(__ATOMIC_VAR_FORCE_SYNC_MACROS) && defined(__ATOMIC_RELAXED) && !defined(__sun) && (!defined(__clang__) || !defined(__APPLE__) || __apple_build_version__ > 4210057) 72 | /* Implementation using __atomic macros. */ 73 | 74 | #define atomicIncr(var,count) __atomic_add_fetch(&var,(count),__ATOMIC_RELAXED) 75 | #define atomicGetIncr(var,oldvalue_var,count) do { \ 76 | oldvalue_var = __atomic_fetch_add(&var,(count),__ATOMIC_RELAXED); \ 77 | } while(0) 78 | #define atomicDecr(var,count) __atomic_sub_fetch(&var,(count),__ATOMIC_RELAXED) 79 | #define atomicGet(var,dstvar) do { \ 80 | dstvar = __atomic_load_n(&var,__ATOMIC_RELAXED); \ 81 | } while(0) 82 | #define atomicSet(var,value) __atomic_store_n(&var,value,__ATOMIC_RELAXED) 83 | #define REDIS_ATOMIC_API "atomic-builtin" 84 | 85 | #elif defined(HAVE_ATOMIC) 86 | /* Implementation using __sync macros. */ 87 | 88 | #define atomicIncr(var,count) __sync_add_and_fetch(&var,(count)) 89 | #define atomicGetIncr(var,oldvalue_var,count) do { \ 90 | oldvalue_var = __sync_fetch_and_add(&var,(count)); \ 91 | } while(0) 92 | #define atomicDecr(var,count) __sync_sub_and_fetch(&var,(count)) 93 | #define atomicGet(var,dstvar) do { \ 94 | dstvar = __sync_sub_and_fetch(&var,0); \ 95 | } while(0) 96 | #define atomicSet(var,value) do { \ 97 | while(!__sync_bool_compare_and_swap(&var,var,value)); \ 98 | } while(0) 99 | #define REDIS_ATOMIC_API "sync-builtin" 100 | 101 | #else 102 | /* Implementation using pthread mutex. */ 103 | 104 | #define atomicIncr(var,count) do { \ 105 | pthread_mutex_lock(&var ## _mutex); \ 106 | var += (count); \ 107 | pthread_mutex_unlock(&var ## _mutex); \ 108 | } while(0) 109 | #define atomicGetIncr(var,oldvalue_var,count) do { \ 110 | pthread_mutex_lock(&var ## _mutex); \ 111 | oldvalue_var = var; \ 112 | var += (count); \ 113 | pthread_mutex_unlock(&var ## _mutex); \ 114 | } while(0) 115 | #define atomicDecr(var,count) do { \ 116 | pthread_mutex_lock(&var ## _mutex); \ 117 | var -= (count); \ 118 | pthread_mutex_unlock(&var ## _mutex); \ 119 | } while(0) 120 | #define atomicGet(var,dstvar) do { \ 121 | pthread_mutex_lock(&var ## _mutex); \ 122 | dstvar = var; \ 123 | pthread_mutex_unlock(&var ## _mutex); \ 124 | } while(0) 125 | #define atomicSet(var,value) do { \ 126 | pthread_mutex_lock(&var ## _mutex); \ 127 | var = value; \ 128 | pthread_mutex_unlock(&var ## _mutex); \ 129 | } while(0) 130 | #define REDIS_ATOMIC_API "pthread-mutex" 131 | 132 | #endif 133 | #endif /* __ATOMIC_VAR_H */ 134 | -------------------------------------------------------------------------------- /redis/sha256.c: -------------------------------------------------------------------------------- 1 | /********************************************************************* 2 | * Filename: sha256.c 3 | * Author: Brad Conte (brad AT bradconte.com) 4 | * Copyright: 5 | * Disclaimer: This code is presented "as is" without any guarantees. 6 | * Details: Implementation of the SHA-256 hashing algorithm. 7 | SHA-256 is one of the three algorithms in the SHA2 8 | specification. The others, SHA-384 and SHA-512, are not 9 | offered in this implementation. 10 | Algorithm specification can be found here: 11 | * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf 12 | This implementation uses little endian byte order. 13 | *********************************************************************/ 14 | 15 | /*************************** HEADER FILES ***************************/ 16 | #include 17 | #include 18 | #include "sha256.h" 19 | 20 | /****************************** MACROS ******************************/ 21 | #define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b)))) 22 | #define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b)))) 23 | 24 | #define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z))) 25 | #define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) 26 | #define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22)) 27 | #define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25)) 28 | #define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3)) 29 | #define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10)) 30 | 31 | /**************************** VARIABLES *****************************/ 32 | static const WORD k[64] = { 33 | 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 34 | 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 35 | 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 36 | 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 37 | 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 38 | 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 39 | 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 40 | 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 41 | }; 42 | 43 | /*********************** FUNCTION DEFINITIONS ***********************/ 44 | void sha256_transform(SHA256_CTX *ctx, const BYTE data[]) 45 | { 46 | WORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64]; 47 | 48 | for (i = 0, j = 0; i < 16; ++i, j += 4) 49 | m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]); 50 | for ( ; i < 64; ++i) 51 | m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; 52 | 53 | a = ctx->state[0]; 54 | b = ctx->state[1]; 55 | c = ctx->state[2]; 56 | d = ctx->state[3]; 57 | e = ctx->state[4]; 58 | f = ctx->state[5]; 59 | g = ctx->state[6]; 60 | h = ctx->state[7]; 61 | 62 | for (i = 0; i < 64; ++i) { 63 | t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; 64 | t2 = EP0(a) + MAJ(a,b,c); 65 | h = g; 66 | g = f; 67 | f = e; 68 | e = d + t1; 69 | d = c; 70 | c = b; 71 | b = a; 72 | a = t1 + t2; 73 | } 74 | 75 | ctx->state[0] += a; 76 | ctx->state[1] += b; 77 | ctx->state[2] += c; 78 | ctx->state[3] += d; 79 | ctx->state[4] += e; 80 | ctx->state[5] += f; 81 | ctx->state[6] += g; 82 | ctx->state[7] += h; 83 | } 84 | 85 | void sha256_init(SHA256_CTX *ctx) 86 | { 87 | ctx->datalen = 0; 88 | ctx->bitlen = 0; 89 | ctx->state[0] = 0x6a09e667; 90 | ctx->state[1] = 0xbb67ae85; 91 | ctx->state[2] = 0x3c6ef372; 92 | ctx->state[3] = 0xa54ff53a; 93 | ctx->state[4] = 0x510e527f; 94 | ctx->state[5] = 0x9b05688c; 95 | ctx->state[6] = 0x1f83d9ab; 96 | ctx->state[7] = 0x5be0cd19; 97 | } 98 | 99 | void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len) 100 | { 101 | WORD i; 102 | 103 | for (i = 0; i < len; ++i) { 104 | ctx->data[ctx->datalen] = data[i]; 105 | ctx->datalen++; 106 | if (ctx->datalen == 64) { 107 | sha256_transform(ctx, ctx->data); 108 | ctx->bitlen += 512; 109 | ctx->datalen = 0; 110 | } 111 | } 112 | } 113 | 114 | void sha256_final(SHA256_CTX *ctx, BYTE hash[]) 115 | { 116 | WORD i; 117 | 118 | i = ctx->datalen; 119 | 120 | // Pad whatever data is left in the buffer. 121 | if (ctx->datalen < 56) { 122 | ctx->data[i++] = 0x80; 123 | while (i < 56) 124 | ctx->data[i++] = 0x00; 125 | } 126 | else { 127 | ctx->data[i++] = 0x80; 128 | while (i < 64) 129 | ctx->data[i++] = 0x00; 130 | sha256_transform(ctx, ctx->data); 131 | memset(ctx->data, 0, 56); 132 | } 133 | 134 | // Append to the padding the total message's length in bits and transform. 135 | ctx->bitlen += ctx->datalen * 8; 136 | ctx->data[63] = ctx->bitlen; 137 | ctx->data[62] = ctx->bitlen >> 8; 138 | ctx->data[61] = ctx->bitlen >> 16; 139 | ctx->data[60] = ctx->bitlen >> 24; 140 | ctx->data[59] = ctx->bitlen >> 32; 141 | ctx->data[58] = ctx->bitlen >> 40; 142 | ctx->data[57] = ctx->bitlen >> 48; 143 | ctx->data[56] = ctx->bitlen >> 56; 144 | sha256_transform(ctx, ctx->data); 145 | 146 | // Since this implementation uses little endian byte ordering and SHA uses big endian, 147 | // reverse all the bytes when copying the final state to the output hash. 148 | for (i = 0; i < 4; ++i) { 149 | hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff; 150 | hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff; 151 | hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff; 152 | hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff; 153 | hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff; 154 | hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff; 155 | hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff; 156 | hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /redis/localtime.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Salvatore Sanfilippo 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 | #include 31 | 32 | /* This is a safe version of localtime() which contains no locks and is 33 | * fork() friendly. Even the _r version of localtime() cannot be used safely 34 | * in Redis. Another thread may be calling localtime() while the main thread 35 | * forks(). Later when the child process calls localtime() again, for instance 36 | * in order to log something to the Redis log, it may deadlock: in the copy 37 | * of the address space of the forked process the lock will never be released. 38 | * 39 | * This function takes the timezone 'tz' as argument, and the 'dst' flag is 40 | * used to check if daylight saving time is currently in effect. The caller 41 | * of this function should obtain such information calling tzset() ASAP in the 42 | * main() function to obtain the timezone offset from the 'timezone' global 43 | * variable. To obtain the daylight information, if it is currently active or not, 44 | * one trick is to call localtime() in main() ASAP as well, and get the 45 | * information from the tm_isdst field of the tm structure. However the daylight 46 | * time may switch in the future for long running processes, so this information 47 | * should be refreshed at safe times. 48 | * 49 | * Note that this function does not work for dates < 1/1/1970, it is solely 50 | * designed to work with what time(NULL) may return, and to support Redis 51 | * logging of the dates, it's not really a complete implementation. */ 52 | static int is_leap_year(time_t year) { 53 | if (year % 4) return 0; /* A year not divisible by 4 is not leap. */ 54 | else if (year % 100) return 1; /* If div by 4 and not 100 is surely leap. */ 55 | else if (year % 400) return 0; /* If div by 100 *and* not by 400 is not leap. */ 56 | else return 1; /* If div by 100 and 400 is leap. */ 57 | } 58 | 59 | void nolocks_localtime(struct tm *tmp, time_t t, time_t tz, int dst) { 60 | const time_t secs_min = 60; 61 | const time_t secs_hour = 3600; 62 | const time_t secs_day = 3600*24; 63 | 64 | t -= tz; /* Adjust for timezone. */ 65 | t += 3600*dst; /* Adjust for daylight time. */ 66 | time_t days = t / secs_day; /* Days passed since epoch. */ 67 | time_t seconds = t % secs_day; /* Remaining seconds. */ 68 | 69 | tmp->tm_isdst = dst; 70 | tmp->tm_hour = seconds / secs_hour; 71 | tmp->tm_min = (seconds % secs_hour) / secs_min; 72 | tmp->tm_sec = (seconds % secs_hour) % secs_min; 73 | 74 | /* 1/1/1970 was a Thursday, that is, day 4 from the POV of the tm structure 75 | * where sunday = 0, so to calculate the day of the week we have to add 4 76 | * and take the modulo by 7. */ 77 | tmp->tm_wday = (days+4)%7; 78 | 79 | /* Calculate the current year. */ 80 | tmp->tm_year = 1970; 81 | while(1) { 82 | /* Leap years have one day more. */ 83 | time_t days_this_year = 365 + is_leap_year(tmp->tm_year); 84 | if (days_this_year > days) break; 85 | days -= days_this_year; 86 | tmp->tm_year++; 87 | } 88 | tmp->tm_yday = days; /* Number of day of the current year. */ 89 | 90 | /* We need to calculate in which month and day of the month we are. To do 91 | * so we need to skip days according to how many days there are in each 92 | * month, and adjust for the leap year that has one more day in February. */ 93 | int mdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 94 | mdays[1] += is_leap_year(tmp->tm_year); 95 | 96 | tmp->tm_mon = 0; 97 | while(days >= mdays[tmp->tm_mon]) { 98 | days -= mdays[tmp->tm_mon]; 99 | tmp->tm_mon++; 100 | } 101 | 102 | tmp->tm_mday = days+1; /* Add 1 since our 'days' is zero-based. */ 103 | tmp->tm_year -= 1900; /* Surprisingly tm_year is year-1900. */ 104 | } 105 | 106 | #ifdef LOCALTIME_TEST_MAIN 107 | #include 108 | 109 | int main(void) { 110 | /* Obtain timezone and daylight info. */ 111 | tzset(); /* Now 'timezome' global is populated. */ 112 | time_t t = time(NULL); 113 | struct tm *aux = localtime(&t); 114 | int daylight_active = aux->tm_isdst; 115 | 116 | struct tm tm; 117 | char buf[1024]; 118 | 119 | nolocks_localtime(&tm,t,timezone,daylight_active); 120 | strftime(buf,sizeof(buf),"%d %b %H:%M:%S",&tm); 121 | printf("[timezone: %d, dl: %d] %s\n", (int)timezone, (int)daylight_active, buf); 122 | } 123 | #endif 124 | -------------------------------------------------------------------------------- /redis/syncio.c: -------------------------------------------------------------------------------- 1 | /* Synchronous socket and file I/O operations useful across the core. 2 | * 3 | * Copyright (c) 2009-2010, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the name of Redis nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #include "server.h" 32 | 33 | /* ----------------- Blocking sockets I/O with timeouts --------------------- */ 34 | 35 | /* Redis performs most of the I/O in a nonblocking way, with the exception 36 | * of the SYNC command where the slave does it in a blocking way, and 37 | * the MIGRATE command that must be blocking in order to be atomic from the 38 | * point of view of the two instances (one migrating the key and one receiving 39 | * the key). This is why need the following blocking I/O functions. 40 | * 41 | * All the functions take the timeout in milliseconds. */ 42 | 43 | #define SYNCIO__RESOLUTION 10 /* Resolution in milliseconds */ 44 | 45 | /* Write the specified payload to 'fd'. If writing the whole payload will be 46 | * done within 'timeout' milliseconds the operation succeeds and 'size' is 47 | * returned. Otherwise the operation fails, -1 is returned, and an unspecified 48 | * partial write could be performed against the file descriptor. */ 49 | ssize_t syncWrite(int fd, char *ptr, ssize_t size, long long timeout) { 50 | ssize_t nwritten, ret = size; 51 | long long start = mstime(); 52 | long long remaining = timeout; 53 | 54 | while(1) { 55 | long long wait = (remaining > SYNCIO__RESOLUTION) ? 56 | remaining : SYNCIO__RESOLUTION; 57 | long long elapsed; 58 | 59 | /* Optimistically try to write before checking if the file descriptor 60 | * is actually writable. At worst we get EAGAIN. */ 61 | nwritten = write(fd,ptr,size); 62 | if (nwritten == -1) { 63 | if (errno != EAGAIN) return -1; 64 | } else { 65 | ptr += nwritten; 66 | size -= nwritten; 67 | } 68 | if (size == 0) return ret; 69 | 70 | /* Wait */ 71 | aeWait(fd,AE_WRITABLE,wait); 72 | elapsed = mstime() - start; 73 | if (elapsed >= timeout) { 74 | errno = ETIMEDOUT; 75 | return -1; 76 | } 77 | remaining = timeout - elapsed; 78 | } 79 | } 80 | 81 | /* Read the specified amount of bytes from 'fd'. If all the bytes are read 82 | * within 'timeout' milliseconds the operation succeed and 'size' is returned. 83 | * Otherwise the operation fails, -1 is returned, and an unspecified amount of 84 | * data could be read from the file descriptor. */ 85 | ssize_t syncRead(int fd, char *ptr, ssize_t size, long long timeout) { 86 | ssize_t nread, totread = 0; 87 | long long start = mstime(); 88 | long long remaining = timeout; 89 | 90 | if (size == 0) return 0; 91 | while(1) { 92 | long long wait = (remaining > SYNCIO__RESOLUTION) ? 93 | remaining : SYNCIO__RESOLUTION; 94 | long long elapsed; 95 | 96 | /* Optimistically try to read before checking if the file descriptor 97 | * is actually readable. At worst we get EAGAIN. */ 98 | nread = read(fd,ptr,size); 99 | if (nread == 0) return -1; /* short read. */ 100 | if (nread == -1) { 101 | if (errno != EAGAIN) return -1; 102 | } else { 103 | ptr += nread; 104 | size -= nread; 105 | totread += nread; 106 | } 107 | if (size == 0) return totread; 108 | 109 | /* Wait */ 110 | aeWait(fd,AE_READABLE,wait); 111 | elapsed = mstime() - start; 112 | if (elapsed >= timeout) { 113 | errno = ETIMEDOUT; 114 | return -1; 115 | } 116 | remaining = timeout - elapsed; 117 | } 118 | } 119 | 120 | /* Read a line making sure that every char will not require more than 'timeout' 121 | * milliseconds to be read. 122 | * 123 | * On success the number of bytes read is returned, otherwise -1. 124 | * On success the string is always correctly terminated with a 0 byte. */ 125 | ssize_t syncReadLine(int fd, char *ptr, ssize_t size, long long timeout) { 126 | ssize_t nread = 0; 127 | 128 | size--; 129 | while(size) { 130 | char c; 131 | 132 | if (syncRead(fd,&c,1,timeout) == -1) return -1; 133 | if (c == '\n') { 134 | *ptr = '\0'; 135 | if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0'; 136 | return nread; 137 | } else { 138 | *ptr++ = c; 139 | *ptr = '\0'; 140 | nread++; 141 | } 142 | size--; 143 | } 144 | return nread; 145 | } 146 | -------------------------------------------------------------------------------- /redis/ae.h: -------------------------------------------------------------------------------- 1 | /* A simple event-driven programming library. Originally I wrote this code 2 | * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated 3 | * it in form of a library for easy reuse. 4 | * 5 | * Copyright (c) 2006-2012, Salvatore Sanfilippo 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions are met: 10 | * 11 | * * Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * * Neither the name of Redis nor the names of its contributors may be used 17 | * to endorse or promote products derived from this software without 18 | * specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #ifndef __AE_H__ 34 | #define __AE_H__ 35 | 36 | #include 37 | 38 | #define AE_OK 0 39 | #define AE_ERR -1 40 | 41 | #define AE_NONE 0 /* No events registered. */ 42 | #define AE_READABLE 1 /* Fire when descriptor is readable. */ 43 | #define AE_WRITABLE 2 /* Fire when descriptor is writable. */ 44 | #define AE_BARRIER 4 /* With WRITABLE, never fire the event if the 45 | READABLE event already fired in the same event 46 | loop iteration. Useful when you want to persist 47 | things to disk before sending replies, and want 48 | to do that in a group fashion. */ 49 | 50 | #define AE_FILE_EVENTS (1<<0) 51 | #define AE_TIME_EVENTS (1<<1) 52 | #define AE_ALL_EVENTS (AE_FILE_EVENTS|AE_TIME_EVENTS) 53 | #define AE_DONT_WAIT (1<<2) 54 | #define AE_CALL_BEFORE_SLEEP (1<<3) 55 | #define AE_CALL_AFTER_SLEEP (1<<4) 56 | 57 | #define AE_NOMORE -1 58 | #define AE_DELETED_EVENT_ID -1 59 | 60 | /* Macros */ 61 | #define AE_NOTUSED(V) ((void) V) 62 | 63 | struct aeEventLoop; 64 | 65 | /* Types and data structures */ 66 | typedef void aeFileProc(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask); 67 | typedef int aeTimeProc(struct aeEventLoop *eventLoop, long long id, void *clientData); 68 | typedef void aeEventFinalizerProc(struct aeEventLoop *eventLoop, void *clientData); 69 | typedef void aeBeforeSleepProc(struct aeEventLoop *eventLoop); 70 | 71 | /* File event structure */ 72 | typedef struct aeFileEvent { 73 | //主要分为可读事件, 可写事件,BARRIER 74 | int mask; /* one of AE_(READABLE|WRITABLE|BARRIER) */ 75 | 76 | aeFileProc *rfileProc; 77 | aeFileProc *wfileProc; 78 | void *clientData; 79 | } aeFileEvent; 80 | 81 | /* Time event structure */ 82 | typedef struct aeTimeEvent { 83 | long long id; /* time event identifier. */ 84 | long when_sec; /* seconds */ 85 | long when_ms; /* milliseconds */ 86 | aeTimeProc *timeProc; 87 | aeEventFinalizerProc *finalizerProc; 88 | void *clientData; 89 | struct aeTimeEvent *prev; 90 | struct aeTimeEvent *next; 91 | int refcount; /* refcount to prevent timer events from being 92 | * freed in recursive time event calls. */ 93 | } aeTimeEvent; 94 | 95 | /* A fired event */ 96 | typedef struct aeFiredEvent { 97 | int fd; 98 | int mask; 99 | } aeFiredEvent; 100 | 101 | /* State of an event based program */ 102 | typedef struct aeEventLoop { 103 | int maxfd; /* highest file descriptor currently registered */ 104 | int setsize; /* max number of file descriptors tracked */ 105 | long long timeEventNextId; 106 | time_t lastTime; /* Used to detect system clock skew */ 107 | //已经注册的文件事件(主要和网络io挂钩的) 108 | aeFileEvent *events; /* Registered events */ 109 | aeFiredEvent *fired; /* Fired events */ 110 | aeTimeEvent *timeEventHead; 111 | int stop; 112 | void *apidata; /* This is used for polling API specific data */ 113 | aeBeforeSleepProc *beforesleep; 114 | aeBeforeSleepProc *aftersleep; 115 | int flags; 116 | } aeEventLoop; 117 | 118 | /* Prototypes */ 119 | aeEventLoop *aeCreateEventLoop(int setsize); 120 | void aeDeleteEventLoop(aeEventLoop *eventLoop); 121 | void aeStop(aeEventLoop *eventLoop); 122 | int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, 123 | aeFileProc *proc, void *clientData); 124 | void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask); 125 | int aeGetFileEvents(aeEventLoop *eventLoop, int fd); 126 | long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, 127 | aeTimeProc *proc, void *clientData, 128 | aeEventFinalizerProc *finalizerProc); 129 | int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id); 130 | int aeProcessEvents(aeEventLoop *eventLoop, int flags); 131 | int aeWait(int fd, int mask, long long milliseconds); 132 | void aeMain(aeEventLoop *eventLoop); 133 | char *aeGetApiName(void); 134 | void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep); 135 | void aeSetAfterSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *aftersleep); 136 | int aeGetSetSize(aeEventLoop *eventLoop); 137 | int aeResizeSetSize(aeEventLoop *eventLoop, int setsize); 138 | void aeSetDontWait(aeEventLoop *eventLoop, int noWait); 139 | 140 | #endif 141 | -------------------------------------------------------------------------------- /redis/pqsort.c: -------------------------------------------------------------------------------- 1 | /* The following is the NetBSD libc qsort implementation modified in order to 2 | * support partial sorting of ranges for Redis. 3 | * 4 | * Copyright(C) 2009-2012 Salvatore Sanfilippo. All rights reserved. 5 | * 6 | * The original copyright notice follows. */ 7 | 8 | 9 | /* $NetBSD: qsort.c,v 1.19 2009/01/30 23:38:44 lukem Exp $ */ 10 | 11 | /*- 12 | * Copyright (c) 1992, 1993 13 | * The Regents of the University of California. All rights reserved. 14 | * 15 | * Redistribution and use in source and binary forms, with or without 16 | * modification, are permitted provided that the following conditions 17 | * are met: 18 | * 1. Redistributions of source code must retain the above copyright 19 | * notice, this list of conditions and the following disclaimer. 20 | * 2. Redistributions in binary form must reproduce the above copyright 21 | * notice, this list of conditions and the following disclaimer in the 22 | * documentation and/or other materials provided with the distribution. 23 | * 3. Neither the name of the University nor the names of its contributors 24 | * may be used to endorse or promote products derived from this software 25 | * without specific prior written permission. 26 | * 27 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 28 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 29 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 30 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 31 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 32 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 33 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 34 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 35 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 36 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 37 | * SUCH DAMAGE. 38 | */ 39 | 40 | #include 41 | 42 | #include 43 | #include 44 | 45 | static inline char *med3 (char *, char *, char *, 46 | int (*)(const void *, const void *)); 47 | static inline void swapfunc (char *, char *, size_t, int); 48 | 49 | #define min(a, b) (a) < (b) ? a : b 50 | 51 | /* 52 | * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function". 53 | */ 54 | #define swapcode(TYPE, parmi, parmj, n) { \ 55 | size_t i = (n) / sizeof (TYPE); \ 56 | TYPE *pi = (TYPE *)(void *)(parmi); \ 57 | TYPE *pj = (TYPE *)(void *)(parmj); \ 58 | do { \ 59 | TYPE t = *pi; \ 60 | *pi++ = *pj; \ 61 | *pj++ = t; \ 62 | } while (--i > 0); \ 63 | } 64 | 65 | #define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \ 66 | es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1; 67 | 68 | static inline void 69 | swapfunc(char *a, char *b, size_t n, int swaptype) 70 | { 71 | 72 | if (swaptype <= 1) 73 | swapcode(long, a, b, n) 74 | else 75 | swapcode(char, a, b, n) 76 | } 77 | 78 | #define swap(a, b) \ 79 | if (swaptype == 0) { \ 80 | long t = *(long *)(void *)(a); \ 81 | *(long *)(void *)(a) = *(long *)(void *)(b); \ 82 | *(long *)(void *)(b) = t; \ 83 | } else \ 84 | swapfunc(a, b, es, swaptype) 85 | 86 | #define vecswap(a, b, n) if ((n) > 0) swapfunc((a), (b), (size_t)(n), swaptype) 87 | 88 | static inline char * 89 | med3(char *a, char *b, char *c, 90 | int (*cmp) (const void *, const void *)) 91 | { 92 | 93 | return cmp(a, b) < 0 ? 94 | (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a )) 95 | :(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c )); 96 | } 97 | 98 | static void 99 | _pqsort(void *a, size_t n, size_t es, 100 | int (*cmp) (const void *, const void *), void *lrange, void *rrange) 101 | { 102 | char *pa, *pb, *pc, *pd, *pl, *pm, *pn; 103 | size_t d, r; 104 | int swaptype, cmp_result; 105 | 106 | loop: SWAPINIT(a, es); 107 | if (n < 7) { 108 | for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es) 109 | for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0; 110 | pl -= es) 111 | swap(pl, pl - es); 112 | return; 113 | } 114 | pm = (char *) a + (n / 2) * es; 115 | if (n > 7) { 116 | pl = (char *) a; 117 | pn = (char *) a + (n - 1) * es; 118 | if (n > 40) { 119 | d = (n / 8) * es; 120 | pl = med3(pl, pl + d, pl + 2 * d, cmp); 121 | pm = med3(pm - d, pm, pm + d, cmp); 122 | pn = med3(pn - 2 * d, pn - d, pn, cmp); 123 | } 124 | pm = med3(pl, pm, pn, cmp); 125 | } 126 | swap(a, pm); 127 | pa = pb = (char *) a + es; 128 | 129 | pc = pd = (char *) a + (n - 1) * es; 130 | for (;;) { 131 | while (pb <= pc && (cmp_result = cmp(pb, a)) <= 0) { 132 | if (cmp_result == 0) { 133 | swap(pa, pb); 134 | pa += es; 135 | } 136 | pb += es; 137 | } 138 | while (pb <= pc && (cmp_result = cmp(pc, a)) >= 0) { 139 | if (cmp_result == 0) { 140 | swap(pc, pd); 141 | pd -= es; 142 | } 143 | pc -= es; 144 | } 145 | if (pb > pc) 146 | break; 147 | swap(pb, pc); 148 | pb += es; 149 | pc -= es; 150 | } 151 | 152 | pn = (char *) a + n * es; 153 | r = min(pa - (char *) a, pb - pa); 154 | vecswap(a, pb - r, r); 155 | r = min((size_t)(pd - pc), pn - pd - es); 156 | vecswap(pb, pn - r, r); 157 | if ((r = pb - pa) > es) { 158 | void *_l = a, *_r = ((unsigned char*)a)+r-1; 159 | if (!((lrange < _l && rrange < _l) || 160 | (lrange > _r && rrange > _r))) 161 | _pqsort(a, r / es, es, cmp, lrange, rrange); 162 | } 163 | if ((r = pd - pc) > es) { 164 | void *_l, *_r; 165 | 166 | /* Iterate rather than recurse to save stack space */ 167 | a = pn - r; 168 | n = r / es; 169 | 170 | _l = a; 171 | _r = ((unsigned char*)a)+r-1; 172 | if (!((lrange < _l && rrange < _l) || 173 | (lrange > _r && rrange > _r))) 174 | goto loop; 175 | } 176 | /* qsort(pn - r, r / es, es, cmp);*/ 177 | } 178 | 179 | void 180 | pqsort(void *a, size_t n, size_t es, 181 | int (*cmp) (const void *, const void *), size_t lrange, size_t rrange) 182 | { 183 | _pqsort(a,n,es,cmp,((unsigned char*)a)+(lrange*es), 184 | ((unsigned char*)a)+((rrange+1)*es)-1); 185 | } 186 | -------------------------------------------------------------------------------- /redis/notify.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013, Salvatore Sanfilippo 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 | #include "server.h" 31 | 32 | /* This file implements keyspace events notification via Pub/Sub and 33 | * described at https://redis.io/topics/notifications. */ 34 | 35 | /* Turn a string representing notification classes into an integer 36 | * representing notification classes flags xored. 37 | * 38 | * The function returns -1 if the input contains characters not mapping to 39 | * any class. */ 40 | int keyspaceEventsStringToFlags(char *classes) { 41 | char *p = classes; 42 | int c, flags = 0; 43 | 44 | while((c = *p++) != '\0') { 45 | switch(c) { 46 | case 'A': flags |= NOTIFY_ALL; break; 47 | case 'g': flags |= NOTIFY_GENERIC; break; 48 | case '$': flags |= NOTIFY_STRING; break; 49 | case 'l': flags |= NOTIFY_LIST; break; 50 | case 's': flags |= NOTIFY_SET; break; 51 | case 'h': flags |= NOTIFY_HASH; break; 52 | case 'z': flags |= NOTIFY_ZSET; break; 53 | case 'x': flags |= NOTIFY_EXPIRED; break; 54 | case 'e': flags |= NOTIFY_EVICTED; break; 55 | case 'K': flags |= NOTIFY_KEYSPACE; break; 56 | case 'E': flags |= NOTIFY_KEYEVENT; break; 57 | case 't': flags |= NOTIFY_STREAM; break; 58 | case 'm': flags |= NOTIFY_KEY_MISS; break; 59 | default: return -1; 60 | } 61 | } 62 | return flags; 63 | } 64 | 65 | /* This function does exactly the revese of the function above: it gets 66 | * as input an integer with the xored flags and returns a string representing 67 | * the selected classes. The string returned is an sds string that needs to 68 | * be released with sdsfree(). */ 69 | sds keyspaceEventsFlagsToString(int flags) { 70 | sds res; 71 | 72 | res = sdsempty(); 73 | if ((flags & NOTIFY_ALL) == NOTIFY_ALL) { 74 | res = sdscatlen(res,"A",1); 75 | } else { 76 | if (flags & NOTIFY_GENERIC) res = sdscatlen(res,"g",1); 77 | if (flags & NOTIFY_STRING) res = sdscatlen(res,"$",1); 78 | if (flags & NOTIFY_LIST) res = sdscatlen(res,"l",1); 79 | if (flags & NOTIFY_SET) res = sdscatlen(res,"s",1); 80 | if (flags & NOTIFY_HASH) res = sdscatlen(res,"h",1); 81 | if (flags & NOTIFY_ZSET) res = sdscatlen(res,"z",1); 82 | if (flags & NOTIFY_EXPIRED) res = sdscatlen(res,"x",1); 83 | if (flags & NOTIFY_EVICTED) res = sdscatlen(res,"e",1); 84 | if (flags & NOTIFY_STREAM) res = sdscatlen(res,"t",1); 85 | } 86 | if (flags & NOTIFY_KEYSPACE) res = sdscatlen(res,"K",1); 87 | if (flags & NOTIFY_KEYEVENT) res = sdscatlen(res,"E",1); 88 | if (flags & NOTIFY_KEY_MISS) res = sdscatlen(res,"m",1); 89 | return res; 90 | } 91 | 92 | /* The API provided to the rest of the Redis core is a simple function: 93 | * 94 | * notifyKeyspaceEvent(char *event, robj *key, int dbid); 95 | * 96 | * 'event' is a C string representing the event name. 97 | * 'key' is a Redis object representing the key name. 98 | * 'dbid' is the database ID where the key lives. */ 99 | void notifyKeyspaceEvent(int type, char *event, robj *key, int dbid) { 100 | sds chan; 101 | robj *chanobj, *eventobj; 102 | int len = -1; 103 | char buf[24]; 104 | 105 | /* If any modules are interested in events, notify the module system now. 106 | * This bypasses the notifications configuration, but the module engine 107 | * will only call event subscribers if the event type matches the types 108 | * they are interested in. */ 109 | moduleNotifyKeyspaceEvent(type, event, key, dbid); 110 | 111 | /* If notifications for this class of events are off, return ASAP. */ 112 | if (!(server.notify_keyspace_events & type)) return; 113 | 114 | eventobj = createStringObject(event,strlen(event)); 115 | 116 | /* __keyspace@__: notifications. */ 117 | if (server.notify_keyspace_events & NOTIFY_KEYSPACE) { 118 | chan = sdsnewlen("__keyspace@",11); 119 | len = ll2string(buf,sizeof(buf),dbid); 120 | chan = sdscatlen(chan, buf, len); 121 | chan = sdscatlen(chan, "__:", 3); 122 | chan = sdscatsds(chan, key->ptr); 123 | chanobj = createObject(OBJ_STRING, chan); 124 | pubsubPublishMessage(chanobj, eventobj); 125 | decrRefCount(chanobj); 126 | } 127 | 128 | /* __keyevent@__: notifications. */ 129 | if (server.notify_keyspace_events & NOTIFY_KEYEVENT) { 130 | chan = sdsnewlen("__keyevent@",11); 131 | if (len == -1) len = ll2string(buf,sizeof(buf),dbid); 132 | chan = sdscatlen(chan, buf, len); 133 | chan = sdscatlen(chan, "__:", 3); 134 | chan = sdscatsds(chan, eventobj->ptr); 135 | chanobj = createObject(OBJ_STRING, chan); 136 | pubsubPublishMessage(chanobj, key); 137 | decrRefCount(chanobj); 138 | } 139 | decrRefCount(eventobj); 140 | } 141 | -------------------------------------------------------------------------------- /redis/stream.h: -------------------------------------------------------------------------------- 1 | #ifndef STREAM_H 2 | #define STREAM_H 3 | 4 | #include "rax.h" 5 | #include "listpack.h" 6 | 7 | /* Stream item ID: a 128 bit number composed of a milliseconds time and 8 | * a sequence counter. IDs generated in the same millisecond (or in a past 9 | * millisecond if the clock jumped backward) will use the millisecond time 10 | * of the latest generated ID and an incremented sequence. */ 11 | typedef struct streamID { 12 | uint64_t ms; /* Unix time in milliseconds. */ 13 | uint64_t seq; /* Sequence number. */ 14 | } streamID; 15 | 16 | typedef struct stream { 17 | rax *rax; /* The radix tree holding the stream. */ 18 | uint64_t length; /* Number of elements inside this stream. */ 19 | streamID last_id; /* Zero if there are yet no items. */ 20 | rax *cgroups; /* Consumer groups dictionary: name -> streamCG */ 21 | } stream; 22 | 23 | /* We define an iterator to iterate stream items in an abstract way, without 24 | * caring about the radix tree + listpack representation. Technically speaking 25 | * the iterator is only used inside streamReplyWithRange(), so could just 26 | * be implemented inside the function, but practically there is the AOF 27 | * rewriting code that also needs to iterate the stream to emit the XADD 28 | * commands. */ 29 | typedef struct streamIterator { 30 | stream *stream; /* The stream we are iterating. */ 31 | streamID master_id; /* ID of the master entry at listpack head. */ 32 | uint64_t master_fields_count; /* Master entries # of fields. */ 33 | unsigned char *master_fields_start; /* Master entries start in listpack. */ 34 | unsigned char *master_fields_ptr; /* Master field to emit next. */ 35 | int entry_flags; /* Flags of entry we are emitting. */ 36 | int rev; /* True if iterating end to start (reverse). */ 37 | uint64_t start_key[2]; /* Start key as 128 bit big endian. */ 38 | uint64_t end_key[2]; /* End key as 128 bit big endian. */ 39 | raxIterator ri; /* Rax iterator. */ 40 | unsigned char *lp; /* Current listpack. */ 41 | unsigned char *lp_ele; /* Current listpack cursor. */ 42 | unsigned char *lp_flags; /* Current entry flags pointer. */ 43 | /* Buffers used to hold the string of lpGet() when the element is 44 | * integer encoded, so that there is no string representation of the 45 | * element inside the listpack itself. */ 46 | unsigned char field_buf[LP_INTBUF_SIZE]; 47 | unsigned char value_buf[LP_INTBUF_SIZE]; 48 | } streamIterator; 49 | 50 | /* Consumer group. */ 51 | typedef struct streamCG { 52 | streamID last_id; /* Last delivered (not acknowledged) ID for this 53 | group. Consumers that will just ask for more 54 | messages will served with IDs > than this. */ 55 | rax *pel; /* Pending entries list. This is a radix tree that 56 | has every message delivered to consumers (without 57 | the NOACK option) that was yet not acknowledged 58 | as processed. The key of the radix tree is the 59 | ID as a 64 bit big endian number, while the 60 | associated value is a streamNACK structure.*/ 61 | rax *consumers; /* A radix tree representing the consumers by name 62 | and their associated representation in the form 63 | of streamConsumer structures. */ 64 | } streamCG; 65 | 66 | /* A specific consumer in a consumer group. */ 67 | typedef struct streamConsumer { 68 | mstime_t seen_time; /* Last time this consumer was active. */ 69 | sds name; /* Consumer name. This is how the consumer 70 | will be identified in the consumer group 71 | protocol. Case sensitive. */ 72 | rax *pel; /* Consumer specific pending entries list: all 73 | the pending messages delivered to this 74 | consumer not yet acknowledged. Keys are 75 | big endian message IDs, while values are 76 | the same streamNACK structure referenced 77 | in the "pel" of the conumser group structure 78 | itself, so the value is shared. */ 79 | } streamConsumer; 80 | 81 | /* Pending (yet not acknowledged) message in a consumer group. */ 82 | typedef struct streamNACK { 83 | mstime_t delivery_time; /* Last time this message was delivered. */ 84 | uint64_t delivery_count; /* Number of times this message was delivered.*/ 85 | streamConsumer *consumer; /* The consumer this message was delivered to 86 | in the last delivery. */ 87 | } streamNACK; 88 | 89 | /* Stream propagation informations, passed to functions in order to propagate 90 | * XCLAIM commands to AOF and slaves. */ 91 | typedef struct streamPropInfo { 92 | robj *keyname; 93 | robj *groupname; 94 | } streamPropInfo; 95 | 96 | /* Prototypes of exported APIs. */ 97 | struct client; 98 | 99 | /* Flags for streamLookupConsumer */ 100 | #define SLC_NONE 0 101 | #define SLC_NOCREAT (1<<0) /* Do not create the consumer if it doesn't exist */ 102 | #define SLC_NOREFRESH (1<<1) /* Do not update consumer's seen-time */ 103 | 104 | stream *streamNew(void); 105 | void freeStream(stream *s); 106 | unsigned long streamLength(const robj *subject); 107 | size_t streamReplyWithRange(client *c, stream *s, streamID *start, streamID *end, size_t count, int rev, streamCG *group, streamConsumer *consumer, int flags, streamPropInfo *spi); 108 | void streamIteratorStart(streamIterator *si, stream *s, streamID *start, streamID *end, int rev); 109 | int streamIteratorGetID(streamIterator *si, streamID *id, int64_t *numfields); 110 | void streamIteratorGetField(streamIterator *si, unsigned char **fieldptr, unsigned char **valueptr, int64_t *fieldlen, int64_t *valuelen); 111 | void streamIteratorStop(streamIterator *si); 112 | streamCG *streamLookupCG(stream *s, sds groupname); 113 | streamConsumer *streamLookupConsumer(streamCG *cg, sds name, int flags); 114 | streamCG *streamCreateCG(stream *s, char *name, size_t namelen, streamID *id); 115 | streamNACK *streamCreateNACK(streamConsumer *consumer); 116 | void streamDecodeID(void *buf, streamID *id); 117 | int streamCompareID(streamID *a, streamID *b); 118 | void streamFreeNACK(streamNACK *na); 119 | void streamIncrID(streamID *id); 120 | 121 | #endif 122 | -------------------------------------------------------------------------------- /redis/lzfP.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2000-2007 Marc Alexander Lehmann 3 | * 4 | * Redistribution and use in source and binary forms, with or without modifica- 5 | * tion, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, 8 | * this list of conditions and the following disclaimer. 9 | * 10 | * 2. 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 | * 14 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 15 | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- 16 | * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 17 | * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- 18 | * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 19 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 20 | * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 21 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- 22 | * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 23 | * OF THE POSSIBILITY OF SUCH DAMAGE. 24 | * 25 | * Alternatively, the contents of this file may be used under the terms of 26 | * the GNU General Public License ("GPL") version 2 or any later version, 27 | * in which case the provisions of the GPL are applicable instead of 28 | * the above. If you wish to allow the use of your version of this file 29 | * only under the terms of the GPL and not to allow others to use your 30 | * version of this file under the BSD license, indicate your decision 31 | * by deleting the provisions above and replace them with the notice 32 | * and other provisions required by the GPL. If you do not delete the 33 | * provisions above, a recipient may use your version of this file under 34 | * either the BSD or the GPL. 35 | */ 36 | 37 | #ifndef LZFP_h 38 | #define LZFP_h 39 | 40 | #define STANDALONE 1 /* at the moment, this is ok. */ 41 | 42 | #ifndef STANDALONE 43 | # include "lzf.h" 44 | #endif 45 | 46 | /* 47 | * Size of hashtable is (1 << HLOG) * sizeof (char *) 48 | * decompression is independent of the hash table size 49 | * the difference between 15 and 14 is very small 50 | * for small blocks (and 14 is usually a bit faster). 51 | * For a low-memory/faster configuration, use HLOG == 13; 52 | * For best compression, use 15 or 16 (or more, up to 22). 53 | */ 54 | #ifndef HLOG 55 | # define HLOG 16 56 | #endif 57 | 58 | /* 59 | * Sacrifice very little compression quality in favour of compression speed. 60 | * This gives almost the same compression as the default code, and is 61 | * (very roughly) 15% faster. This is the preferred mode of operation. 62 | */ 63 | #ifndef VERY_FAST 64 | # define VERY_FAST 1 65 | #endif 66 | 67 | /* 68 | * Sacrifice some more compression quality in favour of compression speed. 69 | * (roughly 1-2% worse compression for large blocks and 70 | * 9-10% for small, redundant, blocks and >>20% better speed in both cases) 71 | * In short: when in need for speed, enable this for binary data, 72 | * possibly disable this for text data. 73 | */ 74 | #ifndef ULTRA_FAST 75 | # define ULTRA_FAST 0 76 | #endif 77 | 78 | /* 79 | * Unconditionally aligning does not cost very much, so do it if unsure 80 | */ 81 | #ifndef STRICT_ALIGN 82 | # if !(defined(__i386) || defined (__amd64)) 83 | # define STRICT_ALIGN 1 84 | # else 85 | # define STRICT_ALIGN 0 86 | # endif 87 | #endif 88 | 89 | /* 90 | * You may choose to pre-set the hash table (might be faster on some 91 | * modern cpus and large (>>64k) blocks, and also makes compression 92 | * deterministic/repeatable when the configuration otherwise is the same). 93 | */ 94 | #ifndef INIT_HTAB 95 | # define INIT_HTAB 0 96 | #endif 97 | 98 | /* 99 | * Avoid assigning values to errno variable? for some embedding purposes 100 | * (linux kernel for example), this is necessary. NOTE: this breaks 101 | * the documentation in lzf.h. Avoiding errno has no speed impact. 102 | */ 103 | #ifndef AVOID_ERRNO 104 | # define AVOID_ERRNO 0 105 | #endif 106 | 107 | /* 108 | * Whether to pass the LZF_STATE variable as argument, or allocate it 109 | * on the stack. For small-stack environments, define this to 1. 110 | * NOTE: this breaks the prototype in lzf.h. 111 | */ 112 | #ifndef LZF_STATE_ARG 113 | # define LZF_STATE_ARG 0 114 | #endif 115 | 116 | /* 117 | * Whether to add extra checks for input validity in lzf_decompress 118 | * and return EINVAL if the input stream has been corrupted. This 119 | * only shields against overflowing the input buffer and will not 120 | * detect most corrupted streams. 121 | * This check is not normally noticeable on modern hardware 122 | * (<1% slowdown), but might slow down older cpus considerably. 123 | */ 124 | #ifndef CHECK_INPUT 125 | # define CHECK_INPUT 1 126 | #endif 127 | 128 | /* 129 | * Whether to store pointers or offsets inside the hash table. On 130 | * 64 bit architetcures, pointers take up twice as much space, 131 | * and might also be slower. Default is to autodetect. 132 | */ 133 | /*#define LZF_USER_OFFSETS autodetect */ 134 | 135 | /*****************************************************************************/ 136 | /* nothing should be changed below */ 137 | 138 | #ifdef __cplusplus 139 | # include 140 | # include 141 | using namespace std; 142 | #else 143 | # include 144 | # include 145 | #endif 146 | 147 | #ifndef LZF_USE_OFFSETS 148 | # if defined (WIN32) 149 | # define LZF_USE_OFFSETS defined(_M_X64) 150 | # else 151 | # if __cplusplus > 199711L 152 | # include 153 | # else 154 | # include 155 | # endif 156 | # define LZF_USE_OFFSETS (UINTPTR_MAX > 0xffffffffU) 157 | # endif 158 | #endif 159 | 160 | typedef unsigned char u8; 161 | 162 | #if LZF_USE_OFFSETS 163 | # define LZF_HSLOT_BIAS ((const u8 *)in_data) 164 | typedef unsigned int LZF_HSLOT; 165 | #else 166 | # define LZF_HSLOT_BIAS 0 167 | typedef const u8 *LZF_HSLOT; 168 | #endif 169 | 170 | typedef LZF_HSLOT LZF_STATE[1 << (HLOG)]; 171 | 172 | #if !STRICT_ALIGN 173 | /* for unaligned accesses we need a 16 bit datatype. */ 174 | # if USHRT_MAX == 65535 175 | typedef unsigned short u16; 176 | # elif UINT_MAX == 65535 177 | typedef unsigned int u16; 178 | # else 179 | # undef STRICT_ALIGN 180 | # define STRICT_ALIGN 1 181 | # endif 182 | #endif 183 | 184 | #if ULTRA_FAST 185 | # undef VERY_FAST 186 | #endif 187 | 188 | #endif 189 | 190 | --------------------------------------------------------------------------------