Path: blob/main/contrib/libevent/bufferevent_async.c
39475 views
/*1* Copyright (c) 2009-2012 Niels Provos and Nick Mathewson2*3* All rights reserved.4*5* Redistribution and use in source and binary forms, with or without6* modification, are permitted provided that the following conditions7* are met:8* 1. Redistributions of source code must retain the above copyright9* notice, this list of conditions and the following disclaimer.10* 2. Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13* 3. The name of the author may not be used to endorse or promote products14* derived from this software without specific prior written permission.15*16* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR17* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES18* 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, BUT21* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,22* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY23* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT24* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF25* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.26*/2728#include "event2/event-config.h"29#include "evconfig-private.h"3031#ifdef EVENT__HAVE_SYS_TIME_H32#include <sys/time.h>33#endif3435#include <errno.h>36#include <stdio.h>37#include <stdlib.h>38#include <string.h>39#ifdef EVENT__HAVE_STDARG_H40#include <stdarg.h>41#endif42#ifdef EVENT__HAVE_UNISTD_H43#include <unistd.h>44#endif4546#ifdef _WIN3247#include <winsock2.h>48#include <winerror.h>49#include <ws2tcpip.h>50#endif5152#include <sys/queue.h>5354#include "event2/util.h"55#include "event2/bufferevent.h"56#include "event2/buffer.h"57#include "event2/bufferevent_struct.h"58#include "event2/event.h"59#include "event2/util.h"60#include "event-internal.h"61#include "log-internal.h"62#include "mm-internal.h"63#include "bufferevent-internal.h"64#include "util-internal.h"65#include "iocp-internal.h"6667#ifndef SO_UPDATE_CONNECT_CONTEXT68/* Mingw is sometimes missing this */69#define SO_UPDATE_CONNECT_CONTEXT 0x701070#endif7172/* prototypes */73static int be_async_enable(struct bufferevent *, short);74static int be_async_disable(struct bufferevent *, short);75static void be_async_destruct(struct bufferevent *);76static int be_async_flush(struct bufferevent *, short, enum bufferevent_flush_mode);77static int be_async_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);7879struct bufferevent_async {80struct bufferevent_private bev;81struct event_overlapped connect_overlapped;82struct event_overlapped read_overlapped;83struct event_overlapped write_overlapped;84size_t read_in_progress;85size_t write_in_progress;86unsigned ok : 1;87unsigned read_added : 1;88unsigned write_added : 1;89};9091const struct bufferevent_ops bufferevent_ops_async = {92"socket_async",93evutil_offsetof(struct bufferevent_async, bev.bev),94be_async_enable,95be_async_disable,96NULL, /* Unlink */97be_async_destruct,98bufferevent_generic_adj_timeouts_,99be_async_flush,100be_async_ctrl,101};102103static inline void104be_async_run_eventcb(struct bufferevent *bev, short what, int options)105{ bufferevent_run_eventcb_(bev, what, options|BEV_TRIG_DEFER_CALLBACKS); }106107static inline void108be_async_trigger_nolock(struct bufferevent *bev, short what, int options)109{ bufferevent_trigger_nolock_(bev, what, options|BEV_TRIG_DEFER_CALLBACKS); }110111static inline int112fatal_error(int err)113{114switch (err) {115/* We may have already associated this fd with a port.116* Let's hope it's this port, and that the error code117* for doing this neer changes. */118case ERROR_INVALID_PARAMETER:119return 0;120}121return 1;122}123124static inline struct bufferevent_async *125upcast(struct bufferevent *bev)126{127struct bufferevent_async *bev_a;128if (!BEV_IS_ASYNC(bev))129return NULL;130bev_a = EVUTIL_UPCAST(bev, struct bufferevent_async, bev.bev);131return bev_a;132}133134static inline struct bufferevent_async *135upcast_connect(struct event_overlapped *eo)136{137struct bufferevent_async *bev_a;138bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, connect_overlapped);139EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));140return bev_a;141}142143static inline struct bufferevent_async *144upcast_read(struct event_overlapped *eo)145{146struct bufferevent_async *bev_a;147bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, read_overlapped);148EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));149return bev_a;150}151152static inline struct bufferevent_async *153upcast_write(struct event_overlapped *eo)154{155struct bufferevent_async *bev_a;156bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, write_overlapped);157EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));158return bev_a;159}160161static void162bev_async_del_write(struct bufferevent_async *beva)163{164struct bufferevent *bev = &beva->bev.bev;165166if (beva->write_added) {167beva->write_added = 0;168event_base_del_virtual_(bev->ev_base);169}170}171172static void173bev_async_del_read(struct bufferevent_async *beva)174{175struct bufferevent *bev = &beva->bev.bev;176177if (beva->read_added) {178beva->read_added = 0;179event_base_del_virtual_(bev->ev_base);180}181}182183static void184bev_async_add_write(struct bufferevent_async *beva)185{186struct bufferevent *bev = &beva->bev.bev;187188if (!beva->write_added) {189beva->write_added = 1;190event_base_add_virtual_(bev->ev_base);191}192}193194static void195bev_async_add_read(struct bufferevent_async *beva)196{197struct bufferevent *bev = &beva->bev.bev;198199if (!beva->read_added) {200beva->read_added = 1;201event_base_add_virtual_(bev->ev_base);202}203}204205static void206bev_async_consider_writing(struct bufferevent_async *beva)207{208size_t at_most;209int limit;210struct bufferevent *bev = &beva->bev.bev;211212/* Don't write if there's a write in progress, or we do not213* want to write, or when there's nothing left to write. */214if (beva->write_in_progress || beva->bev.connecting)215return;216if (!beva->ok || !(bev->enabled&EV_WRITE) ||217!evbuffer_get_length(bev->output)) {218bev_async_del_write(beva);219return;220}221222at_most = evbuffer_get_length(bev->output);223224/* This is safe so long as bufferevent_get_write_max never returns225* more than INT_MAX. That's true for now. XXXX */226limit = (int)bufferevent_get_write_max_(&beva->bev);227if (at_most >= (size_t)limit && limit >= 0)228at_most = limit;229230if (beva->bev.write_suspended) {231bev_async_del_write(beva);232return;233}234235/* XXXX doesn't respect low-water mark very well. */236bufferevent_incref_(bev);237if (evbuffer_launch_write_(bev->output, at_most,238&beva->write_overlapped)) {239bufferevent_decref_(bev);240beva->ok = 0;241be_async_run_eventcb(bev, BEV_EVENT_ERROR, 0);242} else {243beva->write_in_progress = at_most;244bufferevent_decrement_write_buckets_(&beva->bev, at_most);245bev_async_add_write(beva);246}247}248249static void250bev_async_consider_reading(struct bufferevent_async *beva)251{252size_t cur_size;253size_t read_high;254size_t at_most;255int limit;256struct bufferevent *bev = &beva->bev.bev;257258/* Don't read if there is a read in progress, or we do not259* want to read. */260if (beva->read_in_progress || beva->bev.connecting)261return;262if (!beva->ok || !(bev->enabled&EV_READ)) {263bev_async_del_read(beva);264return;265}266267/* Don't read if we're full */268cur_size = evbuffer_get_length(bev->input);269read_high = bev->wm_read.high;270if (read_high) {271if (cur_size >= read_high) {272bev_async_del_read(beva);273return;274}275at_most = read_high - cur_size;276} else {277at_most = 16384; /* FIXME totally magic. */278}279280/* XXXX This over-commits. */281/* XXXX see also not above on cast on bufferevent_get_write_max_() */282limit = (int)bufferevent_get_read_max_(&beva->bev);283if (at_most >= (size_t)limit && limit >= 0)284at_most = limit;285286if (beva->bev.read_suspended) {287bev_async_del_read(beva);288return;289}290291bufferevent_incref_(bev);292if (evbuffer_launch_read_(bev->input, at_most, &beva->read_overlapped)) {293beva->ok = 0;294be_async_run_eventcb(bev, BEV_EVENT_ERROR, 0);295bufferevent_decref_(bev);296} else {297beva->read_in_progress = at_most;298bufferevent_decrement_read_buckets_(&beva->bev, at_most);299bev_async_add_read(beva);300}301302return;303}304305static void306be_async_outbuf_callback(struct evbuffer *buf,307const struct evbuffer_cb_info *cbinfo,308void *arg)309{310struct bufferevent *bev = arg;311struct bufferevent_async *bev_async = upcast(bev);312313/* If we added data to the outbuf and were not writing before,314* we may want to write now. */315316bufferevent_incref_and_lock_(bev);317318if (cbinfo->n_added)319bev_async_consider_writing(bev_async);320321bufferevent_decref_and_unlock_(bev);322}323324static void325be_async_inbuf_callback(struct evbuffer *buf,326const struct evbuffer_cb_info *cbinfo,327void *arg)328{329struct bufferevent *bev = arg;330struct bufferevent_async *bev_async = upcast(bev);331332/* If we drained data from the inbuf and were not reading before,333* we may want to read now */334335bufferevent_incref_and_lock_(bev);336337if (cbinfo->n_deleted)338bev_async_consider_reading(bev_async);339340bufferevent_decref_and_unlock_(bev);341}342343static int344be_async_enable(struct bufferevent *buf, short what)345{346struct bufferevent_async *bev_async = upcast(buf);347348if (!bev_async->ok)349return -1;350351if (bev_async->bev.connecting) {352/* Don't launch anything during connection attempts. */353return 0;354}355356if (what & EV_READ)357BEV_RESET_GENERIC_READ_TIMEOUT(buf);358if (what & EV_WRITE)359BEV_RESET_GENERIC_WRITE_TIMEOUT(buf);360361/* If we newly enable reading or writing, and we aren't reading or362writing already, consider launching a new read or write. */363364if (what & EV_READ)365bev_async_consider_reading(bev_async);366if (what & EV_WRITE)367bev_async_consider_writing(bev_async);368return 0;369}370371static int372be_async_disable(struct bufferevent *bev, short what)373{374struct bufferevent_async *bev_async = upcast(bev);375/* XXXX If we disable reading or writing, we may want to consider376* canceling any in-progress read or write operation, though it might377* not work. */378379if (what & EV_READ) {380BEV_DEL_GENERIC_READ_TIMEOUT(bev);381bev_async_del_read(bev_async);382}383if (what & EV_WRITE) {384BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);385bev_async_del_write(bev_async);386}387388return 0;389}390391static void392be_async_destruct(struct bufferevent *bev)393{394struct bufferevent_async *bev_async = upcast(bev);395struct bufferevent_private *bev_p = BEV_UPCAST(bev);396evutil_socket_t fd;397398EVUTIL_ASSERT(!upcast(bev)->write_in_progress &&399!upcast(bev)->read_in_progress);400401bev_async_del_read(bev_async);402bev_async_del_write(bev_async);403404fd = evbuffer_overlapped_get_fd_(bev->input);405if (fd != (evutil_socket_t)EVUTIL_INVALID_SOCKET &&406(bev_p->options & BEV_OPT_CLOSE_ON_FREE)) {407evutil_closesocket(fd);408evbuffer_overlapped_set_fd_(bev->input, EVUTIL_INVALID_SOCKET);409}410}411412/* GetQueuedCompletionStatus doesn't reliably yield WSA error codes, so413* we use WSAGetOverlappedResult to translate. */414static void415bev_async_set_wsa_error(struct bufferevent *bev, struct event_overlapped *eo)416{417DWORD bytes, flags;418evutil_socket_t fd;419420fd = evbuffer_overlapped_get_fd_(bev->input);421WSAGetOverlappedResult(fd, &eo->overlapped, &bytes, FALSE, &flags);422}423424static int425be_async_flush(struct bufferevent *bev, short what,426enum bufferevent_flush_mode mode)427{428return 0;429}430431static void432connect_complete(struct event_overlapped *eo, ev_uintptr_t key,433ev_ssize_t nbytes, int ok)434{435struct bufferevent_async *bev_a = upcast_connect(eo);436struct bufferevent *bev = &bev_a->bev.bev;437evutil_socket_t sock;438439BEV_LOCK(bev);440441EVUTIL_ASSERT(bev_a->bev.connecting);442bev_a->bev.connecting = 0;443sock = evbuffer_overlapped_get_fd_(bev_a->bev.bev.input);444/* XXXX Handle error? */445setsockopt(sock, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);446447if (ok)448bufferevent_async_set_connected_(bev);449else450bev_async_set_wsa_error(bev, eo);451452be_async_run_eventcb(bev, ok ? BEV_EVENT_CONNECTED : BEV_EVENT_ERROR, 0);453454event_base_del_virtual_(bev->ev_base);455456bufferevent_decref_and_unlock_(bev);457}458459static void460read_complete(struct event_overlapped *eo, ev_uintptr_t key,461ev_ssize_t nbytes, int ok)462{463struct bufferevent_async *bev_a = upcast_read(eo);464struct bufferevent *bev = &bev_a->bev.bev;465short what = BEV_EVENT_READING;466ev_ssize_t amount_unread;467BEV_LOCK(bev);468EVUTIL_ASSERT(bev_a->read_in_progress);469470amount_unread = bev_a->read_in_progress - nbytes;471evbuffer_commit_read_(bev->input, nbytes);472bev_a->read_in_progress = 0;473if (amount_unread)474bufferevent_decrement_read_buckets_(&bev_a->bev, -amount_unread);475476if (!ok)477bev_async_set_wsa_error(bev, eo);478479if (bev_a->ok) {480if (ok && nbytes) {481BEV_RESET_GENERIC_READ_TIMEOUT(bev);482be_async_trigger_nolock(bev, EV_READ, 0);483bev_async_consider_reading(bev_a);484} else if (!ok) {485what |= BEV_EVENT_ERROR;486bev_a->ok = 0;487be_async_run_eventcb(bev, what, 0);488} else if (!nbytes) {489what |= BEV_EVENT_EOF;490bev_a->ok = 0;491be_async_run_eventcb(bev, what, 0);492}493}494495bufferevent_decref_and_unlock_(bev);496}497498static void499write_complete(struct event_overlapped *eo, ev_uintptr_t key,500ev_ssize_t nbytes, int ok)501{502struct bufferevent_async *bev_a = upcast_write(eo);503struct bufferevent *bev = &bev_a->bev.bev;504short what = BEV_EVENT_WRITING;505ev_ssize_t amount_unwritten;506507BEV_LOCK(bev);508EVUTIL_ASSERT(bev_a->write_in_progress);509510amount_unwritten = bev_a->write_in_progress - nbytes;511evbuffer_commit_write_(bev->output, nbytes);512bev_a->write_in_progress = 0;513514if (amount_unwritten)515bufferevent_decrement_write_buckets_(&bev_a->bev,516-amount_unwritten);517518519if (!ok)520bev_async_set_wsa_error(bev, eo);521522if (bev_a->ok) {523if (ok && nbytes) {524BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);525be_async_trigger_nolock(bev, EV_WRITE, 0);526bev_async_consider_writing(bev_a);527} else if (!ok) {528what |= BEV_EVENT_ERROR;529bev_a->ok = 0;530be_async_run_eventcb(bev, what, 0);531} else if (!nbytes) {532what |= BEV_EVENT_EOF;533bev_a->ok = 0;534be_async_run_eventcb(bev, what, 0);535}536}537538bufferevent_decref_and_unlock_(bev);539}540541struct bufferevent *542bufferevent_async_new_(struct event_base *base,543evutil_socket_t fd, int options)544{545struct bufferevent_async *bev_a;546struct bufferevent *bev;547struct event_iocp_port *iocp;548549options |= BEV_OPT_THREADSAFE;550551if (!(iocp = event_base_get_iocp_(base)))552return NULL;553554if (fd >= 0 && event_iocp_port_associate_(iocp, fd, 1)<0) {555if (fatal_error(GetLastError()))556return NULL;557}558559if (!(bev_a = mm_calloc(1, sizeof(struct bufferevent_async))))560return NULL;561562bev = &bev_a->bev.bev;563if (!(bev->input = evbuffer_overlapped_new_(fd))) {564mm_free(bev_a);565return NULL;566}567if (!(bev->output = evbuffer_overlapped_new_(fd))) {568evbuffer_free(bev->input);569mm_free(bev_a);570return NULL;571}572573if (bufferevent_init_common_(&bev_a->bev, base, &bufferevent_ops_async,574options)<0)575goto err;576577evbuffer_add_cb(bev->input, be_async_inbuf_callback, bev);578evbuffer_add_cb(bev->output, be_async_outbuf_callback, bev);579580event_overlapped_init_(&bev_a->connect_overlapped, connect_complete);581event_overlapped_init_(&bev_a->read_overlapped, read_complete);582event_overlapped_init_(&bev_a->write_overlapped, write_complete);583584bufferevent_init_generic_timeout_cbs_(bev);585586bev_a->ok = fd >= 0;587588return bev;589err:590bufferevent_free(&bev_a->bev.bev);591return NULL;592}593594void595bufferevent_async_set_connected_(struct bufferevent *bev)596{597struct bufferevent_async *bev_async = upcast(bev);598bev_async->ok = 1;599/* Now's a good time to consider reading/writing */600be_async_enable(bev, bev->enabled);601}602603int604bufferevent_async_can_connect_(struct bufferevent *bev)605{606const struct win32_extension_fns *ext =607event_get_win32_extension_fns_();608609if (BEV_IS_ASYNC(bev) &&610event_base_get_iocp_(bev->ev_base) &&611ext && ext->ConnectEx)612return 1;613614return 0;615}616617int618bufferevent_async_connect_(struct bufferevent *bev, evutil_socket_t fd,619const struct sockaddr *sa, int socklen)620{621BOOL rc;622struct bufferevent_async *bev_async = upcast(bev);623struct sockaddr_storage ss;624const struct win32_extension_fns *ext =625event_get_win32_extension_fns_();626627EVUTIL_ASSERT(ext && ext->ConnectEx && fd >= 0 && sa != NULL);628629/* ConnectEx() requires that the socket be bound to an address630* with bind() before using, otherwise it will fail. We attempt631* to issue a bind() here, taking into account that the error632* code is set to WSAEINVAL when the socket is already bound. */633memset(&ss, 0, sizeof(ss));634if (sa->sa_family == AF_INET) {635struct sockaddr_in *sin = (struct sockaddr_in *)&ss;636sin->sin_family = AF_INET;637sin->sin_addr.s_addr = INADDR_ANY;638} else if (sa->sa_family == AF_INET6) {639struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;640sin6->sin6_family = AF_INET6;641sin6->sin6_addr = in6addr_any;642} else {643/* Well, the user will have to bind() */644return -1;645}646if (bind(fd, (struct sockaddr *)&ss, sizeof(ss)) < 0 &&647WSAGetLastError() != WSAEINVAL)648return -1;649650event_base_add_virtual_(bev->ev_base);651bufferevent_incref_(bev);652rc = ext->ConnectEx(fd, sa, socklen, NULL, 0, NULL,653&bev_async->connect_overlapped.overlapped);654if (rc || WSAGetLastError() == ERROR_IO_PENDING)655return 0;656657event_base_del_virtual_(bev->ev_base);658bufferevent_decref_(bev);659660return -1;661}662663static int664be_async_ctrl(struct bufferevent *bev, enum bufferevent_ctrl_op op,665union bufferevent_ctrl_data *data)666{667switch (op) {668case BEV_CTRL_GET_FD:669data->fd = evbuffer_overlapped_get_fd_(bev->input);670return 0;671case BEV_CTRL_SET_FD: {672struct bufferevent_async *bev_a = upcast(bev);673struct event_iocp_port *iocp;674675if (data->fd == evbuffer_overlapped_get_fd_(bev->input))676return 0;677if (!(iocp = event_base_get_iocp_(bev->ev_base)))678return -1;679if (event_iocp_port_associate_(iocp, data->fd, 1) < 0) {680if (fatal_error(GetLastError()))681return -1;682}683evbuffer_overlapped_set_fd_(bev->input, data->fd);684evbuffer_overlapped_set_fd_(bev->output, data->fd);685bev_a->ok = data->fd >= 0;686return 0;687}688case BEV_CTRL_CANCEL_ALL: {689struct bufferevent_async *bev_a = upcast(bev);690evutil_socket_t fd = evbuffer_overlapped_get_fd_(bev->input);691if (fd != (evutil_socket_t)EVUTIL_INVALID_SOCKET &&692(bev_a->bev.options & BEV_OPT_CLOSE_ON_FREE)) {693closesocket(fd);694evbuffer_overlapped_set_fd_(bev->input, EVUTIL_INVALID_SOCKET);695}696bev_a->ok = 0;697return 0;698}699case BEV_CTRL_GET_UNDERLYING:700default:701return -1;702}703}704705706707708