Commit Graph

75 Commits (8b321612da4e129b8eee4e02af755184d2405fe9)

Author SHA1 Message Date
Jason Rhinelander 1f9779cdcd
Windows compilation fix 2 years ago
Jason Rhinelander 93c01623b0
Format fixes & fix warning in format script
- Don't escape '#' in the greps in format.sh: they warn about a spurious
  `\` in the latest grep.
- reformat
2 years ago
Jason Rhinelander ec91a6db05
ReconfigureDNS fixes, fixes macos exit mode
- ReconfigureDNS wasn't returning the old servers; made it void instead
  (the Apple code can just store a copy of the original upstream
  servers instead).
- Reconfiguring DNS reset the unbound context but didn't replace it, so
  a Down()/Up() would crash.
- Simplify Resolver() destructor to just call Down(), and make it final
  just so that no one tries to inherit from us (so that calling a
  virtual function from the destructor is safe).
- Rename CancelPendingQueries() to Down(); the former cancelled but also
  shut down the object, so the name seemed a bit misleading.
- Rename SetInternalState in Resolver_Base to ResetResolver, so that we
  aren't conflicting with ResetInternalState from Endpoint (which was a
  problem because TunEndpoint inherited from both; it could be resolved
  through the different argument type if we removed the default, but
  that seems gross).
- Make Resolver use a bare unbound context pointer rather than a
  shared_ptr; since Resolver (now) entirely manages it already we don't
  need an extra management layer, and it saves a bunch of `.get()`s.
2 years ago
Jason Rhinelander 2ccc518849
Fix apple dns, part 817 2 years ago
Jeff Becker 13d1301e08
rewire up dns reconfiguration for macos 2 years ago
Jason Rhinelander 52c6cd497f
Apple DNS fix WIP 2 years ago
Jason Rhinelander 2aae56b0e0
Apple DNS configuration fix: don't obliterate trampoline
On Apple, the network extension is outside the tunnel routing, so we
cannot have libunbound talk directly to upstream (it would leak DNS when
exit mode is enabled).  Instead unbound *always* talks to a localhost
port where we have a "dns trampoline" that takes UDP packets and shoves
them through the tunnel.

We were doing that already, but recent changes here were overwriting the
libunbound settings with.

This also moves the upstream DNS configuration part of `Up()` into its
own method.
2 years ago
Jason Rhinelander 517911b499
Fix crash on shutdown
For some (wrong) reason this chunk of code was here.  Removed it to stop
a crash on shutdown.
2 years ago
Jason Rhinelander 15144f193c
cleanups/simplifications 2 years ago
Jason Rhinelander 9ddf7413af
Windows DNS fixes
- windivert was being set up *before* DNS is set up, so the DNS port was
  nullopt and thus we couldn't properly identify upstream DNS traffic.
- close() doesn't close a socket on Windows, so the socket-bind-close
  approach to get a free UDP port wasn't actually closing, and thus
  unbound upstream constrained to the given port were completely
  failing.
- The unbound thread was accessing the same shared_ptr instance as the
  outer code, which isn't thread-safe; changed it to copy a weak_ptr
  into the lambda instead.
- Exclude upstream DNS traffic in the filter rather than capturing and
  reinjecting it.
2 years ago
Jason Rhinelander c470349fb3
Log upstream DNS servers when setting it up 2 years ago
Jason Rhinelander ab2177bee9
Restore Apple hax 2 years ago
Jason Rhinelander de4bce1d96
Disable upstream TCP DNS
windivert, in particular, will get filtered by this and it almost
certainly won't work.
2 years ago
Jason Rhinelander 07231dd9e1
Fixed crash in DNS resolving
The inner lambda here wasn't keeping the `Query` (`this`) alive, so
`src` wasn't valid anymore.  This changes it to copy the `src`
shared_ptr into the lambda instead of capturing `this`, and fixes it.
2 years ago
Jason Rhinelander d4739d5d47
Fix sockaddr_len initial value 2 years ago
Jason Rhinelander 05ed9d6de0
llarp/dns logging refactor
Convert everything in llarp/dns to new-style logging.
2 years ago
Jason Rhinelander 49223a7853
bind/close to find free UDP port
The current code isn't working and gives a 0 (which then fails unbound
initialization).  This replaces it by doing a socket+bind to find a free
port then immediately closes (but passes the port we got into unbound).
2 years ago
Jeff 871c3e3281
changeset for windows port
* wintun vpn platform for windows
* bundle config snippets into nsis installer for exit node, keyfile persisting, reduced hops mode.
* use wintun for vpn platform
* isolate all windows platform specific code into their own compilation units and libraries
* split up internal libraries into more specific components
* rename liblokinet.a target to liblokinet-amalgum.a to elimiate ambiguity with liblokinet.so
* DNS platform for win32
* rename llarp/ev/ev_libuv.{c,h}pp to llarp/ev/libuv.{c,h}pp as the old name was idiotic
* split up net platform into win32 and posix specific compilation units
* rename lokinet_init.c to easter_eggs.cpp as that is what they are for and it does not need to be a c compilation target
* add cmake option STRIP_SYMBOLS for seperating out debug symbols for windows builds
* intercept dns traffic on all interfaces on windows using windivert and feed it into lokinet
2 years ago
Jeff baddad9564
remove compat wrapper 2 years ago
Jeff 74362149eb
refactor dns subsystem
we want to be able to have multiple locally bound dns sockets in lokinet so
i restructured most of the dns subsystem in order to make this easier.

specifically, we have a new structure to dns subsystem:

* dns::QueryJob_Base

base type for holding a dns query and response with virtual methods
in charge of sending a reply to whoever requested.

* dns::PacketSource_Base

base type for reading and writing dns messages to and from wherever they came from

* dns::Resolver_Base

base type for filtering and handling of dns messages asynchronously.

* dns::Server

contextualized per endpoint dns object, responsible for all dns related isms.

this change hides all impelementation details of all of the dns components.
adds some more helper functions for parsing dns and dealing with OwnedBuffer.

overall dns becomes less of a pain with this new structure. probably.
2 years ago
Jeff Becker b52cf97e11
override ShouldHandlePacket on android to bypass non .snode/.loki dns hooking. 3 years ago
Jeff Becker 0d64de17c8
tmp commit for debugging (revert me) 3 years ago
Jeff Becker 82314a3cac
add comment about android dns 3 years ago
Jeff Becker 10cd331863
invert logic for android dns hook 3 years ago
Jason Rhinelander a7decd5ec3
Silence warnings 3 years ago
Jason Rhinelander e11efe9bc5
Reformat 3 years ago
Jason Rhinelander 9dd604820f
Unleak exit mode DNS via unbound DNS trampoline on (macOS)
When we enable/disable exit mode on this restarts the unbound DNS
responder with the DNS trampoline (or restores upstream, when disabling)
to properly route DNS requests through the tunnel (because libunbound's
direct requests don't get tunneled because unbound is inside the network
extension).
3 years ago
Jason Rhinelander 14c93e2b93 Unbound callbacks also need arguments reversed
PR #1725 reversed argument orders but UnboundResolver was still using
(from,to) ordering in its callbacks, which leaked through to make a
wrong order in our reply function (which simply forwards arguments).

This fixes that bug by making UnboundResolver callback argument order
consistent (i.e. using to, from) with the PacketHandler argument order.
3 years ago
Jason Rhinelander 3ce329d2bf Reapply "fix dns on android" + fix argument order
The reason the dns fix on android didn't work is that the DnsInterceptor
had a reversed to/from argument order for its
`SendServerMessageBufferTo` overload, and so android/mac needed the
to/from to be reversed so that the second reverse cancelled out the
first one.

Upon review, the DnsInterceptor order (to, from) is more intuitive than
the base order (from, to), so this reapplies the dns fix and swaps
everything *except* DnsInterceptor to match the (to, from) argument
order.
3 years ago
Jeff Becker a6fbaa7c7a
add dns hosts file option for user side dns filtering 3 years ago
Jeff Becker a24b82119b
fix #1655
* make it so that we don't set up unbound resolver when we have no resolvers provided by config
* clean up dns codepath and make it use llarp::SockAddr instead of llarp::IpAddress
3 years ago
Thomas Winget 7caa87862e standardize include format and pragma once
All #ifndef guards on headers have been removed, I think,
in favor of #pragma once

Headers are now included as `#include "filename"` if the included file
resides in the same directory as the file including it, or any
subdirectory therein.  Otherwise they are included as
`#include <project/top/dir/relative/path/filename>`

The above does not include system/os headers.
3 years ago
Jason Rhinelander 36edabd9b0 Rename EventLoop::udp to EventLoop::make_udp
Makes it consistent with the make_waker, etc.

Also removes some debugging.
3 years ago
Jason Rhinelander ccc7b5c9e9 Merge Logic functions into EventLoop
loop->call(...) is similar to the old logic->Call(...), but is smart
about the current thread: if called from within the event loop it simply
runs the argument directly, otherwise it queues it.

Similarly most of the other event loop calls are also now thread-aware:
for example, `call_later(...)` can queue the job directly when called if
in the event loop rather than having to double-queue through the even
loop (once to call, then inside the call to initiate the time).
3 years ago
Jason Rhinelander 5b555ee5aa Replace libuv with uvw & related refactoring
- removes all the llarp_ev_* functions, replacing with methods/classes/functions in the llarp
  namespace.
- banish ev/ev.h to the void
- Passes various things by const lvalue ref, especially shared_ptr's that don't need to be copied
  (to avoid an atomic refcount increment/decrement).
- Add a llarp::UDPHandle abstract class for UDP handling
- Removes the UDP tick handler; code that needs tick can just do a separate handler on the event
  loop outside the UDP socket.
- Adds an "OwnedBuffer" which owns its own memory but is implicitly convertible to a llarp_buffer_t.
  This is mostly needed to take over ownership of buffers from uvw without copying them as,
  currently, uvw does its own allocation (pending some open upstream issues/PRs).
- Logic:
  - add `make_caller`/`call_forever`/`call_every` utility functions to abstract Call wrapping and
    dependent timed tasks.
  - Add inLogicThread() so that code can tell its inside the logic thread (typically for
    debugging assertions).
  - get rid of janky integer returns and dealing with cancellations on call_later: the other methods
    added here and the event loop code remove the need for them.
- Event loop:
  - redo everything with uvw instead of libuv
  - rename EventLoopWakeup::Wakeup to EventLoopWakeup::Trigger to better reflect what it does.
  - add EventLoopRepeater for repeated events, and replace the code that reschedules itself every
    time it is called with a repeater.
  - Split up `EventLoop::run()` into a non-virtual base method and abstract `run_loop()` methods;
    the base method does a couple extra setup/teardown things that don't need to be in the derived class.
  - udp_listen is replaced with ev->udp(...) which returns a new UDPHandle object rather that
    needing gross C-style-but-not-actually-C-compatible structs.
  - Remove unused register_poll_fd_(un)readable
  - Use shared_ptr for EventLoopWakeup rather than returning a raw pointer; uvw lets us not have to
    worry about having the event loop class maintain ownership of it.
  - Add factory EventLoop::create() function to create a default (uvw-based) event loop (previously
    this was one of the llarp_ev_blahblah unnamespaced functions).
  - ev_libuv: this is mostly rewritten; all of the glue code/structs, in particular, are gone as
    they are no longer needed with uvw.
- DNS:
  - Rename DnsHandler to DnsInterceptor to better describe what it does (this is the code that
    intercepts all DNS to the tun IP range for Android).
- endpoint:
  - remove unused "isolated network" code
  - remove distinct (but actually always the same) variables for router/endpoint logic objects
- llarp_buffer_t
  - make constructors type-safe against being called with points to non-size-1 values
- tun packet reading:
  - read all available packets off the device/file descriptor; previously we were reading one packet
    at a time then returning to the event loop to poll again.
  - ReadNextPacket() now returns a 0-size packet if the read would block (so that we can implement
    the previous point).
  - ReadNextPacket() now throws on I/O error
- Miscellaneous code cleanups/simplifications
3 years ago
Thomas Winget 4c630e0437 Large collection of changes to make android work
- Previous android java and jni code updated to work, but with much love
  still needed to make it work nicely, e.g. handling when the VPN is
  turned off.

- DNS handling refactored to allow android to intercept and handle DNS
  requests as we can't set the system DNS to use a high port
  (and apparently Chrome ignores system DNS settings anyway)

- add packet router structure to allow separate handling of specific
  intercepted traffic, e.g. UDP traffic to port 53 gets handled by our
  DNS handler rather than being naively forwarded as exit traffic.

- For now, android lokinet is exit-only and hard-coded to use exit.loki
  as its exit.  The exit will be configurable before release, but
  allowing to not use exit-only mode is more of a challenge.

- some old gitignore remnants which were matching to things we don't
  want them to (and are no longer relevant) removed

- some minor changes to CI configuration
3 years ago
Jeff Becker ffef3bc48f
wire up sigusr1 to reset libunbound dns resolver 3 years ago
Jeff 49b9ad7197
tun code refactor (#1495)
* partial tun code refactor

* take out the trash

* move vpn platform code into llarp/vpn/platform.cpp

* fix hive build

* fix win32

* fix memory leak on win32

* reduce cpu use

* make macos compile

* win32 patches:

* use wepoll for zmq
* use all cores on windows iocp read loop

* fix zmq patch for windows

* clean up cmake for win32

* add uninstall before reinstall option to win32 installer

* more ipv6 stuff

* make it compile

* fix up route poker

* remove an unneeded code block in macos wtf

* always use call to system

* fix route poker behavior on macos

* disable ipv6 on windows for now

* cpu perf improvement:

* colease calls to Router::PumpLL to 1 per event loop wakeup

* set up THEN add addresses

* emulate proactor event loop on win32

* remove excessively verbose error message

* fix issue #1499

* exclude uv_poll from win32 so that it can start up

* update logtag to include directory

* create minidump on windows if there was a crash

* make windows happy

* use dmp suffix on minidump files

* typo fix

* address feedback from jason
* use PROJECT_SOURCE_DIR instead of CMAKE_SOURCE_DIR
* quote $@ in apply-patches in case path has spaces in it

* address feedback from tom

* remove llarp/ev/pipe
* add comments for clairification
* make event loop queue size constant named
3 years ago
Jeff c81b6049f1
fix crashes on shutdown (#1433) 4 years ago
Jeff dcb48db5fe
enable profiling on clients by default (#1421)
* enable client relay profiling by default

* macos dns fixes

* improve peer profiling algorithm to track timeouts vs failures

* remove debug ioctl call in tuntap code

* use ub_wait instead of ub_process as that was what was there before

* const correctness

* DRY out checking for SIIT

* typofix

* correct name
4 years ago
Thomas Winget a91bb35dbf
Some Windows fixes (#1415)
* Should fix some windows service issues

* fix return condition inversion

* Add some Trace level logging

also make the logger actually respect the log level you set.

* event loop should not queue things to itself...

at present, logic thread queue continues until it is empty, so
queueing things onto itself is just wasteful.

* call_later(foreach thing) is better than foreach thing (call later)

also if you already queued those things but they have not happened yet,
there is no sense to queue them to happen again.

* do not queue read on write finish, only on read finish

* failure to start DNS server should be proper startup failure.

without the DNS server working lokinet is...kinda pointless, right?

* format

* don't queue stuff to logic thread if in logic thread
the thing that clears the queue...clears it.  So you're just delaying and adding overhead.

* windows unbound thread sleep instead of just busy-waiting

also clang-format decided I can't have a blank line for some reason...

* fix unbound async worker on windows
4 years ago
Jeff 3b70b99dd2
fix empty config case (#1400)
* fix empty config case

* * fix case for empty ifname / ifaddr on relay
* bail if no dns server bound

* use AssignmentAcceptor
4 years ago
Jason Rhinelander af6caf776a
Config file improvements (#1397)
* Config file API/comment improvements

API improvements:
=================

Make the config API use position-independent tag parameters (Required,
Default{123}, MultiValue) rather than a sequence of bools with
overloads.  For example, instead of:

    conf.defineOption<int>("a", "b", false, true, 123, [] { ... });

you now write:

    conf.defineOption<int>("a", "b", MultiValue, Default{123}, [] { ... });

The tags are:
- Required
- MultiValue
- Default{value}
plus new abilities (see below):
- Hidden
- RelayOnly
- ClientOnly
- Comment{"line1", "line2", "line3"}

Made option definition more powerful:
=====================================

- `Hidden` allows you to define an option that won't show up in the
  generated config file if it isn't set.

- `RelayOnly`/`ClientOnly` sets up an option that is only accepted and
  only shows up for relay or client configs.  (If neither is specified
  the option shows up in both modes).

- `Comment{...}` lets the option comments be specified as part of the
  defineOption.

Comment improvements
====================

- Rewrote comments for various options to expand on details.
- Inlined all the comments with the option definitions.
- Several options that were missing comments got comments added.
- Made various options for deprecated and or internal options hidden by
  default so that they don't show up in a default config file.
- show the section comment (but not option comments) *after* the
  [section] tag instead of before it as it makes more sense that way
  (particularly for the [bind] section which has a new long comment to
  describe how it works).

Disable profiling by default
============================

We had this weird state where we use and store profiling by default but
never *load* it when starting up.  This commit makes us just not use
profiling at all unless explicitly enabled.

Other misc changes:
===================

- change default worker threads to 0 (= num cpus) instead of 1, and fix
  it to allow 0.
- Actually apply worker-threads option
- fixed default data-dir value erroneously having quotes around it
- reordered ifname/ifaddr/mapaddr (was previously mapaddr/ifaddr/ifname)
  as mapaddr is a sort of specialization of ifaddr and so makes more
  sense to come after it (particularly because it now references ifaddr
  in its help message).
- removed peer-stats option (since we always require it for relays and
  never use it for clients)
- removed router profiles filename option (this doesn't need to be
  configurable)
- removed defunct `service-node-seed` option
- Change default logging output file to "" (which means stdout), and
  also made "-" work for stdout.

* Router hive compilation fixes

* Comments for SNApp SRV settings in ini file

* Add extra blank line after section comments

* Better deprecated option handling

Allow {client,relay}-only options in {relay,client} configs to be
specified as implicitly deprecated options: they warn, and don't set
anything.

Add an explicit `Deprecated` tag and move deprecated option handling
into definition.cpp.

* Move backwards compat options into section definitions

Keep the "addBackwardsCompatibleConfigOptions" only for options in
sections that no longer exist.

* Fix INI parsing issues & C++17-ify

- don't allow inline comments because it seems they aren't allowed in
ini formats in general, and is going to cause problems if there is a
comment character in a value (e.g. an exit auth string).  Additionally
it was breaking on a line such as:

    # some comment; see?

because it was treating only `; see?` as the comment and then producing
an error message about the rest of the line being invalid.

- make section parsing stricter: the `[` and `]` have to be at the
beginning at end of the line now (after stripping whitespace).

- Move whitespace stripping to the top since everything in here does it.

- chop off string_view suffix/prefix rather than maintaining position
values

- fix potential infinite loop/segfault when given a line such as `]foo[`

* Make config parsing failure fatal

Load() LogError's and returns false on failure, so we weren't aborting
on config file errors.

* Formatting: allow `{}` for empty functions/structs

Instead of using two lines when empty:

    {
    }

* Make default dns bind 127.0.0.1 on non-Linux

* Don't show empty section; fix tests

We can conceivably have sections that only make sense for clients or
relays, and so want to completely omit that section if we have no
options for the type of config being generated.

Also fixes missing empty lines between tests.

Co-authored-by: Thomas Winget <tewinget@gmail.com>
4 years ago
Jason Rhinelander 4faaf9082c Fix broken unbound resolver when including upstream port
unbound breaks when given "1.2.3.4:53" as it expects only an IP.
4 years ago
Thomas Winget 8f0330c9f2 std::vector instead of std::array 4 years ago
Thomas Winget b875d40491 restructure how upstream dns replies are handled
llarp::dns::Message does not fully support DNS packets,
so converting the upstream response to one will not work
for all query types.  Also it is kinda silly to begin with,
as the upstream reply is already a network packet, ready to go.
4 years ago
Thomas Winget 221e9ff5de make format 4 years ago
Thomas Winget c2a30692cf Implement upstream DNS using libunbound 4 years ago
Stephen Shelton aee96e53a3
Refactor Addr -> IpAddress/SockAddr 4 years ago
Stephen Shelton 273270916e
The Great Wall of Blame
This commit reflects changes to clang-format rules. Unfortunately,
these rule changes create a massive change to the codebase, which
causes an apparent rewrite of git history.

Git blame's --ignore-rev flag can be used to ignore this commit when
attempting to `git blame` some code.
4 years ago