Import Upstream version 1.4.0

This commit is contained in:
zhouganqing 2022-11-25 16:30:36 +08:00
commit f13deaa139
1097 changed files with 445988 additions and 0 deletions

49
.coveragerc Normal file
View File

@ -0,0 +1,49 @@
[run]
# In coverage 4.0b3, concurrency=gevent is exactly equivalent to
# concurrency=greenlet, except it causes coverage itself to import
# gevent. That messes up our coverage numbers for top-level
# statements, so we use greenlet instead. See https://github.com/gevent/gevent/pull/655#issuecomment-141198002
# See also .coveragerc-pypy
concurrency = greenlet
parallel = True
source = gevent
omit =
# This is for <= 2.7.8, which we don't test
src/gevent/_ssl2.py
src/gevent/libev/_corecffi_build.py
src/gevent/libuv/_corecffi_build.py
src/gevent/win32util.py
# having concurrency=greenlet means that the Queue class
# which is used from multiple real threads doesn't
# properly get covered.
src/gevent/_threading.py
# local.so sometimes gets included, and it can't be parsed
# as source, so it fails the whole process.
*.so
src/gevent/libev/*.so
src/gevent/libuv/*.so
src/gevent/resolver/*.so
[report]
# Coverage is run on Linux under cPython 2/3 and pypy
exclude_lines =
pragma: no cover
def __repr__
raise AssertionError
raise NotImplementedError
except ImportError:
if __name__ == .__main__.:
if sys.platform == 'win32':
if mswindows:
if is_windows:
if WIN:
self.fail
omit =
# local.so sometimes gets included, and it can't be parsed
# as source, so it fails the whole process.
# coverage 4.5 needs this specified here, 4.4.2 needed it in [run]
*.so
/tmp/test_*
# Third-party vendored code
src/gevent/_tblib.py

35
.coveragerc-pypy Normal file
View File

@ -0,0 +1,35 @@
[run]
# This is just like .coveragerc, but
# used for PyPy running. pypy doesn't support concurrency=greenlet
parallel = True
source = gevent
omit =
# This is for <= 2.7.8, which we don't test
src/gevent/_ssl2.py
src/gevent/libev/_corecffi_build.py
src/gevent/libuv/_corecffi_build.py
src/gevent/win32util.py
# having concurrency=greenlet means that the Queue class
# which is used from multiple real threads doesn't
# properly get covered.
src/gevent/_threading.py
test_*
# local.so sometimes gets included, and it can't be parsed
# as source, so it fails the whole process.
*.so
[report]
# Coverage is run on Linux under cPython 2/3 and pypy, so
# exclude branches that are windows specific or pypy
# specific
exclude_lines =
pragma: no cover
def __repr__
raise AssertionError
raise NotImplementedError
except ImportError:
if __name__ == .__main__.:
if sys.platform == 'win32':
if mswindows:
if is_windows:

20
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,20 @@
* gevent version:
* Python version: Please be as specific as possible: "cPython 2.7.9 downloaded from python.org"
* Operating System: Please be as specific as possible: "Raspbian (Debian Linux 8.0 Linux 4.9.35-v7+ armv7l)"
### Description:
**REPLACE ME**: What are you trying to get done, what has happened, what went wrong, and what did you expect?
```
Remember to put tracebacks in literal blocks
```
### What I've run:
**REPLACE ME**: Paste short, self contained, correct example code (sscce.org), tracebacks, etc, here
```python
"Put python code in python blocks"
```

98
.gitignore vendored Normal file
View File

@ -0,0 +1,98 @@
*.py[cod]
build/
.runtimes
.tox/
*.so
*.o
*.egg-info
gevent.*.[ch]
src/gevent/__pycache__
src/gevent/_semaphore.c
src/gevent/local.c
src/gevent/greenlet.c
src/gevent/_ident.c
src/gevent/_imap.c
src/gevent/event.c
src/gevent/_hub_local.c
src/gevent/_waiter.c
src/gevent/_tracer.c
src/gevent/queue.c
src/gevent/_hub_primitives.c
src/gevent/_greenlet_primitives.c
src/gevent/_abstract_linkable.c
src/gevent/libev/corecext.c
src/gevent/libev/corecext.h
src/gevent/libev/_corecffi.c
src/gevent/libev/_corecffi.o
src/gevent/resolver/cares.c
# Cython annotations
src/gevent/*.html
src/gevent/libev/*.html
src/gevent/resolver/*.html
Makefile.ext
MANIFEST
*_flymake.py
.coverage\.*
htmlcov/
.coverage
doc/_build
doc/__pycache__
# Artifacts of configuring in place
deps/c-ares/config.log
deps/c-ares/config.status
deps/c-ares/stamp-h1
deps/c-ares/stamp-h2
deps/c-ares/ares_build.h.orig
deps/c-ares/ares_config.h
deps/c-ares/ares_build.h
deps/c-ares/.libs
deps/c-ares/*.o
deps/c-ares/*.lo
deps/c-ares/*.la
deps/c-ares/.deps
deps/c-ares/acountry
deps/c-ares/adig
deps/c-ares/ahost
deps/c-ares/Makefile
deps/c-ares/libtool
deps/c-ares/libcares.pc
deps/c-ares/test/.deps
deps/c-ares/test/Makefile
deps/c-ares/test/config.log
deps/c-ares/test/config.status
deps/c-ares/test/libtool
deps/c-ares/test/stamp-h1
deps/libev/.deps
deps/libev/Makefile
deps/libev/config.log
deps/libev/config.h
deps/libev/config.status
deps/libev/libtool
deps/libev/stamp-h1
deps/libev/.libs
deps/libev/*.lo
deps/libev/*.la
deps/libev/*.o
deps/libuv/.deps
deps/libuv/Makefile
deps/libuv/config.log
deps/libuv/config.h
deps/libuv/config.status
deps/libduv/libtool
deps/libuv/stamp-h1
deps/libuv/.libs
deps/libuv/*.lo
deps/libuv/*.la
deps/libuv/*.o
# running setup.py on PyPy
config.h
configure-output.txt

125
.landscape.yml Normal file
View File

@ -0,0 +1,125 @@
doc-warnings: no # experimental, raises an exception
test-warnings: no
strictness: veryhigh
max-line-length: 160
# We don't use any of the auto-detected things, and
# auto-detection slows down startup
autodetect: false
requirements:
- dev-requirements.txt
python-targets:
- 2
# - 3 # landscape.io seems to fail if we run both py2 and py3?
ignore-paths:
- examples/webchat/
- deps/libuv/
- doc/
- build/
- deps/
- dist
- .eggs
# util creates lots of warnings. ideally they should be fixed,
# but that code doesn't change often
- util
# likewise with scripts
- scripts/
# This file has invalid syntax for Python 3, which is how
# landscape.io runs things...
- src/gevent/_util_py2.py
# ...and this file has invalid syntax for Python 2, which is how
# travis currently runs things. sigh.
- src/gevent/_socket3.py
# This is vendored with minimal changes
- src/gevent/_tblib.py
# likewise
- src/greentest/_six.py
# This triggers https://github.com/PyCQA/pylint/issues/846 on Travis,
# but the file is really small, so it's better to skip this one
# file than disable that whole check.
- src/gevent/core.py
# sadly, this one is complicated
- setup.py
# This crashes (infinite recursion) trying to get the mro() of a class that extends
# build_ext
- _setuputils.py
- src/greentest/getaddrinfo_module.py
ignore-patterns:
# disabled code
- ^src/greentest/xtest_.*py
# standard library code
- ^src/greentest/2.*
- ^src/greentest/3.*
# benchmarks that aren't used/changed much
- ^src/greentest/bench_.*py
pyroma:
run: true
mccabe:
# We have way too many violations of the complexity measure.
# We should enable this and fix them one at a time, but that's
# more refactoring than I want to do initially.
run: false
pyflakes:
disable:
# F821: undefined name; caught better by pylint, where it can be
# controlled for the whole file/per-line
- F821
# F401: unused import; same story
- F401
# F811: redefined function; same story
- F811
# F403: wildcard import; same story
- F403
pep8:
disable:
# N805: first arg should be self; fails on metaclasses and
# classmethods; pylint does a better job
- N805
# N802: function names should be lower-case; comes from Windows
# funcs and unittest-style asserts and factory funcs
- N802
# N801: class names should use CapWords
- N801
# N803: argument name should be lower-case; comes up with using
# the class name as a keyword-argument
- N803
# N813: camelCase imported as lowercase; socketcommon
- N813
# N806: variable in function should be lowercase; but sometimes we
# want constant-looking names, especially for closures
- N806
# N812: lowercase imported as non-lowercase; from greenlet import
# greenlet as RawGreenlet
- N812
# E261: at least two spaces before inline comment. Really? Who does
# that?
- E261
# E265: Block comment should start with "# ". This arises from
# commenting out individual lines of code.
- E265
# N806: variable in function should be lowercase; but sometimes we
# want constant-looking names, especially for closures
- N806
# W503 line break before binary operator (I like and/or on the
# next line, it makes more sense)
- W503
# E266: too many leading '#' for block comment. (Multiple # can
# set off blocks)
- E266
# E402 module level import not at top of file. (happens in
# setup.py, some test cases)
- E402
# E702: multiple expressions on one line semicolon
# (happens for monkey-patch))
- E702
# E731: do not assign a lambda expression, use a def
# simpler than a def sometimes, and prevents redefinition warnings
- E731
# E302/303: Too many/too few blank lines (between classes, etc)
# This is *really* nitpicky.
- E302
- E303

112
.pylintrc Normal file
View File

@ -0,0 +1,112 @@
[MASTER]
extension-pkg-whitelist=gevent.libuv._corecffi,gevent.libev._corecffi,gevent.local,gevent._ident
[MESSAGES CONTROL]
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
# NOTE: comments must go ABOVE the statement. In Python 2, mixing in
# comments disables all directives that follow, while in Python 3, putting
# comments at the end of the line does the same thing (though Py3 supports
# mixing)
# invalid-name, ; We get lots of these, especially in scripts. should fix many of them
# protected-access, ; We have many cases of this; legit ones need to be examinid and commented, then this removed
# no-self-use, ; common in superclasses with extension points
# too-few-public-methods, ; Exception and marker classes get tagged with this
# exec-used, ; should tag individual instances with this, there are some but not too many
# global-statement, ; should tag individual instances
# multiple-statements, ; "from gevent import monkey; monkey.patch_all()"
# locally-disabled, ; yes, we know we're doing this. don't replace one warning with another
# cyclic-import, ; most of these are deferred imports
# too-many-arguments, ; these are almost always because that's what the stdlib does
# redefined-builtin, ; likewise: these tend to be keyword arguments like len= in the stdlib
# undefined-all-variable, ; XXX: This crashes with pylint 1.5.4 on Travis (but not locally on Py2/3
# ; or landscape.io on Py3). The file causing the problem is unclear. UPDATE: identified and disabled
# that file.
# see https://github.com/PyCQA/pylint/issues/846
# useless-suppression: the only way to avoid repeating it for specific statements everywhere that we
# do Py2/Py3 stuff is to put it here. Sadly this means that we might get better but not realize it.
# duplicate-code: Yeah, the compatibility ssl modules are much the same
# In pylint 1.8.0, inconsistent-return-statements are created for the wrong reasons.
# This code raises it, even though there's only one return (the implicit 'return None' is presumably
# what triggers it):
# def foo():
# if baz:
# return 1
# In Pylint 2dev1, needed for Python 3.7, we get spurious 'useless return' errors:
# @property
# def foo(self):
# return None # generates useless-return
disable=wrong-import-position,
wrong-import-order,
missing-docstring,
ungrouped-imports,
invalid-name,
protected-access,
no-self-use,
too-few-public-methods,
exec-used,
global-statement,
multiple-statements,
locally-disabled,
cyclic-import,
too-many-arguments,
redefined-builtin,
useless-suppression,
duplicate-code,
undefined-all-variable,
inconsistent-return-statements,
useless-return,
useless-object-inheritance
[FORMAT]
# duplicated from setup.cfg
max-line-length=160
max-module-lines=1100
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
#notes=FIXME,XXX,TODO
# Disable that, we don't want them in the report (???)
notes=
[VARIABLES]
dummy-variables-rgx=_.*
[TYPECHECK]
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
# gevent: this is helpful for py3/py2 code.
generated-members=exc_clear
# List of classes names for which member attributes should not be checked
# (useful for classes with attributes dynamically set). This supports can work
# with qualified names.
# greenlet, Greenlet, parent, dead: all attempts to fix issues in greenlet.py
# only seen on the service, e.g., self.parent.loop: class parent has no loop
ignored-classes=SSLContext, SSLSocket, greenlet, Greenlet, parent, dead
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=gevent._corecffi,gevent.os,os,greenlet,threading,gevent.libev.corecffi,gevent.socket,gevent.core
[DESIGN]
max-attributes=12
max-parents=10
[BASIC]
bad-functions=input
# Prospector turns ot unsafe-load-any-extension by default, but
# pylint leaves it off. This is the proximal cause of the
# undefined-all-variable crash.
#unsafe-load-any-extension = no

49
.travis.yml Normal file
View File

@ -0,0 +1,49 @@
# .travis.yml based on https://github.com/DRMacIver/hypothesis/blob/master/.travis.yml
language: python
dist: xenial
group: travis_latest
python:
- 3.7-dev
env:
global:
- BUILD_RUNTIMES=$HOME/.runtimes
- PYTHONHASHSEED=8675309
- CC="ccache gcc"
- CCACHE_NOCPP2=true
- CCACHE_SLOPPINESS=file_macro,time_macros,include_file_ctime,include_file_mtime
- CCACHE_NOHASHDIR=true
- CFLAGS="-g -pipe"
matrix:
# These are ordered to get as much diversity in the
# first group of parallel runs (4) as possible
- TASK=test-py37
- TASK=test-py27
- TASK=test-pypy
- TASK=test-py36
- TASK=test-py27-noembed
- TASK=test-pypy3
- TASK=test-py35
- TASK=test-py34
matrix:
fast_finish: true
script:
- make $TASK
notifications:
email: false
cache:
pip: true
directories:
- $HOME/.venv
- $HOME/.runtimes
- $HOME/.wheelhouse
- $HOME/.ccache
before_cache:
- rm -f $HOME/.cache/pip/log/debug.log

62
AUTHORS Normal file
View File

@ -0,0 +1,62 @@
Gevent is written and maintained by
Denis Bilenko
Matt Iversen
Steffen Prince
Jason Madden
and the contributors (ordered by the date of first contribution):
Jason Toffaletti
Mike Barton
Ludvig Ericson
Marcus Cavanaugh
Matt Goodall
Ralf Schmitt
Daniele Varrazzo
Nicholas Piël
Örjan Persson
Uriel Katz
Ted Suzman
Randall Leeds
Erik Näslund
Alexey Borzenkov
David Hain
Dmitry Chechik
Ned Rockson
Tommie Gannert
Shaun Lindsay
Andreas Blixt
Nick Barkas
Galfy Pundee
Alexander Boudkar
Damien Churchill
Tom Lynn
Shaun Cutts
David LaBissoniere
Alexandre Kandalintsev
Geert Jansen
Vitaly Kruglikov
Saúl Ibarra Corretgé
Oliver Beattie
Bobby Powers
Anton Patrushev
Jan-Philip Gehrcke
Alex Gaynor
陈小玉
Philip Conrad
Heungsub Lee
Ron Rothman
See https://github.com/gevent/gevent/graphs/contributors for more info.
Gevent is inspired by and uses some code from eventlet which was written by
Bob Ipollito
Donovan Preston
The win32util module is taken from Twisted. The tblib module is taken from python-tblib by Ionel Cristian Mărieș.
Some modules (local, ssl) contain code from the Python standard library.
If your code is used in gevent and you are not mentioned above, please contact the maintainer.

815
CHANGES.rst Normal file
View File

@ -0,0 +1,815 @@
===========
Changelog
===========
.. currentmodule:: gevent
1.4.0 (2019-01-04)
==================
- Build with Cython 0.29 in '3str' mode.
- Test with PyPy 6.0 on Windows.
- Add support for application-wide callbacks when ``Greenlet`` objects
are started. See :pr:`1289`, provided by Yury Selivanov.
- Fix consuming a single ready object using
``next(gevent.iwait(objs))``. Previously such a construction would
hang because `iter` was not called. See :pr:`1288`, provided by Josh
Snyder. This is not recommended, though, as unwaited objects will
have dangling links (but see next item).
- Make `gevent.iwait` return an iterator that can now also be used as
a context manager. If you'll only be consuming part of the iterator,
use it in a ``with`` block to avoid leaking resources. See
:pr:`1290`, provided by Josh Snyder.
- Fix semaphores to immediately notify links if they are ready and
``rawlink()`` is called. This behaves like ``Event`` and
``AsyncEvent``. Note that the order in which semaphore links are
called is not specified. See :issue:`1287`, reported by Dan Milon.
- Improve safety of handling exceptions during interpreter shutdown.
See :issue:`1295` reported by BobDenar1212.
- Remove the deprecated ability to specify ``GEVENT_RESOLVER`` and
other importable settings as a ``path/to/a/package.module.item``.
This had race conditions and didn't work with complicated resolver
implementations. Place the required package or module on `sys.path`
first.
- Reduce the chances that using the blocking monitor functionality
could result in apparently random ``SystemError:
Objects/tupleobject.c: bad argument to internal function``. Reported
in :issue:`1302` by Ulrich Petri.
- Refactored the gevent test runner and test suite to make them more
reusable. In particular, the tests are now run with ``python -m
gevent.tests``. See :issue:`1293`.
- Make a monkey-patched ``socket.getaddrinfo`` return socket module
enums instead of plain integers for the socket type and address
family on Python 3. See :issue:`1310` reported by TheYOSH.
- Make gevent's pywsgi server set the non-standard environment value
``wsgi.input_terminated`` to True. See :issue:`1308`.
- Make `gevent.util.assert_switches` produce more informative messages
when the assertion fails.
- Python 2: If a `gevent.socket` was closed asynchronously (in a
different greenlet or a hub callback), `AttributeError` could result
if the socket was already in use. Now the correct socket.error
should be raised.
- Fix :meth:`gevent.threadpool.ThreadPool.join` raising a
`UserWarning` when using the libuv backend. Reported in
:issue:`1321` by ZeroNet.
- Fix ``FileObjectPosix.seek`` raising `OSError` when it should have
been `IOError` on Python 2. Reported by, and PR by, Ricardo Kirkner.
See :issue:`1323`.
- Upgrade libuv from 1.23.2 to 1.24.0.
1.3.7 (2018-10-12)
==================
- Formatting run info no longer includes ``gevent.local.local``
objects that have no value in the greenlet. See :issue:`1275`.
- Fixed negative length in pywsgi's Input read functions for non chunked body.
Reported in :issue:`1274` by tzickel.
- Upgrade libuv from 1.22.0 to 1.23.2.
- Fix opening files in text mode in CPython 2 on Windows by patching
libuv. See :issue:`1282` reported by wiggin15.
1.3.6 (2018-08-17)
==================
- gevent now depends on greenlet 0.4.14 or above. gevent binary wheels
for 1.3.5 and below must have greenlet 0.4.13 installed on Python
3.7 or they will crash. Reported by Alexey Stepanov in :issue:`1260`
and pkittenis in :issue:`1261`.
- :class:`gevent.local.local` subclasses correctly supports
``@staticmethod`` functions. Reported by Brendan Powers in
:issue:`1266`.
1.3.5 (2018-07-16)
==================
- Update the bundled libuv from 1.20.1 to 1.22.0.
- Test Python 3.7 on Appveyor. Fix the handling of Popen's
``close_fds`` argument on 3.7.
- Update Python versions tested on Travis, including PyPy to 6.0. See :issue:`1195`.
- :mod:`gevent.queue` imports ``_PySimpleQueue`` instead of
``SimpleQueue`` so that it doesn't block the event loop.
:func:`gevent.monkey.patch_all` makes this same substitution in
:mod:`queue`. This fixes issues with
:class:`concurrent.futures.ThreadPoolExecutor` as well. Reported in
:issue:`1248` by wwqgtxx and :issue:`1251` by pyld.
- :meth:`gevent.socket.socket.connect` doesn't pass the port (service)
to :func:`socket.getaddrinfo` when it resolves an ``AF_INET`` or
``AF_INET6`` address. (The standard library doesn't either.) This
fixes an issue on Solaris. Reported in :issue:`1252` by wiggin15.
- :meth:`gevent.socket.socket.connect` works with more address
families, notably AF_TIPC, AF_NETLINK, AF_BLUETOOTH, AF_ALG and AF_VSOCK.
1.3.4 (2018-06-20)
==================
- Be more careful about issuing ``MonkeyPatchWarning`` for ssl
imports. Now, we only issue it if we detect the one specific
condition that is known to lead to RecursionError. This may produce
false negatives, but should reduce or eliminate false positives.
- Based on measurements and discussion in :issue:`1233`, adjust the
way :mod:`gevent.pywsgi` generates HTTP chunks. This is intended to
reduce network overhead, especially for smaller chunk sizes.
- Additional slight performance improvements in :mod:`gevent.pywsgi`.
See :pr:`1241`.
1.3.3 (2018-06-08)
==================
- :func:`gevent.sleep` updates the loop's notion of the current time
before sleeping so that sleep duration corresponds more closely to
elapsed (wall clock) time. :class:`gevent.Timeout` does the same.
Reported by champax and FoP in :issue:`1227`.
- Fix an ``UnboundLocalError`` in SSL servers when wrapping a socket
throws an error. Reported in :issue:`1236` by kochelmonster.
1.3.2.post0 (2018-05-30)
========================
- Fix a packaging error in manylinux binary wheels that prevented some
imports from working. See :issue:`1219`.
1.3.2 (2018-05-29)
==================
- Allow weak refeneces to :class:`gevent.queue.Queue`. Reported in
:issue:`1217` by githrdw.
1.3.1 (2018-05-18)
==================
- Allow weak references to :class:`gevent.event.Event`. Reported in
:issue:`1211` by Matias Guijarro.
- Fix embedded uses of :func:`gevent.Greenlet.spawn`, especially under
uwsgi. Reported in :issue:`1212` by Kunal Gangakhedkar.
- Fix :func:`gevent.os.nb_write` and :func:`gevent.os.nb_read` not
always closing the IO event they opened in the event of an
exception. This would be a problem especially for libuv.
1.3.0 (2018-05-11)
==================
- Python 3.7 passes the automated memory leak checks. See :issue:`1197`.
- Update autoconf's config.guess and config.sub to the latest versions
for c-ares and libev.
- :class:`gevent.local.local` subclasses that mix-in ABCs can be instantiated.
Reported in :issue:`1201` by Bob Jordan.
1.3b2 (2018-05-03)
==================
- On Windows, CFFI is now a dependency so that the libuv backend
really can be used by default.
- Fix a bug detecting whether we can use the memory monitoring
features when psutil is not installed.
- `gevent.subprocess.Popen` uses ``/proc/self/fd`` (on Linux) or
``/dev/fd`` (on BSD, including macOS) to find the file descriptors
to close when ``close_fds`` is true. This matches an optimization
added to Python 3 (and backports it to Python 2.7), making process
spawning up to 9 times faster. Also, on Python 3, since Python 3.3
is no longer supported, we can also optimize the case where
``close_fds`` is false (not the default), making process spawning up
to 38 times faster. Initially reported in :issue:`1172` by Ofer Koren.
- The bundled libuv is now 1.20.1, up from 1.19.2. See :issue:`1177`.
- The long-deprecated and undocumented module ``gevent.wsgi`` was removed.
- Add `gevent.util.assert_switches` to build on the monitoring
functions. Fixes :issue:`1182`.
- A started monitor thread for the active hub now survives a fork. See
:issue:`1185`.
- The greenlet tracer functions used for the various monitoring
capabilities are now compiled with Cython for substantially lower
overhead. See :pr:`1190`.
- libuv now collects all pending watchers and runs their callbacks at
the end of the loop iteration using UV_RUN_ONCE. This eliminates the
need to patch libuv to be greenlet-safe. It also means that
zero-duration timer watchers are actual timer watchers again
(instead of being turned into check watchers); newly added
zero-duration timers cannot block the event loop because they won't
be run until a safe time.
- Python 3.7.0b4 is now the tested and supported version of Python
3.7. PyPy 6.0 has been tested, although CI continues to use 5.10.
1.3b1 (2018-04-13)
==================
Dependencies
------------
- Cython 0.28.2 is now used to build gevent from a source checkout.
- The bundled libuv is now 1.19.2, up from 1.18.0.
Platform Support
----------------
- Travis CI tests on Python 3.7.0b3.
- Windows now defaults to the libuv backend if CFFI is installed. See
:issue:`1163`.
Bug Fixes
---------
- On Python 2, when monkey-patching `threading.Event`, also
monkey-patch the underlying class, ``threading._Event``. Some code
may be type-checking for that. See :issue:`1136`.
- Fix libuv io watchers polling for events that only stopped watchers
are interested in, reducing CPU usage. Reported in :issue:`1144` by
wwqgtxx.
Enhancements
------------
- Add additional optimizations for spawning greenlets, making it
faster than 1.3a2.
- Use strongly typed watcher callbacks in the libuv CFFI extensions.
This prevents dozens of compiler warnings.
- When gevent prints a timestamp as part of an error message, it is
now in UTC format as specified by RFC3339.
- Threadpool threads that exit now always destroy their hub (if one
was created). This prevents some forms of resource leaks (notably
visible as blocking functions reported by the new monitoring abilities).
- Hub objects now include the value of their ``name`` attribute in
their repr.
- Pools for greenlets and threads have lower overhead, especially for
``map``. See :pr:`1153`.
- The undocumented, internal implementation classes ``IMap`` and
``IMapUnordered`` classes are now compiled with Cython, further
reducing the overhead of ``[Thread]Pool.imap``.
- The classes `gevent.event.Event` and `gevent.event.AsyncResult`
are compiled with Cython for improved performance, as is the
``gevent.queue`` module and ``gevent.hub.Waiter`` and certain
time-sensitive parts of the hub itself. Please report any
compatibility issues.
- ``python -m gevent.monkey <script>`` accepts more values for
``<script>``, including paths to packages or compiled bytecode.
Reported in :issue:`1157` by Eddie Linder.
- Add a simple event framework for decoupled communication. It uses
:mod:`zope.event` if that is installed.
- :mod:`gevent.monkey` has support for plugins in the form of event
subscribers and setuptools entry points. See :pr:`1158` and
:issue:`1162`. setuptools must be installed at runtime for its entry
points to function.
Monitoring and Debugging
------------------------
- Introduce the configuration variable
`gevent.config.track_greenlet_tree` (aka
``GEVENT_TRACK_GREENLET_TREE``) to allow disabling the greenlet tree
features for applications where greenlet spawning is performance
critical. This restores spawning performance to 1.2 levels.
- Add an optional monitoring thread for each hub. When enabled, this
thread (by default) looks for greenlets that block the event loop
for more than 0.1s. You can add your own periodic monitoring
functions to this thread. Set ``GEVENT_MONITOR_THREAD_ENABLE`` to
use it, and ``GEVENT_MAX_BLOCKING_TIME`` to configure the blocking
interval.
- The monitoring thread emits events when it detects certain
conditions, like loop blocked or memory limits exceeded.
- Add settings for monitoring memory usage and emitting events when a
threshold is exceeded and then corrected. gevent currently supplies
no policy for what to do when memory exceeds the configured limit.
``psutil`` must be installed to use this. See :pr:`1150`.
1.3a2 (2018-03-06)
==================
Dependencies
------------
- Cython 0.28b1 or later is now required to build gevent from a source
checkout (Cython is *not* required to build a source distribution
from PyPI).
- Update c-ares to 1.14.0. See :issue:`1105`.
- gevent now **requires** the patched version of libuv it is
distributed with. Building gevent with a non-embedded libuv, while
not previously supported, is not possible now. See
:issue:`1126`.
Platform Support
----------------
- Travis CI tests on Python 3.7.0b2 and PyPy 2.7 5.10.0 and PyPy 3.5
5.10.1.
Build Changes
-------------
- Fix building from a source distribution (PyPI) without Cython
installed.
Enhancements
------------
- Add the ``dnspython`` resolver as a lightweight alternative to
c-ares. It is generally faster than c-ares and is supported on PyPy.
c-ares may be deprecated in the future. See :pr:`1088` and
:issue:`1103`.
- Add the module :mod:`gevent.time` that can be imported instead of
:mod:`time`, much like :mod:`gevent.socket` can be imported instead
of :mod:`socket`. It contains ``gevent.sleep``. This aids
monkey-patching.
- Simple subclasses of `gevent.local.local` now have the same
(substantially improved) performance characteristics of plain
`gevent.local.local` itself, making them 2 to 3 times faster than
before. See :pr:`1117`. If there are any compatibility
problems, please open issues.
Monitoring and Debugging
~~~~~~~~~~~~~~~~~~~~~~~~
- Greenlet objects now keep track of their spawning parent greenlet
and the code location that spawned them, in addition to maintaining
a "spawn tree local" mapping. This adds some runtime overhead in
relative terms, but absolute numbers are still relatively small.
Based on a proposal from PayPal and comments by Mahmoud Hashemi and
Kurt Rose. See :issue:`755` and :pr:`1115`. As always, feedback is
appreciated.
- Greenlet objects now have a `minimal_ident
<gevent.Greenlet.minimal_ident>` property. It functions
similarly to ``Thread.ident`` or ``id`` by uniquely identifying the
greenlet object while it remains alive, and it can be reused after
the greenlet object is dead. It is different in that it is small and
sequential. Based on a proposal from PayPal and comments by Mahmoud
Hashemi and Kurt Rose. See :issue:`755`. As always, feedback is
appreciated.
- `gevent.Greenlet` objects now have a `gevent.Greenlet.name`
attribute that is included in the default repr.
- Include the values of `gevent.local.local` objects associated with
each greenlet in `gevent.util.format_run_info`.
- Add `gevent.util.GreenletTree` to visualize the greenlet tree. This
is used by `gevent.util.format_run_info`.
Subprocess
~~~~~~~~~~
- Make :class:`gevnt.subprocess.Popen` accept the ``restore_signals``
keyword argument on all versions of Python, and on Python 2 have it
default to false. It previously defaulted to true on all versions;
now it only defaults to true on Python 3. The standard library in
Python 2 does not have this argument and its behaviour with regards
to signals is undocumented, but there is code known to rely on
signals not being restored under Python 2. Initial report and patch
in :pr:`1063` by Florian Margaine.
- Allow :class:`gevent.subprocess.Popen` to accept the keyword
arguments ``pass_fds`` and ``start_new_session`` under Python 2.
They have always had the same default as Python 3, namely an empty
tuple and false, but now are accessible to Python 2.
- Support the ``capture_output`` argument added to Python 3.7 in
:func:`gevent.subprocess.run`.
Configuration
~~~~~~~~~~~~~
- Centralize all gevent configuration in an object at
``gevent.config``, allowing for gevent to be configured through code
and not *necessarily* environment variables, and also provide a
centralized place for documentation. See :issue:`1090`.
- The new ``GEVENT_CORE_CFFI_ONLY`` environment variable has been
replaced with the pre-existing ``GEVENT_LOOP`` environment
variable. That variable may take the values ``libev-cext``,
``libev-cffi``, or ``libuv-cffi``, (or be a list in preference
order, or be a dotted name; it may also be assigned to an
object in Python code at ``gevent.config.loop``).
- The ``GEVENTARES_SERVERS`` environment variable is deprecated in
favor of ``GEVENT_RESOLVER_SERVERS``. See :issue:`1103`.
Bug Fixes
---------
- Fix calling ``shutdown`` on a closed socket. It was raising
``AttributeError``, now it once again raises the correct
``socket.error``. Reported in :issue:`1089` by André Cimander.
- Fix an interpreter crash that could happen if two or more ``loop``
objects referenced the default event loop and one of them was
destroyed and then the other one destroyed or (in the libev C
extension implementation only) deallocated (garbage collected). See
:issue:`1098`.
- Fix a race condition in libuv child callbacks. See :issue:`1104`.
Other Changes
-------------
- The internal, undocumented module ``gevent._threading`` has been
simplified.
- The internal, undocumented class ``gevent._socket3._fileobject`` has
been removed. See :issue:`1084`.
- Simplify handling of the libev default loop and the ``destroy()``
method. The default loop, when destroyed, can again be requested and
it will regenerate itself. The default loop is the only one that can
receive child events.
- Make :meth:`gevent.socket.socket.sendall` up to ten times faster on
PyPy3, through the same change that was applied in gevent 1.1b3 for PyPy2.
- Be more careful about issuing a warning about patching SSL on
Python 2. See :issue:`1108`.
- Signal handling under PyPy with libuv is more reliable. See
:issue:`1112`.
- The :mod:`gevent.greenlet` module is now compiled with Cython to
offset any performance decrease due to :issue:`755`. Please open
issues for any compatibility concerns. See :pr:`1115` and :pr:`1120`.
- On CPython, allow the pure-Python implementations of
`gevent.Greenlet`, `gevent.local` and `gevent.lock` to be
used when the environment variable ``PURE_PYTHON`` is set. This is
not recommended except for debugging and testing. See :issue:`1118`.
- :meth:`gevent.select.poll.poll` now interprets a *timeout* of -1 the
same as a *timeout* of *None* as the standard requires. Previously,
on libuv this was interpreted the same as a *timeout* of 0. In
addition, all *timeout* values less than zero are interpreted like
*None* (as they always were under libev). See :issue:`1127`.
- Monkey-patching now defaults to patching ``threading.Event``.
1.3a1 (2018-01-27)
==================
Dependencies
------------
- gevent is now built and tested with Cython 0.27. This is required
for Python 3.7 support.
- Update c-ares to 1.13.0. See :issue:`990`.
Platform Support
----------------
- Add initial support for Python 3.7a3. It has the same level of
support as Python 3.6.
- Using unreleased Cython 0.28 and greenlet 0.4.13; requires Python 3.7a3.
- The ``async`` functions and classes have been renamed to
``async_`` due to ``async`` becoming a keyword in Python 3.7.
Aliases are still in place for older versions. See :issue:`1047`.
- gevent is now tested on Python 3.6.4. This includes the following
fixes and changes:
- Errors raised from :mod:`gevent.subprocess` will have a
``filename`` attribute set.
- The :class:`threading.Timer` class is now monkey-patched and can
be joined. Previously on Python 3.4 and above, joining a ``Timer``
would hang the process.
- :meth:`gevent.ssl.SSLSocket.unwrap` behaves more like the standard
library, including returning a SSLSocket and allowing certain
timeout-related SSL errors to propagate. The added standard
library tests ``test_ftplib.py`` now passes.
- :class:`gevent.subprocess.Popen` accepts a "path-like object" for
the *cwd* parameter on all platforms. Previously this only worked
on POSIX platforms under Python 3.6. Now it also works on Windows under
Python 3.6 (as expected) and is backported to all previous versions.
- Linux CI now tests on PyPy3 3.5-5.9.0, updated from PyPy3 3.5-5.7.1.
See :issue:`1001`. PyPy2 has been updated to 5.9.0 from 5.7.1,
Python 2.7 has been updated to 2.7.14 from 2.7.13, Python 3.4 is
updated to 3.4.7 from 3.4.5, Python 3.5 is now 3.5.4 from 3.5.3, and
Python 3.6 is now 3.6.4 from 3.6.0.
- Drop support for Python 3.3. The documentation has only claimed
support for 3.4+ since gevent 1.2 was released, and only 3.4+ has
been tested. This merely removes the supporting Trove classifier and
remaining test code. See :issue:`997`.
- PyPy is now known to run on Windows using the libuv backend, with
caveats. See the section on libuv for more information.
- Due to security concerns, official support for Python 2.7.8 and
earlier (without a modern SSL implementation) has been dropped.
These versions are no longer tested with gevent, but gevent can
still be installed on them. Supporting code will be removed in the
next major version of gevent. See :issue:`1073`.
Build Changes
-------------
- When building gevent from a source checkout (*not* a distributed
source distribution), ``make`` is no longer required and the
``Makefile`` is not used. Neither is an external ``cython`` command.
Instead, the ``cythonize`` function is used, as recommended by
Cython. (The external commands were never required by source
distributions.) See :issue:`1076`.
- :class:`gevent.local.local` is compiled with Cython on CPython.
- The Cython ares 'channel' class is no longer declared to be publicly
accessible from a named C structure. Doing so caused a conflict with
the c-ares header files.
Bug Fixes
---------
- If a single greenlet created and destroyed many
:class:`gevent.local.local` objects without ever exiting, there
would be a leak of the function objects intended to clean up the
locals after the greenlet exited. Introduce a weak reference to
avoid that. Reported in :issue:`981` by Heungsub Lee.
- pywsgi also catches and ignores by default
:const:`errno.WSAECONNABORTED` on Windows. Initial patch in
:pr:`999` by Jan van Valburg.
- :meth:`gevent.subprocess.Popen.communicate` returns the correct type
of str (not bytes) in universal newline mode under Python 3, or when
an encoding has been specified. Initial patch in :pr:`939` by
William Grzybowski.
- :meth:`gevent.subprocess.Popen.communicate` (and in general,
accessing ``Popen.stdout`` and ``Popen.stderr``) returns the correct
type of str (bytes) in universal newline mode under Python 2.
Previously it always returned unicode strings. Reported in
:issue:`1039` by Michal Petrucha.
- :class:`gevent.fileobject.FileObjectPosix` returns native strings in
universal newline mode on Python 2. This is consistent with what
:class:`.FileObjectThread` does. See :issue:`1039`.
- ``socket.send()`` now catches ``EPROTOTYPE`` on macOS to handle a race
condition during shutdown. Fixed in :pr:`1035` by Jay Oster.
- :func:`gevent.socket.create_connection` now properly cleans up open
sockets if connecting or binding raises a :exc:`BaseException` like
:exc:`KeyboardInterrupt`, :exc:`greenlet.GreenletExit` or
:exc:`gevent.timeout.Timeout`. Reported in :issue:`1044` by
kochelmonster.
Other Changes
-------------
- ``Pool.add`` now accepts ``blocking`` and ``timeout`` parameters,
which function similarly to their counterparts in ``Semaphore``.
See :pr:`1032` by Ron Rothman.
- Defer adjusting the stdlib's list of active threads until
``threading`` is monkey patched. Previously this was done when
:mod:`gevent.threading` was imported. That module is documented to
be used as a helper for monkey patching, so this should generally
function the same, but some applications ignore the documentation
and directly import that module anyway.
A positive consequence is that ``import gevent.threading, threading;
threading.current_thread()`` will no longer return a DummyThread
before monkey-patching. Another positive consequence is that PyPy
will no longer print a ``KeyError`` on exit if
:mod:`gevent.threading` was imported *without* monkey-patching.
See :issue:`984`.
- Specify the Requires-Python metadata for improved installation
support in certain tools (setuptools v24.2.1 or newer is required).
See :issue:`995`.
- Monkey-patching after the :mod:`ssl` module has been imported now
prints a warning because this can produce ``RecursionError``.
- :class:`gevent.local.local` objects are now approximately 3.5 times faster
getting, setting and deleting attributes on PyPy. This involved
implementing more of the attribute protocols directly. Please open
an issue if you have any compatibility problems. See :issue:`1020`.
- :class:`gevent.local.local` is compiled with Cython on CPython. It
was already 5 to 6 times faster due to the work on :issue:`1020`,
and compiling it with Cython makes it another 5 to 6 times faster,
for a total speed up of about 35 times. It is now in the same
ballpark as the native :class:`threading.local` class. It also uses
one pointer less memory per object, and one pointer less memory per
greenlet. See :pr:`1024`.
- More safely terminate subprocesses on Windows with
:meth:`gevent.subprocess.Popen.terminate`. Reported in :issue:`1023`
by Giacomo Debidda.
- gevent now uses cffi's "extern 'Python'" callbacks. These should be
faster and more stable. This requires at least cffi 1.4.0. See :issue:`1049`.
- gevent now approximately tries to stick to a scheduling interval
when running callbacks, instead of simply running a count of
callbacks. The interval is determined by
:func:`gevent.getswitchinterval`. On Python 3, this is the same as
the thread switch interval. On Python 2, this defaults to 0.005s and
can be changed with :func:`gevent.setswitchinterval`. This should
result in more fair "scheduling" of greenlets, especially when
``gevent.sleep(0)`` or other busy callbacks are in use. The interval
is checked every 50 callbacks to keep overhead low. See
:issue:`1072`. With thanks to Arcadiy Ivanov and Antonio Cuni.
libuv
-----
- Add initial *experimental* support for using libuv as a backend
instead of libev, controlled by setting the environment variable
``GEVENT_CORE_CFFI_ONLY=libuv`` before importing gevent. This
suffers a number of limitations compared to libev, notably:
- libuv support is not available in the manylinux wheels uploaded to
PyPI. The manylinux specification requires glibc 2.5, while libuv
requires glibc 2.12. Install from source to access libuv on Linux
(e.g., pip's ``--no-binary`` option).
- Timers (such as ``gevent.sleep`` and ``gevent.Timeout``) only
support a resolution of 1ms (in practice, it's closer to 1.5ms).
Attempting to use something smaller will automatically increase it
to 1ms and issue a warning. Because libuv only supports
millisecond resolution by rounding a higher-precision clock to an
integer number of milliseconds, timers apparently suffer from more
jitter.
- Using negative timeouts may behave differently from libev.
- libuv blocks delivery of all signals, so signals are handled using
an (arbitrary) 0.3 second timer. This means that signal handling
will be delayed by up to that amount, and that the longest the
event loop can sleep in the operating system's ``poll`` call is
that amount. Note that this is what gevent does for libev on
Windows too.
- libuv only supports one io watcher per file descriptor, whereas
libev and gevent have always supported many watchers using
different settings. The libev behaviour is emulated at the Python
level, but that adds overhead.
- Looping multiple times and expecting events for the same file
descriptor to be raised each time without any data being read or
written (as works with libev) does not appear to work correctly on
Linux when using ``gevent.select.poll`` or a monkey-patched
``selectors.PollSelector``.
- The build system does not support using a system libuv; the
embedded copy must be used. Using setuptools to compile libuv was
the most portable method found.
- If anything unexpected happens, libuv likes to ``abort()`` the
entire process instead of reporting an error. For example, closing
a file descriptor it is using in a watcher may cause the entire
process to be exited.
- There may be occasional otherwise unexplained and hard to
duplicate crashes. If you can duplicate a crash, **please** submit
an issue.
- This is the only backend that PyPy can use on Windows. As of this
alpha, there are many known issues with non-blocking sockets
(e.g., as used by :mod:`asyncore`; see ``test_ftplib.py``) and
sometimes sockets not getting closed in a timely fashion
(apparently; see ``test_httpservers.py``) and communicating with
subprocesses (it always hangs). Help tracking those down would be
appreciated. Only PyPy2 is tested.
Feedback and pull requests are welcome, especially to address the
issues mentioned above.
Other differences include:
- The order in which timers and other callbacks are invoked may be
different than in libev. In particular, timers and IO callbacks
happen in a different order, and timers may easily be off by up to
half of the supposed 1ms resolution. See :issue:`1057`.
- Starting a ``timer`` watcher does not update the loop's time by
default. This is because, unlike libev, a timer callback can cause
other timer callbacks to be run if they expire because the loop's
time updated, without cycling the event loop. See :issue:`1057`.
libev has also been changed to follow this behaviour.
Also see :issue:`1072`.
- Timers of zero duration do not necessarily cause the event loop to
cycle, as they do in libev. Instead, they may be called
immediately. If zero duration timers are added from other zero
duration timer callbacks, this can lead the loop to appear to
hang, as no IO will actually be done.
To mitigate this issue, ``loop.timer()`` detects attempts to use
zero duration timers and turns them into a check watcher. check
watchers do not support the ``again`` method.
- All watchers (e.g., ``loop.io``) and the ``Timeout`` class have a
``close`` method that should be called when code is done using the
object (they also function as context managers and a ``with``
statement will automatically close them). gevent does this
internally for sockets, file objects and internal timeouts.
Neglecting to close an object may result in leaking native
resources. To debug this, set the environment variables
``GEVENT_DEBUG=debug`` and ``PYTHONTRACEMALLOC=n`` before starting
the process.
The traditional cython-based libev backend will not leak if
``close`` is not called and will not produce warnings. The
CFFI-based libev backend will not currently leak but will produce
warnings. The CFFI-based libuv backend may leak and will produce
warnings.
Again, this is extremely experimental and all of it is subject to
change.
See :issue:`790` for history and more in-depth discussion.
libev
-----
- The C extension has been updated to use more modern Cython idioms
and generate less code for simplicity, faster compilation and better
cache usage. See :pr:`1077`.
- Watcher objects may be slightly larger. On a 64-bit platform, a
typical watcher may be 16 bytes (2 pointers) larger. This is
offset by slight performance gains.
- Cython is no longer preprocessed. Certain attributes that were
previously only defined in certain compilation modes (notably
LIBEV_EMBED) are now always defined, but will raise
``AttributeError`` or have a negative value when not available. In
general these attributes are not portable or documented and are
not implemented by libuv or the CFFI backend. See :issue:`1076`.
- Certain private helper functions (``gevent_handle_error``, and part of
``gevent_call``) are now implemented in Cython instead of C. This
reduces our reliance on internal undocumented implementation
details of Cython and Python that could change. See :pr:`1080`.

48
CONTRIBUTING.rst Normal file
View File

@ -0,0 +1,48 @@
Basics
======
Please see `contribution-guide.org <http://www.contribution-guide.org/>`_ for
general details on what we expect from contributors. Thanks!
gevent-specific details
=======================
There are a number of systems in place to help ensure gevent is of the
highest possible quality:
- Builds on Travis CI automatically submit updates to `coveralls.io`_ to
monitor test coverage. Pull requests that don't feature adequate test
coverage will be automatically failed.
.. image:: https://coveralls.io/repos/gevent/gevent/badge.svg?branch=master&service=github
:target: https://coveralls.io/github/gevent/gevent?branch=master
- Likewise, builds on Travis CI will automatically submit updates to
`landscape.io`_ to monitor code health (adherence to PEP8, absence of
common code smells, etc). Pull requests that decrease code health will
be automatically failed.
.. image:: https://landscape.io/github/gevent/gevent/master/landscape.svg?style=flat
:target: https://landscape.io/github/gevent/gevent/master
:alt: Code Health
- A test suite is run for every push and pull request submitted. Travis
CI is used to test on Linux, and `AppVeyor`_ runs the builds on
Windows. Pull requests with tests that don't pass will be
automatically failed.
.. image:: https://travis-ci.org/gevent/gevent.svg?branch=master
:target: https://travis-ci.org/gevent/gevent
.. image:: https://ci.appveyor.com/api/projects/status/q4kl21ng2yo2ixur?svg=true
:target: https://ci.appveyor.com/project/denik/gevent
.. _landscape.io: https://landscape.io/github/gevent/gevent
.. _coveralls.io: https://coveralls.io/github/gevent/gevent
.. _AppVeyor: https://ci.appveyor.com/project/denik/gevent
Pull requests that don't pass those checks will be automatically
failed. But don't worry, it's all about context. Most of the time
failing checks are easy to fix, and occasionally a PR will be accepted
even with failing checks to be fixed by the maintainers.

25
LICENSE Normal file
View File

@ -0,0 +1,25 @@
MIT License
Except when otherwise stated (look at the beginning of each file) the software
and the documentation in this project are copyrighted by:
Denis Bilenko and the contributors, http://www.gevent.org
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.

69
MANIFEST.in Normal file
View File

@ -0,0 +1,69 @@
recursive-include src/greentest *
recursive-include examples *
recursive-include src/gevent *
recursive-include doc *
recursive-include deps *
recursive-include util *
include LICENSE
include NOTICE
include README.rst
include CONTRIBUTING.rst
include TODO
include changelog.rst
include MANIFEST.in
include AUTHORS
include Makefile.ext
include known_failures.py
include *.yml
include *.txt
include _setup*.py
include CHANGES.rst
include tox.ini
include .pep8
include .pylintrc
recursive-include .github *.md
recursive-include benchmarks *.sh *.py
recursive-include appveyor *.cmd
recursive-include appveyor *.ps1
recursive-include scripts *.sh *.py
include scripts/releases/make-manylinux
### Artifacts of configuring/building in place
# These we want, they come from the Makefile step
#- recursive-exclude gevent corecext.pyx *.c *.h
# This we want if we're on PyPy it's moved there ahead of time
# by setup.py
#- prune gevent/libev
prune */__pycache__
global-exclude *.so
global-exclude *.o
global-exclude *.lo
global-exclude *.la
global-exclude config.log config.status
prune doc/_build
global-exclude *.pyc
recursive-exclude src/greentest .coverage
prune src/greentest/htmlcov
recursive-exclude deps/c-ares stamp-h? ares_build.h.orig
prune deps/libev/.deps
prune deps/libuv/.deps
recursive-exclude deps/libev Makefile libtool stamp-h? config.h
# This is the output of _corecffi_build.py and may be particular
# to each CFFI version/platform
recursive-exclude src/gevent _corecffi.c
# See comments in Makefile; this is renamed to Makefile.ext
# this exclude keeps check-manifest from complaining
exclude Makefile
exclude configure-output
exclude configure-output.txt
exclude deps/TAGS
exclude deps/c-ares/ares_build.h
exclude deps/c-ares/ares_config.h
exclude deps/c-ares/libcares.pc
exclude deps/c-ares/libtool
include Makefile.ext
recursive-exclude deps/c-ares .deps .libs
recursive-exclude deps/libuv .deps .libs
recursive-exclude deps/libev .deps .libs

214
Makefile Normal file
View File

@ -0,0 +1,214 @@
# This file is renamed to "Makefile.ext" in release tarballs so that setup.py won't try to
# run it. If you want setup.py to run "make" automatically, rename it back to "Makefile".
# The pyvenv multiple runtime support is based on https://github.com/DRMacIver/hypothesis/blob/master/Makefile
PYTHON?=python${TRAVIS_PYTHON_VERSION}
CYTHON?=cython
export PATH:=$(BUILD_RUNTIMES)/snakepit:$(TOOLS):$(PATH)
export LC_ALL=C.UTF-8
export GEVENT_RESOLVER_NAMESERVERS=8.8.8.8
clean:
rm -f src/gevent/libev/corecext.c src/gevent/libev/corecext.h
rm -f src/gevent/resolver/cares.c src/gevent/resolver/cares.h
rm -f src/gevent/_semaphore.c src/gevent/_semaphore.h
rm -f src/gevent/local.c src/gevent/local.h
rm -f src/gevent/*.so src/gevent/*.pyd src/gevent/libev/*.so src/gevent/libuv/*.so src/gevent/libev/*.pyd src/gevent/libuv/*.pyd
rm -rf src/gevent/libev/*.o src/gevent/libuv/*.o src/gevent/*.o
rm -rf src/gevent/__pycache__ src/greentest/__pycache__ src/greentest/greentest/__pycache__ src/gevent/libev/__pycache__
rm -rf src/gevent/*.pyc src/greentest/*.pyc src/gevent/libev/*.pyc
rm -rf htmlcov .coverage
rm -rf build
distclean: clean
rm -rf dist
rm -rf deps/libev/config.h deps/libev/config.log deps/libev/config.status deps/libev/.deps deps/libev/.libs
rm -rf deps/c-ares/config.h deps/c-ares/config.log deps/c-ares/config.status deps/c-ares/.deps deps/c-ares/.libs
doc:
cd doc && PYTHONPATH=.. make html
prospector:
which pylint
pylint --rcfile=.pylintrc gevent
# debugging
# pylint --rcfile=.pylintrc --init-hook="import sys, code; sys.excepthook = lambda exc, exc_type, tb: print(tb.tb_next.tb_next.tb_next.tb_next.tb_next.tb_next.tb_next.tb_next.tb_next.tb_next.tb_frame.f_locals['self'])" gevent src/greentest/* || true
# XXX: prospector is failing right now. I can't reproduce locally:
# https://travis-ci.org/gevent/gevent/jobs/345474139
# ${PYTHON} scripts/gprospector.py -X
lint: prospector
test_prelim:
@which ${PYTHON}
@${PYTHON} --version
@${PYTHON} -c 'import greenlet; print(greenlet, greenlet.__version__)'
@${PYTHON} -c 'import gevent.core; print(gevent.core.loop)'
@${PYTHON} -c 'import gevent.ares; print(gevent.ares)'
@make bench
# Folding from https://github.com/travis-ci/travis-rubies/blob/9f7962a881c55d32da7c76baefc58b89e3941d91/build.sh#L38-L44
basictest: test_prelim
@${PYTHON} scripts/travis.py fold_start basictest "Running basic tests"
GEVENT_RESOLVER=thread ${PYTHON} -mgevent.tests --config known_failures.py --quiet
@${PYTHON} scripts/travis.py fold_end basictest
alltest: basictest
@${PYTHON} scripts/travis.py fold_start ares "Running c-ares tests"
GEVENT_RESOLVER=ares ${PYTHON} -mgevent.tests --config known_failures.py --ignore tests_that_dont_use_resolver.txt --quiet
@${PYTHON} scripts/travis.py fold_end ares
@${PYTHON} scripts/travis.py fold_start dnspython "Running dnspython tests"
GEVENT_RESOLVER=dnspython ${PYTHON} -mgevent.tests --config known_failures.py --ignore tests_that_dont_use_resolver.txt --quiet
@${PYTHON} scripts/travis.py fold_end dnspython
# In the past, we included all test files that had a reference to 'subprocess'' somewhere in their
# text. The monkey-patched stdlib tests were specifically included here.
# However, we now always also test on AppVeyor (Windows) which only has GEVENT_FILE=thread,
# so we can save a lot of CI time by reducing the set and excluding the stdlib tests without
# losing any coverage.
@${PYTHON} scripts/travis.py fold_start thread "Running GEVENT_FILE=thread tests"
cd src/gevent/tests && GEVENT_FILE=thread ${PYTHON} -mgevent.tests --config known_failures.py test__*subprocess*.py --quiet
@${PYTHON} scripts/travis.py fold_end thread
allbackendtest:
@${PYTHON} scripts/travis.py fold_start default "Testing default backend"
GEVENTTEST_COVERAGE=1 make alltest
@${PYTHON} scripts/travis.py fold_end default
GEVENTTEST_COVERAGE=1 make cffibackendtest
# because we set parallel=true, each run produces new and different coverage files; they all need
# to be combined
make coverage_combine
cffibackendtest:
@${PYTHON} scripts/travis.py fold_start libuv "Testing libuv backend"
GEVENT_LOOP=libuv make alltest
@${PYTHON} scripts/travis.py fold_end libuv
@${PYTHON} scripts/travis.py fold_start libev "Testing libev CFFI backend"
GEVENT_LOOP=libev-cffi make alltest
@${PYTHON} scripts/travis.py fold_end libev
leaktest: test_prelim
@${PYTHON} scripts/travis.py fold_start leaktest "Running leak tests"
GEVENT_RESOLVER=thread GEVENTTEST_LEAKCHECK=1 ${PYTHON} -mgevent.tests --config known_failures.py --quiet --ignore tests_that_dont_do_leakchecks.txt
@${PYTHON} scripts/travis.py fold_end leaktest
@${PYTHON} scripts/travis.py fold_start default "Testing default backend pure python"
PURE_PYTHON=1 GEVENTTEST_COVERAGE=1 make basictest
@${PYTHON} scripts/travis.py fold_end default
bench:
${PYTHON} benchmarks/bench_sendall.py --loops 3 --processes 2 --values 2 --warmups 2 --quiet
travis_test_linters:
make lint
make leaktest
make cffibackendtest
coverage_combine:
coverage combine .
coverage report -i
-coveralls
.PHONY: clean doc prospector lint travistest travis
# Managing runtimes
BUILD_RUNTIMES?=$(PWD)/.runtimes
PY278=$(BUILD_RUNTIMES)/snakepit/python2.7.8
PY27=$(BUILD_RUNTIMES)/snakepit/python2.7.15
PY34=$(BUILD_RUNTIMES)/snakepit/python3.4.8
PY35=$(BUILD_RUNTIMES)/snakepit/python3.5.5
PY36=$(BUILD_RUNTIMES)/snakepit/python3.6.7
PY37=$(BUILD_RUNTIMES)/snakepit/python3.7.1
PYPY=$(BUILD_RUNTIMES)/snakepit/pypy600
PYPY3=$(BUILD_RUNTIMES)/snakepit/pypy3.5_600
TOOLS=$(BUILD_RUNTIMES)/tools
TOX=$(TOOLS)/tox
TOOL_VIRTUALENV=$(BUILD_RUNTIMES)/virtualenvs/tools
ISORT_VIRTUALENV=$(BUILD_RUNTIMES)/virtualenvs/isort
TOOL_PYTHON=$(TOOL_VIRTUALENV)/bin/python
TOOL_PIP=$(TOOL_VIRTUALENV)/bin/pip
TOOL_INSTALL=$(TOOL_PIP) install --upgrade
$(PY27):
scripts/install.sh 2.7
$(PY34):
scripts/install.sh 3.4
$(PY35):
scripts/install.sh 3.5
$(PY36):
scripts/install.sh 3.6
$(PY37):
scripts/install.sh 3.7
$(PYPY):
scripts/install.sh pypy
$(PYPY3):
scripts/install.sh pypy3
develop:
@${PYTHON} scripts/travis.py fold_start install "Installing gevent"
@echo python is at `which $(PYTHON)`
# First install a newer pip so that it can use the wheel cache
# (only needed until travis upgrades pip to 7.x; note that the 3.5
# environment uses pip 7.1 by default)
${PYTHON} -m pip install -U pip setuptools
# Then start installing our deps so they can be cached. Note that use of --build-options / --global-options / --install-options
# disables the cache.
# We need wheel>=0.26 on Python 3.5. See previous revisions.
time ${PYTHON} -m pip install -U --upgrade-strategy=eager -r ci-requirements.txt
GEVENTSETUP_EV_VERIFY=3 time ${PYTHON} -m pip install -U --upgrade-strategy=eager -e .[test,dnspython,events]
${PYTHON} -m pip freeze
ccache -s
@${PYTHON} scripts/travis.py fold_end install
test-py27: $(PY27)
PYTHON=python2.7.15 PATH=$(BUILD_RUNTIMES)/versions/python2.7.15/bin:$(PATH) make develop leaktest cffibackendtest coverage_combine
test-py34: $(PY34)
PYTHON=python3.4.8 PATH=$(BUILD_RUNTIMES)/versions/python3.4.8/bin:$(PATH) make develop basictest
test-py35: $(PY35)
PYTHON=python3.5.5 PATH=$(BUILD_RUNTIMES)/versions/python3.5.5/bin:$(PATH) GEVENTTEST_COVERAGE=1 make develop basictest coverage_combine
test-py36: $(PY36)
PYTHON=python3.6.7 PATH=$(BUILD_RUNTIMES)/versions/python3.6.7/bin:$(PATH) make develop lint basictest
test-py37: $(PY37)
LD_LIBRARY_PATH=$(BUILD_RUNTIMES)/versions/python3.7.1/openssl/lib PYTHON=python3.7.1 PATH=$(BUILD_RUNTIMES)/versions/python3.7.1/bin:$(PATH) make develop leaktest cffibackendtest coverage_combine
test-pypy: $(PYPY)
PYTHON=$(PYPY) PATH=$(BUILD_RUNTIMES)/versions/pypy600/bin:$(PATH) make develop cffibackendtest
test-pypy3: $(PYPY3)
PYTHON=$(PYPY3) PATH=$(BUILD_RUNTIMES)/versions/pypy3.5_600/bin:$(PATH) make develop basictest
test-py27-noembed: $(PY27)
@python2.7.15 scripts/travis.py fold_start conf_libev "Configuring libev"
cd deps/libev && ./configure --disable-dependency-tracking && make
@python2.7.15 scripts/travis.py fold_end conf_libev
@python2.7.15 scripts/travis.py fold_start conf_cares "Configuring cares"
cd deps/c-ares && ./configure --disable-dependency-tracking && make
@python2.7.15 scripts/travis.py fold_end conf_cares
@python2.7.15 scripts/travis.py fold_start conf_libuv "Configuring libuv"
cd deps/libuv && ./autogen.sh && ./configure --disable-static && make
@python2.7.15 scripts/travis.py fold_end conf_libuv
CPPFLAGS="-Ideps/libev -Ideps/c-ares -Ideps/libuv/include" LDFLAGS="-Ldeps/libev/.libs -Ldeps/c-ares/.libs -Ldeps/libuv/.libs" LD_LIBRARY_PATH="$(PWD)/deps/libev/.libs:$(PWD)/deps/c-ares/.libs:$(PWD)/deps/libuv/.libs" EMBED=0 GEVENT_LOOP=libev-cext PYTHON=python2.7.15 PATH=$(BUILD_RUNTIMES)/versions/python2.7.15/bin:$(PATH) make develop basictest

94
NOTICE Normal file
View File

@ -0,0 +1,94 @@
gevent is licensed under the MIT license. See the LICENSE file for the
complete license.
Portions of this software may have other licenses.
=============================================
greentest/2.7
greentest/2.7.8
greentest/2.7pypy
greentest/3.3
greentest/3.4
greentest/3.5
-----------------
Copyright (c) 2001-2016 Python Software Foundation; All Rights Reserved
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001-2016 Python Software Foundation; All Rights
Reserved" are retained in Python alone or in any derivative version prepared
by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
============================================
gevent/libuv/_corecffi_source.c
gevent/libuv/_corecffi_cdef.c
Originally based on code from https://github.com/veegee/guv
Copyright (c) 2014 V G
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.
===========================================

27
README.rst Normal file
View File

@ -0,0 +1,27 @@
========
gevent
========
.. image:: https://travis-ci.org/gevent/gevent.svg?branch=master
:target: https://travis-ci.org/gevent/gevent
.. image:: https://ci.appveyor.com/api/projects/status/q4kl21ng2yo2ixur?svg=true
:target: https://ci.appveyor.com/project/denik/gevent
.. image:: https://coveralls.io/repos/gevent/gevent/badge.svg?branch=master&service=github
:target: https://coveralls.io/github/gevent/gevent?branch=master
.. include:: doc/_about.rst
Read the documentation online at http://www.gevent.org.
Post feedback and issues on the `bug tracker`_, `mailing list`_, blog_
and `twitter (@gevent)`_.
.. include:: doc/install.rst
.. _bug tracker: https://github.com/gevent/gevent/wiki/Projects
.. _mailing list: http://groups.google.com/group/gevent
.. _blog: http://blog.gevent.org
.. _twitter (@gevent): http://twitter.com/gevent

1
TODO Normal file
View File

@ -0,0 +1 @@
The issue tracker is hosted at https://github.com/gevent/gevent/issues

120
_setupares.py Normal file
View File

@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-
"""
setup helpers for c-ares.
"""
from __future__ import print_function, absolute_import, division
import os
import os.path
import shutil
import sys
from _setuputils import Extension
import distutils.sysconfig # to get CFLAGS to pass into c-ares configure script pylint:disable=import-error
from _setuputils import WIN
from _setuputils import quoted_dep_abspath
from _setuputils import system
from _setuputils import make_universal_header
from _setuputils import should_embed
from _setuputils import LIBRARIES
from _setuputils import DEFINE_MACROS
from _setuputils import glob_many
from _setuputils import dep_abspath
from _setuputils import RUNNING_ON_CI
from _setuputils import RUNNING_FROM_CHECKOUT
from _setuputils import cythonize1
CARES_EMBED = should_embed('c-ares')
# See #616, trouble building for a 32-bit python against a 64-bit platform
_config_vars = distutils.sysconfig.get_config_var("CFLAGS")
if _config_vars and "m32" in _config_vars:
_m32 = 'CFLAGS="' + os.getenv('CFLAGS', '') + ' -m32" '
else:
_m32 = ''
# Use -r, not -e, for support of old solaris. See
# https://github.com/gevent/gevent/issues/777
ares_configure_command = ' '.join([
"(cd ", quoted_dep_abspath('c-ares'),
" && if [ -r ares_build.h ]; then cp ares_build.h ares_build.h.orig; fi ",
" && sh ./configure --disable-dependency-tracking " + _m32 + "CONFIG_COMMANDS= ",
" && cp ares_config.h ares_build.h \"$OLDPWD\" ",
" && cat ares_build.h ",
" && if [ -r ares_build.h.orig ]; then mv ares_build.h.orig ares_build.h; fi)",
"> configure-output.txt"])
def configure_ares(bext, ext):
print("Embedding c-ares", bext, ext)
bdir = os.path.join(bext.build_temp, 'c-ares')
ext.include_dirs.insert(0, bdir)
print("Inserted ", bdir, "in include dirs", ext.include_dirs)
if not os.path.isdir(bdir):
os.makedirs(bdir)
if WIN:
src = "deps\\c-ares\\ares_build.h.dist"
dest = os.path.join(bdir, "ares_build.h")
print("Copying %r to %r" % (src, dest))
shutil.copy(src, dest)
return
cwd = os.getcwd()
os.chdir(bdir)
try:
if os.path.exists('ares_config.h') and os.path.exists('ares_build.h'):
return
try:
system(ares_configure_command)
except:
with open('configure-output.txt', 'r') as t:
print(t.read(), file=sys.stderr)
raise
if sys.platform == 'darwin':
make_universal_header('ares_build.h', 'CARES_SIZEOF_LONG')
make_universal_header('ares_config.h', 'SIZEOF_LONG', 'SIZEOF_SIZE_T', 'SIZEOF_TIME_T')
finally:
os.chdir(cwd)
ARES = Extension(name='gevent.resolver.cares',
sources=['src/gevent/resolver/cares.pyx'],
include_dirs=['src/gevent/resolver'] + [dep_abspath('c-ares')] if CARES_EMBED else [],
libraries=list(LIBRARIES),
define_macros=list(DEFINE_MACROS),
depends=glob_many('src/gevent/resolver/dnshelper.c',
'src/gevent/resolver/cares_*.[ch]'))
ares_required = RUNNING_ON_CI and RUNNING_FROM_CHECKOUT
ARES.optional = not ares_required
if CARES_EMBED:
ARES.sources += glob_many('deps/c-ares/*.c')
# Strip the standalone binaries that would otherwise
# cause linking issues
for bin_c in ('acountry', 'adig', 'ahost'):
ARES.sources.remove('deps/c-ares' + os.sep + bin_c + '.c')
ARES.configure = configure_ares
if WIN:
ARES.libraries += ['advapi32']
ARES.define_macros += [('CARES_STATICLIB', '')]
else:
ARES.define_macros += [('HAVE_CONFIG_H', '')]
if sys.platform != 'darwin':
ARES.libraries += ['rt']
ARES.define_macros += [('CARES_EMBED', '1')]
else:
ARES.libraries.append('cares')
ARES.define_macros += [('HAVE_NETDB_H', '')]
ARES.configure = lambda bext, ext: print("c-ares not embedded, not configuring", bext, ext)
ARES = cythonize1(ARES)

94
_setuplibev.py Normal file
View File

@ -0,0 +1,94 @@
# -*- coding: utf-8 -*-
"""
setup helpers for libev.
"""
from __future__ import print_function, absolute_import, division
import sys
import os.path
from _setuputils import Extension
from _setuputils import system
from _setuputils import quoted_dep_abspath
from _setuputils import WIN
from _setuputils import make_universal_header
from _setuputils import LIBRARIES
from _setuputils import DEFINE_MACROS
from _setuputils import glob_many
from _setuputils import dep_abspath
from _setuputils import should_embed
from _setuputils import cythonize1
LIBEV_EMBED = should_embed('libev')
# Configure libev in place; but cp the config.h to the old directory;
# if we're building a CPython extension, the old directory will be
# the build/temp.XXX/libev/ directory. If we're building from a
# source checkout on pypy, OLDPWD will be the location of setup.py
# and the PyPy branch will clean it up.
libev_configure_command = ' '.join([
"(cd ", quoted_dep_abspath('libev'),
" && sh ./configure ",
" && cp config.h \"$OLDPWD\"",
")",
'> configure-output.txt'
])
def configure_libev(bext, ext):
if WIN:
return
bdir = os.path.join(bext.build_temp, 'libev')
ext.include_dirs.insert(0, bdir)
if not os.path.isdir(bdir):
os.makedirs(bdir)
cwd = os.getcwd()
os.chdir(bdir)
try:
if os.path.exists('config.h'):
return
system(libev_configure_command)
if sys.platform == 'darwin':
make_universal_header('config.h',
'SIZEOF_LONG', 'SIZEOF_SIZE_T', 'SIZEOF_TIME_T')
finally:
os.chdir(cwd)
CORE = Extension(name='gevent.libev.corecext',
sources=[
'src/gevent/libev/corecext.pyx',
'src/gevent/libev/callbacks.c',
],
include_dirs=['src/gevent/libev'] + [dep_abspath('libev')] if LIBEV_EMBED else [],
libraries=list(LIBRARIES),
define_macros=list(DEFINE_MACROS),
depends=glob_many('src/gevent/libev/callbacks.*',
'src/gevent/libev/stathelper.c',
'src/gevent/libev/libev*.h',
'deps/libev/*.[ch]'))
if WIN:
CORE.define_macros.append(('EV_STANDALONE', '1'))
# QQQ libev can also use -lm, however it seems to be added implicitly
if LIBEV_EMBED:
CORE.define_macros += [('LIBEV_EMBED', '1'),
('EV_COMMON', ''), # we don't use void* data
# libev watchers that we don't use currently:
('EV_CLEANUP_ENABLE', '0'),
('EV_EMBED_ENABLE', '0'),
("EV_PERIODIC_ENABLE", '0')]
CORE.configure = configure_libev
if sys.platform == "darwin":
os.environ["CPPFLAGS"] = ("%s %s" % (os.environ.get("CPPFLAGS", ""), "-U__llvm__")).lstrip()
if os.environ.get('GEVENTSETUP_EV_VERIFY') is not None:
CORE.define_macros.append(('EV_VERIFY', os.environ['GEVENTSETUP_EV_VERIFY']))
else:
CORE.libraries.append('ev')
CORE = cythonize1(CORE)

244
_setuputils.py Normal file
View File

@ -0,0 +1,244 @@
# -*- coding: utf-8 -*-
"""
gevent build utilities.
"""
from __future__ import print_function, absolute_import, division
import re
import os
import os.path
import sys
from subprocess import check_call
from glob import glob
from setuptools import Extension as _Extension
from setuptools.command.build_ext import build_ext
THIS_DIR = os.path.dirname(__file__)
## Exported configurations
PYPY = hasattr(sys, 'pypy_version_info')
WIN = sys.platform.startswith('win')
RUNNING_ON_TRAVIS = os.environ.get('TRAVIS')
RUNNING_ON_APPVEYOR = os.environ.get('APPVEYOR')
RUNNING_ON_CI = RUNNING_ON_TRAVIS or RUNNING_ON_APPVEYOR
RUNNING_FROM_CHECKOUT = os.path.isdir(os.path.join(THIS_DIR, ".git"))
LIBRARIES = []
DEFINE_MACROS = []
if WIN:
LIBRARIES += ['ws2_32']
DEFINE_MACROS += [('FD_SETSIZE', '1024'), ('_WIN32', '1')]
### File handling
def quoted_abspath(*segments):
return '"' + os.path.abspath(os.path.join(*segments)) + '"'
def read(*names):
"""Read a file path relative to this file."""
with open(os.path.join(THIS_DIR, *names)) as f:
return f.read()
def read_version(name="src/gevent/__init__.py"):
contents = read(name)
version = re.search(r"__version__\s*=\s*'(.*)'", contents, re.M).group(1)
assert version, "could not read version"
return version
def dep_abspath(depname, *extra):
return os.path.abspath(os.path.join('deps', depname, *extra))
def quoted_dep_abspath(depname):
return quoted_abspath(dep_abspath(depname))
def glob_many(*globs):
"""
Return a list of all the glob patterns expanded.
"""
result = []
for pattern in globs:
result.extend(glob(pattern))
return sorted(result)
## Configuration
def _parse_environ(key):
value = os.environ.get(key)
if not value:
return
value = value.lower().strip()
if value in ('1', 'true', 'on', 'yes'):
return True
if value in ('0', 'false', 'off', 'no'):
return False
raise ValueError('Environment variable %r has invalid value %r. '
'Please set it to 1, 0 or an empty string' % (key, value))
IGNORE_CFFI = _parse_environ("GEVENT_NO_CFFI_BUILD")
SKIP_LIBUV = _parse_environ('GEVENT_NO_LIBUV_BUILD')
def _get_config_value(key, defkey, path=None):
"""
Find a boolean value, configured in the environment at *key* or
*defkey* (typically, *defkey* will be shared by several calls). If
those don't exist, then check for the existence of *path* and return
that (if path is given)
"""
value = _parse_environ(key)
if value is None:
value = _parse_environ(defkey)
if value is not None:
return value
return os.path.exists(path) if path is not None else False
def should_embed(dep_name):
"""
Check the configuration for the dep_name and see if it
should be embedded. Environment keys are derived from the
dep name: libev becomes LIBEV_EMBED and c-ares becomes CARES_EMBED.
"""
path = dep_abspath(dep_name)
defkey = 'EMBED'
key = dep_name.replace('-', '').upper() + '_' + defkey
return _get_config_value(key, defkey, path)
## Headers
def make_universal_header(filename, *defines):
defines = [('#define %s ' % define, define) for define in defines]
with open(filename, 'r') as f:
lines = f.read().split('\n')
ifdef = 0
with open(filename, 'w') as f:
for line in lines:
if line.startswith('#ifdef'):
ifdef += 1
elif line.startswith('#endif'):
ifdef -= 1
elif not ifdef:
for prefix, define in defines:
if line.startswith(prefix):
line = '#ifdef __LP64__\n#define %s 8\n#else\n#define %s 4\n#endif' % (define, define)
break
print(line, file=f)
# Processes
def _system(cmd, cwd=None, env=None, **kwargs):
sys.stdout.write('Running %r in %s\n' % (cmd, cwd or os.getcwd()))
sys.stdout.flush()
if 'shell' not in kwargs:
kwargs['shell'] = True
env = env or os.environ.copy()
if env.get('CC', '').startswith('ccache '):
# Running configure scripts under ccache just adds overhead.
env['CC'] = env['CC'][7:]
return check_call(cmd, cwd=cwd, env=env, **kwargs)
def system(cmd, cwd=None, env=None, **kwargs):
if _system(cmd, cwd=cwd, env=env, **kwargs):
sys.exit(1)
# Cython
# Based on code from
# http://cython.readthedocs.io/en/latest/src/reference/compilation.html#distributing-cython-modules
def _dummy_cythonize(extensions, **_kwargs):
for extension in extensions:
sources = []
for sfile in extension.sources:
path, ext = os.path.splitext(sfile)
if ext in ('.pyx', '.py'):
ext = '.c'
sfile = path + ext
sources.append(sfile)
extension.sources[:] = sources
return extensions
try:
from Cython.Build import cythonize
except ImportError:
# The .c files had better already exist.
cythonize = _dummy_cythonize
def cythonize1(ext):
try:
new_ext = cythonize(
[ext],
include_path=['src/gevent', 'src/gevent/libev', 'src/gevent/resolver'],
annotate=True,
compiler_directives={
'language_level': '3str',
'always_allow_keywords': False,
'infer_types': True,
'nonecheck': False,
}
)[0]
except ValueError:
# 'invalid literal for int() with base 10: '3str'
# This is seen when an older version of Cython is installed.
# It's a bit of a chicken-and-egg, though, because installing
# from dev-requirements first scans this egg for its requirements
# before doing any updates.
import traceback
traceback.print_exc()
new_ext = _dummy_cythonize([ext])[0]
for optional_attr in ('configure', 'optional'):
if hasattr(ext, optional_attr):
setattr(new_ext, optional_attr,
getattr(ext, optional_attr))
return new_ext
## Distutils extensions
class BuildFailed(Exception):
pass
from distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError # pylint:disable=no-name-in-module,import-error
ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError, IOError)
class ConfiguringBuildExt(build_ext):
def gevent_prepare(self, ext):
configure = getattr(ext, 'configure', None)
if configure:
configure(self, ext)
def build_extension(self, ext):
self.gevent_prepare(ext)
try:
result = build_ext.build_extension(self, ext)
except ext_errors:
if getattr(ext, 'optional', False):
raise BuildFailed()
else:
raise
return result
class Extension(_Extension):
# This class exists currently mostly to make pylint
# happy in terms of attributes we use.
def __init__(self, *args, **kwargs):
self.libraries = []
self.define_macros = []
# Python 2 has this as an old-style class for some reason
# so super() doesn't work.
_Extension.__init__(self, *args, **kwargs) # pylint:disable=no-member,non-parent-init-called

187
appveyor.yml Normal file
View File

@ -0,0 +1,187 @@
clone_depth: 50
environment:
global:
# SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the
# /E:ON and /V:ON options are not enabled in the batch script interpreter
# See: http://stackoverflow.com/a/13751649/163740
CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\appveyor\\run_with_env.cmd"
# Use a fixed hash seed for reproducability
PYTHONHASHSEED: 8675309
matrix:
# Pre-installed Python versions, which Appveyor may upgrade to
# a later point release.
# 64-bit
- PYTHON: "C:\\Python37-x64"
PYTHON_VERSION: "3.7.x"
PYTHON_ARCH: "64"
PYTHON_EXE: python
- PYTHON: "C:\\Python27-x64"
PYTHON_VERSION: "2.7.x" # currently 2.7.13
PYTHON_ARCH: "64"
PYTHON_EXE: python
- PYTHON: "C:\\Python36-x64"
PYTHON_VERSION: "3.6.x" # currently 3.6.0
PYTHON_ARCH: "64"
PYTHON_EXE: python
- PYTHON: "C:\\Python35-x64"
PYTHON_VERSION: "3.5.x" # currently 3.5.2
PYTHON_ARCH: "64"
PYTHON_EXE: python
- PYTHON: "C:\\Python34-x64"
PYTHON_VERSION: "3.4.x" # currently 3.4.4
PYTHON_ARCH: "64"
PYTHON_EXE: python
# 32-bit
- PYTHON: "C:\\pypy2-v6.0.0-win32"
PYTHON_ID: "pypy"
PYTHON_EXE: pypy
PYTHON_VERSION: "2.7.x"
PYTHON_ARCH: "32"
# 32-bit, wheel only (no testing)
- PYTHON: "C:\\Python37"
PYTHON_VERSION: "3.7.x"
PYTHON_ARCH: "32"
PYTHON_EXE: python
GWHEEL_ONLY: true
- PYTHON: "C:\\Python36"
PYTHON_VERSION: "3.6.x" # currently 3.6.3
PYTHON_ARCH: "32"
PYTHON_EXE: python
GWHEEL_ONLY: true
- PYTHON: "C:\\Python35"
PYTHON_VERSION: "3.5.x" # currently 3.5.2
PYTHON_ARCH: "32"
PYTHON_EXE: python
GWHEEL_ONLY: true
- PYTHON: "C:\\Python34"
PYTHON_VERSION: "3.4.x" # currently 3.4.3
PYTHON_ARCH: "32"
PYTHON_EXE: python
GWHEEL_ONLY: true
- PYTHON: "C:\\Python27"
PYTHON_VERSION: "2.7.x" # currently 2.7.13
PYTHON_ARCH: "32"
PYTHON_EXE: python
GWHEEL_ONLY: true
# Also test a Python version not pre-installed
# See: https://github.com/ogrisel/python-appveyor-demo/issues/10
# - PYTHON: "C:\\Python266"
# PYTHON_VERSION: "2.6.6"
# PYTHON_ARCH: "32"
# PYTHON_EXE: python
matrix:
allow_failures:
- PYTHON_ID: "pypy"
install:
# If there is a newer build queued for the same PR, cancel this one.
# The AppVeyor 'rollout builds' option is supposed to serve the same
# purpose but it is problematic because it tends to cancel builds pushed
# directly to master instead of just PR builds (or the converse).
# credits: JuliaLang developers.
- ps: if ($env:APPVEYOR_PULL_REQUEST_NUMBER -and $env:APPVEYOR_BUILD_NUMBER -ne ((Invoke-RestMethod `
https://ci.appveyor.com/api/projects/$env:APPVEYOR_ACCOUNT_NAME/$env:APPVEYOR_PROJECT_SLUG/history?recordsNumber=50).builds | `
Where-Object pullRequestId -eq $env:APPVEYOR_PULL_REQUEST_NUMBER)[0].buildNumber) { `
throw "There are newer queued builds for this pull request, failing early." }
- ECHO "Filesystem root:"
- ps: "ls \"C:/\""
- ECHO "Installed SDKs:"
- ps: "ls \"C:/Program Files/Microsoft SDKs/Windows\""
# Install Python (from the official .msi of http://python.org) and pip when
# not already installed.
# PyPy portion based on https://github.com/wbond/asn1crypto/blob/master/appveyor.yml
- ps:
$env:PYTMP = "${env:TMP}\py";
if (!(Test-Path "$env:PYTMP")) {
New-Item -ItemType directory -Path "$env:PYTMP" | Out-Null;
}
if ("${env:PYTHON_ID}" -eq "pypy") {
if (!(Test-Path "${env:PYTMP}\pypy2-v6.0.0-win32.zip")) {
(New-Object Net.WebClient).DownloadFile('https://bitbucket.org/pypy/pypy/downloads/pypy2-v6.0.0-win32.zip', "${env:PYTMP}\pypy2-v6.0.0-win32.zip");
}
7z x -y "${env:PYTMP}\pypy2-v6.0.0-win32.zip" -oC:\ | Out-Null;
& "${env:PYTHON}\pypy.exe" "-mensurepip";
}
elseif (-not(Test-Path($env:PYTHON))) {
& appveyor\install.ps1;
}
# Prepend newly installed Python to the PATH of this build (this cannot be
# done from inside the powershell script as it would require to restart
# the parent CMD process).
- "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PYTHON%\\bin;%PATH%"
- "SET PYEXE=%PYTHON%\\%PYTHON_EXE%.exe"
# Check that we have the expected version and architecture for Python
- "%PYEXE% --version"
- "%PYEXE% -c \"import struct; print(struct.calcsize('P') * 8)\""
# Upgrade to the latest version of pip to avoid it displaying warnings
# about it being out of date.
- "%CMD_IN_ENV% %PYEXE% -m pip install --disable-pip-version-check --user --upgrade pip"
# Install the build dependencies of the project. If some dependencies contain
# compiled extensions and are not provided as pre-built wheel packages,
# pip will build them from source using the MSVC compiler matching the
# target Python version and architecture
- "%CMD_IN_ENV% %PYEXE% -m pip install -U --upgrade-strategy=eager -r ci-requirements.txt"
- ps: "if(Test-Path(\"${env:PYTHON}\\bin\")) {ls ${env:PYTHON}\\bin;}"
- ps: "if(Test-Path(\"${env:PYTHON}\\Scripts\")) {ls ${env:PYTHON}\\Scripts;}"
cache:
- "%TMP%\\py\\"
- '%LOCALAPPDATA%\pip\Cache'
build_script:
# Build the compiled extension
- "%CMD_IN_ENV% %PYEXE% -m pip wheel . -w dist"
- ps: "ls dist"
# Now install the wheel.
# I couldn't get wildcards to work for pip install, so stuff it
# into a variable, using python to glob.
- "%PYEXE% -c \"import glob; print(glob.glob('dist/gevent*whl')[0])\" > whl.txt"
- set /p PYWHL=<whl.txt
- if not "%GWHEEL_ONLY%"=="true" %PYEXE% -m pip install -U --upgrade-strategy=eager %PYWHL%[test,events,dnspython]
test_script:
# Run the project tests
- if not "%GWHEEL_ONLY%"=="true" %PYEXE% -c "import gevent.core; print(gevent.core.loop)"
- if not "%GWHEEL_ONLY%"=="true" %PYEXE% -c "import gevent; print(gevent.config.settings['resolver'].get_options())"
- if not "%GWHEEL_ONLY%"=="true" %PYEXE% -mgevent.tests --config known_failures.py --quiet
after_test:
# We already built the wheel during build_script, because it's
# much faster to do that and install from the wheel than to
# rebuild it here
#- "%CMD_IN_ENV% %PYEXE% setup.py bdist_wheel bdist_wininst"
- ps: "ls dist"
artifacts:
# Archive the generated wheel package in the ci.appveyor.com build report.
- path: dist\gevent*whl
#on_success:
# - TODO: upload the content of dist/*.whl to a public wheelhouse
#

229
appveyor/install.ps1 Normal file
View File

@ -0,0 +1,229 @@
# Sample script to install Python and pip under Windows
# Authors: Olivier Grisel, Jonathan Helmus, Kyle Kastner, and Alex Willmer
# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
$MINICONDA_URL = "http://repo.continuum.io/miniconda/"
$BASE_URL = "https://www.python.org/ftp/python/"
$GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
$GET_PIP_PATH = "C:\get-pip.py"
$PYTHON_PRERELEASE_REGEX = @"
(?x)
(?<major>\d+)
\.
(?<minor>\d+)
\.
(?<micro>\d+)
(?<prerelease>[a-z]{1,2}\d+)
"@
function Download ($filename, $url) {
$webclient = New-Object System.Net.WebClient
$basedir = $pwd.Path + "\"
$filepath = $basedir + $filename
if (Test-Path $filename) {
Write-Host "Reusing" $filepath
return $filepath
}
# Download and retry up to 3 times in case of network transient errors.
Write-Host "Downloading" $filename "from" $url
$retry_attempts = 2
for ($i = 0; $i -lt $retry_attempts; $i++) {
try {
$webclient.DownloadFile($url, $filepath)
break
}
Catch [Exception]{
Start-Sleep 1
}
}
if (Test-Path $filepath) {
Write-Host "File saved at" $filepath
} else {
# Retry once to get the error message if any at the last try
$webclient.DownloadFile($url, $filepath)
}
return $filepath
}
function ParsePythonVersion ($python_version) {
if ($python_version -match $PYTHON_PRERELEASE_REGEX) {
return ([int]$matches.major, [int]$matches.minor, [int]$matches.micro,
$matches.prerelease)
}
$version_obj = [version]$python_version
return ($version_obj.major, $version_obj.minor, $version_obj.build, "")
}
function DownloadPython ($python_version, $platform_suffix) {
$major, $minor, $micro, $prerelease = ParsePythonVersion $python_version
if (($major -le 2 -and $micro -eq 0) `
-or ($major -eq 3 -and $minor -le 2 -and $micro -eq 0) `
) {
$dir = "$major.$minor"
$python_version = "$major.$minor$prerelease"
} else {
$dir = "$major.$minor.$micro"
}
if ($prerelease) {
if (($major -le 2) `
-or ($major -eq 3 -and $minor -eq 1) `
-or ($major -eq 3 -and $minor -eq 2) `
-or ($major -eq 3 -and $minor -eq 3) `
) {
$dir = "$dir/prev"
}
}
if (($major -le 2) -or ($major -le 3 -and $minor -le 4)) {
$ext = "msi"
if ($platform_suffix) {
$platform_suffix = ".$platform_suffix"
}
} else {
$ext = "exe"
if ($platform_suffix) {
$platform_suffix = "-$platform_suffix"
}
}
$filename = "python-$python_version$platform_suffix.$ext"
$url = "$BASE_URL$dir/$filename"
$filepath = Download $filename $url
return $filepath
}
function InstallPython ($python_version, $architecture, $python_home) {
Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home
if (Test-Path $python_home) {
Write-Host $python_home "already exists, skipping."
return $false
}
if ($architecture -eq "32") {
$platform_suffix = ""
} else {
$platform_suffix = "amd64"
}
$installer_path = DownloadPython $python_version $platform_suffix
$installer_ext = [System.IO.Path]::GetExtension($installer_path)
Write-Host "Installing $installer_path to $python_home"
$install_log = $python_home + ".log"
if ($installer_ext -eq '.msi') {
InstallPythonMSI $installer_path $python_home $install_log
} else {
InstallPythonEXE $installer_path $python_home $install_log
}
if (Test-Path $python_home) {
Write-Host "Python $python_version ($architecture) installation complete"
} else {
Write-Host "Failed to install Python in $python_home"
Get-Content -Path $install_log
Exit 1
}
}
function InstallPythonEXE ($exepath, $python_home, $install_log) {
$install_args = "/quiet InstallAllUsers=1 TargetDir=$python_home"
RunCommand $exepath $install_args
}
function InstallPythonMSI ($msipath, $python_home, $install_log) {
$install_args = "/qn /log $install_log /i $msipath TARGETDIR=$python_home"
$uninstall_args = "/qn /x $msipath"
RunCommand "msiexec.exe" $install_args
if (-not(Test-Path $python_home)) {
Write-Host "Python seems to be installed else-where, reinstalling."
RunCommand "msiexec.exe" $uninstall_args
RunCommand "msiexec.exe" $install_args
}
}
function RunCommand ($command, $command_args) {
Write-Host $command $command_args
Start-Process -FilePath $command -ArgumentList $command_args -Wait -Passthru
}
function InstallPip ($python_home) {
$pip_path = $python_home + "\Scripts\pip.exe"
$python_path = $python_home + "\python.exe"
if (-not(Test-Path $pip_path)) {
Write-Host "Installing pip..."
$webclient = New-Object System.Net.WebClient
$webclient.DownloadFile($GET_PIP_URL, $GET_PIP_PATH)
Write-Host "Executing:" $python_path $GET_PIP_PATH
& $python_path $GET_PIP_PATH
} else {
Write-Host "pip already installed."
}
}
function DownloadMiniconda ($python_version, $platform_suffix) {
if ($python_version -eq "3.4") {
$filename = "Miniconda3-3.5.5-Windows-" + $platform_suffix + ".exe"
} else {
$filename = "Miniconda-3.5.5-Windows-" + $platform_suffix + ".exe"
}
$url = $MINICONDA_URL + $filename
$filepath = Download $filename $url
return $filepath
}
function InstallMiniconda ($python_version, $architecture, $python_home) {
Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home
if (Test-Path $python_home) {
Write-Host $python_home "already exists, skipping."
return $false
}
if ($architecture -eq "32") {
$platform_suffix = "x86"
} else {
$platform_suffix = "x86_64"
}
$filepath = DownloadMiniconda $python_version $platform_suffix
Write-Host "Installing" $filepath "to" $python_home
$install_log = $python_home + ".log"
$args = "/S /D=$python_home"
Write-Host $filepath $args
Start-Process -FilePath $filepath -ArgumentList $args -Wait -Passthru
if (Test-Path $python_home) {
Write-Host "Python $python_version ($architecture) installation complete"
} else {
Write-Host "Failed to install Python in $python_home"
Get-Content -Path $install_log
Exit 1
}
}
function InstallMinicondaPip ($python_home) {
$pip_path = $python_home + "\Scripts\pip.exe"
$conda_path = $python_home + "\Scripts\conda.exe"
if (-not(Test-Path $pip_path)) {
Write-Host "Installing pip..."
$args = "install --yes pip"
Write-Host $conda_path $args
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru
} else {
Write-Host "pip already installed."
}
}
function main () {
InstallPython $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON
InstallPip $env:PYTHON
}
main

88
appveyor/run_with_env.cmd Normal file
View File

@ -0,0 +1,88 @@
:: To build extensions for 64 bit Python 3, we need to configure environment
:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of:
:: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1)
::
:: To build extensions for 64 bit Python 2, we need to configure environment
:: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of:
:: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0)
::
:: 32 bit builds, and 64-bit builds for 3.5 and beyond, do not require specific
:: environment configurations.
::
:: Note: this script needs to be run with the /E:ON and /V:ON flags for the
:: cmd interpreter, at least for (SDK v7.0)
::
:: More details at:
:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows
:: http://stackoverflow.com/a/13751649/163740
::
:: Author: Olivier Grisel
:: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
::
:: Notes about batch files for Python people:
::
:: Quotes in values are literally part of the values:
:: SET FOO="bar"
:: FOO is now five characters long: " b a r "
:: If you don't want quotes, don't include them on the right-hand side.
::
:: The CALL lines at the end of this file look redundant, but if you move them
:: outside of the IF clauses, they do not run properly in the SET_SDK_64==Y
:: case, I don't know why.
@ECHO OFF
SET COMMAND_TO_RUN=%*
SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows
SET WIN_WDK=c:\Program Files (x86)\Windows Kits\10\Include\wdf
:: Extract the major and minor versions, and allow for the minor version to be
:: more than 9. This requires the version number to have two dots in it.
SET MAJOR_PYTHON_VERSION=%PYTHON_VERSION:~0,1%
IF "%PYTHON_VERSION:~3,1%" == "." (
SET MINOR_PYTHON_VERSION=%PYTHON_VERSION:~2,1%
) ELSE (
SET MINOR_PYTHON_VERSION=%PYTHON_VERSION:~2,2%
)
:: Based on the Python version, determine what SDK version to use, and whether
:: to set the SDK for 64-bit.
IF %MAJOR_PYTHON_VERSION% == 2 (
SET WINDOWS_SDK_VERSION="v7.0"
SET SET_SDK_64=Y
) ELSE (
IF %MAJOR_PYTHON_VERSION% == 3 (
SET WINDOWS_SDK_VERSION="v7.1"
IF %MINOR_PYTHON_VERSION% LEQ 4 (
SET SET_SDK_64=Y
) ELSE (
SET SET_SDK_64=N
IF EXIST "%WIN_WDK%" (
:: See: https://connect.microsoft.com/VisualStudio/feedback/details/1610302/
REN "%WIN_WDK%" 0wdf
)
)
) ELSE (
ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%"
EXIT 1
)
)
IF %PYTHON_ARCH% == 64 (
IF %SET_SDK_64% == Y (
ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture
SET DISTUTILS_USE_SDK=1
SET MSSdk=1
"%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION%
"%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release
ECHO Executing: %COMMAND_TO_RUN%
call %COMMAND_TO_RUN% || EXIT 1
) ELSE (
ECHO Using default MSVC build environment for 64 bit architecture
ECHO Executing: %COMMAND_TO_RUN%
call %COMMAND_TO_RUN% || EXIT 1
)
) ELSE (
ECHO Using default MSVC build environment for 32 bit architecture
ECHO Executing: %COMMAND_TO_RUN%
call %COMMAND_TO_RUN% || EXIT 1
)

2
benchmarks/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
data/*.json
data/*/*.json

View File

@ -0,0 +1,108 @@
from __future__ import absolute_import, print_function, division
# Best run with dnsmasq configured as a caching nameserver
# with no timeouts and configured to point there via
# /etc/resolv.conf and GEVENT_RESOLVER_NAMESERVERS
# Remember to use --inherit-environ to make that work!
# dnsmasq -d --cache-size=100000 --local-ttl=1000000 --neg-ttl=10000000
# --max-ttl=100000000 --min-cache-ttl=10000000000 --no-poll --auth-ttl=100000000000
from gevent import monkey; monkey.patch_all()
import sys
import socket
import perf
import gevent
from zope.dottedname.resolve import resolve as drresolve
blacklist = {
22, 55, 68, 69, 72, 52, 94, 62, 54, 71, 73, 74, 34, 36,
83, 86, 79, 81, 98, 99, 120, 130, 152, 161, 165, 169,
172, 199, 205, 239, 235, 254, 256, 286, 299, 259, 229,
190, 185, 182, 173, 160, 158, 153, 139, 138, 131, 129,
127, 125, 116, 112, 110, 106,
}
RUN_COUNT = 15 if hasattr(sys, 'pypy_version_info') else 5
def quiet(f, n):
try:
f(n)
except socket.gaierror:
pass
def resolve_seq(res, count=10, begin=0):
for index in range(begin, count + begin):
if index in blacklist:
continue
try:
res.gethostbyname('x%s.com' % index)
except socket.gaierror:
pass
def resolve_par(res, count=10, begin=0):
gs = []
for index in range(begin, count + begin):
if index in blacklist:
continue
gs.append(gevent.spawn(quiet, res.gethostbyname, 'x%s.com' % index))
gevent.joinall(gs)
N = 300
def run_all(resolver_name, resolve):
res = drresolve('gevent.resolver.' + resolver_name + '.Resolver')
res = res()
# dnspython looks up cname aliases by default, but c-ares does not.
# dnsmasq can only cache one address with a given cname at a time,
# and many of our addresses clash on that, so dnspython is put at a
# severe disadvantage. We turn that off here.
res._getaliases = lambda hostname, family: []
if N > 150:
# 150 is the max concurrency in dnsmasq
count = N // 3
resolve(res, count=count)
resolve(res, count=count, begin=count)
resolve(res, count=count, begin=count * 2)
else:
resolve(res, count=N)
def main():
def worker_cmd(cmd, args):
cmd.extend(args.benchmark)
runner = perf.Runner(processes=5, values=3,
add_cmdline_args=worker_cmd)
all_names = 'dnspython', 'blocking', 'ares', 'thread'
runner.argparser.add_argument('benchmark',
nargs='*',
default='all',
choices=all_names + ('all',))
args = runner.parse_args()
if 'all' in args.benchmark or args.benchmark == 'all':
args.benchmark = ['all']
names = all_names
else:
names = args.benchmark
for name in names:
runner.bench_func(name + ' sequential',
run_all,
name, resolve_seq,
inner_loops=N)
runner.bench_func(name + ' parallel',
run_all,
name, resolve_par,
inner_loops=N)
if __name__ == '__main__':
main()

118
benchmarks/bench_hub.py Normal file
View File

@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-
"""
Benchmarks for hub primitive operations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import perf
from perf import perf_counter
import gevent
from greenlet import greenlet
from greenlet import getcurrent
N = 1000
def bench_switch():
class Parent(type(gevent.get_hub())):
def run(self):
parent = self.parent
for _ in range(N):
parent.switch()
def child():
parent = getcurrent().parent
# Back to the hub, which in turn goes
# back to the main greenlet
for _ in range(N):
parent.switch()
hub = Parent(None, None)
child_greenlet = greenlet(child, hub)
for _ in range(N):
child_greenlet.switch()
def bench_wait_ready():
class Watcher(object):
def start(self, cb, obj):
# Immediately switch back to the waiter, mark as ready
cb(obj)
def stop(self):
pass
watcher = Watcher()
hub = gevent.get_hub()
for _ in range(1000):
hub.wait(watcher)
def bench_cancel_wait():
class Watcher(object):
active = True
callback = object()
def close(self):
pass
watcher = Watcher()
hub = gevent.get_hub()
loop = hub.loop
for _ in range(1000):
# Schedule all the callbacks.
hub.cancel_wait(watcher, None, True)
# Run them!
for cb in loop._callbacks:
if cb.callback:
cb.callback(*cb.args)
cb.stop() # so the real loop won't do it
# destroy the loop so we don't keep building these functions
# up
hub.destroy(True)
def bench_wait_func_ready():
from gevent.hub import wait
class ToWatch(object):
def rawlink(self, cb):
cb(self)
watched_objects = [ToWatch() for _ in range(N)]
t0 = perf_counter()
wait(watched_objects)
return perf_counter() - t0
def main():
runner = perf.Runner()
runner.bench_func('multiple wait ready',
bench_wait_func_ready,
inner_loops=N)
runner.bench_func('wait ready',
bench_wait_ready,
inner_loops=N)
runner.bench_func('cancel wait',
bench_cancel_wait,
inner_loops=N)
runner.bench_func('switch',
bench_switch,
inner_loops=N)
if __name__ == '__main__':
main()

88
benchmarks/bench_local.py Normal file
View File

@ -0,0 +1,88 @@
# -*- coding: utf-8 -*-
"""
Benchmarks for thread locals.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import perf
from gevent.local import local as glocal
from threading import local as nlocal
class GLocalSub(glocal):
pass
class NativeSub(nlocal):
pass
benchmarks = []
def _populate(l):
for i in range(10):
setattr(l, 'attr' + str(i), i)
def bench_getattr(loops, local):
t0 = perf.perf_counter()
for _ in range(loops):
# pylint:disable=pointless-statement
local.attr0
local.attr1
local.attr2
local.attr3
local.attr4
local.attr5
local.attr6
local.attr7
local.attr8
local.attr9
return perf.perf_counter() - t0
def bench_setattr(loops, local):
t0 = perf.perf_counter()
for _ in range(loops):
local.attr0 = 0
local.attr1 = 1
local.attr2 = 2
local.attr3 = 3
local.attr4 = 4
local.attr5 = 5
local.attr6 = 6
local.attr7 = 7
local.attr8 = 8
local.attr9 = 9
return perf.perf_counter() - t0
def main():
runner = perf.Runner()
for name, obj in (('gevent', glocal()),
('gevent sub', GLocalSub()),
('native', nlocal()),
('native sub', NativeSub())):
_populate(obj)
benchmarks.append(
runner.bench_time_func('getattr ' + name,
bench_getattr,
obj,
inner_loops=10))
benchmarks.append(
runner.bench_time_func('setattr ' + name,
bench_setattr,
obj,
inner_loops=10))
if __name__ == '__main__':
main()

16
benchmarks/bench_pool.py Normal file
View File

@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
"""
Benchmarks for greenlet pool.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gevent.pool
import bench_threadpool
bench_threadpool.ThreadPool = gevent.pool.Pool
if __name__ == '__main__':
bench_threadpool.main()

101
benchmarks/bench_queue.py Normal file
View File

@ -0,0 +1,101 @@
# -*- coding: utf-8 -*-
"""
Benchmarks for gevent.queue
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import perf
import gevent
from gevent import queue
N = 1000
def _b_no_block(q):
for i in range(N):
q.put(i)
for i in range(N):
j = q.get()
assert i == j, (i, j)
def bench_unbounded_queue_noblock(kind=queue.UnboundQueue):
_b_no_block(kind())
def bench_bounded_queue_noblock(kind=queue.Queue):
_b_no_block(kind(N + 1))
def bench_bounded_queue_block(kind=queue.Queue, hub=False):
q = kind(1)
def get():
for i in range(N):
j = q.get()
assert i == j
return "Finished"
# Run putters in the main greenlet
g = gevent.spawn(get)
if not hub:
for i in range(N):
q.put(i)
else:
# putters in the hub
def put():
assert gevent.getcurrent() is gevent.get_hub()
for i in range(N):
q.put(i)
h = gevent.get_hub()
h.loop.run_callback(put)
h.join()
g.join()
assert g.value == 'Finished'
def main():
runner = perf.Runner()
runner.bench_func('bench_unbounded_queue_noblock',
bench_unbounded_queue_noblock,
inner_loops=N)
runner.bench_func('bench_bounded_queue_noblock',
bench_bounded_queue_noblock,
inner_loops=N)
runner.bench_func('bench_bounded_queue_block',
bench_bounded_queue_block,
inner_loops=N)
runner.bench_func('bench_channel',
bench_bounded_queue_block,
queue.Channel,
inner_loops=N)
runner.bench_func('bench_bounded_queue_block_hub',
bench_bounded_queue_block,
queue.Queue, True,
inner_loops=N)
runner.bench_func('bench_channel_hub',
bench_bounded_queue_block,
queue.Channel, True,
inner_loops=N)
runner.bench_func('bench_unbounded_priority_queue_noblock',
bench_unbounded_queue_noblock,
queue.PriorityQueue,
inner_loops=N)
runner.bench_func('bench_bounded_priority_queue_noblock',
bench_bounded_queue_noblock,
queue.PriorityQueue,
inner_loops=N)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,54 @@
#! /usr/bin/env python
from __future__ import print_function, division, absolute_import
import perf
from gevent import socket
from gevent.server import StreamServer
def recvall(sock, _):
while sock.recv(4096):
pass
N = 10
runs = []
def benchmark(conn, data):
spent_total = 0
for _ in range(N):
start = perf.perf_counter()
conn.sendall(data)
spent = perf.perf_counter() - start
spent_total += spent
runs.append(spent_total)
return spent_total
def main():
runner = perf.Runner()
server = StreamServer(("127.0.0.1", 0), recvall)
server.start()
MB = 1024 * 1024
length = 50 * MB
data = b"x" * length
conn = socket.create_connection((server.server_host, server.server_port))
runner.bench_func('sendall', benchmark, conn, data, inner_loops=N)
conn.close()
server.stop()
if runs:
total = sum(runs)
avg = total / len(runs)
# This is really only true if the perf_counter counts in seconds time
print("~ %.2f MB/s" % (length * N / avg / MB))
if __name__ == "__main__":
main()

View File

@ -0,0 +1,48 @@
"""
Benchmarking sleep(0) performance.
"""
from __future__ import print_function
import perf
try:
xrange
except NameError:
xrange = range
N = 100
def test(loops, sleep, arg):
t0 = perf.perf_counter()
for __ in range(loops):
for _ in xrange(N):
sleep(arg)
return perf.perf_counter() - t0
def bench_gevent(loops, arg):
from gevent import sleep
from gevent import setswitchinterval
setswitchinterval(1000)
return test(loops, sleep, arg)
def bench_eventlet(loops, arg):
from eventlet import sleep
return test(loops, sleep, arg)
def main():
runner = perf.Runner()
for arg in (0, -1, 0.00001, 0.001):
runner.bench_time_func('gevent sleep(%s)' % (arg,),
bench_gevent, arg,
inner_loops=N)
runner.bench_time_func('eventlet sleep(%s)' % (arg,),
bench_eventlet, arg,
inner_loops=N)
if __name__ == '__main__':
main()

155
benchmarks/bench_socket.py Normal file
View File

@ -0,0 +1,155 @@
#! /usr/bin/env python
"""
Basic socket benchmarks.
"""
from __future__ import print_function, division, absolute_import
import os
import sys
import perf
import gevent
from gevent import socket as gsocket
import socket
import threading
def recvall(sock, _):
while sock.recv(4096):
pass
N = 10
MB = 1024 * 1024
length = 50 * MB
BIG_DATA = b"x" * length
SMALL_DATA = b'x' * 1000
def _sendto(loops, conn, data, to_send=None):
addr = ('127.0.0.1', 55678)
spent_total = 0
sent = 0
to_send = len(data) if to_send is None else to_send
for __ in range(loops):
for _ in range(N):
start = perf.perf_counter()
while sent < to_send:
sent += conn.sendto(data, 0, addr)
spent = perf.perf_counter() - start
spent_total += spent
return spent_total
def _sendall(loops, conn, data):
start = perf.perf_counter()
for __ in range(loops):
for _ in range(N):
conn.sendall(data)
taken = perf.perf_counter() - start
conn.close()
return taken
def bench_native_udp(loops):
conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
return _sendto(loops, conn, SMALL_DATA, len(BIG_DATA))
finally:
conn.close()
def bench_gevent_udp(loops):
conn = gsocket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
return _sendto(loops, conn, SMALL_DATA, len(BIG_DATA))
finally:
conn.close()
def _do_sendall(loops, send, recv):
for s in send, recv:
os.set_inheritable(s.fileno(), True)
pid = os.fork()
if not pid:
send.close()
recvall(recv, None)
recv.close()
sys.exit()
return 0
else:
try:
return _sendall(loops, send, BIG_DATA)
finally:
send.close()
recv.close()
def bench_native_thread_default_socketpair(loops):
send, recv = socket.socketpair()
t = threading.Thread(target=recvall, args=(recv, None))
t.daemon = True
t.start()
return _sendall(loops, send, BIG_DATA)
def bench_gevent_greenlet_default_socketpair(loops):
send, recv = gsocket.socketpair()
gevent.spawn(recvall, recv, None)
return _sendall(loops, send, BIG_DATA)
def bench_gevent_forked_socketpair(loops):
send, recv = gsocket.socketpair()
return _do_sendall(loops, send, recv)
def bench_native_forked_socketpair(loops):
send, recv = socket.socketpair()
return _do_sendall(loops, send, recv)
def main():
if '--profile' in sys.argv:
import cProfile
import pstats
import io
pr = cProfile.Profile()
pr.enable()
for _ in range(2):
bench_gevent_forked_socketpair(2)
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
return
runner = perf.Runner()
runner.bench_time_func(
'gevent socketpair sendall greenlet',
bench_gevent_greenlet_default_socketpair,
inner_loops=N)
runner.bench_time_func(
'native socketpair sendall thread',
bench_native_thread_default_socketpair,
inner_loops=N)
runner.bench_time_func(
'gevent socketpair sendall fork',
bench_gevent_forked_socketpair,
inner_loops=N)
runner.bench_time_func(
'native socketpair sendall fork',
bench_native_forked_socketpair,
inner_loops=N)
runner.bench_time_func(
'native udp sendto',
bench_native_udp,
inner_loops=N)
runner.bench_time_func(
'gevent udp sendto',
bench_gevent_udp,
inner_loops=N)
if __name__ == "__main__":
main()

199
benchmarks/bench_spawn.py Normal file
View File

@ -0,0 +1,199 @@
"""Benchmarking spawn() performance.
"""
from __future__ import print_function, absolute_import, division
import perf
try:
xrange
except NameError:
xrange = range
N = 10000
counter = 0
def incr(sleep, **_kwargs):
global counter
counter += 1
def noop(_p):
pass
class Options(object):
# TODO: Add back an argument for that
eventlet_hub = None
loops = None
def __init__(self, sleep, join, **kwargs):
self.kwargs = kwargs
self.sleep = sleep
self.join = join
class Times(object):
def __init__(self,
spawn_duration,
sleep_duration=-1,
join_duration=-1):
self.spawn_duration = spawn_duration
self.sleep_duration = sleep_duration
self.join_duration = join_duration
def _test(spawn, sleep, options):
global counter
counter = 0
before_spawn = perf.perf_counter()
for _ in xrange(N):
spawn(incr, sleep, **options.kwargs)
before_sleep = perf.perf_counter()
if options.sleep:
assert counter == 0, counter
sleep(0)
after_sleep = perf.perf_counter()
assert counter == N, (counter, N)
else:
after_sleep = before_sleep
if options.join:
before_join = perf.perf_counter()
options.join()
after_join = perf.perf_counter()
join_duration = after_join - before_join
else:
join_duration = -1
return Times(before_sleep - before_spawn,
after_sleep - before_sleep,
join_duration)
def test(spawn, sleep, options):
all_times = [_test(spawn, sleep, options)
for _ in xrange(options.loops)]
spawn_duration = sum(x.spawn_duration for x in all_times)
sleep_duration = sum(x.sleep_duration for x in all_times)
join_duration = sum(x.sleep_duration for x in all_times
if x != -1)
return Times(spawn_duration, sleep_duration, join_duration)
def bench_none(options):
options.sleep = False
def spawn(f, sleep, **kwargs):
return f(sleep, **kwargs)
from time import sleep
return test(spawn,
sleep,
options)
def bench_gevent(options):
from gevent import spawn, sleep
return test(spawn, sleep, options)
def bench_geventraw(options):
from gevent import sleep, spawn_raw
return test(spawn_raw, sleep, options)
def bench_geventpool(options):
from gevent import sleep
from gevent.pool import Pool
p = Pool()
if options.join:
options.join = p.join
times = test(p.spawn, sleep, options)
return times
def bench_eventlet(options):
from eventlet import spawn, sleep
from eventlet.hubs import use_hub
if options.eventlet_hub is not None:
use_hub(options.eventlet_hub)
return test(spawn, sleep, options)
def all():
result = [x for x in globals() if x.startswith('bench_') and x != 'bench_all']
result.sort()
result = [x.replace('bench_', '') for x in result]
return result
def main():
def worker_cmd(cmd, args):
cmd.extend(args.benchmark)
runner = perf.Runner(add_cmdline_args=worker_cmd)
runner.argparser.add_argument('benchmark',
nargs='*',
default='all',
choices=all() + ['all'])
def spawn_time(loops, func, options):
options.loops = loops
times = func(options)
return times.spawn_duration
def sleep_time(loops, func, options):
options.loops = loops
times = func(options)
return times.sleep_duration
def join_time(loops, func, options):
options.loops = loops
times = func(options)
return times.join_duration
args = runner.parse_args()
if 'all' in args.benchmark or args.benchmark == 'all':
args.benchmark = ['all']
names = all()
else:
names = args.benchmark
names = sorted(set(names))
for name in names:
runner.bench_time_func(name + ' spawn',
spawn_time,
globals()['bench_' + name],
Options(False, False),
inner_loops=N)
if name != 'none':
runner.bench_time_func(name + ' sleep',
sleep_time,
globals()['bench_' + name],
Options(True, False),
inner_loops=N)
if 'geventpool' in names:
runner.bench_time_func('geventpool join',
join_time,
bench_geventpool,
Options(True, True),
inner_loops=N)
for name in names:
runner.bench_time_func(name + ' spawn kwarg',
spawn_time,
globals()['bench_' + name],
Options(False, False, foo=1, bar='hello'),
inner_loops=N)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
"""
Benchmarks for thread locals.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import perf
from gevent import subprocess as gsubprocess
import subprocess as nsubprocess
N = 10
def _bench_spawn(module, loops, close_fds=True):
total = 0
for _ in range(loops):
t0 = perf.perf_counter()
procs = [module.Popen('/usr/bin/true', close_fds=close_fds)
for _ in range(N)]
t1 = perf.perf_counter()
for p in procs:
p.communicate()
p.poll()
total += (t1 - t0)
return total
def bench_spawn_native(loops, close_fds=True):
return _bench_spawn(nsubprocess, loops, close_fds)
def bench_spawn_gevent(loops, close_fds=True):
return _bench_spawn(gsubprocess, loops, close_fds)
def main():
runner = perf.Runner()
runner.bench_time_func('spawn native no close_fds',
bench_spawn_native,
False,
inner_loops=N)
runner.bench_time_func('spawn gevent no close_fds',
bench_spawn_gevent,
False,
inner_loops=N)
runner.bench_time_func('spawn native close_fds',
bench_spawn_native,
inner_loops=N)
runner.bench_time_func('spawn gevent close_fds',
bench_spawn_gevent,
inner_loops=N)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
"""
Benchmarks for thread pool.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import perf
from gevent.threadpool import ThreadPool
try:
xrange = xrange
except NameError:
xrange = range
def noop():
"Does nothing"
def identity(i):
return i
PAR_COUNT = 5
N = 20
def bench_apply(loops):
pool = ThreadPool(1)
t0 = perf.perf_counter()
for _ in xrange(loops):
for _ in xrange(N):
pool.apply(noop)
pool.join()
pool.kill()
return perf.perf_counter() - t0
def bench_spawn_wait(loops):
pool = ThreadPool(1)
t0 = perf.perf_counter()
for _ in xrange(loops):
for _ in xrange(N):
r = pool.spawn(noop)
r.get()
pool.join()
pool.kill()
return perf.perf_counter() - t0
def _map(pool, pool_func, loops):
data = [1] * N
t0 = perf.perf_counter()
# Must collect for imap to finish
for _ in xrange(loops):
list(pool_func(identity, data))
pool.join()
pool.kill()
return perf.perf_counter() - t0
def _ppool():
pool = ThreadPool(PAR_COUNT)
pool.size = PAR_COUNT
return pool
def bench_map_seq(loops):
pool = ThreadPool(1)
return _map(pool, pool.map, loops)
def bench_map_par(loops):
pool = _ppool()
return _map(pool, pool.map, loops)
def bench_imap_seq(loops):
pool = ThreadPool(1)
return _map(pool, pool.imap, loops)
def bench_imap_par(loops):
pool = _ppool()
return _map(pool, pool.imap, loops)
def bench_imap_un_seq(loops):
pool = ThreadPool(1)
return _map(pool, pool.imap_unordered, loops)
def bench_imap_un_par(loops):
pool = _ppool()
return _map(pool, pool.imap_unordered, loops)
def main():
runner = perf.Runner()
runner.bench_time_func('imap_unordered_seq',
bench_imap_un_seq)
runner.bench_time_func('imap_unordered_par',
bench_imap_un_par)
runner.bench_time_func('imap_seq',
bench_imap_seq)
runner.bench_time_func('imap_par',
bench_imap_par)
runner.bench_time_func('map_seq',
bench_map_seq)
runner.bench_time_func('map_par',
bench_map_par)
runner.bench_time_func('apply',
bench_apply)
runner.bench_time_func('spawn',
bench_spawn_wait)
if __name__ == '__main__':
main()

120
benchmarks/bench_tracer.py Normal file
View File

@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-
"""
Benchmarks for gevent.queue
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import perf
import greenlet
import gevent
from gevent import _tracer as monitor
N = 1000
@contextlib.contextmanager
def tracer(cls, *args):
inst = cls(*args)
try:
yield
finally:
inst.kill()
def _run(loops):
duration = 0
for _ in range(loops):
g1 = None
def switch():
parent = gevent.getcurrent().parent
for _ in range(N):
parent.switch()
g1 = gevent.Greenlet(switch)
g1.parent = gevent.getcurrent()
t1 = perf.perf_counter()
for _ in range(N):
g1.switch()
t2 = perf.perf_counter()
duration += t2 - t1
return duration
def bench_no_trace(loops):
return _run(loops)
def bench_trivial_tracer(loops):
def trivial(_event, _args):
return
greenlet.settrace(trivial)
try:
return _run(loops)
finally:
greenlet.settrace(None)
def bench_monitor_tracer(loops):
with tracer(monitor.GreenletTracer):
return _run(loops)
def bench_hub_switch_tracer(loops):
# use current as the hub, since tracer fires
# when we switch into that greenlet
with tracer(monitor.HubSwitchTracer, gevent.getcurrent(), 1):
return _run(loops)
def bench_max_switch_tracer(loops):
# use object() as the hub, since tracer fires
# when switch into something that's *not* the hub
with tracer(monitor.MaxSwitchTracer, object, 1):
return _run(loops)
def main():
runner = perf.Runner()
runner.bench_time_func(
"no tracer",
bench_no_trace,
inner_loops=N
)
runner.bench_time_func(
"trivial tracer",
bench_trivial_tracer,
inner_loops=N
)
runner.bench_time_func(
"monitor tracer",
bench_monitor_tracer,
inner_loops=N
)
runner.bench_time_func(
"max switch tracer",
bench_max_switch_tracer,
inner_loops=N
)
runner.bench_time_func(
"hub switch tracer",
bench_hub_switch_tracer,
inner_loops=N
)
if __name__ == '__main__':
main()

20
benchmarks/micro.sh Executable file
View File

@ -0,0 +1,20 @@
#!/bin/sh
set -e -x
PYTHON=${PYTHON:=python}
$PYTHON -c 'from __future__ import print_function; import gevent.core; print(gevent.__version__, gevent.core.get_version(), getattr(gevent.core, "get_method", lambda: "n/a")(), getattr(gevent, "get_hub", lambda: "n/a")())'
$PYTHON -mperf timeit -s'obj = Exception(); obj.x=5' 'obj.x'
$PYTHON -mperf timeit -s'from gevent import get_hub; get_hub()' 'get_hub()'
$PYTHON -mperf timeit -s'from gevent import getcurrent' 'getcurrent()'
$PYTHON -mperf timeit -s'from gevent import spawn; f = lambda : 5' 'spawn(f)'
$PYTHON -mperf timeit -s'from gevent import spawn; f = lambda : 5' 'spawn(f).join()'
$PYTHON -mperf timeit -s'from gevent import spawn, wait; from gevent.hub import xrange; f = lambda : 5' 'for _ in xrange(10000): spawn(f)' 'wait()'
$PYTHON -mperf timeit -s'from gevent import spawn_raw; f = lambda : 5' 'spawn_raw(f)'
benchmarks/micro_run_callback.sh
benchmarks/micro_semaphore.sh
benchmarks/micro_sleep.sh
benchmarks/micro_greenlet_link.sh

View File

@ -0,0 +1,9 @@
#!/bin/sh
set -e -x
PYTHON=${PYTHON:=python}
$PYTHON -mperf timeit -s'from gevent import spawn; from gevent.hub import xrange; g = spawn(lambda: 5); l = lambda: 5' 'for _ in xrange(1000): g.link(l)'
$PYTHON -mperf timeit -s'from gevent import spawn; from gevent.hub import xrange; g = spawn(lambda: 5); l = lambda *args: 5' 'for _ in xrange(10): g.link(l);' 'g.join()'
$PYTHON -mperf timeit -s'from gevent import spawn; from gevent.hub import xrange; g = spawn(lambda: 5); l = lambda *args: 5' 'for _ in xrange(100): g.link(l);' 'g.join()'
$PYTHON -mperf timeit -s'from gevent import spawn; from gevent.hub import xrange; g = spawn(lambda: 5); l = lambda *args: 5' 'for _ in xrange(1000): g.link(l);' 'g.join()'
$PYTHON -mperf timeit -s'from gevent import spawn; from gevent.hub import xrange; g = spawn(lambda: 5); l = lambda *args: 5' 'for _ in xrange(10000): g.link(l);' 'g.join()'
$PYTHON -mperf timeit -s'from gevent import spawn; from gevent.hub import xrange; g = spawn(lambda: 5); l = lambda *args: 5' 'for _ in xrange(100000): g.link(l);' 'g.join()'

View File

@ -0,0 +1,9 @@
#!/bin/sh
set -e -x
PYTHON=${PYTHON:=python}
$PYTHON -mperf timeit -s'from gevent import get_hub; run_cb = get_hub().loop.run_callback; f = lambda : 5' 'run_cb(f)'
$PYTHON -mperf timeit -s'from gevent import wait,get_hub; run_cb = get_hub().loop.run_callback; f = lambda : 5' 'run_cb(f)' 'wait()'
$PYTHON -mperf timeit -s'from gevent import get_hub; from gevent.hub import xrange; run_cb = get_hub().loop.run_callback; f = lambda : 5' 'for _ in xrange(100): run_cb(f)'
$PYTHON -mperf timeit -s'from gevent import wait,get_hub; from gevent.hub import xrange; run_cb = get_hub().loop.run_callback; f = lambda : 5' 'for _ in xrange(100): run_cb(f)' 'wait()'
$PYTHON -mperf timeit -s'from gevent import get_hub; from gevent.hub import xrange; run_cb = get_hub().loop.run_callback; f = lambda : 5' 'for _ in xrange(10000): run_cb(f)'
$PYTHON -mperf timeit -s'from gevent import wait,get_hub; from gevent.hub import xrange; run_cb = get_hub().loop.run_callback; f = lambda : 5' 'for _ in xrange(10000): run_cb(f)' 'wait()'

6
benchmarks/micro_semaphore.sh Executable file
View File

@ -0,0 +1,6 @@
#!/bin/sh
set -e -x
PYTHON=${PYTHON:=python}
$PYTHON -mperf timeit -s'from gevent.lock import Semaphore; s = Semaphore()' 's.release()'
$PYTHON -mperf timeit -s'from gevent.lock import Semaphore; from gevent import spawn_raw; s = Semaphore(0)' 'spawn_raw(s.release); s.acquire()'
$PYTHON -mperf timeit -s'from gevent.lock import Semaphore; from gevent import spawn_raw; s = Semaphore(0)' 'spawn_raw(s.release); spawn_raw(s.release); spawn_raw(s.release); spawn_raw(s.release); s.acquire(); s.acquire(); s.acquire(); s.acquire()'

8
benchmarks/micro_sleep.sh Executable file
View File

@ -0,0 +1,8 @@
#!/bin/sh
set -e -x
PYTHON=${PYTHON:=python}
$PYTHON -m perf timeit -s 'from gevent import sleep; f = lambda : 5' 'sleep(0)'
$PYTHON -m perf timeit -s 'from gevent import sleep; f = lambda : 5' 'sleep(0.00001)'
$PYTHON -m perf timeit -s 'from gevent import sleep; f = lambda : 5' 'sleep(0.0001)'
$PYTHON -m perf timeit -s 'from gevent import sleep; f = lambda : 5' 'sleep(0.001)'

22
ci-requirements.txt Normal file
View File

@ -0,0 +1,22 @@
setuptools
wheel
# Python 3.7 requires at least Cython 0.27.3.
# 0.28 is faster, and (important!) lets us specify the target module
# name to be created so that we can have both foo.py and _foo.so
# at the same time. 0.29 fixes some issues with Python 3.7,
# and adds the 3str mode for transition to Python 3.
Cython >= 0.29
# Python 3.7 requires at least 0.4.14, which is ABI incompatible with earlier
greenlet>=0.4.14 ; platform_python_implementation == "CPython"
pylint>=1.8.0 ; python_version < "3.4"
# pylint 2 needs astroid 2; unfortunately, it uses `typed_ast`
# which has a C extension that doesn't build on PyPy
pylint >= 2.1.1 ; python_version >= "3.4" and platform_python_implementation == "CPython"
astroid >= 2.0.2 ; python_version >= "3.4" and platform_python_implementation == "CPython"
# See version requirements in setup.py
cffi >= 1.11.5 ; platform_python_implementation == "CPython"
# benchmarks use this
perf

24
deps/README.rst vendored Normal file
View File

@ -0,0 +1,24 @@
================================
Managing Embedded Dependencies
================================
- Modify the c-ares Makefile.in[c] to empty out the MANPAGES variables
so that we don't have to ship those in the sdist.
XXX: We need a patch for that.
Updating libuv
==============
- Clean up the libuv tree, and apply the patches to libuv (this whole
sequence is meant to be copied and pasted into the terminal)::
rm -rf libuv/.github
rm -rf libuv/docs
rm -rf libuv/samples
rm -rf libuv/test
rm -rf libuv/tools
rm -f libuv/android-configure*
git apply libuv-win-binary.patch

84
deps/c-ares/AUTHORS vendored Normal file
View File

@ -0,0 +1,84 @@
c-ares is based on ares, and these are the people that have worked on it since
the fork was made:
Albert Chin
Alex Loukissas
Alexander Klauer
Alexander Lazic
Alexey Simak
Andreas Rieke
Andrew Andkjar
Andrew Ayer
Andrew C. Morrow
Ashish Sharma
Ben Greear
Ben Noordhuis
BogDan Vatra
Brad House
Brad Spencer
Bram Matthys
Chris Araman
Dan Fandrich
Daniel Johnson
Daniel Stenberg
David Drysdale
David Stuart
Denis Bilenko
Dima Tisnek
Dirk Manske
Dominick Meglio
Doug Goldstein
Doug Kwan
Duncan Wilcox
Eino Tuominen
Erik Kline
Fedor Indutny
Frederic Germain
Geert Uytterhoeven
George Neill
Gisle Vanem
Google LLC
Gregor Jasny
Guenter Knauf
Guilherme Balena Versiani
Gunter Knauf
Henrik Stoerner
Jakub Hrozek
James Bursa
Jérémy Lal
John Schember
Keith Shaw
Lei Shi
Marko Kreen
Michael Wallner
Mike Crowe
Nick Alcock
Nick Mathewson
Nicolas "Pixel" Noble
Ning Dong
Oleg Pudeyev
Patrick Valsecchi
Patrik Thunstrom
Paul Saab
Peter Pentchev
Phil Blundell
Poul Thomas Lomholt
Ravi Pratap
Robin Cornelius
Saúl Ibarra Corretgé
Sebastian at basti79.de
Shmulik Regev
Stefan Bühler
Steinar H. Gunderson
Svante Karlsson
Tofu Linden
Tom Hughes
Tor Arntsen
Viktor Szakats
Vlad Dinulescu
William Ahern
Yang Tse
hpopescu at ixiacom.com
liren at vivisimo.com
nordsturm
saghul

4210
deps/c-ares/CHANGES vendored Normal file

File diff suppressed because it is too large Load Diff

415
deps/c-ares/INSTALL.md vendored Normal file
View File

@ -0,0 +1,415 @@
** This file is adapted from libcurl and not yet fully rewritten for c-ares! **
```
___ __ _ _ __ ___ ___
/ __| ___ / _` | '__/ _ \/ __|
| (_ |___| (_| | | | __/\__ \
\___| \__,_|_| \___||___/
How To Compile
```
Installing Binary Packages
==========================
Lots of people download binary distributions of c-ares. This document
does not describe how to install c-ares using such a binary package.
This document describes how to compile, build and install c-ares from
source code.
Building from Git
=================
If you get your code off a Git repository rather than an official
release tarball, see the [GIT-INFO](GIT-INFO) file in the root directory
for specific instructions on how to proceed.
In particular, if not using CMake you will need to run `./buildconf` (Unix) or
`buildconf.bat` (Windows) to generate build files, and for the former
you will need a local installation of Autotools. If using CMake the steps are
the same for both Git and official release tarballs.
AutoTools Build
===============
### General Information, works on most Unix Platforms (Linux, FreeBSD, etc)
A normal Unix installation is made in three or four steps (after you've
unpacked the source archive):
./configure
make
make ahost adig acountry (optional)
make install
You probably need to be root when doing the last command.
If you have checked out the sources from the git repository, read the
[GIT-INFO](GIT_INFO) on how to proceed.
Get a full listing of all available configure options by invoking it like:
./configure --help
If you want to install c-ares in a different file hierarchy than /usr/local,
you need to specify that already when running configure:
./configure --prefix=/path/to/c-ares/tree
If you happen to have write permission in that directory, you can do `make
install` without being root. An example of this would be to make a local
install in your own home directory:
./configure --prefix=$HOME
make
make install
### More Options
To force configure to use the standard cc compiler if both cc and gcc are
present, run configure like
CC=cc ./configure
# or
env CC=cc ./configure
To force a static library compile, disable the shared library creation
by running configure like:
./configure --disable-shared
If you're a c-ares developer and use gcc, you might want to enable more
debug options with the `--enable-debug` option.
### Special Cases
Some versions of uClibc require configuring with `CPPFLAGS=-D_GNU_SOURCE=1`
to get correct large file support.
The Open Watcom C compiler on Linux requires configuring with the variables:
./configure CC=owcc AR="$WATCOM/binl/wlib" AR_FLAGS=-q \
RANLIB=/bin/true STRIP="$WATCOM/binl/wstrip" CFLAGS=-Wextra
### CROSS COMPILE
(This section was graciously brought to us by Jim Duey, with additions by
Dan Fandrich)
Download and unpack the c-ares package.
`cd` to the new directory. (e.g. `cd c-ares-1.7.6`)
Set environment variables to point to the cross-compile toolchain and call
configure with any options you need. Be sure and specify the `--host` and
`--build` parameters at configuration time. The following script is an
example of cross-compiling for the IBM 405GP PowerPC processor using the
toolchain from MonteVista for Hardhat Linux.
```sh
#! /bin/sh
export PATH=$PATH:/opt/hardhat/devkit/ppc/405/bin
export CPPFLAGS="-I/opt/hardhat/devkit/ppc/405/target/usr/include"
export AR=ppc_405-ar
export AS=ppc_405-as
export LD=ppc_405-ld
export RANLIB=ppc_405-ranlib
export CC=ppc_405-gcc
export NM=ppc_405-nm
./configure --target=powerpc-hardhat-linux \
--host=powerpc-hardhat-linux \
--build=i586-pc-linux-gnu \
--prefix=/opt/hardhat/devkit/ppc/405/target/usr/local \
--exec-prefix=/usr/local
```
You may also need to provide a parameter like `--with-random=/dev/urandom`
to configure as it cannot detect the presence of a random number
generating device for a target system. The `--prefix` parameter
specifies where c-ares will be installed. If `configure` completes
successfully, do `make` and `make install` as usual.
In some cases, you may be able to simplify the above commands to as
little as:
./configure --host=ARCH-OS
### Cygwin (Windows)
Almost identical to the unix installation. Run the configure script in the
c-ares root with `sh configure`. Make sure you have the sh executable in
`/bin/` or you'll see the configure fail toward the end.
Run `make`
### QNX
(This section was graciously brought to us by David Bentham)
As QNX is targeted for resource constrained environments, the QNX headers
set conservative limits. This includes the `FD_SETSIZE` macro, set by default
to 32. Socket descriptors returned within the c-ares library may exceed this,
resulting in memory faults/SIGSEGV crashes when passed into `select(..)`
calls using `fd_set` macros.
A good all-round solution to this is to override the default when building
c-ares, by overriding `CFLAGS` during configure, example:
# configure CFLAGS='-DFD_SETSIZE=64 -g -O2'
### RISC OS
The library can be cross-compiled using gccsdk as follows:
CC=riscos-gcc AR=riscos-ar RANLIB='riscos-ar -s' ./configure \
--host=arm-riscos-aof --without-random --disable-shared
make
where `riscos-gcc` and `riscos-ar` are links to the gccsdk tools.
You can then link your program with `c-ares/lib/.libs/libcares.a`.
### Android
Method using a configure cross-compile (tested with Android NDK r7b):
- prepare the toolchain of the Android NDK for standalone use; this can
be done by invoking the script:
./tools/make-standalone-toolchain.sh
which creates a usual cross-compile toolchain. Lets assume that you put
this toolchain below `/opt` then invoke configure with something
like:
```
export PATH=/opt/arm-linux-androideabi-4.4.3/bin:$PATH
./configure --host=arm-linux-androideabi [more configure options]
make
```
- if you want to compile directly from our GIT repo you might run into
this issue with older automake stuff:
```
checking host system type...
Invalid configuration `arm-linux-androideabi':
system `androideabi' not recognized
configure: error: /bin/sh ./config.sub arm-linux-androideabi failed
```
this issue can be fixed with using more recent versions of `config.sub`
and `config.guess` which can be obtained here:
http://git.savannah.gnu.org/gitweb/?p=config.git;a=tree
you need to replace your system-own versions which usually can be
found in your automake folder:
`find /usr -name config.sub`
CMake builds
============
Current releases of c-ares introduce a CMake v3+ build system that has been
tested on most platforms including Windows, Linux, FreeBSD, MacOS, AIX and
Solaris.
In the most basic form, building with CMake might look like:
```sh
cd /path/to/cmake/source
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local/cares ..
make
sudo make install
```
Options
-------
Options to CMake are passed on the command line using "-D${OPTION}=${VALUE}".
The values defined are all boolean and take values like On, Off, True, False.
* CARES_STATIC - Build the static library (off by default)
* CARES_SHARED - Build the shared library (on by default)
* CARES_INSTALL - Hook in installation, useful to disable if chain building
* CARES_STATIC_PIC - Build the static library as position-independent (off by
default)
Ninja
-----
Ninja is the next-generation build system meant for generators like CMake that
heavily parallize builds. Its use is very similar to the normal build:
```sh
cd /path/to/cmake/source
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local/cares -G "Ninja" ..
ninja
sudo ninja install
```
Windows MSVC Command Line
-------------------------
```
cd \path\to\cmake\source
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=C:\cares -G "NMake Makefiles" ..
nmake
nmake install
```
Windows MinGW-w64 Command Line via MSYS
---------------------------------------
```
cd \path\to\cmake\source
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=C:\cares -G "MSYS Makefiles" ..
make
make install
```
Platform-specific build systems
===============================
Win32
-----
### Building Windows DLLs and C run-time (CRT) linkage issues
As a general rule, building a DLL with static CRT linkage is highly
discouraged, and intermixing CRTs in the same app is something to
avoid at any cost.
Reading and comprehension of Microsoft Knowledge Base articles
KB94248 and KB140584 is a must for any Windows developer. Especially
important is full understanding if you are not going to follow the
advice given above.
- [KB94248](http://support.microsoft.com/kb/94248/en-us) - How To Use the C Run-Time
- [KB140584](http://support.microsoft.com/kb/140584/en-us) - How to link with the correct C Run-Time (CRT) library
- [KB190799](http://msdn.microsoft.com/en-us/library/ms235460) - Potential Errors Passing CRT Objects Across DLL Boundaries
If your app is misbehaving in some strange way, or it is suffering
from memory corruption, before asking for further help, please try
first to rebuild every single library your app uses as well as your
app using the debug multithreaded dynamic C runtime.
### MingW32
Make sure that MinGW32's bin dir is in the search path, for example:
set PATH=c:\mingw32\bin;%PATH%
then run 'make -f Makefile.m32' in the root dir.
### MSVC 6 caveats
If you use MSVC 6 it is required that you use the February 2003 edition PSDK:
http://www.microsoft.com/msdownload/platformsdk/sdkupdate/psdk-full.htm
### MSVC from command line
Run the `vcvars32.bat` file to get a proper environment. The
`vcvars32.bat` file is part of the Microsoft development environment and
you may find it in `C:\Program Files\Microsoft Visual Studio\vc98\bin`
provided that you installed Visual C/C++ 6 in the default directory.
Further details in [README.msvc](README.msvc)
### MSVC IDEs
Details in [README.msvc](README.msvc)
### Important static c-ares usage note
When building an application that uses the static c-ares library, you must
add `-DCARES_STATICLIB` to your `CFLAGS`. Otherwise the linker will look for
dynamic import symbols.
IBM OS/2
--------
Building under OS/2 is not much different from building under unix.
You need:
- emx 0.9d
- GNU make
- GNU patch
- ksh
- GNU bison
- GNU file utilities
- GNU sed
- autoconf 2.13
If during the linking you get an error about `_errno` being an undefined
symbol referenced from the text segment, you need to add `-D__ST_MT_ERRNO__`
in your definitions.
If you're getting huge binaries, probably your makefiles have the `-g` in
`CFLAGS`.
NetWare
-------
To compile `libcares.a` / `libcares.lib` you need:
- either any gcc / nlmconv, or CodeWarrior 7 PDK 4 or later.
- gnu make and awk running on the platform you compile on;
native Win32 versions can be downloaded from:
http://www.gknw.net/development/prgtools/
- recent Novell LibC SDK available from:
http://developer.novell.com/ndk/libc.htm
- or recent Novell CLib SDK available from:
http://developer.novell.com/ndk/clib.htm
Set a search path to your compiler, linker and tools; on Linux make
sure that the var `OSTYPE` contains the string 'linux'; set the var
`NDKBASE` to point to the base of your Novell NDK; and then type
`make -f Makefile.netware` from the top source directory;
PORTS
=====
This is a probably incomplete list of known hardware and operating systems
that c-ares has been compiled for. If you know a system c-ares compiles and
runs on, that isn't listed, please let us know!
- Alpha Tru64 v5.0 5.1
- ARM Android 1.5, 2.1, 2.3
- MIPS IRIX 6.2, 6.5
- Power AIX 3.2.5, 4.2, 4.3.1, 4.3.2, 5.1, 5.2
- i386 Linux 1.3, 2.0, 2.2, 2.3, 2.4, 2.6
- i386 Novell NetWare
- i386 Windows 95, 98, ME, NT, 2000, XP, 2003
- x86_64 Linux
Useful URLs
===========
- c-ares: https://c-ares.haxx.se/
- MingW: http://www.mingw.org/
- MinGW-w64: http://mingw-w64.sourceforge.net/
- OpenWatcom: http://www.openwatcom.org/

15
deps/c-ares/LICENSE.md vendored Normal file
View File

@ -0,0 +1,15 @@
# c-ares license
Copyright (c) 2007 - 2018, Daniel Stenberg with many contributors, see AUTHORS
file.
Copyright 1998 by the Massachusetts Institute of Technology.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of M.I.T. not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
M.I.T. makes no representations about the suitability of this software for any
purpose. It is provided "as is" without express or implied warranty.

164
deps/c-ares/Makefile.Watcom vendored Normal file
View File

@ -0,0 +1,164 @@
#
# Watcom / OpenWatcom / Win32 makefile for cares.
# Quick hack by Guenter; comments to: /dev/nul
#
!ifndef %watcom
!error WATCOM environment variable not set!
!else
SYS_INCL = -I$(%watcom)\h\nt -I$(%watcom)\h
SYS_LIBS = $(%watcom)\lib386\nt;$(%watcom)\lib386
!endif
!ifdef %libname
LIBNAME = $(%libname)
!else
LIBNAME = cares
!endif
TARGETS = $(LIBNAME).dll $(LIBNAME)_imp.lib $(LIBNAME).lib
DEMOS = adig.exe ahost.exe acountry.exe
CC = wcc386
LD = wlink
AR = wlib
RC = wrc
!ifdef __LOADDLL__
! loaddll wcc386 wccd386
! loaddll wpp386 wppd386
! loaddll wlib wlibd
!endif
!if $(__VERSION__) < 1250
RM = del /q /f 2>NUL
!else
RM = rm -f
!endif
MD = mkdir
RD = rmdir /q /s 2>NUL
CP = copy
CFLAGS = -3r -mf -hc -zff -zgf -zq -zm -zc -s -fr=con -w2 -fpi -oilrtfm &
-wcd=201 -bt=nt -d+ -dWIN32 -dCARES_BUILDING_LIBRARY &
-dNTDDI_VERSION=0x05010000 -I. $(SYS_INCL)
LFLAGS = option quiet, map, caseexact, eliminate
!ifdef %debug
DEBUG = -dDEBUG=1 -dDEBUGBUILD
CFLAGS += -d3 $(DEBUG)
LFLAGS += debug all
!else
CFLAGS += -d0
!endif
CFLAGS += -d_WIN32_WINNT=0x0600
#
# Change to suite.
#
!ifdef %use_watt32
CFLAGS += -dWATT32 -I$(%watt_root)\inc
!endif
OBJ_BASE = WC_Win32.obj
LINK_ARG = $(OBJ_BASE)\dyn\wlink.arg
LIB_ARG = $(OBJ_BASE)\stat\wlib.arg
# In order to process Makefile.inc wmake must be called with -u switch!
!ifneq __MAKEOPTS__ -u
!error You MUST call wmake with the -u switch!
!else
!include Makefile.inc
!endif
OBJS = $(CSOURCES:.c=.obj)
OBJS = $OBJ_DIR\$(OBJS: = $OBJ_DIR\)
#
# Use $(OBJS) as a template to generate $(OBJS_STAT) and $(OBJS_DYN).
#
OBJ_DIR = $(OBJ_BASE)\stat
OBJS_STAT = $+ $(OBJS) $-
OBJ_DIR = $(OBJ_BASE)\dyn
OBJS_DYN = $+ $(OBJS) $-
ARESBUILDH = ares_build.h
RESOURCE = $(OBJ_BASE)\dyn\cares.res
all: $(ARESBUILDH) $(OBJ_BASE) $(TARGETS) $(DEMOS) .SYMBOLIC
@echo Welcome to cares
$(OBJ_BASE):
-$(MD) $^@
-$(MD) $^@\stat
-$(MD) $^@\dyn
-$(MD) $^@\demos
$(ARESBUILDH): .EXISTSONLY
$(CP) $^@.dist $^@
$(LIBNAME).dll: $(OBJS_DYN) $(RESOURCE) $(LINK_ARG)
$(LD) name $^@ @$]@
$(LIBNAME).lib: $(OBJS_STAT) $(LIB_ARG)
$(AR) -q -b -c $^@ @$]@
adig.exe: $(OBJ_BASE)\demos\adig.obj $(OBJ_BASE)\demos\ares_getopt.obj $(LIBNAME).lib
$(LD) name $^@ system nt $(LFLAGS) file { $(OBJ_BASE)\demos\ares_getopt.obj $[@ } library $]@, ws2_32.lib
ahost.exe: $(OBJ_BASE)\demos\ahost.obj $(OBJ_BASE)\demos\ares_getopt.obj $(LIBNAME).lib
$(LD) name $^@ system nt $(LFLAGS) file { $(OBJ_BASE)\demos\ares_getopt.obj $[@ } library $]@, ws2_32.lib
acountry.exe: $(OBJ_BASE)\demos\acountry.obj $(OBJ_BASE)\demos\ares_getopt.obj $(LIBNAME).lib
$(LD) name $^@ system nt $(LFLAGS) file { $(OBJ_BASE)\demos\ares_getopt.obj $[@ } library $]@, ws2_32.lib
clean: .SYMBOLIC
-$(RM) $(OBJS_STAT)
-$(RM) $(OBJS_DYN)
-$(RM) $(RESOURCE) $(LINK_ARG) $(LIB_ARG)
vclean realclean: clean .SYMBOLIC
-$(RM) $(TARGETS) $(LIBNAME).map
-$(RM) $(DEMOS) $(DEMOS:.exe=.map)
-$(RD) $(OBJ_BASE)\stat
-$(RD) $(OBJ_BASE)\dyn
-$(RD) $(OBJ_BASE)\demos
-$(RD) $(OBJ_BASE)
.ERASE
$(RESOURCE): cares.rc .AUTODEPEND
$(RC) $(DEBUG) -q -r -zm -I..\include $(SYS_INCL) $[@ -fo=$^@
.ERASE
.c{$(OBJ_BASE)\dyn}.obj:
$(CC) $(CFLAGS) -bd $[@ -fo=$^@
.ERASE
.c{$(OBJ_BASE)\stat}.obj:
$(CC) $(CFLAGS) -DCARES_STATICLIB $[@ -fo=$^@
.ERASE
.c{$(OBJ_BASE)\demos}.obj:
$(CC) $(CFLAGS) -DCARES_STATICLIB $[@ -fo=$^@
$(LINK_ARG): $(__MAKEFILES__)
%create $^@
@%append $^@ system nt dll
@%append $^@ file { $(OBJS_DYN) }
@%append $^@ option res=$(RESOURCE), implib=$(LIBNAME)_imp.lib
@%append $^@ $(LFLAGS)
@%append $^@ libpath $(SYS_LIBS)
# @%append $^@ library clib3r.lib
!ifdef %use_watt32
@%append $^@ library $(%watt_root)\lib\wattcpw_imp.lib
!else
@%append $^@ library ws2_32.lib
!endif
$(LIB_ARG): $(__MAKEFILES__)
%create $^@
@for %f in ($(OBJS_STAT)) do @%append $^@ +- %f

215
deps/c-ares/Makefile.am vendored Normal file
View File

@ -0,0 +1,215 @@
AUTOMAKE_OPTIONS = foreign nostdinc
ACLOCAL_AMFLAGS = -I m4
# Specify our include paths here, and do it relative to $(top_srcdir) and
# $(top_builddir), to ensure that these paths which belong to the library
# being currently built and tested are searched before the library which
# might possibly already be installed in the system.
#
# When using the low-level hard-hacking memory leak tracking code from
# libcurl the generated curl/curlbuild.h file must also be reachable.
# Using the libcurl lowlevel code from within c-ares library is ugly and
# only works when c-ares is built and linked with a similarly debug-build
# libcurl, but we do this anyway for convenience.
#
# $(top_builddir)/../include/curl for generated curlbuild.h included from curl.h
# $(top_builddir)/../include is for libcurl's generated curl/curlbuild.h file
# $(top_srcdir)/../include is for libcurl's external include files
# $(top_builddir)/../lib is for libcurl's generated lib/curl_config.h file
# $(top_srcdir)/../lib is for libcurl's lib/setup.h and other "private" files
# $(top_builddir) is for c-ares's generated ares_config.h file
# $(top_srcdir) is for c-ares's ares_setup.h and other "c-ares-private" files
if CURLDEBUG
AM_CPPFLAGS = -I$(top_builddir)/../include/curl \
-I$(top_builddir)/../include \
-I$(top_srcdir)/../include \
-I$(top_builddir)/../lib \
-I$(top_srcdir)/../lib \
-I$(top_builddir) \
-I$(top_srcdir)
else
AM_CPPFLAGS = -I$(top_builddir) \
-I$(top_srcdir)
endif
lib_LTLIBRARIES = libcares.la
man_MANS = $(MANPAGES)
MSVCFILES = vc/vc6aws.dsw vc/acountry/vc6acountry.dsp vc/adig/vc6adig.dsp \
vc/ahost/vc6ahost.dsp vc/cares/vc6cares.dsp vc/cares/vc6cares.dsw \
msvc_ver.inc
if CURLDEBUG
PROGS =
else
PROGS = ahost adig acountry
endif
noinst_PROGRAMS =$(PROGS)
# adig and ahost are just sample programs and thus not mentioned with the
# regular sources and headers
EXTRA_DIST = AUTHORS CHANGES README.cares Makefile.inc Makefile.dj \
Makefile.m32 Makefile.netware Makefile.msvc Makefile.Watcom $(man_MANS) \
config-win32.h RELEASE-NOTES libcares.pc.in buildconf get_ver.awk maketgz \
TODO ares_build.h.in cares.rc README.msvc $(MSVCFILES) \
$(CSOURCES) $(HHEADERS) config-dos.h acountry.1 adig.1 ahost.1 INSTALL.md \
CMakeLists.txt ares_build.h.cmake ares_config.h.cmake c-ares-config.cmake.in \
libcares.pc.cmake README.md LICENSE.md RELEASE-PROCEDURE.md
CLEANFILES = $(PDFPAGES) $(HTMLPAGES)
DISTCLEANFILES = ares_build.h
DIST_SUBDIRS = test
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libcares.pc
CARES_VERSION_INFO = -version-info 4:0:2
# This flag accepts an argument of the form current[:revision[:age]]. So,
# passing -version-info 3:12:1 sets current to 3, revision to 12, and age to
# 1.
#
# If either revision or age are omitted, they default to 0. Also note that age
# must be less than or equal to the current interface number.
#
# Here are a set of rules to help you update your library version information:
#
# 1.Start with version information of 0:0:0 for each libtool library.
#
# 2.Update the version information only immediately before a public release of
# your software. More frequent updates are unnecessary, and only guarantee
# that the current interface number gets larger faster.
#
# 3.If the library source code has changed at all since the last update, then
# increment revision (c:r+1:a)
#
# 4.If any interfaces have been added, removed, or changed since the last
# update, increment current, and set revision to 0. (c+1:r=0:a)
#
# 5.If any interfaces have been added since the last public release, then
# increment age. (c:r:a+1)
#
# 6.If any interfaces have been removed since the last public release, then
# set age to 0. (c:r:a=0)
#
AM_LDFLAGS =
libcares_la_LDFLAGS_EXTRA =
if CARES_LT_SHLIB_USE_VERSION_INFO
libcares_la_LDFLAGS_EXTRA += $(CARES_VERSION_INFO)
endif
if CARES_LT_SHLIB_USE_NO_UNDEFINED
libcares_la_LDFLAGS_EXTRA += -no-undefined
endif
if CARES_LT_SHLIB_USE_MIMPURE_TEXT
libcares_la_LDFLAGS_EXTRA += -mimpure-text
endif
libcares_la_LDFLAGS = $(AM_LDFLAGS) $(libcares_la_LDFLAGS_EXTRA)
# Add -Werror if defined
CFLAGS += @CARES_CFLAG_EXTRAS@
if USE_CPPFLAG_CARES_STATICLIB
AM_CPPFLAGS += $(CPPFLAG_CARES_STATICLIB)
endif
libcares_la_CFLAGS_EXTRA =
libcares_la_CPPFLAGS_EXTRA = -DCARES_BUILDING_LIBRARY
if DOING_CARES_SYMBOL_HIDING
libcares_la_CFLAGS_EXTRA += $(CFLAG_CARES_SYMBOL_HIDING)
libcares_la_CPPFLAGS_EXTRA += -DCARES_SYMBOL_HIDING
endif
@CODE_COVERAGE_RULES@
libcares_la_LDFLAGS += $(CODE_COVERAGE_LDFLAGS)
libcares_la_CFLAGS_EXTRA += $(CODE_COVERAGE_CFLAGS)
libcares_la_CFLAGS = $(AM_CFLAGS) $(libcares_la_CFLAGS_EXTRA)
libcares_la_CPPFLAGS = $(AM_CPPFLAGS) $(libcares_la_CPPFLAGS_EXTRA)
# Makefile.inc provides the CSOURCES and HHEADERS defines
include Makefile.inc
libcares_la_SOURCES = $(CSOURCES) $(HHEADERS)
# where to install the c-ares headers
libcares_ladir = $(includedir)
# what headers to install on 'make install':
libcares_la_HEADERS = ares.h ares_version.h ares_dns.h \
ares_build.h ares_rules.h
ahost_SOURCES = ahost.c $(SAMPLESOURCES) $(SAMPLEHEADERS)
ahost_LDADD = $(top_builddir)/libcares.la
ahost_CFLAGS = $(AM_CFLAGS)
ahost_CPPFLAGS = $(AM_CPPFLAGS)
adig_SOURCES = adig.c $(SAMPLESOURCES) $(SAMPLEHEADERS)
adig_LDADD = $(top_builddir)/libcares.la
adig_CFLAGS = $(AM_CFLAGS)
adig_CPPFLAGS = $(AM_CPPFLAGS)
acountry_SOURCES = acountry.c $(SAMPLESOURCES) $(SAMPLEHEADERS)
acountry_LDADD = $(top_builddir)/libcares.la
acountry_CFLAGS = $(AM_CFLAGS)
acountry_CPPFLAGS = $(AM_CPPFLAGS)
SOURCEDMANDIR = man3
SOURCEDMANPAGES = ares_init.3
clean-local: clean-sourced-manpages
clean-sourced-manpages:
@srcdmandir='$(SOURCEDMANDIR)'; \
echo "rm -rf $(top_builddir)/$$srcdmandir"; \
rm -rf $(top_builddir)/$$srcdmandir
sourced-manpages: clean-sourced-manpages
@srcdmandir='$(SOURCEDMANDIR)'; \
srcdmanfiles='$(SOURCEDMANPAGES)'; \
mkdir $(top_builddir)/$$srcdmandir; \
for file in $$srcdmanfiles; do \
if test -f $(top_srcdir)/$$file; then \
echo "cp $(top_srcdir)/$$file $(top_builddir)/$$srcdmandir/$$file"; \
cp $(top_srcdir)/$$file $(top_builddir)/$$srcdmandir/$$file; \
fi; \
done
MAN2HTML = roffit --mandir=. < $< >$@
SUFFIXES = .3 .html
html: sourced-manpages $(HTMLPAGES)
.3.html:
$(MAN2HTML)
pdf: sourced-manpages $(PDFPAGES)
.3.pdf:
@(foo=`echo $@ | sed -e 's/\.[0-9]$$//g'`; \
groff -Tps -man $< >$$foo.ps; \
ps2pdf $$foo.ps $@; \
rm $$foo.ps; \
echo "converted $< to $@")
# Make files named *.dist replace the file without .dist extension
dist-hook:
find $(distdir) -name "*.dist" -exec rm {} \;
(distit=`find $(srcdir) -name "*.dist"`; \
for file in $$distit; do \
strip=`echo $$file | sed -e s/^$(srcdir)// -e s/\.dist//`; \
cp $$file $(distdir)$$strip; \
done)

85
deps/c-ares/Makefile.dj vendored Normal file
View File

@ -0,0 +1,85 @@
#
# c-ares Makefile for djgpp/gcc/Watt-32.
# By Gisle Vanem <gvanem@yahoo.no> 2004.
#
TOPDIR = ..
DEPEND_PREREQ = ares_config.h
include ../packages/DOS/common.dj
include Makefile.inc
CFLAGS += -DWATT32 -Dselect=select_s
LDFLAGS = -s
ifeq ($(USE_CURLDEBUG),1)
EX_LIBS = ../lib/libcurl.a
OBJ_HACK = $(OBJECTS)
else
OBJ_HACK = libcares.a
endif
ifeq ($(USE_SSL),1)
EX_LIBS += $(OPENSSL_ROOT)/lib/libssl.a $(OPENSSL_ROOT)/lib/libcrypt.a
endif
ifeq ($(USE_ZLIB),1)
EX_LIBS += $(ZLIB_ROOT)/libz.a
endif
ifeq ($(USE_IDNA),1)
EX_LIBS += $(LIBIDN_ROOT)/lib/dj_obj/libidn.a -liconv
endif
EX_LIBS += $(WATT32_ROOT)/lib/libwatt.a
OBJECTS = $(addprefix $(OBJ_DIR)/, $(CSOURCES:.c=.o))
all: $(OBJ_DIR) ares_config.h libcares.a ahost.exe adig.exe acountry.exe
@echo Welcome to c-ares.
libcares.a: $(OBJECTS)
ar rs $@ $?
ares_config.h: config-dos.h
$(COPY) $^ $@
ahost.exe: ahost.c $(OBJ_DIR)/ares_getopt.o $(OBJ_HACK)
$(CC) $(LDFLAGS) $(CFLAGS) -o $@ $^ $(EX_LIBS)
adig.exe: adig.c $(OBJ_DIR)/ares_getopt.o $(OBJ_HACK)
$(CC) $(LDFLAGS) $(CFLAGS) -o $@ $^ $(EX_LIBS)
acountry.exe: acountry.c $(OBJ_DIR)/ares_getopt.o $(OBJ_HACK)
$(CC) $(LDFLAGS) $(CFLAGS) -o $@ $^ $(EX_LIBS)
# clean generated files
#
genclean:
- $(DELETE) ares_config.h
# clean object files and subdir
#
objclean: genclean
- $(DELETE) $(OBJ_DIR)$(DS)*.o
- $(RMDIR) $(OBJ_DIR)
# clean without removing built library and programs
#
clean: objclean
- $(DELETE) depend.dj
# clean everything
#
realclean vclean: clean
- $(DELETE) libcares.a
- $(DELETE) acountry.exe
- $(DELETE) adig.exe
- $(DELETE) ahost.exe
- $(DELETE) libcares.a
-include depend.dj

2118
deps/c-ares/Makefile.in vendored Normal file

File diff suppressed because it is too large Load Diff

189
deps/c-ares/Makefile.inc vendored Normal file
View File

@ -0,0 +1,189 @@
CSOURCES = ares__close_sockets.c \
ares__get_hostent.c \
ares__read_line.c \
ares__timeval.c \
ares_android.c \
ares_cancel.c \
ares_data.c \
ares_destroy.c \
ares_expand_name.c \
ares_expand_string.c \
ares_fds.c \
ares_free_hostent.c \
ares_free_string.c \
ares_getenv.c \
ares_gethostbyaddr.c \
ares_gethostbyname.c \
ares_getnameinfo.c \
ares_getsock.c \
ares_init.c \
ares_library_init.c \
ares_llist.c \
ares_mkquery.c \
ares_create_query.c \
ares_nowarn.c \
ares_options.c \
ares_parse_a_reply.c \
ares_parse_aaaa_reply.c \
ares_parse_mx_reply.c \
ares_parse_naptr_reply.c \
ares_parse_ns_reply.c \
ares_parse_ptr_reply.c \
ares_parse_soa_reply.c \
ares_parse_srv_reply.c \
ares_parse_txt_reply.c \
ares_platform.c \
ares_process.c \
ares_query.c \
ares_search.c \
ares_send.c \
ares_strcasecmp.c \
ares_strdup.c \
ares_strerror.c \
ares_timeout.c \
ares_version.c \
ares_writev.c \
bitncmp.c \
inet_net_pton.c \
inet_ntop.c \
windows_port.c
HHEADERS = ares.h \
ares_build.h \
ares_data.h \
ares_dns.h \
ares_getenv.h \
ares_inet_net_pton.h \
ares_iphlpapi.h \
ares_ipv6.h \
ares_library_init.h \
ares_llist.h \
ares_nowarn.h \
ares_platform.h \
ares_private.h \
ares_rules.h \
ares_strcasecmp.h \
ares_strdup.h \
ares_version.h \
ares_writev.h \
bitncmp.h \
nameser.h \
ares_setup.h \
setup_once.h
MANPAGES =
HTMLPAGES = ares_cancel.html \
ares_destroy.html \
ares_destroy_options.html \
ares_dup.html \
ares_expand_name.html \
ares_expand_string.html \
ares_fds.html \
ares_free_data.html \
ares_free_hostent.html \
ares_free_string.html \
ares_get_servers.html \
ares_get_servers_ports.html \
ares_gethostbyaddr.html \
ares_gethostbyname.html \
ares_gethostbyname_file.html \
ares_getnameinfo.html \
ares_getsock.html \
ares_init.html \
ares_init_options.html \
ares_library_cleanup.html \
ares_library_init.html \
ares_library_initialized.html \
ares_mkquery.html \
ares_create_query.html \
ares_parse_a_reply.html \
ares_parse_aaaa_reply.html \
ares_parse_mx_reply.html \
ares_parse_ns_reply.html \
ares_parse_ptr_reply.html \
ares_parse_soa_reply.html \
ares_parse_srv_reply.html \
ares_parse_txt_reply.html \
ares_process.html \
ares_query.html \
ares_save_options.html \
ares_search.html \
ares_send.html \
ares_set_local_dev.html \
ares_set_local_ip4.html \
ares_set_local_ip6.html \
ares_set_servers.html \
ares_set_servers_csv.html \
ares_set_servers_ports.html \
ares_set_servers_ports_csv.html \
ares_set_socket_callback.html \
ares_set_socket_configure_callback.html \
ares_set_sortlist.html \
ares_strerror.html \
ares_timeout.html \
ares_version.html \
ares_inet_pton.html \
ares_inet_ntop.html
PDFPAGES = ares_cancel.pdf \
ares_destroy.pdf \
ares_destroy_options.pdf \
ares_dup.pdf \
ares_expand_name.pdf \
ares_expand_string.pdf \
ares_fds.pdf \
ares_free_data.pdf \
ares_free_hostent.pdf \
ares_free_string.pdf \
ares_get_servers.pdf \
ares_get_servers_ports.pdf \
ares_gethostbyaddr.pdf \
ares_gethostbyname.pdf \
ares_gethostbyname_file.pdf \
ares_getnameinfo.pdf \
ares_getsock.pdf \
ares_init.pdf \
ares_init_options.pdf \
ares_library_cleanup.pdf \
ares_library_init.pdf \
ares_library_initialized.pdf \
ares_mkquery.pdf \
ares_create_query.pdf \
ares_parse_a_reply.pdf \
ares_parse_aaaa_reply.pdf \
ares_parse_mx_reply.pdf \
ares_parse_ns_reply.pdf \
ares_parse_ptr_reply.pdf \
ares_parse_soa_reply.pdf \
ares_parse_srv_reply.pdf \
ares_parse_txt_reply.pdf \
ares_process.pdf \
ares_query.pdf \
ares_save_options.pdf \
ares_search.pdf \
ares_send.pdf \
ares_set_local_dev.pdf \
ares_set_local_ip4.pdf \
ares_set_local_ip6.pdf \
ares_set_servers.pdf \
ares_set_servers_csv.pdf \
ares_set_servers_ports.pdf \
ares_set_servers_ports_csv.pdf \
ares_set_socket_callback.pdf \
ares_set_socket_configure_callback.pdf \
ares_set_sortlist.pdf \
ares_strerror.pdf \
ares_timeout.pdf \
ares_version.pdf \
ares_inet_pton.pdf \
ares_inet_ntop.pdf
SAMPLESOURCES = ares_getopt.c \
ares_nowarn.c \
ares_strcasecmp.c
SAMPLEHEADERS = ares_getopt.h \
ares_nowarn.h \
ares_strcasecmp.h

76
deps/c-ares/Makefile.m32 vendored Normal file
View File

@ -0,0 +1,76 @@
#############################################################
#
## Makefile for building libcares.a with MingW32 (GCC-3.2)
## Use: make -f Makefile.m32 [demos]
##
## Quick hack by Guenter; comments to: /dev/nul
#
########################################################
## Nothing more to do below this line!
LIB = libcares.a
AR = $(CROSSPREFIX)ar
CC = $(CROSSPREFIX)gcc
LD = $(CROSSPREFIX)gcc
RANLIB = $(CROSSPREFIX)ranlib
#RM = rm -f
CP = cp -afv
CFLAGS = $(CARES_CFLAG_EXTRAS) -O2 -Wall -I. -D_WIN32_WINNT=0x0600
CFLAGS += -DCARES_STATICLIB
LDFLAGS = $(CARES_LDFLAG_EXTRAS) -s
LIBS = -lwsock32
# Makefile.inc provides the CSOURCES and HHEADERS defines
include Makefile.inc
OBJLIB := $(patsubst %.c,%.o,$(strip $(CSOURCES)))
$(LIB): $(OBJLIB)
$(AR) cru $@ $^
$(RANLIB) $@
all: $(LIB) demos
demos: adig.exe ahost.exe acountry.exe
tags:
etags *.[ch]
%.exe: %.o ares_getopt.o $(LIB)
$(LD) $(LDFLAGS) -o $@ $^ $(LIBS)
$(OBJLIB): ares.h ares_dns.h ares_private.h ares_build.h ares_rules.h
.c.o:
$(CC) $(CFLAGS) -c $<
ares_build.h:
$(CP) ares_build.h.dist ares_build.h
check:
install:
${top_srcdir}/mkinstalldirs ${DESTDIR}${libdir}
${top_srcdir}/mkinstalldirs ${DESTDIR}${includedir}
${top_srcdir}/mkinstalldirs ${DESTDIR}${mandir}/man3
${INSTALL} -m 644 $(LIB) ${DESTDIR}${libdir}
${RANLIB} ${DESTDIR}${libdir}/$(LIB)
chmod u-w ${DESTDIR}${libdir}/$(LIB)
${INSTALL} -m 444 ${srcdir}/ares.h ${DESTDIR}${includedir}
${INSTALL} -m 444 ${srcdir}/ares_build.h ${DESTDIR}${includedir}
${INSTALL} -m 444 ${srcdir}/ares_rules.h ${DESTDIR}${includedir}
(for man in $(MANPAGES); do \
${INSTALL} -m 444 ${srcdir}/$${man} ${DESTDIR}${mandir}/man3; \
done)
clean:
$(RM) ares_getopt.o $(OBJLIB) $(LIB) adig.exe ahost.exe acountry.exe
distclean: clean
$(RM) config.cache config.log config.status Makefile
ifeq "$(wildcard ares_build.h.dist)" "ares_build.h.dist"
$(RM) ares_build.h
endif

470
deps/c-ares/Makefile.msvc vendored Normal file
View File

@ -0,0 +1,470 @@
# Copyright (C) 2009-2013 by Daniel Stenberg
#
# Permission to use, copy, modify, and distribute this
# software and its documentation for any purpose and without
# fee is hereby granted, provided that the above copyright
# notice appear in all copies and that both that copyright
# notice and this permission notice appear in supporting
# documentation, and that the name of M.I.T. not be used in
# advertising or publicity pertaining to distribution of the
# software without specific, written prior permission.
# M.I.T. makes no representations about the suitability of
# this software for any purpose. It is provided "as is"
# without express or implied warranty.
# ------------------------------------------------------------------------------
#
# Makefile for building c-ares libraries and sample programs with MSVC.
#
# Usage: nmake /f makefile.msvc CFG=<config> <target>
#
# <config> must be one of: [ lib-release | lib-debug | dll-release | dll-debug }
# <target> must be one of: [ ALL | c-ares | acountry | adig | ahost | clean }
#
# If a <target> other than ALL or clean is given, <config> becomes mandatory.
#
# If neither <config> nor <target> are specified this results in
# all targets being built for all <config> c-ares library types.
#
# This makefile must be processed from the subdir where it is located.
#
# All results are generated below a subdirectory named msvcXXX.
#
# ------------------------------------------------------------------------------
NAME = cares
# ------------------------------------------------
# c-ares static and dynamic libraries common base
# file names for release and debug configurations
# ------------------------------------------------
STA_LIB_REL = lib$(NAME)
DYN_LIB_REL = $(NAME)
STA_LIB_DBG = $(STA_LIB_REL)d
DYN_LIB_DBG = $(DYN_LIB_REL)d
# -------------------------------------------
# Base names for c-ares DLL import libraries
# -------------------------------------------
IMP_LIB_REL = $(DYN_LIB_REL)
IMP_LIB_DBG = $(DYN_LIB_DBG)
# --------------------------
# Runtime library selection
# --------------------------
RTLIB = /MD
RTLIBD = /MDd
!IF "$(RTLIBCFG)" == "static"
RTLIB = /MT
RTLIBD = /MTd
!ENDIF
# --------------------------------------------------------
# Define USE_WATT32 to 1 to use the Watt-32 tcp/ip stack,
# otherwise Winsock tcp/ip stack will be used as default.
# --------------------------------------------------------
USE_WATT32 = 0
# --------------------------------------------------------
# Detect compiler version.
# --------------------------------------------------------
!INCLUDE .\msvc_ver.inc
# ----------------------------------------------------
# Verify that current subdir is the c-ares source one
# ----------------------------------------------------
!IF ! EXIST(.\ares_init.c)
! MESSAGE Can not process Makefile.msvc from outside of c-ares source subdirectory.
! MESSAGE Change to the subdirectory where Makefile.msvc is found, and try again.
! ERROR See previous message.
!ENDIF
# ------------------------------------------------------------------
# Base subdir is the common root from which other subdirs will hang.
# ------------------------------------------------------------------
BASE_DIR = .\msvc
# ----------------------------------------
# Subdir holding sources for all projects
# ----------------------------------------
SRCDIR = .
# -----------------------------
# Default installation subdirs
# -----------------------------
!IFNDEF INSTALL_DIR
INSTALL_DIR = .
!ENDIF
!IFNDEF INSTALL_DIR_LIB
INSTALL_DIR_LIB = $(INSTALL_DIR)\lib
!ENDIF
!IFNDEF INSTALL_DIR_INC
INSTALL_DIR_INC = $(INSTALL_DIR)\include
!ENDIF
# -------------------------
# Configuration validation
# -------------------------
VALID_CFGSET = FALSE
!IF "$(CFG)" == "lib-release" || "$(CFG)" == "lib-debug" || \
"$(CFG)" == "dll-release" || "$(CFG)" == "dll-debug"
VALID_CFGSET = TRUE
!ENDIF
!IF "$(VALID_CFGSET)" == "FALSE" && "$(CFG)" != ""
! MESSAGE MSVC c-ares makefile
! MESSAGE
! MESSAGE Usage: nmake /f makefile.msvc CFG=<config> <target>
! MESSAGE
! MESSAGE <config> must be one of: [ lib-release | lib-debug | dll-release | dll-debug }
! MESSAGE <target> must be one of: [ ALL | c-ares | acountry | adig | ahost | clean }
! MESSAGE
! MESSAGE If a <target> other than ALL or clean is given, <config> becomes mandatory.
! MESSAGE
! MESSAGE If neither <config> nor <target> are specified this results in
! MESSAGE all targets being built for all <config> c-ares library types.
! MESSAGE
! ERROR Choose a valid configuration.
!ENDIF
# --------------------------------------------------------
# Project subdirs independent of configuration being used
# --------------------------------------------------------
CARES_DIR = $(BASE_DIR)\cares
PROG1_DIR = $(BASE_DIR)\acountry
PROG2_DIR = $(BASE_DIR)\adig
PROG3_DIR = $(BASE_DIR)\ahost
# ---------------------------------------------------
# Subdirs which are configuration dependent are only
# defined when a valid configuration has been given.
# ---------------------------------------------------
!IF "$(VALID_CFGSET)" == "TRUE"
CARES_OUTDIR = $(CARES_DIR)\$(CFG)
PROG1_OUTDIR = $(PROG1_DIR)\$(CFG)
PROG2_OUTDIR = $(PROG2_DIR)\$(CFG)
PROG3_OUTDIR = $(PROG3_DIR)\$(CFG)
CARES_OBJDIR = $(CARES_OUTDIR)\obj
PROG1_OBJDIR = $(PROG1_OUTDIR)\obj
PROG2_OBJDIR = $(PROG2_OUTDIR)\obj
PROG3_OBJDIR = $(PROG3_OUTDIR)\obj
!ELSE
!UNDEF CARES_OUTDIR
!UNDEF PROG1_OUTDIR
!UNDEF PROG2_OUTDIR
!UNDEF PROG3_OUTDIR
!UNDEF CARES_OBJDIR
!UNDEF PROG1_OBJDIR
!UNDEF PROG2_OBJDIR
!UNDEF PROG3_OBJDIR
!ENDIF
# -------------------------------------
# Settings that depend on tcp/ip stack
# -------------------------------------
!IF "$(USE_WATT32)" == "1"
CFLAGS = /UWIN32 /DWATT32 /I$(WATT_ROOT)\inc
EX_LIBS_REL = $(WATT_ROOT)\lib\wattcpvc_imp.lib
EX_LIBS_DBG = $(WATT_ROOT)\lib\wattcpvc_imp_d.lib
!ELSE
CFLAGS = /DWIN32 /D_WIN32_WINNT=0x0600
EX_LIBS_REL = ws2_32.lib advapi32.lib kernel32.lib
EX_LIBS_DBG = ws2_32.lib advapi32.lib kernel32.lib
!ENDIF
# -------------------------------------------------
# Switches that depend on ancient compiler versions
# -------------------------------------------------
!IF $(CC_VERS_NUM) == 60
PDB_NONE = /pdb:none
PDBTYPE_CONSOLIDATE = /pdbtype:consolidate
!ELSE
!UNDEF PDB_NONE
!UNDEF PDBTYPE_CONSOLIDATE
!ENDIF
!IF $(CC_VERS_NUM) <= 70
RT_ERROR_CHECKING = /GZ
!ELSE
RT_ERROR_CHECKING = /RTCsu
!ENDIF
# ----------------------------
# Assorted commands and flags
# ----------------------------
CC_CMD_REL = cl.exe /nologo $(RTLIB) /DNDEBUG /O2
CC_CMD_DBG = cl.exe /nologo $(RTLIBD) /D_DEBUG /Od /Zi $(RT_ERROR_CHECKING)
CC_CFLAGS = $(CFLAGS) /I. /W3 /EHsc /FD
RC_CMD_REL = rc.exe /l 0x409 /d "NDEBUG"
RC_CMD_DBG = rc.exe /l 0x409 /d "_DEBUG"
LINK_CMD_LIB = link.exe /lib /nologo
LINK_CMD_DLL = link.exe /dll /nologo /incremental:no /fixed:no
LINK_CMD_EXE = link.exe /nologo /incremental:no /fixed:no /subsystem:console
LINK_CMD_EXE_REL = $(LINK_CMD_EXE) /release $(PDB_NONE)
LINK_CMD_EXE_DBG = $(LINK_CMD_EXE) /debug $(PDBTYPE_CONSOLIDATE)
# ---------------------------------
# Configuration dependent settings
# ---------------------------------
!IF "$(CFG)" == "lib-release"
CARES_TARGET = $(STA_LIB_REL).lib
CARES_CFLAGS = /DCARES_BUILDING_LIBRARY /DCARES_STATICLIB
CARES_LFLAGS =
SPROG_CFLAGS = /DCARES_STATICLIB
SPROG_LFLAGS = /libpath:$(CARES_OUTDIR) $(EX_LIBS_REL) $(STA_LIB_REL).lib
CARES_LINK = $(LINK_CMD_LIB)
SPROG_LINK = $(LINK_CMD_EXE_REL)
CC_CMD = $(CC_CMD_REL)
!ENDIF
!IF "$(CFG)" == "lib-debug"
CARES_TARGET = $(STA_LIB_DBG).lib
CARES_CFLAGS = /DCARES_BUILDING_LIBRARY /DCARES_STATICLIB /DDEBUGBUILD
CARES_LFLAGS =
SPROG_CFLAGS = /DCARES_STATICLIB
SPROG_LFLAGS = /libpath:$(CARES_OUTDIR) $(EX_LIBS_DBG) $(STA_LIB_DBG).lib
CARES_LINK = $(LINK_CMD_LIB)
SPROG_LINK = $(LINK_CMD_EXE_DBG)
CC_CMD = $(CC_CMD_DBG)
!ENDIF
!IF "$(CFG)" == "dll-release"
CARES_TARGET = $(DYN_LIB_REL).dll
CARES_CFLAGS = /DCARES_BUILDING_LIBRARY
CARES_LFLAGS = /release $(EX_LIBS_REL) /implib:$(CARES_OUTDIR)\$(IMP_LIB_REL).lib $(PDB_NONE)
SPROG_CFLAGS =
SPROG_LFLAGS = /libpath:$(CARES_OUTDIR) $(EX_LIBS_REL) $(IMP_LIB_REL).lib
CARES_LINK = $(LINK_CMD_DLL)
SPROG_LINK = $(LINK_CMD_EXE_REL)
CC_CMD = $(CC_CMD_REL)
USE_RES_FILE = TRUE
RC_CMD = $(RC_CMD_REL)
!ENDIF
!IF "$(CFG)" == "dll-debug"
CARES_TARGET = $(DYN_LIB_DBG).dll
CARES_CFLAGS = /DCARES_BUILDING_LIBRARY /DDEBUGBUILD
CARES_LFLAGS = /debug $(EX_LIBS_DBG) /implib:$(CARES_OUTDIR)\$(IMP_LIB_DBG).lib /pdb:$(CARES_OUTDIR)\$(DYN_LIB_DBG).pdb $(PDBTYPE_CONSOLIDATE)
SPROG_CFLAGS =
SPROG_LFLAGS = /libpath:$(CARES_OUTDIR) $(EX_LIBS_DBG) $(IMP_LIB_DBG).lib
CARES_LINK = $(LINK_CMD_DLL)
SPROG_LINK = $(LINK_CMD_EXE_DBG)
CC_CMD = $(CC_CMD_DBG)
USE_RES_FILE = TRUE
RC_CMD = $(RC_CMD_DBG)
!ENDIF
# --------------------------------------------
# Makefile.inc provides lists of source files
# --------------------------------------------
!INCLUDE .\Makefile.inc
# ----------------------------
# Build lists of object files
# ----------------------------
!IF "$(VALID_CFGSET)" == "TRUE"
!IF [ECHO CARES_OBJS=^$(CARES_OBJDIR)\$(CSOURCES: = $(CARES_OBJDIR^)\) > .\cares_objs.inc] == 0
!INCLUDE .\cares_objs.inc
!IF [DEL .\cares_objs.inc]
!ENDIF
!ELSE
!ERROR Problem generating CARES_OBJS list.
!ENDIF
CARES_OBJS = $(CARES_OBJS:.c=.obj)
!IF "$(USE_RES_FILE)" == "TRUE"
CARES_OBJS = $(CARES_OBJS) $(CARES_OBJDIR)\cares.res
!ENDIF
!IF [ECHO PROG1_OBJS=^$(PROG1_OBJDIR)\$(SAMPLESOURCES: = $(PROG1_OBJDIR^)\) > .\prog1_objs.inc] == 0
!INCLUDE .\prog1_objs.inc
!IF [DEL .\prog1_objs.inc]
!ENDIF
!ELSE
!ERROR Problem generating PROG1_OBJS list.
!ENDIF
PROG1_OBJS = $(PROG1_OBJS:.c=.obj)
PROG1_OBJS = $(PROG1_OBJS) $(PROG1_OBJDIR)\acountry.obj
!IF [ECHO PROG2_OBJS=^$(PROG2_OBJDIR)\$(SAMPLESOURCES: = $(PROG2_OBJDIR^)\) > .\prog2_objs.inc] == 0
!INCLUDE .\prog2_objs.inc
!IF [DEL .\prog2_objs.inc]
!ENDIF
!ELSE
!ERROR Problem generating PROG2_OBJS list.
!ENDIF
PROG2_OBJS = $(PROG2_OBJS:.c=.obj)
PROG2_OBJS = $(PROG2_OBJS) $(PROG2_OBJDIR)\adig.obj
!IF [ECHO PROG3_OBJS=^$(PROG3_OBJDIR)\$(SAMPLESOURCES: = $(PROG3_OBJDIR^)\) > .\prog3_objs.inc] == 0
!INCLUDE .\prog3_objs.inc
!IF [DEL .\prog3_objs.inc]
!ENDIF
!ELSE
!ERROR Problem generating PROG3_OBJS list.
!ENDIF
PROG3_OBJS = $(PROG3_OBJS:.c=.obj)
PROG3_OBJS = $(PROG3_OBJS) $(PROG3_OBJDIR)\ahost.obj
!ENDIF
# --------------------------------
# Only our custom inference rules
# --------------------------------
.SUFFIXES:
.SUFFIXES: .c .rc
{$(SRCDIR)}.rc{$(CARES_OBJDIR)}.res:
$(RC_CMD) /Fo $@ $<
{$(SRCDIR)}.c{$(CARES_OBJDIR)}.obj:
$(CC_CMD) $(CC_CFLAGS) $(CARES_CFLAGS) /Fo$@ /Fd$(@D)\ /c $<
{$(SRCDIR)}.c{$(PROG1_OBJDIR)}.obj:
$(CC_CMD) $(CC_CFLAGS) $(SPROG_CFLAGS) /Fo$@ /Fd$(@D)\ /c $<
{$(SRCDIR)}.c{$(PROG2_OBJDIR)}.obj:
$(CC_CMD) $(CC_CFLAGS) $(SPROG_CFLAGS) /Fo$@ /Fd$(@D)\ /c $<
{$(SRCDIR)}.c{$(PROG3_OBJDIR)}.obj:
$(CC_CMD) $(CC_CFLAGS) $(SPROG_CFLAGS) /Fo$@ /Fd$(@D)\ /c $<
# ------------------------------------------------------------- #
# ------------------------------------------------------------- #
# Default target when no CFG library type has been specified, #
# results in building target ALL for all c-ares library types. #
# ------------------------------------------------------------- #
# ------------------------------------------------------------- #
!IF "$(VALID_CFGSET)" == "FALSE"
ALL:
$(MAKE) /f .\Makefile.msvc CFG=lib-release ALL
$(MAKE) /f .\Makefile.msvc CFG=lib-debug ALL
$(MAKE) /f .\Makefile.msvc CFG=dll-release ALL
$(MAKE) /f .\Makefile.msvc CFG=dll-debug ALL
clean:
@-RMDIR /S /Q $(BASE_DIR) >NUL 2>&1
install:
@$(MAKE) /nologo /f .\Makefile.msvc CFG=lib-release install
@$(MAKE) /nologo /f .\Makefile.msvc CFG=lib-debug install
@$(MAKE) /nologo /f .\Makefile.msvc CFG=dll-release install
@$(MAKE) /nologo /f .\Makefile.msvc CFG=dll-debug install
!ENDIF
# ---------------------------------------------------------------------
# Targets only available when a proper CFG library type has been given
# ---------------------------------------------------------------------
!IF "$(VALID_CFGSET)" == "TRUE"
ALL: c-ares acountry adig ahost
@
c-ares: $(HHEADERS) $(CSOURCES) $(CARES_OBJDIR) $(CARES_OBJS) $(CARES_OUTDIR)
$(CARES_LINK) $(CARES_LFLAGS) /out:$(CARES_OUTDIR)\$(CARES_TARGET) $(CARES_OBJS)
! IF "$(USE_RES_FILE)" == "TRUE"
@if exist $(CARES_OUTDIR)\$(CARES_TARGET).manifest mt -nologo -manifest $(CARES_OUTDIR)\$(CARES_TARGET).manifest -outputresource:$(CARES_OUTDIR)\$(CARES_TARGET);2
! ENDIF
acountry: c-ares acountry.c $(SAMPLESOURCES) $(SAMPLEHEADERS) $(PROG1_OBJDIR) $(PROG1_OBJS) $(PROG1_OUTDIR)
$(SPROG_LINK) $(SPROG_LFLAGS) /out:$(PROG1_OUTDIR)\acountry.exe $(PROG1_OBJS)
@if exist $(PROG1_OUTDIR)\acountry.exe.manifest mt -nologo -manifest $(PROG1_OUTDIR)\acountry.exe.manifest -outputresource:$(PROG1_OUTDIR)\acountry.exe;1
adig: c-ares adig.c $(SAMPLESOURCES) $(SAMPLEHEADERS) $(PROG2_OBJDIR) $(PROG2_OBJS) $(PROG2_OUTDIR)
$(SPROG_LINK) $(SPROG_LFLAGS) /out:$(PROG2_OUTDIR)\adig.exe $(PROG2_OBJS)
@if exist $(PROG2_OUTDIR)\adig.exe.manifest mt -nologo -manifest $(PROG2_OUTDIR)\adig.exe.manifest -outputresource:$(PROG2_OUTDIR)\adig.exe;1
ahost: c-ares ahost.c $(SAMPLESOURCES) $(SAMPLEHEADERS) $(PROG3_OBJDIR) $(PROG3_OBJS) $(PROG3_OUTDIR)
$(SPROG_LINK) $(SPROG_LFLAGS) /out:$(PROG3_OUTDIR)\ahost.exe $(PROG3_OBJS)
@if exist $(PROG3_OUTDIR)\ahost.exe.manifest mt -nologo -manifest $(PROG3_OUTDIR)\ahost.exe.manifest -outputresource:$(PROG3_OUTDIR)\ahost.exe;1
$(CARES_OUTDIR): $(CARES_DIR)
@if not exist $(CARES_OUTDIR) mkdir $(CARES_OUTDIR)
$(PROG1_OUTDIR): $(PROG1_DIR)
@if not exist $(PROG1_OUTDIR) mkdir $(PROG1_OUTDIR)
$(PROG2_OUTDIR): $(PROG2_DIR)
@if not exist $(PROG2_OUTDIR) mkdir $(PROG2_OUTDIR)
$(PROG3_OUTDIR): $(PROG3_DIR)
@if not exist $(PROG3_OUTDIR) mkdir $(PROG3_OUTDIR)
$(CARES_OBJDIR): $(CARES_OUTDIR)
@if not exist $(CARES_OBJDIR) mkdir $(CARES_OBJDIR)
$(PROG1_OBJDIR): $(PROG1_OUTDIR)
@if not exist $(PROG1_OBJDIR) mkdir $(PROG1_OBJDIR)
$(PROG2_OBJDIR): $(PROG2_OUTDIR)
@if not exist $(PROG2_OBJDIR) mkdir $(PROG2_OBJDIR)
$(PROG3_OBJDIR): $(PROG3_OUTDIR)
@if not exist $(PROG3_OBJDIR) mkdir $(PROG3_OBJDIR)
clean:
@-RMDIR /S /Q $(CARES_OUTDIR) >NUL 2>&1
@-RMDIR /S /Q $(PROG1_OUTDIR) >NUL 2>&1
@-RMDIR /S /Q $(PROG2_OUTDIR) >NUL 2>&1
@-RMDIR /S /Q $(PROG3_OUTDIR) >NUL 2>&1
install:
@if not exist $(CARES_OUTDIR)\$(CARES_TARGET) \
$(MAKE) /f .\Makefile.msvc CFG=$(CFG) c-ares
@if not exist "$(INSTALL_DIR)" mkdir "$(INSTALL_DIR)"
@if not exist "$(INSTALL_DIR_LIB)" mkdir "$(INSTALL_DIR_LIB)"
@if not exist "$(INSTALL_DIR_INC)" mkdir "$(INSTALL_DIR_INC)"
@copy /y $(CARES_OUTDIR)\*.* "$(INSTALL_DIR_LIB)" >NUL
@copy /y $(SRCDIR)\ares.h "$(INSTALL_DIR_INC)" >NUL
@copy /y $(SRCDIR)\ares_build.h "$(INSTALL_DIR_INC)" >NUL
@copy /y $(SRCDIR)\ares_rules.h "$(INSTALL_DIR_INC)" >NUL
@copy /y $(SRCDIR)\ares_version.h "$(INSTALL_DIR_INC)" >NUL
@echo Installed c-ares $(CFG)
!ENDIF
$(BASE_DIR):
@if not exist $(BASE_DIR) mkdir $(BASE_DIR)
$(CARES_DIR): $(BASE_DIR)
@if not exist $(CARES_DIR) mkdir $(CARES_DIR)
$(PROG1_DIR): $(BASE_DIR)
@if not exist $(PROG1_DIR) mkdir $(PROG1_DIR)
$(PROG2_DIR): $(BASE_DIR)
@if not exist $(PROG2_DIR) mkdir $(PROG2_DIR)
$(PROG3_DIR): $(BASE_DIR)
@if not exist $(PROG3_DIR) mkdir $(PROG3_DIR)
# End of Makefile.msvc

432
deps/c-ares/Makefile.netware vendored Normal file
View File

@ -0,0 +1,432 @@
#################################################################
#
## Makefile for building libcares (NetWare version - gnu make)
## Use: make -f Makefile.netware
##
## Comments to: Guenter Knauf http://www.gknw.de/phpbb
#
#################################################################
# Edit the path below to point to the base of your Novell NDK.
ifndef NDKBASE
NDKBASE = c:/novell
endif
ifndef INSTDIR
INSTDIR = ../ares-$(LIBCARES_VERSION_STR)-bin-nw
endif
# Edit the vars below to change NLM target settings.
TARGETS = adig.nlm ahost.nlm acountry.nlm
LTARGET = libcares.$(LIBEXT)
VERSION = $(LIBCARES_VERSION)
COPYR = $(LIBCARES_COPYRIGHT_STR)
DESCR = cURL $(subst .def,,$(notdir $@)) $(LIBCARES_VERSION_STR) - http://curl.haxx.se
MTSAFE = YES
STACK = 64000
SCREEN = none
#EXPORTS =
# Comment the line below if you dont want to load protected automatically.
#LDRING = 3
# Edit the var below to point to your lib architecture.
ifndef LIBARCH
LIBARCH = LIBC
endif
# must be equal to NDEBUG or DEBUG, CURLDEBUG
ifndef DB
DB = NDEBUG
endif
# Optimization: -O<n> or debugging: -g
ifeq ($(DB),NDEBUG)
OPT = -O2
OBJDIR = release
else
OPT = -g
OBJDIR = debug
endif
# Include the version info retrieved from curlver.h
-include $(OBJDIR)/version.inc
# The following lines defines your compiler.
ifdef CWFolder
METROWERKS = $(CWFolder)
endif
ifdef METROWERKS
# MWCW_PATH = $(subst \,/,$(METROWERKS))/Novell Support
MWCW_PATH = $(subst \,/,$(METROWERKS))/Novell Support/Metrowerks Support
CC = mwccnlm
else
CC = gcc
endif
# a native win32 awk can be downloaded from here:
# http://www.gknw.net/development/prgtools/awk-20070501.zip
AWK = awk
YACC = bison -y
CP = cp -afv
MKDIR = mkdir
# RM = rm -f
# if you want to mark the target as MTSAFE you will need a tool for
# generating the xdc data for the linker; here's a minimal tool:
# http://www.gknw.net/development/prgtools/mkxdc.zip
MPKXDC = mkxdc
# Global flags for all compilers
CFLAGS += $(OPT) -D$(DB) -DNETWARE -DHAVE_CONFIG_H -nostdinc
ifeq ($(CC),mwccnlm)
LD = mwldnlm
LDFLAGS = -nostdlib $(PRELUDE) $(OBJEXE) $(<:.def=.o) -o $@ -commandfile
AR = mwldnlm
ARFLAGS = -nostdlib -type library -o
LIBEXT = lib
#RANLIB =
CFLAGS += -msgstyle gcc -gccinc -inline off -opt nointrinsics -proc 586
CFLAGS += -relax_pointers
#CFLAGS += -w on
ifeq ($(LIBARCH),LIBC)
PRELUDE = $(SDK_LIBC)/imports/libcpre.o
CFLAGS += -align 4
else
# PRELUDE = $(SDK_CLIB)/imports/clibpre.o
# to avoid the __init_* / __deinit_* whoes dont use prelude from NDK
PRELUDE = "$(MWCW_PATH)/libraries/runtime/prelude.obj"
# CFLAGS += -include "$(MWCW_PATH)/headers/nlm_clib_prefix.h"
CFLAGS += -align 1
endif
else
LD = nlmconv
LDFLAGS = -T
AR = ar
ARFLAGS = -cq
LIBEXT = a
RANLIB = ranlib
CFLAGS += -m32
CFLAGS += -fno-builtin -fno-strict-aliasing
ifeq ($(findstring gcc,$(CC)),gcc)
CFLAGS += -fpcc-struct-return
endif
CFLAGS += -Wall # -pedantic
ifeq ($(LIBARCH),LIBC)
PRELUDE = $(SDK_LIBC)/imports/libcpre.gcc.o
else
# PRELUDE = $(SDK_CLIB)/imports/clibpre.gcc.o
# to avoid the __init_* / __deinit_* whoes dont use prelude from NDK
# http://www.gknw.net/development/mk_nlm/gcc_pre.zip
PRELUDE = $(NDK_ROOT)/pre/prelude.o
CFLAGS += -include $(NDKBASE)/nlmconv/genlm.h
endif
endif
NDK_ROOT = $(NDKBASE)/ndk
SDK_CLIB = $(NDK_ROOT)/nwsdk
SDK_LIBC = $(NDK_ROOT)/libc
ifeq ($(LIBARCH),LIBC)
INCLUDES += -I$(SDK_LIBC)/include
# INCLUDES += -I$(SDK_LIBC)/include/nks
# INCLUDES += -I$(SDK_LIBC)/include/winsock
CFLAGS += -D_POSIX_SOURCE
else
INCLUDES += -I$(SDK_CLIB)/include/nlm
# INCLUDES += -I$(SDK_CLIB)/include/nlm/obsolete
# INCLUDES += -I$(SDK_CLIB)/include
endif
ifeq ($(DB),CURLDEBUG)
INCLUDES += -I../include
endif
CFLAGS += -I. $(INCLUDES)
ifeq ($(MTSAFE),YES)
XDCOPT = -n
endif
ifeq ($(MTSAFE),NO)
XDCOPT = -u
endif
ifeq ($(findstring /sh,$(SHELL)),/sh)
DL = '
#-include $(NDKBASE)/nlmconv/ncpfs.inc
endif
# Makefile.inc provides the CSOURCES and HHEADERS defines
include Makefile.inc
OBJLIB := $(patsubst %.c,$(OBJDIR)/%.o,$(strip $(CSOURCES)))
OBJEXE = $(OBJLIB) $(OBJDIR)/ares_getopt.o
.PHONY: lib nlm prebuild dist install clean
lib: prebuild $(LTARGET)
nlm: prebuild $(TARGETS)
prebuild: $(OBJDIR) ares_build.h $(OBJDIR)/version.inc ares_config.h
install: $(INSTDIR) all
@$(CP) *.nlm $(INSTDIR)
@$(CP) ../CHANGES $(INSTDIR)
@$(CP) ../COPYING $(INSTDIR)
@$(CP) ../README $(INSTDIR)
@$(CP) ../RELEASE-NOTES $(INSTDIR)
clean:
-$(RM) $(LTARGET) $(TARGETS) ares_config.h
-$(RM) -r $(OBJDIR)
-$(RM) -r arpa
%.$(LIBEXT): $(OBJLIB)
@echo Creating $@
@-$(RM) $@
@$(AR) $(ARFLAGS) $@ $^
ifdef RANLIB
@$(RANLIB) $@
endif
%.nlm: $(OBJDIR)/%.def $(OBJDIR)/%.o $(OBJDIR)/%.xdc $(OBJEXE)
@echo Linking $@
@-$(RM) $@
@$(LD) $(LDFLAGS) $<
$(OBJDIR) $(INSTDIR):
@$(MKDIR) $@
$(OBJDIR)/%.o: %.c
# @echo Compiling $<
$(CC) $(CFLAGS) -c $< -o $@
$(OBJDIR)/version.inc: ares_version.h $(OBJDIR)
@echo Creating $@
@$(AWK) -f get_ver.awk $< > $@
$(OBJDIR)/%.xdc: Makefile.netware
@echo Creating $@
@$(MPKXDC) $(XDCOPT) $@
$(OBJDIR)/%.def: Makefile.netware
@echo Creating $@
@echo $(DL)# DEF file for linking with $(LD)$(DL) > $@
@echo $(DL)# Do not edit this file - it is created by make!$(DL) >> $@
@echo $(DL)# All your changes will be lost!!$(DL) >> $@
@echo $(DL)#$(DL) >> $@
@echo $(DL)copyright "$(COPYR)"$(DL) >> $@
@echo $(DL)description "$(DESCR)"$(DL) >> $@
@echo $(DL)version $(VERSION)$(DL) >> $@
ifdef NLMTYPE
@echo $(DL)type $(NLMTYPE)$(DL) >> $@
endif
ifdef STACK
@echo $(DL)stack $(STACK)$(DL) >> $@
endif
ifdef SCREEN
@echo $(DL)screenname "$(SCREEN)"$(DL) >> $@
else
@echo $(DL)screenname "DEFAULT"$(DL) >> $@
endif
ifeq ($(DB),DEBUG)
@echo $(DL)debug$(DL) >> $@
endif
@echo $(DL)threadname "$^"$(DL) >> $@
ifdef XDCOPT
@echo $(DL)xdcdata $(@:.def=.xdc)$(DL) >> $@
endif
ifeq ($(LDRING),0)
@echo $(DL)flag_on 16$(DL) >> $@
endif
ifeq ($(LDRING),3)
@echo $(DL)flag_on 512$(DL) >> $@
endif
ifeq ($(LIBARCH),CLIB)
@echo $(DL)start _Prelude$(DL) >> $@
@echo $(DL)exit _Stop$(DL) >> $@
@echo $(DL)import @$(SDK_CLIB)/imports/clib.imp$(DL) >> $@
@echo $(DL)import @$(SDK_CLIB)/imports/threads.imp$(DL) >> $@
@echo $(DL)import @$(SDK_CLIB)/imports/nlmlib.imp$(DL) >> $@
@echo $(DL)import @$(SDK_CLIB)/imports/socklib.imp$(DL) >> $@
@echo $(DL)module clib$(DL) >> $@
else
@echo $(DL)flag_on 64$(DL) >> $@
@echo $(DL)pseudopreemption$(DL) >> $@
@echo $(DL)start _LibCPrelude$(DL) >> $@
@echo $(DL)exit _LibCPostlude$(DL) >> $@
@echo $(DL)check _LibCCheckUnload$(DL) >> $@
@echo $(DL)import @$(SDK_LIBC)/imports/libc.imp$(DL) >> $@
@echo $(DL)import @$(SDK_LIBC)/imports/netware.imp$(DL) >> $@
@echo $(DL)module libc$(DL) >> $@
endif
ifdef MODULES
@echo $(DL)module $(MODULES)$(DL) >> $@
endif
ifdef EXPORTS
@echo $(DL)export $(EXPORTS)$(DL) >> $@
endif
ifdef IMPORTS
@echo $(DL)import $(IMPORTS)$(DL) >> $@
endif
ifeq ($(LD),nlmconv)
@echo $(DL)input $(PRELUDE)$(DL) >> $@
@echo $(DL)input $(OBJEXE)$(DL) >> $@
@echo $(DL)input $(@:.def=.o)$(DL) >> $@
@echo $(DL)output $(notdir $(@:.def=.nlm))$(DL) >> $@
endif
ares_config.h: Makefile.netware
@echo Creating $@
@echo $(DL)/* $@ for NetWare target.$(DL) > $@
@echo $(DL)** Do not edit this file - it is created by make!$(DL) >> $@
@echo $(DL)** All your changes will be lost!!$(DL) >> $@
@echo $(DL)*/$(DL) >> $@
@echo $(DL)#ifndef NETWARE$(DL) >> $@
@echo $(DL)#error This $(notdir $@) is created for NetWare platform!$(DL) >> $@
@echo $(DL)#endif$(DL) >> $@
@echo $(DL)#define VERSION "$(LIBCARES_VERSION_STR)"$(DL) >> $@
@echo $(DL)#define PACKAGE_BUGREPORT "a suitable curl mailing list => http://curl.haxx.se/mail/"$(DL) >> $@
ifeq ($(LIBARCH),CLIB)
@echo $(DL)#define OS "i586-pc-clib-NetWare"$(DL) >> $@
@echo $(DL)#define HAVE_STRICMP 1$(DL) >> $@
@echo $(DL)#define HAVE_STRNICMP 1$(DL) >> $@
@echo $(DL)#define NETDB_USE_INTERNET 1$(DL) >> $@
@echo $(DL)#define RECV_TYPE_ARG1 int$(DL) >> $@
@echo $(DL)#define RECV_TYPE_ARG2 char *$(DL) >> $@
@echo $(DL)#define RECV_TYPE_ARG3 int$(DL) >> $@
@echo $(DL)#define RECV_TYPE_ARG4 int$(DL) >> $@
@echo $(DL)#define RECV_TYPE_RETV int$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG1 int$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG2 char$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG3 int$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG4 int$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG5 struct sockaddr$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG6 int$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_RETV int$(DL) >> $@
@echo $(DL)#define SEND_QUAL_ARG2$(DL) >> $@
@echo $(DL)#define SEND_TYPE_ARG1 int$(DL) >> $@
@echo $(DL)#define SEND_TYPE_ARG2 char *$(DL) >> $@
@echo $(DL)#define SEND_TYPE_ARG3 int$(DL) >> $@
@echo $(DL)#define SEND_TYPE_ARG4 int$(DL) >> $@
@echo $(DL)#define SEND_TYPE_RETV int$(DL) >> $@
else
@echo $(DL)#define OS "i586-pc-libc-NetWare"$(DL) >> $@
@echo $(DL)#define HAVE_DLFCN_H 1$(DL) >> $@
@echo $(DL)#define HAVE_DLOPEN 1$(DL) >> $@
@echo $(DL)#define HAVE_FTRUNCATE 1$(DL) >> $@
@echo $(DL)#define HAVE_GETTIMEOFDAY 1$(DL) >> $@
@echo $(DL)#define HAVE_INTTYPES_H 1$(DL) >> $@
@echo $(DL)#define HAVE_LONGLONG 1$(DL) >> $@
@echo $(DL)#define HAVE_STDINT_H 1$(DL) >> $@
@echo $(DL)#define HAVE_STRCASECMP 1$(DL) >> $@
@echo $(DL)#define HAVE_STRLCAT 1$(DL) >> $@
@echo $(DL)#define HAVE_STRLCPY 1$(DL) >> $@
@echo $(DL)#define HAVE_STRTOLL 1$(DL) >> $@
@echo $(DL)#define HAVE_SYS_PARAM_H 1$(DL) >> $@
@echo $(DL)#define HAVE_SYS_SELECT_H 1$(DL) >> $@
@echo $(DL)#define HAVE_TERMIOS_H 1$(DL) >> $@
@echo $(DL)#define HAVE_AF_INET6 1$(DL) >> $@
@echo $(DL)#define HAVE_PF_INET6 1$(DL) >> $@
@echo $(DL)#define HAVE_FREEADDRINFO 1$(DL) >> $@
@echo $(DL)#define HAVE_GETADDRINFO 1$(DL) >> $@
@echo $(DL)#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1$(DL) >> $@
@echo $(DL)#define HAVE_STRUCT_IN6_ADDR 1$(DL) >> $@
@echo $(DL)#define HAVE_STRUCT_SOCKADDR_IN6 1$(DL) >> $@
@echo $(DL)#define RECV_TYPE_ARG1 int$(DL) >> $@
@echo $(DL)#define RECV_TYPE_ARG2 void *$(DL) >> $@
@echo $(DL)#define RECV_TYPE_ARG3 size_t$(DL) >> $@
@echo $(DL)#define RECV_TYPE_ARG4 int$(DL) >> $@
@echo $(DL)#define RECV_TYPE_RETV ssize_t$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG1 int$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG2 void$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG3 size_t$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG4 int$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG5 struct sockaddr$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG6 size_t$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_RETV ssize_t$(DL) >> $@
@echo $(DL)#define RECVFROM_TYPE_ARG2_IS_VOID 1$(DL) >> $@
@echo $(DL)#define SEND_QUAL_ARG2$(DL) >> $@
@echo $(DL)#define SEND_TYPE_ARG1 int$(DL) >> $@
@echo $(DL)#define SEND_TYPE_ARG2 void *$(DL) >> $@
@echo $(DL)#define SEND_TYPE_ARG3 size_t$(DL) >> $@
@echo $(DL)#define SEND_TYPE_ARG4 int$(DL) >> $@
@echo $(DL)#define SEND_TYPE_RETV ssize_t$(DL) >> $@
endif
@echo $(DL)#define HAVE_ARPA_INET_H 1$(DL) >> $@
@echo $(DL)#define HAVE_ASSERT_H 1$(DL) >> $@
@echo $(DL)#define HAVE_ERRNO_H 1$(DL) >> $@
@echo $(DL)#define HAVE_ERR_H 1$(DL) >> $@
@echo $(DL)#define HAVE_FCNTL_H 1$(DL) >> $@
@echo $(DL)#define HAVE_GETENV 1$(DL) >> $@
@echo $(DL)#define HAVE_GETHOSTBYADDR 1$(DL) >> $@
@echo $(DL)#define HAVE_GETHOSTBYNAME 1$(DL) >> $@
@echo $(DL)#define HAVE_GETHOSTNAME 1$(DL) >> $@
@echo $(DL)#define HAVE_GETPROTOBYNAME 1$(DL) >> $@
@echo $(DL)#define HAVE_GMTIME_R 1$(DL) >> $@
@echo $(DL)#define HAVE_INET_ADDR 1$(DL) >> $@
@echo $(DL)#define HAVE_IOCTL 1$(DL) >> $@
@echo $(DL)#define HAVE_IOCTL_FIONBIO 1$(DL) >> $@
@echo $(DL)#define HAVE_LIMITS_H 1$(DL) >> $@
@echo $(DL)#define HAVE_LL 1$(DL) >> $@
@echo $(DL)#define HAVE_LOCALTIME_R 1$(DL) >> $@
@echo $(DL)#define HAVE_MALLOC_H 1$(DL) >> $@
@echo $(DL)#define HAVE_NETINET_IN_H 1$(DL) >> $@
@echo $(DL)#define HAVE_RECV 1$(DL) >> $@
@echo $(DL)#define HAVE_RECVFROM 1$(DL) >> $@
@echo $(DL)#define HAVE_SELECT 1$(DL) >> $@
@echo $(DL)#define HAVE_SEND 1$(DL) >> $@
@echo $(DL)#define HAVE_SETJMP_H 1$(DL) >> $@
@echo $(DL)#define HAVE_SIGNAL 1$(DL) >> $@
@echo $(DL)#define HAVE_SIGNAL_H 1$(DL) >> $@
@echo $(DL)#define HAVE_SIG_ATOMIC_T 1$(DL) >> $@
@echo $(DL)#define HAVE_SOCKET 1$(DL) >> $@
@echo $(DL)#define HAVE_STDLIB_H 1$(DL) >> $@
@echo $(DL)#define HAVE_STRDUP 1$(DL) >> $@
@echo $(DL)#define HAVE_STRFTIME 1$(DL) >> $@
@echo $(DL)#define HAVE_STRING_H 1$(DL) >> $@
@echo $(DL)#define HAVE_STRSTR 1$(DL) >> $@
@echo $(DL)#define HAVE_STRUCT_ADDRINFO 1$(DL) >> $@
@echo $(DL)#define HAVE_STRUCT_TIMEVAL 1$(DL) >> $@
@echo $(DL)#define HAVE_SYS_IOCTL_H 1$(DL) >> $@
@echo $(DL)#define HAVE_SYS_STAT_H 1$(DL) >> $@
@echo $(DL)#define HAVE_SYS_TIME_H 1$(DL) >> $@
@echo $(DL)#define HAVE_TIME_H 1$(DL) >> $@
@echo $(DL)#define HAVE_UNAME 1$(DL) >> $@
@echo $(DL)#define HAVE_UNISTD_H 1$(DL) >> $@
@echo $(DL)#define HAVE_UTIME 1$(DL) >> $@
@echo $(DL)#define HAVE_UTIME_H 1$(DL) >> $@
@echo $(DL)#define HAVE_WRITEV 1$(DL) >> $@
@echo $(DL)#define RETSIGTYPE void$(DL) >> $@
@echo $(DL)#define STDC_HEADERS 1$(DL) >> $@
@echo $(DL)#define TIME_WITH_SYS_TIME 1$(DL) >> $@
ifdef NW_WINSOCK
@echo $(DL)#define HAVE_CLOSESOCKET 1$(DL) >> $@
else
@echo $(DL)#define HAVE_SYS_TYPES_H 1$(DL) >> $@
@echo $(DL)#define HAVE_SYS_SOCKET_H 1$(DL) >> $@
@echo $(DL)#define HAVE_SYS_SOCKIO_H 1$(DL) >> $@
@echo $(DL)#define HAVE_NETDB_H 1$(DL) >> $@
endif
@echo $(DL)#ifdef __GNUC__$(DL) >> $@
@echo $(DL)#define HAVE_VARIADIC_MACROS_GCC 1$(DL) >> $@
@echo $(DL)#else$(DL) >> $@
@echo $(DL)#define HAVE_VARIADIC_MACROS_C99 1$(DL) >> $@
@echo $(DL)#endif$(DL) >> $@
FORCE: ;
ares_build.h: Makefile.netware FORCE
@echo Creating $@
@echo $(DL)/* $@ intended for NetWare target.$(DL) > $@
@echo $(DL)** Do not edit this file - it is created by make!$(DL) >> $@
@echo $(DL)** All your changes will be lost!!$(DL) >> $@
@echo $(DL)*/$(DL) >> $@
@echo $(DL)#ifndef NETWARE$(DL) >> $@
@echo $(DL)#error This $(notdir $@) is created for NetWare platform!$(DL) >> $@
@echo $(DL)#endif$(DL) >> $@
@echo $(DL)#ifndef __CARES_BUILD_H$(DL) >> $@
@echo $(DL)#define __CARES_BUILD_H$(DL) >> $@
ifeq ($(LIBARCH),CLIB)
@echo $(DL)#define CARES_TYPEOF_ARES_SOCKLEN_T int$(DL) >> $@
else
@echo $(DL)#define CARES_TYPEOF_ARES_SOCKLEN_T unsigned int$(DL) >> $@
endif
@echo $(DL)typedef CARES_TYPEOF_ARES_SOCKLEN_T ares_socklen_t;$(DL) >> $@
@echo $(DL)#endif /* __CARES_BUILD_H */$(DL) >> $@

21
deps/c-ares/NEWS vendored Normal file
View File

@ -0,0 +1,21 @@
Major changes since:
* see the CHANGES file
Major changes in release 1.1.1:
* ares should now compile as C++ code (no longer uses reserved word
"class").
* Added SRV support to adig test program.
* Fixed a few error handling bugs in query processing.
Major changes in release 1.1.0:
* Added ares_free_string() function so that memory can be freed in the
same layer as it is allocated, a desirable feature in some
environments.
* A few of the ares_dns.h macros are fixed to use the proper bitwise
operator.
* Fixed a couple of fenceposts fixed in ares_expand_name()'s
bounds-checking.
* In process_timeouts(), extract query->next before calling
next_server() and possibly freeing the query structure.
* Casted arguments to ctype macros casted to unsigned char, since not
all char values are valid inputs to those macros according to ANSI.

15
deps/c-ares/README.cares vendored Normal file
View File

@ -0,0 +1,15 @@
c-ares
======
This package is based on ares 1.1.1 (written by Greg Hudson). Daniel Stenberg
decided to fork and release a separate project since the original ares author
didn't want the improvements that were vital for our use of it.
This package is dubbed 'c-ares' since Daniel wanted this for use within the
curl project (hence the letter C) and it makes a nice pun. c-ares is not API
compatible with ares: a new name makes that more obvious to the public.
The original libares was distributed at
ftp://athena-dist.mit.edu:pub/ATHENA/ares (which seems to not be alive
anymore). A local copy of the original ares package is kept here:
https://c-ares.haxx.se/download/ares-1.1.1.tar.gz

66
deps/c-ares/README.md vendored Normal file
View File

@ -0,0 +1,66 @@
c-ares
======
[![Build Status](https://travis-ci.org/c-ares/c-ares.svg?branch=master)](https://travis-ci.org/c-ares/c-ares)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/03i7151772eq3wn3/branch/master?svg=true)](https://ci.appveyor.com/project/c-ares/c-ares)
[![Coverage Status](https://coveralls.io/repos/c-ares/c-ares/badge.svg?branch=master&service=github)](https://coveralls.io/github/c-ares/c-ares?branch=master)
[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/291/badge)](https://bestpractices.coreinfrastructure.org/projects/291)
[![Releases](https://coderelease.io/badge/c-ares/c-ares)](https://coderelease.io/github/repository/c-ares/c-ares)
This is c-ares, an asynchronous resolver library. It is intended for
applications which need to perform DNS queries without blocking, or need to
perform multiple DNS queries in parallel. The primary examples of such
applications are servers which communicate with multiple clients and programs
with graphical user interfaces.
The full source code is available in the ['c-ares' release archives](https://c-ares.haxx.se/download/),
and in a git repository: http://github.com/c-ares/c-ares. See the
[INSTALL.md](INSTALL.md) file for build information.
If you find bugs, correct flaws, have questions or have comments in general in
regard to c-ares (or by all means the original ares too), get in touch with us
on the c-ares mailing list: http://cool.haxx.se/mailman/listinfo/c-ares
c-ares is of course distributed under the same MIT-style license as the
original ares.
You'll find all c-ares details and news here:
https://c-ares.haxx.se/
Notes for c-ares hackers
------------------------
* The distributed `ares_build.h` file is only intended to be used on systems
which can not run the also distributed configure script.
* The distributed `ares_build.h` file is generated as a copy of `ares_build.h.dist`
when the c-ares source code distribution archive file is originally created.
* If you check out from git on a non-configure platform, you must run the
appropriate `buildconf*` script to set up `ares_build.h` and other local files
before being able to compile the library.
* On systems capable of running the `configure` script, the `configure` process
will overwrite the distributed `ares_build.h` file with one that is suitable
and specific to the library being configured and built, this new file is
generated from the `ares_build.h.in` template file.
* If you intend to distribute an already compiled c-ares library you **MUST**
also distribute along with it the generated `ares_build.h` which has been
used to compile it. Otherwise the library will be of no use for the users of
the library that you have built. It is **your** responsibility to provide this
file. No one at the c-ares project can know how you have built the library.
* File `ares_build.h` includes platform and configuration dependent info,
and must not be modified by anyone. Configure script generates it for you.
* We cannot assume anything else but very basic compiler features being
present. While c-ares requires an ANSI C compiler to build, some of the
earlier ANSI compilers clearly can't deal with some preprocessor operators.
* Newlines must remain unix-style for older compilers' sake.
* Comments must be written in the old-style /* unnested C-fashion */
* Try to keep line lengths below 80 columns.

142
deps/c-ares/README.msvc vendored Normal file
View File

@ -0,0 +1,142 @@
___ __ _ _ __ ___ ___
/ __| ___ / _` | '__/ _ \/ __|
| (_ |___| (_| | | | __/\__ \
\___| \__,_|_| \___||___/
How to build c-ares using MSVC or Visual Studio
=================================================
How to build using MSVC from the command line
---------------------------------------------
Open a command prompt window and ensure that the environment is properly
set up in order to use MSVC or Visual Studio compiler tools.
Change to c-ares source folder where Makefile.msvc file is located and run:
> nmake -f Makefile.msvc
This will build all c-ares libraries as well as three sample programs.
Once the above command has finished a new folder named MSVCXX will exist
below the folder where makefile.msvc is found. The name of the folder
depends on the MSVC compiler version being used to build c-ares.
Below the MSVCXX folder there will exist four folders named 'cares',
'ahost', 'acountry', and 'adig'. The 'cares' folder is the one that
holds the c-ares libraries you have just generated, the other three
hold sample programs that use the libraries.
The above command builds four versions of the c-ares library, dynamic
and static versions and each one in release and debug flavours. Each
of these is found in folders named dll-release, dll-debug, lib-release,
and lib-debug, which hang from the 'cares' folder mentioned above. Each
sample program also has folders with the same names to reflect which
library version it is using.
How to install using MSVC from the command line
-----------------------------------------------
In order to allow easy usage of c-ares libraries it may be convenient to
install c-ares libraries and header files to a common subdirectory tree.
Once that c-ares libraries have been built using procedure described above,
use same command prompt window to define environment variable INSTALL_DIR
to designate the top subdirectory where installation of c-ares libraries and
header files will be done.
> set INSTALL_DIR=c:\c-ares
Afterwards, run following command to actually perform the installation:
> nmake -f Makefile.msvc install
Installation procedure will copy c-ares libraries to subdirectory 'lib' and
c-ares header files to subdirectory 'include' below the INSTALL_DIR subdir.
When environment variable INSTALL_DIR is not defined, installation is done
to c-ares source folder where Makefile.msvc file is located.
How to build using Visual Studio 6 IDE
--------------------------------------
A VC++ 6.0 reference workspace (vc6aws.dsw) is available within the 'vc'
folder to allow proper building of the library and sample programs.
1) Open the vc6aws.dsw workspace with MSVC6's IDE.
2) Select 'Build' from top menu.
3) Select 'Batch Build' from dropdown menu.
4) Make sure that the sixteen project configurations are 'checked'.
5) Click on the 'Build' button.
6) Once the sixteen project configurations are built you are done.
Dynamic and static c-ares libraries are built in debug and release flavours,
and can be located each one in its own subdirectory, dll-debug, dll-release,
lib-debug and lib-release, all of them below the 'vc\cares' subdirectory.
In the same way four executable versions of each sample program are built,
each using its respective library. The resulting sample executables are
located in its own subdirectory, dll-debug, dll-release, lib-debug and
lib-release, below the 'vc\acountry', 'vc\adig' and 'vc\ahost'folders.
These reference VC++ 6.0 configurations are generated using the dynamic CRT.
How to build using Visual Studio 2003 or newer IDE
--------------------------------------------------
First you have to convert the VC++ 6.0 reference workspace and project files
to the Visual Studio IDE version you are using, following next steps:
1) Open vc\vc6aws.dsw with VS20XX.
2) Allow VS20XX to update all projects and workspaces.
3) Save ALL and close VS20XX.
4) Open vc\vc6aws.sln with VS20XX.
5) Select batch build, check 'all' projects and click 'build' button.
Same comments relative to generated files and folders as done above for
Visual Studio 6 IDE apply here.
Relationship between c-ares library file names and versions
-----------------------------------------------------------
c-ares static release library version files:
libcares.lib -> static release library
c-ares static debug library version files:
libcaresd.lib -> static debug library
c-ares dynamic release library version files:
cares.dll -> dynamic release library
cares.lib -> import library for the dynamic release library
cares.exp -> export file for the dynamic release library
c-ares dynamic debug library version files:
caresd.dll -> dynamic debug library
caresd.lib -> import library for the dynamic debug library
caresd.exp -> export file for the dynamic debug library
caresd.pdb -> debug symbol file for the dynamic debug library
How to use c-ares static libraries
----------------------------------
When using the c-ares static library in your program, you will have to
define preprocessor symbol CARES_STATICLIB while building your program,
otherwise you will get errors at linkage stage.
Have Fun!

47
deps/c-ares/RELEASE-NOTES vendored Normal file
View File

@ -0,0 +1,47 @@
c-ares version 1.14.0
Changes:
o android: Introduce new ares_library_init_android() call for Oreo support. [5]
Bug fixes:
o Fix patch for CVE-2017-1000381 to not be overly aggressive. [1]
o win32: Preserve DNS server order returned by Windows when sorting and exclude
DNS servers in legacy subnets. [2] [4]
o win32: Support most recent Visual Studio 2017
o gethostbyaddr should fail with ECANCELLED not ENOTFOUND when ares_cancel
is called. [3]
o win32: Exclude legacy ipv6 subnets [4]
o android: Applications compiled for Oreo can no longer use
__system_property_get and must use Java calls to retrieve DNS servers.
[5] [7]
o win32: Force use of ANSI functions [6]
o CMake minimum version is now 3.1
o ares_gethostbyname.3: fix callback status values [8]
o docs: Document WSAStartup requirement [9]
o Fix a typo in init_by_resolv_conf [10]
o Android JNI code leaks local references in some cases [11]
o Force using the ANSI versions of WinAPI functions [12]
Thanks go to these friendly people for their efforts and contributions:
AC Thompson, Anna Henningsen, Antonio Tajuelo, Brad House, Brad Spencer,
Christian Ammer, Daniel Stenberg, David Drysdale, David Hotham, Felix Yan,
Gergely Nagy, Gregor Jasny, Jakub Hrozek, John Schember,
Konstantinos Sofokleous, Roman Teterin, Sergey Kolomenkin, Sheel Bedi,
(18 contributors)
References to bug reports and discussions on issues:
[1] = https://github.com/c-ares/c-ares/commit/18ea99
[2] = https://github.com/c-ares/c-ares/issues/150
[3] = https://github.com/c-ares/c-ares/pull/138
[4] = https://github.com/c-ares/c-ares/pull/144
[5] = https://github.com/c-ares/c-ares/pull/148
[6] = https://github.com/c-ares/c-ares/pull/142
[7] = https://github.com/c-ares/c-ares/pull/175
[8] = https://c-ares.haxx.se/mail/c-ares-archive-2011-06/0012.shtml
[9] = https://github.com/c-ares/c-ares/pull/180
[10] = https://github.com/c-ares/c-ares/pull/160
[11] = https://github.com/c-ares/c-ares/pull/175
[12] = https://github.com/c-ares/c-ares/pull/142

23
deps/c-ares/TODO vendored Normal file
View File

@ -0,0 +1,23 @@
TODO
====
ares_reinit()
- To allow an app to force a re-read of /etc/resolv.conf etc, pretty much
like the res_init() resolver function offers
ares_gethostbyname
- When built to support IPv6, it needs to also support PF_UNSPEC or similar,
so that an application can ask for any protocol and then c-ares would return
all known resolves and not just explicitly IPv4 _or_ IPv6 resolves.
ares_process
- Upon next ABI breakage ares_process() should be changed to return 'int'
and return ARES_ENOTINITIALIZED if ares_library_init() has not been called.
ares_process_fd
- Upon next ABI breakage ares_process_fd() should be changed to return
'int' and return ARES_ENOTINITIALIZED if library has not been initialized.

1915
deps/c-ares/acinclude.m4 vendored Normal file

File diff suppressed because it is too large Load Diff

1209
deps/c-ares/aclocal.m4 vendored Normal file

File diff suppressed because it is too large Load Diff

621
deps/c-ares/acountry.c vendored Normal file
View File

@ -0,0 +1,621 @@
/*
*
* IP-address/hostname to country converter.
*
* Problem; you want to know where IP a.b.c.d is located.
*
* Use ares_gethostbyname ("d.c.b.a.zz.countries.nerd.dk")
* and get the CNAME (host->h_name). Result will be:
* CNAME = zz<CC>.countries.nerd.dk with address 127.0.x.y (ver 1) or
* CNAME = <a.b.c.d>.zz.countries.nerd.dk with address 127.0.x.y (ver 2)
*
* The 2 letter country code is in <CC> and the ISO-3166 country
* number is in x.y (number = x*256 + y). Version 2 of the protocol is missing
* the <CC> number.
*
* Ref: http://countries.nerd.dk/more.html
*
* Written by G. Vanem <gvanem@yahoo.no> 2006, 2007
*
* NB! This program may not be big-endian aware.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#if defined(WIN32) && !defined(WATT32)
#include <winsock.h>
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
#include "ares.h"
#include "ares_getopt.h"
#include "ares_nowarn.h"
#ifndef HAVE_STRDUP
# include "ares_strdup.h"
# define strdup(ptr) ares_strdup(ptr)
#endif
#ifndef HAVE_STRCASECMP
# include "ares_strcasecmp.h"
# define strcasecmp(p1,p2) ares_strcasecmp(p1,p2)
#endif
#ifndef HAVE_STRNCASECMP
# include "ares_strcasecmp.h"
# define strncasecmp(p1,p2,n) ares_strncasecmp(p1,p2,n)
#endif
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif
static const char *usage = "acountry [-vh?] {host|addr} ...\n";
static const char nerd_fmt[] = "%u.%u.%u.%u.zz.countries.nerd.dk";
static const char *nerd_ver1 = nerd_fmt + 14; /* .countries.nerd.dk */
static const char *nerd_ver2 = nerd_fmt + 11; /* .zz.countries.nerd.dk */
static int verbose = 0;
#define TRACE(fmt) do { \
if (verbose > 0) \
printf fmt ; \
} WHILE_FALSE
static void wait_ares(ares_channel channel);
static void callback(void *arg, int status, int timeouts, struct hostent *host);
static void callback2(void *arg, int status, int timeouts, struct hostent *host);
static void find_country_from_cname(const char *cname, struct in_addr addr);
static void Abort(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
exit(1);
}
int main(int argc, char **argv)
{
ares_channel channel;
int ch, status;
#if defined(WIN32) && !defined(WATT32)
WORD wVersionRequested = MAKEWORD(USE_WINSOCK,USE_WINSOCK);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
#endif
status = ares_library_init(ARES_LIB_INIT_ALL);
if (status != ARES_SUCCESS)
{
fprintf(stderr, "ares_library_init: %s\n", ares_strerror(status));
return 1;
}
while ((ch = ares_getopt(argc, argv, "dvh?")) != -1)
switch (ch)
{
case 'd':
#ifdef WATT32
dbug_init();
#endif
break;
case 'v':
verbose++;
break;
case 'h':
case '?':
default:
Abort(usage);
}
argc -= optind;
argv += optind;
if (argc < 1)
Abort(usage);
status = ares_init(&channel);
if (status != ARES_SUCCESS)
{
fprintf(stderr, "ares_init: %s\n", ares_strerror(status));
return 1;
}
/* Initiate the queries, one per command-line argument. */
for ( ; *argv; argv++)
{
struct in_addr addr;
char buf[100];
/* If this fails, assume '*argv' is a host-name that
* must be resolved first
*/
if (ares_inet_pton(AF_INET, *argv, &addr) != 1)
{
ares_gethostbyname(channel, *argv, AF_INET, callback2, &addr);
wait_ares(channel);
if (addr.s_addr == INADDR_NONE)
{
printf("Failed to lookup %s\n", *argv);
continue;
}
}
sprintf(buf, nerd_fmt,
(unsigned int)(addr.s_addr >> 24),
(unsigned int)((addr.s_addr >> 16) & 255),
(unsigned int)((addr.s_addr >> 8) & 255),
(unsigned int)(addr.s_addr & 255));
TRACE(("Looking up %s...", buf));
fflush(stdout);
ares_gethostbyname(channel, buf, AF_INET, callback, buf);
}
wait_ares(channel);
ares_destroy(channel);
ares_library_cleanup();
#if defined(WIN32) && !defined(WATT32)
WSACleanup();
#endif
return 0;
}
/*
* Wait for the queries to complete.
*/
static void wait_ares(ares_channel channel)
{
for (;;)
{
struct timeval *tvp, tv;
fd_set read_fds, write_fds;
int nfds;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
nfds = ares_fds(channel, &read_fds, &write_fds);
if (nfds == 0)
break;
tvp = ares_timeout(channel, NULL, &tv);
nfds = select(nfds, &read_fds, &write_fds, NULL, tvp);
if (nfds < 0)
continue;
ares_process(channel, &read_fds, &write_fds);
}
}
/*
* This is the callback used when we have the IP-address of interest.
* Extract the CNAME and figure out the country-code from it.
*/
static void callback(void *arg, int status, int timeouts, struct hostent *host)
{
const char *name = (const char*)arg;
const char *cname;
char buf[20];
(void)timeouts;
if (!host || status != ARES_SUCCESS)
{
printf("Failed to lookup %s: %s\n", name, ares_strerror(status));
return;
}
TRACE(("\nFound address %s, name %s\n",
ares_inet_ntop(AF_INET,(const char*)host->h_addr,buf,sizeof(buf)),
host->h_name));
cname = host->h_name; /* CNAME gets put here */
if (!cname)
printf("Failed to get CNAME for %s\n", name);
else
find_country_from_cname(cname, *(struct in_addr*)host->h_addr);
}
/*
* This is the callback used to obtain the IP-address of the host of interest.
*/
static void callback2(void *arg, int status, int timeouts, struct hostent *host)
{
struct in_addr *addr = (struct in_addr*) arg;
(void)timeouts;
if (!host || status != ARES_SUCCESS)
memset(addr, INADDR_NONE, sizeof(*addr));
else
memcpy(addr, host->h_addr, sizeof(*addr));
}
struct search_list {
int country_number; /* ISO-3166 country number */
char short_name[3]; /* A2 short country code */
const char *long_name; /* normal country name */
};
static const struct search_list *list_lookup(int number, const struct search_list *list, int num)
{
while (num > 0 && list->long_name)
{
if (list->country_number == number)
return (list);
num--;
list++;
}
return (NULL);
}
/*
* Ref: ftp://ftp.ripe.net/iso3166-countrycodes.txt
*/
static const struct search_list country_list[] = {
{ 4, "af", "Afghanistan" },
{ 248, "ax", "Åland Island" },
{ 8, "al", "Albania" },
{ 12, "dz", "Algeria" },
{ 16, "as", "American Samoa" },
{ 20, "ad", "Andorra" },
{ 24, "ao", "Angola" },
{ 660, "ai", "Anguilla" },
{ 10, "aq", "Antarctica" },
{ 28, "ag", "Antigua & Barbuda" },
{ 32, "ar", "Argentina" },
{ 51, "am", "Armenia" },
{ 533, "aw", "Aruba" },
{ 36, "au", "Australia" },
{ 40, "at", "Austria" },
{ 31, "az", "Azerbaijan" },
{ 44, "bs", "Bahamas" },
{ 48, "bh", "Bahrain" },
{ 50, "bd", "Bangladesh" },
{ 52, "bb", "Barbados" },
{ 112, "by", "Belarus" },
{ 56, "be", "Belgium" },
{ 84, "bz", "Belize" },
{ 204, "bj", "Benin" },
{ 60, "bm", "Bermuda" },
{ 64, "bt", "Bhutan" },
{ 68, "bo", "Bolivia" },
{ 70, "ba", "Bosnia & Herzegowina" },
{ 72, "bw", "Botswana" },
{ 74, "bv", "Bouvet Island" },
{ 76, "br", "Brazil" },
{ 86, "io", "British Indian Ocean Territory" },
{ 96, "bn", "Brunei Darussalam" },
{ 100, "bg", "Bulgaria" },
{ 854, "bf", "Burkina Faso" },
{ 108, "bi", "Burundi" },
{ 116, "kh", "Cambodia" },
{ 120, "cm", "Cameroon" },
{ 124, "ca", "Canada" },
{ 132, "cv", "Cape Verde" },
{ 136, "ky", "Cayman Islands" },
{ 140, "cf", "Central African Republic" },
{ 148, "td", "Chad" },
{ 152, "cl", "Chile" },
{ 156, "cn", "China" },
{ 162, "cx", "Christmas Island" },
{ 166, "cc", "Cocos Islands" },
{ 170, "co", "Colombia" },
{ 174, "km", "Comoros" },
{ 178, "cg", "Congo" },
{ 180, "cd", "Congo" },
{ 184, "ck", "Cook Islands" },
{ 188, "cr", "Costa Rica" },
{ 384, "ci", "Cote d'Ivoire" },
{ 191, "hr", "Croatia" },
{ 192, "cu", "Cuba" },
{ 196, "cy", "Cyprus" },
{ 203, "cz", "Czech Republic" },
{ 208, "dk", "Denmark" },
{ 262, "dj", "Djibouti" },
{ 212, "dm", "Dominica" },
{ 214, "do", "Dominican Republic" },
{ 218, "ec", "Ecuador" },
{ 818, "eg", "Egypt" },
{ 222, "sv", "El Salvador" },
{ 226, "gq", "Equatorial Guinea" },
{ 232, "er", "Eritrea" },
{ 233, "ee", "Estonia" },
{ 231, "et", "Ethiopia" },
{ 238, "fk", "Falkland Islands" },
{ 234, "fo", "Faroe Islands" },
{ 242, "fj", "Fiji" },
{ 246, "fi", "Finland" },
{ 250, "fr", "France" },
{ 249, "fx", "France, Metropolitan" },
{ 254, "gf", "French Guiana" },
{ 258, "pf", "French Polynesia" },
{ 260, "tf", "French Southern Territories" },
{ 266, "ga", "Gabon" },
{ 270, "gm", "Gambia" },
{ 268, "ge", "Georgia" },
{ 276, "de", "Germany" },
{ 288, "gh", "Ghana" },
{ 292, "gi", "Gibraltar" },
{ 300, "gr", "Greece" },
{ 304, "gl", "Greenland" },
{ 308, "gd", "Grenada" },
{ 312, "gp", "Guadeloupe" },
{ 316, "gu", "Guam" },
{ 320, "gt", "Guatemala" },
{ 324, "gn", "Guinea" },
{ 624, "gw", "Guinea-Bissau" },
{ 328, "gy", "Guyana" },
{ 332, "ht", "Haiti" },
{ 334, "hm", "Heard & Mc Donald Islands" },
{ 336, "va", "Vatican City" },
{ 340, "hn", "Honduras" },
{ 344, "hk", "Hong kong" },
{ 348, "hu", "Hungary" },
{ 352, "is", "Iceland" },
{ 356, "in", "India" },
{ 360, "id", "Indonesia" },
{ 364, "ir", "Iran" },
{ 368, "iq", "Iraq" },
{ 372, "ie", "Ireland" },
{ 376, "il", "Israel" },
{ 380, "it", "Italy" },
{ 388, "jm", "Jamaica" },
{ 392, "jp", "Japan" },
{ 400, "jo", "Jordan" },
{ 398, "kz", "Kazakhstan" },
{ 404, "ke", "Kenya" },
{ 296, "ki", "Kiribati" },
{ 408, "kp", "Korea (north)" },
{ 410, "kr", "Korea (south)" },
{ 414, "kw", "Kuwait" },
{ 417, "kg", "Kyrgyzstan" },
{ 418, "la", "Laos" },
{ 428, "lv", "Latvia" },
{ 422, "lb", "Lebanon" },
{ 426, "ls", "Lesotho" },
{ 430, "lr", "Liberia" },
{ 434, "ly", "Libya" },
{ 438, "li", "Liechtenstein" },
{ 440, "lt", "Lithuania" },
{ 442, "lu", "Luxembourg" },
{ 446, "mo", "Macao" },
{ 807, "mk", "Macedonia" },
{ 450, "mg", "Madagascar" },
{ 454, "mw", "Malawi" },
{ 458, "my", "Malaysia" },
{ 462, "mv", "Maldives" },
{ 466, "ml", "Mali" },
{ 470, "mt", "Malta" },
{ 584, "mh", "Marshall Islands" },
{ 474, "mq", "Martinique" },
{ 478, "mr", "Mauritania" },
{ 480, "mu", "Mauritius" },
{ 175, "yt", "Mayotte" },
{ 484, "mx", "Mexico" },
{ 583, "fm", "Micronesia" },
{ 498, "md", "Moldova" },
{ 492, "mc", "Monaco" },
{ 496, "mn", "Mongolia" },
{ 500, "ms", "Montserrat" },
{ 504, "ma", "Morocco" },
{ 508, "mz", "Mozambique" },
{ 104, "mm", "Myanmar" },
{ 516, "na", "Namibia" },
{ 520, "nr", "Nauru" },
{ 524, "np", "Nepal" },
{ 528, "nl", "Netherlands" },
{ 530, "an", "Netherlands Antilles" },
{ 540, "nc", "New Caledonia" },
{ 554, "nz", "New Zealand" },
{ 558, "ni", "Nicaragua" },
{ 562, "ne", "Niger" },
{ 566, "ng", "Nigeria" },
{ 570, "nu", "Niue" },
{ 574, "nf", "Norfolk Island" },
{ 580, "mp", "Northern Mariana Islands" },
{ 578, "no", "Norway" },
{ 512, "om", "Oman" },
{ 586, "pk", "Pakistan" },
{ 585, "pw", "Palau" },
{ 275, "ps", "Palestinian Territory" },
{ 591, "pa", "Panama" },
{ 598, "pg", "Papua New Guinea" },
{ 600, "py", "Paraguay" },
{ 604, "pe", "Peru" },
{ 608, "ph", "Philippines" },
{ 612, "pn", "Pitcairn" },
{ 616, "pl", "Poland" },
{ 620, "pt", "Portugal" },
{ 630, "pr", "Puerto Rico" },
{ 634, "qa", "Qatar" },
{ 638, "re", "Reunion" },
{ 642, "ro", "Romania" },
{ 643, "ru", "Russia" },
{ 646, "rw", "Rwanda" },
{ 659, "kn", "Saint Kitts & Nevis" },
{ 662, "lc", "Saint Lucia" },
{ 670, "vc", "Saint Vincent" },
{ 882, "ws", "Samoa" },
{ 674, "sm", "San Marino" },
{ 678, "st", "Sao Tome & Principe" },
{ 682, "sa", "Saudi Arabia" },
{ 686, "sn", "Senegal" },
{ 891, "cs", "Serbia and Montenegro" },
{ 690, "sc", "Seychelles" },
{ 694, "sl", "Sierra Leone" },
{ 702, "sg", "Singapore" },
{ 703, "sk", "Slovakia" },
{ 705, "si", "Slovenia" },
{ 90, "sb", "Solomon Islands" },
{ 706, "so", "Somalia" },
{ 710, "za", "South Africa" },
{ 239, "gs", "South Georgia" },
{ 724, "es", "Spain" },
{ 144, "lk", "Sri Lanka" },
{ 654, "sh", "St. Helena" },
{ 666, "pm", "St. Pierre & Miquelon" },
{ 736, "sd", "Sudan" },
{ 740, "sr", "Suriname" },
{ 744, "sj", "Svalbard & Jan Mayen Islands" },
{ 748, "sz", "Swaziland" },
{ 752, "se", "Sweden" },
{ 756, "ch", "Switzerland" },
{ 760, "sy", "Syrian Arab Republic" },
{ 626, "tl", "Timor-Leste" },
{ 158, "tw", "Taiwan" },
{ 762, "tj", "Tajikistan" },
{ 834, "tz", "Tanzania" },
{ 764, "th", "Thailand" },
{ 768, "tg", "Togo" },
{ 772, "tk", "Tokelau" },
{ 776, "to", "Tonga" },
{ 780, "tt", "Trinidad & Tobago" },
{ 788, "tn", "Tunisia" },
{ 792, "tr", "Turkey" },
{ 795, "tm", "Turkmenistan" },
{ 796, "tc", "Turks & Caicos Islands" },
{ 798, "tv", "Tuvalu" },
{ 800, "ug", "Uganda" },
{ 804, "ua", "Ukraine" },
{ 784, "ae", "United Arab Emirates" },
{ 826, "gb", "United Kingdom" },
{ 840, "us", "United States" },
{ 581, "um", "United States Minor Outlying Islands" },
{ 858, "uy", "Uruguay" },
{ 860, "uz", "Uzbekistan" },
{ 548, "vu", "Vanuatu" },
{ 862, "ve", "Venezuela" },
{ 704, "vn", "Vietnam" },
{ 92, "vg", "Virgin Islands (British)" },
{ 850, "vi", "Virgin Islands (US)" },
{ 876, "wf", "Wallis & Futuna Islands" },
{ 732, "eh", "Western Sahara" },
{ 887, "ye", "Yemen" },
{ 894, "zm", "Zambia" },
{ 716, "zw", "Zimbabwe" }
};
/*
* Check if start of 'str' is simply an IPv4 address.
*/
#define BYTE_OK(x) ((x) >= 0 && (x) <= 255)
static int is_addr(char *str, char **end)
{
int a0, a1, a2, a3, num, rc = 0, length = 0;
num = sscanf(str,"%3d.%3d.%3d.%3d%n",&a0,&a1,&a2,&a3,&length);
if( (num == 4) &&
BYTE_OK(a0) && BYTE_OK(a1) && BYTE_OK(a2) && BYTE_OK(a3) &&
length >= (3+4))
{
rc = 1;
*end = str + length;
}
return rc;
}
/*
* Find the country-code and name from the CNAME. E.g.:
* version 1: CNAME = zzno.countries.nerd.dk with address 127.0.2.66
* yields ccode_A" = "no" and cnumber 578 (2.66).
* version 2: CNAME = <a.b.c.d>.zz.countries.nerd.dk with address 127.0.2.66
* yields cnumber 578 (2.66). ccode_A is "";
*/
static void find_country_from_cname(const char *cname, struct in_addr addr)
{
const struct search_list *country;
char ccode_A2[3], *ccopy, *dot_4;
int cnumber, z0, z1, ver_1, ver_2;
unsigned long ip;
ip = ntohl(addr.s_addr);
z0 = TOLOWER(cname[0]);
z1 = TOLOWER(cname[1]);
ccopy = strdup(cname);
dot_4 = NULL;
ver_1 = (z0 == 'z' && z1 == 'z' && !strcasecmp(cname+4,nerd_ver1));
ver_2 = (is_addr(ccopy,&dot_4) && !strcasecmp(dot_4,nerd_ver2));
if (ver_1)
{
const char *dot = strchr(cname, '.');
if (dot != cname+4)
{
printf("Unexpected CNAME %s (ver_1)\n", cname);
free(ccopy);
return;
}
}
else if (ver_2)
{
z0 = TOLOWER(dot_4[1]);
z1 = TOLOWER(dot_4[2]);
if (z0 != 'z' && z1 != 'z')
{
printf("Unexpected CNAME %s (ver_2)\n", cname);
free(ccopy);
return;
}
}
else
{
printf("Unexpected CNAME %s (ver?)\n", cname);
free(ccopy);
return;
}
if (ver_1)
{
ccode_A2[0] = (char)TOLOWER(cname[2]);
ccode_A2[1] = (char)TOLOWER(cname[3]);
ccode_A2[2] = '\0';
}
else
ccode_A2[0] = '\0';
cnumber = ip & 0xFFFF;
TRACE(("Found country-code `%s', number %d\n",
ver_1 ? ccode_A2 : "<n/a>", cnumber));
country = list_lookup(cnumber, country_list,
sizeof(country_list) / sizeof(country_list[0]));
if (!country)
printf("Name for country-number %d not found.\n", cnumber);
else
{
if (ver_1)
{
if ((country->short_name[0] != ccode_A2[0]) ||
(country->short_name[1] != ccode_A2[1]) ||
(country->short_name[2] != ccode_A2[2]))
printf("short-name mismatch; %s vs %s\n",
country->short_name, ccode_A2);
}
printf("%s (%s), number %d.\n",
country->long_name, country->short_name, cnumber);
}
free(ccopy);
}

827
deps/c-ares/adig.c vendored Normal file
View File

@ -0,0 +1,827 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#ifdef HAVE_ARPA_NAMESER_H
# include <arpa/nameser.h>
#else
# include "nameser.h"
#endif
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
# include <arpa/nameser_compat.h>
#endif
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif
#include "ares.h"
#include "ares_dns.h"
#include "ares_getopt.h"
#include "ares_nowarn.h"
#ifndef HAVE_STRDUP
# include "ares_strdup.h"
# define strdup(ptr) ares_strdup(ptr)
#endif
#ifndef HAVE_STRCASECMP
# include "ares_strcasecmp.h"
# define strcasecmp(p1,p2) ares_strcasecmp(p1,p2)
#endif
#ifndef HAVE_STRNCASECMP
# include "ares_strcasecmp.h"
# define strncasecmp(p1,p2,n) ares_strncasecmp(p1,p2,n)
#endif
#ifdef WATT32
#undef WIN32 /* Redefined in MingW headers */
#endif
#ifndef T_SRV
# define T_SRV 33 /* Server selection */
#endif
#ifndef T_NAPTR
# define T_NAPTR 35 /* Naming authority pointer */
#endif
#ifndef T_DS
# define T_DS 43 /* Delegation Signer (RFC4034) */
#endif
#ifndef T_SSHFP
# define T_SSHFP 44 /* SSH Key Fingerprint (RFC4255) */
#endif
#ifndef T_RRSIG
# define T_RRSIG 46 /* Resource Record Signature (RFC4034) */
#endif
#ifndef T_NSEC
# define T_NSEC 47 /* Next Secure (RFC4034) */
#endif
#ifndef T_DNSKEY
# define T_DNSKEY 48 /* DNS Public Key (RFC4034) */
#endif
struct nv {
const char *name;
int value;
};
static const struct nv flags[] = {
{ "usevc", ARES_FLAG_USEVC },
{ "primary", ARES_FLAG_PRIMARY },
{ "igntc", ARES_FLAG_IGNTC },
{ "norecurse", ARES_FLAG_NORECURSE },
{ "stayopen", ARES_FLAG_STAYOPEN },
{ "noaliases", ARES_FLAG_NOALIASES }
};
static const int nflags = sizeof(flags) / sizeof(flags[0]);
static const struct nv classes[] = {
{ "IN", C_IN },
{ "CHAOS", C_CHAOS },
{ "HS", C_HS },
{ "ANY", C_ANY }
};
static const int nclasses = sizeof(classes) / sizeof(classes[0]);
static const struct nv types[] = {
{ "A", T_A },
{ "NS", T_NS },
{ "MD", T_MD },
{ "MF", T_MF },
{ "CNAME", T_CNAME },
{ "SOA", T_SOA },
{ "MB", T_MB },
{ "MG", T_MG },
{ "MR", T_MR },
{ "NULL", T_NULL },
{ "WKS", T_WKS },
{ "PTR", T_PTR },
{ "HINFO", T_HINFO },
{ "MINFO", T_MINFO },
{ "MX", T_MX },
{ "TXT", T_TXT },
{ "RP", T_RP },
{ "AFSDB", T_AFSDB },
{ "X25", T_X25 },
{ "ISDN", T_ISDN },
{ "RT", T_RT },
{ "NSAP", T_NSAP },
{ "NSAP_PTR", T_NSAP_PTR },
{ "SIG", T_SIG },
{ "KEY", T_KEY },
{ "PX", T_PX },
{ "GPOS", T_GPOS },
{ "AAAA", T_AAAA },
{ "LOC", T_LOC },
{ "SRV", T_SRV },
{ "AXFR", T_AXFR },
{ "MAILB", T_MAILB },
{ "MAILA", T_MAILA },
{ "NAPTR", T_NAPTR },
{ "DS", T_DS },
{ "SSHFP", T_SSHFP },
{ "RRSIG", T_RRSIG },
{ "NSEC", T_NSEC },
{ "DNSKEY", T_DNSKEY },
{ "ANY", T_ANY }
};
static const int ntypes = sizeof(types) / sizeof(types[0]);
static const char *opcodes[] = {
"QUERY", "IQUERY", "STATUS", "(reserved)", "NOTIFY",
"(unknown)", "(unknown)", "(unknown)", "(unknown)",
"UPDATEA", "UPDATED", "UPDATEDA", "UPDATEM", "UPDATEMA",
"ZONEINIT", "ZONEREF"
};
static const char *rcodes[] = {
"NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN", "NOTIMP", "REFUSED",
"(unknown)", "(unknown)", "(unknown)", "(unknown)", "(unknown)",
"(unknown)", "(unknown)", "(unknown)", "(unknown)", "NOCHANGE"
};
static void callback(void *arg, int status, int timeouts,
unsigned char *abuf, int alen);
static const unsigned char *display_question(const unsigned char *aptr,
const unsigned char *abuf,
int alen);
static const unsigned char *display_rr(const unsigned char *aptr,
const unsigned char *abuf, int alen);
static const char *type_name(int type);
static const char *class_name(int dnsclass);
static void usage(void);
static void destroy_addr_list(struct ares_addr_node *head);
static void append_addr_list(struct ares_addr_node **head,
struct ares_addr_node *node);
int main(int argc, char **argv)
{
ares_channel channel;
int c, i, optmask = ARES_OPT_FLAGS, dnsclass = C_IN, type = T_A;
int status, nfds, count;
struct ares_options options;
struct hostent *hostent;
fd_set read_fds, write_fds;
struct timeval *tvp, tv;
struct ares_addr_node *srvr, *servers = NULL;
#ifdef USE_WINSOCK
WORD wVersionRequested = MAKEWORD(USE_WINSOCK,USE_WINSOCK);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
#endif
status = ares_library_init(ARES_LIB_INIT_ALL);
if (status != ARES_SUCCESS)
{
fprintf(stderr, "ares_library_init: %s\n", ares_strerror(status));
return 1;
}
options.flags = ARES_FLAG_NOCHECKRESP;
options.servers = NULL;
options.nservers = 0;
while ((c = ares_getopt(argc, argv, "df:s:c:t:T:U:")) != -1)
{
switch (c)
{
case 'd':
#ifdef WATT32
dbug_init();
#endif
break;
case 'f':
/* Add a flag. */
for (i = 0; i < nflags; i++)
{
if (strcmp(flags[i].name, optarg) == 0)
break;
}
if (i < nflags)
options.flags |= flags[i].value;
else
usage();
break;
case 's':
/* User-specified name servers override default ones. */
srvr = malloc(sizeof(struct ares_addr_node));
if (!srvr)
{
fprintf(stderr, "Out of memory!\n");
destroy_addr_list(servers);
return 1;
}
append_addr_list(&servers, srvr);
if (ares_inet_pton(AF_INET, optarg, &srvr->addr.addr4) > 0)
srvr->family = AF_INET;
else if (ares_inet_pton(AF_INET6, optarg, &srvr->addr.addr6) > 0)
srvr->family = AF_INET6;
else
{
hostent = gethostbyname(optarg);
if (!hostent)
{
fprintf(stderr, "adig: server %s not found.\n", optarg);
destroy_addr_list(servers);
return 1;
}
switch (hostent->h_addrtype)
{
case AF_INET:
srvr->family = AF_INET;
memcpy(&srvr->addr.addr4, hostent->h_addr,
sizeof(srvr->addr.addr4));
break;
case AF_INET6:
srvr->family = AF_INET6;
memcpy(&srvr->addr.addr6, hostent->h_addr,
sizeof(srvr->addr.addr6));
break;
default:
fprintf(stderr,
"adig: server %s unsupported address family.\n", optarg);
destroy_addr_list(servers);
return 1;
}
}
/* Notice that calling ares_init_options() without servers in the
* options struct and with ARES_OPT_SERVERS set simultaneously in
* the options mask, results in an initialization with no servers.
* When alternative name servers have been specified these are set
* later calling ares_set_servers() overriding any existing server
* configuration. To prevent initial configuration with default
* servers that will be discarded later, ARES_OPT_SERVERS is set.
* If this flag is not set here the result shall be the same but
* ares_init_options() will do needless work. */
optmask |= ARES_OPT_SERVERS;
break;
case 'c':
/* Set the query class. */
for (i = 0; i < nclasses; i++)
{
if (strcasecmp(classes[i].name, optarg) == 0)
break;
}
if (i < nclasses)
dnsclass = classes[i].value;
else
usage();
break;
case 't':
/* Set the query type. */
for (i = 0; i < ntypes; i++)
{
if (strcasecmp(types[i].name, optarg) == 0)
break;
}
if (i < ntypes)
type = types[i].value;
else
usage();
break;
case 'T':
/* Set the TCP port number. */
if (!ISDIGIT(*optarg))
usage();
options.tcp_port = (unsigned short)strtol(optarg, NULL, 0);
optmask |= ARES_OPT_TCP_PORT;
break;
case 'U':
/* Set the UDP port number. */
if (!ISDIGIT(*optarg))
usage();
options.udp_port = (unsigned short)strtol(optarg, NULL, 0);
optmask |= ARES_OPT_UDP_PORT;
break;
}
}
argc -= optind;
argv += optind;
if (argc == 0)
usage();
status = ares_init_options(&channel, &options, optmask);
if (status != ARES_SUCCESS)
{
fprintf(stderr, "ares_init_options: %s\n",
ares_strerror(status));
return 1;
}
if(servers)
{
status = ares_set_servers(channel, servers);
destroy_addr_list(servers);
if (status != ARES_SUCCESS)
{
fprintf(stderr, "ares_init_options: %s\n",
ares_strerror(status));
return 1;
}
}
/* Initiate the queries, one per command-line argument. If there is
* only one query to do, supply NULL as the callback argument;
* otherwise, supply the query name as an argument so we can
* distinguish responses for the user when printing them out.
*/
if (argc == 1)
ares_query(channel, *argv, dnsclass, type, callback, (char *) NULL);
else
{
for (; *argv; argv++)
ares_query(channel, *argv, dnsclass, type, callback, *argv);
}
/* Wait for all queries to complete. */
for (;;)
{
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
nfds = ares_fds(channel, &read_fds, &write_fds);
if (nfds == 0)
break;
tvp = ares_timeout(channel, NULL, &tv);
count = select(nfds, &read_fds, &write_fds, NULL, tvp);
if (count < 0 && (status = SOCKERRNO) != EINVAL)
{
printf("select fail: %d", status);
return 1;
}
ares_process(channel, &read_fds, &write_fds);
}
ares_destroy(channel);
ares_library_cleanup();
#ifdef USE_WINSOCK
WSACleanup();
#endif
return 0;
}
static void callback(void *arg, int status, int timeouts,
unsigned char *abuf, int alen)
{
char *name = (char *) arg;
int id, qr, opcode, aa, tc, rd, ra, rcode;
unsigned int qdcount, ancount, nscount, arcount, i;
const unsigned char *aptr;
(void) timeouts;
/* Display the query name if given. */
if (name)
printf("Answer for query %s:\n", name);
/* Display an error message if there was an error, but only stop if
* we actually didn't get an answer buffer.
*/
if (status != ARES_SUCCESS)
{
printf("%s\n", ares_strerror(status));
if (!abuf)
return;
}
/* Won't happen, but check anyway, for safety. */
if (alen < HFIXEDSZ)
return;
/* Parse the answer header. */
id = DNS_HEADER_QID(abuf);
qr = DNS_HEADER_QR(abuf);
opcode = DNS_HEADER_OPCODE(abuf);
aa = DNS_HEADER_AA(abuf);
tc = DNS_HEADER_TC(abuf);
rd = DNS_HEADER_RD(abuf);
ra = DNS_HEADER_RA(abuf);
rcode = DNS_HEADER_RCODE(abuf);
qdcount = DNS_HEADER_QDCOUNT(abuf);
ancount = DNS_HEADER_ANCOUNT(abuf);
nscount = DNS_HEADER_NSCOUNT(abuf);
arcount = DNS_HEADER_ARCOUNT(abuf);
/* Display the answer header. */
printf("id: %d\n", id);
printf("flags: %s%s%s%s%s\n",
qr ? "qr " : "",
aa ? "aa " : "",
tc ? "tc " : "",
rd ? "rd " : "",
ra ? "ra " : "");
printf("opcode: %s\n", opcodes[opcode]);
printf("rcode: %s\n", rcodes[rcode]);
/* Display the questions. */
printf("Questions:\n");
aptr = abuf + HFIXEDSZ;
for (i = 0; i < qdcount; i++)
{
aptr = display_question(aptr, abuf, alen);
if (aptr == NULL)
return;
}
/* Display the answers. */
printf("Answers:\n");
for (i = 0; i < ancount; i++)
{
aptr = display_rr(aptr, abuf, alen);
if (aptr == NULL)
return;
}
/* Display the NS records. */
printf("NS records:\n");
for (i = 0; i < nscount; i++)
{
aptr = display_rr(aptr, abuf, alen);
if (aptr == NULL)
return;
}
/* Display the additional records. */
printf("Additional records:\n");
for (i = 0; i < arcount; i++)
{
aptr = display_rr(aptr, abuf, alen);
if (aptr == NULL)
return;
}
}
static const unsigned char *display_question(const unsigned char *aptr,
const unsigned char *abuf,
int alen)
{
char *name;
int type, dnsclass, status;
long len;
/* Parse the question name. */
status = ares_expand_name(aptr, abuf, alen, &name, &len);
if (status != ARES_SUCCESS)
return NULL;
aptr += len;
/* Make sure there's enough data after the name for the fixed part
* of the question.
*/
if (aptr + QFIXEDSZ > abuf + alen)
{
ares_free_string(name);
return NULL;
}
/* Parse the question type and class. */
type = DNS_QUESTION_TYPE(aptr);
dnsclass = DNS_QUESTION_CLASS(aptr);
aptr += QFIXEDSZ;
/* Display the question, in a format sort of similar to how we will
* display RRs.
*/
printf("\t%-15s.\t", name);
if (dnsclass != C_IN)
printf("\t%s", class_name(dnsclass));
printf("\t%s\n", type_name(type));
ares_free_string(name);
return aptr;
}
static const unsigned char *display_rr(const unsigned char *aptr,
const unsigned char *abuf, int alen)
{
const unsigned char *p;
int type, dnsclass, ttl, dlen, status;
long len;
char addr[46];
union {
unsigned char * as_uchar;
char * as_char;
} name;
/* Parse the RR name. */
status = ares_expand_name(aptr, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
aptr += len;
/* Make sure there is enough data after the RR name for the fixed
* part of the RR.
*/
if (aptr + RRFIXEDSZ > abuf + alen)
{
ares_free_string(name.as_char);
return NULL;
}
/* Parse the fixed part of the RR, and advance to the RR data
* field. */
type = DNS_RR_TYPE(aptr);
dnsclass = DNS_RR_CLASS(aptr);
ttl = DNS_RR_TTL(aptr);
dlen = DNS_RR_LEN(aptr);
aptr += RRFIXEDSZ;
if (aptr + dlen > abuf + alen)
{
ares_free_string(name.as_char);
return NULL;
}
/* Display the RR name, class, and type. */
printf("\t%-15s.\t%d", name.as_char, ttl);
if (dnsclass != C_IN)
printf("\t%s", class_name(dnsclass));
printf("\t%s", type_name(type));
ares_free_string(name.as_char);
/* Display the RR data. Don't touch aptr. */
switch (type)
{
case T_CNAME:
case T_MB:
case T_MD:
case T_MF:
case T_MG:
case T_MR:
case T_NS:
case T_PTR:
/* For these types, the RR data is just a domain name. */
status = ares_expand_name(aptr, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s.", name.as_char);
ares_free_string(name.as_char);
break;
case T_HINFO:
/* The RR data is two length-counted character strings. */
p = aptr;
len = *p;
if (p + len + 1 > aptr + dlen)
return NULL;
status = ares_expand_string(p, abuf, alen, &name.as_uchar, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s", name.as_char);
ares_free_string(name.as_char);
p += len;
len = *p;
if (p + len + 1 > aptr + dlen)
return NULL;
status = ares_expand_string(p, abuf, alen, &name.as_uchar, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s", name.as_char);
ares_free_string(name.as_char);
break;
case T_MINFO:
/* The RR data is two domain names. */
p = aptr;
status = ares_expand_name(p, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s.", name.as_char);
ares_free_string(name.as_char);
p += len;
status = ares_expand_name(p, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s.", name.as_char);
ares_free_string(name.as_char);
break;
case T_MX:
/* The RR data is two bytes giving a preference ordering, and
* then a domain name.
*/
if (dlen < 2)
return NULL;
printf("\t%d", (int)DNS__16BIT(aptr));
status = ares_expand_name(aptr + 2, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s.", name.as_char);
ares_free_string(name.as_char);
break;
case T_SOA:
/* The RR data is two domain names and then five four-byte
* numbers giving the serial number and some timeouts.
*/
p = aptr;
status = ares_expand_name(p, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s.\n", name.as_char);
ares_free_string(name.as_char);
p += len;
status = ares_expand_name(p, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t\t\t\t\t\t%s.\n", name.as_char);
ares_free_string(name.as_char);
p += len;
if (p + 20 > aptr + dlen)
return NULL;
printf("\t\t\t\t\t\t( %u %u %u %u %u )",
DNS__32BIT(p), DNS__32BIT(p+4),
DNS__32BIT(p+8), DNS__32BIT(p+12),
DNS__32BIT(p+16));
break;
case T_TXT:
/* The RR data is one or more length-counted character
* strings. */
p = aptr;
while (p < aptr + dlen)
{
len = *p;
if (p + len + 1 > aptr + dlen)
return NULL;
status = ares_expand_string(p, abuf, alen, &name.as_uchar, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s", name.as_char);
ares_free_string(name.as_char);
p += len;
}
break;
case T_A:
/* The RR data is a four-byte Internet address. */
if (dlen != 4)
return NULL;
printf("\t%s", ares_inet_ntop(AF_INET,aptr,addr,sizeof(addr)));
break;
case T_AAAA:
/* The RR data is a 16-byte IPv6 address. */
if (dlen != 16)
return NULL;
printf("\t%s", ares_inet_ntop(AF_INET6,aptr,addr,sizeof(addr)));
break;
case T_WKS:
/* Not implemented yet */
break;
case T_SRV:
/* The RR data is three two-byte numbers representing the
* priority, weight, and port, followed by a domain name.
*/
printf("\t%d", (int)DNS__16BIT(aptr));
printf(" %d", (int)DNS__16BIT(aptr + 2));
printf(" %d", (int)DNS__16BIT(aptr + 4));
status = ares_expand_name(aptr + 6, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t%s.", name.as_char);
ares_free_string(name.as_char);
break;
case T_NAPTR:
printf("\t%d", (int)DNS__16BIT(aptr)); /* order */
printf(" %d\n", (int)DNS__16BIT(aptr + 2)); /* preference */
p = aptr + 4;
status = ares_expand_string(p, abuf, alen, &name.as_uchar, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t\t\t\t\t\t%s\n", name.as_char);
ares_free_string(name.as_char);
p += len;
status = ares_expand_string(p, abuf, alen, &name.as_uchar, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t\t\t\t\t\t%s\n", name.as_char);
ares_free_string(name.as_char);
p += len;
status = ares_expand_string(p, abuf, alen, &name.as_uchar, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t\t\t\t\t\t%s\n", name.as_char);
ares_free_string(name.as_char);
p += len;
status = ares_expand_name(p, abuf, alen, &name.as_char, &len);
if (status != ARES_SUCCESS)
return NULL;
printf("\t\t\t\t\t\t%s", name.as_char);
ares_free_string(name.as_char);
break;
case T_DS:
case T_SSHFP:
case T_RRSIG:
case T_NSEC:
case T_DNSKEY:
printf("\t[RR type parsing unavailable]");
break;
default:
printf("\t[Unknown RR; cannot parse]");
break;
}
printf("\n");
return aptr + dlen;
}
static const char *type_name(int type)
{
int i;
for (i = 0; i < ntypes; i++)
{
if (types[i].value == type)
return types[i].name;
}
return "(unknown)";
}
static const char *class_name(int dnsclass)
{
int i;
for (i = 0; i < nclasses; i++)
{
if (classes[i].value == dnsclass)
return classes[i].name;
}
return "(unknown)";
}
static void usage(void)
{
fprintf(stderr, "usage: adig [-f flag] [-s server] [-c class] "
"[-t type] [-p port] name ...\n");
exit(1);
}
static void destroy_addr_list(struct ares_addr_node *head)
{
while(head)
{
struct ares_addr_node *detached = head;
head = head->next;
free(detached);
}
}
static void append_addr_list(struct ares_addr_node **head,
struct ares_addr_node *node)
{
struct ares_addr_node *last;
node->next = NULL;
if(*head)
{
last = *head;
while(last->next)
last = last->next;
last->next = node;
}
else
*head = node;
}

206
deps/c-ares/ahost.c vendored Normal file
View File

@ -0,0 +1,206 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#if !defined(WIN32) || defined(WATT32)
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include "ares.h"
#include "ares_dns.h"
#include "ares_getopt.h"
#include "ares_ipv6.h"
#include "ares_nowarn.h"
#ifndef HAVE_STRDUP
# include "ares_strdup.h"
# define strdup(ptr) ares_strdup(ptr)
#endif
#ifndef HAVE_STRCASECMP
# include "ares_strcasecmp.h"
# define strcasecmp(p1,p2) ares_strcasecmp(p1,p2)
#endif
#ifndef HAVE_STRNCASECMP
# include "ares_strcasecmp.h"
# define strncasecmp(p1,p2,n) ares_strncasecmp(p1,p2,n)
#endif
static void callback(void *arg, int status, int timeouts, struct hostent *host);
static void usage(void);
int main(int argc, char **argv)
{
struct ares_options options;
int optmask = 0;
ares_channel channel;
int status, nfds, c, addr_family = AF_INET;
fd_set read_fds, write_fds;
struct timeval *tvp, tv;
struct in_addr addr4;
struct ares_in6_addr addr6;
#ifdef USE_WINSOCK
WORD wVersionRequested = MAKEWORD(USE_WINSOCK,USE_WINSOCK);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
#endif
memset(&options, 0, sizeof(options));
status = ares_library_init(ARES_LIB_INIT_ALL);
if (status != ARES_SUCCESS)
{
fprintf(stderr, "ares_library_init: %s\n", ares_strerror(status));
return 1;
}
while ((c = ares_getopt(argc,argv,"dt:hs:")) != -1)
{
switch (c)
{
case 'd':
#ifdef WATT32
dbug_init();
#endif
break;
case 's':
optmask |= ARES_OPT_DOMAINS;
options.ndomains++;
options.domains = (char **)realloc(options.domains,
options.ndomains * sizeof(char *));
options.domains[options.ndomains - 1] = strdup(optarg);
break;
case 't':
if (!strcasecmp(optarg,"a"))
addr_family = AF_INET;
else if (!strcasecmp(optarg,"aaaa"))
addr_family = AF_INET6;
else if (!strcasecmp(optarg,"u"))
addr_family = AF_UNSPEC;
else
usage();
break;
case 'h':
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc < 1)
usage();
status = ares_init_options(&channel, &options, optmask);
if (status != ARES_SUCCESS)
{
fprintf(stderr, "ares_init: %s\n", ares_strerror(status));
return 1;
}
/* Initiate the queries, one per command-line argument. */
for ( ; *argv; argv++)
{
if (ares_inet_pton(AF_INET, *argv, &addr4) == 1)
{
ares_gethostbyaddr(channel, &addr4, sizeof(addr4), AF_INET, callback,
*argv);
}
else if (ares_inet_pton(AF_INET6, *argv, &addr6) == 1)
{
ares_gethostbyaddr(channel, &addr6, sizeof(addr6), AF_INET6, callback,
*argv);
}
else
{
ares_gethostbyname(channel, *argv, addr_family, callback, *argv);
}
}
/* Wait for all queries to complete. */
for (;;)
{
int res;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
nfds = ares_fds(channel, &read_fds, &write_fds);
if (nfds == 0)
break;
tvp = ares_timeout(channel, NULL, &tv);
res = select(nfds, &read_fds, &write_fds, NULL, tvp);
if (-1 == res)
break;
ares_process(channel, &read_fds, &write_fds);
}
ares_destroy(channel);
ares_library_cleanup();
#ifdef USE_WINSOCK
WSACleanup();
#endif
return 0;
}
static void callback(void *arg, int status, int timeouts, struct hostent *host)
{
char **p;
(void)timeouts;
if (status != ARES_SUCCESS)
{
fprintf(stderr, "%s: %s\n", (char *) arg, ares_strerror(status));
return;
}
for (p = host->h_addr_list; *p; p++)
{
char addr_buf[46] = "??";
ares_inet_ntop(host->h_addrtype, *p, addr_buf, sizeof(addr_buf));
printf("%-32s\t%s", host->h_name, addr_buf);
#if 0
if (host->h_aliases[0])
{
int i;
printf (", Aliases: ");
for (i = 0; host->h_aliases[i]; i++)
printf("%s ", host->h_aliases[i]);
}
#endif
puts("");
}
}
static void usage(void)
{
fprintf(stderr, "usage: ahost [-t {a|aaaa|u}] {host|addr} ...\n");
exit(1);
}

668
deps/c-ares/ares.h vendored Normal file
View File

@ -0,0 +1,668 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
* Copyright (C) 2007-2013 by Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#ifndef ARES__H
#define ARES__H
#include "ares_version.h" /* c-ares version defines */
#include "ares_build.h" /* c-ares build definitions */
#include "ares_rules.h" /* c-ares rules enforcement */
/*
* Define WIN32 when build target is Win32 API
*/
#if (defined(_WIN32) || defined(__WIN32__)) && \
!defined(WIN32) && !defined(__SYMBIAN32__)
# define WIN32
#endif
#include <sys/types.h>
/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish
libc5-based Linux systems. Only include it on system that are known to
require it! */
#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \
defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \
defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \
defined(__QNXNTO__)
#include <sys/select.h>
#endif
#if (defined(NETWARE) && !defined(__NOVELL_LIBC__))
#include <sys/bsdskt.h>
#endif
#if defined(WATT32)
# include <netinet/in.h>
# include <sys/socket.h>
# include <tcp.h>
#elif defined(_WIN32_WCE)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <winsock.h>
#elif defined(WIN32)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <winsock2.h>
# include <ws2tcpip.h>
#else
# include <sys/socket.h>
# include <netinet/in.h>
#endif
#if defined(ANDROID) || defined(__ANDROID__)
#include <jni.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
** c-ares external API function linkage decorations.
*/
#ifdef CARES_STATICLIB
# define CARES_EXTERN
#elif defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)
# if defined(CARES_BUILDING_LIBRARY)
# define CARES_EXTERN __declspec(dllexport)
# else
# define CARES_EXTERN __declspec(dllimport)
# endif
#elif defined(CARES_BUILDING_LIBRARY) && defined(CARES_SYMBOL_HIDING)
# define CARES_EXTERN CARES_SYMBOL_SCOPE_EXTERN
#else
# define CARES_EXTERN
#endif
#define ARES_SUCCESS 0
/* Server error codes (ARES_ENODATA indicates no relevant answer) */
#define ARES_ENODATA 1
#define ARES_EFORMERR 2
#define ARES_ESERVFAIL 3
#define ARES_ENOTFOUND 4
#define ARES_ENOTIMP 5
#define ARES_EREFUSED 6
/* Locally generated error codes */
#define ARES_EBADQUERY 7
#define ARES_EBADNAME 8
#define ARES_EBADFAMILY 9
#define ARES_EBADRESP 10
#define ARES_ECONNREFUSED 11
#define ARES_ETIMEOUT 12
#define ARES_EOF 13
#define ARES_EFILE 14
#define ARES_ENOMEM 15
#define ARES_EDESTRUCTION 16
#define ARES_EBADSTR 17
/* ares_getnameinfo error codes */
#define ARES_EBADFLAGS 18
/* ares_getaddrinfo error codes */
#define ARES_ENONAME 19
#define ARES_EBADHINTS 20
/* Uninitialized library error code */
#define ARES_ENOTINITIALIZED 21 /* introduced in 1.7.0 */
/* ares_library_init error codes */
#define ARES_ELOADIPHLPAPI 22 /* introduced in 1.7.0 */
#define ARES_EADDRGETNETWORKPARAMS 23 /* introduced in 1.7.0 */
/* More error codes */
#define ARES_ECANCELLED 24 /* introduced in 1.7.0 */
/* Flag values */
#define ARES_FLAG_USEVC (1 << 0)
#define ARES_FLAG_PRIMARY (1 << 1)
#define ARES_FLAG_IGNTC (1 << 2)
#define ARES_FLAG_NORECURSE (1 << 3)
#define ARES_FLAG_STAYOPEN (1 << 4)
#define ARES_FLAG_NOSEARCH (1 << 5)
#define ARES_FLAG_NOALIASES (1 << 6)
#define ARES_FLAG_NOCHECKRESP (1 << 7)
#define ARES_FLAG_EDNS (1 << 8)
/* Option mask values */
#define ARES_OPT_FLAGS (1 << 0)
#define ARES_OPT_TIMEOUT (1 << 1)
#define ARES_OPT_TRIES (1 << 2)
#define ARES_OPT_NDOTS (1 << 3)
#define ARES_OPT_UDP_PORT (1 << 4)
#define ARES_OPT_TCP_PORT (1 << 5)
#define ARES_OPT_SERVERS (1 << 6)
#define ARES_OPT_DOMAINS (1 << 7)
#define ARES_OPT_LOOKUPS (1 << 8)
#define ARES_OPT_SOCK_STATE_CB (1 << 9)
#define ARES_OPT_SORTLIST (1 << 10)
#define ARES_OPT_SOCK_SNDBUF (1 << 11)
#define ARES_OPT_SOCK_RCVBUF (1 << 12)
#define ARES_OPT_TIMEOUTMS (1 << 13)
#define ARES_OPT_ROTATE (1 << 14)
#define ARES_OPT_EDNSPSZ (1 << 15)
#define ARES_OPT_NOROTATE (1 << 16)
/* Nameinfo flag values */
#define ARES_NI_NOFQDN (1 << 0)
#define ARES_NI_NUMERICHOST (1 << 1)
#define ARES_NI_NAMEREQD (1 << 2)
#define ARES_NI_NUMERICSERV (1 << 3)
#define ARES_NI_DGRAM (1 << 4)
#define ARES_NI_TCP 0
#define ARES_NI_UDP ARES_NI_DGRAM
#define ARES_NI_SCTP (1 << 5)
#define ARES_NI_DCCP (1 << 6)
#define ARES_NI_NUMERICSCOPE (1 << 7)
#define ARES_NI_LOOKUPHOST (1 << 8)
#define ARES_NI_LOOKUPSERVICE (1 << 9)
/* Reserved for future use */
#define ARES_NI_IDN (1 << 10)
#define ARES_NI_IDN_ALLOW_UNASSIGNED (1 << 11)
#define ARES_NI_IDN_USE_STD3_ASCII_RULES (1 << 12)
/* Addrinfo flag values */
#define ARES_AI_CANONNAME (1 << 0)
#define ARES_AI_NUMERICHOST (1 << 1)
#define ARES_AI_PASSIVE (1 << 2)
#define ARES_AI_NUMERICSERV (1 << 3)
#define ARES_AI_V4MAPPED (1 << 4)
#define ARES_AI_ALL (1 << 5)
#define ARES_AI_ADDRCONFIG (1 << 6)
/* Reserved for future use */
#define ARES_AI_IDN (1 << 10)
#define ARES_AI_IDN_ALLOW_UNASSIGNED (1 << 11)
#define ARES_AI_IDN_USE_STD3_ASCII_RULES (1 << 12)
#define ARES_AI_CANONIDN (1 << 13)
#define ARES_AI_MASK (ARES_AI_CANONNAME|ARES_AI_NUMERICHOST|ARES_AI_PASSIVE| \
ARES_AI_NUMERICSERV|ARES_AI_V4MAPPED|ARES_AI_ALL| \
ARES_AI_ADDRCONFIG)
#define ARES_GETSOCK_MAXNUM 16 /* ares_getsock() can return info about this
many sockets */
#define ARES_GETSOCK_READABLE(bits,num) (bits & (1<< (num)))
#define ARES_GETSOCK_WRITABLE(bits,num) (bits & (1 << ((num) + \
ARES_GETSOCK_MAXNUM)))
/* c-ares library initialization flag values */
#define ARES_LIB_INIT_NONE (0)
#define ARES_LIB_INIT_WIN32 (1 << 0)
#define ARES_LIB_INIT_ALL (ARES_LIB_INIT_WIN32)
/*
* Typedef our socket type
*/
#ifndef ares_socket_typedef
#ifdef WIN32
typedef SOCKET ares_socket_t;
#define ARES_SOCKET_BAD INVALID_SOCKET
#else
typedef int ares_socket_t;
#define ARES_SOCKET_BAD -1
#endif
#define ares_socket_typedef
#endif /* ares_socket_typedef */
typedef void (*ares_sock_state_cb)(void *data,
ares_socket_t socket_fd,
int readable,
int writable);
struct apattern;
/* NOTE about the ares_options struct to users and developers.
This struct will remain looking like this. It will not be extended nor
shrunk in future releases, but all new options will be set by ares_set_*()
options instead of with the ares_init_options() function.
Eventually (in a galaxy far far away), all options will be settable by
ares_set_*() options and the ares_init_options() function will become
deprecated.
When new options are added to c-ares, they are not added to this
struct. And they are not "saved" with the ares_save_options() function but
instead we encourage the use of the ares_dup() function. Needless to say,
if you add config options to c-ares you need to make sure ares_dup()
duplicates this new option.
*/
struct ares_options {
int flags;
int timeout; /* in seconds or milliseconds, depending on options */
int tries;
int ndots;
unsigned short udp_port;
unsigned short tcp_port;
int socket_send_buffer_size;
int socket_receive_buffer_size;
struct in_addr *servers;
int nservers;
char **domains;
int ndomains;
char *lookups;
ares_sock_state_cb sock_state_cb;
void *sock_state_cb_data;
struct apattern *sortlist;
int nsort;
int ednspsz;
};
struct hostent;
struct timeval;
struct sockaddr;
struct ares_channeldata;
typedef struct ares_channeldata *ares_channel;
typedef void (*ares_callback)(void *arg,
int status,
int timeouts,
unsigned char *abuf,
int alen);
typedef void (*ares_host_callback)(void *arg,
int status,
int timeouts,
struct hostent *hostent);
typedef void (*ares_nameinfo_callback)(void *arg,
int status,
int timeouts,
char *node,
char *service);
typedef int (*ares_sock_create_callback)(ares_socket_t socket_fd,
int type,
void *data);
typedef int (*ares_sock_config_callback)(ares_socket_t socket_fd,
int type,
void *data);
CARES_EXTERN int ares_library_init(int flags);
CARES_EXTERN int ares_library_init_mem(int flags,
void *(*amalloc)(size_t size),
void (*afree)(void *ptr),
void *(*arealloc)(void *ptr, size_t size));
#if defined(ANDROID) || defined(__ANDROID__)
CARES_EXTERN void ares_library_init_jvm(JavaVM *jvm);
CARES_EXTERN int ares_library_init_android(jobject connectivity_manager);
CARES_EXTERN int ares_library_android_initialized(void);
#endif
CARES_EXTERN int ares_library_initialized(void);
CARES_EXTERN void ares_library_cleanup(void);
CARES_EXTERN const char *ares_version(int *version);
CARES_EXTERN int ares_init(ares_channel *channelptr);
CARES_EXTERN int ares_init_options(ares_channel *channelptr,
struct ares_options *options,
int optmask);
CARES_EXTERN int ares_save_options(ares_channel channel,
struct ares_options *options,
int *optmask);
CARES_EXTERN void ares_destroy_options(struct ares_options *options);
CARES_EXTERN int ares_dup(ares_channel *dest,
ares_channel src);
CARES_EXTERN void ares_destroy(ares_channel channel);
CARES_EXTERN void ares_cancel(ares_channel channel);
/* These next 3 configure local binding for the out-going socket
* connection. Use these to specify source IP and/or network device
* on multi-homed systems.
*/
CARES_EXTERN void ares_set_local_ip4(ares_channel channel, unsigned int local_ip);
/* local_ip6 should be 16 bytes in length */
CARES_EXTERN void ares_set_local_ip6(ares_channel channel,
const unsigned char* local_ip6);
/* local_dev_name should be null terminated. */
CARES_EXTERN void ares_set_local_dev(ares_channel channel,
const char* local_dev_name);
CARES_EXTERN void ares_set_socket_callback(ares_channel channel,
ares_sock_create_callback callback,
void *user_data);
CARES_EXTERN void ares_set_socket_configure_callback(ares_channel channel,
ares_sock_config_callback callback,
void *user_data);
CARES_EXTERN int ares_set_sortlist(ares_channel channel,
const char *sortstr);
/*
* Virtual function set to have user-managed socket IO.
* Note that all functions need to be defined, and when
* set, the library will not do any bind nor set any
* socket options, assuming the client handles these
* through either socket creation or the
* ares_sock_config_callback call.
*/
struct iovec;
struct ares_socket_functions {
ares_socket_t(*asocket)(int, int, int, void *);
int(*aclose)(ares_socket_t, void *);
int(*aconnect)(ares_socket_t, const struct sockaddr *, ares_socklen_t, void *);
ares_ssize_t(*arecvfrom)(ares_socket_t, void *, size_t, int, struct sockaddr *, ares_socklen_t *, void *);
ares_ssize_t(*asendv)(ares_socket_t, const struct iovec *, int, void *);
};
CARES_EXTERN void ares_set_socket_functions(ares_channel channel,
const struct ares_socket_functions * funcs,
void *user_data);
CARES_EXTERN void ares_send(ares_channel channel,
const unsigned char *qbuf,
int qlen,
ares_callback callback,
void *arg);
CARES_EXTERN void ares_query(ares_channel channel,
const char *name,
int dnsclass,
int type,
ares_callback callback,
void *arg);
CARES_EXTERN void ares_search(ares_channel channel,
const char *name,
int dnsclass,
int type,
ares_callback callback,
void *arg);
CARES_EXTERN void ares_gethostbyname(ares_channel channel,
const char *name,
int family,
ares_host_callback callback,
void *arg);
CARES_EXTERN int ares_gethostbyname_file(ares_channel channel,
const char *name,
int family,
struct hostent **host);
CARES_EXTERN void ares_gethostbyaddr(ares_channel channel,
const void *addr,
int addrlen,
int family,
ares_host_callback callback,
void *arg);
CARES_EXTERN void ares_getnameinfo(ares_channel channel,
const struct sockaddr *sa,
ares_socklen_t salen,
int flags,
ares_nameinfo_callback callback,
void *arg);
CARES_EXTERN int ares_fds(ares_channel channel,
fd_set *read_fds,
fd_set *write_fds);
CARES_EXTERN int ares_getsock(ares_channel channel,
ares_socket_t *socks,
int numsocks);
CARES_EXTERN struct timeval *ares_timeout(ares_channel channel,
struct timeval *maxtv,
struct timeval *tv);
CARES_EXTERN void ares_process(ares_channel channel,
fd_set *read_fds,
fd_set *write_fds);
CARES_EXTERN void ares_process_fd(ares_channel channel,
ares_socket_t read_fd,
ares_socket_t write_fd);
CARES_EXTERN int ares_create_query(const char *name,
int dnsclass,
int type,
unsigned short id,
int rd,
unsigned char **buf,
int *buflen,
int max_udp_size);
CARES_EXTERN int ares_mkquery(const char *name,
int dnsclass,
int type,
unsigned short id,
int rd,
unsigned char **buf,
int *buflen);
CARES_EXTERN int ares_expand_name(const unsigned char *encoded,
const unsigned char *abuf,
int alen,
char **s,
long *enclen);
CARES_EXTERN int ares_expand_string(const unsigned char *encoded,
const unsigned char *abuf,
int alen,
unsigned char **s,
long *enclen);
/*
* NOTE: before c-ares 1.7.0 we would most often use the system in6_addr
* struct below when ares itself was built, but many apps would use this
* private version since the header checked a HAVE_* define for it. Starting
* with 1.7.0 we always declare and use our own to stop relying on the
* system's one.
*/
struct ares_in6_addr {
union {
unsigned char _S6_u8[16];
} _S6_un;
};
struct ares_addrttl {
struct in_addr ipaddr;
int ttl;
};
struct ares_addr6ttl {
struct ares_in6_addr ip6addr;
int ttl;
};
struct ares_srv_reply {
struct ares_srv_reply *next;
char *host;
unsigned short priority;
unsigned short weight;
unsigned short port;
};
struct ares_mx_reply {
struct ares_mx_reply *next;
char *host;
unsigned short priority;
};
struct ares_txt_reply {
struct ares_txt_reply *next;
unsigned char *txt;
size_t length; /* length excludes null termination */
};
/* NOTE: This structure is a superset of ares_txt_reply
*/
struct ares_txt_ext {
struct ares_txt_ext *next;
unsigned char *txt;
size_t length;
/* 1 - if start of new record
* 0 - if a chunk in the same record */
unsigned char record_start;
};
struct ares_naptr_reply {
struct ares_naptr_reply *next;
unsigned char *flags;
unsigned char *service;
unsigned char *regexp;
char *replacement;
unsigned short order;
unsigned short preference;
};
struct ares_soa_reply {
char *nsname;
char *hostmaster;
unsigned int serial;
unsigned int refresh;
unsigned int retry;
unsigned int expire;
unsigned int minttl;
};
/*
** Parse the buffer, starting at *abuf and of length alen bytes, previously
** obtained from an ares_search call. Put the results in *host, if nonnull.
** Also, if addrttls is nonnull, put up to *naddrttls IPv4 addresses along with
** their TTLs in that array, and set *naddrttls to the number of addresses
** so written.
*/
CARES_EXTERN int ares_parse_a_reply(const unsigned char *abuf,
int alen,
struct hostent **host,
struct ares_addrttl *addrttls,
int *naddrttls);
CARES_EXTERN int ares_parse_aaaa_reply(const unsigned char *abuf,
int alen,
struct hostent **host,
struct ares_addr6ttl *addrttls,
int *naddrttls);
CARES_EXTERN int ares_parse_ptr_reply(const unsigned char *abuf,
int alen,
const void *addr,
int addrlen,
int family,
struct hostent **host);
CARES_EXTERN int ares_parse_ns_reply(const unsigned char *abuf,
int alen,
struct hostent **host);
CARES_EXTERN int ares_parse_srv_reply(const unsigned char* abuf,
int alen,
struct ares_srv_reply** srv_out);
CARES_EXTERN int ares_parse_mx_reply(const unsigned char* abuf,
int alen,
struct ares_mx_reply** mx_out);
CARES_EXTERN int ares_parse_txt_reply(const unsigned char* abuf,
int alen,
struct ares_txt_reply** txt_out);
CARES_EXTERN int ares_parse_txt_reply_ext(const unsigned char* abuf,
int alen,
struct ares_txt_ext** txt_out);
CARES_EXTERN int ares_parse_naptr_reply(const unsigned char* abuf,
int alen,
struct ares_naptr_reply** naptr_out);
CARES_EXTERN int ares_parse_soa_reply(const unsigned char* abuf,
int alen,
struct ares_soa_reply** soa_out);
CARES_EXTERN void ares_free_string(void *str);
CARES_EXTERN void ares_free_hostent(struct hostent *host);
CARES_EXTERN void ares_free_data(void *dataptr);
CARES_EXTERN const char *ares_strerror(int code);
struct ares_addr_node {
struct ares_addr_node *next;
int family;
union {
struct in_addr addr4;
struct ares_in6_addr addr6;
} addr;
};
struct ares_addr_port_node {
struct ares_addr_port_node *next;
int family;
union {
struct in_addr addr4;
struct ares_in6_addr addr6;
} addr;
int udp_port;
int tcp_port;
};
CARES_EXTERN int ares_set_servers(ares_channel channel,
struct ares_addr_node *servers);
CARES_EXTERN int ares_set_servers_ports(ares_channel channel,
struct ares_addr_port_node *servers);
/* Incomming string format: host[:port][,host[:port]]... */
CARES_EXTERN int ares_set_servers_csv(ares_channel channel,
const char* servers);
CARES_EXTERN int ares_set_servers_ports_csv(ares_channel channel,
const char* servers);
CARES_EXTERN int ares_get_servers(ares_channel channel,
struct ares_addr_node **servers);
CARES_EXTERN int ares_get_servers_ports(ares_channel channel,
struct ares_addr_port_node **servers);
CARES_EXTERN const char *ares_inet_ntop(int af, const void *src, char *dst,
ares_socklen_t size);
CARES_EXTERN int ares_inet_pton(int af, const char *src, void *dst);
#ifdef __cplusplus
}
#endif
#endif /* ARES__H */

61
deps/c-ares/ares__close_sockets.c vendored Normal file
View File

@ -0,0 +1,61 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares.h"
#include "ares_private.h"
void ares__close_sockets(ares_channel channel, struct server_state *server)
{
struct send_request *sendreq;
/* Free all pending output buffers. */
while (server->qhead)
{
/* Advance server->qhead; pull out query as we go. */
sendreq = server->qhead;
server->qhead = sendreq->next;
if (sendreq->data_storage != NULL)
ares_free(sendreq->data_storage);
ares_free(sendreq);
}
server->qtail = NULL;
/* Reset any existing input buffer. */
if (server->tcp_buffer)
ares_free(server->tcp_buffer);
server->tcp_buffer = NULL;
server->tcp_lenbuf_pos = 0;
/* Reset brokenness */
server->is_broken = 0;
/* Close the TCP and UDP sockets. */
if (server->tcp_socket != ARES_SOCKET_BAD)
{
SOCK_STATE_CALLBACK(channel, server->tcp_socket, 0, 0);
ares__socket_close(channel, server->tcp_socket);
server->tcp_socket = ARES_SOCKET_BAD;
server->tcp_connection_generation = ++channel->tcp_connection_generation;
}
if (server->udp_socket != ARES_SOCKET_BAD)
{
SOCK_STATE_CALLBACK(channel, server->udp_socket, 0, 0);
ares__socket_close(channel, server->udp_socket);
server->udp_socket = ARES_SOCKET_BAD;
}
}

261
deps/c-ares/ares__get_hostent.c vendored Normal file
View File

@ -0,0 +1,261 @@
/* Copyright 1998, 2011 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#include "ares.h"
#include "ares_inet_net_pton.h"
#include "ares_nowarn.h"
#include "ares_private.h"
int ares__get_hostent(FILE *fp, int family, struct hostent **host)
{
char *line = NULL, *p, *q, **alias;
char *txtaddr, *txthost, *txtalias;
int status;
size_t addrlen, linesize, naliases;
struct ares_addr addr;
struct hostent *hostent = NULL;
*host = NULL; /* Assume failure */
/* Validate family */
switch (family) {
case AF_INET:
case AF_INET6:
case AF_UNSPEC:
break;
default:
return ARES_EBADFAMILY;
}
while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
{
/* Trim line comment. */
p = line;
while (*p && (*p != '#'))
p++;
*p = '\0';
/* Trim trailing whitespace. */
q = p - 1;
while ((q >= line) && ISSPACE(*q))
q--;
*++q = '\0';
/* Skip leading whitespace. */
p = line;
while (*p && ISSPACE(*p))
p++;
if (!*p)
/* Ignore line if empty. */
continue;
/* Pointer to start of IPv4 or IPv6 address part. */
txtaddr = p;
/* Advance past address part. */
while (*p && !ISSPACE(*p))
p++;
if (!*p)
/* Ignore line if reached end of line. */
continue;
/* Null terminate address part. */
*p = '\0';
/* Advance to host name */
p++;
while (*p && ISSPACE(*p))
p++;
if (!*p)
/* Ignore line if reached end of line. */
continue; /* LCOV_EXCL_LINE: trailing whitespace already stripped */
/* Pointer to start of host name. */
txthost = p;
/* Advance past host name. */
while (*p && !ISSPACE(*p))
p++;
/* Pointer to start of first alias. */
txtalias = NULL;
if (*p)
{
q = p + 1;
while (*q && ISSPACE(*q))
q++;
if (*q)
txtalias = q;
}
/* Null terminate host name. */
*p = '\0';
/* find out number of aliases. */
naliases = 0;
if (txtalias)
{
p = txtalias;
while (*p)
{
while (*p && !ISSPACE(*p))
p++;
while (*p && ISSPACE(*p))
p++;
naliases++;
}
}
/* Convert address string to network address for the requested family. */
addrlen = 0;
addr.family = AF_UNSPEC;
addr.addrV4.s_addr = INADDR_NONE;
if ((family == AF_INET) || (family == AF_UNSPEC))
{
addr.addrV4.s_addr = inet_addr(txtaddr);
if (addr.addrV4.s_addr != INADDR_NONE)
{
/* Actual network address family and length. */
addr.family = AF_INET;
addrlen = sizeof(addr.addrV4);
}
}
if ((family == AF_INET6) || ((family == AF_UNSPEC) && (!addrlen)))
{
if (ares_inet_pton(AF_INET6, txtaddr, &addr.addrV6) > 0)
{
/* Actual network address family and length. */
addr.family = AF_INET6;
addrlen = sizeof(addr.addrV6);
}
}
if (!addrlen)
/* Ignore line if invalid address string for the requested family. */
continue;
/*
** Actual address family possible values are AF_INET and AF_INET6 only.
*/
/* Allocate memory for the hostent structure. */
hostent = ares_malloc(sizeof(struct hostent));
if (!hostent)
break;
/* Initialize fields for out of memory condition. */
hostent->h_aliases = NULL;
hostent->h_addr_list = NULL;
/* Copy official host name. */
hostent->h_name = ares_strdup(txthost);
if (!hostent->h_name)
break;
/* Copy network address. */
hostent->h_addr_list = ares_malloc(2 * sizeof(char *));
if (!hostent->h_addr_list)
break;
hostent->h_addr_list[1] = NULL;
hostent->h_addr_list[0] = ares_malloc(addrlen);
if (!hostent->h_addr_list[0])
break;
if (addr.family == AF_INET)
memcpy(hostent->h_addr_list[0], &addr.addrV4, sizeof(addr.addrV4));
else
memcpy(hostent->h_addr_list[0], &addr.addrV6, sizeof(addr.addrV6));
/* Copy aliases. */
hostent->h_aliases = ares_malloc((naliases + 1) * sizeof(char *));
if (!hostent->h_aliases)
break;
alias = hostent->h_aliases;
while (naliases)
*(alias + naliases--) = NULL;
*alias = NULL;
while (txtalias)
{
p = txtalias;
while (*p && !ISSPACE(*p))
p++;
q = p;
while (*q && ISSPACE(*q))
q++;
*p = '\0';
if ((*alias = ares_strdup(txtalias)) == NULL)
break;
alias++;
txtalias = *q ? q : NULL;
}
if (txtalias)
/* Alias memory allocation failure. */
break;
/* Copy actual network address family and length. */
hostent->h_addrtype = aresx_sitoss(addr.family);
hostent->h_length = aresx_uztoss(addrlen);
/* Free line buffer. */
ares_free(line);
/* Return hostent successfully */
*host = hostent;
return ARES_SUCCESS;
}
/* If allocated, free line buffer. */
if (line)
ares_free(line);
if (status == ARES_SUCCESS)
{
/* Memory allocation failure; clean up. */
if (hostent)
{
if (hostent->h_name)
ares_free((char *) hostent->h_name);
if (hostent->h_aliases)
{
for (alias = hostent->h_aliases; *alias; alias++)
ares_free(*alias);
ares_free(hostent->h_aliases);
}
if (hostent->h_addr_list)
{
if (hostent->h_addr_list[0])
ares_free(hostent->h_addr_list[0]);
ares_free(hostent->h_addr_list);
}
ares_free(hostent);
}
return ARES_ENOMEM;
}
return status;
}

73
deps/c-ares/ares__read_line.c vendored Normal file
View File

@ -0,0 +1,73 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares.h"
#include "ares_nowarn.h"
#include "ares_private.h"
/* This is an internal function. Its contract is to read a line from
* a file into a dynamically allocated buffer, zeroing the trailing
* newline if there is one. The calling routine may call
* ares__read_line multiple times with the same buf and bufsize
* pointers; *buf will be reallocated and *bufsize adjusted as
* appropriate. The initial value of *buf should be NULL. After the
* calling routine is done reading lines, it should free *buf.
*/
int ares__read_line(FILE *fp, char **buf, size_t *bufsize)
{
char *newbuf;
size_t offset = 0;
size_t len;
if (*buf == NULL)
{
*buf = ares_malloc(128);
if (!*buf)
return ARES_ENOMEM;
*bufsize = 128;
}
for (;;)
{
int bytestoread = aresx_uztosi(*bufsize - offset);
if (!fgets(*buf + offset, bytestoread, fp))
return (offset != 0) ? 0 : (ferror(fp)) ? ARES_EFILE : ARES_EOF;
len = offset + strlen(*buf + offset);
if ((*buf)[len - 1] == '\n')
{
(*buf)[len - 1] = 0;
break;
}
offset = len;
if(len < *bufsize - 1)
continue;
/* Allocate more space. */
newbuf = ares_realloc(*buf, *bufsize * 2);
if (!newbuf)
{
ares_free(*buf);
*buf = NULL;
return ARES_ENOMEM;
}
*buf = newbuf;
*bufsize *= 2;
}
return ARES_SUCCESS;
}

111
deps/c-ares/ares__timeval.c vendored Normal file
View File

@ -0,0 +1,111 @@
/* Copyright (C) 2008 by Daniel Stenberg et al
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. M.I.T. makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares.h"
#include "ares_private.h"
#if defined(WIN32) && !defined(MSDOS)
struct timeval ares__tvnow(void)
{
/*
** GetTickCount() is available on _all_ Windows versions from W95 up
** to nowadays. Returns milliseconds elapsed since last system boot,
** increases monotonically and wraps once 49.7 days have elapsed.
*/
struct timeval now;
DWORD milliseconds = GetTickCount();
now.tv_sec = milliseconds / 1000;
now.tv_usec = (milliseconds % 1000) * 1000;
return now;
}
#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
struct timeval ares__tvnow(void)
{
/*
** clock_gettime() is granted to be increased monotonically when the
** monotonic clock is queried. Time starting point is unspecified, it
** could be the system start-up time, the Epoch, or something else,
** in any case the time starting point does not change once that the
** system has started up.
*/
struct timeval now;
struct timespec tsnow;
if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) {
now.tv_sec = tsnow.tv_sec;
now.tv_usec = tsnow.tv_nsec / 1000;
}
/*
** Even when the configure process has truly detected monotonic clock
** availability, it might happen that it is not actually available at
** run-time. When this occurs simply fallback to other time source.
*/
#ifdef HAVE_GETTIMEOFDAY
else
(void)gettimeofday(&now, NULL); /* LCOV_EXCL_LINE */
#else
else {
now.tv_sec = (long)time(NULL);
now.tv_usec = 0;
}
#endif
return now;
}
#elif defined(HAVE_GETTIMEOFDAY)
struct timeval ares__tvnow(void)
{
/*
** gettimeofday() is not granted to be increased monotonically, due to
** clock drifting and external source time synchronization it can jump
** forward or backward in time.
*/
struct timeval now;
(void)gettimeofday(&now, NULL);
return now;
}
#else
struct timeval ares__tvnow(void)
{
/*
** time() returns the value of time in seconds since the Epoch.
*/
struct timeval now;
now.tv_sec = (long)time(NULL);
now.tv_usec = 0;
return now;
}
#endif
#if 0 /* Not used */
/*
* Make sure that the first argument is the more recent time, as otherwise
* we'll get a weird negative time-diff back...
*
* Returns: the time difference in number of milliseconds.
*/
long ares__tvdiff(struct timeval newer, struct timeval older)
{
return (newer.tv_sec-older.tv_sec)*1000+
(newer.tv_usec-older.tv_usec)/1000;
}
#endif

347
deps/c-ares/ares_android.c vendored Normal file
View File

@ -0,0 +1,347 @@
/* Copyright (C) 2017 by John Schember <john@nachtimwald.com>
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#if defined(ANDROID) || defined(__ANDROID__)
#include <jni.h>
#include "ares_setup.h"
#include "ares.h"
#include "ares_android.h"
#include "ares_private.h"
static JavaVM *android_jvm = NULL;
static jobject android_connectivity_manager = NULL;
/* ConnectivityManager.getActiveNetwork */
static jmethodID android_cm_active_net_mid = NULL;
/* ConnectivityManager.getLinkProperties */
static jmethodID android_cm_link_props_mid = NULL;
/* LinkProperties.getDnsServers */
static jmethodID android_lp_dns_servers_mid = NULL;
/* List.size */
static jmethodID android_list_size_mid = NULL;
/* List.get */
static jmethodID android_list_get_mid = NULL;
/* InetAddress.getHostAddress */
static jmethodID android_ia_host_addr_mid = NULL;
static jclass jni_get_class(JNIEnv *env, const char *path)
{
jclass cls = NULL;
if (env == NULL || path == NULL || *path == '\0')
return NULL;
cls = (*env)->FindClass(env, path);
if ((*env)->ExceptionOccurred(env)) {
(*env)->ExceptionClear(env);
return NULL;
}
return cls;
}
static jmethodID jni_get_method_id(JNIEnv *env, jclass cls,
const char *func_name, const char *signature)
{
jmethodID mid = NULL;
if (env == NULL || cls == NULL || func_name == NULL || *func_name == '\0' ||
signature == NULL || *signature == '\0')
{
return NULL;
}
mid = (*env)->GetMethodID(env, cls, func_name, signature);
if ((*env)->ExceptionOccurred(env))
{
(*env)->ExceptionClear(env);
return NULL;
}
return mid;
}
void ares_library_init_jvm(JavaVM *jvm)
{
android_jvm = jvm;
}
int ares_library_init_android(jobject connectivity_manager)
{
JNIEnv *env = NULL;
int need_detatch = 0;
int res;
int ret = ARES_ENOTINITIALIZED;
jclass obj_cls = NULL;
if (android_jvm == NULL)
goto cleanup;
res = (*android_jvm)->GetEnv(android_jvm, (void **)&env, JNI_VERSION_1_6);
if (res == JNI_EDETACHED)
{
env = NULL;
res = (*android_jvm)->AttachCurrentThread(android_jvm, &env, NULL);
need_detatch = 1;
}
if (res != JNI_OK || env == NULL)
goto cleanup;
android_connectivity_manager =
(*env)->NewGlobalRef(env, connectivity_manager);
if (android_connectivity_manager == NULL)
goto cleanup;
/* Initialization has succeeded. Now attempt to cache the methods that will be
* called by ares_get_android_server_list. */
ret = ARES_SUCCESS;
/* ConnectivityManager in API 1. */
obj_cls = jni_get_class(env, "android/net/ConnectivityManager");
if (obj_cls == NULL)
goto cleanup;
/* ConnectivityManager.getActiveNetwork in API 23. */
android_cm_active_net_mid =
jni_get_method_id(env, obj_cls, "getActiveNetwork",
"()Landroid/net/Network;");
if (android_cm_active_net_mid == NULL)
goto cleanup;
/* ConnectivityManager.getLinkProperties in API 21. */
android_cm_link_props_mid =
jni_get_method_id(env, obj_cls, "getLinkProperties",
"(Landroid/net/Network;)Landroid/net/LinkProperties;");
if (android_cm_link_props_mid == NULL)
goto cleanup;
/* LinkProperties in API 21. */
(*env)->DeleteLocalRef(env, obj_cls);
obj_cls = jni_get_class(env, "android/net/LinkProperties");
if (obj_cls == NULL)
goto cleanup;
/* getDnsServers in API 21. */
android_lp_dns_servers_mid = jni_get_method_id(env, obj_cls, "getDnsServers",
"()Ljava/util/List;");
if (android_lp_dns_servers_mid == NULL)
goto cleanup;
(*env)->DeleteLocalRef(env, obj_cls);
obj_cls = jni_get_class(env, "java/util/List");
if (obj_cls == NULL)
goto cleanup;
android_list_size_mid = jni_get_method_id(env, obj_cls, "size", "()I");
if (android_list_size_mid == NULL)
goto cleanup;
android_list_get_mid = jni_get_method_id(env, obj_cls, "get",
"(I)Ljava/lang/Object;");
if (android_list_get_mid == NULL)
goto cleanup;
(*env)->DeleteLocalRef(env, obj_cls);
obj_cls = jni_get_class(env, "java/net/InetAddress");
if (obj_cls == NULL)
goto cleanup;
android_ia_host_addr_mid = jni_get_method_id(env, obj_cls, "getHostAddress",
"()Ljava/lang/String;");
if (android_ia_host_addr_mid == NULL)
goto cleanup;
(*env)->DeleteLocalRef(env, obj_cls);
goto done;
cleanup:
if (obj_cls != NULL)
(*env)->DeleteLocalRef(env, obj_cls);
android_cm_active_net_mid = NULL;
android_cm_link_props_mid = NULL;
android_lp_dns_servers_mid = NULL;
android_list_size_mid = NULL;
android_list_get_mid = NULL;
android_ia_host_addr_mid = NULL;
done:
if (need_detatch)
(*android_jvm)->DetachCurrentThread(android_jvm);
return ret;
}
int ares_library_android_initialized(void)
{
if (android_jvm == NULL || android_connectivity_manager == NULL)
return ARES_ENOTINITIALIZED;
return ARES_SUCCESS;
}
void ares_library_cleanup_android(void)
{
JNIEnv *env = NULL;
int need_detatch = 0;
int res;
if (android_jvm == NULL || android_connectivity_manager == NULL)
return;
res = (*android_jvm)->GetEnv(android_jvm, (void **)&env, JNI_VERSION_1_6);
if (res == JNI_EDETACHED)
{
env = NULL;
res = (*android_jvm)->AttachCurrentThread(android_jvm, &env, NULL);
need_detatch = 1;
}
if (res != JNI_OK || env == NULL)
return;
android_cm_active_net_mid = NULL;
android_cm_link_props_mid = NULL;
android_lp_dns_servers_mid = NULL;
android_list_size_mid = NULL;
android_list_get_mid = NULL;
android_ia_host_addr_mid = NULL;
(*env)->DeleteGlobalRef(env, android_connectivity_manager);
android_connectivity_manager = NULL;
if (need_detatch)
(*android_jvm)->DetachCurrentThread(android_jvm);
}
char **ares_get_android_server_list(size_t max_servers,
size_t *num_servers)
{
JNIEnv *env = NULL;
jobject active_network = NULL;
jobject link_properties = NULL;
jobject server_list = NULL;
jobject server = NULL;
jstring str = NULL;
jint nserv;
const char *ch_server_address;
int res;
size_t i;
char **dns_list = NULL;
int need_detatch = 0;
if (android_jvm == NULL || android_connectivity_manager == NULL ||
max_servers == 0 || num_servers == NULL)
{
return NULL;
}
if (android_cm_active_net_mid == NULL || android_cm_link_props_mid == NULL ||
android_lp_dns_servers_mid == NULL || android_list_size_mid == NULL ||
android_list_get_mid == NULL || android_ia_host_addr_mid == NULL)
{
return NULL;
}
res = (*android_jvm)->GetEnv(android_jvm, (void **)&env, JNI_VERSION_1_6);
if (res == JNI_EDETACHED)
{
env = NULL;
res = (*android_jvm)->AttachCurrentThread(android_jvm, &env, NULL);
need_detatch = 1;
}
if (res != JNI_OK || env == NULL)
goto done;
/* JNI below is equivalent to this Java code.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import java.net.InetAddress;
import java.util.List;
ConnectivityManager cm = (ConnectivityManager)this.getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
Network an = cm.getActiveNetwork();
LinkProperties lp = cm.getLinkProperties(an);
List<InetAddress> dns = lp.getDnsServers();
for (InetAddress ia: dns) {
String ha = ia.getHostAddress();
}
Note: The JNI ConnectivityManager object and all method IDs were previously
initialized in ares_library_init_android.
*/
active_network = (*env)->CallObjectMethod(env, android_connectivity_manager,
android_cm_active_net_mid);
if (active_network == NULL)
goto done;
link_properties =
(*env)->CallObjectMethod(env, android_connectivity_manager,
android_cm_link_props_mid, active_network);
if (link_properties == NULL)
goto done;
server_list = (*env)->CallObjectMethod(env, link_properties,
android_lp_dns_servers_mid);
if (server_list == NULL)
goto done;
nserv = (*env)->CallIntMethod(env, server_list, android_list_size_mid);
if (nserv > (jint)max_servers)
nserv = (jint)max_servers;
if (nserv <= 0)
goto done;
*num_servers = (size_t)nserv;
dns_list = ares_malloc(sizeof(*dns_list)*(*num_servers));
for (i=0; i<*num_servers; i++)
{
server = (*env)->CallObjectMethod(env, server_list, android_list_get_mid,
(jint)i);
dns_list[i] = ares_malloc(64);
dns_list[i][0] = 0;
if (server == NULL)
{
continue;
}
str = (*env)->CallObjectMethod(env, server, android_ia_host_addr_mid);
ch_server_address = (*env)->GetStringUTFChars(env, str, 0);
strncpy(dns_list[i], ch_server_address, 64);
(*env)->ReleaseStringUTFChars(env, str, ch_server_address);
(*env)->DeleteLocalRef(env, str);
(*env)->DeleteLocalRef(env, server);
}
done:
if ((*env)->ExceptionOccurred(env))
(*env)->ExceptionClear(env);
if (server_list != NULL)
(*env)->DeleteLocalRef(env, server_list);
if (link_properties != NULL)
(*env)->DeleteLocalRef(env, link_properties);
if (active_network != NULL)
(*env)->DeleteLocalRef(env, active_network);
if (need_detatch)
(*android_jvm)->DetachCurrentThread(android_jvm);
return dns_list;
}
#else
/* warning: ISO C forbids an empty translation unit */
typedef int dummy_make_iso_compilers_happy;
#endif

267
deps/c-ares/ares_build.h.dist vendored Normal file
View File

@ -0,0 +1,267 @@
#ifndef __CARES_BUILD_H
#define __CARES_BUILD_H
/* Copyright (C) 2009 - 2013 by Daniel Stenberg et al
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. M.I.T. makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
/* ================================================================ */
/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* See file ares_build.h.in, run configure, and forget that this file
* exists it is only used for non-configure systems.
* But you can keep reading if you want ;-)
*
*/
/* ================================================================ */
/* NOTES FOR NON-CONFIGURE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* Nothing in this file is intended to be modified or adjusted by the
* c-ares library user nor by the c-ares library builder.
*
* If you think that something actually needs to be changed, adjusted
* or fixed in this file, then, report it on the c-ares development
* mailing list: http://cool.haxx.se/mailman/listinfo/c-ares/
*
* Try to keep one section per platform, compiler and architecture,
* otherwise, if an existing section is reused for a different one and
* later on the original is adjusted, probably the piggybacking one can
* be adversely changed.
*
* In order to differentiate between platforms/compilers/architectures
* use only compiler built in predefined preprocessor symbols.
*
* This header file shall only export symbols which are 'cares' or 'CARES'
* prefixed, otherwise public name space would be polluted.
*
* NOTE 2:
* -------
*
* Right now you might be staring at file ares_build.h.dist or ares_build.h,
* this is due to the following reason: file ares_build.h.dist is renamed
* to ares_build.h when the c-ares source code distribution archive file is
* created.
*
* File ares_build.h.dist is not included in the distribution archive.
* File ares_build.h is not present in the git tree.
*
* The distributed ares_build.h file is only intended to be used on systems
* which can not run the also distributed configure script.
*
* On systems capable of running the configure script, the configure process
* will overwrite the distributed ares_build.h file with one that is suitable
* and specific to the library being configured and built, which is generated
* from the ares_build.h.in template file.
*
* If you check out from git on a non-configure platform, you must run the
* appropriate buildconf* script to set up ares_build.h and other local files.
*
*/
/* ================================================================ */
/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */
/* ================================================================ */
#ifdef CARES_SIZEOF_LONG
# error "CARES_SIZEOF_LONG shall not be defined except in ares_build.h"
Error Compilation_aborted_CARES_SIZEOF_LONG_already_defined
#endif
#ifdef CARES_TYPEOF_ARES_SOCKLEN_T
# error "CARES_TYPEOF_ARES_SOCKLEN_T shall not be defined except in ares_build.h"
Error Compilation_aborted_CARES_TYPEOF_ARES_SOCKLEN_T_already_defined
#endif
#ifdef CARES_SIZEOF_ARES_SOCKLEN_T
# error "CARES_SIZEOF_ARES_SOCKLEN_T shall not be defined except in ares_build.h"
Error Compilation_aborted_CARES_SIZEOF_ARES_SOCKLEN_T_already_defined
#endif
/* ================================================================ */
/* EXTERNAL INTERFACE SETTINGS FOR NON-CONFIGURE SYSTEMS ONLY */
/* ================================================================ */
#if defined(__DJGPP__) || defined(__GO32__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__SALFORDC__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__BORLANDC__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__TURBOC__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__WATCOMC__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__POCC__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__LCC__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__SYMBIAN32__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T unsigned int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__MWERKS__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(_WIN32_WCE)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__MINGW32__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__VMS)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T unsigned int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
#elif defined(__OS400__)
# if defined(__ILEC400__)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T socklen_t
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
# define CARES_PULL_SYS_TYPES_H 1
# define CARES_PULL_SYS_SOCKET_H 1
# endif
#elif defined(__MVS__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# if defined(_ILP32)
# define CARES_SIZEOF_LONG 4
# elif defined(_LP64)
# define CARES_SIZEOF_LONG 8
# endif
# define CARES_TYPEOF_ARES_SOCKLEN_T socklen_t
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
# define CARES_PULL_SYS_TYPES_H 1
# define CARES_PULL_SYS_SOCKET_H 1
# endif
#elif defined(__370__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# if defined(_ILP32)
# define CARES_SIZEOF_LONG 4
# elif defined(_LP64)
# define CARES_SIZEOF_LONG 8
# endif
# define CARES_TYPEOF_ARES_SOCKLEN_T socklen_t
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
# define CARES_PULL_SYS_TYPES_H 1
# define CARES_PULL_SYS_SOCKET_H 1
# endif
#elif defined(TPF)
# define CARES_SIZEOF_LONG 8
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
/* ===================================== */
/* KEEP MSVC THE PENULTIMATE ENTRY */
/* ===================================== */
#elif defined(_MSC_VER)
# define CARES_SIZEOF_LONG 4
# define CARES_TYPEOF_ARES_SOCKLEN_T int
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
/* ===================================== */
/* KEEP GENERIC GCC THE LAST ENTRY */
/* ===================================== */
#elif defined(__GNUC__)
# if defined(__LP64__) || \
defined(__x86_64__) || defined(__ppc64__)
# define CARES_SIZEOF_LONG 8
# elif defined(__ILP32__) || \
defined(__i386__) || defined(__ppc__) || defined(__arm__)
# define CARES_SIZEOF_LONG 4
# endif
# define CARES_TYPEOF_ARES_SOCKLEN_T socklen_t
# define CARES_SIZEOF_ARES_SOCKLEN_T 4
# define CARES_PULL_SYS_TYPES_H 1
# define CARES_PULL_SYS_SOCKET_H 1
#else
# error "Unknown non-configure build target!"
Error Compilation_aborted_Unknown_non_configure_build_target
#endif
/* CARES_PULL_SYS_TYPES_H is defined above when inclusion of header file */
/* sys/types.h is required here to properly make type definitions below. */
#ifdef CARES_PULL_SYS_TYPES_H
# include <sys/types.h>
#endif
/* CARES_PULL_SYS_SOCKET_H is defined above when inclusion of header file */
/* sys/socket.h is required here to properly make type definitions below. */
#ifdef CARES_PULL_SYS_SOCKET_H
# include <sys/socket.h>
#endif
/* Data type definition of ares_socklen_t. */
#ifdef CARES_TYPEOF_ARES_SOCKLEN_T
typedef CARES_TYPEOF_ARES_SOCKLEN_T ares_socklen_t;
#endif
/* Data type definition of ares_ssize_t. */
#ifdef _WIN32
# ifdef _WIN64
# define CARES_TYPEOF_ARES_SSIZE_T __int64
# else
# define CARES_TYPEOF_ARES_SSIZE_T long
# endif
#else
# define CARES_TYPEOF_ARES_SSIZE_T ssize_t;
#endif
typedef CARES_TYPEOF_ARES_SSIZE_T ares_ssize_t;
#endif /* __CARES_BUILD_H */

100
deps/c-ares/ares_build.h.in vendored Normal file
View File

@ -0,0 +1,100 @@
#ifndef __CARES_BUILD_H
#define __CARES_BUILD_H
/* Copyright (C) 2009 by Daniel Stenberg et al
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. M.I.T. makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
/* ================================================================ */
/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */
/* ================================================================ */
/*
* NOTE 1:
* -------
*
* Nothing in this file is intended to be modified or adjusted by the
* c-ares library user nor by the c-ares library builder.
*
* If you think that something actually needs to be changed, adjusted
* or fixed in this file, then, report it on the c-ares development
* mailing list: http://cool.haxx.se/mailman/listinfo/c-ares/
*
* This header file shall only export symbols which are 'cares' or 'CARES'
* prefixed, otherwise public name space would be polluted.
*
* NOTE 2:
* -------
*
* Right now you might be staring at file ares_build.h.in or ares_build.h,
* this is due to the following reason:
*
* On systems capable of running the configure script, the configure process
* will overwrite the distributed ares_build.h file with one that is suitable
* and specific to the library being configured and built, which is generated
* from the ares_build.h.in template file.
*
*/
/* ================================================================ */
/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */
/* ================================================================ */
#ifdef CARES_TYPEOF_ARES_SOCKLEN_T
# error "CARES_TYPEOF_ARES_SOCKLEN_T shall not be defined except in ares_build.h"
Error Compilation_aborted_CARES_TYPEOF_ARES_SOCKLEN_T_already_defined
#endif
/* ================================================================ */
/* EXTERNAL INTERFACE SETTINGS FOR CONFIGURE CAPABLE SYSTEMS ONLY */
/* ================================================================ */
/* Configure process defines this to 1 when it finds out that system */
/* header file ws2tcpip.h must be included by the external interface. */
#undef CARES_PULL_WS2TCPIP_H
#ifdef CARES_PULL_WS2TCPIP_H
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <winsock2.h>
# include <ws2tcpip.h>
#endif
/* Configure process defines this to 1 when it finds out that system */
/* header file sys/types.h must be included by the external interface. */
#undef CARES_PULL_SYS_TYPES_H
#ifdef CARES_PULL_SYS_TYPES_H
# include <sys/types.h>
#endif
/* Configure process defines this to 1 when it finds out that system */
/* header file sys/socket.h must be included by the external interface. */
#undef CARES_PULL_SYS_SOCKET_H
#ifdef CARES_PULL_SYS_SOCKET_H
# include <sys/socket.h>
#endif
/* Integral data type used for ares_socklen_t. */
#undef CARES_TYPEOF_ARES_SOCKLEN_T
/* Data type definition of ares_socklen_t. */
typedef CARES_TYPEOF_ARES_SOCKLEN_T ares_socklen_t;
/* Integral data type used for ares_ssize_t. */
#undef CARES_TYPEOF_ARES_SSIZE_T
/* Data type definition of ares_ssize_t. */
typedef CARES_TYPEOF_ARES_SSIZE_T ares_ssize_t;
#endif /* __CARES_BUILD_H */

63
deps/c-ares/ares_cancel.c vendored Normal file
View File

@ -0,0 +1,63 @@
/* Copyright (C) 2004 by Daniel Stenberg et al
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. M.I.T. makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include <assert.h>
#include "ares.h"
#include "ares_private.h"
/*
* ares_cancel() cancels all ongoing requests/resolves that might be going on
* on the given channel. It does NOT kill the channel, use ares_destroy() for
* that.
*/
void ares_cancel(ares_channel channel)
{
struct query *query;
struct list_node list_head_copy;
struct list_node* list_head;
struct list_node* list_node;
int i;
if (!ares__is_list_empty(&(channel->all_queries)))
{
/* Swap list heads, so that only those queries which were present on entry
* into this function are cancelled. New queries added by callbacks of
* queries being cancelled will not be cancelled themselves.
*/
list_head = &(channel->all_queries);
list_head_copy.prev = list_head->prev;
list_head_copy.next = list_head->next;
list_head_copy.prev->next = &list_head_copy;
list_head_copy.next->prev = &list_head_copy;
list_head->prev = list_head;
list_head->next = list_head;
for (list_node = list_head_copy.next; list_node != &list_head_copy; )
{
query = list_node->data;
list_node = list_node->next; /* since we're deleting the query */
query->callback(query->arg, ARES_ECANCELLED, 0, NULL, 0);
ares__free_query(query);
}
}
if (!(channel->flags & ARES_FLAG_STAYOPEN) && ares__is_list_empty(&(channel->all_queries)))
{
if (channel->servers)
{
for (i = 0; i < channel->nservers; i++)
ares__close_sockets(channel, &channel->servers[i]);
}
}
}

504
deps/c-ares/ares_config.h.in vendored Normal file
View File

@ -0,0 +1,504 @@
/* ares_config.h.in. Generated from configure.ac by autoheader. */
/* Define if building universal (internal helper macro) */
#undef AC_APPLE_UNIVERSAL_BUILD
/* define this if ares is built for a big endian system */
#undef ARES_BIG_ENDIAN
/* when building as static part of libcurl */
#undef BUILDING_LIBCURL
/* Defined for build that exposes internal static functions for testing. */
#undef CARES_EXPOSE_STATICS
/* Defined for build with symbol hiding. */
#undef CARES_SYMBOL_HIDING
/* Definition to make a library symbol externally visible. */
#undef CARES_SYMBOL_SCOPE_EXTERN
/* the signed version of size_t */
#undef CARES_TYPEOF_ARES_SSIZE_T
/* Use resolver library to configure cares */
#undef CARES_USE_LIBRESOLV
/* if a /etc/inet dir is being used */
#undef ETC_INET
/* Define to the type of arg 2 for gethostname. */
#undef GETHOSTNAME_TYPE_ARG2
/* Define to the type qualifier of arg 1 for getnameinfo. */
#undef GETNAMEINFO_QUAL_ARG1
/* Define to the type of arg 1 for getnameinfo. */
#undef GETNAMEINFO_TYPE_ARG1
/* Define to the type of arg 2 for getnameinfo. */
#undef GETNAMEINFO_TYPE_ARG2
/* Define to the type of args 4 and 6 for getnameinfo. */
#undef GETNAMEINFO_TYPE_ARG46
/* Define to the type of arg 7 for getnameinfo. */
#undef GETNAMEINFO_TYPE_ARG7
/* Specifies the number of arguments to getservbyport_r */
#undef GETSERVBYPORT_R_ARGS
/* Specifies the size of the buffer to pass to getservbyport_r */
#undef GETSERVBYPORT_R_BUFSIZE
/* Define to 1 if you have AF_INET6. */
#undef HAVE_AF_INET6
/* Define to 1 if you have the <arpa/inet.h> header file. */
#undef HAVE_ARPA_INET_H
/* Define to 1 if you have the <arpa/nameser_compat.h> header file. */
#undef HAVE_ARPA_NAMESER_COMPAT_H
/* Define to 1 if you have the <arpa/nameser.h> header file. */
#undef HAVE_ARPA_NAMESER_H
/* Define to 1 if you have the <assert.h> header file. */
#undef HAVE_ASSERT_H
/* Define to 1 if you have the `bitncmp' function. */
#undef HAVE_BITNCMP
/* Define to 1 if bool is an available type. */
#undef HAVE_BOOL_T
/* Define to 1 if you have the clock_gettime function and monotonic timer. */
#undef HAVE_CLOCK_GETTIME_MONOTONIC
/* Define to 1 if you have the closesocket function. */
#undef HAVE_CLOSESOCKET
/* Define to 1 if you have the CloseSocket camel case function. */
#undef HAVE_CLOSESOCKET_CAMEL
/* Define to 1 if you have the connect function. */
#undef HAVE_CONNECT
/* define if the compiler supports basic C++11 syntax */
#undef HAVE_CXX11
/* Define to 1 if you have the <dlfcn.h> header file. */
#undef HAVE_DLFCN_H
/* Define to 1 if you have the <errno.h> header file. */
#undef HAVE_ERRNO_H
/* Define to 1 if you have the fcntl function. */
#undef HAVE_FCNTL
/* Define to 1 if you have the <fcntl.h> header file. */
#undef HAVE_FCNTL_H
/* Define to 1 if you have a working fcntl O_NONBLOCK function. */
#undef HAVE_FCNTL_O_NONBLOCK
/* Define to 1 if you have the freeaddrinfo function. */
#undef HAVE_FREEADDRINFO
/* Define to 1 if you have a working getaddrinfo function. */
#undef HAVE_GETADDRINFO
/* Define to 1 if the getaddrinfo function is threadsafe. */
#undef HAVE_GETADDRINFO_THREADSAFE
/* Define to 1 if you have the getenv function. */
#undef HAVE_GETENV
/* Define to 1 if you have the gethostbyaddr function. */
#undef HAVE_GETHOSTBYADDR
/* Define to 1 if you have the gethostbyname function. */
#undef HAVE_GETHOSTBYNAME
/* Define to 1 if you have the gethostname function. */
#undef HAVE_GETHOSTNAME
/* Define to 1 if you have the getnameinfo function. */
#undef HAVE_GETNAMEINFO
/* Define to 1 if you have the getservbyport_r function. */
#undef HAVE_GETSERVBYPORT_R
/* Define to 1 if you have the `gettimeofday' function. */
#undef HAVE_GETTIMEOFDAY
/* Define to 1 if you have the `if_indextoname' function. */
#undef HAVE_IF_INDEXTONAME
/* Define to 1 if you have a IPv6 capable working inet_net_pton function. */
#undef HAVE_INET_NET_PTON
/* Define to 1 if you have a IPv6 capable working inet_ntop function. */
#undef HAVE_INET_NTOP
/* Define to 1 if you have a IPv6 capable working inet_pton function. */
#undef HAVE_INET_PTON
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the ioctl function. */
#undef HAVE_IOCTL
/* Define to 1 if you have the ioctlsocket function. */
#undef HAVE_IOCTLSOCKET
/* Define to 1 if you have the IoctlSocket camel case function. */
#undef HAVE_IOCTLSOCKET_CAMEL
/* Define to 1 if you have a working IoctlSocket camel case FIONBIO function.
*/
#undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO
/* Define to 1 if you have a working ioctlsocket FIONBIO function. */
#undef HAVE_IOCTLSOCKET_FIONBIO
/* Define to 1 if you have a working ioctl FIONBIO function. */
#undef HAVE_IOCTL_FIONBIO
/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */
#undef HAVE_IOCTL_SIOCGIFADDR
/* Define to 1 if you have the `resolve' library (-lresolve). */
#undef HAVE_LIBRESOLVE
/* Define to 1 if you have the <limits.h> header file. */
#undef HAVE_LIMITS_H
/* if your compiler supports LL */
#undef HAVE_LL
/* Define to 1 if the compiler supports the 'long long' data type. */
#undef HAVE_LONGLONG
/* Define to 1 if you have the malloc.h header file. */
#undef HAVE_MALLOC_H
/* Define to 1 if you have the memory.h header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the MSG_NOSIGNAL flag. */
#undef HAVE_MSG_NOSIGNAL
/* Define to 1 if you have the <netdb.h> header file. */
#undef HAVE_NETDB_H
/* Define to 1 if you have the <netinet/in.h> header file. */
#undef HAVE_NETINET_IN_H
/* Define to 1 if you have the <netinet/tcp.h> header file. */
#undef HAVE_NETINET_TCP_H
/* Define to 1 if you have the <net/if.h> header file. */
#undef HAVE_NET_IF_H
/* Define to 1 if you have PF_INET6. */
#undef HAVE_PF_INET6
/* Define to 1 if you have the recv function. */
#undef HAVE_RECV
/* Define to 1 if you have the recvfrom function. */
#undef HAVE_RECVFROM
/* Define to 1 if you have the send function. */
#undef HAVE_SEND
/* Define to 1 if you have the setsockopt function. */
#undef HAVE_SETSOCKOPT
/* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */
#undef HAVE_SETSOCKOPT_SO_NONBLOCK
/* Define to 1 if you have the <signal.h> header file. */
#undef HAVE_SIGNAL_H
/* Define to 1 if sig_atomic_t is an available typedef. */
#undef HAVE_SIG_ATOMIC_T
/* Define to 1 if sig_atomic_t is already defined as volatile. */
#undef HAVE_SIG_ATOMIC_T_VOLATILE
/* Define to 1 if your struct sockaddr_in6 has sin6_scope_id. */
#undef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
/* Define to 1 if you have the socket function. */
#undef HAVE_SOCKET
/* Define to 1 if you have the <socket.h> header file. */
#undef HAVE_SOCKET_H
/* Define to 1 if you have the <stdbool.h> header file. */
#undef HAVE_STDBOOL_H
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the strcasecmp function. */
#undef HAVE_STRCASECMP
/* Define to 1 if you have the strcmpi function. */
#undef HAVE_STRCMPI
/* Define to 1 if you have the strdup function. */
#undef HAVE_STRDUP
/* Define to 1 if you have the stricmp function. */
#undef HAVE_STRICMP
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the strncasecmp function. */
#undef HAVE_STRNCASECMP
/* Define to 1 if you have the strncmpi function. */
#undef HAVE_STRNCMPI
/* Define to 1 if you have the strnicmp function. */
#undef HAVE_STRNICMP
/* Define to 1 if you have the <stropts.h> header file. */
#undef HAVE_STROPTS_H
/* Define to 1 if you have struct addrinfo. */
#undef HAVE_STRUCT_ADDRINFO
/* Define to 1 if you have struct in6_addr. */
#undef HAVE_STRUCT_IN6_ADDR
/* Define to 1 if you have struct sockaddr_in6. */
#undef HAVE_STRUCT_SOCKADDR_IN6
/* if struct sockaddr_storage is defined */
#undef HAVE_STRUCT_SOCKADDR_STORAGE
/* Define to 1 if you have the timeval struct. */
#undef HAVE_STRUCT_TIMEVAL
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#undef HAVE_SYS_IOCTL_H
/* Define to 1 if you have the <sys/param.h> header file. */
#undef HAVE_SYS_PARAM_H
/* Define to 1 if you have the <sys/select.h> header file. */
#undef HAVE_SYS_SELECT_H
/* Define to 1 if you have the <sys/socket.h> header file. */
#undef HAVE_SYS_SOCKET_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/time.h> header file. */
#undef HAVE_SYS_TIME_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have the <sys/uio.h> header file. */
#undef HAVE_SYS_UIO_H
/* Define to 1 if you have the <time.h> header file. */
#undef HAVE_TIME_H
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to 1 if you have the windows.h header file. */
#undef HAVE_WINDOWS_H
/* Define to 1 if you have the winsock2.h header file. */
#undef HAVE_WINSOCK2_H
/* Define to 1 if you have the winsock.h header file. */
#undef HAVE_WINSOCK_H
/* Define to 1 if you have the writev function. */
#undef HAVE_WRITEV
/* Define to 1 if you have the ws2tcpip.h header file. */
#undef HAVE_WS2TCPIP_H
/* Define if __system_property_get exists. */
#undef HAVE___SYSTEM_PROPERTY_GET
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#undef LT_OBJDIR
/* Define to 1 if you need the malloc.h header file even with stdlib.h */
#undef NEED_MALLOC_H
/* Define to 1 if you need the memory.h header file even with stdlib.h */
#undef NEED_MEMORY_H
/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */
#undef NEED_REENTRANT
/* Define to 1 if _THREAD_SAFE preprocessor symbol must be defined. */
#undef NEED_THREAD_SAFE
/* cpu-machine-OS */
#undef OS
/* Name of package */
#undef PACKAGE
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the home page for this package. */
#undef PACKAGE_URL
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* a suitable file/device to read random data from */
#undef RANDOM_FILE
/* Define to the type qualifier pointed by arg 5 for recvfrom. */
#undef RECVFROM_QUAL_ARG5
/* Define to the type of arg 1 for recvfrom. */
#undef RECVFROM_TYPE_ARG1
/* Define to the type pointed by arg 2 for recvfrom. */
#undef RECVFROM_TYPE_ARG2
/* Define to 1 if the type pointed by arg 2 for recvfrom is void. */
#undef RECVFROM_TYPE_ARG2_IS_VOID
/* Define to the type of arg 3 for recvfrom. */
#undef RECVFROM_TYPE_ARG3
/* Define to the type of arg 4 for recvfrom. */
#undef RECVFROM_TYPE_ARG4
/* Define to the type pointed by arg 5 for recvfrom. */
#undef RECVFROM_TYPE_ARG5
/* Define to 1 if the type pointed by arg 5 for recvfrom is void. */
#undef RECVFROM_TYPE_ARG5_IS_VOID
/* Define to the type pointed by arg 6 for recvfrom. */
#undef RECVFROM_TYPE_ARG6
/* Define to 1 if the type pointed by arg 6 for recvfrom is void. */
#undef RECVFROM_TYPE_ARG6_IS_VOID
/* Define to the function return type for recvfrom. */
#undef RECVFROM_TYPE_RETV
/* Define to the type of arg 1 for recv. */
#undef RECV_TYPE_ARG1
/* Define to the type of arg 2 for recv. */
#undef RECV_TYPE_ARG2
/* Define to the type of arg 3 for recv. */
#undef RECV_TYPE_ARG3
/* Define to the type of arg 4 for recv. */
#undef RECV_TYPE_ARG4
/* Define to the function return type for recv. */
#undef RECV_TYPE_RETV
/* Define as the return type of signal handlers (`int' or `void'). */
#undef RETSIGTYPE
/* Define to the type qualifier of arg 2 for send. */
#undef SEND_QUAL_ARG2
/* Define to the type of arg 1 for send. */
#undef SEND_TYPE_ARG1
/* Define to the type of arg 2 for send. */
#undef SEND_TYPE_ARG2
/* Define to the type of arg 3 for send. */
#undef SEND_TYPE_ARG3
/* Define to the type of arg 4 for send. */
#undef SEND_TYPE_ARG4
/* Define to the function return type for send. */
#undef SEND_TYPE_RETV
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#undef TIME_WITH_SYS_TIME
/* Define to disable non-blocking sockets. */
#undef USE_BLOCKING_SOCKETS
/* Version number of package */
#undef VERSION
/* Define to avoid automatic inclusion of winsock.h */
#undef WIN32_LEAN_AND_MEAN
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
# undef WORDS_BIGENDIAN
# endif
#endif
/* Define to 1 if OS is AIX. */
#ifndef _ALL_SOURCE
# undef _ALL_SOURCE
#endif
/* Enable large inode numbers on Mac OS X 10.5. */
#ifndef _DARWIN_USE_64_BIT_INODE
# define _DARWIN_USE_64_BIT_INODE 1
#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 empty if `const' does not conform to ANSI C. */
#undef const
/* Type to use in place of in_addr_t when system does not provide it. */
#undef in_addr_t
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef size_t

202
deps/c-ares/ares_create_query.c vendored Normal file
View File

@ -0,0 +1,202 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_NAMESER_H
# include <arpa/nameser.h>
#else
# include "nameser.h"
#endif
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
# include <arpa/nameser_compat.h>
#endif
#include "ares.h"
#include "ares_dns.h"
#include "ares_private.h"
#ifndef T_OPT
# define T_OPT 41 /* EDNS0 option (meta-RR) */
#endif
/* Header format, from RFC 1035:
* 1 1 1 1 1 1
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | ID |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | QDCOUNT |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | ANCOUNT |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | NSCOUNT |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | ARCOUNT |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*
* AA, TC, RA, and RCODE are only set in responses. Brief description
* of the remaining fields:
* ID Identifier to match responses with queries
* QR Query (0) or response (1)
* Opcode For our purposes, always QUERY
* RD Recursion desired
* Z Reserved (zero)
* QDCOUNT Number of queries
* ANCOUNT Number of answers
* NSCOUNT Number of name server records
* ARCOUNT Number of additional records
*
* Question format, from RFC 1035:
* 1 1 1 1 1 1
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | |
* / QNAME /
* / /
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | QTYPE |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | QCLASS |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*
* The query name is encoded as a series of labels, each represented
* as a one-byte length (maximum 63) followed by the text of the
* label. The list is terminated by a label of length zero (which can
* be thought of as the root domain).
*/
int ares_create_query(const char *name, int dnsclass, int type,
unsigned short id, int rd, unsigned char **bufp,
int *buflenp, int max_udp_size)
{
size_t len;
unsigned char *q;
const char *p;
size_t buflen;
unsigned char *buf;
/* Set our results early, in case we bail out early with an error. */
*buflenp = 0;
*bufp = NULL;
/* Allocate a memory area for the maximum size this packet might need. +2
* is for the length byte and zero termination if no dots or ecscaping is
* used.
*/
len = strlen(name) + 2 + HFIXEDSZ + QFIXEDSZ +
(max_udp_size ? EDNSFIXEDSZ : 0);
buf = ares_malloc(len);
if (!buf)
return ARES_ENOMEM;
/* Set up the header. */
q = buf;
memset(q, 0, HFIXEDSZ);
DNS_HEADER_SET_QID(q, id);
DNS_HEADER_SET_OPCODE(q, QUERY);
if (rd) {
DNS_HEADER_SET_RD(q, 1);
}
else {
DNS_HEADER_SET_RD(q, 0);
}
DNS_HEADER_SET_QDCOUNT(q, 1);
if (max_udp_size) {
DNS_HEADER_SET_ARCOUNT(q, 1);
}
/* A name of "." is a screw case for the loop below, so adjust it. */
if (strcmp(name, ".") == 0)
name++;
/* Start writing out the name after the header. */
q += HFIXEDSZ;
while (*name)
{
if (*name == '.') {
ares_free (buf);
return ARES_EBADNAME;
}
/* Count the number of bytes in this label. */
len = 0;
for (p = name; *p && *p != '.'; p++)
{
if (*p == '\\' && *(p + 1) != 0)
p++;
len++;
}
if (len > MAXLABEL) {
ares_free (buf);
return ARES_EBADNAME;
}
/* Encode the length and copy the data. */
*q++ = (unsigned char)len;
for (p = name; *p && *p != '.'; p++)
{
if (*p == '\\' && *(p + 1) != 0)
p++;
*q++ = *p;
}
/* Go to the next label and repeat, unless we hit the end. */
if (!*p)
break;
name = p + 1;
}
/* Add the zero-length label at the end. */
*q++ = 0;
/* Finish off the question with the type and class. */
DNS_QUESTION_SET_TYPE(q, type);
DNS_QUESTION_SET_CLASS(q, dnsclass);
q += QFIXEDSZ;
if (max_udp_size)
{
memset(q, 0, EDNSFIXEDSZ);
q++;
DNS_RR_SET_TYPE(q, T_OPT);
DNS_RR_SET_CLASS(q, max_udp_size);
q += (EDNSFIXEDSZ-1);
}
buflen = (q - buf);
/* Reject names that are longer than the maximum of 255 bytes that's
* specified in RFC 1035 ("To simplify implementations, the total length of
* a domain name (i.e., label octets and label length octets) is restricted
* to 255 octets or less."). */
if (buflen > (MAXCDNAME + HFIXEDSZ + QFIXEDSZ +
(max_udp_size ? EDNSFIXEDSZ : 0))) {
ares_free (buf);
return ARES_EBADNAME;
}
/* we know this fits in an int at this point */
*buflenp = (int) buflen;
*bufp = buf;
return ARES_SUCCESS;
}

222
deps/c-ares/ares_data.c vendored Normal file
View File

@ -0,0 +1,222 @@
/* Copyright (C) 2009-2013 by Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include <stddef.h>
#include "ares.h"
#include "ares_data.h"
#include "ares_private.h"
/*
** ares_free_data() - c-ares external API function.
**
** This function must be used by the application to free data memory that
** has been internally allocated by some c-ares function and for which a
** pointer has already been returned to the calling application. The list
** of c-ares functions returning pointers that must be free'ed using this
** function is:
**
** ares_get_servers()
** ares_parse_srv_reply()
** ares_parse_txt_reply()
*/
void ares_free_data(void *dataptr)
{
while (dataptr != NULL) {
struct ares_data *ptr;
void *next_data = NULL;
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:1684)
/* 1684: conversion from pointer to same-sized integral type */
#endif
ptr = (void *)((char *)dataptr - offsetof(struct ares_data, data));
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
if (ptr->mark != ARES_DATATYPE_MARK)
return;
switch (ptr->type)
{
case ARES_DATATYPE_MX_REPLY:
if (ptr->data.mx_reply.next)
next_data = ptr->data.mx_reply.next;
if (ptr->data.mx_reply.host)
ares_free(ptr->data.mx_reply.host);
break;
case ARES_DATATYPE_SRV_REPLY:
if (ptr->data.srv_reply.next)
next_data = ptr->data.srv_reply.next;
if (ptr->data.srv_reply.host)
ares_free(ptr->data.srv_reply.host);
break;
case ARES_DATATYPE_TXT_REPLY:
case ARES_DATATYPE_TXT_EXT:
if (ptr->data.txt_reply.next)
next_data = ptr->data.txt_reply.next;
if (ptr->data.txt_reply.txt)
ares_free(ptr->data.txt_reply.txt);
break;
case ARES_DATATYPE_ADDR_NODE:
if (ptr->data.addr_node.next)
next_data = ptr->data.addr_node.next;
break;
case ARES_DATATYPE_ADDR_PORT_NODE:
if (ptr->data.addr_port_node.next)
next_data = ptr->data.addr_port_node.next;
break;
case ARES_DATATYPE_NAPTR_REPLY:
if (ptr->data.naptr_reply.next)
next_data = ptr->data.naptr_reply.next;
if (ptr->data.naptr_reply.flags)
ares_free(ptr->data.naptr_reply.flags);
if (ptr->data.naptr_reply.service)
ares_free(ptr->data.naptr_reply.service);
if (ptr->data.naptr_reply.regexp)
ares_free(ptr->data.naptr_reply.regexp);
if (ptr->data.naptr_reply.replacement)
ares_free(ptr->data.naptr_reply.replacement);
break;
case ARES_DATATYPE_SOA_REPLY:
if (ptr->data.soa_reply.nsname)
ares_free(ptr->data.soa_reply.nsname);
if (ptr->data.soa_reply.hostmaster)
ares_free(ptr->data.soa_reply.hostmaster);
break;
default:
return;
}
ares_free(ptr);
dataptr = next_data;
}
}
/*
** ares_malloc_data() - c-ares internal helper function.
**
** This function allocates memory for a c-ares private ares_data struct
** for the specified ares_datatype, initializes c-ares private fields
** and zero initializes those which later might be used from the public
** API. It returns an interior pointer which can be passed by c-ares
** functions to the calling application, and that must be free'ed using
** c-ares external API function ares_free_data().
*/
void *ares_malloc_data(ares_datatype type)
{
struct ares_data *ptr;
ptr = ares_malloc(sizeof(struct ares_data));
if (!ptr)
return NULL;
switch (type)
{
case ARES_DATATYPE_MX_REPLY:
ptr->data.mx_reply.next = NULL;
ptr->data.mx_reply.host = NULL;
ptr->data.mx_reply.priority = 0;
break;
case ARES_DATATYPE_SRV_REPLY:
ptr->data.srv_reply.next = NULL;
ptr->data.srv_reply.host = NULL;
ptr->data.srv_reply.priority = 0;
ptr->data.srv_reply.weight = 0;
ptr->data.srv_reply.port = 0;
break;
case ARES_DATATYPE_TXT_EXT:
ptr->data.txt_ext.record_start = 0;
/* FALLTHROUGH */
case ARES_DATATYPE_TXT_REPLY:
ptr->data.txt_reply.next = NULL;
ptr->data.txt_reply.txt = NULL;
ptr->data.txt_reply.length = 0;
break;
case ARES_DATATYPE_ADDR_NODE:
ptr->data.addr_node.next = NULL;
ptr->data.addr_node.family = 0;
memset(&ptr->data.addr_node.addrV6, 0,
sizeof(ptr->data.addr_node.addrV6));
break;
case ARES_DATATYPE_ADDR_PORT_NODE:
ptr->data.addr_port_node.next = NULL;
ptr->data.addr_port_node.family = 0;
ptr->data.addr_port_node.udp_port = 0;
ptr->data.addr_port_node.tcp_port = 0;
memset(&ptr->data.addr_port_node.addrV6, 0,
sizeof(ptr->data.addr_port_node.addrV6));
break;
case ARES_DATATYPE_NAPTR_REPLY:
ptr->data.naptr_reply.next = NULL;
ptr->data.naptr_reply.flags = NULL;
ptr->data.naptr_reply.service = NULL;
ptr->data.naptr_reply.regexp = NULL;
ptr->data.naptr_reply.replacement = NULL;
ptr->data.naptr_reply.order = 0;
ptr->data.naptr_reply.preference = 0;
break;
case ARES_DATATYPE_SOA_REPLY:
ptr->data.soa_reply.nsname = NULL;
ptr->data.soa_reply.hostmaster = NULL;
ptr->data.soa_reply.serial = 0;
ptr->data.soa_reply.refresh = 0;
ptr->data.soa_reply.retry = 0;
ptr->data.soa_reply.expire = 0;
ptr->data.soa_reply.minttl = 0;
break;
default:
ares_free(ptr);
return NULL;
}
ptr->mark = ARES_DATATYPE_MARK;
ptr->type = type;
return &ptr->data;
}

72
deps/c-ares/ares_data.h vendored Normal file
View File

@ -0,0 +1,72 @@
/* Copyright (C) 2009-2013 by Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
typedef enum {
ARES_DATATYPE_UNKNOWN = 1, /* unknown data type - introduced in 1.7.0 */
ARES_DATATYPE_SRV_REPLY, /* struct ares_srv_reply - introduced in 1.7.0 */
ARES_DATATYPE_TXT_REPLY, /* struct ares_txt_reply - introduced in 1.7.0 */
ARES_DATATYPE_TXT_EXT, /* struct ares_txt_ext - introduced in 1.11.0 */
ARES_DATATYPE_ADDR_NODE, /* struct ares_addr_node - introduced in 1.7.1 */
ARES_DATATYPE_MX_REPLY, /* struct ares_mx_reply - introduced in 1.7.2 */
ARES_DATATYPE_NAPTR_REPLY,/* struct ares_naptr_reply - introduced in 1.7.6 */
ARES_DATATYPE_SOA_REPLY, /* struct ares_soa_reply - introduced in 1.9.0 */
#if 0
ARES_DATATYPE_ADDR6TTL, /* struct ares_addrttl */
ARES_DATATYPE_ADDRTTL, /* struct ares_addr6ttl */
ARES_DATATYPE_HOSTENT, /* struct hostent */
ARES_DATATYPE_OPTIONS, /* struct ares_options */
#endif
ARES_DATATYPE_ADDR_PORT_NODE, /* struct ares_addr_port_node - introduced in 1.11.0 */
ARES_DATATYPE_LAST /* not used - introduced in 1.7.0 */
} ares_datatype;
#define ARES_DATATYPE_MARK 0xbead
/*
* ares_data struct definition is internal to c-ares and shall not
* be exposed by the public API in order to allow future changes
* and extensions to it without breaking ABI. This will be used
* internally by c-ares as the container of multiple types of data
* dynamically allocated for which a reference will be returned
* to the calling application.
*
* c-ares API functions returning a pointer to c-ares internally
* allocated data will actually be returning an interior pointer
* into this ares_data struct.
*
* All this is 'invisible' to the calling application, the only
* requirement is that this kind of data must be free'ed by the
* calling application using ares_free_data() with the pointer
* it has received from a previous c-ares function call.
*/
struct ares_data {
ares_datatype type; /* Actual data type identifier. */
unsigned int mark; /* Private ares_data signature. */
union {
struct ares_txt_reply txt_reply;
struct ares_txt_ext txt_ext;
struct ares_srv_reply srv_reply;
struct ares_addr_node addr_node;
struct ares_addr_port_node addr_port_node;
struct ares_mx_reply mx_reply;
struct ares_naptr_reply naptr_reply;
struct ares_soa_reply soa_reply;
} data;
};
void *ares_malloc_data(ares_datatype type);

108
deps/c-ares/ares_destroy.c vendored Normal file
View File

@ -0,0 +1,108 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
* Copyright (C) 2004-2011 by Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include <assert.h>
#include "ares.h"
#include "ares_private.h"
void ares_destroy_options(struct ares_options *options)
{
int i;
if(options->servers)
ares_free(options->servers);
for (i = 0; i < options->ndomains; i++)
ares_free(options->domains[i]);
if(options->domains)
ares_free(options->domains);
if(options->sortlist)
ares_free(options->sortlist);
if(options->lookups)
ares_free(options->lookups);
}
void ares_destroy(ares_channel channel)
{
int i;
struct query *query;
struct list_node* list_head;
struct list_node* list_node;
if (!channel)
return;
list_head = &(channel->all_queries);
for (list_node = list_head->next; list_node != list_head; )
{
query = list_node->data;
list_node = list_node->next; /* since we're deleting the query */
query->callback(query->arg, ARES_EDESTRUCTION, 0, NULL, 0);
ares__free_query(query);
}
#ifndef NDEBUG
/* Freeing the query should remove it from all the lists in which it sits,
* so all query lists should be empty now.
*/
assert(ares__is_list_empty(&(channel->all_queries)));
for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
{
assert(ares__is_list_empty(&(channel->queries_by_qid[i])));
}
for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
{
assert(ares__is_list_empty(&(channel->queries_by_timeout[i])));
}
#endif
ares__destroy_servers_state(channel);
if (channel->domains) {
for (i = 0; i < channel->ndomains; i++)
ares_free(channel->domains[i]);
ares_free(channel->domains);
}
if(channel->sortlist)
ares_free(channel->sortlist);
if (channel->lookups)
ares_free(channel->lookups);
ares_free(channel);
}
void ares__destroy_servers_state(ares_channel channel)
{
struct server_state *server;
int i;
if (channel->servers)
{
for (i = 0; i < channel->nservers; i++)
{
server = &channel->servers[i];
ares__close_sockets(channel, server);
assert(ares__is_list_empty(&server->queries_to_server));
}
ares_free(channel->servers);
channel->servers = NULL;
}
channel->nservers = -1;
}

103
deps/c-ares/ares_dns.h vendored Normal file
View File

@ -0,0 +1,103 @@
#ifndef HEADER_CARES_DNS_H
#define HEADER_CARES_DNS_H
/* Copyright 1998, 2011 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
/*
* Macro DNS__16BIT reads a network short (16 bit) given in network
* byte order, and returns its value as an unsigned short.
*/
#define DNS__16BIT(p) ((unsigned short)((unsigned int) 0xffff & \
(((unsigned int)((unsigned char)(p)[0]) << 8U) | \
((unsigned int)((unsigned char)(p)[1])))))
/*
* Macro DNS__32BIT reads a network long (32 bit) given in network
* byte order, and returns its value as an unsigned int.
*/
#define DNS__32BIT(p) ((unsigned int) \
(((unsigned int)((unsigned char)(p)[0]) << 24U) | \
((unsigned int)((unsigned char)(p)[1]) << 16U) | \
((unsigned int)((unsigned char)(p)[2]) << 8U) | \
((unsigned int)((unsigned char)(p)[3]))))
#define DNS__SET16BIT(p, v) (((p)[0] = (unsigned char)(((v) >> 8) & 0xff)), \
((p)[1] = (unsigned char)((v) & 0xff)))
#define DNS__SET32BIT(p, v) (((p)[0] = (unsigned char)(((v) >> 24) & 0xff)), \
((p)[1] = (unsigned char)(((v) >> 16) & 0xff)), \
((p)[2] = (unsigned char)(((v) >> 8) & 0xff)), \
((p)[3] = (unsigned char)((v) & 0xff)))
#if 0
/* we cannot use this approach on systems where we can't access 16/32 bit
data on un-aligned addresses */
#define DNS__16BIT(p) ntohs(*(unsigned short*)(p))
#define DNS__32BIT(p) ntohl(*(unsigned long*)(p))
#define DNS__SET16BIT(p, v) *(unsigned short*)(p) = htons(v)
#define DNS__SET32BIT(p, v) *(unsigned long*)(p) = htonl(v)
#endif
/* Macros for parsing a DNS header */
#define DNS_HEADER_QID(h) DNS__16BIT(h)
#define DNS_HEADER_QR(h) (((h)[2] >> 7) & 0x1)
#define DNS_HEADER_OPCODE(h) (((h)[2] >> 3) & 0xf)
#define DNS_HEADER_AA(h) (((h)[2] >> 2) & 0x1)
#define DNS_HEADER_TC(h) (((h)[2] >> 1) & 0x1)
#define DNS_HEADER_RD(h) ((h)[2] & 0x1)
#define DNS_HEADER_RA(h) (((h)[3] >> 7) & 0x1)
#define DNS_HEADER_Z(h) (((h)[3] >> 4) & 0x7)
#define DNS_HEADER_RCODE(h) ((h)[3] & 0xf)
#define DNS_HEADER_QDCOUNT(h) DNS__16BIT((h) + 4)
#define DNS_HEADER_ANCOUNT(h) DNS__16BIT((h) + 6)
#define DNS_HEADER_NSCOUNT(h) DNS__16BIT((h) + 8)
#define DNS_HEADER_ARCOUNT(h) DNS__16BIT((h) + 10)
/* Macros for constructing a DNS header */
#define DNS_HEADER_SET_QID(h, v) DNS__SET16BIT(h, v)
#define DNS_HEADER_SET_QR(h, v) ((h)[2] |= (unsigned char)(((v) & 0x1) << 7))
#define DNS_HEADER_SET_OPCODE(h, v) ((h)[2] |= (unsigned char)(((v) & 0xf) << 3))
#define DNS_HEADER_SET_AA(h, v) ((h)[2] |= (unsigned char)(((v) & 0x1) << 2))
#define DNS_HEADER_SET_TC(h, v) ((h)[2] |= (unsigned char)(((v) & 0x1) << 1))
#define DNS_HEADER_SET_RD(h, v) ((h)[2] |= (unsigned char)((v) & 0x1))
#define DNS_HEADER_SET_RA(h, v) ((h)[3] |= (unsigned char)(((v) & 0x1) << 7))
#define DNS_HEADER_SET_Z(h, v) ((h)[3] |= (unsigned char)(((v) & 0x7) << 4))
#define DNS_HEADER_SET_RCODE(h, v) ((h)[3] |= (unsigned char)((v) & 0xf))
#define DNS_HEADER_SET_QDCOUNT(h, v) DNS__SET16BIT((h) + 4, v)
#define DNS_HEADER_SET_ANCOUNT(h, v) DNS__SET16BIT((h) + 6, v)
#define DNS_HEADER_SET_NSCOUNT(h, v) DNS__SET16BIT((h) + 8, v)
#define DNS_HEADER_SET_ARCOUNT(h, v) DNS__SET16BIT((h) + 10, v)
/* Macros for parsing the fixed part of a DNS question */
#define DNS_QUESTION_TYPE(q) DNS__16BIT(q)
#define DNS_QUESTION_CLASS(q) DNS__16BIT((q) + 2)
/* Macros for constructing the fixed part of a DNS question */
#define DNS_QUESTION_SET_TYPE(q, v) DNS__SET16BIT(q, v)
#define DNS_QUESTION_SET_CLASS(q, v) DNS__SET16BIT((q) + 2, v)
/* Macros for parsing the fixed part of a DNS resource record */
#define DNS_RR_TYPE(r) DNS__16BIT(r)
#define DNS_RR_CLASS(r) DNS__16BIT((r) + 2)
#define DNS_RR_TTL(r) DNS__32BIT((r) + 4)
#define DNS_RR_LEN(r) DNS__16BIT((r) + 8)
/* Macros for constructing the fixed part of a DNS resource record */
#define DNS_RR_SET_TYPE(r, v) DNS__SET16BIT(r, v)
#define DNS_RR_SET_CLASS(r, v) DNS__SET16BIT((r) + 2, v)
#define DNS_RR_SET_TTL(r, v) DNS__SET32BIT((r) + 4, v)
#define DNS_RR_SET_LEN(r, v) DNS__SET16BIT((r) + 8, v)
#endif /* HEADER_CARES_DNS_H */

209
deps/c-ares/ares_expand_name.c vendored Normal file
View File

@ -0,0 +1,209 @@
/* Copyright 1998, 2011 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_NAMESER_H
# include <arpa/nameser.h>
#else
# include "nameser.h"
#endif
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
# include <arpa/nameser_compat.h>
#endif
#include "ares.h"
#include "ares_nowarn.h"
#include "ares_private.h" /* for the memdebug */
/* Maximum number of indirections allowed for a name */
#define MAX_INDIRS 50
static int name_length(const unsigned char *encoded, const unsigned char *abuf,
int alen);
/* Expand an RFC1035-encoded domain name given by encoded. The
* containing message is given by abuf and alen. The result given by
* *s, which is set to a NUL-terminated allocated buffer. *enclen is
* set to the length of the encoded name (not the length of the
* expanded name; the goal is to tell the caller how many bytes to
* move forward to get past the encoded name).
*
* In the simple case, an encoded name is a series of labels, each
* composed of a one-byte length (limited to values between 0 and 63
* inclusive) followed by the label contents. The name is terminated
* by a zero-length label.
*
* In the more complicated case, a label may be terminated by an
* indirection pointer, specified by two bytes with the high bits of
* the first byte (corresponding to INDIR_MASK) set to 11. With the
* two high bits of the first byte stripped off, the indirection
* pointer gives an offset from the beginning of the containing
* message with more labels to decode. Indirection can happen an
* arbitrary number of times, so we have to detect loops.
*
* Since the expanded name uses '.' as a label separator, we use
* backslashes to escape periods or backslashes in the expanded name.
*/
int ares_expand_name(const unsigned char *encoded, const unsigned char *abuf,
int alen, char **s, long *enclen)
{
int len, indir = 0;
char *q;
const unsigned char *p;
union {
ares_ssize_t sig;
size_t uns;
} nlen;
nlen.sig = name_length(encoded, abuf, alen);
if (nlen.sig < 0)
return ARES_EBADNAME;
*s = ares_malloc(nlen.uns + 1);
if (!*s)
return ARES_ENOMEM;
q = *s;
if (nlen.uns == 0) {
/* RFC2181 says this should be ".": the root of the DNS tree.
* Since this function strips trailing dots though, it becomes ""
*/
q[0] = '\0';
/* indirect root label (like 0xc0 0x0c) is 2 bytes long (stupid, but
valid) */
if ((*encoded & INDIR_MASK) == INDIR_MASK)
*enclen = 2L;
else
*enclen = 1L; /* the caller should move one byte to get past this */
return ARES_SUCCESS;
}
/* No error-checking necessary; it was all done by name_length(). */
p = encoded;
while (*p)
{
if ((*p & INDIR_MASK) == INDIR_MASK)
{
if (!indir)
{
*enclen = aresx_uztosl(p + 2U - encoded);
indir = 1;
}
p = abuf + ((*p & ~INDIR_MASK) << 8 | *(p + 1));
}
else
{
len = *p;
p++;
while (len--)
{
if (*p == '.' || *p == '\\')
*q++ = '\\';
*q++ = *p;
p++;
}
*q++ = '.';
}
}
if (!indir)
*enclen = aresx_uztosl(p + 1U - encoded);
/* Nuke the trailing period if we wrote one. */
if (q > *s)
*(q - 1) = 0;
else
*q = 0; /* zero terminate; LCOV_EXCL_LINE: empty names exit above */
return ARES_SUCCESS;
}
/* Return the length of the expansion of an encoded domain name, or
* -1 if the encoding is invalid.
*/
static int name_length(const unsigned char *encoded, const unsigned char *abuf,
int alen)
{
int n = 0, offset, indir = 0, top;
/* Allow the caller to pass us abuf + alen and have us check for it. */
if (encoded >= abuf + alen)
return -1;
while (*encoded)
{
top = (*encoded & INDIR_MASK);
if (top == INDIR_MASK)
{
/* Check the offset and go there. */
if (encoded + 1 >= abuf + alen)
return -1;
offset = (*encoded & ~INDIR_MASK) << 8 | *(encoded + 1);
if (offset >= alen)
return -1;
encoded = abuf + offset;
/* If we've seen more indirects than the message length,
* then there's a loop.
*/
++indir;
if (indir > alen || indir > MAX_INDIRS)
return -1;
}
else if (top == 0x00)
{
offset = *encoded;
if (encoded + offset + 1 >= abuf + alen)
return -1;
encoded++;
while (offset--)
{
n += (*encoded == '.' || *encoded == '\\') ? 2 : 1;
encoded++;
}
n++;
}
else
{
/* RFC 1035 4.1.4 says other options (01, 10) for top 2
* bits are reserved.
*/
return -1;
}
}
/* If there were any labels at all, then the number of dots is one
* less than the number of labels, so subtract one.
*/
return (n) ? n - 1 : n;
}
/* Like ares_expand_name but returns EBADRESP in case of invalid input. */
int ares__expand_name_for_response(const unsigned char *encoded,
const unsigned char *abuf, int alen,
char **s, long *enclen)
{
int status = ares_expand_name(encoded, abuf, alen, s, enclen);
if (status == ARES_EBADNAME)
status = ARES_EBADRESP;
return status;
}

70
deps/c-ares/ares_expand_string.c vendored Normal file
View File

@ -0,0 +1,70 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_NAMESER_H
# include <arpa/nameser.h>
#else
# include "nameser.h"
#endif
#include "ares.h"
#include "ares_private.h" /* for the memdebug */
/* Simply decodes a length-encoded character string. The first byte of the
* input is the length of the string to be returned and the bytes thereafter
* are the characters of the string. The returned result will be NULL
* terminated.
*/
int ares_expand_string(const unsigned char *encoded,
const unsigned char *abuf,
int alen,
unsigned char **s,
long *enclen)
{
unsigned char *q;
union {
ares_ssize_t sig;
size_t uns;
} elen;
if (encoded == abuf+alen)
return ARES_EBADSTR;
elen.uns = *encoded;
if (encoded+elen.sig+1 > abuf+alen)
return ARES_EBADSTR;
encoded++;
*s = ares_malloc(elen.uns+1);
if (*s == NULL)
return ARES_ENOMEM;
q = *s;
strncpy((char *)q, (char *)encoded, elen.uns);
q[elen.uns] = '\0';
*s = q;
*enclen = (long)(elen.sig+1);
return ARES_SUCCESS;
}

59
deps/c-ares/ares_fds.c vendored Normal file
View File

@ -0,0 +1,59 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares.h"
#include "ares_nowarn.h"
#include "ares_private.h"
int ares_fds(ares_channel channel, fd_set *read_fds, fd_set *write_fds)
{
struct server_state *server;
ares_socket_t nfds;
int i;
/* Are there any active queries? */
int active_queries = !ares__is_list_empty(&(channel->all_queries));
nfds = 0;
for (i = 0; i < channel->nservers; i++)
{
server = &channel->servers[i];
/* We only need to register interest in UDP sockets if we have
* outstanding queries.
*/
if (active_queries && server->udp_socket != ARES_SOCKET_BAD)
{
FD_SET(server->udp_socket, read_fds);
if (server->udp_socket >= nfds)
nfds = server->udp_socket + 1;
}
/* We always register for TCP events, because we want to know
* when the other side closes the connection, so we don't waste
* time trying to use a broken connection.
*/
if (server->tcp_socket != ARES_SOCKET_BAD)
{
FD_SET(server->tcp_socket, read_fds);
if (server->qhead)
FD_SET(server->tcp_socket, write_fds);
if (server->tcp_socket >= nfds)
nfds = server->tcp_socket + 1;
}
}
return (int)nfds;
}

41
deps/c-ares/ares_free_hostent.c vendored Normal file
View File

@ -0,0 +1,41 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#include "ares.h"
#include "ares_private.h" /* for memdebug */
void ares_free_hostent(struct hostent *host)
{
char **p;
if (!host)
return;
ares_free((char *)(host->h_name));
for (p = host->h_aliases; *p; p++)
ares_free(*p);
ares_free(host->h_aliases);
ares_free(host->h_addr_list[0]); /* no matter if there is one or many entries,
there is only one malloc for all of them */
ares_free(host->h_addr_list);
ares_free(host);
}

25
deps/c-ares/ares_free_string.c vendored Normal file
View File

@ -0,0 +1,25 @@
/* Copyright 2000 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares.h"
#include "ares_private.h"
void ares_free_string(void *str)
{
ares_free(str);
}

30
deps/c-ares/ares_getenv.c vendored Normal file
View File

@ -0,0 +1,30 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares_getenv.h"
#ifndef HAVE_GETENV
char *ares_getenv(const char *name)
{
#ifdef _WIN32_WCE
return NULL;
#endif
}
#endif

26
deps/c-ares/ares_getenv.h vendored Normal file
View File

@ -0,0 +1,26 @@
#ifndef HEADER_CARES_GETENV_H
#define HEADER_CARES_GETENV_H
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifndef HAVE_GETENV
extern char *ares_getenv(const char *name);
#endif
#endif /* HEADER_CARES_GETENV_H */

294
deps/c-ares/ares_gethostbyaddr.c vendored Normal file
View File

@ -0,0 +1,294 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#ifdef HAVE_ARPA_NAMESER_H
# include <arpa/nameser.h>
#else
# include "nameser.h"
#endif
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
# include <arpa/nameser_compat.h>
#endif
#include "ares.h"
#include "ares_inet_net_pton.h"
#include "ares_platform.h"
#include "ares_private.h"
#ifdef WATT32
#undef WIN32
#endif
struct addr_query {
/* Arguments passed to ares_gethostbyaddr() */
ares_channel channel;
struct ares_addr addr;
ares_host_callback callback;
void *arg;
const char *remaining_lookups;
int timeouts;
};
static void next_lookup(struct addr_query *aquery);
static void addr_callback(void *arg, int status, int timeouts,
unsigned char *abuf, int alen);
static void end_aquery(struct addr_query *aquery, int status,
struct hostent *host);
static int file_lookup(struct ares_addr *addr, struct hostent **host);
static void ptr_rr_name(char *name, const struct ares_addr *addr);
void ares_gethostbyaddr(ares_channel channel, const void *addr, int addrlen,
int family, ares_host_callback callback, void *arg)
{
struct addr_query *aquery;
if (family != AF_INET && family != AF_INET6)
{
callback(arg, ARES_ENOTIMP, 0, NULL);
return;
}
if ((family == AF_INET && addrlen != sizeof(aquery->addr.addrV4)) ||
(family == AF_INET6 && addrlen != sizeof(aquery->addr.addrV6)))
{
callback(arg, ARES_ENOTIMP, 0, NULL);
return;
}
aquery = ares_malloc(sizeof(struct addr_query));
if (!aquery)
{
callback(arg, ARES_ENOMEM, 0, NULL);
return;
}
aquery->channel = channel;
if (family == AF_INET)
memcpy(&aquery->addr.addrV4, addr, sizeof(aquery->addr.addrV4));
else
memcpy(&aquery->addr.addrV6, addr, sizeof(aquery->addr.addrV6));
aquery->addr.family = family;
aquery->callback = callback;
aquery->arg = arg;
aquery->remaining_lookups = channel->lookups;
aquery->timeouts = 0;
next_lookup(aquery);
}
static void next_lookup(struct addr_query *aquery)
{
const char *p;
char name[128];
int status;
struct hostent *host;
for (p = aquery->remaining_lookups; *p; p++)
{
switch (*p)
{
case 'b':
ptr_rr_name(name, &aquery->addr);
aquery->remaining_lookups = p + 1;
ares_query(aquery->channel, name, C_IN, T_PTR, addr_callback,
aquery);
return;
case 'f':
status = file_lookup(&aquery->addr, &host);
/* this status check below previously checked for !ARES_ENOTFOUND,
but we should not assume that this single error code is the one
that can occur, as that is in fact no longer the case */
if (status == ARES_SUCCESS)
{
end_aquery(aquery, status, host);
return;
}
break;
}
}
end_aquery(aquery, ARES_ENOTFOUND, NULL);
}
static void addr_callback(void *arg, int status, int timeouts,
unsigned char *abuf, int alen)
{
struct addr_query *aquery = (struct addr_query *) arg;
struct hostent *host;
size_t addrlen;
aquery->timeouts += timeouts;
if (status == ARES_SUCCESS)
{
if (aquery->addr.family == AF_INET)
{
addrlen = sizeof(aquery->addr.addrV4);
status = ares_parse_ptr_reply(abuf, alen, &aquery->addr.addrV4,
(int)addrlen, AF_INET, &host);
}
else
{
addrlen = sizeof(aquery->addr.addrV6);
status = ares_parse_ptr_reply(abuf, alen, &aquery->addr.addrV6,
(int)addrlen, AF_INET6, &host);
}
end_aquery(aquery, status, host);
}
else if (status == ARES_EDESTRUCTION || status == ARES_ECANCELLED)
end_aquery(aquery, status, NULL);
else
next_lookup(aquery);
}
static void end_aquery(struct addr_query *aquery, int status,
struct hostent *host)
{
aquery->callback(aquery->arg, status, aquery->timeouts, host);
if (host)
ares_free_hostent(host);
ares_free(aquery);
}
static int file_lookup(struct ares_addr *addr, struct hostent **host)
{
FILE *fp;
int status;
int error;
#ifdef WIN32
char PATH_HOSTS[MAX_PATH];
win_platform platform;
PATH_HOSTS[0] = '\0';
platform = ares__getplatform();
if (platform == WIN_NT) {
char tmp[MAX_PATH];
HKEY hkeyHosts;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ,
&hkeyHosts) == ERROR_SUCCESS)
{
DWORD dwLength = MAX_PATH;
RegQueryValueExA(hkeyHosts, DATABASEPATH, NULL, NULL, (LPBYTE)tmp,
&dwLength);
ExpandEnvironmentStringsA(tmp, PATH_HOSTS, MAX_PATH);
RegCloseKey(hkeyHosts);
}
}
else if (platform == WIN_9X)
GetWindowsDirectoryA(PATH_HOSTS, MAX_PATH);
else
return ARES_ENOTFOUND;
strcat(PATH_HOSTS, WIN_PATH_HOSTS);
#elif defined(WATT32)
extern const char *_w32_GetHostsFile (void);
const char *PATH_HOSTS = _w32_GetHostsFile();
if (!PATH_HOSTS)
return ARES_ENOTFOUND;
#endif
fp = fopen(PATH_HOSTS, "r");
if (!fp)
{
error = ERRNO;
switch(error)
{
case ENOENT:
case ESRCH:
return ARES_ENOTFOUND;
default:
DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
error, strerror(error)));
DEBUGF(fprintf(stderr, "Error opening file: %s\n",
PATH_HOSTS));
*host = NULL;
return ARES_EFILE;
}
}
while ((status = ares__get_hostent(fp, addr->family, host)) == ARES_SUCCESS)
{
if (addr->family != (*host)->h_addrtype)
{
ares_free_hostent(*host);
continue;
}
if (addr->family == AF_INET)
{
if (memcmp((*host)->h_addr, &addr->addrV4,
sizeof(addr->addrV4)) == 0)
break;
}
else if (addr->family == AF_INET6)
{
if (memcmp((*host)->h_addr, &addr->addrV6,
sizeof(addr->addrV6)) == 0)
break;
}
ares_free_hostent(*host);
}
fclose(fp);
if (status == ARES_EOF)
status = ARES_ENOTFOUND;
if (status != ARES_SUCCESS)
*host = NULL;
return status;
}
static void ptr_rr_name(char *name, const struct ares_addr *addr)
{
if (addr->family == AF_INET)
{
unsigned long laddr = ntohl(addr->addrV4.s_addr);
unsigned long a1 = (laddr >> 24UL) & 0xFFUL;
unsigned long a2 = (laddr >> 16UL) & 0xFFUL;
unsigned long a3 = (laddr >> 8UL) & 0xFFUL;
unsigned long a4 = laddr & 0xFFUL;
sprintf(name, "%lu.%lu.%lu.%lu.in-addr.arpa", a4, a3, a2, a1);
}
else
{
unsigned char *bytes = (unsigned char *)&addr->addrV6;
/* There are too many arguments to do this in one line using
* minimally C89-compliant compilers */
sprintf(name,
"%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.",
bytes[15]&0xf, bytes[15] >> 4, bytes[14]&0xf, bytes[14] >> 4,
bytes[13]&0xf, bytes[13] >> 4, bytes[12]&0xf, bytes[12] >> 4,
bytes[11]&0xf, bytes[11] >> 4, bytes[10]&0xf, bytes[10] >> 4,
bytes[9]&0xf, bytes[9] >> 4, bytes[8]&0xf, bytes[8] >> 4);
sprintf(name+strlen(name),
"%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.arpa",
bytes[7]&0xf, bytes[7] >> 4, bytes[6]&0xf, bytes[6] >> 4,
bytes[5]&0xf, bytes[5] >> 4, bytes[4]&0xf, bytes[4] >> 4,
bytes[3]&0xf, bytes[3] >> 4, bytes[2]&0xf, bytes[2] >> 4,
bytes[1]&0xf, bytes[1] >> 4, bytes[0]&0xf, bytes[0] >> 4);
}
}

518
deps/c-ares/ares_gethostbyname.c vendored Normal file
View File

@ -0,0 +1,518 @@
/* Copyright 1998, 2011, 2013 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#ifdef HAVE_ARPA_NAMESER_H
# include <arpa/nameser.h>
#else
# include "nameser.h"
#endif
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
# include <arpa/nameser_compat.h>
#endif
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include "ares.h"
#include "ares_inet_net_pton.h"
#include "bitncmp.h"
#include "ares_platform.h"
#include "ares_nowarn.h"
#include "ares_private.h"
#ifdef WATT32
#undef WIN32
#endif
struct host_query {
/* Arguments passed to ares_gethostbyname() */
ares_channel channel;
char *name;
ares_host_callback callback;
void *arg;
int sent_family; /* this family is what was is being used */
int want_family; /* this family is what is asked for in the API */
const char *remaining_lookups;
int timeouts;
};
static void next_lookup(struct host_query *hquery, int status_code);
static void host_callback(void *arg, int status, int timeouts,
unsigned char *abuf, int alen);
static void end_hquery(struct host_query *hquery, int status,
struct hostent *host);
static int fake_hostent(const char *name, int family,
ares_host_callback callback, void *arg);
static int file_lookup(const char *name, int family, struct hostent **host);
static void sort_addresses(struct hostent *host,
const struct apattern *sortlist, int nsort);
static void sort6_addresses(struct hostent *host,
const struct apattern *sortlist, int nsort);
static int get_address_index(const struct in_addr *addr,
const struct apattern *sortlist, int nsort);
static int get6_address_index(const struct ares_in6_addr *addr,
const struct apattern *sortlist, int nsort);
void ares_gethostbyname(ares_channel channel, const char *name, int family,
ares_host_callback callback, void *arg)
{
struct host_query *hquery;
/* Right now we only know how to look up Internet addresses - and unspec
means try both basically. */
switch (family) {
case AF_INET:
case AF_INET6:
case AF_UNSPEC:
break;
default:
callback(arg, ARES_ENOTIMP, 0, NULL);
return;
}
if (fake_hostent(name, family, callback, arg))
return;
/* Allocate and fill in the host query structure. */
hquery = ares_malloc(sizeof(struct host_query));
if (!hquery)
{
callback(arg, ARES_ENOMEM, 0, NULL);
return;
}
hquery->channel = channel;
hquery->name = ares_strdup(name);
hquery->want_family = family;
hquery->sent_family = -1; /* nothing is sent yet */
if (!hquery->name) {
ares_free(hquery);
callback(arg, ARES_ENOMEM, 0, NULL);
return;
}
hquery->callback = callback;
hquery->arg = arg;
hquery->remaining_lookups = channel->lookups;
hquery->timeouts = 0;
/* Start performing lookups according to channel->lookups. */
next_lookup(hquery, ARES_ECONNREFUSED /* initial error code */);
}
static void next_lookup(struct host_query *hquery, int status_code)
{
const char *p;
struct hostent *host;
int status = status_code;
for (p = hquery->remaining_lookups; *p; p++)
{
switch (*p)
{
case 'b':
/* DNS lookup */
hquery->remaining_lookups = p + 1;
if ((hquery->want_family == AF_INET6) ||
(hquery->want_family == AF_UNSPEC)) {
/* if inet6 or unspec, start out with AAAA */
hquery->sent_family = AF_INET6;
ares_search(hquery->channel, hquery->name, C_IN, T_AAAA,
host_callback, hquery);
}
else {
hquery->sent_family = AF_INET;
ares_search(hquery->channel, hquery->name, C_IN, T_A,
host_callback, hquery);
}
return;
case 'f':
/* Host file lookup */
status = file_lookup(hquery->name, hquery->want_family, &host);
/* this status check below previously checked for !ARES_ENOTFOUND,
but we should not assume that this single error code is the one
that can occur, as that is in fact no longer the case */
if (status == ARES_SUCCESS)
{
end_hquery(hquery, status, host);
return;
}
status = status_code; /* Use original status code */
break;
}
}
end_hquery(hquery, status, NULL);
}
static void host_callback(void *arg, int status, int timeouts,
unsigned char *abuf, int alen)
{
struct host_query *hquery = (struct host_query *) arg;
ares_channel channel = hquery->channel;
struct hostent *host = NULL;
hquery->timeouts += timeouts;
if (status == ARES_SUCCESS)
{
if (hquery->sent_family == AF_INET)
{
status = ares_parse_a_reply(abuf, alen, &host, NULL, NULL);
if (host && channel->nsort)
sort_addresses(host, channel->sortlist, channel->nsort);
}
else if (hquery->sent_family == AF_INET6)
{
status = ares_parse_aaaa_reply(abuf, alen, &host, NULL, NULL);
if ((status == ARES_ENODATA || status == ARES_EBADRESP ||
(status == ARES_SUCCESS && host && host->h_addr_list[0] == NULL)) &&
hquery->want_family == AF_UNSPEC) {
/* The query returned something but either there were no AAAA
records (e.g. just CNAME) or the response was malformed. Try
looking up A instead. */
if (host)
ares_free_hostent(host);
hquery->sent_family = AF_INET;
ares_search(hquery->channel, hquery->name, C_IN, T_A,
host_callback, hquery);
return;
}
if (host && channel->nsort)
sort6_addresses(host, channel->sortlist, channel->nsort);
}
end_hquery(hquery, status, host);
}
else if ((status == ARES_ENODATA || status == ARES_EBADRESP ||
status == ARES_ETIMEOUT) && (hquery->sent_family == AF_INET6 &&
hquery->want_family == AF_UNSPEC))
{
/* The AAAA query yielded no useful result. Now look up an A instead. */
hquery->sent_family = AF_INET;
ares_search(hquery->channel, hquery->name, C_IN, T_A, host_callback,
hquery);
}
else if (status == ARES_EDESTRUCTION)
end_hquery(hquery, status, NULL);
else
next_lookup(hquery, status);
}
static void end_hquery(struct host_query *hquery, int status,
struct hostent *host)
{
hquery->callback(hquery->arg, status, hquery->timeouts, host);
if (host)
ares_free_hostent(host);
ares_free(hquery->name);
ares_free(hquery);
}
/* If the name looks like an IP address, fake up a host entry, end the
* query immediately, and return true. Otherwise return false.
*/
static int fake_hostent(const char *name, int family,
ares_host_callback callback, void *arg)
{
struct hostent hostent;
char *aliases[1] = { NULL };
char *addrs[2];
int result = 0;
struct in_addr in;
struct ares_in6_addr in6;
if (family == AF_INET || family == AF_INET6)
{
/* It only looks like an IP address if it's all numbers and dots. */
int numdots = 0, valid = 1;
const char *p;
for (p = name; *p; p++)
{
if (!ISDIGIT(*p) && *p != '.') {
valid = 0;
break;
} else if (*p == '.') {
numdots++;
}
}
/* if we don't have 3 dots, it is illegal
* (although inet_addr doesn't think so).
*/
if (numdots != 3 || !valid)
result = 0;
else
result = ((in.s_addr = inet_addr(name)) == INADDR_NONE ? 0 : 1);
if (result)
family = AF_INET;
}
if (family == AF_INET6)
result = (ares_inet_pton(AF_INET6, name, &in6) < 1 ? 0 : 1);
if (!result)
return 0;
if (family == AF_INET)
{
hostent.h_length = (int)sizeof(struct in_addr);
addrs[0] = (char *)&in;
}
else if (family == AF_INET6)
{
hostent.h_length = (int)sizeof(struct ares_in6_addr);
addrs[0] = (char *)&in6;
}
/* Duplicate the name, to avoid a constness violation. */
hostent.h_name = ares_strdup(name);
if (!hostent.h_name)
{
callback(arg, ARES_ENOMEM, 0, NULL);
return 1;
}
/* Fill in the rest of the host structure and terminate the query. */
addrs[1] = NULL;
hostent.h_aliases = aliases;
hostent.h_addrtype = aresx_sitoss(family);
hostent.h_addr_list = addrs;
callback(arg, ARES_SUCCESS, 0, &hostent);
ares_free((char *)(hostent.h_name));
return 1;
}
/* This is an API method */
int ares_gethostbyname_file(ares_channel channel, const char *name,
int family, struct hostent **host)
{
int result;
/* We only take the channel to ensure that ares_init() been called. */
if(channel == NULL)
{
/* Anything will do, really. This seems fine, and is consistent with
other error cases. */
*host = NULL;
return ARES_ENOTFOUND;
}
/* Just chain to the internal implementation we use here; it's exactly
* what we want.
*/
result = file_lookup(name, family, host);
if(result != ARES_SUCCESS)
{
/* We guarantee a NULL hostent on failure. */
*host = NULL;
}
return result;
}
static int file_lookup(const char *name, int family, struct hostent **host)
{
FILE *fp;
char **alias;
int status;
int error;
#ifdef WIN32
char PATH_HOSTS[MAX_PATH];
win_platform platform;
PATH_HOSTS[0] = '\0';
platform = ares__getplatform();
if (platform == WIN_NT) {
char tmp[MAX_PATH];
HKEY hkeyHosts;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ,
&hkeyHosts) == ERROR_SUCCESS)
{
DWORD dwLength = MAX_PATH;
RegQueryValueExA(hkeyHosts, DATABASEPATH, NULL, NULL, (LPBYTE)tmp,
&dwLength);
ExpandEnvironmentStringsA(tmp, PATH_HOSTS, MAX_PATH);
RegCloseKey(hkeyHosts);
}
}
else if (platform == WIN_9X)
GetWindowsDirectoryA(PATH_HOSTS, MAX_PATH);
else
return ARES_ENOTFOUND;
strcat(PATH_HOSTS, WIN_PATH_HOSTS);
#elif defined(WATT32)
extern const char *_w32_GetHostsFile (void);
const char *PATH_HOSTS = _w32_GetHostsFile();
if (!PATH_HOSTS)
return ARES_ENOTFOUND;
#endif
fp = fopen(PATH_HOSTS, "r");
if (!fp)
{
error = ERRNO;
switch(error)
{
case ENOENT:
case ESRCH:
return ARES_ENOTFOUND;
default:
DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
error, strerror(error)));
DEBUGF(fprintf(stderr, "Error opening file: %s\n",
PATH_HOSTS));
*host = NULL;
return ARES_EFILE;
}
}
while ((status = ares__get_hostent(fp, family, host)) == ARES_SUCCESS)
{
if (strcasecmp((*host)->h_name, name) == 0)
break;
for (alias = (*host)->h_aliases; *alias; alias++)
{
if (strcasecmp(*alias, name) == 0)
break;
}
if (*alias)
break;
ares_free_hostent(*host);
}
fclose(fp);
if (status == ARES_EOF)
status = ARES_ENOTFOUND;
if (status != ARES_SUCCESS)
*host = NULL;
return status;
}
static void sort_addresses(struct hostent *host,
const struct apattern *sortlist, int nsort)
{
struct in_addr a1, a2;
int i1, i2, ind1, ind2;
/* This is a simple insertion sort, not optimized at all. i1 walks
* through the address list, with the loop invariant that everything
* to the left of i1 is sorted. In the loop body, the value at i1 is moved
* back through the list (via i2) until it is in sorted order.
*/
for (i1 = 0; host->h_addr_list[i1]; i1++)
{
memcpy(&a1, host->h_addr_list[i1], sizeof(struct in_addr));
ind1 = get_address_index(&a1, sortlist, nsort);
for (i2 = i1 - 1; i2 >= 0; i2--)
{
memcpy(&a2, host->h_addr_list[i2], sizeof(struct in_addr));
ind2 = get_address_index(&a2, sortlist, nsort);
if (ind2 <= ind1)
break;
memcpy(host->h_addr_list[i2 + 1], &a2, sizeof(struct in_addr));
}
memcpy(host->h_addr_list[i2 + 1], &a1, sizeof(struct in_addr));
}
}
/* Find the first entry in sortlist which matches addr. Return nsort
* if none of them match.
*/
static int get_address_index(const struct in_addr *addr,
const struct apattern *sortlist,
int nsort)
{
int i;
for (i = 0; i < nsort; i++)
{
if (sortlist[i].family != AF_INET)
continue;
if (sortlist[i].type == PATTERN_MASK)
{
if ((addr->s_addr & sortlist[i].mask.addr4.s_addr)
== sortlist[i].addrV4.s_addr)
break;
}
else
{
if (!ares__bitncmp(&addr->s_addr, &sortlist[i].addrV4.s_addr,
sortlist[i].mask.bits))
break;
}
}
return i;
}
static void sort6_addresses(struct hostent *host,
const struct apattern *sortlist, int nsort)
{
struct ares_in6_addr a1, a2;
int i1, i2, ind1, ind2;
/* This is a simple insertion sort, not optimized at all. i1 walks
* through the address list, with the loop invariant that everything
* to the left of i1 is sorted. In the loop body, the value at i1 is moved
* back through the list (via i2) until it is in sorted order.
*/
for (i1 = 0; host->h_addr_list[i1]; i1++)
{
memcpy(&a1, host->h_addr_list[i1], sizeof(struct ares_in6_addr));
ind1 = get6_address_index(&a1, sortlist, nsort);
for (i2 = i1 - 1; i2 >= 0; i2--)
{
memcpy(&a2, host->h_addr_list[i2], sizeof(struct ares_in6_addr));
ind2 = get6_address_index(&a2, sortlist, nsort);
if (ind2 <= ind1)
break;
memcpy(host->h_addr_list[i2 + 1], &a2, sizeof(struct ares_in6_addr));
}
memcpy(host->h_addr_list[i2 + 1], &a1, sizeof(struct ares_in6_addr));
}
}
/* Find the first entry in sortlist which matches addr. Return nsort
* if none of them match.
*/
static int get6_address_index(const struct ares_in6_addr *addr,
const struct apattern *sortlist,
int nsort)
{
int i;
for (i = 0; i < nsort; i++)
{
if (sortlist[i].family != AF_INET6)
continue;
if (!ares__bitncmp(addr, &sortlist[i].addrV6, sortlist[i].mask.bits))
break;
}
return i;
}

442
deps/c-ares/ares_getnameinfo.c vendored Normal file
View File

@ -0,0 +1,442 @@
/* Copyright 2005 by Dominick Meglio
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_GETSERVBYPORT_R
# if !defined(GETSERVBYPORT_R_ARGS) || \
(GETSERVBYPORT_R_ARGS < 4) || (GETSERVBYPORT_R_ARGS > 6)
# error "you MUST specifiy a valid number of arguments for getservbyport_r"
# endif
#endif
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#ifdef HAVE_ARPA_NAMESER_H
# include <arpa/nameser.h>
#else
# include "nameser.h"
#endif
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
# include <arpa/nameser_compat.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
#include "ares.h"
#include "ares_ipv6.h"
#include "ares_nowarn.h"
#include "ares_private.h"
struct nameinfo_query {
ares_nameinfo_callback callback;
void *arg;
union {
struct sockaddr_in addr4;
struct sockaddr_in6 addr6;
} addr;
int family;
int flags;
int timeouts;
};
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
#define IPBUFSIZ \
(sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255") + IF_NAMESIZE)
#else
#define IPBUFSIZ \
(sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"))
#endif
static void nameinfo_callback(void *arg, int status, int timeouts,
struct hostent *host);
static char *lookup_service(unsigned short port, int flags,
char *buf, size_t buflen);
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
static void append_scopeid(struct sockaddr_in6 *addr6, unsigned int scopeid,
char *buf, size_t buflen);
#endif
STATIC_TESTABLE char *ares_striendstr(const char *s1, const char *s2);
void ares_getnameinfo(ares_channel channel, const struct sockaddr *sa,
ares_socklen_t salen,
int flags, ares_nameinfo_callback callback, void *arg)
{
struct sockaddr_in *addr = NULL;
struct sockaddr_in6 *addr6 = NULL;
struct nameinfo_query *niquery;
unsigned int port = 0;
/* Validate socket address family and length */
if ((sa->sa_family == AF_INET) &&
(salen == sizeof(struct sockaddr_in)))
{
addr = (struct sockaddr_in *)sa;
port = addr->sin_port;
}
else if ((sa->sa_family == AF_INET6) &&
(salen == sizeof(struct sockaddr_in6)))
{
addr6 = (struct sockaddr_in6 *)sa;
port = addr6->sin6_port;
}
else
{
callback(arg, ARES_ENOTIMP, 0, NULL, NULL);
return;
}
/* If neither, assume they want a host */
if (!(flags & ARES_NI_LOOKUPSERVICE) && !(flags & ARES_NI_LOOKUPHOST))
flags |= ARES_NI_LOOKUPHOST;
/* All they want is a service, no need for DNS */
if ((flags & ARES_NI_LOOKUPSERVICE) && !(flags & ARES_NI_LOOKUPHOST))
{
char buf[33], *service;
service = lookup_service((unsigned short)(port & 0xffff),
flags, buf, sizeof(buf));
callback(arg, ARES_SUCCESS, 0, NULL, service);
return;
}
/* They want a host lookup */
if ((flags & ARES_NI_LOOKUPHOST))
{
/* A numeric host can be handled without DNS */
if ((flags & ARES_NI_NUMERICHOST))
{
char ipbuf[IPBUFSIZ];
char srvbuf[33];
char *service = NULL;
ipbuf[0] = 0;
/* Specifying not to lookup a host, but then saying a host
* is required has to be illegal.
*/
if (flags & ARES_NI_NAMEREQD)
{
callback(arg, ARES_EBADFLAGS, 0, NULL, NULL);
return;
}
if (salen == sizeof(struct sockaddr_in6))
{
ares_inet_ntop(AF_INET6, &addr6->sin6_addr, ipbuf, IPBUFSIZ);
/* If the system supports scope IDs, use it */
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
append_scopeid(addr6, flags, ipbuf, sizeof(ipbuf));
#endif
}
else
{
ares_inet_ntop(AF_INET, &addr->sin_addr, ipbuf, IPBUFSIZ);
}
/* They also want a service */
if (flags & ARES_NI_LOOKUPSERVICE)
service = lookup_service((unsigned short)(port & 0xffff),
flags, srvbuf, sizeof(srvbuf));
callback(arg, ARES_SUCCESS, 0, ipbuf, service);
return;
}
/* This is where a DNS lookup becomes necessary */
else
{
niquery = ares_malloc(sizeof(struct nameinfo_query));
if (!niquery)
{
callback(arg, ARES_ENOMEM, 0, NULL, NULL);
return;
}
niquery->callback = callback;
niquery->arg = arg;
niquery->flags = flags;
niquery->timeouts = 0;
if (sa->sa_family == AF_INET)
{
niquery->family = AF_INET;
memcpy(&niquery->addr.addr4, addr, sizeof(niquery->addr.addr4));
ares_gethostbyaddr(channel, &addr->sin_addr,
sizeof(struct in_addr), AF_INET,
nameinfo_callback, niquery);
}
else
{
niquery->family = AF_INET6;
memcpy(&niquery->addr.addr6, addr6, sizeof(niquery->addr.addr6));
ares_gethostbyaddr(channel, &addr6->sin6_addr,
sizeof(struct ares_in6_addr), AF_INET6,
nameinfo_callback, niquery);
}
}
}
}
static void nameinfo_callback(void *arg, int status, int timeouts,
struct hostent *host)
{
struct nameinfo_query *niquery = (struct nameinfo_query *) arg;
char srvbuf[33];
char *service = NULL;
niquery->timeouts += timeouts;
if (status == ARES_SUCCESS)
{
/* They want a service too */
if (niquery->flags & ARES_NI_LOOKUPSERVICE)
{
if (niquery->family == AF_INET)
service = lookup_service(niquery->addr.addr4.sin_port,
niquery->flags, srvbuf, sizeof(srvbuf));
else
service = lookup_service(niquery->addr.addr6.sin6_port,
niquery->flags, srvbuf, sizeof(srvbuf));
}
/* NOFQDN means we have to strip off the domain name portion. We do
this by determining our own domain name, then searching the string
for this domain name and removing it.
*/
#ifdef HAVE_GETHOSTNAME
if (niquery->flags & ARES_NI_NOFQDN)
{
char buf[255];
char *domain;
gethostname(buf, 255);
if ((domain = strchr(buf, '.')) != NULL)
{
char *end = ares_striendstr(host->h_name, domain);
if (end)
*end = 0;
}
}
#endif
niquery->callback(niquery->arg, ARES_SUCCESS, niquery->timeouts,
(char *)(host->h_name),
service);
ares_free(niquery);
return;
}
/* We couldn't find the host, but it's OK, we can use the IP */
else if (status == ARES_ENOTFOUND && !(niquery->flags & ARES_NI_NAMEREQD))
{
char ipbuf[IPBUFSIZ];
if (niquery->family == AF_INET)
ares_inet_ntop(AF_INET, &niquery->addr.addr4.sin_addr, ipbuf,
IPBUFSIZ);
else
{
ares_inet_ntop(AF_INET6, &niquery->addr.addr6.sin6_addr, ipbuf,
IPBUFSIZ);
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
append_scopeid(&niquery->addr.addr6, niquery->flags, ipbuf,
sizeof(ipbuf));
#endif
}
/* They want a service too */
if (niquery->flags & ARES_NI_LOOKUPSERVICE)
{
if (niquery->family == AF_INET)
service = lookup_service(niquery->addr.addr4.sin_port,
niquery->flags, srvbuf, sizeof(srvbuf));
else
service = lookup_service(niquery->addr.addr6.sin6_port,
niquery->flags, srvbuf, sizeof(srvbuf));
}
niquery->callback(niquery->arg, ARES_SUCCESS, niquery->timeouts, ipbuf,
service);
ares_free(niquery);
return;
}
niquery->callback(niquery->arg, status, niquery->timeouts, NULL, NULL);
ares_free(niquery);
}
static char *lookup_service(unsigned short port, int flags,
char *buf, size_t buflen)
{
const char *proto;
struct servent *sep;
#ifdef HAVE_GETSERVBYPORT_R
struct servent se;
#endif
char tmpbuf[4096];
char *name;
size_t name_len;
if (port)
{
if (flags & ARES_NI_NUMERICSERV)
sep = NULL;
else
{
if (flags & ARES_NI_UDP)
proto = "udp";
else if (flags & ARES_NI_SCTP)
proto = "sctp";
else if (flags & ARES_NI_DCCP)
proto = "dccp";
else
proto = "tcp";
#ifdef HAVE_GETSERVBYPORT_R
memset(&se, 0, sizeof(se));
sep = &se;
memset(tmpbuf, 0, sizeof(tmpbuf));
#if GETSERVBYPORT_R_ARGS == 6
if (getservbyport_r(port, proto, &se, (void *)tmpbuf,
sizeof(tmpbuf), &sep) != 0)
sep = NULL; /* LCOV_EXCL_LINE: buffer large so this never fails */
#elif GETSERVBYPORT_R_ARGS == 5
sep = getservbyport_r(port, proto, &se, (void *)tmpbuf,
sizeof(tmpbuf));
#elif GETSERVBYPORT_R_ARGS == 4
if (getservbyport_r(port, proto, &se, (void *)tmpbuf) != 0)
sep = NULL;
#else
/* Lets just hope the OS uses TLS! */
sep = getservbyport(port, proto);
#endif
#else
/* Lets just hope the OS uses TLS! */
#if (defined(NETWARE) && !defined(__NOVELL_LIBC__))
sep = getservbyport(port, (char*)proto);
#else
sep = getservbyport(port, proto);
#endif
#endif
}
if (sep && sep->s_name)
{
/* get service name */
name = sep->s_name;
}
else
{
/* get port as a string */
sprintf(tmpbuf, "%u", (unsigned int)ntohs(port));
name = tmpbuf;
}
name_len = strlen(name);
if (name_len < buflen)
/* return it if buffer big enough */
memcpy(buf, name, name_len + 1);
else
/* avoid reusing previous one */
buf[0] = '\0'; /* LCOV_EXCL_LINE: no real service names are too big */
return buf;
}
buf[0] = '\0';
return NULL;
}
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
static void append_scopeid(struct sockaddr_in6 *addr6, unsigned int flags,
char *buf, size_t buflen)
{
#ifdef HAVE_IF_INDEXTONAME
int is_ll, is_mcll;
#endif
char tmpbuf[IF_NAMESIZE + 2];
size_t bufl;
int is_scope_long = sizeof(addr6->sin6_scope_id) > sizeof(unsigned int);
tmpbuf[0] = '%';
#ifdef HAVE_IF_INDEXTONAME
is_ll = IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr);
is_mcll = IN6_IS_ADDR_MC_LINKLOCAL(&addr6->sin6_addr);
if ((flags & ARES_NI_NUMERICSCOPE) ||
(!is_ll && !is_mcll))
{
if (is_scope_long)
{
sprintf(&tmpbuf[1], "%lu", (unsigned long)addr6->sin6_scope_id);
}
else
{
sprintf(&tmpbuf[1], "%u", (unsigned int)addr6->sin6_scope_id);
}
}
else
{
if (if_indextoname(addr6->sin6_scope_id, &tmpbuf[1]) == NULL)
{
if (is_scope_long)
{
sprintf(&tmpbuf[1], "%lu", (unsigned long)addr6->sin6_scope_id);
}
else
{
sprintf(&tmpbuf[1], "%u", (unsigned int)addr6->sin6_scope_id);
}
}
}
#else
if (is_scope_long)
{
sprintf(&tmpbuf[1], "%lu", (unsigned long)addr6->sin6_scope_id);
}
else
{
sprintf(&tmpbuf[1], "%u", (unsigned int)addr6->sin6_scope_id);
}
(void) flags;
#endif
tmpbuf[IF_NAMESIZE + 1] = '\0';
bufl = strlen(buf);
if(bufl + strlen(tmpbuf) < buflen)
/* only append the scopeid string if it fits in the target buffer */
strcpy(&buf[bufl], tmpbuf);
}
#endif
/* Determines if s1 ends with the string in s2 (case-insensitive) */
STATIC_TESTABLE char *ares_striendstr(const char *s1, const char *s2)
{
const char *c1, *c2, *c1_begin;
int lo1, lo2;
size_t s1_len = strlen(s1), s2_len = strlen(s2);
/* If the substr is longer than the full str, it can't match */
if (s2_len > s1_len)
return NULL;
/* Jump to the end of s1 minus the length of s2 */
c1_begin = s1+s1_len-s2_len;
c1 = (const char *)c1_begin;
c2 = s2;
while (c2 < s2+s2_len)
{
lo1 = TOLOWER(*c1);
lo2 = TOLOWER(*c2);
if (lo1 != lo2)
return NULL;
else
{
c1++;
c2++;
}
}
return (char *)c1_begin;
}

122
deps/c-ares/ares_getopt.c vendored Normal file
View File

@ -0,0 +1,122 @@
/*
* Original file name getopt.c Initial import into the c-ares source tree
* on 2007-04-11. Lifted from version 5.2 of the 'Open Mash' project with
* the modified BSD license, BSD license without the advertising clause.
*
*/
/*
* getopt.c --
*
* Standard UNIX getopt function. Code is from BSD.
*
* Copyright (c) 1987-2001 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* A. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* B. 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.
* C. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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.
*/
/* #if !defined(lint)
* static char sccsid[] = "@(#)getopt.c 8.2 (Berkeley) 4/2/94";
* #endif
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ares_getopt.h"
int opterr = 1, /* if error message should be printed */
optind = 1; /* index into parent argv vector */
int optopt = 0; /* character checked for validity */
static int optreset; /* reset getopt */
char *optarg; /* argument associated with option */
#define BADCH (int)'?'
#define BADARG (int)':'
#define EMSG (char *)""
/*
* ares_getopt --
* Parse argc/argv argument vector.
*/
int
ares_getopt(int nargc, char * const nargv[], const char *ostr)
{
static char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
if (optreset || !*place) { /* update scanning pointer */
optreset = 0;
if (optind >= nargc || *(place = nargv[optind]) != '-') {
place = EMSG;
return (EOF);
}
if (place[1] && *++place == '-') { /* found "--" */
++optind;
place = EMSG;
return (EOF);
}
} /* option letter okay? */
if ((optopt = (int)*place++) == (int)':' ||
(oli = strchr(ostr, optopt)) == NULL) {
/*
* if the user didn't specify '-' as an option,
* assume it means EOF.
*/
if (optopt == (int)'-')
return (EOF);
if (!*place)
++optind;
if (opterr && *ostr != ':')
(void)fprintf(stderr,
"%s: illegal option -- %c\n", __FILE__, optopt);
return (BADCH);
}
if (*++oli != ':') { /* don't need argument */
optarg = NULL;
if (!*place)
++optind;
}
else { /* need an argument */
if (*place) /* no white space */
optarg = place;
else if (nargc <= ++optind) { /* no arg */
place = EMSG;
if (*ostr == ':')
return (BADARG);
if (opterr)
(void)fprintf(stderr,
"%s: option requires an argument -- %c\n",
__FILE__, optopt);
return (BADCH);
}
else /* white space */
optarg = nargv[optind];
place = EMSG;
++optind;
}
return (optopt); /* dump back option letter */
}

53
deps/c-ares/ares_getopt.h vendored Normal file
View File

@ -0,0 +1,53 @@
#ifndef ARES_GETOPT_H
#define ARES_GETOPT_H
/*
* Copyright (c) 1987-2001 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* A. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* B. 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.
* C. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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.
*/
int ares_getopt(int nargc, char * const nargv[], const char *ostr);
#undef optarg
#undef optind
#undef opterr
#undef optopt
#undef optreset
#define optarg ares_optarg
#define optind ares_optind
#define opterr ares_opterr
#define optopt ares_optopt
#define optreset ares_optreset
extern char *optarg;
extern int optind;
extern int opterr;
extern int optopt;
#endif /* ARES_GETOPT_H */

66
deps/c-ares/ares_getsock.c vendored Normal file
View File

@ -0,0 +1,66 @@
/* Copyright (C) 2005 - 2010, Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. M.I.T. makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares.h"
#include "ares_private.h"
int ares_getsock(ares_channel channel,
ares_socket_t *socks,
int numsocks) /* size of the 'socks' array */
{
struct server_state *server;
int i;
int sockindex=0;
int bitmap = 0;
unsigned int setbits = 0xffffffff;
/* Are there any active queries? */
int active_queries = !ares__is_list_empty(&(channel->all_queries));
for (i = 0; i < channel->nservers; i++)
{
server = &channel->servers[i];
/* We only need to register interest in UDP sockets if we have
* outstanding queries.
*/
if (active_queries && server->udp_socket != ARES_SOCKET_BAD)
{
if(sockindex >= numsocks || sockindex >= ARES_GETSOCK_MAXNUM)
break;
socks[sockindex] = server->udp_socket;
bitmap |= ARES_GETSOCK_READABLE(setbits, sockindex);
sockindex++;
}
/* We always register for TCP events, because we want to know
* when the other side closes the connection, so we don't waste
* time trying to use a broken connection.
*/
if (server->tcp_socket != ARES_SOCKET_BAD)
{
if(sockindex >= numsocks || sockindex >= ARES_GETSOCK_MAXNUM)
break;
socks[sockindex] = server->tcp_socket;
bitmap |= ARES_GETSOCK_READABLE(setbits, sockindex);
if (server->qhead && active_queries)
/* then the tcp socket is also writable! */
bitmap |= ARES_GETSOCK_WRITABLE(setbits, sockindex);
sockindex++;
}
}
return bitmap;
}

25
deps/c-ares/ares_inet_net_pton.h vendored Normal file
View File

@ -0,0 +1,25 @@
#ifndef HEADER_CARES_INET_NET_PTON_H
#define HEADER_CARES_INET_NET_PTON_H
/* Copyright (C) 2005-2013 by Daniel Stenberg et al
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#ifdef HAVE_INET_NET_PTON
#define ares_inet_net_pton(w,x,y,z) inet_net_pton(w,x,y,z)
#else
int ares_inet_net_pton(int af, const char *src, void *dst, size_t size);
#endif
#endif /* HEADER_CARES_INET_NET_PTON_H */

2638
deps/c-ares/ares_init.c vendored Normal file

File diff suppressed because it is too large Load Diff

221
deps/c-ares/ares_iphlpapi.h vendored Normal file
View File

@ -0,0 +1,221 @@
#ifndef HEADER_CARES_IPHLPAPI_H
#define HEADER_CARES_IPHLPAPI_H
/* Copyright 1998 by the Massachusetts Institute of Technology.
* Copyright (C) 2004 - 2011 by Daniel Stenberg et al
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#if defined(USE_WINSOCK)
#ifndef INET_ADDRSTRLEN
#define INET_ADDRSTRLEN 22
#endif
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 65
#endif
/* ---------------------------------- */
#if !defined(_WS2DEF_) && \
!defined(__CSADDR_DEFINED__) && \
!defined(__CSADDR_T_DEFINED)
/* ---------------------------------- */
typedef struct _SOCKET_ADDRESS {
LPSOCKADDR lpSockaddr;
INT iSockaddrLength;
} SOCKET_ADDRESS, *PSOCKET_ADDRESS;
typedef struct _CSADDR_INFO {
SOCKET_ADDRESS LocalAddr;
SOCKET_ADDRESS RemoteAddr;
INT iSocketType;
INT iProtocol;
} CSADDR_INFO, *PCSADDR_INFO;
/* --------------------------------- */
#endif /* ! _WS2DEF_ && \ */
/* ! __CSADDR_DEFINED__ && \ */
/* ! __CSADDR_T_DEFINED */
/* --------------------------------- */
/* ------------------------------- */
#if !defined(IP_ADAPTER_DDNS_ENABLED)
/* ------------------------------- */
#define IP_ADAPTER_ADDRESS_DNS_ELIGIBLE 0x0001
#define IP_ADAPTER_ADDRESS_TRANSIENT 0x0002
#define IP_ADAPTER_DDNS_ENABLED 0x0001
#define IP_ADAPTER_REGISTER_ADAPTER_SUFFIX 0x0002
#define IP_ADAPTER_DHCP_ENABLED 0x0004
#define IP_ADAPTER_RECEIVE_ONLY 0x0008
#define IP_ADAPTER_NO_MULTICAST 0x0010
#define IP_ADAPTER_IPV6_OTHER_STATEFUL_CONFIG 0x0020
#define GAA_FLAG_SKIP_UNICAST 0x0001
#define GAA_FLAG_SKIP_ANYCAST 0x0002
#define GAA_FLAG_SKIP_MULTICAST 0x0004
#define GAA_FLAG_SKIP_DNS_SERVER 0x0008
#define GAA_FLAG_INCLUDE_PREFIX 0x0010
#define GAA_FLAG_SKIP_FRIENDLY_NAME 0x0020
typedef enum {
IpPrefixOriginOther = 0,
IpPrefixOriginManual,
IpPrefixOriginWellKnown,
IpPrefixOriginDhcp,
IpPrefixOriginRouterAdvertisement
} IP_PREFIX_ORIGIN;
typedef enum {
IpSuffixOriginOther = 0,
IpSuffixOriginManual,
IpSuffixOriginWellKnown,
IpSuffixOriginDhcp,
IpSuffixOriginLinkLayerAddress,
IpSuffixOriginRandom
} IP_SUFFIX_ORIGIN;
typedef enum {
IpDadStateInvalid = 0,
IpDadStateTentative,
IpDadStateDuplicate,
IpDadStateDeprecated,
IpDadStatePreferred
} IP_DAD_STATE;
typedef enum {
IfOperStatusUp = 1,
IfOperStatusDown,
IfOperStatusTesting,
IfOperStatusUnknown,
IfOperStatusDormant,
IfOperStatusNotPresent,
IfOperStatusLowerLayerDown
} IF_OPER_STATUS;
typedef enum {
ScopeLevelInterface = 0x0001,
ScopeLevelLink = 0x0002,
ScopeLevelSubnet = 0x0003,
ScopeLevelAdmin = 0x0004,
ScopeLevelSite = 0x0005,
ScopeLevelOrganization = 0x0008,
ScopeLevelGlobal = 0x000E
} SCOPE_LEVEL;
typedef struct _IP_ADAPTER_UNICAST_ADDRESS {
union {
ULONGLONG Alignment;
struct {
ULONG Length;
DWORD Flags;
} s;
} u;
struct _IP_ADAPTER_UNICAST_ADDRESS *Next;
SOCKET_ADDRESS Address;
IP_PREFIX_ORIGIN PrefixOrigin;
IP_SUFFIX_ORIGIN SuffixOrigin;
IP_DAD_STATE DadState;
ULONG ValidLifetime;
ULONG PreferredLifetime;
ULONG LeaseLifetime;
} IP_ADAPTER_UNICAST_ADDRESS, *PIP_ADAPTER_UNICAST_ADDRESS;
typedef struct _IP_ADAPTER_ANYCAST_ADDRESS {
union {
ULONGLONG Alignment;
struct {
ULONG Length;
DWORD Flags;
} s;
} u;
struct _IP_ADAPTER_ANYCAST_ADDRESS *Next;
SOCKET_ADDRESS Address;
} IP_ADAPTER_ANYCAST_ADDRESS, *PIP_ADAPTER_ANYCAST_ADDRESS;
typedef struct _IP_ADAPTER_MULTICAST_ADDRESS {
union {
ULONGLONG Alignment;
struct {
ULONG Length;
DWORD Flags;
} s;
} u;
struct _IP_ADAPTER_MULTICAST_ADDRESS *Next;
SOCKET_ADDRESS Address;
} IP_ADAPTER_MULTICAST_ADDRESS, *PIP_ADAPTER_MULTICAST_ADDRESS;
typedef struct _IP_ADAPTER_DNS_SERVER_ADDRESS {
union {
ULONGLONG Alignment;
struct {
ULONG Length;
DWORD Reserved;
} s;
} u;
struct _IP_ADAPTER_DNS_SERVER_ADDRESS *Next;
SOCKET_ADDRESS Address;
} IP_ADAPTER_DNS_SERVER_ADDRESS, *PIP_ADAPTER_DNS_SERVER_ADDRESS;
typedef struct _IP_ADAPTER_PREFIX {
union {
ULONGLONG Alignment;
struct {
ULONG Length;
DWORD Flags;
} s;
} u;
struct _IP_ADAPTER_PREFIX *Next;
SOCKET_ADDRESS Address;
ULONG PrefixLength;
} IP_ADAPTER_PREFIX, *PIP_ADAPTER_PREFIX;
typedef struct _IP_ADAPTER_ADDRESSES {
union {
ULONGLONG Alignment;
struct {
ULONG Length;
DWORD IfIndex;
} s;
} u;
struct _IP_ADAPTER_ADDRESSES *Next;
PCHAR AdapterName;
PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress;
PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress;
PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress;
PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress;
PWCHAR DnsSuffix;
PWCHAR Description;
PWCHAR FriendlyName;
BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH];
DWORD PhysicalAddressLength;
DWORD Flags;
DWORD Mtu;
DWORD IfType;
IF_OPER_STATUS OperStatus;
DWORD Ipv6IfIndex;
DWORD ZoneIndices[16];
PIP_ADAPTER_PREFIX FirstPrefix;
} IP_ADAPTER_ADDRESSES, *PIP_ADAPTER_ADDRESSES;
/* -------------------------------- */
#endif /* ! IP_ADAPTER_DDNS_ENABLED */
/* -------------------------------- */
#endif /* USE_WINSOCK */
#endif /* HEADER_CARES_IPHLPAPI_H */

78
deps/c-ares/ares_ipv6.h vendored Normal file
View File

@ -0,0 +1,78 @@
/* Copyright (C) 2005 by Dominick Meglio
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#ifndef ARES_IPV6_H
#define ARES_IPV6_H
#ifndef HAVE_PF_INET6
#define PF_INET6 AF_INET6
#endif
#ifndef HAVE_STRUCT_SOCKADDR_IN6
struct sockaddr_in6
{
unsigned short sin6_family;
unsigned short sin6_port;
unsigned long sin6_flowinfo;
struct ares_in6_addr sin6_addr;
unsigned int sin6_scope_id;
};
#endif
#ifndef HAVE_STRUCT_ADDRINFO
struct addrinfo
{
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
ares_socklen_t ai_addrlen; /* Follow rfc3493 struct addrinfo */
char *ai_canonname;
struct sockaddr *ai_addr;
struct addrinfo *ai_next;
};
#endif
#ifndef NS_IN6ADDRSZ
#ifndef HAVE_STRUCT_IN6_ADDR
/* We cannot have it set to zero, so we pick a fixed value here */
#define NS_IN6ADDRSZ 16
#else
#define NS_IN6ADDRSZ sizeof(struct in6_addr)
#endif
#endif
#ifndef NS_INADDRSZ
#define NS_INADDRSZ sizeof(struct in_addr)
#endif
#ifndef NS_INT16SZ
#define NS_INT16SZ 2
#endif
#ifndef IF_NAMESIZE
#ifdef IFNAMSIZ
#define IF_NAMESIZE IFNAMSIZ
#else
#define IF_NAMESIZE 256
#endif
#endif
/* Defined in inet_net_pton.c for no particular reason. */
extern const struct ares_in6_addr ares_in6addr_any; /* :: */
#endif /* ARES_IPV6_H */

185
deps/c-ares/ares_library_init.c vendored Normal file
View File

@ -0,0 +1,185 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
* Copyright (C) 2004-2009 by Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares.h"
#include "ares_library_init.h"
#include "ares_private.h"
/* library-private global and unique instance vars */
#ifdef USE_WINSOCK
fpGetNetworkParams_t ares_fpGetNetworkParams = ZERO_NULL;
fpSystemFunction036_t ares_fpSystemFunction036 = ZERO_NULL;
fpGetAdaptersAddresses_t ares_fpGetAdaptersAddresses = ZERO_NULL;
fpGetBestRoute2_t ares_fpGetBestRoute2 = ZERO_NULL;
#endif
#if defined(ANDROID) || defined(__ANDROID__)
#include "ares_android.h"
#endif
/* library-private global vars with source visibility restricted to this file */
static unsigned int ares_initialized;
static int ares_init_flags;
/* library-private global vars with visibility across the whole library */
void *(*ares_malloc)(size_t size) = malloc;
void *(*ares_realloc)(void *ptr, size_t size) = realloc;
void (*ares_free)(void *ptr) = free;
#ifdef USE_WINSOCK
static HMODULE hnd_iphlpapi;
static HMODULE hnd_advapi32;
#endif
static int ares_win32_init(void)
{
#ifdef USE_WINSOCK
hnd_iphlpapi = 0;
hnd_iphlpapi = LoadLibraryW(L"iphlpapi.dll");
if (!hnd_iphlpapi)
return ARES_ELOADIPHLPAPI;
ares_fpGetNetworkParams = (fpGetNetworkParams_t)
GetProcAddress(hnd_iphlpapi, "GetNetworkParams");
if (!ares_fpGetNetworkParams)
{
FreeLibrary(hnd_iphlpapi);
return ARES_EADDRGETNETWORKPARAMS;
}
ares_fpGetAdaptersAddresses = (fpGetAdaptersAddresses_t)
GetProcAddress(hnd_iphlpapi, "GetAdaptersAddresses");
if (!ares_fpGetAdaptersAddresses)
{
/* This can happen on clients before WinXP, I don't
think it should be an error, unless we don't want to
support Windows 2000 anymore */
}
ares_fpGetBestRoute2 = (fpGetBestRoute2_t)
GetProcAddress(hnd_iphlpapi, "GetBestRoute2");
if (!ares_fpGetBestRoute2)
{
/* This can happen on clients before Vista, I don't
think it should be an error, unless we don't want to
support Windows XP anymore */
}
/*
* When advapi32.dll is unavailable or advapi32.dll has no SystemFunction036,
* also known as RtlGenRandom, which is the case for Windows versions prior
* to WinXP then c-ares uses portable rand() function. Then don't error here.
*/
hnd_advapi32 = 0;
hnd_advapi32 = LoadLibraryW(L"advapi32.dll");
if (hnd_advapi32)
{
ares_fpSystemFunction036 = (fpSystemFunction036_t)
GetProcAddress(hnd_advapi32, "SystemFunction036");
}
#endif
return ARES_SUCCESS;
}
static void ares_win32_cleanup(void)
{
#ifdef USE_WINSOCK
if (hnd_advapi32)
FreeLibrary(hnd_advapi32);
if (hnd_iphlpapi)
FreeLibrary(hnd_iphlpapi);
#endif
}
int ares_library_init(int flags)
{
int res;
if (ares_initialized)
{
ares_initialized++;
return ARES_SUCCESS;
}
ares_initialized++;
if (flags & ARES_LIB_INIT_WIN32)
{
res = ares_win32_init();
if (res != ARES_SUCCESS)
return res; /* LCOV_EXCL_LINE: can't test Win32 init failure */
}
ares_init_flags = flags;
return ARES_SUCCESS;
}
int ares_library_init_mem(int flags,
void *(*amalloc)(size_t size),
void (*afree)(void *ptr),
void *(*arealloc)(void *ptr, size_t size))
{
if (amalloc)
ares_malloc = amalloc;
if (arealloc)
ares_realloc = arealloc;
if (afree)
ares_free = afree;
return ares_library_init(flags);
}
void ares_library_cleanup(void)
{
if (!ares_initialized)
return;
ares_initialized--;
if (ares_initialized)
return;
if (ares_init_flags & ARES_LIB_INIT_WIN32)
ares_win32_cleanup();
#if defined(ANDROID) || defined(__ANDROID__)
ares_library_cleanup_android();
#endif
ares_init_flags = ARES_LIB_INIT_NONE;
ares_malloc = malloc;
ares_realloc = realloc;
ares_free = free;
}
int ares_library_initialized(void)
{
#ifdef USE_WINSOCK
if (!ares_initialized)
return ARES_ENOTINITIALIZED;
#endif
return ARES_SUCCESS;
}

43
deps/c-ares/ares_library_init.h vendored Normal file
View File

@ -0,0 +1,43 @@
#ifndef HEADER_CARES_LIBRARY_INIT_H
#define HEADER_CARES_LIBRARY_INIT_H
/* Copyright 1998 by the Massachusetts Institute of Technology.
* Copyright (C) 2004-2011 by Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef USE_WINSOCK
#include <iphlpapi.h>
#include <ares_iphlpapi.h>
typedef DWORD (WINAPI *fpGetNetworkParams_t) (FIXED_INFO*, DWORD*);
typedef BOOLEAN (APIENTRY *fpSystemFunction036_t) (void*, ULONG);
typedef ULONG (WINAPI *fpGetAdaptersAddresses_t) ( ULONG, ULONG, void*, IP_ADAPTER_ADDRESSES*, ULONG* );
typedef NETIO_STATUS (WINAPI *fpGetBestRoute2_t) ( NET_LUID *, NET_IFINDEX, const SOCKADDR_INET *, const SOCKADDR_INET *, ULONG, PMIB_IPFORWARD_ROW2, SOCKADDR_INET * );
/* Forward-declaration of variables defined in ares_library_init.c */
/* that are global and unique instances for whole c-ares library. */
extern fpGetNetworkParams_t ares_fpGetNetworkParams;
extern fpSystemFunction036_t ares_fpSystemFunction036;
extern fpGetAdaptersAddresses_t ares_fpGetAdaptersAddresses;
extern fpGetBestRoute2_t ares_fpGetBestRoute2;
#endif /* USE_WINSOCK */
#endif /* HEADER_CARES_LIBRARY_INIT_H */

63
deps/c-ares/ares_llist.c vendored Normal file
View File

@ -0,0 +1,63 @@
/* Copyright 1998 by the Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#include "ares.h"
#include "ares_private.h"
/* Routines for managing doubly-linked circular linked lists with a
* dummy head.
*/
/* Initialize a new head node */
void ares__init_list_head(struct list_node* head) {
head->prev = head;
head->next = head;
head->data = NULL;
}
/* Initialize a list node */
void ares__init_list_node(struct list_node* node, void* d) {
node->prev = NULL;
node->next = NULL;
node->data = d;
}
/* Returns true iff the given list is empty */
int ares__is_list_empty(struct list_node* head) {
return ((head->next == head) && (head->prev == head));
}
/* Inserts new_node before old_node */
void ares__insert_in_list(struct list_node* new_node,
struct list_node* old_node) {
new_node->next = old_node;
new_node->prev = old_node->prev;
old_node->prev->next = new_node;
old_node->prev = new_node;
}
/* Removes the node from the list it's in, if any */
void ares__remove_from_list(struct list_node* node) {
if (node->next != NULL) {
node->prev->next = node->next;
node->next->prev = node->prev;
node->prev = NULL;
node->next = NULL;
}
}

Some files were not shown because too many files have changed in this diff Show More