1 /* $NetBSD: bufferevent-internal.h,v 1.4 2016/01/08 21:35:40 christos Exp $ */ 2 3 /* 4 * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. 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 * 3. The name of the author may not be used to endorse or promote products 15 * derived from this software without specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 */ 28 #ifndef BUFFEREVENT_INTERNAL_H_INCLUDED_ 29 #define BUFFEREVENT_INTERNAL_H_INCLUDED_ 30 31 #ifdef __cplusplus 32 extern "C" { 33 #endif 34 35 #include "event2/event-config.h" 36 #include "event2/event_struct.h" 37 #include "evconfig-private.h" 38 #include "event2/util.h" 39 #include "defer-internal.h" 40 #include "evthread-internal.h" 41 #include "event2/thread.h" 42 #include "ratelim-internal.h" 43 #include "event2/bufferevent_struct.h" 44 45 /* These flags are reasons that we might be declining to actually enable 46 reading or writing on a bufferevent. 47 */ 48 49 /* On a all bufferevents, for reading: used when we have read up to the 50 watermark value. 51 52 On a filtering bufferevent, for writing: used when the underlying 53 bufferevent's write buffer has been filled up to its watermark 54 value. 55 */ 56 #define BEV_SUSPEND_WM 0x01 57 /* On a base bufferevent: when we have emptied a bandwidth buckets */ 58 #define BEV_SUSPEND_BW 0x02 59 /* On a base bufferevent: when we have emptied the group's bandwidth bucket. */ 60 #define BEV_SUSPEND_BW_GROUP 0x04 61 /* On a socket bufferevent: can't do any operations while we're waiting for 62 * name lookup to finish. */ 63 #define BEV_SUSPEND_LOOKUP 0x08 64 /* On a base bufferevent, for reading: used when a filter has choked this 65 * (underlying) bufferevent because it has stopped reading from it. */ 66 #define BEV_SUSPEND_FILT_READ 0x10 67 68 typedef ev_uint16_t bufferevent_suspend_flags; 69 70 struct bufferevent_rate_limit_group { 71 /** List of all members in the group */ 72 LIST_HEAD(rlim_group_member_list, bufferevent_private) members; 73 /** Current limits for the group. */ 74 struct ev_token_bucket rate_limit; 75 struct ev_token_bucket_cfg rate_limit_cfg; 76 77 /** True iff we don't want to read from any member of the group.until 78 * the token bucket refills. */ 79 unsigned read_suspended : 1; 80 /** True iff we don't want to write from any member of the group.until 81 * the token bucket refills. */ 82 unsigned write_suspended : 1; 83 /** True iff we were unable to suspend one of the bufferevents in the 84 * group for reading the last time we tried, and we should try 85 * again. */ 86 unsigned pending_unsuspend_read : 1; 87 /** True iff we were unable to suspend one of the bufferevents in the 88 * group for writing the last time we tried, and we should try 89 * again. */ 90 unsigned pending_unsuspend_write : 1; 91 92 /*@{*/ 93 /** Total number of bytes read or written in this group since last 94 * reset. */ 95 ev_uint64_t total_read; 96 ev_uint64_t total_written; 97 /*@}*/ 98 99 /** The number of bufferevents in the group. */ 100 int n_members; 101 102 /** The smallest number of bytes that any member of the group should 103 * be limited to read or write at a time. */ 104 ev_ssize_t min_share; 105 ev_ssize_t configured_min_share; 106 107 /** Timeout event that goes off once a tick, when the bucket is ready 108 * to refill. */ 109 struct event master_refill_event; 110 111 /** Seed for weak random number generator. Protected by 'lock' */ 112 struct evutil_weakrand_state weakrand_seed; 113 114 /** Lock to protect the members of this group. This lock should nest 115 * within every bufferevent lock: if you are holding this lock, do 116 * not assume you can lock another bufferevent. */ 117 void *lock; 118 }; 119 120 /** Fields for rate-limiting a single bufferevent. */ 121 struct bufferevent_rate_limit { 122 /* Linked-list elements for storing this bufferevent_private in a 123 * group. 124 * 125 * Note that this field is supposed to be protected by the group 126 * lock */ 127 LIST_ENTRY(bufferevent_private) next_in_group; 128 /** The rate-limiting group for this bufferevent, or NULL if it is 129 * only rate-limited on its own. */ 130 struct bufferevent_rate_limit_group *group; 131 132 /* This bufferevent's current limits. */ 133 struct ev_token_bucket limit; 134 /* Pointer to the rate-limit configuration for this bufferevent. 135 * Can be shared. XXX reference-count this? */ 136 struct ev_token_bucket_cfg *cfg; 137 138 /* Timeout event used when one this bufferevent's buckets are 139 * empty. */ 140 struct event refill_bucket_event; 141 }; 142 143 /** Parts of the bufferevent structure that are shared among all bufferevent 144 * types, but not exposed in bufferevent_struct.h. */ 145 struct bufferevent_private { 146 /** The underlying bufferevent structure. */ 147 struct bufferevent bev; 148 149 /** Evbuffer callback to enforce watermarks on input. */ 150 struct evbuffer_cb_entry *read_watermarks_cb; 151 152 /** If set, we should free the lock when we free the bufferevent. */ 153 unsigned own_lock : 1; 154 155 /** Flag: set if we have deferred callbacks and a read callback is 156 * pending. */ 157 unsigned readcb_pending : 1; 158 /** Flag: set if we have deferred callbacks and a write callback is 159 * pending. */ 160 unsigned writecb_pending : 1; 161 /** Flag: set if we are currently busy connecting. */ 162 unsigned connecting : 1; 163 /** Flag: set if a connect failed prematurely; this is a hack for 164 * getting around the bufferevent abstraction. */ 165 unsigned connection_refused : 1; 166 /** Set to the events pending if we have deferred callbacks and 167 * an events callback is pending. */ 168 short eventcb_pending; 169 170 /** If set, read is suspended until one or more conditions are over. 171 * The actual value here is a bitfield of those conditions; see the 172 * BEV_SUSPEND_* flags above. */ 173 bufferevent_suspend_flags read_suspended; 174 175 /** If set, writing is suspended until one or more conditions are over. 176 * The actual value here is a bitfield of those conditions; see the 177 * BEV_SUSPEND_* flags above. */ 178 bufferevent_suspend_flags write_suspended; 179 180 /** Set to the current socket errno if we have deferred callbacks and 181 * an events callback is pending. */ 182 int errno_pending; 183 184 /** The DNS error code for bufferevent_socket_connect_hostname */ 185 int dns_error; 186 187 /** Used to implement deferred callbacks */ 188 struct event_callback deferred; 189 190 /** The options this bufferevent was constructed with */ 191 enum bufferevent_options options; 192 193 /** Current reference count for this bufferevent. */ 194 int refcnt; 195 196 /** Lock for this bufferevent. Shared by the inbuf and the outbuf. 197 * If NULL, locking is disabled. */ 198 void *lock; 199 200 /** No matter how big our bucket gets, don't try to read more than this 201 * much in a single read operation. */ 202 ev_ssize_t max_single_read; 203 204 /** No matter how big our bucket gets, don't try to write more than this 205 * much in a single write operation. */ 206 ev_ssize_t max_single_write; 207 208 /** Rate-limiting information for this bufferevent */ 209 struct bufferevent_rate_limit *rate_limiting; 210 }; 211 212 /** Possible operations for a control callback. */ 213 enum bufferevent_ctrl_op { 214 BEV_CTRL_SET_FD, 215 BEV_CTRL_GET_FD, 216 BEV_CTRL_GET_UNDERLYING, 217 BEV_CTRL_CANCEL_ALL 218 }; 219 220 /** Possible data types for a control callback */ 221 union bufferevent_ctrl_data { 222 void *ptr; 223 evutil_socket_t fd; 224 }; 225 226 /** 227 Implementation table for a bufferevent: holds function pointers and other 228 information to make the various bufferevent types work. 229 */ 230 struct bufferevent_ops { 231 /** The name of the bufferevent's type. */ 232 const char *type; 233 /** At what offset into the implementation type will we find a 234 bufferevent structure? 235 236 Example: if the type is implemented as 237 struct bufferevent_x { 238 int extra_data; 239 struct bufferevent bev; 240 } 241 then mem_offset should be offsetof(struct bufferevent_x, bev) 242 */ 243 off_t mem_offset; 244 245 /** Enables one or more of EV_READ|EV_WRITE on a bufferevent. Does 246 not need to adjust the 'enabled' field. Returns 0 on success, -1 247 on failure. 248 */ 249 int (*enable)(struct bufferevent *, short); 250 251 /** Disables one or more of EV_READ|EV_WRITE on a bufferevent. Does 252 not need to adjust the 'enabled' field. Returns 0 on success, -1 253 on failure. 254 */ 255 int (*disable)(struct bufferevent *, short); 256 257 /** Detatches the bufferevent from related data structures. Called as 258 * soon as its reference count reaches 0. */ 259 void (*unlink)(struct bufferevent *); 260 261 /** Free any storage and deallocate any extra data or structures used 262 in this implementation. Called when the bufferevent is 263 finalized. 264 */ 265 void (*destruct)(struct bufferevent *); 266 267 /** Called when the timeouts on the bufferevent have changed.*/ 268 int (*adj_timeouts)(struct bufferevent *); 269 270 /** Called to flush data. */ 271 int (*flush)(struct bufferevent *, short, enum bufferevent_flush_mode); 272 273 /** Called to access miscellaneous fields. */ 274 int (*ctrl)(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *); 275 276 }; 277 278 extern const struct bufferevent_ops bufferevent_ops_socket; 279 extern const struct bufferevent_ops bufferevent_ops_filter; 280 extern const struct bufferevent_ops bufferevent_ops_pair; 281 282 #define BEV_IS_SOCKET(bevp) ((bevp)->be_ops == &bufferevent_ops_socket) 283 #define BEV_IS_FILTER(bevp) ((bevp)->be_ops == &bufferevent_ops_filter) 284 #define BEV_IS_PAIR(bevp) ((bevp)->be_ops == &bufferevent_ops_pair) 285 286 #ifdef _WIN32 287 extern const struct bufferevent_ops bufferevent_ops_async; 288 #define BEV_IS_ASYNC(bevp) ((bevp)->be_ops == &bufferevent_ops_async) 289 #else 290 #define BEV_IS_ASYNC(bevp) 0 291 #endif 292 293 /** Initialize the shared parts of a bufferevent. */ 294 int bufferevent_init_common_(struct bufferevent_private *, struct event_base *, const struct bufferevent_ops *, enum bufferevent_options options); 295 296 /** For internal use: temporarily stop all reads on bufev, until the conditions 297 * in 'what' are over. */ 298 void bufferevent_suspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what); 299 /** For internal use: clear the conditions 'what' on bufev, and re-enable 300 * reading if there are no conditions left. */ 301 void bufferevent_unsuspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what); 302 303 /** For internal use: temporarily stop all writes on bufev, until the conditions 304 * in 'what' are over. */ 305 void bufferevent_suspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what); 306 /** For internal use: clear the conditions 'what' on bufev, and re-enable 307 * writing if there are no conditions left. */ 308 void bufferevent_unsuspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what); 309 310 #define bufferevent_wm_suspend_read(b) \ 311 bufferevent_suspend_read_((b), BEV_SUSPEND_WM) 312 #define bufferevent_wm_unsuspend_read(b) \ 313 bufferevent_unsuspend_read_((b), BEV_SUSPEND_WM) 314 315 /* 316 Disable a bufferevent. Equivalent to bufferevent_disable(), but 317 first resets 'connecting' flag to force EV_WRITE down for sure. 318 319 XXXX this method will go away in the future; try not to add new users. 320 See comment in evhttp_connection_reset_() for discussion. 321 322 @param bufev the bufferevent to be disabled 323 @param event any combination of EV_READ | EV_WRITE. 324 @return 0 if successful, or -1 if an error occurred 325 @see bufferevent_disable() 326 */ 327 int bufferevent_disable_hard_(struct bufferevent *bufev, short event); 328 329 /** Internal: Set up locking on a bufferevent. If lock is set, use it. 330 * Otherwise, use a new lock. */ 331 int bufferevent_enable_locking_(struct bufferevent *bufev, void *lock); 332 /** Internal: Increment the reference count on bufev. */ 333 void bufferevent_incref_(struct bufferevent *bufev); 334 /** Internal: Lock bufev and increase its reference count. 335 * unlocking it otherwise. */ 336 void bufferevent_incref_and_lock_(struct bufferevent *bufev); 337 /** Internal: Decrement the reference count on bufev. Returns 1 if it freed 338 * the bufferevent.*/ 339 int bufferevent_decref_(struct bufferevent *bufev); 340 /** Internal: Drop the reference count on bufev, freeing as necessary, and 341 * unlocking it otherwise. Returns 1 if it freed the bufferevent. */ 342 int bufferevent_decref_and_unlock_(struct bufferevent *bufev); 343 344 /** Internal: If callbacks are deferred and we have a read callback, schedule 345 * a readcb. Otherwise just run the readcb. Ignores watermarks. */ 346 void bufferevent_run_readcb_(struct bufferevent *bufev, int options); 347 /** Internal: If callbacks are deferred and we have a write callback, schedule 348 * a writecb. Otherwise just run the writecb. Ignores watermarks. */ 349 void bufferevent_run_writecb_(struct bufferevent *bufev, int options); 350 /** Internal: If callbacks are deferred and we have an eventcb, schedule 351 * it to run with events "what". Otherwise just run the eventcb. 352 * See bufferevent_trigger_event for meaning of "options". */ 353 void bufferevent_run_eventcb_(struct bufferevent *bufev, short what, int options); 354 355 /** Internal: Run or schedule (if deferred or options contain 356 * BEV_TRIG_DEFER_CALLBACKS) I/O callbacks specified in iotype. 357 * Must already hold the bufev lock. Honors watermarks unless 358 * BEV_TRIG_IGNORE_WATERMARKS is in options. */ 359 static inline void bufferevent_trigger_nolock_(struct bufferevent *bufev, short iotype, int options); 360 361 /* Making this inline since all of the common-case calls to this function in 362 * libevent use constant arguments. */ 363 static inline void 364 bufferevent_trigger_nolock_(struct bufferevent *bufev, short iotype, int options) 365 { 366 if ((iotype & EV_READ) && ((options & BEV_TRIG_IGNORE_WATERMARKS) || 367 evbuffer_get_length(bufev->input) >= bufev->wm_read.low)) 368 bufferevent_run_readcb_(bufev, options); 369 if ((iotype & EV_WRITE) && ((options & BEV_TRIG_IGNORE_WATERMARKS) || 370 evbuffer_get_length(bufev->output) <= bufev->wm_write.low)) 371 bufferevent_run_writecb_(bufev, options); 372 } 373 374 /** Internal: Add the event 'ev' with timeout tv, unless tv is set to 0, in 375 * which case add ev with no timeout. */ 376 int bufferevent_add_event_(struct event *ev, const struct timeval *tv); 377 378 /* ========= 379 * These next functions implement timeouts for bufferevents that aren't doing 380 * anything else with ev_read and ev_write, to handle timeouts. 381 * ========= */ 382 /** Internal use: Set up the ev_read and ev_write callbacks so that 383 * the other "generic_timeout" functions will work on it. Call this from 384 * the constructor function. */ 385 void bufferevent_init_generic_timeout_cbs_(struct bufferevent *bev); 386 /** Internal use: Add or delete the generic timeout events as appropriate. 387 * (If an event is enabled and a timeout is set, we add the event. Otherwise 388 * we delete it.) Call this from anything that changes the timeout values, 389 * that enabled EV_READ or EV_WRITE, or that disables EV_READ or EV_WRITE. */ 390 int bufferevent_generic_adj_timeouts_(struct bufferevent *bev); 391 392 enum bufferevent_options bufferevent_get_options_(struct bufferevent *bev); 393 394 /** Internal use: We have just successfully read data into an inbuf, so 395 * reset the read timeout (if any). */ 396 #define BEV_RESET_GENERIC_READ_TIMEOUT(bev) \ 397 do { \ 398 if (evutil_timerisset(&(bev)->timeout_read)) \ 399 event_add(&(bev)->ev_read, &(bev)->timeout_read); \ 400 } while (0) 401 /** Internal use: We have just successfully written data from an inbuf, so 402 * reset the read timeout (if any). */ 403 #define BEV_RESET_GENERIC_WRITE_TIMEOUT(bev) \ 404 do { \ 405 if (evutil_timerisset(&(bev)->timeout_write)) \ 406 event_add(&(bev)->ev_write, &(bev)->timeout_write); \ 407 } while (0) 408 #define BEV_DEL_GENERIC_READ_TIMEOUT(bev) \ 409 event_del(&(bev)->ev_read) 410 #define BEV_DEL_GENERIC_WRITE_TIMEOUT(bev) \ 411 event_del(&(bev)->ev_write) 412 413 414 /** Internal: Given a bufferevent, return its corresponding 415 * bufferevent_private. */ 416 #define BEV_UPCAST(b) EVUTIL_UPCAST((b), struct bufferevent_private, bev) 417 418 #ifdef EVENT__DISABLE_THREAD_SUPPORT 419 #define BEV_LOCK(b) EVUTIL_NIL_STMT_ 420 #define BEV_UNLOCK(b) EVUTIL_NIL_STMT_ 421 #else 422 /** Internal: Grab the lock (if any) on a bufferevent */ 423 #define BEV_LOCK(b) do { \ 424 struct bufferevent_private *locking = BEV_UPCAST(b); \ 425 EVLOCK_LOCK(locking->lock, 0); \ 426 } while (0) 427 428 /** Internal: Release the lock (if any) on a bufferevent */ 429 #define BEV_UNLOCK(b) do { \ 430 struct bufferevent_private *locking = BEV_UPCAST(b); \ 431 EVLOCK_UNLOCK(locking->lock, 0); \ 432 } while (0) 433 #endif 434 435 436 /* ==== For rate-limiting. */ 437 438 int bufferevent_decrement_write_buckets_(struct bufferevent_private *bev, 439 ev_ssize_t bytes); 440 int bufferevent_decrement_read_buckets_(struct bufferevent_private *bev, 441 ev_ssize_t bytes); 442 ev_ssize_t bufferevent_get_read_max_(struct bufferevent_private *bev); 443 ev_ssize_t bufferevent_get_write_max_(struct bufferevent_private *bev); 444 445 int bufferevent_ratelim_init_(struct bufferevent_private *bev); 446 447 #ifdef __cplusplus 448 } 449 #endif 450 451 452 #endif /* BUFFEREVENT_INTERNAL_H_INCLUDED_ */ 453