├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── COPYING
├── HISTORY.rst
├── LICENSE
├── README.rst
├── broker
├── .gitignore
├── contrib
│ ├── tunneldigger.service
│ └── tunneldigger.upstart
├── l2tp_broker.cfg.example
├── scripts
│ ├── bridge_functions.sh
│ ├── broker.connection-rate-limit.sh
│ ├── session.down.sh
│ ├── session.mtu-changed.sh
│ ├── session.up.sh
│ └── tunneldigger-broker
├── setup.py
└── src
│ └── tunneldigger_broker
│ ├── __init__.py
│ ├── broker.py
│ ├── eventloop.py
│ ├── genetlink.py
│ ├── hooks.py
│ ├── l2tp.py
│ ├── limits.py
│ ├── main.py
│ ├── netlink.py
│ ├── network.py
│ ├── protocol.py
│ ├── timerfd.py
│ ├── traffic_control.py
│ └── tunnel.py
├── client
├── .gitignore
├── CMakeLists.txt
├── l2tp_client.c
└── libasyncns
│ ├── asyncns.c
│ └── asyncns.h
├── docs
├── Makefile
├── client.rst
├── conf.py
├── index.rst
├── server.rst
└── wireshark-tunneldigger.lua
└── tests
├── .gitignore
├── README.md
├── Vagrantfile
├── hook_client.sh
├── hook_server
├── bridge_functions.sh
├── mtu_changed.sh
├── setup_interface.sh
└── teardown_interface.sh
├── lib_ci.sh
├── prepare_client.sh
├── prepare_server.sh
├── run_client.sh
├── run_server.sh
├── test_nose.py
├── test_usage.py
├── travis.sh
└── tunneldigger.py
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - 'master'
7 | - 'ci'
8 | pull_request:
9 | branches:
10 | - 'master'
11 |
12 | jobs:
13 | server:
14 | name: Test Server
15 | strategy:
16 | fail-fast: false
17 | matrix:
18 | include:
19 | - SELECT: nose
20 | OLD_REV: "HEAD"
21 | - SELECT: nose
22 | OLD_REV: "origin/legacy"
23 | - SELECT: nose
24 | OLD_REV: "v0.3.0"
25 | # even older servers (before 436a420aad8aff687822ce342360f5306281ea0b) have the broken
26 | # Python conntrack bindings, they do not work any more
27 | - SELECT: usage
28 | runs-on: ubuntu-20.04
29 | steps:
30 | - uses: actions/checkout@v3
31 | - name: Setup
32 | run: |
33 | set -x
34 | git fetch --unshallow # GHA only does a shallow clone
35 | sudo add-apt-repository universe
36 | sudo apt-get -qq update
37 | # This is only what we need to install on the *host*.
38 | # Server and client will be built in containers set up by `setup_template` in `tunneldigger.py`
39 | # as well as the `prepare_{server,client}.sh` scripts.
40 | sudo apt-get --assume-no install lxc python3-lxc python3-nose linux-modules-extra-$(uname -r)
41 | sudo modprobe l2tp_netlink
42 | sudo modprobe l2tp_eth
43 | # Newer versions of the broker don't need the following but keep it around for cross-version testing
44 | sudo modprobe nf_conntrack
45 | sudo modprobe nf_conntrack_netlink
46 | sudo iptables -t nat -L >/dev/null
47 | sudo iptables -t filter -P FORWARD ACCEPT
48 | - name: Run tests
49 | run: |
50 | export SELECT=${{ matrix.SELECT }}
51 | export OLD_REV=${{ matrix.OLD_REV }}
52 | sudo -E ./tests/travis.sh
53 | client:
54 | name: Test Client
55 | runs-on: ubuntu-20.04
56 | steps:
57 | - uses: actions/checkout@v3
58 | - name: Setup
59 | run: |
60 | sudo apt-get --assume-no install cmake libnl-3-dev libnl-genl-3-dev libasyncns-dev
61 | - name: Run tests
62 | run: |
63 | export SELECT=client
64 | sudo -E ./tests/travis.sh
65 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.swp
2 | *.pyc
3 | *.o
4 | l2tp_client
5 | *.sublime-*
6 | *.cfg
7 | /docs/_build
8 | /tests/test-data
9 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/HISTORY.rst:
--------------------------------------------------------------------------------
1 | vNEXT
2 | -----
3 |
4 | v0.4.0, 2023-Aug-19
5 | -----
6 |
7 | Broker changes:
8 |
9 | * The following Linux kernel versions are supported: >= 5.10.152, 5.15.76,
10 | 6.0.6, 6.1+.
11 | * Improve documentation and automated checks.
12 | * Python 3 support.
13 | Python 2 is no longer supported.
14 | **NOTE:** If you are running the broker in a Python virtualenv you will have to
15 | rebuild the virtualenv using a Python 3 interpreter.
16 | This can be achieved by deleting the old virtualenv folder and recreating it.
17 | For recreating the virtualenv you can refer to the "Installation" section of
18 | the broker `installation chapter in the Tunneldigger documentation`_.
19 | * Remove NAT-based handling of many client tunnels on the same server port.
20 | The broker now relies on the kernel properly distinguishing those UDP sockets.
21 | * Remove dependency on Netfilter.
22 | * Fix compatibility with new Linux kernels on the broker side: New kernels
23 | force the l2tpv3 session ID to be unique system-wide, while old tunneldigger
24 | clients have a hard-coded ID of 1 for both ends of the tunnel. When a new
25 | client talks to a new broker, they will instead use a unique ID. Moreover,
26 | when the broker detects that it runs on an affected kernel, it reports maximal
27 | usage to old clients -- so if the client does usage-based selection, it will
28 | pick another broker.
29 | * Improve PMTU discovery to complete more quickly after tunnel creation.
30 | * More session and broker information is available for the hooks.
31 | * Make logging more detailed and more consistent.
32 | * l2tp_broker.cfg confguration file changes:
33 |
34 | * Add option ``connection_rate_limit`` to configure the delay between two
35 | clients connecting. Default is 10 (seconds), which is the limit applied
36 | by previous versions. Valid values include whole seconds (10) or
37 | fractions of a second (0.2). A value of 0 disables this feature. This
38 | is applied per broker port.
39 | * Add options ``connection_rate_limit_per_ip_count`` and
40 | ``connection_rate_limit_per_ip_time`` to configure a connection rate limit
41 | per client IP address. If either value is 0, the functionality is disabled.
42 | The default values are 0. This is applied per broker port.
43 | * Add hook ``broker.connection-rate-limit`` which is called when the connection
44 | rate per IP address limit is exceeded.
45 | * Add option ``pmtu``, defaults to 0 (auto-discovery). If set to a non-zero
46 | value, this disables PMTU discovery and replying to client's PMTU discovery
47 | probes.
48 | * Remove option ``filename``. All log message are sent to STDOUT or STDERR
49 | * Remove option ``port_base``. No longer needed without the NAT-based
50 | approach
51 | * Remove option ``namespace``. No longer needed without the NAT-based
52 | approach
53 | * Remove option ``check_modules``. No longer implemented since v0.2.0
54 |
55 | Client changes:
56 |
57 | * Add cmake build system.
58 | * Improve client behavior on broker failure: when a connection to a broker
59 | fails, the client prefers other brokers for the reconnects.
60 | * Add support for the protocol extensions that ensure unique session IDs on the
61 | broker side.
62 | * Decrease some reconnect timeouts.
63 | * Replace libnl-1 with libnl-3.
64 |
65 | .. _`installation chapter in the Tunneldigger documentation`: https://tunneldigger.readthedocs.io/en/latest/server.html#installation
66 | .. _very recent kernel: https://github.com/wlanslovenija/tunneldigger/issues/126
67 |
68 | v0.3.0, 2017-Apr-02
69 | -------------------
70 |
71 | * Fixed double command bug in traffic control code.
72 | * Added optional broker selection based on usage.
73 | * Fixed off-by-one error in PREPARE package.
74 | * Added tests.
75 | * Added ``fq_codel`` ``tc`` rule to help alleviate buffer bloat.
76 | * Added new CFFI-based conntrack bindings.
77 | * Broker can now be installed as a Python package via ``setup.py``. Due to
78 | this change it is now run as ``python -m tunneldigger_broker.main l2tp_broker.cfg``
79 | after installation.
80 |
81 | v0.2.0, 2015-Dec-24
82 | -------------------
83 |
84 | * Broker rewrite so that it can run on OpenWrt.
85 | The broker now enforces a 10s delay between two clients connecting.
86 | Support for several config options got dropped: max_cookies, tunnel_timeout, pmtu_discovery, check_modules, filename.
87 | Hooks run asynchronously. In particular, the pre-down hook is not guaranteed to complete before the tunnel is shut down.
88 | * Broker is now run as ``python -m broker.main l2tp_broker.cfg`` from the repository directory.
89 |
90 | v0.1.0, 2015-Dec-16
91 | -------------------
92 |
93 | * Version with broker which does not run on OpenWrt.
94 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (C) 2012-2020 wlan slovenija, open wireless network of Slovenia
2 |
3 | This program is free software: you can redistribute it and/or modify it under
4 | the terms of the GNU Affero General Public License as published by the Free
5 | Software Foundation, either version 3 of the License, or (at your option) any
6 | later version.
7 |
8 | This program is distributed in the hope that it will be useful, but WITHOUT ANY
9 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
10 | PARTICULAR PURPOSE. See the GNU Affero General Public License for more
11 | details.
12 |
13 | You should have received a copy of the GNU Affero General Public License along
14 | with this program. If not, see .
15 |
16 | Together with the source code this program may contain also additional content.
17 | Unless specified otherwise, this content is available under Creative Commons
18 | Attribution-ShareAlike license, either version 3.0 of the license, or (at your
19 | option) any later version. You are free to copy, distribute, transmit, adapt
20 | and/or commercially use this content or part(s) of it, provided you publicly,
21 | clearly and visibly attribute wlan slovenija, open wireless network of
22 | Slovenia, and provide a link to its website , if
23 | applicable. If you alter, transform, or build upon this content or part(s) of
24 | it, you may distribute the results only under the same or similar license to
25 | this one.
26 |
27 | For more information about Creative Commons Attribution-ShareAlike license see
28 | .
29 |
30 | This program may contain, use, link to and/or distribute also parts under third
31 | party copyright with possibly different licensing conditions. Make sure you
32 | check and respect also those conditions.
33 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | Tunneldigger
2 | ============
3 |
4 | L2TPv3 VPN tunneling solution
5 |
6 | About
7 | -----
8 |
9 | Tunneldigger is one of the projects of `wlan slovenija`_ open wireless network.
10 | It is a simple VPN tunneling solution based on the Linux kernel support for
11 | L2TPv3 tunnels over UDP.
12 |
13 | .. _wlan slovenija: https://wlan-si.net
14 |
15 | Tunneldigger consists of a client and a server portion.
16 |
17 | The client is written in C for minimal binary size and optimized to run on
18 | embedded devices such as wireless routers running OpenWrt_.
19 |
20 | .. _OpenWrt: https://openwrt.org
21 |
22 | The server portion, referred to as the broker, is written in Python.
23 |
24 | Installation and Use
25 | --------------------
26 |
27 | Information on set up and use of Tunneldigger can be found in the
28 | documentation:
29 |
30 | https://tunneldigger.readthedocs.org/
31 |
32 | Source Code and Issue Tracker
33 | -----------------------------
34 |
35 | Development happens on GitHub_ and issues can be filed in the `Issue tracker`_.
36 |
37 | .. _GitHub: https://github.com/wlanslovenija/tunneldigger
38 | .. _Issue tracker: https://github.com/wlanslovenija/tunneldigger/issues
39 |
40 | License
41 | -------
42 |
43 | Tunneldigger is licensed under AGPLv3_.
44 |
45 | .. _AGPLv3: https://www.gnu.org/licenses/agpl-3.0.en.html
46 |
47 | Contributions
48 | -------------
49 |
50 | We welcome code and documentation contributions to Tunneldigger in the form of
51 | `Pull Requests`_ on GitHub where they can be reviewed and discussed by the
52 | community.
53 | We encourage everyone to check out any pending pull requests and offer comments
54 | or ideas as well.
55 |
56 | .. _Pull Requests: https://github.com/wlanslovenija/tunneldigger/pulls
57 |
58 | Tunneldigger is developed by a community of developers from many different
59 | backgrounds.
60 |
61 | You can visualize all code contributions using `GitHub Insights`_.
62 |
63 | .. _GitHub Insights: https://github.com/wlanslovenija/tunneldigger/graphs/contributors
64 |
--------------------------------------------------------------------------------
/broker/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | *.egg-info
3 | /build/
4 | /dist/
5 |
--------------------------------------------------------------------------------
/broker/contrib/tunneldigger.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=tunneldigger tunnelling network daemon using l2tpv3
3 | After=network.target auditd.service
4 |
5 | [Service]
6 | Type=simple
7 | WorkingDirectory=/home/tunneldigger/tunneldigger
8 | ExecStart=/home/tunneldigger/env/bin/python -m broker.main /home/tunneldigger/tunneldigger/broker/l2tp_broker.cfg
9 | KillMode=process
10 | Restart=on-failure
11 |
12 | [Install]
13 | WantedBy=multi-user.target
14 |
--------------------------------------------------------------------------------
/broker/contrib/tunneldigger.upstart:
--------------------------------------------------------------------------------
1 | description "tunneldigger tunnelling network daemon using l2tpv3"
2 |
3 | start on runlevel [2345]
4 | stop on runlevel [!2345]
5 |
6 | respawn
7 |
8 | chdir /home/tunneldigger/tunneldigger
9 | exec /home/tunneldigger/env/bin/python -m broker.main /home/tunneldigger/tunneldigger/broker/l2tp_broker.cfg
10 |
--------------------------------------------------------------------------------
/broker/l2tp_broker.cfg.example:
--------------------------------------------------------------------------------
1 | [broker]
2 | ; IP address the broker will listen and accept tunnels on
3 | address=127.0.0.1
4 | ; Ports where the broker will listen on
5 | port=53,123,8942
6 | ; Interface with that IP address
7 | interface=lo
8 | ; Maximum number of tunnels that will be allowed by the broker.
9 | ; On a cheap VPS, more than 256 tunnels usually do not make sense.
10 | ; Physical machines can take more.
11 | max_tunnels=256
12 | ; Tunnel id base
13 | tunnel_id_base=100
14 | ; Reject connections if there are less than N seconds since the last connection.
15 | ; Can be less than a second (e.g., 0.1). Note that this is applied *per broker port*.
16 | ; Disabled if set to 0.
17 | connection_rate_limit=0.2
18 | ; Reject connection if an IP address connects more than COUNT times in TIME seconds to
19 | ; the same broker port. Also runs "broker.connection-rate-limit" hook (e.g. to block client via iptables).
20 | ; Disabled when at least one value is 0 (the default).
21 | ;connection_rate_limit_per_ip_count=20
22 | ;connection_rate_limit_per_ip_time=60
23 | ; Set PMTU to a fixed value. Use 0 for automatic PMTU discovery. A non-0 value also disables
24 | ; PMTU discovery on the client side, by having the server not respond to client-side PMTU
25 | ; discovery probes.
26 | pmtu=0
27 |
28 | [log]
29 | ; Verbosity
30 | verbosity=DEBUG
31 | ; Should IP addresses be logged or not
32 | log_ip_addresses=false
33 |
34 | [hooks]
35 | ; Note that hooks are called asynchonously!
36 |
37 | ; Arguments to the session.{up,pre-down,down} hooks are as follows:
38 | ;
39 | ;
40 | ;
41 | ; Arguments to the session.mtu-changed hook are as follows:
42 | ;
43 | ;
44 | ;
45 |
46 | ; Called after the tunnel interface goes up
47 | session.up=
48 | ; Called just before the tunnel interface goes down
49 | ; (However, due to hooks being asynchonous, the hook may actually execute after the interface was
50 | ; already removed.)
51 | session.pre-down=
52 | ; Called after the tunnel interface goes down
53 | session.down=
54 | ; Called after the tunnel MTU gets changed because of PMTU discovery
55 | session.mtu-changed=
56 | ; Called when the tunnel connection rate per ip limit is exceeded
57 | broker.connection-rate-limit=
58 |
--------------------------------------------------------------------------------
/broker/scripts/bridge_functions.sh:
--------------------------------------------------------------------------------
1 | ensure_policy()
2 | {
3 | ip rule del $*
4 | ip rule add $*
5 | }
6 |
7 | ensure_bridge()
8 | {
9 | local brname="$1"
10 | brctl addbr $brname 2>/dev/null
11 |
12 | if [[ "$?" == "0" ]]; then
13 | # Bridge did not exist before, we have to initialize it
14 | ip link set dev $brname up
15 | # TODO The IP address should probably not be hardcoded here?
16 | ip addr add 10.254.0.2/16 dev $brname
17 | # TODO Policy routing should probably not be hardcoded here?
18 | ensure_policy from all iif $brname lookup mesh prio 1000
19 | # Disable forwarding between bridge ports
20 | ebtables -A FORWARD --logical-in $brname -j DROP
21 | fi
22 | }
23 |
24 |
--------------------------------------------------------------------------------
/broker/scripts/broker.connection-rate-limit.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | ENDPOINT_IP="$1"
5 | ENDPOINT_PORT="$2"
6 | UUID="$3"
7 |
8 | # This assumes that an ipset was created with something like
9 | # ```
10 | # ipset create create tunneldigger_blocked hash:ip family inet timeout 300
11 | # ```
12 | # and that a firewall rule like the following uses the ipset to block connections:
13 | # ```
14 | # -A INPUT -m set --match-set tunneldigger_blocked src -j DROP
15 | # ```
16 | ipset add tunneldigger_blocked "$ENDPOINT_IP"
17 |
--------------------------------------------------------------------------------
/broker/scripts/session.down.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | TUNNEL_ID="$1"
3 | INTERFACE="$3"
4 | MTU="$4"
5 | ENDPOINT_IP="$5"
6 | ENDPOINT_PORT="$6"
7 | LOCAL_PORT="$7"
8 | UUID="$8"
9 | LOCAL_BROKER_PORT="$9"
10 |
11 | # Remove the interface from our bridge
12 | brctl delif digger${MTU} $INTERFACE
13 |
14 |
--------------------------------------------------------------------------------
/broker/scripts/session.mtu-changed.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | TUNNEL_ID="$1"
3 | INTERFACE="$3"
4 | OLD_MTU="$4"
5 | NEW_MTU="$5"
6 |
7 | . scripts/bridge_functions.sh
8 |
9 | # Remove interface from old bridge
10 | brctl delif digger${OLD_MTU} $INTERFACE
11 |
12 | # Change interface MTU
13 | ip link set dev $INTERFACE mtu $NEW_MTU
14 |
15 | # Add interface to new bridge
16 | ensure_bridge digger${NEW_MTU}
17 | brctl addif digger${NEW_MTU} $INTERFACE
18 |
19 |
--------------------------------------------------------------------------------
/broker/scripts/session.up.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | TUNNEL_ID="$1"
3 | SESSION_ID="$2"
4 | INTERFACE="$3"
5 | MTU="$4"
6 | ENDPOINT_IP="$5"
7 | ENDPOINT_PORT="$6"
8 | LOCAL_PORT="$7"
9 | UUID="$8"
10 | LOCAL_BROKER_PORT="$9"
11 |
12 | . scripts/bridge_functions.sh
13 |
14 | # Set the interface to UP state
15 | ip link set dev $INTERFACE up mtu $MTU
16 |
17 | # Add the interface to our bridge
18 | ensure_bridge digger${MTU}
19 | brctl addif digger${MTU} $INTERFACE
20 |
21 |
--------------------------------------------------------------------------------
/broker/scripts/tunneldigger-broker:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | ### BEGIN INIT INFO
3 | # Provides: tunneldigger-broker
4 | # Required-Start: $local_fs $remote_fs $network $syslog exim4 mongodb postgresql
5 | # Required-Stop: $local_fs $remote_fs $network $syslog exim4 mongodb postgresql
6 | # Default-Start: 2 3 4 5
7 | # Default-Stop: 0 1 6
8 | # Short-Description: Tunneldigger L2TPv3 brokerage daemon
9 | # Description: Start and stop tunneldigger broker deamon using start-stop-daemon.
10 | ### END INIT INFO
11 |
12 | # Do NOT "set -e"
13 |
14 | PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
15 | DESC="Tunneldigger brokerage daemon"
16 | NAME=tunneldigger-broker
17 | PROJECT_PATH=/srv/tunneldigger/tunneldigger/broker
18 | SCRIPTNAME=/etc/init.d/$NAME
19 | DAEMON=/srv/tunneldigger/env_tunneldigger/bin/python
20 | DAEMON_CHDIR=$PROJECT_PATH
21 | DAEMON_USER=root
22 | DAEMON_GROUP=root
23 | PIDFILE=/var/run/$NAME.pid
24 |
25 | # Variables in START*_OPTS and DAEMON_ARGS will be expanded later with eval
26 | STARTSTOP_OPTS='--quiet --exec $DAEMON --chdir $DAEMON_CHDIR \
27 | --chuid $DAEMON_USER --user $DAEMON_USER --group $DAEMON_GROUP'
28 | START_OPTS='--background --make-pidfile'
29 | DAEMON_ARGS='l2tp_broker.py /srv/tunneldigger/tunneldigger/broker/l2tp_broker_implicator.cfg'
30 |
31 | # Activate virtualenv Python environment
32 | . /srv/tunneldigger/env_tunneldigger/bin/activate
33 |
34 | # Exit if the package is not installed
35 | [ -x "$DAEMON" ] || exit 0
36 |
37 | # Read configuration variable file if it is present
38 | [ -r /etc/default/$NAME ] && . /etc/default/$NAME
39 |
40 | # Load the VERBOSE setting and other rcS variables
41 | . /lib/init/vars.sh
42 |
43 | # Define LSB log_* functions.
44 | # Depend on lsb-base (>= 3.2-14) to ensure that this file is present
45 | # and status_of_proc is working.
46 | . /lib/lsb/init-functions
47 |
48 | # Expand variables
49 | STARTSTOP_OPTS=$(eval echo "$STARTSTOP_OPTS")
50 | START_OPTS=$(eval echo "$START_OPTS")
51 | DAEMON_ARGS=$(eval echo "$DAEMON_ARGS")
52 |
53 | #
54 | # Function that starts the daemon/service
55 | #
56 | do_start()
57 | {
58 | # Return
59 | # 0 if daemon has been started
60 | # 1 if daemon was already running
61 | # 2 if daemon could not be started
62 | start-stop-daemon --start --pidfile "$PIDFILE" $START_OPTS $STARTSTOP_OPTS \
63 | --test > /dev/null || return 1
64 |
65 | case "$START_OPTS" in
66 | *--make-pidfile*)
67 | ;;
68 | *)
69 | # Daemon needs write access to PID file
70 | [ ! -e "$PIDFILE" -o -f "$PIDFILE" -a ! -L "$PIDFILE" ] && \
71 | touch "$PIDFILE" && chmod 600 "$PIDFILE" && \
72 | chown $DAEMON_USER:$DAEMON_GROUP "$PIDFILE" || return 2
73 | ;;
74 | esac
75 | start-stop-daemon --start --pidfile "$PIDFILE" $START_OPTS $STARTSTOP_OPTS \
76 | -- $DAEMON_ARGS || return 2
77 | # Add code here, if necessary, that waits for the process to be ready
78 | # to handle requests from services started subsequently which depend
79 | # on this one. As a last resort, sleep for some time.
80 | }
81 |
82 | #
83 | # Function that stops the daemon/service
84 | #
85 | do_stop()
86 | {
87 | # Return
88 | # 0 if daemon has been stopped
89 | # 1 if daemon was already stopped
90 | # 2 if daemon could not be stopped
91 | # other if a failure occurred
92 | start-stop-daemon --stop --retry=TERM/30/KILL/5 --pidfile "$PIDFILE" \
93 | $STARTSTOP_OPTS
94 | RETVAL="$?"
95 | [ "$RETVAL" = 2 ] && return 2
96 | # Wait for children to finish too if this is a daemon that forks
97 | # and if the daemon is only ever run from this initscript.
98 | # If the above conditions are not satisfied then add some other code
99 | # that waits for the process to drop all resources that could be
100 | # needed by services started subsequently. A last resort is to
101 | # sleep for some time.
102 | [ -n "$DAEMON_USER" ] && PS_SELECT="--user $DAEMON_USER"
103 | [ -n "$DAEMON_GROUP" ] && PS_SELECT="$PS_SELECT --group $DAEMON_GROUP"
104 | if [ -n "$PS_SELECT" ] && ps $PS_SELECT -o pid=,cmd= | grep -q "$DAEMON $DAEMON_ARGS"; then
105 | start-stop-daemon --stop --oknodo --retry=0/30/KILL/5 $STARTSTOP_OPTS
106 | [ "$?" = 2 ] && return 2
107 | fi
108 | # Many daemons don't delete their pidfiles when they exit.
109 | rm -f "$PIDFILE"
110 | return "$RETVAL"
111 | }
112 |
113 | case "$1" in
114 | start)
115 | [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
116 | do_start
117 | case "$?" in
118 | 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
119 | *) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
120 | esac
121 | ;;
122 | stop)
123 | [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
124 | do_stop
125 | case "$?" in
126 | 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
127 | *) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
128 | esac
129 | ;;
130 | status)
131 | status_of_proc -p "$PIDFILE" "$DAEMON" "$NAME" && exit 0 || exit $?
132 | ;;
133 | restart|force-reload)
134 | #
135 | # If the "reload" option is implemented then remove the
136 | # 'force-reload' alias
137 | #
138 | log_daemon_msg "Restarting $DESC" "$NAME"
139 | do_stop
140 | case "$?" in
141 | 0|1)
142 | do_start
143 | case "$?" in
144 | 0) log_end_msg 0 ;;
145 | 1) log_end_msg 1 ;; # Old process is still running
146 | *) log_end_msg 1 ;; # Failed to start
147 | esac
148 | ;;
149 | *)
150 | # Failed to stop
151 | log_end_msg 1
152 | ;;
153 | esac
154 | ;;
155 | *)
156 | echo "Usage: $SCRIPTNAME {start|stop|force-reload|restart|status}" >&2
157 | exit 3
158 | ;;
159 | esac
160 |
161 | :
162 |
--------------------------------------------------------------------------------
/broker/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | from setuptools import find_packages, setup
4 |
5 | VERSION = '0.4.1-dev1'
6 |
7 | setup(
8 | name='tunneldigger-broker',
9 | version=VERSION,
10 | description="Tunneldigger broker.",
11 | long_description="Tunneldigger broker.",
12 | author='wlan slovenija',
13 | author_email='open@wlan-si.net',
14 | url='https://github.com/wlanslovenija/tunneldigger',
15 | license='AGPLv3',
16 | package_dir={'': 'src'},
17 | packages=find_packages(where='src'),
18 | package_data={},
19 | classifiers=[
20 | 'Development Status :: 4 - Beta',
21 | 'Intended Audience :: System Administrators',
22 | 'License :: OSI Approved :: GNU Affero General Public License v3',
23 | 'Programming Language :: Python',
24 | 'Programming Language :: Python :: 3 :: Only',
25 | ],
26 | include_package_data=True,
27 | zip_safe=False,
28 | extras_require={},
29 | )
30 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wlanslovenija/tunneldigger/51a5e46ad143c92d2867835a563146ec4fbc6211/broker/src/tunneldigger_broker/__init__.py
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/broker.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import socket
3 | import time
4 | import traceback
5 | from collections import deque
6 |
7 | from . import l2tp, protocol, network, tunnel as td_tunnel
8 |
9 | # Logger.
10 | logger = logging.getLogger("tunneldigger.broker")
11 |
12 |
13 | class TunnelManager(object):
14 | """
15 | Tunnel manager.
16 | """
17 |
18 | def __init__(
19 | self,
20 | hook_manager,
21 | max_tunnels,
22 | tunnel_id_base,
23 | connection_rate_limit,
24 | connection_rate_limit_per_ip_count,
25 | connection_rate_limit_per_ip_time,
26 | pmtu_fixed,
27 | log_ip_addresses,
28 | ):
29 | """
30 | Constructs a tunnel manager.
31 |
32 | :param hook_manager: Hook manager
33 | :param max_tunnels: Maximum number of tunnels to allow
34 | :param tunnel_id_base: Base local tunnel identifier
35 | """
36 |
37 | self.hook_manager = hook_manager
38 | self.max_tunnels = max_tunnels
39 | self.tunnel_id_base = tunnel_id_base
40 | self.tunnel_ids = set(range(tunnel_id_base, tunnel_id_base + max_tunnels))
41 | self.tunnels = {}
42 | self.last_tunnel_created = None
43 | self.last_tunnel_created_per_ip = {} # Key: IP address Value: deque collection with timestamps
44 | self.connection_rate_limit = connection_rate_limit
45 | self.connection_rate_limit_per_ip_count = connection_rate_limit_per_ip_count
46 | self.connection_rate_limit_per_ip_time = connection_rate_limit_per_ip_time
47 | self.pmtu_fixed = pmtu_fixed
48 | self.require_unique_session_id = False
49 | self.log_ip_addresses = log_ip_addresses
50 |
51 | def report_usage(self, client_features):
52 | """
53 | Returns a number between 0 and 1 << 16 (i.e., a 16-bit number) indicating the load of the
54 | broker.
55 |
56 | :param client_features: Client feature flags
57 | """
58 | max_usage = 0xFFFF
59 |
60 | # If we require a unique session ID: report full usage for clients not supporting unique
61 | # session IDs.
62 | if self.require_unique_session_id and not (client_features & protocol.FEATURE_UNIQUE_SESSION_ID):
63 | return max_usage
64 |
65 | return int((float(len(self.tunnels)) / self.max_tunnels) * max_usage)
66 |
67 | def create_tunnel(self, broker, address, uuid, remote_tunnel_id, client_features):
68 | """
69 | Creates a new tunnel.
70 |
71 | :param broker: Broker that received the tunnel request
72 | :param address: Remote tunnel endpoint address (host, port) tuple
73 | :param uuid: Unique tunnel identifier received from the remote host
74 | :param remote_tunnel_id: Remotely assigned tunnel identifier
75 | :param client_features: Client feature flags
76 | :return: True if a tunnel has been created, False otherwise
77 | """
78 |
79 | now = time.time()
80 |
81 | if self.log_ip_addresses:
82 | tunnel_str = "%s:%s (%s)" % (address[0], address[1], uuid)
83 | else:
84 | tunnel_str = "(%s)" % uuid
85 |
86 | # Rate limit creation of new tunnels to at most one every 10 seconds to prevent the
87 | # broker from being overwhelmed with creating tunnels, especially on embedded devices.
88 | # We do this before the per-IP rate limiting so that these failed attempts do not count towards the latter.
89 | if self.last_tunnel_created is not None and now - self.last_tunnel_created < self.connection_rate_limit:
90 | logger.info("Rejecting tunnel %s due to global rate limiting: last tunnel was created too recently" % tunnel_str)
91 | return False
92 |
93 | # Rate limit creation of new tunnels with the same IP address.
94 | # Runs broker.connection-rate-limit hook if threshold exceeded:
95 | if self.connection_rate_limit_per_ip_count > 0 and self.connection_rate_limit_per_ip_time > 0:
96 | if address[0] not in self.last_tunnel_created_per_ip:
97 | # Create deque with max size if IP address does not exist in dict
98 | self.last_tunnel_created_per_ip[address[0]] = deque([], self.connection_rate_limit_per_ip_count)
99 | tunnelCollection = self.last_tunnel_created_per_ip[address[0]]
100 | if len(tunnelCollection) >= self.connection_rate_limit_per_ip_count:
101 | # We have "count" many connection attempts registered from this IP.
102 | # Check if they are all within "time".
103 | delta = now - tunnelCollection[0] # Delta of oldest timestamp in collection and now
104 | if delta <= self.connection_rate_limit_per_ip_time:
105 | logger.info(
106 | "Rejecting tunnel %s due to per-IP rate limiting: %d attempts in %d seconds",
107 | tunnel_str,
108 | len(tunnelCollection),
109 | int(delta),
110 | )
111 | broker.hook_manager.run_hook(
112 | 'broker.connection-rate-limit',
113 | address[0],
114 | address[1],
115 | uuid,
116 | )
117 | # Keep the data in the queue. The client may connect again once TIME seconds
118 | # passed since the oldest registered connection attempt.
119 | # (This rejected attempt does not count to that.)
120 | return False
121 | # Append current timestamp at the end of deque collection so the oldest (first) will be dropped.
122 | tunnelCollection.append(now)
123 |
124 | try:
125 | tunnel_id = self.tunnel_ids.pop()
126 | except KeyError:
127 | logger.warning("No more tunnel IDs available -- %d active tunnels", self.tunnels)
128 | return False
129 |
130 | logger.info("Creating tunnel %s with id %d.", tunnel_str, tunnel_id)
131 |
132 | try:
133 | tunnel = td_tunnel.Tunnel(
134 | broker=broker,
135 | address=broker.address,
136 | endpoint=address,
137 | uuid=uuid,
138 | tunnel_id=tunnel_id,
139 | remote_tunnel_id=remote_tunnel_id,
140 | pmtu_fixed=self.pmtu_fixed,
141 | client_features=client_features,
142 | )
143 | tunnel.register(broker.event_loop)
144 | tunnel.setup_tunnel()
145 | self.tunnels[tunnel_id] = tunnel
146 | self.last_tunnel_created = now
147 | except KeyboardInterrupt:
148 | raise
149 | except l2tp.L2TPTunnelExists as e:
150 | # Do not return the tunnel identifier into the pool.
151 | logger.warning("Tunnel identifier %d already exists." % e.tunnel_id)
152 | return False
153 | except l2tp.L2TPSessionExists as e:
154 | # Return tunnel identifier into the pool.
155 | self.tunnel_ids.add(tunnel_id)
156 | logger.warning("Session identifier %d already exists." % e.session_id)
157 | # From now on, demand unique session IDs
158 | self.require_unique_session_id = True
159 | return False
160 | except:
161 | # Return tunnel identifier into the pool.
162 | self.tunnel_ids.add(tunnel_id)
163 | logger.error("Unhandled exception while creating tunnel %d:" % tunnel_id)
164 | logger.error(traceback.format_exc())
165 | return False
166 |
167 | return True
168 |
169 | def destroy_tunnel(self, tunnel):
170 | """
171 | Removes the given managed tunnel.
172 |
173 | :param tunnel: Previously created tunnel instance to remove
174 | """
175 |
176 | # Return the tunnel identifier to the broker.
177 | self.tunnel_ids.add(tunnel.tunnel_id)
178 | del self.tunnels[tunnel.tunnel_id]
179 |
180 | def initialize(self):
181 | # Initialize netlink.
182 | self.netlink = l2tp.NetlinkInterface()
183 |
184 | # Initialize tunnels.
185 | for tunnel_id, session_id in self.netlink.session_list():
186 | if tunnel_id in self.tunnel_ids:
187 | logger.warning("Removing existing tunnel %d session %d." % (tunnel_id, session_id))
188 | self.netlink.session_delete(tunnel_id, session_id)
189 |
190 | for tunnel_id in self.netlink.tunnel_list():
191 | if tunnel_id in self.tunnel_ids:
192 | logger.warning("Removing existing tunnel %d." % tunnel_id)
193 | self.netlink.tunnel_delete(tunnel_id)
194 |
195 | def close(self):
196 | """
197 | Shuts down all managed tunnels. The tunnel manager instance
198 | should not be used after calling this method.
199 | """
200 |
201 | for tunnel in list(self.tunnels.values()):
202 | try:
203 | tunnel.close(reason=protocol.ERROR_REASON_SHUTDOWN)
204 | except:
205 | traceback.print_exc()
206 |
207 | del self.netlink
208 |
209 |
210 | class Broker(protocol.HandshakeProtocolMixin, network.Pollable):
211 | """
212 | Tunnel broker.
213 | """
214 |
215 | def __init__(self, address, interface, tunnel_manager):
216 | """
217 | Constructs a new tunnel broker.
218 |
219 | :param address: Address (host, port) tuple to bind to
220 | :param interface: Interface name to bind to
221 | :param tunnel_manager: Tunnel manager instance to use
222 | """
223 |
224 | super(Broker, self).__init__(address, interface, "Broker {}".format(address[1]))
225 |
226 | self.tunnel_manager = tunnel_manager
227 | self.hook_manager = tunnel_manager.hook_manager
228 | self.netlink = tunnel_manager.netlink
229 |
230 | def get_tunnel_manager(self):
231 | """
232 | Returns the tunnel manager for this broker.
233 | """
234 |
235 | return self.tunnel_manager
236 |
237 | def create_tunnel(self, address, uuid, remote_tunnel_id, client_features):
238 | """
239 | Called when a new tunnel should be created.
240 |
241 | :param address: Remote tunnel endpoint address (host, port) tuple
242 | :param uuid: Unique tunnel identifier received from the remote host
243 | :param remote_tunnel_id: Remotely assigned tunnel identifier
244 | :param client_features: Client feature flags
245 | :return: True if a tunnel has been created, False otherwise
246 | """
247 |
248 | return self.tunnel_manager.create_tunnel(self, address, uuid, remote_tunnel_id, client_features)
249 |
250 | def message(self, address, msg_type, msg_data, raw_length):
251 | """
252 | Called when a new protocol message is received.
253 |
254 | :param address: Source address (host, port) tuple
255 | :param msg_type: Message type
256 | :param msg_data: Message payload
257 | :param raw_length: Length of the raw message (including headers)
258 | """
259 |
260 | # Due to SO_REUSEPORT bugs, we also see messags here that really ought to
261 | # go to an established tunnel. So check the tunnels first.
262 | for tunnel in self.tunnel_manager.tunnels.values():
263 | if tunnel.address == self.address and tunnel.endpoint == address:
264 | logger.warning("Protocol error: broker received tunnel message. Possibly due to kernel bug. See: https://github.com/wlanslovenija/tunneldigger/issues/126")
265 |
266 | # Fall back to normal broker processing.
267 | if super(Broker, self).message(address, msg_type, msg_data, raw_length):
268 | return True
269 |
270 | # We sometimes see messages for dead tunnels. Ignore them.
271 | return True
272 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/eventloop.py:
--------------------------------------------------------------------------------
1 | import select
2 |
3 | class EventLoop(object):
4 | """
5 | An epoll-based event loop.
6 | """
7 |
8 | def __init__(self):
9 | """
10 | Constructs the event loop.
11 | """
12 |
13 | self.pollables = {}
14 | self.poller = select.epoll()
15 |
16 | def register(self, pollable, file_object, flags):
17 | """
18 | Registers a new pollable into the event loop.
19 |
20 | :param pollable: Pollable instance
21 | :param file_object: File-like object or file descriptor
22 | :param flags: Epoll flags
23 | """
24 |
25 | raw_file_object = file_object
26 |
27 | if hasattr(file_object, 'fileno'):
28 | file_object = file_object.fileno()
29 |
30 | self.poller.register(file_object, flags)
31 | self.pollables[file_object] = (pollable, raw_file_object)
32 |
33 | def unregister(self, fd):
34 | """
35 | Unregisters an existing file descriptor.
36 |
37 | :param fd: File descriptor
38 | """
39 |
40 | self.poller.unregister(fd)
41 | del self.pollables[fd]
42 |
43 | def start(self):
44 | """
45 | Starts the event loop.
46 | """
47 |
48 | while True:
49 | try:
50 | for fd, event in self.poller.poll():
51 | mapping = self.pollables.get(fd, None)
52 | if not mapping:
53 | continue
54 |
55 | pollable, file_object = mapping
56 |
57 | if event & select.EPOLLIN or event & select.EPOLLERR or event & select.EPOLLHUP:
58 | # If there's anything new, we read. If there was an error, the read will
59 | # return that error so we can handle it.
60 | pollable.read(file_object)
61 | except IOError:
62 | # IOError get produced by signal even. in version 3.5 this is fixed an the poll retries
63 | # TODO: in py3 it's InterruptedError
64 | pass
65 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/genetlink.py:
--------------------------------------------------------------------------------
1 | '''
2 | Netlink message generation/parsing
3 |
4 | Copyright 2007 Johannes Berg
5 |
6 | GPLv2+; See copying for details.
7 | '''
8 |
9 | import struct
10 | from .netlink import NLM_F_REQUEST, NLMSG_MIN_TYPE, Message, parse_attributes
11 | from .netlink import NulStrAttr, Connection, NETLINK_GENERIC
12 |
13 | CTRL_CMD_UNSPEC = 0
14 | CTRL_CMD_NEWFAMILY = 1
15 | CTRL_CMD_DELFAMILY = 2
16 | CTRL_CMD_GETFAMILY = 3
17 | CTRL_CMD_NEWOPS = 4
18 | CTRL_CMD_DELOPS = 5
19 | CTRL_CMD_GETOPS = 6
20 |
21 | CTRL_ATTR_UNSPEC = 0
22 | CTRL_ATTR_FAMILY_ID = 1
23 | CTRL_ATTR_FAMILY_NAME = 2
24 | CTRL_ATTR_VERSION = 3
25 | CTRL_ATTR_HDRSIZE = 4
26 | CTRL_ATTR_MAXATTR = 5
27 | CTRL_ATTR_OPS = 6
28 |
29 | class GenlHdr:
30 | def __init__(self, cmd, version = 0):
31 | self.cmd = cmd
32 | self.version = version
33 | def _dump(self):
34 | return struct.pack("BBxx", self.cmd, self.version)
35 |
36 | def _genl_hdr_parse(data):
37 | return GenlHdr(*struct.unpack("BBxx", data))
38 |
39 | GENL_ID_CTRL = NLMSG_MIN_TYPE
40 |
41 | class GeNlMessage(Message):
42 | def __init__(self, family, cmd, attrs=[], flags=0, version=0):
43 | self.cmd = cmd
44 | self.attrs = attrs
45 | self.family = family
46 | Message.__init__(self, family, flags=flags,
47 | payload=[GenlHdr(self.cmd, version = version)]+attrs)
48 |
49 | @staticmethod
50 | def recv(conn, multiple = False):
51 | msgs = conn.recv(multiple = multiple)
52 | genlmsgs = []
53 | if not multiple:
54 | msgs = [msgs]
55 |
56 | for msg in msgs:
57 | packet = msg.payload
58 | if not packet:
59 | continue
60 |
61 | hdr = _genl_hdr_parse(packet[:4])
62 |
63 | genlmsg = GeNlMessage(msg.type, hdr.cmd, [], msg.flags)
64 | genlmsg.attrs = parse_attributes(packet[4:])
65 | genlmsg.version = hdr.version
66 | genlmsgs.append(genlmsg)
67 |
68 | if not multiple:
69 | return genlmsgs[0]
70 |
71 | return genlmsgs
72 |
73 | class Controller:
74 | def __init__(self, conn):
75 | self.conn = conn
76 | def get_family_id(self, family):
77 | a = NulStrAttr(CTRL_ATTR_FAMILY_NAME, family)
78 | m = GeNlMessage(GENL_ID_CTRL, CTRL_CMD_GETFAMILY,
79 | flags=NLM_F_REQUEST, attrs=[a])
80 | m.send(self.conn)
81 | m = GeNlMessage.recv(self.conn)
82 | return m.attrs[CTRL_ATTR_FAMILY_ID].u16()
83 |
84 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/hooks.py:
--------------------------------------------------------------------------------
1 | import fcntl
2 | import io
3 | import os
4 | import select
5 | import signal
6 | import subprocess
7 | import logging
8 |
9 | # Logger.
10 | logger = logging.getLogger("tunneldigger.hooks")
11 |
12 |
13 | class HookProcess(object):
14 | """
15 | Class used for communication with external hook processes.
16 | """
17 |
18 | def __init__(self, name, script, args):
19 | """
20 | Constructs a hook process instance.
21 |
22 | :param name: Hook name
23 | :param script: Script to execute
24 | :param args: List of script arguments
25 | """
26 |
27 | self.name = name
28 | self.process = subprocess.Popen(
29 | [script] + [str(x) for x in args],
30 | stdout=subprocess.PIPE,
31 | stderr=subprocess.PIPE,
32 | )
33 | self.buffer = io.BytesIO()
34 |
35 | def register(self, event_loop):
36 | """
37 | Registers the hook process into an event loop.
38 |
39 | :param event_loop: Event loop instance
40 | """
41 |
42 | # Make the file descriptors non-blocking.
43 | flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL)
44 | fcntl.fcntl(self.process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
45 | flags = fcntl.fcntl(self.process.stderr, fcntl.F_GETFL)
46 | fcntl.fcntl(self.process.stderr, fcntl.F_SETFL, flags | os.O_NONBLOCK)
47 |
48 | # Register the file descriptors with the event loop.
49 | event_loop.register(self, self.process.stdout, select.EPOLLIN)
50 | event_loop.register(self, self.process.stderr, select.EPOLLIN)
51 | self.event_loop = event_loop
52 |
53 | def close(self):
54 | """
55 | Closes the hook process.
56 | """
57 |
58 | if not hasattr(self, "buffer"):
59 | # We have already been closed.
60 | return
61 |
62 | for line in self.buffer.getvalue().decode('utf-8').split('\n'):
63 | if not line:
64 | continue
65 |
66 | logger.info('(%s/%d) %s' % (self.name, self.process.pid, line))
67 |
68 | del self.buffer
69 | self.event_loop.unregister(self.process.stdout.fileno())
70 | self.event_loop.unregister(self.process.stderr.fileno())
71 |
72 | # Kill the process in case it is still running.
73 | try:
74 | self.process.kill()
75 | except OSError:
76 | pass
77 |
78 | self.process.poll()
79 | self.process.stdout.close()
80 | self.process.stderr.close()
81 |
82 | def read(self, file_object):
83 | """
84 | Called when new data is available for reading from the hook process.
85 | """
86 |
87 | try:
88 | data = file_object.read()
89 | if data:
90 | self.buffer.write(data)
91 |
92 | # Check if the process has terminated.
93 | self.process.poll()
94 | if self.process.returncode is not None:
95 | self.close()
96 | except IOError:
97 | pass
98 |
99 |
100 | class HookManager(object):
101 | """
102 | Manages hooks.
103 | """
104 |
105 | def __init__(self, event_loop, log_arguments):
106 | """
107 | Constructs a new hook manager instance.
108 |
109 | :param event_loop: Event loop instance
110 | """
111 |
112 | self.event_loop = event_loop
113 | self.hooks = {}
114 | self.processes = {}
115 | self.log_arguments = log_arguments
116 |
117 | # Create a file descriptor so we can get notified of SIGCHLD signals in the
118 | # context of the event loop (and not in an arbitrary location).
119 | pipe_r, pipe_w = os.pipe()
120 | flags = fcntl.fcntl(pipe_w, fcntl.F_GETFL, 0)
121 | flags = fcntl.fcntl(pipe_w, fcntl.F_SETFL, flags | os.O_NONBLOCK)
122 |
123 |
124 | def sigchld_handler(signal_number, frame):
125 | os.write(pipe_w, b'\x00')
126 |
127 | signal.signal(signal.SIGCHLD, sigchld_handler)
128 | event_loop.register(self, pipe_r, select.EPOLLIN)
129 |
130 | def register_hook(self, name, script):
131 | """
132 | Registers a new hook under a given name.
133 |
134 | :param name: Hook name
135 | :param script: Script that should be executed
136 | """
137 |
138 | self.hooks[name] = script
139 |
140 | def run_hook(self, name, *args):
141 | """
142 | Runs a given hook.
143 |
144 | :param name: Hook name
145 | """
146 |
147 | script = self.hooks.get(name, None)
148 | if not script:
149 | return
150 |
151 | if self.log_arguments:
152 | logger.info("Running hook '%s' via script '%s %s'." % (name, script, " ".join([str(x) for x in args])))
153 | else:
154 | logger.info("Running hook '%s' via script '%s'." % (name, script))
155 |
156 | try:
157 | process = HookProcess(name, script, args)
158 | process.register(self.event_loop)
159 | self.processes[process.process.pid] = process
160 | except OSError as e:
161 | logger.error("Error while executing script '%s': %s" % (script, e))
162 |
163 | def close(self):
164 | os.close(self.sigchld_fd)
165 |
166 | def read(self, file_object):
167 | """
168 | Handles SIGCHLD notifications.
169 | """
170 |
171 | os.read(file_object, 1)
172 |
173 | while True:
174 | try:
175 | pid, returncode = os.waitpid(-1, os.WNOHANG)
176 | if not pid:
177 | return
178 |
179 | process = self.processes.get(pid)
180 | if not process:
181 | continue
182 |
183 | try:
184 | process.close()
185 | finally:
186 | del self.processes[pid]
187 | except OSError:
188 | return
189 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/l2tp.py:
--------------------------------------------------------------------------------
1 | from . import netlink
2 | from . import genetlink
3 | import logging
4 | import traceback
5 | import errno
6 |
7 | # L2TP generic netlink.
8 | L2TP_GENL_NAME = "l2tp"
9 | L2TP_GENL_VERSION = 0x1
10 |
11 | # L2TP netlink commands.
12 | L2TP_CMD_TUNNEL_CREATE = 1
13 | L2TP_CMD_TUNNEL_DELETE = 2
14 | L2TP_CMD_TUNNEL_GET = 4
15 | L2TP_CMD_SESSION_CREATE = 5
16 | L2TP_CMD_SESSION_DELETE = 6
17 | L2TP_CMD_SESSION_MODIFY = 7
18 | L2TP_CMD_SESSION_GET = 8
19 |
20 | # L2TP netlink command attributes.
21 | L2TP_ATTR_NONE = 0
22 | L2TP_ATTR_PW_TYPE = 1
23 | L2TP_ATTR_ENCAP_TYPE = 2
24 | L2TP_ATTR_PROTO_VERSION = 7
25 | L2TP_ATTR_IFNAME = 8
26 | L2TP_ATTR_CONN_ID = 9
27 | L2TP_ATTR_PEER_CONN_ID = 10
28 | L2TP_ATTR_SESSION_ID = 11
29 | L2TP_ATTR_PEER_SESSION_ID = 12
30 | L2TP_ATTR_FD = 23
31 | L2TP_ATTR_MTU = 28
32 |
33 | # L2TP encapsulation types.
34 | L2TP_ENCAPTYPE_UDP = 0
35 |
36 | # L2TP pseudowire types.
37 | L2TP_PWTYPE_ETH = 0x0005
38 |
39 | # Logger.
40 | logger = logging.getLogger("tunneldigger.l2tp")
41 |
42 |
43 | class NetlinkError(Exception):
44 | pass
45 |
46 |
47 | class L2TPSupportUnavailable(NetlinkError):
48 | pass
49 |
50 |
51 | class L2TPTunnelExists(NetlinkError):
52 | def __init__(self, tunnel_id):
53 | NetlinkError.__init__(self)
54 | self.tunnel_id = tunnel_id
55 |
56 | class L2TPSessionExists(NetlinkError):
57 | def __init__(self, session_id):
58 | NetlinkError.__init__(self)
59 | self.session_id = session_id
60 |
61 |
62 | class NetlinkInterface(object):
63 | """
64 | NETLINK interface to L2TP kernel module.
65 | """
66 |
67 | def __init__(self):
68 | """
69 | Class constructor.
70 | """
71 |
72 | # Establish a connection to the kernel via the netlink socket.
73 | self.connection = netlink.Connection(netlink.NETLINK_GENERIC)
74 | controller = genetlink.Controller(self.connection)
75 | try:
76 | self.family_id = controller.get_family_id(L2TP_GENL_NAME)
77 | except OSError:
78 | raise L2TPSupportUnavailable
79 |
80 | def _create_message(self, command, attributes, flags=netlink.NLM_F_REQUEST | netlink.NLM_F_ACK):
81 | return genetlink.GeNlMessage(
82 | self.family_id,
83 | cmd=command,
84 | version=L2TP_GENL_VERSION,
85 | attrs=attributes,
86 | flags=flags
87 | )
88 |
89 | def tunnel_create(self, tunnel_id, peer_tunnel_id, socket):
90 | """
91 | Creates a new L2TP tunnel.
92 |
93 | :param tunnel_id: Local tunnel identifier
94 | :param peer_tunnel_id: Remote peer tunnel identifier
95 | :param socket: UDP socket file descriptor
96 | """
97 |
98 | msg = self._create_message(L2TP_CMD_TUNNEL_CREATE, [
99 | netlink.U32Attr(L2TP_ATTR_CONN_ID, tunnel_id),
100 | netlink.U32Attr(L2TP_ATTR_PEER_CONN_ID, peer_tunnel_id),
101 | netlink.U8Attr(L2TP_ATTR_PROTO_VERSION, 3),
102 | netlink.U16Attr(L2TP_ATTR_ENCAP_TYPE, L2TP_ENCAPTYPE_UDP),
103 | netlink.U32Attr(L2TP_ATTR_FD, socket),
104 | ])
105 | msg.send(self.connection)
106 |
107 | try:
108 | self.connection.recv()
109 | except OSError as e:
110 | if e.errno == errno.EEXIST:
111 | # This tunnel identifier is already in use; make sure to remove it from
112 | # our pool of assignable tunnel identifiers.
113 | raise L2TPTunnelExists(tunnel_id)
114 |
115 | raise NetlinkError
116 |
117 | def tunnel_delete(self, tunnel_id):
118 | """
119 | Deletes an existing tunnel.
120 |
121 | :param tunnel_id: Local tunnel identifier
122 | """
123 |
124 | msg = self._create_message(L2TP_CMD_TUNNEL_DELETE, [
125 | netlink.U32Attr(L2TP_ATTR_CONN_ID, tunnel_id),
126 | ])
127 | msg.send(self.connection)
128 |
129 | try:
130 | self.connection.recv()
131 | except OSError:
132 | logger.debug(traceback.format_exc())
133 | logger.warning("Unable to remove tunnel %d!" % tunnel_id)
134 |
135 | def tunnel_list(self):
136 | """
137 | Returns a list of tunnel identifiers.
138 | """
139 |
140 | tunnels = []
141 | msg = self._create_message(
142 | L2TP_CMD_TUNNEL_GET,
143 | [],
144 | flags=netlink.NLM_F_REQUEST | netlink.NLM_F_DUMP | netlink.NLM_F_ACK
145 | )
146 | msg.send(self.connection)
147 |
148 | for tunnel in genetlink.GeNlMessage.recv(self.connection, multiple=True):
149 | tunnels.append(tunnel.attrs[L2TP_ATTR_CONN_ID].u32())
150 |
151 | return tunnels
152 |
153 | def session_create(self, tunnel_id, session_id, peer_session_id, name):
154 | """
155 | Creates a new ethernet session over the tunnel.
156 |
157 | :param tunnel_id: Local tunnel identifier
158 | :param session_id: Local session identifier
159 | :param peer_session_id: Remote peer session identifier
160 | :param name: Interface name
161 | """
162 |
163 | msg = self._create_message(L2TP_CMD_SESSION_CREATE, [
164 | netlink.U32Attr(L2TP_ATTR_CONN_ID, tunnel_id),
165 | netlink.U32Attr(L2TP_ATTR_SESSION_ID, session_id),
166 | netlink.U32Attr(L2TP_ATTR_PEER_SESSION_ID, peer_session_id),
167 | netlink.U16Attr(L2TP_ATTR_PW_TYPE, L2TP_PWTYPE_ETH),
168 | # TODO: Cookies.
169 | netlink.NulStrAttr(L2TP_ATTR_IFNAME, name),
170 | ])
171 | msg.send(self.connection)
172 |
173 | try:
174 | self.connection.recv()
175 | except OSError as e:
176 | if e.errno == errno.EEXIST:
177 | raise L2TPSessionExists(session_id)
178 |
179 | raise NetlinkError
180 |
181 | def session_delete(self, tunnel_id, session_id):
182 | """
183 | Deletes an existing session.
184 |
185 | :param tunnel_id: Local tunnel identifier
186 | :param session_id: Local session identifier
187 | """
188 |
189 | msg = self._create_message(L2TP_CMD_SESSION_DELETE, [
190 | netlink.U32Attr(L2TP_ATTR_CONN_ID, tunnel_id),
191 | netlink.U32Attr(L2TP_ATTR_SESSION_ID, session_id),
192 | ])
193 | msg.send(self.connection)
194 |
195 | try:
196 | self.connection.recv()
197 | except OSError:
198 | logger.debug(traceback.format_exc())
199 | logger.warning("Unable to remove tunnel %d session %d!" % (tunnel_id, session_id))
200 |
201 | def session_modify(self, tunnel_id, session_id, mtu):
202 | """
203 | Modifies an existing session.
204 |
205 | :param tunnel_id: Local tunnel identifier
206 | :param session_id: Local session identifier
207 | """
208 |
209 | msg = self._create_message(L2TP_CMD_SESSION_MODIFY, [
210 | netlink.U32Attr(L2TP_ATTR_CONN_ID, tunnel_id),
211 | netlink.U32Attr(L2TP_ATTR_SESSION_ID, session_id),
212 | netlink.U16Attr(L2TP_ATTR_MTU, mtu),
213 | ])
214 | msg.send(self.connection)
215 |
216 | try:
217 | self.connection.recv()
218 | except OSError:
219 | logger.debug(traceback.format_exc())
220 | logger.warning("Unable to modify tunnel %d session %d!" % (tunnel_id, session_id))
221 |
222 | def session_list(self):
223 | """
224 | Returns a list of session identifiers for each tunnel.
225 | """
226 |
227 | sessions = []
228 | msg = self._create_message(
229 | L2TP_CMD_SESSION_GET,
230 | [],
231 | flags=netlink.NLM_F_REQUEST | netlink.NLM_F_DUMP | netlink.NLM_F_ACK
232 | )
233 | msg.send(self.connection)
234 |
235 | for session in genetlink.GeNlMessage.recv(self.connection, multiple=True):
236 | sessions.append(
237 | (session.attrs[L2TP_ATTR_CONN_ID].u32(), session.attrs[L2TP_ATTR_SESSION_ID].u32())
238 | )
239 |
240 | return sessions
241 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/limits.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import struct
3 |
4 | from . import protocol, traffic_control
5 |
6 | # Logger.
7 | logger = logging.getLogger("tunneldigger.limits")
8 |
9 |
10 | class LimitManager(object):
11 | """
12 | Tunnel traffic limit manager.
13 | """
14 |
15 | def __init__(self, tunnel):
16 | """
17 | Class constructor.
18 |
19 | :param tunnel: Tunnel instance
20 | """
21 |
22 | self.tunnel = tunnel
23 |
24 | def configure(self, limit_message):
25 | """
26 | Configures a specific limit.
27 |
28 | :param limit_message: Received limit control message
29 | """
30 |
31 | try:
32 | limit_type, config_len = struct.unpack('!BB', limit_message[:2])
33 | except ValueError:
34 | logger.warning("Malformed limit configuration received on tunnel %d." % self.tunnel.tunnel_id)
35 | return False
36 |
37 | if limit_type == protocol.LIMIT_TYPE_BANDWIDTH_DOWN:
38 | # Downstream (client-wise) limit setup.
39 | try:
40 | bandwidth = struct.unpack('!I', limit_message[2:2 + config_len])[0]
41 | except ValueError:
42 | logger.warning("Malformed bandwidth limit configuration received on tunnel %d." % self.tunnel.tunnel_id)
43 | return False
44 |
45 | logger.info("Setting downstream bandwidth limit to %d kbps on tunnel %d." % (bandwidth, self.tunnel.tunnel_id))
46 |
47 | # Setup bandwidth limit using Linux traffic shaping.
48 | try:
49 | tc = traffic_control.TrafficControl(self.tunnel.get_session_name())
50 | tc.reset()
51 | tc.set_fixed_bandwidth(bandwidth)
52 | except traffic_control.TrafficControlError:
53 | logger.warning("Unable to configure traffic shaping for tunnel %d." % self.tunnel.tunnel_id)
54 |
55 | return True
56 | else:
57 | return False
58 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/main.py:
--------------------------------------------------------------------------------
1 | import configparser
2 | import logging
3 | import logging.config
4 | import os
5 | import socket
6 | import sys
7 | import traceback
8 |
9 | from . import broker, eventloop, hooks
10 |
11 | if os.getuid() != 0:
12 | print("ERROR: The tunneldigger broker must be run as root.")
13 | sys.exit(1)
14 |
15 | # Load configuration.
16 | config = configparser.ConfigParser()
17 | try:
18 | config.read(sys.argv[1])
19 | except IOError:
20 | print("ERROR: Failed to open the specified configuration file '%s'!" % sys.argv[1])
21 | sys.exit(1)
22 | except IndexError:
23 | print("ERROR: First argument must be a configuration file path!")
24 | sys.exit(1)
25 |
26 | # Configure logging.
27 | # TODO: Make logging externally configurable.
28 | LOGGING_CONFIGURATION = {
29 | 'version': 1,
30 | 'formatters': {
31 | 'simple': {
32 | 'format': '[%(levelname)s/%(name)s] %(message)s',
33 | },
34 | },
35 | 'handlers': {
36 | 'console': {
37 | 'level': 'DEBUG',
38 | 'class': 'logging.StreamHandler',
39 | 'formatter': 'simple',
40 | },
41 | },
42 | 'loggers': {
43 | 'tunneldigger': {
44 | 'handlers': ['console'],
45 | 'level': config.get('log', 'verbosity'),
46 | }
47 | }
48 | }
49 | logging.config.dictConfig(LOGGING_CONFIGURATION)
50 |
51 | # Logger.
52 | logger = logging.getLogger("tunneldigger.broker")
53 | logger.info("Initializing the tunneldigger broker.")
54 |
55 | # Initialize the event loop.
56 | event_loop = eventloop.EventLoop()
57 |
58 | # Initialize the hook manager.
59 | hook_manager = hooks.HookManager(
60 | event_loop=event_loop,
61 | log_arguments=config.getboolean('log', 'log_ip_addresses'),
62 | )
63 | for hook in ('session.up', 'session.pre-down', 'session.down', 'session.mtu-changed', 'broker.connection-rate-limit'):
64 | try:
65 | script = config.get('hooks', hook).strip()
66 | if not script:
67 | continue
68 | except (configparser.NoOptionError, configparser.NoSectionError):
69 | continue
70 |
71 | hook_manager.register_hook(hook, script)
72 | logger.info("Registered script '%s' for hook '%s'." % (script, hook))
73 |
74 | # Initialize the tunnel manager.
75 | tunnel_manager = broker.TunnelManager(
76 | hook_manager=hook_manager,
77 | max_tunnels=config.getint('broker', 'max_tunnels'),
78 | tunnel_id_base=config.getint('broker', 'tunnel_id_base'),
79 | connection_rate_limit=config.getfloat('broker', 'connection_rate_limit'),
80 | connection_rate_limit_per_ip_count=config.getint('broker', 'connection_rate_limit_per_ip_count', fallback=0),
81 | connection_rate_limit_per_ip_time=config.getfloat('broker', 'connection_rate_limit_per_ip_time', fallback=0),
82 | pmtu_fixed=config.getint('broker', 'pmtu'),
83 | log_ip_addresses=config.getboolean('log', 'log_ip_addresses'),
84 | )
85 | tunnel_manager.initialize()
86 |
87 | logger.info("Maximum number of tunnels is %d." % tunnel_manager.max_tunnels)
88 | logger.info("Tunnel identifier base is %d." % tunnel_manager.tunnel_id_base)
89 |
90 | # Initialize one broker for each port.
91 | brokers = []
92 | broker_host = config.get('broker', 'address')
93 | for port in config.get('broker', 'port').split(','):
94 | try:
95 | broker_instance = broker.Broker(
96 | (broker_host, int(port)),
97 | config.get('broker', 'interface'),
98 | tunnel_manager,
99 | )
100 | logger.info("Listening on %s:%d." % broker_instance.address)
101 | except ValueError:
102 | logger.warning("Malformed port number '%s', skipping." % port)
103 | continue
104 | except socket.error:
105 | # Skip ports that we fail to listen on.
106 | logger.warning("Failed to listen on %s:%s, skipping." % (broker_host, port))
107 | continue
108 |
109 | broker_instance.register(event_loop)
110 | brokers.append(broker_instance)
111 |
112 | logger.info("Broker initialized.")
113 |
114 | try:
115 | # Start the main event loop.
116 | event_loop.start()
117 | except KeyboardInterrupt:
118 | logger.info("SIGINT received.")
119 | except:
120 | logger.error("Unhandled top-level exception:")
121 | logger.error(traceback.format_exc())
122 |
123 | logger.info("Shutting down tunneldigger broker.")
124 |
125 | # Shutdown all brokers and tunnels.
126 | for broker_instance in brokers:
127 | broker_instance.close()
128 | tunnel_manager.close()
129 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/netlink.py:
--------------------------------------------------------------------------------
1 | #
2 | # NETLINK routines. Adapted from work by Johannes Berg .
3 | # See: http://git.sipsolutions.net/?p=pynl80211.git;a=blob;f=netlink.py;hb=HEAD
4 | # This file is licensed under GPLv2+.
5 | #
6 | import socket
7 | import os
8 | import struct
9 |
10 | # Flags
11 | NLM_F_REQUEST = 1
12 | NLM_F_MULTI = 2
13 | NLM_F_ACK = 4
14 | NLM_F_ECHO = 8
15 |
16 | NLM_F_ROOT = 0x100
17 | NLM_F_MATCH = 0x200
18 | NLM_F_ATOMIC = 0x400
19 | NLM_F_DUMP = (NLM_F_ROOT | NLM_F_MATCH)
20 |
21 | # Types
22 | NLMSG_NOOP = 1
23 | NLMSG_ERROR = 2
24 | NLMSG_DONE = 3
25 | NLMSG_OVERRUN = 4
26 | NLMSG_MIN_TYPE = 0x10
27 |
28 | class Attr:
29 | def __init__(self, attr_type, data, *values):
30 | self.type = attr_type
31 | if len(values):
32 | self.data = struct.pack(data, *values)
33 | else:
34 | self.data = data
35 |
36 | def _dump(self):
37 | hdr = struct.pack("HH", len(self.data)+4, self.type)
38 | length = len(self.data)
39 | pad = ((length + 4 - 1) & ~3) - length
40 | return hdr + self.data + b'\0' * pad
41 |
42 | def __repr__(self):
43 | return '' % (self.type, repr(self.data))
44 |
45 | def u16(self):
46 | return struct.unpack('H', self.data)[0]
47 | def s16(self):
48 | return struct.unpack('h', self.data)[0]
49 | def u32(self):
50 | return struct.unpack('I', self.data)[0]
51 | def s32(self):
52 | return struct.unpack('i', self.data)[0]
53 | def str(self):
54 | return self.data
55 | def nulstr(self):
56 | return self.data.split('\0')[0]
57 | def nested(self):
58 | return parse_attributes(self.data)
59 |
60 | class StrAttr(Attr):
61 | def __init__(self, attr_type, data):
62 | Attr.__init__(self, attr_type, "%ds" % len(data), data.encode('utf-8'))
63 |
64 | class NulStrAttr(Attr):
65 | def __init__(self, attr_type, data):
66 | Attr.__init__(self, attr_type, "%dsB" % len(data), data.encode('utf-8'), 0)
67 |
68 | class U32Attr(Attr):
69 | def __init__(self, attr_type, val):
70 | Attr.__init__(self, attr_type, "I", val)
71 |
72 | class U16Attr(Attr):
73 | def __init__(self, attr_type, val):
74 | Attr.__init__(self, attr_type, "H", val)
75 |
76 | class U8Attr(Attr):
77 | def __init__(self, attr_type, val):
78 | Attr.__init__(self, attr_type, "B", val)
79 |
80 | class Nested(Attr):
81 | def __init__(self, attr_type, attrs):
82 | self.attrs = attrs
83 | self.type = attr_type
84 |
85 | def _dump(self):
86 | contents = []
87 | for attr in self.attrs:
88 | contents.append(attr._dump())
89 | contents = ''.join(contents)
90 | length = len(contents)
91 | hdr = struct.pack("HH", length+4, self.type)
92 | return hdr + contents
93 |
94 | NETLINK_ROUTE = 0
95 | NETLINK_UNUSED = 1
96 | NETLINK_USERSOCK = 2
97 | NETLINK_FIREWALL = 3
98 | NETLINK_INET_DIAG = 4
99 | NETLINK_NFLOG = 5
100 | NETLINK_XFRM = 6
101 | NETLINK_SELINUX = 7
102 | NETLINK_ISCSI = 8
103 | NETLINK_AUDIT = 9
104 | NETLINK_FIB_LOOKUP = 10
105 | NETLINK_CONNECTOR = 11
106 | NETLINK_NETFILTER = 12
107 | NETLINK_IP6_FW = 13
108 | NETLINK_DNRTMSG = 14
109 | NETLINK_KOBJECT_UEVENT = 15
110 | NETLINK_GENERIC = 16
111 |
112 | class Message:
113 | def __init__(self, msg_type, flags=0, seq=-1, payload=None):
114 | self.type = msg_type
115 | self.flags = flags
116 | self.seq = seq
117 | self.pid = -1
118 | payload = payload or []
119 | if isinstance(payload, list):
120 | contents = []
121 | for attr in payload:
122 | contents.append(attr._dump())
123 | self.payload = b''.join(contents)
124 | else:
125 | self.payload = payload
126 |
127 | def send(self, conn):
128 | if self.seq == -1:
129 | self.seq = conn.seq()
130 |
131 | self.pid = conn.pid
132 | length = len(self.payload)
133 |
134 | hdr = struct.pack("IHHII", length + 4*4, self.type,
135 | self.flags, self.seq, self.pid)
136 | conn.send(hdr + self.payload)
137 |
138 | def __repr__(self):
139 | return '' % (
140 | self.type, self.pid, self.seq, self.flags, repr(self.payload))
141 |
142 | class Connection:
143 | def __init__(self, nltype, groups=0, unexpected_msg_handler=None):
144 | self.descriptor = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, nltype)
145 | self.descriptor.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65536)
146 | self.descriptor.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536)
147 | self.descriptor.bind((0, groups))
148 | self.pid, self.groups = self.descriptor.getsockname()
149 | self._seq = 0
150 | self.unexpected = unexpected_msg_handler
151 |
152 | def send(self, msg):
153 | self.descriptor.send(msg)
154 |
155 | def recv(self, multiple = False):
156 | """
157 | Receive message(s) from the netlink socket.
158 |
159 | :param multiple: Control the receiving mode.
160 |
161 | In single-message mode, exactly one message is received. If that message is an error,
162 | an exception is raised. Otherwise (including if the message is an ack), it is returned.
163 | In multiple-message mode, messages are received until the first NLMSG_DONE.
164 | If there is an error, an exception is raised. Acks and the final NLMSG_DONE are dropped.
165 | The other messages are returned in a list.
166 | """
167 | messages = []
168 | done = False
169 |
170 | while not done:
171 | contents, (nlpid, nlgrps) = self.descriptor.recvfrom(16384)
172 |
173 | while len(contents):
174 | msglen, msg_type, flags, seq, pid = struct.unpack("IHHII", contents[:16])
175 | msg = Message(msg_type, flags, seq, contents[16:msglen])
176 | msg.pid = pid
177 | contents = contents[msglen:]
178 |
179 | if msg.type == NLMSG_ERROR:
180 | errno = -struct.unpack("i", msg.payload[:4])[0]
181 | if errno != 0:
182 | err = OSError("Netlink error: %s (%d)" % (
183 | os.strerror(errno), errno))
184 | err.errno = errno
185 | raise err
186 |
187 | # A non-error message
188 | if not multiple:
189 | messages.append(msg)
190 | done = True
191 | break
192 | elif msg.type == NLMSG_DONE:
193 | done = True
194 | break
195 | elif msg.type == NLMSG_ERROR:
196 | # an ack
197 | pass
198 | else:
199 | messages.append(msg)
200 |
201 | if not multiple:
202 | return messages[0]
203 |
204 | return messages
205 |
206 | def seq(self):
207 | self._seq += 1
208 | return self._seq
209 |
210 | def parse_attributes(data):
211 | attrs = {}
212 | while len(data):
213 | attr_len, attr_type = struct.unpack("HH", data[:4])
214 | attrs[attr_type] = Attr(attr_type, data[4:attr_len])
215 | attr_len = ((attr_len + 4 - 1) & ~3 )
216 | data = data[attr_len:]
217 | return attrs
218 |
219 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/network.py:
--------------------------------------------------------------------------------
1 | import os
2 | import errno
3 | from . import timerfd
4 | import logging
5 | import traceback
6 | import select
7 | import socket
8 | import struct
9 |
10 | from . import protocol
11 |
12 | # Logger.
13 | logger = logging.getLogger("tunneldigger.network")
14 |
15 |
16 | class PollableNotRegistered(Exception):
17 | pass
18 |
19 |
20 | class Pollable(object):
21 | """
22 | Wrapper around a UDP socket interface, which may be polled by the simple
23 | event loop.
24 | """
25 |
26 | def __init__(self, address, interface, name):
27 | """
28 | Constructs a new pollable instance.
29 |
30 | :param address: Address (host, port) tuple to bind to
31 | :param interface: Interface name to bind to
32 | """
33 |
34 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
35 | # The L2TP kernel driver's design requires each tunnel to have it's own socket.
36 | # Since we want all tunnel and tunnel control traffic to use the same port for
37 | # all clients we enable reuse of ports on the sockets we create.
38 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
39 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface.encode('utf-8'))
40 | self.socket.bind(address)
41 |
42 | self.address = address
43 | self.interface = interface
44 | self.name = name
45 | self.event_loop = None
46 | self.timers = set()
47 |
48 | def register(self, event_loop):
49 | """
50 | Registers the pollable into the event loop.
51 |
52 | :param event_loop: Event loop instance
53 | """
54 |
55 | event_loop.register(self, self.socket, select.EPOLLIN)
56 | self.event_loop = event_loop
57 |
58 | def error(self, direction, e):
59 | """
60 | `direction` can be "reading" or "writing"
61 | """
62 | logger.warning("{}: error {} socket: {}".format(self.name, direction, e))
63 |
64 | def close(self):
65 | """
66 | Closes the underlying socket and stops all timers.
67 | """
68 |
69 | self.event_loop.unregister(self.socket.fileno())
70 | self.socket.close()
71 |
72 | for timer in self.timers.copy():
73 | timer.close()
74 |
75 | def create_timer(self, callback, timeout=None, interval=None):
76 | """
77 | Creates a timer.
78 |
79 | :param callback: Callback to fire on timeout
80 | :param timeout: Delay before timer fires first
81 | :param interval: Interval for repeating timers
82 | :return: Timer object, which may be used to stop the timer
83 | """
84 |
85 | if not self.event_loop:
86 | raise PollableNotRegistered
87 |
88 | if interval is not None and timeout is None:
89 | timeout = interval
90 |
91 | timer = timerfd.create(timerfd.CLOCK_MONOTONIC)
92 | timerfd.settime(timer, 0, timerfd.itimerspec(value=timeout, interval=interval))
93 |
94 | class Timer(object):
95 | def read(timer_self, file_object):
96 | try:
97 | if not os.read(timer, timerfd.bufsize):
98 | return timer_self.close()
99 | except OSError as e:
100 | if e.errno in (errno.EINTR, errno.EAGAIN):
101 | return
102 |
103 | raise
104 |
105 | try:
106 | callback()
107 | finally:
108 | # Unregister the timer if it is a one-shot timer.
109 | if interval is None:
110 | timer_self.close()
111 |
112 | def close(timer_self):
113 | self.event_loop.unregister(timer)
114 | self.timers.remove(timer_self)
115 | os.close(timer)
116 |
117 | handler = Timer()
118 | self.event_loop.register(handler, timer, select.EPOLLIN)
119 | self.timers.add(handler)
120 | return handler
121 |
122 | def write(self, address, data):
123 | """
124 | Writes into the underlying UDP socket.
125 |
126 | :param address: Destination address (host, port) tuple
127 | :param data: Data to write to the socket
128 | """
129 |
130 | try:
131 | self.socket.sendto(data, address)
132 | except socket.error as e:
133 | self.error("writing", e)
134 | return
135 |
136 | def write_message(self, address, msg_type, msg_data=b''):
137 | """
138 | Writes a protocol message into the underlying UDP socket.
139 |
140 | :param address: Destination address (host, port) tuple
141 | :param msg_type: Message type
142 | :param msg_data: Message payload (at most 254 bytes)
143 | """
144 |
145 | assert len(msg_data) < 255
146 |
147 | # The 2nd nibble of the 2nd byte is 3, for the L2TP version.
148 | # The very first bit is 1, indicating that this is a control message.
149 | # This is sufficient for the kernel to ignore this package.
150 | # Also see .
151 | data = b'\x80\x73\xA7\x01'
152 | data += struct.pack('!BB', msg_type, len(msg_data))
153 | data += msg_data
154 |
155 | # Pad the message to be at least 12 bytes long, as otherwise some firewalls
156 | # may filter it when used over port 53.
157 | if len(data) < 12:
158 | data += b'\x00' * (12 - len(data))
159 |
160 | self.write(address, data)
161 |
162 | def read(self, file_object):
163 | """
164 | Called by the event loop when there is new data to be read
165 | from the socket.
166 | """
167 |
168 | try:
169 | data, address = self.socket.recvfrom(2048)
170 | except socket.error as e:
171 | self.error("reading", e)
172 | return
173 |
174 | msg_type, msg_data = protocol.parse_message(data)
175 | if msg_type == protocol.CONTROL_TYPE_INVALID:
176 | return
177 |
178 | try:
179 | if not self.message(address, msg_type, msg_data, len(data)):
180 | logger.warning("{}: Unhandled message type 0x{:x}".format(self.name, msg_type))
181 | except KeyboardInterrupt:
182 | raise
183 | except:
184 | logger.error("{}: Unhandled exception during message processing.".format(self.name))
185 | logger.error(traceback.format_exc())
186 |
187 | def message(self, address, msg_type, msg_data, raw_length):
188 | """
189 | Called when a new protocol message is received.
190 |
191 | :param address: Source address (host, port) tuple
192 | :param msg_type: Message type
193 | :param msg_data: Message payload
194 | :param raw_length: Length of the raw message (including headers)
195 | """
196 |
197 | return False
198 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/protocol.py:
--------------------------------------------------------------------------------
1 | import hashlib
2 | import hmac
3 | import logging
4 | import os
5 | import time
6 | import struct
7 |
8 | # Logger.
9 | logger = logging.getLogger("tunneldigger.protocol")
10 |
11 | # Unreliable messages (0x00 - 0x7F).
12 | CONTROL_TYPE_INVALID = 0x00
13 | CONTROL_TYPE_COOKIE = 0x01
14 | CONTROL_TYPE_PREPARE = 0x02
15 | CONTROL_TYPE_ERROR = 0x03
16 | CONTROL_TYPE_TUNNEL = 0x04
17 | CONTROL_TYPE_KEEPALIVE = 0x05
18 | CONTROL_TYPE_PMTUD = 0x06
19 | CONTROL_TYPE_PMTUD_ACK = 0x07
20 | CONTROL_TYPE_REL_ACK = 0x08
21 | CONTROL_TYPE_PMTU_NTFY = 0x09
22 | CONTROL_TYPE_USAGE = 0x0A
23 |
24 | # Reliable messages (0x80 - 0xFF).
25 | MASK_CONTROL_TYPE_RELIABLE = 0x80
26 | CONTROL_TYPE_LIMIT = 0x80
27 |
28 | # Error Reason Byte.
29 | # e.g. a client shutdown. it sends 0x11 to the server which answer with 0x00 (other request)
30 | # left nibble is direction
31 | ERROR_REASON_FROM_SERVER = 0x00
32 | ERROR_REASON_FROM_CLIENT = 0x10
33 | # right nibble is error code. these are the server error codes.
34 | # (client error codes differ!)
35 | ERROR_REASON_OTHER_REQUEST = 0x01 # other site requested
36 | ERROR_REASON_SHUTDOWN = 0x02 # shutdown
37 | ERROR_REASON_TIMEOUT = 0x03
38 | ERROR_REASON_FAILURE = 0x04 # e.q. on malloc() failure
39 | ERROR_REASON_UNDEFINED = 0x05
40 |
41 | # Session feature flags
42 | FEATURE_UNIQUE_SESSION_ID = 1 << 0
43 | FEATURES_MASK = FEATURE_UNIQUE_SESSION_ID
44 |
45 | # Limit types.
46 | LIMIT_TYPE_BANDWIDTH_DOWN = 0x01
47 |
48 | INVALID_MESSAGE = (CONTROL_TYPE_INVALID, '')
49 |
50 |
51 | def parse_message(data):
52 | """
53 | Parses a tunneldigger control message.
54 |
55 | :param data: Raw data
56 | :return: A tuple (type, payload) containing the message type and payload
57 | """
58 |
59 | if len(data) < 6:
60 | return INVALID_MESSAGE
61 |
62 | # Parse header.
63 | magic1, magic2, version, msg_type, msg_length = struct.unpack('!BHBBB', data[0:6])
64 | if magic1 != 0x80 or magic2 != 0x73A7:
65 | return INVALID_MESSAGE
66 |
67 | if version != 1:
68 | return INVALID_MESSAGE
69 |
70 | try:
71 | return msg_type, data[6:6 + msg_length]
72 | except IndexError:
73 | return INVALID_MESSAGE
74 |
75 | # Generate secret key.
76 | SECRET_KEY = os.urandom(32)
77 | # Determine epoch.
78 | PROTOCOL_EPOCH = int(time.time()) >> 6
79 |
80 |
81 | def protocol_time():
82 | """
83 | Returns the current time in protocol epoch.
84 | """
85 |
86 | return ((int(time.time()) >> 6) - PROTOCOL_EPOCH) % 65536
87 |
88 |
89 | class HandshakeProtocolMixin(object):
90 | """
91 | A mixin that adds handling of the tunneldigger handshake protocol to
92 | a pollable class.
93 | """
94 |
95 | def message(self, address, msg_type, msg_data, raw_length):
96 | """
97 | Called when a new protocol message is received.
98 |
99 | :param address: Source address (host, port) tuple
100 | :param msg_type: Message type
101 | :param msg_data: Message payload
102 | :param raw_length: Length of the raw message (including headers)
103 | """
104 |
105 | if msg_type == CONTROL_TYPE_COOKIE:
106 | # Packet format:
107 | # 8 bytes of padding, to make sure the response is no larger than the request.
108 | if len(msg_data) < 8:
109 | return
110 |
111 | # Generate a random cookie as follows:
112 | # 2 bytes protocol time mod 65536
113 | # 6 bytes HMAC-SHA1 keyed with SECRET_KEY and computed
114 | # over (src_host, src_port, random_bytes)
115 | timestamp = struct.pack('!H', protocol_time())
116 | signed_value = '%s%s%s' % (address[0], address[1], timestamp)
117 | signature = hmac.HMAC(SECRET_KEY, signed_value.encode('utf-8'), hashlib.sha1).digest()[:6]
118 | self.write_message(address, CONTROL_TYPE_COOKIE, timestamp + signature)
119 | return True
120 | elif msg_type == CONTROL_TYPE_PREPARE:
121 | # Packet format:
122 | # 2 bytes protocol time
123 | # 6 bytes "cookie", must be the signature we computed above
124 | # 1 byte UUID length
125 | # N bytes UUID
126 | # optionally 4 bytes remote tunnel ID
127 | # optionally 4 bytes client feature flags
128 |
129 | offset = 0
130 |
131 | # Verify cookie value.
132 | timestamp = msg_data[offset:offset + 2]
133 | offset += 2
134 | signed_value = '%s%s%s' % (address[0], address[1], timestamp)
135 | signature = hmac.HMAC(SECRET_KEY, signed_value.encode('utf-8'), hashlib.sha1).digest()[:6]
136 | timestamp = struct.unpack('!H', timestamp)[0]
137 |
138 | # Reject message if more than 2 protocol ticks old. One tick is 1 >> 6 = 64 seconds.
139 | if signature != msg_data[offset:offset + 6] or abs(protocol_time() - timestamp) > 2:
140 | return
141 | offset += 6
142 |
143 | uuid_len = msg_data[offset]
144 | offset += 1
145 | uuid = msg_data[offset:offset + uuid_len].decode('utf-8')
146 | offset += uuid_len
147 |
148 | # Parse optional data
149 | remote_tunnel_id = 1
150 | client_features = 0
151 | try:
152 | remote_tunnel_id = struct.unpack('!I', msg_data[offset:offset + 4])[0]
153 | offset += 4
154 | client_features = struct.unpack('!I', msg_data[offset:offset + 4])[0]
155 | offset += 4
156 | except (struct.error, IndexError):
157 | pass
158 |
159 | if not self.create_tunnel(address, uuid, remote_tunnel_id, client_features):
160 | logger.warning("{}: Failed to create tunnel ({}) while processing prepare request.".format(self.name, uuid))
161 | self.write_message(address, CONTROL_TYPE_ERROR)
162 |
163 | return True
164 | elif msg_type == CONTROL_TYPE_USAGE:
165 | # Packet format:
166 | # 8 bytes of padding, to make sure the response is no larger than the request.
167 | # optionally 4 bytes client feature flags
168 | if len(msg_data) < 8:
169 | return
170 |
171 | client_features = 0
172 | try:
173 | client_features = struct.unpack('!I', msg_data[8:8 + 4])[0]
174 | except (struct.error, IndexError):
175 | pass
176 |
177 | # Compute tunnel usage information.
178 | usage = self.get_tunnel_manager().report_usage(client_features)
179 | usage = struct.pack('!H', usage)
180 | self.write_message(address, CONTROL_TYPE_USAGE, usage)
181 | return True
182 | else:
183 | # Invalid message at this stage.
184 | return False
185 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/timerfd.py:
--------------------------------------------------------------------------------
1 | __all__ = [
2 | "CLOEXEC",
3 | "NONBLOCK",
4 |
5 | "TIMER_ABSTIME",
6 |
7 | "CLOCK_REALTIME",
8 | "CLOCK_MONOTONIC",
9 |
10 | "bufsize",
11 |
12 | "timespec",
13 | "itimerspec",
14 |
15 | "create",
16 | "settime",
17 | "gettime",
18 | "unpack",
19 | ]
20 |
21 | import ctypes
22 | import ctypes.util
23 | import math
24 | import os
25 | import struct
26 |
27 | CLOEXEC = 0o02000000
28 | NONBLOCK = 0o00004000
29 |
30 | TIMER_ABSTIME = 0x00000001
31 |
32 | CLOCK_REALTIME = 0
33 | CLOCK_MONOTONIC = 1
34 |
35 | bufsize = 8
36 |
37 | libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)
38 |
39 | class timespec(ctypes.Structure):
40 |
41 | _fields_ = [
42 | ("tv_sec", libc.time.restype),
43 | ("tv_nsec", ctypes.c_long),
44 | ]
45 |
46 | def __init__(self, time=None):
47 | ctypes.Structure.__init__(self)
48 |
49 | if time is not None:
50 | self.set_time(time)
51 |
52 | def __repr__(self):
53 | return "timerfd.timespec(%s)" % self.get_time()
54 |
55 | def set_time(self, time):
56 | fraction, integer = math.modf(time)
57 |
58 | self.tv_sec = int(integer)
59 | self.tv_nsec = int(fraction * 1000000000)
60 |
61 | def get_time(self):
62 | if self.tv_nsec:
63 | return self.tv_sec + self.tv_nsec / 1000000000.0
64 | else:
65 | return self.tv_sec
66 |
67 | class itimerspec(ctypes.Structure):
68 |
69 | _fields_ = [
70 | ("it_interval", timespec),
71 | ("it_value", timespec),
72 | ]
73 |
74 | def __init__(self, interval=None, value=None):
75 | ctypes.Structure.__init__(self)
76 |
77 | if interval is not None:
78 | self.it_interval.set_time(interval)
79 |
80 | if value is not None:
81 | self.it_value.set_time(value)
82 |
83 | def __repr__(self):
84 | items = [("interval", self.it_interval), ("value", self.it_value)]
85 | args = ["%s=%s" % (name, value.get_time()) for name, value in items]
86 | return "timerfd.itimerspec(%s)" % ", ".join(args)
87 |
88 | def set_interval(self, time):
89 | self.it_interval.set_time(time)
90 |
91 | def get_interval(self):
92 | return self.it_interval.get_time()
93 |
94 | def set_value(self, time):
95 | self.it_value.set_time(time)
96 |
97 | def get_value(self):
98 | return self.it_value.get_time()
99 |
100 | def errcheck(result, func, arguments):
101 | if result < 0:
102 | errno = ctypes.get_errno()
103 | raise OSError(errno, os.strerror(errno))
104 |
105 | return result
106 |
107 | libc.timerfd_create.argtypes = [ctypes.c_int, ctypes.c_int]
108 | libc.timerfd_create.errcheck = errcheck
109 |
110 | libc.timerfd_settime.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(itimerspec), ctypes.POINTER(itimerspec)]
111 | libc.timerfd_settime.errcheck = errcheck
112 |
113 | libc.timerfd_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(itimerspec)]
114 | libc.timerfd_gettime.errcheck = errcheck
115 |
116 | def create(clock_id, flags=0):
117 | ret = libc.timerfd_create(clock_id, flags)
118 | if ret == -1:
119 | raise OSError
120 | return ret
121 |
122 | def settime(ufd, flags, new_value):
123 | old_value = itimerspec()
124 | ret = libc.timerfd_settime(ufd, flags, ctypes.pointer(new_value), ctypes.pointer(old_value))
125 | if ret == -1:
126 | raise OSError
127 | return old_value
128 |
129 | def gettime(ufd):
130 | curr_value = itimerspec()
131 | ret = libc.timerfd_gettime(ufd, ctypes.pointer(curr_value))
132 | if ret == -1:
133 | raise OSError
134 | return curr_value
135 |
136 | def unpack(buf):
137 | count, = struct.unpack("Q", buf[:bufsize])
138 | return count
139 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/traffic_control.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 |
4 | class TrafficControlError(Exception):
5 | pass
6 |
7 |
8 | class TrafficControl(object):
9 | def __init__(self, interface):
10 | """
11 | Class constructor.
12 |
13 | :param interface: Name of traffic controller interface
14 | """
15 |
16 | self.interface = interface
17 |
18 | def tc(self, command, ignore_fails=False):
19 | """
20 | Executes a traffic control command.
21 | """
22 |
23 | command = 'tc %s' % (command)
24 | if ignore_fails:
25 | command += ' 2>/dev/null'
26 | if os.system(command) != 0 and not ignore_fails:
27 | raise TrafficControlError
28 |
29 | def reset(self):
30 | """
31 | Clears all existing traffic control rules.
32 | """
33 |
34 | self.tc('qdisc del dev %s root handle 1: htb default 0' % self.interface, ignore_fails=True)
35 | self.tc('qdisc add dev %s root handle 1: htb default 1' % self.interface)
36 |
37 | def set_fixed_bandwidth(self, bandwidth):
38 | """
39 | Configures a fixed bandwidth class for this interface.
40 |
41 | :param bandwidth: Bandwidth limit in kbps
42 | """
43 |
44 | self.tc('class add dev %s parent 1: classid 1:1 htb rate %dkbit ceil %dkbit' % (
45 | self.interface, bandwidth, bandwidth
46 | ))
47 | self.tc('qdisc add dev %s parent 1:1 fq_codel' % (
48 | self.interface
49 | ), True)
50 |
--------------------------------------------------------------------------------
/broker/src/tunneldigger_broker/tunnel.py:
--------------------------------------------------------------------------------
1 | import fcntl
2 | import logging
3 | import random
4 | import socket
5 | import struct
6 | import time
7 | import errno
8 |
9 | from . import l2tp, protocol, network, limits
10 |
11 | # Socket options.
12 | IP_MTU_DISCOVER = 10
13 | IP_PMTUDISC_PROBE = 3
14 |
15 | # Ioctls.
16 | SIOCSIFMTU = 0x8922
17 |
18 | # Overhead of IP and UDP headers for measuring PMTU
19 | IPV4_HDR_OVERHEAD = 28
20 |
21 | # L2TP data header overhead for calculating tunnel MTU; takes
22 | # the following headers into account:
23 | #
24 | # 20 bytes (IP header)
25 | # 8 bytes (UDP header)
26 | # 4 bytes (L2TPv3 Session ID)
27 | # 4 bytes (L2TPv3 Cookie)
28 | # 4 bytes (L2TPv3 Pseudowire CE)
29 | # 14 bytes (Ethernet)
30 | #
31 | L2TP_TUN_OVERHEAD = 54
32 |
33 | # PMTU probe sizes.
34 | PMTU_DEFAULT = 1446
35 | PMTU_PROBE_SIZES = [1500, 1492, 1476, 1450, 1400, 1334]
36 | PMTU_PROBE_SIZE_COUNT = len(PMTU_PROBE_SIZES)
37 | PMTU_PROBE_REPEATS = 4
38 | PMTU_PROBE_COMBINATIONS = PMTU_PROBE_SIZE_COUNT * PMTU_PROBE_REPEATS
39 |
40 | # Logger.
41 | logger = logging.getLogger("tunneldigger.tunnel")
42 |
43 |
44 | class TunnelSetupFailed(Exception):
45 | pass
46 |
47 |
48 | class Tunnel(protocol.HandshakeProtocolMixin, network.Pollable):
49 | """
50 | A tunnel descriptor.
51 | """
52 |
53 | def __init__(self, broker, address, endpoint, uuid, tunnel_id, remote_tunnel_id, pmtu_fixed, client_features):
54 | """
55 | Construct a tunnel.
56 |
57 | :param broker: Broker instance that received the initial request
58 | :param address: Destination broker address (host, port) tuple
59 | :param endpoint: Remote tunnel endpoint address (host, port) tuple
60 | :param uuid: Unique tunnel identifier received from the remote host
61 | :param tunnel_id: Locally assigned tunnel identifier
62 | :param remote_tunnel_id: Remotely assigned tunnel identifier
63 | """
64 |
65 | super(Tunnel, self).__init__(address, broker.interface, "Tunnel %d (%s)" % (tunnel_id, uuid))
66 | self.socket.connect(endpoint)
67 | self.socket.setsockopt(socket.IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_PROBE)
68 |
69 | self.broker = broker
70 | self.endpoint = endpoint
71 | self.uuid = uuid
72 | self.client_features = client_features
73 | self.tunnel_id = tunnel_id
74 | self.remote_tunnel_id = remote_tunnel_id
75 | self.session_id = self.tunnel_id if self.client_features & protocol.FEATURE_UNIQUE_SESSION_ID else 1
76 | self.remote_session_id = self.remote_tunnel_id if self.client_features & protocol.FEATURE_UNIQUE_SESSION_ID else 1
77 |
78 | self.last_alive = time.time()
79 | self.created_time = None
80 | self.keepalive_seqno = 0
81 | self.error_count = 0
82 | self.closing = False
83 |
84 | # Initialize PMTU values.
85 | self.automatic_pmtu = pmtu_fixed == 0
86 | self.tunnel_mtu = PMTU_DEFAULT
87 | self.remote_tunnel_mtu = None
88 | self.measured_pmtu = PMTU_DEFAULT if self.automatic_pmtu else pmtu_fixed
89 | self.pmtu_probe_iteration = 0
90 | self.pmtu_probe_size = None
91 | self.pmtu_probe_acked_mtu = 0
92 |
93 | def get_tunnel_manager(self):
94 | """
95 | Returns the tunnel manager for this tunnel.
96 | """
97 |
98 | return self.broker.tunnel_manager
99 |
100 | def get_session_name(self):
101 | """
102 | Returns the interface name for a tunnel's session.
103 | """
104 |
105 | return "l2tp%d-%d" % (self.tunnel_id, self.session_id)
106 |
107 | def setup_tunnel(self):
108 | """
109 | Initializes the tunnel.
110 | """
111 |
112 | # Make the UDP socket an encapsulation socket by asking the kernel to do so.
113 | try:
114 | self.broker.netlink.tunnel_create(self.tunnel_id, self.remote_tunnel_id, self.socket.fileno())
115 |
116 | # Create a pseudowire L2TP session over the tunnel.
117 | self.broker.netlink.session_create(self.tunnel_id, self.session_id, self.remote_session_id, self.get_session_name())
118 | except l2tp.L2TPTunnelExists:
119 | self.socket.close()
120 | raise
121 | except l2tp.L2TPSessionExists:
122 | self.socket.close()
123 | raise
124 | except l2tp.NetlinkError:
125 | self.socket.close()
126 | raise TunnelSetupFailed
127 |
128 | self.created_time = time.time()
129 |
130 | # Update MTU.
131 | self.update_mtu(initial=True)
132 |
133 | # Respond with tunnel establishment message.
134 | server_features = self.client_features & protocol.FEATURES_MASK
135 | if server_features:
136 | # Tell the client which features we support.
137 | msg = struct.pack('!II', self.tunnel_id, server_features)
138 | else:
139 | # There are no features to speak of.
140 | msg = struct.pack('!I', self.tunnel_id)
141 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_TUNNEL, msg)
142 |
143 | # Spawn keepalive timer.
144 | self.create_timer(self.keepalive, timeout=random.randrange(3, 15), interval=5)
145 | # Spawn PMTU measurement timer. The initial timeout is randomized to avoid all tunnels
146 | # from starting the measurements at the same time.
147 | if self.automatic_pmtu:
148 | self.create_timer(self.pmtu_discovery, timeout=random.randrange(0, 5))
149 | else:
150 | # Send our static MTU. No timer.
151 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_PMTU_NTFY, struct.pack('!H', self.measured_pmtu))
152 |
153 | # Call session up hook.
154 | self.broker.hook_manager.run_hook(
155 | 'session.up',
156 | self.tunnel_id,
157 | self.session_id,
158 | self.get_session_name(),
159 | self.tunnel_mtu,
160 | self.endpoint[0],
161 | self.endpoint[1],
162 | self.address[1],
163 | self.uuid,
164 | self.broker.address[1],
165 | )
166 |
167 | def pmtu_discovery(self):
168 | """
169 | Handle periodic PMTU discovery.
170 | """
171 | if self.pmtu_probe_size is not None and self.pmtu_probe_size <= self.pmtu_probe_acked_mtu:
172 | # No need to check lower PMTUs as we already received acknowledgement. Restart
173 | # PMTU discovery after sleeping for some time.
174 | self.pmtu_probe_iteration = 0
175 | self.pmtu_probe_size = None
176 | self.pmtu_probe_acked_mtu = 0
177 | self.create_timer(self.pmtu_discovery, timeout=random.randrange(500, 700))
178 | return
179 |
180 | self.pmtu_probe_size = PMTU_PROBE_SIZES[int(self.pmtu_probe_iteration / PMTU_PROBE_REPEATS)]
181 | self.pmtu_probe_iteration = (self.pmtu_probe_iteration + 1) % PMTU_PROBE_COMBINATIONS
182 |
183 | # Transmit the PMTU probe.
184 | probe = b'\x80\x73\xA7\x01\x06\x00'
185 | probe += b'\x00' * (self.pmtu_probe_size - IPV4_HDR_OVERHEAD - len(probe))
186 | self.write(self.endpoint, probe)
187 |
188 | # Wait some to get the reply, then send the next probe.
189 | self.create_timer(self.pmtu_discovery, timeout=1)
190 |
191 | def update_mtu(self, initial=False):
192 | """
193 | Updates the tunnel MTU from self.measured_pmtu.
194 | """
195 |
196 | detected_pmtu = max(1280, min(self.measured_pmtu, self.remote_tunnel_mtu or PMTU_DEFAULT))
197 | if not initial and detected_pmtu == self.tunnel_mtu:
198 | return
199 |
200 | old_tunnel_mtu = self.tunnel_mtu
201 | self.tunnel_mtu = detected_pmtu
202 | if initial:
203 | logger.info("%s: initial MTU set to %d." % (self.name, detected_pmtu))
204 | else:
205 | logger.info("%s: MTU set to %d (old value: %d)." % (self.name, detected_pmtu, old_tunnel_mtu))
206 |
207 | # Alter tunnel MTU.
208 | try:
209 | interface_name = (self.get_session_name().encode('utf-8') + b'\x00' * 16)[:16]
210 | data = struct.pack("16si", interface_name, self.tunnel_mtu)
211 | fcntl.ioctl(self.socket, SIOCSIFMTU, data)
212 | except IOError:
213 | logger.warning("%s: Failed to set MTU! Is the interface down?" % self.name)
214 |
215 | self.broker.netlink.session_modify(self.tunnel_id, self.session_id, self.tunnel_mtu)
216 |
217 | if not initial:
218 | # Run MTU changed hook.
219 | self.broker.hook_manager.run_hook(
220 | 'session.mtu-changed',
221 | self.tunnel_id,
222 | self.session_id,
223 | self.get_session_name(),
224 | old_tunnel_mtu,
225 | self.tunnel_mtu,
226 | self.uuid,
227 | )
228 |
229 | def keepalive(self):
230 | """
231 | Handle periodic keepalives.
232 | """
233 |
234 | # Transmit keepalive message. The sequence number is needed because some ISPs (usually cable
235 | # or mobile operators) do some "optimisation" and drop udp packets containing the same content.
236 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_KEEPALIVE, struct.pack('!H', self.keepalive_seqno))
237 | self.keepalive_seqno = (self.keepalive_seqno + 1) % 65536
238 |
239 | # Check if the tunnel is still alive.
240 | if time.time() - self.last_alive > 120:
241 | logger.warning("%s: timed out", self.name)
242 | self.close(reason=protocol.ERROR_REASON_TIMEOUT)
243 |
244 | def error(self, direction, e):
245 | if e.errno == errno.EMSGSIZE:
246 | # ignore these, they occur during PMTU probing
247 | return
248 | super(Tunnel, self).error(direction, e)
249 | # This connection is probably dead, but we've seen connections in the wild that occasionally raise
250 | # an error. So only kill the connection if this happens again and again.
251 | # We could just rely on the timeout, but when there's a lot of errors it seems better to
252 | # kill the connection early rather than waiting for 2 whole minutes.
253 | self.error_count += 1
254 | if self.error_count >= 10:
255 | self.close(reason=protocol.ERROR_REASON_FAILURE)
256 |
257 | def close(self, reason=protocol.ERROR_REASON_UNDEFINED):
258 | """
259 | Closes the tunnel.
260 |
261 | :param reason: Reason code for the tunnel being closed
262 | """
263 |
264 | if self.closing:
265 | # While closing we send messages, and that can fail and we can recursively end up here again.
266 | return
267 | self.closing = True
268 |
269 | logger.info("{}: Closing after {} seconds (reason=0x{:x})".format(self.name, int(time.time() - self.created_time), reason))
270 |
271 | # Run pre-down hook.
272 | self.broker.hook_manager.run_hook(
273 | 'session.pre-down',
274 | self.tunnel_id,
275 | self.session_id,
276 | self.get_session_name(),
277 | self.tunnel_mtu,
278 | self.endpoint[0],
279 | self.endpoint[1],
280 | self.address[1],
281 | self.uuid,
282 | self.broker.address[1],
283 | )
284 |
285 | self.broker.netlink.session_delete(self.tunnel_id, self.session_id)
286 |
287 | # Run down hook.
288 | self.broker.hook_manager.run_hook(
289 | 'session.down',
290 | self.tunnel_id,
291 | self.session_id,
292 | self.get_session_name(),
293 | self.tunnel_mtu,
294 | self.endpoint[0],
295 | self.endpoint[1],
296 | self.address[1],
297 | self.uuid,
298 | self.broker.address[1],
299 | )
300 |
301 | # Transmit error message so the other end can tear down the tunnel
302 | # immediately instead of waiting for keepalive timeout.
303 | reason = protocol.ERROR_REASON_FROM_SERVER | reason
304 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_ERROR, bytearray([reason]))
305 |
306 | super(Tunnel, self).close()
307 |
308 | self.broker.tunnel_manager.destroy_tunnel(self)
309 |
310 | def create_tunnel(self, address, uuid, remote_tunnel_id, client_features):
311 | """
312 | The tunnel may receive a valid create tunnel message in case our previous
313 | response has been lost. In this case, we just need to reply with an identical
314 | control message.
315 | """
316 |
317 | if uuid != self.uuid:
318 | logger.warning("{}: Protocol error: tunnel UUID has changed.".format(self.name))
319 | return False
320 |
321 | if remote_tunnel_id != self.remote_tunnel_id:
322 | logger.warning("{}: Protocol error: tunnel identifier has changed.".format(self.name))
323 | return False
324 |
325 | if client_features != self.client_features:
326 | logger.warning("{}: Protocol error: client features have changed.".format(self.name))
327 | return False
328 |
329 | # Respond with tunnel establishment message.
330 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_TUNNEL, struct.pack('!I', self.tunnel_id))
331 |
332 | return True
333 |
334 | def message(self, address, msg_type, msg_data, raw_length):
335 | """
336 | Called when a new protocol message is received.
337 |
338 | :param address: Source address (host, port) tuple
339 | :param msg_type: Message type
340 | :param msg_data: Message payload
341 | :param raw_length: Length of the raw message (including headers)
342 | """
343 |
344 | if address != self.endpoint:
345 | logger.warning("{}: Protocol error: tunnel endpoint has changed. Possibly due to kernel bug. See: https://github.com/wlanslovenija/tunneldigger/issues/126".format(self.name))
346 | return False
347 |
348 |
349 | if super(Tunnel, self).message(address, msg_type, msg_data, raw_length):
350 | return True
351 |
352 | # Update keepalive indicator.
353 | self.last_alive = time.time()
354 | # We got a message, so *something* is working. Reduce error count for transient error tolerance.
355 | if self.error_count > 0:
356 | self.error_count -= 1
357 |
358 | if msg_type == protocol.CONTROL_TYPE_ERROR:
359 | # Error notification from the remote side.
360 | remote_reason = struct.unpack('!B', msg_data)[0]
361 | logger.warning("{}: got error from remote peer, reason=0x{:x}".format(self.name, remote_reason))
362 | self.close(reason=protocol.ERROR_REASON_OTHER_REQUEST)
363 | return True
364 | elif msg_type == protocol.CONTROL_TYPE_PMTUD:
365 | # The other side is performing PMTU discovery. Only cooperate if automatic MTU discovery is
366 | # enabled for this network.
367 | if self.automatic_pmtu:
368 | pmtu_probe = struct.pack('!H', raw_length)
369 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_PMTUD_ACK, pmtu_probe)
370 | else:
371 | # Don't ACK. The current client just sends the same amount of probes whether it gets a reply or not.
372 | # By remaining silent, we avoid the client ever getting its own idea of what the MTU might be.
373 | # Instead tell it about what the static MTU is so it keeps using that (just in case the previous PMTU_NTFY got lost).
374 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_PMTU_NTFY, struct.pack('!H', self.measured_pmtu))
375 | return True
376 | elif msg_type == protocol.CONTROL_TYPE_PMTUD_ACK:
377 | # The other side is acknowledging a specific PMTU value.
378 | # If self.automatic_pmtu is not set, we did not send any probes, so we should not get here.
379 | pmtu = struct.unpack('!H', msg_data)[0] + IPV4_HDR_OVERHEAD
380 | if self.automatic_pmtu and pmtu > self.pmtu_probe_acked_mtu:
381 | self.pmtu_probe_acked_mtu = pmtu
382 | self.measured_pmtu = pmtu - L2TP_TUN_OVERHEAD
383 | self.update_mtu()
384 |
385 | # Notify the other side of our measured MTU.
386 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_PMTU_NTFY, struct.pack('!H', self.measured_pmtu))
387 |
388 | return True
389 | elif msg_type == protocol.CONTROL_TYPE_PMTU_NTFY:
390 | # The other side is notifying us about their tunnel MTU.
391 | # If self.automatic_pmtu is not set, we did not ACK any of their probes, so we should not get here.
392 | remote_mtu = struct.unpack('!H', msg_data)[0]
393 |
394 | if self.automatic_pmtu and remote_mtu != self.remote_tunnel_mtu:
395 | self.remote_tunnel_mtu = remote_mtu
396 | self.update_mtu()
397 |
398 | return True
399 | elif msg_type == protocol.CONTROL_TYPE_KEEPALIVE:
400 | # Already handled above
401 | return True
402 | elif msg_type & protocol.MASK_CONTROL_TYPE_RELIABLE:
403 | # Acknowledge reliable control messages.
404 | self.write_message(self.endpoint, protocol.CONTROL_TYPE_REL_ACK, msg_data[:2])
405 |
406 | if msg_type == protocol.CONTROL_TYPE_LIMIT:
407 | # Client requests limit configuration.
408 | limit_manager = limits.LimitManager(self)
409 | limit_manager.configure(msg_data[2:])
410 | return True
411 |
412 | return False
413 |
--------------------------------------------------------------------------------
/client/.gitignore:
--------------------------------------------------------------------------------
1 | CMakeCache.txt
2 | CMakeFiles
3 | Makefile
4 | cmake_install.cmake
5 | build
6 | tunneldigger
7 |
--------------------------------------------------------------------------------
/client/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 2.8)
2 | project (tunneldigger C)
3 |
4 | set(USE_LIBNL FALSE CACHE BOOL "Explicitly use libnl over libnl-tiny")
5 | set(USE_LIBNL_TINY FALSE CACHE BOOL "Explicitly use libnl-tiny over libnl")
6 |
7 | find_package(PkgConfig)
8 |
9 | if(USE_LIBNL AND USE_LIBNL_TINY)
10 | message(FATAL_ERROR "libnl and libnl-tiny cannot be used together")
11 | elseif(USE_LIBNL_TINY)
12 | pkg_check_modules(LIBNL REQUIRED libnl-tiny)
13 | elseif(NOT USE_LIBNL)
14 | pkg_check_modules(LIBNL libnl-tiny)
15 | endif()
16 |
17 | if(NOT LIBNL_FOUND OR USE_LIBNL)
18 | pkg_check_modules(LIBNL REQUIRED libnl-3.0 libnl-genl-3.0)
19 | endif()
20 |
21 | pkg_check_modules(LIBASYNCNS libasyncns)
22 | if(LIBASYNCNS_FOUND)
23 | add_definitions("-DUSE_SHARED_LIBASYNCNS=1")
24 | add_executable(tunneldigger l2tp_client.c)
25 | else()
26 | add_executable(tunneldigger l2tp_client.c libasyncns/asyncns.c)
27 | endif()
28 |
29 | include_directories(
30 | ${LIBASYNCNS_INCLUDE_DIRS}
31 | ${LIBNL_INCLUDE_DIRS}
32 | ${LIBNL_TINY_INCLUDE_DIRS}
33 | )
34 |
35 | target_link_libraries(tunneldigger
36 | ${LIBASYNCNS_LIBRARIES}
37 | ${LIBNL_LIBRARIES}
38 | ${LIBNL_TINY_LIBRARIES}
39 | -lpthread
40 | -lresolv
41 | -lrt
42 | )
43 |
44 | install(TARGETS tunneldigger DESTINATION bin)
45 |
--------------------------------------------------------------------------------
/client/libasyncns/asyncns.h:
--------------------------------------------------------------------------------
1 | #ifndef fooasyncnshfoo
2 | #define fooasyncnshfoo
3 |
4 | /***
5 | This file is part of libasyncns.
6 |
7 | Copyright 2005-2008 Lennart Poettering
8 |
9 | libasyncns is free software; you can redistribute it and/or modify
10 | it under the terms of the GNU Lesser General Public License as
11 | published by the Free Software Foundation, either version 2.1 of the
12 | License, or (at your option) any later version.
13 |
14 | libasyncns is distributed in the hope that it will be useful, but
15 | WITHOUT ANY WARRANTY; without even the implied warranty of
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 | Lesser General Public License for more details.
18 |
19 | You should have received a copy of the GNU Lesser General Public
20 | License along with libasyncns. If not, see
21 | .
22 | ***/
23 |
24 | #include
25 | #include
26 | #include
27 |
28 | /** \mainpage
29 | *
30 | * \section moo Method of operation
31 | *
32 | * To use libasyncns allocate an asyncns_t object with
33 | * asyncns_new(). This will spawn a number of worker threads (or processes, depending on what is available) which
34 | * are subsequently used to process the queries the controlling
35 | * program issues via asyncns_getaddrinfo() and
36 | * asyncns_getnameinfo(). Use asyncns_free() to shut down the worker
37 | * threads/processes.
38 | *
39 | * Since libasyncns may fork off new processes you have to make sure that
40 | * your program is not irritated by spurious SIGCHLD signals.
41 | */
42 |
43 | /** \example asyncns-test.c
44 | * An example program */
45 |
46 | #ifdef __cplusplus
47 | extern "C" {
48 | #endif
49 |
50 | /** An opaque libasyncns session structure */
51 | typedef struct asyncns asyncns_t;
52 |
53 | /** An opaque libasyncns query structure */
54 | typedef struct asyncns_query asyncns_query_t;
55 |
56 | /** Allocate a new libasyncns session with n_proc worker processes/threads */
57 | asyncns_t* asyncns_new(unsigned n_proc);
58 |
59 | /** Free a libasyncns session. This destroys all attached
60 | * asyncns_query_t objects automatically */
61 | void asyncns_free(asyncns_t *asyncns);
62 |
63 | /** Return the UNIX file descriptor to select() for readability
64 | * on. Use this function to integrate libasyncns with your custom main
65 | * loop. */
66 | int asyncns_fd(asyncns_t *asyncns);
67 |
68 | /** Process pending responses. After this function is called you can
69 | * get the next completed query object(s) using asyncns_getnext(). If
70 | * block is non-zero wait until at least one response has been
71 | * processed. If block is zero, process all pending responses and
72 | * return. */
73 | int asyncns_wait(asyncns_t *asyncns, int block);
74 |
75 | /** Issue a name to address query on the specified session. The
76 | * arguments are compatible with the ones of libc's
77 | * getaddrinfo(3). The function returns a new query object. When the
78 | * query is completed you may retrieve the results using
79 | * asyncns_getaddrinfo_done().*/
80 | asyncns_query_t* asyncns_getaddrinfo(asyncns_t *asyncns, const char *node, const char *service, const struct addrinfo *hints);
81 |
82 | /** Retrieve the results of a preceding asyncns_getaddrinfo()
83 | * call. Returns a addrinfo structure and a return value compatible
84 | * with libc's getaddrinfo(3). The query object q is destroyed by this
85 | * call and may not be used any further. Make sure to free the
86 | * returned addrinfo structure with asyncns_freeaddrinfo() and not
87 | * libc's freeaddrinfo(3)! If the query is not completed yet EAI_AGAIN
88 | * is returned.*/
89 | int asyncns_getaddrinfo_done(asyncns_t *asyncns, asyncns_query_t* q, struct addrinfo **ret_res);
90 |
91 | /** Issue an address to name query on the specified session. The
92 | * arguments are compatible with the ones of libc's
93 | * getnameinfo(3). The function returns a new query object. When the
94 | * query is completed you may retrieve the results using
95 | * asyncns_getnameinfo_done(). Set gethost (resp. getserv) to non-zero
96 | * if you want to query the hostname (resp. the service name). */
97 | asyncns_query_t* asyncns_getnameinfo(asyncns_t *asyncns, const struct sockaddr *sa, socklen_t salen, int flags, int gethost, int getserv);
98 |
99 | /** Retrieve the results of a preceding asyncns_getnameinfo()
100 | * call. Returns the hostname and the service name in ret_host and
101 | * ret_serv. The query object q is destroyed by this call and may not
102 | * be used any further. If the query is not completed yet EAI_AGAIN is
103 | * returned. */
104 | int asyncns_getnameinfo_done(asyncns_t *asyncns, asyncns_query_t* q, char *ret_host, size_t hostlen, char *ret_serv, size_t servlen);
105 |
106 | /** Issue a resolver query on the specified session. The arguments are
107 | * compatible with the ones of libc's res_query(3). The function returns a new
108 | * query object. When the query is completed you may retrieve the results using
109 | * asyncns_res_done(). */
110 | asyncns_query_t* asyncns_res_query(asyncns_t *asyncns, const char *dname, int class, int type);
111 |
112 | /** Issue an resolver query on the specified session. The arguments are
113 | * compatible with the ones of libc's res_search(3). The function returns a new
114 | * query object. When the query is completed you may retrieve the results using
115 | * asyncns_res_done(). */
116 | asyncns_query_t* asyncns_res_search(asyncns_t *asyncns, const char *dname, int class, int type);
117 |
118 | /** Retrieve the results of a preceding asyncns_res_query() or
119 | * asyncns_res_search call. The query object q is destroyed by this
120 | * call and may not be used any further. Returns a pointer to the
121 | * answer of the res_query call. If the query is not completed yet
122 | * -EAGAIN is returned, on failure -errno is returned, otherwise the
123 | * length of answer is returned. Make sure to free the answer is a
124 | * call to asyncns_freeanswer(). */
125 | int asyncns_res_done(asyncns_t *asyncns, asyncns_query_t* q, unsigned char **answer);
126 |
127 | /** Return the next completed query object. If no query has been
128 | * completed yet, return NULL. Please note that you need to run
129 | * asyncns_wait() before this function will return sensible data. */
130 | asyncns_query_t* asyncns_getnext(asyncns_t *asyncns);
131 |
132 | /** Return the number of query objects (completed or not) attached to
133 | * this session */
134 | int asyncns_getnqueries(asyncns_t *asyncns);
135 |
136 | /** Cancel a currently running query. q is is destroyed by this call
137 | * and may not be used any futher. */
138 | void asyncns_cancel(asyncns_t *asyncns, asyncns_query_t* q);
139 |
140 | /** Free the addrinfo structure as returned by
141 | * asyncns_getaddrinfo_done(). Make sure to use this functions instead
142 | * of the libc's freeaddrinfo()! */
143 | void asyncns_freeaddrinfo(struct addrinfo *ai);
144 |
145 | /** Free the answer data as returned by asyncns_res_done().*/
146 | void asyncns_freeanswer(unsigned char *answer);
147 |
148 | /** Returns non-zero when the query operation specified by q has been completed */
149 | int asyncns_isdone(asyncns_t *asyncns, asyncns_query_t*q);
150 |
151 | /** Assign some opaque userdata with a query object */
152 | void asyncns_setuserdata(asyncns_t *asyncns, asyncns_query_t *q, void *userdata);
153 |
154 | /** Return userdata assigned to a query object. Use
155 | * asyncns_setuserdata() to set this data. If no data has been set
156 | * prior to this call it returns NULL. */
157 | void* asyncns_getuserdata(asyncns_t *asyncns, asyncns_query_t *q);
158 |
159 | #ifdef __cplusplus
160 | }
161 | #endif
162 |
163 | #endif
164 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = _build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
14 |
15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
16 |
17 | help:
18 | @echo "Please use \`make ' where is one of"
19 | @echo " html to make standalone HTML files"
20 | @echo " dirhtml to make HTML files named index.html in directories"
21 | @echo " singlehtml to make a single large HTML file"
22 | @echo " pickle to make pickle files"
23 | @echo " json to make JSON files"
24 | @echo " htmlhelp to make HTML files and a HTML help project"
25 | @echo " qthelp to make HTML files and a qthelp project"
26 | @echo " devhelp to make HTML files and a Devhelp project"
27 | @echo " epub to make an epub"
28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
29 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
30 | @echo " text to make text files"
31 | @echo " man to make manual pages"
32 | @echo " changes to make an overview of all changed/added/deprecated items"
33 | @echo " linkcheck to check all external links for integrity"
34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
35 |
36 | clean:
37 | -rm -rf $(BUILDDIR)/*
38 |
39 | html:
40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
41 | @echo
42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
43 |
44 | dirhtml:
45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
48 |
49 | singlehtml:
50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
51 | @echo
52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
53 |
54 | pickle:
55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
56 | @echo
57 | @echo "Build finished; now you can process the pickle files."
58 |
59 | json:
60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
61 | @echo
62 | @echo "Build finished; now you can process the JSON files."
63 |
64 | htmlhelp:
65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
66 | @echo
67 | @echo "Build finished; now you can run HTML Help Workshop with the" \
68 | ".hhp project file in $(BUILDDIR)/htmlhelp."
69 |
70 | qthelp:
71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
72 | @echo
73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/nodewatcher.qhcp"
76 | @echo "To view the help file:"
77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/nodewatcher.qhc"
78 |
79 | devhelp:
80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
81 | @echo
82 | @echo "Build finished."
83 | @echo "To view the help file:"
84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/nodewatcher"
85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/nodewatcher"
86 | @echo "# devhelp"
87 |
88 | epub:
89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
90 | @echo
91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
92 |
93 | latex:
94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
95 | @echo
96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
98 | "(use \`make latexpdf' here to do that automatically)."
99 |
100 | latexpdf:
101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
102 | @echo "Running LaTeX files through pdflatex..."
103 | make -C $(BUILDDIR)/latex all-pdf
104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
105 |
106 | text:
107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
108 | @echo
109 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
110 |
111 | man:
112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
113 | @echo
114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
115 |
116 | changes:
117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
118 | @echo
119 | @echo "The overview file is in $(BUILDDIR)/changes."
120 |
121 | linkcheck:
122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
123 | @echo
124 | @echo "Link check complete; look for any errors in the above output " \
125 | "or in $(BUILDDIR)/linkcheck/output.txt."
126 |
127 | doctest:
128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
129 | @echo "Testing of doctests in the sources finished, look at the " \
130 | "results in $(BUILDDIR)/doctest/output.txt."
131 |
--------------------------------------------------------------------------------
/docs/client.rst:
--------------------------------------------------------------------------------
1 | Client Installation
2 | ===================
3 |
4 | Getting the Source
5 | ------------------
6 |
7 | Tunneldigger source can be retrieved from its Github repository by running
8 | the following command::
9 |
10 | git clone git://github.com/wlanslovenija/tunneldigger.git
11 |
12 | This will give you a ``tunneldigger`` directory which contains the broker and
13 | the client in separate directories. Client code can be compiled into a
14 | stand-alone program.
15 |
16 | OpenWrt Package
17 | ---------------
18 |
19 | Currently supported way to compile and deploy a client is through an OpenWrt_
20 | package. Source code for such OpenWrt package can be `found here`_.
21 |
22 | .. _found here: https://github.com/wlanslovenija/firmware-packages-opkg/tree/master/net/tunneldigger
23 | .. _OpenWrt: https://openwrt.org/
24 |
25 | You can add the whole repository as an OpenWrt feed and add package to your firmware.
26 |
27 | Configuration
28 | -------------
29 |
30 | * **MAX_BROKERS** (default: 10): Maximum number of brokers that can be handled in a single process.
31 |
32 | make CFLAGS="-D MAX_BROKERS=20"
33 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # documentation build configuration file, created by
4 | # sphinx-quickstart on Sun Oct 16 22:53:14 2011.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #sys.path.insert(0, os.path.abspath('.'))
20 |
21 | # -- General configuration -----------------------------------------------------
22 |
23 | # If your documentation needs a minimal Sphinx version, state it here.
24 | #needs_sphinx = '1.0'
25 |
26 | # Add any Sphinx extension module names here, as strings. They can be extensions
27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
28 | extensions = ['sphinx.ext.intersphinx']
29 |
30 | # Add any paths that contain templates here, relative to this directory.
31 | templates_path = ['_templates']
32 |
33 | # The suffix of source filenames.
34 | source_suffix = '.rst'
35 |
36 | # The encoding of source files.
37 | #source_encoding = 'utf-8-sig'
38 |
39 | # The master toctree document.
40 | master_doc = 'index'
41 |
42 | # General information about the project.
43 | project = u'Tunneldigger'
44 | copyright = u'2012-2016, wlan slovenija'
45 |
46 | # The version info for the project you're documenting, acts as replacement for
47 | # |version| and |release|, also used in various other places throughout the
48 | # built documents.
49 | #
50 | # The short X.Y version.
51 | version = 'latest'
52 | # The full version, including alpha/beta/rc tags.
53 | release = 'latest'
54 |
55 | # The language for content autogenerated by Sphinx. Refer to documentation
56 | # for a list of supported languages.
57 | #language = None
58 |
59 | # There are two options for replacing |today|: either, you set today to some
60 | # non-false value, then it is used:
61 | #today = ''
62 | # Else, today_fmt is used as the format for a strftime call.
63 | #today_fmt = '%B %d, %Y'
64 |
65 | # List of patterns, relative to source directory, that match files and
66 | # directories to ignore when looking for source files.
67 | exclude_patterns = ['_build']
68 |
69 | # The reST default role (used for this markup: `text`) to use for all documents.
70 | #default_role = None
71 |
72 | # If true, '()' will be appended to :func: etc. cross-reference text.
73 | #add_function_parentheses = True
74 |
75 | # If true, the current module name will be prepended to all description
76 | # unit titles (such as .. function::).
77 | #add_module_names = True
78 |
79 | # If true, sectionauthor and moduleauthor directives will be shown in the
80 | # output. They are ignored by default.
81 | #show_authors = False
82 |
83 | # The name of the Pygments (syntax highlighting) style to use.
84 | pygments_style = 'sphinx'
85 |
86 | # A list of ignored prefixes for module index sorting.
87 | #modindex_common_prefix = []
88 |
89 |
90 | # -- Options for HTML output ---------------------------------------------------
91 |
92 | # The theme to use for HTML and HTML Help pages. See the documentation for
93 | # a list of builtin themes.
94 | html_theme = 'default'
95 |
96 | # Theme options are theme-specific and customize the look and feel of a theme
97 | # further. For a list of options available for each theme, see the
98 | # documentation.
99 | #html_theme_options = {}
100 |
101 | # Add any paths that contain custom themes here, relative to this directory.
102 | #html_theme_path = []
103 |
104 | # The name for this set of Sphinx documents. If None, it defaults to
105 | # " v documentation".
106 | #html_title = None
107 |
108 | # A shorter title for the navigation bar. Default is the same as html_title.
109 | #html_short_title = None
110 |
111 | # The name of an image file (relative to this directory) to place at the top
112 | # of the sidebar.
113 | #html_logo = None
114 |
115 | # The name of an image file (within the static path) to use as favicon of the
116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
117 | # pixels large.
118 | #html_favicon = None
119 |
120 | # Add any paths that contain custom static files (such as style sheets) here,
121 | # relative to this directory. They are copied after the builtin static files,
122 | # so a file named "default.css" will overwrite the builtin "default.css".
123 | html_static_path = ['_static']
124 |
125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
126 | # using the given strftime format.
127 | #html_last_updated_fmt = '%b %d, %Y'
128 |
129 | # If true, SmartyPants will be used to convert quotes and dashes to
130 | # typographically correct entities.
131 | #html_use_smartypants = True
132 |
133 | # Custom sidebar templates, maps document names to template names.
134 | #html_sidebars = {}
135 |
136 | # Additional templates that should be rendered to pages, maps page names to
137 | # template names.
138 | #html_additional_pages = {}
139 |
140 | # If false, no module index is generated.
141 | #html_domain_indices = True
142 |
143 | # If false, no index is generated.
144 | #html_use_index = True
145 |
146 | # If true, the index is split into individual pages for each letter.
147 | #html_split_index = False
148 |
149 | # If true, links to the reST sources are added to the pages.
150 | #html_show_sourcelink = True
151 |
152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
153 | html_show_sphinx = False
154 |
155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
156 | html_show_copyright = False
157 |
158 | # If true, an OpenSearch description file will be output, and all pages will
159 | # contain a tag referring to it. The value of this option must be the
160 | # base URL from which the finished HTML is served.
161 | #html_use_opensearch = ''
162 |
163 | # This is the file name suffix for HTML files (e.g. ".xhtml").
164 | #html_file_suffix = None
165 |
166 | # Output file base name for HTML help builder.
167 | htmlhelp_basename = 'tunneldiggerdoc'
168 |
169 |
170 | # -- Options for LaTeX output --------------------------------------------------
171 |
172 | # The paper size ('letter' or 'a4').
173 | #latex_paper_size = 'letter'
174 |
175 | # The font size ('10pt', '11pt' or '12pt').
176 | #latex_font_size = '10pt'
177 |
178 | # Grouping the document tree into LaTeX files. List of tuples
179 | # (source start file, target name, title, author, documentclass [howto/manual]).
180 | latex_documents = [
181 | ('index', 'tunneldigger.tex', u'Tunneldigger Documentation',
182 | u'wlan slovenija', 'manual'),
183 | ]
184 |
185 | # The name of an image file (relative to this directory) to place at the top of
186 | # the title page.
187 | #latex_logo = None
188 |
189 | # For "manual" documents, if this is true, then toplevel headings are parts,
190 | # not chapters.
191 | #latex_use_parts = False
192 |
193 | # If true, show page references after internal links.
194 | #latex_show_pagerefs = False
195 |
196 | # If true, show URL addresses after external links.
197 | #latex_show_urls = False
198 |
199 | # Additional stuff for the LaTeX preamble.
200 | #latex_preamble = ''
201 |
202 | # Documents to append as an appendix to all manuals.
203 | #latex_appendices = []
204 |
205 | # If false, no module index is generated.
206 | #latex_domain_indices = True
207 |
208 |
209 | # -- Options for manual page output --------------------------------------------
210 |
211 | # One entry per manual page. List of tuples
212 | # (source start file, name, description, authors, manual section).
213 | man_pages = [
214 | ('index', 'tunneldigger', u'Tunneldigger Documentation',
215 | [u'wlan slovenija'], 1)
216 | ]
217 |
218 |
219 | # Example configuration for intersphinx: refer to the Python standard library.
220 | intersphinx_mapping = {
221 | 'python': ('http://python.readthedocs.org/en/latest/', None),
222 | }
223 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | Tunneldigger documentation
2 | ==========================
3 |
4 | Tunneldigger is one of the projects of `wlan slovenija`_ open wireless network.
5 | It is a simple VPN tunneling solution based on the Linux kernel support for
6 | L2TPv3 tunnels over UDP.
7 |
8 | .. _wlan slovenija: https://wlan-si.net
9 |
10 | Tunneldigger consists of a client and a server portion.
11 |
12 | The client is written in C for minimal binary size and optimized to run on
13 | embedded devices such as wireless routers running OpenWrt_.
14 |
15 | .. _OpenWrt: https://openwrt.org
16 |
17 | The server portion, referred to as the broker, is written in Python.
18 |
19 | Contents
20 | --------
21 |
22 | .. toctree::
23 | :maxdepth: 2
24 |
25 | server
26 | client
27 |
28 | Source Code and Issue Tracker
29 | -----------------------------
30 |
31 | Development happens on GitHub_ and issues can be filed in the `Issue tracker`_.
32 |
33 | .. _GitHub: https://github.com/wlanslovenija/tunneldigger
34 | .. _Issue tracker: https://github.com/wlanslovenija/tunneldigger/issues
35 |
36 | License
37 | -------
38 |
39 | Tunneldigger is licensed under AGPLv3_.
40 |
41 | .. _AGPLv3: https://www.gnu.org/licenses/agpl-3.0.en.html
42 |
43 | Contributions
44 | -------------
45 |
46 | We welcome code and documentation contributions to Tunneldigger in the form of
47 | `Pull Requests`_ on GitHub where they can be reviewed and discussed by the
48 | community.
49 | We encourage everyone to check out any pending pull requests and offer comments
50 | or ideas as well.
51 |
52 | .. _Pull Requests: https://github.com/wlanslovenija/tunneldigger/pulls
53 |
54 | Tunneldigger is developed by a community of developers from many different
55 | backgrounds.
56 |
57 | You can visualize all code contributions using `GitHub Insights`_.
58 |
59 | .. _GitHub Insights: https://github.com/wlanslovenija/tunneldigger/graphs/contributors
60 |
61 | Indices and Tables
62 | ==================
63 |
64 | * :ref:`genindex`
65 | * :ref:`search`
66 |
67 | Related Work
68 | ============
69 |
70 | * `German Tunneldigger Tutorial by Freifunk Franken `__
71 |
72 |
--------------------------------------------------------------------------------
/docs/server.rst:
--------------------------------------------------------------------------------
1 | Server (Broker) Installation
2 | ============================
3 |
4 | The installation of Tunneldigger's server side (broker) is pretty straightforward and is
5 | described in the following sections.
6 |
7 | OpenWrt Package
8 | ---------------
9 |
10 | If you want to run Tunneldigger's server side on OpenWrt_, you can use the `opkg package`_.
11 |
12 | .. _opkg package: https://github.com/wlanslovenija/firmware-packages-opkg/tree/master/net/tunneldigger-broker
13 | .. _OpenWrt: https://openwrt.org/
14 |
15 | You can add the whole repository as an OpenWrt feed and add package to your firmware.
16 |
17 | Getting the Source
18 | ------------------
19 |
20 | If you want to run Tunneldigger from source, it can be retrieved from its GitHub
21 | repository by running the following command::
22 |
23 | git clone git://github.com/wlanslovenija/tunneldigger.git
24 |
25 | This will give you a ``tunneldigger`` directory which contains the broker
26 | and the client in separate directories. Server installations only need
27 | the broker.
28 |
29 | .. warning::
30 | ``master`` branch is not necessary stable and you should not be using it in production.
31 | Instead, use the latest release. See history_ for the list of changes.
32 |
33 | .. _history: https://github.com/wlanslovenija/tunneldigger/blob/master/HISTORY.rst
34 |
35 | Operating System
36 | ----------------
37 |
38 | The first thing you need is a recent (>= 5.2.17, 5.3.1, 5.4+) Linux kernel that supports L2TPv3
39 | tunnels. You can find out your linux kernel version using the command ``uname -a``.
40 | Older kernels unfortunately have a bug that makes them `not work properly`_. For those kernel,
41 | we are maintaining the `legacy branch`_.
42 |
43 | .. _not work properly: https://github.com/wlanslovenija/tunneldigger/issues/126
44 | .. _legacy branch: https://github.com/wlanslovenija/tunneldigger/tree/legacy
45 |
46 | We assume the following instructions to work on the distributions listed below.
47 | You are welcome to add your distribution if the instructions work and to edit them to make them work.
48 |
49 | * Debian
50 | * Fedora with the package ``kernel-modules-extra``
51 | * OpenWrt with the package ``tunneldigger-broker`` in the packages repo
52 | * *add your distribution*
53 |
54 | Kernel Modules
55 | --------------
56 |
57 | The following modules are required for Tunneldigger operation:
58 |
59 | * ``l2tp_core``
60 | * ``l2tp_eth``
61 | * ``l2tp_netlink``
62 |
63 | .. note::
64 |
65 | Fedora and RHEL/CentOS blacklist some of these modules by default for security reasons.
66 | Ensure you remove the blacklisting from ``/etc/modprobe.d/l2tp_eth-blacklist.conf`` and ``/etc/modprobe.d/l2tp_netlink-blacklist.conf``.
67 |
68 | Kernel Module Activation on Boot
69 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
70 |
71 | For the activation of the kernel modules, we recommend adding a file
72 | ``/etc/modules-load.d/tunneldigger.conf`` with the following content:
73 |
74 | .. code:: shell
75 |
76 | l2tp_core
77 | l2tp_eth
78 | l2tp_netlink
79 |
80 | Manual Activation of the Kernel Modules
81 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
82 |
83 | You can also activate the modules using ``modprobe``.
84 | A system restart will *not* load the modules again if you do not create the file as described above.
85 |
86 | .. code:: shell
87 |
88 | $ sudo modprobe l2tp_core
89 | $ sudo modprobe l2tp_eth
90 | $ sudo modprobe l2tp_netlink
91 |
92 | Check if Modules are Loaded
93 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
94 |
95 | You can find out if these modules are loaded by running ``lsmod | grep l2tp``.
96 | If you get no output, they are not activated.
97 | If the modules were loaded successfully,
98 | your listing of the modules might look like this:
99 |
100 | .. code:: shell
101 |
102 | $ lsmod | grep l2tp
103 | l2tp_eth 16384 0
104 | l2tp_netlink 24576 1 l2tp_eth
105 | l2tp_core 32768 2 l2tp_eth,l2tp_netlink
106 | ip6_udp_tunnel 16384 1 l2tp_core
107 | udp_tunnel 16384 1 l2tp_core
108 |
109 | System Packages
110 | ---------------
111 |
112 | Also the following Debian packages are required:
113 |
114 | * ``iproute``
115 | * ``bridge-utils``
116 | * ``python-dev``
117 | * ``libevent-dev``
118 |
119 | If you would like to use the already supplied hook scripts to setup the network
120 | interfaces, you also need the following packages:
121 |
122 | * ``ebtables``
123 |
124 | Since ``ebtables`` is also a kernel module, please activate it as described
125 | in the `Kernel Modules`_ Section.
126 |
127 | Note that the best way to run any Python software is in a virtual environment
128 | (virtualenv_), so the versions you have installed on your base system should
129 | not affect the versions that are installed for Tunneldigger.
130 |
131 | .. _virtualenv: http://pypi.python.org/pypi/virtualenv
132 |
133 | You can install all of the above simply by running on Debian::
134 |
135 | sudo apt-get install iproute bridge-utils python-dev libevent-dev ebtables python-virtualenv
136 |
137 | and for Fedora you can use this command::
138 |
139 | sudo yum install iproute bridge-utils python-devel libevent-devel ebtables libnl-devel python-pip python-virtualenv
140 |
141 | Installation
142 | ------------
143 |
144 | If we assume that you are installing Tunneldigger under ``/srv/tunneldigger``
145 | (the scripts provided with Tunneldigger assume that as well), you can do::
146 |
147 | cd /srv/tunneldigger
148 | virtualenv -p /usr/bin/python3 env_tunneldigger
149 |
150 | .. note::
151 | Tunneldigger only supports Python 3.
152 |
153 | Using the above command ensures the virtualenv is created using a Python 3 interpreter.
154 | In case the Python 3 interpreter you would like to use is not located at ``/usr/bin/python3`` you will have to adjust the path accordingly.
155 | If your distribution uses Python 3 by default you can usually omit the ``-p`` parameter.
156 |
157 | This creates a virtual Python environment in the ``env_tunneldigger`` folder. This
158 | folder can be deleted and recreated as needed using the virtualenv command, should this be required.
159 | You can then checkout the Tunneldigger repository into ``/srv/tunneldigger/tunneldigger`` by doing::
160 |
161 | cd /srv/tunneldigger
162 | git clone https://github.com/wlanslovenija/tunneldigger.git
163 |
164 | Next you have to enter the environment and install the broker alongside its dependencies::
165 |
166 | source env_tunneldigger/bin/activate
167 | pip install tunneldigger/broker
168 |
169 | Configuration
170 | -------------
171 |
172 | The broker must be given a configuration file as first argument, an example of
173 | which is provided in ``l2tp_broker.cfg.example``. There are some options that must be
174 | changed and some that can be left as default:
175 |
176 | * **address** should be configured with the external IP address that the clients will use to connect with the broker.
177 |
178 | * **port** should be configured with the external port (or ports separated by commas) that the clients will use to connect with the broker.
179 |
180 | * **interface** should be configured with the name of the external interface that the clients will connect to.
181 |
182 | * Hooks in the **hooks** section should be configured with paths to executable scripts that will be called when certain events occur in the broker. They are empty by default which means that tunnels will be established but they will not be configured.
183 |
184 | Hook scripts that actually perform interface setup. Examples that we use in
185 | production in *wlan slovenija* network are provided under the ``scripts/``
186 | directory. The configuration file must contain absolute paths to the hook
187 | scripts and the scripts must have the executable bit set.
188 |
189 | Hooks
190 | `````
191 |
192 | There are currently four different hooks, namely:
193 |
194 | * ``session.up`` is called after the tunnel interface has been created by the broker and is ready for configuration at
195 | the higher layers. (Example of such a script is found under ``scripts/session.up.sh``.)
196 |
197 | * ``session.pre-down`` is called just before the tunnel interface is going to be removed by the broker.
198 | Notice that hooks are executed asynchonously, so by the time this script runs, the interface may already be gone.
199 | Thus you probably want to use `session.down` instead.
200 |
201 | * ``session.down`` is called after the tunnel interface has been destroyed and is no longer available.
202 | (Example is found under ``scripts/session.down.sh``.)
203 |
204 | * ``session.mtu-changed`` is called after the broker's path MTU discovery determines that the tunnel's MTU has changed
205 | and should be adjusted. (Example is found under ``scripts/mtu_changed.sh``.)
206 |
207 | * ``broker.connection-rate-limit`` is called when a IP address tries to connect ``connection_rate_limit_per_ip_count``
208 | times within ``connection_rate_limit_per_ip_time`` seconds. (Example is found under ``scripts/broker.connection-rate-limit.sh``.)
209 |
210 | Please look at all the example hook scripts carefully and try to understand
211 | them before use. They should be considered configuration and some things in
212 | them are hardcoded for our deployment. You will probably have some different
213 | network configuration and so you should modify the scripts to suit your setup.
214 | The examples also document the command-line argument passed to the hooks.
215 |
216 | Example hook scripts present in the ``scripts/`` subdirectory are set up to
217 | create one bridge device per MTU and attach L2TP interfaces to these bridges.
218 | They also configure a default IP address to newly created tunnels, set up
219 | ``ebtables`` to isolate bridge ports and update the routing policy via ``ip
220 | rule`` so traffic from these interfaces is routed via the ``mesh`` routing
221 | table.
222 |
223 | * Each tunnel established with the broker will create its own interface. Because we are using OLSRv1, we cannot
224 | dynamically add interfaces to it, so we group tunnel interfaces into bridges.
225 |
226 | * We could put all tunnel interfaces into the same bridge, but this would actually create a performance problem.
227 | Different tunnels can have different MTU values -- but there is only one MTU value for the bridge, the minimum of
228 | all interfaces that are attached to that bridge. To avoid this problem, we create multiple bridges, one for each MTU
229 | value -- this is what the example scripts do.
230 |
231 | * We also configure some ``ip`` policy rules to ensure that traffic coming in from the bridges gets routed via our
232 | ``mesh`` routing table and not the main one (see ``bridge_functions.sh``). Traffic between bridge ports is not
233 | forwarded (this is achieved via ``ebtables)``, otherwise the routing daemons at the nodes would think that all of
234 | them are directly connected -- which would cause them to incorrectly see a very large 1-hop neighbourhood. This
235 | file also contains broker-side IP configuration for the bridge which should really be changed.
236 |
237 | Note that you do not actually need to have the same configuration, this is just
238 | something that we are using at the moment in *wlan slovenija* network. The
239 | scripts should be very flexible and you can configure them to do anything you
240 | want/need.
241 |
242 | Routing Daemon
243 | ''''''''''''''
244 |
245 | The example hook scripts require that the routing daemon (like ``olsrd``) be
246 | configured with the Tunneldigger bridge interfaces.
247 |
248 | Running
249 | -------
250 |
251 | After you configured Tunneldigger, you can run the broker::
252 |
253 | cd /srv/tunneldigger
254 | /srv/env_tunneldigger/bin/python -m tunneldigger_broker.main /srv/tunneldigger/broker/l2tp_broker.cfg
255 |
--------------------------------------------------------------------------------
/docs/wireshark-tunneldigger.lua:
--------------------------------------------------------------------------------
1 |
2 | tunneldigger = Proto("TD", "Tunneldigger")
3 |
4 | local types = { [0] = "INVALID",
5 | [1] = "COOKIE",
6 | [2] = "PREPARE",
7 | [3] = "ERROR",
8 | [4] = "TUNNEL",
9 | [5] = "KEEPALIVE",
10 | [6] = "PMTUD",
11 | [7] = "PMTUD_ACK",
12 | [8] = "REL_ACK",
13 | [9] = "PMTU_NTFY",
14 | [0xA] = "USAGE",
15 | [0x80] = "LIMIT"}
16 |
17 | local limit_types = { [1] = "BANDWIDTH_DOWN" }
18 |
19 | local f_magic1 = ProtoField.uint8("tunneldigger.magic1", "Magic1")
20 | local f_magic2 = ProtoField.uint16("tunneldigger.magic2", "Magic2")
21 | local f_version = ProtoField.uint8("tunneldigger.version", "Version")
22 | local f_type = ProtoField.uint8("tunneldigger.type", "Type", nil, types)
23 | local f_payload_len = ProtoField.uint8("tunneldigger.payload_len", "PayloadLength")
24 | local f_payload = ProtoField.bytes("tunneldigger.payload", "Payload")
25 | local f_padding = ProtoField.bytes("tunneldigger.padding", "Padding")
26 | local f_cookie = ProtoField.bytes("tunneldigger.cookie", "Cookie")
27 | local f_uuid = ProtoField.string("tunneldigger.uuid", "UUID")
28 | local f_uuid_len = ProtoField.uint8("tunneldigger.uuid_len", "Length of UUID")
29 | local f_pmtud = ProtoField.bytes("tunneldigger.pmtud_ack", "Path MTU Discovery Random Data")
30 | local f_pmtud_ack = ProtoField.uint16("tunneldigger.pmtud_ack", "Path MTU Discovery Ack Size")
31 | local f_tunnel_id = ProtoField.uint32("tunneldigger.tunnel_id", "Tunnel ID")
32 | local f_seq_no = ProtoField.uint8("tunneldigger.seq_no", "Sequence Number")
33 | local f_limit_type = ProtoField.uint8("tunneldigger.limit_type", "Type of Limit", nil, limit_types)
34 | local f_limit_bandwidth = ProtoField.uint32("tunneldigger.bandwidth", "Bandwidth")
35 | local f_limit_bandwidth_len = ProtoField.uint8("tunneldigger.bandwidth_len", "Length of Bandwidth")
36 | local f_usage = ProtoField.uint8("tunneldigger.usage", "Usage of Server")
37 | tunneldigger.fields = { f_magic1, f_magic2, f_version, f_type, f_payload_len, f_payload, f_padding, f_cookie, f_pmtud, f_pmtud_ack, f_uuid_len, f_uuid, f_tunnel_id, f_seq_no, f_limit_type, f_limit_bandwidth, f_limit_bandwidth_len, f_usage}
38 |
39 |
40 | function tunneldigger.dissector(buffer, pinfo, tree)
41 |
42 | local type_detail = {}
43 | type_detail["COOKIE"] = {}
44 | type_detail["PREPARE"] = 0x02
45 | type_detail["SCANRESP"] = {[0] = "mac", [1] = "data", [2]="flag"}
46 | type_detail["ERROR"] = 0x03
47 | type_detail["TUNNEL"] = 0x04
48 | type_detail["KEEPALIVE"] = 0x05
49 | type_detail["PMTUD"] = 0x06
50 | type_detail["PMTUD_ACK"] = 0x07
51 | type_detail["REL_ACK"] = 0x08
52 | type_detail["PMTU_NTFY"] = 0x09
53 | type_detail["USAGE"] = 0x0A
54 |
55 | --- check if header is to small
56 | if buffer:len() < 6 then
57 | return
58 | end
59 |
60 | local l2tp_type = buffer(0, 1):uint()
61 | local td_type = buffer(4, 1):uint()
62 | local payload_len = buffer(5, 1):uint()
63 |
64 | if l2tp_type ~= 0x80 then
65 | -- give it to l2tp
66 | local udp_table = DissectorTable.get("udp.port")
67 | local l2tp_dis = udp_table:get_dissector(1701)
68 | l2tp_dis:call(buffer, pinfo, tree)
69 | return
70 | end
71 |
72 | pinfo.cols.protocol = "TD"
73 |
74 | local subtree = tree:add(tunneldigger, buffer(), "Tunneldigger")
75 | subtree:add(f_magic1, buffer(0, 1))
76 | subtree:add(f_magic2, buffer(1, 2))
77 | subtree:add(f_version, buffer(3, 1))
78 | subtree:add(f_type, buffer(4, 1))
79 | subtree:add(f_payload_len, buffer(5, 1))
80 |
81 | if buffer:len() < (6 + payload_len) then
82 | pinfo.cols.info = string.format("%s - Package too small.", types[td_type])
83 | return
84 | else
85 | pinfo.cols.info = types[td_type]
86 | end
87 |
88 | local detail = type_detail[types[td_type]]
89 | if types[td_type] == "COOKIE" then
90 | subtree:add(f_cookie, buffer(6, 8))
91 | elseif types[td_type] == "PMTUD" then
92 | subtree:add(f_pmtud, buffer(6, payload_len))
93 | elseif types[td_type] == "PMTUD_ACK" then
94 | subtree:add(f_pmtud_ack, buffer(6, 2))
95 | elseif types[td_type] == "PREPARE" then
96 | local uuid_len = buffer(14, 1):uint()
97 | subtree:add(f_cookie, buffer(6, 8))
98 | subtree:add(f_uuid_len, buffer(14, 1))
99 | subtree:add(f_uuid, buffer(15, uuid_len))
100 | elseif types[td_type] == "TUNNEL" then
101 | subtree:add(f_tunnel_id, buffer(6, 4))
102 | elseif types[td_type] == "USAGE" then
103 | subtree:add(f_usage, buffer(6, 2))
104 | elseif types[td_type] == "LIMIT" then
105 | --- seq no comes from RELIABLE_MESSAGE
106 | subtree:add(f_seq_no, buffer(6, 2))
107 | subtree:add(f_limit_type, buffer(8, 1))
108 | if limit_types[buffer(8, 1):uint()] == "BANDWIDTH_DOWN" then
109 | subtree:add(f_limit_bandwidth_len, buffer(9, 1))
110 | --- Bandwidth should be always 4 byte long
111 | --- TODO: add a warning here
112 | subtree:add(f_limit_bandwidth, buffer(10, 4))
113 | pinfo.cols.info = string.format("%s to %d kbps", pinfo.cols.info, buffer(10, 4):uint())
114 | end
115 | else
116 | if payload_len > 0 then
117 | subtree:add(f_payload, buffer(6, payload_len))
118 | end
119 | end
120 |
121 | if buffer:len() > (6 + payload_len) then
122 | subtree:add(f_padding, buffer(6 + payload_len, buffer:len() - (6 + payload_len)))
123 | end
124 | end
125 |
126 | udp_table = DissectorTable.get("udp.port")
127 | udp_table:add(8942, tunneldigger)
128 |
--------------------------------------------------------------------------------
/tests/.gitignore:
--------------------------------------------------------------------------------
1 | .vagrant
2 | ubuntu-*.log
3 |
--------------------------------------------------------------------------------
/tests/README.md:
--------------------------------------------------------------------------------
1 | # testing tunneldigger
2 |
3 | The automatic testing with tunneldigger uses lxc container and the python3 api of lxc.
4 |
5 | ## Vagrantfile
6 |
7 | The test setup was tested with Ubuntu Focal; you can use the Vagrantfile to set that up.
8 |
9 | ```shell
10 | vagrant up
11 | vagrant ssh
12 | # Inside the VM:
13 | sudo su
14 | cd /tunneldigger/tests
15 | ./tunneldigger.py --setup focal
16 | CLIENT_REV=HEAD SERVER_REV=HEAD nosetests3 test_nose.py
17 | ```
18 |
19 | ## Setup the environment
20 |
21 | ```./tunneldigger.py --setup```
22 |
23 | will setup the lxc environment and create a snapshot which is used by all tests.
24 | The resulting container is named tunneldigger-base.
25 |
26 |
27 | ## Do a test run
28 |
29 | A test run requires you have setted up the environment.
30 | ```./tunneldigger.py -t -s HEAD -c HEAD```
31 |
32 | will do a test run using HEAD for the server and the client.
33 |
34 | ## What does a test run?
35 |
36 | * generate a build hash
37 | * checkout the repository
38 | * clone containers based on container `tunneldigger-base`, naming them `hash_client` and `hash_server`
39 | * start the scripts `prepare_client.sh` and `prepare_server.sh` in their containers
40 | * start the scripts `run_client.sh` and `run_server.sh`
41 | * do a simple `wget` test
42 |
43 | ## Files
44 |
45 | * travis.sh - entrypoint for travis tests
46 | * jenkins.sh - entrypoint for jenkins tests
47 |
48 | * hook_client.sh - hook for the client to configure the interface ip
49 | * hook_server - hooks for the server. add/remove the interface to the bridge
50 |
51 | * prepare_client.sh - locally checkout the client and compiles it
52 | * prepare_server.sh - do network configuration, install dependencies(pip) and builds the server
53 |
54 | * run_client.sh - starts the client
55 | * run_server.sh - starts the server
56 |
57 | * test-data - empty dir used by tests to put test-data like big files for download-testing into it
58 | * test_nose.py - nose test cases
59 | * tunneldigger.py - LXC logic and basic test logic (no tests)
60 |
61 | ## Future
62 |
63 | * clean up environment if the test fails (stop containers + remove them)
64 |
--------------------------------------------------------------------------------
/tests/Vagrantfile:
--------------------------------------------------------------------------------
1 | # -*- mode: ruby -*-
2 | # vi: set ft=ruby :
3 |
4 | # All Vagrant configuration is done below. The "2" in Vagrant.configure
5 | # configures the configuration version (we support older styles for
6 | # backwards compatibility). Please don't change it unless you know what
7 | # you're doing.
8 | Vagrant.configure("2") do |config|
9 | # The most common configuration options are documented and commented below.
10 | # For a complete reference, please see the online documentation at
11 | # https://docs.vagrantup.com.
12 |
13 | # Every Vagrant development environment requires a box. You can search for
14 | # boxes at https://vagrantcloud.com/search.
15 | config.vm.box = "ubuntu/focal64"
16 | config.vm.synced_folder "../", "/tunneldigger"
17 |
18 | config.vm.provision "shell", inline: <<-SHELL
19 | apt-get update
20 | apt-get install -y lxc python3-lxc python3-nose linux-modules-extra-$(uname -r)
21 | SHELL
22 |
23 | config.vm.define "tunneldigger"
24 | end
25 |
--------------------------------------------------------------------------------
/tests/hook_client.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | HOOK=$1
4 | DEV=$2
5 |
6 | if [ "$HOOK" = "session.up" ] ; then
7 | ip a a 192.168.254.2/24 dev $DEV
8 | ip l s $DEV up
9 | fi
10 |
--------------------------------------------------------------------------------
/tests/hook_server/bridge_functions.sh:
--------------------------------------------------------------------------------
1 | ensure_policy()
2 | {
3 | ip rule del $*
4 | ip rule add $*
5 | }
6 |
7 | ensure_bridge()
8 | {
9 | local brname="$1"
10 | brctl addbr $brname 2>/dev/null
11 |
12 | if [[ "$?" == "0" ]]; then
13 | # Bridge did not exist before, we have to initialize it
14 | ip link set dev $brname up
15 | # Disable forwarding between bridge ports
16 | ebtables -A FORWARD --logical-in $brname -j DROP
17 | fi
18 | }
19 |
20 |
--------------------------------------------------------------------------------
/tests/hook_server/mtu_changed.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | TUNNEL_ID="$1"
3 | INTERFACE="$3"
4 | OLD_MTU="$4"
5 | NEW_MTU="$5"
6 |
7 | . $(dirname $0)/bridge_functions.sh
8 |
9 | # Remove interface from old bridge
10 | brctl delif br0 $INTERFACE
11 |
12 | # Change interface MTU
13 | ip link set dev $INTERFACE mtu $NEW_MTU
14 |
15 | # Add interface to new bridge
16 | ensure_bridge br0
17 | brctl addif br0 $INTERFACE
18 |
19 |
--------------------------------------------------------------------------------
/tests/hook_server/setup_interface.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | TUNNEL_ID="$1"
3 | INTERFACE="$3"
4 | MTU="$4"
5 |
6 | . $(dirname $0)/bridge_functions.sh
7 |
8 | # Set the interface to UP state
9 | ip link set dev $INTERFACE up mtu $MTU
10 |
11 | # Add the interface to our bridge
12 | ensure_bridge br0
13 | brctl addif br0 $INTERFACE
14 |
15 |
--------------------------------------------------------------------------------
/tests/hook_server/teardown_interface.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | TUNNEL_ID="$1"
3 | INTERFACE="$3"
4 | MTU="$4"
5 |
6 | # Remove the interface from our bridge
7 | brctl delif br0 $INTERFACE
8 |
9 |
--------------------------------------------------------------------------------
/tests/lib_ci.sh:
--------------------------------------------------------------------------------
1 | # included by jenkins.sh and travis.sh
2 | #
3 | # 2016 Alexander Couzens
4 |
5 | export WORKSPACE=$PWD
6 |
7 | fail() {
8 | echo -e "$@" >&2
9 | exit 1
10 | }
11 |
12 | function begingroup {
13 | echo "::group::$@"
14 | set -x
15 | }
16 |
17 | function endgroup {
18 | set +x
19 | echo "::endgroup"
20 | }
21 |
22 | setup_container() {
23 | /usr/bin/env python --version
24 | begingroup "Preparing LXC container template"
25 | if ! $WORKSPACE/tests/tunneldigger.py --setup focal ; then
26 | fail "While compiling the setup"
27 | fi
28 | endgroup
29 | }
30 |
31 | test_client_compile() {
32 | # compile test the l2tp client
33 | echo "Try to compile the l2tp client"
34 | cd $WORKSPACE/client/
35 | if [ -f CMakeLists.txt ]; then
36 | if ! cmake . ; then
37 | fail "Failed while preparing the client with cmake"
38 | fi
39 | else
40 | sed -i 's/-lnl/-lnl-3 -lnl-genl-3/g' Makefile
41 | sed -i 's#-I.#-I. -I/usr/include/libnl3 -DLIBNL_TINY#g' Makefile
42 | fi
43 | if ! make VERBOSE=1 ; then
44 | fail "Failed while compiling the client"
45 | fi
46 | }
47 |
48 | test_nose() {
49 | local old_rev=$(git rev-parse $1)
50 | local new_rev=$(git rev-parse $2)
51 |
52 | cd $WORKSPACE/tests/
53 | begingroup "Old client, new server"
54 | if ! CLIENT_REV=$old_rev SERVER_REV=$new_rev nosetests3 --nocapture test_nose.py ; then
55 | fail "while running test_nose cli <> server.\nclient: '$old_rev'\nserver: '$new_rev'"
56 | fi
57 | endgroup
58 | begingroup "Old server, new client"
59 | if ! CLIENT_REV=$new_rev SERVER_REV=$old_rev nosetests3 --nocapture test_nose.py ; then
60 | fail "while running test_nose cli <> server.\nclient: '$new_rev'\nserver: '$old_rev'"
61 | fi
62 | endgroup
63 | }
64 |
65 | test_usage() {
66 | local new_rev=$(git rev-parse $1)
67 |
68 | cd $WORKSPACE/tests/
69 | begingroup "Running usage test"
70 | if ! CLIENT_REV=$new_rev nosetests3 --nocapture test_usage.py ; then
71 | fail "while running usage tests."
72 | fi
73 | endgroup
74 | }
75 |
--------------------------------------------------------------------------------
/tests/prepare_client.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # fail when something fails
4 | set -e
5 |
6 | # checkout the repo
7 | cd /srv
8 | git clone /git_repo tunneldigger
9 | cd /srv/tunneldigger
10 | git checkout "$1"
11 |
12 | cd /srv/tunneldigger/client
13 | if [ -f CMakeLists.txt ]; then
14 | cmake .
15 | make VERBOSE=1
16 | else
17 | # patch makefile as needed...
18 | sed -i 's/-Werror//g' Makefile
19 | sed -i 's/-lnl/-lnl-3 -lnl-genl-3/g' Makefile
20 | sed -i 's#-I.#-I. -I/usr/include/libnl3 -DLIBNL_TINY#g' Makefile
21 | make
22 | fi
23 |
--------------------------------------------------------------------------------
/tests/prepare_server.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # checkout the repo
4 | cd /srv
5 | git clone /git_repo tunneldigger
6 | cd /srv/tunneldigger
7 | git checkout "$1"
8 |
9 | # setup bridge
10 | # 192.168.254.1 is the hard-coded IP of each server inside the tunnel
11 | brctl addbr br0
12 | ip a a 192.168.254.1/24 dev br0
13 | ip l s br0 up
14 |
15 | # determine listening ip (picked by setup_module in test_nose.py)
16 | echo "This should show eth0 and eth1:"
17 | ip addr
18 | echo
19 | # can't hard-code this; for usage tests we have servers in different IPs!
20 | IP=$(ip -4 -o a s dev eth1 | awk '{ print $4 }' | awk -F/ '{print $1}')
21 |
22 | # setup http server
23 | cat > /tmp/lighttpd.conf < /ip.txt
65 |
66 | # WARNING hookpath must be without a leading slash!!!
67 | HOOKPATH=/testing/hook_server
68 | sed -i "s!^session.up=.*!session.up=$HOOKPATH/setup_interface.sh!" /srv/tunneldigger/broker/l2tp_broker.cfg
69 | sed -i "s!^session.down=.*!session.down=$HOOKPATH/teardown_interface.sh!" /srv/tunneldigger/broker/l2tp_broker.cfg
70 |
71 | if [ -f /srv/tunneldigger/broker/l2tp_broker.py ]; then
72 | # old servers have a module check that is broken with current Ubuntu kernels, so we have to disable it.
73 | if grep check_modules /srv/tunneldigger/broker/l2tp_broker.cfg -q; then
74 | # sometimes that's easy, we can just sed the config.
75 | sed -i 's/check_modules=true/check_modules=false/' /srv/tunneldigger/broker/l2tp_broker.cfg
76 | else
77 | # but real old servers don't even have that config, we need to patch the source instead. ouch.
78 | sed -i 's/if not check_for_modules():/if False:/' /srv/tunneldigger/broker/l2tp_broker.py
79 | fi
80 | fi
81 |
--------------------------------------------------------------------------------
/tests/run_client.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | #
3 | # arguments must contain a server like '-b 127.0.0.1:8942'
4 | # but it could also contains additional arguments like '-a'
5 |
6 | cd /srv/tunneldigger/client
7 | if [ -f CMakeLists.txt ]; then
8 | exec /srv/tunneldigger/client/tunneldigger -u foobar -i l2tp0 -t 2 $SERVERS -L 102400 -s /testing/hook_client.sh -f $@
9 | else
10 | exec /srv/tunneldigger/client/l2tp_client -u foobar -i l2tp0 -t 2 $SERVERS -L 102400 -s /testing/hook_client.sh -f $@
11 | fi
12 |
--------------------------------------------------------------------------------
/tests/run_server.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | if [ -f /srv/tunneldigger/broker/l2tp_broker.py ]; then
4 | # Handle old broker version.
5 | cd /srv/tunneldigger/broker/
6 | exec /srv/env_tunneldigger/bin/python /srv/tunneldigger/broker/l2tp_broker.py /srv/tunneldigger/broker/l2tp_broker.cfg
7 | elif [ -f /srv/tunneldigger/broker/main.py ]; then
8 | # Handle new broker old-package version.
9 | cd /srv/tunneldigger
10 | exec /srv/env_tunneldigger/bin/python -m broker.main /srv/tunneldigger/broker/l2tp_broker.cfg
11 | else
12 | # Handle new broker new package version.
13 | exec /srv/env_tunneldigger/bin/python -m tunneldigger_broker.main /srv/tunneldigger/broker/l2tp_broker.cfg
14 | fi
15 |
--------------------------------------------------------------------------------
/tests/test_nose.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import lxc
4 | import os
5 | import signal
6 | from time import sleep
7 | import tunneldigger
8 | from tunneldigger import LOG, run_as_lxc
9 |
10 | # random hash
11 | CONTEXT = None
12 |
13 | # lxc container
14 | SERVER = None
15 | CLIENT = None
16 |
17 | # pids of tunneldigger client and server
18 | SERVER_PID = None
19 | CLIENT_PID = None
20 |
21 | def setup_module():
22 | global CONTEXT, SERVER, CLIENT, SERVER_PID, CLIENT_PID
23 | CONTEXT = tunneldigger.get_random_context()
24 | LOG("using context %s" % CONTEXT)
25 | CLIENT, SERVER = tunneldigger.prepare_containers(CONTEXT, os.environ['CLIENT_REV'], os.environ['SERVER_REV'])
26 | SERVER_PID = tunneldigger.run_server(SERVER)
27 | CLIENT_PID = tunneldigger.run_client(CLIENT, ['-b', '172.16.16.1:8942'])
28 |
29 | if not tunneldigger.check_ping(CLIENT, '172.16.16.1', 10):
30 | raise RuntimeError("Unable to ping server container, possible test network issue")
31 |
32 | # explicit no Exception when ping fails
33 | # it's better to poll the client for a ping rather doing a long sleep
34 | tunneldigger.check_ping(CLIENT, '192.168.254.1', 5)
35 |
36 | def teardown_module():
37 | tunneldigger.clean_up(CONTEXT, CLIENT, SERVER)
38 |
39 | class TestTunneldigger(object):
40 | def test_ping_tunneldigger_server(self):
41 | """ even we check earlier if the ping is working, we want to fail the check here.
42 | If we fail in setup_module, nose will return UNKNOWN state, because the setup fails and
43 | not a "test" """
44 | if not tunneldigger.check_ping(CLIENT, '192.168.254.1', 3):
45 | raise RuntimeError("fail to ping server")
46 |
47 | def test_wget_tunneldigger_server(self):
48 | ret = CLIENT.attach_wait(lxc.attach_run_command, [
49 | "wget", "-t", "2", "-T", "4", "http://192.168.254.1:8080/testing/test-data/test_8m", '-O', '/dev/null'])
50 | if ret != 0:
51 | raise RuntimeError("failed to run the tests")
52 |
53 | def test_ensure_tunnel_up_for_1m(self):
54 | # get id of l2tp0 iface
55 | first_interface_id = run_as_lxc(CLIENT, ['bash', '-c', 'ip -o link show l2tp0 | awk -F: \'{ print $1 }\''])
56 | # sleep 1 minute
57 | sleep(60)
58 | # get id of l2tp0 iface
59 | second_interface_id = run_as_lxc(CLIENT, ['bash', '-c', 'ip -o link show l2tp0 | awk -F: \'{ print $1 }\''])
60 | LOG("Check l2tp is stable for 1m. first id %s == %s second id " % (first_interface_id, second_interface_id))
61 | assert first_interface_id == second_interface_id
62 |
--------------------------------------------------------------------------------
/tests/test_usage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # This tests the current client against two servers. One already has a client connected so we make
3 | # sure to connect to the other.
4 | # We can no longer test against a server without support for "usage" since those
5 | # servers just don't run on today's OSes any more (the old Python conntrack bindings broke).
6 |
7 | import os
8 | import tunneldigger
9 | from tunneldigger import LOG, check_if_git_contains, run_server, run_client, run_as_lxc
10 |
11 | OLD_REV = 'v0.3.0'
12 |
13 | class TestClientUsage(object):
14 | def test_usage(self):
15 | """
16 | - we need to check if the client version is fresh enought to support usage. otherwise SKIP
17 | - setup server A with usage version but one client
18 | - setup server B with usage version without any client
19 | - setup server C with non-usage version
20 |
21 | - start client conf ABC and check if it's connecting to server B
22 | - start client conf AB and check if it's connecting to server B
23 | """
24 | CONTEXT = tunneldigger.get_random_context()
25 |
26 | bridge_name = "br-%s" % CONTEXT
27 | tunneldigger.create_bridge(bridge_name)
28 |
29 | cont_client = tunneldigger.prepare('client', CONTEXT + '_usage_client', os.environ['CLIENT_REV'], bridge_name, '172.16.16.2/24')
30 |
31 | servers = ['172.16.16.100', '172.16.16.101']
32 | cont_first = tunneldigger.prepare('server', CONTEXT + '_first_server', os.environ['CLIENT_REV'], bridge_name, servers[0]+'/24')
33 | cont_second = tunneldigger.prepare('server', CONTEXT + '_second_server', OLD_REV, bridge_name, servers[1]+'/24')
34 | cont_all_servers = [cont_first, cont_second]
35 |
36 | cont_dummy_client = tunneldigger.prepare('client', CONTEXT + '_dummy_client', os.environ['CLIENT_REV'],
37 | bridge_name, '172.16.16.1/24')
38 | cont_all_clients = [cont_dummy_client, cont_client]
39 |
40 | LOG("Created servers {}".format([x.name for x in cont_all_servers]))
41 | LOG("Created clients {}".format([x.name for x in cont_all_clients]))
42 |
43 | # start all servers
44 | pids_all_servers = [run_server(x) for x in cont_all_servers]
45 | pid_dummy_client = run_client(cont_dummy_client, ['-b', servers[0]+':8942'])
46 |
47 | # check if the dummy client is connected to server A
48 | if not tunneldigger.check_ping(cont_dummy_client, '192.168.254.1', 10):
49 | raise RuntimeError("Dummy Client failed to ping server")
50 |
51 | # -a = usage broker
52 | client_args = ['-a']
53 | for srv in servers:
54 | client_args.append('-b')
55 | client_args.append(srv + ":8942")
56 | pid_client = run_client(cont_client, client_args)
57 |
58 | # check if the client is connected to some server
59 | if not tunneldigger.check_ping(cont_client, '192.168.254.1', 10):
60 | raise RuntimeError("Test client failed to ping server")
61 |
62 | # now everything is connect. let's see if it's connecting to server B
63 | address = run_as_lxc(cont_client, ['curl', '--silent', 'http://192.168.254.1:8080/ip.txt']).decode()
64 | # FIXME: LXC has some strange bug where a `_after_at_fork_child_reinit_locks` error appears in all the output.
65 | # So `address` here will be that error followed by the address we want...
66 | if not address.endswith(servers[1]):
67 | raise RuntimeError('Client is connected to "%s" but should be "%s"' % (address, bytes(servers[1], 'utf-8')))
68 |
--------------------------------------------------------------------------------
/tests/travis.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Alexander Couzens
3 | #
4 | # travis script
5 |
6 | . $(dirname $0)/lib_ci.sh
7 |
8 | # We had a lot of intermittent failures with the default keyserver (pool.sks-keyservers.net).
9 | #export DOWNLOAD_KEYSERVER="pgp.mit.edu"
10 | #export DOWNLOAD_KEYSERVER="keyserver.ubuntu.com"
11 |
12 | # run requested test
13 |
14 | case "$SELECT" in
15 | nose)
16 | setup_container
17 | test_nose $OLD_REV HEAD
18 | ;;
19 | usage)
20 | setup_container
21 | test_usage HEAD
22 | ;;
23 | client)
24 | test_client_compile
25 | ;;
26 | *)
27 | # fail
28 | echo "No test selected. required export SELECT=, test in [nose, usage, client]"
29 | echo "You entered '$SELECT'"
30 | exit 1
31 | ;;
32 | esac
33 |
--------------------------------------------------------------------------------
/tests/tunneldigger.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import lxc
4 | from random import randint
5 | from subprocess import check_call, check_output
6 | from time import sleep
7 | import argparse
8 | import os
9 | import shlex
10 | import signal
11 | import sys
12 | from threading import Timer
13 |
14 | def LOG(msg):
15 | print("[TEST] {}".format(msg), flush=True)
16 |
17 | def lxc_run_command(container, command):
18 | if container.attach_wait(lxc.attach_run_command, command):
19 | raise RuntimeError("failed to run command: {}", command)
20 |
21 | def setup_template(ubuntu_release):
22 | """ all test container are cloned from this one
23 | it's important that this container is *NOT* running!
24 | """
25 | LOG("Creating base container")
26 | container = lxc.Container("tunneldigger-base")
27 |
28 | if not container.defined:
29 | for i in range(0, 5): # retry a few times, this tends to fail spuriously on travis
30 | if i > 0:
31 | print("container creation failed, retrying after some waiting...")
32 | sleep(30) # wait a bit before next attempt
33 | if container.create("download", args={"dist": "ubuntu", "release": ubuntu_release, "arch": "amd64"}):
34 | break
35 | else:
36 | raise RuntimeError("failed to create container")
37 |
38 | if not container.running:
39 | if not container.start():
40 | raise RuntimeError("failed to start container")
41 |
42 | lxc_run_command(container, ["ip", "a"])
43 | lxc_run_command(container, ["dhclient", "eth0"])
44 | lxc_run_command(container, ["ip", "a"])
45 | lxc_run_command(container, ["apt-get", "update"])
46 | lxc_run_command(container, ["apt-get", "dist-upgrade", "-y"])
47 |
48 | # tunneldigger requirements
49 | # we install all requirements of past and present versions
50 | # so that we can run both older and newer versions of the code
51 | # with the same container setup
52 | pkg_to_install = [
53 | "iproute2",
54 | "bridge-utils",
55 | "libnetfilter-conntrack3",
56 | "python-dev",
57 | "python3-dev",
58 | "libevent-dev",
59 | "ebtables",
60 | "virtualenv",
61 | "build-essential",
62 | "cmake",
63 | "libnl-3-dev",
64 | "libnl-genl-3-dev",
65 | "libasyncns-dev",
66 | "linux-libc-dev",
67 | "libffi-dev",
68 | "python-cffi",
69 | "libnfnetlink-dev",
70 | "libnetfilter-conntrack-dev",
71 | ]
72 | pkg_to_install += [
73 | "wget",
74 | "curl",
75 | "git",
76 | "iputils-ping"
77 | ]
78 | # for testing the connection
79 | pkg_to_install += [
80 | "lighttpd"
81 | ]
82 |
83 | lxc_run_command(container, ["apt-get", "install", "-y"] + pkg_to_install)
84 | container.shutdown(30)
85 |
86 | def get_random_context():
87 | """ return a random hex similiar to mktemp, but do not check is already used """
88 | context = randint(0, 2**32)
89 | context = hex(context)[2:]
90 | return context
91 |
92 | def configure_network(container, bridge, ip_netmask):
93 | """ configure the container and connect them to the bridge
94 | container is a lxc container
95 | bridge the name of your bridge to attach the container
96 | ip_netmask is the give address in cidr. e.g. 192.168.1.2/24"""
97 | config = [
98 | ('lxc.net.1.type', 'veth'),
99 | ('lxc.net.1.link', bridge),
100 | ('lxc.net.1.flags', 'up'),
101 | ('lxc.net.1.ipv4.address', ip_netmask),
102 | ]
103 |
104 | for item in config:
105 | container.append_config_item(item[0], item[1])
106 |
107 | def configure_mounts(container):
108 | # mount testing dir
109 | local_path = os.path.dirname(os.path.realpath(__file__))
110 | git_repo = local_path + '/../.git'
111 | LOG("Git repo is at {}".format(git_repo))
112 |
113 | # TODO: this mount is very dirty and may be DANGEROUS!!! Unescaped.
114 | # mount this directory to /testing
115 | container.append_config_item('lxc.mount.entry', '%s testing none bind,ro,create=dir 0 0' % local_path)
116 | container.append_config_item('lxc.mount.entry', '%s git_repo none bind,ro,create=dir 0 0' % git_repo)
117 |
118 | # TODO: check if this is required because of libc-dev package
119 | container.append_config_item('lxc.mount.entry', '/usr/src usr/src none bind,ro 0 0')
120 |
121 | def create_bridge(name):
122 | """ setup a linux bridge device """
123 | LOG("Creating bridge %s" % name)
124 | check_call(["brctl", "addbr", name], timeout=10)
125 | check_call(["ip", "link", "set", name, "up"], timeout=10)
126 |
127 | # FIXME: lxc_container: confile.c: network_netdev: 474 no network device defined for 'lxc.network.1.link' = 'br-46723922' option
128 | sleep(3)
129 |
130 | def check_ping(container, server, tries):
131 | """ check the internet connectivity inside the container """
132 | ping = 'ping -c 1 -W 1 %s' % server
133 | for i in range(0, tries):
134 | ret = container.attach_wait(lxc.attach_run_command, shlex.split(ping))
135 | if ret == 0:
136 | return True
137 | sleep(1)
138 | return False
139 |
140 | def generate_test_file():
141 | """ generate a test file with sha256sum"""
142 | local_path = os.path.dirname(os.path.realpath(__file__))
143 | test_data = local_path + '/test-data'
144 | test_8m = test_data + '/test_8m'
145 | sum_file = test_data + '/sha256sum'
146 | if not os.path.exists(test_data):
147 | os.mkdir(test_data)
148 | if not os.path.exists(test_8m):
149 | check_call(['dd', 'if=/dev/urandom', 'of=%s' % test_8m, 'bs=1M', 'count=8'])
150 | output = check_output(['sha256sum', test_8m], cwd=test_data)
151 | f = open(sum_file, 'wb')
152 | f.write(output)
153 | f.close()
154 |
155 | def testing(client_rev, server_rev):
156 | context = get_random_context()
157 | print(("generate a run for %s" % context))
158 | client, server = prepare_containers(context, client_rev, server_rev)
159 | spid = run_server(server)
160 | cpid = run_client(client, ['-b', '172.16.16.1:8942'])
161 |
162 | # wait until client is connected to server
163 | if not check_ping(client, '192.168.254.1', 20):
164 | raise RuntimeError('Tunneldigger client can not connect to the server')
165 | run_tests(server, client)
166 |
167 | def prepare(cont_type, name, revision, bridge, ip_netmask='172.16.16.1/24'):
168 | if cont_type not in ['server', 'client']:
169 | raise RuntimeError('Unknown container type given')
170 | if lxc.Container(name).defined:
171 | raise RuntimeError('Container "%s" already exist!' % name)
172 | LOG("Preparing %s (type=%s, ip=%s, revision=%s)" % (name, cont_type, ip_netmask, revision))
173 |
174 | base = lxc.Container("tunneldigger-base")
175 |
176 | if not base.defined:
177 | raise RuntimeError("Setup first the base container")
178 |
179 | if base.running:
180 | raise RuntimeError(
181 | "base container %s is still running."
182 | "Please run lxc-stop --name %s -t 5" %
183 | (base.name, base.name))
184 |
185 | LOG("Cloning base (%s) to server (%s)" %(base.name, name))
186 | cont = base.clone(name, flags=lxc.LXC_CLONE_SNAPSHOT, bdevtype='overlayfs')
187 | if not cont:
188 | raise RuntimeError('could not create container "%s"' % name)
189 | configure_network(cont, bridge, ip_netmask)
190 |
191 | configure_mounts(cont)
192 | if not cont.start():
193 | raise RuntimeError("Can not start container %s" % cont.name)
194 | sleep(3)
195 | # ping does not work on GHA...
196 | #if not check_ping(cont, 'google-public-dns-a.google.com', 20):
197 | # raise RuntimeError("Container doesn't have an internet connection %s"
198 | # % cont.name)
199 |
200 | script = '/testing/prepare_%s.sh' % cont_type
201 | LOG("Server %s run %s" % (name, script))
202 | ret = cont.attach_wait(lxc.attach_run_command, [script, revision])
203 | if ret != 0:
204 | raise RuntimeError('Failed to prepare the container "%s" type %s' % (name, cont_type))
205 | LOG("Finished prepare_server %s" % name)
206 | return cont
207 |
208 | def prepare_containers(context, client_rev, server_rev):
209 | """ this does the real test.
210 | - cloning containers from tunneldigger-base
211 | - setup network
212 | - checkout git repos
213 | - execute "compiler" steps
214 | - return clientcontainer, servercontainer
215 | """
216 |
217 | generate_test_file()
218 |
219 | server_name = "%s_server" % context
220 | client_name = "%s_client" % context
221 | bridge_name = "br-%s" % context
222 |
223 | create_bridge(bridge_name)
224 | server = prepare('server', server_name, server_rev, bridge_name, '172.16.16.1/24')
225 | client = prepare('client', client_name, client_rev, bridge_name, '172.16.16.100/24')
226 |
227 | return client, server
228 |
229 | def run_server(server):
230 | """ run_server(server)
231 | server is a container
232 | """
233 | spid = server.attach(lxc.attach_run_command, ['/testing/run_server.sh'])
234 | return spid
235 |
236 | def run_client(client, client_arguments):
237 | """ run_client(client)
238 | client is a container
239 | arguments must contains at least one server in the format ['-b', 'localhost:8942']
240 | """
241 |
242 | arguments = ['/testing/run_client.sh']
243 | arguments.extend(client_arguments)
244 | cpid = client.attach(lxc.attach_run_command, arguments)
245 | return cpid
246 |
247 | def run_tests(server, client):
248 | """ the client should be already connect to the server """
249 | ret = client.attach_wait(lxc.attach_run_command, [
250 | "wget", "-t", "2", "-T", "4", "http://192.168.254.1:8080/testing/test-data/test_8m", '-O', '/dev/null'])
251 | if ret != 0:
252 | raise RuntimeError("failed to run the tests")
253 |
254 | def clean_up(context, client, server):
255 | """ clean the up all bridge and containers created by this scripts. It will also abort all running tests."""
256 | LOG("ctx %s clean up" % context)
257 | # stop containers
258 | for cont in [client, server]:
259 | if cont.running:
260 | LOG("ctx %s hardstop container %s" % (context, cont.name))
261 | cont.shutdown(0)
262 | LOG("ctx %s destroy container %s" % (context, cont.name))
263 | cont.destroy()
264 |
265 | # remove bridge
266 | bridge_name = 'br-%s' % context
267 | if os.path.exists('/sys/devices/virtual/net/%s' % bridge_name):
268 | LOG("ctx %s destroy bridge %s" % (context, bridge_name))
269 | check_call(["ip", "link", "set", bridge_name, "down"], timeout=10)
270 | check_call(["brctl", "delbr", bridge_name], timeout=10)
271 |
272 | def check_host():
273 | """ check if the host has all known requirements to run this script """
274 | have_brctl = False
275 |
276 | try:
277 | check_call(["brctl", "--version"], timeout=3)
278 | have_brctl = True
279 | except Exception:
280 | pass
281 |
282 | if not have_brctl:
283 | sys.stderr.write("No brctl installed\n")
284 |
285 | if have_brctl:
286 | print("Everything is installed")
287 | return True
288 | raise RuntimeError("Missing dependencies. See stderr for more info")
289 |
290 | def run_as_lxc(container, command, timeout=10):
291 | """
292 | run command within container and returns output
293 |
294 | command is a list of command and arguments,
295 | The output is limited to the buffersize of pipe (64k on linux)
296 | """
297 | read_fd, write_fd = os.pipe2(os.O_CLOEXEC | os.O_NONBLOCK)
298 | pid = container.attach(lxc.attach_run_command, command, stdout=write_fd, stderr=write_fd)
299 | timer = Timer(timeout, os.kill, args=(pid, signal.SIGKILL), kwargs=None)
300 | if timeout:
301 | timer.start()
302 | output_list = []
303 | os.waitpid(pid, 0)
304 | timer.cancel()
305 | try:
306 | while True:
307 | output_list.append(os.read(read_fd, 1024))
308 | except BlockingIOError:
309 | pass
310 | return bytes().join(output_list)
311 |
312 | def check_if_git_contains(container, repo_path, top_commit, search_for_commit):
313 | """ checks if a git commit is included within a certain tree
314 | look into repo under *repo_path*, check if search_for_commit is included in the top_commit
315 | """
316 | cmd = ['sh', '-c', 'cd %s ; git merge-base "%s" "%s"' % (repo_path, top_commit, search_for_commit)]
317 | base = run_as_lxc(container, cmd)
318 | sys.stderr.write("\nGIT call is %s\n" % cmd)
319 | sys.stderr.write("\nGIT returns is %s\n" % base)
320 | if base.startswith(bytes(search_for_commit, 'utf-8')):
321 | # the base must be the search_for_commit when search_for_commit should included into top_commit
322 | # TODO: replace with git merge-base --is-ancestor
323 | return True
324 | return False
325 |
326 | if __name__ == '__main__':
327 | parser = argparse.ArgumentParser(description="Test Tunneldigger version against each other")
328 | # operation on the hosts
329 | parser.add_argument('--check-host', dest='check_host', action='store_true', default=False,
330 | help="Check if the host has all requirements installed")
331 | parser.add_argument('--setup', dest='setup', type=str,
332 | help="Setup the basic template for the given ubuntu release")
333 | # testing arguments
334 | parser.add_argument('-t', '--test', dest='test', action='store_true', default=False,
335 | help="Do a test run. Server rev and Client rev required. See -s and -c.")
336 | parser.add_argument('-s', '--server', dest='server', type=str,
337 | help="The revision used by the server")
338 | parser.add_argument('-c', '--client', dest='client', type=str,
339 | help="The revision used by the client")
340 | # clean up
341 | parser.add_argument('--clean', action='store_true', default=False,
342 | help="Clean up (old) containers and bridges. This will kill all running tests!")
343 |
344 | args = parser.parse_args()
345 |
346 | if not args.check_host and not args.setup and not args.test and not args.clean:
347 | parser.print_help()
348 |
349 | if args.check_host:
350 | check_host()
351 |
352 | if args.setup:
353 | setup_template(args.setup)
354 |
355 | if args.test:
356 | if not args.server or not args.client:
357 | raise RuntimeError("No client or server revision given. E.g. --test --server aba123 --client aba123.")
358 | testing(args.client, args.server)
359 |
360 | if args.clean:
361 | raise RuntimeError("not yet implemented...")
362 |
--------------------------------------------------------------------------------