hiredis.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*
  2. * Copyright (c) 2009-2011, Salvatore Sanfilippo <antirez at gmail dot com>
  3. * Copyright (c) 2010-2014, Pieter Noordhuis <pcnoordhuis at gmail dot com>
  4. * Copyright (c) 2015, Matt Stancliff <matt at genges dot com>,
  5. * Jan-Erik Rediger <janerik at fnordig dot com>
  6. *
  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. #ifndef __HIREDIS_H
  34. #define __HIREDIS_H
  35. #include "read.h"
  36. #include <stdarg.h> /* for va_list */
  37. #ifndef _MSC_VER
  38. #include <sys/time.h> /* for struct timeval */
  39. #else
  40. struct timeval; /* forward declaration */
  41. typedef long long ssize_t;
  42. #endif
  43. #include <stdint.h> /* uintXX_t, etc */
  44. #include "sds.h" /* for hisds */
  45. #include "alloc.h" /* for allocation wrappers */
  46. #define HIREDIS_MAJOR 1
  47. #define HIREDIS_MINOR 0
  48. #define HIREDIS_PATCH 0
  49. #define HIREDIS_SONAME 1.0.0
  50. /* Connection type can be blocking or non-blocking and is set in the
  51. * least significant bit of the flags field in redisContext. */
  52. #define REDIS_BLOCK 0x1
  53. /* Connection may be disconnected before being free'd. The second bit
  54. * in the flags field is set when the context is connected. */
  55. #define REDIS_CONNECTED 0x2
  56. /* The async API might try to disconnect cleanly and flush the output
  57. * buffer and read all subsequent replies before disconnecting.
  58. * This flag means no new commands can come in and the connection
  59. * should be terminated once all replies have been read. */
  60. #define REDIS_DISCONNECTING 0x4
  61. /* Flag specific to the async API which means that the context should be clean
  62. * up as soon as possible. */
  63. #define REDIS_FREEING 0x8
  64. /* Flag that is set when an async callback is executed. */
  65. #define REDIS_IN_CALLBACK 0x10
  66. /* Flag that is set when the async context has one or more subscriptions. */
  67. #define REDIS_SUBSCRIBED 0x20
  68. /* Flag that is set when monitor mode is active */
  69. #define REDIS_MONITORING 0x40
  70. /* Flag that is set when we should set SO_REUSEADDR before calling bind() */
  71. #define REDIS_REUSEADDR 0x80
  72. /**
  73. * Flag that indicates the user does not want the context to
  74. * be automatically freed upon error
  75. */
  76. #define REDIS_NO_AUTO_FREE 0x200
  77. #define REDIS_KEEPALIVE_INTERVAL 15 /* seconds */
  78. /* number of times we retry to connect in the case of EADDRNOTAVAIL and
  79. * SO_REUSEADDR is being used. */
  80. #define REDIS_CONNECT_RETRIES 10
  81. /* Forward declarations for structs defined elsewhere */
  82. struct redisAsyncContext;
  83. struct redisContext;
  84. /* RESP3 push helpers and callback prototypes */
  85. #define redisIsPushReply(r) (((redisReply*)(r))->type == REDIS_REPLY_PUSH)
  86. typedef void (redisPushFn)(void *, void *);
  87. typedef void (redisAsyncPushFn)(struct redisAsyncContext *, void *);
  88. #ifdef __cplusplus
  89. extern "C" {
  90. #endif
  91. /* This is the reply object returned by redisCommand() */
  92. typedef struct redisReply {
  93. int type; /* REDIS_REPLY_* */
  94. long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
  95. double dval; /* The double when type is REDIS_REPLY_DOUBLE */
  96. size_t len; /* Length of string */
  97. char *str; /* Used for REDIS_REPLY_ERROR, REDIS_REPLY_STRING
  98. REDIS_REPLY_VERB, and REDIS_REPLY_DOUBLE (in additional to dval). */
  99. char vtype[4]; /* Used for REDIS_REPLY_VERB, contains the null
  100. terminated 3 character content type, such as "txt". */
  101. size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
  102. struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
  103. } redisReply;
  104. redisReader *redisReaderCreate(void);
  105. /* Function to free the reply objects hiredis returns by default. */
  106. void freeReplyObject(void *reply);
  107. /* Functions to format a command according to the protocol. */
  108. int redisvFormatCommand(char **target, const char *format, va_list ap);
  109. int redisFormatCommand(char **target, const char *format, ...);
  110. int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen);
  111. int redisFormatSdsCommandArgv(hisds *target, int argc, const char ** argv, const size_t *argvlen);
  112. void redisFreeCommand(char *cmd);
  113. void redisFreeSdsCommand(hisds cmd);
  114. enum redisConnectionType {
  115. REDIS_CONN_TCP,
  116. REDIS_CONN_UNIX,
  117. REDIS_CONN_USERFD
  118. };
  119. struct redisSsl;
  120. #define REDIS_OPT_NONBLOCK 0x01
  121. #define REDIS_OPT_REUSEADDR 0x02
  122. /**
  123. * Don't automatically free the async object on a connection failure,
  124. * or other implicit conditions. Only free on an explicit call to disconnect() or free()
  125. */
  126. #define REDIS_OPT_NOAUTOFREE 0x04
  127. /* Don't automatically intercept and free RESP3 PUSH replies. */
  128. #define REDIS_OPT_NO_PUSH_AUTOFREE 0x08
  129. /* In Unix systems a file descriptor is a regular signed int, with -1
  130. * representing an invalid descriptor. In Windows it is a SOCKET
  131. * (32- or 64-bit unsigned integer depending on the architecture), where
  132. * all bits set (~0) is INVALID_SOCKET. */
  133. #ifndef _WIN32
  134. typedef int redisFD;
  135. #define REDIS_INVALID_FD -1
  136. #else
  137. #ifdef _WIN64
  138. typedef unsigned long long redisFD; /* SOCKET = 64-bit UINT_PTR */
  139. #else
  140. typedef unsigned long redisFD; /* SOCKET = 32-bit UINT_PTR */
  141. #endif
  142. #define REDIS_INVALID_FD ((redisFD)(~0)) /* INVALID_SOCKET */
  143. #endif
  144. typedef struct {
  145. /*
  146. * the type of connection to use. This also indicates which
  147. * `endpoint` member field to use
  148. */
  149. int type;
  150. /* bit field of REDIS_OPT_xxx */
  151. int options;
  152. /* timeout value for connect operation. If NULL, no timeout is used */
  153. const struct timeval *connect_timeout;
  154. /* timeout value for commands. If NULL, no timeout is used. This can be
  155. * updated at runtime with redisSetTimeout/redisAsyncSetTimeout. */
  156. const struct timeval *command_timeout;
  157. union {
  158. /** use this field for tcp/ip connections */
  159. struct {
  160. const char *source_addr;
  161. const char *ip;
  162. int port;
  163. } tcp;
  164. /** use this field for unix domain sockets */
  165. const char *unix_socket;
  166. /**
  167. * use this field to have hiredis operate an already-open
  168. * file descriptor */
  169. redisFD fd;
  170. } endpoint;
  171. /* Optional user defined data/destructor */
  172. void *privdata;
  173. void (*free_privdata)(void *);
  174. /* A user defined PUSH message callback */
  175. redisPushFn *push_cb;
  176. redisAsyncPushFn *async_push_cb;
  177. } redisOptions;
  178. /**
  179. * Helper macros to initialize options to their specified fields.
  180. */
  181. #define REDIS_OPTIONS_SET_TCP(opts, ip_, port_) \
  182. (opts)->type = REDIS_CONN_TCP; \
  183. (opts)->endpoint.tcp.ip = ip_; \
  184. (opts)->endpoint.tcp.port = port_;
  185. #define REDIS_OPTIONS_SET_UNIX(opts, path) \
  186. (opts)->type = REDIS_CONN_UNIX; \
  187. (opts)->endpoint.unix_socket = path;
  188. #define REDIS_OPTIONS_SET_PRIVDATA(opts, data, dtor) \
  189. (opts)->privdata = data; \
  190. (opts)->free_privdata = dtor; \
  191. typedef struct redisContextFuncs {
  192. void (*free_privctx)(void *);
  193. void (*async_read)(struct redisAsyncContext *);
  194. void (*async_write)(struct redisAsyncContext *);
  195. ssize_t (*read)(struct redisContext *, char *, size_t);
  196. ssize_t (*write)(struct redisContext *);
  197. } redisContextFuncs;
  198. /* Context for a connection to Redis */
  199. typedef struct redisContext {
  200. const redisContextFuncs *funcs; /* Function table */
  201. int err; /* Error flags, 0 when there is no error */
  202. char errstr[128]; /* String representation of error when applicable */
  203. redisFD fd;
  204. int flags;
  205. char *obuf; /* Write buffer */
  206. redisReader *reader; /* Protocol reader */
  207. enum redisConnectionType connection_type;
  208. struct timeval *connect_timeout;
  209. struct timeval *command_timeout;
  210. struct {
  211. char *host;
  212. char *source_addr;
  213. int port;
  214. } tcp;
  215. struct {
  216. char *path;
  217. } unix_sock;
  218. /* For non-blocking connect */
  219. struct sockadr *saddr;
  220. size_t addrlen;
  221. /* Optional data and corresponding destructor users can use to provide
  222. * context to a given redisContext. Not used by hiredis. */
  223. void *privdata;
  224. void (*free_privdata)(void *);
  225. /* Internal context pointer presently used by hiredis to manage
  226. * SSL connections. */
  227. void *privctx;
  228. /* An optional RESP3 PUSH handler */
  229. redisPushFn *push_cb;
  230. } redisContext;
  231. redisContext *redisConnectWithOptions(const redisOptions *options);
  232. redisContext *redisConnect(const char *ip, int port);
  233. redisContext *redisConnectWithTimeout(const char *ip, int port, const struct timeval tv);
  234. redisContext *redisConnectNonBlock(const char *ip, int port);
  235. redisContext *redisConnectBindNonBlock(const char *ip, int port,
  236. const char *source_addr);
  237. redisContext *redisConnectBindNonBlockWithReuse(const char *ip, int port,
  238. const char *source_addr);
  239. redisContext *redisConnectUnix(const char *path);
  240. redisContext *redisConnectUnixWithTimeout(const char *path, const struct timeval tv);
  241. redisContext *redisConnectUnixNonBlock(const char *path);
  242. redisContext *redisConnectFd(redisFD fd);
  243. /**
  244. * Reconnect the given context using the saved information.
  245. *
  246. * This re-uses the exact same connect options as in the initial connection.
  247. * host, ip (or path), timeout and bind address are reused,
  248. * flags are used unmodified from the existing context.
  249. *
  250. * Returns REDIS_OK on successful connect or REDIS_ERR otherwise.
  251. */
  252. int redisReconnect(redisContext *c);
  253. redisPushFn *redisSetPushCallback(redisContext *c, redisPushFn *fn);
  254. int redisSetTimeout(redisContext *c, const struct timeval tv);
  255. int redisEnableKeepAlive(redisContext *c);
  256. void redisFree(redisContext *c);
  257. redisFD redisFreeKeepFd(redisContext *c);
  258. int redisBufferRead(redisContext *c);
  259. int redisBufferWrite(redisContext *c, int *done);
  260. /* In a blocking context, this function first checks if there are unconsumed
  261. * replies to return and returns one if so. Otherwise, it flushes the output
  262. * buffer to the socket and reads until it has a reply. In a non-blocking
  263. * context, it will return unconsumed replies until there are no more. */
  264. int redisGetReply(redisContext *c, void **reply);
  265. int redisGetReplyFromReader(redisContext *c, void **reply);
  266. /* Write a formatted command to the output buffer. Use these functions in blocking mode
  267. * to get a pipeline of commands. */
  268. int redisAppendFormattedCommand(redisContext *c, const char *cmd, size_t len);
  269. /* Write a command to the output buffer. Use these functions in blocking mode
  270. * to get a pipeline of commands. */
  271. int redisvAppendCommand(redisContext *c, const char *format, va_list ap);
  272. int redisAppendCommand(redisContext *c, const char *format, ...);
  273. int redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);
  274. /* Issue a command to Redis. In a blocking context, it is identical to calling
  275. * redisAppendCommand, followed by redisGetReply. The function will return
  276. * NULL if there was an error in performing the request, otherwise it will
  277. * return the reply. In a non-blocking context, it is identical to calling
  278. * only redisAppendCommand and will always return NULL. */
  279. void *redisvCommand(redisContext *c, const char *format, va_list ap);
  280. void *redisCommand(redisContext *c, const char *format, ...);
  281. void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);
  282. #ifdef __cplusplus
  283. }
  284. #endif
  285. #endif