]> git.ipfire.org Git - thirdparty/ntp.git/commitdiff
update to libevent git master, after 2.1.1-alpha, as of 14-Jun-2012 git cset
authorDave Hart <hart@ntp.org>
Thu, 14 Jun 2012 22:20:00 +0000 (22:20 +0000)
committerDave Hart <hart@ntp.org>
Thu, 14 Jun 2012 22:20:00 +0000 (22:20 +0000)
e7bf4c84afd7961eb92a2d6583c84b56a87f2555

bk: 4fda63908xZEDuVmObXa2pCfpT-46g

149 files changed:
sntp/libevent/ChangeLog
sntp/libevent/ChangeLog-1.4 [new file with mode: 0644]
sntp/libevent/ChangeLog-2.0 [new file with mode: 0644]
sntp/libevent/Doxyfile
sntp/libevent/LICENSE
sntp/libevent/Makefile.am
sntp/libevent/Makefile.nmake
sntp/libevent/README
sntp/libevent/WIN32-Code/evconfig-private.h
sntp/libevent/WIN32-Code/event2/event-config.h
sntp/libevent/arc4random.c
sntp/libevent/buffer.c
sntp/libevent/buffer_iocp.c
sntp/libevent/bufferevent-internal.h
sntp/libevent/bufferevent.c
sntp/libevent/bufferevent_async.c
sntp/libevent/bufferevent_filter.c
sntp/libevent/bufferevent_openssl.c
sntp/libevent/bufferevent_pair.c
sntp/libevent/bufferevent_ratelim.c
sntp/libevent/bufferevent_sock.c
sntp/libevent/changelist-internal.h
sntp/libevent/compat/sys/queue.h
sntp/libevent/configure.in
sntp/libevent/defer-internal.h
sntp/libevent/devpoll.c
sntp/libevent/epoll.c
sntp/libevent/epoll_sub.c
sntp/libevent/evbuffer-internal.h
sntp/libevent/evconfig-private.h.in
sntp/libevent/evdns.c
sntp/libevent/event-internal.h
sntp/libevent/event.c
sntp/libevent/event_iocp.c
sntp/libevent/event_rpcgen.py
sntp/libevent/event_tagging.c
sntp/libevent/evmap-internal.h
sntp/libevent/evmap.c
sntp/libevent/evport.c
sntp/libevent/evrpc-internal.h
sntp/libevent/evrpc.c
sntp/libevent/evsignal-internal.h
sntp/libevent/evthread-internal.h
sntp/libevent/evthread.c
sntp/libevent/evthread_pthread.c
sntp/libevent/evthread_win32.c
sntp/libevent/evutil.c
sntp/libevent/evutil_rand.c
sntp/libevent/evutil_time.c [new file with mode: 0644]
sntp/libevent/ht-internal.h
sntp/libevent/http-internal.h
sntp/libevent/http.c
sntp/libevent/include/Makefile.am
sntp/libevent/include/evdns.h [moved from sntp/libevent/evdns.h with 88% similarity]
sntp/libevent/include/event.h [moved from sntp/libevent/event.h with 91% similarity]
sntp/libevent/include/event2/buffer.h
sntp/libevent/include/event2/buffer_compat.h
sntp/libevent/include/event2/bufferevent.h
sntp/libevent/include/event2/bufferevent_compat.h
sntp/libevent/include/event2/bufferevent_ssl.h
sntp/libevent/include/event2/bufferevent_struct.h
sntp/libevent/include/event2/dns.h
sntp/libevent/include/event2/dns_compat.h
sntp/libevent/include/event2/dns_struct.h
sntp/libevent/include/event2/event.h
sntp/libevent/include/event2/event_compat.h
sntp/libevent/include/event2/event_struct.h
sntp/libevent/include/event2/http.h
sntp/libevent/include/event2/http_compat.h
sntp/libevent/include/event2/http_struct.h
sntp/libevent/include/event2/keyvalq_struct.h
sntp/libevent/include/event2/listener.h
sntp/libevent/include/event2/rpc.h
sntp/libevent/include/event2/rpc_compat.h
sntp/libevent/include/event2/rpc_struct.h
sntp/libevent/include/event2/tag.h
sntp/libevent/include/event2/tag_compat.h
sntp/libevent/include/event2/thread.h
sntp/libevent/include/event2/util.h
sntp/libevent/include/evhttp.h [moved from sntp/libevent/evhttp.h with 88% similarity]
sntp/libevent/include/evrpc.h [moved from sntp/libevent/evrpc.h with 88% similarity]
sntp/libevent/include/evutil.h [moved from sntp/libevent/evutil.h with 90% similarity]
sntp/libevent/iocp-internal.h
sntp/libevent/ipv6-internal.h
sntp/libevent/kqueue-internal.h [new file with mode: 0644]
sntp/libevent/kqueue.c
sntp/libevent/listener.c
sntp/libevent/log-internal.h
sntp/libevent/log.c
sntp/libevent/m4/libevent_openssl.m4
sntp/libevent/make-event-config.sed [new file with mode: 0644]
sntp/libevent/minheap-internal.h
sntp/libevent/mm-internal.h
sntp/libevent/poll.c
sntp/libevent/ratelim-internal.h
sntp/libevent/sample/Makefile.am
sntp/libevent/sample/dns-example.c
sntp/libevent/sample/event-read-fifo.c [moved from sntp/libevent/sample/event-test.c with 58% similarity]
sntp/libevent/sample/http-server.c
sntp/libevent/sample/signal-test.c
sntp/libevent/sample/time-test.c
sntp/libevent/select.c
sntp/libevent/signal.c
sntp/libevent/strlcpy-internal.h
sntp/libevent/strlcpy.c
sntp/libevent/test/Makefile.am
sntp/libevent/test/bench.c
sntp/libevent/test/bench_cascade.c
sntp/libevent/test/bench_http.c
sntp/libevent/test/bench_httpclient.c
sntp/libevent/test/check-dumpevents.py [new file with mode: 0755]
sntp/libevent/test/regress.c
sntp/libevent/test/regress.h
sntp/libevent/test/regress_buffer.c
sntp/libevent/test/regress_bufferevent.c
sntp/libevent/test/regress_dns.c
sntp/libevent/test/regress_et.c
sntp/libevent/test/regress_http.c
sntp/libevent/test/regress_iocp.c
sntp/libevent/test/regress_listener.c
sntp/libevent/test/regress_main.c
sntp/libevent/test/regress_minheap.c
sntp/libevent/test/regress_rpc.c
sntp/libevent/test/regress_ssl.c
sntp/libevent/test/regress_testutils.c
sntp/libevent/test/regress_testutils.h
sntp/libevent/test/regress_thread.c
sntp/libevent/test/regress_util.c
sntp/libevent/test/regress_zlib.c
sntp/libevent/test/test-changelist.c
sntp/libevent/test/test-dumpevents.c [new file with mode: 0644]
sntp/libevent/test/test-eof.c
sntp/libevent/test/test-fdleak.c [new file with mode: 0644]
sntp/libevent/test/test-init.c
sntp/libevent/test/test-ratelim.c
sntp/libevent/test/test-ratelim.sh
sntp/libevent/test/test-time.c
sntp/libevent/test/test-weof.c
sntp/libevent/test/test.sh
sntp/libevent/test/tinytest.c
sntp/libevent/test/tinytest.h
sntp/libevent/test/tinytest_demo.c
sntp/libevent/test/tinytest_local.h
sntp/libevent/test/tinytest_macros.h
sntp/libevent/time-internal.h [new file with mode: 0644]
sntp/libevent/util-internal.h
sntp/libevent/whatsnew-2.0.txt
sntp/libevent/whatsnew-2.1.txt [new file with mode: 0644]
sntp/libevent/win32select.c

index 520e7397d4822a6ca87c53c2590d173aa3f5339a..274141bb473837e5b3c9a2c9b800946d3b60664f 100644 (file)
-Changes in version 2.0.14-stable (?? ??? 2011)
-BUGFIXES (bufferevents and evbuffers):
- o Propagate errors on the underlying bufferevent to the user. (4a34394 Joachim Bauch)
- o Ignore OpenSSL deprecation warnings on OS X (5d1b255 Sebastian Hahn)
- o Fix handling of group rate limits under 64 bytes of burst (6d5440e)
- o Solaris sendfile: correctly detect amount of data sent (643922e Michael Herf)
- o Make rate limiting work with common_timeout logic (5b18f13)
+Changes in version 2.1.2-alpha (?? ??? 2012)
+
+Changes in version 2.1.1-alpha (4 Apr 2012)
+
+ Libevent 2.1.1-alpha includes a number of new features and performance
+ improvements.  The log below tries to organize them by rough area of
+ effect.  It omits some commits which were pure bugfixes on other commits
+ listed below.  For more detail, see the git changelogs.  For more
+ insight, see the "whatsnew-2.1.txt" document included in the Libevent
+ 2.1.1-alpha distribution.
+
+ Performance: Core
+   o Replace several TAILQ users with LIST. LIST can be a little faster than
+     TAILQ for cases where we don't need queue-like behavior. (f9db33d,
+     6494772, d313c29, 974d004)
+   o Disabled code to optimize the case where we reinsert an existing
+     timeout (e47042f, 09cbc3d)
+   o Remove a needless base-notify when rescheduling the first timeout (77a96fd)
+   o Save a needless comparison when removing/adjusting timeouts (dd5189b)
+   o Possible optimization: split event_queue_insert/remove into
+     separate functions. needs testing (efc4dc5)
+   o Make event_count maintenance branchless at the expense of an
+     extra shift. Needs benchmarking (d1cee3b)
+   o In the 2.1 branch, let's try out lazy gettimeofday/clock_gettime
+     comparison (2a83ecc)
+   o Optimization in event_process_active(): ignore maxcb & endtime
+     for highest priority events. (a9866aa Alexander Drozdov)
+   o Bypass event_add when using event_base_once() for a 0-sec timeout (35c5c95)
+   o Remove the eventqueue list and the ev_next pointers. (604569b 066775e)
+
+ Performance: Evbuffers
+   o Roughly 20% speed increase when line-draining a buffer using
+     EVBUFFER_EOL_CRLF (5dde0f0 Mina Naguib)
+   o Try to squeeze a little more speed out of EVBUFFER_EOL_CRLF (7b9d139)
+   o Fix a bug in the improved EOL_CRLF code (d927965)
+   o Remove a needless branch in evbuffer_drain() (d19a326)
+
+ Performance: Linux
+   o Infrastructure for using faster/fewer syscalls when creating
+     sockets (a1c042b)
+   o Minimize syscalls during socket creation in listener.c (7e9e289)
+   o Use a wrapper function to create the notification
+     pipe/socketpair/eventfd (ca76cd9)
+   o Use pipes for telling signals to main thread when possible (a35f396)
+   o Save syscalls when constructing listener sockets for evhttp (af6c9d8)
+   o Save some syscalls when creating evdns sockets (713e570)
+   o Save some syscalls when constructing a socket for a bufferevent (33fca62)
+   o Prefer epoll_create1 on Linuxen that have it (bac906c)
+
+ Performance: Epoll backend
+   o Use current event set rather than current pending change when
+     deciding whether to no-op a del (04ba27e Mike Smellie)
+   o Replace big chain of if/thens in epoll.c with a table lookup (8c83eb6)
+   o Clean up error handling in epoll_apply_one_change() a little (2d55a19)
+
+ Performance: Evport backend
+   o evport: use evmap_io to track fdinfo status. Should save time and
+     RAM. (4687ce4)
+   o evport: Remove a linear search over recent events when
+     reactivating them (0f77efe)
+   o evport: Use portev_user to remember fdinfo struct (276ec0e)
+   o evport: don't scan more events in ed_pending than needed (849a5cf)
+   o evport: Remove artificial low limit on max events per getn call (c04d927)
+   o Reenable main/many_events_slow_add for evport in 2.1 (e903db3)
+
+ Performance: Windows
+   o Use GetSystemTimeAsFileTime to implement gettimeofday on
+     win32. It's faster and more accurate than our old
+     approach. (b8b8aa5)
+
+ New functions and features: debugging
+   o Add event_enable_debug_logging() to control use of debug logs (e30a82f)
+
+ New functions and features: core
+   o Add event_config function to limit time/callbacks between calls
+     to dispatch (fd4de1e, 9fa56bd, a37a0c0, 3c63edd)
+   o New EVLOOP_NO_EXIT_ON_EMPTY option to keep looping even when no
+     events are pending (084e68f)
+   o Add event_base_get_npriorities() function. (ee3a4ee Alexander Drozdov)
+   o Make evbase_priority_init() and evbase_get_npriorities()
+     threadsafe (3c55b5e)
+   o New event_base_update_cache_time() to set cached_tv to current
+     time (212533e Abel Mathew)
+   o Add event_self_cbarg() to be used in conjunction with
+     event_new(). (ed36e6a Ross Lagerwall, fa931bb, 09a1906, 1338e6c,
+     33e43ef)
+   o Add a new libevent_global_shutdown() to free all globals before
+     exiting. (041ca00 Mark Ellzey, f98c158, 15296d0, 55e991b)
+   o Use getifaddrs to detect our interfaces if possible (7085a45)
+   o Add event_base_get_running_event() to get the event* whose cb we
+     are in (c5732fd, 13dad99)
+
+ New functions and features: building
+   o Implement --enable-gcc-hardening configure option (7550267 Sebastian Hahn)
+
+ New functions and features: evbuffers
+   o Add evbuffer_add_file_segment() so one fd can be used efficiently
+     in more than one evbuffer_add_file at a time (e72afae, c2d9884,
+     3f405d2, 0aad014)
+   o Fix windows file segment mappings (8254de7)
+   o Allow evbuffer_ptr_set to yield a point just after the end of the
+     buffer. (e6fe1da)
+   o Allow evbuffer_ptr to point to position 0 in an empty evbuffer
+     (7aeb2fd Nir Soffer)
+   o Set the special "not found" evbuffer_ptr consistently. (e3e97ae Nir Soffer)
+   o support adding buffers to other buffers non-destructively
+     (9d7368a Joachim Bauch)
+   o prevent nested multicast references, reworked locking (26041a8
+     Joachim Bauch)
+   o New EVBUFFER_EOL_NUL to read NUL-terminated strings from an
+     evbuffer (d7a8b36 Andrea Montefusco, 54142c9)
+   o Make evbuffer_file_segment_types adaptable (c6bbbf1)
+   o Added evbuffer_add_iovec and unit tests. (aaec5ac Mark Ellzey, 27b5398)
+   o Add evbuffer_copyout_from to copy data from the middle of a
+     buffer (27e2225)
+
+ New functions and features: bufferevents
+   o Allow users to set allow_dirty_shutdown (099d27d Catalin Patulea)
+   o Tweak allow_dirty_shutdown documentation (a44cd2b)
+   o Fix two issues in the allow_dirty_shutdown code. (f3b89de)
+   o Add a bufferevent_getcb() to find a bufferevent's current
+     callbacks (a650394)
+   o bufferevent: Add functions to set/get max_single_read/write
+     values. (998c813 Alexander Drozdov)
+   o bev_ssl: Be more specific in event callbacks. evhttp in particular gets
+     confused without at least one of BEV_EVENT_{READING|WRITING}. (f7eb69a
+     Catalin Patulea)
+
+ New functions and features: evconnlisteners
+   o Support TCP_DEFER_ACCEPT sockopts for listeners (5880e4a Mark Ellzey,
+     a270728)
+   o Add another caveat to the TCP_DEFER_ACCEPT documentation (a270728)
+   o Allow evconnlistener to be created in disabled state. (9593a33
+     Alexander Drozdov)
+   o The LEV_OPT_CLOSE_ON_EXEC flag now applies to accepted listener
+     sockets too (4970329)
+
+ Evhttp:
+   o Add new evhttp_{connection_}set_timeout_tv() functions to set
+     finger-grained http timeouts (6350e6c Constantine Verutin)
+   o Performance tweak to evhttp_parse_request_line. (aee1a97 Mark Ellzey)
+   o Add missing break to evhttp_parse_request_line (0fcc536)
+   o Add evhttp callback for bufferevent creation; this lets evhttp
+     support SSL. (8d3a850)
+   o Remove calls to deprecated bufferevent functions from evhttp.c (4d63758)
+   o evhttp: Add evhttp_foreach_bound_socket. (a2c48e3 Samy Al Bahra)
+
+ Build improvements:
+   o Add AC_USE_SYSTEM_EXTENSIONS to configure.in. Requires follow on
+     patches for correctness and robustness. (1fa7dbe Kevin Bowling)
+   o Filter '# define' statements from autoconf and generate
+     event-private.h (321b558 Kevin Bowling)
+   o Remove internal usage of _GNU_SOURCE (3b26541 Kevin Bowling)
+   o Eliminate a couple more manual internal _GNU_SOURCE defines (c51ef93
+     Kevin Bowling)
+   o Add AC_GNU_SOURCE to the fallback case. (ea8fa4c Kevin Bowling)
+   o Use a Configuration Header Template for evconfig-private.h (868f888
+     Kevin Bowling)
+   o Fix a comment warning and add evconfig-private.h to .gitignore
+     (f6d66bc Kevin Bowling)
+   o Include evconfig-private.h in internal files for great good. (0915ca0
+     Kevin Bowling)
+   o Backport libevent to vanilla Autoconf 2.59 (as used in RHEL5)
+     (ad03952 Kevin Bowling)
+   o Prefer the ./configure evconfig-private.h in MinGW, just in
+     case. (f964b72 Kevin Bowling)
+   o Shell hack for weird mkdir -p commands (fd7b5a8 Kevin Bowling)
+   o Add evconfig-private to remaining files (ded0a09 Kevin Bowling)
+   o Allow use of --enable-silent-rules for quieter compilation with
+     automake 1.11 (f1f8514 Dave Hart)
+   o Use "_WIN32", not WIN32: it's standard and we don't need to fake it
+     (9f560b)
+   o In configure, test for _WIN32 not WIN32. (85078b1 Peter Rosin)
+   o Do not define WIN32 in Makefile.nmake (d41f3ea Peter Rosin)
+   o Provide the autoconf m4 macros for the new OpenSSL via pkg-config
+     stuff. (674dc3d Harlan Stenn)
+   o Use pkg-config (if available) to handle OpenSSL. (1c63860 Harlan Stenn)
+   o We need AM_CPPFLAGS when compiling bufferevent_openssl.c (6d2613b
+     Harlan Stenn)
+   o Fix OSX build: $(OPENSSL_INCS) needs to be after
+     $(AM_CPPFLAGS). (46f1769 Zack Weinberg)
+   o Make gcc warnings on by default, and --enable-gcc-warnings only add
+     -Werror (d46517e Sebastian Hahn)
+   o Split up extra-long AC_CHECK_FUNCS/HEADERS lines in configure.in (88a30ad)
+   o Move libevent 1.x headers to include/, to put all public headers in
+     one place. (bbea8d6)
+   o Put #ifdef around some files to support alternate build
+     systems. (76d4c92 Ross Lagerwall)
+   o Also make win32select.c conditional for IDE users (bf2c5a7)
+
+ Debugging:
+   o Add a magic number to debug_locks to better catch lock-coding
+     errors. (b4a29c0 Dave Hart)
+   o munge the debug_lock signature before freeing it: it might help us
+     catch use-after-free (f28084d)
+   o Added --enable-event-debugging in configure (bc7b4e4, a9c2c9a Mark Ellzey)
+   o Debug addition for printing usec on TIMEOUT debugging. (ac43ce0 Mark Ellzey)
+   o Added usec debug in another area for debug (3baab0d Mark Ellzey)
+   o added timeout debug logs to include event ptr. (4b7d298 Mark Ellzey)
+   o more event dbg updates (6727543 Mark Ellzey)
+   o Clarify event_enable_debug_logging a little (6207826)
+   o Make --enable-verbose-debug option match its help text (10c3450)
+   o Add argument checks to some memory functions in `event.c'. (c8953d1
+     Mansour Moufid)
+
+ Testing:
+   o More abstraction in test.sh (cd74c4e)
+   o Add failing test for evbuffer_search_range. (8e26154 Nir Soffer)
+   o Tweaks to return types with end-of-buf ptrs (9ab8ab8)
+   o Add an (internal) usleep function for use by unit tests (f25d9d3)
+   o Synchronize with upstream tinytest (6c81be7)
+   o Make test-changelist faster (7622d26)
+   o Reduce the timeout in the main/fork test. (ab14f7c)
+   o New evhttp function to adjust initial retry timeout (350a3c4)
+   o Make regression tests run over 3x faster. (67a1763)
+   o Use test_timeval_diff_eq more consistently (b77b43f)
+   o Allow more slop in deferred_cb_skew test; freebsd needs it (b9f7e5f)
+   o When including an -internal.h header outside the main tree, do so
+     early (95e2455)
+   o Add a new test: test-fdleak which tests for fd leaks by creating many
+     sockets. (2ef9278 Ross Lagerwall, f7af194, 1c4288f, etc)
+   o Add a unit test for event_base_dump_events() (7afe48a, 8d08cce)
+   o Test more bufferevent_ratelim features (c24f91a)
+
+ Documentation:
+   o Improve evbuffer_ptr documentation (261ba63)
+   o added comments to describe refcounting of multicast chains (ba24f61
+     Joachim Bauch)
+   o Add doxygen for event_base_dump_events (cad5753)
+
+ OSX:
+   o Use "unlimited select" on OSX so that we can have more than
+     FD_SETSIZE fds (1fb5cc6)
+
+ KQueue:
+   o Use SIG_IGN instead of a do-nothing handler for signal events with
+     kqueue (148458e Zack Weinberg)
+
+ evprc:
+   o event_rpcgen.py now prints status information to stdout and errors to
+     stderr. (ffb0ba0 Ross Lagerwall)
+
+ Code improvement and refactoring:
+   o Make event_reinit() more robust and maintainable (272033e)
+   o Restore fast-path event_reinit() for slower backends (2c4b5de)
+   o Check changelist as part of checking representational integrity (39b3f38)
+   o Fix a compile warning in event_reinit (e4a56ed Sebastian Hahn)
+   o Refactor the functions that run over every event. (c89b4e6)
+   o Remove the last vestiges of _EVENT_USE_EVENTLIST (a3cec90)
+   o Make event-config.h depend on Makefile.am (2958a5c)
+
+ Build fixes:
+   o Don't do clang version detection when disabling some flags (083296b
+     Sebastian Hahn)
+
+ C standards conformance:
+   o Check for NULL return on win32 mm_calloc, and set ENOMEM. (af7ba69)
+   o Convert event-config.h macros to avoid reserved identifiers (68120d9)
+   o Generate event-config.h using the correct macros. (f82c57e)
+   o Convert include-guard macro convention to avoid reserved identifiers
+     (3f8c7cd)
+   o Make event_rpcgen.py output conform to identifier conventions (372bff1)
+   o Stop referring to an obsolete include guard in bench_http.h (5c0f7e0)
+   o Make the generated event-config.h use correct include guards (639383a)
+   o Fix all identifiers with names beginning with underscore. (cb9da0b)
+   o Make event_rpcgen.py output conform to identifier conventions, more
+     (bcefd24)
+   o Fix some problems introduced by automated identifier cleanup script
+     (c963534)
+   o Have all visible internal function names end with an underscore. (8ac3c4c)
+   o Apply the naming convention to our EVUTIL_IS* functions (c7848fa)
+   o Clean up lingering _identifiers. (946b584)
+   o Fix doxygen to use new macro conventions (da455e9)
+
+ Bugfixes:
+   o Do not use system EAI/AI values if we are not using the system
+     getaddrinfo. (7bcac07)
+
+ Sample Code:
+   o Fix up sample/event-test.c to use newer interfaces and make it
+     actually work. (19bab4f Ross Lagerwall)
+   o On Unix, remove event.fifo left by sample/event-test.c. (c0dacd2 Ross
+     Lagerwall)
+   o Rename event-test.c to event-read-fifo.c. (a5b370a Ross Lagerwall)
+   o event-read-fifo: Use EV_PERSIST appropriately (24dab0b)
 
-BUGFIXES (IOCP):
- o IOCP: don't launch reads or writes on an unconnected socket (495c227)
- o Make IOCP rate-limiting group support stricter and less surprising. (a98da7b)
- o Have test-ratelim.c support IOCP (0ff2c5a)
- o Make overlapped reads result in evbuffer callbacks getting invoked (6acfbdd)
- o Correctly terminate IO on an async bufferevent on bufferevent_free (e6af35d)
 
-BUGFIXES (other):
- o Fix evsig_dealloc memory leak with debugging turned on. (9b724b2 Leonid Evdokimov)
- o Fix request_finished memory leak with debugging turned on. (aff6ba1 Leonid Evdokimov)
 
-BUILD AND TESTING FIXES:
- o Allow OS-neutral builds for platforms where some versions have arc4random_buf (b442302 Mitchell Livingston)
- o Try to fix 'make distcheck' errors when building out-of-tree (04656ea Dave Hart)
- o Clean up some problems identified by Coverity. (7c11e51 Harlan Stenn)
 
-
-Changes in version 2.0.13-stable (18 Jul 2011)
-BUGFIXES
- o Avoid race-condition when initializing global locks (b683cae)
- o Fix bug in SSL bufferevents backed by a bev with a write high-watermarks (e050703 Joachim Bauch)
- o Speed up invoke_callbacks on evbuffers when there are no callbacks (f87f568 Mark Ellzey)
- o Avoid a segfault when all methods are disabled or broken (27ce38b)
- o Fix incorrect results from evbuffer_search_eol(EOL_LF) (4461f1a)
- o Add some missing checks for mm_calloc failures (89d5e09)
- o Replace an assertion for event_base_free(NULL) with a check-and-warn (09fe97d)
- o Report kqueue ebadf, epipe, and eperm as EV_READ events (1fd34ab)
- o Check if the `evhttp_new_object' function in `http.c' returns NULL. (446cc7a Mansour Moufid)
- o Use the correct printf args when formatting size_t (3203f88)
- o Complain if the caller tries to change threading cbs after setting them (cb6ecee)
-
-DOCUMENTATION FIXES AND IMPROVEMENTS
- o Revise the event/evbuffer/bufferevent doxygen for clarity and accuracy (2888fac)
- o Update Doxyfile to produce more useful output (aea0555)
-
-TEST FIXES
- o Fix up test_evutil_snprintf (caf695a)
- o Fix tinytest invocation from windows shell (57def34 Ed Day)
-
-BUILD FIXES
- o Use AM_CPPFLAGS in sample/Makefile.am, not AM_CFLAGS (4a5c82d)
- o Fix select.c compilation on systems with no NFDBITS (49d1136)
- o Fix a few warnings on OpenBSD (8ee9f9c Nicholas Marriott)
- o Don't break when building tests from git without python installed (b031adf)
- o Don't install event_rpcgen.py when --disable-libevent-install is used (e23cda3 Harlan Stenn)
- o Fix AIX build issue with TAILQ_FOREACH definition (e934096)
-
-
-Changes in version 2.0.12-stable (4 Jun 2011)
-BUGFIXES
- o Fix a warn-and-fail bug in kqueue by providing kevent() room to report errors (28317a0)
- o Fix an assert-inducing fencepost bug in the select backend (d90149d)
- o Fix failing http assertion introducd in commit 0d6622e (0848814 Kevin Ko)
- o Fix a bug that prevented us from configuring IPv6 nameservers. (74760f1)
- o Prevent size_t overflow in evhttp_htmlescape. (06c51cd Mansour Moufid)
- o Added several checks for under/overflow conditions in evhttp_handle_chunked_read (a279272 Mark Ellzey)
- o Added overflow checks in evhttp_read_body and evhttp_get_body (84560fc Mark Ellzey)
-
-DOCUMENTATION:
- o Add missing words to EVLOOP_NONBLOCK documentation (9556a7d)
-
-BUILD FIXES
- o libssl depends on libcrypto, not the other way around. (274dd03 Peter Rosin)
- o Libtool brings in the dependencies of libevent_openssl.la automatically (7b819f2 Peter Rosin)
- o Use OPENSSL_LIBS in Makefile.am (292092e Sebastian Hahn)
- o Move the win32 detection in configure.in (ceb03b9 Sebastian Hahn)
- o Correctly detect openssl on windows (6619385 Sebastian Hahn)
- o Fix a compile warning with zlib 1.2.4 and 1.2.5 (5786b91 Sebastian Hahn)
- o Fix compilation with GCC 2, which had no __builtin_expect (09d39a1 Dave Hart)
- o Fix new warnings from GCC 4.6 (06a714f)
- o Link with -lshell32 and -ladvapi32 on Win32. (86090ee Peter Rosin)
- o Make the tests build when OpenSSL is not available. (07c41be Peter Rosin)
- o Bring in the compile script from automake, if needed. (f3c7a4c Peter Rosin)
- o MSVC does not provide S_ISDIR, so provide it manually. (70be7d1 Peter Rosin)
- o unistd.h and sys/time.h might not exist. (fe93022 Peter Rosin)
- o Make sure TINYTEST_LOCAL is defined when building tinytest.c (8fa030c Peter Rosin)
- o Fix winsock2.h #include issues with MSVC (3d768dc Peter Rosin)
- o Use evutil_gettimeofday instead of relying on the system gettimeofday. (0de87fe Peter Rosin)
- o Always use evutil_snprintf, even if OS provides it (d1b2d11 Sebastian Hahn)
- o InitializeCriticalSectionAndSpinCount requires _WIN32_WINNT >= 0x0403. (816115a Peter Rosin)
- o cygwin: make it possible to build DLLs (d54d3fc)
-
-
-
-Changes in version 2.0.11-stable (27 Apr 2011)
-  [Autogenerated from the Git log, sorted and cleaned by hand.]
-BUGFIXES:
- o Fix evport handling of POLLHUP and POLLERR (b42ce4b)
- o Fix compilation on Windows with NDEBUG (cb8059d)
- o Check for POLLERR, POLLHUP and POLLNVAL for Solaris event ports (0144886 Trond Norbye)
- o Detect and handle more allocation failures. (666b096 Jardel Weyrich)
- o Use event_err() only if the failure is truly unrecoverable. (3f8d22a Jardel Weyrich)
- o Handle resize failures in the select backend better. (83e805a)
- o Correctly free selectop fields when select_resize fails in select_init (0c0ec0b)
- o Make --enable-gcc-warnings a no-op if not using gcc (3267703)
- o Fix a type error in our (unused) arc4random_stir() (f736198)
- o Correctly detect and stop non-chunked http requests when the body is too long (63a715e)
- o Have event_base_gettimeofday_cached() always return wall-clock time (a459ef7)
- o Workaround for http crash bug 3078187 (5dc5662 Tomash Brechko)
- o Fix incorrect assertions and possible use-after-free in evrpc_free() (4b8f02f Christophe Fillot)
- o Reset outgoing http connection when read data in idle state. (272823f Tomash Brechko)
- o Fix subtle recursion in evhttp_connection_cb_cleanup(). (218cf19 Tomash Brechko)
- o Fix the case when failed evhttp_make_request() leaved request in the queue. (0d6622e Tomash Brechko)
- o Fix a crash bug in evdns server circular list code (00e91b3)
- o Handle calloc failure in evdns. (Found by Dave Hart) (364291e)
- o Fix a memory leak on win32 socket->event map. (b4f89f0)
- o Add a forgotten NULL check to evhttp_parse_headers (12311ff Sebastian Hahn)
- o Fix possible NULL-deref in evdns_cancel_request (5208544 Sebastian Hahn)
-
-PORTABILITY:
- o Fall back to sscanf if we have no other way to implement strtoll (453317b)
- o Build correctly on platforms without sockaddr_storage (9184563)
- o Try to build correctly on platforms with no IPv6 support (713c254)
- o Build on systems without AI_PASSIVE (cb92113)
- o Fix http unit test on non-windows platforms without getaddrinfo (6092f12)
- o Do not check for gethostbyname_r versions if we have getaddrinfo (c1260b0)
- o Include arpa/inet.h as needed on HPUX (10c834c Harlan Stenn)
- o Include util-internal.h as needed to build on platforms with no sockaddr_storage (bbf5515 Harlan Stenn)
- o Check for getservbyname even if not on win32. (af08a94 Harlan Stenn)
- o Add -D_OSF_SOURCE to fix hpux builds (0b33479 Harlan Stenn)
- o Check for allocation failures in apply_socktype_protocol_hack (637d17a)
- o Fix the check for multicast or broadcast addresses in evutil_check_interfaces (1a21d7b)
- o Avoid a free(NULL) if out-of-memory in evdns_getaddrinfo. Found by Dave Hart (3417f68)
-
-DEFENSIVE PROGRAMMING:
- o Add compile-time check for AF_UNSPEC==PF_UNSPEC (3c8f4e7)
-
-BUGS IN TESTS:
- o Fix test.sh output on solaris (b4f89b6 Dave Hart)
- o Make test-eof fail with a timeout if we never get an eof. (05a2c22 Harlan Stenn)
- o Use %s with printf in test.sh (039b9bd)
- o Add an assert to appease clang's static analyzer (b0ff7eb Sebastian Hahn)
- o Add a forgotten return value check in the unit tests (3819b62 Sebastian Hahn)
- o Actually send NULL request in http_bad_request_test (b693c32 Sebastian Hahn)
- o add some (void) casts for unused variables (65707d7 Sebastian Hahn)
- o Refactor test_getaddrinfo_async_cancel_stress() (48c44a6 Sebastian Hahn)
- o Be nice and "handle" error return values in sample code (4bac793 Sebastian Hahn)
- o Check return value of evbuffer_add_cb in tests (93a1abb Sebastian Hahn)
- o Remote some dead code from dns-example.c (744c745 Sebastian Hahn)
- o Zero a struct sockaddr_in before using it (646f9fe Sebastian Hahn)
-
-BUILD FIXES:
- o Fix warnings about AC_LANG_PROGRAM usage (f663112 Sebastian Hahn)
- o Skip check for zlib if we have no zlib.h (a317c06 Harlan Stenn)
- o Fix autoconf bracket issues; make check for getaddrinfo include netdb.h (833e5e9 Harlan Stenn)
- o Correct an AM_CFLAGS to an AM_CPPFLAGS in test/Makefile.am (9c469db Dave Hart)
- o Fix make distcheck & installation of libevent 1 headers (b5a1f9f Dave Hart)
- o Fix compilation under LLVM/clang with --enable-gcc-warnings (ad9ff58 Sebastian Hahn)
-
-FEATURES:
- o Make URI parser able to tolerate nonconformant URIs. (95060b5)
-
-DOCUMENTATION:
- o Clarify event_set_mem_functions doc (926f816)
- o Correct evhttp_del_accept_socket documentation on whether socket is closed (f665924)
- o fix spelling mistake in whatsnew-2.0.txt (deb2f73)
- o Fix sample/http-server ipv6 fixes (eb692be)
- o Comment internal headers used in sample code. (4eb281c)
- o Be explicit about how long event loops run in event.h documentation (f95bafb)
- o Add comment to configure.in to explain gc-sections test logic (c621359)
- o Fix a couple of memory leaks in samples/http-server.c. Found by Dave Hart. (2e9f665)
-
-BUILD IMPROVEMENTS:
- o Use the gcc -ffunction-segments feature to allow gc when linking with static libevent (0965c56 Dave Hart)
- o Add configure options to disable installation, regression tests (49e9bb7 Dave Hart)
-
-
-
-Changes in version 2.0.10-stable (16 Dec 2010)
-  [Autogenerated from the Git log, sorted and cleaned by hand.]
-BUGFIXES
- o Minor fix for IOCP shutdown handling fix (2599b2d Kelly Brock)
- o Correctly notify the main thread when activating an event from a subthread (5beeec9)
- o Reject overlong http requests early when Expect:100-continue is set (d23839f Constantine Verutin)
- o EVUTIL_ASSERT: Use sizeof() to avoid "unused variable" warnings with -DNDEBUG. (b63ab17 Evan Jones)
-
-CODE CLEANUPS
- o bufferevent-internal.h: Use the new event2/util.h header, not evutil.h (ef5e65a Evan Jones)
- o Use relative includes instead of system includes consistently. (fbe64f2 Evan Jones)
- o Make whitespace more consistent
-
-TESTING
- o tests: Use new event2 headers instead of old compatibility headers. (4f33209 Evan Jones)
-
-DOCUMENTATION
- o Document that the cpu_hint is only used on Windows with IOCP for now (57689c4)
- o Add stuff to "whats new in 2.0" based on reading include changes since August. (18adc3f)
-
-
-Changes in 2.0.9-rc (30 Nov 2010):
-  [Autogenerated from the Git log, sorted and cleaned by hand.]
-NEW AND MODIFIED APIs
- o Add a function to change a listener's callback. (46ee061)
- o Make evbuffer_add_file take ev_off_t, not off_t (ac7e52d)
- o Make rate-limits go up to SIZE_MAX/EV_SSIZE_MAX, not just INT32_MAX (2cbb1a1)
- o Add a bufferevent_get_base function (aab49b6)
-
-MAJOR BUGFIXES
- o Disable changelist for epoll by default because of Linux dup() bug; add an option and/or an envvar to reenable it for speed. (9531763)
- o Fix a 100%-CPU bug where an SSL connection would sometimes never stop trying to write (1213d3d)
- o Fix a nasty bug related to use of dup() with epoll on Linux (c281aba)
- o Fix bugs in posix thread-id calculation when sizeof(pthread_t) != sizeof(long) (fbaf077)
- o Fix some ints to evutil_socket_t; make tests pass on win64. (f817bfa Dimitre Piskyulev)
- o Set _EVENT_SIZEOF_VOID_P correctly on win32 and win64 (1ae82cd Dimitre Piskyulev)
- o Avoid double-invocation of user callback with EVUTIL_EAI_CANCEL (abf01ed)
- o Set SO_UPDATE_ACCEPT_CONTEXT on sockets from AcceptEx so that shutdown() can work (52aa419)
- o When closing a filtering bufferevent, clear callbacks on the underlying bufferevent (fc7b1b0)
-
-NEW AND MODIFIED HTTP APIs
- o Add evhttp_parse_query_str to be used with evhttp_uri_parse. (2075fbc)
- o Add evhttp_response_code to remove one more reason to include http_struct.h (22e0a9b)
- o Define enumerators for all HTTP methods, including PATCH from RFC5789 (75a7341 Felix Nawothnig)
- o Functions to actually use evhttp_bound_socket with/as evconnlistener. (006efa7)
- o Add evhttp_request_get_command so code can tell GET from POST without peeking at the struct. (49f4bf7)
- o Introduce absolute URI parsing helpers. (86dd720 Pavel Plesov)
- o Revise evhttp_uri_parse implementation to handle more of RFC3986 (eaa5f1d)
- o Add evhttp_connection_get_base() to get the event_base from an http connection (cd00079)
- o Let evhttp_parse_query return -1 on failure (b1756d0)
- o New evhttp_uri(encode|decode) functions to handle + and NUL characters right (a8148ce)
- o Add evhttp_response_code to remove one more reason to include http_struct.h (22e0a9b)
- o Tweak interface for allowed methods (f5b391e)
- o Add evhttp server alias interface, correct flagging of proxy requests. (aab8c38 Christopher Davis)
-
-HTTP BUGFIXES
- o Add some comments to http.c and make a few functions static. (90b3ed5)
- o Fix Content-Length when trying send more than 100GB of data (!) on an evhttp. (525da3e)
- o Fix a bug where we would read too much data in HTTP bodies or requests. (58a1cc6)
- o Correctly count req->body_size on http usage without Content-Length (8e342e5)
- o Avoid missed-request bug when entire http request arrives before data is flushed (74c0e86)
- o reset "chunked" flag when sending non-chunked reply (aa5f55f Joachim Bauch)
- o evhttp_encode_uri encodes all reserved characters, including !$'()*+,/:=@ (2e63a60)
- o Replace exact-version checks for HTTP/1.1 with >= or < checks (647e094)
- o evhttp: Return 501 when we get an unrecognized method, not 400. (536311a)
- o Don't disable reading from the HTTP connection after sending the request to be notified of connection-close in time (c76640b Felix Nawothnig)
- o Never call evhttp_readcb while writing. (0512487)
- o Try to fix an assertion failure related to close detection (0faaa39)
- o Correctly detect timeouts during http connects (04861d5)
- o Preliminary support for Continue expectation in evhttp. (fa9305f Christopher Davis)
-
-OTHER BUGFIXES
- o Correct logic for realigning a chain in evbuffer_add (e4f34e8)
- o Fix a minor syntax error that most compilers didn't care about (e56ff65)
- o Fix some uses of int for socket in regress (5d389dc)
- o Check return value for ioctlsocket on win32 (f5ad31c Trond Norbye)
- o Fix som event_warns that should have been event_warnx (19c71e7)
- o Fix signal handler types for win64. (b81217f)
- o Try to clear up more size_t vs int/long issues. (598d133)
- o Make sure IOCP evconnlistener uses virtual events. (7b40a00 Christopher Davis)
- o Don't free evdns_request handles until after the callback is invoked (9ed30de)
- o Fix some more cancel-related bugs in getaddrinfo_async (c7cfbcf)
- o Make evdns_getaddrinfo_cancel threadsafe (d51b2fc)
- o Only clear underlying callbacks when the user hasn't reset them. (1ac5b23)
- o Fix bug in bufferevent_connect on an openssl bufferevent that already had an fd (4f228a1)
- o Resolve an evport bug in the thread/forking test (3a67d0b)
- o Make sure the CLOEXEC flag is set on fds we open for base notification (3ab578f)
- o Fix IRIX build.  sa_family collides with a #define in sys/socket.h on IRIX. (e874982 Kevin Bowling)
- o If not WIN32, include <sys/socket.h> in event2/util.h. (1cd45e5 Kevin Bowling)
- o Fix some C99-style comments to work with the xlC compiler. (c2e5e22 Kevin Bowling)
- o Add some checks since lack of TAILQ_FOREACH doesn't imply lack of FIRST, END, NEXT, or INSERT_BEFORE.  Quiet some warnings in XL C. (c4dc335 Kevin Bowling)
- o Reworked AIX __ss_family workaround to use AC_STRUCT_MEMBER. (2e2a3d7 Kevin Bowling)
- o Take select from <sys/select.h> when testing in autoconf.  AIX build fix. (a3a9f6b Kevin Bowling)
- o Fix snprintf related failures on IRIX. (3239073 Kevin Bowling)
- o Remove _event_initialized(); make event_initialized() a function(); make it consistent on windows and non-windows (652024b)
- o Do not let EVLOOP_ONCE exit the loop until all deferred callbacks have run (2d5e1bd)
- o Make EVLOOP_ONCE ignore internal events (0617a81)
- o Possible crash fix when freeing an underlying bufferevent of an openssl bufferevent (29f7623)
-
-HTTP CLEANUPS
- o Stop using Libevent-1 headers in regress_http (1f507d7)
- o Modernize header usage in bench_http.c (e587069)
- o fix signed/unsigned warnings in http.c (74a91e5)
- o Update the HTTP regression tests to use Libevent2 apis for non-http stuff (d9ffa89)
- o Start porting http tests to not use legacy interfaces (8505a74)
- o Convert the rest of the http tests to be non-legacy unit tests. (9bb8239)
- o Rename the confusing "base" static variable in regress_http.c (353402a)
- o Stop accessing http request struct directly from in the unit tests. (0b137f4)
- o Refactor http version parsing into a single function (a38140b)
-
-TESTING
- o Improvements to tinytest_macros.h (ad923a1)
- o Add a huge pile of tests for the new URI functions, and make them pass. (a5a76e6)
- o Unit tests for evhttp_uri_set* (bc98f5e)
- o Increase the skew tolerance to 2 seconds in thread/deferred_cb_skew (f806476 Christopher Davis)
- o Reorder backends in test.sh to match preference order in event.c (ece974f)
- o Add a stress test for getaddrinfo_cancel (da1bf52)
- o Units test for unexpected evhttp methods. (75e3320)
-
-DOCUMENTATION
- o Document behavior of URI parsing more thoroughly. (3a33462)
- o Document that two bufferevent functions only work on socket bufferevents (70e1b60)
- o add a requested docstring for event_rpcgen.CommandLine.__init__ (f1250eb)
- o Fix a mistake in http documentation found by Julien Blache (229714d)
- o Add a basic example of how to write a static HTTP server. (4e794d5)
- o Document event_get_assignment (88be27d)
- o Note that reentrant calls to libevent from logging cbs may fail badly (e431bcd)
- o Clarify EVLOOP_* documentation to be more precise. (057a514)
-
-CLEANUPS
- o Simplify the logic for choosing EPOLL_CTL_ADD vs EPOLL_CTL_MOD (2c66983)
- o Rename "size" variables in win32select that were really fd counts. (b6a158c)
- o Fix even more win64 warnings (7484df6)
- o Fix even more win64 warnings: buffer, event_tagging, http, evdns, evrpc (545a611)
- o Fix more wn64 warnings. (34b84b9 Christopher Davis)
- o Use the label_len local variable in evdns instead of recalculating it over and over (ba01456)
- o Fix some irix compilation warnings spotted by Kevin Bowling (7bcace2)
-
-
-
-Changes in 2.0.8-rc (14 Oct 2010):
- [Autogenerated from the Git log, sorted and cleaned by hand.]
-NEW APIS
- o Add error callback to evconnlistener (c4be8d8 Simon Perreault)
- o Add a LEV_OPT_THREADSAFE option for threadsafe evconnlisteners (127d4f2)
-
-CHANGED BEHAVIOR
- o Correct logic on disabling underlying bufferevents when disabling a filter (ac27eb8)
-
-BUGFIXES
- o Obey enabled status when unsuspending (040a019 Simon Perreault)
- o Warn when using the error-prone EV_SIGNAL interface in an error-prone way.  Also, fix a couple of race conditions in signal.c (720bd93)
- O Make default signal backend fully threadsafe (95a7d41)
- o Put internal events at highest priority (90651b3)
- o Fix warnings in the main codebase flagged by -Wsigned-compare (9c8db0, 5e4bafb, 5c214a, 6be589a, e06f514)
- o Fix compile in kqueue.c (b395392 Sebastian Hahn)
- o Do not search outside of the system directory for windows DLLs (d49b5e3)
- o Fix a spurious-call bug on epoll.c (0faaee0)
- o Send a shutdown(SHUT_WR) before closing an http connection (e0fd870 Christopher Davis)
- o Fix warnings on mingw with gcc 4.5 (5b7a370)
- o Fix an EINVAL on evbuffer_write_iovec on OpenSolaris. (fdc640b)
- o Fix allocation error for IOCP listeners. Probably harmless, since struct event is big (481ef92)
- o Make iocp/listener/error work; don't accept again if lev is disabled. (62b429a Christopher Davis)
- o Handle rate-limiting for reading on OpenSSL bufferevents correctly. (819b171)
- o Fix serious bugs in per-bufferevent rate-limiting code (34d64f8)
- o Avoid spurious reads from just-created open openssl bufferevents (223ee40)
- o Fix a case where an ssl bufferevent with CLOSE_ON_FREE didn't close its fd (93bb7d8)
- o The corrected bufferevent filter semantics let us fix our openssl tests (34331e4)
-
-TESTING
- o Make SSL tests cover enabling/disabling EV_READ. (a5ce9ad)
- o Bump to the latest version of tinytest (f0bd83e)
- o Unit tests for listener error callbacks (045eef4)
- o New unit test for ssl bufferevents starting with connected SSLs. (02f6259)
-
-DEBUGGABILITY
- o Make debugging output for epoll backend more comprehensive (ec2b05e)
- o Make event.c debugging messages report fds (e119899)
- o Make the --enable-gcc-warnings option include signed comparison warnings (d3b096c)
-
-DEADCODE REMOVAL
- o Remove the now-useless evsig_caught and evsig_process (4858b79)
- o Remove event_base.evsigbase; nothing used it. (38d0960)
-
-
-
-Changes in 2.0.7-rc (9 Sep 2010):
- [Autogenerated from the Git log, sorted and cleaned by hand.]
-NEW APIS
- o Expose a evdns_base_nameserver_sockaddr_add() function to add a nameserver by sockaddr (1952143)
- o Add event_config_set_num_cpus_hint() for tuning win32 IOCP thread pools, etc. (2447fe8 Christopher Davis)
-
-BUGFIXES
- o Fix a nasty dangling-event bug when using rate-limiting groups (0bffe43)
- o Clean up syntax on TAILQ_ENTRY() usage to build correctly with recent MSVC (60433a0 Gilad Benjamini)
- o Make definition of WIN32_LEAN_AND_MEAN in event.h conditional (3920172 Gilad Benjamini)
- o Correctly detect failure to delete bufferevent read-timeout event (da6e7cd)
- o Set close-on-exec bit for filedescriptors created by dns subsystem (d0b8843)
- o Fix kqueue correctness test on x84_64 (6123d12)
- o Detect events with no ev_base; warn instead of crashing (f1074b7)
- o Fix an issue with forking and signal socketpairs in select/poll backends (d61b2f3)
- o Stop using global arrays to implement the EVUTIL_ctype functions (1fdec20)
- o On windows, make lock/thread function tables static (5de2bcb)
- o Close th_notify_fds and open a new pair on reinit (495ed66)
- o Declare signal handler function as "__cdecl" on Windows (f0056d0)
- o Use the _func() replacements for open, fstat, etc in evutil.c on win32 (e50c0fc)
- o Only process up to MAX_DEFERRED deferred_cbs at a time (17a14f1 Christopher Davis)
-
-THREADING BUGFIXES
- o Avoid deadlock when activating signals (970e6ad)
- o Add a condition variable backend, with implementations for pthreads and win32 (d4977b5)
- o Use conditions instead of current_event_lock to fix a deadlock (e0972c2)
- o Fix logic error in win32 TRY_LOCK that caused problems with rate-limiting (4c32b9d)
- o Avoid needlessly calling evthread_notify_base() when the loop is not running (c7a06bf)
- o Minimize calls to base_notify implementation functions, thereby avoiding needless syscalls (4632b78)
-
-IOCP BUGFIXES
- o IOCP-related evbuffer fixes (03afa20 Christopher Davis)
- o Stop IOCP when freeing the event_base (d844242 Christopher Davis)
- o Some IOCP bufferevent tweaks (76f7e7a Christopher Davis)
-
-TESTS
- o Make the regress_pthread.c tests work on windows with current test APIs (d74ae38)
- o Add a unit test for conditions (5fb1095)
- o Allow more than one copy of regression tests to run at once (a97320a)
- o Fix event_del(0) instance in bench.c (b0f284c Shuo Chen)
- o Fix a few memory leaks in the tests (1115366)
- o IOCP-related unit test tweaks (499452f Christopher Davis)
- o Improve testing of when thread-notification occurs (ce85280)
-
-BUILD AND DISTRIBUTION
- o Add pkgconfig files for libevent_{openssl,pthreads} (ebcb1f0)
- o Change include order in Makefile.nmake (4022b28)
- o Make include/event2/event-config.h not included in source dist (a4af9be)
- o Honor NDEBUG; build without warnings with NDEBUG; make NDEBUG always-off in unit test code (743f866)
- o Declare evkeyvalq and event_list even if event_struct.h comes before sys/queue.h (d3ceca8)
- o Move evkeyvalq into a separate header for evhttp_parse_query users (ca9048f)
- o Prefer autoreconf -ivf to manual autogen.sh (7ea8e89)
-
-CLEANUP
- o Completely remove the (mostly-removed) obsolete thread functions (3808168)
- o Rename regress_pthread.c to regress_thread.c (041989f)
- o Make defer-internal.h use lock macros, not direct calls to lock fns (5218d2a)
-
-DOCUMENTATION
- o Document that DNS_NO_SEARCH is an obsolete alias for DNS_QUERY_NO_SEARCH (33200e7)
- o Update the whatsnew-2.0.txt document (4991669)
-
-
-
-Changes in 2.0.6-rc (6 Aug 2010):
- [Autogenerated from the Git log, sorted by hand.]
-DOCUMENTATION
- o Document a change in the semantics of event_get_struct_event_size() (e21f5d1)
- o Add a comment to describe our plan for library versioning (9659ece)
- o Fix sentence fragment in docs for event_get_struct_event_size() (7b259b6)
-
-NEW FEATURES AND INTERFACE CHANGES
- o Remove the obsolete evthread interfaces (c5bab56)
- o Let evhttp_send_error infer the right error reasons (3990669)
- o Add a function to retrieve the other side of a bufferevent pair (17a8e2d)
- o Add bufferevent_lock()/bufferevent_unlock() (215e629)
- o Stop asserting when asked for a (unsupported) TCP dns port. Just return NULL. (7e87a59)
- o Replace (unused,always 0) is_tcp argument to evdns_add_server_port*() with flags (e1c1167)
- o Constify a couple of arguments to evdns_server_request_add_*_reply (cc2379d)
- o Add an interface to expose min_share in ratelimiting groups (6ae53d6)
-
-BUGFIXES
- o Avoid event_del on uninitialized event in event_base_free (6d19510)
- o Add some missing includes to fix Linux build again (75701e8)
- o Avoid close of uninitialized socket in evbuffer unit test (bda21e7)
- o Correctly recognize .255 addresses as link-local when looking for interfaces (8c3452b)
- o If no evdns request can be launched, return NULL, not a handle (b14f151)
- o Use generic win32 interfaces, not ASCII-only ones, where possible. (899b0a3)
- o Fix the default HTTP error template (06bd056 Felix Nawothnig)
- o Close the file in evutil_read_file whether there's an error or not. (0798dd1 Pierre Phaneuf)
- o Fix possible nullptr dereference in evhttp_send_reply_end() (29b2e23 Felix Nawothnig)
- o never let bufferevent_rlim functions return negative (0859870)
- o Make sample/hello_world work on windows (d89fdba)
- o Fix a deadlock related to event-base notification.  Diagnosed by Zhou Li, Avi Bab, and Scott Lamb. (17522d2)
- o Possible fix to 100% cpu usage with epoll and openssl (cf249e7 Mike Smellie)
- o Don't race when calling event_active/event_add on a running signal event (fc5e0a2)
- o Suppress a spurious EPERM warning in epoll.c (e73cbde)
- o Fix wrong size calculation of iovec buffers when exact=1 (65abdc2 niks)
- o Change bufferevent_openssl::do_write so it doesn't call SSL_write with a 0 length buffer (c991317 Mike Smellie)
- o Fixed compilation of sample/le-proxy.c on win32 (13b912e Trond Norbye)
- o Fix rate-limit calculation on openssl bufferevents. (009f300)
- o Remember to initialize timeout events for bufferevent_async (de1f5d6 Christopher Davis)
-
-BUILD AND DISTRIBUTION CHANGES
- o Test the unlocked-deferred callback case of bufferevents (dfb75ab)
- o Remove the now-unusable EVTHREAD_LOCK/UNLOCK constants (fdfc3fc)
- o Use -Wlogical-op on gcc 4.5 or higher (d14bb92)
- o Add the libtool-generated /m4/* stuff to .gitignore (c21c663)
- o Remove some automake-generated files from version control. (9b14911)
- o Have autogen.sh pass --force-missing to automake (8a44062)
- o Set library version for libevent_pthreads correctly (b2d7440)
- o Really only add libevent_core.la to LIBADD on mingw (1425003 Sebastian Hahn)
- o Build more cleanly with NetBSDs that dislike toupper(char) (42a8c71)
- o Fix unit tests with -DUSE_DEBUG enabled (28f31a4)
- o Fix evdns build with -DUNICODE (5fa30d2)
- o Move event-config.h to include/event2 (ec347b9)
-
-TESTING
- o Add options to test-ratelim.c to check its results (2b44dcc)
- o Make test-ratelim clean up after itself better. (b5bfc44)
- o Remove the now-obsolete setup_test() and cleanup_test() functions (e73f1d7)
- o Remove all non-error prints from test/regress.c (8bc1e3d)
- o Make test.sh exit with nonzero status if tests fail (faf2a04)
- o Have the unit tests report errors from test.sh (3689bd2)
- o Fix logic in correcting high values from FIONREAD (3467f2f)
- o Add test for behavior on remote socket close (44d57ee)
- o Unit test for event_get_struct_event_size() (7510aac)
- o Make test/test.sh call test-changelist (7c92691)
- o Fix badly-behaved subtest of dns/bufferevent_connect_hostname (840a72f Joachim Bauch)
- o Add option to test-ratelim to test min_share (42f6b62)
- o Fix an assertion bug in test-ratelim (b2c6202)
- o Make tests quieter on local dns resolver failure (e996b3d)
- o Increase the tolerance in our unit tests for sloppy clocks. (170ffd2)
- o Use AF_INET socketpair to test sendfile on Solaris (9b60209)
- o Make test-changelist count cpu usage right on win32 (ea1ea3d)
-
-INTERNALS, PERFORMANCE, AND CODE CLEANUPS
- o Mark the event_err() functions as __attribute__((noreturn)) (33bbbed)
- o Do not check that event_base is set in EVBASE_ACQUIRE_LOCK (218a3c3)
- o Replace (safe) use of strcpy with memcpy to appease OpenBSD (caca2f4)
- o Remove some dead assignments (47c5dfb)
- o Fix a pedantic gcc 4.4 warning in event2/event.h (276e7ee)
- o Drain th_notify_fd[0] more bytes at a time. (a5bc15b)
- o Tidy up the code in evthread_make_base_notifiable a little (61e1eee)
- o Pass flags to fcntl(F_SETFL) and fcntl(F_SETFD) as int, not long (7c2dea1)
- o Remove unused variables in test/test-changelist.c (b00d4c0)
- o Fix whitespace. (cb927a5)
- o Improve error message for failed epoll to make debugging easier. (9e725f7)
- o Turn our socketpair() replacement into its own function (57b30cd)
-
-
-
-Changes in 2.0.5-beta (10 May 2010):
- [Autogenerated from the Git log, sorted by hand.]
-DOCUMENTATION
- o Update all our copyright notices to say "2010" (17efc1c)
- o Add Christopher Clark and Maxim Yegorushkin to the LICENSE file (38b7b57)
- o Clarify Christopher Clark's status as writer of original ht code. (78772c3)
- o Try to comment some of the event code more (cdd4c49)
- o Add a few more evmap/changelist comments (c247adc)
- o Add a comment to explain why evdns_request is now separte from request (ceefbe8)
- o Document evutil_secure_rng_init() and evutil_secure_rng_add_bytes() (a5bf43a)
- o Stop distributing and installing manpages: they were too inaccurate (7731ec8)
-
-NEW FEATURES AND INTERFACE CHANGES
- o Remove signal_assign() and signal_new() macros. (2fac0f7)
- o Make evdns use the regular logging system by default (b2f2be6)
- o Allow evbuffer_read() to split across more than 2 iovecs (e470ad3)
- o Functions to manipulate existing rate limiting groups. (ee41aca)
- o Functions to track the total bytes sent over a rate limit group. (fb366c1)
- o Detect and refuse reentrant event_base_loop() calls (b557b17)
- o Limit the maximum number of events on each socket to 65535 (819f949)
- o Add evbuffer_copyout to copy data from an evbuffer without draining (eb86c8c)
- o Expose the request and reply members of rpc_req_generic() (07edf78 Shuo Chen)
- o Add void* arguments to request_new and reply_new evrpc hooks (755fbf1 Shuo Chen)
- o Seed the RNG using sysctl() as well as /dev/urandom (71fc3eb)
- o Make evutil_secure_rng_init() work even with builtin arc4random (f980716)
- o Report DNS error when lookup fails during bufferevent_socket_connect_hostname. (0ef4070 Christopher Davis)
- o Release locks on bufferevents while executing callbacks (a5208fe Joachim Bauch) o Make debug mode catch mixed ET and non-ET events on an fd (cb67074)
- o Catch attempts to enable debug_mode too late (9ecf0d4)
- o Refuse null keys in evhttp_parse_query() (953e229 Frank Denis)
-
-BUGFIXES
- o Avoid a spurious close(-1) on Linux (70a44b6)
- o Do not close(-1) when freeing an uninitialized socket bufferevent (b34abf3)
- o Free evdns_base->req_heads on evdns_base_free (859af67)
- o Avoid an (untriggerable so far) crash bug in bufferevent_free() (0cf1431)
- o Set mem_offset for every bufferevent type (657d1b6)
- o Fix infrequent memory leak in bufferevent_init_common(). (8398641 Jardel Weyrich)
- o Make evutil_signal_active() match declaration. (e1e703d Patrick Galbraith)
- o Fix minheap code to use replacement malloc functions (a527618)
- o Fix a free(NULL) in minheap-internal.h (6f20492)
- o Fix critical bug in evbuffer_write when writev is not available (cda56ab)
- o Make the no_iovecs case of write_atmost compile (8e227b0)
- o Fix a memory leak when appending/prepending to a buffer with unused space. (45068a3)
- o Clean up a mistake in pointer manipulation in evbuffer_remove (28bfed4 Christopher Davis)
- o Always round up when there's a fractional number of msecs. (8f9e60c Christopher Davis)
- o Fix compiler warnings under WIN32 (d469c50 Giuseppe Scrivano)
- o Clean up properly when adding a signal handler fails. (b84b598 Gilad Benjamini) o Ensure that evdns_request is a persistent handle. (15bb82d Christopher Davis)
- o Free search state when finished searching to avoid an infinite loop. (a625840 Christopher Davis)
- o Assert for valid requests as necessary. (67072f3 Christopher Davis)
- o do not leak the request object on persistent connections (9d8edf2)
- o Make evdns logging threadsafe (b1c7950)
- o Fix a couple of bugs in the BSD sysctl arc4seed logic (a47a4b7)
- o Remove one last bug in last_with_datap logic. Found with valgrind (d49b92a)
- o fix a leak when unpausing evrpc requests (94ee125)
- o Fix a memory leak when unmarshalling RPC object arrays (f6ab2a2)
- o Fix compilation when openssl support is disabled (40c301b)
- o Allow empty reason line in HTTP status (739e688 Pierre Phaneuf)
- o Fix a compile warning introduced in 739e688 (bd1ed5f Sebastian Hahn)
- o Fix nonstandard TAILQ_FOREACH_REVERSE() definition (71afc52 Frank Denis)
- o Try /proc on Linux as entropy fallback; use sysctl as last resort (20fda29)
- o Fix symbol conflict between mm_*() macros and libmm (99e50e9)
- o Fix some crazy macro mistakes in arc4random.c (90d4225)
- o Make evbuffer_add_file() work on windows (dcdae6b)
- o Fix unused-variable warning when building with threads disabled (ad811cd)
- o Numerous opensolaris compilation fixes (c44de06)
- o Fix getaddrinfo with protocol unset on Solaris 9. Found by Dagobert Michelsen (2cf2a28)
- o Fix another nasty solaris getaddrinfo() behavior (3557071)
- o Define _REENTRANT as needed on Solaris, elsewhere (c1cd32a)
- o Fix some autoconf issues on OpenBSD (7c519df)
-
-BUILD AND DISTRIBUTION CHANGES
- o Distribute libevent.pc.in, not libevent.pc (22aff04)
- o Avoid errors in evutil.c when building with _UNICODE defined (b677032 Brodie Thiesfield)
- o Avoid errors in http.c when building with VC 2003 .NET (13e4f3b Brodie Thiesfield)
- o Support the standard 'make check' target in place of 'make verify' (426c8fb)
- o Remove redundant stuff from EXTRA_DIST (b660edf)
- o Switch to using AM conditionals in place of AC_LIBOBJ (2e898f5)
- o Remove an orphaned RELEASE flag in Makefile.am (0794b0d)
- o Give a better warning for bad automake versions. (77c917d)
- o Use dist_bin_SCRIPTS, not EXTRA_DIST, to distribute scripts (9eb2fd7)
- o Never test for select() on windows (3eb044d Trond Norbye)
- o Do not inhibit automake dependencies generation (10c4c90 Giuseppe Scrivano)
- o Create shared libraries under Windows (3cbca86 Giuseppe Scrivano)
- o Add ctags/etags files to .gitignore (0861d17)
- o Only specify -no-undefined on mingw (25433b9)
- o Only add libevent_core.la to LIBADD on mingw (fdc6297)
-
-TESTING
- o Get bench_http to work on Windows; add a switch to enable IOCP. (4ac38a5 Christopher Davis)
- o VC has no getopt(), so do without in bench_http. (1273d2f Christopher Davis)
- o Fix an obnoxious typo in the bufferevent_timeout_filter test (0d047c3)
- o Fix a write of uninitialized RAM in regression tests (68dc742)
- o Fix some memory leaks in the unit tests (274a7bd)
- o Make 'main/many_events' test 70 fds, not 64. (33874b0)
- o Unit-test every evbuffer_add_file() implementation. (06a4443)
- o Add more unit tests for evbuffer_expand (8c83e99)
- o Test another case of evbuffer_prepend (1234b95)
- o Fix a possible double-free bug in SSL bufferevents with CLOSE_ON_FREE (7501895) o Add dns/search_cancel unit test. (39b870b Christopher Davis)
- o Make http_base_test stop leaking an event_base. (96730d3)
- o Detect broken unsetenv at unit-test runtime (f37cd4c)
- o Implement regress_make_tempfile on win32 to test evbuffer_add_file (b4f12a1)
- o add more (currently skipped) add_file tests on win32 (05de45d)
- o Fix bench_http build on win32. (384d124)
- o Make unit test for add_file able to tell "error" from "done" (88a543f)
- o Make test for bufferevent_connect_hostname system-neutral (f89168e)
- o Make test.sh support mingw/msys on win32 (0ee6f6c)
- o Fix test.sh on freebsd (3d9e05b)
-
-INTERNALS, PERFORMANCE, AND AND CODE CLEANUPS
- o Improve the speed of evbuffer_readln() (cc1600a)
- o more whitespace normalization (2c2618d)
- o Revise evbuffer to add last_with_data (2a6d2a1)
- o Use last_with_data in place of previous_to_last (c8ac57f)
- o Remove previous_to_last from evbuffer (6f47bd1)
- o Fix last_with_data compilation on windows (1e7b986)
- o Add some glass-box tests for the last_with_data code. (17da042)
- o Improve robustness for refcounting (f1bc125)
- o Remove a needless min_heap_shift_up_() call (7204b91)
- o Increase MIN_BUFFER_SIZE to 512 (1024 on 64-bit) (2014ae4)
- o Do not use evbuffer_expand() to add the first chain to a buffer (5c0ebb3)
- o Make evbuffer_prepend handle empty buffers better (c87272b)
- o Replace last_with_data with a slightly smarter version (b7442f8)
- o Turn the increasingly complex *_CHAIN() macros into functions (96865c4)
- o Rewrite evbuffer_expand and its users (d5ebcf3)
- o Add evutil_tv_to_msec for safe conversion of timevals to milliseconds. (850c3ff Christopher Davis)
- o Initialize last_with_datap correctly in evbuffer_overlapped (a0983b6)
- o Replace EVUTIL_CLOSESOCKET macro with a function (899c1dc Sebastian Sjöberg)
- o Move domain search state to evdns_request. (beaa14a Christopher Davis)
- o Remove redundant checks for lock!=NULL before calling EVLOCK_LOCK (50ec59f)
- o Rename current_base symbol to event_global_current_base_ (c16e684)
- o Fix whitespace in evutil.c (935e150)
- o Replace users of "int fd" with "evutil_socket_t fd" in portable code (c7cf6f0)
-
-
-
-Changes in 2.0.4-alpha (28 Feb 2010):
- [Autogenerated from the Git log, sorted by hand.]
-DOCUMENTATION
- o Add stub header for 2.0.4-alpha changelog. (94d0065)
- o Improve the README with more information and links. (0b42726)
- o Add more people who wrote patches to the acknowledgments (0af10d5)
- o Add a warning about the use of event_initialized. (f32b575)
- o Add a LICENSE file so people can find our license easily (7067006)
- o Add a new "hello world" sample program (becb9f9)
- o Clarify status of example programs (d60a1bd)
- o Update time-test.c to use event2 (f4190bf)
- o Add the arc4random.c license to the LICENSE file. (e15e1e9)
-
-NEW FEATURES AND INTERFACE CHANGES
- o Improved optional lock debugging. (0cd3bb9)
- o Rate-limiting for bufferevents; group and individual limits are supported. (737c9cd)
- o Testing code for bufferevent rate-limiting. (f0c0124)
- o Make the initial nameserver probe timeout configurable. (1e56a32)
- o Revise the locking API: deprecate the old locking callbacks and add trylock. (347952f)
- o Do not make bufferevent_setfd implicitly disable EV_READ and EV_WRITE. (8274379)
- o Do not ignore bufferevent_enable(EV_READ) before bufferevent_connect(). (4a5b534)
- o Introduced evutil_make_socket_closeonexec() to preserve fd flags for F_SETFD. (d0939d2 Jardel Weyrich)
- o evdns_getaddrinfo() now supports the /etc/hosts file. (72dd666)
- o Look at the proper /etc/hosts file on windows. (66c02c7)
- o Allow http connections to use evdns for hostname looksups. (c698b77)
- o Changelist code to defer event changes until just before dispatch (27308aa)
- o do not use a function to assign the evdns base; instead assign it via evhttp_connection_base_new() which is a new function introduced in 2.0 (5032e52)
- o Functions to access more fields of struct event. (0683950)
- o Make kqueue use changelists. (45e5ae3)
- o Remove kqueue->pend_changes. (3225dfb)
- o Minimize epoll_ctl calls by using changelist (c8c6a89)
- o Add support for a "debug mode" to try to catch common errors. (cd17c3a)
- o Note a missing ratelim function (361da8f)
- o Add ev_[u]intptr_t to include/event2/util.h (1fa4c81)
- o const-ify a few more functions in event.h (d38a7a1)
- o Deprecate EVENT_FD and EVENT_SIGNAL. (f6b2694)
- o Remove EVUTIL_CHECK_FMT. (6c21c89)
- o Add EV_*_MAX macros to event2/util.h to expose limits for ev_* types. (aba1fff) o Functions to view and manipulate rate-limiting buckets. (85047a6)
- o Add the rest of the integer limits, and add a test for them. (60742d5)
- o Remove the 'flags' argument from evdns_base_set_option() (1dd7e6d)
- o Add an arc4random implementation for use by evdns (d4de062)
- o Use off_t for the length parameter of evbuffer_add_file (3fe60fd)
- o Construct Windows locks using InitializeCriticalSectionAndSpinCount (32c6f1b)
- o Expose view of current rate limit as constrained by group limit (162ce8a)
- o Provide consistent, tested semantics for bufferevent timeouts (d328829)
-
-BUGFIXES AND TESTS
- o Tolerate code that returns from a fatal_cb. (91fe23f)
- o Parenthesize macro arguments more aggressively (07e9e9b)
- o Fix memory-leak of signal handler array with kqueue. (e1ffbb8)
- o Stop passing EVTHREAD_READ and EVTHREAD_WRITE to non-rw locks. (76cd2b7)
- o Fix two use-after-free bugs in unit tests spoted by lock debugging (d84d838)
- o Fix a locking bug in event_base_loop() (da1718b)
- o Fix an evdns lock violation. (2df1f82 Zhuang Yuyao)
- o Valgrind fix: Clear struct kevent before checking for OSX bug. (56771a3 William Ahern)
- o Fix up evthread compilation on windows (bd6f1ba Roman Puls)
- o Fix regress_iocp.c usage of old lock allocation macros. (31687b4 unknown)
- o Update nmake makefile to build evthread.c (b62d979 unknown)
- o Fix a crash when reading badly formatted resolve.conf; from Yasuoka Masahiko (6c7c579 Yasuoka Masahiko)
- o Fix a snow leopard compile warning in the unit tests. (7ae9445)
- o Fix compile on Snow Leopard with gcc warnings enabled (70cdfe4 Sebastian Hahn)
- o Only define _GNU_SOURCE if it is not already defined. (ea6b1df Joachim Bauch)
- o Update sample/signal-test.c to use newer APIs and not leak. (f6430ac Evan Jones)
- o Fix a segfault when writing a very fragmented evbuffer onto an SSL (a6adeca Joachim Bauch)
- o Fix a segfault when freeing SSL bufferevents in an unusual order (a773df5 Joachim Bauch)
- o Drop install-sh from our git repo: a mismatched version could break "make dist" (6799527)
- o Set all instances of the version number correctly. (5a112d3)
- o Fix a few locking issues on windows. (c51bb3c unknown)
- o Use evutil_socket_t, not int, when logging socket errors. (292467c)
- o Fix up behavior of never-defered callbacks a little (390e056)
- o Replace some cases of uint32_t with ev_uint32_t. (a47d88d)
- o Fix compilation of devpoll.c by adding missing thread includes. (fee2c77 Dagobert Michelsen)
- o Make evutil_make_socket_nonblocking() leave any other flags alone. (4c8b7cd Jardel Weyrich)
- o Fix an fd leak in evconnlistener_new_bind(). (24fb502 Jardel Weyrich)
- o Fix a bogus free in evutil_new_addrinfo() (0d64051 Jardel Weyrich)
- o Adjusted fcntl() retval comparison on evutil_make_socket_nonblocking(). (4df7dbc Jardel Weyrich)
- o Fix the code that allowed DNS options to not end with : (ee4953f)
- o Fix crash bugs when a bufferevent's eventcb is not set. (2e8eeea)
- o Fix test-ratelim compilation on Linux. (885b427)
- o Fix compilation of rate-limiting code on win32. (165d30e)
- o Eradicated the last free() call. Let mm_free() take care of deallocation. (0546ce1 Jardel Weyrich)
- o Fix byte counts when mixing deferred and non-deferred evbuffer callbacks. (29151e6)
- o Fixed a memory leak on windows threads implementation. The CRITICAL_SECTION was not being free'd in evthread_win32_lock_free(). (2f33e00 Jardel Weyrich)
- o Fixed a fd leak in start_accepting(), plus cosmetic changes (4367a33 Jardel Weyrich)
- o Improved error handling in evconnlistener_new_async(). Also keeping the fd open because it is not opened by this function, so the caller is responsible for closing it. Additionally, since evconnlistener_new_bind() creates a socket and passes it to the function above, it required error checking to close the same socket. (fec66f9 Jardel Weyrich)
- o Don't use a bind address for nameservers on loopback (8d4aaf9)
- o Fix compilation of rate-limit code when threading support is disabled (97a8c79)
- o Detect setenv/unsetenv; skip main/base_environ test if we can't fake them. (7296971)
- o Check more internal event_add() calls for failure (ff3f6cd)
- o Fix windows and msvc build (5c7a7bc)
- o Call event_debug_unassign on internal events (a19b4a0)
- o Try to fix a warning in hash_debug_entry (137f2c6)
- o Fix a dumb typo in ev_intptr_t definitions. (27c9a40)
- o do not fail while sending on http connections the client closed. (93d7369)
- o make evhttp_send() safe against terminated connections, too (3978180)
- o Make Libevent 1.4.12 build on win32 with Unicode enabled. (000a33e Brodie Thiesfield)
- o Fix some additional -DUNICODE issues on win32. (a7a9431)
- o Add a check to make soure our EVUTIL_AI flags do not conflict with the native ones (c18490e)
- o Always use our own gai_strerror() replacement. (6810bdb)
- o Make RNG work when we have arc4random() but not arc4random_buf() (4ec8fea)
- o validate close cb on server when client connection closes (2f782af)
- o Fix two unlocked reads in evbuffer. (7116bf2)
- o When working without a current event base, don't try to use IOCP listeners (cb52838)
- o Fix getpid() usage on Windows (ff2a134)
- o Add a unit test for secure rng. (48a29b6)
- o Add some headers to fix freebsd compilation (b72be50)
- o When connect() succeeds immediately, don't invoke the callback immediately. (7515de9)
- o Suspend read/write on bufferevents during hostname lookup (db08f64)
- o Make bufferevent_free() clear all callbacks immediately. (b2fbeb3)
- o Fix some race conditions in persistent events and event_reinit (e2642f0)
- o Fix a bug in resetting timeouts on persistent events when IO triggers. (38ec0a7)
- o Add a test for timeouts on filtering bufferevents. (c02bfe1)
- o Add test for periodic timers that get activated for other reasons (8fcb7a1)
- o Use new timeval diff comparison function in bufferevent test (f3dfe46)
- o Delete stack-alloced event in new unit test before returning. (7ffd387)
- o Fix mingw compilation (23170a6)
- o Try to define a sane _EVENT_SIZEOF_SIZE_T for msvc compilation (1e14f82)
- o Fix arc4random compilation on MSVC. (98edb89)
- o deal with connect() failing immediately (7bc48bf)
- o Small cleanups on freebsd-connect-refused patch. (57b7248)
-
-BUILD AND DISTRIBUTION CHANGES
- o Remove the contents of WIN32-Prj as unmaintained. (c69d5a5)
- o Allow the user to redirect the verbose output of test/test.sh to a file (c382de6)
- o Allow test.sh to be run as ./test/test.sh (7dfbe94)
- o Never believe that we have pthreads on win32, even if gcc thinks we do. (78ed097)
- o Make it compile under gcc --std=c89. (e2ca403)
- o Fix a number of warnings from gcc -pedantic (918e9c5)
- o Add the msvc-generated .lib files to .gitignore. (e244a2e)
- o Add the "compile" script to gitignore. (1ba6bed)
-
-INTERNALS AND CODE CLEANUPS
- o Add a .gitignore file. (ba34071)
- o New EVTHREAD_TRY_LOCK function to try to grab a lock. (689fc09)
- o Add the abilitity to mark some buffer callbacks as never-deferred. (438f9ed)
- o Refactor our 'suspend operation' logic on bufferevents. (0d744aa)
- o Simplify the read high-watermark checking. (5846bf6)
- o Improve readability of evutil_unparse_protoname() (5a43df8 Jardel Weyrich)
- o Expose our cached gettimeofday value with a new interface (47854a8)
- o Whitespace fixes in test.sh (0b151a9)
- o Enable branch-prediction hints with EVUTIL_UNLIKELY. (eaaf27f)
- o Refactor code from evdns into a new internal "read a file" function. (0f7144f)
- o Comestic changes in evconnlistener_new(), new_accepting_socket(), accepted_socket_invoke_user_cb() and iocp_listener_enable(). (510ab6b Jardel Weyrich)
- o Add unit-test for bad_request bug fixed in 1.4 recently. (6cc79c6 Pavel Plesov) o Add a comment on evthread_enable_lock_debuging. (b9f43b2)
- o Fix test.sh on shells without echo -n (94131e9)
- o More unit tests for getaddrinfo_async: v4timeout and cancel. (a334b31)
- o Make http use evconnlistener. (ec34533)
- o move dns utility functions into a separate file so that we can use them for http testing (b822639)
- o add a test for evhttp_connection_base_new with a dns_base (26714ca)
- o forgot to add void to test function (78a50fe)
- o Add a forgotten header (changelist-internal.h) (4b9f307)
- o Remove some commented-out code in evutil (26e1b6f)
- o Remove a needless include of rpc_compat.h (70a4a3e)
- o Use less memory for each entry in a hashtable (a66e947)
- o Try to untangle the logic in server_port_flush(). (439aea0)
- o Use ev_[u]intptr_t types in place of [u]intptr_t (cef61a2)
- o Reduce windows header includes in our own headers. (da6135e)
- o clean up terminate_chunked test (e8a9782)
- o Increment the submicro version number. (63e868e)
- o Update event-config.h version number to match configure.in (aae7db5)
- o Clean up formatting: Disallow space-before-tab. (8fdf09c)
- o Clean up formatting: use tabs, not 8-spaces, to indent. (e5bbd40)
- o Clean up formatting: remove trailing spaces (e5cf987)
- o Clean up formatting: function/keyword spacing consistency. (4faeaea)
-
-
-
-Changes in 2.0.3-alpha (20 Nov 2009):
- o Add a new code to support SSL/TLS on bufferevents, using the OpenSSL library (where available).
- o Fix a bug where we didn't allocate enough memory in event_get_supported_methods().
- o Avoid segfault during failed allocation of locked evdns_base. (Found by Rocco Carbone.)
- o Export new evutil_ascii_* functions to perform locale-independent character type operations.
- o Try to compile better with MSVC: patches from Brodie Thiesfield
- o New evconnlistener_get_fd function to expose a listener's associated socket.
- o Expose an ev_socklen_t type for consistent use across platforms.
- o Make bufferevent_socket_connect() work when the original fd was -1.
- o Fix a bug in bufferevent_socket_connect() when the connection succeeds too quickly.
- o Export an evutil_sockaddr_cmp() to compare to sockaddr objects for equality.
- o Add a bufferevent_get_enabled() to tell what a bufferevent has been configured to do.
- o Add an evbuffer_search_eol() function to locate the end of a line nondestructively.
- o Add an evbuffer_search_range() function to search a bounded range of a buffer.
- o Fix a rare crash bug in evdns.
- o Have bufferevent_socket_connect() with no arguments put a bufferevent into connecting mode.
- o Support sendfile on Solaris: patch from Caitlin Mercer.
- o New functions to explicitly reference a socket used by an evhttp object. Patches from David Reiss.
- o When we send a BEV_EVENT_CONNECTED to indicate connected status, we no longer invoke the write callback as well unless we actually wrote data too.
- o If the kernel tells us that there are a negative number of bytes to read from a socket, do not believe it.  Fixes bug 2841177; found by Alexander Pronchenkov.
- o Do not detect whether we have monotonic clock support every time a new event base is created: instead do it only once.  Patch taken from Chromium.
- o Do not allocate the maximum event queue for the epoll backend at startup.  Instead, start out accepting 32 events at a time, and double the queue's size when it seems that the OS is generating events faster than we're requesting them.  Saves up to 374K per epoll-based event_base.  Resolves bug 2839240.
- o Treat an event with a negative fd as valid but untriggerable by Libevent.  This is useful for applications that want to manually activate events.
- o Fix compilation on Android, which forgot to define fd_mask in its sys/select.h
- o Do not drop data from evbuffer when out of memory; reported by Jacek Masiulaniec
- o New event_base_got_exit() and event_base_got_break() functions to tell whether an event loop exited because of an event_base_loopexit() or an event_base_loopbreak().  Patch from Ka-Hing Cheung.
- o When adding or deleting an event from a non-main thread, only wake up the main thread when its behavior actually needs to change.
- o Fix some bugs when using the old evdns interfaces to initialize the evdns module.
- o Detect errors during bufferevent_connect().  Patch from Christopher Davis.
- o Fix compilation for listener.h for C++ - missing extern "C".  Patch from Ferenc Szalai.
- o Make the event_base_loop() family of functions respect thread-safety better.  This should clear up a few hard-to-debug race conditions.
- o Fix a bug when using a specialized memory allocator on win32.
- o Have the win32 select() backend label TCP-socket-connected events as EV_WRITE, not EV_READ.  This should bring it in line with the other backends, and improve portability.  Patch from Christopher Davis.
- o Stop using enums as arguments or return values when what we mean is a bitfield of enum values.  C++ doesn't believe that you can OR two enum values together and get another enum, and C++ takes its typing seriously.  Patch from Christopher Davis.
- o Add an API to replace all fatal calls to exit() with a user-provided panic function.
- o Replace all assert() calls with a variant that is aware of the user-provided logging and panic functions.
- o Add a return value to event_assign so that it can fail rather than asserting when the user gives it bad input.  event_set still dies on bad input.
- o The event_base_new() and event_base_new_with_config() functions now never call exit() on failure.  For backward "compatibility", event_init() still does, but more consistently.
- o Remove compat/sys/_time.h.  It interfered with system headers on HPUX, and its functionality has been subsumed by event2/util.h and util-internal.h.
- o Add a new bufferevent_socket_connect_hostname() to encapsulate the resolve-then-connect operation.
- o Build kqueue.c correctly on GNU/kFreeBSD platforms. Patch pulled upstream from Debian.
- o Alternative queue-based timeout algorithm for programs that use a large number of timeouts with the same value.
- o New event_base_config option to disable the timeval cache entirely.
- o Make EV_PERSIST timeouts more accurate: schedule the next event based on the scheduled time of the previous event, not based on the current time.
- o Allow http.c to handle cases where getaddrinfo returns an IPv6 address.  Patch from Ryan Phillips.
- o Fix a problem with excessive memory allocation when using multiple event priorities.
- o Default to using arc4random for DNS transaction IDs on systems that have it; from OpenBSD.
- o Never check the environment when we're running setuid or setgid; from OpenBSD.
- o Options passed to evdns_set_option() no longer need to end with a colon.
- o Add an evutil_getaddrinfo() function to clone getaddrinfo on platforms that don't have it.
- o Add an evdns_getaddrinfo() function to provide a nonblocking getaddrinfo using evdns, so programs can perform useful hostname lookup.
- o Finally expose the IOCP-based bufferevent backend.  It passes its unit tests, but probably still has some bugs remaining.  Code by Nick Mathewson and Christopher Davis.
- o Numerous other bugfixes.
- o On FreeBSD and other OSes, connect can return ECONREFUSED immediately; instead of failing the function call, pretend with faileld in the callback.
- o Fix a race condition in the pthreads test case; found by Nick Mathewson
- o Remove most calls to event_err() in http and deal with memory errors instead
-
-
-
-Changes in 2.0.2-alpha (25 Jul 2009):
- o Add a new flag to bufferevents to make all callbacks automatically deferred.
- o Make evdns functionality locked, and automatically defer dns callbacks.
- o Fix a possible free(NULL) when freeing an event_base with no signals.
- o Add a flag to disable checking environment varibles when making an event_base
- o Disallow setting less than 1 priority.
- o Fix a bug when removing a timeout from the heap. [Patch from Marko Kreen]
- o Use signal.h, not sys/signal.h. [Patch from mmadia]
- o Try harder to build with certain older c99 compilers.
- o Make sure that an event_config's flags field is always initialized to 0. [Bug report from Victor Goya]
- o Avoid data corruption when reading data entirely into the second-to-last chain of an evbuffer. [Bug report from Victor Goya]
- o Make sendfile work on FreeBSD
- o Do not use vararg macros for accessing evrpc structures; this is not backwards compatible, but we did not promise any backwards compatibility for the rpc code.
- o Actually define the event_config_set_flag() function.
- o Try harder to compile with Visual C++.
- o Move event_set() and its allies to event2/event_compat.h where they belong.
- o Remove the event_gotsig code, which has long been deprecated and unused.
- o Add an event_get_base() function to return the base assigned to an event.
- o New function to automate connecting on a socket-based bufferevent.
- o New functions to automate listening for incoming TCP connections.
- o Do case-insensitive checks with a locale-independent comparison function.
- o Rename the evbuffercb and everrorcb callbacks to bufferevent_data_cb and bufferevent_event_cb respectively.  The old names are available in bufferevent_compat.h.
- o Rename the EVBUFFER_* codes used by bufferevent event callbacks to BEV_EVENT_*, to avoid namespace collision with evbuffer flags.  The old names are available in bufferevent_compat.h.
- o Move the EVBUFFER_INPUT and EVBUFFER_OUTPUT macros to bufferevent_compat.h
- o Add a bufferevent_getfd() function to mirror bufferevent_setfd()
- o Make bufferevent_setfd() return an error code if the operation is not successful.
- o Shave 22 bytes off struct event on 32-bit platforms by shrinking and re-ordering fields.  The savings on 64-bit platforms is likely higher.
- o Cap the maximum number of priorities at 256.
- o Change the semantics of evbuffer_cb_set_flags() to be set-flag only; add a new evbuffer_cb_clear_flags() to remove set flags.
- o Change the interface of evbuffer_add_reference so that the cleanup callback gets more information
- o Revise the new evbuffer_reserve_space/evbuffer_commit_space() interfaces so that you can use them without causing extraneous copies or leaving gaps in the evbuffer.
- o Add a new evbuffer_peek() interface to inspect data in an evbuffer without removing it.
- o Fix a deadlock when suspending reads in a bufferevent due to a full buffer. (Spotted by Joachim Bauch.)
- o Fix a memory error when freeing a thread-enabled event base with registered events. (Spotted by Joachim Bauch.)
- o Try to contain degree of failure when running on a win32 version so heavily firewalled that we can't fake a socketpair.
- o Activate fd events in a pseudorandom order with O(N) backends, so that we don't systematically favor low fds (select) or earlier-added fds (poll, win32).
- o Replace some read()/write() instances with send()/recv() to work properly on win32.
- o Set truncated flag correctly in evdns server replies.
- o Raise RpcGenError in event_rpcgen.py; from jmanison and Zack Weinberg
- o Fix preamble of rpcgen-generated files to rely on event2 includes; based on work by jmansion; patch from Zack Weinberg.
- o Allow specifying the output filename for rpcgen; based on work by jmansion; patch from Zack Weinberg.
- o Allow C identifiers as struct names; allow multiple comments in .rpc files; from Zack Weinberg
- o Mitigate a race condition when using socket bufferevents in multiple threads.
- o Use AC_SEARCH_LIBS, not AC_CHECK_LIB to avoid needless library use.
- o Do not allow event_del(ev) to return while that event's callback is executing in another thread.  This fixes a nasty race condition.
- o event_get_supported_methods() now lists methods that have been disabled with the EVENT_NO* environment options.
- o Rename encode_int[64] to evtag_encode_int[64] to avoid polluting the global namespace.  The old method names are still available as macros in event2/tag_compat.h.
-
-
-
-Changes in 2.0.1-alpha (17 Apr 2009):
- o free minheap on event_base_free(); from Christopher Layne
- o debug cleanups in signal.c; from Christopher Layne
- o provide event_base_new() that does not set the current_base global
- o bufferevent_write now uses a const source argument; report from Charles Kerr
- o improve documentation on event_base_loopexit; patch from Scott Lamb
- o New function, event_{base_}loopbreak.  Like event_loopexit, it makes an event loop stop executing and return.  Unlike event_loopexit, it keeps subsequent pending events from getting executed.  Patch from Scott Lamb
- o Check return value of event_add in signal.c
- o provide event_reinit() to reintialize an event_base after fork
- o New function event_set_mem_functinons.  It allows the user to give libevent replacement functions to use for memory management in place of malloc(), free(), etc.  This should be generally useful for memory instrumentation, specialized allocators, and so on.
- o The kqueue implementation now catches signals that are raised after event_add() is called but before the event_loop() call.  This makes it match the other implementations.
- o The kqueue implementation now restores original signal handlers correctly when its signal events are removed.
- o Check return value of event_add in signal.c
- o Add a more powerful evbuffer_readln as a replacement for evbuffer_readline.  The new function handles more newline styles, and is more useful with buffers that may contain a nul characters.
- o Do not mangle socket handles on 64-bit windows.
- o The configure script now takes an --enable-gcc-warnigns option that turns on many optional gcc warnings.  (Nick has been building with these for a while, but they might be useful to other developers.)
- o move EV_PERSIST handling out of the event backends
- o small improvements to evhttp documentation
- o always generate Date and Content-Length headers for HTTP/1.1 replies
- o set the correct event base for HTTP close events
- o When building with GCC, use the "format" attribute to verify type correctness of calls to printf-like functions.
- o Rewrite win32.c backend to be O(n lg n) rather than O(n^2).
- o Removed obsoleted recalc code
- o support for 32-bit tag numbers in rpc structures; this is wire compatible, but changes the API slightly.
- o pull setters/getters out of RPC structures into a base class to which we just need to store a pointer; this reduces the memory footprint of these structures.
- o prefix {encode,decode}_tag functions with evtag to avoid collisions
- o fix a bug with event_rpcgen for integers
- o Correctly handle DNS replies with no answers set (Fixes bug 1846282)
- o add -Wstrict-aliasing to warnings and more cleanup
- o removed linger from http server socket; reported by Ilya Martynov
- o event_rpcgen now allows creating integer arrays
- o support string arrays in event_rpcgen
- o change evrpc hooking to allow pausing of RPCs; this will make it possible for the hook to do some meaning ful work; this is not backwards compatible.
- o allow an http request callback to take ownership of a request structure
- o allow association of meta data with RPC requests for hook processing
- o associate more context for hooks to query such as the connection object
- o remove pending timeouts on event_base_free()
- o also check EAGAIN for Solaris' event ports; from W.C.A. Wijngaards
- o devpoll and evport need reinit; tested by W.C.A Wijngaards
- o event_base_get_method; from Springande Ulv
- o Send CRLF after each chunk in HTTP output, for compliance with RFC2626.  Patch from "propanbutan".  Fixes bug 1894184.
- o Add a int64_t parsing function, with unit tests, so we can apply Scott Lamb's fix to allow large HTTP values.
- o Use a 64-bit field to hold HTTP content-lengths.  Patch from Scott Lamb.
- o Allow regression code to build even without Python installed
- o remove NDEBUG ifdefs from evdns.c
- o detect integer types properly on platforms without stdint.h
- o udpate documentation of event_loop and event_base_loop; from Tani Hosokawa.
- o simplify evbuffer by removing orig_buffer
- o do not insert event into list when evsel->add fails
- o add support for PUT/DELETE requests; from Josh Rotenberg
- o introduce evhttp_accept_socket() to accept from an already created socket
- o include Content-Length in reply for HTTP/1.0 requests with keep-alive
- o increase listen queue for http sockets to 128; if that is not enough the evhttp_accpet_socket() api can be used with a prepared socket.
- o Patch from Tani Hosokawa: make some functions in http.c threadsafe.
- o test support for PUT/DELETE requests; from Josh Rotenberg
- o rewrite of the evbuffer code to reduce memory copies
- o Some older Solaris versions demand that _REENTRANT be defined to get strtok_r(); do so.
- o Do not free the kqop file descriptor in other processes, also allow it to be 0; from Andrei Nigmatulin
- o Provide OpenSSL style support for multiple threads accessing the same event_base
- o make event_rpcgen.py generate code include event-config.h; reported by Sam Banks.
- o switch thread support so that locks get allocated as they are needed.
- o make event methods static so that they are not exported; from Andrei Nigmatulin
- o make RPC replies use application/octet-stream as mime type
- o do not delete uninitialized timeout event in evdns
- o Correct the documentation on buffer printf functions.
- o Don't warn on unimplemented epoll_create(): this isn't a problem, just a reason to fall back to poll or select.
- o Correctly handle timeouts larger than 35 minutes on Linux with epoll.c.  This is probably a kernel defect, but we'll have to support old kernels anyway even if it gets fixed.
- o Make name_from_addr() threadsafe in http.c
- o Add new thread-safe interfaces to evdns functions.
- o Make all event_tagging interfaces threadsafe.
- o Rename internal memory management functions.
- o New functions (event_assign, event_new, event_free) for use by apps that want to be safely threadsafe, or want to remain ignorant of the contents of struct event.
- o introduce bufferevent_read_buffer; allows reading without memory copy.
- o expose bufferevent_setwatermark via header files and fix high watermark on read
- o fix a bug in buffrevent read water marks and add a test for them
- o fix a bug in which bufferevent_write_buffer would not schedule a write event
- o provide bufferevent_input and bufferevent_output without requiring knowledge of the structure
- o introduce bufferevent_setcb and bufferevent_setfd to allow better manipulation of bufferevents
- o convert evhttp_connection to use bufferevents.
- o use libevent's internal timercmp on all platforms, to avoid bugs on old platforms where timercmp(a,b,<=) is buggy.
- o Remove the never-exported, never-used evhttp_hostportfile function.
- o Support input/output filters for bufferevents; somewhat similar to libio's model.  This will allow us to implement SSL, compression, etc, transparently to users of bufferevents such as the http layer.
- o allow connections to be removed from an rpc pool
- o add new evtimer_assign, signal_assign, evtimer_new, and signal_new functions to manipulate timer and signal events, analagous to the now-recommended event_assign and event_new
- o switch internal uses of event_set over to use event_assign.
- o introduce evbuffer_contiguous_space() api that tells a user how much data is available in the first buffer chain
- o introduce evbuffer_reserve_space() and evbuffer_commit_space() to make processing in filters more efficient.
- o reduce system calls for getting current time by caching it.
- o separate signal events from io events; making the code less complex.
- o support for periodic timeouts
- o support for virtual HTTP hosts.
- o turn event_initialized() into a function, and add function equivalents to EVENT_SIGNAL and EVENT_FD so that people don't need to include event_struct.h
- o Build test directory correctly with CPPFLAGS set.
- o Provide an API for retrieving the supported event mechanisms.
- o event_base_new_with_config() and corresponding config APIs.
- o migrate the evhttp header to event2/ but accessors are still missing.
- o deprecate timeout_* event functions by moving them to event_compat.h
- o Move        windows gettimeofday replacement into a new evutil_gettimeofday().
- o Make configure script work on IRIX.
- o provide a method for canceling ongoing http requests.
- o Make vsnprintf() returns consistent on win32.
- o Fix connection keep-alive behavior for HTTP/1.0
- o Fix use of freed memory in event_reinit; pointed out by Peter Postma
- o constify struct timeval * where possible
- o make event_get_supported_methods obey environment variables
- o support for edge-triggered events on epoll and kqueue backends: patch from Valery Kholodkov
- o support for selecting event backends by their features, and for querying the features of a backend.
- o change failing behavior of event_base_new_with_config: if a config is provided and no backend is selected, return NULL instead of aborting.
- o deliver partial data to request callbacks when chunked callback is set even if there is no chunking on the http level; allows cancelation of requests from within the chunked callback; from Scott Lamb.
- o allow min_heap_erase to be called on removed members; from liusifan.
- o Rename INPUT and OUTPUT to EVRPC_INPUT and EVRPC_OUTPUT.  Retain INPUT/OUTPUT aliases on on-win32 platforms for backwards compatibility.
- o Do not use SO_REUSEADDR when connecting
- o Support 64-bit integers in RPC structs
- o Correct handling of trailing headers in chunked replies; from Scott Lamb.
- o Support multi-line HTTP headers; based on a patch from Moshe Litvin
- o Reject negative Content-Length headers; anonymous bug report
- o Detect CLOCK_MONOTONIC at runtime for evdns; anonymous bug report   
- o Various HTTP correctness fixes from Scott Lamb
- o Fix a bug where deleting signals with the kqueue backend would cause subsequent adds to fail
- o Support multiple events listening on the same signal; make signals regular events that go on the same event queue; problem report by Alexander Drozdov.
- o Fix a problem with epoll() and reinit; problem report by Alexander Drozdov. 
- o Fix off-by-one errors in devpoll; from Ian Bell
- o Make event_add not change any state if it fails; reported by Ian Bell.
- o Fix a bug where headers arriving in multiple packets were not parsed; fix from Jiang Hong; test by me.
- o Match the query in DNS replies to the query in the request; from Vsevolod Stakhov.
- o Add new utility functions to correctly observe and log winsock errors.
- o Do not remove Accept-Encoding header
- o Clear the timer cache on entering the event loop; reported by Victor Chang
- o Only bind the socket on connect when a local address has been provided; reported by Alejo Sanchez
- o Allow setting of local port for evhttp connections to support millions of connections from a single system; from Richard Jones.
- o Clear the timer cache when leaving the event loop; reported by Robin Haberkorn
- o Fix a typo in setting the global event base; reported by lance.
- o Set the 0x20 bit on outgoing alphabetic characters in DNS requests randomly, and insist on a match in replies.  This helps resist DNS poisoning attacks.
- o Make the http connection close detection work properly with bufferevents and fix a potential memory leak associated with it.
- o Restructure the event backends so that they do not need to keep track of events themselves, as a side effect multiple events can use the same fd or signal.
- o Add generic implementations for parsing and emiting IPv6 addresses on platforms that do not have inet_ntop and/or inet_pton.
- o Allow DNS servers that have IPv6 addresses.
- o Add an evbuffer_write_atmost() function to write a limited number of bytes to an fd.
- o Refactor internal notify-main-thread logic to prefer eventfd to pipe, then pipe to socketpair, and only use socketpairs as a last resort.
- o Try harder to pack all evbuffer reads into as few chains as possible, using readv/WSARecv as appropriate.
- o New evthread_use_windows_threads() and evthread_use_pthreads() functions to set up the evthread callbacks with reasonable defaults.
- o Change the semantics of timeouts in conjunction with EV_PERSIST; timeouts in that case will now repeat until deleted.
- o sendfile, mmap and memory reference support for evbuffers.
- o New evutil_make_listen_socket_reuseable() to abstract SO_REUSEADDR.
- o New bind-to option to allow DNS clients to bind to an arbitrary port for outgoing requests.
- o evbuffers can now be "frozen" to prevent operations at one or both ends.
- o Bufferevents now notice external attempts to add data to an inbuf or remove it from an outbuf, and stop them.
- o Fix parsing of queries where the encoded queries contained \r, \n or +
- o Do not allow internal events to starve lower-priority events.
-
-Changes in 1.4.0:
- o allow \r or \n individually to separate HTTP headers instead of the standard "\r\n"; from Charles Kerr.
- o demote most http warnings to debug messages
- o Fix Solaris compilation; from Magne Mahre
- o Add a "Date" header to HTTP responses, as required by HTTP 1.1.
- o Support specifying the local address of an evhttp_connection using set_local_address
- o Fix a memory leak in which failed HTTP connections whould not free the request object
- o Make adding of array members in event_rpcgen more efficient, but doubling memory allocation
- o Fix a memory leak in the DNS server
- o Fix compilation when DNS_USE_OPENSSL_FOR_ID is enabled
- o Fix buffer size and string generation in evdns_resolve_reverse_ipv6().
- o Respond to nonstandard DNS queries with "NOTIMPL" rather than by ignoring them.
- o In DNS responses, the CD flag should be preserved, not the TC flag.
- o Fix http.c to compile properly with USE_DEBUG; from Christopher Layne
- o Handle NULL timeouts correctly on Solaris; from Trond Norbye
- o Recalculate pending events properly when reallocating event array on Solaris; from Trond Norbye
- o Add Doxygen documentation to header files; from Mark Heily
- o Add a evdns_set_transaction_id_fn() function to override the default
-   transaction ID generation code.
- o Add an evutil module (with header evutil.h) to implement our standard cross-platform hacks, on the theory that somebody else would like to use them too.
- o Fix signals implementation on windows.
- o Fix http module on windows to close sockets properly.
- o Make autogen.sh script run correctly on systems where /bin/sh isn't bash. (Patch from Trond Norbye, rewritten by Hagne Mahre and then Hannah Schroeter.)
- o Skip calling gettime() in timeout_process if we are not in fact waiting for any events. (Patch from Trond Norbye)
- o Make test subdirectory compile under mingw.
- o Fix win32 buffer.c behavior so that it is correct for sockets (which do not like ReadFile and WriteFile).
- o Make the test.sh script run unit tests for the evpoll method.
- o Make the entire evdns.h header enclosed in "extern C" as appropriate.
- o Fix implementation of strsep on platforms that lack it
- o Fix implementation of getaddrinfo on platforms that lack it; mainly, this will make Windows http.c work better.  Original patch by Lubomir Marinov.
- o Fix evport implementation: port_disassociate called on unassociated events resulting in bogus errors; more efficient memory management; from Trond Norbye and Prakash Sangappa
- o support for hooks on rpc input and output; can be used to implement rpc independent processing such as compression or authentication.
- o use a min heap instead of a red-black tree for timeouts; as a result finding the min is a O(1) operation now; from Maxim Yegorushkin
- o associate an event base with an rpc pool
- o added two additional libraries: libevent_core and libevent_extra in addition to the regular libevent.  libevent_core contains only the event core whereas libevent_extra contains dns, http and rpc support
- o Begin using libtool's library versioning support correctly.  If we don't mess up, this will more or less guarantee binaries linked against old versions of libevent continue working when we make changes to libevent that do not break backward compatibility.
- o Fix evhttp.h compilation when TAILQ_ENTRY is not defined.
- o Small code cleanups in epoll_dispatch().
- o Increase the maximum number of addresses read from a packet in evdns to 32.
- o Remove support for the rtsig method: it hasn't compiled for a while, and nobody seems to miss it very much.  Let us know if there's a good reason to put it back in.
- o Rename the "class" field in evdns_server_request to dns_question_class, so that it won't break compilation under C++.  Use a macro so that old code won't break.  Mark the macro as deprecated.
- o Fix DNS unit tests so that having a DNS server with broken IPv6 support is no longer cause for aborting the unit tests.
- o Make event_base_free() succeed even if there are pending non-internal events on a base.  This may still leak memory and fds, but at least it no longer crashes.
- o Post-process the config.h file into a new, installed event-config.h file that we can install, and whose macros will be safe to include in header files.
- o Remove the long-deprecated acconfig.h file.
- o Do not require #include <sys/types.h> before #include <event.h>.
- o Add new evutil_timer* functions to wrap (or replace) the regular timeval manipulation functions.
- o Fix many build issues when using the Microsoft C compiler.
- o Remove a bash-ism in autogen.sh
- o When calling event_del on a signal, restore the signal handler's previous value rather than setting it to SIG_DFL. Patch from Christopher Layne.
- o Make the logic for active events work better with internal events; patch from Christopher Layne.
- o We do not need to specially remove a timeout before calling event_del; patch from Christopher Layne.
diff --git a/sntp/libevent/ChangeLog-1.4 b/sntp/libevent/ChangeLog-1.4
new file mode 100644 (file)
index 0000000..166d308
--- /dev/null
@@ -0,0 +1,231 @@
+Changes in 1.4.14b-stable
+ o Set the VERSION_INFO correctly for 1.4.14
+
+Changes in 1.4.14-stable
+ o Add a .gitignore file for the 1.4 branch. (d014edb)
+ o Backport evbuffer_readln(). (b04cc60 Nicholas Marriott)
+ o Make the evbuffer_readln backport follow the current API (c545485)
+ o Valgrind fix: Clear struct kevent before checking for OSX bug. (5713d5d William Ahern)
+ o Fix a crash when reading badly formatted resolve.conf (5b10d00 Yasuoka Masahiko)
+ o Fix memory-leak of signal handler array with kqueue. [backport] (01f3775)
+ o Update sample/signal-test.c to use newer APIs and not leak. (891765c Evan Jones)
+ o Correct all versions in 1.4 branch (ac0d213)
+ o Make evutil_make_socket_nonblocking() leave any other flags alone. (81c26ba Jardel Weyrich)
+ o Adjusted fcntl() retval comparison on evutil_make_socket_nonblocking(). (5f2e250 Jardel Weyrich)
+ o Correct a debug message in evhttp_parse_request_line (35df59e)
+ o Merge branch 'readln-backport' into patches-1.4 (8771d5b)
+ o Do not send an HTTP error when we've already closed or responded. (4fd2dd9 Pavel Plesov)
+ o Re-add event_siglcb; some old code _was_ still using it. :( (bd03d06)
+ o Make Libevent 1.4 build on win32 with Unicode enabled. (bce58d6 Brodie Thiesfield)
+ o Distribute nmake makefile for 1.4 (20d706d)
+ o do not fail while sending on http connections the client closed. (5c8b446)
+ o make evhttp_send() safe against terminated connections, too (01ea0c5)
+ o Fix a free(NULL) in min_heap.h (2458934)
+ o Fix memory leak when setting up priorities; reported by Alexander Drozdov (cb1a722)
+ o Clean up properly when adding a signal handler fails. (ae6ece0 Gilad Benjamini)
+ o Do not abort HTTP requests missing a reason string. (29d7b32 Pierre Phaneuf)
+ o Fix compile warning in http.c (906d573)
+ o Define _REENTRANT as needed on Solaris, elsewhere (6cbea13)
+
+
+Changes in 1.4.13-stable:
+ o If the kernel tells us that there are a negative number of bytes to read from a socket, do not believe it.  Fixes bug 2841177; found by Alexander Pronchenkov.
+ o Do not allocate the maximum event queue and fd array for the epoll backend at startup.  Instead, start out accepting 32 events at a time, and double the queue's size when it seems that the OS is generating events faster than we're requesting them.  Saves up to 512K per epoll-based event_base.  Resolves bug 2839240.
+ o Fix compilation on Android, which forgot to define fd_mask in its sys/select.h
+ o Do not drop data from evbuffer when out of memory; reported by Jacek Masiulaniec
+ o Rename our replacement compat/sys/_time.h header to avoid build a conflict on HPUX; reported by Kathryn Hogg.
+ o Build kqueue.c correctly on GNU/kFreeBSD platforms. Patch pulled upstream from Debian.
+ o Fix a problem with excessive memory allocation when using multiple event priorities.
+ o When running set[ug]id, don't check the environment. Based on a patch from OpenBSD.
+
+
+Changes in 1.4.12-stable:
+ o Try to contain degree of failure when running on a win32 version so heavily firewalled that we can't fake a socketpair.
+ o Fix an obscure timing-dependent, allocator-dependent crash in the evdns code.
+ o Use __VA_ARGS__ syntax for varargs macros in event_rpcgen when compiler is not GCC.
+ o Activate fd events in a pseudorandom order with O(N) backends, so that we don't systematically favor low fds (select) or earlier-added fds (poll, win32).
+ o Fix another pair of fencepost bugs in epoll.c.  [Patch from Adam Langley.]
+ o Do not break evdns connections to nameservers when our IP changes.
+ o Set truncated flag correctly in evdns server replies.
+ o Disable strict aliasing with GCC: our code is not compliant with it.
+
+Changes in 1.4.11-stable:
+ o Fix a bug when removing a timeout from the heap. [Patch from Marko Kreen]
+ o Remove the limit on size of HTTP headers by removing static buffers.
+ o Fix a nasty dangling pointer bug in epoll.c that could occur after epoll_recalc(). [Patch from Kevin Springborn]
+ o Distribute Win32-Code/event-config.h, not ./event-config.h
+
+Changes in 1.4.10-stable:
+ o clean up buffered http connection data on reset; reported by Brian O'Kelley
+ o bug fix and potential race condition in signal handling; from Alexander Drozdov
+ o rename the Solaris event ports backend to evport
+ o support compilation on Haiku
+ o fix signal processing when a signal callback delivers a signal; from Alexander Drozdov
+ o const-ify some arguments to evdns functions.
+ o off-by-one error in epoll_recalc; reported by Victor Goya
+ o include Doxyfile in tar ball; from Jeff Garzik
+ o correctly parse queries with encoded \r, \n or + characters
+
+Changes in 1.4.9-stable:
+ o event_add would not return error for some backends; from Dean McNamee
+ o Clear the timer cache on entering the event loop; reported by Victor Chang
+ o Only bind the socket on connect when a local address has been provided; reported by Alejo Sanchez
+ o Allow setting of local port for evhttp connections to support millions of connections from a single system; from Richard Jones.
+ o Clear the timer cache when leaving the event loop; reported by Robin Haberkorn
+ o Fix a typo in setting the global event base; reported by lance.
+ o Fix a memory leak when reading multi-line headers
+ o Fix a memory leak by not running explicit close detection for server connections
+
+Changes in 1.4.8-stable:
+ o Match the query in DNS replies to the query in the request; from Vsevolod Stakhov.
+ o Fix a merge problem in which name_from_addr returned pointers to the stack; found by Jiang Hong.
+ o Do not remove Accept-Encoding header
+       
+Changes in 1.4.7-stable:
+ o Fix a bug where headers arriving in multiple packets were not parsed; fix from Jiang Hong; test by me.
+       
+Changes in 1.4.6-stable:
+ o evutil.h now includes <stdarg.h> directly
+ o switch all uses of [v]snprintf over to evutil
+ o Correct handling of trailing headers in chunked replies; from Scott Lamb.
+ o Support multi-line HTTP headers; based on a patch from Moshe Litvin
+ o Reject negative Content-Length headers; anonymous bug report
+ o Detect CLOCK_MONOTONIC at runtime for evdns; anonymous bug report   
+ o Fix a bug where deleting signals with the kqueue backend would cause subsequent adds to fail
+ o Support multiple events listening on the same signal; make signals regular events that go on the same event queue; problem report by Alexander Drozdov.
+ o Deal with evbuffer_read() returning -1 on EINTR|EAGAIN; from Adam Langley.
+ o Fix a bug in which the DNS server would incorrectly set the type of a cname reply to a.
+ o Fix a bug where setting the timeout on a bufferevent would take not effect if the event was already pending.
+ o Fix a memory leak when using signals for some event bases; reported by Alexander Drozdov.
+ o Add libevent.vcproj file to distribution to help with Windows build.
+ o Fix a problem with epoll() and reinit; problem report by Alexander Drozdov. 
+ o Fix off-by-one errors in devpoll; from Ian Bell
+ o Make event_add not change any state if it fails; reported by Ian Bell.
+ o Do not warn on accept when errno is either EAGAIN or EINTR
+
+Changes in 1.4.5-stable:
+ o Fix connection keep-alive behavior for HTTP/1.0
+ o Fix use of freed memory in event_reinit; pointed out by Peter Postma
+ o Constify struct timeval * where possible; pointed out by Forest Wilkinson
+ o allow min_heap_erase to be called on removed members; from liusifan.
+ o Rename INPUT and OUTPUT to EVRPC_INPUT and EVRPC_OUTPUT.  Retain INPUT/OUTPUT aliases on on-win32 platforms for backwards compatibility.
+ o Do not use SO_REUSEADDR when connecting
+ o Fix Windows build
+ o Fix a bug in event_rpcgen when generated fixed-sized entries
+
+Changes in 1.4.4-stable:
+ o Correct the documentation on buffer printf functions.
+ o Don't warn on unimplemented epoll_create(): this isn't a problem, just a reason to fall back to poll or select.
+ o Correctly handle timeouts larger than 35 minutes on Linux with epoll.c.  This is probably a kernel defect, but we'll have to support old kernels anyway even if it gets fixed.
+ o Fix a potential stack corruption bug in tagging on 64-bit CPUs.
+ o expose bufferevent_setwatermark via header files and fix high watermark on read
+ o fix a bug in bufferevent read water marks and add a test for them
+ o introduce bufferevent_setcb and bufferevent_setfd to allow better manipulation of bufferevents
+ o use libevent's internal timercmp on all platforms, to avoid bugs on old platforms where timercmp(a,b,<=) is buggy.
+ o reduce system calls for getting current time by caching it.
+ o fix evhttp_bind_socket() so that multiple sockets can be bound by the same http server.
+ o Build test directory correctly with CPPFLAGS set.
+ o Fix build under Visual C++ 2005.
+ o Expose evhttp_accept_socket() API.
+ o Merge windows gettimeofday() replacement into a new evutil_gettimeofday() function.
+ o Fix autoconf script behavior on IRIX.
+ o Make sure winsock2.h include always comes before windows.h include.
+
+Changes in 1.4.3-stable:
+ o include Content-Length in reply for HTTP/1.0 requests with keep-alive
+ o Patch from Tani Hosokawa: make some functions in http.c threadsafe.
+ o Do not free the kqop file descriptor in other processes, also allow it to be 0; from Andrei Nigmatulin
+ o make event_rpcgen.py generate code include event-config.h; reported by Sam Banks.
+ o make event methods static so that they are not exported; from Andrei Nigmatulin
+ o make RPC replies use application/octet-stream as mime type
+ o do not delete uninitialized timeout event in evdns
+
+Changes in 1.4.2-rc:
+ o remove pending timeouts on event_base_free()
+ o also check EAGAIN for Solaris' event ports; from W.C.A. Wijngaards
+ o devpoll and evport need reinit; tested by W.C.A Wijngaards
+ o event_base_get_method; from Springande Ulv
+ o Send CRLF after each chunk in HTTP output, for compliance with RFC2626.  Patch from "propanbutan".  Fixes bug 1894184.
+ o Add a int64_t parsing function, with unit tests, so we can apply Scott Lamb's fix to allow large HTTP values.
+ o Use a 64-bit field to hold HTTP content-lengths.  Patch from Scott Lamb.
+ o Allow regression code to build even without Python installed
+ o remove NDEBUG ifdefs from evdns.c
+ o update documentation of event_loop and event_base_loop; from Tani Hosokawa.
+ o detect integer types properly on platforms without stdint.h
+ o Remove "AM_MAINTAINER_MODE" declaration in configure.in: now makefiles and configure should get re-generated automatically when Makefile.am or configure.in chanes.
+ o do not insert event into list when evsel->add fails
+
+Changes in 1.4.1-beta:
+ o free minheap on event_base_free(); from Christopher Layne
+ o debug cleanups in signal.c; from Christopher Layne
+ o provide event_base_new() that does not set the current_base global
+ o bufferevent_write now uses a const source argument; report from Charles Kerr
+ o better documentation for event_base_loopexit; from Scott Lamb.
+ o Make kqueue have the same behavior as other backends when a signal is caught between event_add() and event_loop().  Previously, it would catch and ignore such signals.
+ o Make kqueue restore signal handlers correctly when event_del() is called.
+ o provide event_reinit() to reintialize an event_base after fork
+ o small improvements to evhttp documentation
+ o always generate Date and Content-Length headers for HTTP/1.1 replies
+ o set the correct event base for HTTP close events
+ o New function, event_{base_}loopbreak.  Like event_loopexit, it makes an event loop stop executing and return.  Unlike event_loopexit, it keeps subsequent pending events from getting executed.  Patch from Scott Lamb
+ o Removed obsoleted recalc code
+ o pull setters/getters out of RPC structures into a base class to which we just need to store a pointer; this reduces the memory footprint of these structures.
+ o fix a bug with event_rpcgen for integers
+ o move EV_PERSIST handling out of the event backends
+ o support for 32-bit tag numbers in rpc structures; this is wire compatible, but changes the API slightly.
+ o prefix {encode,decode}_tag functions with evtag to avoid collisions
+ o Correctly handle DNS replies with no answers set (Fixes bug 1846282)
+ o The configure script now takes an --enable-gcc-warnigns option that turns on many optional gcc warnings.  (Nick has been building with these for a while, but they might be useful to other developers.)
+ o When building with GCC, use the "format" attribute to verify type correctness of calls to printf-like functions.
+ o removed linger from http server socket; reported by Ilya Martynov
+ o allow \r or \n individually to separate HTTP headers instead of the standard "\r\n"; from Charles Kerr.
+ o demote most http warnings to debug messages
+ o Fix Solaris compilation; from Magne Mahre
+ o Add a "Date" header to HTTP responses, as required by HTTP 1.1.
+ o Support specifying the local address of an evhttp_connection using set_local_address
+ o Fix a memory leak in which failed HTTP connections would not free the request object
+ o Make adding of array members in event_rpcgen more efficient, but doubling memory allocation
+ o Fix a memory leak in the DNS server
+ o Fix compilation when DNS_USE_OPENSSL_FOR_ID is enabled
+ o Fix buffer size and string generation in evdns_resolve_reverse_ipv6().
+ o Respond to nonstandard DNS queries with "NOTIMPL" rather than by ignoring them.
+ o In DNS responses, the CD flag should be preserved, not the TC flag.
+ o Fix http.c to compile properly with USE_DEBUG; from Christopher Layne
+ o Handle NULL timeouts correctly on Solaris; from Trond Norbye
+ o Recalculate pending events properly when reallocating event array on Solaris; from Trond Norbye
+ o Add Doxygen documentation to header files; from Mark Heily
+ o Add a evdns_set_transaction_id_fn() function to override the default
+   transaction ID generation code.
+ o Add an evutil module (with header evutil.h) to implement our standard cross-platform hacks, on the theory that somebody else would like to use them too.
+ o Fix signals implementation on windows.
+ o Fix http module on windows to close sockets properly.
+ o Make autogen.sh script run correctly on systems where /bin/sh isn't bash. (Patch from Trond Norbye, rewritten by Hagne Mahre and then Hannah Schroeter.)
+ o Skip calling gettime() in timeout_process if we are not in fact waiting for any events. (Patch from Trond Norbye)
+ o Make test subdirectory compile under mingw.
+ o Fix win32 buffer.c behavior so that it is correct for sockets (which do not like ReadFile and WriteFile).
+ o Make the test.sh script run unit tests for the evpoll method.
+ o Make the entire evdns.h header enclosed in "extern C" as appropriate.
+ o Fix implementation of strsep on platforms that lack it
+ o Fix implementation of getaddrinfo on platforms that lack it; mainly, this will make Windows http.c work better.  Original patch by Lubomir Marinov.
+ o Fix evport implementation: port_disassociate called on unassociated events resulting in bogus errors; more efficient memory management; from Trond Norbye and Prakash Sangappa
+ o support for hooks on rpc input and output; can be used to implement rpc independent processing such as compression or authentication.
+ o use a min heap instead of a red-black tree for timeouts; as a result finding the min is a O(1) operation now; from Maxim Yegorushkin
+ o associate an event base with an rpc pool
+ o added two additional libraries: libevent_core and libevent_extra in addition to the regular libevent.  libevent_core contains only the event core whereas libevent_extra contains dns, http and rpc support
+ o Begin using libtool's library versioning support correctly.  If we don't mess up, this will more or less guarantee binaries linked against old versions of libevent continue working when we make changes to libevent that do not break backward compatibility.
+ o Fix evhttp.h compilation when TAILQ_ENTRY is not defined.
+ o Small code cleanups in epoll_dispatch().
+ o Increase the maximum number of addresses read from a packet in evdns to 32.
+ o Remove support for the rtsig method: it hasn't compiled for a while, and nobody seems to miss it very much.  Let us know if there's a good reason to put it back in.
+ o Rename the "class" field in evdns_server_request to dns_question_class, so that it won't break compilation under C++.  Use a macro so that old code won't break.  Mark the macro as deprecated.
+ o Fix DNS unit tests so that having a DNS server with broken IPv6 support is no longer cause for aborting the unit tests.
+ o Make event_base_free() succeed even if there are pending non-internal events on a base.  This may still leak memory and fds, but at least it no longer crashes.
+ o Post-process the config.h file into a new, installed event-config.h file that we can install, and whose macros will be safe to include in header files.
+ o Remove the long-deprecated acconfig.h file.
+ o Do not require #include <sys/types.h> before #include <event.h>.
+ o Add new evutil_timer* functions to wrap (or replace) the regular timeval manipulation functions.
+ o Fix many build issues when using the Microsoft C compiler.
+ o Remove a bash-ism in autogen.sh
+ o When calling event_del on a signal, restore the signal handler's previous value rather than setting it to SIG_DFL. Patch from Christopher Layne.
+ o Make the logic for active events work better with internal events; patch from Christopher Layne.
+ o We do not need to specially remove a timeout before calling event_del; patch from Christopher Layne.
diff --git a/sntp/libevent/ChangeLog-2.0 b/sntp/libevent/ChangeLog-2.0
new file mode 100644 (file)
index 0000000..8c838b4
--- /dev/null
@@ -0,0 +1,1225 @@
+Changes in version 2.0.19-stable (0? May 2012)
+BUGFIXES (CORE):
+ o Refactor event_persist_closure: raise and extract some common logic (bec22b4)
+ o If time has jumped so we'd reschedule a periodic event in the past, schedule it for the future instead (dfd808c)
+ o If a higher-priority event becomes active, don't continue running events of the current priority. (2bfda40)
+
+BUGFIXES (SSL):
+ o Fixed potential double-readcb execution with openssl bufferevents. (4e62cd1 Mark Ellzey)
+
+BUGFIXES (DNS):
+ o Cancel a probe request when the server is freed, and ignore cancelled probe callbacks (94d2336 Greg Hazel)
+ o Remove redundant DNS_ERR_CANCEL check, move comment (46b8060 Greg Hazel)
+ o When retransmitting a timed-out DNS request, pick a fresh nameserver. (3d9e52a)
+
+DOCUMENTATION FIXES:
+ o Fix a typo in the bufferevent documentation (98e9119)
+ o Add missing ) to changelog; spotted by rransom (4c7ee6b)
+ o Fix the website URL in the readme (f775521)
+
+COMPILATION FIXES:
+ o Fix a compilation error with MSVC 2005 due to use of mode_t (336dcae)
+ o Configure with gcc older than 2.95 (4a6fd43 Sebastian Hahn)
+ o Generate event-config.h with a single sed script (30b6f88 Zack Weinberg)
+
+FORWARD-COMPATIBILITY:
+ o Backport: provide EVENT_LOG_* names, and deprecate _EVENT_LOG_* (d1a03b2)
+
+TESTING/DEBUGGING SUPPORT:
+ o dns-example.c can now take a resolv.conf file on the commandline (6610fa5)
+ o Make some evdns.c debug logs more verbose (d873d67)
+ o Work-around a stupid gcov-breaking bug in OSX 10.6 (b3887cd)
+
+
+Changes in version 2.0.18-stable (22 Mar 2012)
+BUGFIXES (core):
+ o Make uses of open() close-on-exec safe by introducing an internal evutil_open_closeonexec. (d2b5f72 Ross Lagerwall, 03dce42)
+
+BUGFIXES (kqueue):
+ o Properly zero the kevent in kq_setup_kevent() (c2c7b39 Sebastian Hahn)
+
+BUILD FIXES:
+ o Added OPENSSL_LDFLAGS env variable which is appended to SSL checks. (9278196 Mark Ellzey)
+ o Changed OPENSSL_LDFLAGS to OPENSSL_LIBADD (2d67b63 Mark Ellzey)
+ o Don't do clang version detection when disabling some flags (083296b Sebastian Hahn)
+
+BUGFIXES (dns):
+ o Stop crashing in evdns when nameserver probes give a weird error (bec5068)
+
+
+Changes in version 2.0.17-stable (10 Feb 2012)
+
+BUGFIXES (core):
+ o Be absolutely sure to clear pncalls before leaving event_signal_closure (11f36a5)
+ o check for sysctl before we use it (358c745 Mike Frysinger)
+ o Remove bogus casts of socket to int before calling ev_callback (f032516)
+ o Make evconnlistener work around bug in older Linux when getting nmapped (ecfc720)
+ o Fix a list corruption bug when using event_reinit() with signals present (6e41cdc)
+ o Fix a fd leak in event_reinit() (3f18ad1)
+ o Do a memberwise comparison of threading function tables (c94a5f2 Nate R)
+ o Use C-style comments in C source files (for compatibility with compilers such as xlc on AIX). (d84d917 Greg Hewgill)
+ o Avoid crash when freeing event_iocp and using event_set_mem_functions (19715a6)
+ o In the kqueue backend, do not report EBADF as an EV_READ (5d7bfa1 Nicholas Marriott)
+
+BUGFIXES (evbuffer and bufferevents):
+ o Fix behavior of evbuffer_peek(buf,-1,NULL,NULL,0) (c986f23 Zack Weinberg)
+ o Loop on filtering SSL reads until we are blocked or exhausted. (5b4b812)
+
+BUGFIXES (evhttp):
+ o Force strict validation of HTTP version in response. (790f6b3 Catalin Patulea)
+
+BUGFIXES (evdns):
+ o evdns: fix a bug in circular-queue implementation (d6094b1)
+
+BUILD FIXES:
+ o Fix a silly compilation error with the sun compiler (1927776 Colin Watt)
+ o Suppress a gcc warning from ignoring fwrite return in http-sample.c (7206e8c)
+
+DOCUMENTATION FIXES:
+ o Slightly clarify evbuffer_peek documentation (7bbf6ca)
+ o Update copyright notices to 2012 (e49e289)
+
+NEW APIS:
+ o Backport evhttp_connection_get_bufferevent to Libevent 2.0 (da70fa7 Arno Bakker)
+
+TESTS AND TEST FIXES:
+ o Fix a race condition in the dns/bufferevent_connect_hostname test. (cba48c7)
+ o Add function to check referential integrity of an event_base (27737d5)
+ o Check event_base correctness at end of each unit test (3312b02)
+ o Workaround in the unit tests for an apparent epoll bug in Linux 3.2 (dab9187)
+ o Better workaround for Linux 3.2 edge-triggered epoll bug (9f9e259)
+
+Changes in version 2.0.16-stable (18 Nov 2011)
+BUGFIXES (core):
+ o More detailed message in case of libevent self-debugging failure. (9e6a4ef Leonid Evdokimov)
+ o epoll: close fd on alloc fail at initialization (1aee718 Jamie Iles)
+ o Fix compile warning from saying event2/*.h inside a comment (447b0ba)
+ o Warn when unable to construct base because of failing make_base_notifiable (4e797f3)
+ o Don't try to make notifiable event_base when no threading fns are configured (e787413)
+
+BUGFIXES (evbuffer):
+ o unit test for remove_buffer bug (90bd620 Greg Hazel)
+ o Fix an evbuffer crash in evbuffer_remove_buffer() (c37069c)
+
+BUGFIXES (bufferevent_openssl):
+ o Refactor amount-to-read calculations in buffervent_ssl consider_reading() (a186e73 Mark Ellzey)
+ o Move SSL rate-limit enforcement into bytes_to_read() (96c562f)
+ o Avoid spinning on OpenSSL reads (2aa036f Mark Ellzey)
+
+BUGFIXES (dns)
+ o Empty DNS reply with OK status is another way to say NODATA. (21a08d6 Leonid Evdokimov)
+
+TESTING:
+ o Tests for 94fba5b and f72e8f6 (d58c15e Leonid Evdokimov)
+ o Test for commit aff6ba1 (f7841bf Leonid Evdokimov)
+ o Style and comment tweaks for dns/leak* tests (5e42202)
+ o improve test to remove at least one buffer from src (7eb52eb Greg Hazel)
+
+DOCUMENTATION:
+ o Add note about evhttp_send_reply_end to its doxygen (724bfb5)
+ o Update copyright dates to 2011. (3c824bd)
+ o Fix typo in whatsnew-2.0.txt (674bc6a Mansour Moufid)
+ o Improve win32 behavior of dns-sample.c code (a3f320e Gisle Vanem)
+
+
+
+Changes in version 2.0.15-stable (12 Oct 2011)
+BUGFIXES (DNS):
+ o DNS: add ttl for negative answers using RFC 2308 idea. (f72e8f6 Leonid Evdokimov)
+ o Add DNS_ERR_NODATA error code to handle empty replies. (94fba5b Leonid Evdokimov)
+
+BUFGIXES (bufferevents and evbuffers):
+ o Make evbuffer callbacks get the right n_added value after evbuffer_add (1ef1f68 Alex)
+ o Prefer mmap to sendfile unless a DRAINS_TO_FD flag is set. Allows add_file to work with SSL. (0ba0af9)
+
+BUGFIXES (event loop):
+ o When a signal callback is activated to run multiple times, allow event_base_loopbreak to work even before they all have run. (4e8eb6a)
+
+DOCUMENTATION FIXES:
+ o Fix docstring in dns.h (2b6eae5 Leonid Evdokimov)
+ o refer to non-deprecated evdns functions in comments (ba5c27d Greg Hazel)
+
+BUILD AND TESTING FIXES:
+ o le-proxy and regress depend on openssl directly (9ae061a Sergey Avseyev)
+ o Use _SOURCES, not _sources, in sample/Makefile.am (7f82382)
+ o Fixed compiler warnings for unchecked read/write calls. (c3b62fd Mark Ellzey)
+ o Make write-checking fixes use tt_fail_perror (2b76847)
+ o Fix some "value never used" warnings with gcc 4.6.1 (39c0cf7)
+
+
+
+Changes in version 2.0.14-stable (31 Aug 2011)
+BUGFIXES (bufferevents and evbuffers):
+ o Propagate errors on the underlying bufferevent to the user. (4a34394 Joachim Bauch)
+ o Ignore OpenSSL deprecation warnings on OS X (5d1b255 Sebastian Hahn)
+ o Fix handling of group rate limits under 64 bytes of burst (6d5440e)
+ o Solaris sendfile: correctly detect amount of data sent (643922e Michael Herf)
+ o Make rate limiting work with common_timeout logic (5b18f13)
+ o clear read watermark on underlying bufferevent when creating filtering bev to fix potentially failing fragmented ssl handshakes (54f7e61 Joachim Bauch)
+
+BUGFIXES (IOCP):
+ o IOCP: don't launch reads or writes on an unconnected socket (495c227)
+ o Make IOCP rate-limiting group support stricter and less surprising. (a98da7b)
+ o Have test-ratelim.c support IOCP (0ff2c5a)
+ o Make overlapped reads result in evbuffer callbacks getting invoked (6acfbdd)
+ o Correctly terminate IO on an async bufferevent on bufferevent_free (e6af35d)
+
+BUGFIXES (other):
+ o Fix evsig_dealloc memory leak with debugging turned on. (9b724b2 Leonid Evdokimov)
+ o Fix request_finished memory leak with debugging turned on. (aff6ba1 Leonid Evdokimov)
+
+BUILD AND TESTING FIXES:
+ o Allow OS-neutral builds for platforms where some versions have arc4random_buf (b442302 Mitchell Livingston)
+ o Try to fix 'make distcheck' errors when building out-of-tree (04656ea Dave Hart)
+ o Clean up some problems identified by Coverity. (7c11e51 Harlan Stenn)
+
+
+Changes in version 2.0.13-stable (18 Jul 2011)
+BUGFIXES
+ o Avoid race-condition when initializing global locks (b683cae)
+ o Fix bug in SSL bufferevents backed by a bev with a write high-watermarks (e050703 Joachim Bauch)
+ o Speed up invoke_callbacks on evbuffers when there are no callbacks (f87f568 Mark Ellzey)
+ o Avoid a segfault when all methods are disabled or broken (27ce38b)
+ o Fix incorrect results from evbuffer_search_eol(EOL_LF) (4461f1a)
+ o Add some missing checks for mm_calloc failures (89d5e09)
+ o Replace an assertion for event_base_free(NULL) with a check-and-warn (09fe97d)
+ o Report kqueue ebadf, epipe, and eperm as EV_READ events (1fd34ab)
+ o Check if the `evhttp_new_object' function in `http.c' returns NULL. (446cc7a Mansour Moufid)
+ o Use the correct printf args when formatting size_t (3203f88)
+ o Complain if the caller tries to change threading cbs after setting them (cb6ecee)
+
+DOCUMENTATION FIXES AND IMPROVEMENTS
+ o Revise the event/evbuffer/bufferevent doxygen for clarity and accuracy (2888fac)
+ o Update Doxyfile to produce more useful output (aea0555)
+
+TEST FIXES
+ o Fix up test_evutil_snprintf (caf695a)
+ o Fix tinytest invocation from windows shell (57def34 Ed Day)
+
+BUILD FIXES
+ o Use AM_CPPFLAGS in sample/Makefile.am, not AM_CFLAGS (4a5c82d)
+ o Fix select.c compilation on systems with no NFDBITS (49d1136)
+ o Fix a few warnings on OpenBSD (8ee9f9c Nicholas Marriott)
+ o Don't break when building tests from git without python installed (b031adf)
+ o Don't install event_rpcgen.py when --disable-libevent-install is used (e23cda3 Harlan Stenn)
+ o Fix AIX build issue with TAILQ_FOREACH definition (e934096)
+
+
+Changes in version 2.0.12-stable (4 Jun 2011)
+BUGFIXES
+ o Fix a warn-and-fail bug in kqueue by providing kevent() room to report errors (28317a0)
+ o Fix an assert-inducing fencepost bug in the select backend (d90149d)
+ o Fix failing http assertion introducd in commit 0d6622e (0848814 Kevin Ko)
+ o Fix a bug that prevented us from configuring IPv6 nameservers. (74760f1)
+ o Prevent size_t overflow in evhttp_htmlescape. (06c51cd Mansour Moufid)
+ o Added several checks for under/overflow conditions in evhttp_handle_chunked_read (a279272 Mark Ellzey)
+ o Added overflow checks in evhttp_read_body and evhttp_get_body (84560fc Mark Ellzey)
+
+DOCUMENTATION:
+ o Add missing words to EVLOOP_NONBLOCK documentation (9556a7d)
+
+BUILD FIXES
+ o libssl depends on libcrypto, not the other way around. (274dd03 Peter Rosin)
+ o Libtool brings in the dependencies of libevent_openssl.la automatically (7b819f2 Peter Rosin)
+ o Use OPENSSL_LIBS in Makefile.am (292092e Sebastian Hahn)
+ o Move the win32 detection in configure.in (ceb03b9 Sebastian Hahn)
+ o Correctly detect openssl on windows (6619385 Sebastian Hahn)
+ o Fix a compile warning with zlib 1.2.4 and 1.2.5 (5786b91 Sebastian Hahn)
+ o Fix compilation with GCC 2, which had no __builtin_expect (09d39a1 Dave Hart)
+ o Fix new warnings from GCC 4.6 (06a714f)
+ o Link with -lshell32 and -ladvapi32 on Win32. (86090ee Peter Rosin)
+ o Make the tests build when OpenSSL is not available. (07c41be Peter Rosin)
+ o Bring in the compile script from automake, if needed. (f3c7a4c Peter Rosin)
+ o MSVC does not provide S_ISDIR, so provide it manually. (70be7d1 Peter Rosin)
+ o unistd.h and sys/time.h might not exist. (fe93022 Peter Rosin)
+ o Make sure TINYTEST_LOCAL is defined when building tinytest.c (8fa030c Peter Rosin)
+ o Fix winsock2.h #include issues with MSVC (3d768dc Peter Rosin)
+ o Use evutil_gettimeofday instead of relying on the system gettimeofday. (0de87fe Peter Rosin)
+ o Always use evutil_snprintf, even if OS provides it (d1b2d11 Sebastian Hahn)
+ o InitializeCriticalSectionAndSpinCount requires _WIN32_WINNT >= 0x0403. (816115a Peter Rosin)
+ o cygwin: make it possible to build DLLs (d54d3fc)
+
+
+
+Changes in version 2.0.11-stable (27 Apr 2011)
+  [Autogenerated from the Git log, sorted and cleaned by hand.]
+BUGFIXES:
+ o Fix evport handling of POLLHUP and POLLERR (b42ce4b)
+ o Fix compilation on Windows with NDEBUG (cb8059d)
+ o Check for POLLERR, POLLHUP and POLLNVAL for Solaris event ports (0144886 Trond Norbye)
+ o Detect and handle more allocation failures. (666b096 Jardel Weyrich)
+ o Use event_err() only if the failure is truly unrecoverable. (3f8d22a Jardel Weyrich)
+ o Handle resize failures in the select backend better. (83e805a)
+ o Correctly free selectop fields when select_resize fails in select_init (0c0ec0b)
+ o Make --enable-gcc-warnings a no-op if not using gcc (3267703)
+ o Fix a type error in our (unused) arc4random_stir() (f736198)
+ o Correctly detect and stop non-chunked http requests when the body is too long (63a715e)
+ o Have event_base_gettimeofday_cached() always return wall-clock time (a459ef7)
+ o Workaround for http crash bug 3078187 (5dc5662 Tomash Brechko)
+ o Fix incorrect assertions and possible use-after-free in evrpc_free() (4b8f02f Christophe Fillot)
+ o Reset outgoing http connection when read data in idle state. (272823f Tomash Brechko)
+ o Fix subtle recursion in evhttp_connection_cb_cleanup(). (218cf19 Tomash Brechko)
+ o Fix the case when failed evhttp_make_request() leaved request in the queue. (0d6622e Tomash Brechko)
+ o Fix a crash bug in evdns server circular list code (00e91b3)
+ o Handle calloc failure in evdns. (Found by Dave Hart) (364291e)
+ o Fix a memory leak on win32 socket->event map. (b4f89f0)
+ o Add a forgotten NULL check to evhttp_parse_headers (12311ff Sebastian Hahn)
+ o Fix possible NULL-deref in evdns_cancel_request (5208544 Sebastian Hahn)
+
+PORTABILITY:
+ o Fall back to sscanf if we have no other way to implement strtoll (453317b)
+ o Build correctly on platforms without sockaddr_storage (9184563)
+ o Try to build correctly on platforms with no IPv6 support (713c254)
+ o Build on systems without AI_PASSIVE (cb92113)
+ o Fix http unit test on non-windows platforms without getaddrinfo (6092f12)
+ o Do not check for gethostbyname_r versions if we have getaddrinfo (c1260b0)
+ o Include arpa/inet.h as needed on HPUX (10c834c Harlan Stenn)
+ o Include util-internal.h as needed to build on platforms with no sockaddr_storage (bbf5515 Harlan Stenn)
+ o Check for getservbyname even if not on win32. (af08a94 Harlan Stenn)
+ o Add -D_OSF_SOURCE to fix hpux builds (0b33479 Harlan Stenn)
+ o Check for allocation failures in apply_socktype_protocol_hack (637d17a)
+ o Fix the check for multicast or broadcast addresses in evutil_check_interfaces (1a21d7b)
+ o Avoid a free(NULL) if out-of-memory in evdns_getaddrinfo. Found by Dave Hart (3417f68)
+
+DEFENSIVE PROGRAMMING:
+ o Add compile-time check for AF_UNSPEC==PF_UNSPEC (3c8f4e7)
+
+BUGS IN TESTS:
+ o Fix test.sh output on solaris (b4f89b6 Dave Hart)
+ o Make test-eof fail with a timeout if we never get an eof. (05a2c22 Harlan Stenn)
+ o Use %s with printf in test.sh (039b9bd)
+ o Add an assert to appease clang's static analyzer (b0ff7eb Sebastian Hahn)
+ o Add a forgotten return value check in the unit tests (3819b62 Sebastian Hahn)
+ o Actually send NULL request in http_bad_request_test (b693c32 Sebastian Hahn)
+ o add some (void) casts for unused variables (65707d7 Sebastian Hahn)
+ o Refactor test_getaddrinfo_async_cancel_stress() (48c44a6 Sebastian Hahn)
+ o Be nice and "handle" error return values in sample code (4bac793 Sebastian Hahn)
+ o Check return value of evbuffer_add_cb in tests (93a1abb Sebastian Hahn)
+ o Remote some dead code from dns-example.c (744c745 Sebastian Hahn)
+ o Zero a struct sockaddr_in before using it (646f9fe Sebastian Hahn)
+
+BUILD FIXES:
+ o Fix warnings about AC_LANG_PROGRAM usage (f663112 Sebastian Hahn)
+ o Skip check for zlib if we have no zlib.h (a317c06 Harlan Stenn)
+ o Fix autoconf bracket issues; make check for getaddrinfo include netdb.h (833e5e9 Harlan Stenn)
+ o Correct an AM_CFLAGS to an AM_CPPFLAGS in test/Makefile.am (9c469db Dave Hart)
+ o Fix make distcheck & installation of libevent 1 headers (b5a1f9f Dave Hart)
+ o Fix compilation under LLVM/clang with --enable-gcc-warnings (ad9ff58 Sebastian Hahn)
+
+FEATURES:
+ o Make URI parser able to tolerate nonconformant URIs. (95060b5)
+
+DOCUMENTATION:
+ o Clarify event_set_mem_functions doc (926f816)
+ o Correct evhttp_del_accept_socket documentation on whether socket is closed (f665924)
+ o fix spelling mistake in whatsnew-2.0.txt (deb2f73)
+ o Fix sample/http-server ipv6 fixes (eb692be)
+ o Comment internal headers used in sample code. (4eb281c)
+ o Be explicit about how long event loops run in event.h documentation (f95bafb)
+ o Add comment to configure.in to explain gc-sections test logic (c621359)
+ o Fix a couple of memory leaks in samples/http-server.c. Found by Dave Hart. (2e9f665)
+
+BUILD IMPROVEMENTS:
+ o Use the gcc -ffunction-segments feature to allow gc when linking with static libevent (0965c56 Dave Hart)
+ o Add configure options to disable installation, regression tests (49e9bb7 Dave Hart)
+
+
+
+Changes in version 2.0.10-stable (16 Dec 2010)
+  [Autogenerated from the Git log, sorted and cleaned by hand.]
+BUGFIXES
+ o Minor fix for IOCP shutdown handling fix (2599b2d Kelly Brock)
+ o Correctly notify the main thread when activating an event from a subthread (5beeec9)
+ o Reject overlong http requests early when Expect:100-continue is set (d23839f Constantine Verutin)
+ o EVUTIL_ASSERT: Use sizeof() to avoid "unused variable" warnings with -DNDEBUG. (b63ab17 Evan Jones)
+
+CODE CLEANUPS
+ o bufferevent-internal.h: Use the new event2/util.h header, not evutil.h (ef5e65a Evan Jones)
+ o Use relative includes instead of system includes consistently. (fbe64f2 Evan Jones)
+ o Make whitespace more consistent
+
+TESTING
+ o tests: Use new event2 headers instead of old compatibility headers. (4f33209 Evan Jones)
+
+DOCUMENTATION
+ o Document that the cpu_hint is only used on Windows with IOCP for now (57689c4)
+ o Add stuff to "whats new in 2.0" based on reading include changes since August. (18adc3f)
+
+
+Changes in 2.0.9-rc (30 Nov 2010):
+  [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW AND MODIFIED APIs
+ o Add a function to change a listener's callback. (46ee061)
+ o Make evbuffer_add_file take ev_off_t, not off_t (ac7e52d)
+ o Make rate-limits go up to SIZE_MAX/EV_SSIZE_MAX, not just INT32_MAX (2cbb1a1)
+ o Add a bufferevent_get_base function (aab49b6)
+
+MAJOR BUGFIXES
+ o Disable changelist for epoll by default because of Linux dup() bug; add an option and/or an envvar to reenable it for speed. (9531763)
+ o Fix a 100%-CPU bug where an SSL connection would sometimes never stop trying to write (1213d3d)
+ o Fix a nasty bug related to use of dup() with epoll on Linux (c281aba)
+ o Fix bugs in posix thread-id calculation when sizeof(pthread_t) != sizeof(long) (fbaf077)
+ o Fix some ints to evutil_socket_t; make tests pass on win64. (f817bfa Dimitre Piskyulev)
+ o Set _EVENT_SIZEOF_VOID_P correctly on win32 and win64 (1ae82cd Dimitre Piskyulev)
+ o Avoid double-invocation of user callback with EVUTIL_EAI_CANCEL (abf01ed)
+ o Set SO_UPDATE_ACCEPT_CONTEXT on sockets from AcceptEx so that shutdown() can work (52aa419)
+ o When closing a filtering bufferevent, clear callbacks on the underlying bufferevent (fc7b1b0)
+
+NEW AND MODIFIED HTTP APIs
+ o Add evhttp_parse_query_str to be used with evhttp_uri_parse. (2075fbc)
+ o Add evhttp_response_code to remove one more reason to include http_struct.h (22e0a9b)
+ o Define enumerators for all HTTP methods, including PATCH from RFC5789 (75a7341 Felix Nawothnig)
+ o Functions to actually use evhttp_bound_socket with/as evconnlistener. (006efa7)
+ o Add evhttp_request_get_command so code can tell GET from POST without peeking at the struct. (49f4bf7)
+ o Introduce absolute URI parsing helpers. (86dd720 Pavel Plesov)
+ o Revise evhttp_uri_parse implementation to handle more of RFC3986 (eaa5f1d)
+ o Add evhttp_connection_get_base() to get the event_base from an http connection (cd00079)
+ o Let evhttp_parse_query return -1 on failure (b1756d0)
+ o New evhttp_uri(encode|decode) functions to handle + and NUL characters right (a8148ce)
+ o Add evhttp_response_code to remove one more reason to include http_struct.h (22e0a9b)
+ o Tweak interface for allowed methods (f5b391e)
+ o Add evhttp server alias interface, correct flagging of proxy requests. (aab8c38 Christopher Davis)
+
+HTTP BUGFIXES
+ o Add some comments to http.c and make a few functions static. (90b3ed5)
+ o Fix Content-Length when trying send more than 100GB of data (!) on an evhttp. (525da3e)
+ o Fix a bug where we would read too much data in HTTP bodies or requests. (58a1cc6)
+ o Correctly count req->body_size on http usage without Content-Length (8e342e5)
+ o Avoid missed-request bug when entire http request arrives before data is flushed (74c0e86)
+ o reset "chunked" flag when sending non-chunked reply (aa5f55f Joachim Bauch)
+ o evhttp_encode_uri encodes all reserved characters, including !$'()*+,/:=@ (2e63a60)
+ o Replace exact-version checks for HTTP/1.1 with >= or < checks (647e094)
+ o evhttp: Return 501 when we get an unrecognized method, not 400. (536311a)
+ o Don't disable reading from the HTTP connection after sending the request to be notified of connection-close in time (c76640b Felix Nawothnig)
+ o Never call evhttp_readcb while writing. (0512487)
+ o Try to fix an assertion failure related to close detection (0faaa39)
+ o Correctly detect timeouts during http connects (04861d5)
+ o Preliminary support for Continue expectation in evhttp. (fa9305f Christopher Davis)
+
+OTHER BUGFIXES
+ o Correct logic for realigning a chain in evbuffer_add (e4f34e8)
+ o Fix a minor syntax error that most compilers didn't care about (e56ff65)
+ o Fix some uses of int for socket in regress (5d389dc)
+ o Check return value for ioctlsocket on win32 (f5ad31c Trond Norbye)
+ o Fix som event_warns that should have been event_warnx (19c71e7)
+ o Fix signal handler types for win64. (b81217f)
+ o Try to clear up more size_t vs int/long issues. (598d133)
+ o Make sure IOCP evconnlistener uses virtual events. (7b40a00 Christopher Davis)
+ o Don't free evdns_request handles until after the callback is invoked (9ed30de)
+ o Fix some more cancel-related bugs in getaddrinfo_async (c7cfbcf)
+ o Make evdns_getaddrinfo_cancel threadsafe (d51b2fc)
+ o Only clear underlying callbacks when the user hasn't reset them. (1ac5b23)
+ o Fix bug in bufferevent_connect on an openssl bufferevent that already had an fd (4f228a1)
+ o Resolve an evport bug in the thread/forking test (3a67d0b)
+ o Make sure the CLOEXEC flag is set on fds we open for base notification (3ab578f)
+ o Fix IRIX build.  sa_family collides with a #define in sys/socket.h on IRIX. (e874982 Kevin Bowling)
+ o If not WIN32, include <sys/socket.h> in event2/util.h. (1cd45e5 Kevin Bowling)
+ o Fix some C99-style comments to work with the xlC compiler. (c2e5e22 Kevin Bowling)
+ o Add some checks since lack of TAILQ_FOREACH doesn't imply lack of FIRST, END, NEXT, or INSERT_BEFORE.  Quiet some warnings in XL C. (c4dc335 Kevin Bowling)
+ o Reworked AIX __ss_family workaround to use AC_STRUCT_MEMBER. (2e2a3d7 Kevin Bowling)
+ o Take select from <sys/select.h> when testing in autoconf.  AIX build fix. (a3a9f6b Kevin Bowling)
+ o Fix snprintf related failures on IRIX. (3239073 Kevin Bowling)
+ o Remove _event_initialized(); make event_initialized() a function(); make it consistent on windows and non-windows (652024b)
+ o Do not let EVLOOP_ONCE exit the loop until all deferred callbacks have run (2d5e1bd)
+ o Make EVLOOP_ONCE ignore internal events (0617a81)
+ o Possible crash fix when freeing an underlying bufferevent of an openssl bufferevent (29f7623)
+
+HTTP CLEANUPS
+ o Stop using Libevent-1 headers in regress_http (1f507d7)
+ o Modernize header usage in bench_http.c (e587069)
+ o fix signed/unsigned warnings in http.c (74a91e5)
+ o Update the HTTP regression tests to use Libevent2 apis for non-http stuff (d9ffa89)
+ o Start porting http tests to not use legacy interfaces (8505a74)
+ o Convert the rest of the http tests to be non-legacy unit tests. (9bb8239)
+ o Rename the confusing "base" static variable in regress_http.c (353402a)
+ o Stop accessing http request struct directly from in the unit tests. (0b137f4)
+ o Refactor http version parsing into a single function (a38140b)
+
+TESTING
+ o Improvements to tinytest_macros.h (ad923a1)
+ o Add a huge pile of tests for the new URI functions, and make them pass. (a5a76e6)
+ o Unit tests for evhttp_uri_set* (bc98f5e)
+ o Increase the skew tolerance to 2 seconds in thread/deferred_cb_skew (f806476 Christopher Davis)
+ o Reorder backends in test.sh to match preference order in event.c (ece974f)
+ o Add a stress test for getaddrinfo_cancel (da1bf52)
+ o Units test for unexpected evhttp methods. (75e3320)
+
+DOCUMENTATION
+ o Document behavior of URI parsing more thoroughly. (3a33462)
+ o Document that two bufferevent functions only work on socket bufferevents (70e1b60)
+ o add a requested docstring for event_rpcgen.CommandLine.__init__ (f1250eb)
+ o Fix a mistake in http documentation found by Julien Blache (229714d)
+ o Add a basic example of how to write a static HTTP server. (4e794d5)
+ o Document event_get_assignment (88be27d)
+ o Note that reentrant calls to libevent from logging cbs may fail badly (e431bcd)
+ o Clarify EVLOOP_* documentation to be more precise. (057a514)
+
+CLEANUPS
+ o Simplify the logic for choosing EPOLL_CTL_ADD vs EPOLL_CTL_MOD (2c66983)
+ o Rename "size" variables in win32select that were really fd counts. (b6a158c)
+ o Fix even more win64 warnings (7484df6)
+ o Fix even more win64 warnings: buffer, event_tagging, http, evdns, evrpc (545a611)
+ o Fix more wn64 warnings. (34b84b9 Christopher Davis)
+ o Use the label_len local variable in evdns instead of recalculating it over and over (ba01456)
+ o Fix some irix compilation warnings spotted by Kevin Bowling (7bcace2)
+
+
+
+Changes in 2.0.8-rc (14 Oct 2010):
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW APIS
+ o Add error callback to evconnlistener (c4be8d8 Simon Perreault)
+ o Add a LEV_OPT_THREADSAFE option for threadsafe evconnlisteners (127d4f2)
+
+CHANGED BEHAVIOR
+ o Correct logic on disabling underlying bufferevents when disabling a filter (ac27eb8)
+
+BUGFIXES
+ o Obey enabled status when unsuspending (040a019 Simon Perreault)
+ o Warn when using the error-prone EV_SIGNAL interface in an error-prone way.  Also, fix a couple of race conditions in signal.c (720bd93)
+ O Make default signal backend fully threadsafe (95a7d41)
+ o Put internal events at highest priority (90651b3)
+ o Fix warnings in the main codebase flagged by -Wsigned-compare (9c8db0, 5e4bafb, 5c214a, 6be589a, e06f514)
+ o Fix compile in kqueue.c (b395392 Sebastian Hahn)
+ o Do not search outside of the system directory for windows DLLs (d49b5e3)
+ o Fix a spurious-call bug on epoll.c (0faaee0)
+ o Send a shutdown(SHUT_WR) before closing an http connection (e0fd870 Christopher Davis)
+ o Fix warnings on mingw with gcc 4.5 (5b7a370)
+ o Fix an EINVAL on evbuffer_write_iovec on OpenSolaris. (fdc640b)
+ o Fix allocation error for IOCP listeners. Probably harmless, since struct event is big (481ef92)
+ o Make iocp/listener/error work; don't accept again if lev is disabled. (62b429a Christopher Davis)
+ o Handle rate-limiting for reading on OpenSSL bufferevents correctly. (819b171)
+ o Fix serious bugs in per-bufferevent rate-limiting code (34d64f8)
+ o Avoid spurious reads from just-created open openssl bufferevents (223ee40)
+ o Fix a case where an ssl bufferevent with CLOSE_ON_FREE didn't close its fd (93bb7d8)
+ o The corrected bufferevent filter semantics let us fix our openssl tests (34331e4)
+
+TESTING
+ o Make SSL tests cover enabling/disabling EV_READ. (a5ce9ad)
+ o Bump to the latest version of tinytest (f0bd83e)
+ o Unit tests for listener error callbacks (045eef4)
+ o New unit test for ssl bufferevents starting with connected SSLs. (02f6259)
+
+DEBUGGABILITY
+ o Make debugging output for epoll backend more comprehensive (ec2b05e)
+ o Make event.c debugging messages report fds (e119899)
+ o Make the --enable-gcc-warnings option include signed comparison warnings (d3b096c)
+
+DEADCODE REMOVAL
+ o Remove the now-useless evsig_caught and evsig_process (4858b79)
+ o Remove event_base.evsigbase; nothing used it. (38d0960)
+
+
+
+Changes in 2.0.7-rc (9 Sep 2010):
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW APIS
+ o Expose a evdns_base_nameserver_sockaddr_add() function to add a nameserver by sockaddr (1952143)
+ o Add event_config_set_num_cpus_hint() for tuning win32 IOCP thread pools, etc. (2447fe8 Christopher Davis)
+
+BUGFIXES
+ o Fix a nasty dangling-event bug when using rate-limiting groups (0bffe43)
+ o Clean up syntax on TAILQ_ENTRY() usage to build correctly with recent MSVC (60433a0 Gilad Benjamini)
+ o Make definition of WIN32_LEAN_AND_MEAN in event.h conditional (3920172 Gilad Benjamini)
+ o Correctly detect failure to delete bufferevent read-timeout event (da6e7cd)
+ o Set close-on-exec bit for filedescriptors created by dns subsystem (d0b8843)
+ o Fix kqueue correctness test on x84_64 (6123d12)
+ o Detect events with no ev_base; warn instead of crashing (f1074b7)
+ o Fix an issue with forking and signal socketpairs in select/poll backends (d61b2f3)
+ o Stop using global arrays to implement the EVUTIL_ctype functions (1fdec20)
+ o On windows, make lock/thread function tables static (5de2bcb)
+ o Close th_notify_fds and open a new pair on reinit (495ed66)
+ o Declare signal handler function as "__cdecl" on Windows (f0056d0)
+ o Use the _func() replacements for open, fstat, etc in evutil.c on win32 (e50c0fc)
+ o Only process up to MAX_DEFERRED deferred_cbs at a time (17a14f1 Christopher Davis)
+
+THREADING BUGFIXES
+ o Avoid deadlock when activating signals (970e6ad)
+ o Add a condition variable backend, with implementations for pthreads and win32 (d4977b5)
+ o Use conditions instead of current_event_lock to fix a deadlock (e0972c2)
+ o Fix logic error in win32 TRY_LOCK that caused problems with rate-limiting (4c32b9d)
+ o Avoid needlessly calling evthread_notify_base() when the loop is not running (c7a06bf)
+ o Minimize calls to base_notify implementation functions, thereby avoiding needless syscalls (4632b78)
+
+IOCP BUGFIXES
+ o IOCP-related evbuffer fixes (03afa20 Christopher Davis)
+ o Stop IOCP when freeing the event_base (d844242 Christopher Davis)
+ o Some IOCP bufferevent tweaks (76f7e7a Christopher Davis)
+
+TESTS
+ o Make the regress_pthread.c tests work on windows with current test APIs (d74ae38)
+ o Add a unit test for conditions (5fb1095)
+ o Allow more than one copy of regression tests to run at once (a97320a)
+ o Fix event_del(0) instance in bench.c (b0f284c Shuo Chen)
+ o Fix a few memory leaks in the tests (1115366)
+ o IOCP-related unit test tweaks (499452f Christopher Davis)
+ o Improve testing of when thread-notification occurs (ce85280)
+
+BUILD AND DISTRIBUTION
+ o Add pkgconfig files for libevent_{openssl,pthreads} (ebcb1f0)
+ o Change include order in Makefile.nmake (4022b28)
+ o Make include/event2/event-config.h not included in source dist (a4af9be)
+ o Honor NDEBUG; build without warnings with NDEBUG; make NDEBUG always-off in unit test code (743f866)
+ o Declare evkeyvalq and event_list even if event_struct.h comes before sys/queue.h (d3ceca8)
+ o Move evkeyvalq into a separate header for evhttp_parse_query users (ca9048f)
+ o Prefer autoreconf -ivf to manual autogen.sh (7ea8e89)
+
+CLEANUP
+ o Completely remove the (mostly-removed) obsolete thread functions (3808168)
+ o Rename regress_pthread.c to regress_thread.c (041989f)
+ o Make defer-internal.h use lock macros, not direct calls to lock fns (5218d2a)
+
+DOCUMENTATION
+ o Document that DNS_NO_SEARCH is an obsolete alias for DNS_QUERY_NO_SEARCH (33200e7)
+ o Update the whatsnew-2.0.txt document (4991669)
+
+
+
+Changes in 2.0.6-rc (6 Aug 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Document a change in the semantics of event_get_struct_event_size() (e21f5d1)
+ o Add a comment to describe our plan for library versioning (9659ece)
+ o Fix sentence fragment in docs for event_get_struct_event_size() (7b259b6)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Remove the obsolete evthread interfaces (c5bab56)
+ o Let evhttp_send_error infer the right error reasons (3990669)
+ o Add a function to retrieve the other side of a bufferevent pair (17a8e2d)
+ o Add bufferevent_lock()/bufferevent_unlock() (215e629)
+ o Stop asserting when asked for a (unsupported) TCP dns port. Just return NULL. (7e87a59)
+ o Replace (unused,always 0) is_tcp argument to evdns_add_server_port*() with flags (e1c1167)
+ o Constify a couple of arguments to evdns_server_request_add_*_reply (cc2379d)
+ o Add an interface to expose min_share in ratelimiting groups (6ae53d6)
+
+BUGFIXES
+ o Avoid event_del on uninitialized event in event_base_free (6d19510)
+ o Add some missing includes to fix Linux build again (75701e8)
+ o Avoid close of uninitialized socket in evbuffer unit test (bda21e7)
+ o Correctly recognize .255 addresses as link-local when looking for interfaces (8c3452b)
+ o If no evdns request can be launched, return NULL, not a handle (b14f151)
+ o Use generic win32 interfaces, not ASCII-only ones, where possible. (899b0a3)
+ o Fix the default HTTP error template (06bd056 Felix Nawothnig)
+ o Close the file in evutil_read_file whether there's an error or not. (0798dd1 Pierre Phaneuf)
+ o Fix possible nullptr dereference in evhttp_send_reply_end() (29b2e23 Felix Nawothnig)
+ o never let bufferevent_rlim functions return negative (0859870)
+ o Make sample/hello_world work on windows (d89fdba)
+ o Fix a deadlock related to event-base notification.  Diagnosed by Zhou Li, Avi Bab, and Scott Lamb. (17522d2)
+ o Possible fix to 100% cpu usage with epoll and openssl (cf249e7 Mike Smellie)
+ o Don't race when calling event_active/event_add on a running signal event (fc5e0a2)
+ o Suppress a spurious EPERM warning in epoll.c (e73cbde)
+ o Fix wrong size calculation of iovec buffers when exact=1 (65abdc2 niks)
+ o Change bufferevent_openssl::do_write so it doesn't call SSL_write with a 0 length buffer (c991317 Mike Smellie)
+ o Fixed compilation of sample/le-proxy.c on win32 (13b912e Trond Norbye)
+ o Fix rate-limit calculation on openssl bufferevents. (009f300)
+ o Remember to initialize timeout events for bufferevent_async (de1f5d6 Christopher Davis)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Test the unlocked-deferred callback case of bufferevents (dfb75ab)
+ o Remove the now-unusable EVTHREAD_LOCK/UNLOCK constants (fdfc3fc)
+ o Use -Wlogical-op on gcc 4.5 or higher (d14bb92)
+ o Add the libtool-generated /m4/* stuff to .gitignore (c21c663)
+ o Remove some automake-generated files from version control. (9b14911)
+ o Have autogen.sh pass --force-missing to automake (8a44062)
+ o Set library version for libevent_pthreads correctly (b2d7440)
+ o Really only add libevent_core.la to LIBADD on mingw (1425003 Sebastian Hahn)
+ o Build more cleanly with NetBSDs that dislike toupper(char) (42a8c71)
+ o Fix unit tests with -DUSE_DEBUG enabled (28f31a4)
+ o Fix evdns build with -DUNICODE (5fa30d2)
+ o Move event-config.h to include/event2 (ec347b9)
+
+TESTING
+ o Add options to test-ratelim.c to check its results (2b44dcc)
+ o Make test-ratelim clean up after itself better. (b5bfc44)
+ o Remove the now-obsolete setup_test() and cleanup_test() functions (e73f1d7)
+ o Remove all non-error prints from test/regress.c (8bc1e3d)
+ o Make test.sh exit with nonzero status if tests fail (faf2a04)
+ o Have the unit tests report errors from test.sh (3689bd2)
+ o Fix logic in correcting high values from FIONREAD (3467f2f)
+ o Add test for behavior on remote socket close (44d57ee)
+ o Unit test for event_get_struct_event_size() (7510aac)
+ o Make test/test.sh call test-changelist (7c92691)
+ o Fix badly-behaved subtest of dns/bufferevent_connect_hostname (840a72f Joachim Bauch)
+ o Add option to test-ratelim to test min_share (42f6b62)
+ o Fix an assertion bug in test-ratelim (b2c6202)
+ o Make tests quieter on local dns resolver failure (e996b3d)
+ o Increase the tolerance in our unit tests for sloppy clocks. (170ffd2)
+ o Use AF_INET socketpair to test sendfile on Solaris (9b60209)
+ o Make test-changelist count cpu usage right on win32 (ea1ea3d)
+
+INTERNALS, PERFORMANCE, AND CODE CLEANUPS
+ o Mark the event_err() functions as __attribute__((noreturn)) (33bbbed)
+ o Do not check that event_base is set in EVBASE_ACQUIRE_LOCK (218a3c3)
+ o Replace (safe) use of strcpy with memcpy to appease OpenBSD (caca2f4)
+ o Remove some dead assignments (47c5dfb)
+ o Fix a pedantic gcc 4.4 warning in event2/event.h (276e7ee)
+ o Drain th_notify_fd[0] more bytes at a time. (a5bc15b)
+ o Tidy up the code in evthread_make_base_notifiable a little (61e1eee)
+ o Pass flags to fcntl(F_SETFL) and fcntl(F_SETFD) as int, not long (7c2dea1)
+ o Remove unused variables in test/test-changelist.c (b00d4c0)
+ o Fix whitespace. (cb927a5)
+ o Improve error message for failed epoll to make debugging easier. (9e725f7)
+ o Turn our socketpair() replacement into its own function (57b30cd)
+
+
+
+Changes in 2.0.5-beta (10 May 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Update all our copyright notices to say "2010" (17efc1c)
+ o Add Christopher Clark and Maxim Yegorushkin to the LICENSE file (38b7b57)
+ o Clarify Christopher Clark's status as writer of original ht code. (78772c3)
+ o Try to comment some of the event code more (cdd4c49)
+ o Add a few more evmap/changelist comments (c247adc)
+ o Add a comment to explain why evdns_request is now separte from request (ceefbe8)
+ o Document evutil_secure_rng_init() and evutil_secure_rng_add_bytes() (a5bf43a)
+ o Stop distributing and installing manpages: they were too inaccurate (7731ec8)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Remove signal_assign() and signal_new() macros. (2fac0f7)
+ o Make evdns use the regular logging system by default (b2f2be6)
+ o Allow evbuffer_read() to split across more than 2 iovecs (e470ad3)
+ o Functions to manipulate existing rate limiting groups. (ee41aca)
+ o Functions to track the total bytes sent over a rate limit group. (fb366c1)
+ o Detect and refuse reentrant event_base_loop() calls (b557b17)
+ o Limit the maximum number of events on each socket to 65535 (819f949)
+ o Add evbuffer_copyout to copy data from an evbuffer without draining (eb86c8c)
+ o Expose the request and reply members of rpc_req_generic() (07edf78 Shuo Chen)
+ o Add void* arguments to request_new and reply_new evrpc hooks (755fbf1 Shuo Chen)
+ o Seed the RNG using sysctl() as well as /dev/urandom (71fc3eb)
+ o Make evutil_secure_rng_init() work even with builtin arc4random (f980716)
+ o Report DNS error when lookup fails during bufferevent_socket_connect_hostname. (0ef4070 Christopher Davis)
+ o Release locks on bufferevents while executing callbacks (a5208fe Joachim Bauch) o Make debug mode catch mixed ET and non-ET events on an fd (cb67074)
+ o Catch attempts to enable debug_mode too late (9ecf0d4)
+ o Refuse null keys in evhttp_parse_query() (953e229 Frank Denis)
+
+BUGFIXES
+ o Avoid a spurious close(-1) on Linux (70a44b6)
+ o Do not close(-1) when freeing an uninitialized socket bufferevent (b34abf3)
+ o Free evdns_base->req_heads on evdns_base_free (859af67)
+ o Avoid an (untriggerable so far) crash bug in bufferevent_free() (0cf1431)
+ o Set mem_offset for every bufferevent type (657d1b6)
+ o Fix infrequent memory leak in bufferevent_init_common(). (8398641 Jardel Weyrich)
+ o Make evutil_signal_active() match declaration. (e1e703d Patrick Galbraith)
+ o Fix minheap code to use replacement malloc functions (a527618)
+ o Fix a free(NULL) in minheap-internal.h (6f20492)
+ o Fix critical bug in evbuffer_write when writev is not available (cda56ab)
+ o Make the no_iovecs case of write_atmost compile (8e227b0)
+ o Fix a memory leak when appending/prepending to a buffer with unused space. (45068a3)
+ o Clean up a mistake in pointer manipulation in evbuffer_remove (28bfed4 Christopher Davis)
+ o Always round up when there's a fractional number of msecs. (8f9e60c Christopher Davis)
+ o Fix compiler warnings under WIN32 (d469c50 Giuseppe Scrivano)
+ o Clean up properly when adding a signal handler fails. (b84b598 Gilad Benjamini) o Ensure that evdns_request is a persistent handle. (15bb82d Christopher Davis)
+ o Free search state when finished searching to avoid an infinite loop. (a625840 Christopher Davis)
+ o Assert for valid requests as necessary. (67072f3 Christopher Davis)
+ o do not leak the request object on persistent connections (9d8edf2)
+ o Make evdns logging threadsafe (b1c7950)
+ o Fix a couple of bugs in the BSD sysctl arc4seed logic (a47a4b7)
+ o Remove one last bug in last_with_datap logic. Found with valgrind (d49b92a)
+ o fix a leak when unpausing evrpc requests (94ee125)
+ o Fix a memory leak when unmarshalling RPC object arrays (f6ab2a2)
+ o Fix compilation when openssl support is disabled (40c301b)
+ o Allow empty reason line in HTTP status (739e688 Pierre Phaneuf)
+ o Fix a compile warning introduced in 739e688 (bd1ed5f Sebastian Hahn)
+ o Fix nonstandard TAILQ_FOREACH_REVERSE() definition (71afc52 Frank Denis)
+ o Try /proc on Linux as entropy fallback; use sysctl as last resort (20fda29)
+ o Fix symbol conflict between mm_*() macros and libmm (99e50e9)
+ o Fix some crazy macro mistakes in arc4random.c (90d4225)
+ o Make evbuffer_add_file() work on windows (dcdae6b)
+ o Fix unused-variable warning when building with threads disabled (ad811cd)
+ o Numerous opensolaris compilation fixes (c44de06)
+ o Fix getaddrinfo with protocol unset on Solaris 9. Found by Dagobert Michelsen (2cf2a28)
+ o Fix another nasty solaris getaddrinfo() behavior (3557071)
+ o Define _REENTRANT as needed on Solaris, elsewhere (c1cd32a)
+ o Fix some autoconf issues on OpenBSD (7c519df)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Distribute libevent.pc.in, not libevent.pc (22aff04)
+ o Avoid errors in evutil.c when building with _UNICODE defined (b677032 Brodie Thiesfield)
+ o Avoid errors in http.c when building with VC 2003 .NET (13e4f3b Brodie Thiesfield)
+ o Support the standard 'make check' target in place of 'make verify' (426c8fb)
+ o Remove redundant stuff from EXTRA_DIST (b660edf)
+ o Switch to using AM conditionals in place of AC_LIBOBJ (2e898f5)
+ o Remove an orphaned RELEASE flag in Makefile.am (0794b0d)
+ o Give a better warning for bad automake versions. (77c917d)
+ o Use dist_bin_SCRIPTS, not EXTRA_DIST, to distribute scripts (9eb2fd7)
+ o Never test for select() on windows (3eb044d Trond Norbye)
+ o Do not inhibit automake dependencies generation (10c4c90 Giuseppe Scrivano)
+ o Create shared libraries under Windows (3cbca86 Giuseppe Scrivano)
+ o Add ctags/etags files to .gitignore (0861d17)
+ o Only specify -no-undefined on mingw (25433b9)
+ o Only add libevent_core.la to LIBADD on mingw (fdc6297)
+
+TESTING
+ o Get bench_http to work on Windows; add a switch to enable IOCP. (4ac38a5 Christopher Davis)
+ o VC has no getopt(), so do without in bench_http. (1273d2f Christopher Davis)
+ o Fix an obnoxious typo in the bufferevent_timeout_filter test (0d047c3)
+ o Fix a write of uninitialized RAM in regression tests (68dc742)
+ o Fix some memory leaks in the unit tests (274a7bd)
+ o Make 'main/many_events' test 70 fds, not 64. (33874b0)
+ o Unit-test every evbuffer_add_file() implementation. (06a4443)
+ o Add more unit tests for evbuffer_expand (8c83e99)
+ o Test another case of evbuffer_prepend (1234b95)
+ o Fix a possible double-free bug in SSL bufferevents with CLOSE_ON_FREE (7501895) o Add dns/search_cancel unit test. (39b870b Christopher Davis)
+ o Make http_base_test stop leaking an event_base. (96730d3)
+ o Detect broken unsetenv at unit-test runtime (f37cd4c)
+ o Implement regress_make_tempfile on win32 to test evbuffer_add_file (b4f12a1)
+ o add more (currently skipped) add_file tests on win32 (05de45d)
+ o Fix bench_http build on win32. (384d124)
+ o Make unit test for add_file able to tell "error" from "done" (88a543f)
+ o Make test for bufferevent_connect_hostname system-neutral (f89168e)
+ o Make test.sh support mingw/msys on win32 (0ee6f6c)
+ o Fix test.sh on freebsd (3d9e05b)
+
+INTERNALS, PERFORMANCE, AND AND CODE CLEANUPS
+ o Improve the speed of evbuffer_readln() (cc1600a)
+ o more whitespace normalization (2c2618d)
+ o Revise evbuffer to add last_with_data (2a6d2a1)
+ o Use last_with_data in place of previous_to_last (c8ac57f)
+ o Remove previous_to_last from evbuffer (6f47bd1)
+ o Fix last_with_data compilation on windows (1e7b986)
+ o Add some glass-box tests for the last_with_data code. (17da042)
+ o Improve robustness for refcounting (f1bc125)
+ o Remove a needless min_heap_shift_up_() call (7204b91)
+ o Increase MIN_BUFFER_SIZE to 512 (1024 on 64-bit) (2014ae4)
+ o Do not use evbuffer_expand() to add the first chain to a buffer (5c0ebb3)
+ o Make evbuffer_prepend handle empty buffers better (c87272b)
+ o Replace last_with_data with a slightly smarter version (b7442f8)
+ o Turn the increasingly complex *_CHAIN() macros into functions (96865c4)
+ o Rewrite evbuffer_expand and its users (d5ebcf3)
+ o Add evutil_tv_to_msec for safe conversion of timevals to milliseconds. (850c3ff Christopher Davis)
+ o Initialize last_with_datap correctly in evbuffer_overlapped (a0983b6)
+ o Replace EVUTIL_CLOSESOCKET macro with a function (899c1dc Sebastian Sjöberg)
+ o Move domain search state to evdns_request. (beaa14a Christopher Davis)
+ o Remove redundant checks for lock!=NULL before calling EVLOCK_LOCK (50ec59f)
+ o Rename current_base symbol to event_global_current_base_ (c16e684)
+ o Fix whitespace in evutil.c (935e150)
+ o Replace users of "int fd" with "evutil_socket_t fd" in portable code (c7cf6f0)
+
+
+
+Changes in 2.0.4-alpha (28 Feb 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Add stub header for 2.0.4-alpha changelog. (94d0065)
+ o Improve the README with more information and links. (0b42726)
+ o Add more people who wrote patches to the acknowledgments (0af10d5)
+ o Add a warning about the use of event_initialized. (f32b575)
+ o Add a LICENSE file so people can find our license easily (7067006)
+ o Add a new "hello world" sample program (becb9f9)
+ o Clarify status of example programs (d60a1bd)
+ o Update time-test.c to use event2 (f4190bf)
+ o Add the arc4random.c license to the LICENSE file. (e15e1e9)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Improved optional lock debugging. (0cd3bb9)
+ o Rate-limiting for bufferevents; group and individual limits are supported. (737c9cd)
+ o Testing code for bufferevent rate-limiting. (f0c0124)
+ o Make the initial nameserver probe timeout configurable. (1e56a32)
+ o Revise the locking API: deprecate the old locking callbacks and add trylock. (347952f)
+ o Do not make bufferevent_setfd implicitly disable EV_READ and EV_WRITE. (8274379)
+ o Do not ignore bufferevent_enable(EV_READ) before bufferevent_connect(). (4a5b534)
+ o Introduced evutil_make_socket_closeonexec() to preserve fd flags for F_SETFD. (d0939d2 Jardel Weyrich)
+ o evdns_getaddrinfo() now supports the /etc/hosts file. (72dd666)
+ o Look at the proper /etc/hosts file on windows. (66c02c7)
+ o Allow http connections to use evdns for hostname looksups. (c698b77)
+ o Changelist code to defer event changes until just before dispatch (27308aa)
+ o do not use a function to assign the evdns base; instead assign it via evhttp_connection_base_new() which is a new function introduced in 2.0 (5032e52)
+ o Functions to access more fields of struct event. (0683950)
+ o Make kqueue use changelists. (45e5ae3)
+ o Remove kqueue->pend_changes. (3225dfb)
+ o Minimize epoll_ctl calls by using changelist (c8c6a89)
+ o Add support for a "debug mode" to try to catch common errors. (cd17c3a)
+ o Note a missing ratelim function (361da8f)
+ o Add ev_[u]intptr_t to include/event2/util.h (1fa4c81)
+ o const-ify a few more functions in event.h (d38a7a1)
+ o Deprecate EVENT_FD and EVENT_SIGNAL. (f6b2694)
+ o Remove EVUTIL_CHECK_FMT. (6c21c89)
+ o Add EV_*_MAX macros to event2/util.h to expose limits for ev_* types. (aba1fff) o Functions to view and manipulate rate-limiting buckets. (85047a6)
+ o Add the rest of the integer limits, and add a test for them. (60742d5)
+ o Remove the 'flags' argument from evdns_base_set_option() (1dd7e6d)
+ o Add an arc4random implementation for use by evdns (d4de062)
+ o Use off_t for the length parameter of evbuffer_add_file (3fe60fd)
+ o Construct Windows locks using InitializeCriticalSectionAndSpinCount (32c6f1b)
+ o Expose view of current rate limit as constrained by group limit (162ce8a)
+ o Provide consistent, tested semantics for bufferevent timeouts (d328829)
+
+BUGFIXES AND TESTS
+ o Tolerate code that returns from a fatal_cb. (91fe23f)
+ o Parenthesize macro arguments more aggressively (07e9e9b)
+ o Fix memory-leak of signal handler array with kqueue. (e1ffbb8)
+ o Stop passing EVTHREAD_READ and EVTHREAD_WRITE to non-rw locks. (76cd2b7)
+ o Fix two use-after-free bugs in unit tests spoted by lock debugging (d84d838)
+ o Fix a locking bug in event_base_loop() (da1718b)
+ o Fix an evdns lock violation. (2df1f82 Zhuang Yuyao)
+ o Valgrind fix: Clear struct kevent before checking for OSX bug. (56771a3 William Ahern)
+ o Fix up evthread compilation on windows (bd6f1ba Roman Puls)
+ o Fix regress_iocp.c usage of old lock allocation macros. (31687b4 unknown)
+ o Update nmake makefile to build evthread.c (b62d979 unknown)
+ o Fix a crash when reading badly formatted resolve.conf; from Yasuoka Masahiko (6c7c579 Yasuoka Masahiko)
+ o Fix a snow leopard compile warning in the unit tests. (7ae9445)
+ o Fix compile on Snow Leopard with gcc warnings enabled (70cdfe4 Sebastian Hahn)
+ o Only define _GNU_SOURCE if it is not already defined. (ea6b1df Joachim Bauch)
+ o Update sample/signal-test.c to use newer APIs and not leak. (f6430ac Evan Jones)
+ o Fix a segfault when writing a very fragmented evbuffer onto an SSL (a6adeca Joachim Bauch)
+ o Fix a segfault when freeing SSL bufferevents in an unusual order (a773df5 Joachim Bauch)
+ o Drop install-sh from our git repo: a mismatched version could break "make dist" (6799527)
+ o Set all instances of the version number correctly. (5a112d3)
+ o Fix a few locking issues on windows. (c51bb3c unknown)
+ o Use evutil_socket_t, not int, when logging socket errors. (292467c)
+ o Fix up behavior of never-defered callbacks a little (390e056)
+ o Replace some cases of uint32_t with ev_uint32_t. (a47d88d)
+ o Fix compilation of devpoll.c by adding missing thread includes. (fee2c77 Dagobert Michelsen)
+ o Make evutil_make_socket_nonblocking() leave any other flags alone. (4c8b7cd Jardel Weyrich)
+ o Fix an fd leak in evconnlistener_new_bind(). (24fb502 Jardel Weyrich)
+ o Fix a bogus free in evutil_new_addrinfo() (0d64051 Jardel Weyrich)
+ o Adjusted fcntl() retval comparison on evutil_make_socket_nonblocking(). (4df7dbc Jardel Weyrich)
+ o Fix the code that allowed DNS options to not end with : (ee4953f)
+ o Fix crash bugs when a bufferevent's eventcb is not set. (2e8eeea)
+ o Fix test-ratelim compilation on Linux. (885b427)
+ o Fix compilation of rate-limiting code on win32. (165d30e)
+ o Eradicated the last free() call. Let mm_free() take care of deallocation. (0546ce1 Jardel Weyrich)
+ o Fix byte counts when mixing deferred and non-deferred evbuffer callbacks. (29151e6)
+ o Fixed a memory leak on windows threads implementation. The CRITICAL_SECTION was not being free'd in evthread_win32_lock_free(). (2f33e00 Jardel Weyrich)
+ o Fixed a fd leak in start_accepting(), plus cosmetic changes (4367a33 Jardel Weyrich)
+ o Improved error handling in evconnlistener_new_async(). Also keeping the fd open because it is not opened by this function, so the caller is responsible for closing it. Additionally, since evconnlistener_new_bind() creates a socket and passes it to the function above, it required error checking to close the same socket. (fec66f9 Jardel Weyrich)
+ o Don't use a bind address for nameservers on loopback (8d4aaf9)
+ o Fix compilation of rate-limit code when threading support is disabled (97a8c79)
+ o Detect setenv/unsetenv; skip main/base_environ test if we can't fake them. (7296971)
+ o Check more internal event_add() calls for failure (ff3f6cd)
+ o Fix windows and msvc build (5c7a7bc)
+ o Call event_debug_unassign on internal events (a19b4a0)
+ o Try to fix a warning in hash_debug_entry (137f2c6)
+ o Fix a dumb typo in ev_intptr_t definitions. (27c9a40)
+ o do not fail while sending on http connections the client closed. (93d7369)
+ o make evhttp_send() safe against terminated connections, too (3978180)
+ o Make Libevent 1.4.12 build on win32 with Unicode enabled. (000a33e Brodie Thiesfield)
+ o Fix some additional -DUNICODE issues on win32. (a7a9431)
+ o Add a check to make soure our EVUTIL_AI flags do not conflict with the native ones (c18490e)
+ o Always use our own gai_strerror() replacement. (6810bdb)
+ o Make RNG work when we have arc4random() but not arc4random_buf() (4ec8fea)
+ o validate close cb on server when client connection closes (2f782af)
+ o Fix two unlocked reads in evbuffer. (7116bf2)
+ o When working without a current event base, don't try to use IOCP listeners (cb52838)
+ o Fix getpid() usage on Windows (ff2a134)
+ o Add a unit test for secure rng. (48a29b6)
+ o Add some headers to fix freebsd compilation (b72be50)
+ o When connect() succeeds immediately, don't invoke the callback immediately. (7515de9)
+ o Suspend read/write on bufferevents during hostname lookup (db08f64)
+ o Make bufferevent_free() clear all callbacks immediately. (b2fbeb3)
+ o Fix some race conditions in persistent events and event_reinit (e2642f0)
+ o Fix a bug in resetting timeouts on persistent events when IO triggers. (38ec0a7)
+ o Add a test for timeouts on filtering bufferevents. (c02bfe1)
+ o Add test for periodic timers that get activated for other reasons (8fcb7a1)
+ o Use new timeval diff comparison function in bufferevent test (f3dfe46)
+ o Delete stack-alloced event in new unit test before returning. (7ffd387)
+ o Fix mingw compilation (23170a6)
+ o Try to define a sane _EVENT_SIZEOF_SIZE_T for msvc compilation (1e14f82)
+ o Fix arc4random compilation on MSVC. (98edb89)
+ o deal with connect() failing immediately (7bc48bf)
+ o Small cleanups on freebsd-connect-refused patch. (57b7248)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Remove the contents of WIN32-Prj as unmaintained. (c69d5a5)
+ o Allow the user to redirect the verbose output of test/test.sh to a file (c382de6)
+ o Allow test.sh to be run as ./test/test.sh (7dfbe94)
+ o Never believe that we have pthreads on win32, even if gcc thinks we do. (78ed097)
+ o Make it compile under gcc --std=c89. (e2ca403)
+ o Fix a number of warnings from gcc -pedantic (918e9c5)
+ o Add the msvc-generated .lib files to .gitignore. (e244a2e)
+ o Add the "compile" script to gitignore. (1ba6bed)
+
+INTERNALS AND CODE CLEANUPS
+ o Add a .gitignore file. (ba34071)
+ o New EVTHREAD_TRY_LOCK function to try to grab a lock. (689fc09)
+ o Add the abilitity to mark some buffer callbacks as never-deferred. (438f9ed)
+ o Refactor our 'suspend operation' logic on bufferevents. (0d744aa)
+ o Simplify the read high-watermark checking. (5846bf6)
+ o Improve readability of evutil_unparse_protoname() (5a43df8 Jardel Weyrich)
+ o Expose our cached gettimeofday value with a new interface (47854a8)
+ o Whitespace fixes in test.sh (0b151a9)
+ o Enable branch-prediction hints with EVUTIL_UNLIKELY. (eaaf27f)
+ o Refactor code from evdns into a new internal "read a file" function. (0f7144f)
+ o Comestic changes in evconnlistener_new(), new_accepting_socket(), accepted_socket_invoke_user_cb() and iocp_listener_enable(). (510ab6b Jardel Weyrich)
+ o Add unit-test for bad_request bug fixed in 1.4 recently. (6cc79c6 Pavel Plesov) o Add a comment on evthread_enable_lock_debuging. (b9f43b2)
+ o Fix test.sh on shells without echo -n (94131e9)
+ o More unit tests for getaddrinfo_async: v4timeout and cancel. (a334b31)
+ o Make http use evconnlistener. (ec34533)
+ o move dns utility functions into a separate file so that we can use them for http testing (b822639)
+ o add a test for evhttp_connection_base_new with a dns_base (26714ca)
+ o forgot to add void to test function (78a50fe)
+ o Add a forgotten header (changelist-internal.h) (4b9f307)
+ o Remove some commented-out code in evutil (26e1b6f)
+ o Remove a needless include of rpc_compat.h (70a4a3e)
+ o Use less memory for each entry in a hashtable (a66e947)
+ o Try to untangle the logic in server_port_flush(). (439aea0)
+ o Use ev_[u]intptr_t types in place of [u]intptr_t (cef61a2)
+ o Reduce windows header includes in our own headers. (da6135e)
+ o clean up terminate_chunked test (e8a9782)
+ o Increment the submicro version number. (63e868e)
+ o Update event-config.h version number to match configure.in (aae7db5)
+ o Clean up formatting: Disallow space-before-tab. (8fdf09c)
+ o Clean up formatting: use tabs, not 8-spaces, to indent. (e5bbd40)
+ o Clean up formatting: remove trailing spaces (e5cf987)
+ o Clean up formatting: function/keyword spacing consistency. (4faeaea)
+
+
+
+Changes in 2.0.3-alpha (20 Nov 2009):
+ o Add a new code to support SSL/TLS on bufferevents, using the OpenSSL library (where available).
+ o Fix a bug where we didn't allocate enough memory in event_get_supported_methods().
+ o Avoid segfault during failed allocation of locked evdns_base. (Found by Rocco Carbone.)
+ o Export new evutil_ascii_* functions to perform locale-independent character type operations.
+ o Try to compile better with MSVC: patches from Brodie Thiesfield
+ o New evconnlistener_get_fd function to expose a listener's associated socket.
+ o Expose an ev_socklen_t type for consistent use across platforms.
+ o Make bufferevent_socket_connect() work when the original fd was -1.
+ o Fix a bug in bufferevent_socket_connect() when the connection succeeds too quickly.
+ o Export an evutil_sockaddr_cmp() to compare to sockaddr objects for equality.
+ o Add a bufferevent_get_enabled() to tell what a bufferevent has been configured to do.
+ o Add an evbuffer_search_eol() function to locate the end of a line nondestructively.
+ o Add an evbuffer_search_range() function to search a bounded range of a buffer.
+ o Fix a rare crash bug in evdns.
+ o Have bufferevent_socket_connect() with no arguments put a bufferevent into connecting mode.
+ o Support sendfile on Solaris: patch from Caitlin Mercer.
+ o New functions to explicitly reference a socket used by an evhttp object. Patches from David Reiss.
+ o When we send a BEV_EVENT_CONNECTED to indicate connected status, we no longer invoke the write callback as well unless we actually wrote data too.
+ o If the kernel tells us that there are a negative number of bytes to read from a socket, do not believe it.  Fixes bug 2841177; found by Alexander Pronchenkov.
+ o Do not detect whether we have monotonic clock support every time a new event base is created: instead do it only once.  Patch taken from Chromium.
+ o Do not allocate the maximum event queue for the epoll backend at startup.  Instead, start out accepting 32 events at a time, and double the queue's size when it seems that the OS is generating events faster than we're requesting them.  Saves up to 374K per epoll-based event_base.  Resolves bug 2839240.
+ o Treat an event with a negative fd as valid but untriggerable by Libevent.  This is useful for applications that want to manually activate events.
+ o Fix compilation on Android, which forgot to define fd_mask in its sys/select.h
+ o Do not drop data from evbuffer when out of memory; reported by Jacek Masiulaniec
+ o New event_base_got_exit() and event_base_got_break() functions to tell whether an event loop exited because of an event_base_loopexit() or an event_base_loopbreak().  Patch from Ka-Hing Cheung.
+ o When adding or deleting an event from a non-main thread, only wake up the main thread when its behavior actually needs to change.
+ o Fix some bugs when using the old evdns interfaces to initialize the evdns module.
+ o Detect errors during bufferevent_connect().  Patch from Christopher Davis.
+ o Fix compilation for listener.h for C++ - missing extern "C".  Patch from Ferenc Szalai.
+ o Make the event_base_loop() family of functions respect thread-safety better.  This should clear up a few hard-to-debug race conditions.
+ o Fix a bug when using a specialized memory allocator on win32.
+ o Have the win32 select() backend label TCP-socket-connected events as EV_WRITE, not EV_READ.  This should bring it in line with the other backends, and improve portability.  Patch from Christopher Davis.
+ o Stop using enums as arguments or return values when what we mean is a bitfield of enum values.  C++ doesn't believe that you can OR two enum values together and get another enum, and C++ takes its typing seriously.  Patch from Christopher Davis.
+ o Add an API to replace all fatal calls to exit() with a user-provided panic function.
+ o Replace all assert() calls with a variant that is aware of the user-provided logging and panic functions.
+ o Add a return value to event_assign so that it can fail rather than asserting when the user gives it bad input.  event_set still dies on bad input.
+ o The event_base_new() and event_base_new_with_config() functions now never call exit() on failure.  For backward "compatibility", event_init() still does, but more consistently.
+ o Remove compat/sys/_time.h.  It interfered with system headers on HPUX, and its functionality has been subsumed by event2/util.h and util-internal.h.
+ o Add a new bufferevent_socket_connect_hostname() to encapsulate the resolve-then-connect operation.
+ o Build kqueue.c correctly on GNU/kFreeBSD platforms. Patch pulled upstream from Debian.
+ o Alternative queue-based timeout algorithm for programs that use a large number of timeouts with the same value.
+ o New event_base_config option to disable the timeval cache entirely.
+ o Make EV_PERSIST timeouts more accurate: schedule the next event based on the scheduled time of the previous event, not based on the current time.
+ o Allow http.c to handle cases where getaddrinfo returns an IPv6 address.  Patch from Ryan Phillips.
+ o Fix a problem with excessive memory allocation when using multiple event priorities.
+ o Default to using arc4random for DNS transaction IDs on systems that have it; from OpenBSD.
+ o Never check the environment when we're running setuid or setgid; from OpenBSD.
+ o Options passed to evdns_set_option() no longer need to end with a colon.
+ o Add an evutil_getaddrinfo() function to clone getaddrinfo on platforms that don't have it.
+ o Add an evdns_getaddrinfo() function to provide a nonblocking getaddrinfo using evdns, so programs can perform useful hostname lookup.
+ o Finally expose the IOCP-based bufferevent backend.  It passes its unit tests, but probably still has some bugs remaining.  Code by Nick Mathewson and Christopher Davis.
+ o Numerous other bugfixes.
+ o On FreeBSD and other OSes, connect can return ECONREFUSED immediately; instead of failing the function call, pretend with faileld in the callback.
+ o Fix a race condition in the pthreads test case; found by Nick Mathewson
+ o Remove most calls to event_err() in http and deal with memory errors instead
+
+
+
+Changes in 2.0.2-alpha (25 Jul 2009):
+ o Add a new flag to bufferevents to make all callbacks automatically deferred.
+ o Make evdns functionality locked, and automatically defer dns callbacks.
+ o Fix a possible free(NULL) when freeing an event_base with no signals.
+ o Add a flag to disable checking environment varibles when making an event_base
+ o Disallow setting less than 1 priority.
+ o Fix a bug when removing a timeout from the heap. [Patch from Marko Kreen]
+ o Use signal.h, not sys/signal.h. [Patch from mmadia]
+ o Try harder to build with certain older c99 compilers.
+ o Make sure that an event_config's flags field is always initialized to 0. [Bug report from Victor Goya]
+ o Avoid data corruption when reading data entirely into the second-to-last chain of an evbuffer. [Bug report from Victor Goya]
+ o Make sendfile work on FreeBSD
+ o Do not use vararg macros for accessing evrpc structures; this is not backwards compatible, but we did not promise any backwards compatibility for the rpc code.
+ o Actually define the event_config_set_flag() function.
+ o Try harder to compile with Visual C++.
+ o Move event_set() and its allies to event2/event_compat.h where they belong.
+ o Remove the event_gotsig code, which has long been deprecated and unused.
+ o Add an event_get_base() function to return the base assigned to an event.
+ o New function to automate connecting on a socket-based bufferevent.
+ o New functions to automate listening for incoming TCP connections.
+ o Do case-insensitive checks with a locale-independent comparison function.
+ o Rename the evbuffercb and everrorcb callbacks to bufferevent_data_cb and bufferevent_event_cb respectively.  The old names are available in bufferevent_compat.h.
+ o Rename the EVBUFFER_* codes used by bufferevent event callbacks to BEV_EVENT_*, to avoid namespace collision with evbuffer flags.  The old names are available in bufferevent_compat.h.
+ o Move the EVBUFFER_INPUT and EVBUFFER_OUTPUT macros to bufferevent_compat.h
+ o Add a bufferevent_getfd() function to mirror bufferevent_setfd()
+ o Make bufferevent_setfd() return an error code if the operation is not successful.
+ o Shave 22 bytes off struct event on 32-bit platforms by shrinking and re-ordering fields.  The savings on 64-bit platforms is likely higher.
+ o Cap the maximum number of priorities at 256.
+ o Change the semantics of evbuffer_cb_set_flags() to be set-flag only; add a new evbuffer_cb_clear_flags() to remove set flags.
+ o Change the interface of evbuffer_add_reference so that the cleanup callback gets more information
+ o Revise the new evbuffer_reserve_space/evbuffer_commit_space() interfaces so that you can use them without causing extraneous copies or leaving gaps in the evbuffer.
+ o Add a new evbuffer_peek() interface to inspect data in an evbuffer without removing it.
+ o Fix a deadlock when suspending reads in a bufferevent due to a full buffer. (Spotted by Joachim Bauch.)
+ o Fix a memory error when freeing a thread-enabled event base with registered events. (Spotted by Joachim Bauch.)
+ o Try to contain degree of failure when running on a win32 version so heavily firewalled that we can't fake a socketpair.
+ o Activate fd events in a pseudorandom order with O(N) backends, so that we don't systematically favor low fds (select) or earlier-added fds (poll, win32).
+ o Replace some read()/write() instances with send()/recv() to work properly on win32.
+ o Set truncated flag correctly in evdns server replies.
+ o Raise RpcGenError in event_rpcgen.py; from jmanison and Zack Weinberg
+ o Fix preamble of rpcgen-generated files to rely on event2 includes; based on work by jmansion; patch from Zack Weinberg.
+ o Allow specifying the output filename for rpcgen; based on work by jmansion; patch from Zack Weinberg.
+ o Allow C identifiers as struct names; allow multiple comments in .rpc files; from Zack Weinberg
+ o Mitigate a race condition when using socket bufferevents in multiple threads.
+ o Use AC_SEARCH_LIBS, not AC_CHECK_LIB to avoid needless library use.
+ o Do not allow event_del(ev) to return while that event's callback is executing in another thread.  This fixes a nasty race condition.
+ o event_get_supported_methods() now lists methods that have been disabled with the EVENT_NO* environment options.
+ o Rename encode_int[64] to evtag_encode_int[64] to avoid polluting the global namespace.  The old method names are still available as macros in event2/tag_compat.h.
+
+
+
+Changes in 2.0.1-alpha (17 Apr 2009):
+ o free minheap on event_base_free(); from Christopher Layne
+ o debug cleanups in signal.c; from Christopher Layne
+ o provide event_base_new() that does not set the current_base global
+ o bufferevent_write now uses a const source argument; report from Charles Kerr
+ o improve documentation on event_base_loopexit; patch from Scott Lamb
+ o New function, event_{base_}loopbreak.  Like event_loopexit, it makes an event loop stop executing and return.  Unlike event_loopexit, it keeps subsequent pending events from getting executed.  Patch from Scott Lamb
+ o Check return value of event_add in signal.c
+ o provide event_reinit() to reintialize an event_base after fork
+ o New function event_set_mem_functinons.  It allows the user to give libevent replacement functions to use for memory management in place of malloc(), free(), etc.  This should be generally useful for memory instrumentation, specialized allocators, and so on.
+ o The kqueue implementation now catches signals that are raised after event_add() is called but before the event_loop() call.  This makes it match the other implementations.
+ o The kqueue implementation now restores original signal handlers correctly when its signal events are removed.
+ o Check return value of event_add in signal.c
+ o Add a more powerful evbuffer_readln as a replacement for evbuffer_readline.  The new function handles more newline styles, and is more useful with buffers that may contain a nul characters.
+ o Do not mangle socket handles on 64-bit windows.
+ o The configure script now takes an --enable-gcc-warnigns option that turns on many optional gcc warnings.  (Nick has been building with these for a while, but they might be useful to other developers.)
+ o move EV_PERSIST handling out of the event backends
+ o small improvements to evhttp documentation
+ o always generate Date and Content-Length headers for HTTP/1.1 replies
+ o set the correct event base for HTTP close events
+ o When building with GCC, use the "format" attribute to verify type correctness of calls to printf-like functions.
+ o Rewrite win32.c backend to be O(n lg n) rather than O(n^2).
+ o Removed obsoleted recalc code
+ o support for 32-bit tag numbers in rpc structures; this is wire compatible, but changes the API slightly.
+ o pull setters/getters out of RPC structures into a base class to which we just need to store a pointer; this reduces the memory footprint of these structures.
+ o prefix {encode,decode}_tag functions with evtag to avoid collisions
+ o fix a bug with event_rpcgen for integers
+ o Correctly handle DNS replies with no answers set (Fixes bug 1846282)
+ o add -Wstrict-aliasing to warnings and more cleanup
+ o removed linger from http server socket; reported by Ilya Martynov
+ o event_rpcgen now allows creating integer arrays
+ o support string arrays in event_rpcgen
+ o change evrpc hooking to allow pausing of RPCs; this will make it possible for the hook to do some meaning ful work; this is not backwards compatible.
+ o allow an http request callback to take ownership of a request structure
+ o allow association of meta data with RPC requests for hook processing
+ o associate more context for hooks to query such as the connection object
+ o remove pending timeouts on event_base_free()
+ o also check EAGAIN for Solaris' event ports; from W.C.A. Wijngaards
+ o devpoll and evport need reinit; tested by W.C.A Wijngaards
+ o event_base_get_method; from Springande Ulv
+ o Send CRLF after each chunk in HTTP output, for compliance with RFC2626.  Patch from "propanbutan".  Fixes bug 1894184.
+ o Add a int64_t parsing function, with unit tests, so we can apply Scott Lamb's fix to allow large HTTP values.
+ o Use a 64-bit field to hold HTTP content-lengths.  Patch from Scott Lamb.
+ o Allow regression code to build even without Python installed
+ o remove NDEBUG ifdefs from evdns.c
+ o detect integer types properly on platforms without stdint.h
+ o udpate documentation of event_loop and event_base_loop; from Tani Hosokawa.
+ o simplify evbuffer by removing orig_buffer
+ o do not insert event into list when evsel->add fails
+ o add support for PUT/DELETE requests; from Josh Rotenberg
+ o introduce evhttp_accept_socket() to accept from an already created socket
+ o include Content-Length in reply for HTTP/1.0 requests with keep-alive
+ o increase listen queue for http sockets to 128; if that is not enough the evhttp_accpet_socket() api can be used with a prepared socket.
+ o Patch from Tani Hosokawa: make some functions in http.c threadsafe.
+ o test support for PUT/DELETE requests; from Josh Rotenberg
+ o rewrite of the evbuffer code to reduce memory copies
+ o Some older Solaris versions demand that _REENTRANT be defined to get strtok_r(); do so.
+ o Do not free the kqop file descriptor in other processes, also allow it to be 0; from Andrei Nigmatulin
+ o Provide OpenSSL style support for multiple threads accessing the same event_base
+ o make event_rpcgen.py generate code include event-config.h; reported by Sam Banks.
+ o switch thread support so that locks get allocated as they are needed.
+ o make event methods static so that they are not exported; from Andrei Nigmatulin
+ o make RPC replies use application/octet-stream as mime type
+ o do not delete uninitialized timeout event in evdns
+ o Correct the documentation on buffer printf functions.
+ o Don't warn on unimplemented epoll_create(): this isn't a problem, just a reason to fall back to poll or select.
+ o Correctly handle timeouts larger than 35 minutes on Linux with epoll.c.  This is probably a kernel defect, but we'll have to support old kernels anyway even if it gets fixed.
+ o Make name_from_addr() threadsafe in http.c
+ o Add new thread-safe interfaces to evdns functions.
+ o Make all event_tagging interfaces threadsafe.
+ o Rename internal memory management functions.
+ o New functions (event_assign, event_new, event_free) for use by apps that want to be safely threadsafe, or want to remain ignorant of the contents of struct event.
+ o introduce bufferevent_read_buffer; allows reading without memory copy.
+ o expose bufferevent_setwatermark via header files and fix high watermark on read
+ o fix a bug in buffrevent read water marks and add a test for them
+ o fix a bug in which bufferevent_write_buffer would not schedule a write event
+ o provide bufferevent_input and bufferevent_output without requiring knowledge of the structure
+ o introduce bufferevent_setcb and bufferevent_setfd to allow better manipulation of bufferevents
+ o convert evhttp_connection to use bufferevents.
+ o use libevent's internal timercmp on all platforms, to avoid bugs on old platforms where timercmp(a,b,<=) is buggy.
+ o Remove the never-exported, never-used evhttp_hostportfile function.
+ o Support input/output filters for bufferevents; somewhat similar to libio's model.  This will allow us to implement SSL, compression, etc, transparently to users of bufferevents such as the http layer.
+ o allow connections to be removed from an rpc pool
+ o add new evtimer_assign, signal_assign, evtimer_new, and signal_new functions to manipulate timer and signal events, analagous to the now-recommended event_assign and event_new
+ o switch internal uses of event_set over to use event_assign.
+ o introduce evbuffer_contiguous_space() api that tells a user how much data is available in the first buffer chain
+ o introduce evbuffer_reserve_space() and evbuffer_commit_space() to make processing in filters more efficient.
+ o reduce system calls for getting current time by caching it.
+ o separate signal events from io events; making the code less complex.
+ o support for periodic timeouts
+ o support for virtual HTTP hosts.
+ o turn event_initialized() into a function, and add function equivalents to EVENT_SIGNAL and EVENT_FD so that people don't need to include event_struct.h
+ o Build test directory correctly with CPPFLAGS set.
+ o Provide an API for retrieving the supported event mechanisms.
+ o event_base_new_with_config() and corresponding config APIs.
+ o migrate the evhttp header to event2/ but accessors are still missing.
+ o deprecate timeout_* event functions by moving them to event_compat.h
+ o Move        windows gettimeofday replacement into a new evutil_gettimeofday().
+ o Make configure script work on IRIX.
+ o provide a method for canceling ongoing http requests.
+ o Make vsnprintf() returns consistent on win32.
+ o Fix connection keep-alive behavior for HTTP/1.0
+ o Fix use of freed memory in event_reinit; pointed out by Peter Postma
+ o constify struct timeval * where possible
+ o make event_get_supported_methods obey environment variables
+ o support for edge-triggered events on epoll and kqueue backends: patch from Valery Kholodkov
+ o support for selecting event backends by their features, and for querying the features of a backend.
+ o change failing behavior of event_base_new_with_config: if a config is provided and no backend is selected, return NULL instead of aborting.
+ o deliver partial data to request callbacks when chunked callback is set even if there is no chunking on the http level; allows cancelation of requests from within the chunked callback; from Scott Lamb.
+ o allow min_heap_erase to be called on removed members; from liusifan.
+ o Rename INPUT and OUTPUT to EVRPC_INPUT and EVRPC_OUTPUT.  Retain INPUT/OUTPUT aliases on on-win32 platforms for backwards compatibility.
+ o Do not use SO_REUSEADDR when connecting
+ o Support 64-bit integers in RPC structs
+ o Correct handling of trailing headers in chunked replies; from Scott Lamb.
+ o Support multi-line HTTP headers; based on a patch from Moshe Litvin
+ o Reject negative Content-Length headers; anonymous bug report
+ o Detect CLOCK_MONOTONIC at runtime for evdns; anonymous bug report   
+ o Various HTTP correctness fixes from Scott Lamb
+ o Fix a bug where deleting signals with the kqueue backend would cause subsequent adds to fail
+ o Support multiple events listening on the same signal; make signals regular events that go on the same event queue; problem report by Alexander Drozdov.
+ o Fix a problem with epoll() and reinit; problem report by Alexander Drozdov. 
+ o Fix off-by-one errors in devpoll; from Ian Bell
+ o Make event_add not change any state if it fails; reported by Ian Bell.
+ o Fix a bug where headers arriving in multiple packets were not parsed; fix from Jiang Hong; test by me.
+ o Match the query in DNS replies to the query in the request; from Vsevolod Stakhov.
+ o Add new utility functions to correctly observe and log winsock errors.
+ o Do not remove Accept-Encoding header
+ o Clear the timer cache on entering the event loop; reported by Victor Chang
+ o Only bind the socket on connect when a local address has been provided; reported by Alejo Sanchez
+ o Allow setting of local port for evhttp connections to support millions of connections from a single system; from Richard Jones.
+ o Clear the timer cache when leaving the event loop; reported by Robin Haberkorn
+ o Fix a typo in setting the global event base; reported by lance.
+ o Set the 0x20 bit on outgoing alphabetic characters in DNS requests randomly, and insist on a match in replies.  This helps resist DNS poisoning attacks.
+ o Make the http connection close detection work properly with bufferevents and fix a potential memory leak associated with it.
+ o Restructure the event backends so that they do not need to keep track of events themselves, as a side effect multiple events can use the same fd or signal.
+ o Add generic implementations for parsing and emiting IPv6 addresses on platforms that do not have inet_ntop and/or inet_pton.
+ o Allow DNS servers that have IPv6 addresses.
+ o Add an evbuffer_write_atmost() function to write a limited number of bytes to an fd.
+ o Refactor internal notify-main-thread logic to prefer eventfd to pipe, then pipe to socketpair, and only use socketpairs as a last resort.
+ o Try harder to pack all evbuffer reads into as few chains as possible, using readv/WSARecv as appropriate.
+ o New evthread_use_windows_threads() and evthread_use_pthreads() functions to set up the evthread callbacks with reasonable defaults.
+ o Change the semantics of timeouts in conjunction with EV_PERSIST; timeouts in that case will now repeat until deleted.
+ o sendfile, mmap and memory reference support for evbuffers.
+ o New evutil_make_listen_socket_reuseable() to abstract SO_REUSEADDR.
+ o New bind-to option to allow DNS clients to bind to an arbitrary port for outgoing requests.
+ o evbuffers can now be "frozen" to prevent operations at one or both ends.
+ o Bufferevents now notice external attempts to add data to an inbuf or remove it from an outbuf, and stop them.
+ o Fix parsing of queries where the encoded queries contained \r, \n or +
+ o Do not allow internal events to starve lower-priority events.
index 5d3865e7e793cf298a86fd11494bfff6b6be2131..d9d6603459c323e7ee82413d42aa14bbc8326ee0 100644 (file)
@@ -239,7 +239,7 @@ INCLUDE_FILE_PATTERNS  =
 # undefined via #undef or recursively expanded use the := operator 
 # instead of the = operator.
 
-PREDEFINED             = TAILQ_ENTRY RB_ENTRY _EVENT_DEFINED_TQENTRY _EVENT_IN_DOXYGEN
+PREDEFINED             = TAILQ_ENTRY RB_ENTRY EVENT_DEFINED_TQENTRY_ EVENT_IN_DOXYGEN_
 
 # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then 
 # this tag can be used to specify a list of macro names that should be expanded. 
index 5a315e47ff45345e07d3f82e26f28c6dc7b5feff..402ca50896cd094f020f5d6b2b1b0178bead627c 100644 (file)
@@ -3,7 +3,7 @@ as the 3-clause (or "modified") BSD license:
 
 ==============================
 Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
-Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
@@ -72,3 +72,28 @@ The arc4module is available under the following, sometimes called the
    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 
+==============================
+
+The Windows timer code is based on code from libutp, which is
+distributed under this license, sometimes called the "MIT" license.
+
+
+Copyright (c) 2010 BitTorrent, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
index ff07b26871fe94db97b23b59fcf87f876a0febde..17d0a85d52c7e733193a67a1e4aa0870c35e3c0e 100644 (file)
@@ -1,3 +1,9 @@
+# Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
 # 'foreign' means that we're not enforcing GNU package rules strictly.
 # '1.7' means that we need automake 1.7 or later (and we do).
 AUTOMAKE_OPTIONS = foreign 1.7
@@ -47,6 +53,11 @@ VERSION_INFO = 1:0:0
 #  2.0.10-stable--    2.0        5:1:0 (No ABI change)
 #  2.0.11-stable--    2.0        6:0:1 (ABI changed, backward-compatible)
 #  2.0.12-stable--    2.0        6:1:1 (No ABI change)
+#  2.0.13-stable--    2.0        6:2:1 (No ABI change)
+#  2.0.14-stable--    2.0        6:3:1 (No ABI change)
+#  2.0.15-stable--    2.0        6:3:1 (Forgot to update :( )
+#  2.0.16-stable--    2.0        6:4:1 (No ABI change)
+#  2.0.17-stable--    2.0        6:5:1 (No ABI change)
 #
 # For Libevent 2.1:
 #  2.1.1-alpha --     2.1        1:0:0
@@ -80,17 +91,21 @@ LIBEVENT_PKGCONFIG=libevent.pc
 # These sources are conditionally added by configure.in or conditionally
 # included from other files.
 PLATFORM_DEPENDENT_SRC = \
-       epoll_sub.c \
-       arc4random.c
+       arc4random.c \
+       epoll_sub.c
 
 EXTRA_DIST = \
+       ChangeLog-1.4 \
+       ChangeLog-2.0 \
+       Doxyfile \
        LICENSE \
+       Makefile.nmake test/Makefile.nmake \
        autogen.sh \
        event_rpcgen.py \
        libevent.pc.in \
-       Doxyfile \
+       make-event-config.sed \
        whatsnew-2.0.txt \
-       Makefile.nmake test/Makefile.nmake \
+       whatsnew-2.1.txt \
        $(PLATFORM_DEPENDENT_SRC)
 
 LIBEVENT_LIBS_LA = libevent.la libevent_core.la libevent_extra.la
@@ -149,33 +164,36 @@ if SIGNAL_SUPPORT
 SYS_SRC += signal.c
 endif
 
-BUILT_SOURCES = ./include/event2/event-config.h
-
-./include/event2/event-config.h: config.h
-       $(MKDIR_P) ./include/event2 || true
-       echo '/* event2/event-config.h' > $@
-       echo ' *' >> $@
-       echo ' * This file was generated by autoconf when libevent was built, and post-' >> $@
-       echo ' * processed by Libevent so that its macros would have a uniform prefix.' >> $@
-       echo ' *' >> $@
-       echo ' * DO NOT EDIT THIS FILE.' >> $@
-       echo ' *' >> $@
-       echo ' * Do not rely on macros in this file existing in later versions.'>> $@
-       echo ' */' >> $@
-       echo '#ifndef _EVENT2_EVENT_CONFIG_H_' >> $@
-       echo '#define _EVENT2_EVENT_CONFIG_H_' >> $@
-
-       sed -e 's/#define /#define _EVENT_/' \
-           -e 's/#undef /#undef _EVENT_/' \
-           -e 's/# define /# define _EVENT_/' \
-           -e 's/#ifndef /#ifndef _EVENT_/' < config.h >> $@
-       echo "#endif" >> $@
-
-CORE_SRC = event.c evthread.c buffer.c \
-       bufferevent.c bufferevent_sock.c bufferevent_filter.c \
-       bufferevent_pair.c listener.c bufferevent_ratelim.c \
-       evmap.c log.c evutil.c evutil_rand.c strlcpy.c $(SYS_SRC)
-EXTRA_SRC = event_tagging.c http.c evdns.c evrpc.c
+BUILT_SOURCES = include/event2/event-config.h
+
+include/event2/event-config.h: config.h make-event-config.sed
+       test -d include/event2 || $(MKDIR_P) include/event2
+       $(SED) -f $(srcdir)/make-event-config.sed < config.h > $@T
+       mv -f $@T $@
+
+CORE_SRC =                                     \
+       buffer.c                                \
+       bufferevent.c                           \
+       bufferevent_filter.c                    \
+       bufferevent_pair.c                      \
+       bufferevent_ratelim.c                   \
+       bufferevent_sock.c                      \
+       event.c                                 \
+       evmap.c                                 \
+       evthread.c                              \
+       evutil.c                                \
+       evutil_rand.c                           \
+       evutil_time.c                           \
+       listener.c                              \
+       log.c                                   \
+       strlcpy.c                               \
+       $(SYS_SRC)
+
+EXTRA_SRC =                                    \
+       evdns.c                                 \
+       event_tagging.c                         \
+       evrpc.c                                 \
+       http.c
 
 if BUILD_WITH_NO_UNDEFINED
 NO_UNDEFINED = -no-undefined
@@ -212,20 +230,41 @@ libevent_openssl_la_LDFLAGS = $(GENERIC_LDFLAGS)
 libevent_openssl_la_CPPFLAGS = $(AM_CPPFLAGS) $(OPENSSL_INCS)
 endif
 
-noinst_HEADERS = util-internal.h mm-internal.h ipv6-internal.h \
-       evrpc-internal.h strlcpy-internal.h evbuffer-internal.h \
-       bufferevent-internal.h http-internal.h event-internal.h \
-       evthread-internal.h ht-internal.h defer-internal.h \
-       minheap-internal.h log-internal.h evsignal-internal.h evmap-internal.h \
-       changelist-internal.h iocp-internal.h \
-       ratelim-internal.h \
-       evconfig-private.h \
-       WIN32-Code/event2/event-config.h \
-       WIN32-Code/evconfig-private.h \
-       WIN32-Code/tree.h \
-       compat/sys/queue.h
-
-EVENT1_HDRS = event.h evhttp.h evdns.h evrpc.h evutil.h
+noinst_HEADERS =                               \
+       WIN32-Code/evconfig-private.h           \
+       WIN32-Code/event2/event-config.h        \
+       WIN32-Code/tree.h                       \
+       bufferevent-internal.h                  \
+       changelist-internal.h                   \
+       compat/sys/queue.h                      \
+       defer-internal.h                        \
+       evbuffer-internal.h                     \
+       evconfig-private.h                      \
+       event-internal.h                        \
+       evmap-internal.h                        \
+       evrpc-internal.h                        \
+       evsignal-internal.h                     \
+       evthread-internal.h                     \
+       ht-internal.h                           \
+       http-internal.h                         \
+       iocp-internal.h                         \
+       ipv6-internal.h                         \
+       kqueue-internal.h                       \
+       log-internal.h                          \
+       minheap-internal.h                      \
+       mm-internal.h                           \
+       ratelim-internal.h                      \
+       ratelim-internal.h                      \
+       strlcpy-internal.h                      \
+       time-internal.h                         \
+       util-internal.h
+
+EVENT1_HDRS = \
+       include/evdns.h \
+       include/event.h \
+       include/evhttp.h \
+       include/evrpc.h \
+       include/evutil.h
 
 if INSTALL_LIBEVENT
 include_HEADERS = $(EVENT1_HDRS)
index e472e98894ff7081cf0c2dae5a380333d8f1985d..f0ec102320dc5bcb042f15a16877b7d050f5d19b 100644 (file)
@@ -1,5 +1,7 @@
-# WATCH OUT!  This makefile is a work in progress.  It is probably missing
-# tons of important things.  DO NOT RELY ON IT TO BUILD A GOOD LIBEVENT.
+# WATCH OUT!  This makefile is a work in progress.
+#
+# I'm not very knowledgeable about MSVC and nmake beyond their most basic
+# aspects.  If anything here looks wrong to you, please let me know.
 
 # Needed for correctness
 CFLAGS=/IWIN32-Code /Iinclude /Icompat /DHAVE_CONFIG_H /I.
@@ -14,7 +16,7 @@ LIBFLAGS=/nologo
 CORE_OBJS=event.obj buffer.obj bufferevent.obj bufferevent_sock.obj \
        bufferevent_pair.obj listener.obj evmap.obj log.obj evutil.obj \
        strlcpy.obj signal.obj bufferevent_filter.obj evthread.obj \
-       bufferevent_ratelim.obj evutil_rand.obj
+       bufferevent_ratelim.obj evutil_rand.obj evutil_time.obj
 WIN_OBJS=win32select.obj evthread_win32.obj buffer_iocp.obj \
        event_iocp.obj bufferevent_async.obj
 EXTRA_OBJS=event_tagging.obj http.obj evdns.obj evrpc.obj
index 1ca99906df0b4c3262308ccb38b9357bfbad78da..c79fb7bd9f15b48576aa5d63913682460dfe6c4c 100644 (file)
@@ -47,7 +47,7 @@ The configure script also supports the following flags:
 2. USEFUL LINKS:
 
 For the latest released version of Libevent, see the official website at
-http://monkey.org/~provos/libevent/ .
+http://libevent.org/ .
 
 There's a pretty good work-in-progress manual up at
    http://www.wangafu.net/~nickm/libevent-book/ .
@@ -71,20 +71,24 @@ use and development: http://archives.seul.org/libevent/users/
 The following people have helped with suggestions, ideas, code or
 fixing bugs:
 
-  Alejo
+  Samy Al Bahra
+  Jacob Appelbaum
+  Arno Bakker
   Weston Andros Adamson
   William Ahern
   Ivan Andropov
+  Sergey Avseyev
   Avi Bab
+  Joachim Bauch
   Gilad Benjamini
   Stas Bekman
-  Joachim Bauch
   Denis Bilenko
   Julien Blache
   Kevin Bowling
   Tomash Brechko
   Kelly Brock
   Ralph Castain
+  Adrian Chadd
   Lawnstein Chan
   Shuo Chen
   Ka-Hing Cheung
@@ -93,40 +97,59 @@ fixing bugs:
   Christopher Davis
   Mike Davis
   Mihai Draghicioiu
+  Alexander Drozdov
   Mark Ellzey
   Shie Erlich
+  Leonid Evdokimov
   Christophe Fillot
+  Mike Frysinger
+  Remi Gacogne
   Alexander von Gernler
   Artur Grabowski
+  Sebastian Hahn
   Dave Hart
+  Greg Hazel
   Michael Herf
   Sebastian Hahn
+  Savg He
+  Mark Heily
+  Michael Herf
+  Greg Hewgill
   Aaron Hopkins
   Tani Hosokawa
+  Jamie Iles
   Claudio Jeker
   Evan Jones
+  George Kadianakis
   Phua Keat
   Kevin Ko
   Brian Koehmstedt
   Marko Kreen
   Valery Kyholodov
+  Ross Lagerwall
   Scott Lamb
   Christopher Layne
   Adam Langley
+  Graham Leggett
   Philip Lewis
   Zhou Li
   David Libenzi
   Yan Lin
   Moshe Litvin
+  Mitchell Livingston
   Hagne Mahre
   Lubomir Marinov
+  Abilio Marques
+  Abel Mathew
   Nick Mathewson
   James Mansion
   Nicholas Marriott
   Andrey Matveev
   Caitlin Mercer
   Dagobert Michelsen
+  Andrea Montefusco
   Mansour Moufid
+  Mina Naguib
   Felix Nawothnig
   Trond Norbye
   Linus Nordberg
@@ -135,31 +158,45 @@ fixing bugs:
   Phil Oleson
   Dave Pacheco
   Tassilo von Parseval
+  Catalin Patulea
   Simon Perreault
   Pierre Phaneuf
+  Amarin Phaosawasdi
   Ryan Phillips
   Dimitre Piskyulev
   Pavel Plesov
   Jon Poland
+  Nate R
   Robert Ransom
   Bert JW Regeer
   Peter Rosin
+  Maseeb Abdul Qadir
+  Wang Qin
+  Alex S
   Hanna Schroeter
   Ralf Schmitt
   Mike Smellie
   Kevin Springborn
+  Nir Soffer
   Harlan Stenn
-  Ferenc Szalai
+  Steve Snyder
   Dug Song
   Dongsheng Song
+  Hannes Sowa
+  Ferenc Szalai
   Brodie Thiesfield
   Jason Toffaletti
+  Gisle Vanem
   Bas Verhoeven
   Constantine Verutin
+  Colin Watt
   Zack Weinberg
   Jardel Weyrich
+  Alejo
+  Alex
   Taral
   propanbutan
   mmadia
 
+
 If we have forgotten your name, please contact us.
index 88b3f44f90ac22d7ddecf20be7f4acb05ccc5890..88e206272bf9979aefe6da71dba0826d07e8aeae 100644 (file)
@@ -1,5 +1,5 @@
-#if !defined(_EVENT_EVCONFIG__PRIVATE_H) && !defined(__MINGW32__)
-#define _EVENT_EVCONFIG__PRIVATE_H
+#if !defined(EVENT_EVCONFIG__PRIVATE_H_) && !defined(__MINGW32__)
+#define EVENT_EVCONFIG__PRIVATE_H_
 
 /* Nothing to see here.  Move along. */
 
index 93b590a93b518e19eab3705ff9dfa543d4e9f3ef..a765507bdbadd5a03b8e40f5add4a13d297f086a 100644 (file)
  *
  * Do not rely on macros in this file existing in later versions.
  */
-#ifndef _EVENT_CONFIG_H_
-#define _EVENT_CONFIG_H_
+#ifndef EVENT_CONFIG_H__
+#define EVENT_CONFIG_H__
 /* config.h.  Generated by configure.  */
 /* config.h.in.  Generated from configure.in by autoheader.  */
 
 /* Define if libevent should not allow replacing the mm functions */
-/* #undef _EVENT_DISABLE_MM_REPLACEMENT */
+/* #undef EVENT__DISABLE_MM_REPLACEMENT */
 
 /* Define if libevent should not be compiled with thread support */
-/* #undef _EVENT_DISABLE_THREAD_SUPPORT */
+/* #undef EVENT__DISABLE_THREAD_SUPPORT */
 
 /* Define if clock_gettime is available in libc */
 /* #undef _EVENT_DNS_USE_CPU_CLOCK_FOR_ID */
 
 /* Define is no secure id variant is available */
 /* #define _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID 1 */
-#define _EVENT_DNS_USE_FTIME_FOR_ID 1
+#define EVENT_DNS_USE_FTIME_FOR_ID_ 1
 
 /* Define to 1 if you have the <arpa/inet.h> header file. */
-/* #undef _EVENT_HAVE_ARPA_INET_H */
+/* #undef EVENT__HAVE_ARPA_INET_H */
 
 /* Define to 1 if you have the `clock_gettime' function. */
-/* #undef _EVENT_HAVE_CLOCK_GETTIME */
+/* #undef EVENT__HAVE_CLOCK_GETTIME */
 
 /* Define if /dev/poll is available */
-/* #undef _EVENT_HAVE_DEVPOLL */
+/* #undef EVENT__HAVE_DEVPOLL */
 
 /* Define to 1 if you have the <dlfcn.h> header file. */
-/* #undef _EVENT_HAVE_DLFCN_H */
+/* #undef EVENT__HAVE_DLFCN_H */
 
 /* Define if your system supports the epoll system calls */
-/* #undef _EVENT_HAVE_EPOLL */
+/* #undef EVENT__HAVE_EPOLL */
 
 /* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef _EVENT_HAVE_EPOLL_CTL */
+/* #undef EVENT__HAVE_EPOLL_CTL */
 
 /* Define to 1 if you have the `eventfd' function. */
-/* #undef _EVENT_HAVE_EVENTFD */
+/* #undef EVENT__HAVE_EVENTFD */
 
 /* Define if your system supports event ports */
-/* #undef _EVENT_HAVE_EVENT_PORTS */
+/* #undef EVENT__HAVE_EVENT_PORTS */
 
 /* Define to 1 if you have the `fcntl' function. */
-/* #undef _EVENT_HAVE_FCNTL */
+/* #undef EVENT__HAVE_FCNTL */
 
 /* Define to 1 if you have the <fcntl.h> header file. */
-#define _EVENT_HAVE_FCNTL_H 1
+#define EVENT__HAVE_FCNTL_H 1
 
 /* Define to 1 if you have the `getaddrinfo' function. */
-#define _EVENT_HAVE_GETADDRINFO 1
+#define EVENT__HAVE_GETADDRINFO 1
 
 /* Define to 1 if you have the `getnameinfo' function. */
-#define _EVENT_HAVE_GETNAMEINFO 1
+#define EVENT__HAVE_GETNAMEINFO 1
 
 /* Define to 1 if you have the `getprotobynumber' function. */
-#define _EVENT_HAVE_GETPROTOBYNUMBER 1
+#define EVENT__HAVE_GETPROTOBYNUMBER 1
 
 /* Define to 1 if you have the `getservbyname' function. */
-#define _EVENT_HAVE_GETSERVBYNAME 1
+#define EVENT__HAVE_GETSERVBYNAME 1
 
 /* Define to 1 if you have the `gettimeofday' function. */
-/* #define _EVENT_HAVE_GETTIMEOFDAY 1 */
+/* #define EVENT__HAVE_GETTIMEOFDAY 1 */
 
 /* Define to 1 if you have the `inet_aton' function. */
-/* #undef _EVENT_HAVE_INET_ATON */
+/* #undef EVENT__HAVE_INET_ATON */
 
 /* Define to 1 if you have the `inet_ntop' function. */
-/* #undef _EVENT_HAVE_INET_NTOP */
+/* #undef EVENT__HAVE_INET_NTOP */
 
 /* Define to 1 if you have the `inet_pton' function. */
-/* #undef _EVENT_HAVE_INET_PTON */
+/* #undef EVENT__HAVE_INET_PTON */
 
 /* Define to 1 if you have the <inttypes.h> header file. */
-/* #define _EVENT_HAVE_INTTYPES_H 1 */
+/* #define EVENT__HAVE_INTTYPES_H 1 */
 
 /* Define to 1 if you have the `kqueue' function. */
-/* #undef _EVENT_HAVE_KQUEUE */
+/* #undef EVENT__HAVE_KQUEUE */
 
 /* Define if the system has zlib */
-/* #undef _EVENT_HAVE_LIBZ */
+/* #undef EVENT__HAVE_LIBZ */
 
 /* Define to 1 if you have the <memory.h> header file. */
-#define _EVENT_HAVE_MEMORY_H 1
+#define EVENT__HAVE_MEMORY_H 1
 
 /* Define to 1 if you have the `mmap' function. */
-/* #undef _EVENT_HAVE_MMAP */
+/* #undef EVENT__HAVE_MMAP */
 
 /* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef _EVENT_HAVE_NETINET_IN6_H */
+/* #undef EVENT__HAVE_NETINET_IN6_H */
 
 /* Define to 1 if you have the <netinet/in.h> header file. */
-/* #undef _EVENT_HAVE_NETINET_IN_H */
+/* #undef EVENT__HAVE_NETINET_IN_H */
 
 /* Define to 1 if you have the `pipe' function. */
-/* #undef _EVENT_HAVE_PIPE */
+/* #undef EVENT__HAVE_PIPE */
 
 /* Define to 1 if you have the `poll' function. */
-/* #undef _EVENT_HAVE_POLL */
+/* #undef EVENT__HAVE_POLL */
 
 /* Define to 1 if you have the <poll.h> header file. */
-/* #undef _EVENT_HAVE_POLL_H */
+/* #undef EVENT__HAVE_POLL_H */
 
 /* Define to 1 if you have the `port_create' function. */
-/* #undef _EVENT_HAVE_PORT_CREATE */
+/* #undef EVENT__HAVE_PORT_CREATE */
 
 /* Define to 1 if you have the <port.h> header file. */
-/* #undef _EVENT_HAVE_PORT_H */
+/* #undef EVENT__HAVE_PORT_H */
 
 /* Define if you have POSIX threads libraries and header files. */
-/* #undef _EVENT_HAVE_PTHREAD */
+/* #undef EVENT__HAVE_PTHREAD */
 
 /* Define if we have pthreads on this system */
-/* #undef _EVENT_HAVE_PTHREADS */
+/* #undef EVENT__HAVE_PTHREADS */
 
 /* Define to 1 if the system has the type `sa_family_t'. */
-/* #undef _EVENT_HAVE_SA_FAMILY_T */
+/* #undef EVENT__HAVE_SA_FAMILY_T */
 
 /* Define to 1 if you have the `select' function. */
-/* #undef _EVENT_HAVE_SELECT */
+/* #undef EVENT__HAVE_SELECT */
 
 /* Define to 1 if you have the `sendfile' function. */
-/* #undef _EVENT_HAVE_SENDFILE */
+/* #undef EVENT__HAVE_SENDFILE */
 
 /* Define if F_SETFD is defined in <fcntl.h> */
-/* #undef _EVENT_HAVE_SETFD */
+/* #undef EVENT__HAVE_SETFD */
 
 /* Define to 1 if you have the `sigaction' function. */
-/* #undef _EVENT_HAVE_SIGACTION */
+/* #undef EVENT__HAVE_SIGACTION */
 
 /* Define to 1 if you have the `signal' function. */
-#define _EVENT_HAVE_SIGNAL 1
+#define EVENT__HAVE_SIGNAL 1
 
 /* Define to 1 if you have the `splice' function. */
-/* #undef _EVENT_HAVE_SPLICE */
+/* #undef EVENT__HAVE_SPLICE */
 
 /* Define to 1 if you have the <stdarg.h> header file. */
-#define _EVENT_HAVE_STDARG_H 1
+#define EVENT__HAVE_STDARG_H 1
 
 /* Define to 1 if you have the <stddef.h> header file. */
-#define _EVENT_HAVE_STDDEF_H 1
+#define EVENT__HAVE_STDDEF_H 1
 
 /* Define to 1 if you have the <stdint.h> header file. */
-/* #define _EVENT_HAVE_STDINT_H 1 */
+/* #define EVENT__HAVE_STDINT_H 1 */
 
 /* Define to 1 if you have the <stdlib.h> header file. */
-#define _EVENT_HAVE_STDLIB_H 1
+#define EVENT__HAVE_STDLIB_H 1
 
 /* Define to 1 if you have the <strings.h> header file. */
-#define _EVENT_HAVE_STRINGS_H 1
+#define EVENT__HAVE_STRINGS_H 1
 
 /* Define to 1 if you have the <string.h> header file. */
-#define _EVENT_HAVE_STRING_H 1
+#define EVENT__HAVE_STRING_H 1
 
 /* Define to 1 if you have the `strlcpy' function. */
-/* #undef _EVENT_HAVE_STRLCPY */
+/* #undef EVENT__HAVE_STRLCPY */
 
 /* Define to 1 if you have the `strsep' function. */
-/* #undef _EVENT_HAVE_STRSEP */
+/* #undef EVENT__HAVE_STRSEP */
 
 /* Define to 1 if you have the `strtok_r' function. */
-/* #undef _EVENT_HAVE_STRTOK_R */
+/* #undef EVENT__HAVE_STRTOK_R */
 
 /* Define to 1 if you have the `strtoll' function. */
-/* #define _EVENT_HAVE_STRTOLL 1 */
+/* #define EVENT__HAVE_STRTOLL 1 */
 
-#define _EVENT_HAVE_STRUCT_ADDRINFO 1
+#define EVENT__HAVE_STRUCT_ADDRINFO 1
 
 /* Define to 1 if the system has the type `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR 1
+#define EVENT__HAVE_STRUCT_IN6_ADDR 1
 
 /* Define to 1 if `s6_addr16' is member of `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR_S6_ADDR16 1
+#define EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 1
 
 /* Define to 1 if `s6_addr32' is member of `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR_S6_ADDR32 1
+#define EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 1
 
 /* Define to 1 if the system has the type `struct sockaddr_in6'. */
-#define _EVENT_HAVE_STRUCT_SOCKADDR_IN6 1
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
 
 /* Define to 1 if `sin6_len' is member of `struct sockaddr_in6'. */
-/* #undef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */
 
 /* Define to 1 if `sin_len' is member of `struct sockaddr_in'. */
-/* #undef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
 
 /* Define to 1 if the system has the type `struct sockaddr_storage'. */
-#define _EVENT_HAVE_STRUCT_SOCKADDR_STORAGE 1
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
 
 /* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_DEVPOLL_H */
+/* #undef EVENT__HAVE_SYS_DEVPOLL_H */
 
 /* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EPOLL_H */
+/* #undef EVENT__HAVE_SYS_EPOLL_H */
 
 /* Define to 1 if you have the <sys/eventfd.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EVENTFD_H */
+/* #undef EVENT__HAVE_SYS_EVENTFD_H */
 
 /* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EVENT_H */
+/* #undef EVENT__HAVE_SYS_EVENT_H */
 
 /* Define to 1 if you have the <sys/ioctl.h> header file. */
-/* #undef _EVENT_HAVE_SYS_IOCTL_H */
+/* #undef EVENT__HAVE_SYS_IOCTL_H */
 
 /* Define to 1 if you have the <sys/mman.h> header file. */
-/* #undef _EVENT_HAVE_SYS_MMAN_H */
+/* #undef EVENT__HAVE_SYS_MMAN_H */
 
 /* Define to 1 if you have the <sys/param.h> header file. */
-/* #define _EVENT_HAVE_SYS_PARAM_H 1 */
+/* #define EVENT__HAVE_SYS_PARAM_H 1 */
 
 /* Define to 1 if you have the <sys/queue.h> header file. */
-/* #undef _EVENT_HAVE_SYS_QUEUE_H */
+/* #undef EVENT__HAVE_SYS_QUEUE_H */
 
 /* Define to 1 if you have the <sys/select.h> header file. */
-/* #undef _EVENT_HAVE_SYS_SELECT_H */
+/* #undef EVENT__HAVE_SYS_SELECT_H */
 
 /* Define to 1 if you have the <sys/sendfile.h> header file. */
-/* #undef _EVENT_HAVE_SYS_SENDFILE_H */
+/* #undef EVENT__HAVE_SYS_SENDFILE_H */
 
 /* Define to 1 if you have the <sys/socket.h> header file. */
-/* #undef _EVENT_HAVE_SYS_SOCKET_H */
+/* #undef EVENT__HAVE_SYS_SOCKET_H */
 
 /* Define to 1 if you have the <sys/stat.h> header file. */
-#define _EVENT_HAVE_SYS_STAT_H 1
+#define EVENT__HAVE_SYS_STAT_H 1
 
 /* Define to 1 if you have the <sys/time.h> header file. */
-/* #define _EVENT_HAVE_SYS_TIME_H 1 */
+/* #define EVENT__HAVE_SYS_TIME_H 1 */
 
 /* Define to 1 if you have the <sys/types.h> header file. */
-#define _EVENT_HAVE_SYS_TYPES_H 1
+#define EVENT__HAVE_SYS_TYPES_H 1
 
 /* Define to 1 if you have the <sys/uio.h> header file. */
-/* #undef _EVENT_HAVE_SYS_UIO_H */
+/* #undef EVENT__HAVE_SYS_UIO_H */
 
 /* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-/* #undef _EVENT_HAVE_TAILQFOREACH */
+/* #undef EVENT__HAVE_TAILQFOREACH */
 
 /* Define if timeradd is defined in <sys/time.h> */
-/* #undef _EVENT_HAVE_TIMERADD */
+/* #undef EVENT__HAVE_TIMERADD */
 
 /* Define if timerclear is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCLEAR 1
+#define EVENT__HAVE_TIMERCLEAR 1
 
 /* Define if timercmp is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCMP 1
+#define EVENT__HAVE_TIMERCMP 1
 
 /* Define if timerisset is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERISSET 1
+#define EVENT__HAVE_TIMERISSET 1
 
 /* Define to 1 if the system has the type `uint16_t'. */
-/* #define _EVENT_HAVE_UINT16_T 1 */
+/* #define EVENT__HAVE_UINT16_T 1 */
 
 /* Define to 1 if the system has the type `uint32_t'. */
-/* #define _EVENT_HAVE_UINT32_T 1 */
+/* #define EVENT__HAVE_UINT32_T 1 */
 
 /* Define to 1 if the system has the type `uint64_t'. */
-/* #define _EVENT_HAVE_UINT64_T 1 */
+/* #define EVENT__HAVE_UINT64_T 1 */
 
 /* Define to 1 if the system has the type `uint8_t'. */
-/* #define _EVENT_HAVE_UINT8_T 1 */
+/* #define EVENT__HAVE_UINT8_T 1 */
 
 /* Define to 1 if you have the <unistd.h> header file. */
-/* #define _EVENT_HAVE_UNISTD_H 1 */
+/* #define EVENT__HAVE_UNISTD_H 1 */
 
 /* Define to 1 if you have the `vasprintf' function. */
-/* #undef _EVENT_HAVE_VASPRINTF */
+/* #undef EVENT__HAVE_VASPRINTF */
 
 /* Define if kqueue works correctly with pipes */
-/* #undef _EVENT_HAVE_WORKING_KQUEUE */
+/* #undef EVENT__HAVE_WORKING_KQUEUE */
 
 /* Numeric representation of the version */
-#define _EVENT_NUMERIC_VERSION 0x02010001
+#define EVENT__NUMERIC_VERSION 0x02010101
 
 /* Name of package */
-#define _EVENT_PACKAGE "libevent"
+#define EVENT__PACKAGE "libevent"
 
 /* Define to the address where bug reports for this package should be sent. */
-#define _EVENT_PACKAGE_BUGREPORT ""
+#define EVENT__PACKAGE_BUGREPORT ""
 
 /* Define to the full name of this package. */
-#define _EVENT_PACKAGE_NAME ""
+#define EVENT__PACKAGE_NAME ""
 
 /* Define to the full name and version of this package. */
-#define _EVENT_PACKAGE_STRING ""
+#define EVENT__PACKAGE_STRING ""
 
 /* Define to the one symbol short name of this package. */
-#define _EVENT_PACKAGE_TARNAME ""
+#define EVENT__PACKAGE_TARNAME ""
 
 /* Define to the version of this package. */
-#define _EVENT_PACKAGE_VERSION ""
+#define EVENT__PACKAGE_VERSION ""
 
 /* Define to necessary symbol if this constant uses a non-standard name on
    your system. */
-/* #undef _EVENT_PTHREAD_CREATE_JOINABLE */
+/* #undef EVENT__PTHREAD_CREATE_JOINABLE */
 
 /* The size of a `int', as computed by sizeof. */
-#define _EVENT_SIZEOF_INT 4
+#define EVENT__SIZEOF_INT 4
 
 /* The size of a `long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG 4
+#define EVENT__SIZEOF_LONG 4
 
 /* The size of a `long long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG_LONG 8
+#define EVENT__SIZEOF_LONG_LONG 8
 
 /* The size of a `short', as computed by sizeof. */
-#define _EVENT_SIZEOF_SHORT 2
+#define EVENT__SIZEOF_SHORT 2
 
 /* The size of `size_t', as computed by sizeof. */
 #ifdef _WIN64
-#define _EVENT_SIZEOF_SIZE_T 8
+#define EVENT__SIZEOF_SIZE_T 8
 #else
-#define _EVENT_SIZEOF_SIZE_T 4
+#define EVENT__SIZEOF_SIZE_T 4
 #endif
 
 /* The size of `void *', as computed by sizeof. */
 #ifdef _WIN64
-#define _EVENT_SIZEOF_VOID_P 8
+#define EVENT__SIZEOF_VOID_P 8
 #else
-#define _EVENT_SIZEOF_VOID_P 4
+#define EVENT__SIZEOF_VOID_P 4
 #endif
 
 /* Define to 1 if you have the ANSI C header files. */
-#define _EVENT_STDC_HEADERS 1
+#define EVENT__STDC_HEADERS 1
 
 /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define _EVENT_TIME_WITH_SYS_TIME 1
+#define EVENT__TIME_WITH_SYS_TIME 1
 
 /* Version number of package */
-#define _EVENT_VERSION "2.1.0-alpha-dev"
+#define EVENT__VERSION "2.1.1-alpha-dev"
 
 /* Define to appropriate substitue if compiler doesnt have __func__ */
-#define _EVENT___func__ __FUNCTION__
+#define EVENT____func__ __FUNCTION__
 
 /* Define to empty if `const' does not conform to ANSI C. */
-/* #undef _EVENT_const */
+/* #undef EVENT__const */
 
 /* Define to `__inline__' or `__inline' if that's what the C compiler
    calls it, or to nothing if 'inline' is not supported under any name.  */
 #ifndef _EVENT___cplusplus
-#define _EVENT_inline __inline
+#define EVENT__inline __inline
 #endif
 
 /* Define to `int' if <sys/types.h> does not define. */
-/* #undef _EVENT_pid_t */
+/* #undef EVENT__pid_t */
 
 /* Define to `unsigned' if <sys/types.h> does not define. */
-/* #undef _EVENT_size_t */
+/* #undef EVENT__size_t */
 
 /* Define to unsigned int if you dont have it */
-#define _EVENT_socklen_t unsigned int
+#define EVENT__socklen_t unsigned int
 
 /* Define to `int' if <sys/types.h> does not define. */
-#define _EVENT_ssize_t SSIZE_T
+#define EVENT__ssize_t SSIZE_T
 
 #endif
index 254c12b6cb0ae0cc3d53171bc521d7364518b093..95497514e24247f4e0ee0536de638a4302e32fcb 100644 (file)
@@ -1,6 +1,7 @@
 /* Portable arc4random.c based on arc4random.c from OpenBSD.
  * Portable version by Chris Davis, adapted for Libevent by Nick Mathewson
  * Copyright (c) 2010 Chris Davis, Niels Provos, and Nick Mathewson
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
  *
  * Note that in Libevent, this file isn't compiled directly.  Instead,
  * it's included from evutil_rand.c
@@ -58,7 +59,7 @@
 #include <unistd.h>
 #include <sys/param.h>
 #include <sys/time.h>
-#ifdef _EVENT_HAVE_SYS_SYSCTL_H
+#ifdef EVENT__HAVE_SYS_SYSCTL_H
 #include <sys/sysctl.h>
 #endif
 #endif
@@ -167,8 +168,8 @@ arc4_seed_win32(void)
 }
 #endif
 
-#if defined(_EVENT_HAVE_SYS_SYSCTL_H)
-#if _EVENT_HAVE_DECL_CTL_KERN && _EVENT_HAVE_DECL_KERN_RANDOM && _EVENT_HAVE_DECL_RANDOM_UUID
+#if defined(EVENT__HAVE_SYS_SYSCTL_H) && defined(EVENT__HAVE_SYSCTL)
+#if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_RANDOM && EVENT__HAVE_DECL_RANDOM_UUID
 #define TRY_SEED_SYSCTL_LINUX
 static int
 arc4_seed_sysctl_linux(void)
@@ -205,7 +206,7 @@ arc4_seed_sysctl_linux(void)
 }
 #endif
 
-#if _EVENT_HAVE_DECL_CTL_KERN && _EVENT_HAVE_DECL_KERN_ARND
+#if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_ARND
 #define TRY_SEED_SYSCTL_BSD
 static int
 arc4_seed_sysctl_bsd(void)
@@ -244,7 +245,7 @@ arc4_seed_sysctl_bsd(void)
        return 0;
 }
 #endif
-#endif /* defined(_EVENT_HAVE_SYS_SYSCTL_H) */
+#endif /* defined(EVENT__HAVE_SYS_SYSCTL_H) */
 
 #ifdef __linux__
 #define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
@@ -260,7 +261,7 @@ arc4_seed_proc_sys_kernel_random_uuid(void)
        unsigned char entropy[64];
        int bytes, n, i, nybbles;
        for (bytes = 0; bytes<ADD_ENTROPY; ) {
-               fd = open("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
+               fd = evutil_open_closeonexec_("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
                if (fd < 0)
                        return -1;
                n = read(fd, buf, sizeof(buf));
@@ -269,8 +270,8 @@ arc4_seed_proc_sys_kernel_random_uuid(void)
                        return -1;
                memset(entropy, 0, sizeof(entropy));
                for (i=nybbles=0; i<n; ++i) {
-                       if (EVUTIL_ISXDIGIT(buf[i])) {
-                               int nyb = evutil_hex_char_to_int(buf[i]);
+                       if (EVUTIL_ISXDIGIT_(buf[i])) {
+                               int nyb = evutil_hex_char_to_int_(buf[i]);
                                if (nybbles & 1) {
                                        entropy[nybbles/2] |= nyb;
                                } else {
@@ -304,7 +305,7 @@ arc4_seed_urandom(void)
        size_t n;
 
        for (i = 0; filenames[i]; ++i) {
-               fd = open(filenames[i], O_RDONLY, 0);
+               fd = evutil_open_closeonexec_(filenames[i], O_RDONLY, 0);
                if (fd<0)
                        continue;
                n = read_all(fd, buf, sizeof(buf));
@@ -437,9 +438,9 @@ ARC4RANDOM_EXPORT int
 arc4random_stir(void)
 {
        int val;
-       _ARC4_LOCK();
+       ARC4_LOCK_();
        val = arc4_stir();
-       _ARC4_UNLOCK();
+       ARC4_UNLOCK_();
        return val;
 }
 #endif
@@ -449,7 +450,7 @@ ARC4RANDOM_EXPORT void
 arc4random_addrandom(const unsigned char *dat, int datlen)
 {
        int j;
-       _ARC4_LOCK();
+       ARC4_LOCK_();
        if (!rs_initialized)
                arc4_stir();
        for (j = 0; j < datlen; j += 256) {
@@ -459,7 +460,7 @@ arc4random_addrandom(const unsigned char *dat, int datlen)
                 * crazy like passing us all the files in /var/log. */
                arc4_addrandom(dat + j, datlen - j);
        }
-       _ARC4_UNLOCK();
+       ARC4_UNLOCK_();
 }
 #endif
 
@@ -468,27 +469,27 @@ ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
 arc4random(void)
 {
        ARC4RANDOM_UINT32 val;
-       _ARC4_LOCK();
+       ARC4_LOCK_();
        arc4_count -= 4;
        arc4_stir_if_needed();
        val = arc4_getword();
-       _ARC4_UNLOCK();
+       ARC4_UNLOCK_();
        return val;
 }
 #endif
 
 ARC4RANDOM_EXPORT void
-arc4random_buf(void *_buf, size_t n)
+arc4random_buf(void *buf_, size_t n)
 {
-       unsigned char *buf = _buf;
-       _ARC4_LOCK();
+       unsigned char *buf = buf_;
+       ARC4_LOCK_();
        arc4_stir_if_needed();
        while (n--) {
                if (--arc4_count <= 0)
                        arc4_stir();
                buf[n] = arc4_getbyte();
        }
-       _ARC4_UNLOCK();
+       ARC4_UNLOCK_();
 }
 
 #ifndef ARC4RANDOM_NOUNIFORM
index 7336c214f4be188217c7245c9a723a9cd5b2c515..b28c9361ba7b2fdd45840de4921029090ead0341 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include <io.h>
 #endif
 
-#ifdef _EVENT_HAVE_VASPRINTF
-/* If we have vasprintf, we need to define _GNU_SOURCE before we include 
+#ifdef EVENT__HAVE_VASPRINTF
+/* If we have vasprintf, we need to define _GNU_SOURCE before we include
  * stdio.h.  This comes from evconfig-private.h.
  */
 #endif
 
 #include <sys/types.h>
 
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 
-#ifdef _EVENT_HAVE_SYS_UIO_H
+#ifdef EVENT__HAVE_SYS_UIO_H
 #include <sys/uio.h>
 #endif
 
-#ifdef _EVENT_HAVE_SYS_IOCTL_H
+#ifdef EVENT__HAVE_SYS_IOCTL_H
 #include <sys/ioctl.h>
 #endif
 
-#ifdef _EVENT_HAVE_SYS_MMAN_H
+#ifdef EVENT__HAVE_SYS_MMAN_H
 #include <sys/mman.h>
 #endif
 
-#ifdef _EVENT_HAVE_SYS_SENDFILE_H
+#ifdef EVENT__HAVE_SYS_SENDFILE_H
 #include <sys/sendfile.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_STAT_H
+#ifdef EVENT__HAVE_SYS_STAT_H
 #include <sys/stat.h>
 #endif
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_STDARG_H
+#ifdef EVENT__HAVE_STDARG_H
 #include <stdarg.h>
 #endif
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #include <limits.h>
 #endif
 
 /* send file support */
-#if defined(_EVENT_HAVE_SYS_SENDFILE_H) && defined(_EVENT_HAVE_SENDFILE) && defined(__linux__)
+#if defined(EVENT__HAVE_SYS_SENDFILE_H) && defined(EVENT__HAVE_SENDFILE) && defined(__linux__)
 #define USE_SENDFILE           1
 #define SENDFILE_IS_LINUX      1
-#elif defined(_EVENT_HAVE_SENDFILE) && defined(__FreeBSD__)
+#elif defined(EVENT__HAVE_SENDFILE) && defined(__FreeBSD__)
 #define USE_SENDFILE           1
 #define SENDFILE_IS_FREEBSD    1
-#elif defined(_EVENT_HAVE_SENDFILE) && defined(__APPLE__)
+#elif defined(EVENT__HAVE_SENDFILE) && defined(__APPLE__)
 #define USE_SENDFILE           1
 #define SENDFILE_IS_MACOSX     1
-#elif defined(_EVENT_HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
+#elif defined(EVENT__HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
 #define USE_SENDFILE           1
 #define SENDFILE_IS_SOLARIS    1
 #endif
 /* evbuffer_ptr support */
 #define PTR_NOT_FOUND(ptr) do {                        \
        (ptr)->pos = -1;                                        \
-       (ptr)->_internal.chain = NULL;          \
-       (ptr)->_internal.pos_in_chain = 0;      \
+       (ptr)->internal_.chain = NULL;          \
+       (ptr)->internal_.pos_in_chain = 0;      \
 } while (0)
 
 static void evbuffer_chain_align(struct evbuffer_chain *chain);
@@ -149,6 +149,8 @@ static struct evbuffer_chain *evbuffer_expand_singlechain(struct evbuffer *buf,
     size_t datlen);
 static int evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
     size_t howfar);
+static int evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg);
+static inline void evbuffer_chain_incref(struct evbuffer_chain *chain);
 
 static struct evbuffer_chain *
 evbuffer_chain_new(size_t size)
@@ -176,17 +178,29 @@ evbuffer_chain_new(size_t size)
         */
        chain->buffer = EVBUFFER_CHAIN_EXTRA(u_char, chain);
 
+       chain->refcnt = 1;
+
        return (chain);
 }
 
 static inline void
 evbuffer_chain_free(struct evbuffer_chain *chain)
 {
+       EVUTIL_ASSERT(chain->refcnt > 0);
+       if (--chain->refcnt > 0) {
+               /* chain is still referenced by other chains */
+               return;
+       }
+
        if (CHAIN_PINNED(chain)) {
+               /* will get freed once no longer dangling */
+               chain->refcnt++;
                chain->flags |= EVBUFFER_DANGLING;
                return;
        }
 
+       /* safe to release chain, it's either a referencing
+        * chain or all references to it have been freed */
        if (chain->flags & EVBUFFER_REFERENCE) {
                struct evbuffer_chain_reference *info =
                    EVBUFFER_CHAIN_EXTRA(
@@ -204,12 +218,27 @@ evbuffer_chain_free(struct evbuffer_chain *chain)
                            chain);
                if (info->segment) {
 #ifdef _WIN32
-                       if (info->segment->type == EVBUF_FS_MMAP)
+                       if (info->segment->is_mapping)
                                UnmapViewOfFile(chain->buffer);
 #endif
                        evbuffer_file_segment_free(info->segment);
                }
        }
+       if (chain->flags & EVBUFFER_MULTICAST) {
+               struct evbuffer_multicast_parent *info =
+                   EVBUFFER_CHAIN_EXTRA(
+                           struct evbuffer_multicast_parent,
+                           chain);
+               /* referencing chain is being freed, decrease
+                * refcounts of source chain and associated
+                * evbuffer (which get freed once both reach
+                * zero) */
+               EVUTIL_ASSERT(info->source != NULL);
+               EVUTIL_ASSERT(info->parent != NULL);
+               EVBUFFER_LOCK(info->source);
+               evbuffer_chain_free(info->parent);
+               evbuffer_decref_and_unlock_(info->source);
+       }
 
        mm_free(chain);
 }
@@ -242,6 +271,31 @@ static inline int evbuffer_chains_all_empty(struct evbuffer_chain *chain) {
 }
 #endif
 
+/* Free all trailing chains in 'buf' that are neither pinned nor empty, prior
+ * to replacing them all with a new chain.  Return a pointer to the place
+ * where the new chain will go.
+ *
+ * Internal; requires lock.  The caller must fix up buf->last and buf->first
+ * as needed; they might have been freed.
+ */
+static struct evbuffer_chain **
+evbuffer_free_trailing_empty_chains(struct evbuffer *buf)
+{
+       struct evbuffer_chain **ch = buf->last_with_datap;
+       /* Find the first victim chain.  It might be *last_with_datap */
+       while ((*ch) && ((*ch)->off != 0 || CHAIN_PINNED(*ch)))
+               ch = &(*ch)->next;
+       if (*ch) {
+               EVUTIL_ASSERT(evbuffer_chains_all_empty(*ch));
+               evbuffer_free_all_chains(*ch);
+               *ch = NULL;
+       }
+       return ch;
+}
+
+/* Add a single chain 'chain' to the end of 'buf', freeing trailing empty
+ * chains as necessary.  Requires lock.  Does not schedule callbacks.
+ */
 static void
 evbuffer_chain_insert(struct evbuffer *buf,
     struct evbuffer_chain *chain)
@@ -253,21 +307,11 @@ evbuffer_chain_insert(struct evbuffer *buf,
                EVUTIL_ASSERT(buf->first == NULL);
                buf->first = buf->last = chain;
        } else {
-               struct evbuffer_chain **ch = buf->last_with_datap;
-               /* Find the first victim chain.  It might be *last_with_datap */
-               while ((*ch) && ((*ch)->off != 0 || CHAIN_PINNED(*ch)))
-                       ch = &(*ch)->next;
-               if (*ch == NULL) {
-                       /* There is no victim; just append this new chain. */
-                       buf->last->next = chain;
-                       if (chain->off)
-                               buf->last_with_datap = &buf->last->next;
-               } else {
-                       /* Replace all victim chains with this chain. */
-                       EVUTIL_ASSERT(evbuffer_chains_all_empty(*ch));
-                       evbuffer_free_all_chains(*ch);
-                       *ch = chain;
-               }
+               struct evbuffer_chain **chp;
+               chp = evbuffer_free_trailing_empty_chains(buf);
+               *chp = chain;
+               if (chain->off)
+                       buf->last_with_datap = chp;
                buf->last = chain;
        }
        buf->total_len += chain->off;
@@ -284,14 +328,14 @@ evbuffer_chain_insert_new(struct evbuffer *buf, size_t datlen)
 }
 
 void
-_evbuffer_chain_pin(struct evbuffer_chain *chain, unsigned flag)
+evbuffer_chain_pin_(struct evbuffer_chain *chain, unsigned flag)
 {
        EVUTIL_ASSERT((chain->flags & flag) == 0);
        chain->flags |= flag;
 }
 
 void
-_evbuffer_chain_unpin(struct evbuffer_chain *chain, unsigned flag)
+evbuffer_chain_unpin_(struct evbuffer_chain *chain, unsigned flag)
 {
        EVUTIL_ASSERT((chain->flags & flag) != 0);
        chain->flags &= ~flag;
@@ -299,6 +343,12 @@ _evbuffer_chain_unpin(struct evbuffer_chain *chain, unsigned flag)
                evbuffer_chain_free(chain);
 }
 
+static inline void
+evbuffer_chain_incref(struct evbuffer_chain *chain)
+{
+    ++chain->refcnt;
+}
+
 struct evbuffer *
 evbuffer_new(void)
 {
@@ -308,15 +358,33 @@ evbuffer_new(void)
        if (buffer == NULL)
                return (NULL);
 
-       TAILQ_INIT(&buffer->callbacks);
+       LIST_INIT(&buffer->callbacks);
        buffer->refcnt = 1;
        buffer->last_with_datap = &buffer->first;
 
        return (buffer);
 }
 
+int
+evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags)
+{
+       EVBUFFER_LOCK(buf);
+       buf->flags |= (ev_uint32_t)flags;
+       EVBUFFER_UNLOCK(buf);
+       return 0;
+}
+
+int
+evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags)
+{
+       EVBUFFER_LOCK(buf);
+       buf->flags &= ~(ev_uint32_t)flags;
+       EVBUFFER_UNLOCK(buf);
+       return 0;
+}
+
 void
-_evbuffer_incref(struct evbuffer *buf)
+evbuffer_incref_(struct evbuffer *buf)
 {
        EVBUFFER_LOCK(buf);
        ++buf->refcnt;
@@ -324,7 +392,7 @@ _evbuffer_incref(struct evbuffer *buf)
 }
 
 void
-_evbuffer_incref_and_lock(struct evbuffer *buf)
+evbuffer_incref_and_lock_(struct evbuffer *buf)
 {
        EVBUFFER_LOCK(buf);
        ++buf->refcnt;
@@ -334,9 +402,9 @@ int
 evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base)
 {
        EVBUFFER_LOCK(buffer);
-       buffer->cb_queue = event_base_get_deferred_cb_queue(base);
+       buffer->cb_queue = event_base_get_deferred_cb_queue_(base);
        buffer->deferred_cbs = 1;
-       event_deferred_cb_init(&buffer->deferred,
+       event_deferred_cb_init_(&buffer->deferred,
            evbuffer_deferred_callback, buffer);
        EVBUFFER_UNLOCK(buffer);
        return 0;
@@ -345,7 +413,7 @@ evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base)
 int
 evbuffer_enable_locking(struct evbuffer *buf, void *lock)
 {
-#ifdef _EVENT_DISABLE_THREAD_SUPPORT
+#ifdef EVENT__DISABLE_THREAD_SUPPORT
        return -1;
 #else
        if (buf->lock)
@@ -367,7 +435,7 @@ evbuffer_enable_locking(struct evbuffer *buf, void *lock)
 }
 
 void
-evbuffer_set_parent(struct evbuffer *buf, struct bufferevent *bev)
+evbuffer_set_parent_(struct evbuffer *buf, struct bufferevent *bev)
 {
        EVBUFFER_LOCK(buf);
        buf->parent = bev;
@@ -399,7 +467,7 @@ evbuffer_run_callbacks(struct evbuffer *buffer, int running_deferred)
 
        ASSERT_EVBUFFER_LOCKED(buffer);
 
-       if (TAILQ_EMPTY(&buffer->callbacks)) {
+       if (LIST_EMPTY(&buffer->callbacks)) {
                buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
                return;
        }
@@ -414,12 +482,12 @@ evbuffer_run_callbacks(struct evbuffer *buffer, int running_deferred)
                buffer->n_add_for_cb = 0;
                buffer->n_del_for_cb = 0;
        }
-       for (cbent = TAILQ_FIRST(&buffer->callbacks);
-            cbent != TAILQ_END(&buffer->callbacks);
+       for (cbent = LIST_FIRST(&buffer->callbacks);
+            cbent != LIST_END(&buffer->callbacks);
             cbent = next) {
                /* Get the 'next' pointer now in case this callback decides
                 * to remove itself or something. */
-               next = TAILQ_NEXT(cbent, next);
+               next = LIST_NEXT(cbent, next);
 
                if ((cbent->flags & mask) != masked_val)
                        continue;
@@ -433,9 +501,9 @@ evbuffer_run_callbacks(struct evbuffer *buffer, int running_deferred)
 }
 
 void
-evbuffer_invoke_callbacks(struct evbuffer *buffer)
+evbuffer_invoke_callbacks_(struct evbuffer *buffer)
 {
-       if (TAILQ_EMPTY(&buffer->callbacks)) {
+       if (LIST_EMPTY(&buffer->callbacks)) {
                buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
                return;
        }
@@ -443,11 +511,11 @@ evbuffer_invoke_callbacks(struct evbuffer *buffer)
        if (buffer->deferred_cbs) {
                if (buffer->deferred.queued)
                        return;
-               _evbuffer_incref_and_lock(buffer);
+               evbuffer_incref_and_lock_(buffer);
                if (buffer->parent)
-                       bufferevent_incref(buffer->parent);
+                       bufferevent_incref_(buffer->parent);
                EVBUFFER_UNLOCK(buffer);
-               event_deferred_cb_schedule(buffer->cb_queue, &buffer->deferred);
+               event_deferred_cb_schedule_(buffer->cb_queue, &buffer->deferred);
        }
 
        evbuffer_run_callbacks(buffer, 0);
@@ -464,9 +532,9 @@ evbuffer_deferred_callback(struct deferred_cb *cb, void *arg)
        EVBUFFER_LOCK(buffer);
        parent = buffer->parent;
        evbuffer_run_callbacks(buffer, 1);
-       _evbuffer_decref_and_unlock(buffer);
+       evbuffer_decref_and_unlock_(buffer);
        if (parent)
-               bufferevent_decref(parent);
+               bufferevent_decref_(parent);
 }
 
 static void
@@ -474,14 +542,14 @@ evbuffer_remove_all_callbacks(struct evbuffer *buffer)
 {
        struct evbuffer_cb_entry *cbent;
 
-       while ((cbent = TAILQ_FIRST(&buffer->callbacks))) {
-           TAILQ_REMOVE(&buffer->callbacks, cbent, next);
-           mm_free(cbent);
+       while ((cbent = LIST_FIRST(&buffer->callbacks))) {
+               LIST_REMOVE(cbent, next);
+               mm_free(cbent);
        }
 }
 
 void
-_evbuffer_decref_and_unlock(struct evbuffer *buffer)
+evbuffer_decref_and_unlock_(struct evbuffer *buffer)
 {
        struct evbuffer_chain *chain, *next;
        ASSERT_EVBUFFER_LOCKED(buffer);
@@ -499,7 +567,7 @@ _evbuffer_decref_and_unlock(struct evbuffer *buffer)
        }
        evbuffer_remove_all_callbacks(buffer);
        if (buffer->deferred_cbs)
-               event_deferred_cb_cancel(buffer->cb_queue, &buffer->deferred);
+               event_deferred_cb_cancel_(buffer->cb_queue, &buffer->deferred);
 
        EVBUFFER_UNLOCK(buffer);
        if (buffer->own_lock)
@@ -511,7 +579,7 @@ void
 evbuffer_free(struct evbuffer *buffer)
 {
        EVBUFFER_LOCK(buffer);
-       _evbuffer_decref_and_unlock(buffer);
+       evbuffer_decref_and_unlock_(buffer);
 }
 
 void
@@ -554,6 +622,42 @@ evbuffer_get_contiguous_space(const struct evbuffer *buf)
        return result;
 }
 
+size_t
+evbuffer_add_iovec(struct evbuffer * buf, struct evbuffer_iovec * vec, int n_vec) {
+       int n;
+       size_t res;
+       size_t to_alloc;
+
+       EVBUFFER_LOCK(buf);
+
+       res = to_alloc = 0;
+
+       for (n = 0; n < n_vec; n++) {
+               to_alloc += vec[n].iov_len;
+       }
+
+       if (evbuffer_expand_fast_(buf, to_alloc, 2) < 0) {
+               goto done;
+       }
+
+       for (n = 0; n < n_vec; n++) {
+               /* XXX each 'add' call here does a bunch of setup that's
+                * obviated by evbuffer_expand_fast_, and some cleanup that we
+                * would like to do only once.  Instead we should just extract
+                * the part of the code that's needed. */
+
+               if (evbuffer_add(buf, vec[n].iov_base, vec[n].iov_len) < 0) {
+                       goto done;
+               }
+
+               res += vec[n].iov_len;
+       }
+
+done:
+    EVBUFFER_UNLOCK(buf);
+    return res;
+}
+
 int
 evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
     struct evbuffer_iovec *vec, int n_vecs)
@@ -575,9 +679,9 @@ evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
                EVUTIL_ASSERT(size<0 || (size_t)vec[0].iov_len >= (size_t)size);
                n = 1;
        } else {
-               if (_evbuffer_expand_fast(buf, size, n_vecs)<0)
+               if (evbuffer_expand_fast_(buf, size, n_vecs)<0)
                        goto done;
-               n = _evbuffer_read_setup_vecs(buf, size, vec, n_vecs,
+               n = evbuffer_read_setup_vecs_(buf, size, vec, n_vecs,
                                &chainp, 0);
        }
 
@@ -666,7 +770,7 @@ okay:
        buf->total_len += added;
        buf->n_add_for_cb += added;
        result = 0;
-       evbuffer_invoke_callbacks(buf);
+       evbuffer_invoke_callbacks_(buf);
 
 done:
        EVBUFFER_UNLOCK(buf);
@@ -782,6 +886,46 @@ APPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
        dst->total_len += src->total_len;
 }
 
+static inline void
+APPEND_CHAIN_MULTICAST(struct evbuffer *dst, struct evbuffer *src)
+{
+       struct evbuffer_chain *tmp;
+       struct evbuffer_chain *chain = src->first;
+       struct evbuffer_multicast_parent *extra;
+
+       ASSERT_EVBUFFER_LOCKED(dst);
+       ASSERT_EVBUFFER_LOCKED(src);
+
+       for (; chain; chain = chain->next) {
+               if (!chain->off || chain->flags & EVBUFFER_DANGLING) {
+                       /* skip empty chains */
+                       continue;
+               }
+
+               tmp = evbuffer_chain_new(sizeof(struct evbuffer_multicast_parent));
+               if (!tmp) {
+                       event_warn("%s: out of memory", __func__);
+                       return;
+               }
+               extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_multicast_parent, tmp);
+               /* reference evbuffer containing source chain so it
+                * doesn't get released while the chain is still
+                * being referenced to */
+               evbuffer_incref_(src);
+               extra->source = src;
+               /* reference source chain which now becomes immutable */
+               evbuffer_chain_incref(chain);
+               extra->parent = chain;
+               chain->flags |= EVBUFFER_IMMUTABLE;
+               tmp->buffer_len = chain->buffer_len;
+               tmp->misalign = chain->misalign;
+               tmp->off = chain->off;
+               tmp->flags |= EVBUFFER_MULTICAST|EVBUFFER_IMMUTABLE;
+               tmp->buffer = chain->buffer;
+               evbuffer_chain_insert(dst, tmp);
+       }
+}
+
 static void
 PREPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
 {
@@ -838,8 +982,51 @@ evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
        inbuf->n_del_for_cb += in_total_len;
        outbuf->n_add_for_cb += in_total_len;
 
-       evbuffer_invoke_callbacks(inbuf);
-       evbuffer_invoke_callbacks(outbuf);
+       evbuffer_invoke_callbacks_(inbuf);
+       evbuffer_invoke_callbacks_(outbuf);
+
+done:
+       EVBUFFER_UNLOCK2(inbuf, outbuf);
+       return result;
+}
+
+int
+evbuffer_add_buffer_reference(struct evbuffer *outbuf, struct evbuffer *inbuf)
+{
+       size_t in_total_len, out_total_len;
+       struct evbuffer_chain *chain;
+       int result = 0;
+
+       EVBUFFER_LOCK2(inbuf, outbuf);
+       in_total_len = inbuf->total_len;
+       out_total_len = outbuf->total_len;
+       chain = inbuf->first;
+
+       if (in_total_len == 0)
+               goto done;
+
+       if (outbuf->freeze_end || outbuf == inbuf) {
+               result = -1;
+               goto done;
+       }
+
+       for (; chain; chain = chain->next) {
+               if ((chain->flags & (EVBUFFER_FILESEGMENT|EVBUFFER_SENDFILE|EVBUFFER_MULTICAST)) != 0) {
+                       /* chain type can not be referenced */
+                       result = -1;
+                       goto done;
+               }
+       }
+
+       if (out_total_len == 0) {
+               /* There might be an empty chain at the start of outbuf; free
+                * it. */
+               evbuffer_free_all_chains(outbuf->first);
+       }
+       APPEND_CHAIN_MULTICAST(outbuf, inbuf);
+
+       outbuf->n_add_for_cb += in_total_len;
+       evbuffer_invoke_callbacks_(outbuf);
 
 done:
        EVBUFFER_UNLOCK2(inbuf, outbuf);
@@ -885,8 +1072,8 @@ evbuffer_prepend_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
        inbuf->n_del_for_cb += in_total_len;
        outbuf->n_add_for_cb += in_total_len;
 
-       evbuffer_invoke_callbacks(inbuf);
-       evbuffer_invoke_callbacks(outbuf);
+       evbuffer_invoke_callbacks_(inbuf);
+       evbuffer_invoke_callbacks_(outbuf);
 done:
        EVBUFFER_UNLOCK2(inbuf, outbuf);
        return result;
@@ -952,7 +1139,7 @@ evbuffer_drain(struct evbuffer *buf, size_t len)
 
        buf->n_del_for_cb += len;
        /* Tell someone about changes in this buffer */
-       evbuffer_invoke_callbacks(buf);
+       evbuffer_invoke_callbacks_(buf);
 
 done:
        EVBUFFER_UNLOCK(buf);
@@ -965,7 +1152,7 @@ evbuffer_remove(struct evbuffer *buf, void *data_out, size_t datlen)
 {
        ev_ssize_t n;
        EVBUFFER_LOCK(buf);
-       n = evbuffer_copyout(buf, data_out, datlen);
+       n = evbuffer_copyout_from(buf, NULL, data_out, datlen);
        if (n > 0) {
                if (evbuffer_drain(buf, n)<0)
                        n = -1;
@@ -976,19 +1163,35 @@ evbuffer_remove(struct evbuffer *buf, void *data_out, size_t datlen)
 
 ev_ssize_t
 evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen)
+{
+       return evbuffer_copyout_from(buf, NULL, data_out, datlen);
+}
+
+ev_ssize_t
+evbuffer_copyout_from(struct evbuffer *buf, const struct evbuffer_ptr *pos,
+    void *data_out, size_t datlen)
 {
        /*XXX fails badly on sendfile case. */
        struct evbuffer_chain *chain;
        char *data = data_out;
        size_t nread;
        ev_ssize_t result = 0;
+       size_t pos_in_chain;
 
        EVBUFFER_LOCK(buf);
 
-       chain = buf->first;
+       if (pos) {
+               chain = pos->internal_.chain;
+               pos_in_chain = pos->internal_.pos_in_chain;
+               if (datlen + pos->pos > buf->total_len)
+                       datlen = buf->total_len - pos->pos;
+       } else {
+               chain = buf->first;
+               pos_in_chain = 0;
+               if (datlen > buf->total_len)
+                       datlen = buf->total_len;
+       }
 
-       if (datlen >= buf->total_len)
-               datlen = buf->total_len;
 
        if (datlen == 0)
                goto done;
@@ -1000,18 +1203,23 @@ evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen)
 
        nread = datlen;
 
-       while (datlen && datlen >= chain->off) {
-               memcpy(data, chain->buffer + chain->misalign, chain->off);
-               data += chain->off;
-               datlen -= chain->off;
+       while (datlen && datlen >= chain->off - pos_in_chain) {
+               size_t copylen = chain->off - pos_in_chain;
+               memcpy(data,
+                   chain->buffer + chain->misalign + pos_in_chain,
+                   copylen);
+               data += copylen;
+               datlen -= copylen;
 
                chain = chain->next;
+               pos_in_chain = 0;
                EVUTIL_ASSERT(chain || datlen==0);
        }
 
        if (datlen) {
                EVUTIL_ASSERT(chain);
-               memcpy(data, chain->buffer + chain->misalign, datlen);
+               memcpy(data, chain->buffer + chain->misalign + pos_in_chain,
+                   datlen);
        }
 
        result = nread;
@@ -1072,10 +1280,13 @@ evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
 
        if (nread) {
                /* we can remove the chain */
+               struct evbuffer_chain **chp;
+               chp = evbuffer_free_trailing_empty_chains(dst);
+
                if (dst->first == NULL) {
                        dst->first = src->first;
                } else {
-                       dst->last->next = src->first;
+                       *chp = src->first;
                }
                dst->last = previous;
                previous->next = NULL;
@@ -1093,12 +1304,15 @@ evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
        chain->off -= datlen;
        nread += datlen;
 
+       /* You might think we would want to increment dst->n_add_for_cb
+        * here too.  But evbuffer_add above already took care of that.
+        */
        src->total_len -= nread;
        src->n_del_for_cb += nread;
 
        if (nread) {
-               evbuffer_invoke_callbacks(dst);
-               evbuffer_invoke_callbacks(src);
+               evbuffer_invoke_callbacks_(dst);
+               evbuffer_invoke_callbacks_(src);
        }
        result = (int)nread;/*XXXX should change return type */
 
@@ -1232,14 +1446,14 @@ evbuffer_readline(struct evbuffer *buffer)
 static inline ev_ssize_t
 evbuffer_strchr(struct evbuffer_ptr *it, const char chr)
 {
-       struct evbuffer_chain *chain = it->_internal.chain;
-       size_t i = it->_internal.pos_in_chain;
+       struct evbuffer_chain *chain = it->internal_.chain;
+       size_t i = it->internal_.pos_in_chain;
        while (chain != NULL) {
                char *buffer = (char *)chain->buffer + chain->misalign;
                char *cp = memchr(buffer+i, chr, chain->off-i);
                if (cp) {
-                       it->_internal.chain = chain;
-                       it->_internal.pos_in_chain = cp - buffer;
+                       it->internal_.chain = chain;
+                       it->internal_.pos_in_chain = cp - buffer;
                        it->pos += (cp - buffer - i);
                        return it->pos;
                }
@@ -1281,14 +1495,14 @@ find_eol_char(char *s, size_t len)
 static ev_ssize_t
 evbuffer_find_eol_char(struct evbuffer_ptr *it)
 {
-       struct evbuffer_chain *chain = it->_internal.chain;
-       size_t i = it->_internal.pos_in_chain;
+       struct evbuffer_chain *chain = it->internal_.chain;
+       size_t i = it->internal_.pos_in_chain;
        while (chain != NULL) {
                char *buffer = (char *)chain->buffer + chain->misalign;
                char *cp = find_eol_char(buffer+i, chain->off-i);
                if (cp) {
-                       it->_internal.chain = chain;
-                       it->_internal.pos_in_chain = cp - buffer;
+                       it->internal_.chain = chain;
+                       it->internal_.pos_in_chain = cp - buffer;
                        it->pos += (cp - buffer) - i;
                        return it->pos;
                }
@@ -1305,8 +1519,8 @@ evbuffer_strspn(
        struct evbuffer_ptr *ptr, const char *chrset)
 {
        int count = 0;
-       struct evbuffer_chain *chain = ptr->_internal.chain;
-       size_t i = ptr->_internal.pos_in_chain;
+       struct evbuffer_chain *chain = ptr->internal_.chain;
+       size_t i = ptr->internal_.pos_in_chain;
 
        if (!chain)
                return 0;
@@ -1319,8 +1533,8 @@ evbuffer_strspn(
                                if (buffer[i] == *p++)
                                        goto next;
                        }
-                       ptr->_internal.chain = chain;
-                       ptr->_internal.pos_in_chain = i;
+                       ptr->internal_.chain = chain;
+                       ptr->internal_.pos_in_chain = i;
                        ptr->pos += count;
                        return count;
                next:
@@ -1329,8 +1543,8 @@ evbuffer_strspn(
                i = 0;
 
                if (! chain->next) {
-                       ptr->_internal.chain = chain;
-                       ptr->_internal.pos_in_chain = i;
+                       ptr->internal_.chain = chain;
+                       ptr->internal_.pos_in_chain = i;
                        ptr->pos += count;
                        return count;
                }
@@ -1343,8 +1557,8 @@ evbuffer_strspn(
 static inline int
 evbuffer_getchr(struct evbuffer_ptr *it)
 {
-       struct evbuffer_chain *chain = it->_internal.chain;
-       size_t off = it->_internal.pos_in_chain;
+       struct evbuffer_chain *chain = it->internal_.chain;
+       size_t off = it->internal_.pos_in_chain;
 
        if (chain == NULL)
                return -1;
@@ -1362,7 +1576,7 @@ evbuffer_search_eol(struct evbuffer *buffer,
        int ok = 0;
 
        /* Avoid locking in trivial edge cases */
-       if (start && start->_internal.chain == NULL) {
+       if (start && start->internal_.chain == NULL) {
                PTR_NOT_FOUND(&it);
                if (eol_len_out)
                        *eol_len_out = extra_drain;
@@ -1375,8 +1589,8 @@ evbuffer_search_eol(struct evbuffer *buffer,
                memcpy(&it, start, sizeof(it));
        } else {
                it.pos = 0;
-               it._internal.chain = buffer->first;
-               it._internal.pos_in_chain = 0;
+               it.internal_.chain = buffer->first;
+               it.internal_.pos_in_chain = 0;
        }
 
        /* the eol_style determines our first stop character and how many
@@ -1421,6 +1635,11 @@ evbuffer_search_eol(struct evbuffer *buffer,
                        goto done;
                extra_drain = 1;
                break;
+       case EVBUFFER_EOL_NUL:
+               if (evbuffer_strchr(&it, '\0') < 0)
+                       goto done;
+               extra_drain = 1;
+               break;
        default:
                goto done;
        }
@@ -1556,9 +1775,10 @@ evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)
        memcpy(tmp->buffer, data, datlen);
        tmp->off = datlen;
        evbuffer_chain_insert(buf, tmp);
+       buf->n_add_for_cb += datlen;
 
 out:
-       evbuffer_invoke_callbacks(buf);
+       evbuffer_invoke_callbacks_(buf);
        result = 0;
 done:
        EVBUFFER_UNLOCK(buf);
@@ -1632,7 +1852,7 @@ evbuffer_prepend(struct evbuffer *buf, const void *data, size_t datlen)
        buf->n_add_for_cb += (size_t)chain->misalign;
 
 out:
-       evbuffer_invoke_callbacks(buf);
+       evbuffer_invoke_callbacks_(buf);
        result = 0;
 done:
        EVBUFFER_UNLOCK(buf);
@@ -1777,7 +1997,7 @@ err:
 /* Make sure that datlen bytes are available for writing in the last n
  * chains.  Never copies or moves data. */
 int
-_evbuffer_expand_fast(struct evbuffer *buf, size_t datlen, int n)
+evbuffer_expand_fast_(struct evbuffer *buf, size_t datlen, int n)
 {
        struct evbuffer_chain *chain = buf->last, *tmp, *next;
        size_t avail;
@@ -1898,13 +2118,13 @@ evbuffer_expand(struct evbuffer *buf, size_t datlen)
  * Reads data from a file descriptor into a buffer.
  */
 
-#if defined(_EVENT_HAVE_SYS_UIO_H) || defined(_WIN32)
+#if defined(EVENT__HAVE_SYS_UIO_H) || defined(_WIN32)
 #define USE_IOVEC_IMPL
 #endif
 
 #ifdef USE_IOVEC_IMPL
 
-#ifdef _EVENT_HAVE_SYS_UIO_H
+#ifdef EVENT__HAVE_SYS_UIO_H
 /* number of iovec we use for writev, fragmentation is going to determine
  * how much we end up writing */
 
@@ -1948,7 +2168,7 @@ evbuffer_expand(struct evbuffer *buf, size_t datlen)
     @return The number of buffers we're using.
  */
 int
-_evbuffer_read_setup_vecs(struct evbuffer *buf, ev_ssize_t howmuch,
+evbuffer_read_setup_vecs_(struct evbuffer *buf, ev_ssize_t howmuch,
     struct evbuffer_iovec *vecs, int n_vecs_avail,
     struct evbuffer_chain ***chainp, int exact)
 {
@@ -2033,19 +2253,19 @@ evbuffer_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch)
 #ifdef USE_IOVEC_IMPL
        /* Since we can use iovecs, we're willing to use the last
         * NUM_READ_IOVEC chains. */
-       if (_evbuffer_expand_fast(buf, howmuch, NUM_READ_IOVEC) == -1) {
+       if (evbuffer_expand_fast_(buf, howmuch, NUM_READ_IOVEC) == -1) {
                result = -1;
                goto done;
        } else {
                IOV_TYPE vecs[NUM_READ_IOVEC];
-#ifdef _EVBUFFER_IOVEC_IS_NATIVE
-               nvecs = _evbuffer_read_setup_vecs(buf, howmuch, vecs,
+#ifdef EVBUFFER_IOVEC_IS_NATIVE_
+               nvecs = evbuffer_read_setup_vecs_(buf, howmuch, vecs,
                    NUM_READ_IOVEC, &chainp, 1);
 #else
                /* We aren't using the native struct iovec.  Therefore,
                   we are on win32. */
                struct evbuffer_iovec ev_vecs[NUM_READ_IOVEC];
-               nvecs = _evbuffer_read_setup_vecs(buf, howmuch, ev_vecs, 2,
+               nvecs = evbuffer_read_setup_vecs_(buf, howmuch, ev_vecs, 2,
                    &chainp, 1);
 
                for (i=0; i < nvecs; ++i)
@@ -2121,7 +2341,7 @@ evbuffer_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch)
        buf->n_add_for_cb += n;
 
        /* Tell someone about changes in this buffer */
-       evbuffer_invoke_callbacks(buf);
+       evbuffer_invoke_callbacks_(buf);
        result = n;
 done:
        EVBUFFER_UNLOCK(buf);
@@ -2317,8 +2537,8 @@ evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
 {
        if (howfar > (size_t)pos->pos)
                return -1;
-       if (pos->_internal.chain && howfar <= pos->_internal.pos_in_chain) {
-               pos->_internal.pos_in_chain -= howfar;
+       if (pos->internal_.chain && howfar <= pos->internal_.pos_in_chain) {
+               pos->internal_.pos_in_chain -= howfar;
                pos->pos -= howfar;
                return 0;
        } else {
@@ -2348,9 +2568,9 @@ evbuffer_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos,
        case EVBUFFER_PTR_ADD:
                /* this avoids iterating over all previous chains if
                   we just want to advance the position */
-               chain = pos->_internal.chain;
+               chain = pos->internal_.chain;
                pos->pos += position;
-               position = pos->_internal.pos_in_chain;
+               position = pos->internal_.pos_in_chain;
                break;
        }
 
@@ -2360,12 +2580,12 @@ evbuffer_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos,
                position = 0;
        }
        if (chain) {
-               pos->_internal.chain = chain;
-               pos->_internal.pos_in_chain = position + left;
+               pos->internal_.chain = chain;
+               pos->internal_.pos_in_chain = position + left;
        } else if (left == 0) {
                /* The first byte in the (nonexistent) chain after the last chain */
-               pos->_internal.chain = NULL;
-               pos->_internal.pos_in_chain = 0;
+               pos->internal_.chain = NULL;
+               pos->internal_.pos_in_chain = 0;
        } else {
                PTR_NOT_FOUND(pos);
                result = -1;
@@ -2393,8 +2613,8 @@ evbuffer_ptr_memcmp(const struct evbuffer *buf, const struct evbuffer_ptr *pos,
        if (pos->pos + len > buf->total_len)
                return -1;
 
-       chain = pos->_internal.chain;
-       position = pos->_internal.pos_in_chain;
+       chain = pos->internal_.chain;
+       position = pos->internal_.pos_in_chain;
        while (len && chain) {
                size_t n_comparable;
                if (len + position > chain->off)
@@ -2432,15 +2652,15 @@ evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, con
 
        if (start) {
                memcpy(&pos, start, sizeof(pos));
-               chain = pos._internal.chain;
+               chain = pos.internal_.chain;
        } else {
                pos.pos = 0;
-               chain = pos._internal.chain = buffer->first;
-               pos._internal.pos_in_chain = 0;
+               chain = pos.internal_.chain = buffer->first;
+               pos.internal_.pos_in_chain = 0;
        }
 
        if (end)
-               last_chain = end->_internal.chain;
+               last_chain = end->internal_.chain;
 
        if (!len || len > EV_SSIZE_MAX)
                goto done;
@@ -2450,12 +2670,12 @@ evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, con
        while (chain) {
                const unsigned char *start_at =
                    chain->buffer + chain->misalign +
-                   pos._internal.pos_in_chain;
+                   pos.internal_.pos_in_chain;
                p = memchr(start_at, first,
-                   chain->off - pos._internal.pos_in_chain);
+                   chain->off - pos.internal_.pos_in_chain);
                if (p) {
                        pos.pos += p - start_at;
-                       pos._internal.pos_in_chain += p - start_at;
+                       pos.internal_.pos_in_chain += p - start_at;
                        if (!evbuffer_ptr_memcmp(buffer, &pos, what, len)) {
                                if (end && pos.pos + (ev_ssize_t)len > end->pos)
                                        goto not_found;
@@ -2463,17 +2683,17 @@ evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, con
                                        goto done;
                        }
                        ++pos.pos;
-                       ++pos._internal.pos_in_chain;
-                       if (pos._internal.pos_in_chain == chain->off) {
-                               chain = pos._internal.chain = chain->next;
-                               pos._internal.pos_in_chain = 0;
+                       ++pos.internal_.pos_in_chain;
+                       if (pos.internal_.pos_in_chain == chain->off) {
+                               chain = pos.internal_.chain = chain->next;
+                               pos.internal_.pos_in_chain = 0;
                        }
                } else {
                        if (chain == last_chain)
                                goto not_found;
-                       pos.pos += chain->off - pos._internal.pos_in_chain;
-                       chain = pos._internal.chain = chain->next;
-                       pos._internal.pos_in_chain = 0;
+                       pos.pos += chain->off - pos.internal_.pos_in_chain;
+                       chain = pos.internal_.chain = chain->next;
+                       pos.internal_.pos_in_chain = 0;
                }
        }
 
@@ -2494,19 +2714,19 @@ evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
        ev_ssize_t len_so_far = 0;
 
        /* Avoid locking in trivial edge cases */
-       if (start_at && start_at->_internal.chain == NULL)
+       if (start_at && start_at->internal_.chain == NULL)
                return 0;
 
        EVBUFFER_LOCK(buffer);
 
        if (start_at) {
-               chain = start_at->_internal.chain;
+               chain = start_at->internal_.chain;
                len_so_far = chain->off
-                   - start_at->_internal.pos_in_chain;
+                   - start_at->internal_.pos_in_chain;
                idx = 1;
                if (n_vec > 0) {
                        vec[0].iov_base = chain->buffer + chain->misalign
-                           + start_at->_internal.pos_in_chain;
+                           + start_at->internal_.pos_in_chain;
                        vec[0].iov_len = len_so_far;
                }
                chain = chain->next;
@@ -2514,14 +2734,21 @@ evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
                chain = buffer->first;
        }
 
+       if (n_vec == 0 && len < 0) {
+               /* If no vectors are provided and they asked for "everything",
+                * pretend they asked for the actual available amount. */
+               len = buffer->total_len - len_so_far;
+       }
+
        while (chain) {
                if (len >= 0 && len_so_far >= len)
                        break;
                if (idx<n_vec) {
                        vec[idx].iov_base = chain->buffer + chain->misalign;
                        vec[idx].iov_len = chain->off;
-               } else if (len<0)
+               } else if (len<0) {
                        break;
+               }
                ++idx;
                len_so_far += chain->off;
                chain = chain->next;
@@ -2580,7 +2807,7 @@ evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
                        buf->n_add_for_cb += sz;
 
                        advance_last_with_data(buf);
-                       evbuffer_invoke_callbacks(buf);
+                       evbuffer_invoke_callbacks_(buf);
                        result = sz;
                        goto done;
                }
@@ -2638,7 +2865,7 @@ evbuffer_add_reference(struct evbuffer *outbuf,
        evbuffer_chain_insert(outbuf, chain);
        outbuf->n_add_for_cb += datlen;
 
-       evbuffer_invoke_callbacks(outbuf);
+       evbuffer_invoke_callbacks_(outbuf);
 
        result = 0;
 done:
@@ -2661,6 +2888,7 @@ evbuffer_file_segment_new(
        seg->refcnt = 1;
        seg->fd = fd;
        seg->flags = flags;
+       seg->file_offset = offset;
 
 #ifdef _WIN32
 #define lseek _lseeki64
@@ -2677,12 +2905,40 @@ evbuffer_file_segment_new(
 
 #if defined(USE_SENDFILE)
        if (!(flags & EVBUF_FS_DISABLE_SENDFILE)) {
-               seg->offset = offset;
-               seg->type = EVBUF_FS_SENDFILE;
+               seg->can_sendfile = 1;
                goto done;
        }
 #endif
-#if defined(_EVENT_HAVE_MMAP)
+
+       if (evbuffer_file_segment_materialize(seg)<0)
+               goto err;
+
+#if defined(USE_SENDFILE)
+done:
+#endif
+       if (!(flags & EVBUF_FS_DISABLE_LOCKING)) {
+               EVTHREAD_ALLOC_LOCK(seg->lock, 0);
+       }
+       return seg;
+err:
+       mm_free(seg);
+       return NULL;
+}
+
+/* DOCDOC */
+/* Requires lock */
+static int
+evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg)
+{
+       const unsigned flags = seg->flags;
+       const int fd = seg->fd;
+       const ev_off_t length = seg->length;
+       const ev_off_t offset = seg->file_offset;
+
+       if (seg->contents)
+               return 0; /* already materialized */
+
+#if defined(EVENT__HAVE_MMAP)
        if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
                off_t offset_rounded = 0, offset_leftover = 0;
                void *mapped;
@@ -2717,8 +2973,8 @@ evbuffer_file_segment_new(
                } else {
                        seg->mapping = mapped;
                        seg->contents = (char*)mapped+offset_leftover;
-                       seg->offset = 0;
-                       seg->type = EVBUF_FS_MMAP;
+                       seg->mmap_offset = 0;
+                       seg->is_mapping = 1;
                        goto done;
                }
        }
@@ -2729,19 +2985,18 @@ evbuffer_file_segment_new(
                HANDLE m;
                ev_uint64_t total_size = length+offset;
                if (h == (long)INVALID_HANDLE_VALUE)
-                       return NULL;
+                       goto err;
                m = CreateFileMapping((HANDLE)h, NULL, PAGE_READONLY,
                    (total_size >> 32), total_size & 0xfffffffful,
                    NULL);
                if (m != INVALID_HANDLE_VALUE) { /* Does h leak? */
                        seg->mapping_handle = m;
-                       seg->offset = offset;
-                       seg->type = EVBUF_FS_MMAP;
+                       seg->mmap_offset = offset;
+                       seg->is_mapping = 1;
                        goto done;
                }
        }
 #endif
-
        {
                ev_off_t start_pos = lseek(fd, 0, SEEK_CUR), pos;
                ev_off_t read_so_far = 0;
@@ -2777,17 +3032,12 @@ evbuffer_file_segment_new(
                }
 
                seg->contents = mem;
-               seg->type = EVBUF_FS_IO;
        }
 
 done:
-       if (!(flags & EVBUF_FS_DISABLE_LOCKING)) {
-               EVTHREAD_ALLOC_LOCK(seg->lock, 0);
-       }
-       return seg;
+       return 0;
 err:
-       mm_free(seg);
-       return NULL;
+       return -1;
 }
 
 void
@@ -2801,17 +3051,14 @@ evbuffer_file_segment_free(struct evbuffer_file_segment *seg)
                return;
        EVUTIL_ASSERT(refcnt == 0);
 
-       if (seg->type == EVBUF_FS_SENDFILE) {
-               ;
-       } else if (seg->type == EVBUF_FS_MMAP) {
+       if (seg->is_mapping) {
 #ifdef _WIN32
                CloseHandle(seg->mapping_handle);
-#elif defined (_EVENT_HAVE_MMAP)
+#elif defined (EVENT__HAVE_MMAP)
                if (munmap(seg->mapping, seg->length) == -1)
                        event_warn("%s: munmap failed", __func__);
 #endif
-       } else {
-               EVUTIL_ASSERT(seg->type == EVBUF_FS_IO);
+       } else if (seg->contents) {
                mm_free(seg->contents);
        }
 
@@ -2829,13 +3076,24 @@ evbuffer_add_file_segment(struct evbuffer *buf,
 {
        struct evbuffer_chain *chain;
        struct evbuffer_chain_file_segment *extra;
+       int can_use_sendfile = 0;
 
+       EVBUFFER_LOCK(buf);
        EVLOCK_LOCK(seg->lock, 0);
+       if (buf->flags & EVBUFFER_FLAG_DRAINS_TO_FD) {
+               can_use_sendfile = 1;
+       } else {
+               if (!seg->contents) {
+                       if (evbuffer_file_segment_materialize(seg)<0) {
+                               EVLOCK_UNLOCK(seg->lock, 0);
+                               EVBUFFER_UNLOCK(buf);
+                               return -1;
+                       }
+               }
+       }
        ++seg->refcnt;
        EVLOCK_UNLOCK(seg->lock, 0);
 
-       EVBUFFER_LOCK(buf);
-
        if (buf->freeze_end)
                goto err;
 
@@ -2855,14 +3113,14 @@ evbuffer_add_file_segment(struct evbuffer *buf,
        extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment, chain);
 
        chain->flags |= EVBUFFER_IMMUTABLE|EVBUFFER_FILESEGMENT;
-       if (seg->type == EVBUF_FS_SENDFILE) {
+       if (can_use_sendfile && seg->can_sendfile) {
                chain->flags |= EVBUFFER_SENDFILE;
-               chain->misalign = seg->offset + offset;
+               chain->misalign = seg->file_offset + offset;
                chain->off = length;
                chain->buffer_len = chain->misalign + length;
-       } else if (seg->type == EVBUF_FS_MMAP) {
+       } else if (seg->is_mapping) {
 #ifdef _WIN32
-               ev_uint64_t total_offset = seg->offset+offset;
+               ev_uint64_t total_offset = seg->mmap_offset+offset;
                ev_uint64_t offset_rounded=0, offset_remaining=0;
                LPVOID data;
                if (total_offset) {
@@ -2892,7 +3150,6 @@ evbuffer_add_file_segment(struct evbuffer *buf,
                chain->off = length;
 #endif
        } else {
-               EVUTIL_ASSERT(seg->type == EVBUF_FS_IO);
                chain->buffer = (unsigned char*)(seg->contents + offset);
                chain->buffer_len = length;
                chain->off = length;
@@ -2902,7 +3159,7 @@ evbuffer_add_file_segment(struct evbuffer *buf,
        buf->n_add_for_cb += length;
        evbuffer_chain_insert(buf, chain);
 
-       evbuffer_invoke_callbacks(buf);
+       evbuffer_invoke_callbacks_(buf);
 
        EVBUFFER_UNLOCK(buf);
 
@@ -2933,7 +3190,7 @@ evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg)
 {
        EVBUFFER_LOCK(buffer);
 
-       if (!TAILQ_EMPTY(&buffer->callbacks))
+       if (!LIST_EMPTY(&buffer->callbacks))
                evbuffer_remove_all_callbacks(buffer);
 
        if (cb) {
@@ -2955,7 +3212,7 @@ evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
        e->cb.cb_func = cb;
        e->cbarg = cbarg;
        e->flags = EVBUFFER_CB_ENABLED;
-       TAILQ_INSERT_HEAD(&buffer->callbacks, e, next);
+       LIST_INSERT_HEAD(&buffer->callbacks, e, next);
        EVBUFFER_UNLOCK(buffer);
        return e;
 }
@@ -2965,7 +3222,7 @@ evbuffer_remove_cb_entry(struct evbuffer *buffer,
                         struct evbuffer_cb_entry *ent)
 {
        EVBUFFER_LOCK(buffer);
-       TAILQ_REMOVE(&buffer->callbacks, ent, next);
+       LIST_REMOVE(ent, next);
        EVBUFFER_UNLOCK(buffer);
        mm_free(ent);
        return 0;
@@ -2977,7 +3234,7 @@ evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
        struct evbuffer_cb_entry *cbent;
        int result = -1;
        EVBUFFER_LOCK(buffer);
-       TAILQ_FOREACH(cbent, &buffer->callbacks, next) {
+       LIST_FOREACH(cbent, &buffer->callbacks, next) {
                if (cb == cbent->cb.cb_func && cbarg == cbent->cbarg) {
                        result = evbuffer_remove_cb_entry(buffer, cbent);
                        goto done;
index a917c01f27fd57a9b4fbaa33e9a734ec7e3309ab..2d76a90e7702c5ba69ab8e631ba4eb9c25e77b7d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -88,13 +88,13 @@ pin_release(struct evbuffer_overlapped *eo, unsigned flag)
        for (i = 0; i < eo->n_buffers; ++i) {
                EVUTIL_ASSERT(chain);
                next = chain->next;
-               _evbuffer_chain_unpin(chain, flag);
+               evbuffer_chain_unpin_(chain, flag);
                chain = next;
        }
 }
 
 void
-evbuffer_commit_read(struct evbuffer *evbuf, ev_ssize_t nBytes)
+evbuffer_commit_read_(struct evbuffer *evbuf, ev_ssize_t nBytes)
 {
        struct evbuffer_overlapped *buf = upcast_evbuffer(evbuf);
        struct evbuffer_chain **chainp;
@@ -129,13 +129,13 @@ evbuffer_commit_read(struct evbuffer *evbuf, ev_ssize_t nBytes)
        evbuf->total_len += nBytes;
        evbuf->n_add_for_cb += nBytes;
 
-       evbuffer_invoke_callbacks(evbuf);
+       evbuffer_invoke_callbacks_(evbuf);
 
-       _evbuffer_decref_and_unlock(evbuf);
+       evbuffer_decref_and_unlock_(evbuf);
 }
 
 void
-evbuffer_commit_write(struct evbuffer *evbuf, ev_ssize_t nBytes)
+evbuffer_commit_write_(struct evbuffer *evbuf, ev_ssize_t nBytes)
 {
        struct evbuffer_overlapped *buf = upcast_evbuffer(evbuf);
 
@@ -145,11 +145,11 @@ evbuffer_commit_write(struct evbuffer *evbuf, ev_ssize_t nBytes)
        evbuffer_drain(evbuf, nBytes);
        pin_release(buf,EVBUFFER_MEM_PINNED_W);
        buf->write_in_progress = 0;
-       _evbuffer_decref_and_unlock(evbuf);
+       evbuffer_decref_and_unlock_(evbuf);
 }
 
 struct evbuffer *
-evbuffer_overlapped_new(evutil_socket_t fd)
+evbuffer_overlapped_new_(evutil_socket_t fd)
 {
        struct evbuffer_overlapped *evo;
 
@@ -157,7 +157,7 @@ evbuffer_overlapped_new(evutil_socket_t fd)
        if (!evo)
                return NULL;
 
-       TAILQ_INIT(&evo->buffer.callbacks);
+       LIST_INIT(&evo->buffer.callbacks);
        evo->buffer.refcnt = 1;
        evo->buffer.last_with_datap = &evo->buffer.first;
 
@@ -168,7 +168,7 @@ evbuffer_overlapped_new(evutil_socket_t fd)
 }
 
 int
-evbuffer_launch_write(struct evbuffer *buf, ev_ssize_t at_most,
+evbuffer_launch_write_(struct evbuffer *buf, ev_ssize_t at_most,
                struct event_overlapped *ol)
 {
        struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
@@ -204,7 +204,7 @@ evbuffer_launch_write(struct evbuffer *buf, ev_ssize_t at_most,
        for (i=0; i < MAX_WSABUFS && chain; ++i, chain=chain->next) {
                WSABUF *b = &buf_o->buffers[i];
                b->buf = (char*)( chain->buffer + chain->misalign );
-               _evbuffer_chain_pin(chain, EVBUFFER_MEM_PINNED_W);
+               evbuffer_chain_pin_(chain, EVBUFFER_MEM_PINNED_W);
 
                if ((size_t)at_most > chain->off) {
                        /* XXXX Cast is safe for now, since win32 has no
@@ -221,7 +221,7 @@ evbuffer_launch_write(struct evbuffer *buf, ev_ssize_t at_most,
        }
 
        buf_o->n_buffers = i;
-       _evbuffer_incref(buf);
+       evbuffer_incref_(buf);
        if (WSASend(buf_o->fd, buf_o->buffers, i, &bytesSent, 0,
                &ol->overlapped, NULL)) {
                int error = WSAGetLastError();
@@ -242,7 +242,7 @@ done:
 }
 
 int
-evbuffer_launch_read(struct evbuffer *buf, size_t at_most,
+evbuffer_launch_read_(struct evbuffer *buf, size_t at_most,
                struct event_overlapped *ol)
 {
        struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
@@ -265,11 +265,11 @@ evbuffer_launch_read(struct evbuffer *buf, size_t at_most,
        buf_o->n_buffers = 0;
        memset(buf_o->buffers, 0, sizeof(buf_o->buffers));
 
-       if (_evbuffer_expand_fast(buf, at_most, MAX_WSABUFS) == -1)
+       if (evbuffer_expand_fast_(buf, at_most, MAX_WSABUFS) == -1)
                goto done;
        evbuffer_freeze(buf, 0);
 
-       nvecs = _evbuffer_read_setup_vecs(buf, at_most,
+       nvecs = evbuffer_read_setup_vecs_(buf, at_most,
            vecs, MAX_WSABUFS, &chainp, 1);
        for (i=0;i<nvecs;++i) {
                WSABUF_FROM_EVBUFFER_IOV(
@@ -282,12 +282,12 @@ evbuffer_launch_read(struct evbuffer *buf, size_t at_most,
 
        npin=0;
        for ( ; chain; chain = chain->next) {
-               _evbuffer_chain_pin(chain, EVBUFFER_MEM_PINNED_R);
+               evbuffer_chain_pin_(chain, EVBUFFER_MEM_PINNED_R);
                ++npin;
        }
        EVUTIL_ASSERT(npin == nvecs);
 
-       _evbuffer_incref(buf);
+       evbuffer_incref_(buf);
        if (WSARecv(buf_o->fd, buf_o->buffers, nvecs, &bytesRead, &flags,
                    &ol->overlapped, NULL)) {
                int error = WSAGetLastError();
@@ -308,14 +308,14 @@ done:
 }
 
 evutil_socket_t
-_evbuffer_overlapped_get_fd(struct evbuffer *buf)
+evbuffer_overlapped_get_fd_(struct evbuffer *buf)
 {
        struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
        return buf_o ? buf_o->fd : -1;
 }
 
 void
-_evbuffer_overlapped_set_fd(struct evbuffer *buf, evutil_socket_t fd)
+evbuffer_overlapped_set_fd_(struct evbuffer *buf, evutil_socket_t fd)
 {
        struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
        EVBUFFER_LOCK(buf);
index 8f47979b6eb73935fe21cadde6095fd259c01fbf..461c46e76ca3a95b00dbbb04615969acd7072d95 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _BUFFEREVENT_INTERNAL_H_
-#define _BUFFEREVENT_INTERNAL_H_
+#ifndef BUFFEREVENT_INTERNAL_H_INCLUDED_
+#define BUFFEREVENT_INTERNAL_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -66,7 +66,7 @@ typedef ev_uint16_t bufferevent_suspend_flags;
 
 struct bufferevent_rate_limit_group {
        /** List of all members in the group */
-       TAILQ_HEAD(rlim_group_member_list, bufferevent_private) members;
+       LIST_HEAD(rlim_group_member_list, bufferevent_private) members;
        /** Current limits for the group. */
        struct ev_token_bucket rate_limit;
        struct ev_token_bucket_cfg rate_limit_cfg;
@@ -104,6 +104,10 @@ struct bufferevent_rate_limit_group {
        /** Timeout event that goes off once a tick, when the bucket is ready
         * to refill. */
        struct event master_refill_event;
+
+       /** Seed for weak random number generator. Protected by 'lock' */
+       struct evutil_weakrand_state weakrand_seed;
+
        /** Lock to protect the members of this group.  This lock should nest
         * within every bufferevent lock: if you are holding this lock, do
         * not assume you can lock another bufferevent. */
@@ -117,7 +121,7 @@ struct bufferevent_rate_limit {
         *
         * Note that this field is supposed to be protected by the group
         * lock */
-       TAILQ_ENTRY(bufferevent_private) next_in_group;
+       LIST_ENTRY(bufferevent_private) next_in_group;
        /** The rate-limiting group for this bufferevent, or NULL if it is
         * only rate-limited on its own. */
        struct bufferevent_rate_limit_group *group;
@@ -190,6 +194,14 @@ struct bufferevent_private {
         * If NULL, locking is disabled. */
        void *lock;
 
+       /** No matter how big our bucket gets, don't try to read more than this
+        * much in a single read operation. */
+       ev_ssize_t max_single_read;
+
+       /** No matter how big our bucket gets, don't try to write more than this
+        * much in a single write operation. */
+       ev_ssize_t max_single_write;
+
        /** Rate-limiting information for this bufferevent */
        struct bufferevent_rate_limit *rate_limiting;
 };
@@ -271,69 +283,69 @@ extern const struct bufferevent_ops bufferevent_ops_async;
 #endif
 
 /** Initialize the shared parts of a bufferevent. */
-int bufferevent_init_common(struct bufferevent_private *, struct event_base *, const struct bufferevent_ops *, enum bufferevent_options options);
+int bufferevent_init_common_(struct bufferevent_private *, struct event_base *, const struct bufferevent_ops *, enum bufferevent_options options);
 
 /** For internal use: temporarily stop all reads on bufev, until the conditions
  * in 'what' are over. */
-void bufferevent_suspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what);
+void bufferevent_suspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what);
 /** For internal use: clear the conditions 'what' on bufev, and re-enable
  * reading if there are no conditions left. */
-void bufferevent_unsuspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what);
+void bufferevent_unsuspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what);
 
 /** For internal use: temporarily stop all writes on bufev, until the conditions
  * in 'what' are over. */
-void bufferevent_suspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what);
+void bufferevent_suspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what);
 /** For internal use: clear the conditions 'what' on bufev, and re-enable
  * writing if there are no conditions left. */
-void bufferevent_unsuspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what);
+void bufferevent_unsuspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what);
 
 #define bufferevent_wm_suspend_read(b) \
-       bufferevent_suspend_read((b), BEV_SUSPEND_WM)
+       bufferevent_suspend_read_((b), BEV_SUSPEND_WM)
 #define bufferevent_wm_unsuspend_read(b) \
-       bufferevent_unsuspend_read((b), BEV_SUSPEND_WM)
+       bufferevent_unsuspend_read_((b), BEV_SUSPEND_WM)
 
 /*
   Disable a bufferevent.  Equivalent to bufferevent_disable(), but
   first resets 'connecting' flag to force EV_WRITE down for sure.
 
   XXXX this method will go away in the future; try not to add new users.
-    See comment in evhttp_connection_reset() for discussion.
+    See comment in evhttp_connection_reset_() for discussion.
 
   @param bufev the bufferevent to be disabled
   @param event any combination of EV_READ | EV_WRITE.
   @return 0 if successful, or -1 if an error occurred
   @see bufferevent_disable()
  */
-int bufferevent_disable_hard(struct bufferevent *bufev, short event);
+int bufferevent_disable_hard_(struct bufferevent *bufev, short event);
 
 /** Internal: Set up locking on a bufferevent.  If lock is set, use it.
  * Otherwise, use a new lock. */
-int bufferevent_enable_locking(struct bufferevent *bufev, void *lock);
+int bufferevent_enable_locking_(struct bufferevent *bufev, void *lock);
 /** Internal: Increment the reference count on bufev. */
-void bufferevent_incref(struct bufferevent *bufev);
+void bufferevent_incref_(struct bufferevent *bufev);
 /** Internal: Lock bufev and increase its reference count.
  * unlocking it otherwise. */
-void _bufferevent_incref_and_lock(struct bufferevent *bufev);
+void bufferevent_incref_and_lock_(struct bufferevent *bufev);
 /** Internal: Decrement the reference count on bufev.  Returns 1 if it freed
  * the bufferevent.*/
-int bufferevent_decref(struct bufferevent *bufev);
+int bufferevent_decref_(struct bufferevent *bufev);
 /** Internal: Drop the reference count on bufev, freeing as necessary, and
  * unlocking it otherwise.  Returns 1 if it freed the bufferevent. */
-int _bufferevent_decref_and_unlock(struct bufferevent *bufev);
+int bufferevent_decref_and_unlock_(struct bufferevent *bufev);
 
 /** Internal: If callbacks are deferred and we have a read callback, schedule
  * a readcb.  Otherwise just run the readcb. */
-void _bufferevent_run_readcb(struct bufferevent *bufev);
+void bufferevent_run_readcb_(struct bufferevent *bufev);
 /** Internal: If callbacks are deferred and we have a write callback, schedule
  * a writecb.  Otherwise just run the writecb. */
-void _bufferevent_run_writecb(struct bufferevent *bufev);
+void bufferevent_run_writecb_(struct bufferevent *bufev);
 /** Internal: If callbacks are deferred and we have an eventcb, schedule
  * it to run with events "what".  Otherwise just run the eventcb. */
-void _bufferevent_run_eventcb(struct bufferevent *bufev, short what);
+void bufferevent_run_eventcb_(struct bufferevent *bufev, short what);
 
 /** Internal: Add the event 'ev' with timeout tv, unless tv is set to 0, in
  * which case add ev with no timeout. */
-int _bufferevent_add_event(struct event *ev, const struct timeval *tv);
+int bufferevent_add_event_(struct event *ev, const struct timeval *tv);
 
 /* =========
  * These next functions implement timeouts for bufferevents that aren't doing
@@ -342,15 +354,15 @@ int _bufferevent_add_event(struct event *ev, const struct timeval *tv);
 /** Internal use: Set up the ev_read and ev_write callbacks so that
  * the other "generic_timeout" functions will work on it.  Call this from
  * the constructor function. */
-void _bufferevent_init_generic_timeout_cbs(struct bufferevent *bev);
+void bufferevent_init_generic_timeout_cbs_(struct bufferevent *bev);
 /** Internal use: Delete the ev_read and ev_write callbacks if they're pending.
  * Call this from the destructor function. */
-int _bufferevent_del_generic_timeout_cbs(struct bufferevent *bev);
+int bufferevent_del_generic_timeout_cbs_(struct bufferevent *bev);
 /** Internal use: Add or delete the generic timeout events as appropriate.
  * (If an event is enabled and a timeout is set, we add the event.  Otherwise
  * we delete it.)  Call this from anything that changes the timeout values,
  * that enabled EV_READ or EV_WRITE, or that disables EV_READ or EV_WRITE. */
-int _bufferevent_generic_adj_timeouts(struct bufferevent *bev);
+int bufferevent_generic_adj_timeouts_(struct bufferevent *bev);
 
 /** Internal use: We have just successfully read data into an inbuf, so
  * reset the read timeout (if any). */
@@ -376,9 +388,9 @@ int _bufferevent_generic_adj_timeouts(struct bufferevent *bev);
  * bufferevent_private. */
 #define BEV_UPCAST(b) EVUTIL_UPCAST((b), struct bufferevent_private, bev)
 
-#ifdef _EVENT_DISABLE_THREAD_SUPPORT
-#define BEV_LOCK(b) _EVUTIL_NIL_STMT
-#define BEV_UNLOCK(b) _EVUTIL_NIL_STMT
+#ifdef EVENT__DISABLE_THREAD_SUPPORT
+#define BEV_LOCK(b) EVUTIL_NIL_STMT_
+#define BEV_UNLOCK(b) EVUTIL_NIL_STMT_
 #else
 /** Internal: Grab the lock (if any) on a bufferevent */
 #define BEV_LOCK(b) do {                                               \
@@ -396,16 +408,18 @@ int _bufferevent_generic_adj_timeouts(struct bufferevent *bev);
 
 /* ==== For rate-limiting. */
 
-int _bufferevent_decrement_write_buckets(struct bufferevent_private *bev,
+int bufferevent_decrement_write_buckets_(struct bufferevent_private *bev,
     ev_ssize_t bytes);
-int _bufferevent_decrement_read_buckets(struct bufferevent_private *bev,
+int bufferevent_decrement_read_buckets_(struct bufferevent_private *bev,
     ev_ssize_t bytes);
-ev_ssize_t _bufferevent_get_read_max(struct bufferevent_private *bev);
-ev_ssize_t _bufferevent_get_write_max(struct bufferevent_private *bev);
+ev_ssize_t bufferevent_get_read_max_(struct bufferevent_private *bev);
+ev_ssize_t bufferevent_get_write_max_(struct bufferevent_private *bev);
+
+int bufferevent_ratelim_init_(struct bufferevent_private *bev);
 
 #ifdef __cplusplus
 }
 #endif
 
 
-#endif /* _BUFFEREVENT_INTERNAL_H_ */
+#endif /* BUFFEREVENT_INTERNAL_H_INCLUDED_ */
index 3a99186050a524ac73f3698d27a9b5f1261c3b5f..0d4b01d6a69ce9ed87d2b10b212b9143eb2edc93 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos, Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos, Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -30,7 +30,7 @@
 
 #include <sys/types.h>
 
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -38,7 +38,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_STDARG_H
+#ifdef EVENT__HAVE_STDARG_H
 #include <stdarg.h>
 #endif
 
 #include "evbuffer-internal.h"
 #include "util-internal.h"
 
-static void _bufferevent_cancel_all(struct bufferevent *bev);
+static void bufferevent_cancel_all_(struct bufferevent *bev);
 
 
 void
-bufferevent_suspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what)
+bufferevent_suspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what)
 {
        struct bufferevent_private *bufev_private =
            EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
@@ -76,7 +76,7 @@ bufferevent_suspend_read(struct bufferevent *bufev, bufferevent_suspend_flags wh
 }
 
 void
-bufferevent_unsuspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what)
+bufferevent_unsuspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what)
 {
        struct bufferevent_private *bufev_private =
            EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
@@ -88,7 +88,7 @@ bufferevent_unsuspend_read(struct bufferevent *bufev, bufferevent_suspend_flags
 }
 
 void
-bufferevent_suspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what)
+bufferevent_suspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what)
 {
        struct bufferevent_private *bufev_private =
            EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
@@ -100,7 +100,7 @@ bufferevent_suspend_write(struct bufferevent *bufev, bufferevent_suspend_flags w
 }
 
 void
-bufferevent_unsuspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what)
+bufferevent_unsuspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what)
 {
        struct bufferevent_private *bufev_private =
            EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
@@ -131,7 +131,7 @@ bufferevent_inbuf_wm_cb(struct evbuffer *buf,
 }
 
 static void
-bufferevent_run_deferred_callbacks_locked(struct deferred_cb *_, void *arg)
+bufferevent_run_deferred_callbacks_locked(struct deferred_cb *cb, void *arg)
 {
        struct bufferevent_private *bufev_private = arg;
        struct bufferevent *bufev = &bufev_private->bev;
@@ -160,11 +160,11 @@ bufferevent_run_deferred_callbacks_locked(struct deferred_cb *_, void *arg)
                EVUTIL_SET_SOCKET_ERROR(err);
                bufev->errorcb(bufev, what, bufev->cbarg);
        }
-       _bufferevent_decref_and_unlock(bufev);
+       bufferevent_decref_and_unlock_(bufev);
 }
 
 static void
-bufferevent_run_deferred_callbacks_unlocked(struct deferred_cb *_, void *arg)
+bufferevent_run_deferred_callbacks_unlocked(struct deferred_cb *cb, void *arg)
 {
        struct bufferevent_private *bufev_private = arg;
        struct bufferevent *bufev = &bufev_private->bev;
@@ -204,21 +204,21 @@ bufferevent_run_deferred_callbacks_unlocked(struct deferred_cb *_, void *arg)
                EVUTIL_SET_SOCKET_ERROR(err);
                UNLOCKED(errorcb(bufev,what,cbarg));
        }
-       _bufferevent_decref_and_unlock(bufev);
+       bufferevent_decref_and_unlock_(bufev);
 #undef UNLOCKED
 }
 
 #define SCHEDULE_DEFERRED(bevp)                                                \
        do {                                                            \
-               bufferevent_incref(&(bevp)->bev);                       \
-               event_deferred_cb_schedule                            \
-                       event_base_get_deferred_cb_queue((bevp)->bev.ev_base), \
+               bufferevent_incref_(&(bevp)->bev);                      \
+               event_deferred_cb_schedule_(                            \
+                       event_base_get_deferred_cb_queue_((bevp)->bev.ev_base), \
                        &(bevp)->deferred);                             \
        } while (0)
 
 
 void
-_bufferevent_run_readcb(struct bufferevent *bufev)
+bufferevent_run_readcb_(struct bufferevent *bufev)
 {
        /* Requires that we hold the lock and a reference */
        struct bufferevent_private *p =
@@ -235,7 +235,7 @@ _bufferevent_run_readcb(struct bufferevent *bufev)
 }
 
 void
-_bufferevent_run_writecb(struct bufferevent *bufev)
+bufferevent_run_writecb_(struct bufferevent *bufev)
 {
        /* Requires that we hold the lock and a reference */
        struct bufferevent_private *p =
@@ -252,7 +252,7 @@ _bufferevent_run_writecb(struct bufferevent *bufev)
 }
 
 void
-_bufferevent_run_eventcb(struct bufferevent *bufev, short what)
+bufferevent_run_eventcb_(struct bufferevent *bufev, short what)
 {
        /* Requires that we hold the lock and a reference */
        struct bufferevent_private *p =
@@ -270,7 +270,7 @@ _bufferevent_run_eventcb(struct bufferevent *bufev, short what)
 }
 
 int
-bufferevent_init_common(struct bufferevent_private *bufev_private,
+bufferevent_init_common_(struct bufferevent_private *bufev_private,
     struct event_base *base,
     const struct bufferevent_ops *ops,
     enum bufferevent_options options)
@@ -298,6 +298,8 @@ bufferevent_init_common(struct bufferevent_private *bufev_private,
 
        bufev->be_ops = ops;
 
+       bufferevent_ratelim_init_(bufev_private);
+
        /*
         * Set to EV_WRITE so that using bufferevent_write is going to
         * trigger a callback.  Reading needs to be explicitly enabled
@@ -305,9 +307,9 @@ bufferevent_init_common(struct bufferevent_private *bufev_private,
         */
        bufev->enabled = EV_WRITE;
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        if (options & BEV_OPT_THREADSAFE) {
-               if (bufferevent_enable_locking(bufev, NULL) < 0) {
+               if (bufferevent_enable_locking_(bufev, NULL) < 0) {
                        /* cleanup */
                        evbuffer_free(bufev->input);
                        evbuffer_free(bufev->output);
@@ -324,19 +326,19 @@ bufferevent_init_common(struct bufferevent_private *bufev_private,
        }
        if (options & BEV_OPT_DEFER_CALLBACKS) {
                if (options & BEV_OPT_UNLOCK_CALLBACKS)
-                       event_deferred_cb_init(&bufev_private->deferred,
+                       event_deferred_cb_init_(&bufev_private->deferred,
                            bufferevent_run_deferred_callbacks_unlocked,
                            bufev_private);
                else
-                       event_deferred_cb_init(&bufev_private->deferred,
+                       event_deferred_cb_init_(&bufev_private->deferred,
                            bufferevent_run_deferred_callbacks_locked,
                            bufev_private);
        }
 
        bufev_private->options = options;
 
-       evbuffer_set_parent(bufev->input, bufev);
-       evbuffer_set_parent(bufev->output, bufev);
+       evbuffer_set_parent_(bufev->input, bufev);
+       evbuffer_set_parent_(bufev->output, bufev);
 
        return 0;
 }
@@ -356,6 +358,26 @@ bufferevent_setcb(struct bufferevent *bufev,
        BEV_UNLOCK(bufev);
 }
 
+void
+bufferevent_getcb(struct bufferevent *bufev,
+    bufferevent_data_cb *readcb_ptr,
+    bufferevent_data_cb *writecb_ptr,
+    bufferevent_event_cb *eventcb_ptr,
+    void **cbarg_ptr)
+{
+       BEV_LOCK(bufev);
+       if (readcb_ptr)
+               *readcb_ptr = bufev->readcb;
+       if (writecb_ptr)
+               *writecb_ptr = bufev->writecb;
+       if (eventcb_ptr)
+               *eventcb_ptr = bufev->errorcb;
+       if (cbarg_ptr)
+               *cbarg_ptr = bufev->cbarg;
+
+       BEV_UNLOCK(bufev);
+}
+
 struct evbuffer *
 bufferevent_get_input(struct bufferevent *bufev)
 {
@@ -412,7 +434,7 @@ bufferevent_enable(struct bufferevent *bufev, short event)
        short impl_events = event;
        int r = 0;
 
-       _bufferevent_incref_and_lock(bufev);
+       bufferevent_incref_and_lock_(bufev);
        if (bufev_private->read_suspended)
                impl_events &= ~EV_READ;
        if (bufev_private->write_suspended)
@@ -423,7 +445,7 @@ bufferevent_enable(struct bufferevent *bufev, short event)
        if (impl_events && bufev->be_ops->enable(bufev, impl_events) < 0)
                r = -1;
 
-       _bufferevent_decref_and_unlock(bufev);
+       bufferevent_decref_and_unlock_(bufev);
        return r;
 }
 
@@ -478,7 +500,7 @@ bufferevent_settimeout(struct bufferevent *bufev,
 
 
 int
-bufferevent_disable_hard(struct bufferevent *bufev, short event)
+bufferevent_disable_hard_(struct bufferevent *bufev, short event)
 {
        int r = 0;
        struct bufferevent_private *bufev_private =
@@ -576,7 +598,7 @@ bufferevent_flush(struct bufferevent *bufev,
 }
 
 void
-_bufferevent_incref_and_lock(struct bufferevent *bufev)
+bufferevent_incref_and_lock_(struct bufferevent *bufev)
 {
        struct bufferevent_private *bufev_private =
            BEV_UPCAST(bufev);
@@ -586,7 +608,7 @@ _bufferevent_incref_and_lock(struct bufferevent *bufev)
 
 #if 0
 static void
-_bufferevent_transfer_lock_ownership(struct bufferevent *donor,
+bufferevent_transfer_lock_ownership_(struct bufferevent *donor,
     struct bufferevent *recipient)
 {
        struct bufferevent_private *d = BEV_UPCAST(donor);
@@ -603,7 +625,7 @@ _bufferevent_transfer_lock_ownership(struct bufferevent *donor,
 #endif
 
 int
-_bufferevent_decref_and_unlock(struct bufferevent *bufev)
+bufferevent_decref_and_unlock_(struct bufferevent *bufev)
 {
        struct bufferevent_private *bufev_private =
            EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
@@ -631,7 +653,7 @@ _bufferevent_decref_and_unlock(struct bufferevent *bufev)
 
        if (bufev_private->rate_limiting) {
                if (bufev_private->rate_limiting->group)
-                       bufferevent_remove_from_rate_limit_group_internal(bufev,0);
+                       bufferevent_remove_from_rate_limit_group_internal_(bufev,0);
                if (event_initialized(&bufev_private->rate_limiting->refill_bucket_event))
                        event_del(&bufev_private->rate_limiting->refill_bucket_event);
                event_debug_unassign(&bufev_private->rate_limiting->refill_bucket_event);
@@ -661,16 +683,16 @@ _bufferevent_decref_and_unlock(struct bufferevent *bufev)
         * It would probably save us some headaches.
         */
        if (underlying)
-               bufferevent_decref(underlying);
+               bufferevent_decref_(underlying);
 
        return 1;
 }
 
 int
-bufferevent_decref(struct bufferevent *bufev)
+bufferevent_decref_(struct bufferevent *bufev)
 {
        BEV_LOCK(bufev);
-       return _bufferevent_decref_and_unlock(bufev);
+       return bufferevent_decref_and_unlock_(bufev);
 }
 
 void
@@ -678,12 +700,12 @@ bufferevent_free(struct bufferevent *bufev)
 {
        BEV_LOCK(bufev);
        bufferevent_setcb(bufev, NULL, NULL, NULL, NULL);
-       _bufferevent_cancel_all(bufev);
-       _bufferevent_decref_and_unlock(bufev);
+       bufferevent_cancel_all_(bufev);
+       bufferevent_decref_and_unlock_(bufev);
 }
 
 void
-bufferevent_incref(struct bufferevent *bufev)
+bufferevent_incref_(struct bufferevent *bufev)
 {
        struct bufferevent_private *bufev_private =
            EVUTIL_UPCAST(bufev, struct bufferevent_private, bev);
@@ -694,9 +716,9 @@ bufferevent_incref(struct bufferevent *bufev)
 }
 
 int
-bufferevent_enable_locking(struct bufferevent *bufev, void *lock)
+bufferevent_enable_locking_(struct bufferevent *bufev, void *lock)
 {
-#ifdef _EVENT_DISABLE_THREAD_SUPPORT
+#ifdef EVENT__DISABLE_THREAD_SUPPORT
        return -1;
 #else
        struct bufferevent *underlying;
@@ -723,7 +745,7 @@ bufferevent_enable_locking(struct bufferevent *bufev, void *lock)
        evbuffer_enable_locking(bufev->output, lock);
 
        if (underlying && !BEV_UPCAST(underlying)->lock)
-               bufferevent_enable_locking(underlying, lock);
+               bufferevent_enable_locking_(underlying, lock);
 
        return 0;
 #endif
@@ -756,7 +778,7 @@ bufferevent_getfd(struct bufferevent *bev)
 }
 
 static void
-_bufferevent_cancel_all(struct bufferevent *bev)
+bufferevent_cancel_all_(struct bufferevent *bev)
 {
        union bufferevent_ctrl_data d;
        memset(&d, 0, sizeof(d));
@@ -793,23 +815,23 @@ static void
 bufferevent_generic_read_timeout_cb(evutil_socket_t fd, short event, void *ctx)
 {
        struct bufferevent *bev = ctx;
-       _bufferevent_incref_and_lock(bev);
+       bufferevent_incref_and_lock_(bev);
        bufferevent_disable(bev, EV_READ);
-       _bufferevent_run_eventcb(bev, BEV_EVENT_TIMEOUT|BEV_EVENT_READING);
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_run_eventcb_(bev, BEV_EVENT_TIMEOUT|BEV_EVENT_READING);
+       bufferevent_decref_and_unlock_(bev);
 }
 static void
 bufferevent_generic_write_timeout_cb(evutil_socket_t fd, short event, void *ctx)
 {
        struct bufferevent *bev = ctx;
-       _bufferevent_incref_and_lock(bev);
+       bufferevent_incref_and_lock_(bev);
        bufferevent_disable(bev, EV_WRITE);
-       _bufferevent_run_eventcb(bev, BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING);
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_run_eventcb_(bev, BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING);
+       bufferevent_decref_and_unlock_(bev);
 }
 
 void
-_bufferevent_init_generic_timeout_cbs(struct bufferevent *bev)
+bufferevent_init_generic_timeout_cbs_(struct bufferevent *bev)
 {
        evtimer_assign(&bev->ev_read, bev->ev_base,
            bufferevent_generic_read_timeout_cb, bev);
@@ -818,7 +840,7 @@ _bufferevent_init_generic_timeout_cbs(struct bufferevent *bev)
 }
 
 int
-_bufferevent_del_generic_timeout_cbs(struct bufferevent *bev)
+bufferevent_del_generic_timeout_cbs_(struct bufferevent *bev)
 {
        int r1,r2;
        r1 = event_del(&bev->ev_read);
@@ -829,7 +851,7 @@ _bufferevent_del_generic_timeout_cbs(struct bufferevent *bev)
 }
 
 int
-_bufferevent_generic_adj_timeouts(struct bufferevent *bev)
+bufferevent_generic_adj_timeouts_(struct bufferevent *bev)
 {
        const short enabled = bev->enabled;
        struct bufferevent_private *bev_p =
@@ -853,7 +875,7 @@ _bufferevent_generic_adj_timeouts(struct bufferevent *bev)
 }
 
 int
-_bufferevent_add_event(struct event *ev, const struct timeval *tv)
+bufferevent_add_event_(struct event *ev, const struct timeval *tv)
 {
        if (tv->tv_sec == 0 && tv->tv_usec == 0)
                return event_add(ev, NULL);
@@ -862,15 +884,15 @@ _bufferevent_add_event(struct event *ev, const struct timeval *tv)
 }
 
 /* For use by user programs only; internally, we should be calling
-   either _bufferevent_incref_and_lock(), or BEV_LOCK. */
+   either bufferevent_incref_and_lock_(), or BEV_LOCK. */
 void
 bufferevent_lock(struct bufferevent *bev)
 {
-       _bufferevent_incref_and_lock(bev);
+       bufferevent_incref_and_lock_(bev);
 }
 
 void
 bufferevent_unlock(struct bufferevent *bev)
 {
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
 }
index 287371d7b4dc3e347d7b08578fe75be98cfdc455..83b5c14191a8096bd28c79060097ec98d1197731 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * All rights reserved.
  *
@@ -29,7 +29,7 @@
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_STDARG_H
+#ifdef EVENT__HAVE_STDARG_H
 #include <stdarg.h>
 #endif
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 
@@ -94,7 +94,7 @@ const struct bufferevent_ops bufferevent_ops_async = {
        be_async_enable,
        be_async_disable,
        be_async_destruct,
-       _bufferevent_generic_adj_timeouts,
+       bufferevent_generic_adj_timeouts_,
        be_async_flush,
        be_async_ctrl,
 };
@@ -143,7 +143,7 @@ bev_async_del_write(struct bufferevent_async *beva)
 
        if (beva->write_added) {
                beva->write_added = 0;
-               event_base_del_virtual(bev->ev_base);
+               event_base_del_virtual_(bev->ev_base);
        }
 }
 
@@ -154,7 +154,7 @@ bev_async_del_read(struct bufferevent_async *beva)
 
        if (beva->read_added) {
                beva->read_added = 0;
-               event_base_del_virtual(bev->ev_base);
+               event_base_del_virtual_(bev->ev_base);
        }
 }
 
@@ -165,7 +165,7 @@ bev_async_add_write(struct bufferevent_async *beva)
 
        if (!beva->write_added) {
                beva->write_added = 1;
-               event_base_add_virtual(bev->ev_base);
+               event_base_add_virtual_(bev->ev_base);
        }
 }
 
@@ -176,7 +176,7 @@ bev_async_add_read(struct bufferevent_async *beva)
 
        if (!beva->read_added) {
                beva->read_added = 1;
-               event_base_add_virtual(bev->ev_base);
+               event_base_add_virtual_(bev->ev_base);
        }
 }
 
@@ -201,7 +201,7 @@ bev_async_consider_writing(struct bufferevent_async *beva)
 
        /* This is safe so long as bufferevent_get_write_max never returns
         * more than INT_MAX.  That's true for now. XXXX */
-       limit = (int)_bufferevent_get_write_max(&beva->bev);
+       limit = (int)bufferevent_get_write_max_(&beva->bev);
        if (at_most >= (size_t)limit && limit >= 0)
                at_most = limit;
 
@@ -211,15 +211,15 @@ bev_async_consider_writing(struct bufferevent_async *beva)
        }
 
        /*  XXXX doesn't respect low-water mark very well. */
-       bufferevent_incref(bev);
-       if (evbuffer_launch_write(bev->output, at_most,
+       bufferevent_incref_(bev);
+       if (evbuffer_launch_write_(bev->output, at_most,
            &beva->write_overlapped)) {
-               bufferevent_decref(bev);
+               bufferevent_decref_(bev);
                beva->ok = 0;
-               _bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
+               bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR);
        } else {
                beva->write_in_progress = at_most;
-               _bufferevent_decrement_write_buckets(&beva->bev, at_most);
+               bufferevent_decrement_write_buckets_(&beva->bev, at_most);
                bev_async_add_write(beva);
        }
 }
@@ -256,8 +256,8 @@ bev_async_consider_reading(struct bufferevent_async *beva)
        }
 
        /* XXXX This over-commits. */
-       /* XXXX see also not above on cast on _bufferevent_get_write_max() */
-       limit = (int)_bufferevent_get_read_max(&beva->bev);
+       /* XXXX see also not above on cast on bufferevent_get_write_max_() */
+       limit = (int)bufferevent_get_read_max_(&beva->bev);
        if (at_most >= (size_t)limit && limit >= 0)
                at_most = limit;
 
@@ -266,14 +266,14 @@ bev_async_consider_reading(struct bufferevent_async *beva)
                return;
        }
 
-       bufferevent_incref(bev);
-       if (evbuffer_launch_read(bev->input, at_most, &beva->read_overlapped)) {
+       bufferevent_incref_(bev);
+       if (evbuffer_launch_read_(bev->input, at_most, &beva->read_overlapped)) {
                beva->ok = 0;
-               _bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
-               bufferevent_decref(bev);
+               bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR);
+               bufferevent_decref_(bev);
        } else {
                beva->read_in_progress = at_most;
-               _bufferevent_decrement_read_buckets(&beva->bev, at_most);
+               bufferevent_decrement_read_buckets_(&beva->bev, at_most);
                bev_async_add_read(beva);
        }
 
@@ -291,12 +291,12 @@ be_async_outbuf_callback(struct evbuffer *buf,
        /* If we added data to the outbuf and were not writing before,
         * we may want to write now. */
 
-       _bufferevent_incref_and_lock(bev);
+       bufferevent_incref_and_lock_(bev);
 
        if (cbinfo->n_added)
                bev_async_consider_writing(bev_async);
 
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
 }
 
 static void
@@ -310,12 +310,12 @@ be_async_inbuf_callback(struct evbuffer *buf,
        /* If we drained data from the inbuf and were not reading before,
         * we may want to read now */
 
-       _bufferevent_incref_and_lock(bev);
+       bufferevent_incref_and_lock_(bev);
 
        if (cbinfo->n_deleted)
                bev_async_consider_reading(bev_async);
 
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
 }
 
 static int
@@ -379,7 +379,7 @@ be_async_destruct(struct bufferevent *bev)
        bev_async_del_read(bev_async);
        bev_async_del_write(bev_async);
 
-       fd = _evbuffer_overlapped_get_fd(bev->input);
+       fd = evbuffer_overlapped_get_fd_(bev->input);
        if (bev_p->options & BEV_OPT_CLOSE_ON_FREE) {
                /* XXXX possible double-close */
                evutil_closesocket(fd);
@@ -387,7 +387,7 @@ be_async_destruct(struct bufferevent *bev)
        /* delete this in case non-blocking connect was used */
        if (event_initialized(&bev->ev_write)) {
                event_del(&bev->ev_write);
-               _bufferevent_del_generic_timeout_cbs(bev);
+               bufferevent_del_generic_timeout_cbs_(bev);
        }
 }
 
@@ -399,7 +399,7 @@ bev_async_set_wsa_error(struct bufferevent *bev, struct event_overlapped *eo)
        DWORD bytes, flags;
        evutil_socket_t fd;
 
-       fd = _evbuffer_overlapped_get_fd(bev->input);
+       fd = evbuffer_overlapped_get_fd_(bev->input);
        WSAGetOverlappedResult(fd, &eo->overlapped, &bytes, FALSE, &flags);
 }
 
@@ -422,21 +422,21 @@ connect_complete(struct event_overlapped *eo, ev_uintptr_t key,
 
        EVUTIL_ASSERT(bev_a->bev.connecting);
        bev_a->bev.connecting = 0;
-       sock = _evbuffer_overlapped_get_fd(bev_a->bev.bev.input);
+       sock = evbuffer_overlapped_get_fd_(bev_a->bev.bev.input);
        /* XXXX Handle error? */
        setsockopt(sock, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
 
        if (ok)
-               bufferevent_async_set_connected(bev);
+               bufferevent_async_set_connected_(bev);
        else
                bev_async_set_wsa_error(bev, eo);
 
-       _bufferevent_run_eventcb(bev,
+       bufferevent_run_eventcb_(bev,
                        ok? BEV_EVENT_CONNECTED : BEV_EVENT_ERROR);
 
-       event_base_del_virtual(bev->ev_base);
+       event_base_del_virtual_(bev->ev_base);
 
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
 }
 
 static void
@@ -451,10 +451,10 @@ read_complete(struct event_overlapped *eo, ev_uintptr_t key,
        EVUTIL_ASSERT(bev_a->read_in_progress);
 
        amount_unread = bev_a->read_in_progress - nbytes;
-       evbuffer_commit_read(bev->input, nbytes);
+       evbuffer_commit_read_(bev->input, nbytes);
        bev_a->read_in_progress = 0;
        if (amount_unread)
-               _bufferevent_decrement_read_buckets(&bev_a->bev, -amount_unread);
+               bufferevent_decrement_read_buckets_(&bev_a->bev, -amount_unread);
 
        if (!ok)
                bev_async_set_wsa_error(bev, eo);
@@ -463,20 +463,20 @@ read_complete(struct event_overlapped *eo, ev_uintptr_t key,
                if (ok && nbytes) {
                        BEV_RESET_GENERIC_READ_TIMEOUT(bev);
                        if (evbuffer_get_length(bev->input) >= bev->wm_read.low)
-                               _bufferevent_run_readcb(bev);
+                               bufferevent_run_readcb_(bev);
                        bev_async_consider_reading(bev_a);
                } else if (!ok) {
                        what |= BEV_EVENT_ERROR;
                        bev_a->ok = 0;
-                       _bufferevent_run_eventcb(bev, what);
+                       bufferevent_run_eventcb_(bev, what);
                } else if (!nbytes) {
                        what |= BEV_EVENT_EOF;
                        bev_a->ok = 0;
-                       _bufferevent_run_eventcb(bev, what);
+                       bufferevent_run_eventcb_(bev, what);
                }
        }
 
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
 }
 
 static void
@@ -492,11 +492,11 @@ write_complete(struct event_overlapped *eo, ev_uintptr_t key,
        EVUTIL_ASSERT(bev_a->write_in_progress);
 
        amount_unwritten = bev_a->write_in_progress - nbytes;
-       evbuffer_commit_write(bev->output, nbytes);
+       evbuffer_commit_write_(bev->output, nbytes);
        bev_a->write_in_progress = 0;
 
        if (amount_unwritten)
-               _bufferevent_decrement_write_buckets(&bev_a->bev,
+               bufferevent_decrement_write_buckets_(&bev_a->bev,
                                                     -amount_unwritten);
 
 
@@ -508,24 +508,24 @@ write_complete(struct event_overlapped *eo, ev_uintptr_t key,
                        BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
                        if (evbuffer_get_length(bev->output) <=
                            bev->wm_write.low)
-                               _bufferevent_run_writecb(bev);
+                               bufferevent_run_writecb_(bev);
                        bev_async_consider_writing(bev_a);
                } else if (!ok) {
                        what |= BEV_EVENT_ERROR;
                        bev_a->ok = 0;
-                       _bufferevent_run_eventcb(bev, what);
+                       bufferevent_run_eventcb_(bev, what);
                } else if (!nbytes) {
                        what |= BEV_EVENT_EOF;
                        bev_a->ok = 0;
-                       _bufferevent_run_eventcb(bev, what);
+                       bufferevent_run_eventcb_(bev, what);
                }
        }
 
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
 }
 
 struct bufferevent *
-bufferevent_async_new(struct event_base *base,
+bufferevent_async_new_(struct event_base *base,
     evutil_socket_t fd, int options)
 {
        struct bufferevent_async *bev_a;
@@ -534,10 +534,10 @@ bufferevent_async_new(struct event_base *base,
 
        options |= BEV_OPT_THREADSAFE;
 
-       if (!(iocp = event_base_get_iocp(base)))
+       if (!(iocp = event_base_get_iocp_(base)))
                return NULL;
 
-       if (fd >= 0 && event_iocp_port_associate(iocp, fd, 1)<0) {
+       if (fd >= 0 && event_iocp_port_associate_(iocp, fd, 1)<0) {
                int err = GetLastError();
                /* We may have alrady associated this fd with a port.
                 * Let's hope it's this port, and that the error code
@@ -550,30 +550,30 @@ bufferevent_async_new(struct event_base *base,
                return NULL;
 
        bev = &bev_a->bev.bev;
-       if (!(bev->input = evbuffer_overlapped_new(fd))) {
+       if (!(bev->input = evbuffer_overlapped_new_(fd))) {
                mm_free(bev_a);
                return NULL;
        }
-       if (!(bev->output = evbuffer_overlapped_new(fd))) {
+       if (!(bev->output = evbuffer_overlapped_new_(fd))) {
                evbuffer_free(bev->input);
                mm_free(bev_a);
                return NULL;
        }
 
-       if (bufferevent_init_common(&bev_a->bev, base, &bufferevent_ops_async,
+       if (bufferevent_init_common_(&bev_a->bev, base, &bufferevent_ops_async,
                options)<0)
                goto err;
 
        evbuffer_add_cb(bev->input, be_async_inbuf_callback, bev);
        evbuffer_add_cb(bev->output, be_async_outbuf_callback, bev);
 
-       event_overlapped_init(&bev_a->connect_overlapped, connect_complete);
-       event_overlapped_init(&bev_a->read_overlapped, read_complete);
-       event_overlapped_init(&bev_a->write_overlapped, write_complete);
+       event_overlapped_init_(&bev_a->connect_overlapped, connect_complete);
+       event_overlapped_init_(&bev_a->read_overlapped, read_complete);
+       event_overlapped_init_(&bev_a->write_overlapped, write_complete);
 
        bev_a->ok = fd >= 0;
        if (bev_a->ok)
-               _bufferevent_init_generic_timeout_cbs(bev);
+               bufferevent_init_generic_timeout_cbs_(bev);
 
        return bev;
 err:
@@ -582,23 +582,23 @@ err:
 }
 
 void
-bufferevent_async_set_connected(struct bufferevent *bev)
+bufferevent_async_set_connected_(struct bufferevent *bev)
 {
        struct bufferevent_async *bev_async = upcast(bev);
        bev_async->ok = 1;
-       _bufferevent_init_generic_timeout_cbs(bev);
+       bufferevent_init_generic_timeout_cbs_(bev);
        /* Now's a good time to consider reading/writing */
        be_async_enable(bev, bev->enabled);
 }
 
 int
-bufferevent_async_can_connect(struct bufferevent *bev)
+bufferevent_async_can_connect_(struct bufferevent *bev)
 {
        const struct win32_extension_fns *ext =
-           event_get_win32_extension_fns();
+           event_get_win32_extension_fns_();
 
        if (BEV_IS_ASYNC(bev) &&
-           event_base_get_iocp(bev->ev_base) &&
+           event_base_get_iocp_(bev->ev_base) &&
            ext && ext->ConnectEx)
                return 1;
 
@@ -606,14 +606,14 @@ bufferevent_async_can_connect(struct bufferevent *bev)
 }
 
 int
-bufferevent_async_connect(struct bufferevent *bev, evutil_socket_t fd,
+bufferevent_async_connect_(struct bufferevent *bev, evutil_socket_t fd,
        const struct sockaddr *sa, int socklen)
 {
        BOOL rc;
        struct bufferevent_async *bev_async = upcast(bev);
        struct sockaddr_storage ss;
        const struct win32_extension_fns *ext =
-           event_get_win32_extension_fns();
+           event_get_win32_extension_fns_();
 
        EVUTIL_ASSERT(ext && ext->ConnectEx && fd >= 0 && sa != NULL);
 
@@ -638,15 +638,15 @@ bufferevent_async_connect(struct bufferevent *bev, evutil_socket_t fd,
            WSAGetLastError() != WSAEINVAL)
                return -1;
 
-       event_base_add_virtual(bev->ev_base);
-       bufferevent_incref(bev);
+       event_base_add_virtual_(bev->ev_base);
+       bufferevent_incref_(bev);
        rc = ext->ConnectEx(fd, sa, socklen, NULL, 0, NULL,
                            &bev_async->connect_overlapped.overlapped);
        if (rc || WSAGetLastError() == ERROR_IO_PENDING)
                return 0;
 
-       event_base_del_virtual(bev->ev_base);
-       bufferevent_decref(bev);
+       event_base_del_virtual_(bev->ev_base);
+       bufferevent_decref_(bev);
 
        return -1;
 }
@@ -657,24 +657,24 @@ be_async_ctrl(struct bufferevent *bev, enum bufferevent_ctrl_op op,
 {
        switch (op) {
        case BEV_CTRL_GET_FD:
-               data->fd = _evbuffer_overlapped_get_fd(bev->input);
+               data->fd = evbuffer_overlapped_get_fd_(bev->input);
                return 0;
        case BEV_CTRL_SET_FD: {
                struct event_iocp_port *iocp;
 
-               if (data->fd == _evbuffer_overlapped_get_fd(bev->input))
+               if (data->fd == evbuffer_overlapped_get_fd_(bev->input))
                        return 0;
-               if (!(iocp = event_base_get_iocp(bev->ev_base)))
+               if (!(iocp = event_base_get_iocp_(bev->ev_base)))
                        return -1;
-               if (event_iocp_port_associate(iocp, data->fd, 1) < 0)
+               if (event_iocp_port_associate_(iocp, data->fd, 1) < 0)
                        return -1;
-               _evbuffer_overlapped_set_fd(bev->input, data->fd);
-               _evbuffer_overlapped_set_fd(bev->output, data->fd);
+               evbuffer_overlapped_set_fd_(bev->input, data->fd);
+               evbuffer_overlapped_set_fd_(bev->output, data->fd);
                return 0;
        }
        case BEV_CTRL_CANCEL_ALL: {
                struct bufferevent_async *bev_a = upcast(bev);
-               evutil_socket_t fd = _evbuffer_overlapped_get_fd(bev->input);
+               evutil_socket_t fd = evbuffer_overlapped_get_fd_(bev->input);
                if (fd != (evutil_socket_t)INVALID_SOCKET &&
                    (bev_a->bev.options & BEV_OPT_CLOSE_ON_FREE)) {
                        closesocket(fd);
index bc30b6dfc07b6fd6681d53cfeca28a79dbab97ed..8a74f808afad7ae59406ce9b5d66a1ef13918fe0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
  * All rights reserved.
  *
@@ -32,7 +32,7 @@
 
 #include "event2/event-config.h"
 
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -40,7 +40,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_STDARG_H
+#ifdef EVENT__HAVE_STDARG_H
 #include <stdarg.h>
 #endif
 
@@ -100,7 +100,7 @@ const struct bufferevent_ops bufferevent_ops_filter = {
        be_filter_enable,
        be_filter_disable,
        be_filter_destruct,
-       _bufferevent_generic_adj_timeouts,
+       bufferevent_generic_adj_timeouts_,
        be_filter_flush,
        be_filter_ctrl,
 };
@@ -182,13 +182,13 @@ bufferevent_filter_new(struct bufferevent *underlying,
        if (!bufev_f)
                return NULL;
 
-       if (bufferevent_init_common(&bufev_f->bev, underlying->ev_base,
+       if (bufferevent_init_common_(&bufev_f->bev, underlying->ev_base,
                                    &bufferevent_ops_filter, tmp_options) < 0) {
                mm_free(bufev_f);
                return NULL;
        }
        if (options & BEV_OPT_THREADSAFE) {
-               bufferevent_enable_locking(downcast(bufev_f), NULL);
+               bufferevent_enable_locking_(downcast(bufev_f), NULL);
        }
 
        bufev_f->underlying = underlying;
@@ -204,11 +204,11 @@ bufferevent_filter_new(struct bufferevent *underlying,
        bufev_f->outbuf_cb = evbuffer_add_cb(downcast(bufev_f)->output,
           bufferevent_filtered_outbuf_cb, bufev_f);
 
-       _bufferevent_init_generic_timeout_cbs(downcast(bufev_f));
-       bufferevent_incref(underlying);
+       bufferevent_init_generic_timeout_cbs_(downcast(bufev_f));
+       bufferevent_incref_(underlying);
 
        bufferevent_enable(underlying, EV_READ|EV_WRITE);
-       bufferevent_suspend_read(underlying, BEV_SUSPEND_FILT_READ);
+       bufferevent_suspend_read_(underlying, BEV_SUSPEND_FILT_READ);
 
        return downcast(bufev_f);
 }
@@ -222,7 +222,7 @@ be_filter_destruct(struct bufferevent *bev)
                bevf->free_context(bevf->context);
 
        if (bevf->bev.options & BEV_OPT_CLOSE_ON_FREE) {
-               /* Yes, there is also a decref in bufferevent_decref.
+               /* Yes, there is also a decref in bufferevent_decref_.
                 * That decref corresponds to the incref when we set
                 * underlying for the first time.  This decref is an
                 * extra one to remove the last reference.
@@ -238,12 +238,12 @@ be_filter_destruct(struct bufferevent *bev)
                        if (bevf->underlying->errorcb == be_filter_eventcb)
                                bufferevent_setcb(bevf->underlying,
                                    NULL, NULL, NULL, NULL);
-                       bufferevent_unsuspend_read(bevf->underlying,
+                       bufferevent_unsuspend_read_(bevf->underlying,
                            BEV_SUSPEND_FILT_READ);
                }
        }
 
-       _bufferevent_del_generic_timeout_cbs(bev);
+       bufferevent_del_generic_timeout_cbs_(bev);
 }
 
 static int
@@ -255,7 +255,7 @@ be_filter_enable(struct bufferevent *bev, short event)
 
        if (event & EV_READ) {
                BEV_RESET_GENERIC_READ_TIMEOUT(bev);
-               bufferevent_unsuspend_read(bevf->underlying,
+               bufferevent_unsuspend_read_(bevf->underlying,
                    BEV_SUSPEND_FILT_READ);
        }
        return 0;
@@ -269,7 +269,7 @@ be_filter_disable(struct bufferevent *bev, short event)
                BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
        if (event & EV_READ) {
                BEV_DEL_GENERIC_READ_TIMEOUT(bev);
-               bufferevent_suspend_read(bevf->underlying,
+               bufferevent_suspend_read_(bevf->underlying,
                    BEV_SUSPEND_FILT_READ);
        }
        return 0;
@@ -372,7 +372,7 @@ be_filter_process_output(struct bufferevent_filtered *bevf,
                if (processed &&
                    evbuffer_get_length(bufev->output) <= bufev->wm_write.low) {
                        /* call the write callback.*/
-                       _bufferevent_run_writecb(bufev);
+                       bufferevent_run_writecb_(bufev);
 
                        if (res == BEV_OK &&
                            (bufev->enabled & EV_WRITE) &&
@@ -405,23 +405,23 @@ bufferevent_filtered_outbuf_cb(struct evbuffer *buf,
                int processed_any = 0;
                /* Somebody added more data to the output buffer. Try to
                 * process it, if we should. */
-               _bufferevent_incref_and_lock(bev);
+               bufferevent_incref_and_lock_(bev);
                be_filter_process_output(bevf, BEV_NORMAL, &processed_any);
-               _bufferevent_decref_and_unlock(bev);
+               bufferevent_decref_and_unlock_(bev);
        }
 }
 
 /* Called when the underlying socket has read. */
 static void
-be_filter_readcb(struct bufferevent *underlying, void *_me)
+be_filter_readcb(struct bufferevent *underlying, void *me_)
 {
-       struct bufferevent_filtered *bevf = _me;
+       struct bufferevent_filtered *bevf = me_;
        enum bufferevent_filter_result res;
        enum bufferevent_flush_mode state;
        struct bufferevent *bufev = downcast(bevf);
        int processed_any = 0;
 
-       _bufferevent_incref_and_lock(bufev);
+       bufferevent_incref_and_lock_(bufev);
 
        if (bevf->got_eof)
                state = BEV_FINISHED;
@@ -437,36 +437,36 @@ be_filter_readcb(struct bufferevent *underlying, void *_me)
         * force readcb calls as needed. */
        if (processed_any &&
            evbuffer_get_length(bufev->input) >= bufev->wm_read.low)
-               _bufferevent_run_readcb(bufev);
+               bufferevent_run_readcb_(bufev);
 
-       _bufferevent_decref_and_unlock(bufev);
+       bufferevent_decref_and_unlock_(bufev);
 }
 
 /* Called when the underlying socket has drained enough that we can write to
    it. */
 static void
-be_filter_writecb(struct bufferevent *underlying, void *_me)
+be_filter_writecb(struct bufferevent *underlying, void *me_)
 {
-       struct bufferevent_filtered *bevf = _me;
+       struct bufferevent_filtered *bevf = me_;
        struct bufferevent *bev = downcast(bevf);
        int processed_any = 0;
 
-       _bufferevent_incref_and_lock(bev);
+       bufferevent_incref_and_lock_(bev);
        be_filter_process_output(bevf, BEV_NORMAL, &processed_any);
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
 }
 
 /* Called when the underlying socket has given us an error */
 static void
-be_filter_eventcb(struct bufferevent *underlying, short what, void *_me)
+be_filter_eventcb(struct bufferevent *underlying, short what, void *me_)
 {
-       struct bufferevent_filtered *bevf = _me;
+       struct bufferevent_filtered *bevf = me_;
        struct bufferevent *bev = downcast(bevf);
 
-       _bufferevent_incref_and_lock(bev);
+       bufferevent_incref_and_lock_(bev);
        /* All we can really to is tell our own eventcb. */
-       _bufferevent_run_eventcb(bev, what);
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_run_eventcb_(bev, what);
+       bufferevent_decref_and_unlock_(bev);
 }
 
 static int
@@ -477,7 +477,7 @@ be_filter_flush(struct bufferevent *bufev,
        int processed_any = 0;
        EVUTIL_ASSERT(bevf);
 
-       _bufferevent_incref_and_lock(bufev);
+       bufferevent_incref_and_lock_(bufev);
 
        if (iotype & EV_READ) {
                be_filter_process_input(bevf, mode, &processed_any);
@@ -489,7 +489,7 @@ be_filter_flush(struct bufferevent *bufev,
        /* XXX does this want to recursively call lower-level flushes? */
        bufferevent_flush(bevf->underlying, iotype, mode);
 
-       _bufferevent_decref_and_unlock(bufev);
+       bufferevent_decref_and_unlock_(bufev);
 
        return processed_any;
 }
index ff8138fd8ccb54cd9ded09201350dd5aa5371ab7..33f7d3799bf179f2ffebfc25dbc85aac8d314d3b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -29,7 +29,7 @@
 
 #include <sys/types.h>
 
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_STDARG_H
+#ifdef EVENT__HAVE_STDARG_H
 #include <stdarg.h>
 #endif
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 
@@ -313,7 +313,7 @@ struct bufferevent_openssl {
        unsigned read_blocked_on_write : 1;
        /* When we next get data, we should say "write" instead of "read". */
        unsigned write_blocked_on_read : 1;
-       /* XXX */
+       /* Treat TCP close before SSL close on SSL >= v3 as clean EOF. */
        unsigned allow_dirty_shutdown : 1;
        /* XXXX */
        unsigned fd_is_set : 1;
@@ -377,15 +377,15 @@ static int
 start_reading(struct bufferevent_openssl *bev_ssl)
 {
        if (bev_ssl->underlying) {
-               bufferevent_unsuspend_read(bev_ssl->underlying,
+               bufferevent_unsuspend_read_(bev_ssl->underlying,
                    BEV_SUSPEND_FILT_READ);
                return 0;
        } else {
                struct bufferevent *bev = &bev_ssl->bev.bev;
                int r;
-               r = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
+               r = bufferevent_add_event_(&bev->ev_read, &bev->timeout_read);
                if (r == 0 && bev_ssl->read_blocked_on_write)
-                       r = _bufferevent_add_event(&bev->ev_write,
+                       r = bufferevent_add_event_(&bev->ev_write,
                            &bev->timeout_write);
                return r;
        }
@@ -402,9 +402,9 @@ start_writing(struct bufferevent_openssl *bev_ssl)
                ;
        } else {
                struct bufferevent *bev = &bev_ssl->bev.bev;
-               r = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
+               r = bufferevent_add_event_(&bev->ev_write, &bev->timeout_write);
                if (!r && bev_ssl->write_blocked_on_read)
-                       r = _bufferevent_add_event(&bev->ev_read,
+                       r = bufferevent_add_event_(&bev->ev_read,
                            &bev->timeout_read);
        }
        return r;
@@ -416,7 +416,7 @@ stop_reading(struct bufferevent_openssl *bev_ssl)
        if (bev_ssl->write_blocked_on_read)
                return;
        if (bev_ssl->underlying) {
-               bufferevent_suspend_read(bev_ssl->underlying,
+               bufferevent_suspend_read_(bev_ssl->underlying,
                    BEV_SUSPEND_FILT_READ);
        } else {
                struct bufferevent *bev = &bev_ssl->bev.bev;
@@ -483,7 +483,7 @@ clear_wbor(struct bufferevent_openssl *bev_ssl)
 }
 
 static void
-conn_closed(struct bufferevent_openssl *bev_ssl, int errcode, int ret)
+conn_closed(struct bufferevent_openssl *bev_ssl, int when, int errcode, int ret)
 {
        int event = BEV_EVENT_ERROR;
        int dirty_shutdown = 0;
@@ -529,7 +529,9 @@ conn_closed(struct bufferevent_openssl *bev_ssl, int errcode, int ret)
        stop_reading(bev_ssl);
        stop_writing(bev_ssl);
 
-       _bufferevent_run_eventcb(&bev_ssl->bev.bev, event);
+       /* when is BEV_EVENT_{READING|WRITING} */
+       event = when | event;
+       bufferevent_run_eventcb_(&bev_ssl->bev.bev, event);
 }
 
 static void
@@ -550,9 +552,9 @@ decrement_buckets(struct bufferevent_openssl *bev_ssl)
        unsigned long w = num_w - bev_ssl->counts.n_written;
        unsigned long r = num_r - bev_ssl->counts.n_read;
        if (w)
-               _bufferevent_decrement_write_buckets(&bev_ssl->bev, w);
+               bufferevent_decrement_write_buckets_(&bev_ssl->bev, w);
        if (r)
-               _bufferevent_decrement_read_buckets(&bev_ssl->bev, r);
+               bufferevent_decrement_read_buckets_(&bev_ssl->bev, r);
        bev_ssl->counts.n_written = num_w;
        bev_ssl->counts.n_read = num_r;
 }
@@ -567,7 +569,7 @@ do_read(struct bufferevent_openssl *bev_ssl, int n_to_read)
        int r, n, i, n_used = 0, blocked = 0, atmost;
        struct evbuffer_iovec space[2];
 
-       atmost = _bufferevent_get_read_max(&bev_ssl->bev);
+       atmost = bufferevent_get_read_max_(&bev_ssl->bev);
        if (n_to_read > atmost)
                n_to_read = atmost;
 
@@ -604,7 +606,7 @@ do_read(struct bufferevent_openssl *bev_ssl, int n_to_read)
                                                return -1;
                                break;
                        default:
-                               conn_closed(bev_ssl, err, r);
+                               conn_closed(bev_ssl, BEV_EVENT_READING, err, r);
                                break;
                        }
                        blocked = 1;
@@ -616,9 +618,6 @@ do_read(struct bufferevent_openssl *bev_ssl, int n_to_read)
                evbuffer_commit_space(input, space, n_used);
                if (bev_ssl->underlying)
                        BEV_RESET_GENERIC_READ_TIMEOUT(bev);
-
-               if (evbuffer_get_length(input) >= bev->wm_read.low)
-                       _bufferevent_run_readcb(bev);
        }
 
        return blocked ? 0 : 1;
@@ -635,7 +634,7 @@ do_write(struct bufferevent_openssl *bev_ssl, int atmost)
        if (bev_ssl->last_write > 0)
                atmost = bev_ssl->last_write;
        else
-               atmost = _bufferevent_get_write_max(&bev_ssl->bev);
+               atmost = bufferevent_get_write_max_(&bev_ssl->bev);
 
        n = evbuffer_peek(output, atmost, NULL, space, 8);
        if (n < 0)
@@ -682,7 +681,7 @@ do_write(struct bufferevent_openssl *bev_ssl, int atmost)
                                bev_ssl->last_write = space[i].iov_len;
                                break;
                        default:
-                               conn_closed(bev_ssl, err, r);
+                               conn_closed(bev_ssl, BEV_EVENT_WRITING, err, r);
                                bev_ssl->last_write = -1;
                                break;
                        }
@@ -696,7 +695,7 @@ do_write(struct bufferevent_openssl *bev_ssl, int atmost)
                        BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
 
                if (evbuffer_get_length(output) <= bev->wm_write.low)
-                       _bufferevent_run_writecb(bev);
+                       bufferevent_run_writecb_(bev);
        }
        return blocked ? 0 : 1;
 }
@@ -705,6 +704,50 @@ do_write(struct bufferevent_openssl *bev_ssl, int atmost)
 
 #define READ_DEFAULT 4096
 
+/* Try to figure out how many bytes to read; return 0 if we shouldn't be
+ * reading. */
+static int
+bytes_to_read(struct bufferevent_openssl *bev)
+{
+       struct evbuffer *input = bev->bev.bev.input;
+       struct event_watermark *wm = &bev->bev.bev.wm_read;
+       int result = READ_DEFAULT;
+       ev_ssize_t limit;
+       /* XXX 99% of this is generic code that nearly all bufferevents will
+        * want. */
+
+       if (bev->write_blocked_on_read) {
+               return 0;
+       }
+
+       if (! (bev->bev.bev.enabled & EV_READ)) {
+               return 0;
+       }
+
+       if (bev->bev.read_suspended) {
+               return 0;
+       }
+
+       if (wm->high) {
+               if (evbuffer_get_length(input) >= wm->high) {
+                       return 0;
+               }
+
+               result = wm->high - evbuffer_get_length(input);
+       } else {
+               result = READ_DEFAULT;
+       }
+
+       /* Respect the rate limit */
+       limit = bufferevent_get_read_max_(&bev->bev);
+       if (result > limit) {
+               result = limit;
+       }
+
+       return result;
+}
+
+
 /* Things look readable.  If write is blocked on read, write till it isn't.
  * Read from the underlying buffer until we block or we hit our high-water
  * mark.
@@ -713,8 +756,8 @@ static void
 consider_reading(struct bufferevent_openssl *bev_ssl)
 {
        int r;
-       struct evbuffer *input = bev_ssl->bev.bev.input;
-       struct event_watermark *wm = &bev_ssl->bev.bev.wm_read;
+       int n_to_read;
+       int read_data = 0;
 
        while (bev_ssl->write_blocked_on_read) {
                r = do_write(bev_ssl, WRITE_FRAME);
@@ -723,15 +766,50 @@ consider_reading(struct bufferevent_openssl *bev_ssl)
        }
        if (bev_ssl->write_blocked_on_read)
                return;
-       while ((bev_ssl->bev.bev.enabled & EV_READ) &&
-           (! bev_ssl->bev.read_suspended) &&
-           (! wm->high || evbuffer_get_length(input) < wm->high)) {
-               int n_to_read =
-                   wm->high ? wm->high - evbuffer_get_length(input)
-                            : READ_DEFAULT;
-               r = do_read(bev_ssl, n_to_read);
-               if (r <= 0)
+
+       n_to_read = bytes_to_read(bev_ssl);
+
+       while (n_to_read) {
+               if (do_read(bev_ssl, n_to_read) <= 0)
                        break;
+
+               read_data = 1;
+
+               /* Read all pending data.  This won't hit the network
+                * again, and will (most importantly) put us in a state
+                * where we don't need to read anything else until the
+                * socket is readable again.  It'll potentially make us
+                * overrun our read high-watermark (somewhat
+                * regrettable).  The damage to the rate-limit has
+                * already been done, since OpenSSL went and read a
+                * whole SSL record anyway. */
+               n_to_read = SSL_pending(bev_ssl->ssl);
+
+               /* XXX This if statement is actually a bad bug, added to avoid
+                * XXX a worse bug.
+                *
+                * The bad bug: It can potentially cause resource unfairness
+                * by reading too much data from the underlying bufferevent;
+                * it can potentially cause read looping if the underlying
+                * bufferevent is a bufferevent_pair and deferred callbacks
+                * aren't used.
+                *
+                * The worse bug: If we didn't do this, then we would
+                * potentially not read any more from bev_ssl->underlying
+                * until more data arrived there, which could lead to us
+                * waiting forever.
+                */
+               if (!n_to_read && bev_ssl->underlying)
+                       n_to_read = bytes_to_read(bev_ssl);
+       }
+
+       if (read_data == 1) {
+               struct bufferevent *bev = &bev_ssl->bev.bev;
+               struct evbuffer *input = bev->input;
+
+               if (evbuffer_get_length(input) >= bev->wm_read.low) {
+                       bufferevent_run_readcb_(bev);
+               }
        }
 
        if (!bev_ssl->underlying) {
@@ -755,6 +833,14 @@ consider_writing(struct bufferevent_openssl *bev_ssl)
                r = do_read(bev_ssl, 1024); /* XXXX 1024 is a hack */
                if (r <= 0)
                        break;
+               else {
+                       struct bufferevent *bev = &bev_ssl->bev.bev;
+                       struct evbuffer *input = bev->input;
+
+                       if (evbuffer_get_length(input) >= bev->wm_read.low) {
+                               bufferevent_run_readcb_(bev);
+                       }
+               }
        }
        if (bev_ssl->read_blocked_on_write)
                return;
@@ -823,33 +909,33 @@ be_openssl_eventcb(struct bufferevent *bev_base, short what, void *ctx)
                   eat it. */
        }
        if (event)
-               _bufferevent_run_eventcb(&bev_ssl->bev.bev, event);
+               bufferevent_run_eventcb_(&bev_ssl->bev.bev, event);
 }
 
 static void
 be_openssl_readeventcb(evutil_socket_t fd, short what, void *ptr)
 {
        struct bufferevent_openssl *bev_ssl = ptr;
-       _bufferevent_incref_and_lock(&bev_ssl->bev.bev);
+       bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
        if (what & EV_TIMEOUT) {
-               _bufferevent_run_eventcb(&bev_ssl->bev.bev,
+               bufferevent_run_eventcb_(&bev_ssl->bev.bev,
                    BEV_EVENT_TIMEOUT|BEV_EVENT_READING);
        } else
                consider_reading(bev_ssl);
-       _bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
+       bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
 }
 
 static void
 be_openssl_writeeventcb(evutil_socket_t fd, short what, void *ptr)
 {
        struct bufferevent_openssl *bev_ssl = ptr;
-       _bufferevent_incref_and_lock(&bev_ssl->bev.bev);
+       bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
        if (what & EV_TIMEOUT) {
-               _bufferevent_run_eventcb(&bev_ssl->bev.bev,
+               bufferevent_run_eventcb_(&bev_ssl->bev.bev,
                    BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING);
        }
        consider_writing(bev_ssl);
-       _bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
+       bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
 }
 
 static int
@@ -876,9 +962,9 @@ set_open_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
                event_assign(&bev->ev_write, bev->ev_base, fd,
                    EV_WRITE|EV_PERSIST, be_openssl_writeeventcb, bev_ssl);
                if (rpending)
-                       r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
+                       r1 = bufferevent_add_event_(&bev->ev_read, &bev->timeout_read);
                if (wpending)
-                       r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
+                       r2 = bufferevent_add_event_(&bev->ev_write, &bev->timeout_write);
                if (fd >= 0) {
                        bev_ssl->fd_is_set = 1;
                }
@@ -909,7 +995,7 @@ do_handshake(struct bufferevent_openssl *bev_ssl)
                set_open_callbacks(bev_ssl, -1); /* XXXX handle failure */
                /* Call do_read and do_write as needed */
                bufferevent_enable(&bev_ssl->bev.bev, bev_ssl->bev.bev.enabled);
-               _bufferevent_run_eventcb(&bev_ssl->bev.bev,
+               bufferevent_run_eventcb_(&bev_ssl->bev.bev,
                    BEV_EVENT_CONNECTED);
                return 1;
        } else {
@@ -929,7 +1015,7 @@ do_handshake(struct bufferevent_openssl *bev_ssl)
                        }
                        return 0;
                default:
-                       conn_closed(bev_ssl, err, r);
+                       conn_closed(bev_ssl, BEV_EVENT_READING, err, r);
                        return -1;
                }
        }
@@ -947,12 +1033,12 @@ be_openssl_handshakeeventcb(evutil_socket_t fd, short what, void *ptr)
 {
        struct bufferevent_openssl *bev_ssl = ptr;
 
-       _bufferevent_incref_and_lock(&bev_ssl->bev.bev);
+       bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
        if (what & EV_TIMEOUT) {
-               _bufferevent_run_eventcb(&bev_ssl->bev.bev, BEV_EVENT_TIMEOUT);
+               bufferevent_run_eventcb_(&bev_ssl->bev.bev, BEV_EVENT_TIMEOUT);
        } else
                do_handshake(bev_ssl);/* XXX handle failure */
-       _bufferevent_decref_and_unlock(&bev_ssl->bev.bev);
+       bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
 }
 
 static int
@@ -978,8 +1064,8 @@ set_handshake_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
                event_assign(&bev->ev_write, bev->ev_base, fd,
                    EV_WRITE|EV_PERSIST, be_openssl_handshakeeventcb, bev_ssl);
                if (fd >= 0) {
-                       r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
-                       r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
+                       r1 = bufferevent_add_event_(&bev->ev_read, &bev->timeout_read);
+                       r2 = bufferevent_add_event_(&bev->ev_write, &bev->timeout_write);
                        bev_ssl->fd_is_set = 1;
                }
                return (r1<0 || r2<0) ? -1 : 0;
@@ -1012,7 +1098,7 @@ be_openssl_outbuf_cb(struct evbuffer *buf,
 
        if (cbinfo->n_added && bev_ssl->state == BUFFEREVENT_SSL_OPEN) {
                if (cbinfo->orig_size == 0)
-                       r = _bufferevent_add_event(&bev_ssl->bev.bev.ev_write,
+                       r = bufferevent_add_event_(&bev_ssl->bev.bev.ev_write,
                            &bev_ssl->bev.bev.timeout_write);
                consider_writing(bev_ssl);
        }
@@ -1076,7 +1162,7 @@ be_openssl_destruct(struct bufferevent *bev)
        struct bufferevent_openssl *bev_ssl = upcast(bev);
 
        if (bev_ssl->underlying) {
-               _bufferevent_del_generic_timeout_cbs(bev);
+               bufferevent_del_generic_timeout_cbs_(bev);
        } else {
                event_del(&bev->ev_read);
                event_del(&bev->ev_write);
@@ -1105,7 +1191,7 @@ be_openssl_destruct(struct bufferevent *bev)
                        if (bev_ssl->underlying->errorcb == be_openssl_eventcb)
                                bufferevent_setcb(bev_ssl->underlying,
                                    NULL,NULL,NULL,NULL);
-                       bufferevent_unsuspend_read(bev_ssl->underlying,
+                       bufferevent_unsuspend_read_(bev_ssl->underlying,
                            BEV_SUSPEND_FILT_READ);
                }
        }
@@ -1117,13 +1203,13 @@ be_openssl_adj_timeouts(struct bufferevent *bev)
        struct bufferevent_openssl *bev_ssl = upcast(bev);
 
        if (bev_ssl->underlying)
-               return _bufferevent_generic_adj_timeouts(bev);
+               return bufferevent_generic_adj_timeouts_(bev);
        else {
                int r1=0, r2=0;
                if (event_pending(&bev->ev_read, EV_READ, NULL))
-                       r1 = _bufferevent_add_event(&bev->ev_read, &bev->timeout_read);
+                       r1 = bufferevent_add_event_(&bev->ev_read, &bev->timeout_read);
                if (event_pending(&bev->ev_write, EV_WRITE, NULL))
-                       r2 = _bufferevent_add_event(&bev->ev_write, &bev->timeout_write);
+                       r2 = bufferevent_add_event_(&bev->ev_write, &bev->timeout_write);
                return (r1<0 || r2<0) ? -1 : 0;
        }
 }
@@ -1203,7 +1289,7 @@ bufferevent_openssl_new_impl(struct event_base *base,
 
        bev_p = &bev_ssl->bev;
 
-       if (bufferevent_init_common(bev_p, base,
+       if (bufferevent_init_common_(bev_p, base,
                &bufferevent_ops_openssl, tmp_options) < 0)
                goto err;
 
@@ -1218,11 +1304,11 @@ bufferevent_openssl_new_impl(struct event_base *base,
            be_openssl_outbuf_cb, bev_ssl);
 
        if (options & BEV_OPT_THREADSAFE)
-               bufferevent_enable_locking(&bev_ssl->bev.bev, NULL);
+               bufferevent_enable_locking_(&bev_ssl->bev.bev, NULL);
 
        if (underlying) {
-               _bufferevent_init_generic_timeout_cbs(&bev_ssl->bev.bev);
-               bufferevent_incref(underlying);
+               bufferevent_init_generic_timeout_cbs_(&bev_ssl->bev.bev);
+               bufferevent_incref_(underlying);
        }
 
        bev_ssl->state = state;
@@ -1253,7 +1339,7 @@ bufferevent_openssl_new_impl(struct event_base *base,
                bufferevent_setwatermark(underlying, EV_READ, 0, 0);
                bufferevent_enable(underlying, EV_READ|EV_WRITE);
                if (state == BUFFEREVENT_SSL_OPEN)
-                       bufferevent_suspend_read(underlying,
+                       bufferevent_suspend_read_(underlying,
                            BEV_SUSPEND_FILT_READ);
        } else {
                bev_ssl->bev.bev.enabled = EV_READ|EV_WRITE;
@@ -1337,6 +1423,31 @@ bufferevent_openssl_socket_new(struct event_base *base,
                base, NULL, fd, ssl, state, options);
 }
 
+int
+bufferevent_openssl_get_allow_dirty_shutdown(struct bufferevent *bev)
+{
+       int allow_dirty_shutdown = -1;
+       struct bufferevent_openssl *bev_ssl;
+       BEV_LOCK(bev);
+       bev_ssl = upcast(bev);
+       if (bev_ssl)
+               allow_dirty_shutdown = bev_ssl->allow_dirty_shutdown;
+       BEV_UNLOCK(bev);
+       return allow_dirty_shutdown;
+}
+
+void
+bufferevent_openssl_set_allow_dirty_shutdown(struct bufferevent *bev,
+    int allow_dirty_shutdown)
+{
+       struct bufferevent_openssl *bev_ssl;
+       BEV_LOCK(bev);
+       bev_ssl = upcast(bev);
+       if (bev_ssl)
+               bev_ssl->allow_dirty_shutdown = !!allow_dirty_shutdown;
+       BEV_UNLOCK(bev);
+}
+
 unsigned long
 bufferevent_get_openssl_error(struct bufferevent *bev)
 {
index 33f85e7e47ddb19b03eacd3238b0e9b54522a6c8..da4b11175f379e831fefbbab2595874a8215025f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos, Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -67,10 +67,10 @@ static inline void
 incref_and_lock(struct bufferevent *b)
 {
        struct bufferevent_pair *bevp;
-       _bufferevent_incref_and_lock(b);
+       bufferevent_incref_and_lock_(b);
        bevp = upcast(b);
        if (bevp->partner)
-               _bufferevent_incref_and_lock(downcast(bevp->partner));
+               bufferevent_incref_and_lock_(downcast(bevp->partner));
 }
 
 static inline void
@@ -78,8 +78,8 @@ decref_and_unlock(struct bufferevent *b)
 {
        struct bufferevent_pair *bevp = upcast(b);
        if (bevp->partner)
-               _bufferevent_decref_and_unlock(downcast(bevp->partner));
-       _bufferevent_decref_and_unlock(b);
+               bufferevent_decref_and_unlock_(downcast(bevp->partner));
+       bufferevent_decref_and_unlock_(b);
 }
 
 /* XXX Handle close */
@@ -94,7 +94,7 @@ bufferevent_pair_elt_new(struct event_base *base,
        struct bufferevent_pair *bufev;
        if (! (bufev = mm_calloc(1, sizeof(struct bufferevent_pair))))
                return NULL;
-       if (bufferevent_init_common(&bufev->bev, base, &bufferevent_ops_pair,
+       if (bufferevent_init_common_(&bufev->bev, base, &bufferevent_ops_pair,
                options)) {
                mm_free(bufev);
                return NULL;
@@ -104,7 +104,7 @@ bufferevent_pair_elt_new(struct event_base *base,
                return NULL;
        }
 
-       _bufferevent_init_generic_timeout_cbs(&bufev->bev.bev);
+       bufferevent_init_generic_timeout_cbs_(&bufev->bev.bev);
 
        return bufev;
 }
@@ -130,7 +130,7 @@ bufferevent_pair_new(struct event_base *base, int options,
 
        if (options & BEV_OPT_THREADSAFE) {
                /*XXXX check return */
-               bufferevent_enable_locking(downcast(bufev2), bufev1->bev.lock);
+               bufferevent_enable_locking_(downcast(bufev2), bufev1->bev.lock);
        }
 
        bufev1->partner = bufev2;
@@ -186,10 +186,10 @@ be_pair_transfer(struct bufferevent *src, struct bufferevent *dst,
        dst_size = evbuffer_get_length(dst->input);
 
        if (dst_size >= dst->wm_read.low) {
-               _bufferevent_run_readcb(dst);
+               bufferevent_run_readcb_(dst);
        }
        if (src_size <= src->wm_write.low) {
-               _bufferevent_run_writecb(src);
+               bufferevent_run_writecb_(src);
        }
 done:
        evbuffer_freeze(src->output, 1);
@@ -275,7 +275,7 @@ be_pair_destruct(struct bufferevent *bev)
                bev_p->partner = NULL;
        }
 
-       _bufferevent_del_generic_timeout_cbs(bev);
+       bufferevent_del_generic_timeout_cbs_(bev);
 }
 
 static int
@@ -300,7 +300,7 @@ be_pair_flush(struct bufferevent *bev, short iotype,
                be_pair_transfer(bev, partner, 1);
 
        if (mode == BEV_FINISHED) {
-               _bufferevent_run_eventcb(partner, iotype|BEV_EVENT_EOF);
+               bufferevent_run_eventcb_(partner, iotype|BEV_EVENT_EOF);
        }
        decref_and_unlock(bev);
        return 0;
@@ -327,7 +327,7 @@ const struct bufferevent_ops bufferevent_ops_pair = {
        be_pair_enable,
        be_pair_disable,
        be_pair_destruct,
-       _bufferevent_generic_adj_timeouts,
+       bufferevent_generic_adj_timeouts_,
        be_pair_flush,
        NULL, /* ctrl */
 };
index 506e82ab912179b6e2eaed2f1ba89c6bc831ac0d..f7de86a9309ece739cfca1007562a7e75dad9630 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
  * All rights reserved.
  *
@@ -47,7 +47,7 @@
 #include "event-internal.h"
 
 int
-ev_token_bucket_init(struct ev_token_bucket *bucket,
+ev_token_bucket_init_(struct ev_token_bucket *bucket,
     const struct ev_token_bucket_cfg *cfg,
     ev_uint32_t current_tick,
     int reinitialize)
@@ -71,7 +71,7 @@ ev_token_bucket_init(struct ev_token_bucket *bucket,
 }
 
 int
-ev_token_bucket_update(struct ev_token_bucket *bucket,
+ev_token_bucket_update_(struct ev_token_bucket *bucket,
     const struct ev_token_bucket_cfg *cfg,
     ev_uint32_t current_tick)
 {
@@ -117,14 +117,14 @@ bufferevent_update_buckets(struct bufferevent_private *bev)
        struct timeval now;
        unsigned tick;
        event_base_gettimeofday_cached(bev->bev.ev_base, &now);
-       tick = ev_token_bucket_get_tick(&now, bev->rate_limiting->cfg);
+       tick = ev_token_bucket_get_tick_(&now, bev->rate_limiting->cfg);
        if (tick != bev->rate_limiting->limit.last_updated)
-               ev_token_bucket_update(&bev->rate_limiting->limit,
+               ev_token_bucket_update_(&bev->rate_limiting->limit,
                    bev->rate_limiting->cfg, tick);
 }
 
 ev_uint32_t
-ev_token_bucket_get_tick(const struct timeval *tv,
+ev_token_bucket_get_tick_(const struct timeval *tv,
     const struct ev_token_bucket_cfg *cfg)
 {
        /* This computation uses two multiplies and a divide.  We could do
@@ -178,30 +178,27 @@ ev_token_bucket_cfg_free(struct ev_token_bucket_cfg *cfg)
        mm_free(cfg);
 }
 
-/* No matter how big our bucket gets, don't try to read more than this
- * much in a single read operation. */
-#define MAX_TO_READ_EVER 16384
-/* No matter how big our bucket gets, don't try to write more than this
- * much in a single write operation. */
-#define MAX_TO_WRITE_EVER 16384
+/* Default values for max_single_read & max_single_write variables. */
+#define MAX_SINGLE_READ_DEFAULT 16384
+#define MAX_SINGLE_WRITE_DEFAULT 16384
 
 #define LOCK_GROUP(g) EVLOCK_LOCK((g)->lock, 0)
 #define UNLOCK_GROUP(g) EVLOCK_UNLOCK((g)->lock, 0)
 
-static int _bev_group_suspend_reading(struct bufferevent_rate_limit_group *g);
-static int _bev_group_suspend_writing(struct bufferevent_rate_limit_group *g);
-static void _bev_group_unsuspend_reading(struct bufferevent_rate_limit_group *g);
-static void _bev_group_unsuspend_writing(struct bufferevent_rate_limit_group *g);
+static int bev_group_suspend_reading_(struct bufferevent_rate_limit_group *g);
+static int bev_group_suspend_writing_(struct bufferevent_rate_limit_group *g);
+static void bev_group_unsuspend_reading_(struct bufferevent_rate_limit_group *g);
+static void bev_group_unsuspend_writing_(struct bufferevent_rate_limit_group *g);
 
 /** Helper: figure out the maximum amount we should write if is_write, or
     the maximum amount we should read if is_read.  Return that maximum, or
     0 if our bucket is wholly exhausted.
  */
 static inline ev_ssize_t
-_bufferevent_get_rlim_max(struct bufferevent_private *bev, int is_write)
+bufferevent_get_rlim_max_(struct bufferevent_private *bev, int is_write)
 {
        /* needs lock on bev. */
-       ev_ssize_t max_so_far = is_write?MAX_TO_WRITE_EVER:MAX_TO_READ_EVER;
+       ev_ssize_t max_so_far = is_write?bev->max_single_write:bev->max_single_read;
 
 #define LIM(x)                                         \
        (is_write ? (x).write_limit : (x).read_limit)
@@ -238,10 +235,10 @@ _bufferevent_get_rlim_max(struct bufferevent_private *bev, int is_write)
                         * particular bufferevent while suspending the whole
                         * group. */
                        if (is_write)
-                               bufferevent_suspend_write(&bev->bev,
+                               bufferevent_suspend_write_(&bev->bev,
                                    BEV_SUSPEND_BW_GROUP);
                        else
-                               bufferevent_suspend_read(&bev->bev,
+                               bufferevent_suspend_read_(&bev->bev,
                                    BEV_SUSPEND_BW_GROUP);
                        share = 0;
                } else {
@@ -261,19 +258,19 @@ _bufferevent_get_rlim_max(struct bufferevent_private *bev, int is_write)
 }
 
 ev_ssize_t
-_bufferevent_get_read_max(struct bufferevent_private *bev)
+bufferevent_get_read_max_(struct bufferevent_private *bev)
 {
-       return _bufferevent_get_rlim_max(bev, 0);
+       return bufferevent_get_rlim_max_(bev, 0);
 }
 
 ev_ssize_t
-_bufferevent_get_write_max(struct bufferevent_private *bev)
+bufferevent_get_write_max_(struct bufferevent_private *bev)
 {
-       return _bufferevent_get_rlim_max(bev, 1);
+       return bufferevent_get_rlim_max_(bev, 1);
 }
 
 int
-_bufferevent_decrement_read_buckets(struct bufferevent_private *bev, ev_ssize_t bytes)
+bufferevent_decrement_read_buckets_(struct bufferevent_private *bev, ev_ssize_t bytes)
 {
        /* XXXXX Make sure all users of this function check its return value */
        int r = 0;
@@ -284,14 +281,14 @@ _bufferevent_decrement_read_buckets(struct bufferevent_private *bev, ev_ssize_t
        if (bev->rate_limiting->cfg) {
                bev->rate_limiting->limit.read_limit -= bytes;
                if (bev->rate_limiting->limit.read_limit <= 0) {
-                       bufferevent_suspend_read(&bev->bev, BEV_SUSPEND_BW);
+                       bufferevent_suspend_read_(&bev->bev, BEV_SUSPEND_BW);
                        if (event_add(&bev->rate_limiting->refill_bucket_event,
                                &bev->rate_limiting->cfg->tick_timeout) < 0)
                                r = -1;
                } else if (bev->read_suspended & BEV_SUSPEND_BW) {
                        if (!(bev->write_suspended & BEV_SUSPEND_BW))
                                event_del(&bev->rate_limiting->refill_bucket_event);
-                       bufferevent_unsuspend_read(&bev->bev, BEV_SUSPEND_BW);
+                       bufferevent_unsuspend_read_(&bev->bev, BEV_SUSPEND_BW);
                }
        }
 
@@ -300,9 +297,9 @@ _bufferevent_decrement_read_buckets(struct bufferevent_private *bev, ev_ssize_t
                bev->rate_limiting->group->rate_limit.read_limit -= bytes;
                bev->rate_limiting->group->total_read += bytes;
                if (bev->rate_limiting->group->rate_limit.read_limit <= 0) {
-                       _bev_group_suspend_reading(bev->rate_limiting->group);
+                       bev_group_suspend_reading_(bev->rate_limiting->group);
                } else if (bev->rate_limiting->group->read_suspended) {
-                       _bev_group_unsuspend_reading(bev->rate_limiting->group);
+                       bev_group_unsuspend_reading_(bev->rate_limiting->group);
                }
                UNLOCK_GROUP(bev->rate_limiting->group);
        }
@@ -311,7 +308,7 @@ _bufferevent_decrement_read_buckets(struct bufferevent_private *bev, ev_ssize_t
 }
 
 int
-_bufferevent_decrement_write_buckets(struct bufferevent_private *bev, ev_ssize_t bytes)
+bufferevent_decrement_write_buckets_(struct bufferevent_private *bev, ev_ssize_t bytes)
 {
        /* XXXXX Make sure all users of this function check its return value */
        int r = 0;
@@ -322,14 +319,14 @@ _bufferevent_decrement_write_buckets(struct bufferevent_private *bev, ev_ssize_t
        if (bev->rate_limiting->cfg) {
                bev->rate_limiting->limit.write_limit -= bytes;
                if (bev->rate_limiting->limit.write_limit <= 0) {
-                       bufferevent_suspend_write(&bev->bev, BEV_SUSPEND_BW);
+                       bufferevent_suspend_write_(&bev->bev, BEV_SUSPEND_BW);
                        if (event_add(&bev->rate_limiting->refill_bucket_event,
                                &bev->rate_limiting->cfg->tick_timeout) < 0)
                                r = -1;
                } else if (bev->write_suspended & BEV_SUSPEND_BW) {
                        if (!(bev->read_suspended & BEV_SUSPEND_BW))
                                event_del(&bev->rate_limiting->refill_bucket_event);
-                       bufferevent_unsuspend_write(&bev->bev, BEV_SUSPEND_BW);
+                       bufferevent_unsuspend_write_(&bev->bev, BEV_SUSPEND_BW);
                }
        }
 
@@ -338,9 +335,9 @@ _bufferevent_decrement_write_buckets(struct bufferevent_private *bev, ev_ssize_t
                bev->rate_limiting->group->rate_limit.write_limit -= bytes;
                bev->rate_limiting->group->total_written += bytes;
                if (bev->rate_limiting->group->rate_limit.write_limit <= 0) {
-                       _bev_group_suspend_writing(bev->rate_limiting->group);
+                       bev_group_suspend_writing_(bev->rate_limiting->group);
                } else if (bev->rate_limiting->group->write_suspended) {
-                       _bev_group_unsuspend_writing(bev->rate_limiting->group);
+                       bev_group_unsuspend_writing_(bev->rate_limiting->group);
                }
                UNLOCK_GROUP(bev->rate_limiting->group);
        }
@@ -350,22 +347,22 @@ _bufferevent_decrement_write_buckets(struct bufferevent_private *bev, ev_ssize_t
 
 /** Stop reading on every bufferevent in <b>g</b> */
 static int
-_bev_group_suspend_reading(struct bufferevent_rate_limit_group *g)
+bev_group_suspend_reading_(struct bufferevent_rate_limit_group *g)
 {
        /* Needs group lock */
        struct bufferevent_private *bev;
        g->read_suspended = 1;
        g->pending_unsuspend_read = 0;
 
-       /* Note that in this loop we call EVLOCK_TRY_LOCK instead of BEV_LOCK,
+       /* Note that in this loop we call EVLOCK_TRY_LOCK_ instead of BEV_LOCK,
           to prevent a deadlock.  (Ordinarily, the group lock nests inside
           the bufferevent locks.  If we are unable to lock any individual
           bufferevent, it will find out later when it looks at its limit
-          and sees that its group is suspended.
+          and sees that its group is suspended.)
        */
-       TAILQ_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
-               if (EVLOCK_TRY_LOCK(bev->lock)) {
-                       bufferevent_suspend_read(&bev->bev,
+       LIST_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
+               if (EVLOCK_TRY_LOCK_(bev->lock)) {
+                       bufferevent_suspend_read_(&bev->bev,
                            BEV_SUSPEND_BW_GROUP);
                        EVLOCK_UNLOCK(bev->lock, 0);
                }
@@ -375,15 +372,15 @@ _bev_group_suspend_reading(struct bufferevent_rate_limit_group *g)
 
 /** Stop writing on every bufferevent in <b>g</b> */
 static int
-_bev_group_suspend_writing(struct bufferevent_rate_limit_group *g)
+bev_group_suspend_writing_(struct bufferevent_rate_limit_group *g)
 {
        /* Needs group lock */
        struct bufferevent_private *bev;
        g->write_suspended = 1;
        g->pending_unsuspend_write = 0;
-       TAILQ_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
-               if (EVLOCK_TRY_LOCK(bev->lock)) {
-                       bufferevent_suspend_write(&bev->bev,
+       LIST_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
+               if (EVLOCK_TRY_LOCK_(bev->lock)) {
+                       bufferevent_suspend_write_(&bev->bev,
                            BEV_SUSPEND_BW_GROUP);
                        EVLOCK_UNLOCK(bev->lock, 0);
                }
@@ -394,7 +391,7 @@ _bev_group_suspend_writing(struct bufferevent_rate_limit_group *g)
 /** Timer callback invoked on a single bufferevent with one or more exhausted
     buckets when they are ready to refill. */
 static void
-_bev_refill_callback(evutil_socket_t fd, short what, void *arg)
+bev_refill_callback_(evutil_socket_t fd, short what, void *arg)
 {
        unsigned tick;
        struct timeval now;
@@ -408,22 +405,22 @@ _bev_refill_callback(evutil_socket_t fd, short what, void *arg)
 
        /* First, update the bucket */
        event_base_gettimeofday_cached(bev->bev.ev_base, &now);
-       tick = ev_token_bucket_get_tick(&now,
+       tick = ev_token_bucket_get_tick_(&now,
            bev->rate_limiting->cfg);
-       ev_token_bucket_update(&bev->rate_limiting->limit,
+       ev_token_bucket_update_(&bev->rate_limiting->limit,
            bev->rate_limiting->cfg,
            tick);
 
        /* Now unsuspend any read/write operations as appropriate. */
        if ((bev->read_suspended & BEV_SUSPEND_BW)) {
                if (bev->rate_limiting->limit.read_limit > 0)
-                       bufferevent_unsuspend_read(&bev->bev, BEV_SUSPEND_BW);
+                       bufferevent_unsuspend_read_(&bev->bev, BEV_SUSPEND_BW);
                else
                        again = 1;
        }
        if ((bev->write_suspended & BEV_SUSPEND_BW)) {
                if (bev->rate_limiting->limit.write_limit > 0)
-                       bufferevent_unsuspend_write(&bev->bev, BEV_SUSPEND_BW);
+                       bufferevent_unsuspend_write_(&bev->bev, BEV_SUSPEND_BW);
                else
                        again = 1;
        }
@@ -441,9 +438,12 @@ _bev_refill_callback(evutil_socket_t fd, short what, void *arg)
        BEV_UNLOCK(&bev->bev);
 }
 
-/** Helper: grab a random element from a bufferevent group. */
+/** Helper: grab a random element from a bufferevent group.
+ *
+ * Requires that we hold the lock on the group.
+ */
 static struct bufferevent_private *
-_bev_group_random_element(struct bufferevent_rate_limit_group *group)
+bev_group_random_element_(struct bufferevent_rate_limit_group *group)
 {
        int which;
        struct bufferevent_private *bev;
@@ -453,13 +453,13 @@ _bev_group_random_element(struct bufferevent_rate_limit_group *group)
        if (!group->n_members)
                return NULL;
 
-       EVUTIL_ASSERT(! TAILQ_EMPTY(&group->members));
+       EVUTIL_ASSERT(! LIST_EMPTY(&group->members));
 
-       which = _evutil_weakrand() % group->n_members;
+       which = evutil_weakrand_range_(&group->weakrand_seed, group->n_members);
 
-       bev = TAILQ_FIRST(&group->members);
+       bev = LIST_FIRST(&group->members);
        while (which--)
-               bev = TAILQ_NEXT(bev, rate_limiting->next_in_group);
+               bev = LIST_NEXT(bev, rate_limiting->next_in_group);
 
        return bev;
 }
@@ -473,27 +473,27 @@ _bev_group_random_element(struct bufferevent_rate_limit_group *group)
  */
 #define FOREACH_RANDOM_ORDER(block)                    \
        do {                                            \
-               first = _bev_group_random_element(g);   \
-               for (bev = first; bev != TAILQ_END(&g->members); \
-                   bev = TAILQ_NEXT(bev, rate_limiting->next_in_group)) { \
+               first = bev_group_random_element_(g);   \
+               for (bev = first; bev != LIST_END(&g->members); \
+                   bev = LIST_NEXT(bev, rate_limiting->next_in_group)) { \
                        block ;                                  \
                }                                                \
-               for (bev = TAILQ_FIRST(&g->members); bev && bev != first; \
-                   bev = TAILQ_NEXT(bev, rate_limiting->next_in_group)) { \
+               for (bev = LIST_FIRST(&g->members); bev && bev != first; \
+                   bev = LIST_NEXT(bev, rate_limiting->next_in_group)) { \
                        block ;                                         \
                }                                                       \
        } while (0)
 
 static void
-_bev_group_unsuspend_reading(struct bufferevent_rate_limit_group *g)
+bev_group_unsuspend_reading_(struct bufferevent_rate_limit_group *g)
 {
        int again = 0;
        struct bufferevent_private *bev, *first;
 
        g->read_suspended = 0;
        FOREACH_RANDOM_ORDER({
-               if (EVLOCK_TRY_LOCK(bev->lock)) {
-                       bufferevent_unsuspend_read(&bev->bev,
+               if (EVLOCK_TRY_LOCK_(bev->lock)) {
+                       bufferevent_unsuspend_read_(&bev->bev,
                            BEV_SUSPEND_BW_GROUP);
                        EVLOCK_UNLOCK(bev->lock, 0);
                } else {
@@ -504,15 +504,15 @@ _bev_group_unsuspend_reading(struct bufferevent_rate_limit_group *g)
 }
 
 static void
-_bev_group_unsuspend_writing(struct bufferevent_rate_limit_group *g)
+bev_group_unsuspend_writing_(struct bufferevent_rate_limit_group *g)
 {
        int again = 0;
        struct bufferevent_private *bev, *first;
        g->write_suspended = 0;
 
        FOREACH_RANDOM_ORDER({
-               if (EVLOCK_TRY_LOCK(bev->lock)) {
-                       bufferevent_unsuspend_write(&bev->bev,
+               if (EVLOCK_TRY_LOCK_(bev->lock)) {
+                       bufferevent_unsuspend_write_(&bev->bev,
                            BEV_SUSPEND_BW_GROUP);
                        EVLOCK_UNLOCK(bev->lock, 0);
                } else {
@@ -526,7 +526,7 @@ _bev_group_unsuspend_writing(struct bufferevent_rate_limit_group *g)
     and unsuspend group members as needed.
  */
 static void
-_bev_group_refill_callback(evutil_socket_t fd, short what, void *arg)
+bev_group_refill_callback_(evutil_socket_t fd, short what, void *arg)
 {
        struct bufferevent_rate_limit_group *g = arg;
        unsigned tick;
@@ -536,16 +536,16 @@ _bev_group_refill_callback(evutil_socket_t fd, short what, void *arg)
 
        LOCK_GROUP(g);
 
-       tick = ev_token_bucket_get_tick(&now, &g->rate_limit_cfg);
-       ev_token_bucket_update(&g->rate_limit, &g->rate_limit_cfg, tick);
+       tick = ev_token_bucket_get_tick_(&now, &g->rate_limit_cfg);
+       ev_token_bucket_update_(&g->rate_limit, &g->rate_limit_cfg, tick);
 
        if (g->pending_unsuspend_read ||
            (g->read_suspended && (g->rate_limit.read_limit >= g->min_share))) {
-               _bev_group_unsuspend_reading(g);
+               bev_group_unsuspend_reading_(g);
        }
        if (g->pending_unsuspend_write ||
            (g->write_suspended && (g->rate_limit.write_limit >= g->min_share))){
-               _bev_group_unsuspend_writing(g);
+               bev_group_unsuspend_writing_(g);
        }
 
        /* XXXX Rather than waiting to the next tick to unsuspend stuff
@@ -575,8 +575,8 @@ bufferevent_set_rate_limit(struct bufferevent *bev,
                if (bevp->rate_limiting) {
                        rlim = bevp->rate_limiting;
                        rlim->cfg = NULL;
-                       bufferevent_unsuspend_read(bev, BEV_SUSPEND_BW);
-                       bufferevent_unsuspend_write(bev, BEV_SUSPEND_BW);
+                       bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
+                       bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
                        if (event_initialized(&rlim->refill_bucket_event))
                                event_del(&rlim->refill_bucket_event);
                }
@@ -585,7 +585,7 @@ bufferevent_set_rate_limit(struct bufferevent *bev,
        }
 
        event_base_gettimeofday_cached(bev->ev_base, &now);
-       tick = ev_token_bucket_get_tick(&now, cfg);
+       tick = ev_token_bucket_get_tick_(&now, cfg);
 
        if (bevp->rate_limiting && bevp->rate_limiting->cfg == cfg) {
                /* no-op */
@@ -603,25 +603,25 @@ bufferevent_set_rate_limit(struct bufferevent *bev,
        reinit = rlim->cfg != NULL;
 
        rlim->cfg = cfg;
-       ev_token_bucket_init(&rlim->limit, cfg, tick, reinit);
+       ev_token_bucket_init_(&rlim->limit, cfg, tick, reinit);
 
        if (reinit) {
                EVUTIL_ASSERT(event_initialized(&rlim->refill_bucket_event));
                event_del(&rlim->refill_bucket_event);
        }
        evtimer_assign(&rlim->refill_bucket_event, bev->ev_base,
-           _bev_refill_callback, bevp);
+           bev_refill_callback_, bevp);
 
        if (rlim->limit.read_limit > 0) {
-               bufferevent_unsuspend_read(bev, BEV_SUSPEND_BW);
+               bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
        } else {
-               bufferevent_suspend_read(bev, BEV_SUSPEND_BW);
+               bufferevent_suspend_read_(bev, BEV_SUSPEND_BW);
                suspended=1;
        }
        if (rlim->limit.write_limit > 0) {
-               bufferevent_unsuspend_write(bev, BEV_SUSPEND_BW);
+               bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
        } else {
-               bufferevent_suspend_write(bev, BEV_SUSPEND_BW);
+               bufferevent_suspend_write_(bev, BEV_SUSPEND_BW);
                suspended = 1;
        }
 
@@ -644,18 +644,18 @@ bufferevent_rate_limit_group_new(struct event_base *base,
        ev_uint32_t tick;
 
        event_base_gettimeofday_cached(base, &now);
-       tick = ev_token_bucket_get_tick(&now, cfg);
+       tick = ev_token_bucket_get_tick_(&now, cfg);
 
        g = mm_calloc(1, sizeof(struct bufferevent_rate_limit_group));
        if (!g)
                return NULL;
        memcpy(&g->rate_limit_cfg, cfg, sizeof(g->rate_limit_cfg));
-       TAILQ_INIT(&g->members);
+       LIST_INIT(&g->members);
 
-       ev_token_bucket_init(&g->rate_limit, cfg, tick, 0);
+       ev_token_bucket_init_(&g->rate_limit, cfg, tick, 0);
 
        event_assign(&g->master_refill_event, base, -1, EV_PERSIST,
-           _bev_group_refill_callback, g);
+           bev_group_refill_callback_, g);
        /*XXXX handle event_add failure */
        event_add(&g->master_refill_event, &cfg->tick_timeout);
 
@@ -663,6 +663,9 @@ bufferevent_rate_limit_group_new(struct event_base *base,
 
        bufferevent_rate_limit_group_set_min_share(g, 64);
 
+       evutil_weakrand_seed_(&g->weakrand_seed,
+           (ev_uint32_t) ((now.tv_sec + now.tv_usec) + (ev_intptr_t)g));
+
        return g;
 }
 
@@ -746,7 +749,7 @@ bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
                        return -1;
                }
                evtimer_assign(&rlim->refill_bucket_event, bev->ev_base,
-                   _bev_refill_callback, bevp);
+                   bev_refill_callback_, bevp);
                bevp->rate_limiting = rlim;
        }
 
@@ -760,7 +763,7 @@ bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
        LOCK_GROUP(g);
        bevp->rate_limiting->group = g;
        ++g->n_members;
-       TAILQ_INSERT_TAIL(&g->members, bevp, rate_limiting->next_in_group);
+       LIST_INSERT_HEAD(&g->members, bevp, rate_limiting->next_in_group);
 
        rsuspend = g->read_suspended;
        wsuspend = g->write_suspended;
@@ -768,9 +771,9 @@ bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
        UNLOCK_GROUP(g);
 
        if (rsuspend)
-               bufferevent_suspend_read(bev, BEV_SUSPEND_BW_GROUP);
+               bufferevent_suspend_read_(bev, BEV_SUSPEND_BW_GROUP);
        if (wsuspend)
-               bufferevent_suspend_write(bev, BEV_SUSPEND_BW_GROUP);
+               bufferevent_suspend_write_(bev, BEV_SUSPEND_BW_GROUP);
 
        BEV_UNLOCK(bev);
        return 0;
@@ -779,11 +782,11 @@ bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
 int
 bufferevent_remove_from_rate_limit_group(struct bufferevent *bev)
 {
-       return bufferevent_remove_from_rate_limit_group_internal(bev, 1);
+       return bufferevent_remove_from_rate_limit_group_internal_(bev, 1);
 }
 
 int
-bufferevent_remove_from_rate_limit_group_internal(struct bufferevent *bev,
+bufferevent_remove_from_rate_limit_group_internal_(struct bufferevent *bev,
     int unsuspend)
 {
        struct bufferevent_private *bevp =
@@ -795,12 +798,12 @@ bufferevent_remove_from_rate_limit_group_internal(struct bufferevent *bev,
                LOCK_GROUP(g);
                bevp->rate_limiting->group = NULL;
                --g->n_members;
-               TAILQ_REMOVE(&g->members, bevp, rate_limiting->next_in_group);
+               LIST_REMOVE(bevp, rate_limiting->next_in_group);
                UNLOCK_GROUP(g);
        }
        if (unsuspend) {
-               bufferevent_unsuspend_read(bev, BEV_SUSPEND_BW_GROUP);
-               bufferevent_unsuspend_write(bev, BEV_SUSPEND_BW_GROUP);
+               bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW_GROUP);
+               bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW_GROUP);
        }
        BEV_UNLOCK(bev);
        return 0;
@@ -814,7 +817,7 @@ bufferevent_remove_from_rate_limit_group_internal(struct bufferevent *bev,
  * === */
 
 /* Mostly you don't want to use this function from inside libevent;
- * _bufferevent_get_read_max() is more likely what you want*/
+ * bufferevent_get_read_max_() is more likely what you want*/
 ev_ssize_t
 bufferevent_get_read_limit(struct bufferevent *bev)
 {
@@ -833,7 +836,7 @@ bufferevent_get_read_limit(struct bufferevent *bev)
 }
 
 /* Mostly you don't want to use this function from inside libevent;
- * _bufferevent_get_write_max() is more likely what you want*/
+ * bufferevent_get_write_max_() is more likely what you want*/
 ev_ssize_t
 bufferevent_get_write_limit(struct bufferevent *bev)
 {
@@ -851,12 +854,62 @@ bufferevent_get_write_limit(struct bufferevent *bev)
        return r;
 }
 
+int
+bufferevent_set_max_single_read(struct bufferevent *bev, size_t size)
+{
+       struct bufferevent_private *bevp;
+       BEV_LOCK(bev);
+       bevp = BEV_UPCAST(bev);
+       if (size == 0 || size > EV_SSIZE_MAX)
+               bevp->max_single_read = MAX_SINGLE_READ_DEFAULT;
+       else
+               bevp->max_single_read = size;
+       BEV_UNLOCK(bev);
+       return 0;
+}
+
+int
+bufferevent_set_max_single_write(struct bufferevent *bev, size_t size)
+{
+       struct bufferevent_private *bevp;
+       BEV_LOCK(bev);
+       bevp = BEV_UPCAST(bev);
+       if (size == 0 || size > EV_SSIZE_MAX)
+               bevp->max_single_write = MAX_SINGLE_WRITE_DEFAULT;
+       else
+               bevp->max_single_write = size;
+       BEV_UNLOCK(bev);
+       return 0;
+}
+
+ev_ssize_t
+bufferevent_get_max_single_read(struct bufferevent *bev)
+{
+       ev_ssize_t r;
+
+       BEV_LOCK(bev);
+       r = BEV_UPCAST(bev)->max_single_read;
+       BEV_UNLOCK(bev);
+       return r;
+}
+
+ev_ssize_t
+bufferevent_get_max_single_write(struct bufferevent *bev)
+{
+       ev_ssize_t r;
+
+       BEV_LOCK(bev);
+       r = BEV_UPCAST(bev)->max_single_write;
+       BEV_UNLOCK(bev);
+       return r;
+}
+
 ev_ssize_t
 bufferevent_get_max_to_read(struct bufferevent *bev)
 {
        ev_ssize_t r;
        BEV_LOCK(bev);
-       r = _bufferevent_get_read_max(BEV_UPCAST(bev));
+       r = bufferevent_get_read_max_(BEV_UPCAST(bev));
        BEV_UNLOCK(bev);
        return r;
 }
@@ -866,14 +919,14 @@ bufferevent_get_max_to_write(struct bufferevent *bev)
 {
        ev_ssize_t r;
        BEV_LOCK(bev);
-       r = _bufferevent_get_write_max(BEV_UPCAST(bev));
+       r = bufferevent_get_write_max_(BEV_UPCAST(bev));
        BEV_UNLOCK(bev);
        return r;
 }
 
 
 /* Mostly you don't want to use this function from inside libevent;
- * _bufferevent_get_read_max() is more likely what you want*/
+ * bufferevent_get_read_max_() is more likely what you want*/
 ev_ssize_t
 bufferevent_rate_limit_group_get_read_limit(
        struct bufferevent_rate_limit_group *grp)
@@ -886,7 +939,7 @@ bufferevent_rate_limit_group_get_read_limit(
 }
 
 /* Mostly you don't want to use this function from inside libevent;
- * _bufferevent_get_write_max() is more likely what you want. */
+ * bufferevent_get_write_max_() is more likely what you want. */
 ev_ssize_t
 bufferevent_rate_limit_group_get_write_limit(
        struct bufferevent_rate_limit_group *grp)
@@ -911,14 +964,14 @@ bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr)
 
        new_limit = (bevp->rate_limiting->limit.read_limit -= decr);
        if (old_limit > 0 && new_limit <= 0) {
-               bufferevent_suspend_read(bev, BEV_SUSPEND_BW);
+               bufferevent_suspend_read_(bev, BEV_SUSPEND_BW);
                if (event_add(&bevp->rate_limiting->refill_bucket_event,
                        &bevp->rate_limiting->cfg->tick_timeout) < 0)
                        r = -1;
        } else if (old_limit <= 0 && new_limit > 0) {
                if (!(bevp->write_suspended & BEV_SUSPEND_BW))
                        event_del(&bevp->rate_limiting->refill_bucket_event);
-               bufferevent_unsuspend_read(bev, BEV_SUSPEND_BW);
+               bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
        }
 
        BEV_UNLOCK(bev);
@@ -940,14 +993,14 @@ bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr)
 
        new_limit = (bevp->rate_limiting->limit.write_limit -= decr);
        if (old_limit > 0 && new_limit <= 0) {
-               bufferevent_suspend_write(bev, BEV_SUSPEND_BW);
+               bufferevent_suspend_write_(bev, BEV_SUSPEND_BW);
                if (event_add(&bevp->rate_limiting->refill_bucket_event,
                        &bevp->rate_limiting->cfg->tick_timeout) < 0)
                        r = -1;
        } else if (old_limit <= 0 && new_limit > 0) {
                if (!(bevp->read_suspended & BEV_SUSPEND_BW))
                        event_del(&bevp->rate_limiting->refill_bucket_event);
-               bufferevent_unsuspend_write(bev, BEV_SUSPEND_BW);
+               bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
        }
 
        BEV_UNLOCK(bev);
@@ -965,9 +1018,9 @@ bufferevent_rate_limit_group_decrement_read(
        new_limit = (grp->rate_limit.read_limit -= decr);
 
        if (old_limit > 0 && new_limit <= 0) {
-               _bev_group_suspend_reading(grp);
+               bev_group_suspend_reading_(grp);
        } else if (old_limit <= 0 && new_limit > 0) {
-               _bev_group_unsuspend_reading(grp);
+               bev_group_unsuspend_reading_(grp);
        }
 
        UNLOCK_GROUP(grp);
@@ -985,9 +1038,9 @@ bufferevent_rate_limit_group_decrement_write(
        new_limit = (grp->rate_limit.write_limit -= decr);
 
        if (old_limit > 0 && new_limit <= 0) {
-               _bev_group_suspend_writing(grp);
+               bev_group_suspend_writing_(grp);
        } else if (old_limit <= 0 && new_limit > 0) {
-               _bev_group_unsuspend_writing(grp);
+               bev_group_unsuspend_writing_(grp);
        }
 
        UNLOCK_GROUP(grp);
@@ -1010,3 +1063,13 @@ bufferevent_rate_limit_group_reset_totals(struct bufferevent_rate_limit_group *g
 {
        grp->total_read = grp->total_written = 0;
 }
+
+int
+bufferevent_ratelim_init_(struct bufferevent_private *bev)
+{
+       bev->rate_limiting = NULL;
+       bev->max_single_read = MAX_SINGLE_READ_DEFAULT;
+       bev->max_single_write = MAX_SINGLE_WRITE_DEFAULT;
+
+       return 0;
+}
index a37e302af7747ff6ca1e01a13f392420b46a63e5..3f78215536334f2a438f4ff8f1632196bf22d108 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
  * All rights reserved.
  *
@@ -31,7 +31,7 @@
 
 #include <sys/types.h>
 
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_STDARG_H
+#ifdef EVENT__HAVE_STDARG_H
 #include <stdarg.h>
 #endif
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 
 #include <ws2tcpip.h>
 #endif
 
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
-#ifdef _EVENT_HAVE_NETINET_IN_H
+#ifdef EVENT__HAVE_NETINET_IN_H
 #include <netinet/in.h>
 #endif
-#ifdef _EVENT_HAVE_NETINET_IN6_H
+#ifdef EVENT__HAVE_NETINET_IN6_H
 #include <netinet/in6.h>
 #endif
 
@@ -97,7 +97,7 @@ const struct bufferevent_ops bufferevent_ops_socket = {
 };
 
 #define be_socket_add(ev, t)                   \
-       _bufferevent_add_event((ev), (t))
+       bufferevent_add_event_((ev), (t))
 
 static void
 bufferevent_socket_outbuf_cb(struct evbuffer *buf,
@@ -115,7 +115,7 @@ bufferevent_socket_outbuf_cb(struct evbuffer *buf,
                /* Somebody added data to the buffer, and we would like to
                 * write, and we were not writing.  So, start writing. */
                if (be_socket_add(&bufev->ev_write, &bufev->timeout_write) == -1) {
-                   // Should we log this?
+                   /* Should we log this? */
                }
        }
 }
@@ -131,7 +131,7 @@ bufferevent_readcb(evutil_socket_t fd, short event, void *arg)
        short what = BEV_EVENT_READING;
        ev_ssize_t howmuch = -1, readmax=-1;
 
-       _bufferevent_incref_and_lock(bufev);
+       bufferevent_incref_and_lock_(bufev);
 
        if (event == EV_TIMEOUT) {
                what |= BEV_EVENT_TIMEOUT;
@@ -152,7 +152,7 @@ bufferevent_readcb(evutil_socket_t fd, short event, void *arg)
                        goto done;
                }
        }
-       readmax = _bufferevent_get_read_max(bufev_p);
+       readmax = bufferevent_get_read_max_(bufev_p);
        if (howmuch < 0 || howmuch > readmax) /* The use of -1 for "unlimited"
                                               * uglifies this code. XXXX */
                howmuch = readmax;
@@ -177,11 +177,11 @@ bufferevent_readcb(evutil_socket_t fd, short event, void *arg)
        if (res <= 0)
                goto error;
 
-       _bufferevent_decrement_read_buckets(bufev_p, res);
+       bufferevent_decrement_read_buckets_(bufev_p, res);
 
        /* Invoke the user callback - must always be called last */
        if (evbuffer_get_length(input) >= bufev->wm_read.low)
-               _bufferevent_run_readcb(bufev);
+               bufferevent_run_readcb_(bufev);
 
        goto done;
 
@@ -190,10 +190,10 @@ bufferevent_readcb(evutil_socket_t fd, short event, void *arg)
 
  error:
        bufferevent_disable(bufev, EV_READ);
-       _bufferevent_run_eventcb(bufev, what);
+       bufferevent_run_eventcb_(bufev, what);
 
  done:
-       _bufferevent_decref_and_unlock(bufev);
+       bufferevent_decref_and_unlock_(bufev);
 }
 
 static void
@@ -207,14 +207,14 @@ bufferevent_writecb(evutil_socket_t fd, short event, void *arg)
        int connected = 0;
        ev_ssize_t atmost = -1;
 
-       _bufferevent_incref_and_lock(bufev);
+       bufferevent_incref_and_lock_(bufev);
 
        if (event == EV_TIMEOUT) {
                what |= BEV_EVENT_TIMEOUT;
                goto error;
        }
        if (bufev_p->connecting) {
-               int c = evutil_socket_finished_connecting(fd);
+               int c = evutil_socket_finished_connecting_(fd);
                /* we need to fake the error if the connection was refused
                 * immediately - usually connection to localhost on BSD */
                if (bufev_p->connection_refused) {
@@ -229,20 +229,20 @@ bufferevent_writecb(evutil_socket_t fd, short event, void *arg)
                if (c < 0) {
                        event_del(&bufev->ev_write);
                        event_del(&bufev->ev_read);
-                       _bufferevent_run_eventcb(bufev, BEV_EVENT_ERROR);
+                       bufferevent_run_eventcb_(bufev, BEV_EVENT_ERROR);
                        goto done;
                } else {
                        connected = 1;
 #ifdef _WIN32
                        if (BEV_IS_ASYNC(bufev)) {
                                event_del(&bufev->ev_write);
-                               bufferevent_async_set_connected(bufev);
-                               _bufferevent_run_eventcb(bufev,
+                               bufferevent_async_set_connected_(bufev);
+                               bufferevent_run_eventcb_(bufev,
                                                BEV_EVENT_CONNECTED);
                                goto done;
                        }
 #endif
-                       _bufferevent_run_eventcb(bufev,
+                       bufferevent_run_eventcb_(bufev,
                                        BEV_EVENT_CONNECTED);
                        if (!(bufev->enabled & EV_WRITE) ||
                            bufev_p->write_suspended) {
@@ -252,7 +252,7 @@ bufferevent_writecb(evutil_socket_t fd, short event, void *arg)
                }
        }
 
-       atmost = _bufferevent_get_write_max(bufev_p);
+       atmost = bufferevent_get_write_max_(bufev_p);
 
        if (bufev_p->write_suspended)
                goto done;
@@ -276,7 +276,7 @@ bufferevent_writecb(evutil_socket_t fd, short event, void *arg)
                if (res <= 0)
                        goto error;
 
-               _bufferevent_decrement_write_buckets(bufev_p, res);
+               bufferevent_decrement_write_buckets_(bufev_p, res);
        }
 
        if (evbuffer_get_length(bufev->output) == 0) {
@@ -289,7 +289,7 @@ bufferevent_writecb(evutil_socket_t fd, short event, void *arg)
         */
        if ((res || !connected) &&
            evbuffer_get_length(bufev->output) <= bufev->wm_write.low) {
-               _bufferevent_run_writecb(bufev);
+               bufferevent_run_writecb_(bufev);
        }
 
        goto done;
@@ -302,10 +302,10 @@ bufferevent_writecb(evutil_socket_t fd, short event, void *arg)
 
  error:
        bufferevent_disable(bufev, EV_WRITE);
-       _bufferevent_run_eventcb(bufev, what);
+       bufferevent_run_eventcb_(bufev, what);
 
  done:
-       _bufferevent_decref_and_unlock(bufev);
+       bufferevent_decref_and_unlock_(bufev);
 }
 
 struct bufferevent *
@@ -316,19 +316,20 @@ bufferevent_socket_new(struct event_base *base, evutil_socket_t fd,
        struct bufferevent *bufev;
 
 #ifdef _WIN32
-       if (base && event_base_get_iocp(base))
-               return bufferevent_async_new(base, fd, options);
+       if (base && event_base_get_iocp_(base))
+               return bufferevent_async_new_(base, fd, options);
 #endif
 
        if ((bufev_p = mm_calloc(1, sizeof(struct bufferevent_private)))== NULL)
                return NULL;
 
-       if (bufferevent_init_common(bufev_p, base, &bufferevent_ops_socket,
+       if (bufferevent_init_common_(bufev_p, base, &bufferevent_ops_socket,
                                    options) < 0) {
                mm_free(bufev_p);
                return NULL;
        }
        bufev = &bufev_p->bev;
+       evbuffer_set_flags(bufev->output, EVBUFFER_FLAG_DRAINS_TO_FD);
 
        event_assign(&bufev->ev_read, bufev->ev_base, fd,
            EV_READ|EV_PERSIST, bufferevent_readcb, bufev);
@@ -355,7 +356,7 @@ bufferevent_socket_connect(struct bufferevent *bev,
        int result=-1;
        int ownfd = 0;
 
-       _bufferevent_incref_and_lock(bev);
+       bufferevent_incref_and_lock_(bev);
 
        if (!bufev_p)
                goto done;
@@ -364,18 +365,17 @@ bufferevent_socket_connect(struct bufferevent *bev,
        if (fd < 0) {
                if (!sa)
                        goto done;
-               fd = socket(sa->sa_family, SOCK_STREAM, 0);
+               fd = evutil_socket_(sa->sa_family,
+                   SOCK_STREAM|EVUTIL_SOCK_NONBLOCK, 0);
                if (fd < 0)
                        goto done;
-               if (evutil_make_socket_nonblocking(fd)<0)
-                       goto done;
                ownfd = 1;
        }
        if (sa) {
 #ifdef _WIN32
-               if (bufferevent_async_can_connect(bev)) {
+               if (bufferevent_async_can_connect_(bev)) {
                        bufferevent_setfd(bev, fd);
-                       r = bufferevent_async_connect(bev, fd, sa, socklen);
+                       r = bufferevent_async_connect_(bev, fd, sa, socklen);
                        if (r < 0)
                                goto freesock;
                        bufev_p->connecting = 1;
@@ -383,7 +383,7 @@ bufferevent_socket_connect(struct bufferevent *bev,
                        goto done;
                } else
 #endif
-               r = evutil_socket_connect(&fd, sa, socklen);
+               r = evutil_socket_connect_(&fd, sa, socklen);
                if (r < 0)
                        goto freesock;
        }
@@ -419,12 +419,12 @@ bufferevent_socket_connect(struct bufferevent *bev,
        goto done;
 
 freesock:
-       _bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
+       bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR);
        if (ownfd)
                evutil_closesocket(fd);
        /* do something about the error? */
 done:
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
        return result;
 }
 
@@ -438,13 +438,13 @@ bufferevent_connect_getaddrinfo_cb(int result, struct evutil_addrinfo *ai,
        int r;
        BEV_LOCK(bev);
 
-       bufferevent_unsuspend_write(bev, BEV_SUSPEND_LOOKUP);
-       bufferevent_unsuspend_read(bev, BEV_SUSPEND_LOOKUP);
+       bufferevent_unsuspend_write_(bev, BEV_SUSPEND_LOOKUP);
+       bufferevent_unsuspend_read_(bev, BEV_SUSPEND_LOOKUP);
 
        if (result != 0) {
                bev_p->dns_error = result;
-               _bufferevent_run_eventcb(bev, BEV_EVENT_ERROR);
-               _bufferevent_decref_and_unlock(bev);
+               bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR);
+               bufferevent_decref_and_unlock_(bev);
                if (ai)
                        evutil_freeaddrinfo(ai);
                return;
@@ -454,7 +454,7 @@ bufferevent_connect_getaddrinfo_cb(int result, struct evutil_addrinfo *ai,
        /* XXX use this return value */
        r = bufferevent_socket_connect(bev, ai->ai_addr, (int)ai->ai_addrlen);
        (void)r;
-       _bufferevent_decref_and_unlock(bev);
+       bufferevent_decref_and_unlock_(bev);
        evutil_freeaddrinfo(ai);
 }
 
@@ -484,18 +484,18 @@ bufferevent_socket_connect_hostname(struct bufferevent *bev,
        hint.ai_protocol = IPPROTO_TCP;
        hint.ai_socktype = SOCK_STREAM;
 
-       bufferevent_suspend_write(bev, BEV_SUSPEND_LOOKUP);
-       bufferevent_suspend_read(bev, BEV_SUSPEND_LOOKUP);
+       bufferevent_suspend_write_(bev, BEV_SUSPEND_LOOKUP);
+       bufferevent_suspend_read_(bev, BEV_SUSPEND_LOOKUP);
 
-       bufferevent_incref(bev);
-       err = evutil_getaddrinfo_async(evdns_base, hostname, portbuf,
+       bufferevent_incref_(bev);
+       err = evutil_getaddrinfo_async_(evdns_base, hostname, portbuf,
            &hint, bufferevent_connect_getaddrinfo_cb, bev);
 
        if (err == 0) {
                return 0;
        } else {
-               bufferevent_unsuspend_write(bev, BEV_SUSPEND_LOOKUP);
-               bufferevent_unsuspend_read(bev, BEV_SUSPEND_LOOKUP);
+               bufferevent_unsuspend_write_(bev, BEV_SUSPEND_LOOKUP);
+               bufferevent_unsuspend_read_(bev, BEV_SUSPEND_LOOKUP);
                return -1;
        }
 }
index 2bcc228921456244438b22f7d436eba3e324485a..0ec2eeafffaf7556fb8c4679ecc41efdb224685a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _CHANGELIST_H_
-#define _CHANGELIST_H_
+#ifndef CHANGELIST_INTERNAL_H_INCLUDED_
+#define CHANGELIST_INTERNAL_H_INCLUDED_
 
 /*
   A "changelist" is a list of all the fd status changes that should be made
@@ -82,20 +82,20 @@ struct event_change {
 #define EVENT_CHANGELIST_FDINFO_SIZE sizeof(int)
 
 /** Set up the data fields in a changelist. */
-void event_changelist_init(struct event_changelist *changelist);
+void event_changelist_init_(struct event_changelist *changelist);
 /** Remove every change in the changelist, and make corresponding changes
  * in the event maps in the base.  This function is generally used right
  * after making all the changes in the changelist. */
-void event_changelist_remove_all(struct event_changelist *changelist,
+void event_changelist_remove_all_(struct event_changelist *changelist,
     struct event_base *base);
 /** Free all memory held in a changelist. */
-void event_changelist_freemem(struct event_changelist *changelist);
+void event_changelist_freemem_(struct event_changelist *changelist);
 
 /** Implementation of eventop_add that queues the event in a changelist. */
-int event_changelist_add(struct event_base *base, evutil_socket_t fd, short old, short events,
+int event_changelist_add_(struct event_base *base, evutil_socket_t fd, short old, short events,
     void *p);
 /** Implementation of eventop_del that queues the event in a changelist. */
-int event_changelist_del(struct event_base *base, evutil_socket_t fd, short old, short events,
+int event_changelist_del_(struct event_base *base, evutil_socket_t fd, short old, short events,
     void *p);
 
 #endif
index 6a9c581b634361592cb8f7257724bc8b08a4dec7..c387bdcf5049e8c2384fa27983d632fc550f2b85 100644 (file)
@@ -32,8 +32,8 @@
  *     @(#)queue.h     8.5 (Berkeley) 8/20/94
  */
 
-#ifndef        _SYS_QUEUE_H_
-#define        _SYS_QUEUE_H_
+#ifndef        SYS_QUEUE_H__
+#define        SYS_QUEUE_H__
 
 /*
  * This file defines five types of data structures: singly-linked lists,
@@ -485,4 +485,4 @@ struct {                                                            \
                (elm2)->field.cqe_prev->field.cqe_next = (elm2);        \
 } while (0)
 
-#endif /* !_SYS_QUEUE_H_ */
+#endif /* !SYS_QUEUE_H__ */
index 770c46fc71786b003fde99c0c02f2056575354f4..f1972bf633b13f0855b732f1dc2c706ba60c9291 100644 (file)
@@ -1,15 +1,20 @@
-dnl configure.in for libevent
-dnl Dug Song <dugsong@monkey.org>
+dnl Copyright 2000-2007 Niels Provos
+dnl Copyright 2007-2012 Niels Provos and Nick Mathewson
+dnl
+dnl See LICENSE for copying information.
+dnl
+dnl Original version Dug Song <dugsong@monkey.org>
+
 AC_PREREQ(2.59)
 AC_INIT(event.c)
 
 AC_CONFIG_MACRO_DIR([m4])
 
-AM_INIT_AUTOMAKE(libevent,2.1.0-alpha-dev)
+AM_INIT_AUTOMAKE(libevent,2.1.1-alpha-dev)
 dnl AM_SILENT_RULES req. automake 1.11.  [no] defaults V=1
 m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([no])])
 AM_CONFIG_HEADER(config.h  evconfig-private.h:evconfig-private.h.in)
-AC_DEFINE(NUMERIC_VERSION, 0x02010001, [Numeric representation of the version])
+AC_DEFINE(NUMERIC_VERSION, 0x02010101, [Numeric representation of the version])
 
 dnl Initialize prefix.
 if test "$prefix" = "NONE"; then
@@ -38,7 +43,6 @@ dnl the 'host' machine is where the resulting stuff runs.
 #esac
 
 dnl Checks for programs.
-AC_PROG_CC
 AM_PROG_CC_C_O
 AC_PROG_INSTALL
 AC_PROG_LN_S
@@ -46,12 +50,21 @@ AC_PROG_LN_S
 
 AC_PROG_GCC_TRADITIONAL
 
+# We need to test for at least gcc 2.95 here, because older versions don't
+# have -fno-strict-aliasing
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__GNUC__) || (__GNUC__ < 2) || (__GNUC__ == 2 && __GNUC_MINOR__ < 95)
+#error
+#endif])], have_gcc295=yes, have_gcc295=no)
+
 if test "$GCC" = "yes" ; then
         # Enable many gcc warnings by default...
         CFLAGS="$CFLAGS -Wall"
        # And disable the strict-aliasing optimization, since it breaks
        # our sockaddr-handling code in strange ways.
-       CFLAGS="$CFLAGS -fno-strict-aliasing"
+       if test x$have_gcc295 = xyes; then
+               CFLAGS="$CFLAGS -fno-strict-aliasing"
+       fi
 fi
 
 # OS X Lion started deprecating the system openssl. Let's just disable
@@ -64,7 +77,16 @@ case "$host_os" in
 esac
 
 AC_ARG_ENABLE(gcc-warnings,
-     AS_HELP_STRING(--enable-gcc-warnings, enable verbose warnings with GCC))
+     AS_HELP_STRING(--disable-gcc-warnings, disable verbose warnings with GCC))
+
+AC_ARG_ENABLE(gcc-hardening,
+     AS_HELP_STRING(--enable-gcc-hardening, enable compiler security checks),
+[if test x$enableval = xyes; then
+    CFLAGS="$CFLAGS -D_FORTIFY_SOURCE=2 -fstack-protector-all"
+    CFLAGS="$CFLAGS -fwrapv -fPIE -Wstack-protector"
+    CFLAGS="$CFLAGS --param ssp-buffer-size=1"
+fi])
+
 AC_ARG_ENABLE(thread-support,
      AS_HELP_STRING(--disable-thread-support, disable support for threading),
        [], [enable_thread_support=yes])
@@ -86,7 +108,7 @@ AC_ARG_ENABLE([libevent-regress],
 AC_ARG_ENABLE([function-sections],
      AS_HELP_STRING([--enable-function-sections, make static library allow smaller binaries with --gc-sections]),
        [], [enable_function_sections=no])
-AC_ARG_ENABLE(event-debugging,
+AC_ARG_ENABLE([verbose-debug],
                AS_HELP_STRING([--enable-verbose-debug, verbose debug logging]),
        [], [enable_verbose_debug=no])
 
@@ -162,12 +184,43 @@ else
 fi
 AC_SUBST(EV_LIB_WS32)
 AC_SUBST(EV_LIB_GDI)
+AC_SUBST(OPENSSL_LIBADD)
+
+AC_SYS_LARGEFILE
 
 LIBEVENT_OPENSSL
 
 dnl Checks for header files.
-AC_HEADER_STDC
-AC_CHECK_HEADERS([fcntl.h stdarg.h inttypes.h stdint.h stddef.h poll.h unistd.h sys/epoll.h sys/time.h sys/queue.h sys/event.h sys/param.h sys/ioctl.h sys/select.h sys/devpoll.h port.h netinet/in.h netinet/in6.h sys/socket.h sys/uio.h arpa/inet.h sys/eventfd.h sys/mman.h sys/sendfile.h sys/wait.h netdb.h])
+AC_CHECK_HEADERS([ \
+  arpa/inet.h \
+  fcntl.h \
+  ifaddrs.h \
+  mach/mach_time.h \
+  netdb.h \
+  netinet/in.h \
+  netinet/in6.h \
+  netinet/tcp.h \
+  poll.h \
+  port.h \
+  stdarg.h \
+  stddef.h \
+  sys/devpoll.h \
+  sys/epoll.h \
+  sys/event.h \
+  sys/eventfd.h \
+  sys/ioctl.h \
+  sys/mman.h \
+  sys/param.h \
+  sys/queue.h \
+  sys/resource.h \
+  sys/select.h \
+  sys/sendfile.h \
+  sys/socket.h \
+  sys/time.h \
+  sys/timerfd.h \
+  sys/uio.h \
+  sys/wait.h \
+])
 AC_CHECK_HEADERS(sys/sysctl.h, [], [], [
 #ifdef HAVE_SYS_PARAM_H
 #include <sys/param.h>
@@ -265,8 +318,46 @@ AC_C_INLINE
 AC_HEADER_TIME
 
 dnl Checks for library functions.
-AC_CHECK_FUNCS([gettimeofday vasprintf fcntl clock_gettime strtok_r strsep])
-AC_CHECK_FUNCS([getnameinfo strlcpy inet_ntop inet_pton signal sigaction strtoll inet_aton pipe eventfd sendfile mmap splice arc4random arc4random_buf issetugid geteuid getegid getprotobynumber setenv unsetenv putenv])
+AC_CHECK_FUNCS([ \
+  accept4 \
+  arc4random \
+  arc4random_buf \
+  clock_gettime \
+  eventfd \
+  epoll_create1 \
+  fcntl \
+  getegid \
+  geteuid \
+  getifaddrs \
+  getnameinfo \
+  getprotobynumber \
+  gettimeofday \
+  inet_aton \
+  inet_ntop \
+  inet_pton \
+  issetugid \
+  mach_absolute_time \
+  mmap \
+  nanosleep \
+  pipe \
+  pipe2 \
+  putenv \
+  sendfile \
+  setenv \
+  setrlimit \
+  sigaction \
+  signal \
+  splice \
+  strlcpy \
+  strsep \
+  strtok_r \
+  strtoll \
+  sysctl \
+  timerfd_create \
+  unsetenv \
+  usleep \
+  vasprintf \
+])
 
 AC_CACHE_CHECK(
     [for getaddrinfo],
@@ -349,8 +440,6 @@ AC_CHECK_FUNC(gethostbyname_r, [
 
 fi
 
-AC_CHECK_SIZEOF(long)
-
 AC_MSG_CHECKING(for F_SETFD in fcntl.h)
 AC_EGREP_CPP(yes,
 [
@@ -533,6 +622,7 @@ AC_CHECK_SIZEOF(int)
 AC_CHECK_SIZEOF(short)
 AC_CHECK_SIZEOF(size_t)
 AC_CHECK_SIZEOF(void *)
+AC_CHECK_SIZEOF(off_t)
 
 AC_CHECK_TYPES([struct in6_addr, struct sockaddr_in6, sa_family_t, struct addrinfo, struct sockaddr_storage], , ,
 [#define _GNU_SOURCE
@@ -655,7 +745,7 @@ AM_CONDITIONAL(OPENSSL, [test "$enable_openssl" != "no" && test "$have_openssl"
 
 # Add some more warnings which we use in development but not in the
 # released versions.  (Some relevant gcc versions can't handle these.)
-if test x$enable_gcc_warnings = xyes && test "$GCC" = "yes"; then
+if test x$enable_gcc_warnings != xno && test "$GCC" = "yes"; then
 
   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
 #if !defined(__GNUC__) || (__GNUC__ < 4)
@@ -677,12 +767,11 @@ if test x$enable_gcc_warnings = xyes && test "$GCC" = "yes"; then
 #error
 #endif])], have_clang=yes, have_clang=no)
 
-  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
-#if !defined(__clang__) || (__clang_major__ > 2) || (__clang_major__ == 2 && __clang_minor__ > 9)
-#error
-#endif])], have_clang29orlower=yes, have_clang29orlower=no)
+  CFLAGS="$CFLAGS -W -Wfloat-equal -Wundef -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes -Wwrite-strings -Wredundant-decls -Wchar-subscripts -Wcomment -Wformat -Wwrite-strings -Wmissing-declarations -Wredundant-decls -Wnested-externs -Wbad-function-cast -Wswitch-enum"
+  if test x$enable_gcc_warnings = xyes; then
+    CFLAGS="$CFLAGS -Werror"
+  fi
 
-  CFLAGS="$CFLAGS -W -Wfloat-equal -Wundef -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes -Wwrite-strings -Wredundant-decls -Wchar-subscripts -Wcomment -Wformat -Wwrite-strings -Wmissing-declarations -Wredundant-decls -Wnested-externs -Wbad-function-cast -Wswitch-enum -Werror"
   CFLAGS="$CFLAGS -Wno-unused-parameter -Wstrict-aliasing"
 
   if test x$have_gcc4 = xyes ; then
@@ -696,10 +785,8 @@ if test x$enable_gcc_warnings = xyes && test "$GCC" = "yes"; then
     CFLAGS="$CFLAGS -Waddress"
   fi
 
-  if test x$have_gcc42 = xyes && test x$have_clang29orlower = xno; then
+  if test x$have_gcc42 = xyes && test x$have_clang = xno; then
     # These warnings break gcc 4.0.2 and clang, but work on gcc 4.2
-    # We only disable these for clang 2.9 and lower, in case they are
-    # supported in later versions.
     CFLAGS="$CFLAGS -Wnormalized=id -Woverride-init"
   fi
 
index 68fe88514960c14731411646ad114ec9e0fd5a5b..114a9dc27ef0f8c21646655dbb2027c5db3ee855 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _DEFER_INTERNAL_H_
-#define _DEFER_INTERNAL_H_
+#ifndef DEFER_INTERNAL_H_INCLUDED_
+#define DEFER_INTERNAL_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -80,15 +80,15 @@ struct deferred_cb_queue {
    @param cb The function to run when the deferred_cb executes.
    @param arg The function's second argument.
  */
-void event_deferred_cb_init(struct deferred_cb *, deferred_cb_fn, void *);
+void event_deferred_cb_init_(struct deferred_cb *, deferred_cb_fn, void *);
 /**
    Cancel a deferred_cb if it is currently scheduled in an event_base.
  */
-void event_deferred_cb_cancel(struct deferred_cb_queue *, struct deferred_cb *);
+void event_deferred_cb_cancel_(struct deferred_cb_queue *, struct deferred_cb *);
 /**
    Activate a deferred_cb if it is not currently scheduled in an event_base.
  */
-void event_deferred_cb_schedule(struct deferred_cb_queue *, struct deferred_cb *);
+void event_deferred_cb_schedule_(struct deferred_cb_queue *, struct deferred_cb *);
 
 #define LOCK_DEFERRED_QUEUE(q)                                         \
        EVLOCK_LOCK((q)->lock, 0)
@@ -99,8 +99,8 @@ void event_deferred_cb_schedule(struct deferred_cb_queue *, struct deferred_cb *
 }
 #endif
 
-void event_deferred_cb_queue_init(struct deferred_cb_queue *);
-struct deferred_cb_queue *event_base_get_deferred_cb_queue(struct event_base *);
+void event_deferred_cb_queue_init_(struct deferred_cb_queue *);
+struct deferred_cb_queue *event_base_get_deferred_cb_queue_(struct event_base *);
 
-#endif /* _EVENT_INTERNAL_H_ */
+#endif /* EVENT_INTERNAL_H_INCLUDED_ */
 
index 2a6a0aa2b60f62fdd3f011d2c3b1bf45a5ad95eb..3a2f86d6f1aac4a740e4a4480e5c7b2bbb1403f5 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright 2000-2009 Niels Provos <provos@citi.umich.edu>
- * Copyright 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
+#ifdef EVENT__HAVE_DEVPOLL
+
 #include <sys/types.h>
 #include <sys/resource.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -130,7 +132,7 @@ devpoll_init(struct event_base *base)
                nfiles = rl.rlim_cur;
 
        /* Initialize the kernel queue */
-       if ((dpfd = open("/dev/poll", O_RDWR)) == -1) {
+       if ((dpfd = evutil_open_closeonexec_("/dev/poll", O_RDWR, 0)) == -1) {
                event_warn("open: /dev/poll");
                mm_free(devpollop);
                return (NULL);
@@ -157,7 +159,7 @@ devpoll_init(struct event_base *base)
                return (NULL);
        }
 
-       evsig_init(base);
+       evsig_init_(base);
 
        return (devpollop);
 }
@@ -215,7 +217,7 @@ devpoll_dispatch(struct event_base *base, struct timeval *tv)
                        continue;
 
                /* XXX(niels): not sure if this works for devpoll */
-               evmap_io_active(base, events[i].fd, which);
+               evmap_io_active_(base, events[i].fd, which);
        }
 
        return (0);
@@ -294,7 +296,7 @@ devpoll_dealloc(struct event_base *base)
 {
        struct devpollop *devpollop = base->evbase;
 
-       evsig_dealloc(base);
+       evsig_dealloc_(base);
        if (devpollop->events)
                mm_free(devpollop->events);
        if (devpollop->changes)
@@ -305,3 +307,5 @@ devpoll_dealloc(struct event_base *base)
        memset(devpollop, 0, sizeof(struct devpollop));
        mm_free(devpollop);
 }
+
+#endif /* EVENT__HAVE_DEVPOLL */
index 7253358bf81c6c25b68f7242520e994a892d7646..edd4e18b480a4e3bb4ba499edea36f6763d6aa46 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos, Nick Mathewson
+ * Copyright 2007-2012 Niels Provos, Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
+#ifdef EVENT__HAVE_EPOLL
+
 #include <stdint.h>
 #include <sys/types.h>
 #include <sys/resource.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
 #include <string.h>
 #include <unistd.h>
 #include <errno.h>
-#ifdef _EVENT_HAVE_FCNTL_H
+#ifdef EVENT__HAVE_FCNTL_H
 #include <fcntl.h>
 #endif
+#ifdef EVENT__HAVE_SYS_TIMERFD_H
+#include <sys/timerfd.h>
+#endif
 
 #include "event-internal.h"
 #include "evsignal-internal.h"
 #include "log-internal.h"
 #include "evmap-internal.h"
 #include "changelist-internal.h"
+#include "time-internal.h"
+
+#if defined(EVENT__HAVE_SYS_TIMERFD_H) &&                        \
+       defined(EVENT__HAVE_TIMERFD_CREATE) &&                    \
+       defined(HAVE_POSIX_MONOTONIC) && defined(TFD_NONBLOCK) && \
+       defined(TFD_CLOEXEC)
+/* Note that we only use timerfd if TFD_NONBLOCK and TFD_CLOEXEC are available
+   and working.  This means that we can't support it on 2.6.25 (where timerfd
+   was introduced) or 2.6.26, since 2.6.27 introduced those flags.
+ */
+#define USING_TIMERFD
+#endif
 
 struct epollop {
        struct epoll_event *events;
        int nevents;
        int epfd;
+#ifdef USING_TIMERFD
+       int timerfd;
+#endif
 };
 
 static void *epoll_init(struct event_base *);
@@ -67,8 +87,8 @@ static void epoll_dealloc(struct event_base *);
 static const struct eventop epollops_changelist = {
        "epoll (with changelist)",
        epoll_init,
-       event_changelist_add,
-       event_changelist_del,
+       event_changelist_add_,
+       event_changelist_del_,
        epoll_dispatch,
        epoll_dealloc,
        1, /* need reinit */
@@ -108,21 +128,28 @@ const struct eventop epollops = {
 static void *
 epoll_init(struct event_base *base)
 {
-       int epfd;
+       int epfd = -1;
        struct epollop *epollop;
 
-       /* Initialize the kernel queue.  (The size field is ignored since
-        * 2.6.8.) */
-       if ((epfd = epoll_create(32000)) == -1) {
-               if (errno != ENOSYS)
-                       event_warn("epoll_create");
-               return (NULL);
+#ifdef EVENT__HAVE_EPOLL_CREATE1
+       /* First, try the shiny new epoll_create1 interface, if we have it. */
+       epfd = epoll_create1(EPOLL_CLOEXEC);
+#endif
+       if (epfd == -1) {
+               /* Initialize the kernel queue using the old interface.  (The
+               size field is ignored   since 2.6.8.) */
+               if ((epfd = epoll_create(32000)) == -1) {
+                       if (errno != ENOSYS)
+                               event_warn("epoll_create");
+                       return (NULL);
+               }
+               evutil_make_socket_closeonexec(epfd);
        }
 
-       evutil_make_socket_closeonexec(epfd);
-
-       if (!(epollop = mm_calloc(1, sizeof(struct epollop))))
+       if (!(epollop = mm_calloc(1, sizeof(struct epollop)))) {
+               close(epfd);
                return (NULL);
+       }
 
        epollop->epfd = epfd;
 
@@ -130,16 +157,47 @@ epoll_init(struct event_base *base)
        epollop->events = mm_calloc(INITIAL_NEVENT, sizeof(struct epoll_event));
        if (epollop->events == NULL) {
                mm_free(epollop);
+               close(epfd);
                return (NULL);
        }
        epollop->nevents = INITIAL_NEVENT;
 
        if ((base->flags & EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST) != 0 ||
            ((base->flags & EVENT_BASE_FLAG_IGNORE_ENV) == 0 &&
-               evutil_getenv("EVENT_EPOLL_USE_CHANGELIST") != NULL))
+               evutil_getenv_("EVENT_EPOLL_USE_CHANGELIST") != NULL)) {
+
                base->evsel = &epollops_changelist;
+       }
 
-       evsig_init(base);
+#ifdef USING_TIMERFD
+       /*
+         The epoll interface ordinarily gives us one-millisecond precision,
+         so on Linux it makes perfect sense to use the CLOCK_MONOTONIC_COARSE
+         timer.  But when the user has set the new PRECISE_TIMER flag for an
+         event_base, we can try to use timerfd to give them finer granularity.
+       */
+       if ((base->flags & EVENT_BASE_FLAG_PRECISE_TIMER) &&
+           base->monotonic_timer.monotonic_clock == CLOCK_MONOTONIC) {
+               int fd;
+               fd = epollop->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
+               if (epollop->timerfd >= 0) {
+                       struct epoll_event epev;
+                       epev.data.fd = epollop->timerfd;
+                       epev.events = EPOLLIN;
+                       if (epoll_ctl(epollop->epfd, EPOLL_CTL_ADD, fd, &epev) < 0) {
+                               event_warn("epoll_ctl(timerfd)");
+                               close(fd);
+                               epollop->timerfd = -1;
+                       }
+               } else {
+                       event_warn("timerfd_create");
+               }
+       } else {
+               epollop->timerfd = -1;
+       }
+#endif
+
+       evsig_init_(base);
 
        return (epollop);
 }
@@ -498,8 +556,35 @@ epoll_dispatch(struct event_base *base, struct timeval *tv)
        int i, res;
        long timeout = -1;
 
+#ifdef USING_TIMERFD
+       if (epollop->timerfd >= 0) {
+               struct itimerspec is;
+               is.it_interval.tv_sec = 0;
+               is.it_interval.tv_nsec = 0;
+               if (tv == NULL) {
+                       /* No timeout; disarm the timer. */
+                       is.it_value.tv_sec = 0;
+                       is.it_value.tv_nsec = 0;
+               } else {
+                       if (tv->tv_sec == 0 && tv->tv_usec == 0) {
+                               /* we need to exit immediately; timerfd can't
+                                * do that. */
+                               timeout = 0;
+                       }
+                       is.it_value.tv_sec = tv->tv_sec;
+                       is.it_value.tv_nsec = tv->tv_usec * 1000;
+               }
+               /* TODO: we could avoid unnecessary syscalls here by only
+                  calling timerfd_settime when the top timeout changes, or
+                  when we're called with a different timeval.
+               */
+               if (timerfd_settime(epollop->timerfd, 0, &is, NULL) < 0) {
+                       event_warn("timerfd_settime");
+               }
+       } else
+#endif
        if (tv != NULL) {
-               timeout = evutil_tv_to_msec(tv);
+               timeout = evutil_tv_to_msec_(tv);
                if (timeout < 0 || timeout > MAX_EPOLL_TIMEOUT_MSEC) {
                        /* Linux kernels can wait forever if the timeout is
                         * too big; see comment on MAX_EPOLL_TIMEOUT_MSEC. */
@@ -508,7 +593,7 @@ epoll_dispatch(struct event_base *base, struct timeval *tv)
        }
 
        epoll_apply_changes(base);
-       event_changelist_remove_all(&base->changelist, base);
+       event_changelist_remove_all_(&base->changelist, base);
 
        EVBASE_RELEASE_LOCK(base, th_base_lock);
 
@@ -531,6 +616,10 @@ epoll_dispatch(struct event_base *base, struct timeval *tv)
        for (i = 0; i < res; i++) {
                int what = events[i].events;
                short ev = 0;
+#ifdef USING_TIMERFD
+               if (events[i].data.fd == epollop->timerfd)
+                       continue;
+#endif
 
                if (what & (EPOLLHUP|EPOLLERR)) {
                        ev = EV_READ | EV_WRITE;
@@ -544,7 +633,7 @@ epoll_dispatch(struct event_base *base, struct timeval *tv)
                if (!ev)
                        continue;
 
-               evmap_io_active(base, events[i].data.fd, ev | EV_ET);
+               evmap_io_active_(base, events[i].data.fd, ev | EV_ET);
        }
 
        if (res == epollop->nevents && epollop->nevents < MAX_NEVENT) {
@@ -570,12 +659,18 @@ epoll_dealloc(struct event_base *base)
 {
        struct epollop *epollop = base->evbase;
 
-       evsig_dealloc(base);
+       evsig_dealloc_(base);
        if (epollop->events)
                mm_free(epollop->events);
        if (epollop->epfd >= 0)
                close(epollop->epfd);
+#ifdef USING_TIMERFD
+       if (epollop->timerfd >= 0)
+               close(epollop->timerfd);
+#endif
 
        memset(epollop, 0, sizeof(struct epollop));
        mm_free(epollop);
 }
+
+#endif /* EVENT__HAVE_EPOLL */
index 57599362d7747fa76afeadaf4ba4a694e96c2f69..af35daa7f22c063b63ac622079828bf58b029580 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright 2003-2009 Niels Provos <provos@citi.umich.edu>
- * Copyright 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
index 0a146910a77ecc163ee6d07b5a23f5c4f02a9d1a..480c35a3d7bce002e926fc4368da192b3d87e408 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVBUFFER_INTERNAL_H_
-#define _EVBUFFER_INTERNAL_H_
+#ifndef EVBUFFER_INTERNAL_H_INCLUDED_
+#define EVBUFFER_INTERNAL_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -50,7 +50,7 @@ extern "C" {
 /* Minimum allocation for a chain.  We define this so that we're burning no
  * more than 5% of each allocation on overhead.  It would be nice to lose even
  * less space, though. */
-#if _EVENT_SIZEOF_VOID_P < 8
+#if EVENT__SIZEOF_VOID_P < 8
 #define MIN_BUFFER_SIZE        512
 #else
 #define MIN_BUFFER_SIZE        1024
@@ -60,7 +60,7 @@ extern "C" {
  * when bytes are added to or removed from the evbuffer. */
 struct evbuffer_cb_entry {
        /** Structures to implement a doubly-linked queue of callbacks */
-       TAILQ_ENTRY(evbuffer_cb_entry) next;
+       LIST_ENTRY(evbuffer_cb_entry) next;
        /** The callback function to invoke when this callback is called.
            If EVBUFFER_CB_OBSOLETE is set in flags, the cb_obsolete field is
            valid; otherwise, cb_func is valid. */
@@ -107,7 +107,7 @@ struct evbuffer {
         * tried to invoke callbacks. */
        size_t n_del_for_cb;
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        /** A lock used to mediate access to this buffer. */
        void *lock;
 #endif
@@ -130,6 +130,8 @@ struct evbuffer {
        /** True iff this buffer is set up for overlapped IO. */
        unsigned is_overlapped : 1;
 #endif
+       /** Zero or more EVBUFFER_FLAG_* bits */
+       ev_uint32_t flags;
 
        /** Used to implement deferred callbacks. */
        struct deferred_cb_queue *cb_queue;
@@ -145,7 +147,7 @@ struct evbuffer {
        struct deferred_cb deferred;
 
        /** A doubly-linked-list of callback functions */
-       TAILQ_HEAD(evbuffer_cb_queue, evbuffer_cb_entry) callbacks;
+       LIST_HEAD(evbuffer_cb_queue, evbuffer_cb_entry) callbacks;
 
        /** The parent bufferevent object this evbuffer belongs to.
         * NULL if the evbuffer stands alone. */
@@ -183,6 +185,11 @@ struct evbuffer_chain {
        /** a chain that should be freed, but can't be freed until it is
         * un-pinned. */
 #define EVBUFFER_DANGLING      0x0040
+       /** a chain that is a referenced copy of another chain */
+#define EVBUFFER_MULTICAST     0x0080
+
+       /** number of references to this chain */
+       int refcnt;
 
        /** Usually points to the read-write memory belonging to this
         * buffer allocated as part of the evbuffer_chain allocation.
@@ -218,7 +225,8 @@ struct evbuffer_file_segment {
        unsigned flags; /**< combination of EVBUF_FS_* flags  */
 
        /** What kind of file segment is this? */
-       enum {EVBUF_FS_MMAP, EVBUF_FS_SENDFILE, EVBUF_FS_IO} type;
+       unsigned can_sendfile : 1;
+       unsigned is_mapping : 1;
 
        /** The fd that we read the data from. */
        int fd;
@@ -231,15 +239,24 @@ struct evbuffer_file_segment {
        /** If we're using mmap or IO, this is the content of the file
         * segment. */
        char *contents;
+       /** Position of this segment within the file. */
+       ev_off_t file_offset;
        /** If we're using mmap, this is the offset within 'mapping' where
-        * this data segment begins.  If we're using sendfile, this is the
-        * offset within the file where this data begins.  If we're using IO,
-        * this is 0. */
-       ev_off_t offset;
+        * this data segment begins. */
+       ev_off_t mmap_offset;
        /** The length of this segment. */
        ev_off_t length;
 };
 
+/** Information about the multicast parent of a chain.  Lives at the
+ * end of an evbuffer_chain with the EVBUFFER_MULTICAST flag set.  */
+struct evbuffer_multicast_parent {
+       /** source buffer the multicast parent belongs to */
+       struct evbuffer *source;
+       /** multicast parent for this chain */
+       struct evbuffer_chain *parent;
+};
+
 #define EVBUFFER_CHAIN_SIZE sizeof(struct evbuffer_chain)
 /** Return a pointer to extra data allocated along with an evbuffer. */
 #define EVBUFFER_CHAIN_EXTRA(t, c) (t *)((struct evbuffer_chain *)(c) + 1)
@@ -266,21 +283,21 @@ struct evbuffer_file_segment {
        } while (0)
 
 /** Increase the reference count of buf by one. */
-void _evbuffer_incref(struct evbuffer *buf);
+void evbuffer_incref_(struct evbuffer *buf);
 /** Increase the reference count of buf by one and acquire the lock. */
-void _evbuffer_incref_and_lock(struct evbuffer *buf);
+void evbuffer_incref_and_lock_(struct evbuffer *buf);
 /** Pin a single buffer chain using a given flag. A pinned chunk may not be
  * moved or freed until it is unpinned. */
-void _evbuffer_chain_pin(struct evbuffer_chain *chain, unsigned flag);
+void evbuffer_chain_pin_(struct evbuffer_chain *chain, unsigned flag);
 /** Unpin a single buffer chain using a given flag. */
-void _evbuffer_chain_unpin(struct evbuffer_chain *chain, unsigned flag);
+void evbuffer_chain_unpin_(struct evbuffer_chain *chain, unsigned flag);
 /** As evbuffer_free, but requires that we hold a lock on the buffer, and
  * releases the lock before freeing it and the buffer. */
-void _evbuffer_decref_and_unlock(struct evbuffer *buffer);
+void evbuffer_decref_and_unlock_(struct evbuffer *buffer);
 
 /** As evbuffer_expand, but does not guarantee that the newly allocated memory
  * is contiguous.  Instead, it may be split across two or more chunks. */
-int _evbuffer_expand_fast(struct evbuffer *, size_t, int);
+int evbuffer_expand_fast_(struct evbuffer *, size_t, int);
 
 /** Helper: prepares for a readv/WSARecv call by expanding the buffer to
  * hold enough memory to read 'howmuch' bytes in possibly noncontiguous memory.
@@ -288,7 +305,7 @@ int _evbuffer_expand_fast(struct evbuffer *, size_t, int);
  * extent, and *chainp to point to the first chain that we'll try to read into.
  * Returns the number of vecs used.
  */
-int _evbuffer_read_setup_vecs(struct evbuffer *buf, ev_ssize_t howmuch,
+int evbuffer_read_setup_vecs_(struct evbuffer *buf, ev_ssize_t howmuch,
     struct evbuffer_iovec *vecs, int n_vecs, struct evbuffer_chain ***chainp,
     int exact);
 
@@ -301,12 +318,12 @@ int _evbuffer_read_setup_vecs(struct evbuffer *buf, ev_ssize_t howmuch,
  * See note in buffer_iocp's launch_write function */
 
 /** Set the parent bufferevent object for buf to bev */
-void evbuffer_set_parent(struct evbuffer *buf, struct bufferevent *bev);
+void evbuffer_set_parent_(struct evbuffer *buf, struct bufferevent *bev);
 
-void evbuffer_invoke_callbacks(struct evbuffer *buf);
+void evbuffer_invoke_callbacks_(struct evbuffer *buf);
 
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* _EVBUFFER_INTERNAL_H_ */
+#endif /* EVBUFFER_INTERNAL_H_INCLUDED_ */
index cffdf53103412c855c146ff874113ed248b19d58..7b3dfdb10e90ae5fbd166d51036929fb3ca06626 100644 (file)
@@ -1,7 +1,7 @@
 /* evconfig-private.h template - see "Configuration Header Templates" */
 /* in AC manual.  Kevin Bowling <kevin.bowling@kev009.com */
-#ifndef _EVENT_EVCONFIG__PRIVATE_H
-#define _EVENT_EVCONFIG__PRIVATE_H
+#ifndef EVCONFIG_PRIVATE_H_INCLUDED_
+#define EVCONFIG_PRIVATE_H_INCLUDED_
 
 /* Enable extensions on AIX 3, Interix.  */
 #ifndef _ALL_SOURCE
 # undef __EXTENSIONS__
 #endif
 
+/* Number of bits in a file offset, on hosts where this is settable. */
+#undef _FILE_OFFSET_BITS
+/* Define for large files, on AIX-style hosts. */
+#undef _LARGE_FILES
+
 /* Define to 1 if on MINIX. */
 #ifndef _MINIX
 #undef _MINIX
index 9094f8442b53cdcbf920d7a60defca3b4bf2377d..41d8b6b2369e4a4d45e9fa0b0edbcfb0306262ec 100644 (file)
@@ -1,18 +1,32 @@
-/* $Id: evdns.c 6979 2006-08-04 18:31:13Z nickm $ */
-
-/* The original version of this module was written by Adam Langley; for
- * a history of modifications, check out the subversion logs.
+/* Copyright 2006-2007 Niels Provos
+ * Copyright 2007-2012 Nick Mathewson and Niels Provos
  *
- * When editing this module, try to keep it re-mergeable by Adam.  Don't
- * reformat the whitespace, add Tor dependencies, or so on.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
  *
- * TODO:
- *   - Support IPv6 and PTR records.
- *   - Replace all externally visible magic numbers with #defined constants.
- *   - Write documentation for APIs of all external functions.
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-/* Async DNS Library
+/* Based on software by Adam Langly. Adam's original message:
+ *
+ * Async DNS Library
  * Adam Langley <agl@imperialviolet.org>
  * http://www.imperialviolet.org/eventdns.html
  * Public Domain code
 
 #include <string.h>
 #include <fcntl.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#ifdef _EVENT_HAVE_STDINT_H
+#ifdef EVENT__HAVE_STDINT_H
 #include <stdint.h>
 #endif
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #include <limits.h>
 #include <arpa/inet.h>
 #endif
 
-#ifdef _EVENT_HAVE_NETINET_IN6_H
+#ifdef EVENT__HAVE_NETINET_IN6_H
 #include <netinet/in6.h>
 #endif
 
 #define TYPE_A        EVDNS_TYPE_A
 #define TYPE_CNAME     5
 #define TYPE_PTR       EVDNS_TYPE_PTR
+#define TYPE_SOA       EVDNS_TYPE_SOA
 #define TYPE_AAAA      EVDNS_TYPE_AAAA
 
 #define CLASS_INET     EVDNS_CLASS_INET
@@ -168,6 +183,7 @@ struct request {
        struct nameserver *ns;  /* the server which we last sent it */
 
        /* these objects are kept in a circular list */
+       /* XXX We could turn this into a CIRCLEQ. */
        struct request *next, *prev;
 
        struct event timeout_event;
@@ -237,7 +253,7 @@ struct evdns_server_port {
        struct server_request *pending_replies;
        struct event_base *event_base;
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        void *lock;
 #endif
 };
@@ -339,7 +355,7 @@ struct evdns_base {
 
        TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        void *lock;
 #endif
 };
@@ -397,10 +413,10 @@ static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_request
 
 static int strtoint(const char *const str);
 
-#ifdef _EVENT_DISABLE_THREAD_SUPPORT
-#define EVDNS_LOCK(base)  _EVUTIL_NIL_STMT
-#define EVDNS_UNLOCK(base) _EVUTIL_NIL_STMT
-#define ASSERT_LOCKED(base) _EVUTIL_NIL_STMT
+#ifdef EVENT__DISABLE_THREAD_SUPPORT
+#define EVDNS_LOCK(base)  EVUTIL_NIL_STMT_
+#define EVDNS_UNLOCK(base) EVUTIL_NIL_STMT_
+#define ASSERT_LOCKED(base) EVUTIL_NIL_STMT_
 #else
 #define EVDNS_LOCK(base)                       \
        EVLOCK_LOCK((base)->lock, 0)
@@ -435,9 +451,9 @@ evdns_set_log_fn(evdns_debug_log_fn_type fn)
 #define EVDNS_LOG_CHECK
 #endif
 
-static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
+static void evdns_log_(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
 static void
-_evdns_log(int warn, const char *fmt, ...)
+evdns_log_(int warn, const char *fmt, ...)
 {
        va_list args;
        char buf[512];
@@ -456,7 +472,7 @@ _evdns_log(int warn, const char *fmt, ...)
 
 }
 
-#define log _evdns_log
+#define log evdns_log_
 
 /* This walks the list of inflight requests to find the */
 /* one with a matching transaction id. Returns NULL on */
@@ -531,7 +547,7 @@ nameserver_probe_failed(struct nameserver *const ns) {
                char addrbuf[128];
                log(EVDNS_LOG_WARN,
                    "Error from libevent when adding timer event for %s",
-                   evutil_format_sockaddr_port(
+                   evutil_format_sockaddr_port_(
                            (struct sockaddr *)&ns->address,
                            addrbuf, sizeof(addrbuf)));
        }
@@ -552,7 +568,7 @@ nameserver_failed(struct nameserver *const ns, const char *msg) {
        if (!ns->state) return;
 
        log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
-           evutil_format_sockaddr_port(
+           evutil_format_sockaddr_port_(
                    (struct sockaddr *)&ns->address,
                    addrbuf, sizeof(addrbuf)),
            msg);
@@ -570,7 +586,7 @@ nameserver_failed(struct nameserver *const ns, const char *msg) {
                &base->global_nameserver_probe_initial_timeout) < 0) {
                log(EVDNS_LOG_WARN,
                    "Error from libevent when adding timer event for %s",
-                   evutil_format_sockaddr_port(
+                   evutil_format_sockaddr_port_(
                            (struct sockaddr *)&ns->address,
                            addrbuf, sizeof(addrbuf)));
                /* ???? Do more? */
@@ -606,7 +622,7 @@ nameserver_up(struct nameserver *const ns)
        ASSERT_LOCKED(ns->base);
        if (ns->state) return;
        log(EVDNS_LOG_MSG, "Nameserver %s is back up",
-           evutil_format_sockaddr_port(
+           evutil_format_sockaddr_port_(
                    (struct sockaddr *)&ns->address,
                    addrbuf, sizeof(addrbuf)));
        evtimer_del(&ns->timeout_event);
@@ -762,7 +778,7 @@ reply_run_callback(struct deferred_cb *d, void *user_pointer)
                            cb->reply.data.a.addresses,
                            user_pointer);
                else
-                       cb->user_callback(cb->err, 0, 0, 0, NULL, user_pointer);
+                       cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
                break;
        case TYPE_PTR:
                if (cb->have_reply) {
@@ -770,7 +786,7 @@ reply_run_callback(struct deferred_cb *d, void *user_pointer)
                        cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
                            &name, user_pointer);
                } else {
-                       cb->user_callback(cb->err, 0, 0, 0, NULL, user_pointer);
+                       cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
                }
                break;
        case TYPE_AAAA:
@@ -780,7 +796,7 @@ reply_run_callback(struct deferred_cb *d, void *user_pointer)
                            cb->reply.data.aaaa.addresses,
                            user_pointer);
                else
-                       cb->user_callback(cb->err, 0, 0, 0, NULL, user_pointer);
+                       cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
                break;
        default:
                EVUTIL_ASSERT(0);
@@ -820,10 +836,10 @@ reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct repl
                d->handle = req->handle;
        }
 
-       event_deferred_cb_init(&d->deferred, reply_run_callback,
+       event_deferred_cb_init_(&d->deferred, reply_run_callback,
            req->user_pointer);
-       event_deferred_cb_schedule(
-               event_base_get_deferred_cb_queue(req->base->event_base),
+       event_deferred_cb_schedule_(
+               event_base_get_deferred_cb_queue_(req->base->event_base),
                &d->deferred);
 }
 
@@ -844,13 +860,17 @@ reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply)
                /* there was an error */
                if (flags & 0x0200) {
                        error = DNS_ERR_TRUNCATED;
-               } else {
+               } else if (flags & 0x000f) {
                        u16 error_code = (flags & 0x000f) - 1;
                        if (error_code > 4) {
                                error = DNS_ERR_UNKNOWN;
                        } else {
                                error = error_codes[error_code];
                        }
+               } else if (reply && !reply->have_answer) {
+                       error = DNS_ERR_NODATA;
+               } else {
+                       error = DNS_ERR_UNKNOWN;
                }
 
                switch (error) {
@@ -873,12 +893,17 @@ reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply)
                         */
                        log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
                                "at %s; will allow the request to time out.",
-                           evutil_format_sockaddr_port(
+                           evutil_format_sockaddr_port_(
                                    (struct sockaddr *)&req->ns->address,
                                    addrbuf, sizeof(addrbuf)));
                        break;
                default:
-                       /* we got a good reply from the nameserver */
+                       /* we got a good reply from the nameserver: it is up. */
+                       if (req->handle == req->ns->probe_request) {
+                               /* Avoid double-free */
+                               req->ns->probe_request = NULL;
+                       }
+
                        nameserver_up(req->ns);
                }
 
@@ -897,7 +922,7 @@ reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply)
                }
 
                /* all else failed. Pass the failure up */
-               reply_schedule_callback(req, 0, error, NULL);
+               reply_schedule_callback(req, ttl, error, NULL);
                request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
        } else {
                /* all ok, tell the user */
@@ -914,8 +939,8 @@ name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
        int name_end = -1;
        int j = *idx;
        int ptr_count = 0;
-#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while (0)
-#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while (0)
+#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
+#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
 
        char *cp = name_out;
@@ -969,8 +994,8 @@ name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
 static int
 reply_parse(struct evdns_base *base, u8 *packet, int length) {
        int j = 0, k = 0;  /* index into packet */
-       u16 _t;  /* used by the macros */
-       u32 _t32;  /* used by the macros */
+       u16 t_;  /* used by the macros */
+       u32 t32_;  /* used by the macros */
        char tmp_name[256], cmp_name[256]; /* used by the macros */
        int name_matches = 0;
 
@@ -1000,8 +1025,8 @@ reply_parse(struct evdns_base *base, u8 *packet, int length) {
 
        /* If it's not an answer, it doesn't correspond to any request. */
        if (!(flags & 0x8000)) return -1;  /* must be an answer */
-       if (flags & 0x020f) {
-               /* there was an error */
+       if ((flags & 0x020f) && (flags & 0x020f) != DNS_ERR_NOTEXIST) {
+               /* there was an error and it's not NXDOMAIN */
                goto err;
        }
        /* if (!answers) return; */  /* must have an answer of some form */
@@ -1041,7 +1066,7 @@ reply_parse(struct evdns_base *base, u8 *packet, int length) {
                 */
                TEST_NAME;
                j += 4;
-               if (j >= length) goto err;
+               if (j > length) goto err;
        }
 
        if (!name_matches)
@@ -1123,6 +1148,39 @@ reply_parse(struct evdns_base *base, u8 *packet, int length) {
                }
        }
 
+       if (!reply.have_answer) {
+               for (i = 0; i < authority; ++i) {
+                       u16 type, class;
+                       SKIP_NAME;
+                       GET16(type);
+                       GET16(class);
+                       GET32(ttl);
+                       GET16(datalength);
+                       if (type == TYPE_SOA && class == CLASS_INET) {
+                               u32 serial, refresh, retry, expire, minimum;
+                               SKIP_NAME;
+                               SKIP_NAME;
+                               GET32(serial);
+                               GET32(refresh);
+                               GET32(retry);
+                               GET32(expire);
+                               GET32(minimum);
+                               (void)expire;
+                               (void)retry;
+                               (void)refresh;
+                               (void)serial;
+                               ttl_r = MIN(ttl_r, ttl);
+                               ttl_r = MIN(ttl_r, minimum);
+                       } else {
+                               /* skip over any other type of resource */
+                               j += datalength;
+                       }
+               }
+       }
+
+       if (ttl_r == 0xffffffff)
+               ttl_r = 0;
+
        reply_handle(req, flags, ttl_r, &reply);
        return 0;
  err:
@@ -1138,7 +1196,7 @@ static int
 request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
 {
        int j = 0;      /* index into packet */
-       u16 _t;  /* used by the macros */
+       u16 t_;  /* used by the macros */
        char tmp_name[256]; /* used by the macros */
 
        int i;
@@ -1313,7 +1371,7 @@ nameserver_read(struct nameserver *ns) {
                        (struct sockaddr*)&ns->address, 0)) {
                        log(EVDNS_LOG_WARN, "Address mismatch on received "
                            "DNS packet.  Apparent source was %s",
-                           evutil_format_sockaddr_port(
+                           evutil_format_sockaddr_port_(
                                    (struct sockaddr *)&ss,
                                    addrbuf, sizeof(addrbuf)));
                        return;
@@ -1403,7 +1461,7 @@ nameserver_write_waiting(struct nameserver *ns, char waiting) {
        if (event_add(&ns->event, NULL) < 0) {
                char addrbuf[128];
                log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
-                   evutil_format_sockaddr_port(
+                   evutil_format_sockaddr_port_(
                            (struct sockaddr *)&ns->address,
                            addrbuf, sizeof(addrbuf)));
                /* ???? Do more? */
@@ -1524,20 +1582,20 @@ dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
                                  struct dnslabel_table *table) {
        const char *end = name + name_len;
        int ref = 0;
-       u16 _t;
+       u16 t_;
 
 #define APPEND16(x) do {                                               \
                if (j + 2 > (off_t)buf_len)                             \
                        goto overflow;                                  \
-               _t = htons(x);                                          \
-               memcpy(buf + j, &_t, 2);                                \
+               t_ = htons(x);                                          \
+               memcpy(buf + j, &t_, 2);                                \
                j += 2;                                                 \
        } while (0)
 #define APPEND32(x) do {                                               \
                if (j + 4 > (off_t)buf_len)                             \
                        goto overflow;                                  \
-               _t32 = htonl(x);                                        \
-               memcpy(buf + j, &_t32, 4);                              \
+               t32_ = htonl(x);                                        \
+               memcpy(buf + j, &t32_, 4);                              \
                j += 4;                                                 \
        } while (0)
 
@@ -1603,7 +1661,7 @@ evdns_request_data_build(const char *const name, const size_t name_len,
     const u16 trans_id, const u16 type, const u16 class,
     u8 *const buf, size_t buf_len) {
        off_t j = 0;  /* current offset into buf */
-       u16 _t;  /* used by the macros */
+       u16 t_;  /* used by the macros */
 
        APPEND16(trans_id);
        APPEND16(0x0100);  /* standard query, recusion needed */
@@ -1678,9 +1736,9 @@ evdns_close_server_port(struct evdns_server_port *port)
 
 /* exported function */
 int
-evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
+evdns_server_request_add_reply(struct evdns_server_request *req_, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
 {
-       struct server_request *req = TO_SERVER_REQUEST(_req);
+       struct server_request *req = TO_SERVER_REQUEST(req_);
        struct server_reply_item **itemp, *item;
        int *countp;
        int result = -1;
@@ -1815,8 +1873,8 @@ evdns_server_request_format_response(struct server_request *req, int err)
        unsigned char buf[1500];
        size_t buf_len = sizeof(buf);
        off_t j = 0, r;
-       u16 _t;
-       u32 _t32;
+       u16 t_;
+       u32 t32_;
        int i;
        u16 flags;
        struct dnslabel_table table;
@@ -1874,8 +1932,8 @@ evdns_server_request_format_response(struct server_request *req, int err)
                                if (r < 0)
                                        goto overflow;
                                j = r;
-                               _t = htons( (short) (j-name_start) );
-                               memcpy(buf+len_idx, &_t, 2);
+                               t_ = htons( (short) (j-name_start) );
+                               memcpy(buf+len_idx, &t_, 2);
                        } else {
                                APPEND16(item->datalen);
                                if (j+item->datalen > (off_t)buf_len)
@@ -1908,9 +1966,9 @@ overflow:
 
 /* exported function */
 int
-evdns_server_request_respond(struct evdns_server_request *_req, int err)
+evdns_server_request_respond(struct evdns_server_request *req_, int err)
 {
-       struct server_request *req = TO_SERVER_REQUEST(_req);
+       struct server_request *req = TO_SERVER_REQUEST(req_);
        struct evdns_server_port *port = req->port;
        int r = -1;
 
@@ -2056,18 +2114,18 @@ server_port_free(struct evdns_server_port *port)
 
 /* exported function */
 int
-evdns_server_request_drop(struct evdns_server_request *_req)
+evdns_server_request_drop(struct evdns_server_request *req_)
 {
-       struct server_request *req = TO_SERVER_REQUEST(_req);
+       struct server_request *req = TO_SERVER_REQUEST(req_);
        server_request_free(req);
        return 0;
 }
 
 /* exported function */
 int
-evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
+evdns_server_request_get_requesting_addr(struct evdns_server_request *req_, struct sockaddr *sa, int addr_len)
 {
-       struct server_request *req = TO_SERVER_REQUEST(_req);
+       struct server_request *req = TO_SERVER_REQUEST(req_);
        if (addr_len < (int)req->addrlen)
                return -1;
        memcpy(sa, &(req->addr), req->addrlen);
@@ -2082,9 +2140,8 @@ evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, stru
 static void
 evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
        struct request *const req = (struct request *) arg;
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
        struct evdns_base *base = req->base;
-#endif
+
        (void) fd;
        (void) events;
 
@@ -2099,11 +2156,19 @@ evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
 
        if (req->tx_count >= req->base->global_max_retransmits) {
                /* this request has failed */
+               log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d",
+                   arg, req->tx_count);
                reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
                request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
        } else {
                /* retransmit it */
+               struct nameserver *new_ns;
+               log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d",
+                   arg, req->tx_count);
                (void) evtimer_del(&req->timeout_event);
+               new_ns = nameserver_pick(base);
+               if (new_ns)
+                       req->ns = new_ns;
                evdns_request_transmit(req);
        }
        EVDNS_UNLOCK(base);
@@ -2173,7 +2238,7 @@ evdns_request_transmit(struct request *req) {
        default:
                /* all ok */
                log(EVDNS_LOG_DEBUG,
-                   "Setting timeout for request %p", req);
+                   "Setting timeout for request %p, sent to nameserver %p", req, req->ns);
                if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
                        log(EVDNS_LOG_WARN,
                      "Error from libevent when adding timer for request %p",
@@ -2194,13 +2259,16 @@ nameserver_probe_callback(int result, char type, int count, int ttl, void *addre
        (void) ttl;
        (void) addresses;
 
-       EVDNS_LOCK(ns->base);
-       ns->probe_request = NULL;
        if (result == DNS_ERR_CANCEL) {
                /* We canceled this request because the nameserver came up
                 * for some other reason.  Do not change our opinion about
                 * the nameserver. */
-       } else if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
+               return;
+       }
+
+       EVDNS_LOCK(ns->base);
+       ns->probe_request = NULL;
+       if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
                /* this is a good reply */
                nameserver_up(ns);
        } else {
@@ -2219,7 +2287,7 @@ nameserver_send_probe(struct nameserver *const ns) {
 
        ASSERT_LOCKED(ns->base);
        log(EVDNS_LOG_DEBUG, "Sending probe to %s",
-           evutil_format_sockaddr_port(
+           evutil_format_sockaddr_port_(
                    (struct sockaddr *)&ns->address,
                    addrbuf, sizeof(addrbuf)));
        handle = mm_calloc(1, sizeof(*handle));
@@ -2305,6 +2373,10 @@ evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
                (void) event_del(&server->event);
                if (evtimer_initialized(&server->timeout_event))
                        (void) evtimer_del(&server->timeout_event);
+               if (server->probe_request) {
+                       evdns_cancel_request(server->base, server->probe_request);
+                       server->probe_request = NULL;
+               }
                if (server->socket >= 0)
                        evutil_closesocket(server->socket);
                mm_free(server);
@@ -2372,7 +2444,7 @@ evdns_resume(void)
 }
 
 static int
-_evdns_nameserver_add_impl(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
+evdns_nameserver_add_impl_(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
        /* first check to see if we already have this nameserver */
 
        const struct nameserver *server = base->server_head, *const started_at = base->server_head;
@@ -2400,13 +2472,12 @@ _evdns_nameserver_add_impl(struct evdns_base *base, const struct sockaddr *addre
 
        evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
 
-       ns->socket = socket(address->sa_family, SOCK_DGRAM, 0);
+       ns->socket = evutil_socket_(address->sa_family,
+           SOCK_DGRAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
        if (ns->socket < 0) { err = 1; goto out1; }
-       evutil_make_socket_closeonexec(ns->socket);
-       evutil_make_socket_nonblocking(ns->socket);
 
        if (base->global_outgoing_addrlen &&
-           !evutil_sockaddr_is_loopback(address)) {
+           !evutil_sockaddr_is_loopback_(address)) {
                if (bind(ns->socket,
                        (struct sockaddr*)&base->global_outgoing_address,
                        base->global_outgoing_addrlen) < 0) {
@@ -2425,8 +2496,8 @@ _evdns_nameserver_add_impl(struct evdns_base *base, const struct sockaddr *addre
                goto out2;
        }
 
-       log(EVDNS_LOG_DEBUG, "Added nameserver %s",
-           evutil_format_sockaddr_port(address, addrbuf, sizeof(addrbuf)));
+       log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p",
+           evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), ns);
 
        /* insert this nameserver into the list of them */
        if (!base->server_head) {
@@ -2436,9 +2507,7 @@ _evdns_nameserver_add_impl(struct evdns_base *base, const struct sockaddr *addre
                ns->next = base->server_head->next;
                ns->prev = base->server_head;
                base->server_head->next = ns;
-               if (base->server_head->prev == base->server_head) {
-                       base->server_head->prev = ns;
-               }
+               ns->next->prev = ns;
        }
 
        base->global_good_nameservers++;
@@ -2451,7 +2520,7 @@ out1:
        event_debug_unassign(&ns->event);
        mm_free(ns);
        log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
-           evutil_format_sockaddr_port(address, addrbuf, sizeof(addrbuf)), err);
+           evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), err);
        return err;
 }
 
@@ -2465,7 +2534,7 @@ evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
        sin.sin_port = htons(53);
        sin.sin_family = AF_INET;
        EVDNS_LOCK(base);
-       res = _evdns_nameserver_add_impl(base, (struct sockaddr*)&sin, sizeof(sin));
+       res = evdns_nameserver_add_impl_(base, (struct sockaddr*)&sin, sizeof(sin));
        EVDNS_UNLOCK(base);
        return res;
 }
@@ -2517,7 +2586,7 @@ evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string)
                sockaddr_setport(sa, 53);
 
        EVDNS_LOCK(base);
-       res = _evdns_nameserver_add_impl(base, sa, len);
+       res = evdns_nameserver_add_impl_(base, sa, len);
        EVDNS_UNLOCK(base);
        return res;
 }
@@ -2536,7 +2605,7 @@ evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
        int res;
        EVUTIL_ASSERT(base);
        EVDNS_LOCK(base);
-       res = _evdns_nameserver_add_impl(base, sa, len);
+       res = evdns_nameserver_add_impl_(base, sa, len);
        EVDNS_UNLOCK(base);
        return res;
 }
@@ -2644,7 +2713,7 @@ request_new(struct evdns_base *base, struct evdns_request *handle, int type,
                strlcpy(namebuf, name, sizeof(namebuf));
                evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
                for (i = 0; i < name_len; ++i) {
-                       if (EVUTIL_ISALPHA(namebuf[i])) {
+                       if (EVUTIL_ISALPHA_(namebuf[i])) {
                                if ((randbits[i >> 3] & (1<<(i & 7))))
                                        namebuf[i] |= 0x20;
                                else
@@ -3174,7 +3243,7 @@ evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
        if (flags & DNS_OPTION_NAMESERVERS) evdns_base_nameserver_ip_add(base,"127.0.0.1");
 }
 
-#ifndef _EVENT_HAVE_STRTOK_R
+#ifndef EVENT__HAVE_STRTOK_R
 static char *
 strtok_r(char *s, const char *delim, char **state) {
        char *cp, *start;
@@ -3477,7 +3546,7 @@ evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char
                        mm_free(fname);
        }
 
-       if ((err = evutil_read_file(filename, &resolv, &n, 0)) < 0) {
+       if ((err = evutil_read_file_(filename, &resolv, &n, 0)) < 0) {
                if (err == -1) {
                        /* No file. */
                        evdns_resolv_set_defaults(base, flags);
@@ -3564,7 +3633,7 @@ load_nameservers_with_getnetworkparams(struct evdns_base *base)
        GetNetworkParams_fn_t fn;
 
        ASSERT_LOCKED(base);
-       if (!(handle = evutil_load_windows_system_library(
+       if (!(handle = evutil_load_windows_system_library_(
                        TEXT("iphlpapi.dll")))) {
                log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
                status = -1;
@@ -3764,7 +3833,7 @@ evdns_base_new(struct event_base *event_base, int initialize_nameservers)
        /* Give the evutil library a hook into its evdns-enabled
         * functionality.  We can't just call evdns_getaddrinfo directly or
         * else libevent-core will depend on libevent-extras. */
-       evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo);
+       evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo);
 
        base = mm_malloc(sizeof(struct evdns_base));
        if (base == NULL)
@@ -3843,6 +3912,7 @@ evdns_err_to_string(int err)
        case DNS_ERR_TIMEOUT: return "request timed out";
        case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
        case DNS_ERR_CANCEL: return "dns request canceled";
+       case DNS_ERR_NODATA: return "no records in the reply";
        default: return "[Unknown error code]";
     }
 }
@@ -4001,7 +4071,7 @@ evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
        ASSERT_LOCKED(base);
 
        if (hosts_fname == NULL ||
-           (err = evutil_read_file(hosts_fname, &str, &len, 0)) < 0) {
+           (err = evutil_read_file_(hosts_fname, &str, &len, 0)) < 0) {
                char tmp[64];
                strlcpy(tmp, "127.0.0.1   localhost", sizeof(tmp));
                evdns_base_parse_hosts_line(base, tmp);
@@ -4320,7 +4390,7 @@ evdns_getaddrinfo_gotresolve(int result, char type, int count,
        for (i=0; i < count; ++i) {
                struct evutil_addrinfo *ai;
                memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
-               ai = evutil_new_addrinfo(sa, socklen, &data->hints);
+               ai = evutil_new_addrinfo_(sa, socklen, &data->hints);
                if (!ai) {
                        if (other_req->r) {
                                evdns_cancel_request(NULL, other_req->r);
@@ -4333,7 +4403,7 @@ evdns_getaddrinfo_gotresolve(int result, char type, int count,
                                free_getaddrinfo_request(data);
                        return;
                }
-               res = evutil_addrinfo_append(res, ai);
+               res = evutil_addrinfo_append_(res, ai);
        }
 
        if (other_req->r) {
@@ -4347,10 +4417,10 @@ evdns_getaddrinfo_gotresolve(int result, char type, int count,
                 * results (if any) and return them. */
                if (data->pending_result) {
                        if (req->type == DNS_IPv4_A)
-                               res = evutil_addrinfo_append(res,
+                               res = evutil_addrinfo_append_(res,
                                    data->pending_result);
                        else
-                               res = evutil_addrinfo_append(
+                               res = evutil_addrinfo_append_(
                                    data->pending_result, res);
                        data->pending_result = NULL;
                }
@@ -4400,13 +4470,13 @@ evdns_getaddrinfo_fromhosts(struct evdns_base *base,
                if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
                    (e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
                        continue;
-               ai_new = evutil_new_addrinfo(&e->addr.sa, e->addrlen, hints);
+               ai_new = evutil_new_addrinfo_(&e->addr.sa, e->addrlen, hints);
                if (!ai_new) {
                        n_found = 0;
                        goto out;
                }
                sockaddr_setport(ai_new->ai_addr, port);
-               ai = evutil_addrinfo_append(ai, ai_new);
+               ai = evutil_addrinfo_append_(ai, ai_new);
        }
        EVDNS_UNLOCK(base);
 out:
@@ -4461,14 +4531,14 @@ evdns_getaddrinfo(struct evdns_base *dns_base,
                hints.ai_family = PF_UNSPEC;
        }
 
-       evutil_adjust_hints_for_addrconfig(&hints);
+       evutil_adjust_hints_for_addrconfig_(&hints);
 
        /* Now try to see if we _can_ answer immediately. */
        /* (It would be nice to do this by calling getaddrinfo directly, with
         * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
         * a reliable way to distinguish the "that wasn't a numeric host!" case
         * from any other EAI_NONAME cases.) */
-       err = evutil_getaddrinfo_common(nodename, servname, &hints, &res, &port);
+       err = evutil_getaddrinfo_common_(nodename, servname, &hints, &res, &port);
        if (err != EVUTIL_EAI_NEED_RESOLVE) {
                cb(err, res, arg);
                return NULL;
index 63895337326afd453948b2a6141f6d3c205c2bb7..60b58c6ca7a24e6b385cd50a2760c83856d293a9 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT_INTERNAL_H_
-#define _EVENT_INTERNAL_H_
+#ifndef EVENT_INTERNAL_H_INCLUDED_
+#define EVENT_INTERNAL_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -45,13 +45,13 @@ extern "C" {
 /* map union members back */
 
 /* mutually exclusive */
-#define ev_signal_next _ev.ev_signal.ev_signal_next
-#define ev_io_next     _ev.ev_io.ev_io_next
-#define ev_io_timeout  _ev.ev_io.ev_timeout
+#define ev_signal_next ev_.ev_signal.ev_signal_next
+#define ev_io_next     ev_.ev_io.ev_io_next
+#define ev_io_timeout  ev_.ev_io.ev_timeout
 
 /* used only by signals */
-#define ev_ncalls      _ev.ev_signal.ev_ncalls
-#define ev_pncalls     _ev.ev_signal.ev_pncalls
+#define ev_ncalls      ev_.ev_signal.ev_ncalls
+#define ev_pncalls     ev_.ev_signal.ev_pncalls
 
 /* Possible values for ev_closure in struct event. */
 #define EV_CLOSURE_NONE 0
@@ -112,6 +112,7 @@ struct eventop {
 /* #define HT_CACHE_HASH_VALS */
 
 #ifdef EVMAP_USE_HT
+#define HT_NO_CACHE_HASH_VALUES
 #include "ht-internal.h"
 struct event_map_entry;
 HT_HEAD(event_io_map, event_map_entry);
@@ -161,10 +162,10 @@ struct event_changelist {
        int changes_size;
 };
 
-#ifndef _EVENT_DISABLE_DEBUG_MODE
+#ifndef EVENT__DISABLE_DEBUG_MODE
 /* Global internal flag: set to one if debug mode is on. */
-extern int _event_debug_mode_on;
-#define EVENT_DEBUG_MODE_IS_ON() (_event_debug_mode_on)
+extern int event_debug_mode_on_;
+#define EVENT_DEBUG_MODE_IS_ON() (event_debug_mode_on_)
 #else
 #define EVENT_DEBUG_MODE_IS_ON() (0)
 #endif
@@ -198,6 +199,11 @@ struct event_base {
        int event_gotterm;
        /** Set if we should terminate the loop immediately */
        int event_break;
+       /** Set if we should start a new instance of the loop immediately. */
+       int event_continue;
+
+       /** The currently running priority of events */
+       int event_running_priority;
 
        /** Set if we're running the event_base_loop function, to prevent
         * reentrant invocation. */
@@ -232,12 +238,6 @@ struct event_base {
        /** Mapping from signal numbers to enabled (added) events. */
        struct event_signal_map sigmap;
 
-       /** All events that have been enabled (added) in this event_base */
-       struct event_list eventqueue;
-
-       /** Stored timeval; used to detect when time is running backwards. */
-       struct timeval event_tv;
-
        /** Priority queue of events with timeouts. */
        struct min_heap timeheap;
 
@@ -245,28 +245,28 @@ struct event_base {
         * too often. */
        struct timeval tv_cache;
 
-#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
+       struct evutil_monotonic_timer monotonic_timer;
+
        /** Difference between internal time (maybe from clock_gettime) and
         * gettimeofday. */
        struct timeval tv_clock_diff;
        /** Second in which we last updated tv_clock_diff, in monotonic time. */
        time_t last_updated_clock_diff;
-#endif
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        /* threading support */
        /** The thread currently running the event_loop for this base */
        unsigned long th_owner_id;
        /** A lock to prevent conflicting accesses to this event_base */
        void *th_base_lock;
-       /** The event whose callback is executing right now */
-       struct event *current_event;
        /** A condition that gets signalled when we're done processing an
         * event with waiters on it. */
        void *current_event_cond;
        /** Number of threads blocking on current_event_cond. */
        int current_event_waiters;
 #endif
+       /** The event whose callback is executing right now */
+       struct event *current_event;
 
 #ifdef _WIN32
        /** IOCP support structure, if IOCP is enabled. */
@@ -292,6 +292,10 @@ struct event_base {
        struct event th_notify;
        /** A function used to wake up the main thread from another thread. */
        int (*th_notify_fn)(struct event_base *base);
+
+       /** Saved seed for weak random number generator. Some backends use
+        * this to produce fairness among sockets. Protected by th_base_lock. */
+       struct evutil_weakrand_state weakrand_seed;
 };
 
 struct event_config_entry {
@@ -314,7 +318,7 @@ struct event_config {
 };
 
 /* Internal use only: Functions that might be missing from <sys/queue.h> */
-#if defined(_EVENT_HAVE_SYS_QUEUE_H) && !defined(_EVENT_HAVE_TAILQFOREACH)
+#if defined(EVENT__HAVE_SYS_QUEUE_H) && !defined(EVENT__HAVE_TAILQFOREACH)
 #ifndef TAILQ_FIRST
 #define        TAILQ_FIRST(head)               ((head)->tqh_first)
 #endif
@@ -345,20 +349,41 @@ struct event_config {
 #define N_ACTIVE_CALLBACKS(base)                                       \
        ((base)->event_count_active + (base)->defer_queue.active_count)
 
-int _evsig_set_handler(struct event_base *base, int evsignal,
+int evsig_set_handler_(struct event_base *base, int evsignal,
                          void (*fn)(int));
-int _evsig_restore_handler(struct event_base *base, int evsignal);
+int evsig_restore_handler_(struct event_base *base, int evsignal);
 
 
-void event_active_nolock(struct event *ev, int res, short count);
+void event_active_nolock_(struct event *ev, int res, short count);
 
 /* FIXME document. */
-void event_base_add_virtual(struct event_base *base);
-void event_base_del_virtual(struct event_base *base);
+void event_base_add_virtual_(struct event_base *base);
+void event_base_del_virtual_(struct event_base *base);
+
+/** For debugging: unless assertions are disabled, verify the referential
+    integrity of the internal data structures of 'base'.  This operation can
+    be expensive.
+
+    Returns on success; aborts on failure.
+*/
+void event_base_assert_ok_(struct event_base *base);
+
+/* Callback type for event_base_foreach_event. */
+typedef int (*event_base_foreach_event_cb)(struct event_base *base, struct event *, void *);
+
+/* Helper function: Call 'fn' exactly once every inserted or active event in
+ * the event_base 'base'.
+ *
+ * If fn returns 0, continue on to the next event. Otherwise, return the same
+ * value that fn returned.
+ *
+ * Requires that 'base' be locked.
+ */
+int event_base_foreach_event_(struct event_base *base,
+    event_base_foreach_event_cb cb, void *arg);
 
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* _EVENT_INTERNAL_H_ */
-
+#endif /* EVENT_INTERNAL_H_INCLUDED_ */
index 66fbfd588c62cf6a03932de776331379af42dc31..c5c118cc1a8964579355421cc8fc28c8eadb71b3 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #undef WIN32_LEAN_AND_MEAN
 #endif
 #include <sys/types.h>
-#if !defined(_WIN32) && defined(_EVENT_HAVE_SYS_TIME_H)
+#if !defined(_WIN32) && defined(EVENT__HAVE_SYS_TIME_H)
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 #include <stdio.h>
 #include <stdlib.h>
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_EVENTFD_H
-#include <sys/eventfd.h>
-#endif
 #include <ctype.h>
 #include <errno.h>
 #include <signal.h>
 #include "evmap-internal.h"
 #include "iocp-internal.h"
 #include "changelist-internal.h"
+#define HT_NO_CACHE_HASH_VALUES
 #include "ht-internal.h"
 #include "util-internal.h"
 
-#ifdef _EVENT_HAVE_EVENT_PORTS
+
+#ifdef EVENT__HAVE_WORKING_KQUEUE
+#include "kqueue-internal.h"
+#endif
+
+#ifdef EVENT__HAVE_EVENT_PORTS
 extern const struct eventop evportops;
 #endif
-#ifdef _EVENT_HAVE_SELECT
+#ifdef EVENT__HAVE_SELECT
 extern const struct eventop selectops;
 #endif
-#ifdef _EVENT_HAVE_POLL
+#ifdef EVENT__HAVE_POLL
 extern const struct eventop pollops;
 #endif
-#ifdef _EVENT_HAVE_EPOLL
+#ifdef EVENT__HAVE_EPOLL
 extern const struct eventop epollops;
 #endif
-#ifdef _EVENT_HAVE_WORKING_KQUEUE
+#ifdef EVENT__HAVE_WORKING_KQUEUE
 extern const struct eventop kqops;
 #endif
-#ifdef _EVENT_HAVE_DEVPOLL
+#ifdef EVENT__HAVE_DEVPOLL
 extern const struct eventop devpollops;
 #endif
 #ifdef _WIN32
@@ -95,22 +98,22 @@ extern const struct eventop win32ops;
 
 /* Array of backends in order of preference. */
 static const struct eventop *eventops[] = {
-#ifdef _EVENT_HAVE_EVENT_PORTS
+#ifdef EVENT__HAVE_EVENT_PORTS
        &evportops,
 #endif
-#ifdef _EVENT_HAVE_WORKING_KQUEUE
+#ifdef EVENT__HAVE_WORKING_KQUEUE
        &kqops,
 #endif
-#ifdef _EVENT_HAVE_EPOLL
+#ifdef EVENT__HAVE_EPOLL
        &epollops,
 #endif
-#ifdef _EVENT_HAVE_DEVPOLL
+#ifdef EVENT__HAVE_DEVPOLL
        &devpollops,
 #endif
-#ifdef _EVENT_HAVE_POLL
+#ifdef EVENT__HAVE_POLL
        &pollops,
 #endif
-#ifdef _EVENT_HAVE_SELECT
+#ifdef EVENT__HAVE_SELECT
        &selectops,
 #endif
 #ifdef _WIN32
@@ -125,7 +128,7 @@ struct event_base *event_global_current_base_ = NULL;
 
 /* Global state */
 
-static int use_monotonic;
+static void *event_self_cbarg_ptr_ = NULL;
 
 /* Prototypes */
 static inline int event_add_internal(struct event *ev,
@@ -138,7 +141,10 @@ static void        event_queue_insert_inserted(struct event_base *, struct event *);
 static void    event_queue_remove_active(struct event_base *, struct event *);
 static void    event_queue_remove_timeout(struct event_base *, struct event *);
 static void    event_queue_remove_inserted(struct event_base *, struct event *);
-static void    event_queue_reinsert_timeout(struct event_base *,struct event *);
+#ifdef USE_REINSERT_TIMEOUT
+/* This code seems buggy; only turn it on if we find out what the trouble is. */
+static void    event_queue_reinsert_timeout(struct event_base *,struct event *, int was_common, int is_common, int old_timeout_idx);
+#endif
 
 static int     event_haveevents(struct event_base *);
 
@@ -146,7 +152,6 @@ static int  event_process_active(struct event_base *);
 
 static int     timeout_next(struct event_base *, struct timeval **);
 static void    timeout_process(struct event_base *);
-static void    timeout_correct(struct event_base *, struct timeval *);
 
 static inline void     event_signal_closure(struct event_base *, struct event *ev);
 static inline void     event_persist_closure(struct event_base *, struct event *ev);
@@ -156,7 +161,7 @@ static int  evthread_notify_base(struct event_base *base);
 static void insert_common_timeout_inorder(struct common_timeout_list *ctl,
     struct event *ev);
 
-#ifndef _EVENT_DISABLE_DEBUG_MODE
+#ifndef EVENT__DISABLE_DEBUG_MODE
 /* These functions implement a hashtable of which 'struct event *' structures
  * have been setup or added.  We don't want to trust the content of the struct
  * event itself, since we're trying to work through cases where an event gets
@@ -190,11 +195,11 @@ eq_debug_entry(const struct event_debug_entry *a,
        return a->ptr == b->ptr;
 }
 
-int _event_debug_mode_on = 0;
+int event_debug_mode_on_ = 0;
 /* Set if it's too late to enable event_debug_mode. */
 static int event_debug_mode_too_late = 0;
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
-static void *_event_debug_map_lock = NULL;
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+static void *event_debug_map_lock_ = NULL;
 #endif
 static HT_HEAD(event_debug_map, event_debug_entry) global_debug_map =
        HT_INITIALIZER();
@@ -205,11 +210,11 @@ HT_GENERATE(event_debug_map, event_debug_entry, node, hash_debug_entry,
     eq_debug_entry, 0.5, mm_malloc, mm_realloc, mm_free)
 
 /* Macro: record that ev is now setup (that is, ready for an add) */
-#define _event_debug_note_setup(ev) do {                               \
-       if (_event_debug_mode_on) {                                     \
+#define event_debug_note_setup_(ev) do {                               \
+       if (event_debug_mode_on_) {                                     \
                struct event_debug_entry *dent,find;                    \
                find.ptr = (ev);                                        \
-               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               EVLOCK_LOCK(event_debug_map_lock_, 0);                  \
                dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
                if (dent) {                                             \
                        dent->added = 0;                                \
@@ -222,127 +227,116 @@ HT_GENERATE(event_debug_map, event_debug_entry, node, hash_debug_entry,
                        dent->added = 0;                                \
                        HT_INSERT(event_debug_map, &global_debug_map, dent); \
                }                                                       \
-               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+               EVLOCK_UNLOCK(event_debug_map_lock_, 0);                \
        }                                                               \
        event_debug_mode_too_late = 1;                                  \
        } while (0)
 /* Macro: record that ev is no longer setup */
-#define _event_debug_note_teardown(ev) do {                            \
-       if (_event_debug_mode_on) {                                     \
+#define event_debug_note_teardown_(ev) do {                            \
+       if (event_debug_mode_on_) {                                     \
                struct event_debug_entry *dent,find;                    \
                find.ptr = (ev);                                        \
-               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               EVLOCK_LOCK(event_debug_map_lock_, 0);                  \
                dent = HT_REMOVE(event_debug_map, &global_debug_map, &find); \
                if (dent)                                               \
                        mm_free(dent);                                  \
-               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+               EVLOCK_UNLOCK(event_debug_map_lock_, 0);                \
        }                                                               \
        event_debug_mode_too_late = 1;                                  \
        } while (0)
 /* Macro: record that ev is now added */
-#define _event_debug_note_add(ev)      do {                            \
-       if (_event_debug_mode_on) {                                     \
+#define event_debug_note_add_(ev)      do {                            \
+       if (event_debug_mode_on_) {                                     \
                struct event_debug_entry *dent,find;                    \
                find.ptr = (ev);                                        \
-               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               EVLOCK_LOCK(event_debug_map_lock_, 0);                  \
                dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
                if (dent) {                                             \
                        dent->added = 1;                                \
                } else {                                                \
-                       event_errx(_EVENT_ERR_ABORT,                    \
-                           "%s: noting an add on a non-setup event %p", \
-                           __func__, (ev));                            \
+                       event_errx(EVENT_ERR_ABORT_,                    \
+                           "%s: noting an add on a non-setup event %p" \
+                           " (events: 0x%x, fd: %d, flags: 0x%x)",     \
+                           __func__, (ev), (ev)->ev_events,            \
+                           (ev)->ev_fd, (ev)->ev_flags);               \
                }                                                       \
-               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+               EVLOCK_UNLOCK(event_debug_map_lock_, 0);                \
        }                                                               \
        event_debug_mode_too_late = 1;                                  \
        } while (0)
 /* Macro: record that ev is no longer added */
-#define _event_debug_note_del(ev) do {                                 \
-       if (_event_debug_mode_on) {                                     \
+#define event_debug_note_del_(ev) do {                                 \
+       if (event_debug_mode_on_) {                                     \
                struct event_debug_entry *dent,find;                    \
                find.ptr = (ev);                                        \
-               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               EVLOCK_LOCK(event_debug_map_lock_, 0);                  \
                dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
                if (dent) {                                             \
                        dent->added = 0;                                \
                } else {                                                \
-                       event_errx(_EVENT_ERR_ABORT,                    \
-                           "%s: noting a del on a non-setup event %p", \
-                           __func__, (ev));                            \
+                       event_errx(EVENT_ERR_ABORT_,                    \
+                           "%s: noting a del on a non-setup event %p"  \
+                           " (events: 0x%x, fd: %d, flags: 0x%x)",     \
+                           __func__, (ev), (ev)->ev_events,            \
+                           (ev)->ev_fd, (ev)->ev_flags);               \
                }                                                       \
-               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+               EVLOCK_UNLOCK(event_debug_map_lock_, 0);                \
        }                                                               \
        event_debug_mode_too_late = 1;                                  \
        } while (0)
 /* Macro: assert that ev is setup (i.e., okay to add or inspect) */
-#define _event_debug_assert_is_setup(ev) do {                          \
-       if (_event_debug_mode_on) {                                     \
+#define event_debug_assert_is_setup_(ev) do {                          \
+       if (event_debug_mode_on_) {                                     \
                struct event_debug_entry *dent,find;                    \
                find.ptr = (ev);                                        \
-               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               EVLOCK_LOCK(event_debug_map_lock_, 0);                  \
                dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
                if (!dent) {                                            \
-                       event_errx(_EVENT_ERR_ABORT,                    \
-                           "%s called on a non-initialized event %p",  \
-                           __func__, (ev));                            \
+                       event_errx(EVENT_ERR_ABORT_,                    \
+                           "%s called on a non-initialized event %p"   \
+                           " (events: 0x%x, fd: %d, flags: 0x%x)",     \
+                           __func__, (ev), (ev)->ev_events,            \
+                           (ev)->ev_fd, (ev)->ev_flags);               \
                }                                                       \
-               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+               EVLOCK_UNLOCK(event_debug_map_lock_, 0);                \
        }                                                               \
        } while (0)
 /* Macro: assert that ev is not added (i.e., okay to tear down or set
  * up again) */
-#define _event_debug_assert_not_added(ev) do {                         \
-       if (_event_debug_mode_on) {                                     \
+#define event_debug_assert_not_added_(ev) do {                         \
+       if (event_debug_mode_on_) {                                     \
                struct event_debug_entry *dent,find;                    \
                find.ptr = (ev);                                        \
-               EVLOCK_LOCK(_event_debug_map_lock, 0);                  \
+               EVLOCK_LOCK(event_debug_map_lock_, 0);                  \
                dent = HT_FIND(event_debug_map, &global_debug_map, &find); \
                if (dent && dent->added) {                              \
-                       event_errx(_EVENT_ERR_ABORT,                    \
-                           "%s called on an already added event %p",   \
-                           __func__, (ev));                            \
+                       event_errx(EVENT_ERR_ABORT_,                    \
+                           "%s called on an already added event %p"    \
+                           " (events: 0x%x, fd: %d, flags: 0x%x)",     \
+                           __func__, (ev), (ev)->ev_events,            \
+                           (ev)->ev_fd, (ev)->ev_flags);               \
                }                                                       \
-               EVLOCK_UNLOCK(_event_debug_map_lock, 0);                \
+               EVLOCK_UNLOCK(event_debug_map_lock_, 0);                \
        }                                                               \
        } while (0)
 #else
-#define _event_debug_note_setup(ev) \
+#define event_debug_note_setup_(ev) \
        ((void)0)
-#define _event_debug_note_teardown(ev) \
+#define event_debug_note_teardown_(ev) \
        ((void)0)
-#define _event_debug_note_add(ev) \
+#define event_debug_note_add_(ev) \
        ((void)0)
-#define _event_debug_note_del(ev) \
+#define event_debug_note_del_(ev) \
        ((void)0)
-#define _event_debug_assert_is_setup(ev) \
+#define event_debug_assert_is_setup_(ev) \
        ((void)0)
-#define _event_debug_assert_not_added(ev) \
+#define event_debug_assert_not_added_(ev) \
        ((void)0)
 #endif
 
 #define EVENT_BASE_ASSERT_LOCKED(base)         \
        EVLOCK_ASSERT_LOCKED((base)->th_base_lock)
 
-/* The first time this function is called, it sets use_monotonic to 1
- * if we have a clock function that supports monotonic time */
-static void
-detect_monotonic(void)
-{
-#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
-       struct timespec ts;
-       static int use_monotonic_initialized = 0;
-
-       if (use_monotonic_initialized)
-               return;
-
-       if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
-               use_monotonic = 1;
-
-       use_monotonic_initialized = 1;
-#endif
-}
-
 /* How often (in seconds) do we check for changes in wall clock time relative
  * to monotonic time?  Set this to -1 for 'never.' */
 #define CLOCK_SYNC_INTERVAL 5
@@ -362,28 +356,19 @@ gettime(struct event_base *base, struct timeval *tp)
                return (0);
        }
 
-#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
-       if (use_monotonic) {
-               struct timespec ts;
-
-               if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
-                       return (-1);
-
-               tp->tv_sec = ts.tv_sec;
-               tp->tv_usec = ts.tv_nsec / 1000;
-               if (base->last_updated_clock_diff + CLOCK_SYNC_INTERVAL
-                   < ts.tv_sec) {
-                       struct timeval tv;
-                       evutil_gettimeofday(&tv,NULL);
-                       evutil_timersub(&tv, tp, &base->tv_clock_diff);
-                       base->last_updated_clock_diff = ts.tv_sec;
-               }
+       if (evutil_gettime_monotonic_(&base->monotonic_timer, tp) == -1) {
+               return -1;
+       }
 
-               return (0);
+       if (base->last_updated_clock_diff + CLOCK_SYNC_INTERVAL
+           < tp->tv_sec) {
+               struct timeval tv;
+               evutil_gettimeofday(&tv,NULL);
+               evutil_timersub(&tv, tp, &base->tv_clock_diff);
+               base->last_updated_clock_diff = tp->tv_sec;
        }
-#endif
 
-       return (evutil_gettimeofday(tp, NULL));
+       return 0;
 }
 
 int
@@ -400,11 +385,7 @@ event_base_gettimeofday_cached(struct event_base *base, struct timeval *tv)
        if (base->tv_cache.tv_sec == 0) {
                r = evutil_gettimeofday(tv, NULL);
        } else {
-#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
                evutil_timeradd(&base->tv_cache, &base->tv_clock_diff, tv);
-#else
-               *tv = base->tv_cache;
-#endif
                r = 0;
        }
        EVBASE_RELEASE_LOCK(base, th_base_lock);
@@ -427,6 +408,22 @@ update_time_cache(struct event_base *base)
            gettime(base, &base->tv_cache);
 }
 
+int
+event_base_update_cache_time(struct event_base *base)
+{
+
+       if (!base) {
+               base = current_base;
+               if (!current_base)
+                       return -1;
+       }
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       update_time_cache(base);
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       return 0;
+}
+
 struct event_base *
 event_init(void)
 {
@@ -480,10 +477,10 @@ event_is_method_disabled(const char *name)
 
        evutil_snprintf(environment, sizeof(environment), "EVENT_NO%s", name);
        for (i = 8; environment[i] != '\0'; ++i)
-               environment[i] = EVUTIL_TOUPPER(environment[i]);
-       /* Note that evutil_getenv() ignores the environment entirely if
+               environment[i] = EVUTIL_TOUPPER_(environment[i]);
+       /* Note that evutil_getenv_() ignores the environment entirely if
         * we're setuid */
-       return (evutil_getenv(environment) != NULL);
+       return (evutil_getenv_(environment) != NULL);
 }
 
 int
@@ -493,7 +490,7 @@ event_base_get_features(const struct event_base *base)
 }
 
 void
-event_deferred_cb_queue_init(struct deferred_cb_queue *cb)
+event_deferred_cb_queue_init_(struct deferred_cb_queue *cb)
 {
        memset(cb, 0, sizeof(struct deferred_cb_queue));
        TAILQ_INIT(&cb->deferred_cb_list);
@@ -509,7 +506,7 @@ notify_base_cbq_callback(struct deferred_cb_queue *cb, void *baseptr)
 }
 
 struct deferred_cb_queue *
-event_base_get_deferred_cb_queue(struct event_base *base)
+event_base_get_deferred_cb_queue_(struct event_base *base)
 {
        return base ? &base->defer_queue : NULL;
 }
@@ -517,14 +514,14 @@ event_base_get_deferred_cb_queue(struct event_base *base)
 void
 event_enable_debug_mode(void)
 {
-#ifndef _EVENT_DISABLE_DEBUG_MODE
-       if (_event_debug_mode_on)
+#ifndef EVENT__DISABLE_DEBUG_MODE
+       if (event_debug_mode_on_)
                event_errx(1, "%s was called twice!", __func__);
        if (event_debug_mode_too_late)
                event_errx(1, "%s must be called *before* creating any events "
                    "or event_bases",__func__);
 
-       _event_debug_mode_on = 1;
+       event_debug_mode_on_ = 1;
 
        HT_INIT(event_debug_map, &global_debug_map);
 #endif
@@ -536,14 +533,14 @@ event_disable_debug_mode(void)
 {
        struct event_debug_entry **ent, *victim;
 
-       EVLOCK_LOCK(_event_debug_map_lock, 0);
+       EVLOCK_LOCK(event_debug_map_lock_, 0);
        for (ent = HT_START(event_debug_map, &global_debug_map); ent; ) {
                victim = *ent;
                ent = HT_NEXT_RMV(event_debug_map,&global_debug_map, ent);
                mm_free(victim);
        }
        HT_CLEAR(event_debug_map, &global_debug_map);
-       EVLOCK_UNLOCK(_event_debug_map_lock , 0);
+       EVLOCK_UNLOCK(event_debug_map_lock_ , 0);
 }
 #endif
 
@@ -554,7 +551,7 @@ event_base_new_with_config(const struct event_config *cfg)
        struct event_base *base;
        int should_check_environment;
 
-#ifndef _EVENT_DISABLE_DEBUG_MODE
+#ifndef EVENT__DISABLE_DEBUG_MODE
        event_debug_mode_too_late = 1;
 #endif
 
@@ -562,32 +559,46 @@ event_base_new_with_config(const struct event_config *cfg)
                event_warn("%s: calloc", __func__);
                return NULL;
        }
-       detect_monotonic();
-       gettime(base, &base->event_tv);
 
-       min_heap_ctor(&base->timeheap);
-       TAILQ_INIT(&base->eventqueue);
+       if (cfg)
+               base->flags = cfg->flags;
+
+       should_check_environment =
+           !(cfg && (cfg->flags & EVENT_BASE_FLAG_IGNORE_ENV));
+
+       {
+               struct timeval tmp;
+               int precise_time =
+                   cfg && (cfg->flags & EVENT_BASE_FLAG_PRECISE_TIMER);
+               int flags;
+               if (should_check_environment && !precise_time) {
+                       precise_time = evutil_getenv_("EVENT_PRECISE_TIMER") != NULL;
+                       base->flags |= EVENT_BASE_FLAG_PRECISE_TIMER;
+               }
+               flags = precise_time ? EV_MONOT_PRECISE : 0;
+               evutil_configure_monotonic_time_(&base->monotonic_timer, flags);
+
+               gettime(base, &tmp);
+       }
+
+       min_heap_ctor_(&base->timeheap);
+
        base->sig.ev_signal_pair[0] = -1;
        base->sig.ev_signal_pair[1] = -1;
        base->th_notify_fd[0] = -1;
        base->th_notify_fd[1] = -1;
 
-       event_deferred_cb_queue_init(&base->defer_queue);
+       event_deferred_cb_queue_init_(&base->defer_queue);
        base->defer_queue.base = base;
        base->defer_queue.notify_fn = notify_base_cbq_callback;
        base->defer_queue.notify_arg = base;
-       if (cfg)
-               base->flags = cfg->flags;
 
-       evmap_io_initmap(&base->io);
-       evmap_signal_initmap(&base->sigmap);
-       event_changelist_init(&base->changelist);
+       evmap_io_initmap_(&base->io);
+       evmap_signal_initmap_(&base->sigmap);
+       event_changelist_init_(&base->changelist);
 
        base->evbase = NULL;
 
-       should_check_environment =
-           !(cfg && (cfg->flags & EVENT_BASE_FLAG_IGNORE_ENV));
-
        if (cfg) {
                memcpy(&base->max_dispatch_time,
                    &cfg->max_dispatch_interval, sizeof(struct timeval));
@@ -635,7 +646,7 @@ event_base_new_with_config(const struct event_config *cfg)
                return NULL;
        }
 
-       if (evutil_getenv("EVENT_SHOW_METHOD"))
+       if (evutil_getenv_("EVENT_SHOW_METHOD"))
                event_msgx("libevent using: %s", base->evsel->name);
 
        /* allocate a single active event queue */
@@ -646,8 +657,9 @@ event_base_new_with_config(const struct event_config *cfg)
 
        /* prepare for threading */
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
-       if (!cfg || !(cfg->flags & EVENT_BASE_FLAG_NOLOCK)) {
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+       if (EVTHREAD_LOCKING_ENABLED() &&
+           (!cfg || !(cfg->flags & EVENT_BASE_FLAG_NOLOCK))) {
                int r;
                EVTHREAD_ALLOC_LOCK(base->th_base_lock,
                    EVTHREAD_LOCKTYPE_RECURSIVE);
@@ -655,6 +667,7 @@ event_base_new_with_config(const struct event_config *cfg)
                EVTHREAD_ALLOC_COND(base->current_event_cond);
                r = evthread_make_base_notifiable(base);
                if (r<0) {
+                       event_warnx("%s: Unable to make base notifiable.", __func__);
                        event_base_free(base);
                        return NULL;
                }
@@ -663,19 +676,19 @@ event_base_new_with_config(const struct event_config *cfg)
 
 #ifdef _WIN32
        if (cfg && (cfg->flags & EVENT_BASE_FLAG_STARTUP_IOCP))
-               event_base_start_iocp(base, cfg->n_cpus_hint);
+               event_base_start_iocp_(base, cfg->n_cpus_hint);
 #endif
 
        return (base);
 }
 
 int
-event_base_start_iocp(struct event_base *base, int n_cpus)
+event_base_start_iocp_(struct event_base *base, int n_cpus)
 {
 #ifdef _WIN32
        if (base->iocp)
                return 0;
-       base->iocp = event_iocp_port_launch(n_cpus);
+       base->iocp = event_iocp_port_launch_(n_cpus);
        if (!base->iocp) {
                event_warnx("%s: Couldn't launch IOCP", __func__);
                return -1;
@@ -687,14 +700,14 @@ event_base_start_iocp(struct event_base *base, int n_cpus)
 }
 
 void
-event_base_stop_iocp(struct event_base *base)
+event_base_stop_iocp_(struct event_base *base)
 {
 #ifdef _WIN32
        int rv;
 
        if (!base->iocp)
                return;
-       rv = event_iocp_shutdown(base->iocp, -1);
+       rv = event_iocp_shutdown_(base->iocp, -1);
        EVUTIL_ASSERT(rv >= 0);
        base->iocp = NULL;
 #endif
@@ -723,7 +736,7 @@ event_base_free(struct event_base *base)
        /* XXX(niels) - check for internal events first */
 
 #ifdef _WIN32
-       event_base_stop_iocp(base);
+       event_base_stop_iocp_(base);
 #endif
 
        /* threading fds if we have them */
@@ -738,15 +751,9 @@ event_base_free(struct event_base *base)
        }
 
        /* Delete all non-internal events. */
-       for (ev = TAILQ_FIRST(&base->eventqueue); ev; ) {
-               struct event *next = TAILQ_NEXT(ev, ev_next);
-               if (!(ev->ev_flags & EVLIST_INTERNAL)) {
-                       event_del(ev);
-                       ++n_deleted;
-               }
-               ev = next;
-       }
-       while ((ev = min_heap_top(&base->timeheap)) != NULL) {
+       evmap_delete_all_(base);
+
+       while ((ev = min_heap_top_(&base->timeheap)) != NULL) {
                event_del(ev);
                ++n_deleted;
        }
@@ -790,16 +797,14 @@ event_base_free(struct event_base *base)
        for (i = 0; i < base->nactivequeues; ++i)
                EVUTIL_ASSERT(TAILQ_EMPTY(&base->activequeues[i]));
 
-       EVUTIL_ASSERT(min_heap_empty(&base->timeheap));
-       min_heap_dtor(&base->timeheap);
+       EVUTIL_ASSERT(min_heap_empty_(&base->timeheap));
+       min_heap_dtor_(&base->timeheap);
 
        mm_free(base->activequeues);
 
-       EVUTIL_ASSERT(TAILQ_EMPTY(&base->eventqueue));
-
-       evmap_io_clear(&base->io);
-       evmap_signal_clear(&base->sigmap);
-       event_changelist_freemem(&base->changelist);
+       evmap_io_clear_(&base->io);
+       evmap_signal_clear_(&base->sigmap);
+       event_changelist_freemem_(&base->changelist);
 
        EVTHREAD_FREE_LOCK(base->th_base_lock, EVTHREAD_LOCKTYPE_RECURSIVE);
        EVTHREAD_FREE_COND(base->current_event_cond);
@@ -807,80 +812,122 @@ event_base_free(struct event_base *base)
        mm_free(base);
 }
 
+/* Fake eventop; used to disable the backend temporarily inside event_reinit
+ * so that we can call event_del() on an event without telling the backend.
+ */
+static int
+nil_backend_del(struct event_base *b, evutil_socket_t fd, short old,
+    short events, void *fdinfo)
+{
+       return 0;
+}
+const struct eventop nil_eventop = {
+       "nil",
+       NULL, /* init: unused. */
+       NULL, /* add: unused. */
+       nil_backend_del, /* del: used, so needs to be killed. */
+       NULL, /* dispatch: unused. */
+       NULL, /* dealloc: unused. */
+       0, 0, 0
+};
+
 /* reinitialize the event base after a fork */
 int
 event_reinit(struct event_base *base)
 {
        const struct eventop *evsel;
        int res = 0;
-       struct event *ev;
        int was_notifiable = 0;
+       int had_signal_added = 0;
 
        EVBASE_ACQUIRE_LOCK(base, th_base_lock);
 
        evsel = base->evsel;
 
-#if 0
-       /* Right now, reinit always takes effect, since even if the
-          backend doesn't require it, the signal socketpair code does.
+       /* check if this event mechanism requires reinit on the backend */
+       if (evsel->need_reinit) {
+               /* We're going to call event_del() on our notify events (the
+                * ones that tell about signals and wakeup events).  But we
+                * don't actually want to tell the backend to change its
+                * state, since it might still share some resource (a kqueue,
+                * an epoll fd) with the parent process, and we don't want to
+                * delete the fds from _that_ backend, we temporarily stub out
+                * the evsel with a replacement.
+                */
+               base->evsel = &nil_eventop;
+       }
 
-          XXX
+       /* We need to re-create a new signal-notification fd and a new
+        * thread-notification fd.  Otherwise, we'll still share those with
+        * the parent process, which would make any notification sent to them
+        * get received by one or both of the event loops, more or less at
+        * random.
         */
-       /* check if this event mechanism requires reinit */
-       if (!evsel->need_reinit)
-               goto done;
-#endif
-
-       /* prevent internal delete */
        if (base->sig.ev_signal_added) {
-               /* we cannot call event_del here because the base has
-                * not been reinitialized yet. */
-               event_queue_remove_inserted(base, &base->sig.ev_signal);
-               if (base->sig.ev_signal.ev_flags & EVLIST_ACTIVE)
-                       event_queue_remove_active(base, &base->sig.ev_signal);
+               event_del(&base->sig.ev_signal);
+               event_debug_unassign(&base->sig.ev_signal);
+               memset(&base->sig.ev_signal, 0, sizeof(base->sig.ev_signal));
+               if (base->sig.ev_signal_pair[0] != -1)
+                       EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[0]);
+               if (base->sig.ev_signal_pair[1] != -1)
+                       EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[1]);
+               had_signal_added = 1;
                base->sig.ev_signal_added = 0;
        }
-       if (base->th_notify_fd[0] != -1) {
-               /* we cannot call event_del here because the base has
-                * not been reinitialized yet. */
+       if (base->th_notify_fn != NULL) {
                was_notifiable = 1;
-               event_queue_remove_inserted(base, &base->th_notify);
-               if (base->th_notify.ev_flags & EVLIST_ACTIVE)
-                       event_queue_remove_active(base, &base->th_notify);
-               base->sig.ev_signal_added = 0;
+               base->th_notify_fn = NULL;
+       }
+       if (base->th_notify_fd[0] != -1) {
+               event_del(&base->th_notify);
                EVUTIL_CLOSESOCKET(base->th_notify_fd[0]);
                if (base->th_notify_fd[1] != -1)
                        EVUTIL_CLOSESOCKET(base->th_notify_fd[1]);
                base->th_notify_fd[0] = -1;
                base->th_notify_fd[1] = -1;
                event_debug_unassign(&base->th_notify);
-               base->th_notify_fn = NULL;
        }
 
-       if (base->evsel->dealloc != NULL)
-               base->evsel->dealloc(base);
-       base->evbase = evsel->init(base);
-       if (base->evbase == NULL) {
-               event_errx(1, "%s: could not reinitialize event mechanism",
-                   __func__);
-               res = -1;
-               goto done;
-       }
+       /* Replace the original evsel. */
+        base->evsel = evsel;
 
-       event_changelist_freemem(&base->changelist); /* XXX */
-       evmap_io_clear(&base->io);
-       evmap_signal_clear(&base->sigmap);
-
-       TAILQ_FOREACH(ev, &base->eventqueue, ev_next) {
-               if (ev->ev_events & (EV_READ|EV_WRITE)) {
-                       if (evmap_io_add(base, ev->ev_fd, ev) == -1)
-                               res = -1;
-               } else if (ev->ev_events & EV_SIGNAL) {
-                       if (evmap_signal_add(base, (int)ev->ev_fd, ev) == -1)
-                               res = -1;
+       if (evsel->need_reinit) {
+               /* Reconstruct the backend through brute-force, so that we do
+                * not share any structures with the parent process. For some
+                * backends, this is necessary: epoll and kqueue, for
+                * instance, have events associated with a kernel
+                * structure. If didn't reinitialize, we'd share that
+                * structure with the parent process, and any changes made by
+                * the parent would affect our backend's behavior (and vice
+                * versa).
+                */
+               if (base->evsel->dealloc != NULL)
+                       base->evsel->dealloc(base);
+               base->evbase = evsel->init(base);
+               if (base->evbase == NULL) {
+                       event_errx(1,
+                          "%s: could not reinitialize event mechanism",
+                          __func__);
+                       res = -1;
+                       goto done;
                }
+
+               /* Empty out the changelist (if any): we are starting from a
+                * blank slate. */
+               event_changelist_freemem_(&base->changelist);
+
+               /* Tell the event maps to re-inform the backend about all
+                * pending events. This will make the signal notification
+                * event get re-created if necessary. */
+               if (evmap_reinit_(base) < 0)
+                       res = -1;
+       } else {
+               if (had_signal_added)
+                       res = evsig_init_(base);
        }
 
+       /* If we were notifiable before, and nothing just exploded, become
+        * notifiable again. */
        if (was_notifiable && res == 0)
                res = evthread_make_base_notifiable(base);
 
@@ -1028,14 +1075,17 @@ event_priority_init(int npriorities)
 int
 event_base_priority_init(struct event_base *base, int npriorities)
 {
-       int i;
+       int i, r;
+       r = -1;
+
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
 
        if (N_ACTIVE_CALLBACKS(base) || npriorities < 1
            || npriorities >= EVENT_MAX_PRIORITIES)
-               return (-1);
+               goto err;
 
        if (npriorities == base->nactivequeues)
-               return (0);
+               goto ok;
 
        if (base->nactivequeues) {
                mm_free(base->activequeues);
@@ -1047,7 +1097,7 @@ event_base_priority_init(struct event_base *base, int npriorities)
          mm_calloc(npriorities, sizeof(struct event_list));
        if (base->activequeues == NULL) {
                event_warn("%s: calloc", __func__);
-               return (-1);
+               goto err;
        }
        base->nactivequeues = npriorities;
 
@@ -1055,7 +1105,22 @@ event_base_priority_init(struct event_base *base, int npriorities)
                TAILQ_INIT(&base->activequeues[i]);
        }
 
-       return (0);
+ok:
+       r = 0;
+err:
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       return (r);
+}
+
+int
+event_base_get_npriorities(struct event_base *base)
+{
+
+       int n;
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       n = base->nactivequeues;
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       return (n);
 }
 
 /* Returns true iff we're currently watching any events. */
@@ -1071,22 +1136,29 @@ static inline void
 event_signal_closure(struct event_base *base, struct event *ev)
 {
        short ncalls;
+       int should_break;
 
        /* Allows deletes to work */
        ncalls = ev->ev_ncalls;
-       ev->ev_pncalls = &ncalls;
+       if (ncalls != 0)
+               ev->ev_pncalls = &ncalls;
        EVBASE_RELEASE_LOCK(base, th_base_lock);
        while (ncalls) {
                ncalls--;
                ev->ev_ncalls = ncalls;
                if (ncalls == 0)
                        ev->ev_pncalls = NULL;
-               (*ev->ev_callback)((int)ev->ev_fd, ev->ev_res, ev->ev_arg);
-#if 0
-               /* XXXX we can't do this without a lock on the base. */
-               if (base->event_break)
+               (*ev->ev_callback)(ev->ev_fd, ev->ev_res, ev->ev_arg);
+
+               EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+               should_break = base->event_break;
+               EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+               if (should_break) {
+                       if (ncalls != 0)
+                               ev->ev_pncalls = NULL;
                        return;
-#endif
+               }
        }
 }
 
@@ -1184,7 +1256,7 @@ common_timeout_callback(evutil_socket_t fd, short what, void *arg)
                        (ev->ev_timeout.tv_usec&MICROSECONDS_MASK) > now.tv_usec))
                        break;
                event_del_internal(ev);
-               event_active_nolock(ev, EV_TIMEOUT, 1);
+               event_active_nolock_(ev, EV_TIMEOUT, 1);
        }
        if (ev)
                common_timeout_schedule(ctl, &now, ev);
@@ -1277,12 +1349,12 @@ event_persist_closure(struct event_base *base, struct event *ev)
                 * ev_io_timeout after the last time it was _scheduled_ for,
                 * not ev_io_timeout after _now_.  If it fired for another
                 * reason, though, the timeout ought to start ticking _now_. */
-               struct timeval run_at;
+               struct timeval run_at, relative_to, delay, now;
+               ev_uint32_t usec_mask = 0;
                EVUTIL_ASSERT(is_same_common_timeout(&ev->ev_timeout,
                        &ev->ev_io_timeout));
+               gettime(base, &now);
                if (is_common_timeout(&ev->ev_timeout, base)) {
-                       ev_uint32_t usec_mask;
-                       struct timeval delay, relative_to;
                        delay = ev->ev_io_timeout;
                        usec_mask = delay.tv_usec & ~MICROSECONDS_MASK;
                        delay.tv_usec &= MICROSECONDS_MASK;
@@ -1290,24 +1362,30 @@ event_persist_closure(struct event_base *base, struct event *ev)
                                relative_to = ev->ev_timeout;
                                relative_to.tv_usec &= MICROSECONDS_MASK;
                        } else {
-                               gettime(base, &relative_to);
+                               relative_to = now;
                        }
-                       evutil_timeradd(&relative_to, &delay, &run_at);
-                       run_at.tv_usec |= usec_mask;
                } else {
-                       struct timeval relative_to;
+                       delay = ev->ev_io_timeout;
                        if (ev->ev_res & EV_TIMEOUT) {
                                relative_to = ev->ev_timeout;
                        } else {
-                               gettime(base, &relative_to);
+                               relative_to = now;
                        }
-                       evutil_timeradd(&ev->ev_io_timeout, &relative_to,
-                           &run_at);
                }
+               evutil_timeradd(&relative_to, &delay, &run_at);
+               if (evutil_timercmp(&run_at, &now, <)) {
+                       /* Looks like we missed at least one invocation due to
+                        * a clock jump, not running the event loop for a
+                        * while, really slow callbacks, or
+                        * something. Reschedule relative to now.
+                        */
+                       evutil_timeradd(&now, &delay, &run_at);
+               }
+               run_at.tv_usec |= usec_mask;
                event_add_internal(ev, &run_at, 1);
        }
        EVBASE_RELEASE_LOCK(base, th_base_lock);
-       (*ev->ev_callback)((int)ev->ev_fd, ev->ev_res, ev->ev_arg);
+       (*ev->ev_callback)(ev->ev_fd, ev->ev_res, ev->ev_arg);
 }
 
 /*
@@ -1342,8 +1420,8 @@ event_process_active_single_queue(struct event_base *base,
                        ev->ev_res & EV_WRITE ? "EV_WRITE " : " ",
                        ev->ev_callback));
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
                base->current_event = ev;
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
                base->current_event_waiters = 0;
 #endif
 
@@ -1358,13 +1436,13 @@ event_process_active_single_queue(struct event_base *base,
                case EV_CLOSURE_NONE:
                        EVBASE_RELEASE_LOCK(base, th_base_lock);
                        (*ev->ev_callback)(
-                               (int)ev->ev_fd, ev->ev_res, ev->ev_arg);
+                               ev->ev_fd, ev->ev_res, ev->ev_arg);
                        break;
                }
 
                EVBASE_ACQUIRE_LOCK(base, th_base_lock);
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
                base->current_event = NULL;
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
                if (base->current_event_waiters) {
                        base->current_event_waiters = 0;
                        EVTHREAD_COND_BROADCAST(base->current_event_cond);
@@ -1382,6 +1460,8 @@ event_process_active_single_queue(struct event_base *base,
                        if (evutil_timercmp(&now, endtime, >=))
                                return count;
                }
+               if (base->event_continue)
+                       break;
        }
        return count;
 }
@@ -1454,6 +1534,7 @@ event_process_active(struct event_base *base)
 
        for (i = 0; i < base->nactivequeues; ++i) {
                if (TAILQ_FIRST(&base->activequeues[i]) != NULL) {
+                       base->event_running_priority = i;
                        activeq = &base->activequeues[i];
                        if (i < limit_after_prio)
                                c = event_process_active_single_queue(base, activeq,
@@ -1461,9 +1542,10 @@ event_process_active(struct event_base *base)
                        else
                                c = event_process_active_single_queue(base, activeq,
                                    maxcb, endtime);
-                       if (c < 0)
+                       if (c < 0) {
+                               base->event_running_priority = -1;
                                return -1;
-                       else if (c > 0)
+                       else if (c > 0)
                                break; /* Processed a real event; do not
                                        * consider lower-priority events */
                        /* If we get here, all of the events we processed
@@ -1473,6 +1555,7 @@ event_process_active(struct event_base *base)
 
        event_process_deferred_callbacks(&base->defer_queue,&base->event_break,
            maxcb-c, endtime);
+       base->event_running_priority = -1;
        return c;
 }
 
@@ -1599,17 +1682,19 @@ event_base_loop(struct event_base *base, int flags)
        clear_time_cache(base);
 
        if (base->sig.ev_signal_added && base->sig.ev_n_signals_added)
-               evsig_set_base(base);
+               evsig_set_base_(base);
 
        done = 0;
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        base->th_owner_id = EVTHREAD_GET_ID();
 #endif
 
        base->event_gotterm = base->event_break = 0;
 
        while (!done) {
+               base->event_continue = 0;
+
                /* Terminate the loop if we have been asked to */
                if (base->event_gotterm) {
                        break;
@@ -1619,8 +1704,6 @@ event_base_loop(struct event_base *base, int flags)
                        break;
                }
 
-               timeout_correct(base, &tv);
-
                tv_p = &tv;
                if (!N_ACTIVE_CALLBACKS(base) && !(flags & EVLOOP_NONBLOCK)) {
                        timeout_next(base, &tv_p);
@@ -1633,15 +1716,13 @@ event_base_loop(struct event_base *base, int flags)
                }
 
                /* If we have no events, we just exit */
-               if (!event_haveevents(base) && !N_ACTIVE_CALLBACKS(base)) {
+               if (0==(flags&EVLOOP_NO_EXIT_ON_EMPTY) &&
+                   !event_haveevents(base) && !N_ACTIVE_CALLBACKS(base)) {
                        event_debug(("%s: no events registered.", __func__));
                        retval = 1;
                        goto done;
                }
 
-               /* update last old time */
-               gettime(base, &base->event_tv);
-
                clear_time_cache(base);
 
                res = evsel->dispatch(base, tv_p);
@@ -1713,7 +1794,6 @@ event_base_once(struct event_base *base, evutil_socket_t fd, short events,
     void *arg, const struct timeval *tv)
 {
        struct event_once *eonce;
-       struct timeval etv;
        int res = 0;
 
        /* We cannot support signals that just fire once, or persistent
@@ -1728,12 +1808,16 @@ event_base_once(struct event_base *base, evutil_socket_t fd, short events,
        eonce->arg = arg;
 
        if (events == EV_TIMEOUT) {
-               if (tv == NULL) {
-                       evutil_timerclear(&etv);
-                       tv = &etv;
-               }
-
                evtimer_assign(&eonce->ev, base, event_once_cb, eonce);
+
+               if (tv == NULL || ! evutil_timerisset(tv)) {
+                       /* If the event is going to become active immediately,
+                        * don't put it on the timeout queue.  This is one
+                        * idiom for scheduling a callback, so let's make
+                        * it fast (and order-preserving). */
+                       event_active(&eonce->ev, EV_TIMEOUT, 1);
+                       return 0;
+               }
        } else if (events & (EV_READ|EV_WRITE)) {
                events &= EV_READ|EV_WRITE;
 
@@ -1759,8 +1843,10 @@ event_assign(struct event *ev, struct event_base *base, evutil_socket_t fd, shor
 {
        if (!base)
                base = current_base;
+       if (arg == &event_self_cbarg_ptr_)
+               arg = ev;
 
-       _event_debug_assert_not_added(ev);
+       event_debug_assert_not_added_(ev);
 
        ev->ev_base = base;
 
@@ -1789,14 +1875,14 @@ event_assign(struct event *ev, struct event_base *base, evutil_socket_t fd, shor
                }
        }
 
-       min_heap_elem_init(ev);
+       min_heap_elem_init_(ev);
 
        if (base != NULL) {
                /* by default, we put new events into the middle priority */
                ev->ev_pri = base->nactivequeues / 2;
        }
 
-       _event_debug_note_setup(ev);
+       event_debug_note_setup_(ev);
 
        return 0;
 }
@@ -1808,7 +1894,7 @@ event_base_set(struct event_base *base, struct event *ev)
        if (ev->ev_flags != EVLIST_INIT)
                return (-1);
 
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
 
        ev->ev_base = base;
        ev->ev_pri = base->nactivequeues/2;
@@ -1825,6 +1911,23 @@ event_set(struct event *ev, evutil_socket_t fd, short events,
        EVUTIL_ASSERT(r == 0);
 }
 
+void *
+event_self_cbarg(void)
+{
+       return &event_self_cbarg_ptr_;
+}
+
+struct event *
+event_base_get_running_event(struct event_base *base)
+{
+       struct event *ev = NULL;
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+       if (EVBASE_IN_THREAD(base))
+               ev = base->current_event;
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+       return ev;
+}
+
 struct event *
 event_new(struct event_base *base, evutil_socket_t fd, short events, void (*cb)(evutil_socket_t, short, void *), void *arg)
 {
@@ -1843,11 +1946,11 @@ event_new(struct event_base *base, evutil_socket_t fd, short events, void (*cb)(
 void
 event_free(struct event *ev)
 {
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
 
        /* make sure that this event won't be coming back to haunt us. */
        event_del(ev);
-       _event_debug_note_teardown(ev);
+       event_debug_note_teardown_(ev);
        mm_free(ev);
 
 }
@@ -1855,8 +1958,8 @@ event_free(struct event *ev)
 void
 event_debug_unassign(struct event *ev)
 {
-       _event_debug_assert_not_added(ev);
-       _event_debug_note_teardown(ev);
+       event_debug_assert_not_added_(ev);
+       event_debug_note_teardown_(ev);
 
        ev->ev_flags &= ~EVLIST_INIT;
 }
@@ -1869,7 +1972,7 @@ event_debug_unassign(struct event *ev)
 int
 event_priority_set(struct event *ev, int pri)
 {
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
 
        if (ev->ev_flags & EVLIST_ACTIVE)
                return (-1);
@@ -1890,7 +1993,7 @@ event_pending(const struct event *ev, short event, struct timeval *tv)
 {
        int flags = 0;
 
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
 
        if (ev->ev_flags & EVLIST_INSERTED)
                flags |= (ev->ev_events & (EV_READ|EV_WRITE|EV_SIGNAL));
@@ -1905,12 +2008,8 @@ event_pending(const struct event *ev, short event, struct timeval *tv)
        if (tv != NULL && (flags & event & EV_TIMEOUT)) {
                struct timeval tmp = ev->ev_timeout;
                tmp.tv_usec &= MICROSECONDS_MASK;
-#if defined(_EVENT_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
                /* correctly remamp to real time */
                evutil_timeradd(&ev->ev_base->tv_clock_diff, &tmp, tv);
-#else
-               *tv = tmp;
-#endif
        }
 
        return (flags & event);
@@ -1928,7 +2027,7 @@ event_initialized(const struct event *ev)
 void
 event_get_assignment(const struct event *event, struct event_base **base_out, evutil_socket_t *fd_out, short *events_out, event_callback_fn *callback_out, void **arg_out)
 {
-       _event_debug_assert_is_setup(event);
+       event_debug_assert_is_setup_(event);
 
        if (base_out)
                *base_out = event->ev_base;
@@ -1951,35 +2050,35 @@ event_get_struct_event_size(void)
 evutil_socket_t
 event_get_fd(const struct event *ev)
 {
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
        return ev->ev_fd;
 }
 
 struct event_base *
 event_get_base(const struct event *ev)
 {
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
        return ev->ev_base;
 }
 
 short
 event_get_events(const struct event *ev)
 {
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
        return ev->ev_events;
 }
 
 event_callback_fn
 event_get_callback(const struct event *ev)
 {
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
        return ev->ev_callback;
 }
 
 void *
 event_get_callback_arg(const struct event *ev)
 {
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
        return ev->ev_arg;
 }
 
@@ -2020,7 +2119,7 @@ evthread_notify_base_default(struct event_base *base)
        return (r < 0 && errno != EAGAIN) ? -1 : 0;
 }
 
-#if defined(_EVENT_HAVE_EVENTFD) && defined(_EVENT_HAVE_SYS_EVENTFD_H)
+#ifdef EVENT__HAVE_EVENTFD
 /* Helper callback: wake an event_base from another thread.  This version
  * assumes that you have a working eventfd() implementation. */
 static int
@@ -2036,6 +2135,7 @@ evthread_notify_base_eventfd(struct event_base *base)
 }
 #endif
 
+
 /** Tell the thread currently running the event_loop for base (if any) that it
  * needs to stop waiting in its dispatch function (if it is) and process all
  * active events and deferred callbacks (if there are any).  */
@@ -2064,7 +2164,7 @@ event_add_internal(struct event *ev, const struct timeval *tv,
        int notify = 0;
 
        EVENT_BASE_ASSERT_LOCKED(base);
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
 
        event_debug((
                 "event_add: event: %p (fd %d), %s%s%scall %p",
@@ -2082,8 +2182,8 @@ event_add_internal(struct event *ev, const struct timeval *tv,
         * failure on any step, we should not change any state.
         */
        if (tv != NULL && !(ev->ev_flags & EVLIST_TIMEOUT)) {
-               if (min_heap_reserve(&base->timeheap,
-                       1 + min_heap_size(&base->timeheap)) == -1)
+               if (min_heap_reserve_(&base->timeheap,
+                       1 + min_heap_size_(&base->timeheap)) == -1)
                        return (-1);  /* ENOMEM == errno */
        }
 
@@ -2091,7 +2191,7 @@ event_add_internal(struct event *ev, const struct timeval *tv,
         * callback, and we are not the main thread, then we want to wait
         * until the callback is done before we mess with the event, or else
         * we can race on ev_ncalls and ev_pncalls below. */
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        if (base->current_event == ev && (ev->ev_events & EV_SIGNAL)
            && !EVBASE_IN_THREAD(base)) {
                ++base->current_event_waiters;
@@ -2102,9 +2202,9 @@ event_add_internal(struct event *ev, const struct timeval *tv,
        if ((ev->ev_events & (EV_READ|EV_WRITE|EV_SIGNAL)) &&
            !(ev->ev_flags & (EVLIST_INSERTED|EVLIST_ACTIVE))) {
                if (ev->ev_events & (EV_READ|EV_WRITE))
-                       res = evmap_io_add(base, ev->ev_fd, ev);
+                       res = evmap_io_add_(base, ev->ev_fd, ev);
                else if (ev->ev_events & EV_SIGNAL)
-                       res = evmap_signal_add(base, (int)ev->ev_fd, ev);
+                       res = evmap_signal_add_(base, (int)ev->ev_fd, ev);
                if (res != -1)
                        event_queue_insert_inserted(base, ev);
                if (res == 1) {
@@ -2121,6 +2221,10 @@ event_add_internal(struct event *ev, const struct timeval *tv,
        if (res != -1 && tv != NULL) {
                struct timeval now;
                int common_timeout;
+#ifdef USE_REINSERT_TIMEOUT
+               int was_common;
+               int old_timeout_idx;
+#endif
 
                /*
                 * for persistent timeout events, we remember the
@@ -2131,6 +2235,12 @@ event_add_internal(struct event *ev, const struct timeval *tv,
                if (ev->ev_closure == EV_CLOSURE_PERSIST && !tv_is_absolute)
                        ev->ev_io_timeout = *tv;
 
+#ifndef USE_REINSERT_TIMEOUT
+               if (ev->ev_flags & EVLIST_TIMEOUT) {
+                       event_queue_remove_timeout(base, ev);
+               }
+#endif
+
                /* Check if it is active due to a timeout.  Rescheduling
                 * this timeout before the callback can be executed
                 * removes it from the active list. */
@@ -2152,6 +2262,11 @@ event_add_internal(struct event *ev, const struct timeval *tv,
                gettime(base, &now);
 
                common_timeout = is_common_timeout(tv, base);
+#ifdef USE_REINSERT_TIMEOUT
+               was_common = is_common_timeout(&ev->ev_timeout, base);
+               old_timeout_idx = COMMON_TIMEOUT_IDX(&ev->ev_timeout);
+#endif
+
                if (tv_is_absolute) {
                        ev->ev_timeout = *tv;
                } else if (common_timeout) {
@@ -2168,7 +2283,11 @@ event_add_internal(struct event *ev, const struct timeval *tv,
                         "event_add: event %p, timeout in %d seconds %d useconds, call %p",
                         ev, (int)tv->tv_sec, (int)tv->tv_usec, ev->ev_callback));
 
-               event_queue_reinsert_timeout(base, ev);
+#ifdef USE_REINSERT_TIMEOUT
+               event_queue_reinsert_timeout(base, ev, was_common, common_timeout, old_timeout_idx);
+#else
+               event_queue_insert_timeout(base, ev);
+#endif
 
                if (common_timeout) {
                        struct common_timeout_list *ctl =
@@ -2181,7 +2300,7 @@ event_add_internal(struct event *ev, const struct timeval *tv,
                         * was before: if so, we will need to tell the main
                         * thread to wake up earlier than it would
                         * otherwise. */
-                       if (min_heap_elt_is_top(ev))
+                       if (min_heap_elt_is_top_(ev))
                                notify = 1;
                }
        }
@@ -2190,7 +2309,7 @@ event_add_internal(struct event *ev, const struct timeval *tv,
        if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
                evthread_notify_base(base);
 
-       _event_debug_note_add(ev);
+       event_debug_note_add_(ev);
 
        return (res);
 }
@@ -2236,7 +2355,7 @@ event_del_internal(struct event *ev)
         * when this function returns, it will be safe to free the
         * user-supplied argument. */
        base = ev->ev_base;
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        if (base->current_event == ev && !EVBASE_IN_THREAD(base)) {
                ++base->current_event_waiters;
                EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
@@ -2270,9 +2389,9 @@ event_del_internal(struct event *ev)
        if (ev->ev_flags & EVLIST_INSERTED) {
                event_queue_remove_inserted(base, ev);
                if (ev->ev_events & (EV_READ|EV_WRITE))
-                       res = evmap_io_del(base, ev->ev_fd, ev);
+                       res = evmap_io_del_(base, ev->ev_fd, ev);
                else
-                       res = evmap_signal_del(base, (int)ev->ev_fd, ev);
+                       res = evmap_signal_del_(base, (int)ev->ev_fd, ev);
                if (res == 1) {
                        /* evmap says we need to notify the main thread. */
                        notify = 1;
@@ -2284,7 +2403,7 @@ event_del_internal(struct event *ev)
        if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
                evthread_notify_base(base);
 
-       _event_debug_note_del(ev);
+       event_debug_note_del_(ev);
 
        return (res);
 }
@@ -2299,16 +2418,16 @@ event_active(struct event *ev, int res, short ncalls)
 
        EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
 
-       _event_debug_assert_is_setup(ev);
+       event_debug_assert_is_setup_(ev);
 
-       event_active_nolock(ev, res, ncalls);
+       event_active_nolock_(ev, res, ncalls);
 
        EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
 }
 
 
 void
-event_active_nolock(struct event *ev, int res, short ncalls)
+event_active_nolock_(struct event *ev, int res, short ncalls)
 {
        struct event_base *base;
 
@@ -2328,8 +2447,11 @@ event_active_nolock(struct event *ev, int res, short ncalls)
 
        ev->ev_res = res;
 
+       if (ev->ev_pri < base->event_running_priority)
+               base->event_continue = 1;
+
        if (ev->ev_events & EV_SIGNAL) {
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
                if (base->current_event == ev && !EVBASE_IN_THREAD(base)) {
                        ++base->current_event_waiters;
                        EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
@@ -2346,7 +2468,7 @@ event_active_nolock(struct event *ev, int res, short ncalls)
 }
 
 void
-event_deferred_cb_init(struct deferred_cb *cb, deferred_cb_fn fn, void *arg)
+event_deferred_cb_init_(struct deferred_cb *cb, deferred_cb_fn fn, void *arg)
 {
        memset(cb, 0, sizeof(struct deferred_cb));
        cb->cb = fn;
@@ -2354,7 +2476,7 @@ event_deferred_cb_init(struct deferred_cb *cb, deferred_cb_fn fn, void *arg)
 }
 
 void
-event_deferred_cb_cancel(struct deferred_cb_queue *queue,
+event_deferred_cb_cancel_(struct deferred_cb_queue *queue,
     struct deferred_cb *cb)
 {
        if (!queue) {
@@ -2374,7 +2496,7 @@ event_deferred_cb_cancel(struct deferred_cb_queue *queue,
 }
 
 void
-event_deferred_cb_schedule(struct deferred_cb_queue *queue,
+event_deferred_cb_schedule_(struct deferred_cb_queue *queue,
     struct deferred_cb *cb)
 {
        if (!queue) {
@@ -2404,7 +2526,7 @@ timeout_next(struct event_base *base, struct timeval **tv_p)
        struct timeval *tv = *tv_p;
        int res = 0;
 
-       ev = min_heap_top(&base->timeheap);
+       ev = min_heap_top_(&base->timeheap);
 
        if (ev == NULL) {
                /* if no time-based events are active wait for I/O */
@@ -2432,64 +2554,6 @@ out:
        return (res);
 }
 
-/*
- * Determines if the time is running backwards by comparing the current time
- * against the last time we checked.  Not needed when using clock monotonic.
- * If time is running backwards, we adjust the firing time of every event by
- * the amount that time seems to have jumped.
- */
-static void
-timeout_correct(struct event_base *base, struct timeval *tv)
-{
-       /* Caller must hold th_base_lock. */
-       struct event **pev;
-       unsigned int size;
-       struct timeval off;
-       int i;
-
-       if (use_monotonic)
-               return;
-
-       /* Check if time is running backwards */
-       gettime(base, tv);
-
-       if (evutil_timercmp(tv, &base->event_tv, >=)) {
-               base->event_tv = *tv;
-               return;
-       }
-
-       event_debug(("%s: time is running backwards, corrected",
-                   __func__));
-       evutil_timersub(&base->event_tv, tv, &off);
-
-       /*
-        * We can modify the key element of the node without destroying
-        * the minheap property, because we change every element.
-        */
-       pev = base->timeheap.p;
-       size = base->timeheap.n;
-       for (; size-- > 0; ++pev) {
-               struct timeval *ev_tv = &(**pev).ev_timeout;
-               evutil_timersub(ev_tv, &off, ev_tv);
-       }
-       for (i=0; i<base->n_common_timeouts; ++i) {
-               struct event *ev;
-               struct common_timeout_list *ctl =
-                   base->common_timeout_queues[i];
-               TAILQ_FOREACH(ev, &ctl->events,
-                   ev_timeout_pos.ev_next_with_common_timeout) {
-                       struct timeval *ev_tv = &ev->ev_timeout;
-                       ev_tv->tv_usec &= MICROSECONDS_MASK;
-                       evutil_timersub(ev_tv, &off, ev_tv);
-                       ev_tv->tv_usec |= COMMON_TIMEOUT_MAGIC |
-                           (i<<COMMON_TIMEOUT_IDX_SHIFT);
-               }
-       }
-
-       /* Now remember what the new time turned out to be. */
-       base->event_tv = *tv;
-}
-
 /* Activate every event whose timeout has elapsed. */
 static void
 timeout_process(struct event_base *base)
@@ -2498,13 +2562,13 @@ timeout_process(struct event_base *base)
        struct timeval now;
        struct event *ev;
 
-       if (min_heap_empty(&base->timeheap)) {
+       if (min_heap_empty_(&base->timeheap)) {
                return;
        }
 
        gettime(base, &now);
 
-       while ((ev = min_heap_top(&base->timeheap))) {
+       while ((ev = min_heap_top_(&base->timeheap))) {
                if (evutil_timercmp(&ev->ev_timeout, &now, >))
                        break;
 
@@ -2513,7 +2577,7 @@ timeout_process(struct event_base *base)
 
                event_debug(("timeout_process: event: %p, call %p",
                         ev, ev->ev_callback));
-               event_active_nolock(ev, EV_TIMEOUT, 1);
+               event_active_nolock_(ev, EV_TIMEOUT, 1);
        }
 }
 
@@ -2540,7 +2604,6 @@ event_queue_remove_inserted(struct event_base *base, struct event *ev)
        }
        DECR_EVENT_COUNT(base, ev);
        ev->ev_flags &= ~EVLIST_INSERTED;
-       TAILQ_REMOVE(&base->eventqueue, ev, ev_next);
 }
 static void
 event_queue_remove_active(struct event_base *base, struct event *ev)
@@ -2575,29 +2638,50 @@ event_queue_remove_timeout(struct event_base *base, struct event *ev)
                TAILQ_REMOVE(&ctl->events, ev,
                    ev_timeout_pos.ev_next_with_common_timeout);
        } else {
-               min_heap_erase(&base->timeheap, ev);
+               min_heap_erase_(&base->timeheap, ev);
        }
 }
 
+#ifdef USE_REINSERT_TIMEOUT
 /* Remove and reinsert 'ev' into the timeout queue. */
 static void
-event_queue_reinsert_timeout(struct event_base *base, struct event *ev)
+event_queue_reinsert_timeout(struct event_base *base, struct event *ev,
+    int was_common, int is_common, int old_timeout_idx)
 {
+       struct common_timeout_list *ctl;
        if (!(ev->ev_flags & EVLIST_TIMEOUT)) {
                event_queue_insert_timeout(base, ev);
                return;
        }
 
-       if (is_common_timeout(&ev->ev_timeout, base)) {
-               struct common_timeout_list *ctl =
-                   get_common_timeout_list(base, &ev->ev_timeout);
+       switch ((was_common<<1) | is_common) {
+       case 3: /* Changing from one common timeout to another */
+               ctl = base->common_timeout_queues[old_timeout_idx];
                TAILQ_REMOVE(&ctl->events, ev,
                    ev_timeout_pos.ev_next_with_common_timeout);
+               ctl = get_common_timeout_list(base, &ev->ev_timeout);
                insert_common_timeout_inorder(ctl, ev);
-       } else {
-               min_heap_adjust(&base->timeheap, ev);
+               break;
+       case 2: /* Was common; is no longer common */
+               ctl = base->common_timeout_queues[old_timeout_idx];
+               TAILQ_REMOVE(&ctl->events, ev,
+                   ev_timeout_pos.ev_next_with_common_timeout);
+               min_heap_push_(&base->timeheap, ev);
+               break;
+       case 1: /* Wasn't common; has become common. */
+               min_heap_erase_(&base->timeheap, ev);
+               ctl = get_common_timeout_list(base, &ev->ev_timeout);
+               insert_common_timeout_inorder(ctl, ev);
+               break;
+       case 0: /* was in heap; is still on heap. */
+               min_heap_adjust_(&base->timeheap, ev);
+               break;
+       default:
+               EVUTIL_ASSERT(0); /* unreachable */
+               break;
        }
 }
+#endif
 
 /* Add 'ev' to the common timeout list in 'ev'. */
 static void
@@ -2644,8 +2728,6 @@ event_queue_insert_inserted(struct event_base *base, struct event *ev)
        INCR_EVENT_COUNT(base, ev);
 
        ev->ev_flags |= EVLIST_INSERTED;
-
-       TAILQ_INSERT_TAIL(&base->eventqueue, ev, ev_next);
 }
 
 static void
@@ -2687,7 +2769,7 @@ event_queue_insert_timeout(struct event_base *base, struct event *ev)
                    get_common_timeout_list(base, &ev->ev_timeout);
                insert_common_timeout_inorder(ctl, ev);
        } else {
-               min_heap_push(&base->timeheap, ev);
+               min_heap_push_(&base->timeheap, ev);
        }
 }
 
@@ -2696,13 +2778,13 @@ event_queue_insert_timeout(struct event_base *base, struct event *ev)
 const char *
 event_get_version(void)
 {
-       return (_EVENT_VERSION);
+       return (EVENT__VERSION);
 }
 
 ev_uint32_t
 event_get_version_number(void)
 {
-       return (_EVENT_NUMERIC_VERSION);
+       return (EVENT__NUMERIC_VERSION);
 }
 
 /*
@@ -2716,16 +2798,19 @@ event_get_method(void)
        return (current_base->evsel->name);
 }
 
-#ifndef _EVENT_DISABLE_MM_REPLACEMENT
-static void *(*_mm_malloc_fn)(size_t sz) = NULL;
-static void *(*_mm_realloc_fn)(void *p, size_t sz) = NULL;
-static void (*_mm_free_fn)(void *p) = NULL;
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+static void *(*mm_malloc_fn_)(size_t sz) = NULL;
+static void *(*mm_realloc_fn_)(void *p, size_t sz) = NULL;
+static void (*mm_free_fn_)(void *p) = NULL;
 
 void *
 event_mm_malloc_(size_t sz)
 {
-       if (_mm_malloc_fn)
-               return _mm_malloc_fn(sz);
+       if (sz == 0)
+               return NULL;
+
+       if (mm_malloc_fn_)
+               return mm_malloc_fn_(sz);
        else
                return malloc(sz);
 }
@@ -2733,38 +2818,65 @@ event_mm_malloc_(size_t sz)
 void *
 event_mm_calloc_(size_t count, size_t size)
 {
-       if (_mm_malloc_fn) {
+       if (count == 0 || size == 0)
+               return NULL;
+
+       if (mm_malloc_fn_) {
                size_t sz = count * size;
-               void *p = _mm_malloc_fn(sz);
+               void *p = NULL;
+               if (count > EV_SIZE_MAX / size)
+                       goto error;
+               p = mm_malloc_fn_(sz);
                if (p)
-                       memset(p, 0, sz);
+                       return memset(p, 0, sz);
+       } else {
+               void *p = calloc(count, size);
+#ifdef _WIN32
+               /* Windows calloc doesn't reliably set ENOMEM */
+               if (p == NULL)
+                       goto error;
+#endif
                return p;
-       } else
-               return calloc(count, size);
+       }
+
+error:
+       errno = ENOMEM;
+       return NULL;
 }
 
 char *
 event_mm_strdup_(const char *str)
 {
-       if (_mm_malloc_fn) {
+       if (!str) {
+               errno = EINVAL;
+               return NULL;
+       }
+
+       if (mm_malloc_fn_) {
                size_t ln = strlen(str);
-               void *p = _mm_malloc_fn(ln+1);
+               void *p = NULL;
+               if (ln == EV_SIZE_MAX)
+                       goto error;
+               p = mm_malloc_fn_(ln+1);
                if (p)
-                       memcpy(p, str, ln+1);
-               return p;
+                       return memcpy(p, str, ln+1);
        } else
 #ifdef _WIN32
                return _strdup(str);
 #else
                return strdup(str);
 #endif
+
+error:
+       errno = ENOMEM;
+       return NULL;
 }
 
 void *
 event_mm_realloc_(void *ptr, size_t sz)
 {
-       if (_mm_realloc_fn)
-               return _mm_realloc_fn(ptr, sz);
+       if (mm_realloc_fn_)
+               return mm_realloc_fn_(ptr, sz);
        else
                return realloc(ptr, sz);
 }
@@ -2772,8 +2884,8 @@ event_mm_realloc_(void *ptr, size_t sz)
 void
 event_mm_free_(void *ptr)
 {
-       if (_mm_free_fn)
-               _mm_free_fn(ptr);
+       if (mm_free_fn_)
+               mm_free_fn_(ptr);
        else
                free(ptr);
 }
@@ -2783,13 +2895,13 @@ event_set_mem_functions(void *(*malloc_fn)(size_t sz),
                        void *(*realloc_fn)(void *ptr, size_t sz),
                        void (*free_fn)(void *ptr))
 {
-       _mm_malloc_fn = malloc_fn;
-       _mm_realloc_fn = realloc_fn;
-       _mm_free_fn = free_fn;
+       mm_malloc_fn_ = malloc_fn;
+       mm_realloc_fn_ = realloc_fn;
+       mm_free_fn_ = free_fn;
 }
 #endif
 
-#if defined(_EVENT_HAVE_EVENTFD) && defined(_EVENT_HAVE_SYS_EVENTFD_H)
+#ifdef EVENT__HAVE_EVENTFD
 static void
 evthread_notify_drain_eventfd(evutil_socket_t fd, short what, void *arg)
 {
@@ -2828,8 +2940,8 @@ evthread_notify_drain_default(evutil_socket_t fd, short what, void *arg)
 int
 evthread_make_base_notifiable(struct event_base *base)
 {
-       void (*cb)(evutil_socket_t, short, void *) = evthread_notify_drain_default;
-       int (*notify)(struct event_base *) = evthread_notify_base_default;
+       void (*cb)(evutil_socket_t, short, void *);
+       int (*notify)(struct event_base *);
 
        /* XXXX grab the lock here? */
        if (!base)
@@ -2840,61 +2952,34 @@ evthread_make_base_notifiable(struct event_base *base)
                return 0;
        }
 
-#if defined(_EVENT_HAVE_EVENTFD) && defined(_EVENT_HAVE_SYS_EVENTFD_H)
-#ifndef EFD_CLOEXEC
-#define EFD_CLOEXEC 0
+
+#if defined(EVENT__HAVE_WORKING_KQUEUE)
+       if (base->evsel == &kqops && event_kq_add_notify_event_(base) == 0) {
+               base->th_notify_fn = event_kq_notify_base_;
+               /* No need to add an event here; the backend can wake
+                * itself up just fine. */
+               return 0;
+       }
 #endif
-       base->th_notify_fd[0] = eventfd(0, EFD_CLOEXEC);
+
+#ifdef EVENT__HAVE_EVENTFD
+       base->th_notify_fd[0] = evutil_eventfd_(0,
+           EVUTIL_EFD_CLOEXEC|EVUTIL_EFD_NONBLOCK);
        if (base->th_notify_fd[0] >= 0) {
-               evutil_make_socket_closeonexec(base->th_notify_fd[0]);
+               base->th_notify_fd[1] = -1;
                notify = evthread_notify_base_eventfd;
                cb = evthread_notify_drain_eventfd;
-       }
-#endif
-#if defined(_EVENT_HAVE_PIPE)
-       if (base->th_notify_fd[0] < 0) {
-               if ((base->evsel->features & EV_FEATURE_FDS)) {
-                       if (pipe(base->th_notify_fd) < 0) {
-                               event_warn("%s: pipe", __func__);
-                       } else {
-                               evutil_make_socket_closeonexec(base->th_notify_fd[0]);
-                               evutil_make_socket_closeonexec(base->th_notify_fd[1]);
-                       }
-               }
-       }
-#endif
-
-#ifdef _WIN32
-#define LOCAL_SOCKETPAIR_AF AF_INET
-#else
-#define LOCAL_SOCKETPAIR_AF AF_UNIX
+       } else
 #endif
-       if (base->th_notify_fd[0] < 0) {
-               if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0,
-                       base->th_notify_fd) == -1) {
-                       event_sock_warn(-1, "%s: socketpair", __func__);
-                       return (-1);
-               } else {
-                       evutil_make_socket_closeonexec(base->th_notify_fd[0]);
-                       evutil_make_socket_closeonexec(base->th_notify_fd[1]);
-               }
+       if (evutil_make_internal_pipe_(base->th_notify_fd) == 0) {
+               notify = evthread_notify_base_default;
+               cb = evthread_notify_drain_default;
+       } else {
+               return -1;
        }
 
-       evutil_make_socket_nonblocking(base->th_notify_fd[0]);
-
        base->th_notify_fn = notify;
 
-       /*
-         Making the second socket nonblocking is a bit subtle, given that we
-         ignore any EAGAIN returns when writing to it, and you don't usally
-         do that for a nonblocking socket. But if the kernel gives us EAGAIN,
-         then there's no need to add any more data to the buffer, since
-         the main thread is already either about to wake up and drain it,
-         or woken up and in the process of draining it.
-       */
-       if (base->th_notify_fd[1] > 0)
-               evutil_make_socket_nonblocking(base->th_notify_fd[1]);
-
        /* prepare an event that we can use for wakeup */
        event_assign(&base->th_notify, base, base->th_notify_fd[0],
                                 EV_READ|EV_PERSIST, cb, base);
@@ -2906,39 +2991,129 @@ evthread_make_base_notifiable(struct event_base *base)
        return event_add(&base->th_notify, NULL);
 }
 
-void
-event_base_dump_events(struct event_base *base, FILE *output)
+int
+event_base_foreach_event_(struct event_base *base,
+    int (*fn)(struct event_base *, struct event *, void *), void *arg)
 {
-       struct event *e;
-       int i;
-       fprintf(output, "Inserted events:\n");
-       TAILQ_FOREACH(e, &base->eventqueue, ev_next) {
-               fprintf(output, "  %p [fd %ld]%s%s%s%s%s\n",
-                               (void*)e, (long)e->ev_fd,
-                               (e->ev_events&EV_READ)?" Read":"",
-                               (e->ev_events&EV_WRITE)?" Write":"",
-                               (e->ev_events&EV_SIGNAL)?" Signal":"",
-                               (e->ev_events&EV_TIMEOUT)?" Timeout":"",
-                               (e->ev_events&EV_PERSIST)?" Persist":"");
+       int r, i;
+       unsigned u;
+       struct event *ev;
+
+       /* Start out with all the EVLIST_INSERTED events. */
+       if ((r = evmap_foreach_event_(base, fn, arg)))
+               return r;
+
+       /* Okay, now we deal with those events that have timeouts and are in
+        * the min-heap. */
+       for (u = 0; u < base->timeheap.n; ++u) {
+               ev = base->timeheap.p[u];
+               if (ev->ev_flags & EVLIST_INSERTED) {
+                       /* we already processed this one */
+                       continue;
+               }
+               if ((r = fn(base, ev, arg)))
+                       return r;
+       }
 
+       /* Now for the events in one of the timeout queues.
+        * the min-heap. */
+       for (i = 0; i < base->n_common_timeouts; ++i) {
+               struct common_timeout_list *ctl =
+                   base->common_timeout_queues[i];
+               TAILQ_FOREACH(ev, &ctl->events,
+                   ev_timeout_pos.ev_next_with_common_timeout) {
+                       if (ev->ev_flags & EVLIST_INSERTED) {
+                               /* we already processed this one */
+                               continue;
+                       }
+                       if ((r = fn(base, ev, arg)))
+                               return r;
+               }
        }
+
+       /* Finally, we deal wit all the active events that we haven't touched
+        * yet. */
        for (i = 0; i < base->nactivequeues; ++i) {
-               if (TAILQ_EMPTY(&base->activequeues[i]))
-                       continue;
-               fprintf(output, "Active events [priority %d]:\n", i);
-               TAILQ_FOREACH(e, &base->eventqueue, ev_next) {
-                       fprintf(output, "  %p [fd %ld]%s%s%s%s\n",
-                                       (void*)e, (long)e->ev_fd,
-                                       (e->ev_res&EV_READ)?" Read active":"",
-                                       (e->ev_res&EV_WRITE)?" Write active":"",
-                                       (e->ev_res&EV_SIGNAL)?" Signal active":"",
-                                       (e->ev_res&EV_TIMEOUT)?" Timeout active":"");
+               TAILQ_FOREACH(ev, &base->activequeues[i], ev_active_next) {
+                       if (ev->ev_flags & (EVLIST_INSERTED|EVLIST_TIMEOUT)) {
+                               /* we already processed this one */
+                               continue;
+                       }
+                       if ((r = fn(base, ev, arg)))
+                               return r;
                }
        }
+
+       return 0;
+}
+
+/* Helper for event_base_dump_events: called on each event in the event base;
+ * dumps only the inserted events. */
+static int
+dump_inserted_event_fn(struct event_base *base, struct event *e, void *arg)
+{
+       FILE *output = arg;
+       const char *gloss = (e->ev_events & EV_SIGNAL) ?
+           "sig" : "fd ";
+
+       if (! (e->ev_flags & (EVLIST_INSERTED|EVLIST_TIMEOUT)))
+               return 0;
+
+       fprintf(output, "  %p [%s %ld]%s%s%s%s%s",
+           (void*)e, gloss, (long)e->ev_fd,
+           (e->ev_events&EV_READ)?" Read":"",
+           (e->ev_events&EV_WRITE)?" Write":"",
+           (e->ev_events&EV_SIGNAL)?" Signal":"",
+           (e->ev_events&EV_PERSIST)?" Persist":"",
+           (e->ev_flags&EVLIST_INTERNAL)?" Internal":"");
+       if (e->ev_flags & EVLIST_TIMEOUT) {
+               struct timeval tv;
+               tv.tv_sec = e->ev_timeout.tv_sec;
+               tv.tv_usec = e->ev_timeout.tv_usec & MICROSECONDS_MASK;
+               evutil_timeradd(&tv, &base->tv_clock_diff, &tv);
+               fprintf(output, " Timeout=%ld.%06d",
+                   (long)tv.tv_sec, (int)(tv.tv_usec & MICROSECONDS_MASK));
+       }
+       fputc('\n', output);
+
+       return 0;
+}
+
+/* Helper for event_base_dump_events: called on each event in the event base;
+ * dumps only the active events. */
+static int
+dump_active_event_fn(struct event_base *base, struct event *e, void *arg)
+{
+       FILE *output = arg;
+       const char *gloss = (e->ev_events & EV_SIGNAL) ?
+           "sig" : "fd ";
+
+       if (! (e->ev_flags & EVLIST_ACTIVE))
+               return 0;
+
+       fprintf(output, "  %p [%s %ld, priority=%d]%s%s%s%s active%s\n",
+           (void*)e, gloss, (long)e->ev_fd, e->ev_pri,
+           (e->ev_res&EV_READ)?" Read":"",
+           (e->ev_res&EV_WRITE)?" Write":"",
+           (e->ev_res&EV_SIGNAL)?" Signal":"",
+           (e->ev_res&EV_TIMEOUT)?" Timeout":"",
+           (e->ev_flags&EVLIST_INTERNAL)?" [Internal]":"");
+
+       return 0;
+}
+
+void
+event_base_dump_events(struct event_base *base, FILE *output)
+{
+       fprintf(output, "Inserted events:\n");
+       event_base_foreach_event_(base, dump_inserted_event_fn, output);
+
+       fprintf(output, "Active events:\n");
+       event_base_foreach_event_(base, dump_active_event_fn, output);
 }
 
 void
-event_base_add_virtual(struct event_base *base)
+event_base_add_virtual_(struct event_base *base)
 {
        EVBASE_ACQUIRE_LOCK(base, th_base_lock);
        base->virtual_event_count++;
@@ -2946,7 +3121,7 @@ event_base_add_virtual(struct event_base *base)
 }
 
 void
-event_base_del_virtual(struct event_base *base)
+event_base_del_virtual_(struct event_base *base)
 {
        EVBASE_ACQUIRE_LOCK(base, th_base_lock);
        EVUTIL_ASSERT(base->virtual_event_count > 0);
@@ -2956,12 +3131,58 @@ event_base_del_virtual(struct event_base *base)
        EVBASE_RELEASE_LOCK(base, th_base_lock);
 }
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+static void
+event_free_debug_globals_locks(void)
+{
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_DEBUG_MODE
+       if (event_debug_map_lock_ != NULL) {
+               EVTHREAD_FREE_LOCK(event_debug_map_lock_, 0);
+               event_debug_map_lock_ = NULL;
+       }
+#endif /* EVENT__DISABLE_DEBUG_MODE */
+#endif /* EVENT__DISABLE_THREAD_SUPPORT */
+       return;
+}
+
+static void
+event_free_debug_globals(void)
+{
+       event_free_debug_globals_locks();
+}
+
+static void
+event_free_evsig_globals(void)
+{
+       evsig_free_globals_();
+}
+
+static void
+event_free_evutil_globals(void)
+{
+       evutil_free_globals_();
+}
+
+static void
+event_free_globals(void)
+{
+       event_free_debug_globals();
+       event_free_evsig_globals();
+       event_free_evutil_globals();
+}
+
+void
+libevent_global_shutdown(void)
+{
+       event_free_globals();
+}
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
 int
 event_global_setup_locks_(const int enable_locks)
 {
-#ifndef _EVENT_DISABLE_DEBUG_MODE
-       EVTHREAD_SETUP_GLOBAL_LOCK(_event_debug_map_lock, 0);
+#ifndef EVENT__DISABLE_DEBUG_MODE
+       EVTHREAD_SETUP_GLOBAL_LOCK(event_debug_map_lock_, 0);
 #endif
        if (evsig_global_setup_locks_(enable_locks) < 0)
                return -1;
@@ -2970,3 +3191,53 @@ event_global_setup_locks_(const int enable_locks)
        return 0;
 }
 #endif
+
+void
+event_base_assert_ok_(struct event_base *base)
+{
+       int i;
+       EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+       /* First do checks on the per-fd and per-signal lists */
+       evmap_check_integrity_(base);
+
+       /* Check the heap property */
+       for (i = 1; i < (int)base->timeheap.n; ++i) {
+               int parent = (i - 1) / 2;
+               struct event *ev, *p_ev;
+               ev = base->timeheap.p[i];
+               p_ev = base->timeheap.p[parent];
+               EVUTIL_ASSERT(ev->ev_flags & EVLIST_TIMEOUT);
+               EVUTIL_ASSERT(evutil_timercmp(&p_ev->ev_timeout, &ev->ev_timeout, <=));
+               EVUTIL_ASSERT(ev->ev_timeout_pos.min_heap_idx == i);
+       }
+
+       /* Check that the common timeouts are fine */
+       for (i = 0; i < base->n_common_timeouts; ++i) {
+               struct common_timeout_list *ctl = base->common_timeout_queues[i];
+               struct event *last=NULL, *ev;
+
+               EVUTIL_ASSERT_TAILQ_OK(&ctl->events, event, ev_timeout_pos.ev_next_with_common_timeout);
+
+               TAILQ_FOREACH(ev, &ctl->events, ev_timeout_pos.ev_next_with_common_timeout) {
+                       if (last)
+                               EVUTIL_ASSERT(evutil_timercmp(&last->ev_timeout, &ev->ev_timeout, <=));
+                       EVUTIL_ASSERT(ev->ev_flags & EVLIST_TIMEOUT);
+                       EVUTIL_ASSERT(is_common_timeout(&ev->ev_timeout,base));
+                       EVUTIL_ASSERT(COMMON_TIMEOUT_IDX(&ev->ev_timeout) == i);
+                       last = ev;
+               }
+       }
+
+       /* Check the active queues. */
+       for (i = 0; i < base->nactivequeues; ++i) {
+               struct event *ev;
+               EVUTIL_ASSERT_TAILQ_OK(&base->activequeues[i], event, ev_active_next);
+               TAILQ_FOREACH(ev, &base->activequeues[i], ev_active_next) {
+                       EVUTIL_ASSERT(ev->ev_pri == i);
+                       EVUTIL_ASSERT(ev->ev_flags & EVLIST_ACTIVE);
+               }
+       }
+
+       EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
index 26ad64f2628040a61d46b5a4e33a9ab85315568b..c69946c4961d358d283685c8875217496389d2a3 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos, Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -46,7 +46,7 @@
 #define NOTIFICATION_KEY ((ULONG_PTR)-1)
 
 void
-event_overlapped_init(struct event_overlapped *o, iocp_callback cb)
+event_overlapped_init_(struct event_overlapped *o, iocp_callback cb)
 {
        memset(o, 0, sizeof(struct event_overlapped));
        o->cb = cb;
@@ -61,9 +61,9 @@ handle_entry(OVERLAPPED *o, ULONG_PTR completion_key, DWORD nBytes, int ok)
 }
 
 static void
-loop(void *_port)
+loop(void *port_)
 {
-       struct event_iocp_port *port = _port;
+       struct event_iocp_port *port = port_;
        long ms = port->ms;
        HANDLE p = port->port;
 
@@ -99,7 +99,7 @@ loop(void *_port)
 }
 
 int
-event_iocp_port_associate(struct event_iocp_port *port, evutil_socket_t fd,
+event_iocp_port_associate_(struct event_iocp_port *port, evutil_socket_t fd,
     ev_uintptr_t key)
 {
        HANDLE h;
@@ -162,7 +162,7 @@ static struct win32_extension_fns the_extension_fns;
 static int extension_fns_initialized = 0;
 
 const struct win32_extension_fns *
-event_get_win32_extension_fns(void)
+event_get_win32_extension_fns_(void)
 {
        return &the_extension_fns;
 }
@@ -170,7 +170,7 @@ event_get_win32_extension_fns(void)
 #define N_CPUS_DEFAULT 2
 
 struct event_iocp_port *
-event_iocp_port_launch(int n_cpus)
+event_iocp_port_launch_(int n_cpus)
 {
        struct event_iocp_port *port;
        int i;
@@ -184,7 +184,7 @@ event_iocp_port_launch(int n_cpus)
        if (n_cpus <= 0)
                n_cpus = N_CPUS_DEFAULT;
        port->n_threads = n_cpus * 2;
-       port->threads = calloc(port->n_threads, sizeof(HANDLE));
+       port->threads = mm_calloc(port->n_threads, sizeof(HANDLE));
        if (!port->threads)
                goto err;
 
@@ -221,7 +221,7 @@ err:
 }
 
 static void
-_event_iocp_port_unlock_and_free(struct event_iocp_port *port)
+event_iocp_port_unlock_and_free_(struct event_iocp_port *port)
 {
        DeleteCriticalSection(&port->lock);
        CloseHandle(port->port);
@@ -244,7 +244,7 @@ event_iocp_notify_all(struct event_iocp_port *port)
 }
 
 int
-event_iocp_shutdown(struct event_iocp_port *port, long waitMsec)
+event_iocp_shutdown_(struct event_iocp_port *port, long waitMsec)
 {
        DWORD ms = INFINITE;
        int n;
@@ -262,7 +262,7 @@ event_iocp_shutdown(struct event_iocp_port *port, long waitMsec)
        n = port->n_live_threads;
        LeaveCriticalSection(&port->lock);
        if (n == 0) {
-               _event_iocp_port_unlock_and_free(port);
+               event_iocp_port_unlock_and_free_(port);
                return 0;
        } else {
                return -1;
@@ -270,7 +270,7 @@ event_iocp_shutdown(struct event_iocp_port *port, long waitMsec)
 }
 
 int
-event_iocp_activate_overlapped(
+event_iocp_activate_overlapped_(
     struct event_iocp_port *port, struct event_overlapped *o,
     ev_uintptr_t key, ev_uint32_t n)
 {
@@ -281,7 +281,7 @@ event_iocp_activate_overlapped(
 }
 
 struct event_iocp_port *
-event_base_get_iocp(struct event_base *base)
+event_base_get_iocp_(struct event_base *base)
 {
 #ifdef _WIN32
        return base->iocp;
index 64c81de5b0dbc9b1855b76206f5760432f0a184d..256f5397948d00a2b6e1b1adcaf517fda4e5dbea 100755 (executable)
@@ -1,6 +1,7 @@
 #!/usr/bin/env python
 #
-# Copyright (c) 2005 Niels Provos <provos@citi.umich.edu>
+# Copyright (c) 2005-2007 Niels Provos <provos@citi.umich.edu>
+# Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
 # All rights reserved.
 #
 # Generates marshaling code based on libevent.
@@ -47,7 +48,7 @@ class Struct:
         self._name = name
         self._entries = []
         self._tags = {}
-        print >>sys.stderr, '  Created struct: %s' % name
+        print '  Created struct: %s' % name
 
     def AddEntry(self, entry):
         if self._tags.has_key(entry.Tag()):
@@ -57,7 +58,7 @@ class Struct:
                                     self._tags[entry.Tag()], line_count))
         self._entries.append(entry)
         self._tags[entry.Tag()] = entry.Name()
-        print >>sys.stderr, '    Added entry: %s' % entry.Name()
+        print '    Added entry: %s' % entry.Name()
 
     def Name(self):
         return self._name
@@ -147,7 +148,7 @@ int evtag_unmarshal_%(name)s(struct evbuffer *, ev_uint32_t,
                        ' */\n') % self._name
 
         print >>file, \
-              'static struct %(name)s_access_ __%(name)s_base = {' % \
+              'static struct %(name)s_access_ %(name)s_base__ = {' % \
               { 'name' : self._name }
         for entry in self._entries:
             self.PrintIndented(file, '  ', entry.CodeBase())
@@ -169,7 +170,7 @@ int evtag_unmarshal_%(name)s(struct evbuffer *, ev_uint32_t,
             '    event_warn("%%s: malloc", __func__);\n'
             '    return (NULL);\n'
             '  }\n'
-            '  tmp->base = &__%(name)s_base;\n') % { 'name' : self._name }
+            '  tmp->base = &%(name)s_base__;\n') % { 'name' : self._name }
 
         for entry in self._entries:
             self.PrintIndented(file, '  ', entry.CodeInitialize('tmp'))
@@ -331,11 +332,11 @@ int evtag_unmarshal_%(name)s(struct evbuffer *, ev_uint32_t,
             'evtag_marshal_%(name)s(struct evbuffer *evbuf, ev_uint32_t tag, '
             'const struct %(name)s *msg)\n'
             '{\n'
-            '  struct evbuffer *_buf = evbuffer_new();\n'
-            '  assert(_buf != NULL);\n'
-            '  %(name)s_marshal(_buf, msg);\n'
-            '  evtag_marshal_buffer(evbuf, tag, _buf);\n '
-            '  evbuffer_free(_buf);\n'
+            '  struct evbuffer *buf_ = evbuffer_new();\n'
+            '  assert(buf_ != NULL);\n'
+            '  %(name)s_marshal(buf_, msg);\n'
+            '  evtag_marshal_buffer(evbuf, tag, buf_);\n '
+            '  evbuffer_free(buf_);\n'
             '}\n' ) % { 'name' : self._name }
 
 class Entry:
@@ -1531,7 +1532,7 @@ class CCodeGenerator:
         # Use the complete provided path to the input file, with all
         # non-identifier characters replaced with underscores, to
         # reduce the chance of a collision between guard macros.
-        return '_' + nonident.sub('_', name).upper() + '_'
+        return 'EVENT_RPCOUT_' + nonident.sub('_', name).upper() + '_'
 
     def HeaderPreamble(self, name):
         guard = self.GuardName(name)
@@ -1578,8 +1579,8 @@ class CCodeGenerator:
                  '#include <event2/event.h>\n'
                  '#include <event2/buffer.h>\n'
                  '#include <event2/tag.h>\n\n'
-                 '#ifdef _EVENT___func__\n'
-                 '#define __func__ _EVENT___func__\n'
+                 '#ifdef EVENT____func__\n'
+                 '#define __func__ EVENT____func__\n'
                  '#endif\n\n'
                  )
 
@@ -1667,13 +1668,13 @@ class CommandLine:
         impl_file = self.impl_file
         factory = self.factory
 
-        print >>sys.stderr, 'Reading \"%s\"' % filename
+        print 'Reading \"%s\"' % filename
 
         fp = open(filename, 'r')
         entities = Parse(factory, fp)
         fp.close()
 
-        print >>sys.stderr, '... creating "%s"' % header_file
+        print '... creating "%s"' % header_file
         header_fp = open(header_file, 'w')
         print >>header_fp, factory.HeaderPreamble(filename)
 
@@ -1689,7 +1690,7 @@ class CommandLine:
         print >>header_fp, factory.HeaderPostamble(filename)
         header_fp.close()
 
-        print >>sys.stderr, '... creating "%s"' % impl_file
+        print '... creating "%s"' % impl_file
         impl_fp = open(impl_file, 'w')
         print >>impl_fp, factory.BodyPreamble(filename, header_file)
         for entry in entities:
index 79ca3c9809770a8f9421109fdf4bd34c8c53c2a1..7edd3da5d956122e669232d1c0a26195be8d5d1d 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2009 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_PARAM_H
+#ifdef EVENT__HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
 
@@ -45,7 +45,7 @@
 #endif
 
 #include <sys/queue.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -56,7 +56,7 @@
 #ifndef _WIN32
 #include <syslog.h>
 #endif
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #include <limits.h>
index b31628489c996c8b9512c554cb6efd3f991ec207..dfc81d5087a96d9d80d956592132cbabed3669c3 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVMAP_H_
-#define _EVMAP_H_
+#ifndef EVMAP_INTERNAL_H_INCLUDED_
+#define EVMAP_INTERNAL_H_INCLUDED_
 
 /** @file evmap-internal.h
  *
@@ -39,15 +39,15 @@ struct event;
 
 /** Initialize an event_map for use.
  */
-void evmap_io_initmap(struct event_io_map* ctx);
-void evmap_signal_initmap(struct event_signal_map* ctx);
+void evmap_io_initmap_(struct event_io_map* ctx);
+void evmap_signal_initmap_(struct event_signal_map* ctx);
 
 /** Remove all entries from an event_map.
 
        @param ctx the map to clear.
  */
-void evmap_io_clear(struct event_io_map* ctx);
-void evmap_signal_clear(struct event_signal_map* ctx);
+void evmap_io_clear_(struct event_io_map* ctx);
+void evmap_signal_clear_(struct event_signal_map* ctx);
 
 /** Add an IO event (some combination of EV_READ or EV_WRITE) to an
     event_base's list of events on a given file descriptor, and tell the
@@ -59,7 +59,7 @@ void evmap_signal_clear(struct event_signal_map* ctx);
     @param fd the file descriptor corresponding to ev.
     @param ev the event to add.
 */
-int evmap_io_add(struct event_base *base, evutil_socket_t fd, struct event *ev);
+int evmap_io_add_(struct event_base *base, evutil_socket_t fd, struct event *ev);
 /** Remove an IO event (some combination of EV_READ or EV_WRITE) to an
     event_base's list of events on a given file descriptor, and tell the
     underlying eventops about the fd if its state has changed.
@@ -68,23 +68,50 @@ int evmap_io_add(struct event_base *base, evutil_socket_t fd, struct event *ev);
     @param fd the file descriptor corresponding to ev.
     @param ev the event to remove.
  */
-int evmap_io_del(struct event_base *base, evutil_socket_t fd, struct event *ev);
+int evmap_io_del_(struct event_base *base, evutil_socket_t fd, struct event *ev);
 /** Active the set of events waiting on an event_base for a given fd.
 
     @param base the event_base to operate on.
     @param fd the file descriptor that has become active.
     @param events a bitmask of EV_READ|EV_WRITE|EV_ET.
 */
-void evmap_io_active(struct event_base *base, evutil_socket_t fd, short events);
+void evmap_io_active_(struct event_base *base, evutil_socket_t fd, short events);
 
 
 /* These functions behave in the same way as evmap_io_*, except they work on
  * signals rather than fds.  signals use a linear map everywhere; fds use
  * either a linear map or a hashtable. */
-int evmap_signal_add(struct event_base *base, int signum, struct event *ev);
-int evmap_signal_del(struct event_base *base, int signum, struct event *ev);
-void evmap_signal_active(struct event_base *base, evutil_socket_t signum, int ncalls);
+int evmap_signal_add_(struct event_base *base, int signum, struct event *ev);
+int evmap_signal_del_(struct event_base *base, int signum, struct event *ev);
+void evmap_signal_active_(struct event_base *base, evutil_socket_t signum, int ncalls);
 
-void *evmap_io_get_fdinfo(struct event_io_map *ctx, evutil_socket_t fd);
+/* Return the fdinfo object associated with a given fd.  If the fd has no
+ * events associated with it, the result may be NULL.
+ */
+void *evmap_io_get_fdinfo_(struct event_io_map *ctx, evutil_socket_t fd);
+
+/* Helper for event_reinit(): Tell the backend to re-add every fd and signal
+ * for which we have a pending event.
+ */
+int evmap_reinit_(struct event_base *base);
+
+/* Helper for event_base_free(): Call event_del() on every pending fd and
+ * signal event.
+ */
+void evmap_delete_all_(struct event_base *base);
+
+/* Helper for event_base_assert_ok_(): Check referential integrity of the
+ * evmaps.
+ */
+void evmap_check_integrity_(struct event_base *base);
+
+/* Helper: Call fn on every fd or signal event, passing as its arguments the
+ * provided event_base, the event, and arg.  If fn returns 0, process the next
+ * event.  If it returns any other value, return that value and process no
+ * more events.
+ */
+int evmap_foreach_event_(struct event_base *base,
+    event_base_foreach_event_cb fn,
+    void *arg);
 
-#endif /* _EVMAP_H_ */
+#endif /* EVMAP_INTERNAL_H_INCLUDED_ */
index 626bfb7d7654a104c8937f5b2a6ea9a6dd055777..62ecb7b34873fd398f5bb546b465ce4c4a43905a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -33,7 +33,7 @@
 #undef WIN32_LEAN_AND_MEAN
 #endif
 #include <sys/types.h>
-#if !defined(_WIN32) && defined(_EVENT_HAVE_SYS_TIME_H)
+#if !defined(_WIN32) && defined(EVENT__HAVE_SYS_TIME_H)
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -56,7 +56,7 @@
        write on a given fd, and the number of each.
   */
 struct evmap_io {
-       struct event_list events;
+       struct event_dlist events;
        ev_uint16_t nread;
        ev_uint16_t nwrite;
 };
@@ -64,7 +64,7 @@ struct evmap_io {
 /* An entry for an evmap_signal list: notes all the events that want to know
    when a signal triggers. */
 struct evmap_signal {
-       struct event_list events;
+       struct event_dlist events;
 };
 
 /* On some platforms, fds start at 0 and increment by 1 as they are
@@ -111,38 +111,38 @@ HT_GENERATE(event_io_map, event_map_entry, map_node, hashsocket, eqsocket,
 
 #define GET_IO_SLOT(x, map, slot, type)                                        \
        do {                                                            \
-               struct event_map_entry _key, *_ent;                     \
-               _key.fd = slot;                                         \
-               _ent = HT_FIND(event_io_map, map, &_key);               \
-               (x) = _ent ? &_ent->ent.type : NULL;                    \
+               struct event_map_entry key_, *ent_;                     \
+               key_.fd = slot;                                         \
+               ent_ = HT_FIND(event_io_map, map, &key_);               \
+               (x) = ent_ ? &ent_->ent.type : NULL;                    \
        } while (0);
 
 #define GET_IO_SLOT_AND_CTOR(x, map, slot, type, ctor, fdinfo_len)     \
        do {                                                            \
-               struct event_map_entry _key, *_ent;                     \
-               _key.fd = slot;                                         \
-               _HT_FIND_OR_INSERT(event_io_map, map_node, hashsocket, map, \
-                   event_map_entry, &_key, ptr,                        \
+               struct event_map_entry key_, *ent_;                     \
+               key_.fd = slot;                                         \
+               HT_FIND_OR_INSERT_(event_io_map, map_node, hashsocket, map, \
+                   event_map_entry, &key_, ptr,                        \
                    {                                                   \
-                           _ent = *ptr;                                \
+                           ent_ = *ptr;                                \
                    },                                                  \
                    {                                                   \
-                           _ent = mm_calloc(1,sizeof(struct event_map_entry)+fdinfo_len); \
-                           if (EVUTIL_UNLIKELY(_ent == NULL))          \
+                           ent_ = mm_calloc(1,sizeof(struct event_map_entry)+fdinfo_len); \
+                           if (EVUTIL_UNLIKELY(ent_ == NULL))          \
                                    return (-1);                        \
-                           _ent->fd = slot;                            \
-                           (ctor)(&_ent->ent.type);                    \
-                           _HT_FOI_INSERT(map_node, map, &_key, _ent, ptr) \
+                           ent_->fd = slot;                            \
+                           (ctor)(&ent_->ent.type);                    \
+                           HT_FOI_INSERT_(map_node, map, &key_, ent_, ptr) \
                                });                                     \
-               (x) = &_ent->ent.type;                                  \
+               (x) = &ent_->ent.type;                                  \
        } while (0)
 
-void evmap_io_initmap(struct event_io_map *ctx)
+void evmap_io_initmap_(struct event_io_map *ctx)
 {
        HT_INIT(event_io_map, ctx);
 }
 
-void evmap_io_clear(struct event_io_map *ctx)
+void evmap_io_clear_(struct event_io_map *ctx)
 {
        struct event_map_entry **ent, **next, *this;
        for (ent = HT_START(event_io_map, ctx); ent; ent = next) {
@@ -184,14 +184,14 @@ void evmap_io_clear(struct event_io_map *ctx)
        GET_SIGNAL_SLOT_AND_CTOR(x,map,slot,type,ctor,fdinfo_len)
 #define FDINFO_OFFSET sizeof(struct evmap_io)
 void
-evmap_io_initmap(struct event_io_map* ctx)
+evmap_io_initmap_(struct event_io_map* ctx)
 {
-       evmap_signal_initmap(ctx);
+       evmap_signal_initmap_(ctx);
 }
 void
-evmap_io_clear(struct event_io_map* ctx)
+evmap_io_clear_(struct event_io_map* ctx)
 {
-       evmap_signal_clear(ctx);
+       evmap_signal_clear_(ctx);
 }
 #endif
 
@@ -224,14 +224,14 @@ evmap_make_space(struct event_signal_map *map, int slot, int msize)
 }
 
 void
-evmap_signal_initmap(struct event_signal_map *ctx)
+evmap_signal_initmap_(struct event_signal_map *ctx)
 {
        ctx->nentries = 0;
        ctx->entries = NULL;
 }
 
 void
-evmap_signal_clear(struct event_signal_map *ctx)
+evmap_signal_clear_(struct event_signal_map *ctx)
 {
        if (ctx->entries != NULL) {
                int i;
@@ -252,7 +252,7 @@ evmap_signal_clear(struct event_signal_map *ctx)
 static void
 evmap_io_init(struct evmap_io *entry)
 {
-       TAILQ_INIT(&entry->events);
+       LIST_INIT(&entry->events);
        entry->nread = 0;
        entry->nwrite = 0;
 }
@@ -261,7 +261,7 @@ evmap_io_init(struct evmap_io *entry)
 /* return -1 on error, 0 on success if nothing changed in the event backend,
  * and 1 on success if something did. */
 int
-evmap_io_add(struct event_base *base, evutil_socket_t fd, struct event *ev)
+evmap_io_add_(struct event_base *base, evutil_socket_t fd, struct event *ev)
 {
        const struct eventop *evsel = base->evsel;
        struct event_io_map *io = &base->io;
@@ -306,7 +306,7 @@ evmap_io_add(struct event_base *base, evutil_socket_t fd, struct event *ev)
                return -1;
        }
        if (EVENT_DEBUG_MODE_IS_ON() &&
-           (old_ev = TAILQ_FIRST(&ctx->events)) &&
+           (old_ev = LIST_FIRST(&ctx->events)) &&
            (old_ev->ev_events&EV_ET) != (ev->ev_events&EV_ET)) {
                event_warnx("Tried to mix edge-triggered and non-edge-triggered"
                    " events on fd %d", (int)fd);
@@ -326,7 +326,7 @@ evmap_io_add(struct event_base *base, evutil_socket_t fd, struct event *ev)
 
        ctx->nread = (ev_uint16_t) nread;
        ctx->nwrite = (ev_uint16_t) nwrite;
-       TAILQ_INSERT_TAIL(&ctx->events, ev, ev_io_next);
+       LIST_INSERT_HEAD(&ctx->events, ev, ev_io_next);
 
        return (retval);
 }
@@ -334,7 +334,7 @@ evmap_io_add(struct event_base *base, evutil_socket_t fd, struct event *ev)
 /* return -1 on error, 0 on success if nothing changed in the event backend,
  * and 1 on success if something did. */
 int
-evmap_io_del(struct event_base *base, evutil_socket_t fd, struct event *ev)
+evmap_io_del_(struct event_base *base, evutil_socket_t fd, struct event *ev)
 {
        const struct eventop *evsel = base->evsel;
        struct event_io_map *io = &base->io;
@@ -382,13 +382,13 @@ evmap_io_del(struct event_base *base, evutil_socket_t fd, struct event *ev)
 
        ctx->nread = nread;
        ctx->nwrite = nwrite;
-       TAILQ_REMOVE(&ctx->events, ev, ev_io_next);
+       LIST_REMOVE(ev, ev_io_next);
 
        return (retval);
 }
 
 void
-evmap_io_active(struct event_base *base, evutil_socket_t fd, short events)
+evmap_io_active_(struct event_base *base, evutil_socket_t fd, short events)
 {
        struct event_io_map *io = &base->io;
        struct evmap_io *ctx;
@@ -400,9 +400,9 @@ evmap_io_active(struct event_base *base, evutil_socket_t fd, short events)
        GET_IO_SLOT(ctx, io, fd, evmap_io);
 
        EVUTIL_ASSERT(ctx);
-       TAILQ_FOREACH(ev, &ctx->events, ev_io_next) {
+       LIST_FOREACH(ev, &ctx->events, ev_io_next) {
                if (ev->ev_events & events)
-                       event_active_nolock(ev, ev->ev_events & events, 1);
+                       event_active_nolock_(ev, ev->ev_events & events, 1);
        }
 }
 
@@ -411,12 +411,12 @@ evmap_io_active(struct event_base *base, evutil_socket_t fd, short events)
 static void
 evmap_signal_init(struct evmap_signal *entry)
 {
-       TAILQ_INIT(&entry->events);
+       LIST_INIT(&entry->events);
 }
 
 
 int
-evmap_signal_add(struct event_base *base, int sig, struct event *ev)
+evmap_signal_add_(struct event_base *base, int sig, struct event *ev)
 {
        const struct eventop *evsel = base->evsigsel;
        struct event_signal_map *map = &base->sigmap;
@@ -430,19 +430,19 @@ evmap_signal_add(struct event_base *base, int sig, struct event *ev)
        GET_SIGNAL_SLOT_AND_CTOR(ctx, map, sig, evmap_signal, evmap_signal_init,
            base->evsigsel->fdinfo_len);
 
-       if (TAILQ_EMPTY(&ctx->events)) {
+       if (LIST_EMPTY(&ctx->events)) {
                if (evsel->add(base, ev->ev_fd, 0, EV_SIGNAL, NULL)
                    == -1)
                        return (-1);
        }
 
-       TAILQ_INSERT_TAIL(&ctx->events, ev, ev_signal_next);
+       LIST_INSERT_HEAD(&ctx->events, ev, ev_signal_next);
 
        return (1);
 }
 
 int
-evmap_signal_del(struct event_base *base, int sig, struct event *ev)
+evmap_signal_del_(struct event_base *base, int sig, struct event *ev)
 {
        const struct eventop *evsel = base->evsigsel;
        struct event_signal_map *map = &base->sigmap;
@@ -453,18 +453,18 @@ evmap_signal_del(struct event_base *base, int sig, struct event *ev)
 
        GET_SIGNAL_SLOT(ctx, map, sig, evmap_signal);
 
-       if (TAILQ_FIRST(&ctx->events) == TAILQ_LAST(&ctx->events, event_list)) {
+       LIST_REMOVE(ev, ev_signal_next);
+
+       if (LIST_FIRST(&ctx->events) == NULL) {
                if (evsel->del(base, ev->ev_fd, 0, EV_SIGNAL, NULL) == -1)
                        return (-1);
        }
 
-       TAILQ_REMOVE(&ctx->events, ev, ev_signal_next);
-
        return (1);
 }
 
 void
-evmap_signal_active(struct event_base *base, evutil_socket_t sig, int ncalls)
+evmap_signal_active_(struct event_base *base, evutil_socket_t sig, int ncalls)
 {
        struct event_signal_map *map = &base->sigmap;
        struct evmap_signal *ctx;
@@ -473,12 +473,12 @@ evmap_signal_active(struct event_base *base, evutil_socket_t sig, int ncalls)
        EVUTIL_ASSERT(sig < map->nentries);
        GET_SIGNAL_SLOT(ctx, map, sig, evmap_signal);
 
-       TAILQ_FOREACH(ev, &ctx->events, ev_signal_next)
-               event_active_nolock(ev, EV_SIGNAL, ncalls);
+       LIST_FOREACH(ev, &ctx->events, ev_signal_next)
+               event_active_nolock_(ev, EV_SIGNAL, ncalls);
 }
 
 void *
-evmap_io_get_fdinfo(struct event_io_map *map, evutil_socket_t fd)
+evmap_io_get_fdinfo_(struct event_io_map *map, evutil_socket_t fd)
 {
        struct evmap_io *ctx;
        GET_IO_SLOT(ctx, map, fd, evmap_io);
@@ -488,6 +488,175 @@ evmap_io_get_fdinfo(struct event_io_map *map, evutil_socket_t fd)
                return NULL;
 }
 
+/* Callback type for evmap_io_foreach_fd */
+typedef int (*evmap_io_foreach_fd_cb)(
+       struct event_base *, evutil_socket_t, struct evmap_io *, void *);
+
+/* Multipurpose helper function: Iterate over every file descriptor event_base
+ * for which we could have EV_READ or EV_WRITE events.  For each such fd, call
+ * fn(base, signum, evmap_io, arg), where fn is the user-provided
+ * function, base is the event_base, signum is the signal number, evmap_io
+ * is an evmap_io structure containing a list of events pending on the
+ * file descriptor, and arg is the user-supplied argument.
+ *
+ * If fn returns 0, continue on to the next signal. Otherwise, return the same
+ * value that fn returned.
+ *
+ * Note that there is no guarantee that the file descriptors will be processed
+ * in any particular order.
+ */
+static int
+evmap_io_foreach_fd(struct event_base *base,
+    evmap_io_foreach_fd_cb fn,
+    void *arg)
+{
+       evutil_socket_t fd;
+       struct event_io_map *iomap = &base->io;
+       int r = 0;
+#ifdef EVMAP_USE_HT
+       struct event_map_entry **mapent;
+       HT_FOREACH(mapent, event_io_map, iomap) {
+               struct evmap_io *ctx = &(*mapent)->ent.evmap_io;
+               fd = (*mapent)->fd;
+#else
+       for (fd = 0; fd < iomap->nentries; ++fd) {
+               struct evmap_io *ctx = iomap->entries[fd];
+               if (!ctx)
+                       continue;
+#endif
+               if ((r = fn(base, fd, ctx, arg)))
+                       break;
+       }
+       return r;
+}
+
+/* Callback type for evmap_signal_foreach_signal */
+typedef int (*evmap_signal_foreach_signal_cb)(
+       struct event_base *, int, struct evmap_signal *, void *);
+
+/* Multipurpose helper function: Iterate over every signal number in the
+ * event_base for which we could have signal events.  For each such signal,
+ * call fn(base, signum, evmap_signal, arg), where fn is the user-provided
+ * function, base is the event_base, signum is the signal number, evmap_signal
+ * is an evmap_signal structure containing a list of events pending on the
+ * signal, and arg is the user-supplied argument.
+ *
+ * If fn returns 0, continue on to the next signal. Otherwise, return the same
+ * value that fn returned.
+ */
+static int
+evmap_signal_foreach_signal(struct event_base *base,
+    evmap_signal_foreach_signal_cb fn,
+    void *arg)
+{
+       struct event_signal_map *sigmap = &base->sigmap;
+       int r = 0;
+       int signum;
+
+       for (signum = 0; signum < sigmap->nentries; ++signum) {
+               struct evmap_signal *ctx = sigmap->entries[signum];
+               if (!ctx)
+                       continue;
+               if ((r = fn(base, signum, ctx, arg)))
+                       break;
+       }
+       return r;
+}
+
+/* Helper for evmap_reinit_: tell the backend to add every fd for which we have
+ * pending events, with the appropriate combination of EV_READ, EV_WRITE, and
+ * EV_ET. */
+static int
+evmap_io_reinit_iter_fn(struct event_base *base, evutil_socket_t fd,
+    struct evmap_io *ctx, void *arg)
+{
+       const struct eventop *evsel = base->evsel;
+       void *extra;
+       int *result = arg;
+       short events = 0;
+       struct event *ev;
+       EVUTIL_ASSERT(ctx);
+
+       extra = ((char*)ctx) + sizeof(struct evmap_io);
+       if (ctx->nread)
+               events |= EV_READ;
+       if (ctx->nread)
+               events |= EV_WRITE;
+       if (evsel->fdinfo_len)
+               memset(extra, 0, evsel->fdinfo_len);
+       if (events &&
+           (ev = LIST_FIRST(&ctx->events)) &&
+           (ev->ev_events & EV_ET))
+               events |= EV_ET;
+       if (evsel->add(base, fd, 0, events, extra) == -1)
+               *result = -1;
+
+       return 0;
+}
+
+/* Helper for evmap_reinit_: tell the backend to add every signal for which we
+ * have pending events.  */
+static int
+evmap_signal_reinit_iter_fn(struct event_base *base,
+    int signum, struct evmap_signal *ctx, void *arg)
+{
+       const struct eventop *evsel = base->evsigsel;
+       int *result = arg;
+
+       if (!LIST_EMPTY(&ctx->events)) {
+               if (evsel->add(base, signum, 0, EV_SIGNAL, NULL) == -1)
+                       *result = -1;
+       }
+       return 0;
+}
+
+int
+evmap_reinit_(struct event_base *base)
+{
+       int result = 0;
+
+       evmap_io_foreach_fd(base, evmap_io_reinit_iter_fn, &result);
+       if (result < 0)
+               return -1;
+       evmap_signal_foreach_signal(base, evmap_signal_reinit_iter_fn, &result);
+       if (result < 0)
+               return -1;
+       return 0;
+}
+
+/* Helper for evmap_delete_all_: delete every event in an event_dlist. */
+static int
+delete_all_in_dlist(struct event_dlist *dlist)
+{
+       struct event *ev;
+       while ((ev = LIST_FIRST(dlist)))
+               event_del(ev);
+       return 0;
+}
+
+/* Helper for evmap_delete_all_: delete every event pending on an fd. */
+static int
+evmap_io_delete_all_iter_fn(struct event_base *base, evutil_socket_t fd,
+    struct evmap_io *io_info, void *arg)
+{
+       return delete_all_in_dlist(&io_info->events);
+}
+
+/* Helper for evmap_delete_all_: delete every event pending on a signal. */
+static int
+evmap_signal_delete_all_iter_fn(struct event_base *base, int signum,
+    struct evmap_signal *sig_info, void *arg)
+{
+       return delete_all_in_dlist(&sig_info->events);
+}
+
+void
+evmap_delete_all_(struct event_base *base)
+{
+       evmap_signal_foreach_signal(base, evmap_signal_delete_all_iter_fn, NULL);
+       evmap_io_foreach_fd(base, evmap_io_delete_all_iter_fn, NULL);
+}
+
 /** Per-fd structure for use with changelists.  It keeps track, for each fd or
  * signal using the changelist, of where its entry in the changelist is.
  */
@@ -497,7 +666,7 @@ struct event_changelist_fdinfo {
 };
 
 void
-event_changelist_init(struct event_changelist *changelist)
+event_changelist_init_(struct event_changelist *changelist)
 {
        changelist->changes = NULL;
        changelist->changes_size = 0;
@@ -522,10 +691,26 @@ event_change_get_fdinfo(struct event_base *base,
        return (void*)ptr;
 }
 
-#ifdef DEBUG_CHANGELIST
+/** Callback helper for event_changelist_assert_ok */
+static int
+event_changelist_assert_ok_foreach_iter_fn(
+       struct event_base *base,
+       evutil_socket_t fd, struct evmap_io *io, void *arg)
+{
+       struct event_changelist *changelist = &base->changelist;
+       struct event_changelist_fdinfo *f;
+       f = (void*)
+           ( ((char*)io) + sizeof(struct evmap_io) );
+       if (f->idxplus1) {
+               struct event_change *c = &changelist->changes[f->idxplus1 - 1];
+               EVUTIL_ASSERT(c->fd == fd);
+       }
+       return 0;
+}
+
 /** Make sure that the changelist is consistent with the evmap structures. */
 static void
-event_changelist_check(struct event_base *base)
+event_changelist_assert_ok(struct event_base *base)
 {
        int i;
        struct event_changelist *changelist = &base->changelist;
@@ -540,25 +725,19 @@ event_changelist_check(struct event_base *base)
                EVUTIL_ASSERT(f->idxplus1 == i + 1);
        }
 
-       for (i = 0; i < base->io.nentries; ++i) {
-               struct evmap_io *io = base->io.entries[i];
-               struct event_changelist_fdinfo *f;
-               if (!io)
-                       continue;
-               f = (void*)
-                   ( ((char*)io) + sizeof(struct evmap_io) );
-               if (f->idxplus1) {
-                       struct event_change *c = &changelist->changes[f->idxplus1 - 1];
-                       EVUTIL_ASSERT(c->fd == i);
-               }
-       }
+       evmap_io_foreach_fd(base,
+           event_changelist_assert_ok_foreach_iter_fn,
+           NULL);
 }
+
+#ifdef DEBUG_CHANGELIST
+#define event_changelist_check(base)  event_changelist_assert_ok((base))
 #else
 #define event_changelist_check(base)  ((void)0)
 #endif
 
 void
-event_changelist_remove_all(struct event_changelist *changelist,
+event_changelist_remove_all_(struct event_changelist *changelist,
     struct event_base *base)
 {
        int i;
@@ -579,11 +758,11 @@ event_changelist_remove_all(struct event_changelist *changelist,
 }
 
 void
-event_changelist_freemem(struct event_changelist *changelist)
+event_changelist_freemem_(struct event_changelist *changelist)
 {
        if (changelist->changes)
                mm_free(changelist->changes);
-       event_changelist_init(changelist); /* zero it all out. */
+       event_changelist_init_(changelist); /* zero it all out. */
 }
 
 /** Increase the size of 'changelist' to hold more changes. */
@@ -645,7 +824,7 @@ event_changelist_get_or_construct(struct event_changelist *changelist,
 }
 
 int
-event_changelist_add(struct event_base *base, evutil_socket_t fd, short old, short events,
+event_changelist_add_(struct event_base *base, evutil_socket_t fd, short old, short events,
     void *p)
 {
        struct event_changelist *changelist = &base->changelist;
@@ -676,7 +855,7 @@ event_changelist_add(struct event_base *base, evutil_socket_t fd, short old, sho
 }
 
 int
-event_changelist_del(struct event_base *base, evutil_socket_t fd, short old, short events,
+event_changelist_del_(struct event_base *base, evutil_socket_t fd, short old, short events,
     void *p)
 {
        struct event_changelist *changelist = &base->changelist;
@@ -721,3 +900,115 @@ event_changelist_del(struct event_base *base, evutil_socket_t fd, short old, sho
        return (0);
 }
 
+/* Helper for evmap_check_integrity_: verify that all of the events pending on
+ * given fd are set up correctly, and that the nread and nwrite counts on that
+ * fd are correct. */
+static int
+evmap_io_check_integrity_fn(struct event_base *base, evutil_socket_t fd,
+    struct evmap_io *io_info, void *arg)
+{
+       struct event *ev;
+       int n_read = 0, n_write = 0;
+
+       /* First, make sure the list itself isn't corrupt. Otherwise,
+        * running LIST_FOREACH could be an exciting adventure. */
+       EVUTIL_ASSERT_LIST_OK(&io_info->events, event, ev_io_next);
+
+       LIST_FOREACH(ev, &io_info->events, ev_io_next) {
+               EVUTIL_ASSERT(ev->ev_flags & EVLIST_INSERTED);
+               EVUTIL_ASSERT(ev->ev_fd == fd);
+               EVUTIL_ASSERT(!(ev->ev_events & EV_SIGNAL));
+               EVUTIL_ASSERT((ev->ev_events & (EV_READ|EV_WRITE)));
+               if (ev->ev_events & EV_READ)
+                       ++n_read;
+               if (ev->ev_events & EV_WRITE)
+                       ++n_write;
+       }
+
+       EVUTIL_ASSERT(n_read == io_info->nread);
+       EVUTIL_ASSERT(n_write == io_info->nwrite);
+
+       return 0;
+}
+
+/* Helper for evmap_check_integrity_: verify that all of the events pending
+ * on given signal are set up correctly. */
+static int
+evmap_signal_check_integrity_fn(struct event_base *base,
+    int signum, struct evmap_signal *sig_info, void *arg)
+{
+       struct event *ev;
+       /* First, make sure the list itself isn't corrupt. */
+       EVUTIL_ASSERT_LIST_OK(&sig_info->events, event, ev_signal_next);
+
+       LIST_FOREACH(ev, &sig_info->events, ev_io_next) {
+               EVUTIL_ASSERT(ev->ev_flags & EVLIST_INSERTED);
+               EVUTIL_ASSERT(ev->ev_fd == signum);
+               EVUTIL_ASSERT((ev->ev_events & EV_SIGNAL));
+               EVUTIL_ASSERT(!(ev->ev_events & (EV_READ|EV_WRITE)));
+       }
+       return 0;
+}
+
+void
+evmap_check_integrity_(struct event_base *base)
+{
+       evmap_io_foreach_fd(base, evmap_io_check_integrity_fn, NULL);
+       evmap_signal_foreach_signal(base, evmap_signal_check_integrity_fn, NULL);
+
+       if (base->evsel->add == event_changelist_add_)
+               event_changelist_assert_ok(base);
+}
+
+/* Helper type for evmap_foreach_event_: Bundles a function to call on every
+ * event, and the user-provided void* to use as its third argument. */
+struct evmap_foreach_event_helper {
+       int (*fn)(struct event_base *, struct event *, void *);
+       void *arg;
+};
+
+/* Helper for evmap_foreach_event_: calls a provided function on every event
+ * pending on a given fd.  */
+static int
+evmap_io_foreach_event_fn(struct event_base *base, evutil_socket_t fd,
+    struct evmap_io *io_info, void *arg)
+{
+       struct evmap_foreach_event_helper *h = arg;
+       struct event *ev;
+       int r;
+       LIST_FOREACH(ev, &io_info->events, ev_io_next) {
+               if ((r = h->fn(base, ev, h->arg)))
+                       return r;
+       }
+       return 0;
+}
+
+/* Helper for evmap_foreach_event_: calls a provided function on every event
+ * pending on a given signal.  */
+static int
+evmap_signal_foreach_event_fn(struct event_base *base, int signum,
+    struct evmap_signal *sig_info, void *arg)
+{
+       struct event *ev;
+       struct evmap_foreach_event_helper *h = arg;
+       int r;
+       LIST_FOREACH(ev, &sig_info->events, ev_signal_next) {
+               if ((r = h->fn(base, ev, h->arg)))
+                       return r;
+       }
+       return 0;
+}
+
+int
+evmap_foreach_event_(struct event_base *base,
+    int (*fn)(struct event_base *, struct event *, void *), void *arg)
+{
+       struct evmap_foreach_event_helper h;
+       int r;
+       h.fn = fn;
+       h.arg = arg;
+       if ((r = evmap_io_foreach_fd(base, evmap_io_foreach_event_fn, &h)))
+               return r;
+       return evmap_signal_foreach_signal(base, evmap_signal_foreach_event_fn, &h);
+}
+
index f7f5597466be127cae57f8d99aa258c53ce38632..a014386bfe31158506d15d20e19acae1a47ac270 100644 (file)
@@ -1,6 +1,9 @@
 /*
  * Submitted by David Pacheco (dp.spambait@gmail.com)
  *
+ * Copyright 2006-2007 Niels Provos
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -53,6 +56,8 @@
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
+#ifdef EVENT__HAVE_EVENT_PORTS
+
 #include <sys/time.h>
 #include <sys/queue.h>
 #include <errno.h>
@@ -153,7 +158,7 @@ evport_init(struct event_base *base)
                
        evpd->ed_npending = 0;
 
-       evsig_init(base);
+       evsig_init_(base);
 
        return (evpd);
 }
@@ -286,12 +291,12 @@ evport_dispatch(struct event_base *base, struct timeval *tv)
                if (fd != -1) {
                        /* We might have cleared out this event; we need
                         * to be sure that it's still set. */
-                       fdi = evmap_io_get_fdinfo(&base->io, fd);
+                       fdi = evmap_io_get_fdinfo_(&base->io, fd);
                }
 
                if (fdi != NULL && FDI_HAS_EVENTS(fdi)) {
                        reassociate(epdp, fdi, fd);
-//                     epdp->ed_pending[i] = -1;
+                       /* epdp->ed_pending[i] = -1; */
                        fdi->pending_idx_plus_1 = 0;
                }
        }
@@ -321,7 +326,7 @@ evport_dispatch(struct event_base *base, struct timeval *tv)
                port_event_t *pevt = &pevtlist[i];
                int fd = (int) pevt->portev_object;
                struct fd_info *fdi = pevt->portev_user;
-               //EVUTIL_ASSERT(evmap_io_get_fdinfo(&base->io, fd) == fdi);
+               /*EVUTIL_ASSERT(evmap_io_get_fdinfo_(&base->io, fd) == fdi);*/
 
                check_evportop(epdp);
                check_event(pevt);
@@ -348,7 +353,7 @@ evport_dispatch(struct event_base *base, struct timeval *tv)
                if (pevt->portev_events & (POLLERR|POLLHUP|POLLNVAL))
                        res |= EV_READ|EV_WRITE;
 
-               evmap_io_active(base, fd, res);
+               evmap_io_active_(base, fd, res);
        } /* end of all events gotten */
        epdp->ed_npending = nevents;
 
@@ -431,7 +436,7 @@ evport_dealloc(struct event_base *base)
 {
        struct evport_data *evpd = base->evbase;
 
-       evsig_dealloc(base);
+       evsig_dealloc_(base);
 
        close(evpd->ed_port);
 
@@ -442,3 +447,5 @@ evport_dealloc(struct event_base *base)
 
        mm_free(evpd);
 }
+
+#endif /* EVENT__HAVE_EVENT_PORTS */
index 8497d29882ea62d7b5cf7255e3554e5d1d6689a8..e53d06e0f40cc6454829efe0fadd1165f67493ee 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVRPC_INTERNAL_H_
-#define _EVRPC_INTERNAL_H_
+#ifndef EVRPC_INTERNAL_H_INCLUDED_
+#define EVRPC_INTERNAL_H_INCLUDED_
 
 #include "http-internal.h"
 
@@ -56,7 +56,7 @@ TAILQ_HEAD(evrpc_hook_list, evrpc_hook);
 struct evrpc_hook_ctx;
 TAILQ_HEAD(evrpc_pause_list, evrpc_hook_ctx);
 
-struct _evrpc_hooks {
+struct evrpc_hooks_ {
        /* hooks for processing outbound and inbound rpcs */
        struct evrpc_hook_list in_hooks;
        struct evrpc_hook_list out_hooks;
@@ -69,7 +69,7 @@ struct _evrpc_hooks {
 #define paused_requests common.pause_requests
 
 struct evrpc_base {
-       struct _evrpc_hooks common;
+       struct evrpc_hooks_ common;
 
        /* the HTTP server under which we register our RPC calls */
        struct evhttp* http_server;
@@ -79,11 +79,11 @@ struct evrpc_base {
 };
 
 struct evrpc_req_generic;
-void evrpc_reqstate_free(struct evrpc_req_generic* rpc_state);
+void evrpc_reqstate_free_(struct evrpc_req_generic* rpc_state);
 
 /* A pool for holding evhttp_connection objects */
 struct evrpc_pool {
-       struct _evrpc_hooks common;
+       struct evrpc_hooks_ common;
 
        struct event_base *base;
 
@@ -117,14 +117,14 @@ struct evrpc_hook_meta {
 };
 
 /* allows association of meta data with a request */
-static void evrpc_hook_associate_meta(struct evrpc_hook_meta **pctx,
+static void evrpc_hook_associate_meta_(struct evrpc_hook_meta **pctx,
     struct evhttp_connection *evcon);
 
 /* creates a new meta data store */
-static struct evrpc_hook_meta *evrpc_hook_meta_new(void);
+static struct evrpc_hook_meta *evrpc_hook_meta_new_(void);
 
 /* frees the meta data associated with a request */
-static void evrpc_hook_context_free(struct evrpc_hook_meta *ctx);
+static void evrpc_hook_context_free_(struct evrpc_hook_meta *ctx);
 
 /* the server side of an rpc */
 
@@ -201,4 +201,4 @@ struct evrpc_request_wrapper {
        int (*reply_unmarshal)(void *, struct evbuffer*);
 };
 
-#endif /* _EVRPC_INTERNAL_H_ */
+#endif /* EVRPC_INTERNAL_H_INCLUDED_ */
index 3fe306f4f89ea70e4090739eb7f3946a69029b60..fd1f67c004ab8c0ea12d26eafa3e7fb5f517f6cf 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -38,7 +38,7 @@
 #ifndef _WIN32
 #include <sys/socket.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -122,7 +122,7 @@ evrpc_add_hook(void *vbase,
     int (*cb)(void *, struct evhttp_request *, struct evbuffer *, void *),
     void *cb_arg)
 {
-       struct _evrpc_hooks *base = vbase;
+       struct evrpc_hooks_ *base = vbase;
        struct evrpc_hook_list *head = NULL;
        struct evrpc_hook *hook = NULL;
        switch (hook_type) {
@@ -168,7 +168,7 @@ evrpc_remove_hook_internal(struct evrpc_hook_list *head, void *handle)
 int
 evrpc_remove_hook(void *vbase, enum EVRPC_HOOK_TYPE hook_type, void *handle)
 {
-       struct _evrpc_hooks *base = vbase;
+       struct evrpc_hooks_ *base = vbase;
        struct evrpc_hook_list *head = NULL;
        switch (hook_type) {
        case EVRPC_INPUT:
@@ -302,7 +302,7 @@ evrpc_request_cb(struct evhttp_request *req, void *arg)
        if (TAILQ_FIRST(&rpc->base->input_hooks) != NULL) {
                int hook_res;
 
-               evrpc_hook_associate_meta(&rpc_state->hook_meta, req->evcon);
+               evrpc_hook_associate_meta_(&rpc_state->hook_meta, req->evcon);
 
                /*
                 * allow hooks to modify the outgoing request
@@ -330,7 +330,7 @@ evrpc_request_cb(struct evhttp_request *req, void *arg)
 
 error:
        if (rpc_state != NULL)
-               evrpc_reqstate_free(rpc_state);
+               evrpc_reqstate_free_(rpc_state);
        evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
        return;
 }
@@ -373,14 +373,14 @@ evrpc_request_cb_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
 
 error:
        if (rpc_state != NULL)
-               evrpc_reqstate_free(rpc_state);
+               evrpc_reqstate_free_(rpc_state);
        evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
        return;
 }
 
 
 void
-evrpc_reqstate_free(struct evrpc_req_generic* rpc_state)
+evrpc_reqstate_free_(struct evrpc_req_generic* rpc_state)
 {
        struct evrpc *rpc;
        EVUTIL_ASSERT(rpc_state != NULL);
@@ -388,7 +388,7 @@ evrpc_reqstate_free(struct evrpc_req_generic* rpc_state)
 
        /* clean up all memory */
        if (rpc_state->hook_meta != NULL)
-               evrpc_hook_context_free(rpc_state->hook_meta);
+               evrpc_hook_context_free_(rpc_state->hook_meta);
        if (rpc_state->request != NULL)
                rpc->request_free(rpc_state->request);
        if (rpc_state->reply != NULL)
@@ -428,7 +428,7 @@ evrpc_request_done(struct evrpc_req_generic *rpc_state)
        if (TAILQ_FIRST(&rpc->base->output_hooks) != NULL) {
                int hook_res;
 
-               evrpc_hook_associate_meta(&rpc_state->hook_meta, req->evcon);
+               evrpc_hook_associate_meta_(&rpc_state->hook_meta, req->evcon);
 
                /* do hook based tweaks to the request */
                hook_res = evrpc_process_hooks(&rpc->base->output_hooks,
@@ -455,7 +455,7 @@ evrpc_request_done(struct evrpc_req_generic *rpc_state)
 
 error:
        if (rpc_state != NULL)
-               evrpc_reqstate_free(rpc_state);
+               evrpc_reqstate_free_(rpc_state);
        evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
        return;
 }
@@ -490,13 +490,13 @@ evrpc_request_done_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
        }
        evhttp_send_reply(req, HTTP_OK, "OK", rpc_state->rpc_data);
 
-       evrpc_reqstate_free(rpc_state);
+       evrpc_reqstate_free_(rpc_state);
 
        return;
 
 error:
        if (rpc_state != NULL)
-               evrpc_reqstate_free(rpc_state);
+               evrpc_reqstate_free_(rpc_state);
        evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
        return;
 }
@@ -532,7 +532,7 @@ static void
 evrpc_request_wrapper_free(struct evrpc_request_wrapper *request)
 {
        if (request->hook_meta != NULL)
-               evrpc_hook_context_free(request->hook_meta);
+               evrpc_hook_context_free_(request->hook_meta);
        mm_free(request->name);
        mm_free(request);
 }
@@ -681,7 +681,7 @@ evrpc_schedule_request(struct evhttp_connection *connection,
        if (TAILQ_FIRST(&pool->output_hooks) != NULL) {
                int hook_res;
 
-               evrpc_hook_associate_meta(&ctx->hook_meta, connection);
+               evrpc_hook_associate_meta_(&ctx->hook_meta, connection);
 
                /* apply hooks to the outgoing request */
                hook_res = evrpc_process_hooks(&pool->output_hooks,
@@ -766,7 +766,7 @@ static int
 evrpc_pause_request(void *vbase, void *ctx,
     void (*cb)(void *, enum EVRPC_HOOK_RESULT))
 {
-       struct _evrpc_hooks *base = vbase;
+       struct evrpc_hooks_ *base = vbase;
        struct evrpc_hook_ctx *pause = mm_malloc(sizeof(*pause));
        if (pause == NULL)
                return (-1);
@@ -781,7 +781,7 @@ evrpc_pause_request(void *vbase, void *ctx,
 int
 evrpc_resume_request(void *vbase, void *ctx, enum EVRPC_HOOK_RESULT res)
 {
-       struct _evrpc_hooks *base = vbase;
+       struct evrpc_hooks_ *base = vbase;
        struct evrpc_pause_list *head = &base->pause_requests;
        struct evrpc_hook_ctx *pause;
 
@@ -878,7 +878,7 @@ evrpc_reply_done(struct evhttp_request *req, void *arg)
        }
 
        if (TAILQ_FIRST(&pool->input_hooks) != NULL) {
-               evrpc_hook_associate_meta(&ctx->hook_meta, ctx->evcon);
+               evrpc_hook_associate_meta_(&ctx->hook_meta, ctx->evcon);
 
                /* apply hooks to the incoming request */
                hook_res = evrpc_process_hooks(&pool->input_hooks,
@@ -977,7 +977,7 @@ evrpc_request_timeout(evutil_socket_t fd, short what, void *arg)
        struct evhttp_connection *evcon = ctx->evcon;
        EVUTIL_ASSERT(evcon != NULL);
 
-       evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
+       evhttp_connection_fail_(evcon, EVCON_HTTP_TIMEOUT);
 }
 
 /*
@@ -999,7 +999,7 @@ evrpc_meta_data_free(struct evrpc_meta_list *meta_data)
 }
 
 static struct evrpc_hook_meta *
-evrpc_hook_meta_new(void)
+evrpc_hook_meta_new_(void)
 {
        struct evrpc_hook_meta *ctx;
        ctx = mm_malloc(sizeof(struct evrpc_hook_meta));
@@ -1012,17 +1012,17 @@ evrpc_hook_meta_new(void)
 }
 
 static void
-evrpc_hook_associate_meta(struct evrpc_hook_meta **pctx,
+evrpc_hook_associate_meta_(struct evrpc_hook_meta **pctx,
     struct evhttp_connection *evcon)
 {
        struct evrpc_hook_meta *ctx = *pctx;
        if (ctx == NULL)
-               *pctx = ctx = evrpc_hook_meta_new();
+               *pctx = ctx = evrpc_hook_meta_new_();
        ctx->evcon = evcon;
 }
 
 static void
-evrpc_hook_context_free(struct evrpc_hook_meta *ctx)
+evrpc_hook_context_free_(struct evrpc_hook_meta *ctx)
 {
        evrpc_meta_data_free(&ctx->meta_data);
        mm_free(ctx);
@@ -1038,7 +1038,7 @@ evrpc_hook_add_meta(void *ctx, const char *key,
        struct evrpc_meta *meta = NULL;
 
        if ((store = req->hook_meta) == NULL)
-               store = req->hook_meta = evrpc_hook_meta_new();
+               store = req->hook_meta = evrpc_hook_meta_new_();
 
        meta = mm_malloc(sizeof(struct evrpc_meta));
        EVUTIL_ASSERT(meta != NULL);
index 73d1b6c799b38ac606ad059cbca96050fead07ca..5cff03b525558a267f9c045279cc24ab7e000f0e 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVSIGNAL_H_
-#define _EVSIGNAL_H_
+#ifndef EVSIGNAL_INTERNAL_H_INCLUDED_
+#define EVSIGNAL_INTERNAL_H_INCLUDED_
 
 #ifndef evutil_socket_t
 #include "event2/util.h"
@@ -48,7 +48,7 @@ struct evsig_info {
 
        /* Array of previous signal handler objects before Libevent started
         * messing with them.  Used to restore old signal handlers. */
-#ifdef _EVENT_HAVE_SIGACTION
+#ifdef EVENT__HAVE_SIGACTION
        struct sigaction **sh_old;
 #else
        ev_sighandler_t **sh_old;
@@ -56,9 +56,10 @@ struct evsig_info {
        /* Size of sh_old. */
        int sh_old_max;
 };
-int evsig_init(struct event_base *);
-void evsig_dealloc(struct event_base *);
+int evsig_init_(struct event_base *);
+void evsig_dealloc_(struct event_base *);
 
-void evsig_set_base(struct event_base *base);
+void evsig_set_base_(struct event_base *base);
+void evsig_free_globals_(void);
 
-#endif /* _EVSIGNAL_H_ */
+#endif /* EVSIGNAL_INTERNAL_H_INCLUDED_ */
index 793b5eae65156d7a865fff325c14a2a997d242b8..6de07c247e165a05983bb2e1475f253fa2619116 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008-2010 Niels Provos, Nick Mathewson
+ * Copyright (c) 2008-2012 Niels Provos, Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVTHREAD_INTERNAL_H_
-#define _EVTHREAD_INTERNAL_H_
+#ifndef EVTHREAD_INTERNAL_H_INCLUDED_
+#define EVTHREAD_INTERNAL_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -46,62 +46,62 @@ struct event_base;
 #define EVTHREAD_EXPOSE_STRUCTS
 #endif
 
-#if ! defined(_EVENT_DISABLE_THREAD_SUPPORT) && defined(EVTHREAD_EXPOSE_STRUCTS)
+#if ! defined(EVENT__DISABLE_THREAD_SUPPORT) && defined(EVTHREAD_EXPOSE_STRUCTS)
 /* Global function pointers to lock-related functions. NULL if locking isn't
    enabled. */
-extern struct evthread_lock_callbacks _evthread_lock_fns;
-extern struct evthread_condition_callbacks _evthread_cond_fns;
-extern unsigned long (*_evthread_id_fn)(void);
-extern int _evthread_lock_debugging_enabled;
+extern struct evthread_lock_callbacks evthread_lock_fns_;
+extern struct evthread_condition_callbacks evthread_cond_fns_;
+extern unsigned long (*evthread_id_fn_)(void);
+extern int evthread_lock_debugging_enabled_;
 
 /** Return the ID of the current thread, or 1 if threading isn't enabled. */
 #define EVTHREAD_GET_ID() \
-       (_evthread_id_fn ? _evthread_id_fn() : 1)
+       (evthread_id_fn_ ? evthread_id_fn_() : 1)
 
 /** Return true iff we're in the thread that is currently (or most recently)
  * running a given event_base's loop. Requires lock. */
 #define EVBASE_IN_THREAD(base)                          \
-       (_evthread_id_fn == NULL ||                      \
-       (base)->th_owner_id == _evthread_id_fn())
+       (evthread_id_fn_ == NULL ||                      \
+       (base)->th_owner_id == evthread_id_fn_())
 
 /** Return true iff we need to notify the base's main thread about changes to
  * its state, because it's currently running the main loop in another
  * thread. Requires lock. */
 #define EVBASE_NEED_NOTIFY(base)                        \
-       (_evthread_id_fn != NULL &&                      \
+       (evthread_id_fn_ != NULL &&                      \
            (base)->running_loop &&                      \
-           (base)->th_owner_id != _evthread_id_fn())
+           (base)->th_owner_id != evthread_id_fn_())
 
 /** Allocate a new lock, and store it in lockvar, a void*.  Sets lockvar to
     NULL if locking is not enabled. */
 #define EVTHREAD_ALLOC_LOCK(lockvar, locktype)         \
-       ((lockvar) = _evthread_lock_fns.alloc ?         \
-           _evthread_lock_fns.alloc(locktype) : NULL)
+       ((lockvar) = evthread_lock_fns_.alloc ?         \
+           evthread_lock_fns_.alloc(locktype) : NULL)
 
 /** Free a given lock, if it is present and locking is enabled. */
 #define EVTHREAD_FREE_LOCK(lockvar, locktype)                          \
        do {                                                            \
-               void *_lock_tmp_ = (lockvar);                           \
-               if (_lock_tmp_ && _evthread_lock_fns.free)              \
-                       _evthread_lock_fns.free(_lock_tmp_, (locktype)); \
+               void *lock_tmp_ = (lockvar);                            \
+               if (lock_tmp_ && evthread_lock_fns_.free)               \
+                       evthread_lock_fns_.free(lock_tmp_, (locktype)); \
        } while (0)
 
 /** Acquire a lock. */
 #define EVLOCK_LOCK(lockvar,mode)                                      \
        do {                                                            \
                if (lockvar)                                            \
-                       _evthread_lock_fns.lock(mode, lockvar);         \
+                       evthread_lock_fns_.lock(mode, lockvar);         \
        } while (0)
 
 /** Release a lock */
 #define EVLOCK_UNLOCK(lockvar,mode)                                    \
        do {                                                            \
                if (lockvar)                                            \
-                       _evthread_lock_fns.unlock(mode, lockvar);       \
+                       evthread_lock_fns_.unlock(mode, lockvar);       \
        } while (0)
 
 /** Helper: put lockvar1 and lockvar2 into pointerwise ascending order. */
-#define _EVLOCK_SORTLOCKS(lockvar1, lockvar2)                          \
+#define EVLOCK_SORTLOCKS_(lockvar1, lockvar2)                          \
        do {                                                            \
                if (lockvar1 && lockvar2 && lockvar1 > lockvar2) {      \
                        void *tmp = lockvar1;                           \
@@ -125,19 +125,19 @@ extern int _evthread_lock_debugging_enabled;
  * locked and held by us. */
 #define EVLOCK_ASSERT_LOCKED(lock)                                     \
        do {                                                            \
-               if ((lock) && _evthread_lock_debugging_enabled) {       \
-                       EVUTIL_ASSERT(_evthread_is_debug_lock_held(lock)); \
+               if ((lock) && evthread_lock_debugging_enabled_) {       \
+                       EVUTIL_ASSERT(evthread_is_debug_lock_held_(lock)); \
                }                                                       \
        } while (0)
 
 /** Try to grab the lock for 'lockvar' without blocking, and return 1 if we
  * manage to get it. */
-static inline int EVLOCK_TRY_LOCK(void *lock);
+static inline int EVLOCK_TRY_LOCK_(void *lock);
 static inline int
-EVLOCK_TRY_LOCK(void *lock)
+EVLOCK_TRY_LOCK_(void *lock)
 {
-       if (lock && _evthread_lock_fns.lock) {
-               int r = _evthread_lock_fns.lock(EVTHREAD_TRY, lock);
+       if (lock && evthread_lock_fns_.lock) {
+               int r = evthread_lock_fns_.lock(EVTHREAD_TRY, lock);
                return !r;
        } else {
                /* Locking is disabled either globally or for this thing;
@@ -149,74 +149,79 @@ EVLOCK_TRY_LOCK(void *lock)
 /** Allocate a new condition variable and store it in the void *, condvar */
 #define EVTHREAD_ALLOC_COND(condvar)                                   \
        do {                                                            \
-               (condvar) = _evthread_cond_fns.alloc_condition ?        \
-                   _evthread_cond_fns.alloc_condition(0) : NULL;       \
+               (condvar) = evthread_cond_fns_.alloc_condition ?        \
+                   evthread_cond_fns_.alloc_condition(0) : NULL;       \
        } while (0)
 /** Deallocate and free a condition variable in condvar */
 #define EVTHREAD_FREE_COND(cond)                                       \
        do {                                                            \
                if (cond)                                               \
-                       _evthread_cond_fns.free_condition((cond));      \
+                       evthread_cond_fns_.free_condition((cond));      \
        } while (0)
 /** Signal one thread waiting on cond */
 #define EVTHREAD_COND_SIGNAL(cond)                                     \
-       ( (cond) ? _evthread_cond_fns.signal_condition((cond), 0) : 0 )
+       ( (cond) ? evthread_cond_fns_.signal_condition((cond), 0) : 0 )
 /** Signal all threads waiting on cond */
 #define EVTHREAD_COND_BROADCAST(cond)                                  \
-       ( (cond) ? _evthread_cond_fns.signal_condition((cond), 1) : 0 )
+       ( (cond) ? evthread_cond_fns_.signal_condition((cond), 1) : 0 )
 /** Wait until the condition 'cond' is signalled.  Must be called while
  * holding 'lock'.  The lock will be released until the condition is
  * signalled, at which point it will be acquired again.  Returns 0 for
  * success, -1 for failure. */
 #define EVTHREAD_COND_WAIT(cond, lock)                                 \
-       ( (cond) ? _evthread_cond_fns.wait_condition((cond), (lock), NULL) : 0 )
+       ( (cond) ? evthread_cond_fns_.wait_condition((cond), (lock), NULL) : 0 )
 /** As EVTHREAD_COND_WAIT, but gives up after 'tv' has elapsed.  Returns 1
  * on timeout. */
 #define EVTHREAD_COND_WAIT_TIMED(cond, lock, tv)                       \
-       ( (cond) ? _evthread_cond_fns.wait_condition((cond), (lock), (tv)) : 0 )
-
-#elif ! defined(_EVENT_DISABLE_THREAD_SUPPORT)
-
-unsigned long _evthreadimpl_get_id(void);
-int _evthreadimpl_is_lock_debugging_enabled(void);
-void *_evthreadimpl_lock_alloc(unsigned locktype);
-void _evthreadimpl_lock_free(void *lock, unsigned locktype);
-int _evthreadimpl_lock_lock(unsigned mode, void *lock);
-int _evthreadimpl_lock_unlock(unsigned mode, void *lock);
-void *_evthreadimpl_cond_alloc(unsigned condtype);
-void _evthreadimpl_cond_free(void *cond);
-int _evthreadimpl_cond_signal(void *cond, int broadcast);
-int _evthreadimpl_cond_wait(void *cond, void *lock, const struct timeval *tv);
-
-#define EVTHREAD_GET_ID() _evthreadimpl_get_id()
+       ( (cond) ? evthread_cond_fns_.wait_condition((cond), (lock), (tv)) : 0 )
+
+/** True iff locking functions have been configured. */
+#define EVTHREAD_LOCKING_ENABLED()             \
+       (evthread_lock_fns_.lock != NULL)
+
+#elif ! defined(EVENT__DISABLE_THREAD_SUPPORT)
+
+unsigned long evthreadimpl_get_id_(void);
+int evthreadimpl_is_lock_debugging_enabled_(void);
+void *evthreadimpl_lock_alloc_(unsigned locktype);
+void evthreadimpl_lock_free_(void *lock, unsigned locktype);
+int evthreadimpl_lock_lock_(unsigned mode, void *lock);
+int evthreadimpl_lock_unlock_(unsigned mode, void *lock);
+void *evthreadimpl_cond_alloc_(unsigned condtype);
+void evthreadimpl_cond_free_(void *cond);
+int evthreadimpl_cond_signal_(void *cond, int broadcast);
+int evthreadimpl_cond_wait_(void *cond, void *lock, const struct timeval *tv);
+int evthreadimpl_locking_enabled_(void);
+
+#define EVTHREAD_GET_ID() evthreadimpl_get_id_()
 #define EVBASE_IN_THREAD(base)                         \
-       ((base)->th_owner_id == _evthreadimpl_get_id())
+       ((base)->th_owner_id == evthreadimpl_get_id_())
 #define EVBASE_NEED_NOTIFY(base)                        \
        ((base)->running_loop &&                         \
-           ((base)->th_owner_id != _evthreadimpl_get_id()))
+           ((base)->th_owner_id != evthreadimpl_get_id_()))
 
 #define EVTHREAD_ALLOC_LOCK(lockvar, locktype)         \
-       ((lockvar) = _evthreadimpl_lock_alloc(locktype))
+       ((lockvar) = evthreadimpl_lock_alloc_(locktype))
 
 #define EVTHREAD_FREE_LOCK(lockvar, locktype)                          \
        do {                                                            \
-               void *_lock_tmp_ = (lockvar);                           \
-               if (_lock_tmp_)                                         \
-                       _evthreadimpl_lock_free(_lock_tmp_, (locktype)); \
+               void *lock_tmp_ = (lockvar);                            \
+               if (lock_tmp_)                                          \
+                       evthreadimpl_lock_free_(lock_tmp_, (locktype)); \
        } while (0)
 
 /** Acquire a lock. */
 #define EVLOCK_LOCK(lockvar,mode)                                      \
        do {                                                            \
                if (lockvar)                                            \
-                       _evthreadimpl_lock_lock(mode, lockvar);         \
+                       evthreadimpl_lock_lock_(mode, lockvar);         \
        } while (0)
 
 /** Release a lock */
 #define EVLOCK_UNLOCK(lockvar,mode)                                    \
        do {                                                            \
                if (lockvar)                                            \
-                       _evthreadimpl_lock_unlock(mode, lockvar);       \
+                       evthreadimpl_lock_unlock_(mode, lockvar);       \
        } while (0)
 
 /** Lock an event_base, if it is set up for locking.  Acquires the lock
@@ -234,19 +239,19 @@ int _evthreadimpl_cond_wait(void *cond, void *lock, const struct timeval *tv);
  * locked and held by us. */
 #define EVLOCK_ASSERT_LOCKED(lock)                                     \
        do {                                                            \
-               if ((lock) && _evthreadimpl_is_lock_debugging_enabled()) { \
-                       EVUTIL_ASSERT(_evthread_is_debug_lock_held(lock)); \
+               if ((lock) && evthreadimpl_is_lock_debugging_enabled_()) { \
+                       EVUTIL_ASSERT(evthread_is_debug_lock_held_(lock)); \
                }                                                       \
        } while (0)
 
 /** Try to grab the lock for 'lockvar' without blocking, and return 1 if we
  * manage to get it. */
-static inline int EVLOCK_TRY_LOCK(void *lock);
+static inline int EVLOCK_TRY_LOCK_(void *lock);
 static inline int
-EVLOCK_TRY_LOCK(void *lock)
+EVLOCK_TRY_LOCK_(void *lock)
 {
        if (lock) {
-               int r = _evthreadimpl_lock_lock(EVTHREAD_TRY, lock);
+               int r = evthreadimpl_lock_lock_(EVTHREAD_TRY, lock);
                return !r;
        } else {
                /* Locking is disabled either globally or for this thing;
@@ -258,63 +263,68 @@ EVLOCK_TRY_LOCK(void *lock)
 /** Allocate a new condition variable and store it in the void *, condvar */
 #define EVTHREAD_ALLOC_COND(condvar)                                   \
        do {                                                            \
-               (condvar) = _evthreadimpl_cond_alloc(0);                \
+               (condvar) = evthreadimpl_cond_alloc_(0);                \
        } while (0)
 /** Deallocate and free a condition variable in condvar */
 #define EVTHREAD_FREE_COND(cond)                                       \
        do {                                                            \
                if (cond)                                               \
-                       _evthreadimpl_cond_free((cond));                \
+                       evthreadimpl_cond_free_((cond));                \
        } while (0)
 /** Signal one thread waiting on cond */
 #define EVTHREAD_COND_SIGNAL(cond)                                     \
-       ( (cond) ? _evthreadimpl_cond_signal((cond), 0) : 0 )
+       ( (cond) ? evthreadimpl_cond_signal_((cond), 0) : 0 )
 /** Signal all threads waiting on cond */
 #define EVTHREAD_COND_BROADCAST(cond)                                  \
-       ( (cond) ? _evthreadimpl_cond_signal((cond), 1) : 0 )
+       ( (cond) ? evthreadimpl_cond_signal_((cond), 1) : 0 )
 /** Wait until the condition 'cond' is signalled.  Must be called while
  * holding 'lock'.  The lock will be released until the condition is
  * signalled, at which point it will be acquired again.  Returns 0 for
  * success, -1 for failure. */
 #define EVTHREAD_COND_WAIT(cond, lock)                                 \
-       ( (cond) ? _evthreadimpl_cond_wait((cond), (lock), NULL) : 0 )
+       ( (cond) ? evthreadimpl_cond_wait_((cond), (lock), NULL) : 0 )
 /** As EVTHREAD_COND_WAIT, but gives up after 'tv' has elapsed.  Returns 1
  * on timeout. */
 #define EVTHREAD_COND_WAIT_TIMED(cond, lock, tv)                       \
-       ( (cond) ? _evthreadimpl_cond_wait((cond), (lock), (tv)) : 0 )
+       ( (cond) ? evthreadimpl_cond_wait_((cond), (lock), (tv)) : 0 )
 
-#else /* _EVENT_DISABLE_THREAD_SUPPORT */
+#define EVTHREAD_LOCKING_ENABLED()             \
+       (evthreadimpl_locking_enabled_())
+
+#else /* EVENT__DISABLE_THREAD_SUPPORT */
 
 #define EVTHREAD_GET_ID()      1
-#define EVTHREAD_ALLOC_LOCK(lockvar, locktype) _EVUTIL_NIL_STMT
-#define EVTHREAD_FREE_LOCK(lockvar, locktype) _EVUTIL_NIL_STMT
+#define EVTHREAD_ALLOC_LOCK(lockvar, locktype) EVUTIL_NIL_STMT_
+#define EVTHREAD_FREE_LOCK(lockvar, locktype) EVUTIL_NIL_STMT_
 
-#define EVLOCK_LOCK(lockvar, mode) _EVUTIL_NIL_STMT
-#define EVLOCK_UNLOCK(lockvar, mode) _EVUTIL_NIL_STMT
-#define EVLOCK_LOCK2(lock1,lock2,mode1,mode2) _EVUTIL_NIL_STMT
-#define EVLOCK_UNLOCK2(lock1,lock2,mode1,mode2) _EVUTIL_NIL_STMT
+#define EVLOCK_LOCK(lockvar, mode) EVUTIL_NIL_STMT_
+#define EVLOCK_UNLOCK(lockvar, mode) EVUTIL_NIL_STMT_
+#define EVLOCK_LOCK2(lock1,lock2,mode1,mode2) EVUTIL_NIL_STMT_
+#define EVLOCK_UNLOCK2(lock1,lock2,mode1,mode2) EVUTIL_NIL_STMT_
 
 #define EVBASE_IN_THREAD(base) 1
 #define EVBASE_NEED_NOTIFY(base) 0
-#define EVBASE_ACQUIRE_LOCK(base, lock) _EVUTIL_NIL_STMT
-#define EVBASE_RELEASE_LOCK(base, lock) _EVUTIL_NIL_STMT
-#define EVLOCK_ASSERT_LOCKED(lock) _EVUTIL_NIL_STMT
+#define EVBASE_ACQUIRE_LOCK(base, lock) EVUTIL_NIL_STMT_
+#define EVBASE_RELEASE_LOCK(base, lock) EVUTIL_NIL_STMT_
+#define EVLOCK_ASSERT_LOCKED(lock) EVUTIL_NIL_STMT_
+
+#define EVLOCK_TRY_LOCK_(lock) 1
 
-#define EVLOCK_TRY_LOCK(lock) 1
+#define EVTHREAD_ALLOC_COND(condvar) EVUTIL_NIL_STMT_
+#define EVTHREAD_FREE_COND(cond) EVUTIL_NIL_STMT_
+#define EVTHREAD_COND_SIGNAL(cond) EVUTIL_NIL_STMT_
+#define EVTHREAD_COND_BROADCAST(cond) EVUTIL_NIL_STMT_
+#define EVTHREAD_COND_WAIT(cond, lock) EVUTIL_NIL_STMT_
+#define EVTHREAD_COND_WAIT_TIMED(cond, lock, howlong) EVUTIL_NIL_STMT_
 
-#define EVTHREAD_ALLOC_COND(condvar) _EVUTIL_NIL_STMT
-#define EVTHREAD_FREE_COND(cond) _EVUTIL_NIL_STMT
-#define EVTHREAD_COND_SIGNAL(cond) _EVUTIL_NIL_STMT
-#define EVTHREAD_COND_BROADCAST(cond) _EVUTIL_NIL_STMT
-#define EVTHREAD_COND_WAIT(cond, lock) _EVUTIL_NIL_STMT
-#define EVTHREAD_COND_WAIT_TIMED(cond, lock, howlong) _EVUTIL_NIL_STMT
+#define EVTHREAD_LOCKING_ENABLED() 0
 
 #endif
 
 /* This code is shared between both lock impls */
-#if ! defined(_EVENT_DISABLE_THREAD_SUPPORT)
+#if ! defined(EVENT__DISABLE_THREAD_SUPPORT)
 /** Helper: put lockvar1 and lockvar2 into pointerwise ascending order. */
-#define _EVLOCK_SORTLOCKS(lockvar1, lockvar2)                          \
+#define EVLOCK_SORTLOCKS_(lockvar1, lockvar2)                          \
        do {                                                            \
                if (lockvar1 && lockvar2 && lockvar1 > lockvar2) {      \
                        void *tmp = lockvar1;                           \
@@ -327,26 +337,26 @@ EVLOCK_TRY_LOCK(void *lock)
  * so that two threads locking two locks with LOCK2 will not deadlock. */
 #define EVLOCK_LOCK2(lock1,lock2,mode1,mode2)                          \
        do {                                                            \
-               void *_lock1_tmplock = (lock1);                         \
-               void *_lock2_tmplock = (lock2);                         \
-               _EVLOCK_SORTLOCKS(_lock1_tmplock,_lock2_tmplock);       \
-               EVLOCK_LOCK(_lock1_tmplock,mode1);                      \
-               if (_lock2_tmplock != _lock1_tmplock)                   \
-                       EVLOCK_LOCK(_lock2_tmplock,mode2);              \
+               void *lock1_tmplock_ = (lock1);                         \
+               void *lock2_tmplock_ = (lock2);                         \
+               EVLOCK_SORTLOCKS_(lock1_tmplock_,lock2_tmplock_);       \
+               EVLOCK_LOCK(lock1_tmplock_,mode1);                      \
+               if (lock2_tmplock_ != lock1_tmplock_)                   \
+                       EVLOCK_LOCK(lock2_tmplock_,mode2);              \
        } while (0)
 /** Release both lock1 and lock2.  */
 #define EVLOCK_UNLOCK2(lock1,lock2,mode1,mode2)                                \
        do {                                                            \
-               void *_lock1_tmplock = (lock1);                         \
-               void *_lock2_tmplock = (lock2);                         \
-               _EVLOCK_SORTLOCKS(_lock1_tmplock,_lock2_tmplock);       \
-               if (_lock2_tmplock != _lock1_tmplock)                   \
-                       EVLOCK_UNLOCK(_lock2_tmplock,mode2);            \
-               EVLOCK_UNLOCK(_lock1_tmplock,mode1);                    \
+               void *lock1_tmplock_ = (lock1);                         \
+               void *lock2_tmplock_ = (lock2);                         \
+               EVLOCK_SORTLOCKS_(lock1_tmplock_,lock2_tmplock_);       \
+               if (lock2_tmplock_ != lock1_tmplock_)                   \
+                       EVLOCK_UNLOCK(lock2_tmplock_,mode2);            \
+               EVLOCK_UNLOCK(lock1_tmplock_,mode1);                    \
        } while (0)
 
-int _evthread_is_debug_lock_held(void *lock);
-void *_evthread_debug_get_real_lock(void *lock);
+int evthread_is_debug_lock_held_(void *lock);
+void *evthread_debug_get_real_lock_(void *lock);
 
 void *evthread_setup_global_lock_(void *lock_, unsigned locktype,
     int enable_locks);
@@ -371,4 +381,4 @@ int evutil_secure_rng_global_setup_locks_(const int enable_locks);
 }
 #endif
 
-#endif /* _EVTHREAD_INTERNAL_H_ */
+#endif /* EVTHREAD_INTERNAL_H_INCLUDED_ */
index 22d09ae4de19bb16db9a29f5abb363526ecdc226..b5d3d577e3f83f1aa580914a3a3b3e48180adef2 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008-2010 Niels Provos, Nick Mathewson
+ * Copyright (c) 2008-2012 Niels Provos, Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,7 +27,7 @@
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
 
 #include "event2/thread.h"
 
 #endif
 
 /* globals */
-GLOBAL int _evthread_lock_debugging_enabled = 0;
-GLOBAL struct evthread_lock_callbacks _evthread_lock_fns = {
+GLOBAL int evthread_lock_debugging_enabled_ = 0;
+GLOBAL struct evthread_lock_callbacks evthread_lock_fns_ = {
        0, 0, NULL, NULL, NULL, NULL
 };
-GLOBAL unsigned long (*_evthread_id_fn)(void) = NULL;
-GLOBAL struct evthread_condition_callbacks _evthread_cond_fns = {
+GLOBAL unsigned long (*evthread_id_fn_)(void) = NULL;
+GLOBAL struct evthread_condition_callbacks evthread_cond_fns_ = {
        0, NULL, NULL, NULL, NULL
 };
 
 /* Used for debugging */
-static struct evthread_lock_callbacks _original_lock_fns = {
+static struct evthread_lock_callbacks original_lock_fns_ = {
        0, 0, NULL, NULL, NULL, NULL
 };
-static struct evthread_condition_callbacks _original_cond_fns = {
+static struct evthread_condition_callbacks original_cond_fns_ = {
        0, NULL, NULL, NULL, NULL
 };
 
 void
 evthread_set_id_callback(unsigned long (*id_fn)(void))
 {
-       _evthread_id_fn = id_fn;
+       evthread_id_fn_ = id_fn;
 }
 
 int
 evthread_set_lock_callbacks(const struct evthread_lock_callbacks *cbs)
 {
        struct evthread_lock_callbacks *target =
-           _evthread_lock_debugging_enabled
-           ? &_original_lock_fns : &_evthread_lock_fns;
+           evthread_lock_debugging_enabled_
+           ? &original_lock_fns_ : &evthread_lock_fns_;
 
        if (!cbs) {
                if (target->alloc)
                        event_warnx("Trying to disable lock functions after "
                            "they have been set up will probaby not work.");
-               memset(target, 0, sizeof(_evthread_lock_fns));
+               memset(target, 0, sizeof(evthread_lock_fns_));
                return 0;
        }
        if (target->alloc) {
                /* Uh oh; we already had locking callbacks set up.*/
-               if (!memcmp(target, cbs, sizeof(_evthread_lock_fns))) {
+               if (target->lock_api_version == cbs->lock_api_version &&
+                       target->supported_locktypes == cbs->supported_locktypes &&
+                       target->alloc == cbs->alloc &&
+                       target->free == cbs->free &&
+                       target->lock == cbs->lock &&
+                       target->unlock == cbs->unlock) {
                        /* no change -- allow this. */
                        return 0;
                }
@@ -94,7 +99,7 @@ evthread_set_lock_callbacks(const struct evthread_lock_callbacks *cbs)
                return -1;
        }
        if (cbs->alloc && cbs->free && cbs->lock && cbs->unlock) {
-               memcpy(target, cbs, sizeof(_evthread_lock_fns));
+               memcpy(target, cbs, sizeof(evthread_lock_fns_));
                return event_global_setup_locks_(1);
        } else {
                return -1;
@@ -105,20 +110,24 @@ int
 evthread_set_condition_callbacks(const struct evthread_condition_callbacks *cbs)
 {
        struct evthread_condition_callbacks *target =
-           _evthread_lock_debugging_enabled
-           ? &_original_cond_fns : &_evthread_cond_fns;
+           evthread_lock_debugging_enabled_
+           ? &original_cond_fns_ : &evthread_cond_fns_;
 
        if (!cbs) {
                if (target->alloc_condition)
                        event_warnx("Trying to disable condition functions "
                            "after they have been set up will probaby not "
                            "work.");
-               memset(target, 0, sizeof(_evthread_cond_fns));
+               memset(target, 0, sizeof(evthread_cond_fns_));
                return 0;
        }
        if (target->alloc_condition) {
                /* Uh oh; we already had condition callbacks set up.*/
-               if (!memcmp(target, cbs, sizeof(_evthread_cond_fns))) {
+               if (target->condition_api_version == cbs->condition_api_version &&
+                       target->alloc_condition == cbs->alloc_condition &&
+                       target->free_condition == cbs->free_condition &&
+                       target->signal_condition == cbs->signal_condition &&
+                       target->wait_condition == cbs->wait_condition) {
                        /* no change -- allow this. */
                        return 0;
                }
@@ -128,12 +137,12 @@ evthread_set_condition_callbacks(const struct evthread_condition_callbacks *cbs)
        }
        if (cbs->alloc_condition && cbs->free_condition &&
            cbs->signal_condition && cbs->wait_condition) {
-               memcpy(target, cbs, sizeof(_evthread_cond_fns));
+               memcpy(target, cbs, sizeof(evthread_cond_fns_));
        }
-       if (_evthread_lock_debugging_enabled) {
-               _evthread_cond_fns.alloc_condition = cbs->alloc_condition;
-               _evthread_cond_fns.free_condition = cbs->free_condition;
-               _evthread_cond_fns.signal_condition = cbs->signal_condition;
+       if (evthread_lock_debugging_enabled_) {
+               evthread_cond_fns_.alloc_condition = cbs->alloc_condition;
+               evthread_cond_fns_.free_condition = cbs->free_condition;
+               evthread_cond_fns_.signal_condition = cbs->signal_condition;
        }
        return 0;
 }
@@ -156,8 +165,8 @@ debug_lock_alloc(unsigned locktype)
        struct debug_lock *result = mm_malloc(sizeof(struct debug_lock));
        if (!result)
                return NULL;
-       if (_original_lock_fns.alloc) {
-               if (!(result->lock = _original_lock_fns.alloc(
+       if (original_lock_fns_.alloc) {
+               if (!(result->lock = original_lock_fns_.alloc(
                                locktype|EVTHREAD_LOCKTYPE_RECURSIVE))) {
                        mm_free(result);
                        return NULL;
@@ -179,8 +188,8 @@ debug_lock_free(void *lock_, unsigned locktype)
        EVUTIL_ASSERT(lock->count == 0);
        EVUTIL_ASSERT(locktype == lock->locktype);
        EVUTIL_ASSERT(DEBUG_LOCK_SIG == lock->signature);
-       if (_original_lock_fns.free) {
-               _original_lock_fns.free(lock->lock,
+       if (original_lock_fns_.free) {
+               original_lock_fns_.free(lock->lock,
                    lock->locktype|EVTHREAD_LOCKTYPE_RECURSIVE);
        }
        lock->lock = NULL;
@@ -196,9 +205,9 @@ evthread_debug_lock_mark_locked(unsigned mode, struct debug_lock *lock)
        ++lock->count;
        if (!(lock->locktype & EVTHREAD_LOCKTYPE_RECURSIVE))
                EVUTIL_ASSERT(lock->count == 1);
-       if (_evthread_id_fn) {
+       if (evthread_id_fn_) {
                unsigned long me;
-               me = _evthread_id_fn();
+               me = evthread_id_fn_();
                if (lock->count > 1)
                        EVUTIL_ASSERT(lock->held_by == me);
                lock->held_by = me;
@@ -214,8 +223,8 @@ debug_lock_lock(unsigned mode, void *lock_)
                EVUTIL_ASSERT(mode & (EVTHREAD_READ|EVTHREAD_WRITE));
        else
                EVUTIL_ASSERT((mode & (EVTHREAD_READ|EVTHREAD_WRITE)) == 0);
-       if (_original_lock_fns.lock)
-               res = _original_lock_fns.lock(mode, lock->lock);
+       if (original_lock_fns_.lock)
+               res = original_lock_fns_.lock(mode, lock->lock);
        if (!res) {
                evthread_debug_lock_mark_locked(mode, lock);
        }
@@ -230,9 +239,9 @@ evthread_debug_lock_mark_unlocked(unsigned mode, struct debug_lock *lock)
                EVUTIL_ASSERT(mode & (EVTHREAD_READ|EVTHREAD_WRITE));
        else
                EVUTIL_ASSERT((mode & (EVTHREAD_READ|EVTHREAD_WRITE)) == 0);
-       if (_evthread_id_fn) {
+       if (evthread_id_fn_) {
                unsigned long me;
-               me = _evthread_id_fn();
+               me = evthread_id_fn_();
                EVUTIL_ASSERT(lock->held_by == me);
                if (lock->count == 1)
                        lock->held_by = 0;
@@ -247,21 +256,21 @@ debug_lock_unlock(unsigned mode, void *lock_)
        struct debug_lock *lock = lock_;
        int res = 0;
        evthread_debug_lock_mark_unlocked(mode, lock);
-       if (_original_lock_fns.unlock)
-               res = _original_lock_fns.unlock(mode, lock->lock);
+       if (original_lock_fns_.unlock)
+               res = original_lock_fns_.unlock(mode, lock->lock);
        return res;
 }
 
 static int
-debug_cond_wait(void *_cond, void *_lock, const struct timeval *tv)
+debug_cond_wait(void *cond_, void *lock_, const struct timeval *tv)
 {
        int r;
-       struct debug_lock *lock = _lock;
+       struct debug_lock *lock = lock_;
        EVUTIL_ASSERT(lock);
        EVUTIL_ASSERT(DEBUG_LOCK_SIG == lock->signature);
-       EVLOCK_ASSERT_LOCKED(_lock);
+       EVLOCK_ASSERT_LOCKED(lock_);
        evthread_debug_lock_mark_unlocked(0, lock);
-       r = _original_cond_fns.wait_condition(_cond, lock->lock, tv);
+       r = original_cond_fns_.wait_condition(cond_, lock->lock, tv);
        evthread_debug_lock_mark_locked(0, lock);
        return r;
 }
@@ -277,30 +286,30 @@ evthread_enable_lock_debuging(void)
                debug_lock_lock,
                debug_lock_unlock
        };
-       if (_evthread_lock_debugging_enabled)
+       if (evthread_lock_debugging_enabled_)
                return;
-       memcpy(&_original_lock_fns, &_evthread_lock_fns,
+       memcpy(&original_lock_fns_, &evthread_lock_fns_,
            sizeof(struct evthread_lock_callbacks));
-       memcpy(&_evthread_lock_fns, &cbs,
+       memcpy(&evthread_lock_fns_, &cbs,
            sizeof(struct evthread_lock_callbacks));
 
-       memcpy(&_original_cond_fns, &_evthread_cond_fns,
+       memcpy(&original_cond_fns_, &evthread_cond_fns_,
            sizeof(struct evthread_condition_callbacks));
-       _evthread_cond_fns.wait_condition = debug_cond_wait;
-       _evthread_lock_debugging_enabled = 1;
+       evthread_cond_fns_.wait_condition = debug_cond_wait;
+       evthread_lock_debugging_enabled_ = 1;
 
        /* XXX return value should get checked. */
        event_global_setup_locks_(0);
 }
 
 int
-_evthread_is_debug_lock_held(void *lock_)
+evthread_is_debug_lock_held_(void *lock_)
 {
        struct debug_lock *lock = lock_;
        if (! lock->count)
                return 0;
-       if (_evthread_id_fn) {
-               unsigned long me = _evthread_id_fn();
+       if (evthread_id_fn_) {
+               unsigned long me = evthread_id_fn_();
                if (lock->held_by != me)
                        return 0;
        }
@@ -308,7 +317,7 @@ _evthread_is_debug_lock_held(void *lock_)
 }
 
 void *
-_evthread_debug_get_real_lock(void *lock_)
+evthread_debug_get_real_lock_(void *lock_)
 {
        struct debug_lock *lock = lock_;
        return lock->lock;
@@ -323,23 +332,23 @@ evthread_setup_global_lock_(void *lock_, unsigned locktype, int enable_locks)
           3) we're turning on locking; debugging is not on.
           4) we're turning on locking; debugging is on. */
 
-       if (!enable_locks && _original_lock_fns.alloc == NULL) {
+       if (!enable_locks && original_lock_fns_.alloc == NULL) {
                /* Case 1: allocate a debug lock. */
                EVUTIL_ASSERT(lock_ == NULL);
                return debug_lock_alloc(locktype);
-       } else if (!enable_locks && _original_lock_fns.alloc != NULL) {
+       } else if (!enable_locks && original_lock_fns_.alloc != NULL) {
                /* Case 2: wrap the lock in a debug lock. */
                struct debug_lock *lock;
                EVUTIL_ASSERT(lock_ != NULL);
 
                if (!(locktype & EVTHREAD_LOCKTYPE_RECURSIVE)) {
                        /* We can't wrap it: We need a recursive lock */
-                       _original_lock_fns.free(lock_, locktype);
+                       original_lock_fns_.free(lock_, locktype);
                        return debug_lock_alloc(locktype);
                }
                lock = mm_malloc(sizeof(struct debug_lock));
                if (!lock) {
-                       _original_lock_fns.free(lock_, locktype);
+                       original_lock_fns_.free(lock_, locktype);
                        return NULL;
                }
                lock->lock = lock_;
@@ -347,18 +356,18 @@ evthread_setup_global_lock_(void *lock_, unsigned locktype, int enable_locks)
                lock->count = 0;
                lock->held_by = 0;
                return lock;
-       } else if (enable_locks && ! _evthread_lock_debugging_enabled) {
+       } else if (enable_locks && ! evthread_lock_debugging_enabled_) {
                /* Case 3: allocate a regular lock */
                EVUTIL_ASSERT(lock_ == NULL);
-               return _evthread_lock_fns.alloc(locktype);
+               return evthread_lock_fns_.alloc(locktype);
        } else {
                /* Case 4: Fill in a debug lock with a real lock */
                struct debug_lock *lock = lock_;
                EVUTIL_ASSERT(enable_locks &&
-                             _evthread_lock_debugging_enabled);
+                             evthread_lock_debugging_enabled_);
                EVUTIL_ASSERT(lock->locktype == locktype);
                EVUTIL_ASSERT(lock->lock == NULL);
-               lock->lock = _original_lock_fns.alloc(
+               lock->lock = original_lock_fns_.alloc(
                        locktype|EVTHREAD_LOCKTYPE_RECURSIVE);
                if (!lock->lock) {
                        lock->count = -200;
@@ -372,70 +381,76 @@ evthread_setup_global_lock_(void *lock_, unsigned locktype, int enable_locks)
 
 #ifndef EVTHREAD_EXPOSE_STRUCTS
 unsigned long
-_evthreadimpl_get_id()
+evthreadimpl_get_id_()
 {
-       return _evthread_id_fn ? _evthread_id_fn() : 1;
+       return evthread_id_fn_ ? evthread_id_fn_() : 1;
 }
 void *
-_evthreadimpl_lock_alloc(unsigned locktype)
+evthreadimpl_lock_alloc_(unsigned locktype)
 {
-       return _evthread_lock_fns.alloc ?
-           _evthread_lock_fns.alloc(locktype) : NULL;
+       return evthread_lock_fns_.alloc ?
+           evthread_lock_fns_.alloc(locktype) : NULL;
 }
 void
-_evthreadimpl_lock_free(void *lock, unsigned locktype)
+evthreadimpl_lock_free_(void *lock, unsigned locktype)
 {
-       if (_evthread_lock_fns.free)
-               _evthread_lock_fns.free(lock, locktype);
+       if (evthread_lock_fns_.free)
+               evthread_lock_fns_.free(lock, locktype);
 }
 int
-_evthreadimpl_lock_lock(unsigned mode, void *lock)
+evthreadimpl_lock_lock_(unsigned mode, void *lock)
 {
-       if (_evthread_lock_fns.lock)
-               return _evthread_lock_fns.lock(mode, lock);
+       if (evthread_lock_fns_.lock)
+               return evthread_lock_fns_.lock(mode, lock);
        else
                return 0;
 }
 int
-_evthreadimpl_lock_unlock(unsigned mode, void *lock)
+evthreadimpl_lock_unlock_(unsigned mode, void *lock)
 {
-       if (_evthread_lock_fns.unlock)
-               return _evthread_lock_fns.unlock(mode, lock);
+       if (evthread_lock_fns_.unlock)
+               return evthread_lock_fns_.unlock(mode, lock);
        else
                return 0;
 }
 void *
-_evthreadimpl_cond_alloc(unsigned condtype)
+evthreadimpl_cond_alloc_(unsigned condtype)
 {
-       return _evthread_cond_fns.alloc_condition ?
-           _evthread_cond_fns.alloc_condition(condtype) : NULL;
+       return evthread_cond_fns_.alloc_condition ?
+           evthread_cond_fns_.alloc_condition(condtype) : NULL;
 }
 void
-_evthreadimpl_cond_free(void *cond)
+evthreadimpl_cond_free_(void *cond)
 {
-       if (_evthread_cond_fns.free_condition)
-               _evthread_cond_fns.free_condition(cond);
+       if (evthread_cond_fns_.free_condition)
+               evthread_cond_fns_.free_condition(cond);
 }
 int
-_evthreadimpl_cond_signal(void *cond, int broadcast)
+evthreadimpl_cond_signal_(void *cond, int broadcast)
 {
-       if (_evthread_cond_fns.signal_condition)
-               return _evthread_cond_fns.signal_condition(cond, broadcast);
+       if (evthread_cond_fns_.signal_condition)
+               return evthread_cond_fns_.signal_condition(cond, broadcast);
        else
                return 0;
 }
 int
-_evthreadimpl_cond_wait(void *cond, void *lock, const struct timeval *tv)
+evthreadimpl_cond_wait_(void *cond, void *lock, const struct timeval *tv)
 {
-       if (_evthread_cond_fns.wait_condition)
-               return _evthread_cond_fns.wait_condition(cond, lock, tv);
+       if (evthread_cond_fns_.wait_condition)
+               return evthread_cond_fns_.wait_condition(cond, lock, tv);
        else
                return 0;
 }
 int
-_evthreadimpl_is_lock_debugging_enabled(void)
+evthreadimpl_is_lock_debugging_enabled_(void)
+{
+       return evthread_lock_debugging_enabled_;
+}
+
+int
+evthreadimpl_locking_enabled_(void)
 {
-       return _evthread_lock_debugging_enabled;
+       return evthread_lock_fns_.lock != NULL;
 }
 #endif
 
index b806922a9ce0d0a2110e545ad6fb99d1b8860020..4e11f74970ab633acdb3cf08ddb6330169244988 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -58,17 +58,17 @@ evthread_posix_lock_alloc(unsigned locktype)
 }
 
 static void
-evthread_posix_lock_free(void *_lock, unsigned locktype)
+evthread_posix_lock_free(void *lock_, unsigned locktype)
 {
-       pthread_mutex_t *lock = _lock;
+       pthread_mutex_t *lock = lock_;
        pthread_mutex_destroy(lock);
        mm_free(lock);
 }
 
 static int
-evthread_posix_lock(unsigned mode, void *_lock)
+evthread_posix_lock(unsigned mode, void *lock_)
 {
-       pthread_mutex_t *lock = _lock;
+       pthread_mutex_t *lock = lock_;
        if (mode & EVTHREAD_TRY)
                return pthread_mutex_trylock(lock);
        else
@@ -76,9 +76,9 @@ evthread_posix_lock(unsigned mode, void *_lock)
 }
 
 static int
-evthread_posix_unlock(unsigned mode, void *_lock)
+evthread_posix_unlock(unsigned mode, void *lock_)
 {
-       pthread_mutex_t *lock = _lock;
+       pthread_mutex_t *lock = lock_;
        return pthread_mutex_unlock(lock);
 }
 
@@ -87,13 +87,13 @@ evthread_posix_get_id(void)
 {
        union {
                pthread_t thr;
-#if _EVENT_SIZEOF_PTHREAD_T > _EVENT_SIZEOF_LONG
+#if EVENT__SIZEOF_PTHREAD_T > EVENT__SIZEOF_LONG
                ev_uint64_t id;
 #else
                unsigned long id;
 #endif
        } r;
-#if _EVENT_SIZEOF_PTHREAD_T < _EVENT_SIZEOF_LONG
+#if EVENT__SIZEOF_PTHREAD_T < EVENT__SIZEOF_LONG
        memset(&r, 0, sizeof(r));
 #endif
        r.thr = pthread_self();
@@ -114,17 +114,17 @@ evthread_posix_cond_alloc(unsigned condflags)
 }
 
 static void
-evthread_posix_cond_free(void *_cond)
+evthread_posix_cond_free(void *cond_)
 {
-       pthread_cond_t *cond = _cond;
+       pthread_cond_t *cond = cond_;
        pthread_cond_destroy(cond);
        mm_free(cond);
 }
 
 static int
-evthread_posix_cond_signal(void *_cond, int broadcast)
+evthread_posix_cond_signal(void *cond_, int broadcast)
 {
-       pthread_cond_t *cond = _cond;
+       pthread_cond_t *cond = cond_;
        int r;
        if (broadcast)
                r = pthread_cond_broadcast(cond);
@@ -134,11 +134,11 @@ evthread_posix_cond_signal(void *_cond, int broadcast)
 }
 
 static int
-evthread_posix_cond_wait(void *_cond, void *_lock, const struct timeval *tv)
+evthread_posix_cond_wait(void *cond_, void *lock_, const struct timeval *tv)
 {
        int r;
-       pthread_cond_t *cond = _cond;
-       pthread_mutex_t *lock = _lock;
+       pthread_cond_t *cond = cond_;
+       pthread_mutex_t *lock = lock_;
 
        if (tv) {
                struct timeval now, abstime;
index 2dcd70c2022fcc97be1367fae0fdd1e7426fc745..fb319e77cc0fab6e3498515a6b386cac42042c93 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -43,6 +43,7 @@ struct event_base;
 
 #include "mm-internal.h"
 #include "evthread-internal.h"
+#include "time-internal.h"
 
 #define SPIN_COUNT 2000
 
@@ -60,17 +61,17 @@ evthread_win32_lock_create(unsigned locktype)
 }
 
 static void
-evthread_win32_lock_free(void *_lock, unsigned locktype)
+evthread_win32_lock_free(void *lock_, unsigned locktype)
 {
-       CRITICAL_SECTION *lock = _lock;
+       CRITICAL_SECTION *lock = lock_;
        DeleteCriticalSection(lock);
        mm_free(lock);
 }
 
 static int
-evthread_win32_lock(unsigned mode, void *_lock)
+evthread_win32_lock(unsigned mode, void *lock_)
 {
-       CRITICAL_SECTION *lock = _lock;
+       CRITICAL_SECTION *lock = lock_;
        if ((mode & EVTHREAD_TRY)) {
                return ! TryEnterCriticalSection(lock);
        } else {
@@ -80,9 +81,9 @@ evthread_win32_lock(unsigned mode, void *_lock)
 }
 
 static int
-evthread_win32_unlock(unsigned mode, void *_lock)
+evthread_win32_unlock(unsigned mode, void *lock_)
 {
-       CRITICAL_SECTION *lock = _lock;
+       CRITICAL_SECTION *lock = lock_;
        LeaveCriticalSection(lock);
        return 0;
 }
@@ -134,17 +135,17 @@ evthread_win32_condvar_alloc(unsigned condflags)
 }
 
 static void
-evthread_win32_condvar_free(void *_cond)
+evthread_win32_condvar_free(void *cond_)
 {
-       CONDITION_VARIABLE *cond = _cond;
+       CONDITION_VARIABLE *cond = cond_;
        /* There doesn't _seem_ to be a cleaup fn here... */
        mm_free(cond);
 }
 
 static int
-evthread_win32_condvar_signal(void *_cond, int broadcast)
+evthread_win32_condvar_signal(void *cond, int broadcast)
 {
-       CONDITION_VARIABLE *cond = _cond;
+       CONDITION_VARIABLE *cond = cond_;
        if (broadcast)
                WakeAllConditionVariable_fn(cond);
        else
@@ -153,15 +154,15 @@ evthread_win32_condvar_signal(void *_cond, int broadcast)
 }
 
 static int
-evthread_win32_condvar_wait(void *_cond, void *_lock, const struct timeval *tv)
+evthread_win32_condvar_wait(void *cond_, void *lock_, const struct timeval *tv)
 {
-       CONDITION_VARIABLE *cond = _cond;
-       CRITICAL_SECTION *lock = _lock;
+       CONDITION_VARIABLE *cond = cond_;
+       CRITICAL_SECTION *lock = lock_;
        DWORD ms, err;
        BOOL result;
 
        if (tv)
-               ms = evutil_tv_to_msec(tv);
+               ms = evutil_tv_to_msec_(tv);
        else
                ms = INFINITE;
        result = SleepConditionVariableCS_fn(cond, lock, ms);
@@ -205,18 +206,18 @@ evthread_win32_cond_alloc(unsigned flags)
 }
 
 static void
-evthread_win32_cond_free(void *_cond)
+evthread_win32_cond_free(void *cond_)
 {
-       struct evthread_win32_cond *cond = _cond;
+       struct evthread_win32_cond *cond = cond_;
        DeleteCriticalSection(&cond->lock);
        CloseHandle(cond->event);
        mm_free(cond);
 }
 
 static int
-evthread_win32_cond_signal(void *_cond, int broadcast)
+evthread_win32_cond_signal(void *cond_, int broadcast)
 {
-       struct evthread_win32_cond *cond = _cond;
+       struct evthread_win32_cond *cond = cond_;
        EnterCriticalSection(&cond->lock);
        if (broadcast)
                cond->n_to_wake = cond->n_waiting;
@@ -229,16 +230,16 @@ evthread_win32_cond_signal(void *_cond, int broadcast)
 }
 
 static int
-evthread_win32_cond_wait(void *_cond, void *_lock, const struct timeval *tv)
+evthread_win32_cond_wait(void *cond_, void *lock_, const struct timeval *tv)
 {
-       struct evthread_win32_cond *cond = _cond;
-       CRITICAL_SECTION *lock = _lock;
+       struct evthread_win32_cond *cond = cond_;
+       CRITICAL_SECTION *lock = lock_;
        int generation_at_start;
        int waiting = 1;
        int result = -1;
        DWORD ms = INFINITE, ms_orig = INFINITE, startTime, endTime;
        if (tv)
-               ms_orig = ms = evutil_tv_to_msec(tv);
+               ms_orig = ms = evutil_tv_to_msec_(tv);
 
        EnterCriticalSection(&cond->lock);
        ++cond->n_waiting;
index 4f1c85949d7b0dc66233bfc45c5907b0629584f8..bc4ee99e31d6f643a012ca8040ed7551d8e9f3bf 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #undef WIN32_LEAN_AND_MEAN
 #include <io.h>
 #include <tchar.h>
+#undef _WIN32_WINNT
+/* For structs needed by GetAdaptersAddresses */
+#define _WIN32_WINNT 0x0501
+#include <iphlpapi.h>
 #endif
 
 #include <sys/types.h>
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-#ifdef _EVENT_HAVE_FCNTL_H
+#ifdef EVENT__HAVE_FCNTL_H
 #include <fcntl.h>
 #endif
-#ifdef _EVENT_HAVE_STDLIB_H
+#ifdef EVENT__HAVE_STDLIB_H
 #include <stdlib.h>
 #endif
 #include <errno.h>
 #include <limits.h>
 #include <stdio.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_NETINET_IN_H
+#ifdef EVENT__HAVE_NETINET_IN_H
 #include <netinet/in.h>
 #endif
-#ifdef _EVENT_HAVE_NETINET_IN6_H
+#ifdef EVENT__HAVE_NETINET_IN6_H
 #include <netinet/in6.h>
 #endif
-#ifdef _EVENT_HAVE_ARPA_INET_H
+#ifdef EVENT__HAVE_NETINET_TCP_H
+#include <netinet/tcp.h>
+#endif
+#ifdef EVENT__HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
-
-#ifndef _EVENT_HAVE_GETTIMEOFDAY
-#include <sys/timeb.h>
 #include <time.h>
-#endif
 #include <sys/stat.h>
+#ifdef EVENT__HAVE_IFADDRS_H
+#include <ifaddrs.h>
+#endif
 
 #include "event2/util.h"
 #include "util-internal.h"
 #define close _close
 #define fstat _fstati64
 #define stat _stati64
+#define mode_t int
+#endif
+
+int
+evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
+{
+       int fd;
+
+#ifdef O_CLOEXEC
+       if (flags & O_CREAT)
+               fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
+       else
+               fd = open(pathname, flags|O_CLOEXEC);
+       if (fd >= 0 || errno == EINVAL)
+               return fd;
+       /* If we got an EINVAL, fall through and try without O_CLOEXEC */
 #endif
+       if (flags & O_CREAT)
+               fd = open(pathname, flags, (mode_t)mode);
+       else
+               fd = open(pathname, flags);
+       if (fd < 0)
+               return -1;
+
+#if defined(FD_CLOEXEC)
+       if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
+               return -1;
+#endif
+
+       return fd;
+}
 
 /**
    Read the contents of 'filename' into a newly allocated NUL-terminated
    Used internally only; may go away in a future version.
  */
 int
-evutil_read_file(const char *filename, char **content_out, size_t *len_out,
+evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
     int is_binary)
 {
        int fd, r;
@@ -116,7 +152,7 @@ evutil_read_file(const char *filename, char **content_out, size_t *len_out,
                mode |= O_BINARY;
 #endif
 
-       fd = open(filename, mode);
+       fd = evutil_open_closeonexec_(filename, mode, 0);
        if (fd < 0)
                return -1;
        if (fstat(fd, &st) || st.st_size < 0 ||
@@ -159,12 +195,12 @@ evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
 #ifndef _WIN32
        return socketpair(family, type, protocol, fd);
 #else
-       return evutil_ersatz_socketpair(family, type, protocol, fd);
+       return evutil_ersatz_socketpair_(family, type, protocol, fd);
 #endif
 }
 
 int
-evutil_ersatz_socketpair(int family, int type, int protocol,
+evutil_ersatz_socketpair_(int family, int type, int protocol,
     evutil_socket_t fd[2])
 {
        /* This code is originally from Tor.  Used with permission. */
@@ -292,6 +328,24 @@ evutil_make_socket_nonblocking(evutil_socket_t fd)
        return 0;
 }
 
+/* Faster version of evutil_make_socket_nonblocking for internal use.
+ *
+ * Requires that no F_SETFL flags were previously set on the fd.
+ */
+static int
+evutil_fast_socket_nonblocking(evutil_socket_t fd)
+{
+#ifdef _WIN32
+       return evutil_make_socket_nonblocking(fd);
+#else
+       if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
+               event_warn("fcntl(%d, F_SETFL)", fd);
+               return -1;
+       }
+       return 0;
+#endif
+}
+
 int
 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
 {
@@ -307,10 +361,24 @@ evutil_make_listen_socket_reuseable(evutil_socket_t sock)
 #endif
 }
 
+int
+evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
+{
+#if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
+       int one = 1;
+
+       /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
+        * has arrived and ready to read */ 
+       return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
+               (ev_socklen_t)sizeof(one)); 
+#endif
+       return 0;
+}
+
 int
 evutil_make_socket_closeonexec(evutil_socket_t fd)
 {
-#if !defined(_WIN32) && defined(_EVENT_HAVE_SETFD)
+#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
        int flags;
        if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
                event_warn("fcntl(%d, F_GETFD)", fd);
@@ -324,6 +392,22 @@ evutil_make_socket_closeonexec(evutil_socket_t fd)
        return 0;
 }
 
+/* Faster version of evutil_make_socket_closeonexec for internal use.
+ *
+ * Requires that no F_SETFD flags were previously set on the fd.
+ */
+static int
+evutil_fast_socket_closeonexec(evutil_socket_t fd)
+{
+#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
+       if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
+               event_warn("fcntl(%d, F_SETFD)", fd);
+               return -1;
+       }
+#endif
+       return 0;
+}
+
 int
 evutil_closesocket(evutil_socket_t sock)
 {
@@ -337,9 +421,9 @@ evutil_closesocket(evutil_socket_t sock)
 ev_int64_t
 evutil_strtoll(const char *s, char **endptr, int base)
 {
-#ifdef _EVENT_HAVE_STRTOLL
+#ifdef EVENT__HAVE_STRTOLL
        return (ev_int64_t)strtoll(s, endptr, base);
-#elif _EVENT_SIZEOF_LONG == 8
+#elif EVENT__SIZEOF_LONG == 8
        return (ev_int64_t)strtol(s, endptr, base);
 #elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
        /* XXXX on old versions of MS APIs, we only support base
@@ -359,7 +443,7 @@ evutil_strtoll(const char *s, char **endptr, int base)
        return r;
 #elif defined(_WIN32)
        return (ev_int64_t) _strtoi64(s, endptr, base);
-#elif defined(_EVENT_SIZEOF_LONG_LONG) && _EVENT_SIZEOF_LONG_LONG == 8
+#elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
        long long r;
        int n;
        if (base != 10 && base != 16)
@@ -375,15 +459,15 @@ evutil_strtoll(const char *s, char **endptr, int base)
        }
        if (n != 1)
                return 0;
-       while (EVUTIL_ISSPACE(*s))
+       while (EVUTIL_ISSPACE_(*s))
                ++s;
        if (*s == '-')
                ++s;
        if (base == 10) {
-               while (EVUTIL_ISDIGIT(*s))
+               while (EVUTIL_ISDIGIT_(*s))
                        ++s;
        } else {
-               while (EVUTIL_ISXDIGIT(*s))
+               while (EVUTIL_ISXDIGIT_(*s))
                        ++s;
        }
        if (endptr)
@@ -394,46 +478,6 @@ evutil_strtoll(const char *s, char **endptr, int base)
 #endif
 }
 
-#ifndef _EVENT_HAVE_GETTIMEOFDAY
-/* No gettimeofday; this must be windows. */
-int
-evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
-{
-#ifdef _MSC_VER
-#define U64_LITERAL(n) n##ui64
-#else
-#define U64_LITERAL(n) n##llu
-#endif
-
-       /* Conversion logic taken from Tor, which in turn took it
-        * from Perl.  GetSystemTimeAsFileTime returns its value as
-        * an unaligned (!) 64-bit value containing the number of
-        * 100-nanosecond intervals since 1 January 1601 UTC. */
-#define EPOCH_BIAS U64_LITERAL(116444736000000000)
-#define UNITS_PER_SEC U64_LITERAL(10000000)
-#define USEC_PER_SEC U64_LITERAL(1000000)
-#define UNITS_PER_USEC U64_LITERAL(10)
-       union {
-               FILETIME ft_ft;
-               ev_uint64_t ft_64;
-       } ft;
-
-       if (tv == NULL)
-               return -1;
-
-       GetSystemTimeAsFileTime(&ft.ft_ft);
-
-       if (EVUTIL_UNLIKELY(ft.ft_64 < EPOCH_BIAS)) {
-               /* Time before the unix epoch. */
-               return -1;
-       }
-       ft.ft_64 -= EPOCH_BIAS;
-       tv->tv_sec = (long) (ft.ft_64 / UNITS_PER_SEC);
-       tv->tv_usec = (long) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
-       return 0;
-}
-#endif
-
 #ifdef _WIN32
 int
 evutil_socket_geterror(evutil_socket_t sock)
@@ -454,7 +498,7 @@ evutil_socket_geterror(evutil_socket_t sock)
 /* XXX we should use an enum here. */
 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
 int
-evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
+evutil_socket_connect_(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
 {
        int made_fd = 0;
 
@@ -491,7 +535,7 @@ err:
    error case, set the current socket errno to the error that happened during
    the connect operation. */
 int
-evutil_socket_finished_connecting(evutil_socket_t fd)
+evutil_socket_finished_connecting_(evutil_socket_t fd)
 {
        int e;
        ev_socklen_t elen = sizeof(e);
@@ -534,28 +578,150 @@ static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
  */
 #define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
 
+static void
+evutil_found_ifaddr(const struct sockaddr *sa)
+{
+       const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
+           "\x00\x00\x00\x00\x00\x00\x00\x00";
+
+       if (sa->sa_family == AF_INET) {
+               const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
+               ev_uint32_t addr = ntohl(sin->sin_addr.s_addr);
+               if (addr == 0 ||
+                   EVUTIL_V4ADDR_IS_LOCALHOST(addr) ||
+                   EVUTIL_V4ADDR_IS_CLASSD(addr)) {
+                       /* Not actually a usable external address. */
+               } else {
+                       event_debug(("Detected an IPv4 interface"));
+                       had_ipv4_address = 1;
+               }
+       } else if (sa->sa_family == AF_INET6) {
+               const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+               const unsigned char *addr =
+                   (unsigned char*)sin6->sin6_addr.s6_addr;
+               if (!memcmp(addr, ZEROES, 8) ||
+                   ((addr[0] & 0xfe) == 0xfc) ||
+                   (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
+                   (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
+                   (addr[0] == 0xff)) {
+                       /* This is a reserved, ipv4compat, ipv4map, loopback,
+                        * link-local, multicast, or unspecified address. */
+               } else {
+                       event_debug(("Detected an IPv6 interface"));
+                       had_ipv6_address = 1;
+               }
+       }
+}
+
+#ifdef _WIN32
+typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
+              ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
+#endif
+
+static int
+evutil_check_ifaddrs(void)
+{
+#if defined(EVENT__HAVE_GETIFADDRS)
+       /* Most free Unixy systems provide getifaddrs, which gives us a linked list
+        * of struct ifaddrs. */
+       struct ifaddrs *ifa = NULL;
+       const struct ifaddrs *i;
+       if (getifaddrs(&ifa) < 0) {
+               event_warn("Unable to call getifaddrs()");
+               return -1;
+       }
+
+       for (i = ifa; i; i = i->ifa_next) {
+               if (!i->ifa_addr)
+                       continue;
+               evutil_found_ifaddr(i->ifa_addr);
+       }
+
+       freeifaddrs(ifa);
+       return 0;
+#elif defined(_WIN32)
+       /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
+          "GetAdaptersInfo", but that's deprecated; let's just try
+          GetAdaptersAddresses and fall back to connect+getsockname.
+       */
+       HANDLE lib = evutil_load_windows_system_library_(TEXT("ihplapi.dll"));
+       GetAdaptersAddresses_fn_t fn;
+       ULONG size, res;
+       IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
+       int result = -1;
+
+#define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
+               GAA_FLAG_SKIP_MULTICAST | \
+               GAA_FLAG_SKIP_DNS_SERVER)
+
+       if (!lib)
+               goto done;
+
+       if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
+               goto done;
+
+       /* Guess how much space we need. */
+       size = 15*1024;
+       addresses = mm_malloc(size);
+       if (!addresses)
+               goto done;
+       res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
+       if (res == ERROR_BUFFER_OVERFLOW) {
+               /* we didn't guess that we needed enough space; try again */
+               mm_free(addresses);
+               addresses = mm_malloc(size);
+               if (!addresses)
+                       goto done;
+               res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
+       }
+       if (res != NO_ERROR)
+               goto done;
+
+       for (address = addresses; address; address = address->Next) {
+               IP_ADAPTER_UNICAST_ADDRESS *a;
+               for (a = address->FirstUnicastAddress; a; a = a->Next) {
+                       /* Yes, it's a linked list inside a linked list */
+                       struct sockaddr *sa = a->Address.lpSockaddr;
+                       evutil_found_ifaddr(sa);
+               }
+       }
+
+       result = 0;
+done:
+       if (lib)
+               FreeLibrary(lib);
+       if (addresses)
+               mm_free(addresses);
+       return result;
+#else
+       return -1;
+#endif
+}
+
 /* Test whether we have an ipv4 interface and an ipv6 interface.  Return 0 if
  * the test seemed successful. */
 static int
 evutil_check_interfaces(int force_recheck)
 {
-       const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
-           "\x00\x00\x00\x00\x00\x00\x00\x00";
        evutil_socket_t fd = -1;
        struct sockaddr_in sin, sin_out;
        struct sockaddr_in6 sin6, sin6_out;
        ev_socklen_t sin_out_len = sizeof(sin_out);
        ev_socklen_t sin6_out_len = sizeof(sin6_out);
        int r;
-       char buf[128];
        if (have_checked_interfaces && !force_recheck)
                return 0;
 
-       /* To check whether we have an interface open for a given protocol, we
-        * try to make a UDP 'connection' to a remote host on the internet.
-        * We don't actually use it, so the address doesn't matter, but we
-        * want to pick one that keep us from using a host- or link-local
-        * interface. */
+       if (evutil_check_ifaddrs() == 0) {
+               /* Use a nice sane interface, if this system has one. */
+               return 0;
+       }
+
+       /* Ugh. There was no nice sane interface.  So to check whether we have
+        * an interface open for a given protocol, will try to make a UDP
+        * 'connection' to a remote host on the internet.  We don't actually
+        * use it, so the address doesn't matter, but we want to pick one that
+        * keep us from using a host- or link-local interface. */
        memset(&sin, 0, sizeof(sin));
        sin.sin_family = AF_INET;
        sin.sin_port = htons(53);
@@ -576,21 +742,7 @@ evutil_check_interfaces(int force_recheck)
            connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
            getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
                /* We might have an IPv4 interface. */
-               ev_uint32_t addr = ntohl(sin_out.sin_addr.s_addr);
-               if (addr == 0 ||
-                   EVUTIL_V4ADDR_IS_LOCALHOST(addr) ||
-                   EVUTIL_V4ADDR_IS_CLASSD(addr)) {
-                       evutil_inet_ntop(AF_INET, &sin_out.sin_addr,
-                           buf, sizeof(buf));
-                       /* This is a reserved, ipv4compat, ipv4map, loopback,
-                        * link-local or unspecified address.  The host should
-                        * never have given it to us; it could never connect
-                        * to sin. */
-                       event_warnx("Got a strange local ipv4 address %s",buf);
-               } else {
-                       event_debug(("Detected an IPv4 interface"));
-                       had_ipv4_address = 1;
-               }
+               evutil_found_ifaddr((struct sockaddr*) &sin_out);
        }
        if (fd >= 0)
                evutil_closesocket(fd);
@@ -599,21 +751,7 @@ evutil_check_interfaces(int force_recheck)
            connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
            getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
                /* We might have an IPv6 interface. */
-               const unsigned char *addr =
-                   (unsigned char*)sin6_out.sin6_addr.s6_addr;
-               if (!memcmp(addr, ZEROES, 8) ||
-                   (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80)) {
-                       /* This is a reserved, ipv4compat, ipv4map, loopback,
-                        * link-local or unspecified address.  The host should
-                        * never have given it to us; it could never connect
-                        * to sin6. */
-                       evutil_inet_ntop(AF_INET6, &sin6_out.sin6_addr,
-                           buf, sizeof(buf));
-                       event_warnx("Got a strange local ipv6 address %s",buf);
-               } else {
-                       event_debug(("Detected an IPv4 interface"));
-                       had_ipv6_address = 1;
-               }
+               evutil_found_ifaddr((struct sockaddr*) &sin6_out);
        }
 
        if (fd >= 0)
@@ -634,7 +772,7 @@ evutil_check_interfaces(int force_recheck)
  * allocate both a TCP and a UDP addrinfo.
  */
 struct evutil_addrinfo *
-evutil_new_addrinfo(struct sockaddr *sa, ev_socklen_t socklen,
+evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
     const struct evutil_addrinfo *hints)
 {
        struct evutil_addrinfo *res;
@@ -646,11 +784,11 @@ evutil_new_addrinfo(struct sockaddr *sa, ev_socklen_t socklen,
                struct evutil_addrinfo tmp;
                memcpy(&tmp, hints, sizeof(tmp));
                tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
-               r1 = evutil_new_addrinfo(sa, socklen, &tmp);
+               r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
                if (!r1)
                        return NULL;
                tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
-               r2 = evutil_new_addrinfo(sa, socklen, &tmp);
+               r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
                if (!r2) {
                        evutil_freeaddrinfo(r1);
                        return NULL;
@@ -679,7 +817,7 @@ evutil_new_addrinfo(struct sockaddr *sa, ev_socklen_t socklen,
  * the list.  Either element can be NULL, in which case we return the element
  * that is not NULL. */
 struct evutil_addrinfo *
-evutil_addrinfo_append(struct evutil_addrinfo *first,
+evutil_addrinfo_append_(struct evutil_addrinfo *first,
     struct evutil_addrinfo *append)
 {
        struct evutil_addrinfo *ai = first;
@@ -714,7 +852,7 @@ evutil_parse_servname(const char *servname, const char *protocol,
        int n = parse_numeric_servname(servname);
        if (n>=0)
                return n;
-#if defined(_EVENT_HAVE_GETSERVBYNAME) || defined(_WIN32)
+#if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
        if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
                struct servent *ent = getservbyname(servname, protocol);
                if (ent) {
@@ -742,7 +880,7 @@ evutil_unparse_protoname(int proto)
                return "sctp";
 #endif
        default:
-#ifdef _EVENT_HAVE_GETPROTOBYNUMBER
+#ifdef EVENT__HAVE_GETPROTOBYNUMBER
                {
                        struct protoent *ent = getprotobynumber(proto);
                        if (ent)
@@ -795,7 +933,7 @@ evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
  * set *res as getaddrinfo would.
  */
 int
-evutil_getaddrinfo_common(const char *nodename, const char *servname,
+evutil_getaddrinfo_common_(const char *nodename, const char *servname,
     struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
 {
        int port = 0;
@@ -837,7 +975,7 @@ evutil_getaddrinfo_common(const char *nodename, const char *servname,
                                /* connect to ::1 */
                                sin6.sin6_addr.s6_addr[15] = 1;
                        }
-                       res6 = evutil_new_addrinfo((struct sockaddr*)&sin6,
+                       res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
                            sizeof(sin6), hints);
                        if (!res6)
                                return EVUTIL_EAI_MEMORY;
@@ -854,7 +992,7 @@ evutil_getaddrinfo_common(const char *nodename, const char *servname,
                                /* connect to 127.0.0.1 */
                                sin.sin_addr.s_addr = htonl(0x7f000001);
                        }
-                       res4 = evutil_new_addrinfo((struct sockaddr*)&sin,
+                       res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
                            sizeof(sin), hints);
                        if (!res4) {
                                if (res6)
@@ -862,7 +1000,7 @@ evutil_getaddrinfo_common(const char *nodename, const char *servname,
                                return EVUTIL_EAI_MEMORY;
                        }
                }
-               *res = evutil_addrinfo_append(res4, res6);
+               *res = evutil_addrinfo_append_(res4, res6);
                return 0;
        }
 
@@ -876,7 +1014,7 @@ evutil_getaddrinfo_common(const char *nodename, const char *servname,
                        /* Got an ipv6 address. */
                        sin6.sin6_family = AF_INET6;
                        sin6.sin6_port = htons(port);
-                       *res = evutil_new_addrinfo((struct sockaddr*)&sin6,
+                       *res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
                            sizeof(sin6), hints);
                        if (!*res)
                                return EVUTIL_EAI_MEMORY;
@@ -892,7 +1030,7 @@ evutil_getaddrinfo_common(const char *nodename, const char *servname,
                        /* Got an ipv6 address. */
                        sin.sin_family = AF_INET;
                        sin.sin_port = htons(port);
-                       *res = evutil_new_addrinfo((struct sockaddr*)&sin,
+                       *res = evutil_new_addrinfo_((struct sockaddr*)&sin,
                            sizeof(sin), hints);
                        if (!*res)
                                return EVUTIL_EAI_MEMORY;
@@ -911,7 +1049,7 @@ evutil_getaddrinfo_common(const char *nodename, const char *servname,
        return EVUTIL_EAI_NEED_RESOLVE;
 }
 
-#ifdef _EVENT_HAVE_GETADDRINFO
+#ifdef EVENT__HAVE_GETADDRINFO
 #define USE_NATIVE_GETADDRINFO
 #endif
 
@@ -1010,12 +1148,12 @@ addrinfo_from_hostent(const struct hostent *ent,
 
        for (i = 0; ent->h_addr_list[i]; ++i) {
                memcpy(addrp, ent->h_addr_list[i], ent->h_length);
-               ai = evutil_new_addrinfo(sa, socklen, hints);
+               ai = evutil_new_addrinfo_(sa, socklen, hints);
                if (!ai) {
                        evutil_freeaddrinfo(res);
                        return NULL;
                }
-               res = evutil_addrinfo_append(res, ai);
+               res = evutil_addrinfo_append_(res, ai);
        }
 
        if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
@@ -1035,7 +1173,7 @@ addrinfo_from_hostent(const struct hostent *ent,
  * that we'll only get addresses we could maybe connect to.
  */
 void
-evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints)
+evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
 {
        if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
                return;
@@ -1061,7 +1199,7 @@ static int tested_for_getaddrinfo_hacks=0;
    turns out that the bug is present, then:
 
     - If nodename==NULL and servname is numeric, we build an answer
-      ourselves using evutil_getaddrinfo_common().
+      ourselves using evutil_getaddrinfo_common_().
 
     - If nodename!=NULL and servname is numeric, then we set
       servname=NULL when calling getaddrinfo, and post-process the
@@ -1191,7 +1329,7 @@ evutil_getaddrinfo(const char *nodename, const char *servname,
        /* Not every system has AI_ADDRCONFIG, so fake it. */
        if (hints.ai_family == PF_UNSPEC &&
            (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
-               evutil_adjust_hints_for_addrconfig(&hints);
+               evutil_adjust_hints_for_addrconfig_(&hints);
        }
 #endif
 
@@ -1217,7 +1355,7 @@ evutil_getaddrinfo(const char *nodename, const char *servname,
 #ifdef _WIN32
        {
                int tmp_port;
-               err = evutil_getaddrinfo_common(nodename,servname,&hints,
+               err = evutil_getaddrinfo_common_(nodename,servname,&hints,
                    res, &tmp_port);
                if (err == 0 ||
                    err == EVUTIL_EAI_MEMORY ||
@@ -1233,7 +1371,7 @@ evutil_getaddrinfo(const char *nodename, const char *servname,
            && ((portnum=parse_numeric_servname(servname)) >= 0);
        if (need_np_hack) {
                if (!nodename)
-                       return evutil_getaddrinfo_common(
+                       return evutil_getaddrinfo_common_(
                                NULL,servname,&hints, res, &portnum);
                servname = NULL;
        }
@@ -1278,9 +1416,9 @@ evutil_getaddrinfo(const char *nodename, const char *servname,
                hints.ai_family = PF_UNSPEC;
        }
 
-       evutil_adjust_hints_for_addrconfig(&hints);
+       evutil_adjust_hints_for_addrconfig_(&hints);
 
-       err = evutil_getaddrinfo_common(nodename, servname, &hints, res, &port);
+       err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
        if (err != EVUTIL_EAI_NEED_RESOLVE) {
                /* We either succeeded or failed.  No need to continue */
                return err;
@@ -1289,19 +1427,19 @@ evutil_getaddrinfo(const char *nodename, const char *servname,
        err = 0;
        /* Use any of the various gethostbyname_r variants as available. */
        {
-#ifdef _EVENT_HAVE_GETHOSTBYNAME_R_6_ARG
+#ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
                /* This one is what glibc provides. */
                char buf[2048];
                struct hostent hostent;
                int r;
                r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
                    &err);
-#elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_5_ARG)
+#elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
                char buf[2048];
                struct hostent hostent;
                ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
                    &err);
-#elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_3_ARG)
+#elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
                struct hostent_data data;
                struct hostent hostent;
                memset(&data, 0, sizeof(data));
@@ -1366,7 +1504,7 @@ evutil_getaddrinfo(const char *nodename, const char *servname,
 void
 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
 {
-#ifdef _EVENT_HAVE_GETADDRINFO
+#ifdef EVENT__HAVE_GETADDRINFO
        if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
                freeaddrinfo(ai);
                return;
@@ -1384,7 +1522,7 @@ evutil_freeaddrinfo(struct evutil_addrinfo *ai)
 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
 
 void
-evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn)
+evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
 {
        if (!evdns_getaddrinfo_impl)
                evdns_getaddrinfo_impl = fn;
@@ -1395,7 +1533,7 @@ evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn)
  * way that evdns_getaddrinfo would.
  */
 int
-evutil_getaddrinfo_async(struct evdns_base *dns_base,
+evutil_getaddrinfo_async_(struct evdns_base *dns_base,
     const char *nodename, const char *servname,
     const struct evutil_addrinfo *hints_in,
     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
@@ -1575,7 +1713,7 @@ evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
 const char *
 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
 {
-#if defined(_EVENT_HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
+#if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
        return inet_ntop(af, src, dst, len);
 #else
        if (af == AF_INET) {
@@ -1671,7 +1809,7 @@ evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
 int
 evutil_inet_pton(int af, const char *src, void *dst)
 {
-#if defined(_EVENT_HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
+#if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
        return inet_pton(af, src, dst);
 #else
        if (af == AF_INET) {
@@ -1700,7 +1838,7 @@ evutil_inet_pton(int af, const char *src, void *dst)
                else {
                        int byte1,byte2,byte3,byte4;
                        char more;
-                       for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT(*eow); --eow)
+                       for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
                                ;
                        ++eow;
 
@@ -1725,7 +1863,7 @@ evutil_inet_pton(int af, const char *src, void *dst)
                while (src < eow) {
                        if (i > 7)
                                return 0;
-                       if (EVUTIL_ISXDIGIT(*src)) {
+                       if (EVUTIL_ISXDIGIT_(*src)) {
                                char *next;
                                long r = strtol(src, &next, 16);
                                if (next > 4+src)
@@ -1848,7 +1986,7 @@ evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *
        {
                struct sockaddr_in6 sin6;
                memset(&sin6, 0, sizeof(sin6));
-#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
                sin6.sin6_len = sizeof(sin6);
 #endif
                sin6.sin6_family = AF_INET6;
@@ -1867,7 +2005,7 @@ evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *
        {
                struct sockaddr_in sin;
                memset(&sin, 0, sizeof(sin));
-#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
                sin.sin_len = sizeof(sin);
 #endif
                sin.sin_family = AF_INET;
@@ -1884,7 +2022,7 @@ evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *
 }
 
 const char *
-evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen)
+evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
 {
        char b[128];
        const char *res=NULL;
@@ -2008,7 +2146,7 @@ static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
 };
 
 #define IMPL_CTYPE_FN(name)                                            \
-       int EVUTIL_##name(char c) {                                     \
+       int EVUTIL_##name##_(char c) {                                  \
                ev_uint8_t u = c;                                       \
                return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
        }
@@ -2021,11 +2159,11 @@ IMPL_CTYPE_FN(ISPRINT)
 IMPL_CTYPE_FN(ISLOWER)
 IMPL_CTYPE_FN(ISUPPER)
 
-char EVUTIL_TOLOWER(char c)
+char EVUTIL_TOLOWER_(char c)
 {
        return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
 }
-char EVUTIL_TOUPPER(char c)
+char EVUTIL_TOUPPER_(char c)
 {
        return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
 }
@@ -2034,8 +2172,8 @@ evutil_ascii_strcasecmp(const char *s1, const char *s2)
 {
        char c1, c2;
        while (1) {
-               c1 = EVUTIL_TOLOWER(*s1++);
-               c2 = EVUTIL_TOLOWER(*s2++);
+               c1 = EVUTIL_TOLOWER_(*s1++);
+               c2 = EVUTIL_TOLOWER_(*s2++);
                if (c1 < c2)
                        return -1;
                else if (c1 > c2)
@@ -2048,8 +2186,8 @@ int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
 {
        char c1, c2;
        while (n--) {
-               c1 = EVUTIL_TOLOWER(*s1++);
-               c2 = EVUTIL_TOLOWER(*s2++);
+               c1 = EVUTIL_TOLOWER_(*s1++);
+               c2 = EVUTIL_TOLOWER_(*s2++);
                if (c1 < c2)
                        return -1;
                else if (c1 > c2)
@@ -2063,15 +2201,15 @@ int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
 static int
 evutil_issetugid(void)
 {
-#ifdef _EVENT_HAVE_ISSETUGID
+#ifdef EVENT__HAVE_ISSETUGID
        return issetugid();
 #else
 
-#ifdef _EVENT_HAVE_GETEUID
+#ifdef EVENT__HAVE_GETEUID
        if (getuid() != geteuid())
                return 1;
 #endif
-#ifdef _EVENT_HAVE_GETEGID
+#ifdef EVENT__HAVE_GETEGID
        if (getgid() != getegid())
                return 1;
 #endif
@@ -2080,7 +2218,7 @@ evutil_issetugid(void)
 }
 
 const char *
-evutil_getenv(const char *varname)
+evutil_getenv_(const char *varname)
 {
        if (evutil_issetugid())
                return NULL;
@@ -2088,18 +2226,56 @@ evutil_getenv(const char *varname)
        return getenv(varname);
 }
 
-long
-_evutil_weakrand(void)
+ev_uint32_t
+evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
 {
+       if (seed == 0) {
+               struct timeval tv;
+               evutil_gettimeofday(&tv, NULL);
+               seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
 #ifdef _WIN32
-       return rand();
+               seed += (ev_uint32_t) _getpid();
 #else
-       return random();
+               seed += (ev_uint32_t) getpid();
 #endif
+       }
+       state->seed = seed;
+       return seed;
+}
+
+ev_int32_t
+evutil_weakrand_(struct evutil_weakrand_state *state)
+{
+       /* This RNG implementation is a linear congruential generator, with
+        * modulus 2^31, multiplier 1103515245, and addend 12345.  It's also
+        * used by OpenBSD, and by Glibc's TYPE_0 RNG.
+        *
+        * The linear congruential generator is not an industrial-strength
+        * RNG!  It's fast, but it can have higher-order patterns.  Notably,
+        * the low bits tend to have periodicity.
+        */
+       state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
+       return (ev_int32_t)(state->seed);
+}
+
+ev_int32_t
+evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
+{
+       ev_int32_t divisor, result;
+
+       /* We can't just do weakrand() % top, since the low bits of the LCG
+        * are less random than the high ones.  (Specifically, since the LCG
+        * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
+        * therefore the low m bits of the LCG will have period 2^m.) */
+       divisor = EVUTIL_WEAKRAND_MAX / top;
+       do {
+               result = evutil_weakrand_(state) / divisor;
+       } while (result >= top);
+       return result;
 }
 
 int
-evutil_sockaddr_is_loopback(const struct sockaddr *addr)
+evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
 {
        static const char LOOPBACK_S6[16] =
            "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
@@ -2113,20 +2289,8 @@ evutil_sockaddr_is_loopback(const struct sockaddr *addr)
        return 0;
 }
 
-#define MAX_SECONDS_IN_MSEC_LONG \
-       (((LONG_MAX) - 999) / 1000)
-
-long
-evutil_tv_to_msec(const struct timeval *tv)
-{
-       if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
-               return -1;
-
-       return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
-}
-
 int
-evutil_hex_char_to_int(char c)
+evutil_hex_char_to_int_(char c)
 {
        switch(c)
        {
@@ -2152,7 +2316,7 @@ evutil_hex_char_to_int(char c)
 
 #ifdef _WIN32
 HANDLE
-evutil_load_windows_system_library(const TCHAR *library_name)
+evutil_load_windows_system_library_(const TCHAR *library_name)
 {
   TCHAR path[MAX_PATH];
   unsigned n;
@@ -2165,3 +2329,182 @@ evutil_load_windows_system_library(const TCHAR *library_name)
 }
 #endif
 
+/* Internal wrapper around 'socket' to provide Linux-style support for
+ * syscall-saving methods where available.
+ *
+ * In addition to regular socket behavior, you can use a bitwise or to set the
+ * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
+ * to make the socket nonblocking or close-on-exec with as few syscalls as
+ * possible.
+ */
+evutil_socket_t
+evutil_socket_(int domain, int type, int protocol)
+{
+       evutil_socket_t r;
+#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
+       r = socket(domain, type, protocol);
+       if (r >= 0)
+               return r;
+       else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
+               return -1;
+#endif
+#define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
+       r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
+       if (r < 0)
+               return -1;
+       if (type & EVUTIL_SOCK_NONBLOCK) {
+               if (evutil_fast_socket_nonblocking(r) < 0) {
+                       evutil_closesocket(r);
+                       return -1;
+               }
+       }
+       if (type & EVUTIL_SOCK_CLOEXEC) {
+               if (evutil_fast_socket_closeonexec(r) < 0) {
+                       evutil_closesocket(r);
+                       return -1;
+               }
+       }
+       return r;
+}
+
+/* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
+ * support for syscall-saving methods where available.
+ *
+ * In addition to regular accept behavior, you can set one or more of flags
+ * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
+ * make the socket nonblocking or close-on-exec with as few syscalls as
+ * possible.
+ */
+evutil_socket_t
+evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
+    ev_socklen_t *addrlen, int flags)
+{
+       evutil_socket_t result;
+#if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
+       result = accept4(sockfd, addr, addrlen, flags);
+       if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
+               /* A nonnegative result means that we succeeded, so return.
+                * Failing with EINVAL means that an option wasn't supported,
+                * and failing with ENOSYS means that the syscall wasn't
+                * there: in those cases we want to fall back.  Otherwise, we
+                * got a real error, and we should return. */
+               return result;
+       }
+#endif
+       result = accept(sockfd, addr, addrlen);
+       if (result < 0)
+               return result;
+
+       if (flags & EVUTIL_SOCK_CLOEXEC) {
+               if (evutil_fast_socket_closeonexec(result) < 0) {
+                       evutil_closesocket(result);
+                       return -1;
+               }
+       }
+       if (flags & EVUTIL_SOCK_NONBLOCK) {
+               if (evutil_fast_socket_nonblocking(result) < 0) {
+                       evutil_closesocket(result);
+                       return -1;
+               }
+       }
+       return result;
+}
+
+/* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
+ * fd[0] get read from fd[1].  Make both fds nonblocking and close-on-exec.
+ * Return 0 on success, -1 on failure.
+ */
+int
+evutil_make_internal_pipe_(evutil_socket_t fd[2])
+{
+       /*
+         Making the second socket nonblocking is a bit subtle, given that we
+         ignore any EAGAIN returns when writing to it, and you don't usally
+         do that for a nonblocking socket. But if the kernel gives us EAGAIN,
+         then there's no need to add any more data to the buffer, since
+         the main thread is already either about to wake up and drain it,
+         or woken up and in the process of draining it.
+       */
+
+#if defined(EVENT__HAVE_PIPE2)
+       if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
+               return 0;
+#endif
+#if defined(EVENT__HAVE_PIPE)
+       if (pipe(fd) == 0) {
+               if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
+                   evutil_fast_socket_nonblocking(fd[1]) < 0 ||
+                   evutil_fast_socket_closeonexec(fd[0]) < 0 ||
+                   evutil_fast_socket_closeonexec(fd[1]) < 0) {
+                       close(fd[0]);
+                       close(fd[1]);
+                       fd[0] = fd[1] = -1;
+                       return -1;
+               }
+               return 0;
+       } else {
+               event_warn("%s: pipe", __func__);
+       }
+#endif
+
+#ifdef _WIN32
+#define LOCAL_SOCKETPAIR_AF AF_INET
+#else
+#define LOCAL_SOCKETPAIR_AF AF_UNIX
+#endif
+       if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
+               if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
+                   evutil_fast_socket_nonblocking(fd[1]) < 0 ||
+                   evutil_fast_socket_closeonexec(fd[0]) < 0 ||
+                   evutil_fast_socket_closeonexec(fd[1]) < 0) {
+                       evutil_closesocket(fd[0]);
+                       evutil_closesocket(fd[1]);
+                       fd[0] = fd[1] = -1;
+                       return -1;
+               }
+               return 0;
+       }
+       fd[0] = fd[1] = -1;
+       return -1;
+}
+
+/* Wrapper around eventfd on systems that provide it.  Unlike the system
+ * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
+ * flags.  Returns -1 on error or if eventfd is not supported.
+ */
+evutil_socket_t
+evutil_eventfd_(unsigned initval, int flags)
+{
+#if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
+       int r;
+#if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
+       r = eventfd(initval, flags);
+       if (r >= 0 || flags == 0)
+               return r;
+#endif
+       r = eventfd(initval, 0);
+       if (r < 0)
+               return r;
+       if (flags & EVUTIL_EFD_CLOEXEC) {
+               if (evutil_fast_socket_closeonexec(r) < 0) {
+                       evutil_closesocket(r);
+                       return -1;
+               }
+       }
+       if (flags & EVUTIL_EFD_NONBLOCK) {
+               if (evutil_fast_socket_nonblocking(r) < 0) {
+                       evutil_closesocket(r);
+                       return -1;
+               }
+       }
+       return r;
+#else
+       return -1;
+#endif
+}
+
+void
+evutil_free_globals_(void)
+{
+       evutil_free_secure_rng_globals_();
+}
index 610158681daf05140a11d58793d3ea2b2dd757b3..dd31a8df5cc987f3d4c925c3529490ab0f737839 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -40,7 +40,7 @@
 #include "util-internal.h"
 #include "evthread-internal.h"
 
-#ifdef _EVENT_HAVE_ARC4RANDOM
+#ifdef EVENT__HAVE_ARC4RANDOM
 #include <stdlib.h>
 #include <string.h>
 int
@@ -50,19 +50,37 @@ evutil_secure_rng_init(void)
        (void) arc4random();
        return 0;
 }
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
 int
 evutil_secure_rng_global_setup_locks_(const int enable_locks)
 {
        return 0;
 }
+#endif
+static void
+evutil_free_secure_rng_globals_locks(void)
+{
+}
 
 static void
 ev_arc4random_buf(void *buf, size_t n)
 {
-#ifdef _EVENT_HAVE_ARC4RANDOM_BUF
+       unsigned char *b = buf;
+#if defined(EVENT__HAVE_ARC4RANDOM_BUF) && !defined(__APPLE__)
        return arc4random_buf(buf, n);
 #else
-       unsigned char *b = buf;
+
+#if defined(EVENT__HAVE_ARC4RANDOM_BUF)
+       /* OSX 10.7 introducd arc4random_buf, so if you build your program
+        * there, you'll get surprised when older versions of OSX fail to run.
+        * To solve this, we can check whether the function pointer is set,
+        * and fall back otherwise.  (OSX does this using some linker
+        * trickery.)
+        */
+       if (arc4random_buf != NULL) {
+               return arc4random_buf(buf, n);
+       }
+#endif
        /* Make sure that we start out with b at a 4-byte alignment; plenty
         * of CPUs care about this for 32-bit access. */
        if (n >= 4 && ((ev_uintptr_t)b) & 3) {
@@ -84,15 +102,15 @@ ev_arc4random_buf(void *buf, size_t n)
 #endif
 }
 
-#else /* !_EVENT_HAVE_ARC4RANDOM { */
+#else /* !EVENT__HAVE_ARC4RANDOM { */
 
-#ifdef _EVENT_ssize_t
-#define ssize_t _EVENT_SSIZE_t
+#ifdef EVENT__ssize_t
+#define ssize_t EVENT__ssize_t
 #endif
 #define ARC4RANDOM_EXPORT static
-#define _ARC4_LOCK() EVLOCK_LOCK(arc4rand_lock, 0)
-#define _ARC4_UNLOCK() EVLOCK_UNLOCK(arc4rand_lock, 0)
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#define ARC4_LOCK_() EVLOCK_LOCK(arc4rand_lock, 0)
+#define ARC4_UNLOCK_() EVLOCK_UNLOCK(arc4rand_lock, 0)
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
 static void *arc4rand_lock;
 #endif
 
@@ -103,7 +121,7 @@ static void *arc4rand_lock;
 
 #include "./arc4random.c"
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
 int
 evutil_secure_rng_global_setup_locks_(const int enable_locks)
 {
@@ -112,16 +130,28 @@ evutil_secure_rng_global_setup_locks_(const int enable_locks)
 }
 #endif
 
+static void
+evutil_free_secure_rng_globals_locks(void)
+{
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+       if (arc4rand_lock != NULL) {
+               EVTHREAD_FREE_LOCK(arc4rand_lock, 0);
+               arc4rand_lock = NULL;
+       }
+#endif
+       return;
+}
+
 int
 evutil_secure_rng_init(void)
 {
        int val;
 
-       _ARC4_LOCK();
+       ARC4_LOCK_();
        if (!arc4_seeded_ok)
                arc4_stir();
        val = arc4_seeded_ok ? 0 : -1;
-       _ARC4_UNLOCK();
+       ARC4_UNLOCK_();
        return val;
 }
 
@@ -131,7 +161,7 @@ ev_arc4random_buf(void *buf, size_t n)
        arc4random_buf(buf, n);
 }
 
-#endif /* } !_EVENT_HAVE_ARC4RANDOM */
+#endif /* } !EVENT__HAVE_ARC4RANDOM */
 
 void
 evutil_secure_rng_get_bytes(void *buf, size_t n)
@@ -146,3 +176,8 @@ evutil_secure_rng_add_bytes(const char *buf, size_t n)
            n>(size_t)INT_MAX ? INT_MAX : (int)n);
 }
 
+void
+evutil_free_secure_rng_globals_(void)
+{
+    evutil_free_secure_rng_globals_locks();
+}
diff --git a/sntp/libevent/evutil_time.c b/sntp/libevent/evutil_time.c
new file mode 100644 (file)
index 0000000..7b2043b
--- /dev/null
@@ -0,0 +1,485 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+
+#include <sys/types.h>
+#ifdef EVENT__HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#include <errno.h>
+#include <limits.h>
+#ifndef EVENT__HAVE_GETTIMEOFDAY
+#include <sys/timeb.h>
+#endif
+#if !defined(EVENT__HAVE_NANOSLEEP) && !defined(EVENT_HAVE_USLEEP) && \
+       !defined(_WIN32)
+#include <sys/select.h>
+#endif
+#include <time.h>
+#include <sys/stat.h>
+#include <string.h>
+
+#include "event2/util.h"
+#include "util-internal.h"
+#include "log-internal.h"
+
+#ifndef EVENT__HAVE_GETTIMEOFDAY
+/* No gettimeofday; this must be windows. */
+int
+evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+#ifdef _MSC_VER
+#define U64_LITERAL(n) n##ui64
+#else
+#define U64_LITERAL(n) n##llu
+#endif
+
+       /* Conversion logic taken from Tor, which in turn took it
+        * from Perl.  GetSystemTimeAsFileTime returns its value as
+        * an unaligned (!) 64-bit value containing the number of
+        * 100-nanosecond intervals since 1 January 1601 UTC. */
+#define EPOCH_BIAS U64_LITERAL(116444736000000000)
+#define UNITS_PER_SEC U64_LITERAL(10000000)
+#define USEC_PER_SEC U64_LITERAL(1000000)
+#define UNITS_PER_USEC U64_LITERAL(10)
+       union {
+               FILETIME ft_ft;
+               ev_uint64_t ft_64;
+       } ft;
+
+       if (tv == NULL)
+               return -1;
+
+       GetSystemTimeAsFileTime(&ft.ft_ft);
+
+       if (EVUTIL_UNLIKELY(ft.ft_64 < EPOCH_BIAS)) {
+               /* Time before the unix epoch. */
+               return -1;
+       }
+       ft.ft_64 -= EPOCH_BIAS;
+       tv->tv_sec = (long) (ft.ft_64 / UNITS_PER_SEC);
+       tv->tv_usec = (long) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
+       return 0;
+}
+#endif
+
+#define MAX_SECONDS_IN_MSEC_LONG \
+       (((LONG_MAX) - 999) / 1000)
+
+long
+evutil_tv_to_msec_(const struct timeval *tv)
+{
+       if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
+               return -1;
+
+       return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
+}
+
+/*
+  Replacement for usleep on platforms that don't have one.  Not guaranteed to
+  be any more finegrained than 1 msec.
+ */
+void
+evutil_usleep_(const struct timeval *tv)
+{
+       if (!tv)
+               return;
+#if defined(_WIN32)
+       {
+               long msec = evutil_tv_to_msec_(tv);
+               Sleep((DWORD)msec);
+       }
+#elif defined(EVENT__HAVE_NANOSLEEP)
+       {
+               struct timespec ts;
+               ts.tv_sec = tv->tv_sec;
+               ts.tv_nsec = tv->tv_usec*1000;
+               nanosleep(&ts, NULL);
+       }
+#elif defined(EVENT__HAVE_USLEEP)
+       /* Some systems don't like to usleep more than 999999 usec */
+       sleep(tv->tv_sec);
+       usleep(tv->tv_usec);
+#else
+       select(0, NULL, NULL, NULL, tv);
+#endif
+}
+
+/*
+   This function assumes it's called repeatedly with a
+   not-actually-so-monotonic time source whose outputs are in 'tv'. It
+   implements a trivial ratcheting mechanism so that the values never go
+   backwards.
+ */
+static void
+adjust_monotonic_time(struct evutil_monotonic_timer *base,
+    struct timeval *tv)
+{
+       evutil_timeradd(tv, &base->adjust_monotonic_clock, tv);
+
+       if (evutil_timercmp(tv, &base->last_time, <)) {
+               /* Guess it wasn't monotonic after all. */
+               struct timeval adjust;
+               evutil_timersub(&base->last_time, tv, &adjust);
+               evutil_timeradd(&adjust, &base->adjust_monotonic_clock,
+                   &base->adjust_monotonic_clock);
+               *tv = base->last_time;
+       }
+       base->last_time = *tv;
+}
+
+#if defined(HAVE_POSIX_MONOTONIC)
+/* =====
+   The POSIX clock_gettime() interface provides a few ways to get at a
+   monotonic clock.  CLOCK_MONOTONIC is most widely supported.  Linux also
+   provides a CLOCK_MONOTONIC_COARSE with accuracy of about 1-4 msec.
+
+   On all platforms I'm aware of, CLOCK_MONOTONIC really is monotonic.
+   Platforms don't agree about whether it should jump on a sleep/resume.
+ */
+
+int
+evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
+    int flags)
+{
+       /* CLOCK_MONOTONIC exists on FreeBSD, Linux, and Solaris.  You need to
+        * check for it at runtime, because some older kernel versions won't
+        * have it working. */
+       const int precise = flags & EV_MONOT_PRECISE;
+       const int fallback = flags & EV_MONOT_FALLBACK;
+       struct timespec ts;
+
+#ifdef CLOCK_MONOTONIC_COARSE
+#if CLOCK_MONOTONIC_COARSE < 0
+       /* Technically speaking, nothing keeps CLOCK_* from being negative (as
+        * far as I know). This check and the one below make sure that it's
+        * safe for us to use -1 as an "unset" value. */
+#error "I didn't expect CLOCK_MONOTONIC_COARSE to be < 0"
+#endif
+       if (! precise && ! fallback) {
+               if (clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) == 0) {
+                       base->monotonic_clock = CLOCK_MONOTONIC_COARSE;
+                       return 0;
+               }
+       }
+#endif
+       if (!fallback && clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
+               base->monotonic_clock = CLOCK_MONOTONIC;
+               return 0;
+       }
+
+#if CLOCK_MONOTONIC < 0
+#error "I didn't expect CLOCK_MONOTONIC to be < 0"
+#endif
+
+       base->monotonic_clock = -1;
+       return 0;
+}
+
+int
+evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
+    struct timeval *tp)
+{
+       struct timespec ts;
+
+       if (base->monotonic_clock < 0) {
+               if (evutil_gettimeofday(tp, NULL) < 0)
+                       return -1;
+               adjust_monotonic_time(base, tp);
+               return 0;
+       }
+
+       if (clock_gettime(base->monotonic_clock, &ts) == -1)
+               return -1;
+       tp->tv_sec = ts.tv_sec;
+       tp->tv_usec = ts.tv_nsec / 1000;
+
+       return 0;
+}
+#endif
+
+#if defined(HAVE_MACH_MONOTONIC)
+/* ======
+   Apple is a little late to the POSIX party.  And why not?  Instead of
+   clock_gettime(), they provide mach_absolute_time().  Its units are not
+   fixed; we need to use mach_timebase_info() to get the right functions to
+   convert its units into nanoseconds.
+
+   To all appearances, mach_absolute_time() seems to be honest-to-goodness
+   monotonic.  Whether it stops during sleep or not is unspecified in
+   principle, and dependent on CPU architecture in practice.
+ */
+
+int
+evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
+    int flags)
+{
+       const int fallback = flags & EV_MONOT_FALLBACK;
+       struct mach_timebase_info mi;
+       memset(base, 0, sizeof(*base));
+       /* OSX has mach_absolute_time() */
+       if (!fallback &&
+           mach_timebase_info(&mi) == 0 &&
+           mach_absolute_time() != 0) {
+               /* mach_timebase_info tells us how to convert
+                * mach_absolute_time() into nanoseconds, but we
+                * want to use microseconds instead. */
+               mi.denom *= 1000;
+               memcpy(&base->mach_timebase_units, &mi, sizeof(mi));
+       } else {
+               base->mach_timebase_units.numer = 0;
+       }
+       return 0;
+}
+
+int
+evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
+    struct timeval *tp)
+{
+       ev_uint64_t abstime, usec;
+       if (base->mach_timebase_units.numer == 0) {
+               if (evutil_gettimeofday(tp, NULL) < 0)
+                       return -1;
+               adjust_monotonic_time(base, tp);
+               return 0;
+       }
+
+       abstime = mach_absolute_time();
+       usec = (abstime * base->mach_timebase_units.numer)
+           / (base->mach_timebase_units.denom);
+       tp->tv_sec = usec / 1000000;
+       tp->tv_usec = usec % 1000000;
+
+       return 0;
+}
+#endif
+
+#if defined(HAVE_WIN32_MONOTONIC)
+/* =====
+   Turn we now to Windows.  Want monontonic time on Windows?
+
+   Windows has QueryPerformanceCounter(), which gives time most high-
+   resolution time.  It's a pity it's not so monotonic in practice; it's
+   also got some fun bugs, especially: with older Windowses, under
+   virtualizations, with funny hardware, on multiprocessor systems, and so
+   on.  PEP418 [1] has a nice roundup of the issues here.
+
+   There's GetTickCount64() on Vista and later, which gives a number of 1-msec
+   ticks since startup.  The accuracy here might be as bad as 10-20 msec, I
+   hear.  There's an undocumented function (NtSetTimerResolution) that
+   allegedly increases the accuracy. Good luck!
+
+   There's also GetTickCount(), which is only 32 bits, but seems to be
+   supported on pre-Vista versions of Windows.  Apparently, you can coax
+   another 14 bits out of it, giving you 2231 years before rollover.
+
+   The less said about timeGetTime() the better.
+
+   "We don't care.  We don't have to.  We're the Phone Company."
+            -- Lily Tomlin, SNL
+
+   Our strategy, if precise timers are turned off, is to just use the best
+   GetTickCount equivalent available.  If we've been asked for precise timing,
+   then we mostly[2] assume that GetTickCount is monotonic, and correct
+   GetPerformanceCounter to approximate it.
+
+   [1] http://www.python.org/dev/peps/pep-0418
+   [2] Of course, we feed the Windows stuff into adjust_monotonic_time()
+       anyway, just in case it isn't.
+
+ */
+/*
+    Parts of our logic in the win32 timer code here are closely based on
+    BitTorrent's libUTP library.  That code is subject to the following
+    license:
+
+      Copyright (c) 2010 BitTorrent, Inc.
+
+      Permission is hereby granted, free of charge, to any person obtaining a
+      copy of this software and associated documentation files (the
+      "Software"), to deal in the Software without restriction, including
+      without limitation the rights to use, copy, modify, merge, publish,
+      distribute, sublicense, and/or sell copies of the Software, and to
+      permit persons to whom the Software is furnished to do so, subject to
+      the following conditions:
+
+      The above copyright notice and this permission notice shall be included
+      in all copies or substantial portions of the Software.
+
+      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+      OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+      MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+      NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+      LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+      OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+      WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+static ev_uint64_t
+evutil_GetTickCount_(struct evutil_monotonic_timer *base)
+{
+       if (base->GetTickCount64_fn) {
+               /* Let's just use GetTickCount64 if we can. */
+               return base->GetTickCount64_fn();
+       } else if (base->GetTickCount_fn) {
+               /* Greg Hazel assures me that this works, that BitTorrent has
+                * done it for years, and this it won't turn around and
+                * bite us.  He says they found it on some game programmers'
+                * forum some time around 2007.
+                */
+               ev_uint64_t v = base->GetTickCount_fn();
+               return (DWORD)v | ((v >> 18) & 0xFFFFFFFF00000000);
+       } else {
+               /* Here's the fallback implementation. We have to use
+                * GetTickCount() with its given signature, so we only get
+                * 32 bits worth of milliseconds, which will roll ove every
+                * 49 days or so.  */
+               DWORD ticks = GetTickCount();
+               if (ticks < base->last_tick_count) {
+                       base->adjust_tick_count += ((ev_uint64_t)1) << 32;
+               }
+               base->last_tick_count = ticks;
+               return ticks + base->adjust_tick_count;
+       }
+}
+
+int
+evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
+    int flags)
+{
+       const int precise = flags & EV_MONOT_PRECISE;
+       const int fallback = flags & EV_MONOT_FALLBACK;
+       HANDLE h;
+       memset(base, 0, sizeof(*base));
+
+       h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
+       if (h != NULL && !fallback) {
+               base->GetTickCount64_fn = (ev_GetTickCount_func)GetProcAddress(h, "GetTickCount64");
+               base->GetTickCount_fn = (ev_GetTickCount_func)GetProcAddress(h, "GetTickCount");
+       }
+
+       base->first_tick = base->last_tick_count = evutil_GetTickCount_(base);
+       if (precise && !fallback) {
+               LARGE_INTEGER freq;
+               if (QueryPerformanceFrequency(&freq)) {
+                       LARGE_INTEGER counter;
+                       QueryPerformanceCounter(&counter);
+                       base->first_counter = counter.QuadPart;
+                       base->usec_per_count = 1.0e6 / freq.QuadPart;
+                       base->use_performance_counter = 1;
+               }
+       }
+
+       return 0;
+}
+
+static inline ev_int64_t
+abs64(ev_int64_t i)
+{
+       return i < 0 ? -i : i;
+}
+
+
+int
+evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
+    struct timeval *tp)
+{
+       ev_uint64_t ticks = evutil_GetTickCount_(base);
+       if (base->use_performance_counter) {
+               /* Here's a trick we took from BitTorrent's libutp, at Greg
+                * Hazel's recommendation.  We use QueryPerformanceCounter for
+                * our high-resolution timer, but use GetTickCount*() to keep
+                * it sane, and adjust_monotonic_time() to keep it monotonic.
+                */
+               LARGE_INTEGER counter;
+               ev_int64_t counter_elapsed, counter_usec_elapsed, ticks_elapsed;
+               QueryPerformanceCounter(&counter);
+               counter_elapsed = (ev_int64_t)
+                   (counter.QuadPart - base->first_counter);
+               ticks_elapsed = ticks - base->first_tick;
+               /* TODO: This may upset VC6. If you need this to work with
+                * VC6, please supply an appropriate patch. */
+               counter_usec_elapsed = (ev_int64_t)
+                   (counter_elapsed * base->usec_per_count);
+
+               if (abs64(ticks_elapsed*1000 - counter_usec_elapsed) > 1000000) {
+                       /* It appears that the QueryPerformanceCounter()
+                        * result is more than 1 second away from
+                        * GetTickCount() result. Let's adjust it to be as
+                        * accurate as we can; adjust_monotnonic_time() below
+                        * will keep it monotonic. */
+                       counter_usec_elapsed = ticks_elapsed * 1000;
+                       base->first_counter = counter.QuadPart - counter_usec_elapsed / base->usec_per_count;
+               }
+               tp->tv_sec = counter_usec_elapsed / 1000000;
+               tp->tv_usec = counter_usec_elapsed % 1000000;
+
+       } else {
+               /* We're just using GetTickCount(). */
+               tp->tv_sec = ticks / 1000;
+               tp->tv_usec = (ticks % 1000) * 1000;
+       }
+       adjust_monotonic_time(base, tp);
+
+       return 0;
+}
+#endif
+
+#if defined(HAVE_FALLBACK_MONOTONIC)
+/* =====
+   And if none of the other options work, let's just use gettimeofday(), and
+   ratchet it forward so that it acts like a monotonic timer, whether it
+   wants to or not.
+ */
+
+int
+evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
+    int precise)
+{
+       memset(base, 0, sizeof(*base));
+       return 0;
+}
+
+int
+evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
+    struct timeval *tp)
+{
+       if (evutil_gettimeofday(tp, NULL) < 0)
+               return -1;
+       adjust_monotonic_time(base, tp);
+       return 0;
+
+}
+#endif
index d20e14df82a52c453e5de535d85c4d17529846d8..8842f4cd75b24706ca4293384710e332f202bba2 100644 (file)
@@ -1,12 +1,12 @@
-/* Based on work Copyright 2002 Christopher Clark */
-/* Copyright 2005-2010 Nick Mathewson */
-/* Copyright 2009-2010 Niels Provos and Nick Mathewson */
+/* Copyright 2002 Christopher Clark */
+/* Copyright 2005-2012 Nick Mathewson */
+/* Copyright 2009-2012 Niels Provos and Nick Mathewson */
 /* See license at end. */
 
 /* Based on ideas by Christopher Clark and interfaces from Niels Provos. */
 
-#ifndef _EVENT_HT_H
-#define _EVENT_HT_H
+#ifndef HT_INTERNAL_H_INCLUDED_
+#define HT_INTERNAL_H_INCLUDED_
 
 #define HT_HEAD(name, type)                                             \
   struct name {                                                         \
 #define HT_INITIALIZER()                        \
   { NULL, 0, 0, 0, -1 }
 
-#ifdef HT_CACHE_HASH_VALUES
+#ifdef HT_NO_CACHE_HASH_VALUES
 #define HT_ENTRY(type)                          \
   struct {                                      \
     struct type *hte_next;                      \
-    unsigned hte_hash;                          \
   }
 #else
 #define HT_ENTRY(type)                          \
   struct {                                      \
     struct type *hte_next;                      \
+    unsigned hte_hash;                          \
   }
 #endif
 
 #define HT_SIZE(head)                           \
   ((head)->hth_n_entries)
 
+/* Return memory usage for a hashtable (not counting the entries themselves) */
+#define HT_MEM_USAGE(head)                         \
+  (sizeof(*head) + (head)->hth_table_length * sizeof(void*))
+
 #define HT_FIND(name, head, elm)     name##_HT_FIND((head), (elm))
 #define HT_INSERT(name, head, elm)   name##_HT_INSERT((head), (elm))
 #define HT_REPLACE(name, head, elm)  name##_HT_REPLACE((head), (elm))
@@ -56,7 +60,7 @@
 #define HT_INIT(name, head)          name##_HT_INIT(head)
 /* Helper: */
 static inline unsigned
-ht_improve_hash(unsigned h)
+ht_improve_hash_(unsigned h)
 {
   /* Aim to protect against poor hash functions by adding logic here
    * - logic taken from java 1.4 hashtable source */
@@ -70,7 +74,7 @@ ht_improve_hash(unsigned h)
 #if 0
 /** Basic string hash function, from Java standard String.hashCode(). */
 static inline unsigned
-ht_string_hash(const char *s)
+ht_string_hash_(const char *s)
 {
   unsigned h = 0;
   int m = 1;
@@ -84,7 +88,7 @@ ht_string_hash(const char *s)
 
 /** Basic string hash function, from Python's str.__hash__() */
 static inline unsigned
-ht_string_hash(const char *s)
+ht_string_hash_(const char *s)
 {
   unsigned h;
   const unsigned char *cp = (const unsigned char *)s;
@@ -97,25 +101,25 @@ ht_string_hash(const char *s)
   return h;
 }
 
-#ifdef HT_CACHE_HASH_VALUES
-#define _HT_SET_HASH(elm, field, hashfn)        \
+#ifndef HT_NO_CACHE_HASH_VALUES
+#define HT_SET_HASH_(elm, field, hashfn)        \
        do { (elm)->field.hte_hash = hashfn(elm); } while (0)
-#define _HT_SET_HASHVAL(elm, field, val)       \
+#define HT_SET_HASHVAL_(elm, field, val)       \
        do { (elm)->field.hte_hash = (val); } while (0)
-#define _HT_ELT_HASH(elm, field, hashfn)       \
+#define HT_ELT_HASH_(elm, field, hashfn)       \
        ((elm)->field.hte_hash)
 #else
-#define _HT_SET_HASH(elm, field, hashfn)       \
+#define HT_SET_HASH_(elm, field, hashfn)       \
        ((void)0)
-#define _HT_ELT_HASH(elm, field, hashfn)       \
+#define HT_ELT_HASH_(elm, field, hashfn)       \
        (hashfn(elm))
-#define _HT_SET_HASHVAL(elm, field, val)       \
+#define HT_SET_HASHVAL_(elm, field, val)       \
         ((void)0)
 #endif
 
 /* Helper: alias for the bucket containing 'elm'. */
-#define _HT_BUCKET(head, field, elm, hashfn)                           \
-       ((head)->hth_table[_HT_ELT_HASH(elm,field,hashfn) % head->hth_table_length])
+#define HT_BUCKET_(head, field, elm, hashfn)                           \
+       ((head)->hth_table[HT_ELT_HASH_(elm,field,hashfn) % head->hth_table_length])
 
 #define HT_FOREACH(x, name, head)                 \
   for ((x) = HT_START(name, head);                \
@@ -125,7 +129,7 @@ ht_string_hash(const char *s)
 #define HT_PROTOTYPE(name, type, field, hashfn, eqfn)                   \
   int name##_HT_GROW(struct name *ht, unsigned min_capacity);           \
   void name##_HT_CLEAR(struct name *ht);                                \
-  int _##name##_HT_REP_IS_BAD(const struct name *ht);                   \
+  int name##_HT_REP_IS_BAD_(const struct name *ht);                    \
   static inline void                                                    \
   name##_HT_INIT(struct name *head) {                                   \
     head->hth_table_length = 0;                                         \
@@ -137,12 +141,12 @@ ht_string_hash(const char *s)
   /* Helper: returns a pointer to the right location in the table       \
    * 'head' to find or insert the element 'elm'. */                     \
   static inline struct type **                                          \
-  _##name##_HT_FIND_P(struct name *head, struct type *elm)              \
+  name##_HT_FIND_P_(struct name *head, struct type *elm)               \
   {                                                                     \
     struct type **p;                                                    \
     if (!head->hth_table)                                               \
       return NULL;                                                      \
-    p = &_HT_BUCKET(head, field, elm, hashfn);                         \
+    p = &HT_BUCKET_(head, field, elm, hashfn);                         \
     while (*p) {                                                        \
       if (eqfn(*p, elm))                                                \
         return p;                                                       \
@@ -157,8 +161,8 @@ ht_string_hash(const char *s)
   {                                                                     \
     struct type **p;                                                    \
     struct name *h = (struct name *) head;                              \
-    _HT_SET_HASH(elm, field, hashfn);                                   \
-    p = _##name##_HT_FIND_P(h, elm);                                    \
+    HT_SET_HASH_(elm, field, hashfn);                                   \
+    p = name##_HT_FIND_P_(h, elm);                                     \
     return p ? *p : NULL;                                               \
   }                                                                     \
   /* Insert the element 'elm' into the table 'head'.  Do not call this  \
@@ -170,8 +174,8 @@ ht_string_hash(const char *s)
     if (!head->hth_table || head->hth_n_entries >= head->hth_load_limit) \
       name##_HT_GROW(head, head->hth_n_entries+1);                      \
     ++head->hth_n_entries;                                              \
-    _HT_SET_HASH(elm, field, hashfn);                                   \
-    p = &_HT_BUCKET(head, field, elm, hashfn);                         \
+    HT_SET_HASH_(elm, field, hashfn);                                   \
+    p = &HT_BUCKET_(head, field, elm, hashfn);                         \
     elm->field.hte_next = *p;                                           \
     *p = elm;                                                           \
   }                                                                     \
@@ -184,8 +188,8 @@ ht_string_hash(const char *s)
     struct type **p, *r;                                                \
     if (!head->hth_table || head->hth_n_entries >= head->hth_load_limit) \
       name##_HT_GROW(head, head->hth_n_entries+1);                      \
-    _HT_SET_HASH(elm, field, hashfn);                                   \
-    p = _##name##_HT_FIND_P(head, elm);                                 \
+    HT_SET_HASH_(elm, field, hashfn);                                   \
+    p = name##_HT_FIND_P_(head, elm);                                  \
     r = *p;                                                             \
     *p = elm;                                                           \
     if (r && (r!=elm)) {                                                \
@@ -203,8 +207,8 @@ ht_string_hash(const char *s)
   name##_HT_REMOVE(struct name *head, struct type *elm)                 \
   {                                                                     \
     struct type **p, *r;                                                \
-    _HT_SET_HASH(elm, field, hashfn);                                   \
-    p = _##name##_HT_FIND_P(head,elm);                                  \
+    HT_SET_HASH_(elm, field, hashfn);                                   \
+    p = name##_HT_FIND_P_(head,elm);                                   \
     if (!p || !*p)                                                      \
       return NULL;                                                      \
     r = *p;                                                             \
@@ -265,7 +269,7 @@ ht_string_hash(const char *s)
     if ((*elm)->field.hte_next) {                                       \
       return &(*elm)->field.hte_next;                                   \
     } else {                                                            \
-      unsigned b = (_HT_ELT_HASH(*elm, field, hashfn) % head->hth_table_length)+1; \
+      unsigned b = (HT_ELT_HASH_(*elm, field, hashfn) % head->hth_table_length)+1; \
       while (b < head->hth_table_length) {                              \
         if (head->hth_table[b])                                         \
           return &head->hth_table[b];                                   \
@@ -277,7 +281,7 @@ ht_string_hash(const char *s)
   static inline struct type **                                          \
   name##_HT_NEXT_RMV(struct name *head, struct type **elm)              \
   {                                                                     \
-    unsigned h = _HT_ELT_HASH(*elm, field, hashfn);                    \
+    unsigned h = HT_ELT_HASH_(*elm, field, hashfn);                    \
     *elm = (*elm)->field.hte_next;                                      \
     --head->hth_n_entries;                                              \
     if (*elm) {                                                         \
@@ -334,7 +338,7 @@ ht_string_hash(const char *s)
         elm = head->hth_table[b];                                       \
         while (elm) {                                                   \
           next = elm->field.hte_next;                                   \
-          b2 = _HT_ELT_HASH(elm, field, hashfn) % new_len;              \
+          b2 = HT_ELT_HASH_(elm, field, hashfn) % new_len;              \
           elm->field.hte_next = new_table[b2];                          \
           new_table[b2] = elm;                                          \
           elm = next;                                                   \
@@ -352,7 +356,7 @@ ht_string_hash(const char *s)
       for (b=0; b < head->hth_table_length; ++b) {                      \
         struct type *e, **pE;                                           \
         for (pE = &new_table[b], e = *pE; e != NULL; e = *pE) {         \
-          b2 = _HT_ELT_HASH(e, field, hashfn) % new_len;                \
+          b2 = HT_ELT_HASH_(e, field, hashfn) % new_len;                \
           if (b2 == b) {                                                \
             pE = &e->field.hte_next;                                    \
           } else {                                                      \
@@ -382,7 +386,7 @@ ht_string_hash(const char *s)
   /* Debugging helper: return false iff the representation of 'head' is \
    * internally consistent. */                                          \
   int                                                                   \
-  _##name##_HT_REP_IS_BAD(const struct name *head)                      \
+  name##_HT_REP_IS_BAD_(const struct name *head)                       \
   {                                                                     \
     unsigned n, i;                                                      \
     struct type *elm;                                                   \
@@ -404,9 +408,9 @@ ht_string_hash(const char *s)
       return 5;                                                         \
     for (n = i = 0; i < head->hth_table_length; ++i) {                  \
       for (elm = head->hth_table[i]; elm; elm = elm->field.hte_next) {  \
-        if (_HT_ELT_HASH(elm, field, hashfn) != hashfn(elm))           \
+        if (HT_ELT_HASH_(elm, field, hashfn) != hashfn(elm))           \
           return 1000 + i;                                              \
-        if ((_HT_ELT_HASH(elm, field, hashfn) % head->hth_table_length) != i) \
+        if ((HT_ELT_HASH_(elm, field, hashfn) % head->hth_table_length) != i) \
           return 10000 + i;                                             \
         ++n;                                                            \
       }                                                                 \
@@ -419,24 +423,24 @@ ht_string_hash(const char *s)
 /** Implements an over-optimized "find and insert if absent" block;
  * not meant for direct usage by typical code, or usage outside the critical
  * path.*/
-#define _HT_FIND_OR_INSERT(name, field, hashfn, head, eltype, elm, var, y, n) \
+#define HT_FIND_OR_INSERT_(name, field, hashfn, head, eltype, elm, var, y, n) \
   {                                                                     \
-    struct name *_##var##_head = head;                                  \
-    struct eltype **var;                                                                                               \
-    if (!_##var##_head->hth_table ||                                    \
-        _##var##_head->hth_n_entries >= _##var##_head->hth_load_limit)  \
-      name##_HT_GROW(_##var##_head, _##var##_head->hth_n_entries+1);     \
-    _HT_SET_HASH((elm), field, hashfn);                                \
-    var = _##name##_HT_FIND_P(_##var##_head, (elm));                    \
+    struct name *var##_head_ = head;                                    \
+    struct eltype **var;                                                \
+    if (!var##_head_->hth_table ||                                      \
+        var##_head_->hth_n_entries >= var##_head_->hth_load_limit)      \
+      name##_HT_GROW(var##_head_, var##_head_->hth_n_entries+1);        \
+    HT_SET_HASH_((elm), field, hashfn);                                 \
+    var = name##_HT_FIND_P_(var##_head_, (elm));                        \
     if (*var) {                                                         \
       y;                                                                \
     } else {                                                            \
       n;                                                                \
     }                                                                   \
   }
-#define _HT_FOI_INSERT(field, head, elm, newent, var)       \
+#define HT_FOI_INSERT_(field, head, elm, newent, var)       \
   {                                                         \
-    _HT_SET_HASHVAL(newent, field, (elm)->field.hte_hash);  \
+    HT_SET_HASHVAL_(newent, field, (elm)->field.hte_hash);  \
     newent->field.hte_next = NULL;                          \
     *var = newent;                                          \
     ++((head)->hth_n_entries);                              \
@@ -444,7 +448,7 @@ ht_string_hash(const char *s)
 
 /*
  * Copyright 2005, Nick Mathewson.  Implementation logic is adapted from code
- * by Cristopher Clark, retrofit to allow drop-in memory management, and to
+ * by Christopher Clark, retrofit to allow drop-in memory management, and to
  * use the same interface as Niels Provos's tree.h.  This is probably still
  * a derived work, so the original license below still applies.
  *
index 05e286cab5655ba1a12beaf2d4329c0104f43186..e366c7c60adf9ae40f13878213bf6eb1fb93b51f 100644 (file)
@@ -1,14 +1,14 @@
 /*
  * Copyright 2001-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * This header file contains definitions for dealing with HTTP requests
  * that are internal to libevent.  As user of the library, you should not
  * need to know about these.
  */
 
-#ifndef _HTTP_INTERNAL_H_
-#define _HTTP_INTERNAL_H_
+#ifndef HTTP_INTERNAL_H_INCLUDED_
+#define HTTP_INTERNAL_H_INCLUDED_
 
 #include "event2/event_struct.h"
 #include "util-internal.h"
@@ -42,7 +42,7 @@ struct addrinfo;
 struct evhttp_request;
 
 /* Indicates an unknown request method. */
-#define _EVHTTP_REQ_UNKNOWN (1<<15)
+#define EVHTTP_REQ_UNKNOWN_ (1<<15)
 
 enum evhttp_connection_state {
        EVCON_DISCONNECTED,     /**< not currently connected not trying either*/
@@ -86,6 +86,9 @@ struct evhttp_connection {
        struct timeval timeout;         /* timeout for events */
        int retry_cnt;                  /* retry count */
        int retry_max;                  /* maximum number of retries */
+       struct timeval initial_retry_timeout; /* Timeout for low long to wait
+                                              * after first failing attempt
+                                              * before retry */
 
        enum evhttp_connection_state state;
 
@@ -165,6 +168,8 @@ struct evhttp {
           don't match. */
        void (*gencb)(struct evhttp_request *req, void *);
        void *gencbarg;
+       struct bufferevent* (*bevcb)(struct event_base *, void *);
+       void *bevcbarg;
 
        struct event_base *base;
 };
@@ -172,24 +177,24 @@ struct evhttp {
 /* XXX most of these functions could be static. */
 
 /* resets the connection; can be reused for more requests */
-void evhttp_connection_reset(struct evhttp_connection *);
+void evhttp_connection_reset_(struct evhttp_connection *);
 
 /* connects if necessary */
-int evhttp_connection_connect(struct evhttp_connection *);
+int evhttp_connection_connect_(struct evhttp_connection *);
 
 /* notifies the current request that it failed; resets connection */
-void evhttp_connection_fail(struct evhttp_connection *,
+void evhttp_connection_fail_(struct evhttp_connection *,
     enum evhttp_connection_error error);
 
 enum message_read_status;
 
-enum message_read_status evhttp_parse_firstline(struct evhttp_request *, struct evbuffer*);
-enum message_read_status evhttp_parse_headers(struct evhttp_request *, struct evbuffer*);
+enum message_read_status evhttp_parse_firstline_(struct evhttp_request *, struct evbuffer*);
+enum message_read_status evhttp_parse_headers_(struct evhttp_request *, struct evbuffer*);
 
-void evhttp_start_read(struct evhttp_connection *);
+void evhttp_start_read_(struct evhttp_connection *);
 
 /* response sending HTML the data in the buffer */
-void evhttp_response_code(struct evhttp_request *, int, const char *);
-void evhttp_send_page(struct evhttp_request *, struct evbuffer *);
+void evhttp_response_code_(struct evhttp_request *, int, const char *);
+void evhttp_send_page_(struct evhttp_request *, struct evbuffer *);
 
 #endif /* _HTTP_H */
index 58fef1695a258badec647ea607ec94ddcf6d12cc..786105d37bab3c2d578361c9dca1354e9ac754af 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
-#ifdef _EVENT_HAVE_SYS_PARAM_H
+#ifdef EVENT__HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
 
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #ifdef HAVE_SYS_IOCCOM_H
 
 #include <sys/queue.h>
 
-#ifdef _EVENT_HAVE_NETINET_IN_H
+#ifdef EVENT__HAVE_NETINET_IN_H
 #include <netinet/in.h>
 #endif
-#ifdef _EVENT_HAVE_ARPA_INET_H
+#ifdef EVENT__HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
-#ifdef _EVENT_HAVE_NETDB_H
+#ifdef EVENT__HAVE_NETDB_H
 #include <netdb.h>
 #endif
 
 #endif
 #include <signal.h>
 #include <time.h>
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-#ifdef _EVENT_HAVE_FCNTL_H
+#ifdef EVENT__HAVE_FCNTL_H
 #include <fcntl.h>
 #endif
 
@@ -92,7 +92,6 @@
 #include "event2/event.h"
 #include "event2/buffer.h"
 #include "event2/bufferevent.h"
-#include "event2/bufferevent_compat.h"
 #include "event2/http_struct.h"
 #include "event2/http_compat.h"
 #include "event2/util.h"
 #include "mm-internal.h"
 #include "bufferevent-internal.h"
 
-#ifndef _EVENT_HAVE_GETNAMEINFO
+#ifndef EVENT__HAVE_GETNAMEINFO
 #define NI_MAXSERV 32
 #define NI_MAXHOST 1025
 
@@ -199,7 +198,7 @@ static int evhttp_decode_uri_internal(const char *uri, size_t length,
 static int evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
                  const char *hostname);
 
-#ifndef _EVENT_HAVE_STRSEP
+#ifndef EVENT__HAVE_STRSEP
 /* strsep replacement for platforms that lack it.  Only works if
  * del is one character long. */
 static char *
@@ -353,23 +352,6 @@ evhttp_response_needs_body(struct evhttp_request *req)
                req->type != EVHTTP_REQ_HEAD);
 }
 
-/** Helper: adds the event 'ev' with the timeout 'timeout', or with
- * default_timeout if timeout is -1.
- */
-static int
-evhttp_add_event(struct event *ev, int timeout, int default_timeout)
-{
-       if (timeout != 0) {
-               struct timeval tv;
-
-               evutil_timerclear(&tv);
-               tv.tv_sec = timeout != -1 ? timeout : default_timeout;
-               return event_add(ev, &tv);
-       } else {
-               return event_add(ev, NULL);
-       }
-}
-
 /** Helper: called after we've added some data to an evcon's bufferevent's
  * output buffer.  Sets the evconn's writing-is-done callback, and puts
  * the bufferevent into writing mode.
@@ -696,7 +678,7 @@ evhttp_connection_incoming_fail(struct evhttp_request *req,
  * retry any pending requests, and inform the user.  If it's incoming,
  * delegates to evhttp_connection_incoming_fail(). */
 void
-evhttp_connection_fail(struct evhttp_connection *evcon,
+evhttp_connection_fail_(struct evhttp_connection *evcon,
     enum evhttp_connection_error error)
 {
        struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
@@ -738,11 +720,11 @@ evhttp_connection_fail(struct evhttp_connection *evcon,
        evhttp_request_free(req);
 
        /* reset the connection */
-       evhttp_connection_reset(evcon);
+       evhttp_connection_reset_(evcon);
 
        /* We are trying the next request that was queued on us */
        if (TAILQ_FIRST(&evcon->requests) != NULL)
-               evhttp_connection_connect(evcon);
+               evhttp_connection_connect_(evcon);
 
        /* inform the user */
        if (cb != NULL)
@@ -788,7 +770,7 @@ evhttp_connection_done(struct evhttp_connection *evcon)
 
                /* check if we got asked to close the connection */
                if (need_close)
-                       evhttp_connection_reset(evcon);
+                       evhttp_connection_reset_(evcon);
 
                if (TAILQ_FIRST(&evcon->requests) != NULL) {
                        /*
@@ -796,7 +778,7 @@ evhttp_connection_done(struct evhttp_connection *evcon)
                         * and deal with the next request.
                         */
                        if (!evhttp_connected(evcon))
-                               evhttp_connection_connect(evcon);
+                               evhttp_connection_connect_(evcon);
                        else
                                evhttp_request_dispatch(evcon);
                } else if (!need_close) {
@@ -935,10 +917,10 @@ evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
 {
        struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
 
-       switch (evhttp_parse_headers(req, buf)) {
+       switch (evhttp_parse_headers_(req, buf)) {
        case DATA_CORRUPTED:
        case DATA_TOO_LONG:
-               evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+               evhttp_connection_fail_(evcon, EVCON_HTTP_INVALID_HEADER);
                break;
        case ALL_DATA_READ:
                bufferevent_disable(evcon->bufev, EV_READ);
@@ -967,7 +949,7 @@ evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
                case DATA_CORRUPTED:
                case DATA_TOO_LONG:/*separate error for this? XXX */
                        /* corrupted data */
-                       evhttp_connection_fail(evcon,
+                       evhttp_connection_fail_(evcon,
                            EVCON_HTTP_INVALID_HEADER);
                        return;
                case REQUEST_CANCELED:
@@ -981,7 +963,7 @@ evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
        } else if (req->ntoread < 0) {
                /* Read until connection close. */
                if ((size_t)(req->body_size + evbuffer_get_length(buf)) < req->body_size) {
-                       evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+                       evhttp_connection_fail_(evcon, EVCON_HTTP_INVALID_HEADER);
                        return;
                }
 
@@ -1006,7 +988,7 @@ evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
                /* XXX: The above casted comparison must checked for overflow */
                /* failed body length test */
                event_debug(("Request body is too long"));
-               evhttp_connection_fail(evcon,
+               evhttp_connection_fail_(evcon,
                                       EVCON_HTTP_INVALID_HEADER);
                return;
        }
@@ -1035,7 +1017,7 @@ evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
 }
 
 #define get_deferred_queue(evcon)              \
-       (event_base_get_deferred_cb_queue((evcon)->base))
+       (event_base_get_deferred_cb_queue_((evcon)->base))
 
 /*
  * Gets called when more data becomes available
@@ -1048,7 +1030,7 @@ evhttp_read_cb(struct bufferevent *bufev, void *arg)
        struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
 
        /* Cancel if it's pending. */
-       event_deferred_cb_cancel(get_deferred_queue(evcon),
+       event_deferred_cb_cancel_(get_deferred_queue(evcon),
            &evcon->read_more_deferred_cb);
 
        switch (evcon->state) {
@@ -1084,7 +1066,7 @@ evhttp_read_cb(struct bufferevent *bufev, void *arg)
                                __func__, EV_SIZE_ARG(total_len)));
 #endif
 
-                       evhttp_connection_reset(evcon);
+                       evhttp_connection_reset_(evcon);
                }
                break;
        case EVCON_DISCONNECTED:
@@ -1115,7 +1097,7 @@ evhttp_write_connectioncb(struct evhttp_connection *evcon, void *arg)
        /* We are done writing our header and are now expecting the response */
        req->kind = EVHTTP_RESPONSE;
 
-       evhttp_start_read(evcon);
+       evhttp_start_read_(evcon);
 }
 
 /*
@@ -1136,7 +1118,7 @@ evhttp_connection_free(struct evhttp_connection *evcon)
        /* remove all requests that might be queued on this
         * connection.  for server connections, this should be empty.
         * because it gets dequeued either in evhttp_connection_done or
-        * evhttp_connection_fail.
+        * evhttp_connection_fail_.
         */
        while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
                TAILQ_REMOVE(&evcon->requests, req, next);
@@ -1156,7 +1138,7 @@ evhttp_connection_free(struct evhttp_connection *evcon)
        if (evcon->bufev != NULL)
                bufferevent_free(evcon->bufev);
 
-       event_deferred_cb_cancel(get_deferred_queue(evcon),
+       event_deferred_cb_cancel_(get_deferred_queue(evcon),
            &evcon->read_more_deferred_cb);
 
        if (evcon->fd != -1) {
@@ -1218,7 +1200,7 @@ evhttp_request_dispatch(struct evhttp_connection* evcon)
 /* Reset our connection state: disables reading/writing, closes our fd (if
 * any), clears out buffers, and puts us in state DISCONNECTED. */
 void
-evhttp_connection_reset(struct evhttp_connection *evcon)
+evhttp_connection_reset_(struct evhttp_connection *evcon)
 {
        struct evbuffer *tmp;
 
@@ -1231,9 +1213,9 @@ evhttp_connection_reset(struct evhttp_connection *evcon)
           bufferevent is connecting, then you can't actually stop the
           bufferevent from trying to connect with bufferevent_disable().  The
           connect will never trigger, since we close the fd, but the timeout
-          might.  That caused an assertion failure in evhttp_connection_fail.
+          might.  That caused an assertion failure in evhttp_connection_fail_.
        */
-       bufferevent_disable_hard(evcon->bufev, EV_READ|EV_WRITE);
+       bufferevent_disable_hard_(evcon->bufev, EV_READ|EV_WRITE);
 
        if (evcon->fd != -1) {
                /* inform interested parties about connection close */
@@ -1276,7 +1258,7 @@ evhttp_connection_retry(evutil_socket_t fd, short what, void *arg)
        struct evhttp_connection *evcon = arg;
 
        evcon->state = EVCON_DISCONNECTED;
-       evhttp_connection_connect(evcon);
+       evhttp_connection_connect_(evcon);
 }
 
 static void
@@ -1285,15 +1267,27 @@ evhttp_connection_cb_cleanup(struct evhttp_connection *evcon)
        struct evcon_requestq requests;
 
        if (evcon->retry_max < 0 || evcon->retry_cnt < evcon->retry_max) {
+               struct timeval tv_retry = evcon->initial_retry_timeout;
+               int i;
                evtimer_assign(&evcon->retry_ev, evcon->base, evhttp_connection_retry, evcon);
                /* XXXX handle failure from evhttp_add_event */
-               evhttp_add_event(&evcon->retry_ev,
-                   MIN(3600, 2 << evcon->retry_cnt),
-                   HTTP_CONNECT_TIMEOUT);
+               for (i=0; i < evcon->retry_cnt; ++i) {
+                       tv_retry.tv_usec *= 2;
+                       if (tv_retry.tv_usec > 1000000) {
+                               tv_retry.tv_usec -= 1000000;
+                               tv_retry.tv_sec += 1;
+                       }
+                       tv_retry.tv_sec *= 2;
+                       if (tv_retry.tv_sec > 3600) {
+                               tv_retry.tv_sec = 3600;
+                               tv_retry.tv_usec = 0;
+                       }
+               }
+               event_add(&evcon->retry_ev, &tv_retry);
                evcon->retry_cnt++;
                return;
        }
-       evhttp_connection_reset(evcon);
+       evhttp_connection_reset_(evcon);
 
        /*
         * User callback can do evhttp_make_request() on the same
@@ -1367,16 +1361,17 @@ evhttp_error_cb(struct bufferevent *bufev, short what, void *arg)
                 * disconnected.
                 */
                EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
-               evhttp_connection_reset(evcon);
+               evhttp_connection_reset_(evcon);
                return;
        }
 
        if (what & BEV_EVENT_TIMEOUT) {
-               evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
+               evhttp_connection_fail_(evcon, EVCON_HTTP_TIMEOUT);
        } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
-               evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
+               evhttp_connection_fail_(evcon, EVCON_HTTP_EOF);
+       } else if (what == BEV_EVENT_CONNECTED) {
        } else {
-               evhttp_connection_fail(evcon, EVCON_HTTP_BUFFER_ERROR);
+               evhttp_connection_fail_(evcon, EVCON_HTTP_BUFFER_ERROR);
        }
 }
 
@@ -1434,8 +1429,9 @@ evhttp_connection_cb(struct bufferevent *bufev, short what, void *arg)
            evcon);
 
        if (!evutil_timerisset(&evcon->timeout)) {
-               bufferevent_settimeout(evcon->bufev,
-                   HTTP_READ_TIMEOUT, HTTP_WRITE_TIMEOUT);
+               const struct timeval read_tv = { HTTP_READ_TIMEOUT, 0 };
+               const struct timeval write_tv = { HTTP_WRITE_TIMEOUT, 0 };
+               bufferevent_set_timeouts(evcon->bufev, &read_tv, &write_tv);
        } else {
                bufferevent_set_timeouts(evcon->bufev, &evcon->timeout, &evcon->timeout);
        }
@@ -1467,7 +1463,7 @@ evhttp_parse_http_version(const char *version, struct evhttp_request *req)
        int major, minor;
        char ch;
        int n = sscanf(version, "HTTP/%d.%d%c", &major, &minor, &ch);
-       if (n > 2 || major > 1) {
+       if (n != 2 || major > 1) {
                event_debug(("%s: bad version %s on message %p from %s",
                        __func__, version, req, req->remote_host));
                return (-1);
@@ -1536,7 +1532,7 @@ evhttp_parse_request_line(struct evhttp_request *req, char *line)
                return (-1);
 
        method_len = (uri - method) - 1;
-       type       = _EVHTTP_REQ_UNKNOWN;
+       type       = EVHTTP_REQ_UNKNOWN_;
 
        /* First line */
        switch (method_len) {
@@ -1643,7 +1639,7 @@ evhttp_parse_request_line(struct evhttp_request *req, char *line)
                break;
        } /* switch */
 
-       if (type == _EVHTTP_REQ_UNKNOWN) {
+       if (type == EVHTTP_REQ_UNKNOWN_) {
                event_debug(("%s: bad method %s on request %p from %s",
                        __func__, method, req, req->remote_host));
                 /* No error yet; we'll give a better error later when
@@ -1806,7 +1802,7 @@ evhttp_add_header_internal(struct evkeyvalq *headers,
  */
 
 enum message_read_status
-evhttp_parse_firstline(struct evhttp_request *req, struct evbuffer *buffer)
+evhttp_parse_firstline_(struct evhttp_request *req, struct evbuffer *buffer)
 {
        char *line;
        enum message_read_status status = ALL_DATA_READ;
@@ -1871,7 +1867,7 @@ evhttp_append_to_last_header(struct evkeyvalq *headers, const char *line)
 }
 
 enum message_read_status
-evhttp_parse_headers(struct evhttp_request *req, struct evbuffer* buffer)
+evhttp_parse_headers_(struct evhttp_request *req, struct evbuffer* buffer)
 {
        enum message_read_status errcode = DATA_CORRUPTED;
        char *line;
@@ -2011,7 +2007,7 @@ evhttp_get_body(struct evhttp_connection *evcon, struct evhttp_request *req)
                req->ntoread = -1;
        } else {
                if (evhttp_get_body_length(req) == -1) {
-                       evhttp_connection_fail(evcon,
+                       evhttp_connection_fail_(evcon,
                            EVCON_HTTP_INVALID_HEADER);
                        return;
                }
@@ -2063,12 +2059,12 @@ evhttp_read_firstline(struct evhttp_connection *evcon,
 {
        enum message_read_status res;
 
-       res = evhttp_parse_firstline(req, bufferevent_get_input(evcon->bufev));
+       res = evhttp_parse_firstline_(req, bufferevent_get_input(evcon->bufev));
        if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
                /* Error while reading, terminate */
                event_debug(("%s: bad header lines on %d\n",
                        __func__, evcon->fd));
-               evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+               evhttp_connection_fail_(evcon, EVCON_HTTP_INVALID_HEADER);
                return;
        } else if (res == MORE_DATA_EXPECTED) {
                /* Need more header lines */
@@ -2086,11 +2082,11 @@ evhttp_read_header(struct evhttp_connection *evcon,
        enum message_read_status res;
        evutil_socket_t fd = evcon->fd;
 
-       res = evhttp_parse_headers(req, bufferevent_get_input(evcon->bufev));
+       res = evhttp_parse_headers_(req, bufferevent_get_input(evcon->bufev));
        if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
                /* Error while reading, terminate */
                event_debug(("%s: bad header lines on %d\n", __func__, fd));
-               evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+               evhttp_connection_fail_(evcon, EVCON_HTTP_INVALID_HEADER);
                return;
        } else if (res == MORE_DATA_EXPECTED) {
                /* Need more header lines */
@@ -2112,7 +2108,7 @@ evhttp_read_header(struct evhttp_connection *evcon,
        case EVHTTP_RESPONSE:
                /* Start over if we got a 100 Continue response. */
                if (req->response_code == 100) {
-                       evhttp_start_read(evcon);
+                       evhttp_start_read_(evcon);
                        return;
                }
                if (!evhttp_response_needs_body(req)) {
@@ -2130,7 +2126,7 @@ evhttp_read_header(struct evhttp_connection *evcon,
 
        default:
                event_warnx("%s: bad header on %d", __func__, fd);
-               evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
+               evhttp_connection_fail_(evcon, EVCON_HTTP_INVALID_HEADER);
                break;
        }
        /* request may have been freed above */
@@ -2153,7 +2149,7 @@ evhttp_connection_new(const char *address, unsigned short port)
 }
 
 struct evhttp_connection *
-evhttp_connection_base_new(struct event_base *base, struct evdns_base *dnsbase,
+evhttp_connection_base_bufferevent_new(struct event_base *base, struct evdns_base *dnsbase, struct bufferevent* bev,
     const char *address, unsigned short port)
 {
        struct evhttp_connection *evcon = NULL;
@@ -2179,24 +2175,29 @@ evhttp_connection_base_new(struct event_base *base, struct evdns_base *dnsbase,
                goto error;
        }
 
-       if ((evcon->bufev = bufferevent_new(-1,
-                   evhttp_read_cb,
-                   evhttp_write_cb,
-                   evhttp_error_cb, evcon)) == NULL) {
-               event_warn("%s: bufferevent_new failed", __func__);
-               goto error;
+       if (bev == NULL) {
+               if (!(bev = bufferevent_socket_new(base, -1, 0))) {
+                       event_warn("%s: bufferevent_socket_new failed", __func__);
+                       goto error;
+               }
        }
 
+       bufferevent_setcb(bev, evhttp_read_cb, evhttp_write_cb, evhttp_error_cb, evcon);
+       evcon->bufev = bev;
+
        evcon->state = EVCON_DISCONNECTED;
        TAILQ_INIT(&evcon->requests);
 
+       evcon->initial_retry_timeout.tv_sec = 2;
+       evcon->initial_retry_timeout.tv_usec = 0;
+
        if (base != NULL) {
                evcon->base = base;
-               bufferevent_base_set(base, evcon->bufev);
+               if (bufferevent_get_base(bev) != base)
+                       bufferevent_base_set(base, evcon->bufev);
        }
 
-
-       event_deferred_cb_init(&evcon->read_more_deferred_cb,
+       event_deferred_cb_init_(&evcon->read_more_deferred_cb,
            evhttp_deferred_read_cb, evcon);
 
        evcon->dns_base = dnsbase;
@@ -2209,6 +2210,18 @@ evhttp_connection_base_new(struct event_base *base, struct evdns_base *dnsbase,
        return (NULL);
 }
 
+struct bufferevent* evhttp_connection_get_bufferevent(struct evhttp_connection *evcon)
+{
+       return evcon->bufev;
+}
+
+struct evhttp_connection *
+evhttp_connection_base_new(struct event_base *base, struct evdns_base *dnsbase,
+    const char *address, unsigned short port)
+{
+       return evhttp_connection_base_bufferevent_new(base, dnsbase, NULL, address, port);
+}
+
 void
 evhttp_connection_set_base(struct evhttp_connection *evcon,
     struct event_base *base)
@@ -2241,8 +2254,22 @@ evhttp_connection_set_timeout_tv(struct evhttp_connection *evcon,
                evcon->timeout = *tv;
                bufferevent_set_timeouts(evcon->bufev, &evcon->timeout, &evcon->timeout);
        } else {
+               const struct timeval read_tv = { HTTP_READ_TIMEOUT, 0 };
+               const struct timeval write_tv = { HTTP_WRITE_TIMEOUT, 0 };
                evutil_timerclear(&evcon->timeout);
-               bufferevent_settimeout(evcon->bufev, HTTP_READ_TIMEOUT, HTTP_WRITE_TIMEOUT);
+               bufferevent_set_timeouts(evcon->bufev, &read_tv, &write_tv);
+       }
+}
+
+void
+evhttp_connection_set_initial_retry_tv(struct evhttp_connection *evcon,
+    const struct timeval *tv)
+{
+       if (tv) {
+               evcon->initial_retry_timeout = *tv;
+       } else {
+               evutil_timerclear(&evcon->initial_retry_timeout);
+               evcon->initial_retry_timeout.tv_sec = 2;
        }
 }
 
@@ -2270,12 +2297,12 @@ evhttp_connection_get_peer(struct evhttp_connection *evcon,
 }
 
 int
-evhttp_connection_connect(struct evhttp_connection *evcon)
+evhttp_connection_connect_(struct evhttp_connection *evcon)
 {
        if (evcon->state == EVCON_CONNECTING)
                return (0);
 
-       evhttp_connection_reset(evcon);
+       evhttp_connection_reset_(evcon);
 
        EVUTIL_ASSERT(!(evcon->flags & EVHTTP_CON_INCOMING));
        evcon->flags |= EVHTTP_CON_OUTGOING;
@@ -2295,10 +2322,12 @@ evhttp_connection_connect(struct evhttp_connection *evcon)
            NULL /* evhttp_write_cb */,
            evhttp_connection_cb,
            evcon);
-       if (!evutil_timerisset(&evcon->timeout))
-               bufferevent_settimeout(evcon->bufev, 0, HTTP_CONNECT_TIMEOUT);
-       else
+       if (!evutil_timerisset(&evcon->timeout)) {
+               const struct timeval conn_tv = { HTTP_CONNECT_TIMEOUT, 0 };
+               bufferevent_set_timeouts(evcon->bufev, NULL, &conn_tv);
+       } else {
                bufferevent_set_timeouts(evcon->bufev, NULL, &evcon->timeout);
+       }
        /* make sure that we get a write callback */
        bufferevent_enable(evcon->bufev, EV_WRITE);
 
@@ -2355,9 +2384,9 @@ evhttp_make_request(struct evhttp_connection *evcon,
 
        /* If the connection object is not connected; make it so */
        if (!evhttp_connected(evcon)) {
-               int res = evhttp_connection_connect(evcon);
-              /* evhttp_connection_fail(), which is called through
-               * evhttp_connection_connect(), assumes that req lies in
+               int res = evhttp_connection_connect_(evcon);
+              /* evhttp_connection_fail_(), which is called through
+               * evhttp_connection_connect_(), assumes that req lies in
                * evcon->requests.  Thus, enqueue the request in advance and r
                * it in the error case. */
               if (res != 0)
@@ -2387,7 +2416,7 @@ evhttp_cancel_request(struct evhttp_request *req)
                        /* it's currently being worked on, so reset
                         * the connection.
                         */
-                       evhttp_connection_fail(evcon,
+                       evhttp_connection_fail_(evcon,
                            EVCON_HTTP_REQUEST_CANCEL);
 
                        /* connection fail freed the request */
@@ -2409,7 +2438,7 @@ evhttp_cancel_request(struct evhttp_request *req)
  */
 
 void
-evhttp_start_read(struct evhttp_connection *evcon)
+evhttp_start_read_(struct evhttp_connection *evcon)
 {
        /* Set up an event to read the headers */
        bufferevent_disable(evcon->bufev, EV_WRITE);
@@ -2425,7 +2454,7 @@ evhttp_start_read(struct evhttp_connection *evcon)
        /* If there's still data pending, process it next time through the
         * loop.  Don't do it now; that could get recusive. */
        if (evbuffer_get_length(bufferevent_get_input(evcon->bufev))) {
-               event_deferred_cb_schedule(get_deferred_queue(evcon),
+               event_deferred_cb_schedule_(get_deferred_queue(evcon),
                    &evcon->read_more_deferred_cb);
        }
 }
@@ -2481,11 +2510,11 @@ evhttp_send_error(struct evhttp_request *req, int error, const char *reason)
                reason = evhttp_response_phrase_internal(error);
        }
 
-       evhttp_response_code(req, error, reason);
+       evhttp_response_code_(req, error, reason);
 
        evbuffer_add_printf(buf, ERR_FORMAT, error, reason, reason);
 
-       evhttp_send_page(req, buf);
+       evhttp_send_page_(req, buf);
 
        evbuffer_free(buf);
 #undef ERR_FORMAT
@@ -2522,7 +2551,7 @@ void
 evhttp_send_reply(struct evhttp_request *req, int code, const char *reason,
     struct evbuffer *databuf)
 {
-       evhttp_response_code(req, code, reason);
+       evhttp_response_code_(req, code, reason);
 
        evhttp_send(req, databuf);
 }
@@ -2531,7 +2560,7 @@ void
 evhttp_send_reply_start(struct evhttp_request *req, int code,
     const char *reason)
 {
-       evhttp_response_code(req, code, reason);
+       evhttp_response_code_(req, code, reason);
        if (evhttp_find_header(req->output_headers, "Content-Length") == NULL &&
            REQ_VERSION_ATLEAST(req, 1, 1) &&
            evhttp_response_needs_body(req)) {
@@ -2697,7 +2726,7 @@ evhttp_response_phrase_internal(int code)
 }
 
 void
-evhttp_response_code(struct evhttp_request *req, int code, const char *reason)
+evhttp_response_code_(struct evhttp_request *req, int code, const char *reason)
 {
        req->kind = EVHTTP_RESPONSE;
        req->response_code = code;
@@ -2713,7 +2742,7 @@ evhttp_response_code(struct evhttp_request *req, int code, const char *reason)
 }
 
 void
-evhttp_send_page(struct evhttp_request *req, struct evbuffer *databuf)
+evhttp_send_page_(struct evhttp_request *req, struct evbuffer *databuf)
 {
        if (!req->major || !req->minor) {
                req->major = 1;
@@ -2721,7 +2750,7 @@ evhttp_send_page(struct evhttp_request *req, struct evbuffer *databuf)
        }
 
        if (req->kind != EVHTTP_RESPONSE)
-               evhttp_response_code(req, 200, "OK");
+               evhttp_response_code_(req, 200, "OK");
 
        evhttp_clear_headers(req->output_headers);
        evhttp_add_header(req->output_headers, "Content-Type", "text/html");
@@ -2822,8 +2851,8 @@ evhttp_decode_uri_internal(
                                decode_plus = 1;
                } else if (c == '+' && decode_plus) {
                        c = ' ';
-               } else if (c == '%' && EVUTIL_ISXDIGIT(uri[i+1]) &&
-                   EVUTIL_ISXDIGIT(uri[i+2])) {
+               } else if (c == '%' && EVUTIL_ISXDIGIT_(uri[i+1]) &&
+                   EVUTIL_ISXDIGIT_(uri[i+2])) {
                        char tmp[3];
                        tmp[0] = uri[i+1];
                        tmp[1] = uri[i+2];
@@ -3011,7 +3040,7 @@ prefix_suffix_match(const char *pattern, const char *name, int ignorecase)
                default:
                        if (c != *name) {
                                if (!ignorecase ||
-                                   EVUTIL_TOLOWER(c) != EVUTIL_TOLOWER(*name))
+                                   EVUTIL_TOLOWER_(c) != EVUTIL_TOLOWER_(*name))
                                        return (0);
                        }
                        ++name;
@@ -3152,13 +3181,13 @@ evhttp_handle_request(struct evhttp_request *req, void *arg)
                        return;
                }
 
-               evhttp_response_code(req, HTTP_NOTFOUND, "Not Found");
+               evhttp_response_code_(req, HTTP_NOTFOUND, "Not Found");
 
                evbuffer_add_printf(buf, ERR_FORMAT, escaped_html);
 
                mm_free(escaped_html);
 
-               evhttp_send_page(req, buf);
+               evhttp_send_page_(req, buf);
 
                evbuffer_free(buf);
 #undef ERR_FORMAT
@@ -3220,6 +3249,16 @@ evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd)
        return (0);
 }
 
+void
+evhttp_foreach_bound_socket(struct evhttp *http,
+                            evhttp_bound_socket_foreach_fn *function,
+                            void *argument)
+{
+       struct evhttp_bound_socket *bound;
+
+       TAILQ_FOREACH(bound, &http->sockets, next)
+               function(bound, argument);
+}
 
 struct evhttp_bound_socket *
 evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd)
@@ -3562,6 +3601,14 @@ evhttp_set_gencb(struct evhttp *http,
        http->gencbarg = cbarg;
 }
 
+void
+evhttp_set_bevcb(struct evhttp *http,
+    struct bufferevent* (*cb)(struct event_base *, void *), void *cbarg)
+{
+       http->bevcb = cb;
+       http->bevcbarg = cbarg;
+}
+
 /*
  * Request related functions
  */
@@ -3719,7 +3766,7 @@ evhttp_request_get_host(struct evhttp_request *req)
                   to be consistent with uri_elems case above. */
                if (host) {
                        p = host + strlen(host) - 1;
-                       while (p > host && EVUTIL_ISDIGIT(*p))
+                       while (p > host && EVUTIL_ISDIGIT_(*p))
                                --p;
                        if (p > host && *p == ':') {
                                len = p - host;
@@ -3786,6 +3833,7 @@ evhttp_get_request_connection(
 {
        struct evhttp_connection *evcon;
        char *hostname = NULL, *portname = NULL;
+       struct bufferevent* bev = NULL;
 
        name_from_addr(sa, salen, &hostname, &portname);
        if (hostname == NULL || portname == NULL) {
@@ -3798,8 +3846,11 @@ evhttp_get_request_connection(
                        __func__, hostname, portname, fd));
 
        /* we need a connection object to put the http request on */
-       evcon = evhttp_connection_base_new(
-               http->base, NULL, hostname, atoi(portname));
+       if (http->bevcb != NULL) {
+               bev = (*http->bevcb)(http->base, http->bevcbarg);
+       }
+       evcon = evhttp_connection_base_bufferevent_new(
+               http->base, NULL, bev, hostname, atoi(portname));
        mm_free(hostname);
        mm_free(portname);
        if (evcon == NULL)
@@ -3848,7 +3899,7 @@ evhttp_associate_new_request_with_connection(struct evhttp_connection *evcon)
        req->kind = EVHTTP_REQUEST;
 
 
-       evhttp_start_read(evcon);
+       evhttp_start_read_(evcon);
 
        return (0);
 }
@@ -3895,7 +3946,7 @@ name_from_addr(struct sockaddr *sa, ev_socklen_t salen,
        char strport[NI_MAXSERV];
        int ni_result;
 
-#ifdef _EVENT_HAVE_GETNAMEINFO
+#ifdef EVENT__HAVE_GETNAMEINFO
        ni_result = getnameinfo(sa, salen,
                ntop, sizeof(ntop), strport, sizeof(strport),
                NI_NUMERICHOST|NI_NUMERICSERV);
@@ -3933,17 +3984,13 @@ bind_socket_ai(struct evutil_addrinfo *ai, int reuse)
        int serrno;
 
        /* Create listen socket */
-       fd = socket(ai ? ai->ai_family : AF_INET, SOCK_STREAM, 0);
+       fd = evutil_socket_(ai ? ai->ai_family : AF_INET,
+           SOCK_STREAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
        if (fd == -1) {
                        event_sock_warn(-1, "socket");
                        return (-1);
        }
 
-       if (evutil_make_socket_nonblocking(fd) < 0)
-               goto out;
-       if (evutil_make_socket_closeonexec(fd) < 0)
-               goto out;
-
        setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
        if (reuse)
                evutil_make_listen_socket_reuseable(fd);
@@ -4050,10 +4097,10 @@ scheme_ok(const char *s, const char *eos)
        EVUTIL_ASSERT(eos >= s);
        if (s == eos)
                return 0;
-       if (!EVUTIL_ISALPHA(*s))
+       if (!EVUTIL_ISALPHA_(*s))
                return 0;
        while (++s < eos) {
-               if (! EVUTIL_ISALNUM(*s) &&
+               if (! EVUTIL_ISALNUM_(*s) &&
                    *s != '+' && *s != '-' && *s != '.')
                        return 0;
        }
@@ -4072,8 +4119,8 @@ userinfo_ok(const char *s, const char *eos)
                    *s == ':')
                        ++s;
                else if (*s == '%' && s+2 < eos &&
-                   EVUTIL_ISXDIGIT(s[1]) &&
-                   EVUTIL_ISXDIGIT(s[2]))
+                   EVUTIL_ISXDIGIT_(s[1]) &&
+                   EVUTIL_ISXDIGIT_(s[2]))
                        s += 3;
                else
                        return 0;
@@ -4089,8 +4136,8 @@ regname_ok(const char *s, const char *eos)
                    strchr(SUBDELIMS, *s))
                        ++s;
                else if (*s == '%' &&
-                   EVUTIL_ISXDIGIT(s[1]) &&
-                   EVUTIL_ISXDIGIT(s[2]))
+                   EVUTIL_ISXDIGIT_(s[1]) &&
+                   EVUTIL_ISXDIGIT_(s[2]))
                        s += 3;
                else
                        return 0;
@@ -4103,7 +4150,7 @@ parse_port(const char *s, const char *eos)
 {
        int portnum = 0;
        while (s < eos) {
-               if (! EVUTIL_ISDIGIT(*s))
+               if (! EVUTIL_ISDIGIT_(*s))
                        return -1;
                portnum = (portnum * 10) + (*s - '0');
                if (portnum < 0)
@@ -4125,10 +4172,10 @@ bracket_addr_ok(const char *s, const char *eos)
                 */
                s += 2; /* skip [v */
                --eos;
-               if (!EVUTIL_ISXDIGIT(*s)) /*require at least one*/
+               if (!EVUTIL_ISXDIGIT_(*s)) /*require at least one*/
                        return 0;
                while (s < eos && *s != '.') {
-                       if (EVUTIL_ISXDIGIT(*s))
+                       if (EVUTIL_ISXDIGIT_(*s))
                                ++s;
                        else
                                return 0;
@@ -4188,7 +4235,7 @@ parse_authority(struct evhttp_uri *uri, char *s, char *eos)
                cp = s;
        }
        /* Optionally, we end with ":port" */
-       for (port=eos-1; port >= cp && EVUTIL_ISDIGIT(*port); --port)
+       for (port=eos-1; port >= cp && EVUTIL_ISDIGIT_(*port); --port)
                ;
        if (port >= cp && *port == ':') {
                if (port+1 == eos) /* Leave port unspecified; the RFC allows a
@@ -4272,8 +4319,8 @@ end_of_path(char *cp, enum uri_part part, unsigned flags)
                    strchr(SUBDELIMS, *cp) ||
                    *cp == ':' || *cp == '@' || *cp == '/')
                        ++cp;
-               else if (*cp == '%' && EVUTIL_ISXDIGIT(cp[1]) &&
-                   EVUTIL_ISXDIGIT(cp[2]))
+               else if (*cp == '%' && EVUTIL_ISXDIGIT_(cp[1]) &&
+                   EVUTIL_ISXDIGIT_(cp[2]))
                        cp += 3;
                else if (*cp == '?' && part != PART_PATH)
                        ++cp;
@@ -4433,20 +4480,20 @@ err:
 void
 evhttp_uri_free(struct evhttp_uri *uri)
 {
-#define _URI_FREE_STR(f)               \
+#define URI_FREE_STR_(f)               \
        if (uri->f) {                   \
                mm_free(uri->f);                \
        }
 
-       _URI_FREE_STR(scheme);
-       _URI_FREE_STR(userinfo);
-       _URI_FREE_STR(host);
-       _URI_FREE_STR(path);
-       _URI_FREE_STR(query);
-       _URI_FREE_STR(fragment);
+       URI_FREE_STR_(scheme);
+       URI_FREE_STR_(userinfo);
+       URI_FREE_STR_(host);
+       URI_FREE_STR_(path);
+       URI_FREE_STR_(query);
+       URI_FREE_STR_(fragment);
 
        mm_free(uri);
-#undef _URI_FREE_STR
+#undef URI_FREE_STR_
 }
 
 char *
@@ -4456,7 +4503,7 @@ evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit)
        size_t joined_size = 0;
        char *output = NULL;
 
-#define _URI_ADD(f)    evbuffer_add(tmp, uri->f, strlen(uri->f))
+#define URI_ADD_(f)    evbuffer_add(tmp, uri->f, strlen(uri->f))
 
        if (!uri || !buf || !limit)
                return NULL;
@@ -4466,14 +4513,14 @@ evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit)
                return NULL;
 
        if (uri->scheme) {
-               _URI_ADD(scheme);
+               URI_ADD_(scheme);
                evbuffer_add(tmp, ":", 1);
        }
        if (uri->host) {
                evbuffer_add(tmp, "//", 2);
                if (uri->userinfo)
                        evbuffer_add_printf(tmp,"%s@", uri->userinfo);
-               _URI_ADD(host);
+               URI_ADD_(host);
                if (uri->port >= 0)
                        evbuffer_add_printf(tmp,":%d", uri->port);
 
@@ -4482,16 +4529,16 @@ evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit)
        }
 
        if (uri->path)
-               _URI_ADD(path);
+               URI_ADD_(path);
 
        if (uri->query) {
                evbuffer_add(tmp, "?", 1);
-               _URI_ADD(query);
+               URI_ADD_(query);
        }
 
        if (uri->fragment) {
                evbuffer_add(tmp, "#", 1);
-               _URI_ADD(fragment);
+               URI_ADD_(fragment);
        }
 
        evbuffer_add(tmp, "\0", 1); /* NUL */
@@ -4510,7 +4557,7 @@ err:
        evbuffer_free(tmp);
 
        return output;
-#undef _URI_ADD
+#undef URI_ADD_
 }
 
 const char *
@@ -4549,7 +4596,7 @@ evhttp_uri_get_fragment(const struct evhttp_uri *uri)
        return uri->fragment;
 }
 
-#define _URI_SET_STR(f) do {                                   \
+#define URI_SET_STR_(f) do {                                   \
        if (uri->f)                                             \
                mm_free(uri->f);                                \
        if (f) {                                                \
@@ -4568,7 +4615,7 @@ evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme)
        if (scheme && !scheme_ok(scheme, scheme+strlen(scheme)))
                return -1;
 
-       _URI_SET_STR(scheme);
+       URI_SET_STR_(scheme);
        return 0;
 }
 int
@@ -4576,7 +4623,7 @@ evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo)
 {
        if (userinfo && !userinfo_ok(userinfo, userinfo+strlen(userinfo)))
                return -1;
-       _URI_SET_STR(userinfo);
+       URI_SET_STR_(userinfo);
        return 0;
 }
 int
@@ -4592,7 +4639,7 @@ evhttp_uri_set_host(struct evhttp_uri *uri, const char *host)
                }
        }
 
-       _URI_SET_STR(host);
+       URI_SET_STR_(host);
        return 0;
 }
 int
@@ -4612,7 +4659,7 @@ evhttp_uri_set_path(struct evhttp_uri *uri, const char *path)
        if (path && end_of_cpath(path, PART_PATH, uri->flags) != path+strlen(path))
                return -1;
 
-       _URI_SET_STR(path);
+       URI_SET_STR_(path);
        return 0;
 }
 int
@@ -4620,7 +4667,7 @@ evhttp_uri_set_query(struct evhttp_uri *uri, const char *query)
 {
        if (query && end_of_cpath(query, PART_QUERY, uri->flags) != query+strlen(query))
                return -1;
-       _URI_SET_STR(query);
+       URI_SET_STR_(query);
        return 0;
 }
 int
@@ -4628,6 +4675,6 @@ evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment)
 {
        if (fragment && end_of_cpath(fragment, PART_FRAGMENT, uri->flags) != fragment+strlen(fragment))
                return -1;
-       _URI_SET_STR(fragment);
+       URI_SET_STR_(fragment);
        return 0;
 }
index fbf459ebb7c707746d4c75376b04c7f14d752382..5153db27cf49ac4d2422253f68fc77da7e6f40c0 100644 (file)
@@ -1,3 +1,9 @@
+# include/Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
 AUTOMAKE_OPTIONS = foreign
 
 EVENT2_EXPORT = \
similarity index 88%
rename from sntp/libevent/evdns.h
rename to sntp/libevent/include/evdns.h
index f5aa91c40e549b7084e396e5a50dc8985e03b6ed..8672db03698fb22b994e89e093bfba9d2d265c59 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVDNS_H_
-#define _EVDNS_H_
+#ifndef EVENT1_EVDNS_H_INCLUDED_
+#define EVENT1_EVDNS_H_INCLUDED_
 
 /** @file evdns.h
 
@@ -33,7 +33,7 @@
 
   The <evdns.h> header is deprecated in Libevent 2.0 and later; please
   use <event2/evdns.h> instead.  Depending on what functionality you
-  need, you may also want to include more of the other event2/*.h
+  need, you may also want to include more of the other <event2/...>
   headers.
  */
 
@@ -42,4 +42,4 @@
 #include <event2/dns_compat.h>
 #include <event2/dns_struct.h>
 
-#endif /* _EVDNS_H_ */
+#endif /* EVENT1_EVDNS_H_INCLUDED_ */
similarity index 91%
rename from sntp/libevent/event.h
rename to sntp/libevent/include/event.h
index cf59a0f237809fcf7739872ec27001371a769992..3a1b0c2c0e435cf6fd7a371b8a861bc99757d99d 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT_H_
-#define _EVENT_H_
+#ifndef EVENT1_EVENT_H_INCLUDED_
+#define EVENT1_EVENT_H_INCLUDED_
 
 /** @file event.h
 
@@ -42,13 +42,13 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#ifdef _EVENT_HAVE_STDINT_H
+#ifdef EVENT__HAVE_STDINT_H
 #include <stdint.h>
 #endif
 #include <stdarg.h>
@@ -82,4 +82,4 @@ typedef unsigned short u_short;
 }
 #endif
 
-#endif /* _EVENT_H_ */
+#endif /* EVENT1_EVENT_H_INCLUDED_ */
index 66cd3d13c0e7dfeee529009e938689495998a32d..ad0013fc6435191fed07db614a959a60315fb46d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_BUFFER_H_
-#define _EVENT2_BUFFER_H_
+#ifndef EVENT2_BUFFER_H_INCLUDED_
+#define EVENT2_BUFFER_H_INCLUDED_
 
 /** @file event2/buffer.h
 
@@ -78,10 +78,10 @@ extern "C" {
 
 #include <event2/event-config.h>
 #include <stdarg.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_UIO_H
+#ifdef EVENT__HAVE_SYS_UIO_H
 #include <sys/uio.h>
 #endif
 #include <event2/util.h>
@@ -93,7 +93,7 @@ extern "C" {
    @see event2/event.h for more information
 */
 struct evbuffer
-#ifdef _EVENT_IN_DOXYGEN
+#ifdef EVENT_IN_DOXYGEN_
 {}
 #endif
 ;
@@ -124,7 +124,7 @@ struct evbuffer_ptr {
        struct {
                void *chain;
                size_t pos_in_chain;
-       } _internal;
+       } internal_;
 };
 
 /** Describes a single extent of memory inside an evbuffer.  Used for
@@ -132,10 +132,10 @@ struct evbuffer_ptr {
 
     @see evbuffer_reserve_space, evbuffer_commit_space, evbuffer_peek
  */
-#ifdef _EVENT_HAVE_SYS_UIO_H
+#ifdef EVENT__HAVE_SYS_UIO_H
 #define evbuffer_iovec iovec
 /* Internal use -- defined only if we are using the native struct iovec */
-#define _EVBUFFER_IOVEC_IS_NATIVE
+#define EVBUFFER_IOVEC_IS_NATIVE_
 #else
 struct evbuffer_iovec {
        /** The start of the extent of memory. */
@@ -152,7 +152,6 @@ struct evbuffer_iovec {
        occurred
  */
 struct evbuffer *evbuffer_new(void);
-
 /**
   Deallocate storage for an evbuffer.
 
@@ -186,6 +185,41 @@ void evbuffer_lock(struct evbuffer *buf);
 */
 void evbuffer_unlock(struct evbuffer *buf);
 
+
+/** If this flag is set, then we will not use evbuffer_peek(),
+ * evbuffer_remove(), evbuffer_remove_buffer(), and so on to read bytes
+ * from this buffer: we'll only take bytes out of this buffer by
+ * writing them to the network (as with evbuffer_write_atmost), by
+ * removing them without observing them (as with evbuffer_drain),
+ * or by copying them all out at once (as with evbuffer_add_buffer).
+ *
+ * Using this option allows the implementation to use sendfile-based
+ * operations for evbuffer_add_file(); see that function for more
+ * information.
+ *
+ * This flag is on by default for bufferevents that can take advantage
+ * of it; you should never actually need to set it on a bufferevent's
+ * output buffer.
+ */
+#define EVBUFFER_FLAG_DRAINS_TO_FD 1
+
+/** Change the flags that are set for an evbuffer by adding more.
+ *
+ * @param buffer the evbuffer that the callback is watching.
+ * @param cb the callback whose status we want to change.
+ * @param flags One or more EVBUFFER_FLAG_* options
+ * @return 0 on success, -1 on failure.
+ */
+int evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags);
+/** Change the flags that are set for an evbuffer by removing some.
+ *
+ * @param buffer the evbuffer that the callback is watching.
+ * @param cb the callback whose status we want to change.
+ * @param flags One or more EVBUFFER_FLAG_* options
+ * @return 0 on success, -1 on failure.
+ */
+int evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags);
+
 /**
   Returns the total number of bytes stored in the evbuffer
 
@@ -318,6 +352,20 @@ int evbuffer_remove(struct evbuffer *buf, void *data, size_t datlen);
  */
 ev_ssize_t evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen);
 
+/**
+  Read data from the middle of an evbuffer, and leave the buffer unchanged.
+
+  If more bytes are requested than are available in the evbuffer, we
+  only extract as many bytes as were available.
+
+  @param buf the evbuffer to be read from
+  @param pos the position to start reading from
+  @param data_out the destination buffer to store the result
+  @param datlen the maximum size of the destination buffer
+  @return the number of bytes read, or -1 if we can't drain the buffer.
+ */
+ev_ssize_t evbuffer_copyout_from(struct evbuffer *buf, const struct evbuffer_ptr *pos, void *data_out, size_t datlen);
+
 /**
   Read data from an evbuffer into another evbuffer, draining
   the bytes from the source buffer.  This function avoids copy
@@ -353,7 +401,9 @@ enum evbuffer_eol_style {
        /** An EOL is a CR followed by an LF. */
        EVBUFFER_EOL_CRLF_STRICT,
        /** An EOL is a LF. */
-       EVBUFFER_EOL_LF
+       EVBUFFER_EOL_LF,
+       /** An EOL is a NUL character (that is, a single byte with value 0) */
+       EVBUFFER_EOL_NUL
 };
 
 /**
@@ -387,6 +437,22 @@ char *evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
  */
 int evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf);
 
+/**
+  Copy data from one evbuffer into another evbuffer.
+  
+  This is a non-destructive add.  The data from one buffer is copied
+  into the other buffer.  However, no unnecessary memory copies occur.
+  
+  Note that buffers already containing buffer references can't be added
+  to other buffers.
+  
+  @param outbuf the output buffer
+  @param inbuf the input buffer
+  @return 0 if successful, or -1 if an error occurred
+ */
+int evbuffer_add_buffer_reference(struct evbuffer *outbuf,
+    struct evbuffer *inbuf);
+
 /**
    A cleanup function for a piece of memory added to an evbuffer by
    reference.
@@ -419,8 +485,9 @@ int evbuffer_add_reference(struct evbuffer *outbuf,
   Copy data from a file into the evbuffer for writing to a socket.
 
   This function avoids unnecessary data copies between userland and
-  kernel.  Where available, it uses sendfile or splice; failing those,
-  it tries to use mmap.
+  kernel.  If sendfile is available and the EVBUFFER_FLAG_DRAINS_TO_FD
+  flag is set, it uses those functions.  Otherwise, it tries to use
+  mmap (or CreateFileMapping on Windows).
 
   The function owns the resulting file descriptor and will close it
   when finished transferring data.
@@ -712,8 +779,10 @@ struct evbuffer_ptr evbuffer_search_eol(struct evbuffer *buffer,
     the buffer does not have as much data as you asked to see).
 
     @param buffer the evbuffer to peek into,
-    @param len the number of bytes to try to peek.  If negative, we
-       will try to fill as much of vec_out as we can.
+    @param len the number of bytes to try to peek.  If len is negative, we
+       will try to fill as much of vec_out as we can.  If len is negative
+       and vec_out is not provided, we return the number of evbuffer_iovecs
+       that would be needed to get all the data in the buffer.
     @param start_at an evbuffer_ptr indicating the point at which we
        should start looking for data.  NULL means, "At the start of the
        buffer."
@@ -915,8 +984,23 @@ struct event_base;
  */
 int evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base);
 
+/**
+  Append data from 1 or more iovec's to an evbuffer
+
+  Calculates the number of bytes needed for an iovec structure and guarantees
+  all data will fit into a single chain. Can be used in lieu of functionality
+  which calls evbuffer_add() constantly before being used to increase
+  performance.
+
+  @param buffer the destination buffer
+  @param vec the source iovec
+  @param n_vec the number of iovec structures.
+  @return the number of bytes successfully written to the output buffer.
+*/
+size_t evbuffer_add_iovec(struct evbuffer * buffer, struct evbuffer_iovec * vec, int n_vec);
+
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* _EVENT2_BUFFER_H_ */
+#endif /* EVENT2_BUFFER_H_INCLUDED_ */
index 65e1c82d92b398ba85510eb2475a3e263c3e6b7f..c155332e4e1db4a891581ca58d8c40dc6f017ee6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef _EVENT2_BUFFER_COMPAT_H_
-#define _EVENT2_BUFFER_COMPAT_H_
+#ifndef EVENT2_BUFFER_COMPAT_H_INCLUDED_
+#define EVENT2_BUFFER_COMPAT_H_INCLUDED_
 
 /** @file event2/buffer_compat.h
 
index dac988e33ee83ba6e3e3da6452059d2318a8c93b..9e65873f501da956a2569e23ec5b328e356986ac 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_BUFFEREVENT_H_
-#define _EVENT2_BUFFEREVENT_H_
+#ifndef EVENT2_BUFFEREVENT_H_INCLUDED_
+#define EVENT2_BUFFEREVENT_H_INCLUDED_
 
 /**
    @file event2/bufferevent.h
@@ -79,10 +79,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -109,7 +109,7 @@ extern "C" {
    @see event2/bufferevent.h
  */
 struct bufferevent
-#ifdef _EVENT_IN_DOXYGEN
+#ifdef EVENT_IN_DOXYGEN_
 {}
 #endif
 ;
@@ -277,6 +277,9 @@ int bufferevent_priority_set(struct bufferevent *bufev, int pri);
 /**
   Deallocate the storage associated with a bufferevent structure.
 
+  If there is pending data to write on the bufferevent, it probably won't be
+  flushed before the bufferevent is freed.
+
   @param bufev the bufferevent structure to be freed.
   */
 void bufferevent_free(struct bufferevent *bufev);
@@ -300,6 +303,26 @@ void bufferevent_setcb(struct bufferevent *bufev,
     bufferevent_data_cb readcb, bufferevent_data_cb writecb,
     bufferevent_event_cb eventcb, void *cbarg);
 
+/**
+ Retrieves the callbacks for a bufferevent.
+
+ @param bufev the bufferevent to examine.
+ @param readcb_ptr if readcb_ptr is nonnull, *readcb_ptr is set to the current
+    read callback for the bufferevent.
+ @param writecb_ptr if writecb_ptr is nonnull, *writecb_ptr is set to the
+    current write callback for the bufferevent.
+ @param eventcb_ptr if eventcb_ptr is nonnull, *eventcb_ptr is set to the
+    current event callback for the bufferevent.
+ @param cbarg_ptr if cbarg_ptr is nonnull, *cbarg_ptr is set to the current
+    callback argument for the bufferevent.
+ @see buffervent_setcb()
+*/
+void bufferevent_getcb(struct bufferevent *bufev,
+    bufferevent_data_cb *readcb_ptr,
+    bufferevent_data_cb *writecb_ptr,
+    bufferevent_event_cb *eventcb_ptr,
+    void **cbarg_ptr);
+
 /**
   Changes the file descriptor on which the bufferevent operates.
   Not supported for all bufferevent types.
@@ -724,6 +747,30 @@ int bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
 /** Remove 'bev' from its current rate-limit group (if any). */
 int bufferevent_remove_from_rate_limit_group(struct bufferevent *bev);
 
+/**
+   Set the size limit for single read operation.
+
+   Set to 0 for a reasonable default.
+
+   Return 0 on success and -1 on failure.
+ */
+int bufferevent_set_max_single_read(struct bufferevent *bev, size_t size);
+
+/**
+   Set the size limit for single write operation.
+
+   Set to 0 for a reasonable default.
+
+   Return 0 on success and -1 on failure.
+ */
+int bufferevent_set_max_single_write(struct bufferevent *bev, size_t size);
+
+/** Get the current size limit for single read operation. */
+ev_ssize_t bufferevent_get_max_single_read(struct bufferevent *bev);
+
+/** Get the current size limit for single write operation. */
+ev_ssize_t bufferevent_get_max_single_write(struct bufferevent *bev);
+
 /**
    @name Rate limit inspection
 
@@ -743,7 +790,7 @@ ev_ssize_t bufferevent_get_max_to_read(struct bufferevent *bev);
 ev_ssize_t bufferevent_get_max_to_write(struct bufferevent *bev);
 
 /**
-   @name GrouprRate limit inspection
+   @name Group Rate limit inspection
 
    Return the read or write bucket size for a bufferevent rate limit
    group.  Note that it can return a negative value if bufferevents in
@@ -818,4 +865,4 @@ bufferevent_rate_limit_group_reset_totals(
 }
 #endif
 
-#endif /* _EVENT2_BUFFEREVENT_H_ */
+#endif /* EVENT2_BUFFEREVENT_H_INCLUDED_ */
index 6064a40fe650dbdfd6f109da9b6ee029fcaab92e..65482042f9d16b3f382aa2551162a53bbc312438 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos, Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos, Nick Mathewson
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
  * All rights reserved.
  *
@@ -25,8 +25,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_BUFFEREVENT_COMPAT_H_
-#define _EVENT2_BUFFEREVENT_COMPAT_H_
+#ifndef EVENT2_BUFFEREVENT_COMPAT_H_INCLUDED_
+#define EVENT2_BUFFEREVENT_COMPAT_H_INCLUDED_
 
 #define evbuffercb bufferevent_data_cb
 #define everrorcb bufferevent_event_cb
index 12f00d63680fd695f4fe40357aeb74b052e1bf60..2b7e614173be2c866b18e69087bd8861ea3fe226 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_BUFFEREVENT_SSL_H_
-#define _EVENT2_BUFFEREVENT_SSL_H_
+#ifndef EVENT2_BUFFEREVENT_SSL_H_INCLUDED_
+#define EVENT2_BUFFEREVENT_SSL_H_INCLUDED_
 
 /** @file event2/bufferevent_ssl.h
 
@@ -52,7 +52,7 @@ enum bufferevent_ssl_state {
        BUFFEREVENT_SSL_ACCEPTING = 2
 };
 
-#if defined(_EVENT_HAVE_OPENSSL) || defined(_EVENT_IN_DOXYGEN)
+#if defined(EVENT__HAVE_OPENSSL) || defined(EVENT_IN_DOXYGEN_)
 /**
    Create a new SSL bufferevent to send its data over another bufferevent.
 
@@ -88,6 +88,26 @@ bufferevent_openssl_socket_new(struct event_base *base,
     enum bufferevent_ssl_state state,
     int options);
 
+/** Control how to report dirty SSL shutdowns.
+
+    If the peer (or the network, or an attacker) closes the TCP
+    connection before closing the SSL channel, and the protocol is SSL >= v3,
+    this is a "dirty" shutdown.  If allow_dirty_shutdown is 0 (default),
+    this is reported as BEV_EVENT_ERROR.
+
+    If instead allow_dirty_shutdown=1, a dirty shutdown is reported as
+    BEV_EVENT_EOF.
+
+    (Note that if the protocol is < SSLv3, you will always receive
+    BEV_EVENT_EOF, since SSL 2 and earlier cannot distinguish a secure
+    connection close from a dirty one.  This is one reason (among many)
+    not to use SSL 2.)
+*/
+
+int bufferevent_openssl_get_allow_dirty_shutdown(struct bufferevent *bev);
+void bufferevent_openssl_set_allow_dirty_shutdown(struct bufferevent *bev,
+    int allow_dirty_shutdown);
+
 /** Return the underlying openssl SSL * object for an SSL bufferevent. */
 struct ssl_st *
 bufferevent_openssl_get_ssl(struct bufferevent *bufev);
@@ -104,4 +124,4 @@ unsigned long bufferevent_get_openssl_error(struct bufferevent *bev);
 }
 #endif
 
-#endif /* _EVENT2_BUFFEREVENT_SSL_H_ */
+#endif /* EVENT2_BUFFEREVENT_SSL_H_INCLUDED_ */
index d4a0a067279ace13ca32b3f0ac83ead8044de37c..e84c082c30cc9066735e280f5a7482e668dcc844 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_BUFFEREVENT_STRUCT_H_
-#define _EVENT2_BUFFEREVENT_STRUCT_H_
+#ifndef EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_
+#define EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_
 
 /** @file event2/bufferevent_struct.h
 
@@ -42,10 +42,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -113,4 +113,4 @@ struct bufferevent {
 }
 #endif
 
-#endif /* _EVENT2_BUFFEREVENT_STRUCT_H_ */
+#endif /* EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_ */
index be726faa4e2f833799f18236ecda9c99caa8b330..e4accf21e63a250192d3dabca1d1f27024253f89 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * with the next probe.
  */
 
-#ifndef _EVENT2_DNS_H_
-#define _EVENT2_DNS_H_
+#ifndef EVENT2_DNS_H_INCLUDED_
+#define EVENT2_DNS_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -166,6 +166,10 @@ extern "C" {
 #define DNS_ERR_SHUTDOWN 68
 /** The request was canceled via a call to evdns_cancel_request */
 #define DNS_ERR_CANCEL 69
+/** There were no answers and no error condition in the DNS packet.
+ * This can happen when you ask for an address that exists, but a record
+ * type that doesn't. */
+#define DNS_ERR_NODATA 70
 
 #define DNS_IPv4_A 1
 #define DNS_PTR 2
@@ -206,7 +210,7 @@ struct event_base;
 
   @param event_base the event base to associate the dns client with
   @param initialize_nameservers 1 if resolve.conf processing should occur
-  @return 0 if successful, or -1 if an error occurred
+  @return evdns_base object if successful, or NULL if an error occurred.
   @see evdns_base_free()
  */
 struct evdns_base * evdns_base_new(struct event_base *event_base, int initialize_nameservers);
@@ -266,7 +270,7 @@ int evdns_base_count_nameservers(struct evdns_base *base);
 /**
   Remove all configured nameservers, and suspend all pending resolves.
 
-  Resolves will not necessarily be re-attempted until evdns_resume() is called.
+  Resolves will not necessarily be re-attempted until evdns_base_resume() is called.
 
   @param base the evdns_base to which to apply this operation
   @return 0 if successful, or -1 if an error occurred
@@ -279,7 +283,7 @@ int evdns_base_clear_nameservers_and_suspend(struct evdns_base *base);
   Resume normal operation and continue any suspended resolve requests.
 
   Re-attempt resolves left in limbo after an earlier call to
-  evdns_clear_nameservers_and_suspend().
+  evdns_base_clear_nameservers_and_suspend().
 
   @param base the evdns_base to which to apply this operation
   @return 0 if successful, or -1 if an error occurred
@@ -597,7 +601,7 @@ struct sockaddr;
 /**
     Get the address that made a DNS request.
  */
-int evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len);
+int evdns_server_request_get_requesting_addr(struct evdns_server_request *req, struct sockaddr *sa, int addr_len);
 
 /** Callback for evdns_getaddrinfo. */
 typedef void (*evdns_getaddrinfo_cb)(int result, struct evutil_addrinfo *res, void *arg);
@@ -636,4 +640,4 @@ void evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *req);
 }
 #endif
 
-#endif  /* !_EVENT2_DNS_H_ */
+#endif  /* !EVENT2_DNS_H_INCLUDED_ */
index 14dfb4973ef332c28554c635826b2a9ad4347dc1..965fd65445b476696702df665afae660b6759ecb 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_DNS_COMPAT_H_
-#define _EVENT2_DNS_COMPAT_H_
+#ifndef EVENT2_DNS_COMPAT_H_INCLUDED_
+#define EVENT2_DNS_COMPAT_H_INCLUDED_
 
 /** @file event2/dns_compat.h
 
@@ -40,10 +40,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -333,4 +333,4 @@ int evdns_config_windows_nameservers(void);
 }
 #endif
 
-#endif /* _EVENT2_EVENT_COMPAT_H_ */
+#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
index 0eefd40e919207e82354d5524b1da951a55006f3..593a8a70b649e1ab3b41ba33da942340a2c0159e 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_DNS_STRUCT_H_
-#define _EVENT2_DNS_STRUCT_H_
+#ifndef EVENT2_DNS_STRUCT_H_INCLUDED_
+#define EVENT2_DNS_STRUCT_H_INCLUDED_
 
 /** @file event2/dns_struct.h
 
@@ -39,10 +39,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -76,5 +76,5 @@ struct evdns_server_question {
 }
 #endif
 
-#endif /* _EVENT2_DNS_STRUCT_H_ */
+#endif /* EVENT2_DNS_STRUCT_H_INCLUDED_ */
 
index fae5bb87a8acdb114f583117955acd51c0650165..cf358c03f712cff7a2bc030679d799978e1a6363 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_EVENT_H_
-#define _EVENT2_EVENT_H_
+#ifndef EVENT2_EVENT_H_INCLUDED_
+#define EVENT2_EVENT_H_INCLUDED_
 
 /**
    @mainpage
@@ -185,10 +185,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -211,7 +211,7 @@ extern "C" {
  *    event_base_new_with_config()
  */
 struct event_base
-#ifdef _EVENT_IN_DOXYGEN
+#ifdef EVENT_IN_DOXYGEN_
 {/*Empty body so that doxygen will generate documentation here.*/}
 #endif
 ;
@@ -270,7 +270,7 @@ struct event_base
  *    event_priority_set()
  */
 struct event
-#ifdef _EVENT_IN_DOXYGEN
+#ifdef EVENT_IN_DOXYGEN_
 {/*Empty body so that doxygen will generate documentation here.*/}
 #endif
 ;
@@ -289,7 +289,7 @@ struct event
  *   event_config_set_flag(), event_config_set_num_cpus_hint()
  */
 struct event_config
-#ifdef _EVENT_IN_DOXYGEN
+#ifdef EVENT_IN_DOXYGEN_
 {/*Empty body so that doxygen will generate documentation here.*/}
 #endif
 ;
@@ -450,7 +450,11 @@ enum event_method_feature {
  */
 enum event_base_config_flag {
        /** Do not allocate a lock for the event base, even if we have
-           locking set up. */
+           locking set up.
+
+           Setting this option will make it unsafe and nonfunctional to call
+           functions on the base concurrently from multiple threads.
+       */
        EVENT_BASE_FLAG_NOLOCK = 0x01,
        /** Do not check the EVENT_* environment variables when configuring
            an event_base  */
@@ -481,7 +485,14 @@ enum event_base_config_flag {
            This flag has no effect if you wind up using a backend other than
            epoll.
         */
-       EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST = 0x10
+       EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST = 0x10,
+
+       /** Ordinarily, Libevent implements its time and timeout code using
+           the fastest monotonic timer that we have.  If this flag is set,
+           however, we use less efficient more precise timer, assuming one is
+           present.
+        */
+       EVENT_BASE_FLAG_PRECISE_TIMER = 0x20
 };
 
 /**
@@ -595,12 +606,19 @@ void event_base_free(struct event_base *);
 /** @name Log severities
  */
 /**@{*/
-#define _EVENT_LOG_DEBUG 0
-#define _EVENT_LOG_MSG   1
-#define _EVENT_LOG_WARN  2
-#define _EVENT_LOG_ERR   3
+#define EVENT_LOG_DEBUG 0
+#define EVENT_LOG_MSG   1
+#define EVENT_LOG_WARN  2
+#define EVENT_LOG_ERR   3
 /**@}*/
 
+/* Obsolete names: these are deprecated, but older programs might use them.
+ * They violate the reserved-identifier namespace. */
+#define _EVENT_LOG_DEBUG EVENT_LOG_DEBUG
+#define _EVENT_LOG_MSG EVENT_LOG_MSG
+#define _EVENT_LOG_WARN EVENT_LOG_WARN
+#define _EVENT_LOG_ERR EVENT_LOG_ERR
+
 /**
   A callback function used to intercept Libevent's log messages.
 
@@ -611,7 +629,7 @@ typedef void (*event_log_cb)(int severity, const char *msg);
   Redirect Libevent's log messages.
 
   @param cb a function taking two arguments: an integer severity between
-     _EVENT_LOG_DEBUG and _EVENT_LOG_ERR, and a string.  If cb is NULL,
+     EVENT_LOG_DEBUG and EVENT_LOG_ERR, and a string.  If cb is NULL,
         then the default log is used.
 
   NOTE: The function you provide *must not* call any other libevent
@@ -635,11 +653,30 @@ typedef void (*event_fatal_cb)(int err);
  something is wrong with your program, or with Libevent: any subsequent calls
  to Libevent may result in undefined behavior.
 
- Libevent will (almost) always log an _EVENT_LOG_ERR message before calling
+ Libevent will (almost) always log an EVENT_LOG_ERR message before calling
  this function; look at the last log message to see why Libevent has died.
  */
 void event_set_fatal_callback(event_fatal_cb cb);
 
+#define EVENT_DBG_ALL 0xffffffffu
+#define EVENT_DBG_NONE 0
+
+/**
+ Turn on debugging logs and have them sent to the default log handler.
+
+ This is a global setting; if you are going to call it, you must call this
+ before any calls that create an event-base.  You must call it before any
+ multithreaded use of Libevent.
+
+ Debug logs are verbose.
+
+ @param which Controls which debug messages are turned on.  This option is
+   unused for now; for forward compatibility, you must pass in the constant
+   "EVENT_DBG_ALL" to turn debugging logs on, or "EVENT_DBG_NONE" to turn
+   debugging logs off.
+ */
+void event_enable_debug_logging(ev_uint32_t which);
+
 /**
   Associate a different event base with an event.
 
@@ -662,6 +699,11 @@ int event_base_set(struct event_base *, struct event *);
 /** Do not block: see which events are ready now, run the callbacks
  * of the highest-priority ones, then exit. */
 #define EVLOOP_NONBLOCK        0x02
+/** Do not exit the loop because we have no pending events.  Instead, keep
+ * running until event_base_loopexit() or event_base_loopbreak() makes us
+ * stop.
+ */
+#define EVLOOP_NO_EXIT_ON_EMPTY 0x04
 /**@}*/
 
 /**
@@ -814,6 +856,30 @@ int event_base_got_break(struct event_base *);
  */
 typedef void (*event_callback_fn)(evutil_socket_t, short, void *);
 
+/**
+  Return a value used to specify that the event itself must be used as the callback argument.
+
+  The function event_new() takes a callback argument which is passed
+  to the event's callback function. To specify that the argument to be
+  passed to the callback function is the event that event_new() returns,
+  pass in the return value of event_self_cbarg() as the callback argument
+  for event_new().
+
+  For example:
+  <pre>
+      struct event *ev = event_new(base, sock, events, callback, %event_self_cbarg());
+  </pre>
+
+  For consistency with event_new(), it is possible to pass the return value
+  of this function as the callback argument for event_assign() &ndash; this
+  achieves the same result as passing the event in directly.
+
+  @return a value to be passed as the callback argument to event_new() or
+  event_assign().
+  @see event_new(), event_assign()
+ */
+void *event_self_cbarg(void);
+
 /**
   Allocate and asssign a new event structure, ready to be added.
 
@@ -1006,6 +1072,13 @@ void event_active(struct event *ev, int res, short ncalls);
  */
 int event_pending(const struct event *ev, short events, struct timeval *tv);
 
+/**
+   If called from within the callback for an event, returns that event.
+
+   The behavior of this function is not defined when called from outside the
+   callback function for an event.
+ */
+struct event *event_base_get_running_event(struct event_base *base);
 
 /**
   Test if an event structure might be initialized.
@@ -1106,10 +1179,10 @@ const char *event_get_version(void);
 ev_uint32_t event_get_version_number(void);
 
 /** As event_get_version, but gives the version of Libevent's headers. */
-#define LIBEVENT_VERSION _EVENT_VERSION
+#define LIBEVENT_VERSION EVENT__VERSION
 /** As event_get_version_number, but gives the version number of Libevent's
  * headers. */
-#define LIBEVENT_VERSION_NUMBER _EVENT_NUMERIC_VERSION
+#define LIBEVENT_VERSION_NUMBER EVENT__NUMERIC_VERSION
 
 /** Largest number of priorities that Libevent can support. */
 #define EVENT_MAX_PRIORITIES 256
@@ -1142,6 +1215,15 @@ ev_uint32_t event_get_version_number(void);
  */
 int    event_base_priority_init(struct event_base *, int);
 
+/**
+  Get the number of different event priorities.
+
+  @param eb the event_base structure returned by event_base_new()
+  @return Number of different event priorities
+  @see event_base_priority_init()
+*/
+int    event_base_get_npriorities(struct event_base *eb);
+
 /**
   Assign a priority to an event.
 
@@ -1174,7 +1256,7 @@ int       event_priority_set(struct event *, int);
 const struct timeval *event_base_init_common_timeout(struct event_base *base,
     const struct timeval *duration);
 
-#if !defined(_EVENT_DISABLE_MM_REPLACEMENT) || defined(_EVENT_IN_DOXYGEN)
+#if !defined(EVENT__DISABLE_MM_REPLACEMENT) || defined(EVENT_IN_DOXYGEN_)
 /**
  Override the functions that Libevent uses for memory management.
 
@@ -1206,6 +1288,16 @@ void event_set_mem_functions(
 #define EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
 #endif
 
+/**
+   Writes a human-readable description of all inserted and/or active
+   events to a provided stdio stream.
+
+   This is intended for debugging; its format is not guaranteed to be the same
+   between libevent versions.
+
+   @param base An event_base on which to scan the events.
+   @param output A stdio file to write on.
+ */
 void event_base_dump_events(struct event_base *, FILE *);
 
 /** Sets 'tv' to the current time (as returned by gettimeofday()),
@@ -1222,8 +1314,38 @@ void event_base_dump_events(struct event_base *, FILE *);
 int event_base_gettimeofday_cached(struct event_base *base,
     struct timeval *tv);
 
+/** Update cached_tv in the 'base' to the current time
+ *
+ * You can use this function is useful for selectively increasing
+ * the accuracy of the cached time value in 'base' during callbacks
+ * that take a long time to execute.
+ *
+ * This function has no effect if the base is currently not in its
+ * event loop, or if timeval caching is disabled via
+ * EVENT_BASE_FLAG_NO_CACHE_TIME.
+ *
+ * @return 0 on success, -1 on failure
+ */
+int event_base_update_cache_time(struct event_base *base);
+
+/** Release up all globally-allocated resources allocated by Libevent.
+
+    This function does not free developer-controlled resources like
+    event_bases, events, bufferevents, listeners, and so on.  It only releases
+    resources like global locks that there is no other way to free.
+
+    It is not actually necessary to call this function before exit: every
+    resource that it frees would be released anyway on exit.  It mainly exists
+    so that resource-leak debugging tools don't see Libevent as holding
+    resources at exit.
+
+    You should only call this function when no other Libevent functions will
+    be invoked -- e.g., when cleanly exiting a program.
+ */
+void libevent_global_shutdown(void);
+
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* _EVENT2_EVENT_H_ */
+#endif /* EVENT2_EVENT_H_INCLUDED_ */
index cb77515400e4b094cda76e411b2beb34a1524972..87403a4d1d42a4f8883213ed0a804135ba8c19bc 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_EVENT_COMPAT_H_
-#define _EVENT2_EVENT_COMPAT_H_
+#ifndef EVENT2_EVENT_COMPAT_H_INCLUDED_
+#define EVENT2_EVENT_COMPAT_H_INCLUDED_
 
 /** @file event2/event_compat.h
 
@@ -47,10 +47,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -217,4 +217,4 @@ void event_set(struct event *, evutil_socket_t, short, void (*)(evutil_socket_t,
 }
 #endif
 
-#endif /* _EVENT2_EVENT_COMPAT_H_ */
+#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
index d3cfb0cca9bba916c6c5d98a8a310514b3905a40..44bb6f7e2646f6f6e3d36f5be7411a0965f52322 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_EVENT_STRUCT_H_
-#define _EVENT2_EVENT_STRUCT_H_
+#ifndef EVENT2_EVENT_STRUCT_H_INCLUDED_
+#define EVENT2_EVENT_STRUCT_H_INCLUDED_
 
 /** @file event2/event_struct.h
 
@@ -41,10 +41,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -66,7 +66,7 @@ extern "C" {
 
 /* Fix so that people don't have to run with <sys/queue.h> */
 #ifndef TAILQ_ENTRY
-#define _EVENT_DEFINED_TQENTRY
+#define EVENT_DEFINED_TQENTRY_
 #define TAILQ_ENTRY(type)                                              \
 struct {                                                               \
        struct type *tqe_next;  /* next element */                      \
@@ -75,7 +75,7 @@ struct {                                                              \
 #endif /* !TAILQ_ENTRY */
 
 #ifndef TAILQ_HEAD
-#define _EVENT_DEFINED_TQHEAD
+#define EVENT_DEFINED_TQHEAD_
 #define TAILQ_HEAD(name, type)                 \
 struct name {                                  \
        struct type *tqh_first;                 \
@@ -83,10 +83,20 @@ struct name {                                       \
 }
 #endif
 
+/* Fix so that people don't have to run with <sys/queue.h> */
+#ifndef LIST_ENTRY
+#define EVENT_DEFINED_LISTENTRY_
+#define LIST_ENTRY(type)                                               \
+struct {                                                               \
+       struct type *le_next;   /* next element */                      \
+       struct type **le_prev;  /* address of previous next element */  \
+}
+#endif /* !TAILQ_ENTRY */
+
 struct event_base;
 struct event {
        TAILQ_ENTRY(event) ev_active_next;
-       TAILQ_ENTRY(event) ev_next;
+
        /* for managing timeouts */
        union {
                TAILQ_ENTRY(event) ev_next_with_common_timeout;
@@ -99,18 +109,18 @@ struct event {
        union {
                /* used for io events */
                struct {
-                       TAILQ_ENTRY(event) ev_io_next;
+                       LIST_ENTRY (event) ev_io_next;
                        struct timeval ev_timeout;
                } ev_io;
 
                /* used by signal events */
                struct {
-                       TAILQ_ENTRY(event) ev_signal_next;
+                       LIST_ENTRY (event) ev_signal_next;
                        short ev_ncalls;
                        /* Allows deletes in callback */
                        short *ev_pncalls;
                } ev_signal;
-       } _ev;
+       } ev_;
 
        short ev_events;
        short ev_res;           /* result passed to event callback */
@@ -126,16 +136,24 @@ struct event {
 
 TAILQ_HEAD (event_list, event);
 
-#ifdef _EVENT_DEFINED_TQENTRY
+#ifdef EVENT_DEFINED_TQENTRY_
 #undef TAILQ_ENTRY
 #endif
 
-#ifdef _EVENT_DEFINED_TQHEAD
+#ifdef EVENT_DEFINED_TQHEAD_
 #undef TAILQ_HEAD
 #endif
 
+#ifdef EVENT_DEFINED_LISTENTRY_
+#undef LIST_ENTRY
+struct event_dlist;
+#undef EVENT_DEFINED_LISTENTRY_
+#else
+LIST_HEAD (event_dlist, event);
+#endif /* EVENT_DEFINED_LISTENTRY_ */
+
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* _EVENT2_EVENT_STRUCT_H_ */
+#endif /* EVENT2_EVENT_STRUCT_H_INCLUDED_ */
index e69ebf9eced0a3feeb09b56702fead80bde7e722..109b73b0e5b9da4f6d19722c7ade31f4617080ac 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_HTTP_H_
-#define _EVENT2_HTTP_H_
+#ifndef EVENT2_HTTP_H_INCLUDED_
+#define EVENT2_HTTP_H_INCLUDED_
 
 /* For int types. */
 #include <event2/util.h>
@@ -37,6 +37,7 @@ extern "C" {
 /* In case we haven't included the right headers yet. */
 struct evbuffer;
 struct event_base;
+struct bufferevent;
 
 /** @file event2/http.h
  *
@@ -69,6 +70,7 @@ struct evhttp_request;
 struct evkeyvalq;
 struct evhttp_bound_socket;
 struct evconnlistener;
+struct evdns_base;
 
 /**
  * Create a new HTTP server.
@@ -148,6 +150,19 @@ struct evhttp_bound_socket *evhttp_bind_listener(struct evhttp *http, struct evc
  */
 struct evconnlistener *evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound);
 
+typedef void evhttp_bound_socket_foreach_fn(struct evhttp_bound_socket *, void *);
+/**
+ * Applies the function specified in the first argument to all
+ * evhttp_bound_sockets associated with "http". The user must not
+ * attempt to free or remove any connections, sockets or listeners
+ * in the callback "function".
+ *
+ * @param http pointer to an evhttp object
+ * @param function function to apply to every bound socket
+ * @param argument pointer value passed to function for every socket iterated
+ */
+void evhttp_foreach_bound_socket(struct evhttp *http, evhttp_bound_socket_foreach_fn *function, void *argument);
+
 /**
  * Makes an HTTP server stop accepting connections on the specified socket
  *
@@ -233,6 +248,23 @@ int evhttp_del_cb(struct evhttp *, const char *);
 void evhttp_set_gencb(struct evhttp *http,
     void (*cb)(struct evhttp_request *, void *), void *arg);
 
+/**
+   Set a callback used to create new bufferevents for connections
+   to a given evhttp object.
+
+   You can use this to override the default bufferevent type -- for example,
+   to make this evhttp object use SSL bufferevents rather than unencrypted
+   ones.
+
+   New bufferevents must be allocated with no fd set on them.
+
+   @param http the evhttp server object for which to set the callback
+   @param cb the callback to invoke for incoming connections
+   @param arg an context argument for the callback
+ */
+void evhttp_set_bevcb(struct evhttp *http,
+    struct bufferevent *(*cb)(struct event_base *, void *), void *arg);
+
 /**
    Adds a virtual host to the http server.
 
@@ -365,7 +397,7 @@ void evhttp_send_reply_start(struct evhttp_request *req, int code,
 void evhttp_send_reply_chunk(struct evhttp_request *req,
     struct evbuffer *databuf);
 /**
-   Complete a chunked reply.
+   Complete a chunked reply, freeing the request as appropriate.
 
    @param req a request object
 */
@@ -397,6 +429,29 @@ enum evhttp_cmd_type {
 /** a request object can represent either a request or a reply */
 enum evhttp_request_kind { EVHTTP_REQUEST, EVHTTP_RESPONSE };
 
+/**
+ * Create and return a connection object that can be used to for making HTTP
+ * requests.  The connection object tries to resolve address and establish the
+ * connection when it is given an http request object.
+ *
+ * @param base the event_base to use for handling the connection
+ * @param dnsbase the dns_base to use for resolving host names; if not
+ *     specified host name resolution will block.
+ * @param bev a bufferevent to use for connecting to the server; if NULL, a
+ *     socket-based bufferevent will be created.  This buffrevent will be freed
+ *     when the connection closes.  It must have no fd set on it.
+ * @param address the address to which to connect
+ * @param port the port to connect to
+ * @return an evhttp_connection object that can be used for making requests
+ */
+struct evhttp_connection *evhttp_connection_base_bufferevent_new(
+       struct event_base *base, struct evdns_base *dnsbase, struct bufferevent* bev, const char *address, unsigned short port);
+
+/**
+ * Return the bufferevent that an evhttp_connection is using.
+ */
+struct bufferevent* evhttp_connection_get_bufferevent(struct evhttp_connection *evcon);
+
 /**
  * Creates a new request object that needs to be filled in with the request
  * parameters.  The callback is executed when the request completed or an
@@ -418,12 +473,10 @@ void evhttp_request_set_chunked_cb(struct evhttp_request *,
 /** Frees the request object and removes associated events. */
 void evhttp_request_free(struct evhttp_request *req);
 
-struct evdns_base;
-
 /**
- * A connection object that can be used to for making HTTP requests.  The
- * connection object tries to resolve address and establish the connection
- * when it is given an http request object.
+ * Create and return a connection object that can be used to for making HTTP
+ * requests.  The connection object tries to resolve address and establish the
+ * connection when it is given an http request object.
  *
  * @param base the event_base to use for handling the connection
  * @param dnsbase the dns_base to use for resolving host names; if not
@@ -485,6 +538,13 @@ void evhttp_connection_set_timeout(struct evhttp_connection *evcon,
 void evhttp_connection_set_timeout_tv(struct evhttp_connection *evcon,
     const struct timeval *tv);
 
+/** Sets the delay before retrying requests on this connection. This is only
+ * used if evhttp_connection_set_retries is used to make the number of retries
+ * at least one. Each retry after the first is twice as long as the one before
+ * it. */
+void evhttp_connection_set_initial_retry_tv(struct evhttp_connection *evcon,
+    const struct timeval *tv);
+
 /** Sets the retry limit for this connection - -1 repeats indefinitely */
 void evhttp_connection_set_retries(struct evhttp_connection *evcon,
     int retry_max);
@@ -867,4 +927,4 @@ char *evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit);
 }
 #endif
 
-#endif /* _EVENT2_HTTP_H_ */
+#endif /* EVENT2_HTTP_H_INCLUDED_ */
index 02a080beb712bcb0d035d3d664415da98596ee50..0d9af17f3feda103a0b9957a55589057e61b611a 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_HTTP_COMPAT_H_
-#define _EVENT2_HTTP_COMPAT_H_
+#ifndef EVENT2_HTTP_COMPAT_H_INCLUDED_
+#define EVENT2_HTTP_COMPAT_H_INCLUDED_
 
 /** @file event2/http_compat.h
 
@@ -39,10 +39,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -87,4 +87,4 @@ void evhttp_connection_set_base(struct evhttp_connection *evcon,
 }
 #endif
 
-#endif /* _EVENT2_EVENT_COMPAT_H_ */
+#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
index 3545fdf5b93983f4f4ac39745309cee996cbe19b..f245dff8ff65dff3c808e445e2339b74855583b3 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_HTTP_STRUCT_H_
-#define _EVENT2_HTTP_STRUCT_H_
+#ifndef EVENT2_HTTP_STRUCT_H_INCLUDED_
+#define EVENT2_HTTP_STRUCT_H_INCLUDED_
 
 /** @file event2/http_struct.h
 
@@ -39,10 +39,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -126,5 +126,5 @@ struct {
 }
 #endif
 
-#endif /* _EVENT2_HTTP_STRUCT_H_ */
+#endif /* EVENT2_HTTP_STRUCT_H_INCLUDED_ */
 
index 3390dd153877fcc7e9da56762c27aef099760755..bffa54b3a7668a1742a2d2ef3ac90b08c643cf99 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_EVENT_KEYVALQ_STRUCT_H_
-#define _EVENT2_EVENT_KEYVALQ_STRUCT_H_
+#ifndef EVENT2_KEYVALQ_STRUCT_H_INCLUDED_
+#define EVENT2_KEYVALQ_STRUCT_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -34,7 +34,7 @@ extern "C" {
 /* Fix so that people don't have to run with <sys/queue.h> */
 /* XXXX This code is duplicated with event_struct.h */
 #ifndef TAILQ_ENTRY
-#define _EVENT_DEFINED_TQENTRY
+#define EVENT_DEFINED_TQENTRY_
 #define TAILQ_ENTRY(type)                                              \
 struct {                                                               \
        struct type *tqe_next;  /* next element */                      \
@@ -43,7 +43,7 @@ struct {                                                              \
 #endif /* !TAILQ_ENTRY */
 
 #ifndef TAILQ_HEAD
-#define _EVENT_DEFINED_TQHEAD
+#define EVENT_DEFINED_TQHEAD_
 #define TAILQ_HEAD(name, type)                 \
 struct name {                                  \
        struct type *tqh_first;                 \
@@ -65,11 +65,11 @@ struct evkeyval {
 TAILQ_HEAD (evkeyvalq, evkeyval);
 
 /* XXXX This code is duplicated with event_struct.h */
-#ifdef _EVENT_DEFINED_TQENTRY
+#ifdef EVENT_DEFINED_TQENTRY_
 #undef TAILQ_ENTRY
 #endif
 
-#ifdef _EVENT_DEFINED_TQHEAD
+#ifdef EVENT_DEFINED_TQHEAD_
 #undef TAILQ_HEAD
 #endif
 
index 0cb8583ccdfa2b55d6c8bff2d64ed8c6e3471fc2..3ad52c52b6110322994f1b69ee355aab7a16d8e0 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_LISTENER_H_
-#define _EVENT2_LISTENER_H_
+#ifndef EVENT2_LISTENER_H_INCLUDED_
+#define EVENT2_LISTENER_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -69,6 +69,23 @@ typedef void (*evconnlistener_errorcb)(struct evconnlistener *, void *);
 /** Flag: Indicates that the listener should be locked so it's safe to use
  * from multiple threadcs at once. */
 #define LEV_OPT_THREADSAFE             (1u<<4)
+/** Flag: Indicates that the listener should be created in disabled
+ * state. Use evconnlistener_enable() to enable it later. */
+#define LEV_OPT_DISABLED               (1u<<5)
+/** Flag: Indicates that the listener should defer accept() until data is
+ * available, if possible.  Ignored on platforms that do not support this.
+ *
+ * This option can help performance for protocols where the client transmits
+ * immediately after connecting.  Do not use this option if your protocol
+ * _doesn't_ start out with the client transmitting data, since in that case
+ * this option will sometimes cause the kernel to never tell you about the
+ * connection.
+ *
+ * This option is only supported by evconnlistener_new_bind(): it can't
+ * work with evconnlistener_new_fd(), since the listener needs to be told
+ * to use the option before it is actually bound.
+ */
+#define LEV_OPT_DEFERRED_ACCEPT                (1u<<6)
 
 /**
    Allocate a new evconnlistener object to listen for incoming TCP connections
index 2fee4c2d1e4ea9bf2c59836be13665274dae25c6..dd43df266a179372c9baaae4579e8e3d3c2ef370 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_RPC_H_
-#define _EVENT2_RPC_H_
+#ifndef EVENT2_RPC_H_INCLUDED_
+#define EVENT2_RPC_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -76,7 +76,7 @@ extern "C" {
 #define EVTAG_HAS(msg, member) \
        ((msg)->member##_set == 1)
 
-#ifndef _EVENT2_RPC_COMPAT_H_
+#ifndef EVENT2_RPC_COMPAT_H_INCLUDED_
 
 /**
    Assigns a value to the member in the message.
@@ -119,7 +119,7 @@ extern "C" {
 #define EVTAG_GET_WITH_LEN(msg, member, pvalue, plen)  \
        (*(msg)->base->member##_get)((msg), (pvalue), (plen))
 
-#endif  /* _EVENT2_RPC_COMPAT_H_ */
+#endif  /* EVENT2_RPC_COMPAT_H_INCLUDED_ */
 
 /**
    Adds a value to an array.
@@ -272,8 +272,8 @@ void *evrpc_get_reply(struct evrpc_req_generic *req);
  * @param rpc_req the rpc request structure provided to the server callback
  */
 #define EVRPC_REQUEST_DONE(rpc_req) do { \
-  struct evrpc_req_generic *_req = (struct evrpc_req_generic *)(rpc_req); \
-  evrpc_request_done(_req);                                    \
+  struct evrpc_req_generic *req_ = (struct evrpc_req_generic *)(rpc_req); \
+  evrpc_request_done(req_);                                    \
 } while (0)
 
 
@@ -593,4 +593,4 @@ void evrpc_request_set_cb(struct evrpc_request_wrapper *ctx,
 }
 #endif
 
-#endif /* _EVENT2_RPC_H_ */
+#endif /* EVENT2_RPC_H_INCLUDED_ */
index 1f3b3a1fd5f0fe40732ce14040b374bfa020c379..8d8334d25f9de4215d2323bfa1a20a4c39d9a639 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_RPC_COMPAT_H_
-#define _EVENT2_RPC_COMPAT_H_
+#ifndef EVENT2_RPC_COMPAT_H_INCLUDED_
+#define EVENT2_RPC_COMPAT_H_INCLUDED_
 
 /** @file event2/rpc_compat.h
 
@@ -58,4 +58,4 @@ extern "C" {
 }
 #endif
 
-#endif /* _EVENT2_EVENT_COMPAT_H_ */
+#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
index 1345fb7430380a36018c22157ffd798f51b9efa4..8f691f49fbcdd912b902dab29f283245046e8456 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_RPC_STRUCT_H_
-#define _EVENT2_RPC_STRUCT_H_
+#ifndef EVENT2_RPC_STRUCT_H_INCLUDED_
+#define EVENT2_RPC_STRUCT_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -97,4 +97,4 @@ struct evrpc {
 }
 #endif
 
-#endif /* _EVENT2_RPC_STRUCT_H_ */
+#endif /* EVENT2_RPC_STRUCT_H_INCLUDED_ */
index 54ce8c65828c2fe6f97fc6631ced76d9a055858e..7632bd5897e8d7c992b5577a19ca50b09e994f60 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_TAG_H_
-#define _EVENT2_TAG_H_
+#ifndef EVENT2_TAG_H_INCLUDED_
+#define EVENT2_TAG_H_INCLUDED_
 
 /** @file event2/tag.h
 
@@ -38,10 +38,10 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
@@ -121,4 +121,4 @@ int evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
 }
 #endif
 
-#endif /* _EVENT2_TAG_H_ */
+#endif /* EVENT2_TAG_H_INCLUDED_ */
index 8a47e8a38ce514ae982231dfcd7ecd972e99199b..a276c0d35b6ec24ae89f80270ead612daaa86916 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_TAG_COMPAT_H_
-#define _EVENT2_TAG_COMPAT_H_
+#ifndef EVENT2_TAG_COMPAT_H_INCLUDED_
+#define EVENT2_TAG_COMPAT_H_INCLUDED_
 
 /** @file event2/tag_compat.h
 
@@ -46,4 +46,4 @@
 #define encode_int64(evbuf, number) evtag_encode_int64((evbuf), (number))
 /**@}*/
 
-#endif /* _EVENT2_TAG_H_ */
+#endif /* EVENT2_TAG_H_INCLUDED_ */
index 3e7216d1237f39317fdff4911929209521f9c937..cf21afe2596f212abf6f4ac4530f119647f441c9 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_THREAD_H_
-#define _EVENT2_THREAD_H_
+#ifndef EVENT2_THREAD_H_INCLUDED_
+#define EVENT2_THREAD_H_INCLUDED_
 
 /** @file event2/thread.h
 
@@ -69,7 +69,7 @@ extern "C" {
 #define EVTHREAD_TRY    0x10
 /**@}*/
 
-#if !defined(_EVENT_DISABLE_THREAD_SUPPORT) || defined(_EVENT_IN_DOXYGEN)
+#if !defined(EVENT__DISABLE_THREAD_SUPPORT) || defined(EVENT_IN_DOXYGEN_)
 
 #define EVTHREAD_LOCK_API_VERSION 1
 
@@ -187,7 +187,7 @@ int evthread_set_condition_callbacks(
 void evthread_set_id_callback(
     unsigned long (*id_fn)(void));
 
-#if (defined(_WIN32) && !defined(_EVENT_DISABLE_THREAD_SUPPORT)) || defined(_EVENT_IN_DOXYGEN)
+#if (defined(_WIN32) && !defined(EVENT__DISABLE_THREAD_SUPPORT)) || defined(EVENT_IN_DOXYGEN_)
 /** Sets up Libevent for use with Windows builtin locking and thread ID
     functions.  Unavailable if Libevent is not built for Windows.
 
@@ -199,7 +199,7 @@ int evthread_use_windows_threads(void);
 #define EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED 1
 #endif
 
-#if defined(_EVENT_HAVE_PTHREADS) || defined(_EVENT_IN_DOXYGEN)
+#if defined(EVENT__HAVE_PTHREADS) || defined(EVENT_IN_DOXYGEN_)
 /** Sets up Libevent for use with Pthreads locking and thread ID functions.
     Unavailable if Libevent is not build for use with pthreads.  Requires
     libraries to link against Libevent_pthreads as well as Libevent.
@@ -219,12 +219,15 @@ int evthread_use_pthreads(void);
  **/
 void evthread_enable_lock_debuging(void);
 
-#endif /* _EVENT_DISABLE_THREAD_SUPPORT */
+#endif /* EVENT__DISABLE_THREAD_SUPPORT */
 
 struct event_base;
 /** Make sure it's safe to tell an event base to wake up from another thread
     or a signal handler.
 
+    You shouldn't need to call this by hand; configuring the base with thread
+    support should be necessary and sufficient.
+
     @return 0 on success, -1 on failure.
  */
 int evthread_make_base_notifiable(struct event_base *base);
@@ -233,4 +236,4 @@ int evthread_make_base_notifiable(struct event_base *base);
 }
 #endif
 
-#endif /* _EVENT2_THREAD_H_ */
+#endif /* EVENT2_THREAD_H_INCLUDED_ */
index c71fdcf510cded8ebbc0f6ed35a83aa295982be3..eb120b217db32e299821de535cde2b56e9fbd8fd 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT2_UTIL_H_
-#define _EVENT2_UTIL_H_
+#ifndef EVENT2_UTIL_H_INCLUDED_
+#define EVENT2_UTIL_H_INCLUDED_
 
 /** @file event2/util.h
 
@@ -38,25 +38,25 @@ extern "C" {
 #endif
 
 #include <event2/event-config.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#ifdef _EVENT_HAVE_STDINT_H
+#ifdef EVENT__HAVE_STDINT_H
 #include <stdint.h>
-#elif defined(_EVENT_HAVE_INTTYPES_H)
+#elif defined(EVENT__HAVE_INTTYPES_H)
 #include <inttypes.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_TYPES_H
+#ifdef EVENT__HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#ifdef _EVENT_HAVE_STDDEF_H
+#ifdef EVENT__HAVE_STDDEF_H
 #include <stddef.h>
 #endif
 #ifdef _MSC_VER
 #include <BaseTsd.h>
 #endif
 #include <stdarg.h>
-#ifdef _EVENT_HAVE_NETDB_H
+#ifdef EVENT__HAVE_NETDB_H
 #if !defined(_GNU_SOURCE)
 #define _GNU_SOURCE
 #endif
@@ -65,13 +65,17 @@ extern "C" {
 
 #ifdef _WIN32
 #include <winsock2.h>
+#ifdef EVENT__HAVE_GETADDRINFO
+/* for EAI_* definitions. */
+#include <ws2tcpip.h>
+#endif
 #else
 #include <sys/socket.h>
 #endif
 
 /* Some openbsd autoconf versions get the name of this macro wrong. */
-#if defined(_EVENT_SIZEOF_VOID__) && !defined(_EVENT_SIZEOF_VOID_P)
-#define _EVENT_SIZEOF_VOID_P _EVENT_SIZEOF_VOID__
+#if defined(EVENT__SIZEOF_VOID__) && !defined(EVENT__SIZEOF_VOID_P)
+#define EVENT__SIZEOF_VOID_P EVENT__SIZEOF_VOID__
 #endif
 
 /**
@@ -103,67 +107,67 @@ extern "C" {
  *
  * @{
  */
-#ifdef _EVENT_HAVE_UINT64_T
+#ifdef EVENT__HAVE_UINT64_T
 #define ev_uint64_t uint64_t
 #define ev_int64_t int64_t
 #elif defined(_WIN32)
 #define ev_uint64_t unsigned __int64
 #define ev_int64_t signed __int64
-#elif _EVENT_SIZEOF_LONG_LONG == 8
+#elif EVENT__SIZEOF_LONG_LONG == 8
 #define ev_uint64_t unsigned long long
 #define ev_int64_t long long
-#elif _EVENT_SIZEOF_LONG == 8
+#elif EVENT__SIZEOF_LONG == 8
 #define ev_uint64_t unsigned long
 #define ev_int64_t long
-#elif defined(_EVENT_IN_DOXYGEN)
+#elif defined(EVENT_IN_DOXYGEN_)
 #define ev_uint64_t ...
 #define ev_int64_t ...
 #else
 #error "No way to define ev_uint64_t"
 #endif
 
-#ifdef _EVENT_HAVE_UINT32_T
+#ifdef EVENT__HAVE_UINT32_T
 #define ev_uint32_t uint32_t
 #define ev_int32_t int32_t
 #elif defined(_WIN32)
 #define ev_uint32_t unsigned int
 #define ev_int32_t signed int
-#elif _EVENT_SIZEOF_LONG == 4
+#elif EVENT__SIZEOF_LONG == 4
 #define ev_uint32_t unsigned long
 #define ev_int32_t signed long
-#elif _EVENT_SIZEOF_INT == 4
+#elif EVENT__SIZEOF_INT == 4
 #define ev_uint32_t unsigned int
 #define ev_int32_t signed int
-#elif defined(_EVENT_IN_DOXYGEN)
+#elif defined(EVENT_IN_DOXYGEN_)
 #define ev_uint32_t ...
 #define ev_int32_t ...
 #else
 #error "No way to define ev_uint32_t"
 #endif
 
-#ifdef _EVENT_HAVE_UINT16_T
+#ifdef EVENT__HAVE_UINT16_T
 #define ev_uint16_t uint16_t
 #define ev_int16_t  int16_t
 #elif defined(_WIN32)
 #define ev_uint16_t unsigned short
 #define ev_int16_t  signed short
-#elif _EVENT_SIZEOF_INT == 2
+#elif EVENT__SIZEOF_INT == 2
 #define ev_uint16_t unsigned int
 #define ev_int16_t  signed int
-#elif _EVENT_SIZEOF_SHORT == 2
+#elif EVENT__SIZEOF_SHORT == 2
 #define ev_uint16_t unsigned short
 #define ev_int16_t  signed short
-#elif defined(_EVENT_IN_DOXYGEN)
+#elif defined(EVENT_IN_DOXYGEN_)
 #define ev_uint16_t ...
 #define ev_int16_t ...
 #else
 #error "No way to define ev_uint16_t"
 #endif
 
-#ifdef _EVENT_HAVE_UINT8_T
+#ifdef EVENT__HAVE_UINT8_T
 #define ev_uint8_t uint8_t
 #define ev_int8_t int8_t
-#elif defined(_EVENT_IN_DOXYGEN)
+#elif defined(EVENT_IN_DOXYGEN_)
 #define ev_uint8_t ...
 #define ev_int8_t ...
 #else
@@ -171,30 +175,43 @@ extern "C" {
 #define ev_int8_t signed char
 #endif
 
-#ifdef _EVENT_HAVE_UINTPTR_T
+#ifdef EVENT__HAVE_UINTPTR_T
 #define ev_uintptr_t uintptr_t
 #define ev_intptr_t intptr_t
-#elif _EVENT_SIZEOF_VOID_P <= 4
+#elif EVENT__SIZEOF_VOID_P <= 4
 #define ev_uintptr_t ev_uint32_t
 #define ev_intptr_t ev_int32_t
-#elif _EVENT_SIZEOF_VOID_P <= 8
+#elif EVENT__SIZEOF_VOID_P <= 8
 #define ev_uintptr_t ev_uint64_t
 #define ev_intptr_t ev_int64_t
-#elif defined(_EVENT_IN_DOXYGEN)
+#elif defined(EVENT_IN_DOXYGEN_)
 #define ev_uintptr_t ...
 #define ev_intptr_t ...
 #else
 #error "No way to define ev_uintptr_t"
 #endif
 
-#ifdef _EVENT_ssize_t
-#define ev_ssize_t _EVENT_ssize_t
+#ifdef EVENT__ssize_t
+#define ev_ssize_t EVENT__ssize_t
 #else
 #define ev_ssize_t ssize_t
 #endif
 
+/* Note that we define ev_off_t based on the compile-time size of off_t that
+ * we used to build Libevent, and not based on the current size of off_t.
+ * (For example, we don't define ev_off_t to off_t.).  We do this because
+ * some systems let you build your software with different off_t sizes
+ * at runtime, and so putting in any dependency on off_t would risk API
+ * mismatch.
+ */
 #ifdef _WIN32
 #define ev_off_t ev_int64_t
+#elif EVENT__SIZEOF_OFF_T == 8
+#define ev_off_t ev_int64_t
+#elif EVENT__SIZEOF_OFF_T == 4
+#define ev_off_t ev_int32_t
+#elif defined(EVENT_IN_DOXYGEN_)
+#define ev_off_t ...
 #else
 #define ev_off_t off_t
 #endif
@@ -234,13 +251,13 @@ extern "C" {
 
    @{
 */
-#if _EVENT_SIZEOF_SIZE_T == 8
+#if EVENT__SIZEOF_SIZE_T == 8
 #define EV_SIZE_MAX EV_UINT64_MAX
 #define EV_SSIZE_MAX EV_INT64_MAX
-#elif _EVENT_SIZEOF_SIZE_T == 4
+#elif EVENT__SIZEOF_SIZE_T == 4
 #define EV_SIZE_MAX EV_UINT32_MAX
 #define EV_SSIZE_MAX EV_INT32_MAX
-#elif defined(_EVENT_IN_DOXYGEN)
+#elif defined(EVENT_IN_DOXYGEN_)
 #define EV_SIZE_MAX ...
 #define EV_SSIZE_MAX ...
 #else
@@ -252,14 +269,14 @@ extern "C" {
 
 #ifdef _WIN32
 #define ev_socklen_t int
-#elif defined(_EVENT_socklen_t)
-#define ev_socklen_t _EVENT_socklen_t
+#elif defined(EVENT__socklen_t)
+#define ev_socklen_t EVENT__socklen_t
 #else
 #define ev_socklen_t socklen_t
 #endif
 
-#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
-#if !defined(_EVENT_HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
+#if !defined(EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
  && !defined(ss_family)
 #define ss_family __ss_family
 #endif
@@ -323,6 +340,18 @@ int evutil_make_socket_closeonexec(evutil_socket_t sock);
 int evutil_closesocket(evutil_socket_t sock);
 #define EVUTIL_CLOSESOCKET(s) evutil_closesocket(s)
 
+/** Do platform-specific operations, if possible, to make a tcp listener
+ *  socket defer accept()s until there is data to read.
+ *  
+ *  Not all platforms support this.  You don't want to do this for every
+ *  listener socket: only the ones that implement a protocol where the
+ *  client transmits before the server needs to respond.
+ *
+ *  @param sock The listening socket to to make deferred
+ *  @return 0 on success (whether the operation is supported or not),
+ *       -1 on failure
+*/ 
+int evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock);
 
 #ifdef _WIN32
 /** Return the most recent socket error.  Not idempotent on all platforms. */
@@ -334,7 +363,7 @@ int evutil_closesocket(evutil_socket_t sock);
 int evutil_socket_geterror(evutil_socket_t sock);
 /** Convert a socket error to a string. */
 const char *evutil_socket_error_to_string(int errcode);
-#elif defined(_EVENT_IN_DOXYGEN)
+#elif defined(EVENT_IN_DOXYGEN_)
 /**
    @name Socket error functions
 
@@ -375,7 +404,7 @@ const char *evutil_socket_error_to_string(int errcode);
  *
  * @{
  */
-#ifdef _EVENT_HAVE_TIMERADD
+#ifdef EVENT__HAVE_TIMERADD
 #define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
 #define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
 #else
@@ -397,9 +426,9 @@ const char *evutil_socket_error_to_string(int errcode);
                        (vvp)->tv_usec += 1000000;                      \
                }                                                       \
        } while (0)
-#endif /* !_EVENT_HAVE_HAVE_TIMERADD */
+#endif /* !EVENT__HAVE_TIMERADD */
 
-#ifdef _EVENT_HAVE_TIMERCLEAR
+#ifdef EVENT__HAVE_TIMERCLEAR
 #define evutil_timerclear(tvp) timerclear(tvp)
 #else
 #define        evutil_timerclear(tvp)  (tvp)->tv_sec = (tvp)->tv_usec = 0
@@ -413,7 +442,7 @@ const char *evutil_socket_error_to_string(int errcode);
         ((tvp)->tv_usec cmp (uvp)->tv_usec) :                          \
         ((tvp)->tv_sec cmp (uvp)->tv_sec))
 
-#ifdef _EVENT_HAVE_TIMERISSET
+#ifdef EVENT__HAVE_TIMERISSET
 #define evutil_timerisset(tvp) timerisset(tvp)
 #else
 #define        evutil_timerisset(tvp)  ((tvp)->tv_sec || (tvp)->tv_usec)
@@ -431,7 +460,7 @@ const char *evutil_socket_error_to_string(int errcode);
 ev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
 
 /** Replacement for gettimeofday on platforms that lack it. */
-#ifdef _EVENT_HAVE_GETTIMEOFDAY
+#ifdef EVENT__HAVE_GETTIMEOFDAY
 #define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
 #else
 struct timezone;
@@ -498,7 +527,7 @@ int evutil_ascii_strncasecmp(const char *str1, const char *str2, size_t n);
 
 /* Here we define evutil_addrinfo to the native addrinfo type, or redefine it
  * if this system has no getaddrinfo(). */
-#ifdef _EVENT_HAVE_STRUCT_ADDRINFO
+#ifdef EVENT__HAVE_STRUCT_ADDRINFO
 #define evutil_addrinfo addrinfo
 #else
 /** A definition of struct addrinfo for systems that lack it.
@@ -524,32 +553,32 @@ struct evutil_addrinfo {
 
     @{
 */
-#ifdef EAI_ADDRFAMILY
+#if defined(EAI_ADDRFAMILY) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_ADDRFAMILY EAI_ADDRFAMILY
 #else
 #define EVUTIL_EAI_ADDRFAMILY -901
 #endif
-#ifdef EAI_AGAIN
+#if defined(EAI_AGAIN) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_AGAIN EAI_AGAIN
 #else
 #define EVUTIL_EAI_AGAIN -902
 #endif
-#ifdef EAI_BADFLAGS
+#if defined(EAI_BADFLAGS) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_BADFLAGS EAI_BADFLAGS
 #else
 #define EVUTIL_EAI_BADFLAGS -903
 #endif
-#ifdef EAI_FAIL
+#if defined(EAI_FAIL) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_FAIL EAI_FAIL
 #else
 #define EVUTIL_EAI_FAIL -904
 #endif
-#ifdef EAI_FAMILY
+#if defined(EAI_FAMILY) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_FAMILY EAI_FAMILY
 #else
 #define EVUTIL_EAI_FAMILY -905
 #endif
-#ifdef EAI_MEMORY
+#if defined(EAI_MEMORY) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_MEMORY EAI_MEMORY
 #else
 #define EVUTIL_EAI_MEMORY -906
@@ -557,27 +586,27 @@ struct evutil_addrinfo {
 /* This test is a bit complicated, since some MS SDKs decide to
  * remove NODATA or redefine it to be the same as NONAME, in a
  * fun interpretation of RFC 2553 and RFC 3493. */
-#if defined(EAI_NODATA) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
+#if defined(EAI_NODATA) && defined(EVENT__HAVE_GETADDRINFO) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
 #define EVUTIL_EAI_NODATA EAI_NODATA
 #else
 #define EVUTIL_EAI_NODATA -907
 #endif
-#ifdef EAI_NONAME
+#if defined(EAI_NONAME) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_NONAME EAI_NONAME
 #else
 #define EVUTIL_EAI_NONAME -908
 #endif
-#ifdef EAI_SERVICE
+#if defined(EAI_SERVICE) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_SERVICE EAI_SERVICE
 #else
 #define EVUTIL_EAI_SERVICE -909
 #endif
-#ifdef EAI_SOCKTYPE
+#if defined(EAI_SOCKTYPE) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_SOCKTYPE EAI_SOCKTYPE
 #else
 #define EVUTIL_EAI_SOCKTYPE -910
 #endif
-#ifdef EAI_SYSTEM
+#if defined(EAI_SYSTEM) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_EAI_SYSTEM EAI_SYSTEM
 #else
 #define EVUTIL_EAI_SYSTEM -911
@@ -585,37 +614,37 @@ struct evutil_addrinfo {
 
 #define EVUTIL_EAI_CANCEL -90001
 
-#ifdef AI_PASSIVE
+#if defined(AI_PASSIVE) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_AI_PASSIVE AI_PASSIVE
 #else
 #define EVUTIL_AI_PASSIVE 0x1000
 #endif
-#ifdef AI_CANONNAME
+#if defined(AI_CANONNAME) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_AI_CANONNAME AI_CANONNAME
 #else
 #define EVUTIL_AI_CANONNAME 0x2000
 #endif
-#ifdef AI_NUMERICHOST
+#if defined(AI_NUMERICHOST) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_AI_NUMERICHOST AI_NUMERICHOST
 #else
 #define EVUTIL_AI_NUMERICHOST 0x4000
 #endif
-#ifdef AI_NUMERICSERV
+#if defined(AI_NUMERICSERV) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_AI_NUMERICSERV AI_NUMERICSERV
 #else
 #define EVUTIL_AI_NUMERICSERV 0x8000
 #endif
-#ifdef AI_V4MAPPED
+#if defined(AI_V4MAPPED) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_AI_V4MAPPED AI_V4MAPPED
 #else
 #define EVUTIL_AI_V4MAPPED 0x10000
 #endif
-#ifdef AI_ALL
+#if defined(AI_ALL) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_AI_ALL AI_ALL
 #else
 #define EVUTIL_AI_ALL 0x20000
 #endif
-#ifdef AI_ADDRCONFIG
+#if defined(AI_ADDRCONFIG) && defined(EVENT__HAVE_GETADDRINFO)
 #define EVUTIL_AI_ADDRCONFIG AI_ADDRCONFIG
 #else
 #define EVUTIL_AI_ADDRCONFIG 0x40000
@@ -688,4 +717,4 @@ void evutil_secure_rng_add_bytes(const char *dat, size_t datlen);
 }
 #endif
 
-#endif /* _EVUTIL_H_ */
+#endif /* EVENT1_EVUTIL_H_INCLUDED_ */
similarity index 88%
rename from sntp/libevent/evhttp.h
rename to sntp/libevent/include/evhttp.h
index 1707aa7f082bd95e6b17ec4a0de6ca12395602c4..549bc9b14a3ca219569513488f16375891240cf1 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVHTTP_H_
-#define _EVHTTP_H_
+#ifndef EVENT1_EVHTTP_H_INCLUDED_
+#define EVENT1_EVHTTP_H_INCLUDED_
 
 /** @file evhttp.h
 
@@ -33,7 +33,7 @@
 
   The <evhttp.h> header is deprecated in Libevent 2.0 and later; please
   use <event2/http.h> instead.  Depending on what functionality you
-  need, you may also want to include more of the other event2/*.h
+  need, you may also want to include more of the other <event2/...>
   headers.
  */
 
@@ -42,4 +42,4 @@
 #include <event2/http_struct.h>
 #include <event2/http_compat.h>
 
-#endif /* _EVHTTP_H_ */
+#endif /* EVENT1_EVHTTP_H_INCLUDED_ */
similarity index 88%
rename from sntp/libevent/evrpc.h
rename to sntp/libevent/include/evrpc.h
index a9f85d7b3f1a855ee3e24a791a00703294857f85..7e986f7dabbc2bd9a7da081b8b75ac198cfa5a3f 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVRPC_H_
-#define _EVRPC_H_
+#ifndef EVENT1_EVRPC_H_INCLUDED_
+#define EVENT1_EVRPC_H_INCLUDED_
 
 /** @file evrpc.h
 
@@ -33,7 +33,7 @@
 
   The <evrpc.h> header is deprecated in Libevent 2.0 and later; please
   use <event2/rpc.h> instead.  Depending on what functionality you
-  need, you may also want to include more of the other event2/*.h
+  need, you may also want to include more of the other <event2/...>
   headers.
  */
 
@@ -42,4 +42,4 @@
 #include <event2/rpc_struct.h>
 #include <event2/rpc_compat.h>
 
-#endif /* _EVRPC_H_ */
+#endif /* EVENT1_EVRPC_H_INCLUDED_ */
similarity index 90%
rename from sntp/libevent/evutil.h
rename to sntp/libevent/include/evutil.h
index efa2b4241bd6cf3f508bf2f0f3a40ec172a4a8c7..12c137d74506d1740c572387632701256b3de6a8 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVUTIL_H_
-#define _EVUTIL_H_
+#ifndef EVENT1_EVUTIL_H_INCLUDED_
+#define EVENT1_EVUTIL_H_INCLUDED_
 
 /** @file evutil.h
 
@@ -36,4 +36,4 @@
 
 #include <event2/util.h>
 
-#endif /* _EVUTIL_H_ */
+#endif /* EVENT1_EVUTIL_H_INCLUDED_ */
index abfd5af6ae57829a1264a6f01c9ff861c3286bb1..93dbe2b1a454e8a236d6487c62c25ecab831203b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef _EVENT_IOCP_INTERNAL_H
-#define _EVENT_IOCP_INTERNAL_H
+#ifndef IOCP_INTERNAL_H_INCLUDED_
+#define IOCP_INTERNAL_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -92,7 +92,7 @@ struct event_iocp_port {
        HANDLE *shutdownSemaphore;
 };
 
-const struct win32_extension_fns *event_get_win32_extension_fns(void);
+const struct win32_extension_fns *event_get_win32_extension_fns_(void);
 #else
 /* Dummy definition so we can test-compile more things on unix. */
 struct event_overlapped {
@@ -106,61 +106,61 @@ struct event_overlapped {
     @param cb The callback that should be invoked once the IO operation has
        finished.
  */
-void event_overlapped_init(struct event_overlapped *, iocp_callback cb);
+void event_overlapped_init_(struct event_overlapped *, iocp_callback cb);
 
 /** Allocate and return a new evbuffer that supports overlapped IO on a given
     socket.  The socket must be associated with an IO completion port using
-    event_iocp_port_associate.
+    event_iocp_port_associate_.
 */
-struct evbuffer *evbuffer_overlapped_new(evutil_socket_t fd);
+struct evbuffer *evbuffer_overlapped_new_(evutil_socket_t fd);
 
 /** XXXX Document (nickm) */
-evutil_socket_t _evbuffer_overlapped_get_fd(struct evbuffer *buf);
+evutil_socket_t evbuffer_overlapped_get_fd_(struct evbuffer *buf);
 
-void _evbuffer_overlapped_set_fd(struct evbuffer *buf, evutil_socket_t fd);
+void evbuffer_overlapped_set_fd_(struct evbuffer *buf, evutil_socket_t fd);
 
 /** Start reading data onto the end of an overlapped evbuffer.
 
     An evbuffer can only have one read pending at a time.  While the read
     is in progress, no other data may be added to the end of the buffer.
-    The buffer must be created with event_overlapped_init().
-    evbuffer_commit_read() must be called in the completion callback.
+    The buffer must be created with event_overlapped_init_().
+    evbuffer_commit_read_() must be called in the completion callback.
 
     @param buf The buffer to read onto
     @param n The number of bytes to try to read.
     @param ol Overlapped object with associated completion callback.
     @return 0 on success, -1 on error.
  */
-int evbuffer_launch_read(struct evbuffer *buf, size_t n, struct event_overlapped *ol);
+int evbuffer_launch_read_(struct evbuffer *buf, size_t n, struct event_overlapped *ol);
 
 /** Start writing data from the start of an evbuffer.
 
     An evbuffer can only have one write pending at a time.  While the write is
     in progress, no other data may be removed from the front of the buffer.
-    The buffer must be created with event_overlapped_init().
-    evbuffer_commit_write() must be called in the completion callback.
+    The buffer must be created with event_overlapped_init_().
+    evbuffer_commit_write_() must be called in the completion callback.
 
     @param buf The buffer to read onto
     @param n The number of bytes to try to read.
     @param ol Overlapped object with associated completion callback.
     @return 0 on success, -1 on error.
  */
-int evbuffer_launch_write(struct evbuffer *buf, ev_ssize_t n, struct event_overlapped *ol);
+int evbuffer_launch_write_(struct evbuffer *buf, ev_ssize_t n, struct event_overlapped *ol);
 
 /** XXX document */
-void evbuffer_commit_read(struct evbuffer *, ev_ssize_t);
-void evbuffer_commit_write(struct evbuffer *, ev_ssize_t);
+void evbuffer_commit_read_(struct evbuffer *, ev_ssize_t);
+void evbuffer_commit_write_(struct evbuffer *, ev_ssize_t);
 
 /** Create an IOCP, and launch its worker threads.  Internal use only.
 
     This interface is unstable, and will change.
  */
-struct event_iocp_port *event_iocp_port_launch(int n_cpus);
+struct event_iocp_port *event_iocp_port_launch_(int n_cpus);
 
 /** Associate a file descriptor with an iocp, such that overlapped IO on the
     fd will happen on one of the iocp's worker threads.
 */
-int event_iocp_port_associate(struct event_iocp_port *port, evutil_socket_t fd,
+int event_iocp_port_associate_(struct event_iocp_port *port, evutil_socket_t fd,
     ev_uintptr_t key);
 
 /** Tell all threads serving an iocp to stop.  Wait for up to waitMsec for all
@@ -169,29 +169,29 @@ int event_iocp_port_associate(struct event_iocp_port *port, evutil_socket_t fd,
     0. Otherwise, return -1.  If you get a -1 return value, it is safe to call
     this function again.
 */
-int event_iocp_shutdown(struct event_iocp_port *port, long waitMsec);
+int event_iocp_shutdown_(struct event_iocp_port *port, long waitMsec);
 
 /* FIXME document. */
-int event_iocp_activate_overlapped(struct event_iocp_port *port,
+int event_iocp_activate_overlapped_(struct event_iocp_port *port,
     struct event_overlapped *o,
     ev_uintptr_t key, ev_uint32_t n_bytes);
 
 struct event_base;
 /* FIXME document. */
-struct event_iocp_port *event_base_get_iocp(struct event_base *base);
+struct event_iocp_port *event_base_get_iocp_(struct event_base *base);
 
 /* FIXME document. */
-int event_base_start_iocp(struct event_base *base, int n_cpus);
-void event_base_stop_iocp(struct event_base *base);
+int event_base_start_iocp_(struct event_base *base, int n_cpus);
+void event_base_stop_iocp_(struct event_base *base);
 
 /* FIXME document. */
-struct bufferevent *bufferevent_async_new(struct event_base *base,
+struct bufferevent *bufferevent_async_new_(struct event_base *base,
     evutil_socket_t fd, int options);
 
 /* FIXME document. */
-void bufferevent_async_set_connected(struct bufferevent *bev);
-int bufferevent_async_can_connect(struct bufferevent *bev);
-int bufferevent_async_connect(struct bufferevent *bev, evutil_socket_t fd,
+void bufferevent_async_set_connected_(struct bufferevent *bev);
+int bufferevent_async_can_connect_(struct bufferevent *bev);
+int bufferevent_async_connect_(struct bufferevent *bev, evutil_socket_t fd,
        const struct sockaddr *sa, int socklen);
 
 #ifdef __cplusplus
index 18f7ba5d047bd161eaafc261ed6760b8e98c626f..0c207377b8da228ec07dc47ae2af708cfd933a29 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 /* Internal use only: Fake IPv6 structures and values on platforms that
  * do not have them */
 
-#ifndef _EVENT_IPV6_INTERNAL_H
-#define _EVENT_IPV6_INTERNAL_H
+#ifndef IPV6_INTERNAL_H_INCLUDED_
+#define IPV6_INTERNAL_H_INCLUDED_
 
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
 #include <sys/types.h>
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 #include "event2/util.h"
@@ -49,17 +49,17 @@ extern "C" {
  * properly.
  */
 
-#ifndef _EVENT_HAVE_STRUCT_IN6_ADDR
+#ifndef EVENT__HAVE_STRUCT_IN6_ADDR
 struct in6_addr {
        ev_uint8_t s6_addr[16];
 };
 #endif
 
-#ifndef _EVENT_HAVE_SA_FAMILY_T
+#ifndef EVENT__HAVE_SA_FAMILY_T
 typedef int sa_family_t;
 #endif
 
-#ifndef _EVENT_HAVE_STRUCT_SOCKADDR_IN6
+#ifndef EVENT__HAVE_STRUCT_SOCKADDR_IN6
 struct sockaddr_in6 {
        /* This will fail if we find a struct sockaddr that doesn't have
         * sa_family as the first element. */
diff --git a/sntp/libevent/kqueue-internal.h b/sntp/libevent/kqueue-internal.h
new file mode 100644 (file)
index 0000000..02c5a36
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef KQUEUE_INTERNAL_H_INCLUDED_
+#define KQUEUE_INTERNAL_H_INCLUDED_
+
+/** Notification function, used to tell an event base to wake up from another
+ * thread.  Only works when event_kq_add_notify_event_() has previously been
+ * called successfully on that base. */
+int event_kq_notify_base_(struct event_base *base);
+
+/** Prepare a kqueue-using event base to receive notifications via an internal
+ * EVFILT_USER event.  Return 0 on sucess, -1 on failure.
+ */
+int event_kq_add_notify_event_(struct event_base *base);
+
+#endif
index dc61ae3969f9d97a0f27f0fd6ea902343c66089a..39334674244bb0828d2244d5d0479a2f34120936 100644 (file)
@@ -2,7 +2,7 @@
 
 /*
  * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
+#ifdef EVENT__HAVE_KQUEUE
+
 #include <sys/types.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
 #include <string.h>
 #include <unistd.h>
 #include <errno.h>
-#ifdef _EVENT_HAVE_INTTYPES_H
+#ifdef EVENT__HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
 
 /* Some platforms apparently define the udata field of struct kevent as
  * intptr_t, whereas others define it as void*.  There doesn't seem to be an
  * easy way to tell them apart via autoconf, so we need to use OS macros. */
-#if defined(_EVENT_HAVE_INTTYPES_H) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__darwin__) && !defined(__APPLE__)
+#if defined(EVENT__HAVE_INTTYPES_H) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__darwin__) && !defined(__APPLE__)
 #define PTR_TO_UDATA(x)        ((intptr_t)(x))
 #define INT_TO_UDATA(x) ((intptr_t)(x))
 #else
@@ -63,6 +65,8 @@
 #include "evthread-internal.h"
 #include "changelist-internal.h"
 
+#include "kqueue-internal.h"
+
 #define NEVENT         64
 
 struct kqop {
@@ -72,6 +76,7 @@ struct kqop {
        struct kevent *events;
        int events_size;
        int kq;
+       int notify_event_added;
        pid_t pid;
 };
 
@@ -86,8 +91,8 @@ static void kq_dealloc(struct event_base *);
 const struct eventop kqops = {
        "kqueue",
        kq_init,
-       event_changelist_add,
-       event_changelist_del,
+       event_changelist_add_,
+       event_changelist_del_,
        kq_dispatch,
        kq_dealloc,
        1 /* need reinit */,
@@ -169,7 +174,7 @@ err:
 static void
 kq_setup_kevent(struct kevent *out, evutil_socket_t fd, int filter, short change)
 {
-       memset(out, 0, sizeof(out));
+       memset(out, 0, sizeof(struct kevent));
        out->ident = fd;
        out->filter = filter;
 
@@ -265,7 +270,7 @@ kq_dispatch(struct event_base *base, struct timeval *tv)
        if (n_changes < 0)
                return -1;
 
-       event_changelist_remove_all(&base->changelist, base);
+       event_changelist_remove_all_(&base->changelist, base);
 
        /* steal the changes array in case some broken code tries to call
         * dispatch twice at once. */
@@ -328,10 +333,15 @@ kq_dispatch(struct event_base *base, struct timeval *tv)
                        case EINVAL:
                                continue;
 
-                       /* Can occur on a delete if the fd is closed.  Can
-                        * occur on an add if the fd was one side of a pipe,
-                        * and the other side was closed. */
+                       /* Can occur on a delete if the fd is closed. */
                        case EBADF:
+                               /* XXXX On NetBSD, we can also get EBADF if we
+                                * try to add the write side of a pipe, but
+                                * the read side has already been closed.
+                                * Other BSDs call this situation 'EPIPE'. It
+                                * would be good if we had a way to report
+                                * this situation. */
+                               continue;
                        /* These two can occur on an add if the fd was one side
                         * of a pipe, and the other side was closed. */
                        case EPERM:
@@ -362,15 +372,19 @@ kq_dispatch(struct event_base *base, struct timeval *tv)
                        which |= EV_WRITE;
                } else if (events[i].filter == EVFILT_SIGNAL) {
                        which |= EV_SIGNAL;
+#ifdef EVFILT_USER
+               } else if (events[i].filter == EVFILT_USER) {
+                       base->is_notify_pending = 0;
+#endif
                }
 
                if (!which)
                        continue;
 
                if (events[i].filter == EVFILT_SIGNAL) {
-                       evmap_signal_active(base, events[i].ident, 1);
+                       evmap_signal_active_(base, events[i].ident, 1);
                } else {
-                       evmap_io_active(base, events[i].ident, which | EV_ET);
+                       evmap_io_active_(base, events[i].ident, which | EV_ET);
                }
        }
 
@@ -400,7 +414,7 @@ static void
 kq_dealloc(struct event_base *base)
 {
        struct kqop *kqop = base->evbase;
-       evsig_dealloc(base);
+       evsig_dealloc_(base);
        kqop_free(kqop);
 }
 
@@ -431,7 +445,7 @@ kq_sig_add(struct event_base *base, int nsignal, short old, short events, void *
          * if the handler for SIGCHLD is SIG_IGN, the system reaps
          * zombie processes for us, and we don't get any notification.
          * This appears to be the only signal with this quirk. */
-       if (_evsig_set_handler(base, nsignal,
+       if (evsig_set_handler_(base, nsignal,
                                nsignal == SIGCHLD ? SIG_DFL : SIG_IGN) == -1)
                return (-1);
 
@@ -460,8 +474,76 @@ kq_sig_del(struct event_base *base, int nsignal, short old, short events, void *
        if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
                return (-1);
 
-       if (_evsig_restore_handler(base, nsignal) == -1)
+       if (evsig_restore_handler_(base, nsignal) == -1)
                return (-1);
 
        return (0);
 }
+
+
+/* OSX 10.6 and FreeBSD 8.1 add support for EVFILT_USER, which we can use
+ * to wake up the event loop from another thread. */
+
+/* Magic number we use for our filter ID. */
+#define NOTIFY_IDENT 42
+
+int
+event_kq_add_notify_event_(struct event_base *base)
+{
+       struct kqop *kqop = base->evbase;
+#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
+       struct kevent kev;
+       struct timespec timeout = { 0, 0 };
+#endif
+
+       if (kqop->notify_event_added)
+               return 0;
+
+#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
+       memset(&kev, 0, sizeof(kev));
+       kev.ident = NOTIFY_IDENT;
+       kev.filter = EVFILT_USER;
+       kev.flags = EV_ADD | EV_CLEAR;
+
+       if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1) {
+               event_warn("kevent: adding EVFILT_USER event");
+               return -1;
+       }
+
+       kqop->notify_event_added = 1;
+
+       return 0;
+#else
+       return -1;
+#endif
+}
+
+int
+event_kq_notify_base_(struct event_base *base)
+{
+       struct kqop *kqop = base->evbase;
+#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
+       struct kevent kev;
+       struct timespec timeout = { 0, 0 };
+#endif
+       if (! kqop->notify_event_added)
+               return -1;
+
+#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
+       memset(&kev, 0, sizeof(kev));
+       kev.ident = NOTIFY_IDENT;
+       kev.filter = EVFILT_USER;
+       kev.fflags = NOTE_TRIGGER;
+
+       if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1) {
+               event_warn("kevent: triggering EVFILT_USER event");
+               return -1;
+       }
+
+       return 0;
+#else
+       return -1;
+#endif
+}
+
+#endif /* EVENT__HAVE_KQUEUE */
index 7f80338288b8ae265467b5b5e75c57ab66a2d4b1..2cceff24795be00342b2585f007bf94f7c3b47ca 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos, Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include <mswsock.h>
 #endif
 #include <errno.h>
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
-#ifdef _EVENT_HAVE_FCNTL_H
+#ifdef EVENT__HAVE_FCNTL_H
 #include <fcntl.h>
 #endif
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 
@@ -80,6 +80,7 @@ struct evconnlistener {
        void *user_data;
        unsigned flags;
        short refcnt;
+       int accept4_flags;
        unsigned enabled : 1;
 };
 
@@ -159,9 +160,9 @@ evconnlistener_new(struct event_base *base,
        struct evconnlistener_event *lev;
 
 #ifdef _WIN32
-       if (base && event_base_get_iocp(base)) {
+       if (base && event_base_get_iocp_(base)) {
                const struct win32_extension_fns *ext =
-                       event_get_win32_extension_fns();
+                       event_get_win32_extension_fns_();
                if (ext->AcceptEx && ext->GetAcceptExSockaddrs)
                        return evconnlistener_new_async(base, cb, ptr, flags,
                                backlog, fd);
@@ -186,6 +187,12 @@ evconnlistener_new(struct event_base *base,
        lev->base.flags = flags;
        lev->base.refcnt = 1;
 
+       lev->base.accept4_flags = 0;
+       if (!(flags & LEV_OPT_LEAVE_SOCKETS_BLOCKING))
+               lev->base.accept4_flags |= EVUTIL_SOCK_NONBLOCK;
+       if (flags & LEV_OPT_CLOSE_ON_EXEC)
+               lev->base.accept4_flags |= EVUTIL_SOCK_CLOEXEC;
+
        if (flags & LEV_OPT_THREADSAFE) {
                EVTHREAD_ALLOC_LOCK(lev->base.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
        }
@@ -193,7 +200,8 @@ evconnlistener_new(struct event_base *base,
        event_assign(&lev->listener, base, fd, EV_READ|EV_PERSIST,
            listener_read_cb, lev);
 
-       evconnlistener_enable(&lev->base);
+       if (!(flags & LEV_OPT_DISABLED))
+           evconnlistener_enable(&lev->base);
 
        return &lev->base;
 }
@@ -207,31 +215,27 @@ evconnlistener_new_bind(struct event_base *base, evconnlistener_cb cb,
        evutil_socket_t fd;
        int on = 1;
        int family = sa ? sa->sa_family : AF_UNSPEC;
+       int socktype = SOCK_STREAM | EVUTIL_SOCK_NONBLOCK;
 
        if (backlog == 0)
                return NULL;
 
-       fd = socket(family, SOCK_STREAM, 0);
-       if (fd == -1)
-               return NULL;
+       if (flags & LEV_OPT_CLOSE_ON_EXEC)
+               socktype |= EVUTIL_SOCK_CLOEXEC;
 
-       if (evutil_make_socket_nonblocking(fd) < 0) {
-               evutil_closesocket(fd);
+       fd = evutil_socket_(family, socktype, 0);
+       if (fd == -1)
                return NULL;
-       }
-
-       if (flags & LEV_OPT_CLOSE_ON_EXEC) {
-               if (evutil_make_socket_closeonexec(fd) < 0) {
-                       evutil_closesocket(fd);
-                       return NULL;
-               }
-       }
 
        setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&on, sizeof(on));
        if (flags & LEV_OPT_REUSEABLE) {
                evutil_make_listen_socket_reuseable(fd);
        }
 
+       if (flags & LEV_OPT_DEFERRED_ACCEPT) {
+               evutil_make_tcp_listen_socket_deferred(fd);
+       }
+
        if (sa) {
                if (bind(fd, sa, socklen)<0) {
                        evutil_closesocket(fd);
@@ -383,17 +387,16 @@ listener_read_cb(evutil_socket_t fd, short what, void *p)
        LOCK(lev);
        while (1) {
                struct sockaddr_storage ss;
-#ifdef _WIN32
-               int socklen = sizeof(ss);
-#else
-               socklen_t socklen = sizeof(ss);
-#endif
-               evutil_socket_t new_fd = accept(fd, (struct sockaddr*)&ss, &socklen);
+               ev_socklen_t socklen = sizeof(ss);
+               evutil_socket_t new_fd = evutil_accept4_(fd, (struct sockaddr*)&ss, &socklen, lev->accept4_flags);
                if (new_fd < 0)
                        break;
-
-               if (!(lev->flags & LEV_OPT_LEAVE_SOCKETS_BLOCKING))
-                       evutil_make_socket_nonblocking(new_fd);
+               if (socklen == 0) {
+                       /* This can happen with some older linux kernels in
+                        * response to nmap. */
+                       evutil_closesocket(new_fd);
+                       continue;
+               }
 
                if (lev->cb == NULL) {
                        UNLOCK(lev);
@@ -456,7 +459,7 @@ iocp_listener_event_add(struct evconnlistener_iocp *lev)
                return;
 
        lev->event_added = 1;
-       event_base_add_virtual(lev->event_base);
+       event_base_add_virtual_(lev->event_base);
 }
 
 static void
@@ -466,7 +469,7 @@ iocp_listener_event_del(struct evconnlistener_iocp *lev)
                return;
 
        lev->event_added = 0;
-       event_base_del_virtual(lev->event_base);
+       event_base_del_virtual_(lev->event_base);
 }
 
 static struct accepting_socket *
@@ -488,13 +491,13 @@ new_accepting_socket(struct evconnlistener_iocp *lev, int family)
        if (!res)
                return NULL;
 
-       event_overlapped_init(&res->overlapped, accepted_socket_cb);
+       event_overlapped_init_(&res->overlapped, accepted_socket_cb);
        res->s = INVALID_SOCKET;
        res->lev = lev;
        res->buflen = buflen;
        res->family = family;
 
-       event_deferred_cb_init(&res->deferred,
+       event_deferred_cb_init_(&res->deferred,
                accepted_socket_invoke_user_cb, res);
 
        InitializeCriticalSectionAndSpinCount(&res->lock, 1000);
@@ -518,7 +521,7 @@ static int
 start_accepting(struct accepting_socket *as)
 {
        /* requires lock */
-       const struct win32_extension_fns *ext = event_get_win32_extension_fns();
+       const struct win32_extension_fns *ext = event_get_win32_extension_fns_();
        DWORD pending = 0;
        SOCKET s = socket(as->family, SOCK_STREAM, 0);
        int error = 0;
@@ -539,7 +542,7 @@ start_accepting(struct accepting_socket *as)
        if (!(as->lev->base.flags & LEV_OPT_LEAVE_SOCKETS_BLOCKING))
                evutil_make_socket_nonblocking(s);
 
-       if (event_iocp_port_associate(as->lev->port, s, 1) < 0) {
+       if (event_iocp_port_associate_(as->lev->port, s, 1) < 0) {
                closesocket(s);
                return -1;
        }
@@ -562,8 +565,8 @@ start_accepting(struct accepting_socket *as)
 
 report_err:
        as->error = error;
-       event_deferred_cb_schedule(
-               event_base_get_deferred_cb_queue(as->lev->event_base),
+       event_deferred_cb_schedule_(
+               event_base_get_deferred_cb_queue_(as->lev->event_base),
                &as->deferred);
        return 0;
 }
@@ -584,7 +587,7 @@ accepted_socket_invoke_user_cb(struct deferred_cb *dcb, void *arg)
 
        struct sockaddr *sa_local=NULL, *sa_remote=NULL;
        int socklen_local=0, socklen_remote=0;
-       const struct win32_extension_fns *ext = event_get_win32_extension_fns();
+       const struct win32_extension_fns *ext = event_get_win32_extension_fns_();
        struct evconnlistener *lev = &as->lev->base;
        evutil_socket_t sock=-1;
        void *data;
@@ -654,8 +657,8 @@ accepted_socket_cb(struct event_overlapped *o, ev_uintptr_t key, ev_ssize_t n, i
        EnterCriticalSection(&as->lock);
        if (ok) {
                /* XXXX Don't do this if some EV_MT flag is set. */
-               event_deferred_cb_schedule(
-                       event_base_get_deferred_cb_queue(as->lev->event_base),
+               event_deferred_cb_schedule_(
+                       event_base_get_deferred_cb_queue_(as->lev->event_base),
                        &as->deferred);
                LeaveCriticalSection(&as->lock);
        } else if (as->free_on_cb) {
@@ -679,8 +682,8 @@ accepted_socket_cb(struct event_overlapped *o, ev_uintptr_t key, ev_ssize_t n, i
                } else {
                        as->error = WSAGetLastError();
                }
-               event_deferred_cb_schedule(
-                       event_base_get_deferred_cb_queue(as->lev->event_base),
+               event_deferred_cb_schedule_(
+                       event_base_get_deferred_cb_queue_(as->lev->event_base),
                        &as->deferred);
                LeaveCriticalSection(&as->lock);
        }
@@ -792,7 +795,7 @@ evconnlistener_new_async(struct event_base *base,
 
        flags |= LEV_OPT_THREADSAFE;
 
-       if (!base || !event_base_get_iocp(base))
+       if (!base || !event_base_get_iocp_(base))
                goto err;
 
        /* XXXX duplicate code */
@@ -819,12 +822,12 @@ evconnlistener_new_async(struct event_base *base,
        lev->base.refcnt = 1;
        lev->base.enabled = 1;
 
-       lev->port = event_base_get_iocp(base);
+       lev->port = event_base_get_iocp_(base);
        lev->fd = fd;
        lev->event_base = base;
 
 
-       if (event_iocp_port_associate(lev->port, fd, 1) < 0)
+       if (event_iocp_port_associate_(lev->port, fd, 1) < 0)
                goto err_free_lev;
 
        EVTHREAD_ALLOC_LOCK(lev->base.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
index c1905aea34fec5e9991beac399ddd3c3f97b0dac..da4cd73ab15723d24c6148caeb469535f96147e7 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _LOG_H_
-#define _LOG_H_
+#ifndef LOG_INTERNAL_H_INCLUDED_
+#define LOG_INTERNAL_H_INCLUDED_
 
 #include "event2/util.h"
 
 #define EV_NORETURN
 #endif
 
-#define _EVENT_ERR_ABORT ((int)0xdeaddead)
+#define EVENT_ERR_ABORT_ ((int)0xdeaddead)
+
+#define USE_GLOBAL_FOR_DEBUG_LOGGING
+
+#if !defined(EVENT__DISABLE_DEBUG_MODE) || defined(USE_DEBUG)
+#define EVENT_DEBUG_LOGGING_ENABLED
+#endif
+
+#ifdef EVENT_DEBUG_LOGGING_ENABLED
+#ifdef USE_GLOBAL_FOR_DEBUG_LOGGING
+extern ev_uint32_t event_debug_logging_mask_;
+#define event_debug_get_logging_mask_() (event_debug_logging_mask_)
+#else
+ev_uint32_t event_debug_get_logging_mask_(void);
+#endif
+#else
+#define event_debug_get_logging_mask_() (0)
+#endif
 
 void event_err(int eval, const char *fmt, ...) EV_CHECK_FMT(2,3) EV_NORETURN;
 void event_warn(const char *fmt, ...) EV_CHECK_FMT(1,2);
@@ -46,12 +63,16 @@ void event_sock_warn(evutil_socket_t sock, const char *fmt, ...) EV_CHECK_FMT(2,
 void event_errx(int eval, const char *fmt, ...) EV_CHECK_FMT(2,3) EV_NORETURN;
 void event_warnx(const char *fmt, ...) EV_CHECK_FMT(1,2);
 void event_msgx(const char *fmt, ...) EV_CHECK_FMT(1,2);
-void _event_debugx(const char *fmt, ...) EV_CHECK_FMT(1,2);
+void event_debugx_(const char *fmt, ...) EV_CHECK_FMT(1,2);
 
-#ifdef USE_DEBUG
-#define event_debug(x) _event_debugx x
+#ifdef EVENT_DEBUG_LOGGING_ENABLED
+#define event_debug(x) do {                    \
+       if (event_debug_get_logging_mask_()) {  \
+               event_debugx_ x;                \
+       }                                       \
+       } while (0)
 #else
-#define event_debug(x) do {;} while (0)
+#define event_debug(x) ((void)0)
 #endif
 
 #undef EV_CHECK_FMT
index 8a3ca540c831df98589003b4f099910bd0d88846..32e69d45eadea9d189832f9298fe5f5f0136d815 100644 (file)
@@ -5,7 +5,7 @@
  *
  * Based on err.c, which was adapted from OpenBSD libc *err* *warn* code.
  *
- * Copyright (c) 2005-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2005-2012 Niels Provos and Nick Mathewson
  *
  * Copyright (c) 2000 Dug Song <dugsong@monkey.org>
  *
 
 #include "log-internal.h"
 
-static void _warn_helper(int severity, const char *errstr, const char *fmt,
+static void warn_helper_(int severity, const char *errstr, const char *fmt,
     va_list ap);
 static void event_log(int severity, const char *msg);
 static void event_exit(int errcode) EV_NORETURN;
 
 static event_fatal_cb fatal_fn = NULL;
 
+#ifdef EVENT_DEBUG_LOGGING_ENABLED
+#ifdef USE_DEBUG
+#define DEFAULT_MASK EVENT_DBG_ALL
+#else
+#define DEFAULT_MASK 0
+#endif
+
+#ifdef USE_GLOBAL_FOR_DEBUG_LOGGING
+ev_uint32_t event_debug_logging_mask_ = DEFAULT_MASK;
+#else
+static ev_uint32_t event_debug_logging_mask_ = DEFAULT_MASK;
+ev_uint32_t
+event_debug_get_logging_mask_(void)
+{
+       return event_debug_logging_mask_;
+}
+#endif
+#endif /* EVENT_DEBUG_LOGGING_ENABLED */
+
 void
 event_set_fatal_callback(event_fatal_cb cb)
 {
@@ -76,7 +95,7 @@ event_exit(int errcode)
        if (fatal_fn) {
                fatal_fn(errcode);
                exit(errcode); /* should never be reached */
-       } else if (errcode == _EVENT_ERR_ABORT)
+       } else if (errcode == EVENT_ERR_ABORT_)
                abort();
        else
                exit(errcode);
@@ -88,7 +107,7 @@ event_err(int eval, const char *fmt, ...)
        va_list ap;
 
        va_start(ap, fmt);
-       _warn_helper(_EVENT_LOG_ERR, strerror(errno), fmt, ap);
+       warn_helper_(EVENT_LOG_ERR, strerror(errno), fmt, ap);
        va_end(ap);
        event_exit(eval);
 }
@@ -99,7 +118,7 @@ event_warn(const char *fmt, ...)
        va_list ap;
 
        va_start(ap, fmt);
-       _warn_helper(_EVENT_LOG_WARN, strerror(errno), fmt, ap);
+       warn_helper_(EVENT_LOG_WARN, strerror(errno), fmt, ap);
        va_end(ap);
 }
 
@@ -110,7 +129,7 @@ event_sock_err(int eval, evutil_socket_t sock, const char *fmt, ...)
        int err = evutil_socket_geterror(sock);
 
        va_start(ap, fmt);
-       _warn_helper(_EVENT_LOG_ERR, evutil_socket_error_to_string(err), fmt, ap);
+       warn_helper_(EVENT_LOG_ERR, evutil_socket_error_to_string(err), fmt, ap);
        va_end(ap);
        event_exit(eval);
 }
@@ -122,7 +141,7 @@ event_sock_warn(evutil_socket_t sock, const char *fmt, ...)
        int err = evutil_socket_geterror(sock);
 
        va_start(ap, fmt);
-       _warn_helper(_EVENT_LOG_WARN, evutil_socket_error_to_string(err), fmt, ap);
+       warn_helper_(EVENT_LOG_WARN, evutil_socket_error_to_string(err), fmt, ap);
        va_end(ap);
 }
 
@@ -132,7 +151,7 @@ event_errx(int eval, const char *fmt, ...)
        va_list ap;
 
        va_start(ap, fmt);
-       _warn_helper(_EVENT_LOG_ERR, NULL, fmt, ap);
+       warn_helper_(EVENT_LOG_ERR, NULL, fmt, ap);
        va_end(ap);
        event_exit(eval);
 }
@@ -143,7 +162,7 @@ event_warnx(const char *fmt, ...)
        va_list ap;
 
        va_start(ap, fmt);
-       _warn_helper(_EVENT_LOG_WARN, NULL, fmt, ap);
+       warn_helper_(EVENT_LOG_WARN, NULL, fmt, ap);
        va_end(ap);
 }
 
@@ -153,22 +172,22 @@ event_msgx(const char *fmt, ...)
        va_list ap;
 
        va_start(ap, fmt);
-       _warn_helper(_EVENT_LOG_MSG, NULL, fmt, ap);
+       warn_helper_(EVENT_LOG_MSG, NULL, fmt, ap);
        va_end(ap);
 }
 
 void
-_event_debugx(const char *fmt, ...)
+event_debugx_(const char *fmt, ...)
 {
        va_list ap;
 
        va_start(ap, fmt);
-       _warn_helper(_EVENT_LOG_DEBUG, NULL, fmt, ap);
+       warn_helper_(EVENT_LOG_DEBUG, NULL, fmt, ap);
        va_end(ap);
 }
 
 static void
-_warn_helper(int severity, const char *errstr, const char *fmt, va_list ap)
+warn_helper_(int severity, const char *errstr, const char *fmt, va_list ap)
 {
        char buf[1024];
        size_t len;
@@ -204,16 +223,16 @@ event_log(int severity, const char *msg)
        else {
                const char *severity_str;
                switch (severity) {
-               case _EVENT_LOG_DEBUG:
+               case EVENT_LOG_DEBUG:
                        severity_str = "debug";
                        break;
-               case _EVENT_LOG_MSG:
+               case EVENT_LOG_MSG:
                        severity_str = "msg";
                        break;
-               case _EVENT_LOG_WARN:
+               case EVENT_LOG_WARN:
                        severity_str = "warn";
                        break;
-               case _EVENT_LOG_ERR:
+               case EVENT_LOG_ERR:
                        severity_str = "err";
                        break;
                default:
index 7b2732550f749f5ab8ea7c6bcf691675fb7a1390..3cb064a0bd369308e00f754e33e3fda2123e245e 100644 (file)
@@ -13,7 +13,7 @@ case "$enable_openssl" in
        OPENSSL_LIBS=`$PKG_CONFIG --libs openssl 2>/dev/null`
        case "$OPENSSL_LIBS" in
         '') ;;
-        *) OPENSSL_LIBS="$OPENSSL_LIBS $EV_LIB_GDI $EV_LIB_WS32"
+        *) OPENSSL_LIBS="$OPENSSL_LIBS $EV_LIB_GDI $EV_LIB_WS32 $OPENSSL_LIBADD"
            have_openssl=yes
            ;;
        esac
@@ -28,9 +28,9 @@ case "$enable_openssl" in
        OPENSSL_LIBS=""
        AC_SEARCH_LIBS([SSL_new], [ssl],
            [have_openssl=yes
-           OPENSSL_LIBS="$LIBS -lcrypto $EV_LIB_GDI $EV_LIB_WS32"],
+           OPENSSL_LIBS="$LIBS -lcrypto $EV_LIB_GDI $EV_LIB_WS32 $OPENSSL_LIBADD"],
            [have_openssl=no],
-           [-lcrypto $EV_LIB_GDI $EV_LIB_WS32])
+           [-lcrypto $EV_LIB_GDI $EV_LIB_WS32 $OPENSSL_LIBADD])
        LIBS="$save_LIBS"
        ;;
     esac
diff --git a/sntp/libevent/make-event-config.sed b/sntp/libevent/make-event-config.sed
new file mode 100644 (file)
index 0000000..e31018a
--- /dev/null
@@ -0,0 +1,23 @@
+# Sed script to postprocess config.h into event-config.h.
+
+1i\
+/* event2/event-config.h\
+ *\
+ * This file was generated by autoconf when libevent was built, and post-\
+ * processed by Libevent so that its macros would have a uniform prefix.\
+ *\
+ * DO NOT EDIT THIS FILE.\
+ *\
+ * Do not rely on macros in this file existing in later versions.\
+ */\
+\
+#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_\
+#define EVENT2_EVENT_CONFIG_H_INCLUDED_\
+
+$a\
+\
+#endif /* event2/event-config.h */
+
+s/#\( *\)define /#\1define EVENT__/
+s/#\( *\)undef /#\1undef EVENT__/
+s/#\( *\)if\(n*\)def /#\1if\2def EVENT__/
index 53b88886225bbdbb6023ceabb9c1b5c99d105da4..24f19633f9612e2286227135a5047fbe6a6ea1d9 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com>
  *
@@ -25,8 +25,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _MIN_HEAP_H_
-#define _MIN_HEAP_H_
+#ifndef MINHEAP_INTERNAL_H_INCLUDED_
+#define MINHEAP_INTERNAL_H_INCLUDED_
 
 #include "event2/event-config.h"
 #include "evconfig-private.h"
@@ -42,18 +42,18 @@ typedef struct min_heap
        unsigned n, a;
 } min_heap_t;
 
-static inline void          min_heap_ctor(min_heap_t* s);
-static inline void          min_heap_dtor(min_heap_t* s);
-static inline void          min_heap_elem_init(struct event* e);
-static inline int           min_heap_elt_is_top(const struct event *e);
-static inline int           min_heap_empty(min_heap_t* s);
-static inline unsigned      min_heap_size(min_heap_t* s);
-static inline struct event*  min_heap_top(min_heap_t* s);
-static inline int           min_heap_reserve(min_heap_t* s, unsigned n);
-static inline int           min_heap_push(min_heap_t* s, struct event* e);
-static inline struct event*  min_heap_pop(min_heap_t* s);
-static inline int           min_heap_adjust(min_heap_t *s, struct event* e);
-static inline int           min_heap_erase(min_heap_t* s, struct event* e);
+static inline void          min_heap_ctor_(min_heap_t* s);
+static inline void          min_heap_dtor_(min_heap_t* s);
+static inline void          min_heap_elem_init_(struct event* e);
+static inline int           min_heap_elt_is_top_(const struct event *e);
+static inline int           min_heap_empty_(min_heap_t* s);
+static inline unsigned      min_heap_size_(min_heap_t* s);
+static inline struct event*  min_heap_top_(min_heap_t* s);
+static inline int           min_heap_reserve_(min_heap_t* s, unsigned n);
+static inline int           min_heap_push_(min_heap_t* s, struct event* e);
+static inline struct event*  min_heap_pop_(min_heap_t* s);
+static inline int           min_heap_adjust_(min_heap_t *s, struct event* e);
+static inline int           min_heap_erase_(min_heap_t* s, struct event* e);
 static inline void          min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e);
 static inline void          min_heap_shift_up_unconditional_(min_heap_t* s, unsigned hole_index, struct event* e);
 static inline void          min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e);
@@ -61,22 +61,22 @@ static inline void       min_heap_shift_down_(min_heap_t* s, unsigned hole_index,
 #define min_heap_elem_greater(a, b) \
        (evutil_timercmp(&(a)->ev_timeout, &(b)->ev_timeout, >))
 
-void min_heap_ctor(min_heap_t* s) { s->p = 0; s->n = 0; s->a = 0; }
-void min_heap_dtor(min_heap_t* s) { if (s->p) mm_free(s->p); }
-void min_heap_elem_init(struct event* e) { e->ev_timeout_pos.min_heap_idx = -1; }
-int min_heap_empty(min_heap_t* s) { return 0u == s->n; }
-unsigned min_heap_size(min_heap_t* s) { return s->n; }
-struct event* min_heap_top(min_heap_t* s) { return s->n ? *s->p : 0; }
+void min_heap_ctor_(min_heap_t* s) { s->p = 0; s->n = 0; s->a = 0; }
+void min_heap_dtor_(min_heap_t* s) { if (s->p) mm_free(s->p); }
+void min_heap_elem_init_(struct event* e) { e->ev_timeout_pos.min_heap_idx = -1; }
+int min_heap_empty_(min_heap_t* s) { return 0u == s->n; }
+unsigned min_heap_size_(min_heap_t* s) { return s->n; }
+struct event* min_heap_top_(min_heap_t* s) { return s->n ? *s->p : 0; }
 
-int min_heap_push(min_heap_t* s, struct event* e)
+int min_heap_push_(min_heap_t* s, struct event* e)
 {
-       if (min_heap_reserve(s, s->n + 1))
+       if (min_heap_reserve_(s, s->n + 1))
                return -1;
        min_heap_shift_up_(s, s->n++, e);
        return 0;
 }
 
-struct event* min_heap_pop(min_heap_t* s)
+struct event* min_heap_pop_(min_heap_t* s)
 {
        if (s->n)
        {
@@ -88,12 +88,12 @@ struct event* min_heap_pop(min_heap_t* s)
        return 0;
 }
 
-int min_heap_elt_is_top(const struct event *e)
+int min_heap_elt_is_top_(const struct event *e)
 {
        return e->ev_timeout_pos.min_heap_idx == 0;
 }
 
-int min_heap_erase(min_heap_t* s, struct event* e)
+int min_heap_erase_(min_heap_t* s, struct event* e)
 {
        if (-1 != e->ev_timeout_pos.min_heap_idx)
        {
@@ -114,10 +114,10 @@ int min_heap_erase(min_heap_t* s, struct event* e)
        return -1;
 }
 
-int min_heap_adjust(min_heap_t *s, struct event *e)
+int min_heap_adjust_(min_heap_t *s, struct event *e)
 {
        if (-1 == e->ev_timeout_pos.min_heap_idx) {
-               return min_heap_push(s, e);
+               return min_heap_push_(s, e);
        } else {
                unsigned parent = (e->ev_timeout_pos.min_heap_idx - 1) / 2;
                /* The position of e has changed; we shift it up or down
@@ -131,7 +131,7 @@ int min_heap_adjust(min_heap_t *s, struct event *e)
        return -1;
 }
 
-int min_heap_reserve(min_heap_t* s, unsigned n)
+int min_heap_reserve_(min_heap_t* s, unsigned n)
 {
        if (s->a < n)
        {
@@ -186,4 +186,4 @@ void min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e)
     (s->p[hole_index] = e)->ev_timeout_pos.min_heap_idx = hole_index;
 }
 
-#endif /* _MIN_HEAP_H_ */
+#endif /* MINHEAP_INTERNAL_H_INCLUDED_ */
index 79855d6a0538e93fb701c8f4a8cbcfb2aafed34a..4ba6fce4adaf7b67a54d036bed37ffaa98195627 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT_MM_INTERNAL_H
-#define _EVENT_MM_INTERNAL_H
+#ifndef MM_INTERNAL_H_INCLUDED_
+#define MM_INTERNAL_H_INCLUDED_
 
 #include <sys/types.h>
 
 extern "C" {
 #endif
 
-#ifndef _EVENT_DISABLE_MM_REPLACEMENT
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
 /* Internal use only: Memory allocation functions. We give them nice short
  * mm_names for our own use, but make sure that the symbols have longer names
  * so they don't conflict with other libraries (like, say, libmm). */
+
+/** Allocate uninitialized memory.
+ *
+ * @return On success, return a pointer to sz newly allocated bytes.
+ *     On failure, set errno to ENOMEM and return NULL.
+ *     If the argument sz is 0, simply return NULL.
+ */
 void *event_mm_malloc_(size_t sz);
+
+/** Allocate memory initialized to zero.
+ *
+ * @return On success, return a pointer to (count * size) newly allocated
+ *     bytes, initialized to zero.
+ *     On failure, or if the product would result in an integer overflow,
+ *     set errno to ENOMEM and return NULL.
+ *     If either arguments are 0, simply return NULL.
+ */
 void *event_mm_calloc_(size_t count, size_t size);
-char *event_mm_strdup_(const char *s);
+
+/** Duplicate a string.
+ *
+ * @return On success, return a pointer to a newly allocated duplicate
+ *     of a string.
+ *     Set errno to ENOMEM and return NULL if a memory allocation error
+ *     occurs (or would occur) in the process.
+ *     If the argument str is NULL, set errno to EINVAL and return NULL.
+ */
+char *event_mm_strdup_(const char *str);
+
 void *event_mm_realloc_(void *p, size_t sz);
 void event_mm_free_(void *p);
 #define mm_malloc(sz) event_mm_malloc_(sz)
index 540d3a13196523cd33b35f0f935e9d993ea8b0b5..51475934b3480e705239eba7664df430eff79de4 100644 (file)
@@ -2,7 +2,7 @@
 
 /*
  * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
+#ifdef EVENT__HAVE_POLL
+
 #include <sys/types.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -49,6 +51,7 @@
 #include "evmap-internal.h"
 #include "event2/thread.h"
 #include "evthread-internal.h"
+#include "time-internal.h"
 
 struct pollidx {
        int idxplus1;
@@ -64,8 +67,8 @@ struct pollop {
 };
 
 static void *poll_init(struct event_base *);
-static int poll_add(struct event_base *, int, short old, short events, void *_idx);
-static int poll_del(struct event_base *, int, short old, short events, void *_idx);
+static int poll_add(struct event_base *, int, short old, short events, void *idx);
+static int poll_del(struct event_base *, int, short old, short events, void *idx);
 static int poll_dispatch(struct event_base *, struct timeval *);
 static void poll_dealloc(struct event_base *);
 
@@ -89,7 +92,9 @@ poll_init(struct event_base *base)
        if (!(pollop = mm_calloc(1, sizeof(struct pollop))))
                return (NULL);
 
-       evsig_init(base);
+       evsig_init_(base);
+
+       evutil_weakrand_seed_(&base->weakrand_seed, 0);
 
        return (pollop);
 }
@@ -128,7 +133,7 @@ poll_dispatch(struct event_base *base, struct timeval *tv)
 
        nfds = pop->nfds;
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        if (base->th_base_lock) {
                /* If we're using this backend in a multithreaded setting,
                 * then we need to work on a copy of event_set, so that we can
@@ -156,7 +161,7 @@ poll_dispatch(struct event_base *base, struct timeval *tv)
 #endif
 
        if (tv != NULL) {
-               msec = evutil_tv_to_msec(tv);
+               msec = evutil_tv_to_msec_(tv);
                if (msec < 0 || msec > INT_MAX)
                        msec = INT_MAX;
        }
@@ -181,7 +186,7 @@ poll_dispatch(struct event_base *base, struct timeval *tv)
        if (res == 0 || nfds == 0)
                return (0);
 
-       i = random() % nfds;
+       i = evutil_weakrand_range_(&base->weakrand_seed, nfds);
        for (j = 0; j < nfds; j++) {
                int what;
                if (++i == nfds)
@@ -202,18 +207,18 @@ poll_dispatch(struct event_base *base, struct timeval *tv)
                if (res == 0)
                        continue;
 
-               evmap_io_active(base, event_set[i].fd, res);
+               evmap_io_active_(base, event_set[i].fd, res);
        }
 
        return (0);
 }
 
 static int
-poll_add(struct event_base *base, int fd, short old, short events, void *_idx)
+poll_add(struct event_base *base, int fd, short old, short events, void *idx_)
 {
        struct pollop *pop = base->evbase;
        struct pollfd *pfd = NULL;
-       struct pollidx *idx = _idx;
+       struct pollidx *idx = idx_;
        int i;
 
        EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
@@ -270,11 +275,11 @@ poll_add(struct event_base *base, int fd, short old, short events, void *_idx)
  */
 
 static int
-poll_del(struct event_base *base, int fd, short old, short events, void *_idx)
+poll_del(struct event_base *base, int fd, short old, short events, void *idx_)
 {
        struct pollop *pop = base->evbase;
        struct pollfd *pfd = NULL;
-       struct pollidx *idx = _idx;
+       struct pollidx *idx = idx_;
        int i;
 
        EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
@@ -308,7 +313,7 @@ poll_del(struct event_base *base, int fd, short old, short events, void *_idx)
                 */
                memcpy(&pop->event_set[i], &pop->event_set[pop->nfds],
                       sizeof(struct pollfd));
-               idx = evmap_io_get_fdinfo(&base->io, pop->event_set[i].fd);
+               idx = evmap_io_get_fdinfo_(&base->io, pop->event_set[i].fd);
                EVUTIL_ASSERT(idx);
                EVUTIL_ASSERT(idx->idxplus1 == pop->nfds + 1);
                idx->idxplus1 = i + 1;
@@ -323,7 +328,7 @@ poll_dealloc(struct event_base *base)
 {
        struct pollop *pop = base->evbase;
 
-       evsig_dealloc(base);
+       evsig_dealloc_(base);
        if (pop->event_set)
                mm_free(pop->event_set);
        if (pop->event_set_copy)
@@ -332,3 +337,5 @@ poll_dealloc(struct event_base *base)
        memset(pop, 0, sizeof(struct pollop));
        mm_free(pop);
 }
+
+#endif /* EVENT__HAVE_POLL */
index df75f8688d38c4d8957416a94bd8c799131d963b..6cc1cdde2c87ff5f05a67ef02ef364b30c9e9f21 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _RATELIM_INTERNAL_H_
-#define _RATELIM_INTERNAL_H_
+#ifndef RATELIM_INTERNAL_H_INCLUDED_
+#define RATELIM_INTERNAL_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -65,13 +65,13 @@ struct ev_token_bucket_cfg {
 
 /** The current tick is 'current_tick': add bytes to 'bucket' as specified in
  * 'cfg'. */
-int ev_token_bucket_update(struct ev_token_bucket *bucket,
+int ev_token_bucket_update_(struct ev_token_bucket *bucket,
     const struct ev_token_bucket_cfg *cfg,
     ev_uint32_t current_tick);
 
 /** In which tick does 'tv' fall according to 'cfg'?  Note that ticks can
  * overflow easily; your code needs to handle this. */
-ev_uint32_t ev_token_bucket_get_tick(const struct timeval *tv,
+ev_uint32_t ev_token_bucket_get_tick_(const struct timeval *tv,
     const struct ev_token_bucket_cfg *cfg);
 
 /** Adjust 'bucket' to respect 'cfg', and note that it was last updated in
@@ -79,12 +79,12 @@ ev_uint32_t ev_token_bucket_get_tick(const struct timeval *tv,
  * configuration of 'bucket'; otherwise, we are setting it up for the first
  * time.
  */
-int ev_token_bucket_init(struct ev_token_bucket *bucket,
+int ev_token_bucket_init_(struct ev_token_bucket *bucket,
     const struct ev_token_bucket_cfg *cfg,
     ev_uint32_t current_tick,
     int reinitialize);
 
-int bufferevent_remove_from_rate_limit_group_internal(struct bufferevent *bev,
+int bufferevent_remove_from_rate_limit_group_internal_(struct bufferevent *bev,
     int unsuspend);
 
 /** Decrease the read limit of 'b' by 'n' bytes */
index 5d02e77b34b03ad85e6b5f92d281894def0a6ba1..b5904ffe76246c4625cd209cc4cc3384f78336b2 100644 (file)
@@ -1,22 +1,34 @@
+# sample/Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
 AUTOMAKE_OPTIONS = foreign no-dependencies
 
 LDADD = $(LIBEVENT_GC_SECTIONS) ../libevent.la
 AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/compat -I$(top_srcdir)/include -I../include
 
-noinst_PROGRAMS = event-test time-test signal-test dns-example hello-world http-server
+noinst_PROGRAMS =                              \
+       dns-example                             \
+       event-read-fifo                         \
+       hello-world                             \
+       http-server                             \
+       signal-test                             \
+       time-test
 
-event_test_sources = event-test.c
-time_test_sources = time-test.c
-signal_test_sources = signal-test.c
-dns_example_sources = dns-example.c
-hello_world_sources = hello-world.c
-http_server_sources = http-server.c
+event_read_fifo_SOURCES = event-read-fifo.c
+time_test_SOURCES = time-test.c
+signal_test_SOURCES = signal-test.c
+dns_example_SOURCES = dns-example.c
+hello_world_SOURCES = hello-world.c
+http_server_SOURCES = http-server.c
 
 if OPENSSL
 AM_CPPFLAGS += $(OPENSSL_INCS)
 noinst_PROGRAMS += le-proxy
-le_proxy_sources = le-proxy.c
-le_proxy_LDADD = $(LDADD) ../libevent_openssl.la
+le_proxy_SOURCES = le-proxy.c
+le_proxy_LDADD = $(LDADD) ../libevent_openssl.la -lssl -lcrypto ${OPENSSL_LIBADD}
 endif
 
 verify:
index d8134e8311b6ffbe81be156904cdc0e39bd8125a..84988554d7837abb6be026bc1804ce125b8c3e90 100644 (file)
@@ -26,7 +26,7 @@
 #include <event2/dns_struct.h>
 #include <event2/util.h>
 
-#ifdef _EVENT_HAVE_NETINET_IN6_H
+#ifdef EVENT__HAVE_NETINET_IN6_H
 #include <netinet/in6.h>
 #endif
 
@@ -145,8 +145,9 @@ main(int c, char **v) {
        int reverse = 0, servertest = 0, use_getaddrinfo = 0;
        struct event_base *event_base = NULL;
        struct evdns_base *evdns_base = NULL;
+       const char *resolv_conf = NULL;
        if (c<2) {
-               fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
+               fprintf(stderr, "syntax: %s [-x] [-v] [-c resolv.conf] hostname\n", v[0]);
                fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
                return 1;
        }
@@ -160,11 +161,23 @@ main(int c, char **v) {
                        use_getaddrinfo = 1;
                else if (!strcmp(v[idx], "-servertest"))
                        servertest = 1;
-               else
+               else if (!strcmp(v[idx], "-c")) {
+                       if (idx + 1 < c)
+                               resolv_conf = v[++idx];
+                       else
+                               fprintf(stderr, "-c needs an argument\n");
+               } else
                        fprintf(stderr, "Unknown option %s\n", v[idx]);
                ++idx;
        }
 
+#ifdef WIN32
+       {
+               WSADATA WSAData;
+               WSAStartup(0x101, &WSAData);
+       }
+#endif
+
        event_base = event_base_new();
        evdns_base = evdns_base_new(event_base, 0);
        evdns_set_log_fn(logfn);
@@ -188,12 +201,20 @@ main(int c, char **v) {
                evdns_add_server_port_with_base(event_base, sock, 0, evdns_server_callback, NULL);
        }
        if (idx < c) {
+               int res;
 #ifdef _WIN32
-               evdns_base_config_windows_nameservers(evdns_base);
-#else
-               evdns_base_resolv_conf_parse(evdns_base, DNS_OPTION_NAMESERVERS,
-                   "/etc/resolv.conf");
+               if (resolv_conf == NULL)
+                       res = evdns_base_config_windows_nameservers(evdns_base);
+               else
 #endif
+                       res = evdns_base_resolv_conf_parse(evdns_base,
+                           DNS_OPTION_NAMESERVERS,
+                           resolv_conf ? resolv_conf : "/etc/resolv.conf");
+
+               if (res < 0) {
+                       fprintf(stderr, "Couldn't configure nameservers");
+                       return 1;
+               }
        }
 
        printf("EVUTIL_AI_CANONNAME in example = %d\n", EVUTIL_AI_CANONNAME);
similarity index 58%
rename from sntp/libevent/sample/event-test.c
rename to sntp/libevent/sample/event-read-fifo.c
index 0bddcf4e9c1be7019426ce9975b30fcdee16acab..8ed265607f84b5d481ec0244ddaf68a83c505580 100644 (file)
@@ -1,11 +1,12 @@
 /*
- * XXX This sample code was once meant to show how to use the basic Libevent
- * interfaces, but it never worked on non-Unix platforms, and some of the
- * interfaces have changed since it was first written.  It should probably
- * be removed or replaced with something better.
+ * This sample code shows how to use Libevent to read from a named pipe.
+ * XXX This code could make better use of the Libevent interfaces.
  *
- * Compile with:
- * cc -I/usr/local/include -o event-test event-test.c -L/usr/local/lib -levent
+ * XXX This does not work on Windows; ignore everything inside the _WIN32 block.
+ *
+ * On UNIX, compile with:
+ * cc -I/usr/local/include -o event-read-fifo event-read-fifo.c \
+ *     -L/usr/local/lib -levent
  */
 
 #include <event2/event-config.h>
@@ -16,6 +17,7 @@
 #include <sys/queue.h>
 #include <unistd.h>
 #include <sys/time.h>
+#include <signal.h>
 #else
 #include <winsock2.h>
 #include <windows.h>
@@ -26,7 +28,7 @@
 #include <string.h>
 #include <errno.h>
 
-#include <event.h>
+#include <event2/event.h>
 
 static void
 fifo_read(int fd, short event, void *arg)
@@ -38,9 +40,6 @@ fifo_read(int fd, short event, void *arg)
        DWORD dwBytesRead;
 #endif
 
-       /* Reschedule this event */
-       event_add(ev, NULL);
-
        fprintf(stderr, "fifo_read called with fd: %d, event: %d, arg: %p\n",
                fd, event, arg);
 #ifdef _WIN32
@@ -57,11 +56,13 @@ fifo_read(int fd, short event, void *arg)
 #else
        len = read(fd, buf, sizeof(buf) - 1);
 
-       if (len == -1) {
-               perror("read");
-               return;
-       } else if (len == 0) {
-               fprintf(stderr, "Connection closed\n");
+       if (len <= 0) {
+               if (len == -1)
+                       perror("read");
+               else if (len == 0)
+                       fprintf(stderr, "Connection closed\n");
+               event_del(ev);
+               event_base_loopbreak(event_get_base(ev));
                return;
        }
 
@@ -70,10 +71,21 @@ fifo_read(int fd, short event, void *arg)
        fprintf(stdout, "Read: %s\n", buf);
 }
 
+/* On Unix, cleanup event.fifo if SIGINT is received. */
+#ifndef _WIN32
+static void
+signal_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct event_base *base = arg;
+       event_base_loopbreak(base);
+}
+#endif
+
 int
 main(int argc, char **argv)
 {
-       struct event evfifo;
+       struct event *evfifo;
+       struct event_base* base;
 #ifdef _WIN32
        HANDLE socket;
        /* Open a file. */
@@ -89,6 +101,7 @@ main(int argc, char **argv)
                return 1;
 
 #else
+       struct event *signal_int;
        struct stat st;
        const char *fifo = "event.fifo";
        int socket;
@@ -107,12 +120,7 @@ main(int argc, char **argv)
                exit(1);
        }
 
-       /* Linux pipes are broken, we need O_RDWR instead of O_RDONLY */
-#ifdef __linux
-       socket = open(fifo, O_RDWR | O_NONBLOCK, 0);
-#else
        socket = open(fifo, O_RDONLY | O_NONBLOCK, 0);
-#endif
 
        if (socket == -1) {
                perror("open");
@@ -122,22 +130,33 @@ main(int argc, char **argv)
        fprintf(stderr, "Write data to %s\n", fifo);
 #endif
        /* Initalize the event library */
-       event_init();
+       base = event_base_new();
 
        /* Initalize one event */
 #ifdef _WIN32
-       event_set(&evfifo, (int)socket, EV_READ, fifo_read, &evfifo);
+       evfifo = event_new(base, (int)socket, EV_READ|EV_PERSIST, fifo_read,
+                           event_self_cbarg());
 #else
-       event_set(&evfifo, socket, EV_READ, fifo_read, &evfifo);
+       /* catch SIGINT so that event.fifo can be cleaned up */
+       signal_int = evsignal_new(base, SIGINT, signal_cb, base);
+       event_add(signal_int, NULL);
+
+       evfifo = event_new(base, socket, EV_READ|EV_PERSIST, fifo_read,
+                           event_self_cbarg());
 #endif
 
        /* Add it to the active events, without a timeout */
-       event_add(&evfifo, NULL);
+       event_add(evfifo, NULL);
 
-       event_dispatch();
+       event_base_dispatch(base);
+       event_base_free(base);
 #ifdef _WIN32
        CloseHandle(socket);
+#else
+       close(socket);
+       unlink(fifo);
 #endif
+       libevent_global_shutdown();
        return (0);
 }
 
index 5196fff116b1eb007e537cffcce95e6b84829027..a02a66f4cb0ef9eb865a556e628873572d80f558 100644 (file)
@@ -6,6 +6,9 @@
 
  */
 
+/* Compatibility for possible missing IPv6 declarations */
+#include "../util-internal.h"
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <event2/util.h>
 #include <event2/keyvalq_struct.h>
 
-#ifdef _EVENT_HAVE_NETINET_IN_H
+#ifdef EVENT__HAVE_NETINET_IN_H
 #include <netinet/in.h>
 # ifdef _XOPEN_SOURCE_EXTENDED
 #  include <arpa/inet.h>
 # endif
 #endif
 
-/* Compatibility for possible missing IPv6 declarations */
-#include "../util-internal.h"
-
 #ifdef _WIN32
 #define stat _stat
 #define fstat _fstat
@@ -134,7 +134,7 @@ dump_request_cb(struct evhttp_request *req, void *arg)
                char cbuf[128];
                n = evbuffer_remove(buf, cbuf, sizeof(buf)-1);
                if (n > 0)
-                   fwrite(cbuf, 1, n, stdout);
+                       (void) fwrite(cbuf, 1, n, stdout);
        }
        puts(">>>");
 
index 3772e2b7ed4ddd1a3ffa7d9e19138d1058a6ae4f..5d432bf00a1d8a2ff59182defaff89f608832eaa 100644 (file)
 #include <string.h>
 #include <errno.h>
 
-#include <event.h>
+#include <event2/event.h>
 
-#ifdef _EVENT___func__
-#define __func__ _EVENT___func__
+#ifdef EVENT____func__
+#define __func__ EVENT____func__
 #endif
 
 int called = 0;
@@ -37,7 +37,7 @@ signal_cb(evutil_socket_t fd, short event, void *arg)
 {
        struct event *signal = arg;
 
-       printf("%s: got signal %d\n", __func__, EVENT_SIGNAL(signal));
+       printf("%s: got signal %d\n", __func__, event_get_signal(signal));
 
        if (called >= 2)
                event_del(signal);
@@ -48,7 +48,7 @@ signal_cb(evutil_socket_t fd, short event, void *arg)
 int
 main(int argc, char **argv)
 {
-       struct event signal_int;
+       struct event *signal_int;
        struct event_base* base;
 #ifdef _WIN32
        WORD wVersionRequested;
@@ -64,10 +64,9 @@ main(int argc, char **argv)
        base = event_base_new();
 
        /* Initalize one event */
-       event_assign(&signal_int, base, SIGINT, EV_SIGNAL|EV_PERSIST, signal_cb,
-           &signal_int);
+       signal_int = evsignal_new(base, SIGINT, signal_cb, event_self_cbarg());
 
-       event_add(&signal_int, NULL);
+       event_add(signal_int, NULL);
 
        event_base_dispatch(base);
        event_base_free(base);
index ddbc029a8a16188f38941305fbb367f164090d34..8d5e869b9b51d08b6dd808524784b033048e79fa 100644 (file)
@@ -18,7 +18,7 @@
 #include <unistd.h>
 #endif
 #include <time.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <fcntl.h>
index 805c08d0efc1b692cb86a6ee3fe92c7fe208e126..8ae53cc11ec56afa7a81dee8310c17e47350fed1 100644 (file)
@@ -2,7 +2,7 @@
 
 /*
  * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -29,6 +29,8 @@
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
+#ifdef EVENT__HAVE_SELECT
+
 #ifdef __APPLE__
 /* Apple wants us to define this if we might ever pass more than
  * FD_SETSIZE bits to select(). */
 #endif
 
 #include <sys/types.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_SELECT_H
+#ifdef EVENT__HAVE_SYS_SELECT_H
 #include <sys/select.h>
 #endif
 #include <sys/queue.h>
@@ -57,7 +59,7 @@
 #include "log-internal.h"
 #include "evmap-internal.h"
 
-#ifndef _EVENT_HAVE_FD_MASK
+#ifndef EVENT__HAVE_FD_MASK
 /* This type is mandatory, but Android doesn't define it. */
 typedef unsigned long fd_mask;
 #endif
@@ -117,7 +119,9 @@ select_init(struct event_base *base)
                return (NULL);
        }
 
-       evsig_init(base);
+       evsig_init_(base);
+
+       evutil_weakrand_seed_(&base->weakrand_seed, 0);
 
        return (sop);
 }
@@ -184,7 +188,7 @@ select_dispatch(struct event_base *base, struct timeval *tv)
        event_debug(("%s: select reports %d", __func__, res));
 
        check_selectop(sop);
-       i = random() % nfds;
+       i = evutil_weakrand_range_(&base->weakrand_seed, nfds);
        for (j = 0; j < nfds; ++j) {
                if (++i >= nfds)
                        i = 0;
@@ -197,7 +201,7 @@ select_dispatch(struct event_base *base, struct timeval *tv)
                if (res == 0)
                        continue;
 
-               evmap_io_active(base, i, res);
+               evmap_io_active_(base, i, res);
        }
        check_selectop(sop);
 
@@ -334,7 +338,9 @@ select_free_selectop(struct selectop *sop)
 static void
 select_dealloc(struct event_base *base)
 {
-       evsig_dealloc(base);
+       evsig_dealloc_(base);
 
        select_free_selectop(base->evbase);
 }
+
+#endif /* EVENT__HAVE_SELECT */
index 2079204dbd71b0d99e655193f8a72da1210363af..e5dd555ecffc6e86338a98a3a9133ff8b4963eb7 100644 (file)
@@ -2,7 +2,7 @@
 
 /*
  * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #undef WIN32_LEAN_AND_MEAN
 #endif
 #include <sys/types.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #include <errno.h>
-#ifdef _EVENT_HAVE_FCNTL_H
+#ifdef EVENT__HAVE_FCNTL_H
 #include <fcntl.h>
 #endif
 
@@ -101,7 +101,7 @@ static const struct eventop evsigops = {
        0, 0, 0
 };
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
 /* Lock for evsig_base and evsig_base_n_signals_added fields. */
 static void *evsig_base_lock = NULL;
 #endif
@@ -117,12 +117,12 @@ static void __cdecl evsig_handler(int sig);
 #define EVSIGBASE_UNLOCK() EVLOCK_UNLOCK(evsig_base_lock, 0)
 
 void
-evsig_set_base(struct event_base *base)
+evsig_set_base_(struct event_base *base)
 {
        EVSIGBASE_LOCK();
        evsig_base = base;
        evsig_base_n_signals_added = base->sig.ev_n_signals_added;
-       evsig_base_fd = base->sig.ev_signal_pair[0];
+       evsig_base_fd = base->sig.ev_signal_pair[1];
        EVSIGBASE_UNLOCK();
 }
 
@@ -141,7 +141,11 @@ evsig_cb(evutil_socket_t fd, short what, void *arg)
        memset(&ncaught, 0, sizeof(ncaught));
 
        while (1) {
+#ifdef _WIN32
                n = recv(fd, signals, sizeof(signals), 0);
+#else
+               n = read(fd, signals, sizeof(signals));
+#endif
                if (n == -1) {
                        int err = evutil_socket_geterror(fd);
                        if (! EVUTIL_ERR_RW_RETRIABLE(err))
@@ -161,21 +165,20 @@ evsig_cb(evutil_socket_t fd, short what, void *arg)
        EVBASE_ACQUIRE_LOCK(base, th_base_lock);
        for (i = 0; i < NSIG; ++i) {
                if (ncaught[i])
-                       evmap_signal_active(base, i, ncaught[i]);
+                       evmap_signal_active_(base, i, ncaught[i]);
        }
        EVBASE_RELEASE_LOCK(base, th_base_lock);
 }
 
 int
-evsig_init(struct event_base *base)
+evsig_init_(struct event_base *base)
 {
        /*
         * Our signal handler is going to write to one end of the socket
         * pair to wake up our event loop.  The event loop then scans for
         * signals that got delivered.
         */
-       if (evutil_socketpair(
-                   AF_UNIX, SOCK_STREAM, 0, base->sig.ev_signal_pair) == -1) {
+       if (evutil_make_internal_pipe_(base->sig.ev_signal_pair) == -1) {
 #ifdef _WIN32
                /* Make this nonfatal on win32, where sometimes people
                   have localhost firewalled. */
@@ -186,15 +189,13 @@ evsig_init(struct event_base *base)
                return -1;
        }
 
-       evutil_make_socket_closeonexec(base->sig.ev_signal_pair[0]);
-       evutil_make_socket_closeonexec(base->sig.ev_signal_pair[1]);
+       if (base->sig.sh_old) {
+               mm_free(base->sig.sh_old);
+       }
        base->sig.sh_old = NULL;
        base->sig.sh_old_max = 0;
 
-       evutil_make_socket_nonblocking(base->sig.ev_signal_pair[0]);
-       evutil_make_socket_nonblocking(base->sig.ev_signal_pair[1]);
-
-       event_assign(&base->sig.ev_signal, base, base->sig.ev_signal_pair[1],
+       event_assign(&base->sig.ev_signal, base, base->sig.ev_signal_pair[0],
                EV_READ | EV_PERSIST, evsig_cb, base);
 
        base->sig.ev_signal.ev_flags |= EVLIST_INTERNAL;
@@ -208,10 +209,10 @@ evsig_init(struct event_base *base)
 /* Helper: set the signal handler for evsignal to handler in base, so that
  * we can restore the original handler when we clear the current one. */
 int
-_evsig_set_handler(struct event_base *base,
+evsig_set_handler_(struct event_base *base,
     int evsignal, void (__cdecl *handler)(int))
 {
-#ifdef _EVENT_HAVE_SIGACTION
+#ifdef EVENT__HAVE_SIGACTION
        struct sigaction sa;
 #else
        ev_sighandler_t sh;
@@ -248,7 +249,7 @@ _evsig_set_handler(struct event_base *base,
        }
 
        /* save previous handler and setup new handler */
-#ifdef _EVENT_HAVE_SIGACTION
+#ifdef EVENT__HAVE_SIGACTION
        memset(&sa, 0, sizeof(sa));
        sa.sa_handler = handler;
        sa.sa_flags |= SA_RESTART;
@@ -294,11 +295,11 @@ evsig_add(struct event_base *base, evutil_socket_t evsignal, short old, short ev
        }
        evsig_base = base;
        evsig_base_n_signals_added = ++sig->ev_n_signals_added;
-       evsig_base_fd = base->sig.ev_signal_pair[0];
+       evsig_base_fd = base->sig.ev_signal_pair[1];
        EVSIGBASE_UNLOCK();
 
        event_debug(("%s: %d: changing signal handler", __func__, (int)evsignal));
-       if (_evsig_set_handler(base, (int)evsignal, evsig_handler) == -1) {
+       if (evsig_set_handler_(base, (int)evsignal, evsig_handler) == -1) {
                goto err;
        }
 
@@ -320,20 +321,26 @@ err:
 }
 
 int
-_evsig_restore_handler(struct event_base *base, int evsignal)
+evsig_restore_handler_(struct event_base *base, int evsignal)
 {
        int ret = 0;
        struct evsig_info *sig = &base->sig;
-#ifdef _EVENT_HAVE_SIGACTION
+#ifdef EVENT__HAVE_SIGACTION
        struct sigaction *sh;
 #else
        ev_sighandler_t *sh;
 #endif
 
+       if (evsignal >= sig->sh_old_max) {
+               /* Can't actually restore. */
+               /* XXXX.*/
+               return 0;
+       }
+
        /* restore previous handler */
        sh = sig->sh_old[evsignal];
        sig->sh_old[evsignal] = NULL;
-#ifdef _EVENT_HAVE_SIGACTION
+#ifdef EVENT__HAVE_SIGACTION
        if (sigaction(evsignal, sh, NULL) == -1) {
                event_warn("sigaction");
                ret = -1;
@@ -362,7 +369,7 @@ evsig_del(struct event_base *base, evutil_socket_t evsignal, short old, short ev
        --base->sig.ev_n_signals_added;
        EVSIGBASE_UNLOCK();
 
-       return (_evsig_restore_handler(base, (int)evsignal));
+       return (evsig_restore_handler_(base, (int)evsignal));
 }
 
 static void __cdecl
@@ -381,13 +388,20 @@ evsig_handler(int sig)
                return;
        }
 
-#ifndef _EVENT_HAVE_SIGACTION
+#ifndef EVENT__HAVE_SIGACTION
        signal(sig, evsig_handler);
 #endif
 
        /* Wake up our notification mechanism */
        msg = sig;
+#ifdef _WIN32
        send(evsig_base_fd, (char*)&msg, 1, 0);
+#else
+       {
+               int r = write(evsig_base_fd, (char*)&msg, 1);
+               (void)r; /* Suppress 'unused return value' and 'unused var' */
+       }
+#endif
        errno = save_errno;
 #ifdef _WIN32
        EVUTIL_SET_SOCKET_ERROR(socket_errno);
@@ -395,20 +409,20 @@ evsig_handler(int sig)
 }
 
 void
-evsig_dealloc(struct event_base *base)
+evsig_dealloc_(struct event_base *base)
 {
        int i = 0;
        if (base->sig.ev_signal_added) {
                event_del(&base->sig.ev_signal);
                base->sig.ev_signal_added = 0;
        }
-       /* debug event is created in evsig_init/event_assign even when
+       /* debug event is created in evsig_init_/event_assign even when
         * ev_signal_added == 0, so unassign is required */
        event_debug_unassign(&base->sig.ev_signal);
 
        for (i = 0; i < NSIG; ++i) {
                if (i < base->sig.sh_old_max && base->sig.sh_old[i] != NULL)
-                       _evsig_restore_handler(base, i);
+                       evsig_restore_handler_(base, i);
        }
        EVSIGBASE_LOCK();
        if (base == evsig_base) {
@@ -435,11 +449,30 @@ evsig_dealloc(struct event_base *base)
        }
 }
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+static void
+evsig_free_globals_locks(void)
+{
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+       if (evsig_base_lock != NULL) {
+               EVTHREAD_FREE_LOCK(evsig_base_lock, 0);
+               evsig_base_lock = NULL;
+       }
+#endif
+       return;
+}
+
+void
+evsig_free_globals_(void)
+{
+       evsig_free_globals_locks();
+}
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
 int
 evsig_global_setup_locks_(const int enable_locks)
 {
        EVTHREAD_SETUP_GLOBAL_LOCK(evsig_base_lock, 0);
        return 0;
 }
+
 #endif
index 4152b7bd015fe0212d4aaf5553caa5865f84e5fd..cfc27ec662764d8b3de68b3815c3bf045cdcb44b 100644 (file)
@@ -1,5 +1,5 @@
-#ifndef _STRLCPY_INTERNAL_H_
-#define _STRLCPY_INTERNAL_H_
+#ifndef STRLCPY_INTERNAL_H_INCLUDED_
+#define STRLCPY_INTERNAL_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -8,10 +8,10 @@ extern "C" {
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
-#ifndef _EVENT_HAVE_STRLCPY
+#ifndef EVENT__HAVE_STRLCPY
 #include <string.h>
-size_t _event_strlcpy(char *dst, const char *src, size_t siz);
-#define strlcpy _event_strlcpy
+size_t event_strlcpy_(char *dst, const char *src, size_t siz);
+#define strlcpy event_strlcpy_
 #endif
 
 #ifdef __cplusplus
index 3656e9f0642a8308d1326affdc70d862f064f3c5..3876475f5a6fa4d6e8aff897daee2f0b491fde63 100644 (file)
@@ -36,7 +36,7 @@ static char *rcsid = "$OpenBSD: strlcpy.c,v 1.5 2001/05/13 15:40:16 deraadt Exp
 
 #include <sys/types.h>
 
-#ifndef _EVENT_HAVE_STRLCPY
+#ifndef EVENT__HAVE_STRLCPY
 #include "strlcpy-internal.h"
 
 /*
@@ -45,7 +45,7 @@ static char *rcsid = "$OpenBSD: strlcpy.c,v 1.5 2001/05/13 15:40:16 deraadt Exp
  * Returns strlen(src); if retval >= siz, truncation occurred.
  */
 size_t
-_event_strlcpy(dst, src, siz)
+event_strlcpy_(dst, src, siz)
        char *dst;
        const char *src;
        size_t siz;
index bcda535c0269cd245b423f6c64fd6eedf7553dc0..a953edcafe54888030af00cd45ec414d1863f25f 100644 (file)
@@ -1,17 +1,45 @@
+# test/Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
 AUTOMAKE_OPTIONS = foreign
 
 AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/compat -I$(top_srcdir)/include -I../include -DTINYTEST_LOCAL
 
-EXTRA_DIST = regress.rpc regress.gen.h regress.gen.c rpcgen_wrapper.sh test.sh
+EXTRA_DIST =                                   \
+       check-dumpevents.py                     \
+       regress.gen.c                           \
+       regress.gen.h                           \
+       regress.rpc                             \
+       rpcgen_wrapper.sh                       \
+       test.sh
+
+noinst_PROGRAMS = \
+       bench                                   \
+       bench_cascade                           \
+       bench_http                              \
+       bench_httpclient                        \
+       test-changelist                         \
+       test-dumpevents                         \
+       test-eof                                \
+       test-fdleak                             \
+       test-init                               \
+       test-ratelim                            \
+       test-time                               \
+       test-weof
 
-noinst_PROGRAMS = test-init test-eof test-weof test-time \
-       bench bench_cascade bench_http bench_httpclient test-ratelim \
-       test-changelist
 if BUILD_REGRESS
 noinst_PROGRAMS += regress
 endif
 EXTRA_PROGRAMS = regress
-noinst_HEADERS = tinytest.h tinytest_macros.h regress.h tinytest_local.h
+
+noinst_HEADERS =                               \
+       regress.h                               \
+       tinytest.h                              \
+       tinytest_local.h                        \
+       tinytest_macros.h
 
 TESTS = $(top_srcdir)/test/test.sh
 
@@ -22,6 +50,8 @@ endif
 
 test_init_SOURCES = test-init.c
 test_init_LDADD = ../libevent_core.la
+test_dumpevents_SOURCES = test-dumpevents.c
+test_dumpevents_LDADD = ../libevent_core.la
 test_eof_SOURCES = test-eof.c
 test_eof_LDADD = ../libevent_core.la
 test_changelist_SOURCES = test-changelist.c
@@ -32,13 +62,29 @@ test_time_SOURCES = test-time.c
 test_time_LDADD = ../libevent_core.la
 test_ratelim_SOURCES = test-ratelim.c
 test_ratelim_LDADD = ../libevent_core.la -lm
+test_fdleak_SOURCES = test-fdleak.c
+test_fdleak_LDADD = ../libevent_core.la
+
+regress_SOURCES =                              \
+       regress.c                               \
+       regress.gen.c                           \
+       regress.gen.h                           \
+       regress_buffer.c                        \
+       regress_bufferevent.c                   \
+       regress_dns.c                           \
+       regress_et.c                            \
+       regress_http.c                          \
+       regress_listener.c                      \
+       regress_main.c                          \
+       regress_minheap.c                       \
+       regress_rpc.c                           \
+       regress_testutils.c                     \
+       regress_testutils.h                     \
+       regress_util.c                          \
+       tinytest.c                              \
+       $(regress_thread_SOURCES)               \
+       $(regress_zlib_SOURCES)
 
-regress_SOURCES = regress.c regress_buffer.c regress_http.c regress_dns.c \
-       regress_testutils.c regress_testutils.h \
-       regress_rpc.c regress.gen.c regress.gen.h regress_et.c \
-       regress_bufferevent.c regress_listener.c \
-       regress_util.c tinytest.c regress_main.c regress_minheap.c \
-       $(regress_thread_SOURCES) $(regress_zlib_SOURCES)
 if PTHREADS
 regress_thread_SOURCES = regress_thread.c
 PTHREAD_LIBS += ../libevent_pthreads.la
@@ -59,7 +105,7 @@ regress_LDFLAGS = $(PTHREAD_CFLAGS)
 
 if OPENSSL
 regress_SOURCES += regress_ssl.c
-regress_LDADD += ../libevent_openssl.la
+regress_LDADD += ../libevent_openssl.la -lssl -lcrypto ${OPENSSL_LIBADD}
 endif
 
 bench_SOURCES = bench.c
@@ -89,4 +135,5 @@ DISTCLEANFILES = *~
 
 verify: check
 
-bench test-init test-eof test-weof test-time test-changelist: ../libevent.la
+bench test-init test-eof test-weof test-time test-changelist \
+       test-fdleak: ../libevent.la
index 47e8b4d2bc39a38419a0647d23e946be0c07dd3f..7686c71c7393f45bd801a48e70ea3168eb29ac62 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright 2003-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -37,7 +37,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #ifdef _WIN32
@@ -52,7 +52,7 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #include <errno.h>
index f23b58c276993817b0928b8a41052e3eca08eb45..e9293228582aa25d4dad9ffa166969072e3733cf 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -29,7 +29,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #ifdef _WIN32
@@ -44,7 +44,7 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #include <errno.h>
index a6aa4b7f8adcc57b9ec20e356473577a43461b01..09f521b5c49c0eee3e3c37f1d4777e5e4d9214e9 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008-2010 Niels Provos and Nick Mathewson
+ * Copyright 2008-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -169,10 +169,8 @@ main(int argc, char **argv)
        evhttp_set_cb(http, "/ind", http_basic_cb, NULL);
        fprintf(stderr, "/ind - basic content (memory copy)\n");
 
-#ifdef _EVENT2_EVENT_H_
        evhttp_set_cb(http, "/ref", http_ref_cb, NULL);
        fprintf(stderr, "/ref - basic content (reference)\n");
-#endif
 
        fprintf(stderr, "Serving %d bytes on port %d using %s\n",
            (int)content_len, port,
index 73797554a72152a8f2b11c2182b1f79964fc68f7..727abc67987cb167ba8008e73e6baf03ac536b5d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -25,6 +25,9 @@
  *
  */
 
+/* for EVUTIL_ERR_CONNECT_RETRIABLE macro */
+#include "util-internal.h"
+
 #include <sys/types.h>
 #ifdef _WIN32
 #include <winsock2.h>
@@ -44,9 +47,6 @@
 #include "event2/buffer.h"
 #include "event2/util.h"
 
-/* for EVUTIL_ERR_CONNECT_RETRIABLE macro */
-#include "util-internal.h"
-
 const char *resource = NULL;
 struct event_base *base = NULL;
 
diff --git a/sntp/libevent/test/check-dumpevents.py b/sntp/libevent/test/check-dumpevents.py
new file mode 100755 (executable)
index 0000000..7d74932
--- /dev/null
@@ -0,0 +1,54 @@
+#!/usr/bin/python
+#
+# Post-process the output of test-dumpevents and check it for correctness.
+#
+
+import math
+import re
+import sys
+
+text = sys.stdin.readlines()
+
+try:
+    expect_inserted_pos = text.index("Inserted:\n")
+    expect_active_pos = text.index("Active:\n")
+    got_inserted_pos = text.index("Inserted events:\n")
+    got_active_pos = text.index("Active events:\n")
+except ValueError:
+    print >>sys.stderr, "Missing expected dividing line in dumpevents output"
+    sys.exit(1)
+
+if not (expect_inserted_pos < expect_active_pos <
+        got_inserted_pos < got_active_pos):
+    print >>sys.stderr, "Sections out of order in dumpevents output"
+    sys.exit(1)
+
+now,T= text[1].split()
+T = float(T)
+
+want_inserted = set(text[expect_inserted_pos+1:expect_active_pos])
+want_active = set(text[expect_active_pos+1:got_inserted_pos-1])
+got_inserted = set(text[got_inserted_pos+1:got_active_pos])
+got_active = set(text[got_active_pos+1:])
+
+pat = re.compile(r'Timeout=([0-9\.]+)')
+def replace_time(m):
+    t = float(m.group(1))
+    if .9 < abs(t-T) < 1.1:
+        return "Timeout=T+1"
+    elif 2.4 < abs(t-T) < 2.6:
+        return "Timeout=T+2.5"
+    else:
+        return m.group(0)
+
+cleaned_inserted = set( pat.sub(replace_time, s) for s in got_inserted
+                        if "Internal" not in s)
+
+if cleaned_inserted != want_inserted:
+    print >>sys.stderr, "Inserted event lists were not as expected!"
+    sys.exit(1)
+
+if set(got_active) != set(want_active):
+    print >>sys.stderr, "Active event lists were not as expected!"
+    sys.exit(1)
+
index 5d408dc9e70ae86a8fab0a4bcf6d9f8acb983af4..0c5faed76374dd6d60a4e254b251955297361beb 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,6 +24,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "util-internal.h"
 
 #ifdef _WIN32
 #include <winsock2.h>
@@ -34,7 +35,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -63,8 +64,8 @@
 #include "event2/util.h"
 #include "event-internal.h"
 #include "evthread-internal.h"
-#include "util-internal.h"
 #include "log-internal.h"
+#include "time-internal.h"
 
 #include "regress.h"
 
@@ -87,7 +88,6 @@ static struct timeval tcalled;
 
 
 #define TEST1  "this is a test"
-#define SECONDS        1
 
 #ifndef SHUT_WR
 #define SHUT_WR 1
@@ -233,21 +233,7 @@ multiple_read_cb(evutil_socket_t fd, short event, void *arg)
 static void
 timeout_cb(evutil_socket_t fd, short event, void *arg)
 {
-       struct timeval tv;
-       int diff;
-
        evutil_gettimeofday(&tcalled, NULL);
-       if (evutil_timercmp(&tcalled, &tset, >))
-               evutil_timersub(&tcalled, &tset, &tv);
-       else
-               evutil_timersub(&tset, &tcalled, &tv);
-
-       diff = tv.tv_sec*1000 + tv.tv_usec/1000 - SECONDS * 1000;
-       if (diff < 0)
-               diff = -diff;
-
-       if (diff < 100)
-               test_ok = 1;
 }
 
 struct both {
@@ -316,7 +302,10 @@ test_simpleread(void)
        /* Very simple read test */
        setup_test("Simple read: ");
 
-       write(pair[0], TEST1, strlen(TEST1)+1);
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
+
        shutdown(pair[0], SHUT_WR);
 
        event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
@@ -358,7 +347,10 @@ test_simpleread_multiple(void)
        /* Very simple read test */
        setup_test("Simple read to multiple evens: ");
 
-       write(pair[0], TEST1, strlen(TEST1)+1);
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
+
        shutdown(pair[0], SHUT_WR);
 
        event_set(&one, pair[1], EV_READ, simpleread_multiple_cb, NULL);
@@ -577,14 +569,18 @@ test_simpletimeout(void)
 
        setup_test("Simple timeout: ");
 
-       tv.tv_usec = 0;
-       tv.tv_sec = SECONDS;
+       tv.tv_usec = 200*1000;
+       tv.tv_sec = 0;
+       evutil_timerclear(&tcalled);
        evtimer_set(&ev, timeout_cb, NULL);
        evtimer_add(&ev, &tv);
 
        evutil_gettimeofday(&tset, NULL);
        event_dispatch();
+       test_timeval_diff_eq(&tset, &tcalled, 200);
 
+       test_ok = 1;
+end:
        cleanup_test();
 }
 
@@ -621,6 +617,28 @@ test_persistent_timeout(void)
        event_del(&ev);
 }
 
+static void
+test_persistent_timeout_jump(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event ev;
+       int count = 0;
+       struct timeval msec100 = { 0, 100 * 1000 };
+       struct timeval msec50 = { 0, 50 * 1000 };
+       struct timeval msec300 = { 0, 300 * 1000 };
+
+       event_assign(&ev, data->base, -1, EV_PERSIST, periodic_timeout_cb, &count);
+       event_add(&ev, &msec100);
+       /* Wait for a bit */
+       evutil_usleep_(&msec300);
+       event_base_loopexit(data->base, &msec50);
+       event_base_dispatch(data->base);
+       tt_int_op(count, ==, 1);
+
+end:
+       event_del(&ev);
+}
+
 struct persist_active_timeout_called {
        int n;
        short events[16];
@@ -671,9 +689,11 @@ test_persistent_active_timeout(void *ptr)
        tv_exit.tv_usec = 600 * 1000;
        event_base_loopexit(base, &tv_exit);
 
+       event_base_assert_ok_(base);
        evutil_gettimeofday(&start, NULL);
 
        event_base_dispatch(base);
+       event_base_assert_ok_(base);
 
        tt_int_op(res.n, ==, 3);
        tt_int_op(res.events[0], ==, EV_READ);
@@ -699,7 +719,7 @@ common_timeout_cb(evutil_socket_t fd, short event, void *arg)
        struct common_timeout_info *ti = arg;
        ++ti->count;
        evutil_gettimeofday(&ti->called_at, NULL);
-       if (ti->count >= 6)
+       if (ti->count >= 4)
                event_del(&ti->ev);
 }
 
@@ -712,7 +732,7 @@ test_common_timeout(void *ptr)
        int i;
        struct common_timeout_info info[100];
 
-       struct timeval now;
+       struct timeval start;
        struct timeval tmp_100_ms = { 0, 100*1000 };
        struct timeval tmp_200_ms = { 0, 200*1000 };
 
@@ -736,28 +756,40 @@ test_common_timeout(void *ptr)
                event_assign(&info[i].ev, base, -1, EV_TIMEOUT|EV_PERSIST,
                    common_timeout_cb, &info[i]);
                if (i % 2) {
-                       event_add(&info[i].ev, ms_100);
+                       if ((i%20)==1) {
+                               /* Glass-box test: Make sure we survive the
+                                * transition to non-common timeouts. It's
+                                * a little tricky. */
+                               event_add(&info[i].ev, ms_200);
+                               event_add(&info[i].ev, &tmp_100_ms);
+                       } else if ((i%20)==3) {
+                               /* Check heap-to-common too. */
+                               event_add(&info[i].ev, &tmp_200_ms);
+                               event_add(&info[i].ev, ms_100);
+                       } else if ((i%20)==5) {
+                               /* Also check common-to-common. */
+                               event_add(&info[i].ev, ms_200);
+                               event_add(&info[i].ev, ms_100);
+                       } else {
+                               event_add(&info[i].ev, ms_100);
+                       }
                } else {
                        event_add(&info[i].ev, ms_200);
                }
        }
 
+       event_base_assert_ok_(base);
+       evutil_gettimeofday(&start, NULL);
        event_base_dispatch(base);
 
-       evutil_gettimeofday(&now, NULL);
+       event_base_assert_ok_(base);
 
        for (i=0; i<10; ++i) {
-               struct timeval tmp;
-               int ms_diff;
-               tt_int_op(info[i].count, ==, 6);
-               evutil_timersub(&now, &info[i].called_at, &tmp);
-               ms_diff = tmp.tv_usec/1000 + tmp.tv_sec*1000;
+               tt_int_op(info[i].count, ==, 4);
                if (i % 2) {
-                       tt_int_op(ms_diff, >, 500);
-                       tt_int_op(ms_diff, <, 700);
+                       test_timeval_diff_eq(&start, &info[i].called_at, 400);
                } else {
-                       tt_int_op(ms_diff, >, -100);
-                       tt_int_op(ms_diff, <, 100);
+                       test_timeval_diff_eq(&start, &info[i].called_at, 800);
                }
        }
 
@@ -807,7 +839,9 @@ test_fork(void)
        tt_assert(current_base);
        evthread_make_base_notifiable(current_base);
 
-       write(pair[0], TEST1, strlen(TEST1)+1);
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
 
        event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
        if (event_add(&ev, NULL) == -1)
@@ -816,12 +850,19 @@ test_fork(void)
        evsignal_set(&sig_ev, SIGCHLD, child_signal_cb, &got_sigchld);
        evsignal_add(&sig_ev, NULL);
 
-       if ((pid = fork()) == 0) {
+       event_base_assert_ok_(current_base);
+       TT_BLATHER(("Before fork"));
+       if ((pid = regress_fork()) == 0) {
                /* in the child */
+               TT_BLATHER(("In child, before reinit"));
+               event_base_assert_ok_(current_base);
                if (event_reinit(current_base) == -1) {
                        fprintf(stdout, "FAILED (reinit)\n");
                        exit(1);
                }
+               TT_BLATHER(("After reinit"));
+               event_base_assert_ok_(current_base);
+               TT_BLATHER(("After assert-ok"));
 
                evsignal_del(&sig_ev);
 
@@ -838,14 +879,21 @@ test_fork(void)
        }
 
        /* wait for the child to read the data */
-       sleep(1);
+       {
+               const struct timeval tv = { 0, 100000 };
+               evutil_usleep_(&tv);
+       }
 
-       write(pair[0], TEST1, strlen(TEST1)+1);
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
 
+       TT_BLATHER(("Before waitpid"));
        if (waitpid(pid, &status, 0) == -1) {
                fprintf(stdout, "FAILED (fork)\n");
                exit(1);
        }
+       TT_BLATHER(("After waitpid"));
 
        if (WEXITSTATUS(status) != 76) {
                fprintf(stdout, "FAILED (exit): %d\n", WEXITSTATUS(status));
@@ -853,7 +901,10 @@ test_fork(void)
        }
 
        /* test that the current event loop still works */
-       write(pair[0], TEST1, strlen(TEST1)+1);
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               fprintf(stderr, "%s: write\n", __func__);
+       }
+
        shutdown(pair[0], SHUT_WR);
 
        event_dispatch();
@@ -898,7 +949,8 @@ test_simplesignal(void)
        evsignal_add(&ev, NULL);
 
        memset(&itv, 0, sizeof(itv));
-       itv.it_value.tv_sec = 1;
+       itv.it_value.tv_sec = 0;
+       itv.it_value.tv_usec = 100000;
        if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
                goto skip_simplesignal;
 
@@ -925,7 +977,8 @@ test_multiplesignal(void)
        evsignal_add(&ev_two, NULL);
 
        memset(&itv, 0, sizeof(itv));
-       itv.it_value.tv_sec = 1;
+       itv.it_value.tv_sec = 0;
+       itv.it_value.tv_usec = 100000;
        if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
                goto skip_simplesignal;
 
@@ -1088,12 +1141,12 @@ test_signal_restore(void)
 {
        struct event ev;
        struct event_base *base = event_init();
-#ifdef _EVENT_HAVE_SIGACTION
+#ifdef EVENT__HAVE_SIGACTION
        struct sigaction sa;
 #endif
 
        test_ok = 0;
-#ifdef _EVENT_HAVE_SIGACTION
+#ifdef EVENT__HAVE_SIGACTION
        sa.sa_handler = signal_cb_sa;
        sa.sa_flags = 0x0;
        sigemptyset(&sa.sa_mask);
@@ -1213,6 +1266,43 @@ end:
        event_del(&ev1);
 }
 
+static void
+event_selfarg_cb(evutil_socket_t fd, short event, void *arg)
+{
+       struct event *ev = arg;
+       struct event_base *base = event_get_base(ev);
+       event_base_assert_ok_(base);
+       event_base_loopexit(base, NULL);
+       tt_want(ev == event_base_get_running_event(base));
+}
+
+static void
+test_event_new_selfarg(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event_base *base = data->base;
+       struct event *ev = event_new(base, -1, EV_READ, event_selfarg_cb,
+                                     event_self_cbarg());
+
+       event_active(ev, EV_READ, 1);
+       event_base_dispatch(base);
+
+       event_free(ev);
+}
+
+static void
+test_event_assign_selfarg(void *ptr)
+{
+       struct basic_test_data *data = ptr;
+       struct event_base *base = data->base;
+       struct event ev;
+
+       event_assign(&ev, base, -1, EV_READ, event_selfarg_cb,
+                     event_self_cbarg());
+       event_active(&ev, EV_READ, 1);
+       event_base_dispatch(base);
+}
+
 static void
 test_bad_assign(void *ptr)
 {
@@ -1314,23 +1404,22 @@ test_loopexit(void)
        evtimer_set(&ev, timeout_cb, NULL);
        evtimer_add(&ev, &tv);
 
-       tv.tv_usec = 0;
-       tv.tv_sec = 1;
+       tv.tv_usec = 300*1000;
+       tv.tv_sec = 0;
        event_loopexit(&tv);
 
        evutil_gettimeofday(&tv_start, NULL);
        event_dispatch();
        evutil_gettimeofday(&tv_end, NULL);
-       evutil_timersub(&tv_end, &tv_start, &tv_end);
 
        evtimer_del(&ev);
 
        tt_assert(event_base_got_exit(global_base));
        tt_assert(!event_base_got_break(global_base));
 
-       if (tv.tv_sec < 2)
-               test_ok = 1;
+       test_timeval_diff_eq(&tv_start, &tv_end, 300);
 
+       test_ok = 1;
 end:
        cleanup_test();
 }
@@ -1338,28 +1427,32 @@ end:
 static void
 test_loopexit_multiple(void)
 {
-       struct timeval tv;
+       struct timeval tv, tv_start, tv_end;
        struct event_base *base;
 
        setup_test("Loop Multiple exit: ");
 
        base = event_base_new();
 
-       tv.tv_usec = 0;
-       tv.tv_sec = 1;
+       tv.tv_usec = 200*1000;
+       tv.tv_sec = 0;
        event_base_loopexit(base, &tv);
 
        tv.tv_usec = 0;
-       tv.tv_sec = 2;
+       tv.tv_sec = 3;
        event_base_loopexit(base, &tv);
 
+       evutil_gettimeofday(&tv_start, NULL);
        event_base_dispatch(base);
+       evutil_gettimeofday(&tv_end, NULL);
 
        tt_assert(event_base_got_exit(base));
        tt_assert(!event_base_got_break(base));
 
        event_base_free(base);
 
+       test_timeval_diff_eq(&tv_start, &tv_end, 200);
+
        test_ok = 1;
 
 end:
@@ -1413,7 +1506,11 @@ re_add_read_cb(evutil_socket_t fd, short event, void *arg)
        char buf[256];
        struct event *ev_other = arg;
        readd_test_event_last_added = ev_other;
-       (void) read(fd, buf, sizeof(buf));
+
+       if (read(fd, buf, sizeof(buf)) < 0) {
+               tt_fail_perror("read");
+       }
+
        event_add(ev_other, NULL);
        ++test_ok;
 }
@@ -1426,8 +1523,15 @@ test_nonpersist_readd(void)
        setup_test("Re-add nonpersistent events: ");
        event_set(&ev1, pair[0], EV_READ, re_add_read_cb, &ev2);
        event_set(&ev2, pair[1], EV_READ, re_add_read_cb, &ev1);
-       (void) write(pair[0], "Hello", 5);
-       (void) write(pair[1], "Hello", 5);
+
+       if (write(pair[0], "Hello", 5) < 0) {
+               tt_fail_perror("write(pair[0])");
+       }
+
+       if (write(pair[1], "Hello", 5) < 0) {
+               tt_fail_perror("write(pair[1])\n");
+       }
+
        if (event_add(&ev1, NULL) == -1 ||
            event_add(&ev2, NULL) == -1) {
                test_ok = 0;
@@ -1542,6 +1646,58 @@ test_priorities(void)
                test_priorities_impl(3);
 }
 
+/* priority-active-inversion: activate a higher-priority event, and make sure
+ * it keeps us from running a lower-priority event first. */
+static int n_pai_calls = 0;
+static struct event pai_events[3];
+
+static void
+prio_active_inversion_cb(evutil_socket_t fd, short what, void *arg)
+{
+       int *call_order = arg;
+       *call_order = n_pai_calls++;
+       if (n_pai_calls == 1) {
+               /* This should activate later, even though it shares a
+                  priority with us. */
+               event_active(&pai_events[1], EV_READ, 1);
+               /* This should activate next, since its priority is higher,
+                  even though we activated it second. */
+               event_active(&pai_events[2], EV_TIMEOUT, 1);
+       }
+}
+
+static void
+test_priority_active_inversion(void *data_)
+{
+       struct basic_test_data *data = data_;
+       struct event_base *base = data->base;
+       int call_order[3];
+       int i;
+       tt_int_op(event_base_priority_init(base, 8), ==, 0);
+
+       n_pai_calls = 0;
+       memset(call_order, 0, sizeof(call_order));
+
+       for (i=0;i<3;++i) {
+               event_assign(&pai_events[i], data->base, -1, 0,
+                   prio_active_inversion_cb, &call_order[i]);
+       }
+
+       event_priority_set(&pai_events[0], 4);
+       event_priority_set(&pai_events[1], 4);
+       event_priority_set(&pai_events[2], 0);
+
+       event_active(&pai_events[0], EV_WRITE, 1);
+
+       event_base_dispatch(base);
+       tt_int_op(n_pai_calls, ==, 3);
+       tt_int_op(call_order[0], ==, 0);
+       tt_int_op(call_order[1], ==, 2);
+       tt_int_op(call_order[2], ==, 1);
+end:
+       ;
+}
+
 
 static void
 test_multiple_cb(evutil_socket_t fd, short event, void *arg)
@@ -1565,7 +1721,11 @@ test_multiple_events_for_same_fd(void)
    event_add(&e2, NULL);
    event_loop(EVLOOP_ONCE);
    event_del(&e2);
-   write(pair[1], TEST1, strlen(TEST1)+1);
+
+   if (write(pair[1], TEST1, strlen(TEST1)+1) < 0) {
+          tt_fail_perror("write");
+   }
+
    event_loop(EVLOOP_ONCE);
    event_del(&e1);
 
@@ -1592,8 +1752,12 @@ read_once_cb(evutil_socket_t fd, short event, void *arg)
                test_ok = 0;
        } else if (len) {
                /* Assumes global pair[0] can be used for writing */
-               write(pair[0], TEST1, strlen(TEST1)+1);
-               test_ok = 1;
+               if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+                       tt_fail_perror("write");
+                       test_ok = 0;
+               } else {
+                       test_ok = 1;
+               }
        }
 
        called++;
@@ -1608,11 +1772,13 @@ test_want_only_once(void)
        /* Very simple read test */
        setup_test("Want read only once: ");
 
-       write(pair[0], TEST1, strlen(TEST1)+1);
+       if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
 
        /* Setup the loop termination */
        evutil_timerclear(&tv);
-       tv.tv_sec = 1;
+       tv.tv_usec = 300*1000;
        event_loopexit(&tv);
 
        event_set(&ev, pair[1], EV_READ, read_once_cb, &ev);
@@ -1850,10 +2016,10 @@ end:
                event_config_free(cfg);
 }
 
-#ifdef _EVENT_HAVE_SETENV
+#ifdef EVENT__HAVE_SETENV
 #define SETENV_OK
-#elif !defined(_EVENT_HAVE_SETENV) && defined(_EVENT_HAVE_PUTENV)
-static void setenv(const char *k, const char *v, int _o)
+#elif !defined(EVENT__HAVE_SETENV) && defined(EVENT__HAVE_PUTENV)
+static void setenv(const char *k, const char *v, int o_)
 {
        char b[256];
        evutil_snprintf(b, sizeof(b), "%s=%s",k,v);
@@ -1862,9 +2028,9 @@ static void setenv(const char *k, const char *v, int _o)
 #define SETENV_OK
 #endif
 
-#ifdef _EVENT_HAVE_UNSETENV
+#ifdef EVENT__HAVE_UNSETENV
 #define UNSETENV_OK
-#elif !defined(_EVENT_HAVE_UNSETENV) && defined(_EVENT_HAVE_PUTENV)
+#elif !defined(EVENT__HAVE_UNSETENV) && defined(EVENT__HAVE_PUTENV)
 static void unsetenv(const char *k)
 {
        char b[256];
@@ -1881,7 +2047,7 @@ methodname_to_envvar(const char *mname, char *buf, size_t buflen)
        char *cp;
        evutil_snprintf(buf, buflen, "EVENT_NO%s", mname);
        for (cp = buf; *cp; ++cp) {
-               *cp = EVUTIL_TOUPPER(*cp);
+               *cp = EVUTIL_TOUPPER_(*cp);
        }
 }
 #endif
@@ -1902,7 +2068,7 @@ test_base_environ(void *arg)
        setenv("EVENT_NOWAFFLES", "1", 1);
        unsetenv("EVENT_NOWAFFLES");
        if (getenv("EVENT_NOWAFFLES") != NULL) {
-#ifndef _EVENT_HAVE_UNSETENV
+#ifndef EVENT__HAVE_UNSETENV
                TT_DECLARE("NOTE", ("Can't fake unsetenv; skipping test"));
 #else
                TT_DECLARE("NOTE", ("unsetenv doesn't work; skipping test"));
@@ -1984,6 +2150,15 @@ end:
        ;
 }
 
+static void
+immediate_called_twice_cb(evutil_socket_t fd, short event, void *arg)
+{
+       tt_int_op(event, ==, EV_TIMEOUT);
+       called += 1000;
+end:
+       ;
+}
+
 static void
 test_event_once(void *ptr)
 {
@@ -2002,13 +2177,24 @@ test_event_once(void *ptr)
        tt_int_op(r, ==, 0);
        r = event_base_once(data->base, -1, 0, NULL, NULL, NULL);
        tt_int_op(r, <, 0);
+       r = event_base_once(data->base, -1, EV_TIMEOUT,
+           immediate_called_twice_cb, NULL, NULL);
+       tt_int_op(r, ==, 0);
+       tv.tv_sec = 0;
+       tv.tv_usec = 0;
+       r = event_base_once(data->base, -1, EV_TIMEOUT,
+           immediate_called_twice_cb, NULL, &tv);
+       tt_int_op(r, ==, 0);
+
+       if (write(data->pair[1], TEST1, strlen(TEST1)+1) < 0) {
+               tt_fail_perror("write");
+       }
 
-       write(data->pair[1], TEST1, strlen(TEST1)+1);
        shutdown(data->pair[1], SHUT_WR);
 
        event_base_dispatch(data->base);
 
-       tt_int_op(called, ==, 101);
+       tt_int_op(called, ==, 2101);
 end:
        ;
 }
@@ -2018,7 +2204,7 @@ test_event_pending(void *ptr)
 {
        struct basic_test_data *data = ptr;
        struct event *r=NULL, *w=NULL, *t=NULL;
-       struct timeval tv, now, tv2, diff;
+       struct timeval tv, now, tv2;
 
        tv.tv_sec = 0;
        tv.tv_usec = 500 * 1000;
@@ -2041,10 +2227,8 @@ test_event_pending(void *ptr)
        tt_assert( event_pending(t, EV_TIMEOUT, &tv2));
 
        tt_assert(evutil_timercmp(&tv2, &now, >));
-       evutil_timeradd(&now, &tv, &tv);
-       evutil_timersub(&tv2, &tv, &diff);
-       tt_int_op(diff.tv_sec, ==, 0);
-       tt_int_op(labs(diff.tv_usec), <, 1000);
+
+       test_timeval_diff_eq(&now, &tv2, 500);
 
 end:
        if (r) {
@@ -2131,17 +2315,17 @@ end:
 }
 #endif
 
-#ifdef _EVENT_DISABLE_MM_REPLACEMENT
+#ifdef EVENT__DISABLE_MM_REPLACEMENT
 static void
 test_mm_functions(void *arg)
 {
-       _tinytest_set_test_skipped();
+       tinytest_set_test_skipped_();
 }
 #else
 static int
-check_dummy_mem_ok(void *_mem)
+check_dummy_mem_ok(void *mem_)
 {
-       char *mem = _mem;
+       char *mem = mem_;
        mem -= 16;
        return !memcmp(mem, "{[<guardedram>]}", 16);
 }
@@ -2155,22 +2339,22 @@ dummy_malloc(size_t len)
 }
 
 static void *
-dummy_realloc(void *_mem, size_t len)
+dummy_realloc(void *mem_, size_t len)
 {
-       char *mem = _mem;
+       char *mem = mem_;
        if (!mem)
                return dummy_malloc(len);
-       tt_want(check_dummy_mem_ok(_mem));
+       tt_want(check_dummy_mem_ok(mem_));
        mem -= 16;
        mem = realloc(mem, len+16);
        return mem+16;
 }
 
 static void
-dummy_free(void *_mem)
+dummy_free(void *mem_)
 {
-       char *mem = _mem;
-       tt_want(check_dummy_mem_ok(_mem));
+       char *mem = mem_;
+       tt_want(check_dummy_mem_ok(mem_));
        mem -= 16;
        free(mem);
 }
@@ -2279,15 +2463,18 @@ struct testcase_t main_testcases[] = {
        BASIC(free_active_base, TT_FORK|TT_NEED_SOCKETPAIR),
 
        BASIC(manipulate_active_events, TT_FORK|TT_NEED_BASE),
+       BASIC(event_new_selfarg, TT_FORK|TT_NEED_BASE),
+       BASIC(event_assign_selfarg, TT_FORK|TT_NEED_BASE),
 
        BASIC(bad_assign, TT_FORK|TT_NEED_BASE|TT_NO_LOGS),
        BASIC(bad_reentrant, TT_FORK|TT_NEED_BASE|TT_NO_LOGS),
 
-       /* These are still using the old API */
        LEGACY(persistent_timeout, TT_FORK|TT_NEED_BASE),
+       { "persistent_timeout_jump", test_persistent_timeout_jump, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
        { "persistent_active_timeout", test_persistent_active_timeout,
          TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
        LEGACY(priorities, TT_FORK|TT_NEED_BASE),
+       BASIC(priority_active_inversion, TT_FORK|TT_NEED_BASE),
        { "common_timeout", test_common_timeout, TT_FORK|TT_NEED_BASE,
          &basic_setup, NULL },
 
index b9324dcbe0a3f059dc981b332d03fe77d059bfcf..449a59b0080bc450cc14c732e3df37841ee7c9b2 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _REGRESS_H_
-#define _REGRESS_H_
+#ifndef REGRESS_H_INCLUDED_
+#define REGRESS_H_INCLUDED_
 
 #ifdef __cplusplus
 extern "C" {
@@ -102,11 +102,11 @@ void run_legacy_test_fn(void *ptr);
 struct evutil_addrinfo;
 struct evutil_addrinfo *ai_find_by_family(struct evutil_addrinfo *ai, int f);
 struct evutil_addrinfo *ai_find_by_protocol(struct evutil_addrinfo *ai, int p);
-int _test_ai_eq(const struct evutil_addrinfo *ai, const char *sockaddr_port,
+int test_ai_eq_(const struct evutil_addrinfo *ai, const char *sockaddr_port,
     int socktype, int protocol, int line);
 
 #define test_ai_eq(ai, str, s, p) do {                                 \
-               if (_test_ai_eq((ai), (str), (s), (p), __LINE__)<0)     \
+               if (test_ai_eq_((ai), (str), (s), (p), __LINE__)<0)     \
                        goto end;                                       \
        } while (0)
 
@@ -118,8 +118,12 @@ int _test_ai_eq(const struct evutil_addrinfo *ai, const char *sockaddr_port,
 
 long timeval_msec_diff(const struct timeval *start, const struct timeval *end);
 
+#ifndef _WIN32
+pid_t regress_fork(void);
+#endif
+
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* _REGRESS_H_ */
+#endif /* REGRESS_H_INCLUDED_ */
index 03a27ead17c85fd6d4940aded9279b752365a1c8..d183b4f9db75568fe4332a24543f7f5493eb7832 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,6 +24,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "util-internal.h"
 
 #ifdef _WIN32
 #include <winsock2.h>
@@ -34,7 +35,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
 
 #include "evbuffer-internal.h"
 #include "log-internal.h"
-#include "util-internal.h"
 
 #include "regress.h"
 
 /* Validates that an evbuffer is good. Returns false if it isn't, true if it
  * is*/
 static int
-_evbuffer_validate(struct evbuffer *buf)
+evbuffer_validate_(struct evbuffer *buf)
 {
        struct evbuffer_chain *chain;
        size_t sum = 0;
@@ -164,7 +164,7 @@ evbuffer_get_waste(struct evbuffer *buf, size_t *allocatedp, size_t *wastedp, si
 }
 
 #define evbuffer_validate(buf)                 \
-       TT_STMT_BEGIN if (!_evbuffer_validate(buf)) TT_DIE(("Buffer format invalid")); TT_STMT_END
+       TT_STMT_BEGIN if (!evbuffer_validate_(buf)) TT_DIE(("Buffer format invalid")); TT_STMT_END
 
 static void
 test_evbuffer(void *ptr)
@@ -285,6 +285,43 @@ test_evbuffer(void *ptr)
        evbuffer_free(evb_two);
 }
 
+static void
+no_cleanup(const void *data, size_t datalen, void *extra)
+{
+}
+
+static void
+test_evbuffer_remove_buffer_with_empty(void *ptr)
+{
+    struct evbuffer *src = evbuffer_new();
+    struct evbuffer *dst = evbuffer_new();
+    char buf[2];
+
+    evbuffer_validate(src);
+    evbuffer_validate(dst);
+
+    /* setup the buffers */
+    /* we need more data in src than we will move later */
+    evbuffer_add_reference(src, buf, sizeof(buf), no_cleanup, NULL);
+    evbuffer_add_reference(src, buf, sizeof(buf), no_cleanup, NULL);
+    /* we need one buffer in dst and one empty buffer at the end */
+    evbuffer_add(dst, buf, sizeof(buf));
+    evbuffer_add_reference(dst, buf, 0, no_cleanup, NULL);
+
+    evbuffer_validate(src);
+    evbuffer_validate(dst);
+
+    /* move three bytes over */
+    evbuffer_remove_buffer(src, dst, 3);
+
+    evbuffer_validate(src);
+    evbuffer_validate(dst);
+
+end:
+    evbuffer_free(src);
+    evbuffer_free(dst);
+}
+
 static void
 test_evbuffer_reserve2(void *ptr)
 {
@@ -652,7 +689,7 @@ test_evbuffer_add_file(void *ptr)
        size_t datalen, expect_len;
        const char *compare;
        int fd = -1;
-       int want_type = 0;
+       int want_ismapping = -1, want_cansendfile = -1;
        unsigned flags = 0;
        int use_segment = 1, use_bigfile = 0, map_from_offset = 0,
            view_from_offset = 0;
@@ -662,6 +699,7 @@ test_evbuffer_add_file(void *ptr)
        struct event *rev=NULL, *wev=NULL;
        struct event_base *base = testdata->base;
        evutil_socket_t pair[2] = {-1, -1};
+       struct evutil_weakrand_state seed = { 123456789U };
 
        /* This test is highly parameterized based on substrings of its
         * argument.  The strings are: */
@@ -692,17 +730,20 @@ test_evbuffer_add_file(void *ptr)
                /* If sendfile is set, we try to use a sendfile/splice style
                 * backend. */
                flags = EVBUF_FS_DISABLE_MMAP;
-               want_type = EVBUF_FS_SENDFILE;
+               want_cansendfile = 1;
+               want_ismapping = 0;
        } else if (strstr(impl, "mmap")) {
                /* If sendfile is set, we try to use a mmap/CreateFileMapping
                 * style backend. */
                flags = EVBUF_FS_DISABLE_SENDFILE;
-               want_type = EVBUF_FS_MMAP;
+               want_ismapping = 1;
+               want_cansendfile = 0;
        } else if (strstr(impl, "linear")) {
                /* If linear is set, we try to use a read-the-whole-thing
                 * backend. */
                flags = EVBUF_FS_DISABLE_SENDFILE|EVBUF_FS_DISABLE_MMAP;
-               want_type = EVBUF_FS_IO;
+               want_ismapping = 0;
+               want_cansendfile = 0;
        } else if (strstr(impl, "default")) {
                /* The caller doesn't care which backend we use. */
                ;
@@ -717,7 +758,7 @@ test_evbuffer_add_file(void *ptr)
                data = malloc(1024*512);
                tt_assert(data);
                for (i = 0; i < datalen; ++i)
-                       data[i] = _evutil_weakrand();
+                       data[i] = (char)evutil_weakrand_(&seed);
        } else {
                data = strdup("here is a relatively small string.");
                tt_assert(data);
@@ -747,14 +788,23 @@ test_evbuffer_add_file(void *ptr)
                seg = evbuffer_file_segment_new(fd, starting_offset,
                    mapping_len, flags);
                tt_assert(seg);
-               if ((int)seg->type != (int)want_type)
-                       tt_skip();
+               if (want_ismapping >= 0) {
+                       if (seg->is_mapping != (unsigned)want_ismapping)
+                               tt_skip();
+               }
+               if (want_cansendfile >= 0) {
+                       if (seg->can_sendfile != (unsigned)want_cansendfile)
+                               tt_skip();
+               }
        }
 
-#if defined(_EVENT_HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
+       /* Say that it drains to a fd so that we can use sendfile. */
+       evbuffer_set_flags(src, EVBUFFER_FLAG_DRAINS_TO_FD);
+
+#if defined(EVENT__HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
        /* We need to use a pair of AF_INET sockets, since Solaris
           doesn't support sendfile() over AF_UNIX. */
-       if (evutil_ersatz_socketpair(AF_INET, SOCK_STREAM, 0, pair) == -1)
+       if (evutil_ersatz_socketpair_(AF_INET, SOCK_STREAM, 0, pair) == -1)
                tt_abort_msg("ersatz_socketpair failed");
 #else
        if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
@@ -818,7 +868,7 @@ test_evbuffer_add_file(void *ptr)
        }
 }
 
-#ifndef _EVENT_DISABLE_MM_REPLACEMENT
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
 static void *
 failing_malloc(size_t how_much)
 {
@@ -971,6 +1021,32 @@ test_evbuffer_readln(void *ptr)
        free(cp);
        evbuffer_validate(evb);
 
+       /* Test NUL */
+       tt_int_op(evbuffer_get_length(evb), ==, 0);
+       {
+               char x[] =
+                   "NUL\n\0\0"
+                   "The all-zeros character which may serve\0"
+                   "to accomplish time fill\0and media fill";
+               /* Add all but the final NUL of x. */
+               evbuffer_add(evb, x, sizeof(x)-1);
+       }
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+       tt_line_eq("NUL\n");
+       free(cp);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+       tt_line_eq("");
+       free(cp);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+       tt_line_eq("The all-zeros character which may serve");
+       free(cp);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+       tt_line_eq("to accomplish time fill");
+       free(cp);
+       cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+       tt_ptr_op(cp, ==, NULL);
+       evbuffer_drain(evb, -1);
+
        /* Test CRLF_STRICT - across boundaries*/
        s = " and a bad crlf\nand a good one\r";
        evbuffer_add(evb_tmp, s, strlen(s));
@@ -1023,7 +1099,7 @@ test_evbuffer_readln(void *ptr)
        evbuffer_validate(evb);
 
        /* the next call to readline should fail */
-#ifndef _EVENT_DISABLE_MM_REPLACEMENT
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
        event_set_mem_functions(failing_malloc, realloc, free);
        cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
        tt_assert(cp == NULL);
@@ -1521,6 +1597,111 @@ end:
                evbuffer_free(buf2);
 }
 
+static void
+test_evbuffer_multicast(void *ptr)
+{
+       const char chunk1[] = "If you have found the answer to such a problem";
+       const char chunk2[] = "you ought to write it up for publication";
+                         /* -- Knuth's "Notes on the Exercises" from TAOCP */
+       char tmp[16];
+       size_t len1 = strlen(chunk1), len2=strlen(chunk2);
+
+       struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+       buf1 = evbuffer_new();
+       tt_assert(buf1);
+
+       evbuffer_add(buf1, chunk1, len1);
+       evbuffer_add(buf1, ", ", 2);
+       evbuffer_add(buf1, chunk2, len2);
+       tt_int_op(evbuffer_get_length(buf1), ==, len1+len2+2);
+
+       buf2 = evbuffer_new();
+       tt_assert(buf2);
+
+       tt_int_op(evbuffer_add_buffer_reference(buf2, buf1), ==, 0);
+       /* nested references are not allowed */
+       tt_int_op(evbuffer_add_buffer_reference(buf2, buf2), ==, -1);
+       tt_int_op(evbuffer_add_buffer_reference(buf1, buf2), ==, -1);
+
+       /* both buffers contain the same amount of data */
+       tt_int_op(evbuffer_get_length(buf1), ==, evbuffer_get_length(buf1));
+
+       /* Make sure we can drain a little from the first buffer. */
+       tt_int_op(evbuffer_remove(buf1, tmp, 6), ==, 6);
+       tt_int_op(memcmp(tmp, "If you", 6), ==, 0);
+       tt_int_op(evbuffer_remove(buf1, tmp, 5), ==, 5);
+       tt_int_op(memcmp(tmp, " have", 5), ==, 0);
+
+       /* Make sure that prepending does not meddle with immutable data */
+       tt_int_op(evbuffer_prepend(buf1, "I have ", 7), ==, 0);
+       tt_int_op(memcmp(chunk1, "If you", 6), ==, 0);
+       evbuffer_validate(buf1);
+
+       /* Make sure we can drain a little from the second buffer. */
+       tt_int_op(evbuffer_remove(buf2, tmp, 6), ==, 6);
+       tt_int_op(memcmp(tmp, "If you", 6), ==, 0);
+       tt_int_op(evbuffer_remove(buf2, tmp, 5), ==, 5);
+       tt_int_op(memcmp(tmp, " have", 5), ==, 0);
+
+       /* Make sure that prepending does not meddle with immutable data */
+       tt_int_op(evbuffer_prepend(buf2, "I have ", 7), ==, 0);
+       tt_int_op(memcmp(chunk1, "If you", 6), ==, 0);
+       evbuffer_validate(buf2);
+
+       /* Make sure the data can be read from the second buffer when the first is freed */
+       evbuffer_free(buf1);
+       buf1 = NULL;
+
+       tt_int_op(evbuffer_remove(buf2, tmp, 6), ==, 6);
+       tt_int_op(memcmp(tmp, "I have", 6), ==, 0);
+
+       tt_int_op(evbuffer_remove(buf2, tmp, 6), ==, 6);
+       tt_int_op(memcmp(tmp, "  foun", 6), ==, 0);
+
+end:
+       if (buf1)
+               evbuffer_free(buf1);
+       if (buf2)
+               evbuffer_free(buf2);
+}
+
+static void
+test_evbuffer_multicast_drain(void *ptr)
+{
+       const char chunk1[] = "If you have found the answer to such a problem";
+       const char chunk2[] = "you ought to write it up for publication";
+                         /* -- Knuth's "Notes on the Exercises" from TAOCP */
+       size_t len1 = strlen(chunk1), len2=strlen(chunk2);
+
+       struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+       buf1 = evbuffer_new();
+       tt_assert(buf1);
+
+       evbuffer_add(buf1, chunk1, len1);
+       evbuffer_add(buf1, ", ", 2);
+       evbuffer_add(buf1, chunk2, len2);
+       tt_int_op(evbuffer_get_length(buf1), ==, len1+len2+2);
+
+       buf2 = evbuffer_new();
+       tt_assert(buf2);
+
+       tt_int_op(evbuffer_add_buffer_reference(buf2, buf1), ==, 0);
+       tt_int_op(evbuffer_get_length(buf2), ==, len1+len2+2);
+       tt_int_op(evbuffer_drain(buf1, evbuffer_get_length(buf1)), ==, 0);
+       tt_int_op(evbuffer_get_length(buf2), ==, len1+len2+2);
+       tt_int_op(evbuffer_drain(buf2, evbuffer_get_length(buf2)), ==, 0);
+       evbuffer_validate(buf1);
+       evbuffer_validate(buf2);
+
+end:
+       if (buf1)
+               evbuffer_free(buf1);
+       if (buf2)
+               evbuffer_free(buf2);
+}
+
 /* Some cases that we didn't get in test_evbuffer() above, for more coverage. */
 static void
 test_evbuffer_prepend(void *ptr)
@@ -1600,6 +1781,10 @@ test_evbuffer_peek(void *info)
                evbuffer_add_buffer(buf, tmp_buf);
        }
 
+       /* How many chunks do we need for everything? */
+       i = evbuffer_peek(buf, -1, NULL, NULL, 0);
+       tt_int_op(i, ==, 16);
+
        /* Simple peek: get everything. */
        i = evbuffer_peek(buf, -1, NULL, v, 20);
        tt_int_op(i, ==, 16); /* we used only 16 chunks. */
@@ -1778,6 +1963,131 @@ end:
                evbuffer_free(tmp_buf);
 }
 
+static void
+test_evbuffer_add_iovec(void * ptr)
+{
+       struct evbuffer * buf = NULL;
+       struct evbuffer_iovec vec[4];
+       const char * data[] = {
+               "Guilt resembles a sword with two edges.",
+               "On the one hand, it cuts for Justice, imposing practical morality upon those who fear it.",
+               "Conscience does not always adhere to rational judgment.",
+               "Guilt is always a self-imposed burden, but it is not always rightly imposed."
+               /* -- R.A. Salvatore, _Sojurn_ */
+       };
+       size_t expected_length = 0;
+       size_t returned_length = 0;
+       int i;
+
+       buf = evbuffer_new();
+
+       for (i = 0; i < 4; i++) {
+               vec[i].iov_len  = strlen(data[i]);
+               vec[i].iov_base = (char*) data[i];
+               expected_length += vec[i].iov_len;
+       }
+
+       returned_length = evbuffer_add_iovec(buf, vec, 4);
+
+       tt_int_op(returned_length, ==, evbuffer_get_length(buf));
+       tt_int_op(evbuffer_get_length(buf), ==, expected_length);
+
+       for (i = 0; i < 4; i++) {
+               char charbuf[1024];
+
+               memset(charbuf, 0, 1024);
+               evbuffer_remove(buf, charbuf, strlen(data[i]));
+               tt_assert(strcmp(charbuf, data[i]) == 0);
+       }
+
+       tt_assert(evbuffer_get_length(buf) == 0);
+end:
+       if (buf) {
+               evbuffer_free(buf);
+       }
+}
+
+static void
+test_evbuffer_copyout(void *dummy)
+{
+       const char string[] =
+           "Still they skirmish to and fro, men my messmates on the snow "
+           "When we headed off the aurochs turn for turn; "
+           "When the rich Allobrogenses never kept amanuenses, "
+           "And our only plots were piled in lakes at Berne.";
+       /* -- Kipling, "In The Neolithic Age" */
+       char tmp[256];
+       struct evbuffer_ptr ptr;
+       struct evbuffer *buf;
+
+       (void)dummy;
+
+       buf = evbuffer_new();
+       tt_assert(buf);
+
+       tt_int_op(strlen(string), ==, 206);
+
+       /* Ensure separate chains */
+       evbuffer_add_reference(buf, string, 80, no_cleanup, NULL);
+       evbuffer_add_reference(buf, string+80, 80, no_cleanup, NULL);
+       evbuffer_add(buf, string+160, strlen(string)-160);
+
+       tt_int_op(206, ==, evbuffer_get_length(buf));
+
+       /* First, let's test plain old copyout. */
+
+       /* Copy a little from the beginning. */
+       tt_int_op(10, ==, evbuffer_copyout(buf, tmp, 10));
+       tt_int_op(0, ==, memcmp(tmp, "Still they", 10));
+
+       /* Now copy more than a little from the beginning */
+       memset(tmp, 0, sizeof(tmp));
+       tt_int_op(100, ==, evbuffer_copyout(buf, tmp, 100));
+       tt_int_op(0, ==, memcmp(tmp, string, 100));
+
+       /* Copy too much; ensure truncation. */
+       memset(tmp, 0, sizeof(tmp));
+       tt_int_op(206, ==, evbuffer_copyout(buf, tmp, 230));
+       tt_int_op(0, ==, memcmp(tmp, string, 206));
+
+       /* That was supposed to be nondestructive, btw */
+       tt_int_op(206, ==, evbuffer_get_length(buf));
+
+       /* Now it's time to test copyout_from!  First, let's start in the
+        * first chain. */
+       evbuffer_ptr_set(buf, &ptr, 15, EVBUFFER_PTR_SET);
+       memset(tmp, 0, sizeof(tmp));
+       tt_int_op(10, ==, evbuffer_copyout_from(buf, &ptr, tmp, 10));
+       tt_int_op(0, ==, memcmp(tmp, "mish to an", 10));
+
+       /* Right up to the end of the first chain */
+       memset(tmp, 0, sizeof(tmp));
+       tt_int_op(65, ==, evbuffer_copyout_from(buf, &ptr, tmp, 65));
+       tt_int_op(0, ==, memcmp(tmp, string+15, 65));
+
+       /* Span into the second chain */
+       memset(tmp, 0, sizeof(tmp));
+       tt_int_op(90, ==, evbuffer_copyout_from(buf, &ptr, tmp, 90));
+       tt_int_op(0, ==, memcmp(tmp, string+15, 90));
+
+       /* Span into the third chain */
+       memset(tmp, 0, sizeof(tmp));
+       tt_int_op(160, ==, evbuffer_copyout_from(buf, &ptr, tmp, 160));
+       tt_int_op(0, ==, memcmp(tmp, string+15, 160));
+
+       /* Overrun */
+       memset(tmp, 0, sizeof(tmp));
+       tt_int_op(206-15, ==, evbuffer_copyout_from(buf, &ptr, tmp, 999));
+       tt_int_op(0, ==, memcmp(tmp, string+15, 206-15));
+
+       /* That was supposed to be nondestructive, too */
+       tt_int_op(206, ==, evbuffer_get_length(buf));
+
+end:
+       if (buf)
+               evbuffer_free(buf);
+}
+
 static void *
 setup_passthrough(const struct testcase_t *testcase)
 {
@@ -1797,6 +2107,7 @@ static const struct testcase_setup_t nil_setup = {
 
 struct testcase_t evbuffer_testcases[] = {
        { "evbuffer", test_evbuffer, 0, NULL, NULL },
+       { "remove_buffer_with_empty", test_evbuffer_remove_buffer_with_empty, 0, NULL, NULL },
        { "reserve2", test_evbuffer_reserve2, 0, NULL, NULL },
        { "reserve_many", test_evbuffer_reserve_many, 0, NULL, NULL },
        { "reserve_many2", test_evbuffer_reserve_many, 0, &nil_setup, (void*)"add" },
@@ -1811,10 +2122,14 @@ struct testcase_t evbuffer_testcases[] = {
        { "search", test_evbuffer_search, 0, NULL, NULL },
        { "callbacks", test_evbuffer_callbacks, 0, NULL, NULL },
        { "add_reference", test_evbuffer_add_reference, 0, NULL, NULL },
+       { "multicast", test_evbuffer_multicast, 0, NULL, NULL },
+       { "multicast_drain", test_evbuffer_multicast_drain, 0, NULL, NULL },
        { "prepend", test_evbuffer_prepend, TT_FORK, NULL, NULL },
        { "peek", test_evbuffer_peek, 0, NULL, NULL },
        { "freeze_start", test_evbuffer_freeze, 0, &nil_setup, (void*)"start" },
        { "freeze_end", test_evbuffer_freeze, 0, &nil_setup, (void*)"end" },
+       { "add_iovec", test_evbuffer_add_iovec, 0, NULL, NULL},
+       { "copyout", test_evbuffer_copyout, 0, NULL, NULL},
 
 #define ADDFILE_TEST(name, parameters)                                 \
        { name, test_evbuffer_add_file, TT_FORK|TT_NEED_BASE,           \
index 79816396b8c14af902339976a08834394621dd69..06b8831ff93be3eeef5305e421b69f6ad1770ad2 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,6 +24,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "util-internal.h"
 
 /* The old tests here need assertions to work. */
 #undef NDEBUG
@@ -37,7 +38,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -57,7 +58,7 @@
 #include <errno.h>
 #include <assert.h>
 
-#ifdef _EVENT_HAVE_ARPA_INET_H
+#ifdef EVENT__HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
 
@@ -131,7 +132,7 @@ test_bufferevent_impl(int use_pair)
                tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
                bev1 = pair[0];
                bev2 = pair[1];
-               bufferevent_setcb(bev1, readcb, writecb, errorcb, NULL);
+               bufferevent_setcb(bev1, readcb, writecb, errorcb, bev1);
                bufferevent_setcb(bev2, readcb, writecb, errorcb, NULL);
                tt_int_op(bufferevent_getfd(bev1), ==, -1);
                tt_ptr_op(bufferevent_get_underlying(bev1), ==, NULL);
@@ -146,6 +147,18 @@ test_bufferevent_impl(int use_pair)
                tt_ptr_op(bufferevent_pair_get_partner(bev2), ==, NULL);
        }
 
+       {
+               /* Test getcb. */
+               bufferevent_data_cb r, w;
+               bufferevent_event_cb e;
+               void *a;
+               bufferevent_getcb(bev1, &r, &w, &e, &a);
+               tt_ptr_op(r, ==, readcb);
+               tt_ptr_op(w, ==, writecb);
+               tt_ptr_op(e, ==, errorcb);
+               tt_ptr_op(a, ==, use_pair ? bev1 : NULL);
+       }
+
        bufferevent_disable(bev1, EV_READ);
        bufferevent_enable(bev2, EV_READ);
 
@@ -490,7 +503,7 @@ test_bufferevent_connect(void *arg)
        if (!strcmp((char*)data->setup_data, "unset_connectex")) {
                struct win32_extension_fns *ext =
                    (struct win32_extension_fns *)
-                   event_get_win32_extension_fns();
+                   event_get_win32_extension_fns_();
                ext->ConnectEx = NULL;
        }
 #endif
@@ -746,8 +759,8 @@ test_bufferevent_timeouts(void *arg)
        bufferevent_set_timeouts(bev2, &tv_r, &tv_w);
        bufferevent_enable(bev2, EV_WRITE);
 
-       tv_r.tv_sec = 1;
-       tv_r.tv_usec = 0;
+       tv_r.tv_sec = 0;
+       tv_r.tv_usec = 350000;
 
        event_base_loopexit(data->base, &tv_r);
        event_base_dispatch(data->base);
@@ -801,7 +814,7 @@ struct testcase_t bufferevent_testcases[] = {
          TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"filter" },
        { "bufferevent_timeout_filter_pair", test_bufferevent_timeouts,
          TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"filter pair" },
-#ifdef _EVENT_HAVE_LIBZ
+#ifdef EVENT__HAVE_LIBZ
        LEGACY(bufferevent_zlib, TT_ISOLATED),
 #else
        { "bufferevent_zlib", NULL, TT_SKIP, NULL, NULL },
index 01cb0dbf975ac8b01d11e84e7a7941aeed57f0be..ae1fc30a3fe4cd5e981f1463fc56da96ff020c3a 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,6 +24,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "../util-internal.h"
 
 #ifdef _WIN32
 #include <winsock2.h>
@@ -35,7 +36,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -46,7 +47,7 @@
 #include <arpa/inet.h>
 #include <unistd.h>
 #endif
-#ifdef _EVENT_HAVE_NETINET_IN6_H
+#ifdef EVENT__HAVE_NETINET_IN6_H
 #include <netinet/in6.h>
 #endif
 #ifdef HAVE_NETDB_H
@@ -71,8 +72,6 @@
 #include "regress.h"
 #include "regress_testutils.h"
 
-#include "../util-internal.h"
-
 static int dns_ok = 0;
 static int dns_got_cancel = 0;
 static int dns_err = 0;
@@ -99,7 +98,7 @@ dns_gethostbyname_cb(int result, char type, int count, int ttl,
 
        switch (type) {
        case DNS_IPv6_AAAA: {
-#if defined(_EVENT_HAVE_STRUCT_IN6_ADDR) && defined(_EVENT_HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
+#if defined(EVENT__HAVE_STRUCT_IN6_ADDR) && defined(EVENT__HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
                struct in6_addr *in6_addrs = addresses;
                char buf[INET6_ADDRSTRLEN+1];
                int i;
@@ -320,7 +319,7 @@ dns_server_gethostbyname_cb(int result, char type, int count, int ttl,
                break;
        }
        case DNS_IPv6_AAAA: {
-#if defined (_EVENT_HAVE_STRUCT_IN6_ADDR) && defined(_EVENT_HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
+#if defined (EVENT__HAVE_STRUCT_IN6_ADDR) && defined(EVENT__HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
                struct in6_addr *in6_addrs = addresses;
                char buf[INET6_ADDRSTRLEN+1];
                if (memcmp(&in6_addrs[0].s6_addr, "abcdefghijklmnop", 16)
@@ -495,6 +494,9 @@ static struct regress_dns_server_table search_table[] = {
        { "host2.a.example.com", "err", "3", 0 },
        { "host2.b.example.com", "A", "200.100.0.100", 0 },
        { "host2.c.example.com", "err", "3", 0 },
+       { "hostn.a.example.com", "errsoa", "0", 0 },
+       { "hostn.b.example.com", "errsoa", "3", 0 },
+       { "hostn.c.example.com", "err", "0", 0 },
 
        { "host", "err", "3", 0 },
        { "host2", "err", "3", 0 },
@@ -511,7 +513,7 @@ dns_search_test(void *arg)
        ev_uint16_t portnum = 0;
        char buf[64];
 
-       struct generic_dns_callback_result r1, r2, r3, r4, r5;
+       struct generic_dns_callback_result r[8];
 
        tt_assert(regress_dnsserver(base, &portnum, search_table));
        evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
@@ -523,26 +525,35 @@ dns_search_test(void *arg)
        evdns_base_search_add(dns, "b.example.com");
        evdns_base_search_add(dns, "c.example.com");
 
-       n_replies_left = 5;
+       n_replies_left = sizeof(r)/sizeof(r[0]);
        exit_base = base;
 
-       evdns_base_resolve_ipv4(dns, "host", 0, generic_dns_callback, &r1);
-       evdns_base_resolve_ipv4(dns, "host2", 0, generic_dns_callback, &r2);
-       evdns_base_resolve_ipv4(dns, "host", DNS_NO_SEARCH, generic_dns_callback, &r3);
-       evdns_base_resolve_ipv4(dns, "host2", DNS_NO_SEARCH, generic_dns_callback, &r4);
-       evdns_base_resolve_ipv4(dns, "host3", 0, generic_dns_callback, &r5);
+       evdns_base_resolve_ipv4(dns, "host", 0, generic_dns_callback, &r[0]);
+       evdns_base_resolve_ipv4(dns, "host2", 0, generic_dns_callback, &r[1]);
+       evdns_base_resolve_ipv4(dns, "host", DNS_NO_SEARCH, generic_dns_callback, &r[2]);
+       evdns_base_resolve_ipv4(dns, "host2", DNS_NO_SEARCH, generic_dns_callback, &r[3]);
+       evdns_base_resolve_ipv4(dns, "host3", 0, generic_dns_callback, &r[4]);
+       evdns_base_resolve_ipv4(dns, "hostn.a.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[5]);
+       evdns_base_resolve_ipv4(dns, "hostn.b.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[6]);
+       evdns_base_resolve_ipv4(dns, "hostn.c.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[7]);
 
        event_base_dispatch(base);
 
-       tt_int_op(r1.type, ==, DNS_IPv4_A);
-       tt_int_op(r1.count, ==, 1);
-       tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0x0b16212c));
-       tt_int_op(r2.type, ==, DNS_IPv4_A);
-       tt_int_op(r2.count, ==, 1);
-       tt_int_op(((ev_uint32_t*)r2.addrs)[0], ==, htonl(0xc8640064));
-       tt_int_op(r3.result, ==, DNS_ERR_NOTEXIST);
-       tt_int_op(r4.result, ==, DNS_ERR_NOTEXIST);
-       tt_int_op(r5.result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[0].type, ==, DNS_IPv4_A);
+       tt_int_op(r[0].count, ==, 1);
+       tt_int_op(((ev_uint32_t*)r[0].addrs)[0], ==, htonl(0x0b16212c));
+       tt_int_op(r[1].type, ==, DNS_IPv4_A);
+       tt_int_op(r[1].count, ==, 1);
+       tt_int_op(((ev_uint32_t*)r[1].addrs)[0], ==, htonl(0xc8640064));
+       tt_int_op(r[2].result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[3].result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[4].result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[5].result, ==, DNS_ERR_NODATA);
+       tt_int_op(r[5].ttl, ==, 42);
+       tt_int_op(r[6].result, ==, DNS_ERR_NOTEXIST);
+       tt_int_op(r[6].ttl, ==, 42);
+       tt_int_op(r[7].result, ==, DNS_ERR_NODATA);
+       tt_int_op(r[7].ttl, ==, 0);
 
 end:
        if (dns)
@@ -672,9 +683,9 @@ dns_retry_test(void *arg)
 
        dns = evdns_base_new(base, 0);
        tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
-       tt_assert(! evdns_base_set_option(dns, "timeout", "0.3"));
+       tt_assert(! evdns_base_set_option(dns, "timeout", "0.2"));
        tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "10"));
-       tt_assert(! evdns_base_set_option(dns, "initial-probe-timeout", "0.5"));
+       tt_assert(! evdns_base_set_option(dns, "initial-probe-timeout", "0.1"));
 
        evdns_base_resolve_ipv4(dns, "host.example.com", 0,
            generic_dns_callback, &r1);
@@ -693,8 +704,8 @@ dns_retry_test(void *arg)
        /* Now try again, but this time have the server get treated as
         * failed, so we can send it a test probe. */
        drop_count = 4;
-       tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "3"));
-       tt_assert(! evdns_base_set_option(dns, "attempts:", "4"));
+       tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "2"));
+       tt_assert(! evdns_base_set_option(dns, "attempts:", "3"));
        memset(&r1, 0, sizeof(r1));
 
        evdns_base_resolve_ipv4(dns, "host.example.com", 0,
@@ -850,6 +861,7 @@ end:
 /* === Test for bufferevent_socket_connect_hostname */
 
 static int total_connected_or_failed = 0;
+static int total_n_accepted = 0;
 static struct event_base *be_connect_hostname_base = NULL;
 
 /* Implements a DNS server for the connect_hostname test and the
@@ -870,6 +882,8 @@ be_getaddrinfo_server_cb(struct evdns_server_request *req, void *data)
                struct in6_addr ans6;
                memset(&ans6, 0, sizeof(ans6));
 
+               TT_BLATHER(("Got question about %s, type=%d", qname, qtype));
+
                if (qtype == EVDNS_TYPE_A &&
                    qclass == EVDNS_CLASS_INET &&
                    !evutil_ascii_strcasecmp(qname, "nobodaddy.example.com")) {
@@ -970,10 +984,13 @@ be_getaddrinfo_server_cb(struct evdns_server_request *req, void *data)
                        TT_GRIPE(("Got weird request for %s",qname));
                }
        }
-       if (added_any)
+       if (added_any) {
+               TT_BLATHER(("answering"));
                evdns_server_request_respond(req, 0);
-       else
+       } else {
+               TT_BLATHER(("saying nexist."));
                evdns_server_request_respond(req, 3);
+       }
 }
 
 /* Implements a listener for connect_hostname test. */
@@ -983,7 +1000,11 @@ nil_accept_cb(struct evconnlistener *l, evutil_socket_t fd, struct sockaddr *s,
 {
        int *p = arg;
        (*p)++;
+       ++total_n_accepted;
        /* don't do anything with the socket; let it close when we exit() */
+       if (total_n_accepted >= 3 && total_connected_or_failed >= 5)
+               event_base_loopexit(be_connect_hostname_base,
+                   NULL);
 }
 
 struct be_conn_hostname_result {
@@ -1003,14 +1024,14 @@ be_connect_hostname_event_cb(struct bufferevent *bev, short what, void *ctx)
 
                if ((what & BEV_EVENT_CONNECTED) || (what & BEV_EVENT_ERROR)) {
                        int r;
-                       ++total_connected_or_failed;
-                       TT_BLATHER(("Got %d connections or errors.", total_connected_or_failed));
                        if ((r = bufferevent_socket_get_dns_error(bev))) {
                                got->dnserr = r;
                                TT_BLATHER(("DNS error %d: %s", r,
                                           evutil_gai_strerror(r)));
-                       }
-                       if (total_connected_or_failed >= 5)
+                       }                       ++total_connected_or_failed;
+                       TT_BLATHER(("Got %d connections or errors.", total_connected_or_failed));
+
+                       if (total_n_accepted >= 3 && total_connected_or_failed >= 5)
                                event_base_loopexit(be_connect_hostname_base,
                                    NULL);
                }
@@ -1198,6 +1219,9 @@ test_getaddrinfo_async(void *arg)
        /* for localhost */
        evdns_base_load_hosts(dns_base, NULL);
 
+       tt_assert(! evdns_base_set_option(dns_base, "timeout", "0.3"));
+       tt_assert(! evdns_base_set_option(dns_base, "getaddrinfo-allow-skew", "0.2"));
+
        memset(a_out, 0, sizeof(a_out));
 
        n_gai_results_pending = 10000; /* don't think about exiting yet. */
@@ -1625,6 +1649,130 @@ gaic_launch(struct event_base *base, struct evdns_base *dns_base)
        ++pending;
 }
 
+#ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
+/* FIXME: We should move this to regress_main.c if anything else needs it.*/
+
+/* Trivial replacements for malloc/free/realloc to check for memory leaks.
+ * Not threadsafe. */
+static int allocated_chunks = 0;
+
+static void *
+cnt_malloc(size_t sz)
+{
+       allocated_chunks += 1;
+       return malloc(sz);
+}
+
+static void *
+cnt_realloc(void *old, size_t sz)
+{
+       if (!old)
+               allocated_chunks += 1;
+       if (!sz)
+               allocated_chunks -= 1;
+       return realloc(old, sz);
+}
+
+static void
+cnt_free(void *ptr)
+{
+       allocated_chunks -= 1;
+       free(ptr);
+}
+
+struct testleak_env_t {
+       struct event_base *base;
+       struct evdns_base *dns_base;
+       struct evdns_request *req;
+       struct generic_dns_callback_result r;
+};
+
+static void *
+testleak_setup(const struct testcase_t *testcase)
+{
+       struct testleak_env_t *env;
+
+       allocated_chunks = 0;
+       event_set_mem_functions(cnt_malloc, cnt_realloc, cnt_free);
+       event_enable_debug_mode();
+
+       /* not mm_calloc: we don't want to mess with the count. */
+       env = calloc(1, sizeof(struct testleak_env_t));
+       env->base = event_base_new();
+       env->dns_base = evdns_base_new(env->base, 0);
+       env->req = evdns_base_resolve_ipv4(
+               env->dns_base, "example.com", DNS_QUERY_NO_SEARCH,
+               generic_dns_callback, &env->r);
+       return env;
+}
+
+static int
+testleak_cleanup(const struct testcase_t *testcase, void *env_)
+{
+       int ok = 0;
+       struct testleak_env_t *env = env_;
+#ifdef EVENT__DISABLE_DEBUG_MODE
+       tt_int_op(allocated_chunks, ==, 0);
+#else
+       /* FIXME: that's `1' because of event_debug_map_HT_GROW */
+       tt_int_op(allocated_chunks, ==, 1);
+#endif
+       ok = 1;
+end:
+       if (env->dns_base)
+               evdns_base_free(env->dns_base, 0);
+       if (env->base)
+               event_base_free(env->base);
+       if (env)
+               free(env);
+       return ok;
+}
+
+static struct testcase_setup_t testleak_funcs = {
+       testleak_setup, testleak_cleanup
+};
+
+static void
+test_dbg_leak_cancel(void *env_)
+{
+       /* cancel, loop, free/dns, free/base */
+       struct testleak_env_t *env = env_;
+       int send_err_shutdown = 1;
+       evdns_cancel_request(env->dns_base, env->req);
+       env->req = 0;
+
+       /* `req` is freed in callback, that's why one loop is required. */
+       event_base_loop(env->base, EVLOOP_NONBLOCK);
+
+       /* send_err_shutdown means nothing as soon as our request is
+        * already canceled */
+       evdns_base_free(env->dns_base, send_err_shutdown);
+       env->dns_base = 0;
+       event_base_free(env->base);
+       env->base = 0;
+}
+
+static void
+test_dbg_leak_shutdown(void *env_)
+{
+       /* free/dns, loop, free/base */
+       struct testleak_env_t *env = env_;
+       int send_err_shutdown = 1;
+
+       /* `req` is freed both with `send_err_shutdown` and without it,
+        * the only difference is `evdns_callback` call */
+       env->req = 0;
+
+       evdns_base_free(env->dns_base, send_err_shutdown);
+       env->dns_base = 0;
+
+       /* `req` is freed in callback, that's why one loop is required */
+       event_base_loop(env->base, EVLOOP_NONBLOCK);
+       event_base_free(env->base);
+       env->base = 0;
+}
+#endif
+
 static void
 test_getaddrinfo_async_cancel_stress(void *ptr)
 {
@@ -1702,6 +1850,11 @@ struct testcase_t dns_testcases[] = {
        { "getaddrinfo_cancel_stress", test_getaddrinfo_async_cancel_stress,
          TT_FORK, NULL, NULL },
 
+#ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
+       { "leak_shutdown", test_dbg_leak_shutdown, TT_FORK, &testleak_funcs, NULL },
+       { "leak_cancel", test_dbg_leak_cancel, TT_FORK, &testleak_funcs, NULL },
+#endif
+
        END_OF_TESTCASES
 };
 
index ee6e6419219a35adec6a55c4df9f515e38c025a5..74dc4b7d2050989f2aa03e6cbfeb40f0d3a16810 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-
+#include "../util-internal.h"
 #include "event2/event-config.h"
 
 #ifdef _WIN32
@@ -31,7 +31,7 @@
 #endif
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 #include <fcntl.h>
@@ -59,10 +59,6 @@ read_cb(evutil_socket_t fd, short event, void *arg)
 
        len = recv(fd, &buf, sizeof(buf), 0);
 
-       /*printf("%s: %s %d%s\n", __func__, event & EV_ET ? "etread" : "read",
-               len, len ? "" : " - means EOF");
-       */
-
        called++;
        if (event & EV_ET)
                was_et = 1;
@@ -90,9 +86,21 @@ test_edgetriggered(void *et)
        evutil_socket_t pair[2] = {-1,-1};
        int supports_et;
 
+       /* On Linux 3.2.1 (at least, as patched by Fedora and tested by Nick),
+        * doing a "recv" on an AF_UNIX socket resets the readability of the
+        * socket, even though there is no state change, so we don't actually
+        * get edge-triggered behavior.  Yuck!  Linux 3.1.9 didn't have this
+        * problem.
+        */
+#ifdef __linux__
+       if (evutil_ersatz_socketpair_(AF_INET, SOCK_STREAM, 0, pair) == -1) {
+               tt_abort_perror("socketpair");
+       }
+#else
        if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, pair) == -1) {
                tt_abort_perror("socketpair");
        }
+#endif
 
        called = was_et = 0;
 
@@ -154,7 +162,7 @@ test_edgetriggered_mix_error(void *data_)
        struct event_base *base = NULL;
        struct event *ev_et=NULL, *ev_lt=NULL;
 
-#ifdef _EVENT_DISABLE_DEBUG_MODE
+#ifdef EVENT__DISABLE_DEBUG_MODE
        if (1)
                tt_skip();
 #endif
index 48ed525e0a2241bab88bc6d078cae9e815770c03..82f62594604ef4cd2d018324b42c3411459e646b 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,6 +24,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "util-internal.h"
 
 #ifdef _WIN32
 #include <winsock2.h>
@@ -35,7 +36,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -59,7 +60,6 @@
 #include "event2/bufferevent.h"
 #include "event2/util.h"
 #include "log-internal.h"
-#include "util-internal.h"
 #include "http-internal.h"
 #include "regress.h"
 #include "regress_testutils.h"
@@ -212,11 +212,11 @@ http_readcb(struct bufferevent *bev, void *arg)
                enum message_read_status done;
 
                /* req->kind = EVHTTP_RESPONSE; */
-               done = evhttp_parse_firstline(req, bufferevent_get_input(bev));
+               done = evhttp_parse_firstline_(req, bufferevent_get_input(bev));
                if (done != ALL_DATA_READ)
                        goto out;
 
-               done = evhttp_parse_headers(req, bufferevent_get_input(bev));
+               done = evhttp_parse_headers_(req, bufferevent_get_input(bev));
                if (done != ALL_DATA_READ)
                        goto out;
 
@@ -512,11 +512,11 @@ http_badreq_readcb(struct bufferevent *bev, void *arg)
                enum message_read_status done;
 
                /* req->kind = EVHTTP_RESPONSE; */
-               done = evhttp_parse_firstline(req, bufferevent_get_input(bev));
+               done = evhttp_parse_firstline_(req, bufferevent_get_input(bev));
                if (done != ALL_DATA_READ)
                        goto out;
 
-               done = evhttp_parse_headers(req, bufferevent_get_input(bev));
+               done = evhttp_parse_headers_(req, bufferevent_get_input(bev));
                if (done != ALL_DATA_READ)
                        goto out;
 
@@ -628,10 +628,10 @@ http_large_delay_cb(struct evhttp_request *req, void *arg)
 {
        struct timeval tv;
        evutil_timerclear(&tv);
-       tv.tv_sec = 3;
+       tv.tv_usec = 500000;
 
        event_base_once(arg, -1, EV_TIMEOUT, http_delay_reply, req, &tv);
-       evhttp_connection_fail(delayed_client, EVCON_HTTP_EOF);
+       evhttp_connection_fail_(delayed_client, EVCON_HTTP_EOF);
 }
 
 /*
@@ -823,7 +823,7 @@ static void http_request_done(struct evhttp_request *, void *);
 static void http_request_empty_done(struct evhttp_request *, void *);
 
 static void
-_http_connection_test(struct basic_test_data *data, int persistent)
+http_connection_test_(struct basic_test_data *data, int persistent)
 {
        ev_uint16_t port = 0;
        struct evhttp_connection *evcon = NULL;
@@ -907,12 +907,12 @@ _http_connection_test(struct basic_test_data *data, int persistent)
 static void
 http_connection_test(void *arg)
 {
-       _http_connection_test(arg, 0);
+       http_connection_test_(arg, 0);
 }
 static void
 http_persist_connection_test(void *arg)
 {
-       _http_connection_test(arg, 1);
+       http_connection_test_(arg, 1);
 }
 
 static struct regress_dns_server_table search_table[] = {
@@ -1769,7 +1769,7 @@ close_detect_done(struct evhttp_request *req, void *arg)
 
  end:
        evutil_timerclear(&tv);
-       tv.tv_sec = 3;
+       tv.tv_usec = 150000;
        event_base_loopexit(arg, &tv);
 }
 
@@ -1803,9 +1803,10 @@ close_detect_cb(struct evhttp_request *req, void *arg)
        }
 
        evutil_timerclear(&tv);
-       tv.tv_sec = 3;   /* longer than the http time out */
+       tv.tv_sec = 0;   /* longer than the http time out */
+       tv.tv_usec = 600000;   /* longer than the http time out */
 
-       /* launch a new request on the persistent connection in 3 seconds */
+       /* launch a new request on the persistent connection in .3 seconds */
        event_base_once(base, -1, EV_TIMEOUT, close_detect_launch, evcon, &tv);
  end:
        ;
@@ -1813,20 +1814,24 @@ close_detect_cb(struct evhttp_request *req, void *arg)
 
 
 static void
-_http_close_detection(struct basic_test_data *data, int with_delay)
+http_close_detection_(struct basic_test_data *data, int with_delay)
 {
        ev_uint16_t port = 0;
        struct evhttp_connection *evcon = NULL;
        struct evhttp_request *req = NULL;
+       const struct timeval sec_tenth = { 0, 100000 };
 
        test_ok = 0;
        http = http_setup(&port, data->base);
 
-       /* 2 second timeout */
-       evhttp_set_timeout(http, 1);
+       /* .1 second timeout */
+       evhttp_set_timeout_tv(http, &sec_tenth);
 
        evcon = evhttp_connection_base_new(data->base, NULL,
            "127.0.0.1", port);
+       evhttp_connection_set_timeout_tv(evcon, &sec_tenth);
+
+
        tt_assert(evcon);
        delayed_client = evcon;
 
@@ -1861,12 +1866,12 @@ _http_close_detection(struct basic_test_data *data, int with_delay)
 static void
 http_close_detection_test(void *arg)
 {
-       _http_close_detection(arg, 0);
+       http_close_detection_(arg, 0);
 }
 static void
 http_close_detection_delay_test(void *arg)
 {
-       _http_close_detection(arg, 1);
+       http_close_detection_(arg, 1);
 }
 
 static void
@@ -2554,7 +2559,7 @@ http_incomplete_writecb(struct bufferevent *bev, void *arg)
 }
 
 static void
-_http_incomplete_test(struct basic_test_data *data, int use_timeout)
+http_incomplete_test_(struct basic_test_data *data, int use_timeout)
 {
        struct bufferevent *bev;
        evutil_socket_t fd;
@@ -2611,12 +2616,12 @@ _http_incomplete_test(struct basic_test_data *data, int use_timeout)
 static void
 http_incomplete_test(void *arg)
 {
-       _http_incomplete_test(arg, 0);
+       http_incomplete_test_(arg, 0);
 }
 static void
 http_incomplete_timeout_test(void *arg)
 {
-       _http_incomplete_test(arg, 1);
+       http_incomplete_test_(arg, 1);
 }
 
 /*
@@ -2643,11 +2648,11 @@ http_chunked_errorcb(struct bufferevent *bev, short what, void *arg)
                enum message_read_status done;
 
                /* req->kind = EVHTTP_RESPONSE; */
-               done = evhttp_parse_firstline(req, bufferevent_get_input(bev));
+               done = evhttp_parse_firstline_(req, bufferevent_get_input(bev));
                if (done != ALL_DATA_READ)
                        goto out;
 
-               done = evhttp_parse_headers(req, bufferevent_get_input(bev));
+               done = evhttp_parse_headers_(req, bufferevent_get_input(bev));
                if (done != ALL_DATA_READ)
                        goto out;
 
@@ -2905,7 +2910,7 @@ http_stream_in_done(struct evhttp_request *req, void *arg)
  * Makes a request and reads the response in chunks.
  */
 static void
-_http_stream_in_test(struct basic_test_data *data, char const *url,
+http_stream_in_test_(struct basic_test_data *data, char const *url,
     size_t expected_len, char const *expected)
 {
        struct evhttp_connection *evcon;
@@ -2953,10 +2958,10 @@ _http_stream_in_test(struct basic_test_data *data, char const *url,
 static void
 http_stream_in_test(void *arg)
 {
-       _http_stream_in_test(arg, "/chunked", 13 + 18 + 8,
+       http_stream_in_test_(arg, "/chunked", 13 + 18 + 8,
            "This is funnybut not hilarious.bwv 1052");
 
-       _http_stream_in_test(arg, "/test", strlen(BASIC_REQUEST_BODY),
+       http_stream_in_test_(arg, "/test", strlen(BASIC_REQUEST_BODY),
            BASIC_REQUEST_BODY);
 }
 
@@ -3011,7 +3016,7 @@ static void
 http_connection_fail_done(struct evhttp_request *req, void *arg)
 {
        /* An ENETUNREACH error results in an unrecoverable
-        * evhttp_connection error (see evhttp_connection_fail()).  The
+        * evhttp_connection error (see evhttp_connection_fail_()).  The
         * connection will be reset, and the user will be notified with a NULL
         * req parameter. */
        tt_assert(!req);
@@ -3143,7 +3148,12 @@ http_connection_retry_test(void *arg)
         */
        test_ok = 0;
 
-       evhttp_connection_set_timeout(evcon, 1);
+       {
+               const struct timeval tv_timeout = { 0, 500000 };
+               const struct timeval tv_retry = { 0, 500000 };
+               evhttp_connection_set_timeout_tv(evcon, &tv_timeout);
+               evhttp_connection_set_initial_retry_tv(evcon, &tv_retry);
+       }
        evhttp_connection_set_retries(evcon, 1);
 
        req = evhttp_request_new(http_connection_retry_done, data->base);
@@ -3160,9 +3170,9 @@ http_connection_retry_test(void *arg)
        evutil_gettimeofday(&tv_start, NULL);
        event_base_dispatch(data->base);
        evutil_gettimeofday(&tv_end, NULL);
-       evutil_timersub(&tv_end, &tv_start, &tv_end);
-       tt_int_op(tv_end.tv_sec, >, 1);
-       tt_int_op(tv_end.tv_sec, <, 6);
+
+       /* fails fast, .5 sec to wait to retry, fails fast again. */
+       test_timeval_diff_leq(&tv_start, &tv_end, 500, 200);
 
        tt_assert(test_ok == 1);
 
@@ -3186,22 +3196,19 @@ http_connection_retry_test(void *arg)
                tt_abort_msg("Couldn't make request");
        }
 
-       /* start up a web server one second after the connection tried
+       /* start up a web server .2 seconds after the connection tried
         * to send a request
         */
        evutil_timerclear(&tv);
-       tv.tv_sec = 1;
+       tv.tv_usec = 200000;
        http_make_web_server_base = data->base;
        event_base_once(data->base, -1, EV_TIMEOUT, http_make_web_server, &port, &tv);
 
        evutil_gettimeofday(&tv_start, NULL);
        event_base_dispatch(data->base);
        evutil_gettimeofday(&tv_end, NULL);
-
-       evutil_timersub(&tv_end, &tv_start, &tv_end);
-
-       tt_int_op(tv_end.tv_sec, >, 1);
-       tt_int_op(tv_end.tv_sec, <, 6);
+       /* We'll wait twice as long as we did last time. */
+       test_timeval_diff_leq(&tv_start, &tv_end, 1000, 400);
 
        tt_int_op(test_ok, ==, 1);
 
index 60b933043584f216e773ccbd6b1f7287cda6fe5f..17b385241fa1fac04f3b48d5dce968c03f4ea274 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -167,27 +167,27 @@ test_iocp_port(void *ptr)
        tt_assert(o1.lock);
        tt_assert(o2.lock);
 
-       event_overlapped_init(&o1.eo, dummy_cb);
-       event_overlapped_init(&o2.eo, dummy_cb);
+       event_overlapped_init_(&o1.eo, dummy_cb);
+       event_overlapped_init_(&o2.eo, dummy_cb);
 
-       port = event_iocp_port_launch(0);
+       port = event_iocp_port_launch_(0);
        tt_assert(port);
 
-       tt_assert(!event_iocp_activate_overlapped(port, &o1.eo, 10, 100));
-       tt_assert(!event_iocp_activate_overlapped(port, &o2.eo, 20, 200));
+       tt_assert(!event_iocp_activate_overlapped_(port, &o1.eo, 10, 100));
+       tt_assert(!event_iocp_activate_overlapped_(port, &o2.eo, 20, 200));
 
-       tt_assert(!event_iocp_activate_overlapped(port, &o1.eo, 11, 101));
-       tt_assert(!event_iocp_activate_overlapped(port, &o2.eo, 21, 201));
+       tt_assert(!event_iocp_activate_overlapped_(port, &o1.eo, 11, 101));
+       tt_assert(!event_iocp_activate_overlapped_(port, &o2.eo, 21, 201));
 
-       tt_assert(!event_iocp_activate_overlapped(port, &o1.eo, 12, 102));
-       tt_assert(!event_iocp_activate_overlapped(port, &o2.eo, 22, 202));
+       tt_assert(!event_iocp_activate_overlapped_(port, &o1.eo, 12, 102));
+       tt_assert(!event_iocp_activate_overlapped_(port, &o2.eo, 22, 202));
 
-       tt_assert(!event_iocp_activate_overlapped(port, &o1.eo, 13, 103));
-       tt_assert(!event_iocp_activate_overlapped(port, &o2.eo, 23, 203));
+       tt_assert(!event_iocp_activate_overlapped_(port, &o1.eo, 13, 103));
+       tt_assert(!event_iocp_activate_overlapped_(port, &o2.eo, 23, 203));
 
        tt_int_op(count_wait_for(8, 2000), ==, 0);
 
-       tt_want(!event_iocp_shutdown(port, 2000));
+       tt_want(!event_iocp_shutdown_(port, 2000));
 
        tt_int_op(o1.call_count, ==, 4);
        tt_int_op(o2.call_count, ==, 4);
@@ -215,7 +215,7 @@ read_complete(struct event_overlapped *eo, uintptr_t key,
     ev_ssize_t nbytes, int ok)
 {
        tt_assert(ok);
-       evbuffer_commit_read(rbuf, nbytes);
+       evbuffer_commit_read_(rbuf, nbytes);
        count_incr();
 end:
        ;
@@ -226,7 +226,7 @@ write_complete(struct event_overlapped *eo, uintptr_t key,
     ev_ssize_t nbytes, int ok)
 {
        tt_assert(ok);
-       evbuffer_commit_write(wbuf, nbytes);
+       evbuffer_commit_write_(wbuf, nbytes);
        count_incr();
 end:
        ;
@@ -244,24 +244,24 @@ test_iocp_evbuffer(void *ptr)
        int i;
 
        count_init();
-       event_overlapped_init(&rol, read_complete);
-       event_overlapped_init(&wol, write_complete);
+       event_overlapped_init_(&rol, read_complete);
+       event_overlapped_init_(&wol, write_complete);
 
        for (i = 0; i < (int)sizeof(junk); ++i)
                junk[i] = (char)(i);
 
-       rbuf = evbuffer_overlapped_new(data->pair[0]);
-       wbuf = evbuffer_overlapped_new(data->pair[1]);
+       rbuf = evbuffer_overlapped_new_(data->pair[0]);
+       wbuf = evbuffer_overlapped_new_(data->pair[1]);
        evbuffer_enable_locking(rbuf, NULL);
        evbuffer_enable_locking(wbuf, NULL);
 
-       port = event_iocp_port_launch(0);
+       port = event_iocp_port_launch_(0);
        tt_assert(port);
        tt_assert(rbuf);
        tt_assert(wbuf);
 
-       tt_assert(!event_iocp_port_associate(port, data->pair[0], 100));
-       tt_assert(!event_iocp_port_associate(port, data->pair[1], 100));
+       tt_assert(!event_iocp_port_associate_(port, data->pair[0], 100));
+       tt_assert(!event_iocp_port_associate_(port, data->pair[1], 100));
 
        for (i=0;i<10;++i)
                evbuffer_add(wbuf, junk, sizeof(junk));
@@ -269,13 +269,13 @@ test_iocp_evbuffer(void *ptr)
        buf = evbuffer_new();
        tt_assert(buf != NULL);
        evbuffer_add(rbuf, junk, sizeof(junk));
-       tt_assert(!evbuffer_launch_read(rbuf, 2048, &rol));
+       tt_assert(!evbuffer_launch_read_(rbuf, 2048, &rol));
        evbuffer_add_buffer(buf, rbuf);
        tt_int_op(evbuffer_get_length(buf), ==, sizeof(junk));
        for (chain = buf->first; chain; chain = chain->next)
                tt_int_op(chain->flags & EVBUFFER_MEM_PINNED_ANY, ==, 0);
        tt_assert(!evbuffer_get_length(rbuf));
-       tt_assert(!evbuffer_launch_write(wbuf, 512, &wol));
+       tt_assert(!evbuffer_launch_write_(wbuf, 512, &wol));
 
        tt_int_op(count_wait_for(2, 2000), ==, 0);
 
@@ -283,7 +283,7 @@ test_iocp_evbuffer(void *ptr)
 
        /* FIXME Actually test some stuff here. */
 
-       tt_want(!event_iocp_shutdown(port, 2000));
+       tt_want(!event_iocp_shutdown_(port, 2000));
 end:
        count_free();
        evbuffer_free(rbuf);
@@ -310,13 +310,13 @@ test_iocp_bufferevent_async(void *ptr)
        char buf[128];
        size_t n;
 
-       event_base_start_iocp(data->base, 0);
-       port = event_base_get_iocp(data->base);
+       event_base_start_iocp_(data->base, 0);
+       port = event_base_get_iocp_(data->base);
        tt_assert(port);
 
-       bea1 = bufferevent_async_new(data->base, data->pair[0],
+       bea1 = bufferevent_async_new_(data->base, data->pair[0],
            BEV_OPT_DEFER_CALLBACKS);
-       bea2 = bufferevent_async_new(data->base, data->pair[1],
+       bea2 = bufferevent_async_new_(data->base, data->pair[1],
            BEV_OPT_DEFER_CALLBACKS);
        tt_assert(bea1);
        tt_assert(bea2);
index 5a794cc434cce6fd46da1aebe5414d0da3453f12..b2dd04353ad5b3686a863e13e8b635efcba66c14 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,6 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "util-internal.h"
 
 #ifdef _WIN32
 #include <winsock2.h>
@@ -49,7 +50,6 @@
 #include "regress.h"
 #include "tinytest.h"
 #include "tinytest_macros.h"
-#include "util-internal.h"
 
 static void
 acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
@@ -115,9 +115,9 @@ regress_pick_a_port(void *arg)
        tt_ptr_op(evconnlistener_get_base(listener2), ==, base);
 
        fd1 = fd2 = fd3 = -1;
-       evutil_socket_connect(&fd1, (struct sockaddr*)&ss1, slen1);
-       evutil_socket_connect(&fd2, (struct sockaddr*)&ss1, slen1);
-       evutil_socket_connect(&fd3, (struct sockaddr*)&ss2, slen2);
+       evutil_socket_connect_(&fd1, (struct sockaddr*)&ss1, slen1);
+       evutil_socket_connect_(&fd2, (struct sockaddr*)&ss1, slen1);
+       evutil_socket_connect_(&fd3, (struct sockaddr*)&ss2, slen2);
 
 #ifdef _WIN32
        Sleep(100); /* XXXX this is a stupid stopgap. */
index 26635f9e359c29184e43a001d21ac8ecb2002813..05e28433c0d48d403c0341f5f69b537202042898 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,6 +24,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "util-internal.h"
 
 #ifdef _WIN32
 #include <winsock2.h>
 #include <fcntl.h>
 #endif
 
+#if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__)
+#if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 && \
+    __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070)
+#define FORK_BREAKS_GCOV
+#include <vproc.h>
+#endif
+#endif
+
 #include "event2/event-config.h"
 
-#ifdef _EVENT___func__
-#define __func__ _EVENT___func__
+#ifdef EVENT____func__
+#define __func__ EVENT____func__
 #endif
 
 #if 0
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -76,6 +85,7 @@
 #include "tinytest.h"
 #include "tinytest_macros.h"
 #include "../iocp-internal.h"
+#include "../event-internal.h"
 
 long
 timeval_msec_diff(const struct timeval *start, const struct timeval *end)
@@ -84,7 +94,6 @@ timeval_msec_diff(const struct timeval *start, const struct timeval *end)
        ms *= 1000;
        ms += ((end->tv_usec - start->tv_usec)+500) / 1000;
        return ms;
-
 }
 
 /* ============================================================ */
@@ -156,6 +165,18 @@ regress_make_tmpfile(const void *data, size_t datalen, char **filename_out)
 #endif
 }
 
+#ifndef _WIN32
+pid_t
+regress_fork(void)
+{
+       pid_t pid = fork();
+#ifdef FORK_BREAKS_GCOV
+       vproc_transaction_begin(0);
+#endif
+       return pid;
+}
+#endif
+
 static void
 ignore_log_cb(int s, const char *msg)
 {
@@ -212,7 +233,7 @@ basic_test_setup(const struct testcase_t *testcase)
                        exit(1);
        }
        if (testcase->flags & TT_ENABLE_IOCP_FLAG) {
-               if (event_base_start_iocp(base, 0)<0) {
+               if (event_base_start_iocp_(base, 0)<0) {
                        event_base_free(base);
                        return (void*)TT_SKIP;
                }
@@ -257,10 +278,15 @@ basic_test_cleanup(const struct testcase_t *testcase, void *ptr)
        }
 
        if (testcase->flags & TT_NEED_BASE) {
-               if (data->base)
+               if (data->base) {
+                       event_base_assert_ok_(data->base);
                        event_base_free(data->base);
+               }
        }
 
+       if (testcase->flags & TT_FORK)
+               libevent_global_shutdown();
+
        free(data);
 
        return 1;
@@ -328,7 +354,7 @@ const struct testcase_setup_t legacy_setup = {
 
 /* ============================================================ */
 
-#if (!defined(_EVENT_HAVE_PTHREADS) && !defined(_WIN32)) || defined(_EVENT_DISABLE_THREAD_SUPPORT)
+#if (!defined(EVENT__HAVE_PTHREADS) && !defined(_WIN32)) || defined(EVENT__DISABLE_THREAD_SUPPORT)
 struct testcase_t thread_testcases[] = {
        { "basic", NULL, TT_SKIP, NULL, NULL },
        END_OF_TESTCASES
@@ -354,7 +380,7 @@ struct testgroup_t testgroups[] = {
        { "iocp/bufferevent/", bufferevent_iocp_testcases },
        { "iocp/listener/", listener_iocp_testcases },
 #endif
-#ifdef _EVENT_HAVE_OPENSSL
+#ifdef EVENT__HAVE_OPENSSL
        { "ssl/", ssl_testcases },
 #endif
        END_OF_GROUPS
@@ -382,7 +408,7 @@ main(int argc, const char **argv)
        tinytest_skip(testgroups, "http/connection_retry");
 #endif
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        if (!getenv("EVENT_NO_DEBUG_LOCKS"))
                evthread_enable_lock_debuging();
 #endif
@@ -390,6 +416,8 @@ main(int argc, const char **argv)
        if (tinytest_main(argc,argv,testgroups))
                return 1;
 
+       libevent_global_shutdown();
+
        return 0;
 }
 
index 6c00c5b85fcb1060143e3c573a50d93054da264c..a1f554ebbe8ff0f800fd3a8c90350ce698840c4b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "../minheap-internal.h"
 
 #include <stdlib.h>
 #include "event2/event_struct.h"
 
 #include "tinytest.h"
 #include "tinytest_macros.h"
-#include "../minheap-internal.h"
 
 static void
 set_random_timeout(struct event *ev)
@@ -58,38 +58,38 @@ test_heap_randomized(void *ptr)
        struct event *e, *last_e;
        int i;
 
-       min_heap_ctor(&heap);
+       min_heap_ctor_(&heap);
 
        for (i = 0; i < 1024; ++i) {
                inserted[i] = malloc(sizeof(struct event));
                set_random_timeout(inserted[i]);
-               min_heap_push(&heap, inserted[i]);
+               min_heap_push_(&heap, inserted[i]);
        }
        check_heap(&heap);
 
-       tt_assert(min_heap_size(&heap) == 1024);
+       tt_assert(min_heap_size_(&heap) == 1024);
 
        for (i = 0; i < 512; ++i) {
-               min_heap_erase(&heap, inserted[i]);
+               min_heap_erase_(&heap, inserted[i]);
                if (0 == (i % 32))
                        check_heap(&heap);
        }
-       tt_assert(min_heap_size(&heap) == 512);
+       tt_assert(min_heap_size_(&heap) == 512);
 
-       last_e = min_heap_pop(&heap);
+       last_e = min_heap_pop_(&heap);
        while (1) {
-               e = min_heap_pop(&heap);
+               e = min_heap_pop_(&heap);
                if (!e)
                        break;
                tt_want(evutil_timercmp(&last_e->ev_timeout,
                        &e->ev_timeout, <=));
        }
-       tt_assert(min_heap_size(&heap) == 0);
+       tt_assert(min_heap_size_(&heap) == 0);
 end:
        for (i = 0; i < 1024; ++i)
                free(inserted[i]);
 
-       min_heap_dtor(&heap);
+       min_heap_dtor_(&heap);
 }
 
 struct testcase_t minheap_testcases[] = {
index 530b6bf447d29b2a5c3d93f8c9b93c5dd1bab2f4..d33e3337e66b54840a2b3d596de7226783056593 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -37,7 +37,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -590,7 +590,7 @@ done:
 
 /* we just pause the rpc and continue it in the next callback */
 
-struct _rpc_hook_ctx {
+struct rpc_hook_ctx_ {
        void *vbase;
        void *ctx;
 };
@@ -600,7 +600,7 @@ static int hook_pause_cb_called=0;
 static void
 rpc_hook_pause_cb(evutil_socket_t fd, short what, void *arg)
 {
-       struct _rpc_hook_ctx *ctx = arg;
+       struct rpc_hook_ctx_ *ctx = arg;
        ++hook_pause_cb_called;
        evrpc_resume_request(ctx->vbase, ctx->ctx, EVRPC_CONTINUE);
        free(arg);
@@ -610,7 +610,7 @@ static int
 rpc_hook_pause(void *ctx, struct evhttp_request *req, struct evbuffer *evbuf,
     void *arg)
 {
-       struct _rpc_hook_ctx *tmp = malloc(sizeof(*tmp));
+       struct rpc_hook_ctx_ *tmp = malloc(sizeof(*tmp));
        struct timeval tv;
 
        assert(tmp != NULL);
@@ -687,8 +687,8 @@ rpc_client_timeout(void)
 
        pool = rpc_pool_with_connection(port);
 
-       /* set the timeout to 5 seconds */
-       evrpc_pool_set_timeout(pool, 5);
+       /* set the timeout to 1 second. */
+       evrpc_pool_set_timeout(pool, 1);
 
        /* set up the basic message */
        msg = msg_new();
index 6bac30e413297ecbc5ccb44c94e5efe7f682194f..c0c2027928ac57d3a549539f1c587f0d477bdecb 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
index b9446ae7fbe462c265417976a1b036677f40442c..e612c52fae5061e276c309c19b7f17d05faf19b6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,6 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "../util-internal.h"
 
 #ifdef _WIN32
 #include <winsock2.h>
@@ -34,7 +35,7 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include <sys/queue.h>
@@ -45,7 +46,7 @@
 #include <arpa/inet.h>
 #include <unistd.h>
 #endif
-#ifdef _EVENT_HAVE_NETINET_IN6_H
+#ifdef EVENT__HAVE_NETINET_IN6_H
 #include <netinet/in6.h>
 #endif
 #ifdef HAVE_NETDB_H
@@ -68,8 +69,6 @@
 #include "regress.h"
 #include "regress_testutils.h"
 
-#include "../util-internal.h"
-
 /* globals */
 static struct evdns_server_port *dns_port;
 evutil_socket_t dns_sock = -1;
@@ -159,6 +158,23 @@ regress_dns_server_cb(struct evdns_server_request *req, void *data)
                int err = atoi(tab->ans);
                tt_assert(! evdns_server_request_respond(req, err));
                return;
+       } else if (!strcmp(tab->anstype, "errsoa")) {
+               int err = atoi(tab->ans);
+               char soa_record[] =
+                       "\x04" "dns1" "\x05" "icann" "\x03" "org" "\0"
+                       "\x0a" "hostmaster" "\x05" "icann" "\x03" "org" "\0"
+                       "\x77\xde\x5e\xba" /* serial */
+                       "\x00\x00\x1c\x20" /* refreshtime = 2h */
+                       "\x00\x00\x0e\x10" /* retry = 1h */
+                       "\x00\x12\x75\x00" /* expiration = 14d */
+                       "\x00\x00\x0e\x10" /* min.ttl = 1h */
+                       ;
+               evdns_server_request_add_reply(
+                       req, EVDNS_AUTHORITY_SECTION,
+                       "example.com", EVDNS_TYPE_SOA, EVDNS_CLASS_INET,
+                       42, sizeof(soa_record) - 1, 0, soa_record);
+               tt_assert(! evdns_server_request_respond(req, err));
+               return;
        } else if (!strcmp(tab->anstype, "A")) {
                struct in_addr in;
                evutil_inet_pton(AF_INET, tab->ans, &in);
index 7f2936aabbd369fc20deb7affda37879a26ceb76..f90b9c997ab5e523a91313e3e6213aee02005890 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -24,8 +24,8 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef _TESTUTILS_H
-#define _TESTUTILS_H
+#ifndef REGRESS_TESTUTILS_H_INCLUDED_
+#define REGRESS_TESTUTILS_H_INCLUDED_
 
 #include "event2/dns.h"
 
@@ -62,5 +62,5 @@ struct sockaddr;
 int regress_get_listener_addr(struct evconnlistener *lev,
     struct sockaddr *sa, ev_socklen_t *socklen);
 
-#endif /* _TESTUTILS_H */
+#endif /* REGRESS_TESTUTILS_H_INCLUDED_ */
 
index d08edf3671afd624888552c629cbc1907639992d..091bcb73e31c8293d6832cacde2225d28d450bce 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,6 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "util-internal.h"
 
 /* The old tests here need assertions to work. */
 #undef NDEBUG
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_WAIT_H
+#ifdef EVENT__HAVE_SYS_WAIT_H
 #include <sys/wait.h>
 #endif
 
-#ifdef _EVENT_HAVE_PTHREADS
+#ifdef EVENT__HAVE_PTHREADS
 #include <pthread.h>
 #elif defined(_WIN32)
 #include <process.h>
 #endif
 #include <assert.h>
-#ifdef _EVENT_HAVE_UNISTD_H
+#ifdef EVENT__HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #include <time.h>
 
 #include "sys/queue.h"
 
-#include "event2/util.h"
 #include "event2/event.h"
 #include "event2/event_struct.h"
 #include "event2/thread.h"
+#include "event2/util.h"
 #include "evthread-internal.h"
 #include "event-internal.h"
 #include "defer-internal.h"
 #include "regress.h"
 #include "tinytest_macros.h"
+#include "time-internal.h"
 
-#ifdef _EVENT_HAVE_PTHREADS
+#ifdef EVENT__HAVE_PTHREADS
 #define THREAD_T pthread_t
 #define THREAD_FN void *
 #define THREAD_RETURN() return (NULL)
@@ -403,19 +405,22 @@ end:
 #define CB_COUNT 128
 #define QUEUE_THREAD_COUNT 8
 
-#ifdef _WIN32
-#define SLEEP_MS(ms) Sleep(ms)
-#else
-#define SLEEP_MS(ms) usleep((ms) * 1000)
-#endif
+static void
+SLEEP_MS(int ms)
+{
+       struct timeval tv;
+       tv.tv_sec = ms/1000;
+       tv.tv_usec = (ms%1000)*1000;
+       evutil_usleep_(&tv);
+}
 
 struct deferred_test_data {
        struct deferred_cb cbs[CB_COUNT];
        struct deferred_cb_queue *queue;
 };
 
-static time_t timer_start = 0;
-static time_t timer_end = 0;
+static struct timeval timer_start = {0,0};
+static struct timeval timer_end = {0,0};
 static unsigned callback_count = 0;
 static THREAD_T load_threads[QUEUE_THREAD_COUNT];
 static struct deferred_test_data deferred_data[QUEUE_THREAD_COUNT];
@@ -434,8 +439,8 @@ load_deferred_queue(void *arg)
        size_t i;
 
        for (i = 0; i < CB_COUNT; ++i) {
-               event_deferred_cb_init(&data->cbs[i], deferred_callback, NULL);
-               event_deferred_cb_schedule(data->queue, &data->cbs[i]);
+               event_deferred_cb_init_(&data->cbs[i], deferred_callback, NULL);
+               event_deferred_cb_schedule_(data->queue, &data->cbs[i]);
                SLEEP_MS(1);
        }
 
@@ -445,7 +450,7 @@ load_deferred_queue(void *arg)
 static void
 timer_callback(evutil_socket_t fd, short what, void *arg)
 {
-       timer_end = time(NULL);
+       evutil_gettimeofday(&timer_end, NULL);
 }
 
 static void
@@ -463,36 +468,109 @@ static void
 thread_deferred_cb_skew(void *arg)
 {
        struct basic_test_data *data = arg;
-       struct timeval tv_timer = {4, 0};
+       struct timeval tv_timer = {1, 0};
        struct deferred_cb_queue *queue;
-       time_t elapsed;
+       struct timeval elapsed;
+       int elapsed_usec;
        int i;
 
-       queue = event_base_get_deferred_cb_queue(data->base);
+       queue = event_base_get_deferred_cb_queue_(data->base);
        tt_assert(queue);
 
        for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
                deferred_data[i].queue = queue;
 
-       timer_start = time(NULL);
+       evutil_gettimeofday(&timer_start, NULL);
        event_base_once(data->base, -1, EV_TIMEOUT, timer_callback, NULL,
                        &tv_timer);
        event_base_once(data->base, -1, EV_TIMEOUT, start_threads_callback,
                        NULL, NULL);
        event_base_dispatch(data->base);
 
-       elapsed = timer_end - timer_start;
+       evutil_timersub(&timer_end, &timer_start, &elapsed);
        TT_BLATHER(("callback count, %u", callback_count));
-       TT_BLATHER(("elapsed time, %u", (unsigned)elapsed));
+       elapsed_usec =
+           (unsigned)(elapsed.tv_sec*1000000 + elapsed.tv_usec);
+       TT_BLATHER(("elapsed time, %u usec", elapsed_usec));
+
        /* XXX be more intelligent here.  just make sure skew is
-        * within 2 seconds for now. */
-       tt_assert(elapsed >= 4 && elapsed <= 6);
+        * within .4 seconds for now. */
+       tt_assert(elapsed_usec >= 600000 && elapsed_usec <= 1400000);
 
 end:
        for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
                THREAD_JOIN(load_threads[i]);
 }
 
+static struct event time_events[5];
+static struct timeval times[5];
+static struct event_base *exit_base = NULL;
+static void
+note_time_cb(evutil_socket_t fd, short what, void *arg)
+{
+       evutil_gettimeofday(arg, NULL);
+       if (arg == &times[4]) {
+               event_base_loopbreak(exit_base);
+       }
+}
+static THREAD_FN
+register_events_subthread(void *arg)
+{
+       struct timeval tv = {0,0};
+       SLEEP_MS(100);
+       event_active(&time_events[0], EV_TIMEOUT, 1);
+       SLEEP_MS(100);
+       event_active(&time_events[1], EV_TIMEOUT, 1);
+       SLEEP_MS(100);
+       tv.tv_usec = 100*1000;
+       event_add(&time_events[2], &tv);
+       tv.tv_usec = 150*1000;
+       event_add(&time_events[3], &tv);
+       SLEEP_MS(200);
+       event_active(&time_events[4], EV_TIMEOUT, 1);
+
+       THREAD_RETURN();
+}
+
+static void
+thread_no_events(void *arg)
+{
+       THREAD_T thread;
+       struct basic_test_data *data = arg;
+       struct timeval starttime, endtime;
+       int i;
+       exit_base = data->base;
+
+       memset(times,0,sizeof(times));
+       for (i=0;i<5;++i) {
+               event_assign(&time_events[i], data->base,
+                   -1, 0, note_time_cb, &times[i]);
+       }
+
+       evutil_gettimeofday(&starttime, NULL);
+       THREAD_START(thread, register_events_subthread, data->base);
+       event_base_loop(data->base, EVLOOP_NO_EXIT_ON_EMPTY);
+       evutil_gettimeofday(&endtime, NULL);
+       tt_assert(event_base_got_break(data->base));
+       THREAD_JOIN(thread);
+       for (i=0; i<5; ++i) {
+               struct timeval diff;
+               double sec;
+               evutil_timersub(&times[i], &starttime, &diff);
+               sec = diff.tv_sec + diff.tv_usec/1.0e6;
+               TT_BLATHER(("event %d at %.4f seconds", i, sec));
+       }
+       test_timeval_diff_eq(&starttime, &times[0], 100);
+       test_timeval_diff_eq(&starttime, &times[1], 200);
+       test_timeval_diff_eq(&starttime, &times[2], 400);
+       test_timeval_diff_eq(&starttime, &times[3], 450);
+       test_timeval_diff_eq(&starttime, &times[4], 500);
+       test_timeval_diff_eq(&starttime, &endtime,  500);
+
+end:
+       ;
+}
+
 #define TEST(name)                                                     \
        { #name, thread_##name, TT_FORK|TT_NEED_THREADS|TT_NEED_BASE,   \
          &basic_setup, NULL }
@@ -506,6 +584,7 @@ struct testcase_t thread_testcases[] = {
 #endif
        TEST(conditions_simple),
        TEST(deferred_cb_skew),
+       TEST(no_events),
        END_OF_TESTCASES
 };
 
index 66c2af87625aacf78296777ca1d48b0dcc3d1e5c..797fc1c812e933e989ee5353050c07caeaf2d0f4 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Nick Mathewson and Niels Provos
+ * Copyright (c) 2009-2012 Nick Mathewson and Niels Provos
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,6 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "../util-internal.h"
+
 #ifdef _WIN32
 #include <winsock2.h>
 #include <windows.h>
 #include <arpa/inet.h>
 #include <unistd.h>
 #endif
-#ifdef _EVENT_HAVE_NETINET_IN6_H
+#ifdef EVENT__HAVE_NETINET_IN6_H
 #include <netinet/in6.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_WAIT_H
+#ifdef EVENT__HAVE_SYS_WAIT_H
 #include <sys/wait.h>
 #endif
 #include <signal.h>
 #include "event2/event.h"
 #include "event2/util.h"
 #include "../ipv6-internal.h"
-#include "../util-internal.h"
 #include "../log-internal.h"
 #include "../strlcpy-internal.h"
+#include "../mm-internal.h"
+#include "../time-internal.h"
 
 #include "regress.h"
 
@@ -245,7 +248,7 @@ regress_sockaddr_port_parse(void *ptr)
                if (ent->safamily == AF_INET) {
                        struct sockaddr_in sin;
                        memset(&sin, 0, sizeof(sin));
-#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
                        sin.sin_len = sizeof(sin);
 #endif
                        sin.sin_family = AF_INET;
@@ -261,7 +264,7 @@ regress_sockaddr_port_parse(void *ptr)
                } else {
                        struct sockaddr_in6 sin6;
                        memset(&sin6, 0, sizeof(sin6));
-#ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
                        sin6.sin6_len = sizeof(sin6);
 #endif
                        sin6.sin6_family = AF_INET6;
@@ -292,7 +295,7 @@ regress_sockaddr_port_format(void *ptr)
        r = evutil_parse_sockaddr_port("192.168.1.1:80",
            (struct sockaddr*)&ss, &len);
        tt_int_op(r,==,0);
-       cp = evutil_format_sockaddr_port(
+       cp = evutil_format_sockaddr_port_(
                (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
        tt_ptr_op(cp,==,cbuf);
        tt_str_op(cp,==,"192.168.1.1:80");
@@ -301,13 +304,13 @@ regress_sockaddr_port_format(void *ptr)
        r = evutil_parse_sockaddr_port("[ff00::8010]:999",
            (struct sockaddr*)&ss, &len);
        tt_int_op(r,==,0);
-       cp = evutil_format_sockaddr_port(
+       cp = evutil_format_sockaddr_port_(
                (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
        tt_ptr_op(cp,==,cbuf);
        tt_str_op(cp,==,"[ff00::8010]:999");
 
        ss.ss_family=99;
-       cp = evutil_format_sockaddr_port(
+       cp = evutil_format_sockaddr_port_(
                (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
        tt_ptr_op(cp,==,cbuf);
        tt_str_op(cp,==,"<addr with socktype 99>");
@@ -352,7 +355,7 @@ test_evutil_sockaddr_predicates(void *ptr)
                }
 
                /* sockaddr_is_loopback */
-               if (ent->is_loopback != evutil_sockaddr_is_loopback((struct sockaddr*)&ss)) {
+               if (ent->is_loopback != evutil_sockaddr_is_loopback_((struct sockaddr*)&ss)) {
                        TT_FAIL(("evutil_sockaddr_loopback(%s) not as expected",
                                ent->parse));
                }
@@ -469,7 +472,7 @@ check_error_logging(void (*fn)(void), int wantexitcode,
        int status = 0, exitcode;
        fatal_want_severity = wantseverity;
        fatal_want_message = wantmsg;
-       if ((pid = fork()) == 0) {
+       if ((pid = regress_fork()) == 0) {
                /* child process */
                fn();
                exit(0); /* should be unreachable. */
@@ -532,22 +535,22 @@ test_evutil_log(void *ptr)
         * module didn't enforce the requirement that a fatal callback
         * actually exit.  Now, it exits no matter what, so if we wan to
         * reinstate these tests, we'll need to fork for each one. */
-       check_error_logging(errx_fn, 2, _EVENT_LOG_ERR,
+       check_error_logging(errx_fn, 2, EVENT_LOG_ERR,
            "Fatal error; too many kumquats (5)");
        RESET();
 #endif
 
        event_warnx("Far too many %s (%d)", "wombats", 99);
-       LOGEQ(_EVENT_LOG_WARN, "Far too many wombats (99)");
+       LOGEQ(EVENT_LOG_WARN, "Far too many wombats (99)");
        RESET();
 
        event_msgx("Connecting lime to coconut");
-       LOGEQ(_EVENT_LOG_MSG, "Connecting lime to coconut");
+       LOGEQ(EVENT_LOG_MSG, "Connecting lime to coconut");
        RESET();
 
        event_debug(("A millisecond passed! We should log that!"));
 #ifdef USE_DEBUG
-       LOGEQ(_EVENT_LOG_DEBUG, "A millisecond passed! We should log that!");
+       LOGEQ(EVENT_LOG_DEBUG, "A millisecond passed! We should log that!");
 #else
        tt_int_op(logsev,==,0);
        tt_ptr_op(logmsg,==,NULL);
@@ -559,13 +562,13 @@ test_evutil_log(void *ptr)
        event_warn("Couldn't open %s", "/bad/file");
        evutil_snprintf(buf, sizeof(buf),
            "Couldn't open /bad/file: %s",strerror(ENOENT));
-       LOGEQ(_EVENT_LOG_WARN,buf);
+       LOGEQ(EVENT_LOG_WARN,buf);
        RESET();
 
 #ifdef CAN_CHECK_ERR
        evutil_snprintf(buf, sizeof(buf),
            "Couldn't open /very/bad/file: %s",strerror(ENOENT));
-       check_error_logging(err_fn, 5, _EVENT_LOG_ERR, buf);
+       check_error_logging(err_fn, 5, EVENT_LOG_ERR, buf);
        RESET();
 #endif
 
@@ -582,11 +585,11 @@ test_evutil_log(void *ptr)
        errno = EAGAIN;
 #endif
        event_sock_warn(fd, "Unhappy socket");
-       LOGEQ(_EVENT_LOG_WARN, buf);
+       LOGEQ(EVENT_LOG_WARN, buf);
        RESET();
 
 #ifdef CAN_CHECK_ERR
-       check_error_logging(sock_err_fn, 20, _EVENT_LOG_ERR, buf);
+       check_error_logging(sock_err_fn, 20, EVENT_LOG_ERR, buf);
        RESET();
 #endif
 
@@ -765,7 +768,7 @@ ai_find_by_protocol(struct evutil_addrinfo *ai, int protocol)
 
 
 int
-_test_ai_eq(const struct evutil_addrinfo *ai, const char *sockaddr_port,
+test_ai_eq_(const struct evutil_addrinfo *ai, const char *sockaddr_port,
     int socktype, int protocol, int line)
 {
        struct sockaddr_storage ss;
@@ -827,6 +830,7 @@ test_evutil_rand(void *arg)
        char buf2[32];
        int counts[256];
        int i, j, k, n=0;
+       struct evutil_weakrand_state seed = { 12346789U };
 
        memset(buf2, 0, sizeof(buf2));
        memset(counts, 0, sizeof(counts));
@@ -834,8 +838,8 @@ test_evutil_rand(void *arg)
        for (k=0;k<32;++k) {
                /* Try a few different start and end points; try to catch
                 * the various misaligned cases of arc4random_buf */
-               int startpoint = _evutil_weakrand() % 4;
-               int endpoint = 32 - (_evutil_weakrand() % 4);
+               int startpoint = evutil_weakrand_(&seed) % 4;
+               int endpoint = 32 - (evutil_weakrand_(&seed) % 4);
 
                memset(buf2, 0, sizeof(buf2));
 
@@ -866,6 +870,13 @@ test_evutil_rand(void *arg)
                }
        }
 
+       evutil_weakrand_seed_(&seed, 0);
+       for (i = 0; i < 10000; ++i) {
+               ev_int32_t r = evutil_weakrand_range_(&seed, 9999);
+               tt_int_op(0, <=, r);
+               tt_int_op(r, <, 9999);
+       }
+
        /* for (i=0;i<256;++i) { printf("%3d %2d\n", i, counts[i]); } */
 end:
        ;
@@ -1061,7 +1072,7 @@ test_evutil_loadsyslib(void *arg)
 {
        HANDLE h=NULL;
 
-       h = evutil_load_windows_system_library(TEXT("kernel32.dll"));
+       h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
        tt_assert(h);
 
 end:
@@ -1071,6 +1082,227 @@ end:
 }
 #endif
 
+/** Test mm_malloc(). */
+static void
+test_event_malloc(void *arg)
+{
+       void *p = NULL;
+       (void)arg;
+
+       /* mm_malloc(0) should simply return NULL. */
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+       errno = 0;
+       p = mm_malloc(0);
+       tt_assert(p == NULL);
+       tt_int_op(errno, ==, 0);
+#endif
+
+       /* Trivial case. */
+       errno = 0;
+       p = mm_malloc(8);
+       tt_assert(p != NULL);
+       tt_int_op(errno, ==, 0);
+       mm_free(p);
+
+ end:
+       errno = 0;
+       return;
+}
+
+static void
+test_event_calloc(void *arg)
+{
+       void *p = NULL;
+       (void)arg;
+
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+       /* mm_calloc() should simply return NULL
+        * if either argument is zero. */
+       errno = 0;
+       p = mm_calloc(0, 0);
+       tt_assert(p == NULL);
+       tt_int_op(errno, ==, 0);
+       errno = 0;
+       p = mm_calloc(0, 1);
+       tt_assert(p == NULL);
+       tt_int_op(errno, ==, 0);
+       errno = 0;
+       p = mm_calloc(1, 0);
+       tt_assert(p == NULL);
+       tt_int_op(errno, ==, 0);
+#endif
+
+       /* Trivial case. */
+       errno = 0;
+       p = mm_calloc(8, 8);
+       tt_assert(p != NULL);
+       tt_int_op(errno, ==, 0);
+       mm_free(p);
+
+       /* mm_calloc() should set errno = ENOMEM and return NULL
+        * in case of potential overflow. */
+       errno = 0;
+       p = mm_calloc(EV_SIZE_MAX/2, EV_SIZE_MAX/2 + 8);
+       tt_assert(p == NULL);
+       tt_int_op(errno, ==, ENOMEM);
+
+ end:
+       errno = 0;
+       return;
+}
+
+static void
+test_event_strdup(void *arg)
+{
+       void *p = NULL;
+       (void)arg;
+
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+       /* mm_strdup(NULL) should set errno = EINVAL and return NULL. */
+       errno = 0;
+       p = mm_strdup(NULL);
+       tt_assert(p == NULL);
+       tt_int_op(errno, ==, EINVAL);
+#endif
+
+       /* Trivial cases. */
+
+       errno = 0;
+       p = mm_strdup("");
+       tt_assert(p != NULL);
+       tt_int_op(errno, ==, 0);
+       tt_str_op(p, ==, "");
+       mm_free(p);
+
+       errno = 0;
+       p = mm_strdup("foo");
+       tt_assert(p != NULL);
+       tt_int_op(errno, ==, 0);
+       tt_str_op(p, ==, "foo");
+       mm_free(p);
+
+       /* XXX
+        * mm_strdup(str) where str is a string of length EV_SIZE_MAX
+        * should set errno = ENOMEM and return NULL. */
+
+ end:
+       errno = 0;
+       return;
+}
+
+static void
+test_evutil_usleep(void *arg)
+{
+       struct timeval tv1, tv2, tv3, diff1, diff2;
+       const struct timeval quarter_sec = {0, 250*1000};
+       const struct timeval tenth_sec = {0, 100*1000};
+       long usec1, usec2;
+
+       evutil_gettimeofday(&tv1, NULL);
+       evutil_usleep_(&quarter_sec);
+       evutil_gettimeofday(&tv2, NULL);
+       evutil_usleep_(&tenth_sec);
+       evutil_gettimeofday(&tv3, NULL);
+
+       evutil_timersub(&tv2, &tv1, &diff1);
+       evutil_timersub(&tv3, &tv2, &diff2);
+       usec1 = diff1.tv_sec * 1000000 + diff1.tv_usec;
+       usec2 = diff2.tv_sec * 1000000 + diff2.tv_usec;
+
+       tt_int_op(usec1, >, 200000);
+       tt_int_op(usec1, <, 300000);
+       tt_int_op(usec2, >,  80000);
+       tt_int_op(usec2, <, 120000);
+
+end:
+       ;
+}
+
+static void
+test_evutil_monotonic(void *data_)
+{
+       /* Basic santity-test for monotonic timers.  What we'd really like
+        * to do is make sure that they can't go backwards even when the
+        * system clock goes backwards. But we haven't got a good way to
+        * move the system clock backwards.
+        */
+       struct basic_test_data *data = data_;
+       struct evutil_monotonic_timer timer;
+       const int precise = strstr(data->setup_data, "precise") != NULL;
+       const int fallback = strstr(data->setup_data, "fallback") != NULL;
+       struct timeval tv[10], delay;
+       int total_diff = 0;
+
+       int flags = 0, wantres, acceptdiff, i, maxstep = 25*1000;
+       if (precise)
+               flags |= EV_MONOT_PRECISE;
+       if (fallback)
+               flags |= EV_MONOT_FALLBACK;
+       if (precise || fallback) {
+#ifdef _WIN32
+               wantres = 10*1000;
+               acceptdiff = 1000;
+#else
+               wantres = 300;
+               acceptdiff = 100;
+#endif
+       } else {
+               wantres = 40*1000;
+               acceptdiff = 20*1000;
+       }
+       if (precise)
+               maxstep = 500;
+
+       TT_BLATHER(("Precise = %d", precise));
+       TT_BLATHER(("Fallback = %d", fallback));
+
+       /* First, make sure we match up with usleep. */
+
+       delay.tv_sec = 0;
+       delay.tv_usec = wantres;
+
+       tt_int_op(evutil_configure_monotonic_time_(&timer, flags), ==, 0);
+
+       for (i = 0; i < 10; ++i) {
+               evutil_gettime_monotonic_(&timer, &tv[i]);
+               evutil_usleep_(&delay);
+       }
+
+       for (i = 0; i < 9; ++i) {
+               struct timeval diff;
+               tt_assert(evutil_timercmp(&tv[i], &tv[i+1], <));
+               evutil_timersub(&tv[i+1], &tv[i], &diff);
+               tt_int_op(diff.tv_sec, ==, 0);
+               total_diff += diff.tv_usec;
+               TT_BLATHER(("Difference = %d", (int)diff.tv_usec));
+       }
+       tt_int_op(abs(total_diff/9 - wantres), <, acceptdiff);
+
+       /* Second, find out what precision we actually see. */
+
+       evutil_gettime_monotonic_(&timer, &tv[0]);
+       for (i = 1; i < 10; ++i) {
+               do {
+                       evutil_gettime_monotonic_(&timer, &tv[i]);
+               } while (evutil_timercmp(&tv[i-1], &tv[i], ==));
+       }
+
+       total_diff = 0;
+       for (i = 0; i < 9; ++i) {
+               struct timeval diff;
+               tt_assert(evutil_timercmp(&tv[i], &tv[i+1], <));
+               evutil_timersub(&tv[i+1], &tv[i], &diff);
+               tt_int_op(diff.tv_sec, ==, 0);
+               total_diff += diff.tv_usec;
+               TT_BLATHER(("Step difference = %d", (int)diff.tv_usec));
+       }
+       TT_BLATHER(("Average step difference = %d", total_diff / 9));
+       tt_int_op(total_diff/9, <, maxstep);
+
+end:
+       ;
+}
+
 struct testcase_t util_testcases[] = {
        { "ipv4_parse", regress_ipv4_parse, 0, NULL, NULL },
        { "ipv6_parse", regress_ipv6_parse, 0, NULL, NULL },
@@ -1089,6 +1321,13 @@ struct testcase_t util_testcases[] = {
 #ifdef _WIN32
        { "loadsyslib", test_evutil_loadsyslib, TT_FORK, NULL, NULL },
 #endif
+       { "mm_malloc", test_event_malloc, 0, NULL, NULL },
+       { "mm_calloc", test_event_calloc, 0, NULL, NULL },
+       { "mm_strdup", test_event_strdup, 0, NULL, NULL },
+       { "usleep", test_evutil_usleep, 0, NULL, NULL },
+       { "monotonic", test_evutil_monotonic, 0, &basic_setup, (void*)"" },
+       { "monotonic_precise", test_evutil_monotonic, 0, &basic_setup, (void*)"precise" },
+       { "monotonic_fallback", test_evutil_monotonic, 0, &basic_setup, (void*)"fallback" },
        END_OF_TESTCASES,
 };
 
index e74c1fff60393955da4ee376f575b33cd3d0dc9f..f6fa8517da9272d3c60670fbe635deab042da704 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
index 1b2af0e8ad51b98ac0ef8251733c34ea147061f5..509c258e1226d721ed15149acee9c1f5cab87a65 100644 (file)
@@ -1,5 +1,27 @@
 /*
- *  based on test-eof.c
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #include "event2/event-config.h"
 #endif
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 #include <fcntl.h>
@@ -169,8 +191,8 @@ main(int argc, char **argv)
        /* and watch for writability on one end of the pipe */
        ev = event_new(base,pair[1],EV_WRITE | EV_PERSIST, write_cb, &ev);
 
-       tv.tv_sec  = 5;
-       tv.tv_usec = 0;
+       tv.tv_sec  = 1;
+       tv.tv_usec = 500*1000;
 
        evtimer_add(timeout, &tv);
 
@@ -180,6 +202,10 @@ main(int argc, char **argv)
 
        event_base_dispatch(base);
 
+       event_free(ev);
+       event_free(timeout);
+       event_base_free(base);
+
        get_cpu_usage(&timer, &secPassed, &secUsed, &usage);
 
        /* attempt to calculate our cpu usage over the test should be
diff --git a/sntp/libevent/test/test-dumpevents.c b/sntp/libevent/test/test-dumpevents.c
new file mode 100644 (file)
index 0000000..ff01b3f
--- /dev/null
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#else
+#include <unistd.h>
+#endif
+
+#include <stdio.h>
+#include <event2/event.h>
+#include <signal.h>
+
+static void
+sock_perror(const char *s)
+{
+#ifdef _WIN32
+       const char *err = evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR());
+       fprintf(stderr, "%s: %s\n", s, err);
+#else
+       perror(s);
+#endif
+}
+
+static void
+callback1(evutil_socket_t fd, short events, void *arg)
+{
+}
+static void
+callback2(evutil_socket_t fd, short events, void *arg)
+{
+}
+
+/* Testing code for event_base_dump_events().
+
+   Notes that just because we have code to exercise this function,
+   doesn't mean that *ANYTHING* about the output format is guaranteed to
+   remain in the future.
+ */
+int
+main(int argc, char **argv)
+{
+#define N_EVENTS 13
+       int i;
+       struct event *ev[N_EVENTS];
+       evutil_socket_t pair1[2];
+       evutil_socket_t pair2[2];
+       struct timeval tv_onesec = {1,0};
+       struct timeval tv_two5sec = {2,500*1000};
+       const struct timeval *tv_onesec_common;
+       const struct timeval *tv_two5sec_common;
+       struct event_base *base;
+       struct timeval now;
+
+#ifdef _WIN32
+       WORD wVersionRequested;
+       WSADATA wsaData;
+       int     err;
+
+       wVersionRequested = MAKEWORD(2, 2);
+
+       err = WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+#ifdef _WIN32
+#define LOCAL_SOCKETPAIR_AF AF_INET
+#else
+#define LOCAL_SOCKETPAIR_AF AF_UNIX
+#endif
+
+       if (evutil_make_internal_pipe_(pair1) < 0 ||
+           evutil_make_internal_pipe_(pair2) < 0) {
+               sock_perror("evutil_make_internal_pipe_");
+               return 1;
+       }
+
+       if (!(base = event_base_new())) {
+               fprintf(stderr,"Couldn't make event_base\n");
+               return 2;
+       }
+
+       tv_onesec_common = event_base_init_common_timeout(base, &tv_onesec);
+       tv_two5sec_common = event_base_init_common_timeout(base, &tv_two5sec);
+
+       ev[0] = event_new(base, pair1[0], EV_WRITE, callback1, NULL);
+       ev[1] = event_new(base, pair1[1], EV_READ|EV_PERSIST, callback1, NULL);
+       ev[2] = event_new(base, pair2[0], EV_WRITE|EV_PERSIST, callback2, NULL);
+       ev[3] = event_new(base, pair2[1], EV_READ, callback2, NULL);
+
+       /* For timers */
+       ev[4] = evtimer_new(base, callback1, NULL);
+       ev[5] = evtimer_new(base, callback1, NULL);
+       ev[6] = evtimer_new(base, callback1, NULL);
+       ev[7] = event_new(base, -1, EV_PERSIST, callback2, NULL);
+       ev[8] = event_new(base, -1, EV_PERSIST, callback2, NULL);
+       ev[9] = event_new(base, -1, EV_PERSIST, callback2, NULL);
+
+       /* To activate */
+       ev[10] = event_new(base, -1, 0, callback1, NULL);
+       ev[11] = event_new(base, -1, 0, callback2, NULL);
+
+       /* Signals */
+       ev[12] = evsignal_new(base, SIGINT, callback2, NULL);
+
+       event_add(ev[0], NULL);
+       event_add(ev[1], &tv_onesec);
+       event_add(ev[2], tv_onesec_common);
+       event_add(ev[3], tv_two5sec_common);
+
+       event_add(ev[4], tv_onesec_common);
+       event_add(ev[5], tv_onesec_common);
+       event_add(ev[6], &tv_onesec);
+       event_add(ev[7], tv_two5sec_common);
+       event_add(ev[8], tv_onesec_common);
+       event_add(ev[9], &tv_two5sec);
+
+       event_active(ev[10], EV_READ, 1);
+       event_active(ev[11], EV_READ|EV_WRITE|EV_TIMEOUT, 1);
+       event_active(ev[1], EV_READ, 1);
+
+       event_add(ev[12], NULL);
+
+       evutil_gettimeofday(&now,NULL);
+       puts("=====expected");
+       printf("Now= %ld.%06d\n",(long)now.tv_sec,(int)now.tv_usec);
+       puts("Inserted:");
+       printf("  %p [fd  %ld] Write\n",ev[0],(long)pair1[0]);
+       printf("  %p [fd  %ld] Read Persist Timeout=T+1\n",ev[1],(long)pair1[1]);
+       printf("  %p [fd  %ld] Write Persist Timeout=T+1\n",ev[2],(long)pair2[0]);
+       printf("  %p [fd  %ld] Read Timeout=T+2.5\n",ev[3],(long)pair2[1]);
+       printf("  %p [fd  -1] Timeout=T+1\n",ev[4]);
+       printf("  %p [fd  -1] Timeout=T+1\n",ev[5]);
+       printf("  %p [fd  -1] Timeout=T+1\n",ev[6]);
+       printf("  %p [fd  -1] Persist Timeout=T+2.5\n",ev[7]);
+       printf("  %p [fd  -1] Persist Timeout=T+1\n",ev[8]);
+       printf("  %p [fd  -1] Persist Timeout=T+2.5\n",ev[9]);
+       printf("  %p [sig %d] Signal Persist\n", ev[12], (int)SIGINT);
+
+       puts("Active:");
+       printf("  %p [fd  -1, priority=0] Read active\n", ev[10]);
+       printf("  %p [fd  -1, priority=0] Read Write Timeout active\n", ev[11]);
+       printf("  %p [fd  %ld, priority=0] Read active\n", ev[1], (long)pair1[1]);
+
+       puts("======received");
+       event_base_dump_events(base, stdout);
+
+       for (i = 0; i < N_EVENTS; ++i) {
+               event_free(ev[i]);
+       }
+       event_base_free(base);
+
+       return 0;
+}
+
index b3cd7dfdcd8b205d638a7b214d9d17673e07b5a7..cad674603a09a39d0c53533c9b595aa31640ac2c 100644 (file)
@@ -1,6 +1,28 @@
 /*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 #include "event2/event-config.h"
 
 #endif
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 #include <fcntl.h>
@@ -26,8 +48,8 @@
 #include <event.h>
 #include <evutil.h>
 
-#ifdef _EVENT___func__
-#define __func__ _EVENT___func__
+#ifdef EVENT____func__
+#define __func__ EVENT____func__
 #endif
 
 int test_okay = 1;
diff --git a/sntp/libevent/test/test-fdleak.c b/sntp/libevent/test/test-fdleak.c
new file mode 100644 (file)
index 0000000..ee2432b
--- /dev/null
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) 2012 Ross Lagerwall <rosslagerwall@gmail.com>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_SYS_RESOURCE_H
+#include <sys/resource.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+
+#include "event2/event.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/listener.h"
+
+/* Number of requests to make. Setting this too high might result in the machine
+   running out of ephemeral ports */
+#ifdef _WIN32
+#define MAX_REQUESTS 1000
+#else
+#define MAX_REQUESTS 4000
+#endif
+
+/* Provide storage for the address, both for the server & the clients */
+static struct sockaddr_in sin;
+
+/* Number of sucessful requests so far */
+static int num_requests;
+
+static void start_client(struct event_base *base);
+
+static void
+my_perror(const char *s)
+{
+       fprintf(stderr, "%s: %s",
+           s, evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
+}
+
+/*
+===============================================
+Server functions
+===============================================
+*/
+
+/* Read a byte from the client and write it back */
+static void
+server_read_cb(struct bufferevent *bev, void *ctx)
+{
+       while (evbuffer_get_length(bufferevent_get_input(bev))) {
+               unsigned char tmp;
+               bufferevent_read(bev, &tmp, 1);
+               bufferevent_write(bev, &tmp, 1);
+       }
+}
+
+/* Wait for an EOF and then free the bufferevent */
+static void
+server_event_cb(struct bufferevent *bev, short events, void *ctx)
+{
+       if (events & BEV_EVENT_ERROR) {
+               my_perror("Error from bufferevent");
+               exit(1);
+       } else if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
+               bufferevent_free(bev);
+       }
+}
+
+/* Accept a client socket and set it up to for reading & writing */
+static void
+listener_accept_cb(struct evconnlistener *listener, evutil_socket_t sock,
+                   struct sockaddr *addr, int len, void *ptr)
+{
+       struct event_base *base = evconnlistener_get_base(listener);
+       struct bufferevent *bev = bufferevent_socket_new(base, sock,
+                                                         BEV_OPT_CLOSE_ON_FREE);
+
+       bufferevent_setcb(bev, server_read_cb, NULL, server_event_cb, NULL);
+       bufferevent_enable(bev, EV_READ|EV_WRITE);
+}
+
+/* Start the server listening on a random port and start the first client. */
+static void
+start_loop(void)
+{
+       struct event_base *base;
+       struct evconnlistener *listener;
+       struct sockaddr_storage ss;
+       ev_socklen_t socklen = sizeof(ss);
+       evutil_socket_t fd;
+
+       base = event_base_new();
+       if (base == NULL) {
+               puts("Could not open event base!");
+               exit(1);
+       }
+
+       listener = evconnlistener_new_bind(base, listener_accept_cb, NULL,
+           LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
+           -1, (struct sockaddr *)&sin, sizeof(sin));
+       if (listener == NULL) {
+               my_perror("Could not create listener!");
+               exit(1);
+       }
+       fd = evconnlistener_get_fd(listener);
+       if (fd < 0) {
+               puts("Couldn't get fd from listener");
+               exit(1);
+       }
+       if (getsockname(fd, (struct sockaddr *)&ss, &socklen) < 0) {
+               my_perror("getsockname()");
+               exit(1);
+       }
+       memcpy(&sin, &ss, sizeof(sin));
+       if (sin.sin_family != AF_INET) {
+               puts("AF mismatch from getsockname().");
+               exit(1);
+       }
+
+       start_client(base);
+
+       event_base_dispatch(base);
+}
+
+/*
+===============================================
+Client functions
+===============================================
+*/
+
+/* Check that the server sends back the same byte that the client sent.
+   If MAX_REQUESTS have been reached, exit. Otherwise, start another client. */
+static void
+client_read_cb(struct bufferevent *bev, void *ctx)
+{
+       unsigned char tmp;
+       struct event_base *base = bufferevent_get_base(bev);
+
+       bufferevent_read(bev, &tmp, 1);
+       if (tmp != 'A') {
+               puts("Incorrect data received!");
+               exit(2);
+       }
+       bufferevent_free(bev);
+
+       num_requests++;
+       if (num_requests == MAX_REQUESTS) {
+               event_base_loopbreak(base);
+       } else {
+               start_client(base);
+       }
+}
+
+/* Send a byte to the server. */
+static void
+client_event_cb(struct bufferevent *bev, short events, void *ctx)
+{
+       if (events & BEV_EVENT_CONNECTED) {
+               unsigned char tmp = 'A';
+               bufferevent_write(bev, &tmp, 1);
+       } else if (events & BEV_EVENT_ERROR) {
+               puts("Client socket got error!");
+               exit(2);
+       }
+
+       bufferevent_enable(bev, EV_READ);
+}
+
+/* Open a client socket to connect to localhost on sin */
+static void
+start_client(struct event_base *base)
+{
+       struct bufferevent *bev = bufferevent_socket_new(base, -1,
+                                                         BEV_OPT_CLOSE_ON_FREE);
+       bufferevent_setcb(bev, client_read_cb, NULL, client_event_cb, NULL);
+
+       if (bufferevent_socket_connect(bev, (struct sockaddr *)&sin,
+                                       sizeof(sin)) < 0) {
+               my_perror("Could not connect!");
+               bufferevent_free(bev);
+               exit(2);
+       }
+}
+
+int
+main(int argc, char **argv)
+{
+#ifdef EVENT__HAVE_SETRLIMIT
+       /* Set the fd limit to a low value so that any fd leak is caught without
+       making many requests. */
+       struct rlimit rl;
+       rl.rlim_cur = rl.rlim_max = 20;
+       if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
+               my_perror("setrlimit");
+               exit(3);
+       }
+#endif
+
+#ifdef _WIN32
+       WSADATA WSAData;
+       WSAStartup(0x101, &WSAData);
+#endif
+
+       /* Set up an address, used by both client & server. */
+       memset(&sin, 0, sizeof(sin));
+       sin.sin_family = AF_INET;
+       sin.sin_addr.s_addr = htonl(0x7f000001);
+       sin.sin_port = 0; /* Tell the implementation to pick a port. */
+
+       start_loop();
+
+       return 0;
+}
+
+/* XXX why does this test cause so much latency sometimes (OSX 10.5)? */
index 7e1bf8c7afc37530ac6959330c57629bda720402..3d28f0b1c876dc61810656e5da823ea7660d4b68 100644 (file)
@@ -1,15 +1,37 @@
 /*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 #include "event2/event-config.h"
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 #include <fcntl.h>
index c7cfe5520d07c7f665bc04d186fa9ad3fc4320e3..81c4afb54c3d410355081b59fc9afbb7cf57a59f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,6 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#include "../util-internal.h"
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -49,7 +50,6 @@
 #include "event2/listener.h"
 #include "event2/thread.h"
 
-#include "../util-internal.h"
 
 static int cfg_verbose = 0;
 static int cfg_help = 0;
@@ -60,6 +60,7 @@ static int cfg_connlimit = 0;
 static int cfg_grouplimit = 0;
 static int cfg_tick_msec = 1000;
 static int cfg_min_share = -1;
+static int cfg_group_drain = 0;
 
 static int cfg_connlimit_tolerance = -1;
 static int cfg_grouplimit_tolerance = -1;
@@ -79,10 +80,33 @@ static double seconds_per_tick = 0.0;
 struct client_state {
        size_t queued;
        ev_uint64_t received;
+
 };
+static const struct timeval *ms100_common=NULL;
+
+/* info from check_bucket_levels_cb */
+static int total_n_bev_checks = 0;
+static ev_int64_t total_rbucket_level=0;
+static ev_int64_t total_wbucket_level=0;
+static ev_int64_t total_max_to_read=0;
+static ev_int64_t total_max_to_write=0;
+static ev_int64_t max_bucket_level=EV_INT64_MIN;
+static ev_int64_t min_bucket_level=EV_INT64_MAX;
+
+/* from check_group_bucket_levels_cb */
+static int total_n_group_bev_checks = 0;
+static ev_int64_t total_group_rbucket_level = 0;
+static ev_int64_t total_group_wbucket_level = 0;
 
 static int n_echo_conns_open = 0;
 
+/* Info on the open connections */
+struct bufferevent **bevs;
+struct client_state *states;
+struct bufferevent_rate_limit_group *group = NULL;
+
+static void check_bucket_levels_cb(evutil_socket_t fd, short events, void *arg);
+
 static void
 loud_writecb(struct bufferevent *bev, void *ctx)
 {
@@ -159,14 +183,68 @@ echo_listenercb(struct evconnlistener *listener, evutil_socket_t newsock,
 
        bev = bufferevent_socket_new(base, newsock, flags);
        bufferevent_setcb(bev, echo_readcb, echo_writecb, echo_eventcb, NULL);
-       if (conn_bucket_cfg)
+       if (conn_bucket_cfg) {
+               struct event *check_event =
+                   event_new(base, -1, EV_PERSIST, check_bucket_levels_cb, bev);
                bufferevent_set_rate_limit(bev, conn_bucket_cfg);
+               event_add(check_event, ms100_common);
+       }
        if (ratelim_group)
                bufferevent_add_to_rate_limit_group(bev, ratelim_group);
        ++n_echo_conns_open;
        bufferevent_enable(bev, EV_READ|EV_WRITE);
 }
 
+/* Called periodically to check up on how full the buckets are */
+static void
+check_bucket_levels_cb(evutil_socket_t fd, short events, void *arg)
+{
+       struct bufferevent *bev = arg;
+
+       ev_ssize_t r = bufferevent_get_read_limit(bev);
+       ev_ssize_t w = bufferevent_get_write_limit(bev);
+       ev_ssize_t rm = bufferevent_get_max_to_read(bev);
+       ev_ssize_t wm = bufferevent_get_max_to_write(bev);
+       /* XXXX check that no value is above the cofigured burst
+        * limit */
+       total_rbucket_level += r;
+       total_wbucket_level += w;
+       total_max_to_read += rm;
+       total_max_to_write += wm;
+#define B(x) \
+       if ((x) > max_bucket_level)             \
+               max_bucket_level = (x);         \
+       if ((x) < min_bucket_level)             \
+               min_bucket_level = (x)
+       B(r);
+       B(w);
+#undef B
+
+       total_n_bev_checks++;
+       if (total_n_bev_checks >= .8 * (cfg_duration / cfg_tick_msec) * cfg_n_connections) {
+               event_free(event_base_get_running_event(bufferevent_get_base(bev)));
+       }
+}
+
+static void
+check_group_bucket_levels_cb(evutil_socket_t fd, short events, void *arg)
+{
+       if (ratelim_group) {
+               ev_ssize_t r = bufferevent_rate_limit_group_get_read_limit(ratelim_group);
+               ev_ssize_t w = bufferevent_rate_limit_group_get_write_limit(ratelim_group);
+               total_group_rbucket_level += r;
+               total_group_wbucket_level += w;
+       }
+       ++total_n_group_bev_checks;
+}
+
+static void
+group_drain_cb(evutil_socket_t fd, short events, void *arg)
+{
+       bufferevent_rate_limit_group_decrement_read(ratelim_group, cfg_group_drain);
+       bufferevent_rate_limit_group_decrement_write(ratelim_group, cfg_group_drain);
+}
+
 static int
 test_ratelimiting(void)
 {
@@ -177,10 +255,6 @@ test_ratelimiting(void)
        struct sockaddr_storage ss;
        ev_socklen_t slen;
 
-       struct bufferevent **bevs;
-       struct client_state *states;
-       struct bufferevent_rate_limit_group *group = NULL;
-
        int i;
 
        struct timeval tv;
@@ -191,6 +265,8 @@ test_ratelimiting(void)
        double expected_total_persec = -1.0, expected_avg_persec = -1.0;
        int ok = 1;
        struct event_config *base_cfg;
+       struct event *periodic_level_check;
+       struct event *group_drain_event=NULL;
 
        memset(&sin, 0, sizeof(sin));
        sin.sin_family = AF_INET;
@@ -210,6 +286,7 @@ test_ratelimiting(void)
 #endif
 
        base = event_base_new_with_config(base_cfg);
+       event_config_free(base_cfg);
 
        listener = evconnlistener_new_bind(base, echo_listenercb, base,
            LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
@@ -237,7 +314,7 @@ test_ratelimiting(void)
                        &cfg_tick);
                group = ratelim_group = bufferevent_rate_limit_group_new(
                        base, group_bucket_cfg);
-               expected_total_persec = cfg_grouplimit;
+               expected_total_persec = cfg_grouplimit - (cfg_group_drain / seconds_per_tick);
                expected_avg_persec = cfg_grouplimit / cfg_n_connections;
                if (cfg_connlimit > 0 && expected_avg_persec > cfg_connlimit)
                        expected_avg_persec = cfg_connlimit;
@@ -273,9 +350,24 @@ test_ratelimiting(void)
 
        event_base_loopexit(base, &tv);
 
+       tv.tv_sec = 0;
+       tv.tv_usec = 100*1000;
+       ms100_common = event_base_init_common_timeout(base, &tv);
+
+       periodic_level_check = event_new(base, -1, EV_PERSIST, check_group_bucket_levels_cb, NULL);
+       event_add(periodic_level_check, ms100_common);
+
+       if (cfg_group_drain && ratelim_group) {
+               group_drain_event = event_new(base, -1, EV_PERSIST, group_drain_cb, NULL);
+               event_add(group_drain_event, &cfg_tick);
+       }
+
        event_base_dispatch(base);
 
        ratelim_group = NULL; /* So no more responders get added */
+       event_free(periodic_level_check);
+       if (group_drain_event)
+               event_del(group_drain_event);
 
        for (i = 0; i < cfg_n_connections; ++i) {
                bufferevent_free(bevs[i]);
@@ -297,6 +389,27 @@ test_ratelimiting(void)
        if (group)
                bufferevent_rate_limit_group_free(group);
 
+       if (total_n_bev_checks) {
+               printf("Average read bucket level: %f\n",
+                   (double)total_rbucket_level/total_n_bev_checks);
+               printf("Average write bucket level: %f\n",
+                   (double)total_wbucket_level/total_n_bev_checks);
+               printf("Highest read bucket level: %f\n",
+                   (double)max_bucket_level);
+               printf("Highest write bucket level: %f\n",
+                   (double)min_bucket_level);
+               printf("Average max-to-read: %f\n",
+                   ((double)total_max_to_read)/total_n_bev_checks);
+               printf("Average max-to-write: %f\n",
+                   ((double)total_max_to_write)/total_n_bev_checks);
+       }
+       if (total_n_group_bev_checks) {
+               printf("Average group read bucket level: %f\n",
+                   ((double)total_group_rbucket_level)/total_n_group_bev_checks);
+               printf("Average group write bucket level: %f\n",
+                   ((double)total_group_wbucket_level)/total_n_group_bev_checks);
+       }
+
        total_received = 0;
        total_persec = 0.0;
        total_sq_persec = 0.0;
@@ -358,6 +471,7 @@ static struct option {
        { "-d", &cfg_duration, 1, 0 },
        { "-c", &cfg_connlimit, 0, 0 },
        { "-g", &cfg_grouplimit, 0, 0 },
+       { "-G", &cfg_group_drain, -100000, 0 },
        { "-t", &cfg_tick_msec, 10, 0 },
        { "--min-share", &cfg_min_share, 0, 0 },
        { "--check-connlimit", &cfg_connlimit_tolerance, 0, 0 },
@@ -412,6 +526,7 @@ usage(void)
 "         (default: None.)\n"
 "  -g INT: Group-rate limit applied to sum of all usage in bytes per second\n"
 "         (default: None.)\n"
+"  -G INT: drain INT bytes from the group limit every tick. (default: 0)\n"
 "  -t INT: Granularity of timing, in milliseconds (default: 1000 msec)\n");
 }
 
@@ -470,7 +585,7 @@ main(int argc, char **argv)
 #endif
        }
 
-#ifndef _EVENT_DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
        evthread_enable_lock_debuging();
 #endif
 
index 229cba548116f5a9c54d617b6af7f1370f50d220..b5e0ca62a920df77b67f343814bede071c5a0229 100755 (executable)
@@ -66,6 +66,17 @@ run_tests () {
                announce FAILED ;
                FAILED=yes
        fi
+
+       announce_n "  Connection limit and group limit with independent drain:"
+       if $TEST_DIR/test-ratelim -c 1000 -g 35000 -n 30 -t 100 -G 500 --check-grouplimit 1000 --check-connlimit 50 --check-stddev 50 >>"$TEST_OUTPUT_FILE"
+       then
+               announce OKAY ;
+       else
+               announce FAILED ;
+               FAILED=yes
+       fi
+
+
 }
 
 announce "Running rate-limiting tests:"
index 8e4314875fdfba8cdeff6d2a2607b2d5c30d2898..8b763c160d7e4e669dfcb1f65cf8f2e032d6dd7e 100644 (file)
@@ -1,6 +1,28 @@
 /*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 #include "event2/event-config.h"
 
index 87a04a289c89541bdb05adbfbe4d933dcdc2bf5f..7df0e9c94c101731c000bf2ce84e1829f1f81a7d 100644 (file)
@@ -1,6 +1,28 @@
 /*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 #include "event2/event-config.h"
 
 #endif
 #include <sys/types.h>
 #include <sys/stat.h>
-#ifdef _EVENT_HAVE_SYS_TIME_H
+#ifdef EVENT__HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
 #include <fcntl.h>
@@ -29,8 +51,8 @@
 #include "event2/event_compat.h"
 #include "event2/util.h"
 
-#ifdef _EVENT___func__
-#define __func__ _EVENT___func__
+#ifdef EVENT____func__
+#define __func__ EVENT____func__
 #endif
 
 evutil_socket_t pair[2];
index 58ab553113db2033da24230585be7577941243f2..59748c00f6a8dc6da3b51c5f04f6587156cbfb90 100755 (executable)
@@ -1,11 +1,9 @@
 #!/bin/sh
 
+BACKENDS="EVPORT KQUEUE EPOLL DEVPOLL POLL SELECT WIN32"
+TESTS="test-eof test-weof test-time test-changelist test-fdleak"
 FAILED=no
-
-if test "x$TEST_OUTPUT_FILE" = "x"
-then
-       TEST_OUTPUT_FILE=/dev/null
-fi
+TEST_OUTPUT_FILE=${TEST_OUTPUT_FILE:-/dev/null}
 
 # /bin/echo is a little more likely to support -n than sh's builtin echo,
 # printf is even more likely
@@ -27,22 +25,24 @@ then
 fi
 
 TEST_DIR=.
+TEST_SRC_DIR=.
 
 T=`echo "$0" | sed -e 's/test.sh$//'`
 if test -x "$T/test-init"
 then
        TEST_DIR="$T"
 fi
+if test -e "$T/check-dumpevents.py"
+then
+       TEST_SRC_DIR="$T"
+fi
 
 setup () {
-       EVENT_NOKQUEUE=yes; export EVENT_NOKQUEUE
-       EVENT_NODEVPOLL=yes; export EVENT_NODEVPOLL
-       EVENT_NOPOLL=yes; export EVENT_NOPOLL
-       EVENT_NOSELECT=yes; export EVENT_NOSELECT
-       EVENT_NOEPOLL=yes; export EVENT_NOEPOLL
+       for i in $BACKENDS; do
+               eval "EVENT_NO$i=yes; export EVENT_NO$i"
+       done
        unset EVENT_EPOLL_USE_CHANGELIST
-       EVENT_NOEVPORT=yes; export EVENT_NOEVPORT
-       EVENT_NOWIN32=yes; export EVENT_NOWIN32
+       unset EVENT_PRECISE_TIMER
 }
 
 announce () {
@@ -64,38 +64,31 @@ run_tests () {
                announce Skipping test
                return
        fi
-
-       announce_n " test-eof: "
-       if $TEST_DIR/test-eof >>"$TEST_OUTPUT_FILE" ;
-       then
-               announce OKAY ;
-       else
-               announce FAILED ;
-               FAILED=yes
-       fi
-       announce_n " test-weof: "
-       if $TEST_DIR/test-weof >>"$TEST_OUTPUT_FILE" ;
-       then
-               announce OKAY ;
-       else
-               announce FAILED ;
-               FAILED=yes
-       fi
-       announce_n " test-time: "
-       if $TEST_DIR/test-time >>"$TEST_OUTPUT_FILE" ;
-       then
-               announce OKAY ;
+       for i in $TESTS; do
+               announce_n " $i: "
+               if $TEST_DIR/$i >>"$TEST_OUTPUT_FILE" ;
+               then
+                       announce OKAY ;
+               else
+                       announce FAILED ;
+                       FAILED=yes
+               fi
+       done
+       announce_n " test-dumpevents: "
+       if python -c 'import sys; assert(sys.version_info >= (2, 4))' 2>/dev/null; then
+           if $TEST_DIR/test-dumpevents | python $TEST_SRC_DIR/check-dumpevents.py >> "$TEST_OUTPUT_FILE" ;
+           then
+               announce OKAY ;
+           else
+               announce FAILED ;
+           fi
        else
-               announce FAILED ;
-               FAILED=yes
-       fi
-       announce_n " test-changelist: "
-       if $TEST_DIR/test-changelist >>"$TEST_OUTPUT_FILE" ;
-       then
-               announce OKAY ;
-       else
-               announce FAILED ;
-               FAILED=yes
+           # no python
+           if $TEST_DIR/test-dumpevents >/dev/null; then
+               announce "OKAY (output not checked)" ;
+           else
+               announce "FAILED (output not checked)" ;
+           fi
        fi
        test -x $TEST_DIR/regress || return
        announce_n " regress: "
@@ -120,21 +113,24 @@ do_test() {
        unset EVENT_NO$1
        if test "$2" = "(changelist)" ; then
            EVENT_EPOLL_USE_CHANGELIST=yes; export EVENT_EPOLL_USE_CHANGELIST
+       elif test "$2" = "(timerfd)" ; then
+           EVENT_PRECISE_TIMER=1; export EVENT_PRECISE_TIMER
+       elif test "$2" = "(timerfd+changelist)" ; then
+           EVENT_EPOLL_USE_CHANGELIST=yes; export EVENT_EPOLL_USE_CHANGELIST
+           EVENT_PRECISE_TIMER=1; export EVENT_PRECISE_TIMER
         fi
+
        run_tests
 }
 
 announce "Running tests:"
 
-# Need to do this by hand?
-do_test EVPORT
-do_test KQUEUE
-do_test EPOLL
+do_test EPOLL "(timerfd)"
 do_test EPOLL "(changelist)"
-do_test DEVPOLL
-do_test POLL
-do_test SELECT
-do_test WIN32
+do_test EPOLL "(timerfd+changelist)"
+for i in $BACKENDS; do
+       do_test $i
+done
 
 if test "$FAILED" = "yes"; then
        exit 1
index 051d9f9347c9950f39693b3985ac3d0632000384..644ea926c47e08e404ec188bf877d027aae58c10 100644 (file)
@@ -1,4 +1,4 @@
-/* tinytest.c -- Copyright 2009-2010 Nick Mathewson
+/* tinytest.c -- Copyright 2009-2012 Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+#ifdef TINYTEST_LOCAL
+#include "tinytest_local.h"
+#endif
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <assert.h>
 
-#ifdef TINYTEST_LOCAL
-#include "tinytest_local.h"
-#endif
-
 #ifdef _WIN32
 #include <windows.h>
 #else
 #include <unistd.h>
 #endif
 
+#if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__)
+#if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 && \
+    __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070)
+/* Workaround for a stupid bug in OSX 10.6 */
+#define FORK_BREAKS_GCOV
+#include <vproc.h>
+#endif
+#endif
+
 #ifndef __GNUC__
 #define __attribute__(x)
 #endif
@@ -74,7 +82,7 @@ static void usage(struct testgroup_t *groups, int list_groups)
   __attribute__((noreturn));
 
 static enum outcome
-_testcase_run_bare(const struct testcase_t *testcase)
+testcase_run_bare_(const struct testcase_t *testcase)
 {
        void *env = NULL;
        int outcome;
@@ -101,7 +109,7 @@ _testcase_run_bare(const struct testcase_t *testcase)
 #define MAGIC_EXITCODE 42
 
 static enum outcome
-_testcase_run_forked(const struct testgroup_t *group,
+testcase_run_forked_(const struct testgroup_t *group,
                     const struct testcase_t *testcase)
 {
 #ifdef _WIN32
@@ -120,7 +128,7 @@ _testcase_run_forked(const struct testgroup_t *group,
        DWORD exitcode;
 
        if (!in_tinytest_main) {
-               printf("\nERROR.  On Windows, _testcase_run_forked must be"
+               printf("\nERROR.  On Windows, testcase_run_forked_ must be"
                       " called from within tinytest_main.\n");
                abort();
        }
@@ -161,12 +169,15 @@ _testcase_run_forked(const struct testgroup_t *group,
        if (opt_verbosity>0)
                printf("[forking] ");
        pid = fork();
+#ifdef FORK_BREAKS_GCOV
+       vproc_transaction_begin(0);
+#endif
        if (!pid) {
                /* child. */
                int test_r, write_r;
                char b[1];
                close(outcome_pipe[0]);
-               test_r = _testcase_run_bare(testcase);
+               test_r = testcase_run_bare_(testcase);
                assert(0<=(int)test_r && (int)test_r<=2);
                b[0] = "NYS"[test_r];
                write_r = (int)write(outcome_pipe[1], b, 1);
@@ -220,9 +231,9 @@ testcase_run_one(const struct testgroup_t *group,
        }
 
        if ((testcase->flags & TT_FORK) && !(opt_forked||opt_nofork)) {
-               outcome = _testcase_run_forked(group, testcase);
+               outcome = testcase_run_forked_(group, testcase);
        } else {
-               outcome = _testcase_run_bare(testcase);
+               outcome = testcase_run_bare_(testcase);
        }
 
        if (outcome == OK) {
@@ -248,7 +259,7 @@ testcase_run_one(const struct testgroup_t *group,
 }
 
 int
-_tinytest_set_flag(struct testgroup_t *groups, const char *arg, unsigned long flag)
+tinytest_set_flag_(struct testgroup_t *groups, const char *arg, unsigned long flag)
 {
        int i, j;
        size_t length = LONGEST_TEST_NAME;
@@ -280,7 +291,7 @@ usage(struct testgroup_t *groups, int list_groups)
        puts("  Use --list-tests for a list of tests.");
        if (list_groups) {
                puts("Known tests are:");
-               _tinytest_set_flag(groups, "..", 0);
+               tinytest_set_flag_(groups, "..", 0);
        }
        exit(0);
 }
@@ -323,28 +334,28 @@ tinytest_main(int c, const char **v, struct testgroup_t *groups)
                        }
                } else {
                        const char *test = v[i];
-                       int flag = _TT_ENABLED;
+                       int flag = TT_ENABLED_;
                        if (test[0] == ':') {
                                ++test;
                                flag = TT_SKIP;
                        } else {
                                ++n;
                        }
-                       if (!_tinytest_set_flag(groups, test, flag)) {
+                       if (!tinytest_set_flag_(groups, test, flag)) {
                                printf("No such test as %s!\n", v[i]);
                                return -1;
                        }
                }
        }
        if (!n)
-               _tinytest_set_flag(groups, "..", _TT_ENABLED);
+               tinytest_set_flag_(groups, "..", TT_ENABLED_);
 
        setvbuf(stdout, NULL, _IONBF, 0);
 
        ++in_tinytest_main;
        for (i=0; groups[i].prefix; ++i)
                for (j=0; groups[i].cases[j].name; ++j)
-                       if (groups[i].cases[j].flags & _TT_ENABLED)
+                       if (groups[i].cases[j].flags & TT_ENABLED_)
                                testcase_run_one(&groups[i],
                                                 &groups[i].cases[j]);
 
@@ -363,13 +374,13 @@ tinytest_main(int c, const char **v, struct testgroup_t *groups)
 }
 
 int
-_tinytest_get_verbosity(void)
+tinytest_get_verbosity_(void)
 {
        return opt_verbosity;
 }
 
 void
-_tinytest_set_test_failed(void)
+tinytest_set_test_failed_(void)
 {
        if (opt_verbosity <= 0 && cur_test_name) {
                if (opt_verbosity==0) puts("");
@@ -380,7 +391,7 @@ _tinytest_set_test_failed(void)
 }
 
 void
-_tinytest_set_test_skipped(void)
+tinytest_set_test_skipped_(void)
 {
        if (cur_test_outcome==OK)
                cur_test_outcome = SKIP;
index cbe28b7f512ce5dedc5c1d6737ae72718d0841b9..bcac9f079cb5c28438e0e2bef56600524a871df3 100644 (file)
@@ -1,4 +1,4 @@
-/* tinytest.h -- Copyright 2009-2010 Nick Mathewson
+/* tinytest.h -- Copyright 2009-2012 Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef _TINYTEST_H
-#define _TINYTEST_H
+#ifndef TINYTEST_H_INCLUDED_
+#define TINYTEST_H_INCLUDED_
 
 /** Flag for a test that needs to run in a subprocess. */
 #define TT_FORK  (1<<0)
 /** Runtime flag for a test we've decided to skip. */
 #define TT_SKIP  (1<<1)
 /** Internal runtime flag for a test we've decided to run. */
-#define _TT_ENABLED  (1<<2)
+#define TT_ENABLED_  (1<<2)
 /** If you add your own flags, make them start at this point. */
 #define TT_FIRST_USER_FLAG (1<<3)
 
@@ -65,18 +65,18 @@ struct testgroup_t {
 #define END_OF_GROUPS { NULL, NULL}
 
 /** Implementation: called from a test to indicate failure, before logging. */
-void _tinytest_set_test_failed(void);
+void tinytest_set_test_failed_(void);
 /** Implementation: called from a test to indicate that we're skipping. */
-void _tinytest_set_test_skipped(void);
+void tinytest_set_test_skipped_(void);
 /** Implementation: return 0 for quiet, 1 for normal, 2 for loud. */
-int _tinytest_get_verbosity(void);
+int tinytest_get_verbosity_(void);
 /** Implementation: Set a flag on tests matching a name; returns number
  * of tests that matched. */
-int _tinytest_set_flag(struct testgroup_t *, const char *, unsigned long);
+int tinytest_set_flag_(struct testgroup_t *, const char *, unsigned long);
 
 /** Set all tests in 'groups' matching the name 'named' to be skipped. */
 #define tinytest_skip(groups, named) \
-       _tinytest_set_flag(groups, named, TT_SKIP)
+       tinytest_set_flag_(groups, named, TT_SKIP)
 
 /** Run a single testcase in a single group. */
 int testcase_run_one(const struct testgroup_t *,const struct testcase_t *);
index 8838459bd6c019f53bd5d9073eda55b98b283f7e..be95ce4c1db57285d03ea8f707d092cb1f4e0f72 100644 (file)
@@ -1,4 +1,4 @@
-/* tinytest_demo.c -- Copyright 2009-2010 Nick Mathewson
+/* tinytest_demo.c -- Copyright 2009-2012 Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -39,7 +39,7 @@
 /* ============================================================ */
 
 /* First, let's see if strcmp is working.  (All your test cases should be
- * functions declared to take a single void * as) an argument. */
+ * functions declared to take a single void * as an argument.) */
 void
 test_strcmp(void *data)
 {
index 888b1159a91969da4f9e246c794db5fd737fdabc..87ec2fa67e76980406a383b81659fb109b5bf506 100644 (file)
@@ -1,10 +1,10 @@
 
+#include "util-internal.h"
 #ifdef _WIN32
 #include <winsock2.h>
 #endif
 
 #include "event2/util.h"
-#include "util-internal.h"
 
 #ifdef snprintf
 #undef snprintf
index 032393ccf762500228c6f9647e123cf8a7cec0fa..9ff69b1d506dab1f8d1ecc92517f8a4734754bd3 100644 (file)
@@ -1,4 +1,4 @@
-/* tinytest_macros.h -- Copyright 2009-2010 Nick Mathewson
+/* tinytest_macros.h -- Copyright 2009-2012 Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef _TINYTEST_MACROS_H
-#define _TINYTEST_MACROS_H
+#ifndef TINYTEST_MACROS_H_INCLUDED_
+#define TINYTEST_MACROS_H_INCLUDED_
 
 /* Helpers for defining statement-like macros */
 #define TT_STMT_BEGIN do {
 /* Announce a non-failure if we're verbose. */
 #define TT_BLATHER(args)                                               \
        TT_STMT_BEGIN                                                   \
-       if (_tinytest_get_verbosity()>1) TT_DECLARE("  OK", args);      \
+       if (tinytest_get_verbosity_()>1) TT_DECLARE("  OK", args);      \
        TT_STMT_END
 
 #define TT_DIE(args)                                           \
        TT_STMT_BEGIN                                           \
-       _tinytest_set_test_failed();                            \
+       tinytest_set_test_failed_();                            \
        TT_GRIPE(args);                                         \
        TT_EXIT_TEST_FUNCTION;                                  \
        TT_STMT_END
 
 #define TT_FAIL(args)                          \
        TT_STMT_BEGIN                                           \
-       _tinytest_set_test_failed();                            \
+       tinytest_set_test_failed_();                            \
        TT_GRIPE(args);                                         \
        TT_STMT_END
 
@@ -74,7 +74,7 @@
 #define tt_abort() TT_DIE(("%s", "(Failed.)"))
 
 /* Fail but do not abort the current test for the reason in msg. */
-#define tt_fail_printf(msg) TT_FAIL(msg)
+#define tt_failprint_f(msg) TT_FAIL(msg)
 #define tt_fail_perror(op) TT_FAIL(("%s: %s [%d]",(op),strerror(errno), errno))
 #define tt_fail_msg(msg) TT_FAIL(("%s", msg))
 #define tt_fail() TT_FAIL(("%s", "(Failed.)"))
 /* End the current test, and indicate we are skipping it. */
 #define tt_skip()                                              \
        TT_STMT_BEGIN                                           \
-       _tinytest_set_test_skipped();                           \
+       tinytest_set_test_skipped_();                           \
        TT_EXIT_TEST_FUNCTION;                                  \
        TT_STMT_END
 
-#define _tt_want(b, msg, fail)                         \
+#define tt_want_(b, msg, fail)                         \
        TT_STMT_BEGIN                                   \
        if (!(b)) {                                     \
-               _tinytest_set_test_failed();            \
+               tinytest_set_test_failed_();            \
                TT_GRIPE(("%s",msg));                   \
                fail;                                   \
        } else {                                        \
 
 /* Assert b, but do not stop the test if b fails.  Log msg on failure. */
 #define tt_want_msg(b, msg)                    \
-       _tt_want(b, msg, );
+       tt_want_(b, msg, );
 
 /* Assert b and stop the test if b fails.  Log msg on failure. */
 #define tt_assert_msg(b, msg)                  \
-       _tt_want(b, msg, TT_EXIT_TEST_FUNCTION);
+       tt_want_(b, msg, TT_EXIT_TEST_FUNCTION);
 
 /* Assert b, but do not stop the test if b fails. */
 #define tt_want(b)   tt_want_msg( (b), "want("#b")")
 #define tt_assert_test_fmt_type(a,b,str_test,type,test,printf_type,printf_fmt, \
     setup_block,cleanup_block,die_on_fail)                             \
        TT_STMT_BEGIN                                                   \
-       type _val1 = (type)(a);                                         \
-       type _val2 = (type)(b);                                         \
-       int _tt_status = (test);                                        \
-       if (!_tt_status || _tinytest_get_verbosity()>1) {               \
-               printf_type _print;                                     \
-               printf_type _print1;                                    \
-               printf_type _print2;                                    \
-               type _value = _val1;                                    \
+       type val1_ = (type)(a);                                         \
+       type val2_ = (type)(b);                                         \
+       int tt_status_ = (test);                                        \
+       if (!tt_status_ || tinytest_get_verbosity_()>1) {               \
+               printf_type print_;                                     \
+               printf_type print1_;                                    \
+               printf_type print2_;                                    \
+               type value_ = val1_;                                    \
                setup_block;                                            \
-               _print1 = _print;                                       \
-               _value = _val2;                                         \
+               print1_ = print_;                                       \
+               value_ = val2_;                                         \
                setup_block;                                            \
-               _print2 = _print;                                       \
-               TT_DECLARE(_tt_status?"  OK":"FAIL",                    \
+               print2_ = print_;                                       \
+               TT_DECLARE(tt_status_?"  OK":"FAIL",                    \
                           ("assert(%s): "printf_fmt" vs "printf_fmt,   \
-                           str_test, _print1, _print2));               \
-               _print = _print1;                                       \
+                           str_test, print1_, print2_));               \
+               print_ = print1_;                                       \
                cleanup_block;                                          \
-               _print = _print2;                                       \
+               print_ = print2_;                                       \
                cleanup_block;                                          \
-               if (!_tt_status) {                                      \
-                       _tinytest_set_test_failed();                    \
+               if (!tt_status_) {                                      \
+                       tinytest_set_test_failed_();                    \
                        die_on_fail ;                                   \
                }                                                       \
        }                                                               \
 
 #define tt_assert_test_type(a,b,str_test,type,test,fmt,die_on_fail)    \
        tt_assert_test_fmt_type(a,b,str_test,type,test,type,fmt,        \
-           {_print=_value;},{},die_on_fail)
+           {print_=value_;},{},die_on_fail)
 
 /* Helper: assert that a op b, when cast to type.  Format the values with
  * printf format fmt on failure. */
 #define tt_assert_op_type(a,op,b,type,fmt)                             \
-       tt_assert_test_type(a,b,#a" "#op" "#b,type,(_val1 op _val2),fmt, \
+       tt_assert_test_type(a,b,#a" "#op" "#b,type,(val1_ op val2_),fmt, \
            TT_EXIT_TEST_FUNCTION)
 
 #define tt_int_op(a,op,b)                      \
-       tt_assert_test_type(a,b,#a" "#op" "#b,long,(_val1 op _val2), \
+       tt_assert_test_type(a,b,#a" "#op" "#b,long,(val1_ op val2_), \
            "%ld",TT_EXIT_TEST_FUNCTION)
 
 #define tt_uint_op(a,op,b)                                             \
        tt_assert_test_type(a,b,#a" "#op" "#b,unsigned long,            \
-           (_val1 op _val2),"%lu",TT_EXIT_TEST_FUNCTION)
+           (val1_ op val2_),"%lu",TT_EXIT_TEST_FUNCTION)
 
 #define tt_ptr_op(a,op,b)                                              \
        tt_assert_test_type(a,b,#a" "#op" "#b,void*,                    \
-           (_val1 op _val2),"%p",TT_EXIT_TEST_FUNCTION)
+           (val1_ op val2_),"%p",TT_EXIT_TEST_FUNCTION)
 
 #define tt_str_op(a,op,b)                                              \
        tt_assert_test_type(a,b,#a" "#op" "#b,const char *,             \
-           (strcmp(_val1,_val2) op 0),"<%s>",TT_EXIT_TEST_FUNCTION)
+           (strcmp(val1_,val2_) op 0),"<%s>",TT_EXIT_TEST_FUNCTION)
 
 #define tt_want_int_op(a,op,b)                                         \
-       tt_assert_test_type(a,b,#a" "#op" "#b,long,(_val1 op _val2),"%ld",(void)0)
+       tt_assert_test_type(a,b,#a" "#op" "#b,long,(val1_ op val2_),"%ld",(void)0)
 
 #define tt_want_uint_op(a,op,b)                                                \
        tt_assert_test_type(a,b,#a" "#op" "#b,unsigned long,            \
-           (_val1 op _val2),"%lu",(void)0)
+           (val1_ op val2_),"%lu",(void)0)
 
 #define tt_want_ptr_op(a,op,b)                                         \
        tt_assert_test_type(a,b,#a" "#op" "#b,void*,                    \
-           (_val1 op _val2),"%p",(void)0)
+           (val1_ op val2_),"%p",(void)0)
 
 #define tt_want_str_op(a,op,b)                                         \
        tt_assert_test_type(a,b,#a" "#op" "#b,const char *,             \
-           (strcmp(_val1,_val2) op 0),"<%s>",(void)0)
+           (strcmp(val1_,val2_) op 0),"<%s>",(void)0)
 
 #endif
diff --git a/sntp/libevent/time-internal.h b/sntp/libevent/time-internal.h
new file mode 100644 (file)
index 0000000..daf20f4
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef TIME_INTERNAL_H_INCLUDED_
+#define TIME_INTERNAL_H_INCLUDED_
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_MACH_MACH_TIME_H
+/* For mach_timebase_info */
+#include <mach/mach_time.h>
+#endif
+
+#include <time.h>
+
+#include "event2/util.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(EVENT__HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
+#define HAVE_POSIX_MONOTONIC
+#elif defined(EVENT__HAVE_MACH_ABSOLUTE_TIME)
+#define HAVE_MACH_MONOTONIC
+#elif defined(_WIN32)
+#define HAVE_WIN32_MONOTONIC
+#else
+#define HAVE_FALLBACK_MONOTONIC
+#endif
+
+long evutil_tv_to_msec_(const struct timeval *tv);
+void evutil_usleep_(const struct timeval *tv);
+
+#ifdef _WIN32
+typedef ULONGLONG (WINAPI *ev_GetTickCount_func)(void);
+#endif
+
+struct evutil_monotonic_timer {
+
+#ifdef HAVE_MACH_MONOTONIC
+       struct mach_timebase_info mach_timebase_units;
+#endif
+
+#ifdef HAVE_POSIX_MONOTONIC
+       int monotonic_clock;
+#endif
+
+#ifdef HAVE_WIN32_MONOTONIC
+       ev_GetTickCount_func GetTickCount64_fn;
+       ev_GetTickCount_func GetTickCount_fn;
+       ev_uint64_t last_tick_count;
+       ev_uint64_t adjust_tick_count;
+
+       ev_uint64_t first_tick;
+       ev_uint64_t first_counter;
+       double usec_per_count;
+       int use_performance_counter;
+#endif
+
+       struct timeval adjust_monotonic_clock;
+       struct timeval last_time;
+};
+
+#define EV_MONOT_PRECISE  1
+#define EV_MONOT_FALLBACK 2
+
+int evutil_configure_monotonic_time_(struct evutil_monotonic_timer *mt,
+    int flags);
+int evutil_gettime_monotonic_(struct evutil_monotonic_timer *mt, struct timeval *tv);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT_INTERNAL_H_INCLUDED_ */
index 0ff1ce06ab368a148f92b1319cd1d951326481dc..98c816841a691a9ec3b1cd82cc7da565c6bb9fb9 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +23,8 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
-#ifndef _EVENT_UTIL_INTERNAL_H
-#define _EVENT_UTIL_INTERNAL_H
+#ifndef UTIL_INTERNAL_H_INCLUDED_
+#define UTIL_INTERNAL_H_INCLUDED_
 
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 #include "log-internal.h"
 #include <stdio.h>
 #include <stdlib.h>
-#ifdef _EVENT_HAVE_SYS_SOCKET_H
+#ifdef EVENT__HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
+#ifdef EVENT__HAVE_SYS_EVENTFD_H
+#include <sys/eventfd.h>
+#endif
 #include "event2/util.h"
 
+#include "time-internal.h"
 #include "ipv6-internal.h"
 
 #ifdef __cplusplus
@@ -47,21 +51,21 @@ extern "C" {
 #endif
 
 /* If we need magic to say "inline", get it for free internally. */
-#ifdef _EVENT_inline
-#define inline _EVENT_inline
+#ifdef EVENT__inline
+#define inline EVENT__inline
 #endif
-#ifdef _EVENT___func__
-#define __func__ _EVENT___func__
+#ifdef EVENT____func__
+#define __func__ EVENT____func__
 #endif
 
 /* A good no-op to use in macro definitions. */
-#define _EVUTIL_NIL_STMT ((void)0)
+#define EVUTIL_NIL_STMT_ ((void)0)
 /* A no-op that tricks the compiler into thinking a condition is used while
  * definitely not making any code for it.  Used to compile out asserts while
  * avoiding "unused variable" warnings.  The "!" forces the compiler to
  * do the sizeof() on an int, in case "condition" is a bitfield value.
  */
-#define _EVUTIL_NIL_CONDITION(condition) do { \
+#define EVUTIL_NIL_CONDITION_(condition) do { \
        (void)sizeof(!(condition));  \
 } while(0)
 
@@ -109,10 +113,6 @@ extern "C" {
 
 #endif
 
-#ifdef _EVENT_socklen_t
-#define socklen_t _EVENT_socklen_t
-#endif
-
 /* Arguments for shutdown() */
 #ifdef SHUT_RD
 #define EVUTIL_SHUT_RD SHUT_RD
@@ -130,20 +130,93 @@ extern "C" {
 #define EVUTIL_SHUT_BOTH 2
 #endif
 
+/* Helper: Verify that all the elements in 'dlist' are internally consistent.
+ * Checks for circular lists and bad prev/next pointers.
+ *
+ * Example usage:
+ *    EVUTIL_ASSERT_LIST_OK(eventlist, event, ev_next);
+ */
+#define EVUTIL_ASSERT_LIST_OK(dlist, type, field) do {                 \
+               struct type *elm1, *elm2, **nextp;                      \
+               if (LIST_EMPTY((dlist)))                                \
+                       break;                                          \
+                                                                       \
+               /* Check list for circularity using Floyd's */          \
+               /* 'Tortoise and Hare' algorithm */                     \
+               elm1 = LIST_FIRST((dlist));                             \
+               elm2 = LIST_NEXT(elm1, field);                          \
+               while (elm1 && elm2) {                                  \
+                       EVUTIL_ASSERT(elm1 != elm2);                    \
+                       elm1 = LIST_NEXT(elm1, field);                  \
+                       elm2 = LIST_NEXT(elm2, field);                  \
+                       if (!elm2)                                      \
+                               break;                                  \
+                       EVUTIL_ASSERT(elm1 != elm2);                    \
+                       elm2 = LIST_NEXT(elm2, field);                  \
+               }                                                       \
+                                                                       \
+               /* Now check next and prev pointers for consistency. */ \
+               nextp = &LIST_FIRST((dlist));                           \
+               elm1 = LIST_FIRST((dlist));                             \
+               while (elm1) {                                          \
+                       EVUTIL_ASSERT(*nextp == elm1);                  \
+                       EVUTIL_ASSERT(nextp == elm1->field.le_prev);    \
+                       nextp = &LIST_NEXT(elm1, field);                \
+                       elm1 = *nextp;                                  \
+               }                                                       \
+       } while (0)
+
+/* Helper: Verify that all the elements in a TAILQ are internally consistent.
+ * Checks for circular lists and bad prev/next pointers.
+ *
+ * Example usage:
+ *    EVUTIL_ASSERT_TAILQ_OK(activelist, event, ev_active_next);
+ */
+#define EVUTIL_ASSERT_TAILQ_OK(tailq, type, field) do {                        \
+               struct type *elm1, *elm2, **nextp;                      \
+               if (TAILQ_EMPTY((tailq)))                               \
+                       break;                                          \
+                                                                       \
+               /* Check list for circularity using Floyd's */          \
+               /* 'Tortoise and Hare' algorithm */                     \
+               elm1 = TAILQ_FIRST((tailq));                            \
+               elm2 = TAILQ_NEXT(elm1, field);                         \
+               while (elm1 && elm2) {                                  \
+                       EVUTIL_ASSERT(elm1 != elm2);                    \
+                       elm1 = TAILQ_NEXT(elm1, field);                 \
+                       elm2 = TAILQ_NEXT(elm2, field);                 \
+                       if (!elm2)                                      \
+                               break;                                  \
+                       EVUTIL_ASSERT(elm1 != elm2);                    \
+                       elm2 = TAILQ_NEXT(elm2, field);                 \
+               }                                                       \
+                                                                       \
+               /* Now check next and prev pointers for consistency. */ \
+               nextp = &TAILQ_FIRST((tailq));                          \
+               elm1 = TAILQ_FIRST((tailq));                            \
+               while (elm1) {                                          \
+                       EVUTIL_ASSERT(*nextp == elm1);                  \
+                       EVUTIL_ASSERT(nextp == elm1->field.tqe_prev);   \
+                       nextp = &TAILQ_NEXT(elm1, field);               \
+                       elm1 = *nextp;                                  \
+               }                                                       \
+               EVUTIL_ASSERT(nextp == (tailq)->tqh_last);              \
+       } while (0)
+
 /* Locale-independent replacements for some ctypes functions.  Use these
  * when you care about ASCII's notion of character types, because you are about
  * to send those types onto the wire.
  */
-int EVUTIL_ISALPHA(char c);
-int EVUTIL_ISALNUM(char c);
-int EVUTIL_ISSPACE(char c);
-int EVUTIL_ISDIGIT(char c);
-int EVUTIL_ISXDIGIT(char c);
-int EVUTIL_ISPRINT(char c);
-int EVUTIL_ISLOWER(char c);
-int EVUTIL_ISUPPER(char c);
-char EVUTIL_TOUPPER(char c);
-char EVUTIL_TOLOWER(char c);
+int EVUTIL_ISALPHA_(char c);
+int EVUTIL_ISALNUM_(char c);
+int EVUTIL_ISSPACE_(char c);
+int EVUTIL_ISDIGIT_(char c);
+int EVUTIL_ISXDIGIT_(char c);
+int EVUTIL_ISPRINT_(char c);
+int EVUTIL_ISLOWER_(char c);
+int EVUTIL_ISUPPER_(char c);
+char EVUTIL_TOUPPER_(char c);
+char EVUTIL_TOLOWER_(char c);
 
 /** Helper macro.  If we know that a given pointer points to a field in a
     structure, return a pointer to the structure itself.  Used to implement
@@ -163,21 +236,52 @@ char EVUTIL_TOLOWER(char c);
 #define EVUTIL_UPCAST(ptr, type, field)                                \
        ((type *)(((char*)(ptr)) - evutil_offsetof(type, field)))
 
-int evutil_read_file(const char *filename, char **content_out, size_t *len_out,
+/* As open(pathname, flags, mode), except that the file is always opened with
+ * the close-on-exec flag set. (And the mode argument is mandatory.)
+ */
+int evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode);
+
+int evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
     int is_binary);
 
-int evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen);
+int evutil_socket_connect_(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen);
 
-int evutil_socket_finished_connecting(evutil_socket_t fd);
+int evutil_socket_finished_connecting_(evutil_socket_t fd);
 
-int evutil_ersatz_socketpair(int, int , int, evutil_socket_t[]);
+int evutil_ersatz_socketpair_(int, int , int, evutil_socket_t[]);
 
-int evutil_resolve(int family, const char *hostname, struct sockaddr *sa,
+int evutil_resolve_(int family, const char *hostname, struct sockaddr *sa,
     ev_socklen_t *socklen, int port);
 
-const char *evutil_getenv(const char *name);
+const char *evutil_getenv_(const char *name);
+
+/* Structure to hold the state of our weak random number generator.
+ */
+struct evutil_weakrand_state {
+       ev_uint32_t seed;
+};
 
-long _evutil_weakrand(void);
+#define EVUTIL_WEAKRAND_MAX EV_INT32_MAX
+
+/* Initialize the state of a week random number generator based on 'seed'.  If
+ * the seed is 0, construct a new seed based on not-very-strong platform
+ * entropy, like the PID and the time of day.
+ *
+ * This function, and the other evutil_weakrand* functions, are meant for
+ * speed, not security or statistical strength.  If you need a RNG which an
+ * attacker can't predict, or which passes strong statistical tests, use the
+ * evutil_secure_rng* functions instead.
+ */
+ev_uint32_t evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed);
+/* Return a pseudorandom value between 0 and EVUTIL_WEAKRAND_MAX inclusive.
+ * Updates the state in 'seed' as needed -- this value must be protected by a
+ * lock.
+ */
+ev_int32_t evutil_weakrand_(struct evutil_weakrand_state *seed);
+/* Return a pseudorandom value x such that 0 <= x < top. top must be no more
+ * than EVUTIL_WEAKRAND_MAX. Updates the state in 'seed' as needed -- this
+ * value must be proteced by a lock */
+ev_int32_t evutil_weakrand_range_(struct evutil_weakrand_state *seed, ev_int32_t top);
 
 /* Evaluates to the same boolean value as 'p', and hints to the compiler that
  * we expect this value to be false. */
@@ -189,13 +293,13 @@ long _evutil_weakrand(void);
 
 /* Replacement for assert() that calls event_errx on failure. */
 #ifdef NDEBUG
-#define EVUTIL_ASSERT(cond) _EVUTIL_NIL_CONDITION(cond)
+#define EVUTIL_ASSERT(cond) EVUTIL_NIL_CONDITION_(cond)
 #define EVUTIL_FAILURE_CHECK(cond) 0
 #else
 #define EVUTIL_ASSERT(cond)                                            \
        do {                                                            \
                if (EVUTIL_UNLIKELY(!(cond))) {                         \
-                       event_errx(_EVENT_ERR_ABORT,                    \
+                       event_errx(EVENT_ERR_ABORT_,                    \
                            "%s:%d: Assertion %s failed in %s",         \
                            __FILE__,__LINE__,#cond,__func__);          \
                        /* In case a user-supplied handler tries to */  \
@@ -209,7 +313,7 @@ long _evutil_weakrand(void);
 #define EVUTIL_FAILURE_CHECK(cond) EVUTIL_UNLIKELY(cond)
 #endif
 
-#ifndef _EVENT_HAVE_STRUCT_SOCKADDR_STORAGE
+#ifndef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE
 /* Replacement for sockaddr storage that we can use internally on platforms
  * that lack it.  It is not space-efficient, but neither is sockaddr_storage.
  */
@@ -225,7 +329,7 @@ struct sockaddr_storage {
 #endif
 
 /* Internal addrinfo error code.  This one is returned from only from
- * evutil_getaddrinfo_common, when we are sure that we'll have to hit a DNS
+ * evutil_getaddrinfo_common_, when we are sure that we'll have to hit a DNS
  * server. */
 #define EVUTIL_EAI_NEED_RESOLVE      -90002
 
@@ -237,24 +341,24 @@ typedef struct evdns_getaddrinfo_request* (*evdns_getaddrinfo_fn)(
     const struct evutil_addrinfo *hints_in,
     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
 
-void evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn);
+void evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn);
 
-struct evutil_addrinfo *evutil_new_addrinfo(struct sockaddr *sa,
+struct evutil_addrinfo *evutil_new_addrinfo_(struct sockaddr *sa,
     ev_socklen_t socklen, const struct evutil_addrinfo *hints);
-struct evutil_addrinfo *evutil_addrinfo_append(struct evutil_addrinfo *first,
+struct evutil_addrinfo *evutil_addrinfo_append_(struct evutil_addrinfo *first,
     struct evutil_addrinfo *append);
-void evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints);
-int evutil_getaddrinfo_common(const char *nodename, const char *servname,
+void evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints);
+int evutil_getaddrinfo_common_(const char *nodename, const char *servname,
     struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum);
 
-int evutil_getaddrinfo_async(struct evdns_base *dns_base,
+int evutil_getaddrinfo_async_(struct evdns_base *dns_base,
     const char *nodename, const char *servname,
     const struct evutil_addrinfo *hints_in,
     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
 
 /** Return true iff sa is a looback address. (That is, it is 127.0.0.1/8, or
  * ::1). */
-int evutil_sockaddr_is_loopback(const struct sockaddr *sa);
+int evutil_sockaddr_is_loopback_(const struct sockaddr *sa);
 
 
 /**
@@ -262,14 +366,16 @@ int evutil_sockaddr_is_loopback(const struct sockaddr *sa);
     Returns a pointer to out.  Always writes something into out, so it's safe
     to use the output of this function without checking it for NULL.
  */
-const char *evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen);
+const char *evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen);
+
+int evutil_hex_char_to_int_(char c);
 
-long evutil_tv_to_msec(const struct timeval *tv);
 
-int evutil_hex_char_to_int(char c);
+void evutil_free_secure_rng_globals_(void);
+void evutil_free_globals_(void);
 
 #ifdef _WIN32
-HANDLE evutil_load_windows_system_library(const TCHAR *library_name);
+HANDLE evutil_load_windows_system_library_(const TCHAR *library_name);
 #endif
 
 #ifndef EV_SIZE_FMT
@@ -296,7 +402,7 @@ HANDLE evutil_load_windows_system_library(const TCHAR *library_name);
 #endif
 
 #ifndef EV_SIZE_FMT
-#if (_EVENT_SIZEOF_SIZE_T <= _EVENT_SIZEOF_LONG)
+#if (EVENT__SIZEOF_SIZE_T <= EVENT__SIZEOF_LONG)
 #define EV_SIZE_FMT "%lu"
 #define EV_SSIZE_FMT "%ld"
 #define EV_SIZE_ARG(x) ((unsigned long)(x))
@@ -309,6 +415,34 @@ HANDLE evutil_load_windows_system_library(const TCHAR *library_name);
 #endif
 #endif
 
+evutil_socket_t evutil_socket_(int domain, int type, int protocol);
+evutil_socket_t evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
+    ev_socklen_t *addrlen, int flags);
+int evutil_make_internal_pipe_(evutil_socket_t fd[2]);
+evutil_socket_t evutil_eventfd_(unsigned initval, int flags);
+
+#ifdef SOCK_NONBLOCK
+#define EVUTIL_SOCK_NONBLOCK SOCK_NONBLOCK
+#else
+#define EVUTIL_SOCK_NONBLOCK 0x4000000
+#endif
+#ifdef SOCK_CLOEXEC
+#define EVUTIL_SOCK_CLOEXEC SOCK_CLOEXEC
+#else
+#define EVUTIL_SOCK_CLOEXEC 0x80000000
+#endif
+#ifdef EFD_NONBLOCK
+#define EVUTIL_EFD_NONBLOCK EFD_NONBLOCK
+#else
+#define EVUTIL_EFD_NONBLOCK 0x4000
+#endif
+#ifdef EFD_CLOEXEC
+#define EVUTIL_EFD_CLOEXEC EFD_CLOEXEC
+#else
+#define EVUTIL_EFD_CLOEXEC 0x8000
+#endif
+
+
 #ifdef __cplusplus
 }
 #endif
index 5ad6b979bc5a16342006c062bf25dd0c816c66c7..be0c71bc217eba9dabeccc4f0944bfb241430726 100644 (file)
@@ -24,7 +24,7 @@ What's New In Libevent 2.0 so far:
 
   COMPATIBILITY:
 
-  Nearly all existing code that worked with should Libevent 1.4 should still
+  Nearly all existing code that worked with Libevent 1.4 should still
   work correctly with Libevent 2.0.  However, if you are writing new code,
   or if you want to port old code, we strongly recommend using the new APIs
   and avoiding deprecated APIs as much as possible.
diff --git a/sntp/libevent/whatsnew-2.1.txt b/sntp/libevent/whatsnew-2.1.txt
new file mode 100644 (file)
index 0000000..d02c518
--- /dev/null
@@ -0,0 +1,390 @@
+                         What's new in Libevent 2.1
+                             Nick Mathewson
+
+0. Before we start
+
+0.1. About this document
+
+  This document describes the key differences between Libevent 2.0 and
+  Libevent 2.1, from a user's point of view.  It's a work in progress.
+
+  For better documentation about libevent, see the links at
+  http://libevent.org/
+
+  Libevent 2.1 would not be possible without the generous help of
+  numerous volunteers.  For a list of who did what in Libevent 2.1,
+  please see the ChangeLog!
+
+  NOTE: I am very sure that I missed some thing on this list.  Caveat
+  haxxor.
+
+0.2. Where to get help
+
+  Try looking at the other documentation too.  All of the header files
+  have documentation in the doxygen format; this gets turned into nice
+  HTML and linked to from the libevent.org website.
+
+  There is a work-in-progress book with reference manual at
+  http://www.wangafu.net/~nickm/libevent-book/ .
+
+  You can ask questions on the #libevent IRC channel at irc.oftc.net or
+  on the mailing list at libevent-users@freehaven.net.  The mailing list
+  is subscribers-only, so you will need to subscribe before you post.
+
+0.3. Compatibility
+
+  Our source-compatibility policy is that correct code (that is to say,
+  code that uses public interfaces of Libevent and relies only on their
+  documented behavior) should have forward source compatibility: any
+  such code that worked with a previous version of Libevent should work
+  with this version too.
+
+  We don't try to do binary compatibility except within stable release
+  series, so binaries linked against any version of Libevent 2.0 will
+  probably need to be recompiled against Libevent 2.1.1-alpha if you
+  want to use it.  It is probable that we'll break binary compatibility
+  again before Libevent 2.1 is stable.
+
+1. New APIs and features
+
+1.1. New ways to build libevent
+
+  We now provide an --enable-gcc-hardening configure option to turn on
+  GCC features designed for increased code security.
+
+  There is also an --enable-silent-rules configure option to make
+  compilation run more quietly with automake 1.11 or later.
+
+  You no longer need to use the --enable-gcc-warnings option to turn on
+  all of the GCC warnings that Libevent uses.  The only change from
+  using that option now is to turn warnings into errors.
+
+  For IDE users, files that are not supposed to be built are now
+  surrounded with appropriate #ifdef lines to keep your IDE from getting
+  upset.
+
+
+1.2. New functions for events and the event loop
+
+  If you're running Libevent with multiple event priorities, you might
+  want to make sure that Libevent checks for new events frequently, so
+  that time-consuming or numerous low-priority events don't keep it from
+  checking for new high-priority events.  You can now use the
+  event_config_set_max_dispatch_interval() interface to ensure that the
+  loop checks for new events either every N microseconds, every M
+  callbacks, or both.
+
+  There is an EVLOOP_NO_EXIT_ON_EMPTY flag that tells event_base_loop()
+  to keep looping even when there are no pending events.  (Ordinarily,
+  event_base_loop() will exit as soon as no events are pending.)
+
+  Past versions of Libevent have been annoying to use with some
+  memory-leak-checking tools, because Libevent allocated some global
+  singletons but provided no means to free them.  There is now a
+  function, libevent_global_shutdown(), that you can use to free all
+  globally held resources before exiting, so that your leak-check tools
+  don't complain.  (Note: this function doesn't free non-global things
+  like events, bufferevents, and so on; and it doesn't free anything
+  that wouldn't otherwise get cleaned up by the operating system when
+  your process exit()s.  If you aren't using a leak-checking tool, there
+  is not much reason to call libevent_global_shutdown().)
+
+  There is a new event_base_get_npriorities() function to return the
+  number of priorities set in the event base.
+
+  Libevent 2.0 added an event_new() function to construct a new struct
+  event on the heap.  Unfortunately, with event_new(), there was no
+  equivalent for:
+
+         struct event ev;
+         event_assign(&ev, base, fd, EV_READ, callback, &ev);
+
+  In other words, there was no easy way for event_new() to set up an
+  event so that the event itself would be its callback argument.
+  Libevent 2.1 lets you do this by passing "event_self_cbarg()" as the
+  callback argument:
+
+         struct event *evp;
+         evp = event_new(base, fd, EV_READ, callback,
+         event_self_cbarg());
+
+  There's also a new event_base_get_running_event() function you can
+  call from within a Libevent callback to get a pointer to the current
+  event.  This should never be strictly necessary, but it's sometimes
+  convenient.
+
+1.3. New debugging features
+
+  You can now turn on debug logs at runtime using a new function,
+  event_enable_debug_logging().
+
+  There's also been some work done to try to make the debugging logs
+  more generally useful.
+
+1.4. New evbuffer functions
+
+  In Libevent 2.0, we introduced evbuffer_add_file() to add an entire
+  file's contents to an evbuffer, and then send them using sendfile() or
+  mmap() as appropriate.  This API had some drawbacks, however.
+  Notably, it created one mapping or fd for every instance of the same
+  file added to any evbuffer.  Also, adding a file to an evbuffer could
+  make that buffer unusable with SSL bufferevents, filtering
+  bufferevents, and any code that tried to read the contents of the
+  evbuffer.
+
+  Libevent 2.1 adds a new evbuffer_file_segment API to solve these
+  problems.  Now, you can use evbuffer_file_segment_new() to construct a
+  file-segment object, and evbuffer_add_file_segment() to insert it (or
+  part of it) into an evbuffer.  These segments avoid creating redundant
+  maps or fds.  Better still, the code is smart enough (when the OS
+  supports sendfile) to map the file when that's necessary, and use
+  sendfile() otherwise.
+
+  The evbuffer_ptr interface has been extended so that an evbuffer_ptr
+  can now yield a point just after the end of the buffer.  This makes
+  many algorithms simpler to implement.
+
+  There's a new evbuffer_add_buffer() interface that you can use to add
+  one buffer to another nondestructively.  When you say
+  evbuffer_add_buffer_reference(outbuf, inbuf), outbuf now contains a
+  reference to the contents of inbuf.
+
+  To aid in adding data in bulk while minimizing evbuffer calls, there
+  is an evbuffer_add_iovec() function.
+
+  There's a new evbuffer_copyout_from() variant function to enable
+  copying data nondestructively from the middle of a buffer.
+
+  evbuffer_readln() now supports an EVBUFFER_EOL_NUL argument to fetch
+  NUL-terminated strings from buffers.
+
+1.5. New functions and features: bufferevents
+
+  You can now use the bufferevent_getcb() function to find out a
+  bufferevent's callbacks.  Previously, there was no supported way to do
+  that.
+
+  The largest chunk readable or writeable in a single bufferevent
+  callback is no longer hardcoded; it's now configurable with
+  the new functions bufferevent_set_max_single_read() and
+  bufferevent_set_max_single_write().
+
+  For consistency, OpenSSL bufferevents now make sure to always set one
+  of BEV_EVENT_READING or BEV_EVENT_WRITING when invoking an event callback.
+
+1.6. New functions and features: evdns
+
+  The previous evdns interface used an "open a test UDP socket" trick in
+  order to detect IPv6 support.  This was a hack, since it would
+  sometimes badly confuse people's firewall software, even though no
+  packets were sent.  The current evdns interface-detection code uses
+  the appropriate OS functions to see which interfaces are configured.
+
+1.7. New functions and features: evconnlistener
+
+  Libevent 2.1 adds the following evconnlistener flags:
+
+    LEV_OPT_DEFERRED_ACCEPT -- Tells the OS that it doesn't need to
+    report sockets as having arrived until the initiator has sent some
+    data too.  This can greatly improve performance with protocols like
+    HTTP where the client always speaks first.  On operating systems
+    that don't support this functionality, this option has no effect.
+
+    LEV_OPT_DISABLED -- Creates an evconnlistener in the disabled (not
+    listening) state.
+
+  Libevent 2.1 changes the behavior of the LEV_OPT_CLOSE_ON_EXEC
+  flag.  Previously, it would apply to the listener sockets, but not to
+  the accepted sockets themselves.  That's almost never what you want.
+  Now, it applies both to the listener and the accepted sockets.
+
+1.8. New functions and features: evhttp
+
+  **********************************************************************
+  NOTE: The evhttp module will eventually be deprecated in favor of Mark
+  Ellzey's libevhtp library.  Don't worry -- this won't happen until
+  libevhtp provides every feature that evhttp does, and provides a
+  compatible interface that applications can use to migrate.
+  **********************************************************************
+
+  Previously, you could only set evhttp timeouts in increments of one
+  second.  Now, you can use evhttp_set_timeout_tv() and
+  evhttp_connection_set_timeout_tv() to configure
+  microsecond-granularity timeouts.
+
+  There are a new pair of functions: evhttp_set_bevcb() and
+  evhttp_connection_base_bufferevent_new(), that you can use to
+  configure which bufferevents will be used for incoming and outgoing
+  http connections respectively.  These functions, combined with SSL
+  bufferevents, should enable HTTPS support.
+
+  There's a new evhttp_foreach_bound_socket() function to iterate over
+  every listener on an evhttp object.
+
+2. Cross-platform performance improvements
+
+2.1. Better data structures
+
+  We replaced several users of the sys/queue.h "TAILQ" data structure
+  with the "LIST" data structure.  Because this data type doesn't
+  require FIFO access, it requires fewer pointer checks and
+  manipulations to keep it in line.
+
+  All previous versions of Libevent have kept every pending (added)
+  event in an "eventqueue" data structure.  Starting in Libevent 2.0,
+  however, this structure became redundant: every pending timeout event
+  is stored in the timeout heap or in one of the common_timeout queues,
+  and every pending fd or signal event is stored in an evmap.  Libevent
+  2.1 removes this data structure, and thereby saves all of the code
+  that we'd been using to keep it updated.
+
+2.2. Faster activations and timeouts
+
+  It's a common pattern in older code to use event_base_once() with a
+  0-second timeout to ensure that a callback will get run 'as soon as
+  possible' in the current iteration of the Libevent loop.  We optimize
+  this case by calling event_active() directly, and bypassing the
+  timeout pool.  (People who are using this pattern should also consider
+  using event_active() themselves.)
+
+  Libevent 2.0 would wake up a polling event loop whenever the first
+  timeout in the event loop was adjusted--whether it had become earlier
+  or later.  We now only notify the event loop when a change causes the
+  expiration time to become _sooner_ than it would have been otherwise.
+
+  The timeout heap code is now optimized to perform fewer comparisons
+  and shifts when changing or removing a timeout.
+
+  Instead of checking for a wall-clock time jump every time we call
+  clock_gettime(), we now check only every 5 seconds.  This should save
+  a huge number of gettimeofday() calls.
+
+2.3. Microoptimizations
+
+  Internal event list maintainance no longer use the antipattern where
+  we have one function with multiple totally independent behaviors
+  depending on an argument:
+      #define OP1 1
+      #define OP2 2
+      #define OP3 3
+      void func(int operation, struct event *ev) {
+        switch (op) {
+          ...
+        }
+      }
+  Instead, these functions are now split into separate functions for
+  each operation:
+      void func_op1(struct event *ev) { ... }
+      void func_op2(struct event *ev) { ... }
+      void func_op3(struct event *ev) { ... }
+
+  This produces better code generation and inlining decisions on some
+  compilers, and makes the code easier to read and check.
+
+2.4. Evbuffer performance improvements
+
+  The EVBUFFER_EOL_CRLF line-ending type is now much faster, thanks to
+  smart optimizations.
+
+2.5. HTTP performance improvements
+
+   o Performance tweak to evhttp_parse_request_line. (aee1a97 Mark Ellzey)
+   o Add missing break to evhttp_parse_request_line (0fcc536)
+
+
+3. Backend/OS-specific improvements
+
+3.1. Linux-specific improvements
+
+  The logic for deciding which arguements to use with epoll_ctl() is now
+  a table-driven lookup, rather than the previous pile of cascading
+  branches.  This should minimize epoll_ctl() calls and make the epoll
+  code run a little faster on change-heavy loads.
+
+  Libevent now takes advantage of Linux's support for enhanced APIs
+  (e.g., SOCK_CLOEXEC, SOCK_NONBLOCK, accept4, pipe2) that allow us to
+  simultaneously create a socket, make it nonblocking, and make it
+  close-on-exec.  This should save syscalls throughout our codebase, and
+  avoid race-conditions if an exec() occurs after a socket is socket is
+  created but before we can make it close-on-execute on it.
+
+3.2. Windows-specific improvements
+
+  We now use GetSystemTimeAsFileTime to implement gettimeofday.  It's
+  significantly faster and more accurate than our old ftime()-based approach.
+
+3.3. Improvements in the solaris evport backend.
+
+  The evport backend has been updated to use many of the infrastructure
+  improvements from Libevent 2.0.  Notably, it keeps track of per-fd
+  information using the evmap infrastructure, and removes a number of
+  linear scans over recently-added events.  This last change makes it
+  efficient to receive many more events per evport_getn() call, thereby
+  reducing evport overhead in general.
+
+3.4. OSX backend improvements
+
+  The OSX select backend doesn't like to have more than a certain number
+  of fds set unless an "unlimited select" option has been set.
+  Therefore, we now set it.
+
+4. Infrastructure improvements
+
+4.1. Faster tests
+
+  I've spent some time to try to make the unit tests run faster in
+  Libevent 2.1.  Nearly all of this was a matter of searching slow tests
+  for unreasonably long timeouts, and cutting them down to reasonably
+  long delays, though on one or two cases I actually had to parallelize
+  an operation or improve an algorithm.
+
+  On my desktop, a full "make verify" run of Libevent 2.0.18-stable
+  requires about 218 seconds.  Libevent 2.1.1-alpha cuts this down to
+  about 78 seconds.
+
+  Faster unit tests are great, since they let programmers test their
+  changes without losing their train of thought.
+
+4.2. Portability
+
+  Libevent now uses large-file support internally on platforms where it
+  matters.  You shouldn't need to set _LARGEFILE or OFFSET_BITS or
+  anything magic before including the Libevent headers, either, since
+  Libevent now sets the size of ev_off_t to the size of off_t that it
+  received at compile time, not to some (possibly different) size based
+  on current macro definitions when your program is building.
+
+  We now also use the Autoconf AC_USE_SYSTEM_EXTENSIONS mechanism to
+  enable per-system macros needed to enable not-on-by-default features.
+  Unlike the rest of the autoconf macros, we output these to an
+  internal-use-only evconfig-private.h header, since their names need to
+  survive unmangled.  This lets us build correctly on more platforms,
+  and avoid inconsistencies when some files define _GNU_SOURCE and
+  others don't.
+
+  Libevent now tries to detect OpenSSL via pkg-config.
+
+4.3. Standards conformance
+
+  Previous Libevent versions had no consistent convention for internal
+  vs external identifiers, and used identifiers starting with the "_"
+  character throughout the codebase.  That's no good, since the C
+  standard says that identifiers beginning with _ are reserved.  I'm not
+  aware of having any collisions with system identifiers, but it's best
+  to fix these things before they cause trouble.
+
+  We now avoid all use of the _identifiers in the Libevent source code.
+  These changes were made *mainly* through the use of automated scripts,
+  so there shouldn't be any mistakes, but you never know.
+
+  As an exception, the names _EVENT_LOG_DEBUG, _EVENT_LOG_MSG_,
+  _EVENT_LOG_WARN, and _EVENT_LOG_ERR are still exposed in event.h: they
+  are now deprecated, but to support older code, they will need to stay
+  around for a while.  New code should use EVENT_LOG_DEBUG,
+  EVENT_LOG_MSG, EVENT_LOG_WARN, and EVENT_LOG_ERR instead.
+
+5. Testing
+
+  Libevent's test coverage level is more or less unchanged sine before:
+  we still have over 80% line coverage in our tests on Linux and OSX.
+  There are some under-tested modules, though: we need to fix those.
index d1f121bf1d3be2821e5a318c0a8189bafb546242..2c407e4a09bab94056e1e8b36413bb68933ff8fd 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2010 Niels Provos and Nick Mathewson
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
  * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
  * Copyright 2003 Michael A. Davis <mike@datanerds.net>
  *
@@ -28,6 +28,8 @@
 #include "event2/event-config.h"
 #include "evconfig-private.h"
 
+#ifdef _WIN32
+
 #include <winsock2.h>
 #include <windows.h>
 #include <sys/types.h>
@@ -47,6 +49,7 @@
 #include "evmap-internal.h"
 #include "event2/thread.h"
 #include "evthread-internal.h"
+#include "time-internal.h"
 
 #define XFREE(ptr) do { if (ptr) mm_free(ptr); } while (0)
 
@@ -78,8 +81,8 @@ struct win32op {
 };
 
 static void *win32_init(struct event_base *);
-static int win32_add(struct event_base *, evutil_socket_t, short old, short events, void *_idx);
-static int win32_del(struct event_base *, evutil_socket_t, short old, short events, void *_idx);
+static int win32_add(struct event_base *, evutil_socket_t, short old, short events, void *idx_);
+static int win32_del(struct event_base *, evutil_socket_t, short old, short events, void *idx_);
 static int win32_dispatch(struct event_base *base, struct timeval *);
 static void win32_dealloc(struct event_base *);
 
@@ -161,7 +164,7 @@ do_fd_clear(struct event_base *base,
                SOCKET s2;
                s2 = set->fd_array[i] = set->fd_array[set->fd_count];
 
-               ent2 = evmap_io_get_fdinfo(&base->io, s2);
+               ent2 = evmap_io_get_fdinfo_(&base->io, s2);
 
                if (!ent2) /* This indicates a bug. */
                        return (0);
@@ -175,7 +178,7 @@ do_fd_clear(struct event_base *base,
 
 #define NEVENT 32
 void *
-win32_init(struct event_base *_base)
+win32_init(struct event_base *base)
 {
        struct win32op *winop;
        size_t size;
@@ -197,9 +200,11 @@ win32_init(struct event_base *_base)
        winop->readset_out->fd_count = winop->writeset_out->fd_count
                = winop->exset_out->fd_count = 0;
 
-       if (evsig_init(_base) < 0)
+       if (evsig_init_(base) < 0)
                winop->signals_are_broken = 1;
 
+       evutil_weakrand_seed_(&base->weakrand_seed, 0);
+
        return (winop);
  err:
        XFREE(winop->readset_in);
@@ -213,10 +218,10 @@ win32_init(struct event_base *_base)
 
 int
 win32_add(struct event_base *base, evutil_socket_t fd,
-                        short old, short events, void *_idx)
+                        short old, short events, void *idx_)
 {
        struct win32op *win32op = base->evbase;
-       struct idx_info *idx = _idx;
+       struct idx_info *idx = idx_;
 
        if ((events & EV_SIGNAL) && win32op->signals_are_broken)
                return (-1);
@@ -238,10 +243,10 @@ win32_add(struct event_base *base, evutil_socket_t fd,
 
 int
 win32_del(struct event_base *base, evutil_socket_t fd, short old, short events,
-                 void *_idx)
+                 void *idx_)
 {
        struct win32op *win32op = base->evbase;
-       struct idx_info *idx = _idx;
+       struct idx_info *idx = idx_;
 
        event_debug(("%s: Removing event for %d", __func__, fd));
        if (events & EV_READ)
@@ -299,7 +304,7 @@ win32_dispatch(struct event_base *base, struct timeval *tv)
            win32op->readset_out->fd_count : win32op->writeset_out->fd_count;
 
        if (!fd_count) {
-               long msec = evutil_tv_to_msec(tv);
+               long msec = evutil_tv_to_msec_(tv);
                /* Sleep's DWORD argument is unsigned long */
                if (msec < 0)
                        msec = LONG_MAX;
@@ -324,42 +329,45 @@ win32_dispatch(struct event_base *base, struct timeval *tv)
        }
 
        if (win32op->readset_out->fd_count) {
-               i = rand() % win32op->readset_out->fd_count;
+               i = evutil_weakrand_range_(&base->weakrand_seed,
+                   win32op->readset_out->fd_count);
                for (j=0; j<win32op->readset_out->fd_count; ++j) {
                        if (++i >= win32op->readset_out->fd_count)
                                i = 0;
                        s = win32op->readset_out->fd_array[i];
-                       evmap_io_active(base, s, EV_READ);
+                       evmap_io_active_(base, s, EV_READ);
                }
        }
        if (win32op->exset_out->fd_count) {
-               i = rand() % win32op->exset_out->fd_count;
+               i = evutil_weakrand_range_(&base->weakrand_seed,
+                   win32op->exset_out->fd_count);
                for (j=0; j<win32op->exset_out->fd_count; ++j) {
                        if (++i >= win32op->exset_out->fd_count)
                                i = 0;
                        s = win32op->exset_out->fd_array[i];
-                       evmap_io_active(base, s, EV_WRITE);
+                       evmap_io_active_(base, s, EV_WRITE);
                }
        }
        if (win32op->writeset_out->fd_count) {
                SOCKET s;
-               i = rand() % win32op->writeset_out->fd_count;
+               i = evutil_weakrand_range_(&base->weakrand_seed,
+                   win32op->writeset_out->fd_count);
                for (j=0; j<win32op->writeset_out->fd_count; ++j) {
                        if (++i >= win32op->writeset_out->fd_count)
                                i = 0;
                        s = win32op->writeset_out->fd_array[i];
-                       evmap_io_active(base, s, EV_WRITE);
+                       evmap_io_active_(base, s, EV_WRITE);
                }
        }
        return (0);
 }
 
 void
-win32_dealloc(struct event_base *_base)
+win32_dealloc(struct event_base *base)
 {
-       struct win32op *win32op = _base->evbase;
+       struct win32op *win32op = base->evbase;
 
-       evsig_dealloc(_base);
+       evsig_dealloc_(base);
        if (win32op->readset_in)
                mm_free(win32op->readset_in);
        if (win32op->writeset_in)
@@ -375,3 +383,5 @@ win32_dealloc(struct event_base *_base)
        memset(win32op, 0, sizeof(win32op));
        mm_free(win32op);
 }
+
+#endif