Path: blob/main/contrib/libevent/bufferevent-internal.h
39475 views
/*1* Copyright (c) 2008-2012 Niels Provos and Nick Mathewson2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6* 1. Redistributions of source code must retain the above copyright7* notice, this list of conditions and the following disclaimer.8* 2. Redistributions in binary form must reproduce the above copyright9* notice, this list of conditions and the following disclaimer in the10* documentation and/or other materials provided with the distribution.11* 3. The name of the author may not be used to endorse or promote products12* derived from this software without specific prior written permission.13*14* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR15* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES16* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.17* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,18* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT19* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,20* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY21* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT22* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF23* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.24*/25#ifndef BUFFEREVENT_INTERNAL_H_INCLUDED_26#define BUFFEREVENT_INTERNAL_H_INCLUDED_2728#ifdef __cplusplus29extern "C" {30#endif3132#include "event2/event-config.h"33#include "event2/event_struct.h"34#include "evconfig-private.h"35#include "event2/util.h"36#include "defer-internal.h"37#include "evthread-internal.h"38#include "event2/thread.h"39#include "ratelim-internal.h"40#include "event2/bufferevent_struct.h"4142#include "ipv6-internal.h"43#ifdef _WIN3244#include <ws2tcpip.h>45#endif46#ifdef EVENT__HAVE_NETINET_IN_H47#include <netinet/in.h>48#endif49#ifdef EVENT__HAVE_NETINET_IN6_H50#include <netinet/in6.h>51#endif5253/* These flags are reasons that we might be declining to actually enable54reading or writing on a bufferevent.55*/5657/* On a all bufferevents, for reading: used when we have read up to the58watermark value.5960On a filtering bufferevent, for writing: used when the underlying61bufferevent's write buffer has been filled up to its watermark62value.63*/64#define BEV_SUSPEND_WM 0x0165/* On a base bufferevent: when we have emptied a bandwidth buckets */66#define BEV_SUSPEND_BW 0x0267/* On a base bufferevent: when we have emptied the group's bandwidth bucket. */68#define BEV_SUSPEND_BW_GROUP 0x0469/* On a socket bufferevent: can't do any operations while we're waiting for70* name lookup to finish. */71#define BEV_SUSPEND_LOOKUP 0x0872/* On a base bufferevent, for reading: used when a filter has choked this73* (underlying) bufferevent because it has stopped reading from it. */74#define BEV_SUSPEND_FILT_READ 0x107576typedef ev_uint16_t bufferevent_suspend_flags;7778struct bufferevent_rate_limit_group {79/** List of all members in the group */80LIST_HEAD(rlim_group_member_list, bufferevent_private) members;81/** Current limits for the group. */82struct ev_token_bucket rate_limit;83struct ev_token_bucket_cfg rate_limit_cfg;8485/** True iff we don't want to read from any member of the group.until86* the token bucket refills. */87unsigned read_suspended : 1;88/** True iff we don't want to write from any member of the group.until89* the token bucket refills. */90unsigned write_suspended : 1;91/** True iff we were unable to suspend one of the bufferevents in the92* group for reading the last time we tried, and we should try93* again. */94unsigned pending_unsuspend_read : 1;95/** True iff we were unable to suspend one of the bufferevents in the96* group for writing the last time we tried, and we should try97* again. */98unsigned pending_unsuspend_write : 1;99100/*@{*/101/** Total number of bytes read or written in this group since last102* reset. */103ev_uint64_t total_read;104ev_uint64_t total_written;105/*@}*/106107/** The number of bufferevents in the group. */108int n_members;109110/** The smallest number of bytes that any member of the group should111* be limited to read or write at a time. */112ev_ssize_t min_share;113ev_ssize_t configured_min_share;114115/** Timeout event that goes off once a tick, when the bucket is ready116* to refill. */117struct event master_refill_event;118119/** Seed for weak random number generator. Protected by 'lock' */120struct evutil_weakrand_state weakrand_seed;121122/** Lock to protect the members of this group. This lock should nest123* within every bufferevent lock: if you are holding this lock, do124* not assume you can lock another bufferevent. */125void *lock;126};127128/** Fields for rate-limiting a single bufferevent. */129struct bufferevent_rate_limit {130/* Linked-list elements for storing this bufferevent_private in a131* group.132*133* Note that this field is supposed to be protected by the group134* lock */135LIST_ENTRY(bufferevent_private) next_in_group;136/** The rate-limiting group for this bufferevent, or NULL if it is137* only rate-limited on its own. */138struct bufferevent_rate_limit_group *group;139140/* This bufferevent's current limits. */141struct ev_token_bucket limit;142/* Pointer to the rate-limit configuration for this bufferevent.143* Can be shared. XXX reference-count this? */144struct ev_token_bucket_cfg *cfg;145146/* Timeout event used when one this bufferevent's buckets are147* empty. */148struct event refill_bucket_event;149};150151/** Parts of the bufferevent structure that are shared among all bufferevent152* types, but not exposed in bufferevent_struct.h. */153struct bufferevent_private {154/** The underlying bufferevent structure. */155struct bufferevent bev;156157/** Evbuffer callback to enforce watermarks on input. */158struct evbuffer_cb_entry *read_watermarks_cb;159160/** If set, we should free the lock when we free the bufferevent. */161unsigned own_lock : 1;162163/** Flag: set if we have deferred callbacks and a read callback is164* pending. */165unsigned readcb_pending : 1;166/** Flag: set if we have deferred callbacks and a write callback is167* pending. */168unsigned writecb_pending : 1;169/** Flag: set if we are currently busy connecting. */170unsigned connecting : 1;171/** Flag: set if a connect failed prematurely; this is a hack for172* getting around the bufferevent abstraction. */173unsigned connection_refused : 1;174/** Set to the events pending if we have deferred callbacks and175* an events callback is pending. */176short eventcb_pending;177178/** If set, read is suspended until one or more conditions are over.179* The actual value here is a bitfield of those conditions; see the180* BEV_SUSPEND_* flags above. */181bufferevent_suspend_flags read_suspended;182183/** If set, writing is suspended until one or more conditions are over.184* The actual value here is a bitfield of those conditions; see the185* BEV_SUSPEND_* flags above. */186bufferevent_suspend_flags write_suspended;187188/** Set to the current socket errno if we have deferred callbacks and189* an events callback is pending. */190int errno_pending;191192/** The DNS error code for bufferevent_socket_connect_hostname */193int dns_error;194195/** Used to implement deferred callbacks */196struct event_callback deferred;197198/** The options this bufferevent was constructed with */199enum bufferevent_options options;200201/** Current reference count for this bufferevent. */202int refcnt;203204/** Lock for this bufferevent. Shared by the inbuf and the outbuf.205* If NULL, locking is disabled. */206void *lock;207208/** No matter how big our bucket gets, don't try to read more than this209* much in a single read operation. */210ev_ssize_t max_single_read;211212/** No matter how big our bucket gets, don't try to write more than this213* much in a single write operation. */214ev_ssize_t max_single_write;215216/** Rate-limiting information for this bufferevent */217struct bufferevent_rate_limit *rate_limiting;218219/* Saved conn_addr, to extract IP address from it.220*221* Because some servers may reset/close connection without waiting clients,222* in that case we can't extract IP address even in close_cb.223* So we need to save it, just after we connected to remote server, or224* after resolving (to avoid extra dns requests during retrying, since UDP225* is slow) */226union {227struct sockaddr_in6 in6;228struct sockaddr_in in;229} conn_address;230231struct evdns_getaddrinfo_request *dns_request;232};233234/** Possible operations for a control callback. */235enum bufferevent_ctrl_op {236BEV_CTRL_SET_FD,237BEV_CTRL_GET_FD,238BEV_CTRL_GET_UNDERLYING,239BEV_CTRL_CANCEL_ALL240};241242/** Possible data types for a control callback */243union bufferevent_ctrl_data {244void *ptr;245evutil_socket_t fd;246};247248/**249Implementation table for a bufferevent: holds function pointers and other250information to make the various bufferevent types work.251*/252struct bufferevent_ops {253/** The name of the bufferevent's type. */254const char *type;255/** At what offset into the implementation type will we find a256bufferevent structure?257258Example: if the type is implemented as259struct bufferevent_x {260int extra_data;261struct bufferevent bev;262}263then mem_offset should be offsetof(struct bufferevent_x, bev)264*/265off_t mem_offset;266267/** Enables one or more of EV_READ|EV_WRITE on a bufferevent. Does268not need to adjust the 'enabled' field. Returns 0 on success, -1269on failure.270*/271int (*enable)(struct bufferevent *, short);272273/** Disables one or more of EV_READ|EV_WRITE on a bufferevent. Does274not need to adjust the 'enabled' field. Returns 0 on success, -1275on failure.276*/277int (*disable)(struct bufferevent *, short);278279/** Detatches the bufferevent from related data structures. Called as280* soon as its reference count reaches 0. */281void (*unlink)(struct bufferevent *);282283/** Free any storage and deallocate any extra data or structures used284in this implementation. Called when the bufferevent is285finalized.286*/287void (*destruct)(struct bufferevent *);288289/** Called when the timeouts on the bufferevent have changed.*/290int (*adj_timeouts)(struct bufferevent *);291292/** Called to flush data. */293int (*flush)(struct bufferevent *, short, enum bufferevent_flush_mode);294295/** Called to access miscellaneous fields. */296int (*ctrl)(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);297298};299300extern const struct bufferevent_ops bufferevent_ops_socket;301extern const struct bufferevent_ops bufferevent_ops_filter;302extern const struct bufferevent_ops bufferevent_ops_pair;303304#define BEV_IS_SOCKET(bevp) ((bevp)->be_ops == &bufferevent_ops_socket)305#define BEV_IS_FILTER(bevp) ((bevp)->be_ops == &bufferevent_ops_filter)306#define BEV_IS_PAIR(bevp) ((bevp)->be_ops == &bufferevent_ops_pair)307308#if defined(EVENT__HAVE_OPENSSL)309extern const struct bufferevent_ops bufferevent_ops_openssl;310#define BEV_IS_OPENSSL(bevp) ((bevp)->be_ops == &bufferevent_ops_openssl)311#else312#define BEV_IS_OPENSSL(bevp) 0313#endif314315#ifdef _WIN32316extern const struct bufferevent_ops bufferevent_ops_async;317#define BEV_IS_ASYNC(bevp) ((bevp)->be_ops == &bufferevent_ops_async)318#else319#define BEV_IS_ASYNC(bevp) 0320#endif321322/** Initialize the shared parts of a bufferevent. */323EVENT2_EXPORT_SYMBOL324int bufferevent_init_common_(struct bufferevent_private *, struct event_base *, const struct bufferevent_ops *, enum bufferevent_options options);325326/** For internal use: temporarily stop all reads on bufev, until the conditions327* in 'what' are over. */328EVENT2_EXPORT_SYMBOL329void bufferevent_suspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what);330/** For internal use: clear the conditions 'what' on bufev, and re-enable331* reading if there are no conditions left. */332EVENT2_EXPORT_SYMBOL333void bufferevent_unsuspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what);334335/** For internal use: temporarily stop all writes on bufev, until the conditions336* in 'what' are over. */337void bufferevent_suspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what);338/** For internal use: clear the conditions 'what' on bufev, and re-enable339* writing if there are no conditions left. */340void bufferevent_unsuspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what);341342#define bufferevent_wm_suspend_read(b) \343bufferevent_suspend_read_((b), BEV_SUSPEND_WM)344#define bufferevent_wm_unsuspend_read(b) \345bufferevent_unsuspend_read_((b), BEV_SUSPEND_WM)346347/*348Disable a bufferevent. Equivalent to bufferevent_disable(), but349first resets 'connecting' flag to force EV_WRITE down for sure.350351XXXX this method will go away in the future; try not to add new users.352See comment in evhttp_connection_reset_() for discussion.353354@param bufev the bufferevent to be disabled355@param event any combination of EV_READ | EV_WRITE.356@return 0 if successful, or -1 if an error occurred357@see bufferevent_disable()358*/359EVENT2_EXPORT_SYMBOL360int bufferevent_disable_hard_(struct bufferevent *bufev, short event);361362/** Internal: Set up locking on a bufferevent. If lock is set, use it.363* Otherwise, use a new lock. */364EVENT2_EXPORT_SYMBOL365int bufferevent_enable_locking_(struct bufferevent *bufev, void *lock);366/** Internal: backwards compat macro for the now public function367* Increment the reference count on bufev. */368#define bufferevent_incref_(bufev) bufferevent_incref(bufev)369/** Internal: Lock bufev and increase its reference count.370* unlocking it otherwise. */371EVENT2_EXPORT_SYMBOL372void bufferevent_incref_and_lock_(struct bufferevent *bufev);373/** Internal: backwards compat macro for the now public function374* Decrement the reference count on bufev. Returns 1 if it freed375* the bufferevent.*/376#define bufferevent_decref_(bufev) bufferevent_decref(bufev)377378/** Internal: Drop the reference count on bufev, freeing as necessary, and379* unlocking it otherwise. Returns 1 if it freed the bufferevent. */380EVENT2_EXPORT_SYMBOL381int bufferevent_decref_and_unlock_(struct bufferevent *bufev);382383/** Internal: If callbacks are deferred and we have a read callback, schedule384* a readcb. Otherwise just run the readcb. Ignores watermarks. */385EVENT2_EXPORT_SYMBOL386void bufferevent_run_readcb_(struct bufferevent *bufev, int options);387/** Internal: If callbacks are deferred and we have a write callback, schedule388* a writecb. Otherwise just run the writecb. Ignores watermarks. */389EVENT2_EXPORT_SYMBOL390void bufferevent_run_writecb_(struct bufferevent *bufev, int options);391/** Internal: If callbacks are deferred and we have an eventcb, schedule392* it to run with events "what". Otherwise just run the eventcb.393* See bufferevent_trigger_event for meaning of "options". */394EVENT2_EXPORT_SYMBOL395void bufferevent_run_eventcb_(struct bufferevent *bufev, short what, int options);396397/** Internal: Run or schedule (if deferred or options contain398* BEV_TRIG_DEFER_CALLBACKS) I/O callbacks specified in iotype.399* Must already hold the bufev lock. Honors watermarks unless400* BEV_TRIG_IGNORE_WATERMARKS is in options. */401static inline void bufferevent_trigger_nolock_(struct bufferevent *bufev, short iotype, int options);402403/* Making this inline since all of the common-case calls to this function in404* libevent use constant arguments. */405static inline void406bufferevent_trigger_nolock_(struct bufferevent *bufev, short iotype, int options)407{408if ((iotype & EV_READ) && ((options & BEV_TRIG_IGNORE_WATERMARKS) ||409evbuffer_get_length(bufev->input) >= bufev->wm_read.low))410bufferevent_run_readcb_(bufev, options);411if ((iotype & EV_WRITE) && ((options & BEV_TRIG_IGNORE_WATERMARKS) ||412evbuffer_get_length(bufev->output) <= bufev->wm_write.low))413bufferevent_run_writecb_(bufev, options);414}415416/** Internal: Add the event 'ev' with timeout tv, unless tv is set to 0, in417* which case add ev with no timeout. */418EVENT2_EXPORT_SYMBOL419int bufferevent_add_event_(struct event *ev, const struct timeval *tv);420421/* =========422* These next functions implement timeouts for bufferevents that aren't doing423* anything else with ev_read and ev_write, to handle timeouts.424* ========= */425/** Internal use: Set up the ev_read and ev_write callbacks so that426* the other "generic_timeout" functions will work on it. Call this from427* the constructor function. */428EVENT2_EXPORT_SYMBOL429void bufferevent_init_generic_timeout_cbs_(struct bufferevent *bev);430/** Internal use: Add or delete the generic timeout events as appropriate.431* (If an event is enabled and a timeout is set, we add the event. Otherwise432* we delete it.) Call this from anything that changes the timeout values,433* that enabled EV_READ or EV_WRITE, or that disables EV_READ or EV_WRITE. */434EVENT2_EXPORT_SYMBOL435int bufferevent_generic_adj_timeouts_(struct bufferevent *bev);436EVENT2_EXPORT_SYMBOL437int bufferevent_generic_adj_existing_timeouts_(struct bufferevent *bev);438439EVENT2_EXPORT_SYMBOL440enum bufferevent_options bufferevent_get_options_(struct bufferevent *bev);441442EVENT2_EXPORT_SYMBOL443const struct sockaddr*444bufferevent_socket_get_conn_address_(struct bufferevent *bev);445446EVENT2_EXPORT_SYMBOL447void448bufferevent_socket_set_conn_address_fd_(struct bufferevent *bev, evutil_socket_t fd);449450EVENT2_EXPORT_SYMBOL451void452bufferevent_socket_set_conn_address_(struct bufferevent *bev, struct sockaddr *addr, size_t addrlen);453454455/** Internal use: We have just successfully read data into an inbuf, so456* reset the read timeout (if any). */457#define BEV_RESET_GENERIC_READ_TIMEOUT(bev) \458do { \459if (evutil_timerisset(&(bev)->timeout_read)) \460event_add(&(bev)->ev_read, &(bev)->timeout_read); \461} while (0)462/** Internal use: We have just successfully written data from an inbuf, so463* reset the read timeout (if any). */464#define BEV_RESET_GENERIC_WRITE_TIMEOUT(bev) \465do { \466if (evutil_timerisset(&(bev)->timeout_write)) \467event_add(&(bev)->ev_write, &(bev)->timeout_write); \468} while (0)469#define BEV_DEL_GENERIC_READ_TIMEOUT(bev) \470event_del(&(bev)->ev_read)471#define BEV_DEL_GENERIC_WRITE_TIMEOUT(bev) \472event_del(&(bev)->ev_write)473474475/** Internal: Given a bufferevent, return its corresponding476* bufferevent_private. */477#define BEV_UPCAST(b) EVUTIL_UPCAST((b), struct bufferevent_private, bev)478479#ifdef EVENT__DISABLE_THREAD_SUPPORT480#define BEV_LOCK(b) EVUTIL_NIL_STMT_481#define BEV_UNLOCK(b) EVUTIL_NIL_STMT_482#else483/** Internal: Grab the lock (if any) on a bufferevent */484#define BEV_LOCK(b) do { \485struct bufferevent_private *locking = BEV_UPCAST(b); \486EVLOCK_LOCK(locking->lock, 0); \487} while (0)488489/** Internal: Release the lock (if any) on a bufferevent */490#define BEV_UNLOCK(b) do { \491struct bufferevent_private *locking = BEV_UPCAST(b); \492EVLOCK_UNLOCK(locking->lock, 0); \493} while (0)494#endif495496497/* ==== For rate-limiting. */498499EVENT2_EXPORT_SYMBOL500int bufferevent_decrement_write_buckets_(struct bufferevent_private *bev,501ev_ssize_t bytes);502EVENT2_EXPORT_SYMBOL503int bufferevent_decrement_read_buckets_(struct bufferevent_private *bev,504ev_ssize_t bytes);505EVENT2_EXPORT_SYMBOL506ev_ssize_t bufferevent_get_read_max_(struct bufferevent_private *bev);507EVENT2_EXPORT_SYMBOL508ev_ssize_t bufferevent_get_write_max_(struct bufferevent_private *bev);509510int bufferevent_ratelim_init_(struct bufferevent_private *bev);511512#ifdef __cplusplus513}514#endif515516517#endif /* BUFFEREVENT_INTERNAL_H_INCLUDED_ */518519520