bufferevent.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. /*
  2. * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
  3. * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  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. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  17. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  18. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  19. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  21. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  25. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #ifndef _EVENT2_BUFFEREVENT_H_
  28. #define _EVENT2_BUFFEREVENT_H_
  29. /**
  30. @file event2/bufferevent.h
  31. Functions for buffering data for network sending or receiving. Bufferevents
  32. are higher level than evbuffers: each has an underlying evbuffer for reading
  33. and one for writing, and callbacks that are invoked under certain
  34. circumstances.
  35. A bufferevent provides input and output buffers that get filled and
  36. drained automatically. The user of a bufferevent no longer deals
  37. directly with the I/O, but instead is reading from input and writing
  38. to output buffers.
  39. Once initialized, the bufferevent structure can be used repeatedly
  40. with bufferevent_enable() and bufferevent_disable().
  41. When reading is enabled, the bufferevent will try to read from the
  42. file descriptor onto its input buffer, and call the read callback.
  43. When writing is enabled, the bufferevent will try to write data onto its
  44. file descriptor when the output buffer has enough data, and call the write
  45. callback when the output buffer is sufficiently drained.
  46. Bufferevents come in several flavors, including:
  47. <dl>
  48. <dt>Socket-based bufferevents</dt>
  49. <dd>A bufferevent that reads and writes data onto a network
  50. socket. Created with bufferevent_socket_new().</dd>
  51. <dt>Paired bufferevents</dt>
  52. <dd>A pair of bufferevents that send and receive data to one
  53. another without touching the network. Created with
  54. bufferevent_pair_new().</dd>
  55. <dt>Filtering bufferevents</dt>
  56. <dd>A bufferevent that transforms data, and sends or receives it
  57. over another underlying bufferevent. Created with
  58. bufferevent_filter_new().</dd>
  59. <dt>SSL-backed bufferevents</dt>
  60. <dd>A bufferevent that uses the openssl library to send and
  61. receive data over an encrypted connection. Created with
  62. bufferevent_openssl_socket_new() or
  63. bufferevent_openssl_filter_new().</dd>
  64. </dl>
  65. */
  66. #ifdef __cplusplus
  67. extern "C" {
  68. #endif
  69. #include <event2/event-config.h>
  70. #ifdef _EVENT_HAVE_SYS_TYPES_H
  71. #include <sys/types.h>
  72. #endif
  73. #ifdef _EVENT_HAVE_SYS_TIME_H
  74. #include <sys/time.h>
  75. #endif
  76. /* For int types. */
  77. #include <event2/util.h>
  78. /** @name Bufferevent event codes
  79. These flags are passed as arguments to a bufferevent's event callback.
  80. @{
  81. */
  82. #define BEV_EVENT_READING 0x01 /**< error encountered while reading */
  83. #define BEV_EVENT_WRITING 0x02 /**< error encountered while writing */
  84. #define BEV_EVENT_EOF 0x10 /**< eof file reached */
  85. #define BEV_EVENT_ERROR 0x20 /**< unrecoverable error encountered */
  86. #define BEV_EVENT_TIMEOUT 0x40 /**< user-specified timeout reached */
  87. #define BEV_EVENT_CONNECTED 0x80 /**< connect operation finished. */
  88. /**@}*/
  89. /**
  90. An opaque type for handling buffered IO
  91. @see event2/bufferevent.h
  92. */
  93. struct bufferevent
  94. #ifdef _EVENT_IN_DOXYGEN
  95. {}
  96. #endif
  97. ;
  98. struct event_base;
  99. struct evbuffer;
  100. struct sockaddr;
  101. /**
  102. A read or write callback for a bufferevent.
  103. The read callback is triggered when new data arrives in the input
  104. buffer and the amount of readable data exceed the low watermark
  105. which is 0 by default.
  106. The write callback is triggered if the write buffer has been
  107. exhausted or fell below its low watermark.
  108. @param bev the bufferevent that triggered the callback
  109. @param ctx the user-specified context for this bufferevent
  110. */
  111. typedef void (*bufferevent_data_cb)(struct bufferevent *bev, void *ctx);
  112. /**
  113. An event/error callback for a bufferevent.
  114. The event callback is triggered if either an EOF condition or another
  115. unrecoverable error was encountered.
  116. @param bev the bufferevent for which the error condition was reached
  117. @param what a conjunction of flags: BEV_EVENT_READING or BEV_EVENT_WRITING
  118. to indicate if the error was encountered on the read or write path,
  119. and one of the following flags: BEV_EVENT_EOF, BEV_EVENT_ERROR,
  120. BEV_EVENT_TIMEOUT, BEV_EVENT_CONNECTED.
  121. @param ctx the user-specified context for this bufferevent
  122. */
  123. typedef void (*bufferevent_event_cb)(struct bufferevent *bev, short what, void *ctx);
  124. /** Options that can be specified when creating a bufferevent */
  125. enum bufferevent_options {
  126. /** If set, we close the underlying file
  127. * descriptor/bufferevent/whatever when this bufferevent is freed. */
  128. BEV_OPT_CLOSE_ON_FREE = (1<<0),
  129. /** If set, and threading is enabled, operations on this bufferevent
  130. * are protected by a lock */
  131. BEV_OPT_THREADSAFE = (1<<1),
  132. /** If set, callbacks are run deferred in the event loop. */
  133. BEV_OPT_DEFER_CALLBACKS = (1<<2),
  134. /** If set, callbacks are executed without locks being held on the
  135. * bufferevent. This option currently requires that
  136. * BEV_OPT_DEFER_CALLBACKS also be set; a future version of Libevent
  137. * might remove the requirement.*/
  138. BEV_OPT_UNLOCK_CALLBACKS = (1<<3)
  139. };
  140. /**
  141. Create a new socket bufferevent over an existing socket.
  142. @param base the event base to associate with the new bufferevent.
  143. @param fd the file descriptor from which data is read and written to.
  144. This file descriptor is not allowed to be a pipe(2).
  145. It is safe to set the fd to -1, so long as you later
  146. set it with bufferevent_setfd or bufferevent_socket_connect().
  147. @param options Zero or more BEV_OPT_* flags
  148. @return a pointer to a newly allocated bufferevent struct, or NULL if an
  149. error occurred
  150. @see bufferevent_free()
  151. */
  152. struct bufferevent *bufferevent_socket_new(struct event_base *base, evutil_socket_t fd, int options);
  153. /**
  154. Launch a connect() attempt with a socket-based bufferevent.
  155. When the connect succeeds, the eventcb will be invoked with
  156. BEV_EVENT_CONNECTED set.
  157. If the bufferevent does not already have a socket set, we allocate a new
  158. socket here and make it nonblocking before we begin.
  159. If no address is provided, we assume that the socket is already connecting,
  160. and configure the bufferevent so that a BEV_EVENT_CONNECTED event will be
  161. yielded when it is done connecting.
  162. @param bufev an existing bufferevent allocated with
  163. bufferevent_socket_new().
  164. @param addr the address we should connect to
  165. @param socklen The length of the address
  166. @return 0 on success, -1 on failure.
  167. */
  168. int bufferevent_socket_connect(struct bufferevent *, struct sockaddr *, int);
  169. struct evdns_base;
  170. /**
  171. Resolve the hostname 'hostname' and connect to it as with
  172. bufferevent_socket_connect().
  173. @param bufev An existing bufferevent allocated with bufferevent_socket_new()
  174. @param evdns_base Optionally, an evdns_base to use for resolving hostnames
  175. asynchronously. May be set to NULL for a blocking resolve.
  176. @param family A preferred address family to resolve addresses to, or
  177. AF_UNSPEC for no preference. Only AF_INET, AF_INET6, and AF_UNSPEC are
  178. supported.
  179. @param hostname The hostname to resolve; see below for notes on recognized
  180. formats
  181. @param port The port to connect to on the resolved address.
  182. @return 0 if successful, -1 on failure.
  183. Recognized hostname formats are:
  184. www.example.com (hostname)
  185. 1.2.3.4 (ipv4address)
  186. ::1 (ipv6address)
  187. [::1] ([ipv6address])
  188. Performance note: If you do not provide an evdns_base, this function
  189. may block while it waits for a DNS response. This is probably not
  190. what you want.
  191. */
  192. int bufferevent_socket_connect_hostname(struct bufferevent *,
  193. struct evdns_base *, int, const char *, int);
  194. /**
  195. Return the error code for the last failed DNS lookup attempt made by
  196. bufferevent_socket_connect_hostname().
  197. @param bev The bufferevent object.
  198. @return DNS error code.
  199. @see evutil_gai_strerror()
  200. */
  201. int bufferevent_socket_get_dns_error(struct bufferevent *bev);
  202. /**
  203. Assign a bufferevent to a specific event_base.
  204. NOTE that only socket bufferevents support this function.
  205. @param base an event_base returned by event_init()
  206. @param bufev a bufferevent struct returned by bufferevent_new()
  207. or bufferevent_socket_new()
  208. @return 0 if successful, or -1 if an error occurred
  209. @see bufferevent_new()
  210. */
  211. int bufferevent_base_set(struct event_base *base, struct bufferevent *bufev);
  212. /**
  213. Return the event_base used by a bufferevent
  214. */
  215. struct event_base *bufferevent_get_base(struct bufferevent *bev);
  216. /**
  217. Assign a priority to a bufferevent.
  218. Only supported for socket bufferevents.
  219. @param bufev a bufferevent struct
  220. @param pri the priority to be assigned
  221. @return 0 if successful, or -1 if an error occurred
  222. */
  223. int bufferevent_priority_set(struct bufferevent *bufev, int pri);
  224. /**
  225. Deallocate the storage associated with a bufferevent structure.
  226. @param bufev the bufferevent structure to be freed.
  227. */
  228. void bufferevent_free(struct bufferevent *bufev);
  229. /**
  230. Changes the callbacks for a bufferevent.
  231. @param bufev the bufferevent object for which to change callbacks
  232. @param readcb callback to invoke when there is data to be read, or NULL if
  233. no callback is desired
  234. @param writecb callback to invoke when the file descriptor is ready for
  235. writing, or NULL if no callback is desired
  236. @param eventcb callback to invoke when there is an event on the file
  237. descriptor
  238. @param cbarg an argument that will be supplied to each of the callbacks
  239. (readcb, writecb, and errorcb)
  240. @see bufferevent_new()
  241. */
  242. void bufferevent_setcb(struct bufferevent *bufev,
  243. bufferevent_data_cb readcb, bufferevent_data_cb writecb,
  244. bufferevent_event_cb eventcb, void *cbarg);
  245. /**
  246. Changes the file descriptor on which the bufferevent operates.
  247. Not supported for all bufferevent types.
  248. @param bufev the bufferevent object for which to change the file descriptor
  249. @param fd the file descriptor to operate on
  250. */
  251. int bufferevent_setfd(struct bufferevent *bufev, evutil_socket_t fd);
  252. /**
  253. Returns the file descriptor associated with a bufferevent, or -1 if
  254. no file descriptor is associated with the bufferevent.
  255. */
  256. evutil_socket_t bufferevent_getfd(struct bufferevent *bufev);
  257. /**
  258. Returns the underlying bufferevent associated with a bufferevent (if
  259. the bufferevent is a wrapper), or NULL if there is no underlying bufferevent.
  260. */
  261. struct bufferevent *bufferevent_get_underlying(struct bufferevent *bufev);
  262. /**
  263. Write data to a bufferevent buffer.
  264. The bufferevent_write() function can be used to write data to the file
  265. descriptor. The data is appended to the output buffer and written to the
  266. descriptor automatically as it becomes available for writing.
  267. @param bufev the bufferevent to be written to
  268. @param data a pointer to the data to be written
  269. @param size the length of the data, in bytes
  270. @return 0 if successful, or -1 if an error occurred
  271. @see bufferevent_write_buffer()
  272. */
  273. int bufferevent_write(struct bufferevent *bufev,
  274. const void *data, size_t size);
  275. /**
  276. Write data from an evbuffer to a bufferevent buffer. The evbuffer is
  277. being drained as a result.
  278. @param bufev the bufferevent to be written to
  279. @param buf the evbuffer to be written
  280. @return 0 if successful, or -1 if an error occurred
  281. @see bufferevent_write()
  282. */
  283. int bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf);
  284. /**
  285. Read data from a bufferevent buffer.
  286. The bufferevent_read() function is used to read data from the input buffer.
  287. @param bufev the bufferevent to be read from
  288. @param data pointer to a buffer that will store the data
  289. @param size the size of the data buffer, in bytes
  290. @return the amount of data read, in bytes.
  291. */
  292. size_t bufferevent_read(struct bufferevent *bufev, void *data, size_t size);
  293. /**
  294. Read data from a bufferevent buffer into an evbuffer. This avoids
  295. memory copies.
  296. @param bufev the bufferevent to be read from
  297. @param buf the evbuffer to which to add data
  298. @return 0 if successful, or -1 if an error occurred.
  299. */
  300. int bufferevent_read_buffer(struct bufferevent *bufev, struct evbuffer *buf);
  301. /**
  302. Returns the input buffer.
  303. The user MUST NOT set the callback on this buffer.
  304. @param bufev the bufferevent from which to get the evbuffer
  305. @return the evbuffer object for the input buffer
  306. */
  307. struct evbuffer *bufferevent_get_input(struct bufferevent *bufev);
  308. /**
  309. Returns the output buffer.
  310. The user MUST NOT set the callback on this buffer.
  311. When filters are being used, the filters need to be manually
  312. triggered if the output buffer was manipulated.
  313. @param bufev the bufferevent from which to get the evbuffer
  314. @return the evbuffer object for the output buffer
  315. */
  316. struct evbuffer *bufferevent_get_output(struct bufferevent *bufev);
  317. /**
  318. Enable a bufferevent.
  319. @param bufev the bufferevent to be enabled
  320. @param event any combination of EV_READ | EV_WRITE.
  321. @return 0 if successful, or -1 if an error occurred
  322. @see bufferevent_disable()
  323. */
  324. int bufferevent_enable(struct bufferevent *bufev, short event);
  325. /**
  326. Disable a bufferevent.
  327. @param bufev the bufferevent to be disabled
  328. @param event any combination of EV_READ | EV_WRITE.
  329. @return 0 if successful, or -1 if an error occurred
  330. @see bufferevent_enable()
  331. */
  332. int bufferevent_disable(struct bufferevent *bufev, short event);
  333. /**
  334. Return the events that are enabled on a given bufferevent.
  335. @param bufev the bufferevent to inspect
  336. @return A combination of EV_READ | EV_WRITE
  337. */
  338. short bufferevent_get_enabled(struct bufferevent *bufev);
  339. /**
  340. Set the read and write timeout for a bufferevent.
  341. A bufferevent's timeout will fire the first time that the indicated
  342. amount of time has elapsed since a successful read or write operation,
  343. during which the bufferevent was trying to read or write.
  344. (In other words, if reading or writing is disabled, or if the
  345. bufferevent's read or write operation has been suspended because
  346. there's no data to write, or not enough banwidth, or so on, the
  347. timeout isn't active. The timeout only becomes active when we we're
  348. willing to actually read or write.)
  349. Calling bufferevent_enable or setting a timeout for a bufferevent
  350. whose timeout is already pending resets its timeout.
  351. If the timeout elapses, the corresponding operation (EV_READ or
  352. EV_WRITE) becomes disabled until you re-enable it again. The
  353. bufferevent's event callback is called with the
  354. BEV_EVENT_TIMEOUT|BEV_EVENT_READING or
  355. BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING.
  356. @param bufev the bufferevent to be modified
  357. @param timeout_read the read timeout, or NULL
  358. @param timeout_write the write timeout, or NULL
  359. */
  360. int bufferevent_set_timeouts(struct bufferevent *bufev,
  361. const struct timeval *timeout_read, const struct timeval *timeout_write);
  362. /**
  363. Sets the watermarks for read and write events.
  364. On input, a bufferevent does not invoke the user read callback unless
  365. there is at least low watermark data in the buffer. If the read buffer
  366. is beyond the high watermark, the bufferevent stops reading from the network.
  367. On output, the user write callback is invoked whenever the buffered data
  368. falls below the low watermark. Filters that write to this bufev will try
  369. not to write more bytes to this buffer than the high watermark would allow,
  370. except when flushing.
  371. @param bufev the bufferevent to be modified
  372. @param events EV_READ, EV_WRITE or both
  373. @param lowmark the lower watermark to set
  374. @param highmark the high watermark to set
  375. */
  376. void bufferevent_setwatermark(struct bufferevent *bufev, short events,
  377. size_t lowmark, size_t highmark);
  378. /**
  379. Acquire the lock on a bufferevent. Has no effect if locking was not
  380. enabled with BEV_OPT_THREADSAFE.
  381. */
  382. void bufferevent_lock(struct bufferevent *bufev);
  383. /**
  384. Release the lock on a bufferevent. Has no effect if locking was not
  385. enabled with BEV_OPT_THREADSAFE.
  386. */
  387. void bufferevent_unlock(struct bufferevent *bufev);
  388. /**
  389. Flags that can be passed into filters to let them know how to
  390. deal with the incoming data.
  391. */
  392. enum bufferevent_flush_mode {
  393. /** usually set when processing data */
  394. BEV_NORMAL = 0,
  395. /** want to checkpoint all data sent. */
  396. BEV_FLUSH = 1,
  397. /** encountered EOF on read or done sending data */
  398. BEV_FINISHED = 2
  399. };
  400. /**
  401. Triggers the bufferevent to produce more data if possible.
  402. @param bufev the bufferevent object
  403. @param iotype either EV_READ or EV_WRITE or both.
  404. @param mode either BEV_NORMAL or BEV_FLUSH or BEV_FINISHED
  405. @return -1 on failure, 0 if no data was produces, 1 if data was produced
  406. */
  407. int bufferevent_flush(struct bufferevent *bufev,
  408. short iotype,
  409. enum bufferevent_flush_mode mode);
  410. /**
  411. @name Filtering support
  412. @{
  413. */
  414. /**
  415. Values that filters can return.
  416. */
  417. enum bufferevent_filter_result {
  418. /** everything is okay */
  419. BEV_OK = 0,
  420. /** the filter needs to read more data before output */
  421. BEV_NEED_MORE = 1,
  422. /** the filter encountered a critical error, no further data
  423. can be processed. */
  424. BEV_ERROR = 2
  425. };
  426. /** A callback function to implement a filter for a bufferevent.
  427. @param src An evbuffer to drain data from.
  428. @param dst An evbuffer to add data to.
  429. @param limit A suggested upper bound of bytes to write to dst.
  430. The filter may ignore this value, but doing so means that
  431. it will overflow the high-water mark associated with dst.
  432. -1 means "no limit".
  433. @param mode Whether we should write data as may be convenient
  434. (BEV_NORMAL), or flush as much data as we can (BEV_FLUSH),
  435. or flush as much as we can, possibly including an end-of-stream
  436. marker (BEV_FINISH).
  437. @param ctx A user-supplied pointer.
  438. @return BEV_OK if we wrote some data; BEV_NEED_MORE if we can't
  439. produce any more output until we get some input; and BEV_ERROR
  440. on an error.
  441. */
  442. typedef enum bufferevent_filter_result (*bufferevent_filter_cb)(
  443. struct evbuffer *src, struct evbuffer *dst, ev_ssize_t dst_limit,
  444. enum bufferevent_flush_mode mode, void *ctx);
  445. /**
  446. Allocate a new filtering bufferevent on top of an existing bufferevent.
  447. @param underlying the underlying bufferevent.
  448. @param input_filter The filter to apply to data we read from the underlying
  449. bufferevent
  450. @param output_filter The filer to apply to data we write to the underlying
  451. bufferevent
  452. @param options A bitfield of bufferevent options.
  453. @param free_context A function to use to free the filter context when
  454. this bufferevent is freed.
  455. @param ctx A context pointer to pass to the filter functions.
  456. */
  457. struct bufferevent *
  458. bufferevent_filter_new(struct bufferevent *underlying,
  459. bufferevent_filter_cb input_filter,
  460. bufferevent_filter_cb output_filter,
  461. int options,
  462. void (*free_context)(void *),
  463. void *ctx);
  464. /**@}*/
  465. /**
  466. Allocate a pair of linked bufferevents. The bufferevents behave as would
  467. two bufferevent_sock instances connected to opposite ends of a
  468. socketpair(), except that no internal socketpair is allocated.
  469. @param base The event base to associate with the socketpair.
  470. @param options A set of options for this bufferevent
  471. @param pair A pointer to an array to hold the two new bufferevent objects.
  472. @return 0 on success, -1 on failure.
  473. */
  474. int bufferevent_pair_new(struct event_base *base, int options,
  475. struct bufferevent *pair[2]);
  476. /**
  477. Given one bufferevent returned by bufferevent_pair_new(), returns the
  478. other one if it still exists. Otherwise returns NULL.
  479. */
  480. struct bufferevent *bufferevent_pair_get_partner(struct bufferevent *bev);
  481. /**
  482. Abstract type used to configure rate-limiting on a bufferevent or a group
  483. of bufferevents.
  484. */
  485. struct ev_token_bucket_cfg;
  486. /**
  487. A group of bufferevents which are configured to respect the same rate
  488. limit.
  489. */
  490. struct bufferevent_rate_limit_group;
  491. /** Maximum configurable rate- or burst-limit. */
  492. #define EV_RATE_LIMIT_MAX EV_SSIZE_MAX
  493. /**
  494. Initialize and return a new object to configure the rate-limiting behavior
  495. of bufferevents.
  496. @param read_rate The maximum number of bytes to read per tick on
  497. average.
  498. @param read_burst The maximum number of bytes to read in any single tick.
  499. @param write_rate The maximum number of bytes to write per tick on
  500. average.
  501. @param write_burst The maximum number of bytes to write in any single tick.
  502. @param tick_len The length of a single tick. Defaults to one second.
  503. Any fractions of a millisecond are ignored.
  504. Note that all rate-limits hare are currently best-effort: future versions
  505. of Libevent may implement them more tightly.
  506. */
  507. struct ev_token_bucket_cfg *ev_token_bucket_cfg_new(
  508. size_t read_rate, size_t read_burst,
  509. size_t write_rate, size_t write_burst,
  510. const struct timeval *tick_len);
  511. /** Free all storage held in 'cfg'.
  512. Note: 'cfg' is not currently reference-counted; it is not safe to free it
  513. until no bufferevent is using it.
  514. */
  515. void ev_token_bucket_cfg_free(struct ev_token_bucket_cfg *cfg);
  516. /**
  517. Set the rate-limit of a the bufferevent 'bev' to the one specified in
  518. 'cfg'. If 'cfg' is NULL, disable any per-bufferevent rate-limiting on
  519. 'bev'.
  520. Note that only some bufferevent types currently respect rate-limiting.
  521. They are: socket-based bufferevents (normal and IOCP-based), and SSL-based
  522. bufferevents.
  523. Return 0 on sucess, -1 on failure.
  524. */
  525. int bufferevent_set_rate_limit(struct bufferevent *bev,
  526. struct ev_token_bucket_cfg *cfg);
  527. /**
  528. Create a new rate-limit group for bufferevents. A rate-limit group
  529. constrains the maximum number of bytes sent and received, in toto,
  530. by all of its bufferevents.
  531. @param base An event_base to run any necessary timeouts for the group.
  532. Note that all bufferevents in the group do not necessarily need to share
  533. this event_base.
  534. @param cfg The rate-limit for this group.
  535. Note that all rate-limits hare are currently best-effort: future versions
  536. of Libevent may implement them more tightly.
  537. Note also that only some bufferevent types currently respect rate-limiting.
  538. They are: socket-based bufferevents (normal and IOCP-based), and SSL-based
  539. bufferevents.
  540. */
  541. struct bufferevent_rate_limit_group *bufferevent_rate_limit_group_new(
  542. struct event_base *base,
  543. const struct ev_token_bucket_cfg *cfg);
  544. /**
  545. Change the rate-limiting settings for a given rate-limiting group.
  546. Return 0 on success, -1 on failure.
  547. */
  548. int bufferevent_rate_limit_group_set_cfg(
  549. struct bufferevent_rate_limit_group *,
  550. const struct ev_token_bucket_cfg *);
  551. /**
  552. Change the smallest quantum we're willing to allocate to any single
  553. bufferevent in a group for reading or writing at a time.
  554. The rationale is that, because of TCP/IP protocol overheads and kernel
  555. behavior, if a rate-limiting group is so tight on bandwidth that you're
  556. only willing to send 1 byte per tick per bufferevent, you might instead
  557. want to batch up the reads and writes so that you send N bytes per
  558. 1/N of the bufferevents (chosen at random) each tick, so you still wind
  559. up send 1 byte per tick per bufferevent on average, but you don't send
  560. so many tiny packets.
  561. The default min-share is currently 64 bytes.
  562. Returns 0 on success, -1 on faulre.
  563. */
  564. int bufferevent_rate_limit_group_set_min_share(
  565. struct bufferevent_rate_limit_group *, size_t);
  566. /**
  567. Free a rate-limiting group. The group must have no members when
  568. this function is called.
  569. */
  570. void bufferevent_rate_limit_group_free(struct bufferevent_rate_limit_group *);
  571. /**
  572. Add 'bev' to the list of bufferevents whose aggregate reading and writing
  573. is restricted by 'g'. If 'g' is NULL, remove 'bev' from its current group.
  574. A bufferevent may belong to no more than one rate-limit group at a time.
  575. If 'bev' is already a member of a group, it will be removed from its old
  576. group before being added to 'g'.
  577. Return 0 on success and -1 on failure.
  578. */
  579. int bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
  580. struct bufferevent_rate_limit_group *g);
  581. /** Remove 'bev' from its current rate-limit group (if any). */
  582. int bufferevent_remove_from_rate_limit_group(struct bufferevent *bev);
  583. /**
  584. @name Rate limit inspection
  585. Return the current read or write bucket size for a bufferevent.
  586. If it is not configured with a per-bufferevent ratelimit, return
  587. EV_SSIZE_MAX. This function does not inspect the group limit, if any.
  588. Note that it can return a negative value if the bufferevent has been
  589. made to read or write more than its limit.
  590. @{
  591. */
  592. ev_ssize_t bufferevent_get_read_limit(struct bufferevent *bev);
  593. ev_ssize_t bufferevent_get_write_limit(struct bufferevent *bev);
  594. /*@}*/
  595. ev_ssize_t bufferevent_get_max_to_read(struct bufferevent *bev);
  596. ev_ssize_t bufferevent_get_max_to_write(struct bufferevent *bev);
  597. /**
  598. @name Group Rate limit inspection
  599. Return the read or write bucket size for a bufferevent rate limit
  600. group. Note that it can return a negative value if bufferevents in
  601. the group have been made to read or write more than their limits.
  602. @{
  603. */
  604. ev_ssize_t bufferevent_rate_limit_group_get_read_limit(
  605. struct bufferevent_rate_limit_group *);
  606. ev_ssize_t bufferevent_rate_limit_group_get_write_limit(
  607. struct bufferevent_rate_limit_group *);
  608. /*@}*/
  609. /**
  610. @name Rate limit manipulation
  611. Subtract a number of bytes from a bufferevent's read or write bucket.
  612. The decrement value can be negative, if you want to manually refill
  613. the bucket. If the change puts the bucket above or below zero, the
  614. bufferevent will resume or suspend reading writing as appropriate.
  615. These functions make no change in the buckets for the bufferevent's
  616. group, if any.
  617. Returns 0 on success, -1 on internal error.
  618. @{
  619. */
  620. int bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr);
  621. int bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr);
  622. /*@}*/
  623. /**
  624. @name Group rate limit manipulation
  625. Subtract a number of bytes from a bufferevent rate-limiting group's
  626. read or write bucket. The decrement value can be negative, if you
  627. want to manually refill the bucket. If the change puts the bucket
  628. above or below zero, the bufferevents in the group will resume or
  629. suspend reading writing as appropriate.
  630. Returns 0 on success, -1 on internal error.
  631. @{
  632. */
  633. int bufferevent_rate_limit_group_decrement_read(
  634. struct bufferevent_rate_limit_group *, ev_ssize_t);
  635. int bufferevent_rate_limit_group_decrement_write(
  636. struct bufferevent_rate_limit_group *, ev_ssize_t);
  637. /*@}*/
  638. /**
  639. * Inspect the total bytes read/written on a group.
  640. *
  641. * Set the variable pointed to by total_read_out to the total number of bytes
  642. * ever read on grp, and the variable pointed to by total_written_out to the
  643. * total number of bytes ever written on grp. */
  644. void bufferevent_rate_limit_group_get_totals(
  645. struct bufferevent_rate_limit_group *grp,
  646. ev_uint64_t *total_read_out, ev_uint64_t *total_written_out);
  647. /**
  648. * Reset the total bytes read/written on a group.
  649. *
  650. * Reset the number of bytes read or written on grp as given by
  651. * bufferevent_rate_limit_group_reset_totals(). */
  652. void
  653. bufferevent_rate_limit_group_reset_totals(
  654. struct bufferevent_rate_limit_group *grp);
  655. #ifdef __cplusplus
  656. }
  657. #endif
  658. #endif /* _EVENT2_BUFFEREVENT_H_ */